import Phaser from 'phaser';
import { BootScene } from './scenes/BootScene';
import { MenuScene } from './scenes/MenuScene';
import { GameScene } from './scenes/GameScene';
import { SettingsScene } from './scenes/SettingsScene';

const installFullscreenRequest = (host: HTMLElement): void => {
  const canRequestFullscreen =
    typeof document.fullscreenEnabled === 'boolean'
      ? document.fullscreenEnabled
      : typeof host.requestFullscreen === 'function';

  if (!canRequestFullscreen || typeof host.requestFullscreen !== 'function') {
    return;
  }

  let handled = false;
  const events: Array<keyof DocumentEventMap> = ['pointerdown', 'keydown', 'touchstart'];

  const requestFullscreen = async (): Promise<void> => {
    if (handled) {
      return;
    }

    handled = true;
    events.forEach((eventName) => {
      document.removeEventListener(eventName, requestFullscreen);
    });

    if (document.fullscreenElement) {
      return;
    }

    try {
      await host.requestFullscreen();
    } catch {
      // Ignore browser denials so gameplay continues normally.
    }
  };

  events.forEach((eventName) => {
    document.addEventListener(eventName, requestFullscreen, { once: true });
  });
};

const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  width: 1280,
  height: 720,
  backgroundColor: '#1a5c2a',
  parent: 'game',
  scene: [BootScene, MenuScene, GameScene, SettingsScene],
  render: {
    antialias: true,
    antialiasGL: true,
    pixelArt: false,
    roundPixels: false,
  },
  scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
  },
};

const gameHost = document.getElementById('game');

if (gameHost instanceof HTMLElement) {
  installFullscreenRequest(gameHost);
}

new Phaser.Game(config);
