import { Game } from './core/Game';

/**
 * Entry point. Boots the game and shows a friendly message if WebGL is unavailable
 * or initialisation fails, instead of a blank screen.
 */
function showFatal(message: string): void {
  const ui = document.getElementById('ui-root');
  if (!ui) return;
  const box = document.createElement('div');
  box.className = 'fatal';
  box.innerHTML = `<h2>Oh no! 🍐</h2><p>${message}</p><p>Try a recent version of Chrome, Edge, Firefox or Safari.</p>`;
  ui.append(box);
}

function webglAvailable(): boolean {
  try {
    const c = document.createElement('canvas');
    return !!(c.getContext('webgl2') || c.getContext('webgl'));
  } catch {
    return false;
  }
}

async function boot(): Promise<void> {
  const canvas = document.getElementById('game-canvas') as HTMLCanvasElement | null;
  const ui = document.getElementById('ui-root');
  if (!canvas || !ui) return;
  if (!webglAvailable()) {
    showFatal('Your browser does not support WebGL, which Peipei needs to explore the forest.');
    return;
  }
  try {
    const game = new Game(canvas, ui);
    // Exposed for debugging from the browser console.
    (window as unknown as { game: Game }).game = game;
    await game.init();
  } catch (err) {
    console.error(err);
    showFatal('Something went wrong while loading the adventure.');
  }
}

void boot();
