// Space Browser, the game. The client draws what the server sends and asks for
// nothing else: this file is only the wiring, and the one loop that eases and draws.
import { install } from './dev';
import { bind, pointer, step } from './input';
import { toWorld } from './sim';
import { at, cam, canvas, cellOf, wpc } from './stage';
import { PIECE_R, TONE, View } from './view';
import { apply, bodies, follow, loose, ore, own, shots, ships, state } from './world';

const view = new View(canvas);
addEventListener('resize', () => view.resize());
if (import.meta.env.DEV) install();
bind();

// What the pointer is over, in world units: a piece of a hull is round, a body is
// as round as it is drawn. Nothing here decides anything, it only names the cell.
const over = (x: number, y: number, p: { x: number; y: number }, r: number) =>
  (x - p.x) ** 2 + (y - p.y) ** 2 <= r * r;
// On the map every mark is exactly one cell wide, so it is hit as one cell.
const tile = (x: number, y: number) => {
  const r = wpc();
  for (const s of ships.values()) if (s.id !== state?.you && !s.ai && over(x, y, s, r)) return TONE.hull;
  for (const s of state?.systems ?? []) if (over(x, y, s, r)) return TONE.body;
  return TONE.space;
};
const spot = (x: number, y: number) => {
  if (cam.scene === 'galaxy') return tile(x, y);
  for (const s of ships.values()) {
    if (s.id === state?.you) continue; // your own hull is not a target
    if (s.pieces.some((p) => over(x, y, toWorld(s, p), PIECE_R))) return TONE.hull;
  }
  for (const b of bodies.values()) if (over(x, y, b, b.r)) return TONE.body;
  return TONE.space;
};

let last = performance.now();
function frame(): void {
  const now = performance.now();
  const dt = Math.min(0.05, Math.max(0, now - last) / 1000);
  last = now;

  step(dt);
  apply(dt);
  follow(dt);

  // The pointer is a cell mark like the order marker, so it is placed from the
  // camera every frame: a pan slides the world under a pointer that never moved.
  const p = pointer();
  const c = p && cellOf(p.clientX, p.clientY);
  const w = p && at(p);
  view.setPointer(c ? c.cellX : null, c?.cellY, w ? spot(w.x, w.y) : undefined);

  // The marker is the order the server is flying: never a click of our own, and
  // never one it has already flown.
  const me = own();
  if (cam.scene === 'galaxy') {
    view.drawGalaxy(cam, state?.systems ?? [], [...ships.values()], state?.you ?? 0);
  } else {
    view.draw(
      cam,
      [...bodies.values()],
      [...ships.values()],
      state?.you ?? 0,
      [...shots.values()],
      [...loose.values()],
      [...ore.values()],
      me && me.order && !state?.held ? { x: me.tx, y: me.ty } : null,
    );
  }
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
