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

const BUFF_ATTACK_SPEED_BONUS = 0.2

export class HRBPTower extends TowerBase {
  private buffCooldown: number = 0
  private readonly BUFF_INTERVAL = 500
  private nearbyTowersBuff: Set<TowerBaseType> = new Set()

  constructor(scene: Phaser.Scene, gridX: number, gridY: number) {
    super(scene, gridX, gridY, 80, 1, 0, 0)
    this.drawSprite()
  }

  drawSprite(): void {
    if (!this.sprite) return
    this.sprite.clear()
    // 菱形（粉色）
    this.sprite.fillStyle(0xec4899, 1)
    this.sprite.fillTriangle(0, -16, 16, 0, 0, 16)
    this.sprite.fillTriangle(0, -16, -16, 0, 0, 16)
    this.sprite.setPosition(this.px, this.py)
    this.sprite.setDepth(10)
  }

  override update(delta: number, enemies: EnemyBase[]): void {
    // HRBP 没有攻击逻辑，只做 BUFF
    void enemies

    if (!this.isActive) {
      this.stamina = Math.min(
        this.maxStamina,
        this.stamina + (this.staminaRegen * delta) / 1000
      )
      if (this.stamina > 20) this.isActive = true
      this.updateStaminaBar()
      return
    }

    this.buffCooldown -= delta
    if (this.buffCooldown <= 0) {
      this.buffCooldown = this.BUFF_INTERVAL
      this.applyBuffToNearby()
    }
  }

  setNearbyTowers(towers: TowerBaseType[]): void {
    this.nearbyTowersBuff = new Set(towers)
  }

  private applyBuffToNearby(): void {
    if (this.nearbyTowersBuff.size === 0) return
    if (this.stamina < 5) {
      this.isActive = false
      return
    }
    this.stamina -= 5
    this.updateStaminaBar()
    // BUFF 效果通过 attackSpeedMultiplier 外部读取
    // 这里显示一个粉色光圈效果
    this.showBuffEffect()
  }

  private showBuffEffect(): void {
    const g = this.scene.add.graphics()
    g.lineStyle(2, 0xec4899, 0.6)
    g.strokeCircle(this.px, this.py, 90)
    g.setDepth(8)
    this.scene.tweens.add({
      targets: g,
      alpha: 0,
      duration: 400,
      onComplete: () => g.destroy(),
    })
  }

  getBuffedTowers(): Set<TowerBaseType> {
    return this.nearbyTowersBuff
  }

  getAttackSpeedBonus(): number {
    return BUFF_ATTACK_SPEED_BONUS
  }

  // HRBP 无直接攻击
  attack(_target: EnemyBase): void {}
}
