import './style.css';
import { loadAssets } from './assets';
import { Input } from './input';
import { Game } from './game';
import { VIEW } from './level';

const canvas = document.getElementById('game') as HTMLCanvasElement;
const ctx = canvas.getContext('2d')!;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';

function drawLoading(t: number): void {
  ctx.fillStyle = '#07090e';
  ctx.fillRect(0, 0, VIEW.w, VIEW.h);
  ctx.fillStyle = 'rgba(160,210,230,0.8)';
  ctx.font = '16px Georgia, serif';
  ctx.textAlign = 'center';
  ctx.fillText('lighting the lanterns…', VIEW.w / 2, VIEW.h / 2 - 18);
  ctx.strokeStyle = 'rgba(160,210,230,0.4)';
  ctx.strokeRect(VIEW.w / 2 - 100, VIEW.h / 2, 200, 8);
  ctx.fillRect(VIEW.w / 2 - 98, VIEW.h / 2 + 2, 196 * t, 4);
}
drawLoading(0);

const input = new Input();
const assets = await loadAssets((done, total) => drawLoading(done / total));
const game = new Game(assets, input);

// --- e2e / debug hook -------------------------------------------------------
declare global {
  interface Window {
    __game?: {
      state: () => ReturnType<Game['debugState']>;
      teleport: (x: number, y: number) => void;
    };
  }
}
window.__game = {
  state: () => game.debugState(),
  teleport: (x, y) => game.debugTeleport(x, y),
};

// title-screen clicks (RESET SAVE button), mapped to canvas coordinates
canvas.addEventListener('click', (e) => {
  const r = canvas.getBoundingClientRect();
  game.handleClick(
    ((e.clientX - r.left) / r.width) * VIEW.w,
    ((e.clientY - r.top) / r.height) * VIEW.h,
  );
});

// --- fixed-timestep loop ----------------------------------------------------
const STEP = 1 / 120;
let last = performance.now();
let acc = 0;
function frame(now: number): void {
  acc += Math.min(0.05, (now - last) / 1000);
  last = now;
  while (acc >= STEP) {
    game.update(STEP);
    acc -= STEP;
  }
  game.draw(ctx);
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
