import Phaser from "phaser";
import { CAMPAIGN_LEVELS } from "../../game/content/levels";
import type { HudController } from "../../ui/hud";
import { ensureBackgroundMusic } from "../audio/backgroundMusic";
import { createMenuBackdrop, createMenuButton } from "./menuVisuals";

interface SelectKeys {
  esc: Phaser.Input.Keyboard.Key;
}

export class LevelSelectScene extends Phaser.Scene {
  private readonly hud: HudController;

  private keys!: SelectKeys;

  constructor(hud: HudController) {
    super("level-select");
    this.hud = hud;
  }

  create(): void {
    this.hud.setVisible(false);
    ensureBackgroundMusic(this);
    createMenuBackdrop(this);

    const width = this.scale.width;
    const height = this.scale.height;

    this.add.text(width / 2, 58, "Выбор Уровня", {
      fontFamily: '"Chakra Petch", "Trebuchet MS", sans-serif',
      fontSize: "56px",
      color: "#d8feff",
      stroke: "#6ef0ff",
      strokeThickness: 2
    }).setOrigin(0.5);

    createMenuButton(this, {
      x: 116,
      y: 60,
      width: 176,
      height: 54,
      title: "Назад",
      onClick: () => this.scene.start("main-menu")
    });

    const columns = 3;
    const buttonWidth = 232;
    const buttonHeight = 84;
    const gapX = 18;
    const gapY = 14;
    const rows = Math.ceil(CAMPAIGN_LEVELS.length / columns);

    const totalWidth = columns * buttonWidth + (columns - 1) * gapX;
    const totalHeight = rows * buttonHeight + (rows - 1) * gapY;

    const startX = width / 2 - totalWidth / 2 + buttonWidth / 2;
    const startY = Math.max(176, height / 2 - totalHeight / 2 + 78);

    CAMPAIGN_LEVELS.forEach((level, index) => {
      const col = index % columns;
      const row = Math.floor(index / columns);
      const x = startX + col * (buttonWidth + gapX);
      const y = startY + row * (buttonHeight + gapY);
      const levelNumber = `${index + 1}`;

      createMenuButton(this, {
        x,
        y,
        width: buttonWidth,
        height: buttonHeight,
        title: `Уровень ${levelNumber}`,
        subtitle: level.title,
        onClick: () => this.scene.start("game", { startLevelIndex: index })
      });
    });

    this.keys = this.input.keyboard?.addKeys({
      esc: Phaser.Input.Keyboard.KeyCodes.ESC
    }) as SelectKeys;
  }

  update(): void {
    if (Phaser.Input.Keyboard.JustDown(this.keys.esc)) {
      this.scene.start("main-menu");
    }
  }
}
