import type Phaser from 'phaser'
import { EnemyBase, type PathPoint } from './EnemyBase'
import { getRandomQuote } from '../data/quotes'

export class BossVP extends EnemyBase {
  private skillTimer: number = 20000
  private onDestroyTower?: () => void

  constructor(
    scene: Phaser.Scene,
    pathPoints: PathPoint[],
    onDestroyTower?: () => void
  ) {
    super(scene, pathPoints, 800, 40, 30, 150)
    this.onDestroyTower = onDestroyTower
    this.drawSprite()
    // BOSS 出现时全屏红色闪光
    scene.cameras.main.flash(800, 255, 0, 0, false)
    this.showBossAlert()
  }

  private showBossAlert(): void {
    const alert = this.scene.add
      .text(640, 360, '⚠ 空降VP来袭！⚠', {
        fontFamily: 'VT323, monospace',
        fontSize: '36px',
        color: '#FBBF24',
        backgroundColor: '#7F1D1D',
        padding: { x: 16, y: 8 },
      })
      .setOrigin(0.5, 0.5)
      .setDepth(50)
    this.scene.tweens.add({
      targets: alert,
      alpha: 0,
      duration: 2500,
      delay: 500,
      onComplete: () => alert.destroy(),
    })
  }

  drawSprite(): void {
    if (!this.sprite) return
    this.sprite.clear()
    // 金色六边形
    this.sprite.fillStyle(0xfbbf24, 1)
    const r = 22
    this.sprite.fillPoints(this.hexPoints(r), true)
    // 金色外框
    this.sprite.lineStyle(3, 0xf59e0b, 1)
    this.sprite.strokePoints(this.hexPoints(r + 4), false)
    // 内部颜色
    this.sprite.fillStyle(0xd97706, 1)
    this.sprite.fillCircle(0, 0, 8)
    this.sprite.setDepth(12)
    this.sprite.setPosition(this.x, this.y)
  }

  private hexPoints(r: number): Phaser.Types.Math.Vector2Like[] {
    const pts: Phaser.Types.Math.Vector2Like[] = []
    for (let i = 0; i < 6; i++) {
      const angle = (Math.PI / 3) * i - Math.PI / 6
      pts.push({ x: Math.cos(angle) * r, y: Math.sin(angle) * r })
    }
    return pts
  }

  override update(delta: number): void {
    if (this.isDead) return
    super.update(delta)

    this.skillTimer -= delta
    if (this.skillTimer <= 0) {
      this.skillTimer = 20000
      this.triggerOrgRestructure()
    }
    // 重绘六边形到新位置
    this.drawSprite()
  }

  private triggerOrgRestructure(): void {
    // 组织架构调整：随机摧毁一个防御塔
    if (this.onDestroyTower) {
      this.onDestroyTower()
    }
    const txt = this.scene.add
      .text(this.x, this.y - 40, '组织架构调整！', {
        fontFamily: 'VT323, monospace',
        fontSize: '18px',
        color: '#FBBF24',
        backgroundColor: '#7C2D12',
        padding: { x: 6, y: 3 },
      })
      .setOrigin(0.5, 1)
      .setDepth(25)
    this.scene.tweens.add({
      targets: txt,
      y: this.y - 70,
      alpha: 0,
      duration: 2000,
      onComplete: () => txt.destroy(),
    })
  }

  getQuote(): string {
    return getRandomQuote('BossVP')
  }
}
