Back to Gem Warden
SOURCE / PINNED RELEASE

Made of little things.

Gem Warden

Release
7c457bfe5427…
Author-recorded commit
fb5453b5fc06…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-3929629ef1d

Archive hash verified: 895b8dd430aad9fe…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/main.ts
import { STORAGE_DOMAIN, storage } from '@napplet/sdk';
import { runtimeHasDomain } from './domain-availability.js';
import * as G from './game.js';
import './styles.css';

// ------------------------------------------------------------------ palette

const C = {
  night: '#0b0f1a',
  earth: '#141b2b',
  earth2: '#18213a',
  path: '#3a3346',
  pathEdge: '#241f30',
  stone: '#5b5470',
  stoneHi: '#8c84a6',
  rock: '#2a2f45',
  panel: '#10131f',
  panelEdge: '#2b2f48',
  gold: '#f2c66d',
  goldDim: '#9c8350',
  text: '#e9e4f5',
  textDim: '#9a93b5',
  mana: '#47b8ff',
  manaDeep: '#1d4f87',
  danger: '#ff5a6e',
  ok: '#7cf0a0',
};

const FONT = 'ui-rounded, "Trebuchet MS", system-ui, sans-serif';

// ------------------------------------------------------------------ canvas

const canvas = document.querySelector<HTMLCanvasElement>('#game');
if (!canvas) throw new Error('Missing #game canvas');
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;

let W = 0;
let H = 0;
let dpr = 1;

function resize(): void {
  dpr = Math.min(2, window.devicePixelRatio || 1);
  W = Math.max(1, window.innerWidth);
  H = Math.max(1, window.innerHeight);
  canvas!.width = Math.round(W * dpr);
  canvas!.height = Math.round(H * dpr);
  canvas!.style.width = `${W}px`;
  canvas!.style.height = `${H}px`;
  bgKey = '';
}
window.addEventListener('resize', resize);

// ------------------------------------------------------------------ progress

interface Progress {
  stars: number[];
  sound: boolean;
}
let progress: Progress = { stars: G.FIELDS.map(() => 0), sound: true };
const PROGRESS_KEY = 'gem-warden-progress';

async function loadProgress(): Promise<void> {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) return;
  try {
    const raw = await withTimeout(storage.getItem(PROGRESS_KEY), 3000);
    if (!raw) return;
    const data = JSON.parse(raw) as Partial<Progress>;
    if (Array.isArray(data.stars)) {
      progress.stars = G.FIELDS.map((_, i) => Math.max(0, Math.min(3, Number(data.stars?.[i]) || 0)));
    }
    if (typeof data.sound === 'boolean') progress.sound = data.sound;
  } catch {
    // Storage is optional; progress then lasts for this session only.
  }
}

function saveProgress(): void {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) return;
  void withTimeout(storage.setItem(PROGRESS_KEY, JSON.stringify(progress)), 3000).catch(() => undefined);
}

function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
  return Promise.race([p, new Promise<T>((_, reject) => setTimeout(() => reject(new Error('timeout')), ms))]);
}

function unlocked(i: number): boolean {
  return i === 0 || progress.stars[i - 1] > 0;
}

// ------------------------------------------------------------------ sound

let audio: AudioContext | null = null;
let lastKillSound = 0;

function ensureAudio(): void {
  if (audio || !progress.sound) return;
  try {
    audio = new AudioContext();
  } catch {
    audio = null;
  }
}

function tone(freq: number, dur: number, type: OscillatorType, vol: number, slide = 0): void {
  if (!audio || !progress.sound) return;
  const t = audio.currentTime;
  const o = audio.createOscillator();
  const gain = audio.createGain();
  o.type = type;
  o.frequency.setValueAtTime(freq, t);
  if (slide) o.frequency.exponentialRampToValueAtTime(Math.max(30, freq * slide), t + dur);
  gain.gain.setValueAtTime(vol, t);
  gain.gain.exponentialRampToValueAtTime(0.0001, t + dur);
  o.connect(gain).connect(audio.destination);
  o.start(t);
  o.stop(t + dur + 0.02);
}

// ------------------------------------------------------------------ state

type Screen = 'menu' | 'play';
let screen: Screen = 'menu';
let game: G.Game | null = null;
let speed = 1;
let paused = false;
let buildMode: G.StructKind | null = null;
let grade = 1;
let selected: G.GemRef | null = null;
let toast = { text: '', t: 0 };
let resultSaved = false;

interface Particle {
  x: number;
  y: number;
  vx: number;
  vy: number;
  life: number;
  max: number;
  color: string;
  size: number;
  text?: string;
}
let particles: Particle[] = [];

function startField(i: number): void {
  game = G.newGame(i);
  screen = 'play';
  widgets = [];
  speed = 1;
  paused = false;
  buildMode = null;
  selected = null;
  grade = 1;
  particles = [];
  resultSaved = false;
  bgKey = '';
}

function flash(text: string): void {
  toast = { text, t: 2.2 };
}

// ------------------------------------------------------------------ layout

interface Rect {
  x: number;
  y: number;
  w: number;
  h: number;
}

interface Layout {
  field: Rect;
  tile: number;
  panel: Rect;
  portrait: boolean;
}

function computeLayout(): Layout {
  const portrait = W < H * 1.15;
  let panel: Rect;
  let area: Rect;
  if (portrait) {
    const fieldH = (W / G.COLS) * G.ROWS;
    const ph = Math.round(Math.min(Math.max(H - fieldH, 210), 380));
    panel = { x: 0, y: H - ph, w: W, h: ph };
    area = { x: 0, y: 0, w: W, h: H - ph };
  } else {
    const pw = Math.round(Math.min(Math.max(W * 0.27, 200), 300));
    panel = { x: W - pw, y: 0, w: pw, h: H };
    area = { x: 0, y: 0, w: W - pw, h: H };
  }
  const tile = Math.max(4, Math.min(area.w / G.COLS, area.h / G.ROWS));
  const fw = tile * G.COLS;
  const fh = tile * G.ROWS;
  return {
    field: { x: area.x + (area.w - fw) / 2, y: area.y + (area.h - fh) / 2, w: fw, h: fh },
    tile,
    panel,
    portrait,
  };
}

// ------------------------------------------------------------------ UI widgets

interface Widget extends Rect {
  id: string;
  tap?: () => void;
  gemRef?: G.GemRef;
  drop?: G.GemRef | 'sell';
  forge?: G.GemColor;
  random?: boolean;
}
let widgets: Widget[] = [];

function inside(r: Rect, x: number, y: number): boolean {
  return x >= r.x && y >= r.y && x <= r.x + r.w && y <= r.y + r.h;
}

function roundRect(r: Rect, rad: number): void {
  const rr = Math.max(0, Math.min(rad, r.w / 2, r.h / 2));
  ctx.beginPath();
  ctx.moveTo(r.x + rr, r.y);
  ctx.arcTo(r.x + r.w, r.y, r.x + r.w, r.y + r.h, rr);
  ctx.arcTo(r.x + r.w, r.y + r.h, r.x, r.y + r.h, rr);
  ctx.arcTo(r.x, r.y + r.h, r.x, r.y, rr);
  ctx.arcTo(r.x, r.y, r.x + r.w, r.y, rr);
  ctx.closePath();
}

function text(s: string, x: number, y: number, size: number, color: string, align: CanvasTextAlign = 'left', weight = 600): void {
  ctx.font = `${weight} ${size}px ${FONT}`;
  ctx.fillStyle = color;
  ctx.textAlign = align;
  ctx.textBaseline = 'middle';
  ctx.fillText(s, x, y);
}

function fitText(s: string, maxW: number, size: number, weight = 600): number {
  ctx.font = `${weight} ${size}px ${FONT}`;
  const w = ctx.measureText(s).width;
  return w > maxW ? Math.max(7, size * (maxW / w)) : size;
}

function button(r: Rect, id: string, label: string, opts: { active?: boolean; disabled?: boolean; sub?: string; tap?: () => void; accent?: string } = {}): void {
  const hover = pointer.inside && inside(r, pointer.x, pointer.y);
  roundRect(r, Math.min(10, r.h * 0.3));
  ctx.fillStyle = opts.active ? '#2c2650' : hover && !opts.disabled ? '#1d2138' : '#161a2c';
  ctx.fill();
  ctx.lineWidth = opts.active ? 2 : 1;
  ctx.strokeStyle = opts.active ? C.gold : opts.accent ?? C.panelEdge;
  ctx.stroke();
  const col = opts.disabled ? C.textDim : C.text;
  if (opts.sub) {
    const s = fitText(label, r.w - 8, Math.min(15, r.h * 0.36));
    text(label, r.x + r.w / 2, r.y + r.h * 0.37, s, col, 'center', 700);
    const s2 = fitText(opts.sub, r.w - 8, Math.min(12, r.h * 0.28), 500);
    text(opts.sub, r.x + r.w / 2, r.y + r.h * 0.72, s2, opts.disabled ? C.danger : C.goldDim, 'center', 500);
  } else {
    const s = fitText(label, r.w - 8, Math.min(15, r.h * 0.42));
    text(label, r.x + r.w / 2, r.y + r.h / 2, s, col, 'center', 700);
  }
  widgets.push({ ...r, id, tap: opts.tap });
}

// ------------------------------------------------------------------ gem drawing

