/**
 * 大屏空闲/等待画面（全面美化版）
 * 三种状态：未连接、已连接无房间、已连接有房间等待游戏
 */
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../constants.js'
import { drawBubble3D, getBubbleRadius } from './bubble.js'

let _frame = 0

// ─── 工具 ─────────────────────────────────────────────────────────────────────

function rr(ctx, x, y, w, h, r) {
  ctx.beginPath()
  ctx.moveTo(x + r, y)
  ctx.lineTo(x + w - r, y)
  ctx.arcTo(x + w, y, x + w, y + r, r)
  ctx.lineTo(x + w, y + h - r)
  ctx.arcTo(x + w, y + h, x + w - r, y + h, r)
  ctx.lineTo(x + r, y + h)
  ctx.arcTo(x, y + h, x, y + h - r, r)
  ctx.lineTo(x, y + r)
  ctx.arcTo(x, y, x + r, y, r)
  ctx.closePath()
}

// ─── 装饰泡泡（顶部三行漂浮泡泡）────────────────────────────────────────────────

const _decorBubbles = (() => {
  const R = getBubbleRadius()
  const list = []
  let sx = 0.456
  const rand = () => { sx = (sx * 9301 + 49297) % 233280; return sx / 233280 }

  for (let row = 0; row < 3; row++) {
    const cols = row % 2 === 0 ? 11 : 10
    for (let col = 0; col < cols; col++) {
      const x = row % 2 === 0 ? col * 2 * R + R : col * 2 * R + 2 * R
      const y = row * (R * Math.sqrt(3)) + R
      list.push({ x, y, color: Math.floor(rand() * 6) + 1, phase: rand() * Math.PI * 2 })
    }
  }
  return list
})()

function drawDecorBubbles(ctx) {
  ctx.save()
  ctx.globalAlpha = 0.55
  for (const b of _decorBubbles) {
    const dy = Math.sin(_frame * 0.018 + b.phase) * 3
    drawBubble3D(ctx, b.x, b.y + dy, getBubbleRadius(), b.color)
  }
  ctx.restore()
}

// ─── 标题 ─────────────────────────────────────────────────────────────────────

function drawTitle(ctx, cx, y) {
  ctx.save()
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'

  // 小标签
  ctx.font = 'bold 13px Arial'
  ctx.fillStyle = 'rgba(167,139,250,0.65)'
  ctx.fillText('BUBBLE SHOOTER', cx, y - 36)

  // 主标题阴影
  ctx.font = `bold ${SCREEN_WIDTH * 0.145}px Arial`
  ctx.fillStyle = 'rgba(0,0,0,0.45)'
  ctx.fillText('伙伴泡泡', cx + 3, y + 3)

  // 主标题渐变
  const tg = ctx.createLinearGradient(cx - 90, y - 30, cx + 90, y + 30)
  tg.addColorStop(0, '#C4B5FD')
  tg.addColorStop(0.45, '#ffffff')
  tg.addColorStop(1, '#F9A8D4')
  ctx.shadowColor = 'rgba(168,85,247,0.8)'
  ctx.shadowBlur = 28
  ctx.fillStyle = tg
  ctx.fillText('伙伴泡泡', cx, y)
  ctx.shadowBlur = 0

  // 副标题
  ctx.font = `${SCREEN_WIDTH * 0.038}px Arial`
  ctx.fillStyle = 'rgba(196,181,253,0.6)'
  ctx.fillText('大屏展示系统', cx, y + 40)
  ctx.restore()
}

// ─── 连接状态指示（左上）─────────────────────────────────────────────────────────

