import { Application, Container } from "pixi.js";
import { CANVAS_WIDTH, CANVAS_HEIGHT } from "./game.config";
import { initParticles } from "./particles";
import { createMenuScene } from "./scenes/menuScene";
import { createGameScene } from "./scenes/gameScene";
import { createResultScene } from "./scenes/resultScene";
import { createHelpScene } from "./scenes/helpScene";
import { playBGM, stopBGM } from "./audio";

export const app = new Application();

export type SceneName = "menu" | "help" | "game" | "result";

export let currentScene: Container | null = null;
export let boxesCompleted = 0;

export function setBoxesCompleted(n: number) {
  boxesCompleted = n;
}

const sceneContainer = new Container();

export async function gotoScene(name: SceneName) {
  if (currentScene) {
    sceneContainer.removeChild(currentScene);
    currentScene.destroy({ children: true });
    currentScene = null;
  }

  let scene: Container;

  if (name === "menu") {
    scene = createMenuScene(gotoScene);
    playBGM();
  } else if (name === "help") {
    scene = createHelpScene(gotoScene);
  } else if (name === "game") {
    scene = createGameScene(app, gotoScene);
    playBGM();
  } else {
    scene = createResultScene(gotoScene, boxesCompleted);
  }

  currentScene = scene;
  sceneContainer.addChild(scene);
}

async function init() {
  await app.init({
    width: CANVAS_WIDTH,
    height: CANVAS_HEIGHT,
    backgroundColor: 0xfff3e0,
    antialias: true,
  });

  document.body.appendChild(app.canvas);

  app.stage.addChild(sceneContainer);

  const overlayContainer = new Container();
  app.stage.addChild(overlayContainer);
  initParticles(app, overlayContainer);

  gotoScene("menu");
}

document.fonts.ready.then(() => {
  init();
});
