import Phaser from "phaser";
import { OverlayComponent } from "./OverlayComponent";
import { type CombatantActor } from "../../core/types";

export class CharacterOverlay extends OverlayComponent {
  private attrText!: Phaser.GameObjects.Text;
  private statPointsText!: Phaser.GameObjects.Text;
  private skillPointsText!: Phaser.GameObjects.Text;
  private secondaryStatsText!: Phaser.GameObjects.Text;

  protected setupContent() {
    const panelH = 500;

    const title = this.scene.add.text(0, -panelH / 2 + 25, "CHARACTER", { 
      fontSize: "28px", 
      color: "#d4af37", 
      fontStyle: "bold"
    }).setOrigin(0.5);
    this.container.add(title);

    this.createAttributesSection();
    this.createSecondaryStatsSection();
    this.createPassiveTreePreview();
  }

  private createAttributesSection() {
    const attrX = -200;
    const attrY = -50;
    
    this.attrText = this.scene.add.text(attrX, attrY, "", { fontSize: "16px", color: "#ffffff", lineSpacing: 20 }).setOrigin(0.5);
    this.container.add(this.attrText);

    const statsNames = ["strength", "dexterity", "intelligence"];
    statsNames.forEach((name, i) => {
        const btn = this.scene.add.text(attrX + 80, attrY - 20 + i * 40, "[ + ]", { fontSize: "16px", color: "#00ff00" }).setOrigin(0, 0.5);
        btn.setInteractive({ useHandCursor: true }).on("pointerdown", () => {
             this.scene.events.emit("allocate-stat", name);
        });
        this.container.add(btn);
    });

    this.statPointsText = this.scene.add.text(attrX, attrY + 100, "Stat Points: 0", { fontSize: "16px", color: "#d4af37" }).setOrigin(0.5);
    this.container.add(this.statPointsText);
  }

  private createSecondaryStatsSection() {
    const x = 200;
    const y = 0;
    this.secondaryStatsText = this.scene.add.text(x, y, "", { fontSize: "14px", color: "#ffffff", lineSpacing: 8 }).setOrigin(0.5);
    this.container.add(this.secondaryStatsText);
  }

  private createPassiveTreePreview() {
      // Simplified tree for now
      this.skillPointsText = this.scene.add.text(0, 200, "Skill Points: 0", { fontSize: "18px", color: "#d4af37", fontStyle: "bold" }).setOrigin(0.5);
      this.container.add(this.skillPointsText);
  }

  update(player: CombatantActor) {
    const s = player.stats;
    if (!s) return;

    this.attrText.setText(`STR: ${s.strength}\nDEX: ${s.dexterity}\nINT: ${s.intelligence}`);
    this.statPointsText.setText(`Unspent: ${s.statPoints}`);
    this.skillPointsText.setText(`Skill Points: ${s.skillPoints}`);

    const lines = [
        "SECONDARY STATS",
        `Attack: ${s.attack}`,
        `Defense: ${s.defense}`,
        `Speed: ${player.speed}`,
        `Crit: ${s.critChance}%`,
        `Accuracy: ${s.accuracy}%`,
        `Evasion: ${s.evasion}%`,
        `Block: ${s.blockChance}%`,
    ];
    this.secondaryStatsText.setText(lines.join("\n"));
  }
}