function drawStatusBadge(ctx, connStatus) {
  const bx = 12, by = 12
  let color, label

  if (connStatus === 1)      { color = '#4ade80'; label = '已连接' }
  else if (connStatus === 2) {
    const a = (0.55 + 0.45 * Math.sin(_frame * 0.08)).toFixed(2)
    color = `rgba(250,204,21,${a})`; label = '重连中'
  } else { color = '#f87171'; label = '未连接' }

  ctx.save()
  ctx.font = '11px Arial'
  const tw = ctx.measureText(label).width
  const bw = tw + 28, bh = 22, br = 11
  rr(ctx, bx, by, bw, bh, br)
  ctx.fillStyle = 'rgba(0,0,0,0.35)'
  ctx.fill()
  rr(ctx, bx, by, bw, bh, br)
  ctx.strokeStyle = color
  ctx.lineWidth = 1.5
  ctx.stroke()

  // 圆点
  ctx.shadowColor = color
  ctx.shadowBlur = 6
  ctx.fillStyle = color
  ctx.beginPath()
  ctx.arc(bx + 10, by + bh / 2, 4, 0, Math.PI * 2)
  ctx.fill()
  ctx.shadowBlur = 0

  ctx.fillStyle = 'rgba(255,255,255,0.85)'
  ctx.textBaseline = 'middle'
  ctx.fillText(label, bx + 18, by + bh / 2)
  ctx.restore()
}

// ─── 分割线 ───────────────────────────────────────────────────────────────────

function drawDivider(ctx, cx, y, hw = 90) {
  ctx.save()
  const g = ctx.createLinearGradient(cx - hw, y, cx + hw, y)
  g.addColorStop(0, 'rgba(168,85,247,0)')
  g.addColorStop(0.5, 'rgba(168,85,247,0.55)')
  g.addColorStop(1, 'rgba(168,85,247,0)')
  ctx.strokeStyle = g
  ctx.lineWidth = 1
  ctx.beginPath()
  ctx.moveTo(cx - hw, y)
  ctx.lineTo(cx + hw, y)
  ctx.stroke()
  ctx.restore()
}

// ─── 浮动装饰粒子 ─────────────────────────────────────────────────────────────

const _particles = [
  { bx: 0.08, by: 0.55, sp: 0.020, r: 3.0, c: [168, 85,  247] },
  { bx: 0.92, by: 0.48, sp: 0.015, r: 2.5, c: [236, 72,  153] },
  { bx: 0.05, by: 0.80, sp: 0.025, r: 2.0, c: [96,  165, 250] },
  { bx: 0.95, by: 0.75, sp: 0.018, r: 3.0, c: [251, 191, 36 ] },
  { bx: 0.50, by: 0.95, sp: 0.022, r: 2.0, c: [167, 243, 208] },
  { bx: 0.18, by: 0.65, sp: 0.012, r: 1.5, c: [249, 168, 212] },
  { bx: 0.82, by: 0.62, sp: 0.017, r: 1.5, c: [147, 197, 253] },
]

function drawParticles(ctx, w, h) {
  ctx.save()
  for (const p of _particles) {
    const t = _frame * p.sp
    const x = p.bx * w + Math.sin(t) * 14
    const y = p.by * h + Math.cos(t * 1.3) * 10
    const a = (0.2 + 0.3 * Math.sin(t * 2)).toFixed(2)
    ctx.beginPath()
    ctx.arc(x, y, p.r, 0, Math.PI * 2)
    ctx.fillStyle = `rgba(${p.c[0]},${p.c[1]},${p.c[2]},${a})`
    ctx.shadowColor = `rgba(${p.c[0]},${p.c[1]},${p.c[2]},0.8)`
    ctx.shadowBlur = 10
    ctx.fill()
  }
  ctx.shadowBlur = 0
  ctx.restore()
}

// ─── 未连接状态 ───────────────────────────────────────────────────────────────

