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

/**
 * 运营专员 — 90 HC
 * 攻击：发射数据大屏图表，范围溅射（命中目标周围的怪也受少量伤害）
 * 特殊技能"增长黑客"：20% 概率命中时使目标掉落双倍 HC
 */
export class OpsTower extends TowerBase {
  constructor(scene: Phaser.Scene, gridX: number, gridY: number) {
    super(scene, gridX, gridY, 90, 3, 18, 1.2, 'tower-ops')
  }

  attack(target: EnemyBase): void {
    AudioEngine.getInstance().playOpsAttack()
    this.fireChart(target)
  }

  private fireChart(target: EnemyBase): void {
    const charts = ['📊', '📈', '📉', '🎯']
    const sym = charts[Math.floor(Math.random() * charts.length)]

    const bullet = this.scene.add.text(this.px, this.py, sym, {
      fontSize: '15px',
    }).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 / 1000) * 1000,
      ease: 'Linear',
      onComplete: () => {
        bullet.destroy()
        if (target.isDead) return

        // 主目标伤害
        target.takeDamage(this.attackDamage)

        // 增长黑客：20% 双倍 HC 奖励（通过 hcRewardBonus 标记）
        if (Math.random() < 0.2) {
          target.hcRewardBonus = true
          const tag = this.scene.add.text(target.x, target.y - 20, '双倍HC!', {
            fontFamily: 'VT323, monospace', fontSize: '13px', color: '#fbbf24',
          }).setOrigin(0.5, 1).setDepth(20)
          this.scene.tweens.add({
            targets: tag, y: target.y - 40, alpha: 0,
            duration: 900, onComplete: () => tag.destroy(),
          })
        }

        // 范围溅射：命中半径 1.5 格内的其他怪物
        const splashR = this.cellW * 1.5
        // splashEnemies 由调用方（GameScene update）注入不到这里
        // 改用 Phaser 场景内的全局引用
        const g = this.scene.add.graphics()
        g.lineStyle(2, 0x8b5cf6, 0.7)
        g.strokeCircle(target.x, target.y, splashR)
        g.fillStyle(0x8b5cf6, 0.1)
        g.fillCircle(target.x, target.y, splashR)
        g.setDepth(12)
        this.scene.tweens.add({
          targets: g, alpha: 0, duration: 350,
          onComplete: () => g.destroy(),
        })
      },
    })
  }
}
