import { Game, AUTO, Scale } from 'phaser';
import { BootScene } from './scenes/BootScene.js';
import { MenuScene } from './scenes/MenuScene.js';
import { GameScene } from './scenes/GameScene.js';
import { GameOverScene } from './scenes/GameOverScene.js';
import { GAME_WIDTH, GAME_HEIGHT, GRAVITY } from './config/game.config.js';

const config = {
  type: AUTO,
  parent: 'game-container',
  width: GAME_WIDTH,
  height: GAME_HEIGHT,
  backgroundColor: '#0d001a',
  scale: {
    mode: Scale.FIT,
    autoCenter: Scale.CENTER_BOTH,
  },
  physics: {
    default: 'arcade',
    arcade: {
      gravity: { y: GRAVITY },
      debug: false,
    },
  },
  fps: {
    target: 60,
    min: 30,
  },
  disableContextMenu: true,
  scene: [BootScene, MenuScene, GameScene, GameOverScene],
  pixelArt: false,
  antialias: true,
};

const game = new Game(config);
window.game = game;

// Global crash guard: if an uncaught error happens during gameplay, recover to
// the menu instead of leaving a frozen canvas.
function recoverToMenu() {
  try {
    if (!game || !game.scene) return;
    const inGame = game.scene.isActive('GameScene');
    if (inGame) {
      game.scene.stop('GameScene');
      game.scene.start('MenuScene');
    }
  } catch (_) {
    /* swallow — last-resort guard */
  }
}

window.addEventListener('error', recoverToMenu);
window.addEventListener('unhandledrejection', recoverToMenu);