/** Gem outline by grade: rounded triangle, square, pentagon, hexagon, then circle. */
function gemPath(gr: number, cx: number, cy: number, r: number): void {
  ctx.beginPath();
  if (gr >= 5) {
    ctx.arc(cx, cy, r * 0.92, 0, Math.PI * 2);
    return;
  }
  const sides = gr + 2;
  const off = sides === 4 ? -Math.PI / 4 : -Math.PI / 2;
  // The triangle's centroid sits low, so lift it and grow it to match the others' weight.
  const rr = sides === 3 ? r * 1.12 : r;
  const oy = sides === 3 ? r * 0.12 : 0;
  const pts: [number, number][] = [];
  for (let i = 0; i < sides; i++) {
    const a = (i / sides) * Math.PI * 2 + off;
    pts.push([cx + Math.cos(a) * rr, cy + oy + Math.sin(a) * rr]);
  }
  const round = rr * (sides === 3 ? 0.3 : 0.18);
  const mid = (i: number): [number, number] => {
    const p = pts[i % sides];
    const q = pts[(i + 1) % sides];
    return [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2];
  };
  const m0 = mid(sides - 1);
  ctx.moveTo(m0[0], m0[1]);
  for (let i = 0; i < sides; i++) {
    const m = mid(i);
    ctx.arcTo(pts[i][0], pts[i][1], m[0], m[1], round);
  }
  ctx.closePath();
}

function drawGem(gem: G.Gem, cx: number, cy: number, r: number, glow = false, label = true): void {
  const hex = G.gemColorHex(gem);
  const gr = G.gemGrade(gem);
  ctx.save();
  if (glow) {
    ctx.shadowColor = hex;
    ctx.shadowBlur = r * 0.9;
  }
  gemPath(gr, cx, cy, r);
  const grad = ctx.createRadialGradient(cx - r * 0.3, cy - r * 0.35, r * 0.1, cx, cy, r);
  grad.addColorStop(0, '#ffffff');
  grad.addColorStop(0.25, hex);
  grad.addColorStop(1, shade(hex, -0.55));
  ctx.fillStyle = grad;
  ctx.fill();
  ctx.shadowBlur = 0;
  ctx.lineWidth = Math.max(1, r * 0.08);
  ctx.strokeStyle = shade(hex, 0.35);
  ctx.stroke();
  // inner facet
  gemPath(gr, cx, cy, r * 0.5);
  ctx.strokeStyle = 'rgba(255,255,255,0.35)';
  ctx.lineWidth = Math.max(0.6, r * 0.05);
  ctx.stroke();
  ctx.restore();
  if (label && r >= 7) {
    const fs = Math.max(8, r * 0.75);
    ctx.font = `800 ${fs}px ${FONT}`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.lineWidth = Math.max(2, fs * 0.22);
    ctx.strokeStyle = 'rgba(8,8,16,0.85)';
    ctx.strokeText(String(gr), cx + r * 0.62, cy + r * 0.58);
    ctx.fillStyle = '#fff';
    ctx.fillText(String(gr), cx + r * 0.62, cy + r * 0.58);
  }
}

function shade(hex: string, amt: number): string {
  const n = parseInt(hex.slice(1), 16);
  let r = (n >> 16) & 255;
  let g = (n >> 8) & 255;
  let b = n & 255;
  if (amt < 0) {
    r *= 1 + amt;
    g *= 1 + amt;
    b *= 1 + amt;
  } else {
    r += (255 - r) * amt;
    g += (255 - g) * amt;
    b += (255 - b) * amt;
  }
  return `rgb(${Math.round(r)},${Math.round(g)},${Math.round(b)})`;
}

// ------------------------------------------------------------------ background

let bgKey = '';
let bg: HTMLCanvasElement | null = null;

function renderBackground(L: Layout, g: G.Game): void {
  const k = `${W}x${H}:${dpr}:${g.fieldIndex}`;
  if (k === bgKey && bg) return;
  bgKey = k;
  bg = document.createElement('canvas');
  bg.width = Math.round(L.field.w * dpr);
  bg.height = Math.round(L.field.h * dpr);
  const b = bg.getContext('2d') as CanvasRenderingContext2D;
  b.scale(dpr, dpr);
  const t = L.tile;
  const rng = G.makeRng(99 + g.fieldIndex);
  b.fillStyle = C.earth;
  b.fillRect(0, 0, L.field.w, L.field.h);
  for (let x = 0; x < G.COLS; x++)
    for (let y = 0; y < G.ROWS; y++) {
      b.fillStyle = (x + y) % 2 ? C.earth : C.earth2;
      b.globalAlpha = 0.55;
      b.fillRect(x * t, y * t, t, t);
      b.globalAlpha = 1;
      for (let i = 0; i < 3; i++) {
        b.fillStyle = `rgba(120,170,140,${0.05 + rng() * 0.07})`;
        b.fillRect(x * t + rng() * t, y * t + rng() * t, Math.max(1, t * 0.06), Math.max(1, t * 0.14));
      }
    }
  // path
  for (const kk of g.pathTiles) {
    const [x, y] = kk.split(',').map(Number);
    b.fillStyle = C.pathEdge;
    b.fillRect(x * t - t * 0.06, y * t - t * 0.06, t * 1.12, t * 1.12);
  }
  for (const kk of g.pathTiles) {
    const [x, y] = kk.split(',').map(Number);
    b.fillStyle = C.path;
    b.fillRect(x * t + 0.5, y * t + 0.5, t - 1, t - 1);
    for (let i = 0; i < 3; i++) {
      b.fillStyle = `rgba(255,255,255,${0.03 + rng() * 0.04})`;
      const s = t * (0.15 + rng() * 0.2);
      b.beginPath();
      b.ellipse(x * t + rng() * t, y * t + rng() * t, s, s * 0.6, rng() * 3, 0, Math.PI * 2);
      b.fill();
    }
  }
  // rocks
  for (const [x, y] of g.field.rocks) {
    const cx = (x + 0.5) * t;
    const cy = (y + 0.5) * t;
    b.fillStyle = C.rock;
    b.beginPath();
    b.ellipse(cx, cy + t * 0.08, t * 0.42, t * 0.34, 0, 0, Math.PI * 2);
    b.fill();
    b.fillStyle = '#3b4160';
    b.beginPath();
    b.ellipse(cx - t * 0.08, cy - t * 0.04, t * 0.26, t * 0.2, -0.4, 0, Math.PI * 2);
    b.fill();
  }
  // portal at the start
  const [sx, sy] = g.pathPoints[0];
  const pg = b.createRadialGradient((sx + 0.5) * t, (sy + 0.5) * t, 1, (sx + 0.5) * t, (sy + 0.5) * t, t * 0.7);
  pg.addColorStop(0, '#000');
  pg.addColorStop(0.6, '#3a1030');
  pg.addColorStop(1, 'rgba(120,20,80,0)');
  b.fillStyle = pg;
  b.beginPath();
  b.arc((sx + 0.5) * t, (sy + 0.5) * t, t * 0.7, 0, Math.PI * 2);
  b.fill();
}

// ------------------------------------------------------------------ input

const pointer = { shift: false, x: 0, y: 0, inside: false, down: false, startX: 0, startY: 0, dragging: false, dragRef: null as G.GemRef | null, downWidget: null as Widget | null };

canvas.addEventListener('pointermove', (e) => {
  pointer.x = e.offsetX;
  pointer.y = e.offsetY;
  pointer.inside = true;
  if (pointer.down && pointer.dragRef && !pointer.dragging && Math.hypot(pointer.x - pointer.startX, pointer.y - pointer.startY) > 8) {
    pointer.dragging = true;
  }
});
canvas.addEventListener('pointerleave', () => {
  pointer.inside = false;
});
canvas.addEventListener('pointerdown', (e) => {
  ensureAudio();
  canvas.setPointerCapture(e.pointerId);
  pointer.x = e.offsetX;
  pointer.y = e.offsetY;
  pointer.inside = true;
  pointer.down = true;
  pointer.startX = pointer.x;
  pointer.startY = pointer.y;
  pointer.dragging = false;
  pointer.downWidget = widgetAt(pointer.x, pointer.y);
  pointer.dragRef = widgetGem(pointer.downWidget) ?? fieldGemAt(pointer.x, pointer.y);
});
canvas.addEventListener('pointerup', (e) => {
  pointer.shift = e.shiftKey;
  pointer.x = e.offsetX;
  pointer.y = e.offsetY;
  const wasDragging = pointer.dragging;
  const ref = pointer.dragRef;
  pointer.down = false;
  pointer.dragging = false;
  pointer.dragRef = null;
  if (wasDragging && ref) {
    dropGem(ref, pointer.x, pointer.y);
    return;
  }
  tapAt(pointer.x, pointer.y);
});
canvas.addEventListener('pointercancel', () => {
  pointer.down = false;
  pointer.dragging = false;
  pointer.dragRef = null;
});
canvas.addEventListener('contextmenu', (e) => e.preventDefault());

/** Inventory contents can change between frames, so resolve the gem at event time. */
function widgetGem(w: Widget | null): G.GemRef | undefined {
  if (!w || !game || typeof w.drop !== 'object' || w.drop.kind !== 'inv') return w?.gemRef;
  return game.inventory[w.drop.index] ? w.drop : undefined;
}

function widgetAt(x: number, y: number): Widget | null {
  for (let i = widgets.length - 1; i >= 0; i--) if (inside(widgets[i], x, y)) return widgets[i];
  return null;
}

function tileAt(x: number, y: number): [number, number] | null {
  const L = computeLayout();
  if (!inside(L.field, x, y)) return null;
  return [Math.floor((x - L.field.x) / L.tile), Math.floor((y - L.field.y) / L.tile)];
}

function structAt(x: number, y: number): G.Structure | null {
  if (!game) return null;
  const t = tileAt(x, y);
  if (!t) return null;
  return game.structures.find((s) => s.x === t[0] && s.y === t[1]) ?? null;
}

