import type Phaser from 'phaser'
import { TowerBase } from './TowerBase'
import { AudioEngine } from '../AudioEngine'
import type { EnemyBase } from '../enemies/EnemyBase'

/**
 * 产品经理 PM — 160 HC
 * 攻击：射出原型图（需求变更弹幕），命中使怪物"需求混乱"（双重减速 + 持续伤害）
 * 特殊技能"需求变更"：每 4 次攻击强制随机重置目标位置（怪物被打回 2 个路径节点）
 */
export class PMTower extends TowerBase {
  private hitCount = 0

  constructor(scene: Phaser.Scene, gridX: number, gridY: number) {
    super(scene, gridX, gridY, 160, 4, 20, 0.8, 'tower-pm')
  }

  attack(target: EnemyBase): void {
    AudioEngine.getInstance().playPMAttack()
    this.firePRD(target)
  }

  private firePRD(target: EnemyBase): void {
    // 原型图：白色矩形框符号
    const bullet = this.scene.add.text(this.px, this.py, '📋', {
      fontSize: '16px',
    }).setOrigin(0.5, 0.5).setDepth(13)

    const dx = target.x - this.px
    const dy = target.y - this.py
    const dist = Math.sqrt(dx * dx + dy * dy)

    this.scene.tweens.add({
      targets: bullet,
      x: target.x, y: target.y,
      duration: (dist / 900) * 1000,
      ease: 'Linear',
      onComplete: () => {
        bullet.destroy()
        if (target.isDead) return

        target.takeDamage(this.attackDamage)
        // 双重减速：60% 持续 3 秒
        target.addSlow(0.6, 3000)
        target.addDOT(5, 3000)

        this.hitCount++
        if (this.hitCount % 4 === 0) {
          // 需求变更：打回 2 个路径节点
          target.rewindPath(2)
          this.showMessage('需求变更！打回重做！', '#06b6d4')
        }

        // 命中特效：蓝色震荡圈
        const g = this.scene.add.graphics()
        g.lineStyle(2, 0x06b6d4, 0.9)
        g.strokeRect(target.x - 12, target.y - 10, 24, 20)
        g.setDepth(15)
        this.scene.tweens.add({
          targets: g, scaleX: 1.8, scaleY: 1.8, alpha: 0,
          duration: 350, onComplete: () => g.destroy(),
        })
      },
    })
  }

  private showMessage(msg: string, color: string): void {
    const txt = this.scene.add
      .text(this.px, this.py - 30, msg, {
        fontFamily: 'VT323, monospace', fontSize: '14px',
        color, backgroundColor: '#0c4a6e', padding: { x: 4, y: 2 },
      }).setOrigin(0.5, 1).setDepth(20)
    this.scene.tweens.add({
      targets: txt, y: this.py - 55, alpha: 0,
      duration: 1200, onComplete: () => txt.destroy(),
    })
  }
}
