/**
 * 射击器渲染（大屏端，仅绘制不含触摸）
 * 鸡身体朝向跟随瞄准方向倾斜 + 呼吸浮动 + 弹跳动画
 *
 * 所有尺寸参数与 minigame-1/js/bubble/shooter.js 保持 1:1 一致
 */
import { SCREEN_WIDTH, SCREEN_HEIGHT, SAFE_AREA_BOTTOM } from '../constants.js'
import { getBubbleRadius, drawBubble3D } from './bubble.js'

const NEXT_SCALE = 0.65

// 鸡朝向参数（与小游戏端一致）
const MIN_ANGLE = 15 * Math.PI / 180
const MAX_ANGLE = 165 * Math.PI / 180
const MAX_LEAN_ANGLE = 25 * Math.PI / 180
const LEAN_LERP = 0.15
// 呼吸浮动参数（与小游戏端一致：BOB_SPEED=0.04, BOB_AMOUNT=R*0.2）
const BOB_SPEED = 0.04

// 加载鸡图片
const _chickenImg = new Image()
_chickenImg.src = '/images/chicken.png'

// 模块级动画状态
let _currentLean = 0
let _bobPhase = 0

function calcAimPoints(originX, originY, angle) {
  const R = getBubbleRadius()
  const points = [{ x: originX, y: originY }]
  let cx = originX, cy = originY
  let vx = Math.cos(angle), vy = -Math.sin(angle)

  for (let i = 0; i < 6; i++) {
    const tLeft = vx < 0 ? (R - cx) / vx : Infinity
    const tRight = vx > 0 ? (SCREEN_WIDTH - R - cx) / vx : Infinity
    const tTop = vy < 0 ? (R - cy) / vy : Infinity
    const t = Math.min(tLeft, tRight, tTop)
    if (!isFinite(t) || t <= 0) break
    cx += vx * t
    cy += vy * t
    points.push({ x: cx, y: cy })
    if (t === tTop) break
    vx = -vx
  }
  return points
}

function drawAimLine(ctx, aimPoints) {
  if (!aimPoints || aimPoints.length < 2) return
  ctx.save()
  ctx.setLineDash([6, 7])
  ctx.strokeStyle = 'rgba(255,255,255,0.65)'
  ctx.lineWidth = 2
  ctx.lineJoin = 'round'
  ctx.beginPath()
  ctx.moveTo(aimPoints[0].x, aimPoints[0].y)
  for (let i = 1; i < aimPoints.length; i++) {
    ctx.lineTo(aimPoints[i].x, aimPoints[i].y)
  }
  ctx.stroke()
  ctx.setLineDash([])
  ctx.restore()
}

/**
 * 绘制射击器
 * @param {CanvasRenderingContext2D} ctx
 * @param {Object} shooterState { aimAngle, isAiming, currentColor, nextColor, bounceScaleX, bounceScaleY }
 */
export function drawShooter(ctx, shooterState) {
  if (!shooterState) return

  const R = getBubbleRadius()
  // 以下所有比例系数与 minigame-1/js/bubble/shooter.js 完全一致
  const CHICKEN_WIDTH  = R * 5
  const CHICKEN_HEIGHT = R * 6
  const CHICKEN_BOTTOM_MARGIN = R * 0.8
  const BUBBLE_TOP_OFFSET = R * 0.4
  const NEXT_X_OFFSET = R * 3.8       // 与小游戏一致（原大屏是 3.2）
  const NEXT_Y_OFFSET = R * -1.5      // 与小游戏一致（原大屏是 +0.5）
  const BOB_AMOUNT = R * 0.2          // 与小游戏一致（原大屏是 R*0.15）

  const x = SCREEN_WIDTH / 2
  const chickenBottom = SCREEN_HEIGHT - SAFE_AREA_BOTTOM - CHICKEN_BOTTOM_MARGIN
  const bubbleBaseY = chickenBottom - CHICKEN_HEIGHT - BUBBLE_TOP_OFFSET

  const aimAngle = shooterState.aimAngle ?? Math.PI / 2
  const isAiming = shooterState.isAiming ?? false
  const currentColor = shooterState.currentColor ?? 1
  const nextColor = shooterState.nextColor ?? 1
  const bounceScaleX = shooterState.bounceScaleX ?? 1
  const bounceScaleY = shooterState.bounceScaleY ?? 1
  const bounceOffsetY = (1 - bounceScaleY) * CHICKEN_HEIGHT / 2

  // 计算目标倾斜角度（跟随瞄准方向）
  let targetLean = 0
  if (isAiming) {
    const normalized = (aimAngle - Math.PI / 2) / (MAX_ANGLE - Math.PI / 2)
    targetLean = -normalized * MAX_LEAN_ANGLE
  }
  _currentLean += (targetLean - _currentLean) * LEAN_LERP

  // 呼吸浮动（与小游戏端一致）
  _bobPhase += BOB_SPEED
  if (_bobPhase > Math.PI * 2) _bobPhase -= Math.PI * 2
  const bobOffset = Math.sin(_bobPhase) * BOB_AMOUNT

  // 绘制鸡（以底部中心为旋转轴，跟随瞄准方向倾斜）
  const bottomY = chickenBottom + bounceOffsetY + bobOffset

  ctx.save()
  ctx.translate(x, bottomY)
  ctx.rotate(_currentLean)
  ctx.scale(bounceScaleX, bounceScaleY)
  ctx.drawImage(_chickenImg, -CHICKEN_WIDTH / 2, -CHICKEN_HEIGHT, CHICKEN_WIDTH, CHICKEN_HEIGHT)
  ctx.restore()

  // 当前待射泡泡（鸡头顶，跟随倾斜）
  const headX = x + Math.sin(_currentLean) * CHICKEN_HEIGHT * bounceScaleY
  const headY = bottomY - Math.cos(_currentLean) * CHICKEN_HEIGHT * bounceScaleY - BUBBLE_TOP_OFFSET
  drawBubble3D(ctx, headX, headY, R, currentColor)

  // 瞄准线从泡泡中心（headX/headY）出发
  if (isAiming) {
    const aimPts = calcAimPoints(headX, headY, aimAngle)
    drawAimLine(ctx, aimPts)
  }

  // 下一颗预览泡泡（与小游戏一致：在鸡底部偏右上方）
  const nextR = R * NEXT_SCALE
  const nextX = x + NEXT_X_OFFSET
  const nextY = chickenBottom + NEXT_Y_OFFSET
  drawBubble3D(ctx, nextX, nextY, nextR, nextColor)

  ctx.save()
  ctx.fillStyle = 'rgba(255,255,255,0.65)'
  ctx.font = `bold ${Math.round(R * 0.6)}px Arial`
  ctx.textAlign = 'center'
  ctx.textBaseline = 'bottom'
  ctx.fillText('下一个', nextX, nextY - nextR - 2)
  ctx.restore()
}