function fieldGemAt(x: number, y: number): G.GemRef | null {
  if (screen !== 'play') return null;
  const s = structAt(x, y);
  return s?.gem ? { kind: 'struct', id: s.id } : null;
}

function targetAt(x: number, y: number): G.GemRef | 'sell' | null {
  const w = widgetAt(x, y);
  if (w?.drop) return w.drop;
  const s = structAt(x, y);
  return s ? { kind: 'struct', id: s.id } : null;
}

function applyMove(src: G.GemRef, dst: G.GemRef | 'sell'): boolean {
  if (!game) return false;
  if (dst === 'sell') {
    const gem = G.gemAt(game, src);
    if (gem && G.sellGem(game, src)) {
      flash(`Sold for ${G.gemValue(gem)} mana`);
      tone(520, 0.15, 'triangle', 0.08, 0.6);
      return true;
    }
    return false;
  }
  const a = G.gemAt(game, src);
  const b = G.gemAt(game, dst);
  if (!G.moveGem(game, src, dst)) return false;
  const merged = G.gemAt(game, dst);
  if (a && b && merged) {
    const gr = G.gemGrade(merged);
    const next = Math.round(G.gradeProgress(merged) * 100);
    flash(next > 0 ? `Combined: G${gr} ${gemName(merged)}, ${next}% to G${gr + 1}` : `Combined into G${gr} ${gemName(merged)}`);
  }
  return true;
}

function dropGem(ref: G.GemRef, x: number, y: number): void {
  const dst = targetAt(x, y);
  if (dst) applyMove(ref, dst);
  selected = null;
}

function tapAt(x: number, y: number): void {
  const w = widgetAt(x, y);
  if (w && pointer.downWidget?.id === w.id) {
    const ref = widgetGem(w);
    if (ref) {
      if (selected && !G.sameRef(selected, ref)) {
        applyMove(selected, ref);
        selected = null;
      } else selected = selected && G.sameRef(selected, ref) ? null : ref;
      return;
    }
    if (w.drop && selected) {
      applyMove(selected, w.drop);
      selected = null;
      return;
    }
    w.tap?.();
    return;
  }
  if (screen !== 'play' || !game || game.state !== 'playing') return;
  const t = tileAt(x, y);
  if (!t) {
    selected = null;
    buildMode = null;
    return;
  }
  const s = structAt(x, y);
  if (buildMode && !s) {
    if (G.canBuild(game, buildMode, t[0], t[1])) {
      if (G.build(game, buildMode, t[0], t[1]) && !pointer.shift) buildMode = null;
    } else flash(buildMode === 'trap' ? 'Traps go on the path' : 'Towers go beside the path');
    return;
  }
  if (s) {
    const ref: G.GemRef = { kind: 'struct', id: s.id };
    if (selected && !G.sameRef(selected, ref)) {
      applyMove(selected, ref);
      selected = null;
    } else if (s.gem) selected = selected ? null : ref;
    return;
  }
  selected = null;
}

window.addEventListener('keydown', (e) => {
  if (screen === 'menu') {
    const n = Number(e.key);
    if (n >= 1 && n <= G.FIELDS.length && unlocked(n - 1)) startField(n - 1);
    return;
  }
  if (!game) return;
  const k = e.key.toLowerCase();
  if (game.state !== 'playing') {
    if (k === 'enter' || k === ' ') afterGame();
    if (k === 'escape') screen = 'menu';
    return;
  }
  if (k === 't') buildMode = buildMode === 'tower' ? null : 'tower';
  else if (k === 'r') buildMode = buildMode === 'trap' ? null : 'trap';
  else if (k === 'p') doPool();
  else if (k === 'n') doNextWave();
  else if (k === ' ') {
    paused = !paused;
    e.preventDefault();
  } else if (k === 'f') speed = speed === 3 ? 1 : speed + 1;
  else if (k === '+' || k === '=') grade = Math.min(10, grade + 1);
  else if (k === '-') grade = Math.max(1, grade - 1);
  else if ((k === 's' || k === 'delete' || k === 'backspace') && selected) {
    applyMove(selected, 'sell');
    selected = null;
  } else if (k === 'escape') {
    buildMode = null;
    selected = null;
  } else if (/^[1-6]$/.test(k)) {
    const color = game.field.colors[Number(k) - 1];
    if (color) makeGem(color);
  } else if (k === '0') {
    makeRandomGems();
  }
});

function forgePreview(color: G.GemColor): G.Gem {
  return { id: 0, mass: Math.pow(2, grade - 1), comp: { [color]: 1 }, kills: 0 };
}

function makeRandomGems(): void {
  if (!game) return;
  if (G.createRandomGems(game, grade).length) {
    tone(620 + grade * 40, 0.1, 'sine', 0.06, 1.5);
    setTimeout(() => tone(780 + grade * 40, 0.12, 'sine', 0.05, 1.5), 80);
    selected = null;
  }
}

function makeGem(color: G.GemColor): void {
  if (!game) return;
  const slot = G.createGem(game, color, grade);
  if (slot >= 0) {
    tone(660 + grade * 40, 0.12, 'sine', 0.06, 1.5);
    selected = null;
  }
}

function doPool(): void {
  if (!game) return;
  if (G.expandPool(game)) {
    flash(`Mana pool expanded · gains ×${game.manaMult.toFixed(2)}`);
    tone(300, 0.4, 'sine', 0.08, 2.5);
  }
}

function doNextWave(): void {
  if (!game) return;
  const bonus = G.callWaveEarly(game);
  if (bonus > 0) flash(`Wave called early · +${Math.round(bonus * game.manaMult)} mana`);
}

function afterGame(): void {
  if (!game) return;
  if (game.state === 'won' && game.fieldIndex + 1 < G.FIELDS.length) startField(game.fieldIndex + 1);
  else startField(game.fieldIndex);
}

// ------------------------------------------------------------------ game loop

let last = performance.now();
function frame(now: number): void {
  const dt = Math.min(0.1, (now - last) / 1000);
  last = now;
  if (screen === 'play' && game && !paused) {
    let left = dt * speed;
    while (left > 0) {
      const d = Math.min(1 / 60, left);
      G.step(game, d);
      left -= d;
    }
  }
  // Also while paused, so a refused action still explains itself.
  if (screen === 'play' && game) consumeEvents(game);
  if (game && game.state !== 'playing' && !resultSaved) {
    resultSaved = true;
    if (game.state === 'won') {
      const s = G.stars(game);
      progress.stars[game.fieldIndex] = Math.max(progress.stars[game.fieldIndex], s);
      saveProgress();
      tone(523, 0.25, 'triangle', 0.1);
      setTimeout(() => tone(784, 0.4, 'triangle', 0.1), 180);
    } else {
      tone(200, 0.8, 'sawtooth', 0.08, 0.4);
    }
  }
  toast.t -= dt;
  updateParticles(screen === 'play' && !paused ? dt * speed : 0);
  draw(now / 1000);
  requestAnimationFrame(frame);
}

function consumeEvents(g: G.Game): void {
  const L = computeLayout();
  const t = L.tile;
  for (const ev of g.events) {
    switch (ev.type) {
      case 'hit':
        for (let i = 0; i < (ev.crit ? 7 : 3); i++) {
          const a = Math.random() * Math.PI * 2;
          const v = (ev.crit ? 3 : 1.6) * (0.5 + Math.random());
          particles.push({ x: ev.x, y: ev.y, vx: Math.cos(a) * v, vy: Math.sin(a) * v, life: 0.35, max: 0.35, color: ev.color, size: t * (ev.crit ? 0.12 : 0.08) });
        }
        break;
      case 'kill':
        particles.push({ x: ev.x, y: ev.y - 0.2, vx: 0, vy: -0.9, life: 0.9, max: 0.9, color: C.mana, size: t * 0.32, text: `+${Math.round(ev.mana)}` });
        if (performance.now() - lastKillSound > 70) {
          lastKillSound = performance.now();
          tone(880 + Math.random() * 200, 0.07, 'square', 0.025, 0.5);
        }
        break;
      case 'banish':
        particles.push({ x: ev.x, y: ev.y - 0.3, vx: 0, vy: -0.6, life: 1.3, max: 1.3, color: C.danger, size: t * 0.4, text: `−${ev.cost}` });
        for (let i = 0; i < 14; i++) {
          const a = (i / 14) * Math.PI * 2;
          particles.push({ x: ev.x, y: ev.y, vx: Math.cos(a) * 3, vy: Math.sin(a) * 3, life: 0.6, max: 0.6, color: C.danger, size: t * 0.1 });
        }
        tone(160, 0.35, 'sawtooth', 0.07, 0.5);
        break;
      case 'build':
        tone(220, 0.18, 'triangle', 0.08, 1.6);
        for (let i = 0; i < 10; i++) {
          const a = Math.random() * Math.PI * 2;
          particles.push({ x: ev.x, y: ev.y, vx: Math.cos(a) * 1.4, vy: Math.sin(a) * 1.4, life: 0.5, max: 0.5, color: C.stoneHi, size: t * 0.07 });
        }
        break;
      case 'combine':
        tone(500, 0.12, 'sine', 0.07, 2);
        setTimeout(() => tone(750 + ev.grade * 30, 0.18, 'sine', 0.06, 1.3), 90);
        break;
      case 'wave':
        tone(110, 0.5, 'triangle', 0.09, 1.4);
        break;
      case 'error':
        flash(ev.message);
        tone(140, 0.12, 'square', 0.04);
        break;
    }
  }
  g.events.length = 0;
}

