import Phaser from 'phaser';
import { effectTracks, musicTracks } from './game/audio/audioAssets';
import { soundDirector } from './game/audio/SoundDirector';
import { BattleScene } from './game/scenes/BattleScene';
import { BootScene } from './game/scenes/BootScene';
import { CampScene } from './game/scenes/CampScene';
import { StoryScene } from './game/scenes/StoryScene';
import { TitleScene } from './game/scenes/TitleScene';
import './styles/global.css';

declare global {
  interface Window {
    __HEROS_GAME__?: Phaser.Game;
    __HEROS_DEBUG__?: HerosDebugApi;
  }
}

type DebugBattleScene = Phaser.Scene & {
  getDebugState?: () => unknown;
  toggleDebugOverlay?: () => void;
  debugForceBattleOutcome?: (outcome: 'victory' | 'defeat') => void;
};

type DebugCampScene = Phaser.Scene & {
  getDebugState?: () => unknown;
};

type HerosDebugApi = {
  game: Phaser.Game;
  activeScenes: () => string[];
  battle: () => unknown;
  camp: () => unknown;
  goToBattle: () => void;
  goToCamp: () => void;
  forceBattleOutcome: (outcome: 'victory' | 'defeat') => void;
  scene: (key: string) => Phaser.Scene | undefined;
  toggleBattleOverlay: () => void;
};

const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  parent: 'game',
  width: 1280,
  height: 720,
  backgroundColor: '#10131a',
  scale: {
    mode: Phaser.Scale.RESIZE,
    autoCenter: Phaser.Scale.CENTER_BOTH
  },
  scene: [BootScene, TitleScene, StoryScene, BattleScene, CampScene]
};

soundDirector.registerMusicTracks(musicTracks);
soundDirector.registerEffectTracks(effectTracks);

const game = new Phaser.Game(config);

if (import.meta.env.DEV) {
  window.__HEROS_GAME__ = game;
  window.__HEROS_DEBUG__ = createDebugApi(game);
  console.info('[Heros Debug] Use window.__HEROS_DEBUG__.battle() or press F9 in battle.');
}

function createDebugApi(game: Phaser.Game): HerosDebugApi {
  const scene = (key: string) => game.scene.getScene(key);
  const battleScene = () => scene('BattleScene') as DebugBattleScene | undefined;
  const campScene = () => scene('CampScene') as DebugCampScene | undefined;

  return {
    game,
    activeScenes: () => game.scene.getScenes(true).map((activeScene) => activeScene.scene.key),
    battle: () => battleScene()?.getDebugState?.() ?? { active: false, reason: 'BattleScene is not active yet.' },
    camp: () => campScene()?.getDebugState?.() ?? { active: false, reason: 'CampScene is not active yet.' },
    goToBattle: () => {
      game.scene.start('BattleScene');
    },
    goToCamp: () => {
      game.scene.start('CampScene');
    },
    forceBattleOutcome: (outcome) => {
      battleScene()?.debugForceBattleOutcome?.(outcome);
    },
    scene,
    toggleBattleOverlay: () => {
      battleScene()?.toggleDebugOverlay?.();
    }
  };
}
