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

export class DeathOverlay {
  private scene: Phaser.Scene;
  private container!: Phaser.GameObjects.Container;
  private deathText!: Phaser.GameObjects.Text;

  constructor(scene: Phaser.Scene) {
    this.scene = scene;
  }

  create() {
    const { width, height } = this.scene.scale;
    this.container = this.scene.add.container(width / 2, height / 2);
    this.container.setScrollFactor(0).setDepth(3000).setVisible(false);

    const bg = this.scene.add.rectangle(0, 0, width, height, 0x000000, 0.85);
    this.container.add(bg);

    const panel = this.scene.add.rectangle(0, 0, 400, 500, 0x000000, 0.9);
    panel.setStrokeStyle(4, 0xff0000);
    this.container.add(panel);

    const title = this.scene.add.text(0, -200, "YOU DIED", {
      fontSize: "48px",
      color: "#ff0000",
      fontStyle: "bold"
    }).setOrigin(0.5);
    this.container.add(title);

    this.deathText = this.scene.add.text(0, -50, "", {
      fontSize: "20px",
      color: "#ffffff",
      align: "center",
      lineSpacing: 10
    }).setOrigin(0.5);
    this.container.add(this.deathText);

    const restartBtn = this.scene.add.text(0, 180, "NEW GAME", {
      fontSize: "24px",
      color: "#ffffff",
      backgroundColor: "#660000",
      padding: { x: 20, y: 10 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true });
    
    restartBtn.on("pointerdown", () => {
      const gameScene = this.scene.scene.get("GameScene");
      gameScene.events.emit("restart-game");
    });
    this.container.add(restartBtn);
  }

  show(data: { floor: number; gold: number; stats: Stats }) {
    const lines = [
      `Floor reached: ${data.floor}`,
      `Gold: ${data.gold}`,
      `Level: ${data.stats.level}`,
      `Attack: ${data.stats.attack.toFixed(1)}`,
      `Defense: ${data.stats.defense}`
    ];
    this.deathText.setText(lines.join("\n"));
    this.container.setVisible(true);
  }

  hide() {
    this.container.setVisible(false);
  }
}