function updateParticles(dt: number): void {
  for (const p of particles) {
    p.life -= dt || 0.016;
    p.x += p.vx * dt;
    p.y += p.vy * dt;
    if (!p.text) {
      p.vx *= 0.92;
      p.vy *= 0.92;
    }
  }
  particles = particles.filter((p) => p.life > 0);
  if (particles.length > 600) particles.splice(0, particles.length - 600);
}

// ------------------------------------------------------------------ drawing

function draw(time: number): void {
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.fillStyle = C.night;
  ctx.fillRect(0, 0, W, H);
  widgets = [];
  if (W < 280 || H < 200) {
    wrapText('Gem Warden needs a bit more room. Make the frame larger or go full screen.', W / 2, H / 2 - 12, W - 16, 12, C.gold);
    return;
  }
  if (screen === 'menu' || !game) drawMenu(time);
  else drawPlay(game, time);
}

function drawMenu(time: number): void {
  const cx = W / 2;
  // drifting gem backdrop
  for (let i = 0; i < 14; i++) {
    const c = G.COLORS[i % 6];
    const x = ((i * 137 + time * 12 * (1 + (i % 3))) % (W + 80)) - 40;
    const y = (H * ((i * 61) % 100)) / 100;
    ctx.globalAlpha = 0.18;
    drawGem({ id: 0, mass: 1, comp: { [c]: 1 }, kills: 0 }, x, y, 10 + (i % 4) * 4);
    ctx.globalAlpha = 1;
  }
  const titleSize = Math.min(54, W * 0.09, H * 0.1);
  ctx.save();
  ctx.shadowColor = C.gold;
  ctx.shadowBlur = 18;
  text('Gem Warden', cx, H * 0.12, titleSize, C.gold, 'center', 800);
  ctx.restore();
  text('Forge gems, guard the orb.', cx, H * 0.12 + titleSize * 0.85, Math.max(11, titleSize * 0.32), C.textDim, 'center', 500);

  const cols = W > H * 1.2 ? 3 : 2;
  const rows = Math.ceil(G.FIELDS.length / cols);
  const top = H * 0.12 + titleSize * 1.4;
  const bottomSpace = Math.max(64, H * 0.14);
  const gap = Math.max(8, Math.min(W, H) * 0.02);
  const cw = Math.min(260, (W - gap * (cols + 1)) / cols);
  const ch = Math.min(120, (H - top - bottomSpace - gap * (rows + 1)) / rows);
  const gx = cx - (cw * cols + gap * (cols - 1)) / 2;
  G.FIELDS.forEach((f, i) => {
    const r = { x: gx + (i % cols) * (cw + gap), y: top + gap + Math.floor(i / cols) * (ch + gap), w: cw, h: ch };
    const open = unlocked(i);
    const hover = pointer.inside && inside(r, pointer.x, pointer.y) && open;
    roundRect(r, 12);
    ctx.fillStyle = open ? (hover ? '#1f2440' : '#151a2e') : '#0f1220';
    ctx.fill();
    ctx.strokeStyle = open ? (hover ? C.gold : C.panelEdge) : '#1a1d2c';
    ctx.lineWidth = hover ? 2 : 1;
    ctx.stroke();
    drawMiniMap(f, { x: r.x + 8, y: r.y + 8, w: r.h - 16, h: r.h - 16 }, open);
    const tx = r.x + r.h;
    const tw = r.w - r.h - 8;
    text(`${i + 1}. ${f.name}`, tx, r.y + r.h * 0.26, fitText(`${i + 1}. ${f.name}`, tw, Math.min(16, ch * 0.17), 700), open ? C.text : C.textDim, 'left', 700);
    text(open ? `${f.waves} waves` : 'Locked', tx, r.y + r.h * 0.5, Math.min(12, ch * 0.13), C.textDim, 'left', 500);
    const st = progress.stars[i];
    for (let s = 0; s < 3; s++) drawStar(tx + 9 + s * Math.min(22, ch * 0.2), r.y + r.h * 0.76, Math.min(8, ch * 0.075), s < st);
    let dx = tx + 9 + 3 * Math.min(22, ch * 0.2);
    for (const c of f.colors) {
      ctx.fillStyle = COLOR_HEX(c);
      ctx.beginPath();
      ctx.arc(dx, r.y + r.h * 0.76, Math.min(4, ch * 0.04), 0, Math.PI * 2);
      ctx.fill();
      dx += Math.min(10, ch * 0.09);
    }
    if (open) widgets.push({ ...r, id: `field-${i}`, tap: () => startField(i) });
  });

  const help = 'Build towers beside the path, forge gems and drop them in. Drop a gem onto another to combine; pure gems beat mixes. Monsters that reach the orb cost mana; run out and you lose.';
  wrapText(help, cx, H - bottomSpace + 6, Math.min(W - 24, 640), Math.max(10, Math.min(13, W / 50)), C.textDim);
  const sr = { x: W - 108, y: H - 36, w: 100, h: 28 };
  button(sr, 'sound', progress.sound ? 'Sound on' : 'Sound off', {
    tap: () => {
      progress.sound = !progress.sound;
      if (progress.sound) ensureAudio();
      saveProgress();
    },
  });
}

function COLOR_HEX(c: G.GemColor): string {
  return G.COLOR_INFO[c].hex;
}

function wrapText(s: string, cx: number, y: number, maxW: number, size: number, color: string): void {
  ctx.font = `500 ${size}px ${FONT}`;
  const words = s.split(' ');
  let line = '';
  let yy = y;
  for (const w of words) {
    const test = line ? `${line} ${w}` : w;
    if (ctx.measureText(test).width > maxW && line) {
      text(line, cx, yy, size, color, 'center', 500);
      line = w;
      yy += size * 1.35;
    } else line = test;
  }
  if (line) text(line, cx, yy, size, color, 'center', 500);
}

function drawStar(x: number, y: number, r: number, on: boolean): void {
  ctx.beginPath();
  for (let i = 0; i < 10; i++) {
    const a = (i / 10) * Math.PI * 2 - Math.PI / 2;
    const rr = i % 2 ? r * 0.45 : r;
    ctx.lineTo(x + Math.cos(a) * rr, y + Math.sin(a) * rr);
  }
  ctx.closePath();
  ctx.fillStyle = on ? C.gold : '#2a2d42';
  ctx.fill();
}

function drawMiniMap(f: G.FieldDef, r: Rect, open: boolean): void {
  const t = Math.min(r.w / G.COLS, r.h / G.ROWS);
  const ox = r.x + (r.w - t * G.COLS) / 2;
  const oy = r.y + (r.h - t * G.ROWS) / 2;
  ctx.fillStyle = open ? C.earth2 : '#11141f';
  ctx.fillRect(ox, oy, t * G.COLS, t * G.ROWS);
  ctx.strokeStyle = open ? C.stoneHi : '#2a2d42';
  ctx.lineWidth = Math.max(1.5, t * 0.8);
  ctx.lineJoin = 'round';
  ctx.beginPath();
  f.path.forEach(([x, y], i) => {
    const px = ox + (x + 0.5) * t;
    const py = oy + (y + 0.5) * t;
    if (i === 0) ctx.moveTo(px, py);
    else ctx.lineTo(px, py);
  });
  ctx.stroke();
  const [ex, ey] = f.path[f.path.length - 1];
  ctx.fillStyle = open ? C.mana : '#2a2d42';
  ctx.beginPath();
  ctx.arc(ox + (ex + 0.5) * t, oy + (ey + 0.5) * t, t * 1.1, 0, Math.PI * 2);
  ctx.fill();
}

