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

interface VictorySceneData {
  levelCount?: number;
  isCustomSession?: boolean;
}

interface VictoryKeys {
  enter: Phaser.Input.Keyboard.Key;
  space: Phaser.Input.Keyboard.Key;
  r: Phaser.Input.Keyboard.Key;
  l: Phaser.Input.Keyboard.Key;
  m: Phaser.Input.Keyboard.Key;
  esc: Phaser.Input.Keyboard.Key;
}

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

  private keys!: VictoryKeys;

  private levelCount = 0;

  private isCustomSession = false;

  constructor(hud: HudController) {
    super("victory");
    this.hud = hud;
  }

  init(data: VictorySceneData): void {
    this.levelCount = Number.isFinite(data?.levelCount) ? Math.max(0, Math.floor(data.levelCount as number)) : 0;
    this.isCustomSession = data?.isCustomSession === true;
  }

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

    const width = this.scale.width;
    const height = this.scale.height;
    const subtitleY = 206;
    const hintY = height - 22;

    const primaryButtonHeight = 78;
    const secondaryButtonHeight = 78;
    const menuButtonHeight = 62;
    const buttonGap = 10;
    const buttonBlockHeight = primaryButtonHeight + secondaryButtonHeight + menuButtonHeight + buttonGap * 2;
    const buttonAreaTop = subtitleY + 28;
    const buttonAreaBottom = hintY - 50;
    const buttonBlockTop = buttonAreaTop + (buttonAreaBottom - buttonAreaTop - buttonBlockHeight) / 2;
    const firstButtonY = buttonBlockTop + primaryButtonHeight / 2;
    const secondButtonY = firstButtonY + primaryButtonHeight / 2 + buttonGap + secondaryButtonHeight / 2;
    const thirdButtonY = secondButtonY + secondaryButtonHeight / 2 + buttonGap + menuButtonHeight / 2;

    const glow = this.add.text(width / 2, 128, "ПОБЕДА", {
      fontFamily: '"Chakra Petch", "Trebuchet MS", sans-serif',
      fontSize: "94px",
      color: "#9cf8ff"
    }).setOrigin(0.5);
    glow.setAlpha(0.22);
    glow.setBlendMode(Phaser.BlendModes.ADD);

    const title = this.add.text(width / 2, 122, "ПОБЕДА", {
      fontFamily: '"Chakra Petch", "Trebuchet MS", sans-serif',
      fontSize: "82px",
      color: "#deffff",
      stroke: "#7ef2ff",
      strokeThickness: 2
    }).setOrigin(0.5);

    const subtitle = this.isCustomSession
      ? "Уровень успешно пройден."
      : this.levelCount > 0
        ? `Ты прошёл кампанию из ${this.levelCount} уровней.`
        : "Ты прошёл всю кампанию.";

    this.add.text(width / 2, 206, subtitle, {
      fontFamily: '"Chakra Petch", "Trebuchet MS", sans-serif',
      fontSize: "30px",
      color: "#9addea"
    }).setOrigin(0.5);

    createMenuButton(this, {
      x: width / 2,
      y: firstButtonY,
      width: 360,
      height: primaryButtonHeight,
      title: "Играть Снова",
      subtitle: "Старт кампании с первого уровня",
      onClick: () => this.scene.start("game", { startLevelIndex: 0 })
    });

    createMenuButton(this, {
      x: width / 2,
      y: secondButtonY,
      width: 360,
      height: secondaryButtonHeight,
      title: "Выбор Уровня",
      subtitle: "Выбрать любой этап",
      onClick: () => this.scene.start("level-select")
    });

    createMenuButton(this, {
      x: width / 2,
      y: thirdButtonY,
      width: 360,
      height: menuButtonHeight,
      title: "Главное Меню",
      onClick: () => this.scene.start("main-menu")
    });

    const hint = this.add.text(width / 2, height - 22, "Enter/Space/R - снова, L - уровни, M/Esc - меню", {
      fontFamily: '"Chakra Petch", "Trebuchet MS", sans-serif',
      fontSize: "18px",
      color: "#84cfdd"
    }).setOrigin(0.5);

    pulse(this, glow, 0.2, 0.36, 860);
    pulse(this, hint, 0.58, 1, 700);
    this.tweens.add({
      targets: title,
      scaleX: 1.015,
      scaleY: 1.015,
      duration: 1500,
      ease: "Sine.easeInOut",
      yoyo: true,
      repeat: -1
    });

    this.keys = this.input.keyboard?.addKeys({
      enter: Phaser.Input.Keyboard.KeyCodes.ENTER,
      space: Phaser.Input.Keyboard.KeyCodes.SPACE,
      r: Phaser.Input.Keyboard.KeyCodes.R,
      l: Phaser.Input.Keyboard.KeyCodes.L,
      m: Phaser.Input.Keyboard.KeyCodes.M,
      esc: Phaser.Input.Keyboard.KeyCodes.ESC
    }) as VictoryKeys;
  }

  update(): void {
    if (
      Phaser.Input.Keyboard.JustDown(this.keys.enter)
      || Phaser.Input.Keyboard.JustDown(this.keys.space)
      || Phaser.Input.Keyboard.JustDown(this.keys.r)
    ) {
      this.scene.start("game", { startLevelIndex: 0 });
      return;
    }

    if (Phaser.Input.Keyboard.JustDown(this.keys.l)) {
      this.scene.start("level-select");
      return;
    }

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

function pulse(
  scene: Phaser.Scene,
  target: Phaser.GameObjects.GameObject,
  from: number,
  to: number,
  duration: number
): void {
  scene.tweens.add({
    targets: target,
    alpha: { from, to },
    duration,
    ease: "Sine.easeInOut",
    repeat: -1,
    yoyo: true
  });
}
