import Phaser from 'phaser';
import { Director } from './core/Director';
import { Audio } from './core/Audio';
import * as quests from './core/quests';
import { BootScene } from './scenes/BootScene';
import { TitleScene } from './scenes/TitleScene';
import { WorldScene } from './scenes/WorldScene';
import { UIScene } from './scenes/UIScene';
import { EndingScene } from './scenes/EndingScene';

const BASE_W = 320, BASE_H = 180;

const game = new Phaser.Game({
  type: Phaser.AUTO,
  parent: 'game',
  width: BASE_W,
  height: BASE_H,
  pixelArt: true,
  roundPixels: true,
  backgroundColor: '#101014',
  scale: { mode: Phaser.Scale.NONE, autoCenter: Phaser.Scale.CENTER_BOTH },
  physics: { default: 'arcade', arcade: { debug: false } },
  scene: [BootScene, TitleScene, WorldScene, UIScene, EndingScene],
});

// 整数倍缩放居中（§12）
function fit() {
  const z = Math.max(1, Math.floor(Math.min(window.innerWidth / BASE_W, window.innerHeight / BASE_H)));
  game.scale.setZoom(z);
}
window.addEventListener('resize', fit);
game.events.once('ready', fit);
fit();

// 音频随侵蚀阶段联动（§6.4/§6.6）——全局唯一订阅
Director.on('stage', () => Audio.setStage(Director.params));

// 首个用户手势后恢复音频（浏览器策略）
const resume = () => { Audio.ctx?.resume(); };
window.addEventListener('pointerdown', resume);
window.addEventListener('keydown', resume);

// 测试/验收辅助句柄（无害只读引用；正常游玩不使用）
(window as any).HV = {
  game, Director, Audio, quests,
  ui: () => game.scene.getScene('UI'),
  world: () => game.scene.getScene('World'),
  say: (nodes: any[]) => (game.scene.getScene('UI') as any).showDialogue(nodes),
};
