// An agent driving this page sees no cursor and cannot know where the camera is,
// so it gets the transform the game itself uses, never a copy of it: world point
// to screen pixel, screen pixel to world point, and every clickable thing already
// converted. It also gets the pointer drawn in cells, because a screenshot cannot
// show the browser's own cursor. Nothing here runs in a build a player sees.
import { CELL } from './view';
import { toWorld } from './sim';
import { at, cam, cellOf, rect, screen, screenOf } from './stage';
import { bodies, loose, ore, ships, state } from './world';

type Target = {
  id: number;
  kind: string; // me, ship, piece, loose, ore, or a body kind
  owner: number; // the hull a piece belongs to, 0 for anything loose
  x: number;
  y: number;
  px: number;
  py: number;
  cellX: number;
  cellY: number;
  cellPx: number; // the centre of that cell: a click lands on a glyph, not between four
  cellPy: number;
  d: number; // world distance from your hull, nearest first
};

// The canvas box and the world<->screen transform, read once per use: a layout read
// per target would make the pointer cost a forced reflow for every thing on screen.
const boxOf = (r: DOMRect) => ({
  left: r.left,
  top: r.top,
  width: r.width,
  height: r.height,
  cell: CELL,
  cols: r.width / CELL,
  rows: r.height / CELL,
});
const canvasBox = () => boxOf(rect());

const targets = (): Target[] => {
  const me = ships.get(state?.you ?? 0);
  const galaxy = cam.scene === 'galaxy';
  const r = rect();
  const box = boxOf(r);
  const out: Target[] = [];
  const add = (id: number, kind: string, owner: number, x: number, y: number) => {
    const s = screenOf(r, x, y);
    const c = cellOf(s.px, s.py, r);
    out.push({
      id,
      kind,
      owner,
      x,
      y,
      px: s.px,
      py: s.py,
      ...c,
      cellPx: box.left + (c.cellX + 0.5) * CELL,
      cellPy: box.top + (c.cellY + 0.5) * CELL,
      d: me ? Math.hypot(x - me.x, y - me.y) : 0,
    });
  };
  for (const s of ships.values()) {
    if (galaxy && s.ai) continue; // the map draws players only
    add(s.id, s.id === state?.you ? 'me' : s.ai ? 'ai' : 'ship', 0, s.x, s.y);
    if (galaxy) continue; // and one dot per ship, not its hull
    for (const p of s.pieces) {
      const w = toWorld(s, p);
      add(p.id, 'piece', s.id, w.x, w.y);
    }
  }
  if (galaxy) {
    // The map draws systems and nothing else: a body, an ore or a round is not a
    // glyph at this scale, so it is not a target either.
    for (const s of state?.systems ?? []) add(s.id, 'system', 0, s.x, s.y);
    return out.sort((a, b) => a.d - b.d);
  }
  for (const l of loose.values()) add(l.id, 'loose', 0, l.x, l.y);
  for (const o of ore.values()) add(o.id, 'ore', 0, o.x, o.y);
  for (const b of bodies.values()) add(b.id, b.kind, 0, b.x, b.y);
  return out.sort((a, b) => a.d - b.d);
};

let pointer: { px: number; py: number; cellX: number; cellY: number; world: { x: number; y: number } } | null = null;
const dev = import.meta.env.DEV;
const label = dev ? document.createElement('pre') : null;

const game = {
  get cam() {
    return { x: cam.x, y: cam.y, zoom: cam.zoom, follow: cam.follow, scene: cam.scene };
  },
  get state() {
    return state;
  },
  get pointer() {
    return pointer;
  },
  canvas: canvasBox,
  cellOf,
  toScreen: screen,
  toWorld: (px: number, py: number) => at({ clientX: px, clientY: py } as MouseEvent),
  targets,
};
declare global {
  interface Window {
    __game: typeof game;
  }
}

export function install(): void {
  if (!label) return;
  label.id = 'dev';
  document.body.append(label);
  window.__game = game;
}

// Drawn every move: one line of text spelling out the cell, the world point and
// the thing under it.
export function aim(e: MouseEvent): void {
  const c = cellOf(e.clientX, e.clientY);
  const w = at(e);
  pointer = { px: e.clientX, py: e.clientY, ...c, world: w };
  if (!label) return;
  const hit = targets().find((t) => t.cellX === c.cellX && t.cellY === c.cellY);
  label.textContent =
    `cell ${c.cellX},${c.cellY}  world ${Math.round(w.x)},${Math.round(w.y)}  px ${Math.round(e.clientX)},${Math.round(e.clientY)}` +
    (hit ? `\n${hit.kind} ${hit.id}` : '');
}