function drawDisconnected(ctx, cx, cy, connStatus) {
  const isReconnecting = connStatus === 2
  const pulse = 0.6 + 0.4 * Math.sin(_frame * 0.07)
  const baseC = isReconnecting ? `rgba(250,204,21,` : `rgba(248,113,113,`

  ctx.save()
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'

  // 圆形背景
  ctx.beginPath()
  ctx.arc(cx, cy - 18, 32, 0, Math.PI * 2)
  ctx.strokeStyle = `${baseC}${pulse.toFixed(2)})`
  ctx.lineWidth = 2
  ctx.shadowColor = `${baseC}0.5)`
  ctx.shadowBlur = 12
  ctx.stroke()
  ctx.shadowBlur = 0

  ctx.font = isReconnecting ? 'bold 28px Arial' : 'bold 32px Arial'
  ctx.fillStyle = `${baseC}${pulse.toFixed(2)})`
  ctx.fillText(isReconnecting ? '↻' : '✕', cx, cy - 16)

  ctx.font = 'bold 16px Arial'
  ctx.fillStyle = `${baseC}0.95)`
  ctx.fillText(isReconnecting ? '正在重新连接...' : '无法连接服务器', cx, cy + 26)

  ctx.font = '12px Arial'
  ctx.fillStyle = 'rgba(255,255,255,0.3)'
  ctx.fillText('请确认服务器已启动并刷新页面', cx, cy + 50)
  ctx.restore()
}

// ─── 已连接无房间 ──────────────────────────────────────────────────────────────

function drawNoRoom(ctx, cx, cy) {
  const pulse = 0.6 + 0.4 * Math.sin(_frame * 0.04)
  ctx.save()
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'

  // 脉冲圆
  ctx.beginPath()
  ctx.arc(cx, cy - 20, 30 * (1 + 0.06 * Math.sin(_frame * 0.04)), 0, Math.PI * 2)
  ctx.strokeStyle = `rgba(168,85,247,${(pulse * 0.5).toFixed(2)})`
  ctx.lineWidth = 1.5
  ctx.stroke()

  ctx.beginPath()
  ctx.arc(cx, cy - 20, 22, 0, Math.PI * 2)
  ctx.strokeStyle = `rgba(168,85,247,${pulse.toFixed(2)})`
  ctx.lineWidth = 2
  ctx.shadowColor = 'rgba(168,85,247,0.6)'
  ctx.shadowBlur = 10
  ctx.stroke()
  ctx.shadowBlur = 0

  ctx.font = '20px Arial'
  ctx.fillStyle = 'rgba(196,181,253,0.9)'
  ctx.fillText('●', cx, cy - 20)

  ctx.font = 'bold 14px Arial'
  ctx.fillStyle = 'rgba(255,255,255,0.75)'
  ctx.fillText('等待管理后台分配房间', cx, cy + 22)

  const dots = '.'.repeat(Math.floor((_frame / 22) % 4))
  ctx.font = '12px Arial'
  ctx.fillStyle = 'rgba(196,181,253,0.5)'
  ctx.fillText(`请在管理页面指定投屏${dots}`, cx, cy + 46)
  ctx.restore()
}

// ─── 有房间等待开始 ───────────────────────────────────────────────────────────

