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

export class SeniorDevTower extends TowerBase {
  constructor(scene: Phaser.Scene, gridX: number, gridY: number) {
    super(scene, gridX, gridY, 120, 5, 30, 1.0, 'tower-senior')
  }

  attack(target: EnemyBase): void {
    AudioEngine.getInstance().playKeyboard()
    this.fireCodeBullet(target)
  }

  private fireCodeBullet(target: EnemyBase): void {
    // 随机代码符号作为子弹
    const symbols = ['</>', '{}', '=>', '??', '&&', '||', '++', '!=']
    const sym = symbols[Math.floor(Math.random() * symbols.length)]

    const bullet = this.scene.add.text(this.px, this.py, sym, {
      fontFamily: 'monospace',
      fontSize: '13px',
      color: '#86efac',
      stroke: '#14532d',
      strokeThickness: 2,
    }).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)
    // 子弹速度 1200px/s，比原来快 2.4 倍
    const duration = (dist / 1200) * 1000

    this.scene.tweens.add({
      targets: bullet,
      x: target.x,
      y: target.y,
      duration,
      ease: 'Linear',
      onComplete: () => {
        bullet.destroy()
        if (!target.isDead) {
          target.takeDamage(this.attackDamage)
          target.addDOT(10, 3000)
          // DOT 命中：绿色代码粒子爆散
          for (let i = 0; i < 4; i++) {
            const p = this.scene.add.text(
              target.x, target.y,
              ['bug', 'err', '!!!', '???'][i],
              { fontFamily: 'monospace', fontSize: '10px', color: '#22c55e' }
            ).setOrigin(0.5, 0.5).setDepth(15)
            const angle = (i / 4) * Math.PI * 2
            this.scene.tweens.add({
              targets: p,
              x: target.x + Math.cos(angle) * 22,
              y: target.y + Math.sin(angle) * 22,
              alpha: 0,
              duration: 400,
              onComplete: () => p.destroy(),
            })
          }
        }
      },
    })
  }
}
