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

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

  constructor(scene: Phaser.Scene, gridX: number, gridY: number) {
    super(scene, gridX, gridY, 80, 1, 0, 0, 'tower-hrbp')
  }

  override update(delta: number, enemies: EnemyBase[]): void {
    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: TowerBase[]): 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()
    this.showBuffEffect()
  }

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

  getBuffedTowers(): Set<TowerBase> { return this.nearbyTowersBuff }
  getAttackSpeedBonus(): number { return 0.2 }
  attack(_target: EnemyBase): void {}
}