function drawRoomBound(ctx, cx, cy, roomId) {
  ctx.save()
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'

  // 房间标签
  ctx.font = '13px Arial'
  ctx.fillStyle = 'rgba(196,181,253,0.55)'
  ctx.fillText('当前投屏房间', cx, cy - 70)

  // 房间号
  ctx.shadowColor = 'rgba(251,191,36,0.85)'
  ctx.shadowBlur = 30
  ctx.font = `bold ${SCREEN_WIDTH * 0.18}px Arial`
  const ng = ctx.createLinearGradient(cx - 80, 0, cx + 80, 0)
  ng.addColorStop(0, '#FDE68A')
  ng.addColorStop(0.5, '#FCD34D')
  ng.addColorStop(1, '#F59E0B')
  ctx.fillStyle = ng
  ctx.fillText(String(roomId), cx, cy - 14)
  ctx.shadowBlur = 0

  // 卡片背景
  const cardW = SCREEN_WIDTH * 0.7
  const cardH = 72
  const cardX = cx - cardW / 2
  const cardY = cy + 18

  ctx.shadowColor = 'rgba(0,0,0,0.4)'
  ctx.shadowBlur = 12
  ctx.shadowOffsetY = 4
  const cg = ctx.createLinearGradient(cardX, cardY, cardX, cardY + cardH)
  cg.addColorStop(0, 'rgba(72,40,140,0.85)')
  cg.addColorStop(1, 'rgba(36,18,80,0.9)')
  ctx.fillStyle = cg
  rr(ctx, cardX, cardY, cardW, cardH, 16)
  ctx.fill()
  ctx.shadowBlur = 0
  ctx.strokeStyle = 'rgba(139,92,246,0.4)'
  ctx.lineWidth = 1.5
  rr(ctx, cardX, cardY, cardW, cardH, 16)
  ctx.stroke()

  // 图标行
  const iconY = cardY + cardH / 2
  const icons = ['🎮', '🫧', '✨', '🎯']
  const spacing = cardW / (icons.length + 1)
  ctx.font = '22px Arial'
  icons.forEach((icon, i) => {
    const ix = cardX + spacing * (i + 1)
    const dy = Math.sin(_frame * 0.06 + i * 1.2) * 3
    ctx.fillText(icon, ix, iconY + dy)
  })

  // 等待动画
  const dots = '.'.repeat(Math.floor((_frame / 24) % 4))
  ctx.font = 'bold 13px Arial'
  ctx.fillStyle = 'rgba(196,181,253,0.7)'
  ctx.fillText(`等待游戏开始${dots}`, cx, cardY + cardH + 22)

  ctx.restore()
}

// ─── 屏幕名徽章 ───────────────────────────────────────────────────────────────

function drawScreenBadge(ctx, cx, y, screenName) {
  if (!screenName) return
  ctx.save()
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.font = '11px Arial'
  const label = `屏幕: ${screenName}`
  const tw = ctx.measureText(label).width
  const bw = tw + 22, bh = 22, br = 11
  rr(ctx, cx - bw / 2, y - bh / 2, bw, bh, br)
  ctx.fillStyle = 'rgba(168,85,247,0.2)'
  ctx.fill()
  ctx.strokeStyle = 'rgba(168,85,247,0.4)'
  ctx.lineWidth = 1
  ctx.stroke()
  ctx.fillStyle = 'rgba(196,181,253,0.8)'
  ctx.fillText(label, cx, y)
  ctx.restore()
}

// ─── 主入口 ───────────────────────────────────────────────────────────────────

export function drawIdleScreen(ctx, width, height, roomId, connStatus, screenName, frame) {
  _frame = frame
  const cx = width / 2

  // 顶部装饰泡泡
  drawDecorBubbles(ctx)

  // 顶部遮罩（让泡泡看起来更像背景）
  const topMask = ctx.createLinearGradient(0, 0, 0, getBubbleRadius() * 4)
  topMask.addColorStop(0, 'rgba(30,12,60,0)')
  topMask.addColorStop(1, 'rgba(30,12,60,0.55)')
  ctx.fillStyle = topMask
  ctx.fillRect(0, 0, width, getBubbleRadius() * 4)

  // 浮动粒子
  drawParticles(ctx, width, height)

  // 左上角状态
  drawStatusBadge(ctx, connStatus)

  if (connStatus !== 1) {
    // 未连接
    drawTitle(ctx, cx, height * 0.30)
    drawDivider(ctx, cx, height * 0.41)
    drawDisconnected(ctx, cx, height * 0.60, connStatus)
  } else if (roomId) {
    // 有房间
    drawTitle(ctx, cx, height * 0.22)
    drawScreenBadge(ctx, cx, height * 0.33, screenName)
    drawDivider(ctx, cx, height * 0.38)
    drawRoomBound(ctx, cx, height * 0.62, roomId)
  } else {
    // 无房间
    drawTitle(ctx, cx, height * 0.33)
    drawScreenBadge(ctx, cx, height * 0.45, screenName)
    drawDivider(ctx, cx, height * 0.51)
    drawNoRoom(ctx, cx, height * 0.66)
  }
}
