// main.ts：Phaser 配置（CONTRACT §4）——逻辑 320×180、pixelArt、整数倍放大居中。

import Phaser from 'phaser';
import { GAME_W, GAME_H } from './types';
import { setGame } from './core/gameRef';
import { audio } from './audio/AudioEngine';
import { DebugPanel } from './debug/DebugPanel';
import { BootScene } from './scenes/BootScene';
import { TitleScene } from './scenes/TitleScene';
import { HouseScene } from './scenes/HouseScene';
import { PlazaScene } from './scenes/PlazaScene';
import { BakeryScene } from './scenes/BakeryScene';
import { ShopScene } from './scenes/ShopScene';
import { ClinicScene } from './scenes/ClinicScene';
import { LakeScene } from './scenes/LakeScene';
import { FieldScene } from './scenes/FieldScene';
import { WellScene } from './scenes/WellScene';
import { FogScene } from './scenes/FogScene';
import { WhiteScene } from './scenes/WhiteScene';
import { UIScene } from './scenes/UIScene';
import { DreamScene } from './scenes/DreamScene';
import { EndingScene } from './scenes/EndingScene';

const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  width: GAME_W,
  height: GAME_H,
  pixelArt: true,
  parent: 'game',
  backgroundColor: '#000000',
  scale: {
    mode: Phaser.Scale.NONE,
    autoCenter: Phaser.Scale.CENTER_BOTH,
    parent: 'game',
  },
  physics: {
    default: 'arcade',
    arcade: { debug: false },
  },
  scene: [
    BootScene, TitleScene,
    HouseScene, PlazaScene, BakeryScene, ShopScene, ClinicScene,
    LakeScene, FieldScene, WellScene, FogScene, WhiteScene,
    UIScene, DreamScene, EndingScene,
  ],
};

const game = new Phaser.Game(config);
setGame(game);
new DebugPanel();

// 测试钩子（无 UI 痕迹，供验收脚本内省）
import { director } from './core/CorruptionDirector';
import { petalCount } from './scenes/UIScene';
(window as unknown as Record<string, unknown>).__game = game;
(window as unknown as Record<string, unknown>).__director = director;
(window as unknown as Record<string, unknown>).__audio = audio;
(window as unknown as Record<string, unknown>).__petalCount = petalCount;

// 整数倍放大居中：canvas style 宽高 = 320k×180k，k = max(1, floor(min(winW/320, winH/180)))
function fitCanvas(): void {
  const canvas = game.canvas;
  if (!canvas) return;
  const k = Math.max(1, Math.floor(Math.min(window.innerWidth / GAME_W, window.innerHeight / GAME_H)));
  canvas.style.width = `${GAME_W * k}px`;
  canvas.style.height = `${GAME_H * k}px`;
}
window.addEventListener('resize', fitCanvas);
game.events.once('ready', fitCanvas);
fitCanvas();

// 首次用户交互后再启动 AudioContext
const bootAudio = (): void => {
  audio.start();
  window.removeEventListener('pointerdown', bootAudio);
  window.removeEventListener('keydown', bootAudio);
};
window.addEventListener('pointerdown', bootAudio);
window.addEventListener('keydown', bootAudio);
