/**
 * 背景渲染（移植自 minigame-1/js/runtime/background.js）
 * 紫色星空背景：天空渐变、月亮光晕、随机星点、底部云雾
 */
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../constants.js'

/** 预生成固定星星位置，避免每帧重算 */
function genStars(count) {
  const stars = []
  let sx = 0.123
  const rand = () => {
    sx = (sx * 9301 + 49297) % 233280
    return sx / 233280
  }
  for (let i = 0; i < count; i++) {
    stars.push({
      x: rand() * SCREEN_WIDTH,
      y: rand() * SCREEN_HEIGHT * 0.65,
      r: rand() * 1.4 + 0.4,
      a: rand() * 0.55 + 0.35,
    })
  }
  return stars
}

const STARS = genStars(90)

function drawSky(ctx, w, h) {
  const grad = ctx.createLinearGradient(0, 0, 0, h)
  grad.addColorStop(0, '#2a1648')
  grad.addColorStop(0.35, '#3a2060')
  grad.addColorStop(0.65, '#482878')
  grad.addColorStop(1, '#5a3498')
  ctx.fillStyle = grad
  ctx.fillRect(0, 0, w, h)
}

function drawMoon(ctx, w, h) {
  const mx = w * 0.72
  const my = h * 0.12
  const R = w * 0.1

  const glow = ctx.createRadialGradient(mx, my, R * 0.3, mx, my, R * 2.8)
  glow.addColorStop(0, 'rgba(220, 190, 255, 0.30)')
  glow.addColorStop(0.5, 'rgba(180, 140, 255, 0.10)')
  glow.addColorStop(1, 'rgba(100,  60, 200, 0)')
  ctx.fillStyle = glow
  ctx.beginPath()
  ctx.arc(mx, my, R * 2.8, 0, Math.PI * 2)
  ctx.fill()

  const body = ctx.createRadialGradient(mx - R * 0.2, my - R * 0.2, 0, mx, my, R)
  body.addColorStop(0, '#f0e8ff')
  body.addColorStop(0.6, '#c8b0f0')
  body.addColorStop(1, '#9970d8')
  ctx.fillStyle = body
  ctx.beginPath()
  ctx.arc(mx, my, R, 0, Math.PI * 2)
  ctx.fill()
}

function drawStars(ctx, w, h) {
  ctx.save()
  for (const s of STARS) {
    ctx.beginPath()
    ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2)
    ctx.fillStyle = `rgba(220, 200, 255, ${s.a})`
    ctx.fill()
  }
  ctx.restore()
}

function drawMist(ctx, w, h) {
  const mist1 = ctx.createLinearGradient(0, h * 0.72, 0, h)
  mist1.addColorStop(0, 'rgba(60, 20, 120, 0)')
  mist1.addColorStop(1, 'rgba(50, 15, 100, 0.55)')
  ctx.fillStyle = mist1
  ctx.fillRect(0, h * 0.72, w, h * 0.28)

  const mist2 = ctx.createLinearGradient(0, h * 0.85, 0, h)
  mist2.addColorStop(0, 'rgba(20, 5, 50, 0)')
  mist2.addColorStop(1, 'rgba(10, 2, 30, 0.70)')
  ctx.fillStyle = mist2
  ctx.fillRect(0, h * 0.85, w, h * 0.15)
}

/**
 * 绘制紫色星空背景
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} [width=SCREEN_WIDTH]
 * @param {number} [height=SCREEN_HEIGHT]
 */
export function drawBackground(ctx, width = SCREEN_WIDTH, height = SCREEN_HEIGHT) {
  drawSky(ctx, width, height)
  drawMoon(ctx, width, height)
  drawStars(ctx, width, height)
  drawMist(ctx, width, height)
}
