import Phaser from 'phaser';
import { GAME_HEIGHT, GAME_WIDTH } from './data/constants';
import { BootScene } from './scenes/BootScene';
import { TitleScene } from './scenes/TitleScene';
import { NameScene } from './scenes/NameScene';
import { UIScene } from './scenes/UIScene';
import { DreamScene } from './scenes/DreamScene';
import { EndingScene } from './scenes/EndingScene';
import { createMapScenes } from './scenes/WorldScene';

const mapScenes = createMapScenes();

const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  width: GAME_WIDTH,
  height: GAME_HEIGHT,
  parent: 'game-container',
  backgroundColor: '#87CEEB',
  pixelArt: true,
  antialias: false,
  roundPixels: true,
  scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
  },
  physics: {
    default: 'arcade',
    arcade: {
      gravity: { x: 0, y: 0 },
      debug: false,
    },
  },
  scene: [BootScene, TitleScene, NameScene, ...mapScenes, UIScene, DreamScene, EndingScene],
  render: {
    pixelArt: true,
    antialias: false,
    roundPixels: true,
  },
};

// Integer scale: FIT already scales; force integer zoom via resize hook
function applyIntegerScale(game: Phaser.Game): void {
  const scale = game.scale;
  const w = window.innerWidth;
  const h = window.innerHeight;
  const zoom = Math.max(1, Math.floor(Math.min(w / GAME_WIDTH, h / GAME_HEIGHT)));
  scale.setZoom(1);
  // Phaser FIT handles CSS size; canvas internal stays 320x180
  const canvas = game.canvas;
  if (canvas) {
    canvas.style.imageRendering = 'pixelated';
    canvas.style.width = `${GAME_WIDTH * zoom}px`;
    canvas.style.height = `${GAME_HEIGHT * zoom}px`;
  }
}

const game = new Phaser.Game(config);
game.events.once('ready', () => applyIntegerScale(game));
window.addEventListener('resize', () => applyIntegerScale(game));

export default game;