function drawPlay(g: G.Game, time: number): void {
  const L = computeLayout();
  renderBackground(L, g);
  const t = L.tile;
  const fx = L.field.x;
  const fy = L.field.y;
  if (bg) ctx.drawImage(bg, fx, fy, L.field.w, L.field.h);

  const X = (v: number) => fx + v * t;
  const Y = (v: number) => fy + v * t;

  // build preview
  const hoverTile = pointer.inside ? tileAt(pointer.x, pointer.y) : null;
  if (buildMode && hoverTile && g.state === 'playing') {
    const ok = G.canBuild(g, buildMode, hoverTile[0], hoverTile[1]);
    ctx.fillStyle = ok ? 'rgba(124,240,160,0.22)' : 'rgba(255,90,110,0.22)';
    ctx.fillRect(X(hoverTile[0]), Y(hoverTile[1]), t, t);
    if (ok && buildMode === 'tower') {
      ctx.strokeStyle = 'rgba(124,240,160,0.35)';
      ctx.setLineDash([4, 4]);
      ctx.beginPath();
      ctx.arc(X(hoverTile[0] + 0.5), Y(hoverTile[1] + 0.5), t * 2.9, 0, Math.PI * 2);
      ctx.stroke();
      ctx.setLineDash([]);
    }
  }

  // orb
  const [ox, oy] = g.orb;
  const fill = g.mana / g.manaCap;
  const pulse = 1 + Math.sin(time * 2.2) * 0.05;
  ctx.save();
  ctx.shadowColor = C.mana;
  ctx.shadowBlur = t * 0.9;
  const og = ctx.createRadialGradient(X(ox + 0.4), Y(oy + 0.35), t * 0.05, X(ox + 0.5), Y(oy + 0.5), t * 0.62 * pulse);
  og.addColorStop(0, '#eaf8ff');
  og.addColorStop(0.35, C.mana);
  og.addColorStop(1, C.manaDeep);
  ctx.fillStyle = og;
  ctx.beginPath();
  ctx.arc(X(ox + 0.5), Y(oy + 0.5), t * 0.6 * pulse, 0, Math.PI * 2);
  ctx.fill();
  ctx.restore();
  ctx.strokeStyle = C.gold;
  ctx.lineWidth = Math.max(1.5, t * 0.07);
  ctx.beginPath();
  ctx.arc(X(ox + 0.5), Y(oy + 0.5), t * 0.78, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * fill);
  ctx.stroke();

  // structures
  const sel = selected && selected.kind === 'struct' ? selected.id : -1;
  for (const s of g.structures) {
    const x = X(s.x);
    const y = Y(s.y);
    if (s.kind === 'tower') {
      ctx.fillStyle = '#00000055';
      ctx.fillRect(x + t * 0.12, y + t * 0.16, t * 0.84, t * 0.84);
      roundRect({ x: x + t * 0.08, y: y + t * 0.08, w: t * 0.84, h: t * 0.84 }, t * 0.14);
      const sg = ctx.createLinearGradient(x, y, x, y + t);
      sg.addColorStop(0, C.stoneHi);
      sg.addColorStop(1, C.stone);
      ctx.fillStyle = sg;
      ctx.fill();
      ctx.fillStyle = '#1b1828';
      ctx.beginPath();
      ctx.arc(x + t / 2, y + t / 2, t * 0.3, 0, Math.PI * 2);
      ctx.fill();
    } else {
      ctx.strokeStyle = s.gem ? G.gemColorHex(s.gem) : C.stoneHi;
      ctx.globalAlpha = 0.75;
      ctx.lineWidth = Math.max(1, t * 0.06);
      ctx.beginPath();
      ctx.arc(x + t / 2, y + t / 2, t * 0.4, 0, Math.PI * 2);
      ctx.stroke();
      ctx.beginPath();
      for (let i = 0; i < 5; i++) {
        const a = (i / 5) * Math.PI * 2 * 2 - Math.PI / 2 + time * 0.3;
        ctx.lineTo(x + t / 2 + Math.cos(a) * t * 0.36, y + t / 2 + Math.sin(a) * t * 0.36);
      }
      ctx.closePath();
      ctx.stroke();
      ctx.globalAlpha = 1;
    }
    const dragged = pointer.dragging && pointer.dragRef?.kind === 'struct' && pointer.dragRef.id === s.id;
    if (s.gem && !dragged) drawGem(s.gem, x + t / 2, y + t / 2, t * (s.kind === 'trap' ? 0.24 : 0.27), true);
    if (s.id === sel) {
      ctx.strokeStyle = C.gold;
      ctx.lineWidth = 2;
      ctx.strokeRect(x + 1, y + 1, t - 2, t - 2);
    }
  }
  // range for selected or hovered structure gem
  const hovered = hoverTile ? g.structures.find((s) => s.x === hoverTile[0] && s.y === hoverTile[1]) : undefined;
  const ringStruct = g.structures.find((s) => s.id === sel) ?? (hovered?.gem ? hovered : undefined);
  if (ringStruct?.gem) {
    const st = G.gemStats(ringStruct.gem, ringStruct.kind);
    ctx.strokeStyle = 'rgba(242,198,109,0.55)';
    ctx.fillStyle = 'rgba(242,198,109,0.06)';
    ctx.lineWidth = 1.5;
    ctx.beginPath();
    ctx.arc(X(ringStruct.x + 0.5), Y(ringStruct.y + 0.5), st.range * t, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
  }

  // monsters
  for (const m of g.monsters) {
    const wob = Math.sin(time * 9 + m.wobble) * t * 0.04;
    const x = X(m.x);
    const y = Y(m.y) + wob;
    const r = t * MONSTER_LOOK[m.type].size;
    const col = MONSTER_LOOK[m.type].col;
    ctx.fillStyle = '#00000066';
    ctx.beginPath();
    ctx.ellipse(x, y + r * 0.8, r * 0.9, r * 0.35, 0, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = m.slowT > 0 ? shade(col, 0.15).replace('rgb', 'rgb') : col;
    if (m.type === 'brute') {
      roundRect({ x: x - r, y: y - r, w: r * 2, h: r * 2 }, r * 0.35);
      ctx.fill();
      ctx.strokeStyle = '#d6dbe8';
      ctx.lineWidth = Math.max(1, m.armor > 0 ? t * 0.05 : 0.5);
      ctx.stroke();
    } else if (m.type === 'runner') {
      diamond(x, y, r * 1.2);
      ctx.fill();
    } else {
      ctx.beginPath();
      ctx.arc(x, y, r, 0, Math.PI * 2);
      ctx.fill();
    }
    if (m.ward > 0) {
      // The ward ring thins as its charges run out.
      ctx.strokeStyle = 'rgba(207,216,255,0.9)';
      ctx.lineWidth = Math.max(1, t * 0.025 * Math.min(4, 1 + m.ward / 3));
      ctx.beginPath();
      ctx.arc(x, y, r + t * 0.09, 0, Math.PI * 2);
      ctx.stroke();
    }
    if (m.regen > 0 && m.poisonT <= 0) plus(x, y - r * 1.05, Math.max(2, r * 0.35), '#d8fff0');
    if (m.slowT > 0) {
      ctx.strokeStyle = '#7cc4ff';
      ctx.lineWidth = Math.max(1, t * 0.05);
      ctx.beginPath();
      ctx.arc(x, y, r + t * 0.05, 0, Math.PI * 2);
      ctx.stroke();
    }
    if (m.poisonT > 0) {
      ctx.fillStyle = 'rgba(79,224,106,0.8)';
      ctx.beginPath();
      ctx.arc(x + r * 0.5, y - r * 0.6, Math.max(1.5, t * 0.06), 0, Math.PI * 2);
      ctx.fill();
    }
    // eyes
    ctx.fillStyle = '#ffe9a8';
    ctx.fillRect(x - r * 0.4, y - r * 0.2, Math.max(1, r * 0.22), Math.max(1, r * 0.22));
    ctx.fillRect(x + r * 0.18, y - r * 0.2, Math.max(1, r * 0.22), Math.max(1, r * 0.22));
    // hp bar
    if (m.hp < m.maxHp) {
      const bw = Math.max(t * 0.6, r * 2);
      ctx.fillStyle = '#000a';
      ctx.fillRect(x - bw / 2, y - r - t * 0.16, bw, Math.max(2, t * 0.08));
      ctx.fillStyle = m.hp / m.maxHp > 0.4 ? C.ok : C.danger;
      ctx.fillRect(x - bw / 2, y - r - t * 0.16, bw * Math.max(0, m.hp / m.maxHp), Math.max(2, t * 0.08));
    }
  }

  // shots
  for (const p of g.shots) {
    ctx.save();
    ctx.shadowColor = p.color;
    ctx.shadowBlur = t * 0.4;
    ctx.fillStyle = p.color;
    ctx.beginPath();
    ctx.arc(X(p.x), Y(p.y), Math.max(2, t * 0.09), 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
  }

  // particles
  for (const p of particles) {
    const a = Math.max(0, p.life / p.max);
    ctx.globalAlpha = a;
    if (p.text) {
      ctx.font = `800 ${p.size}px ${FONT}`;
      ctx.textAlign = 'center';
      ctx.lineWidth = 3;
      ctx.strokeStyle = '#000';
      ctx.strokeText(p.text, X(p.x), Y(p.y));
      ctx.fillStyle = p.color;
      ctx.fillText(p.text, X(p.x), Y(p.y));
    } else {
      ctx.fillStyle = p.color;
      ctx.fillRect(X(p.x) - p.size / 2, Y(p.y) - p.size / 2, p.size, p.size);
    }
  }
  ctx.globalAlpha = 1;

  drawHint(g, L);
  drawPanel(g, L);
  drawInfo(g, L);

  // dragged gem follows the pointer
  if (pointer.dragging && pointer.dragRef) {
    const gem = G.gemAt(g, pointer.dragRef);
    if (gem) drawGem(gem, pointer.x, pointer.y, Math.max(14, t * 0.4), true);
  }

  if (toast.t > 0 && toast.text) {
    ctx.globalAlpha = Math.min(1, toast.t * 2);
    const size = Math.max(12, Math.min(16, L.field.w / 40));
    ctx.font = `700 ${size}px ${FONT}`;
    const tw = ctx.measureText(toast.text).width + 24;
    const r = { x: L.field.x + L.field.w / 2 - tw / 2, y: L.field.y + L.field.h - size * 3.2, w: tw, h: size * 2 };
    roundRect(r, 10);
    ctx.fillStyle = '#0d1020ee';
    ctx.fill();
    ctx.strokeStyle = C.goldDim;
    ctx.stroke();
    text(toast.text, r.x + r.w / 2, r.y + r.h / 2, size, C.text, 'center', 700);
    ctx.globalAlpha = 1;
  }

  if (paused && g.state === 'playing') {
    ctx.fillStyle = 'rgba(5,6,12,0.45)';
    ctx.fillRect(L.field.x, L.field.y, L.field.w, L.field.h);
    text('Paused', L.field.x + L.field.w / 2, L.field.y + L.field.h / 2, Math.min(40, L.field.w / 10), C.gold, 'center', 800);
  }
  if (g.state !== 'playing') drawResult(g, L);
}

function drawHint(g: G.Game, L: Layout): void {
  if (g.state !== 'playing') return;
  let hint = '';
  const towers = g.structures.filter((s) => s.kind === 'tower');
  const hasInv = g.inventory.some((x) => x);
  if (buildMode) hint = buildMode === 'tower' ? 'Tap a grass tile to build a tower' : 'Tap a path tile to build a trap';
  else if (towers.length === 0) hint = 'Tap Tower, then tap grass beside the path';
  else if (!towers.some((s) => s.gem) && !hasInv) hint = 'Tap a gem colour to forge a gem';
  else if (hasInv && towers.some((s) => !s.gem) && g.nextWave < 3) hint = 'Drag the gem onto a tower (or tap gem, then tower)';
  else if (g.nextWave === 0) hint = `First wave in ${Math.ceil(g.waveTimer)}s · tap Next wave for bonus mana`;
  else if (g.fieldIndex === 0 && g.nextWave < 4 && g.time < 160) hint = 'Drop a gem on an equal gem to combine into a higher grade';
  if (!hint) return;
  const size = Math.max(10, Math.min(14, L.field.w / 46));
  ctx.font = `600 ${size}px ${FONT}`;
  const tw = ctx.measureText(hint).width + 20;
  const r = { x: L.field.x + L.field.w / 2 - tw / 2, y: L.field.y + 6, w: tw, h: size * 1.9 };
  roundRect(r, 8);
  ctx.fillStyle = '#0d1020cc';
  ctx.fill();
  text(hint, r.x + r.w / 2, r.y + r.h / 2, size, C.gold, 'center', 600);
}

function drawPanel(g: G.Game, L: Layout): void {
  const P = L.panel;
  ctx.fillStyle = C.panel;
  ctx.fillRect(P.x, P.y, P.w, P.h);
  ctx.strokeStyle = C.panelEdge;
  ctx.beginPath();
  if (L.portrait) {
    ctx.moveTo(P.x, P.y + 0.5);
    ctx.lineTo(P.x + P.w, P.y + 0.5);
  } else {
    ctx.moveTo(P.x + 0.5, P.y);
    ctx.lineTo(P.x + 0.5, P.y + P.h);
  }
  ctx.stroke();

  const pad = 8;
  const gap = 6;
  let colA: Rect;
  let colB: Rect;
  if (L.portrait) {
    const aw = Math.round(P.w * 0.56);
    colA = { x: P.x + pad, y: P.y + pad, w: aw - pad * 1.5, h: P.h - pad * 2 };
    colB = { x: P.x + aw + pad * 0.5, y: P.y + pad, w: P.w - aw - pad * 1.5, h: P.h - pad * 2 };
  } else {
    colA = { x: P.x + pad, y: P.y + pad, w: P.w - pad * 2, h: P.h - pad * 2 };
    colB = colA;
  }

  // Row heights: column A holds header(2 small rows), build, colors, grade, controls.
  const invRows = 3;
  const invCols = 4;
  const units = L.portrait ? 5.4 : 6.25 + invRows * 1.2;
  const rowH = Math.max(18, Math.min(L.portrait ? 56 : 46, (colA.h - gap * (L.portrait ? 5 : 8)) / units));
  let y = colA.y;

  // mana bar
  const mb = { x: colA.x, y, w: colA.w, h: rowH * 0.8 };
  roundRect(mb, 6);
  ctx.fillStyle = '#0a0d18';
  ctx.fill();
  const frac = Math.max(0, Math.min(1, g.mana / g.manaCap));
  roundRect({ x: mb.x, y: mb.y, w: Math.max(6, mb.w * frac), h: mb.h }, 6);
  const mg = ctx.createLinearGradient(mb.x, 0, mb.x + mb.w, 0);
  mg.addColorStop(0, C.manaDeep);
  mg.addColorStop(1, C.mana);
  ctx.fillStyle = mg;
  ctx.fill();
  ctx.strokeStyle = C.panelEdge;
  roundRect(mb, 6);
  ctx.stroke();
  const ms = `${Math.floor(g.mana)} / ${g.manaCap} mana`;
  text(ms, mb.x + mb.w / 2, mb.y + mb.h / 2, fitText(ms, mb.w - 10, Math.min(14, mb.h * 0.55), 800), '#fff', 'center', 800);
  y += mb.h + gap;

  // wave line + upcoming
  const wl = { x: colA.x, y, w: colA.w, h: rowH * 0.8 };
  const waveStr = g.nextWave >= g.waves.length ? `All ${g.waves.length} waves out` : `Wave ${g.nextWave}/${g.waves.length} · next ${Math.ceil(g.waveTimer)}s`;
  text(waveStr, wl.x, wl.y + wl.h / 2, fitText(waveStr, wl.w * 0.62, Math.min(13, wl.h * 0.5)), C.text, 'left', 600);
  waveIcons = [];
  for (let i = 0; i < 3; i++) {
    const wd = g.waves[g.nextWave + i];
    if (!wd) break;
    const cx = wl.x + wl.w - (2.5 - i) * Math.min(wl.h, wl.w * 0.12);
    const ir = Math.min(wl.h * 0.42, wl.w * 0.05);
    drawWaveIcon(wd, cx, wl.y + wl.h / 2, ir, i === 0);
    waveIcons.push({ x: cx, y: wl.y + wl.h / 2, r: Math.max(ir * 1.3, 10), def: wd, index: g.nextWave + i });
  }
  y += wl.h + gap;

  // build row
  const bw = (colA.w - gap * 2) / 3;
  button({ x: colA.x, y, w: bw, h: rowH }, 'tower', 'Tower', {
    sub: `${G.towerCost(g)}`,
    active: buildMode === 'tower',
    disabled: g.mana < G.towerCost(g),
    tap: () => (buildMode = buildMode === 'tower' ? null : 'tower'),
  });
  button({ x: colA.x + bw + gap, y, w: bw, h: rowH }, 'trap', 'Trap', {
    sub: `${G.trapCost(g)}`,
    active: buildMode === 'trap',
    disabled: g.mana < G.trapCost(g),
    tap: () => (buildMode = buildMode === 'trap' ? null : 'trap'),
  });
  button({ x: colA.x + (bw + gap) * 2, y, w: bw, h: rowH }, 'pool', 'Pool +', {
    sub: `${G.poolCost(g)}`,
    disabled: g.mana < G.poolCost(g),
    tap: doPool,
  });
  y += rowH + gap;

  // gem colours
  const colors = g.field.colors;
  // One extra tile at the end forges a random batch.
  const tiles = colors.length + 1;
  const cw = Math.min(rowH * 1.6, (colA.w - gap * (tiles - 1)) / tiles);
  const cx0 = colA.x + (colA.w - (cw * tiles + gap * (tiles - 1))) / 2;
  const cost = G.gemCost(grade);
  colors.forEach((c, i) => {
    const r = { x: cx0 + i * (cw + gap), y, w: cw, h: rowH };
    const open = true;
    const hover = pointer.inside && inside(r, pointer.x, pointer.y);
    roundRect(r, 8);
    ctx.fillStyle = hover && open ? '#1d2138' : '#141828';
    ctx.fill();
    ctx.strokeStyle = open ? shade(COLOR_HEX(c), -0.3) : '#1c1f30';
    ctx.stroke();
    if (open) {
      ctx.globalAlpha = g.mana >= cost ? 1 : 0.4;
      drawGem(forgePreview(c), r.x + r.w / 2, r.y + r.h / 2, Math.min(r.w, r.h) * 0.32);
      ctx.globalAlpha = 1;
      text(String(i + 1), r.x + 4, r.y + 7, 9, C.textDim, 'left', 600);
      widgets.push({ ...r, id: `gem-${c}`, forge: c, tap: () => makeGem(c) });
    }
  });
  {
    const r = { x: cx0 + colors.length * (cw + gap), y, w: cw, h: rowH };
    const hover = pointer.inside && inside(r, pointer.x, pointer.y);
    roundRect(r, 8);
    ctx.fillStyle = hover ? '#1d2138' : '#141828';
    ctx.fill();
    ctx.strokeStyle = C.stoneHi;
    ctx.stroke();
    ctx.globalAlpha = g.mana >= G.randomBatchCost(grade) ? 1 : 0.4;
    const gr = Math.min(r.w, r.h) * 0.2;
    for (let i = 0; i < 3; i++) {
      const a = -Math.PI / 2 + (i * Math.PI * 2) / 3;
      const c = colors[i % colors.length];
      drawGem(forgePreview(c), r.x + r.w / 2 + Math.cos(a) * gr, r.y + r.h / 2 + Math.sin(a) * gr * 0.9, gr * 0.85, false, false);
    }
    ctx.globalAlpha = 1;
    text('0', r.x + 4, r.y + 7, 9, C.textDim, 'left', 600);
    widgets.push({ ...r, id: 'gem-random', random: true, tap: makeRandomGems });
  }
  y += rowH + gap;

  // grade stepper
  const gh = rowH * 0.8;
  const sw = Math.min(gh * 1.3, colA.w * 0.18);
  button({ x: colA.x, y, w: sw, h: gh }, 'grade-', '−', { tap: () => (grade = Math.max(1, grade - 1)) });
  button({ x: colA.x + colA.w - sw, y, w: sw, h: gh }, 'grade+', '+', { tap: () => (grade = Math.min(10, grade + 1)) });
  const gs = `Forge grade ${grade} · ${cost} mana`;
  text(gs, colA.x + colA.w / 2, y + gh / 2, fitText(gs, colA.w - sw * 2 - 10, Math.min(13, gh * 0.5)), g.mana >= cost ? C.text : C.danger, 'center', 600);
  y += gh + gap;

  // inventory
  let inv: Rect;
  if (L.portrait) {
    inv = { x: colB.x, y: colB.y, w: colB.w, h: colB.h - rowH - gap };
  } else {
    inv = { x: colA.x, y, w: colA.w, h: invRows * rowH * 1.2 + gap * (invRows - 1) };
    y += inv.h + gap;
  }
  const cell = Math.min((inv.w - gap * (invCols - 1)) / invCols, (inv.h - gap * (invRows - 1)) / invRows);
  const ix = inv.x + (inv.w - (cell * invCols + gap * (invCols - 1))) / 2;
  for (let i = 0; i < G.INVENTORY_SIZE; i++) {
    const r = { x: ix + (i % invCols) * (cell + gap), y: inv.y + Math.floor(i / invCols) * (cell + gap), w: cell, h: cell };
    const ref: G.GemRef = { kind: 'inv', index: i };
    const gem = g.inventory[i];
    const isSel = selected?.kind === 'inv' && selected.index === i;
    roundRect(r, 8);
    ctx.fillStyle = '#0c0f1b';
    ctx.fill();
    ctx.strokeStyle = isSel ? C.gold : pointer.dragging && inside(r, pointer.x, pointer.y) ? C.ok : C.panelEdge;
    ctx.lineWidth = isSel ? 2 : 1;
    ctx.stroke();
    ctx.lineWidth = 1;
    const dragged = pointer.dragging && pointer.dragRef?.kind === 'inv' && pointer.dragRef.index === i;
    if (gem && !dragged) drawGem(gem, r.x + r.w / 2, r.y + r.h / 2, cell * 0.32);
    widgets.push({ ...r, id: `inv-${i}`, gemRef: gem ? ref : undefined, drop: ref });
  }

  // controls
  const cy = L.portrait ? colB.y + colB.h - rowH : y;
  const cr = L.portrait ? colB : colA;
  if (L.portrait) {
    // In portrait the controls are split: sell + next on the right column, speed/pause/menu under column A.
    const half = (cr.w - gap) / 2;
    button({ x: cr.x, y: cy, w: half, h: rowH }, 'sell', 'Sell', { sub: selectedValue(g), disabled: !selected, accent: C.goldDim, tap: sellSelected });
    widgets[widgets.length - 1].drop = 'sell';
    nextWaveButton(g, { x: cr.x + half + gap, y: cy, w: half, h: rowH });
    const ay = colA.y + colA.h - rowH;
    if (ay >= y - 2) controlRow({ x: colA.x, y: ay, w: colA.w, h: rowH }, gap);
    else controlRow({ x: colA.x, y, w: colA.w, h: Math.max(20, colA.y + colA.h - y) }, gap);
  } else {
    const w2 = (cr.w - gap) / 2;
    button({ x: cr.x, y: cy, w: w2, h: rowH }, 'sell', 'Sell', { sub: selectedValue(g), disabled: !selected, accent: C.goldDim, tap: sellSelected });
    widgets[widgets.length - 1].drop = 'sell';
    nextWaveButton(g, { x: cr.x + w2 + gap, y: cy, w: w2, h: rowH });
    controlRow({ x: cr.x, y: cy + rowH + gap, w: cr.w, h: rowH * 0.85 }, gap);
  }
}

function selectedValue(g: G.Game): string {
  const gem = selected ? G.gemAt(g, selected) : null;
  return gem ? `+${G.gemValue(gem)}` : 'drop gem';
}

function sellSelected(): void {
  if (selected) applyMove(selected, 'sell');
  selected = null;
}

function nextWaveButton(g: G.Game, r: Rect): void {
  const left = g.waves.length - g.nextWave;
  const bonus = left > 0 ? Math.round(g.waveTimer * (1.5 + g.nextWave * 0.6 + g.fieldIndex) * g.manaMult) : 0;
  button(r, 'next', 'Next wave', { sub: left > 0 ? `+${bonus}` : 'none left', disabled: left === 0, accent: C.manaDeep, tap: doNextWave });
}

function controlRow(r: Rect, gap: number): void {
  const w = (r.w - gap * 2) / 3;
  button({ x: r.x, y: r.y, w, h: r.h }, 'speed', `${speed}× speed`, { tap: () => (speed = speed === 3 ? 1 : speed + 1) });
  button({ x: r.x + w + gap, y: r.y, w, h: r.h }, 'pause', paused ? 'Resume' : 'Pause', { active: paused, tap: () => (paused = !paused) });
  button({ x: r.x + (w + gap) * 2, y: r.y, w, h: r.h }, 'menu', 'Fields', {
    tap: () => {
      screen = 'menu';
      widgets = [];
      paused = false;
    },
  });
}

const MONSTER_LOOK: Record<G.MonsterType, { col: string; size: number }> = {
  crawler: { col: '#c9604a', size: 0.26 },
  swarm: { col: '#d16ad8', size: 0.16 },
  brute: { col: '#8a93a8', size: 0.3 },
  giant: { col: '#9b3b3b', size: 0.42 },
  runner: { col: '#e0a63a', size: 0.2 },
  warded: { col: '#6f86d6', size: 0.26 },
  mender: { col: '#3fb6a8', size: 0.27 },
};

function diamond(x: number, y: number, r: number): void {
  ctx.beginPath();
  ctx.moveTo(x, y - r);
  ctx.lineTo(x + r, y);
  ctx.lineTo(x, y + r);
  ctx.lineTo(x - r, y);
  ctx.closePath();
}

function plus(x: number, y: number, r: number, col: string): void {
  ctx.fillStyle = col;
  const w = Math.max(1, r * 0.4);
  ctx.fillRect(x - r, y - w / 2, r * 2, w);
  ctx.fillRect(x - w / 2, y - r, w, r * 2);
}

/** Upcoming-wave icons drawn this frame, for the hover card. */
let waveIcons: { x: number; y: number; r: number; def: G.WaveDef; index: number }[] = [];

function drawWaveIcon(w: G.WaveDef, cx: number, cy: number, r: number, next: boolean): void {
  ctx.globalAlpha = next ? 1 : 0.55;
  ctx.fillStyle = MONSTER_LOOK[w.type].col;
  if (w.type === 'brute') ctx.fillRect(cx - r * 0.8, cy - r * 0.8, r * 1.6, r * 1.6);
  else if (w.type === 'runner') {
    diamond(cx, cy, r * 0.85);
    ctx.fill();
  }
  else if (w.type === 'swarm') {
    for (let i = 0; i < 3; i++) {
      ctx.beginPath();
      ctx.arc(cx + (i - 1) * r * 0.6, cy + (i % 2 ? -r * 0.3 : r * 0.3), r * 0.4, 0, Math.PI * 2);
      ctx.fill();
    }
  } else {
    ctx.beginPath();
    ctx.arc(cx, cy, w.type === 'giant' ? r : r * 0.7, 0, Math.PI * 2);
    ctx.fill();
    if (w.type === 'warded') {
      ctx.strokeStyle = '#cfd8ff';
      ctx.lineWidth = Math.max(1, r * 0.18);
      ctx.beginPath();
      ctx.arc(cx, cy, r * 0.95, 0, Math.PI * 2);
      ctx.stroke();
    } else if (w.type === 'mender') plus(cx, cy, r * 0.4, '#d8fff0');
  }
  ctx.globalAlpha = 1;
}

function drawInfo(g: G.Game, L: Layout): void {
  let gem: G.Gem | null = null;
  let kind: G.StructKind = 'tower';
  let title = '';
  let titleColor = '';
  const head: [string, string][] = [];
  const kindOf = (r: G.GemRef): G.StructKind => (r.kind === 'struct' ? g.structures.find((s) => s.id === r.id)?.kind ?? 'tower' : 'tower');
  const ref = pointer.dragging ? pointer.dragRef : selected;
  const over = pointer.inside ? targetAt(pointer.x, pointer.y) : null;
  if (ref) {
    gem = G.gemAt(g, ref);
    kind = kindOf(ref);
    // Over another gem: show what the combine would make and what it costs.
    const other = over && over !== 'sell' && !G.sameRef(over, ref) ? G.gemAt(g, over) : null;
    if (gem && other) {
      const ga = G.gemGrade(gem);
      const gb = G.gemGrade(other);
      kind = kindOf(over as G.GemRef);
      gem = G.combine(gem, other, 0);
      gem.kills = 0;
      title = `G${ga} + G${gb} → G${G.gemGrade(gem)} ${gemName(gem)}`;
      if (ga !== gb) head.push(['Unequal grades', `${Math.round(G.gradeProgress(gem) * 100)}% to G${G.gemGrade(gem) + 1}`]);
    }
  } else if (pointer.inside && !pointer.down) {
    const w = widgetAt(pointer.x, pointer.y);
    const wref = widgetGem(w);
    if (wref) gem = G.gemAt(g, wref);
    else if (w?.random) {
      drawRandomCard(g, L);
      return;
    } else if (w?.forge) {
      gem = forgePreview(w.forge);
      const cost = G.gemCost(grade);
      title = `Forge G${grade} ${gemName(gem)}`;
      head.push(['Cost', `${cost} mana`]);
      if (g.mana < cost) titleColor = C.danger;
    } else {
      const s = structAt(pointer.x, pointer.y);
      if (s?.gem) {
        gem = s.gem;
        kind = s.kind;
      }
    }
  }
  if (!gem) {
    if (pointer.inside && !pointer.down && !ref) drawMonsterCard(g, L);
    return;
  }
  const st = G.gemStats(gem, kind);
  const lines: [string, string][] = [...head];
  lines.push(['Damage', `${Math.round(st.damage * 0.8)}–${Math.round(st.damage * 1.2)}`]);
  lines.push(['Rate', `${st.rate.toFixed(2)}/s`]);
  lines.push(['Range', st.range.toFixed(1)]);
  if (st.splash > 0.005) lines.push(['Splash', `${Math.round(st.splash * 100)}%`]);
  if (st.leech > 0.05) lines.push(['Mana/hit', st.leech.toFixed(1)]);
  if (st.crit > 0.005) lines.push(['Crit', `${Math.round(st.crit * 100)}% ×${st.critMult.toFixed(1)}`]);
  if (st.poison > 0.05) lines.push(['Poison', `${st.poison.toFixed(1)}/s`]);
  if (st.slow > 0.005) lines.push(['Slow', `${Math.round(st.slow * 100)}%`]);
  if (st.tear > 0.01) lines.push(['Armor tear', st.tear.toFixed(1)]);
  const purity = G.gemPurity(gem);
  if (purity < 0.999) lines.push(['Purity', `${Math.round(purity * 100)}%`]);
  const prog = G.gradeProgress(gem);
  if (prog > 0.005 && !head.length) lines.push(['Next grade', `${Math.round(prog * 100)}%`]);
  if (!title) lines.push(['Kills', String(gem.kills)]);
  const size = Math.max(10, Math.min(13, L.field.w / 55));
  const lh = size * 1.45;
  const w = size * 15.5;
  const h = lh * (lines.length + 2.6);
  const r = { x: L.field.x + 6, y: L.field.y + L.field.h - h - 6, w, h };
  roundRect(r, 8);
  ctx.fillStyle = '#0b0e1aee';
  ctx.fill();
  ctx.strokeStyle = G.gemColorHex(gem);
  ctx.stroke();
  const t = (title || `G${G.gemGrade(gem)} ${gemName(gem)}`) + (kind === 'trap' ? ' (trap)' : '');
  text(t, r.x + 8, r.y + lh * 0.8, fitText(t, w - 14, size + 1, 800), titleColor || G.gemColorHex(gem), 'left', 800);
  const what = gemSpecials(gem);
  text(what, r.x + 8, r.y + lh * 1.85, fitText(what, w - 14, size, 600), C.gold, 'left', 600);
  lines.forEach(([k, v], i) => {
    text(k, r.x + 8, r.y + lh * (i + 2.9), size, C.textDim, 'left', 500);
    text(v, r.x + r.w - 8, r.y + lh * (i + 2.9), size, C.text, 'right', 700);
  });
}

/** Hovering a monster on the field or an upcoming-wave icon explains it. */
function drawMonsterCard(g: G.Game, L: Layout): void {
  const icon = waveIcons.find((w) => Math.hypot(pointer.x - w.x, pointer.y - w.y) <= w.r);
  let m: G.Monster | null = null;
  if (!icon && inside(L.field, pointer.x, pointer.y)) {
    let bd = Math.max(10, L.tile * 0.5);
    for (const o of g.monsters) {
      const d = Math.hypot(L.field.x + o.x * L.tile - pointer.x, L.field.y + o.y * L.tile - pointer.y);
      if (d < bd) {
        bd = d;
        m = o;
      }
    }
  }
  const type = icon?.def.type ?? m?.type;
  if (!type) return;
  const info = G.MONSTER_INFO[type];
  const lines: [string, string][] = [];
  if (icon) {
    const d = icon.def;
    lines.push(['Wave', `${icon.index + 1} · ${d.count} monsters`]);
    lines.push(['Health', String(Math.round(d.hp))]);
    if (d.armor > 0) lines.push(['Armour', String(d.armor)]);
    if (d.ward) lines.push(['Ward', `${d.ward} hits`]);
    if (d.regen) lines.push(['Heals', `${Math.round(d.regen * 100)}% health/s`]);
  } else if (m) {
    lines.push(['Health', `${Math.ceil(m.hp)} / ${Math.round(m.maxHp)}`]);
    if (m.armor > 0.5) lines.push(['Armour', String(Math.round(m.armor))]);
    if (m.ward > 0) lines.push(['Ward', `${m.ward} hits`]);
    if (m.regen > 0) lines.push(['Heals', m.poisonT > 0 ? 'stopped by poison' : `${Math.round(m.regen)}/s`]);
    if (m.slowT > 0) lines.push(['Slowed', `${Math.round(m.slowF * 100)}%`]);
  }
  const size = Math.max(10, Math.min(13, L.field.w / 55));
  const lh = size * 1.45;
  const w = size * 17;
  const h = lh * (lines.length + 3.6);
  const r = { x: L.field.x + 6, y: L.field.y + L.field.h - h - 6, w, h };
  roundRect(r, 8);
  ctx.fillStyle = '#0b0e1aee';
  ctx.fill();
  ctx.strokeStyle = MONSTER_LOOK[type].col;
  ctx.stroke();
  text(info.name, r.x + 8, r.y + lh * 0.8, size + 1, MONSTER_LOOK[type].col, 'left', 800);
  text(info.trait, r.x + 8, r.y + lh * 1.85, fitText(info.trait, w - 14, size, 600), C.text, 'left', 600);
  const beat = `Beat it with: ${info.counter}`;
  text(beat, r.x + 8, r.y + lh * 2.9, fitText(beat, w - 14, size, 600), C.gold, 'left', 600);
  lines.forEach(([k, v], i) => {
    text(k, r.x + 8, r.y + lh * (i + 3.9), size, C.textDim, 'left', 500);
    text(v, r.x + r.w - 8, r.y + lh * (i + 3.9), size, C.text, 'right', 700);
  });
}

function drawRandomCard(g: G.Game, L: Layout): void {
  const cost = G.randomBatchCost(grade);
  const names = g.field.colors.map((c) => G.COLOR_INFO[c].name).join(', ');
  const lines: [string, string][] = [
    ['Cost', `${cost} mana`],
    ['Forged singly', `${G.gemCost(grade) * G.RANDOM_BATCH} mana`],
    ['Free slots needed', String(G.RANDOM_BATCH)],
  ];
  const size = Math.max(10, Math.min(13, L.field.w / 55));
  const lh = size * 1.45;
  const w = size * 15.5;
  const h = lh * (lines.length + 3.6);
  const r = { x: L.field.x + 6, y: L.field.y + L.field.h - h - 6, w, h };
  roundRect(r, 8);
  ctx.fillStyle = '#0b0e1aee';
  ctx.fill();
  ctx.strokeStyle = C.goldDim;
  ctx.stroke();
  const title = `${G.RANDOM_BATCH} random G${grade} gems`;
  text(title, r.x + 8, r.y + lh * 0.8, fitText(title, w - 14, size + 1, 800), g.mana >= cost ? C.gold : C.danger, 'left', 800);
  const save = `Saves ${G.gemCost(grade) * G.RANDOM_BATCH - cost} mana`;
  text(save, r.x + 8, r.y + lh * 1.85, fitText(save, w - 14, size, 600), C.gold, 'left', 600);
  text(names, r.x + 8, r.y + lh * 2.9, fitText(names, w - 14, size, 500), C.textDim, 'left', 500);
  lines.forEach(([k, v], i) => {
    text(k, r.x + 8, r.y + lh * (i + 3.9), size, C.textDim, 'left', 500);
    text(v, r.x + r.w - 8, r.y + lh * (i + 3.9), size, C.text, 'right', 700);
  });
}

/** What the gem does: the full special for a pure gem, short names for a mix. */
function gemSpecials(gem: G.Gem): string {
  const parts = G.COLORS.filter((c) => (gem.comp[c] ?? 0) >= 0.15).sort((a, b) => (gem.comp[b] ?? 0) - (gem.comp[a] ?? 0));
  if (parts.length <= 1) return G.COLOR_INFO[G.dominantColor(gem)].special;
  return parts.map((c) => G.COLOR_INFO[c].short).join(' + ');
}

function gemName(gem: G.Gem): string {
  const parts = G.COLORS.filter((c) => (gem.comp[c] ?? 0) >= 0.15).sort((a, b) => (gem.comp[b] ?? 0) - (gem.comp[a] ?? 0));
  if (parts.length <= 1) return G.COLOR_INFO[G.dominantColor(gem)].name;
  return parts.slice(0, 2).map((c) => G.COLOR_INFO[c].name).join('-');
}

function drawResult(g: G.Game, L: Layout): void {
  ctx.fillStyle = 'rgba(5,6,12,0.72)';
  ctx.fillRect(0, 0, W, H);
  const won = g.state === 'won';
  const cx = L.field.x + L.field.w / 2;
  const cy = L.field.y + L.field.h / 2;
  const size = Math.min(44, L.field.w / 9);
  text(won ? 'Field defended!' : 'The orb shattered', cx, cy - size * 1.6, size, won ? C.gold : C.danger, 'center', 800);
  if (won) {
    const s = G.stars(g);
    for (let i = 0; i < 3; i++) drawStar(cx + (i - 1) * size * 1.1, cy - size * 0.3, size * 0.45, i < s);
    const notes = `★ won   ${g.banished === 0 ? '★' : '☆'} nothing reached the orb   ${g.built <= 5 ? '★' : '☆'} five or fewer buildings`;
    text(notes, cx, cy + size * 0.5, fitText(notes, L.field.w - 20, Math.max(10, size * 0.3), 500), C.textDim, 'center', 500);
  } else {
    const n = `Reached wave ${g.nextWave} of ${g.waves.length}`;
    text(n, cx, cy - size * 0.3, Math.max(12, size * 0.4), C.textDim, 'center', 500);
  }
  const bw = Math.min(150, L.field.w * 0.3);
  const bh = Math.max(34, size * 0.9);
  const nextLabel = won ? (g.fieldIndex + 1 < G.FIELDS.length ? 'Next field' : 'Play again') : 'Retry';
  button({ x: cx - bw - 6, y: cy + size * 1.1, w: bw, h: bh }, 'again', nextLabel, { active: true, tap: afterGame });
  button({ x: cx + 6, y: cy + size * 1.1, w: bw, h: bh }, 'fields', 'Fields', {
    tap: () => {
      screen = 'menu';
      widgets = [];
    },
  });
}

// ------------------------------------------------------------------ boot

resize();
void loadProgress();
requestAnimationFrame(frame);