import type Phaser from 'phaser'
import { TowerBase } from './TowerBase'
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)
    this.drawSprite()
  }

  drawSprite(): void {
    if (!this.sprite) return
    this.sprite.clear()
    // 深蓝色方块
    this.sprite.fillStyle(0x3b82f6, 1)
    this.sprite.fillRect(-12, -12, 24, 24)
    this.sprite.lineStyle(1, 0x93c5fd, 1)
    this.sprite.strokeRect(-12, -12, 24, 24)
    this.sprite.setPosition(this.px, this.py)
    this.sprite.setDepth(10)

    // 顶部 </> 符号文字
    if (this.scene) {
      const existing = this.scene.children.getByName(`dev_label_${this.gridX}_${this.gridY}`)
      if (!existing) {
        this.scene.add
          .text(this.px, this.py, '</>', {
            fontFamily: 'monospace',
            fontSize: '10px',
            color: '#DBEAFE',
          })
          .setOrigin(0.5, 0.5)
          .setDepth(11)
          .setName(`dev_label_${this.gridX}_${this.gridY}`)
      }
    }
  }

  attack(target: EnemyBase): void {
    // 发射绿色代码块子弹
    this.fireBullet(target)
  }

  private fireBullet(target: EnemyBase): void {
    const bullet = this.scene.add.graphics()
    bullet.fillStyle(0x22c55e, 1)
    bullet.fillRect(-4, -4, 8, 8)
    bullet.setPosition(this.px, this.py)
    bullet.setDepth(13)

    const startX = this.px
    const startY = this.py
    const targetX = target.sprite.x
    const targetY = target.sprite.y

    const dx = targetX - startX
    const dy = targetY - startY
    const dist = Math.sqrt(dx * dx + dy * dy)
    const duration = (dist / 400) * 1000

    this.scene.tweens.add({
      targets: bullet,
      x: targetX,
      y: targetY,
      duration,
      onComplete: () => {
        bullet.destroy()
        if (!target.isDead) {
          target.takeDamage(this.attackDamage)
          // 代码屎山：附加 DOT
          target.addDOT(10, 3000)
        }
      },
    })
  }
}
