Back to Gem Warden
SOURCE / PINNED RELEASE

Made of little things.

Gem Warden

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

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

src/main.ts
import { MEDIA_DOMAIN, STORAGE_DOMAIN, media, storage } from '@napplet/sdk';
import { runtimeHasDomain } from './domain-availability.js';
import * as A from './audio.js';
import { type AudioMediaClient, CoordinatedAudio } from './coordinated-audio.js';
import * as FX from './fx.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[];
  /** Best score per field, 0 when not won yet. */
  best: number[];
  /** Which scoring the bests were made under; older ones do not compare and are dropped. */
  scoring: number;
  /** Effects and music; music plays only with the effects on. */
  sound: boolean;
  music: boolean;
}
/** 2: kills are scored from the median kill. 3: health times the kill multiplier.
 *  4: plus the early kill bonus. 5: health killed times multipliers. */
const SCORING = 5;
let progress: Progress = { stars: G.FIELDS.map(() => 0), best: G.FIELDS.map(() => 0), scoring: SCORING, sound: true, music: 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 (Array.isArray(data.best) && data.scoring === SCORING) progress.best = G.FIELDS.map((_, i) => Math.max(0, Math.round(Number(data.best?.[i]) || 0)));
    if (typeof data.sound === 'boolean') progress.sound = data.sound;
    if (typeof data.music === 'boolean') progress.music = data.music && progress.sound;
    // A first tap may have started audio before the saved choice arrived.
    applySound();
  } 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))]);
}

/** Fields opened for this session by tapping a locked card five times, for testing. */
const testOpen = new Set<number>();
const lockedTaps = new Map<number, number>();

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

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

/** A host without the media domain gets no sound: audio that the host cannot
 *  pause or turn down must not play. The plain dev server has no host, so it
 *  grants itself a session. */
const devMedia: AudioMediaClient = {
  createSession: async () => ({ owner: 'napplet', sessionId: 'dev' }),
  onCommand: () => ({ close: () => undefined }),
  reportState: () => undefined,
  destroySession: () => undefined,
};
function mediaAvailable(): boolean {
  return import.meta.env.DEV || runtimeHasDomain(MEDIA_DOMAIN);
}

/** Made on the first gesture, when the host has surely injected its domains. */
let sound: CoordinatedAudio | null = null;
function coordinated(): CoordinatedAudio {
  const client = runtimeHasDomain(MEDIA_DOMAIN) ? (media as unknown as AudioMediaClient) : import.meta.env.DEV ? devMedia : undefined;
  return (sound ??= new CoordinatedAudio(client, 'Gem Warden'));
}

/** False once the host has refused or ended the session. */
function soundAlive(): boolean {
  return mediaAvailable() && sound?.context?.state !== 'closed';
}

/** Starts audio on a tap or key; browsers allow it only from a gesture. It
 *  never overrides a pause from the host. */
function ensureAudio(): void {
  if (!progress.sound && !progress.music) return;
  const s = coordinated();
  s.activate();
  if (s.context && s.output && A.init(s.context, s.output)) applySound();
}

function applySound(): void {
  A.setEnabled(progress.sound, progress.music);
  sound?.setMuted(!progress.sound && !progress.music);
}

/** Steps through everything on, effects only and silent. */
function cycleSound(): void {
  if (!soundAlive()) return;
  if (progress.sound && progress.music) progress.music = false;
  else if (progress.sound) progress.sound = false;
  else progress.sound = progress.music = true;
  ensureAudio();
  applySound();
  A.sfx.click();
  saveProgress();
}

function soundLabel(): string {
  if (!soundAlive()) return 'No sound here';
  return progress.sound && progress.music ? 'Sound + music' : progress.sound ? 'Sound only' : 'Silent';
}

/** Stereo position for something at tile column x. */
function panAt(x: number): number {
  return (x / G.COLS - 0.5) * 1.2;
}

document.addEventListener('visibilitychange', () => {
  // Switching tabs pauses the field.
  if (document.hidden && screen === 'play' && game?.state === 'playing') paused = true;
  if (!sound?.context || sound.context.state === 'closed') return;
  if (document.hidden) void sound.context.suspend().catch(() => undefined);
  else sound.activate();
});
window.addEventListener('pagehide', () => sound?.dispose());

// ------------------------------------------------------------------ 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;
/** The old 80-mana G10; grades now start at the old G3. */
const MAX_FORGE_GRADE = 8;
let selected: G.GemRef | null = null;
let toast = { text: '', t: 0 };
let resultSaved = false;
/** Real seconds this run has been on screen, and how many of them count for focus:
 *  all but the pauses the player did not act in. */
let wallTime = 0;
let focusTime = 0;
/** True until the player acts during a pause; worth ×2. */
let noPause = true;
/** The player has acted during this pause: the fog is lifted and the time counts. */
let pauseActed = false;
/** Mana lost to a full orb lately, shown at the orb until it stops for a moment. */
let overflow = { amount: 0, t: 0, seen: 0 };
let newBest = false;

/** Game seconds for field effects, so they freeze with a pause; real seconds for the interface. */
let fxT = 0;
let nowT = 0;
const motionQuery = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
let reducedMotion = !!motionQuery?.matches;
const baseQuality = () => (reducedMotion ? 0.4 : 1);
FX.setQuality(baseQuality(), reducedMotion);
motionQuery?.addEventListener?.('change', (e) => {
  reducedMotion = e.matches;
  FX.setQuality(baseQuality(), reducedMotion);
});

/** When each monster was last hit, for the white flash. */
const hitFlash = new Map<number, number>();
/** When the structure on a tile last fired, by tile index. */
const firedAt = new Map<number, number>();
/** When a structure or gem appeared, for the pop-in; real seconds. */
const structBorn = new Map<number, number>();
const gemBorn = new Map<number, number>();
const trails = new WeakMap<G.Shot, number[]>();
/** Short-lived swells: mana arriving, a monster hitting the orb, a spawn. */
let orbPulse = 0;
let orbHurt = 0;
let portalPulse = 0;
let manaFlash = 0;
let manaShake = 0;
let manaBar: Rect = { x: 0, y: 0, w: 0, h: 0 };
let banner: { title: string; sub: string; color: string; t0: number } | null = null;
/** Real time the field started and ended, for the fade-in and the result screen. */
let fieldT0 = 0;
let endT = 0;
let fireworkT = 0;
let starsShown = 0;
/** The result's buttons are on screen and its keys live. */
let resultReady = false;
/** The score formulas are open over the result. */
let showFormula = false;
/** Kills in quick succession climb the chord. */
let combo = { n: 0, t: 0 };
let lastLeechMote = 0;
let pressed = { id: '', t: 0 };
/** How heated the fight is and how close the orb is to a hit; both steer the music. */
let intensity = 0;
let danger = 0;
let fireflies: { x: number; y: number; phase: number; pace: number; color: string }[] = [];

function clamp01(v: number): number {
  return Math.max(0, Math.min(1, v));
}

/** Eases out past the target and back, for things that pop into place. */
function backOut(k: number): number {
  const c = 1.70158;
  return 1 + (c + 1) * Math.pow(k - 1, 3) + c * Math.pow(k - 1, 2);
}

function cubicOut(k: number): number {
  return 1 - Math.pow(1 - k, 3);
}

function tileIndex(x: number, y: number): number {
  return Math.floor(y) * G.COLS + Math.floor(x);
}

function startField(i: number): void {
  game = G.newGame(i);
  screen = 'play';
  widgets = [];
  speed = 1;
  paused = false;
  buildMode = null;
  selected = null;
  grade = 1;
  resultSaved = false;
  wallTime = 0;
  focusTime = 0;
  noPause = true;
  pauseActed = false;
  overflow = { amount: 0, t: 0, seen: 0 };
  newBest = false;
  showFormula = false;
  bgKey = '';
  FX.clear();
  FX.setQuality(baseQuality(), reducedMotion);
  slowFrames = 0;
  hitFlash.clear();
  firedAt.clear();
  structBorn.clear();
  gemBorn.clear();
  orbPulse = orbHurt = manaFlash = manaShake = 0;
  portalPulse = 1;
  banner = null;
  fieldT0 = nowT;
  combo = { n: 0, t: 0 };
  intensity = danger = 0;
  const rng = G.makeRng(31 + i);
  fireflies = Array.from({ length: 22 }, () => ({
    x: rng() * G.COLS,
    y: rng() * G.ROWS,
    phase: rng() * 6.28,
    pace: 0.25 + rng() * 0.5,
    color: ['#9fe8b0', '#ffe9a8', '#8fd0ff'][Math.floor(rng() * 3)],
  }));
  A.sfx.start();
}

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();
  // A press lights the button for a moment.
  const press = pressed.id === id ? 1 - (nowT - pressed.t) / 0.22 : 0;
  if (press > 0) {
    ctx.fillStyle = `rgba(242,198,109,${0.35 * press})`;
    ctx.fill();
  }
  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);
  // A new gem pops into its slot.
  const born = gemBorn.get(gem.id);
  if (born !== undefined) {
    const k = (nowT - born) / 0.35;
    if (k >= 1) gemBorn.delete(gem.id);
    else r *= 0.35 + 0.65 * backOut(Math.max(0, k));
  }
  ctx.save();
  if (glow) {
    FX.light(ctx, cx, cy, r * 2.5, hex, 0.5 + 0.12 * Math.sin(nowT * 2.4 + gem.id));
    // Higher grades carry lights in orbit, one more with each grade from the third.
    const orbit = FX.quality < 0.5 ? 0 : Math.min(4, gr - 2);
    for (let i = 0; i < orbit; i++) {
      const a = nowT * (1.4 + gr * 0.12) + (i * Math.PI * 2) / orbit + gem.id;
      FX.light(ctx, cx + Math.cos(a) * r * 1.5, cy + Math.sin(a) * r * 1.25, Math.max(2, r * 0.4), hex, 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.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();
  // Every real gem catches the light now and then, the better ones more often.
  if (gem.id > 0 && r >= 5) {
    const phase = nowT * (0.3 + gr * 0.04) + gem.id * 0.618;
    const f = phase - Math.floor(phase);
    if (f < 0.2) FX.glint(ctx, cx - r * 0.3, cy - r * 0.38, r * 1.1, f / 0.2, '#ffffff', 0.3);
  }
  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();
  // Dark corners, painted once here: blending them over the field every frame
  // cost more than all the other effects together.
  const far = Math.hypot(L.field.w, L.field.h) / 2;
  const vg = b.createRadialGradient(L.field.w / 2, L.field.h / 2, far * 0.6, L.field.w / 2, L.field.h / 2, far);
  vg.addColorStop(0, 'rgba(3,4,10,0)');
  vg.addColorStop(1, 'rgba(3,4,10,0.55)');
  b.fillStyle = vg;
  b.fillRect(0, 0, L.field.w, L.field.h);
}

// ------------------------------------------------------------------ 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);
  if (!['pause', 'sound'].includes(pointer.downWidget?.id ?? '')) actDuringPause();
  pointer.dragRef = widgetGem(pointer.downWidget) ?? fieldGemAt(pointer.x, pointer.y);
});
canvas.addEventListener('pointerup', (e) => {
  // A touch only counts as a gesture when it lifts, so audio may have to start here.
  ensureAudio();
  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;
}

/** Where a gem slot is, for effects: structures in field tiles, inventory slots in pixels. */
function refSpot(ref: G.GemRef): { space: FX.Space; x: number; y: number; r: number } | null {
  if (ref.kind === 'struct') {
    const s = game?.structures.find((st) => st.id === ref.id);
    return s ? { space: FX.FIELD, x: s.x + 0.5, y: s.y + 0.5, r: 0.5 } : null;
  }
  const w = widgets.find((wd) => wd.id === `inv-${ref.index}`);
  return w ? { space: FX.UI, x: w.x + w.w / 2, y: w.y + w.h / 2, r: w.w / 2 } : null;
}

/** A flash of light and sparks on a gem slot; `big` grows it for higher grades. */
function gemBurst(ref: G.GemRef, color: string, big: number): void {
  const p = refSpot(ref);
  if (!p) return;
  FX.realTime(() => {
    FX.ring(p.space, p.x, p.y, p.r * 0.3, p.r * (1.5 + big * 0.4), 0.4, color, p.r * 0.16);
    FX.glow(p.space, p.x, p.y, p.r * (1.8 + big * 0.7), 0.35, color);
    FX.sparks(p.space, p.x, p.y, 8 + big * 5, color, { speed: p.r * (5 + big * 1.5), life: 0.45, size: p.r * 0.1 });
    FX.star(p.space, p.x, p.y, p.r * (1 + Math.min(big, 5) * 0.1), 0.4, '#ffffff');
  });
}

function applyMove(src: G.GemRef, dst: G.GemRef | 'sell'): boolean {
  if (!game) return false;
  if (dst === 'sell') {
    const gem = G.gemAt(game, src);
    const from = refSpot(src);
    if (gem && G.sellGem(game, src)) {
      flash(`Sold for ${G.gemValue(gem)} mana`);
      A.sfx.sell();
      if (from) {
        // The gem breaks up and its worth flies to the mana bar as coins.
        const L = computeLayout();
        const px = from.space === FX.UI ? from.x : L.field.x + from.x * L.tile;
        const py = from.space === FX.UI ? from.y : L.field.y + from.y * L.tile;
        const hex = G.gemColorHex(gem);
        FX.shards(FX.UI, px, py, 9, hex, { speed: 150, life: 0.6, size: 4, gravity: 500 });
        FX.glow(FX.UI, px, py, 30, 0.3, hex);
        for (let i = 0; i < FX.amount(6); i++) {
          FX.mote(FX.UI, px, py, manaBar.x + manaBar.w * Math.min(1, game.mana / game.manaCap), manaBar.y + manaBar.h / 2, C.gold, 3, 160, () => (manaFlash = 1), i * 0.04);
        }
      }
      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)}`);
    // Light rushes in, then the new gem bursts out of it.
    const hex = G.gemColorHex(merged);
    const p = refSpot(dst);
    if (p) FX.realTime(() => FX.implode(p.space, p.x, p.y, 12 + gr * 2, hex, p.r * 2.4, 0.16, p.r * 0.1));
    gemBorn.set(merged.id, nowT + 0.1);
    FX.after(0.14, () => gemBurst(dst, hex, gr));
  } else if (merged) {
    gemBorn.set(merged.id, nowT);
    const p = refSpot(dst);
    if (p) FX.realTime(() => FX.ring(p.space, p.x, p.y, p.r * 0.4, p.r * 1.3, 0.3, G.gemColorHex(merged), p.r * 0.12));
    A.sfx.place();
  }
  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 {
  // The second tap of a double-tap on a field card must not hit a control under the fade-in.
  if (screen === 'play' && nowT - fieldT0 < 0.3) return;
  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;
    }
    if (w.tap) {
      pressed = { id: w.id, t: nowT };
      // Forging and the wave call have sounds of their own.
      if (!w.forge && !w.random && !['pool', 'next', 'sound'].includes(w.id)) A.sfx.click();
      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) => {
  ensureAudio();
  if (e.key.toLowerCase() === 'm') {
    cycleSound();
    return;
  }
  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') {
    // Not before the result is up: a Space meant as a pause must not skip it.
    if (!resultReady) return;
    if (k === '?' || k === 'h') showFormula = !showFormula;
    else if (k === 'escape' && showFormula) showFormula = false;
    else if (k === 'enter' || k === ' ') afterGame();
    else if (k === 'escape') screen = 'menu';
    return;
  }
  if (/^([trpnfs0-6+=-]|delete|backspace|escape)$/.test(k)) actDuringPause();
  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(MAX_FORGE_GRADE, 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();
  }
});

/** Playing during a pause lifts the fog, lets the time count for focus and
 *  drops the no-pause ×2 for the run. */
function actDuringPause(): void {
  if (screen !== 'play' || !paused || pauseActed || game?.state !== 'playing') return;
  pauseActed = true;
  noPause = false;
}

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;
  const slots = G.createRandomGems(game, grade);
  if (slots.length) {
    A.sfx.forgeBatch();
    slots.forEach((slot, i) => {
      const gem = game?.inventory[slot];
      if (!gem) return;
      gemBorn.set(gem.id, nowT + i * 0.08);
      FX.after(i * 0.08, () => gemBurst({ kind: 'inv', index: slot }, G.gemColorHex(gem), 0));
    });
    selected = null;
  }
}

function makeGem(color: G.GemColor): void {
  if (!game) return;
  const slot = G.createGem(game, color, grade);
  if (slot >= 0) {
    const gem = game.inventory[slot];
    if (gem) gemBorn.set(gem.id, nowT);
    gemBurst({ kind: 'inv', index: slot }, COLOR_HEX(color), grade / 3);
    A.sfx.forge(color, grade);
    selected = null;
  }
}

function doPool(): void {
  if (!game) return;
  if (G.expandPool(game)) {
    flash(`Mana pool expanded · gains ×${game.manaMult.toFixed(2)}`);
    A.sfx.pool();
    const [ox, oy] = [game.orb[0] + 0.5, game.orb[1] + 0.5];
    orbPulse = 1;
    manaFlash = 1;
    FX.realTime(() => {
      FX.ring(FX.FIELD, ox, oy, 0.4, 2.6, 0.7, C.mana, 0.16);
      FX.ring(FX.FIELD, ox, oy, 0.4, 1.8, 0.6, '#eaf8ff', 0.1, 0.12);
      FX.implode(FX.FIELD, ox, oy, 26, C.mana, 2.4, 0.35, 0.07);
    });
  }
}

function doNextWave(): void {
  if (!game) return;
  const bonus = G.callWaveEarly(game);
  if (bonus > 0) flash(`+${Math.round(bonus * game.manaMult)} to the pot · paid when all are dead`);
}

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();
let frameMs = 16;
let slowFrames = 0;

function frame(now: number): void {
  const raw = (now - last) / 1000;
  const dt = Math.min(0.1, raw);
  last = now;
  nowT = now / 1000;
  const g = screen === 'play' ? game : null;
  if (!paused) pauseActed = false;
  if (g && g.state === 'playing') {
    wallTime += dt;
    if (!paused || pauseActed) focusTime += dt;
  }
  if (g && !paused) {
    let left = dt * speed;
    while (left > 0) {
      const d = Math.min(1 / 60, left);
      G.step(g, d);
      left -= d;
    }
  }
  // Field effects follow game time; once the field is over they run at real speed.
  const dtField = !g ? 0 : g.state !== 'playing' ? dt : paused ? 0 : dt * speed;
  fxT += dtField;
  if (g) {
    // Also while paused, so a refused action still explains itself.
    consumeEvents(g);
    const lost = g.wasted - overflow.seen;
    overflow.seen = g.wasted;
    if (lost > 0) {
      overflow.amount += lost;
      overflow.t = 1.5;
    } else if (!paused && (overflow.t -= dt) <= 0) overflow.amount = 0;
    if (overflow.t > 0 && overflow.amount >= 1 && !paused && g.state === 'playing') A.sfx.overflow();
  }
  if (g && g.state !== 'playing' && !resultSaved) {
    resultSaved = true;
    endT = nowT;
    starsShown = 0;
    resultReady = false;
    const [ox, oy] = [g.orb[0] + 0.5, g.orb[1] + 0.5];
    if (g.state === 'won') {
      const s = G.stars(g);
      progress.stars[g.fieldIndex] = Math.max(progress.stars[g.fieldIndex], s);
      const total = G.score(g, focusTime, noPause).total;
      newBest = total > progress.best[g.fieldIndex];
      if (newBest) progress.best[g.fieldIndex] = total;
      saveProgress();
      A.sfx.win();
      FX.flash('#fff2c4', 0.3);
      FX.ring(FX.FIELD, ox, oy, 0.5, 5, 0.9, C.gold, 0.2);
      fireworkT = 0.4;
    } else {
      // The orb bursts.
      FX.shards(FX.FIELD, ox, oy, 46, C.mana, { speed: 7, life: 1.5, size: 0.14, gravity: 5 });
      FX.shards(FX.FIELD, ox, oy, 18, '#eaf8ff', { speed: 5, life: 1.2, size: 0.1, gravity: 5 });
      FX.sparks(FX.FIELD, ox, oy, 40, '#bfeaff', { speed: 9, life: 0.9, size: 0.08 });
      for (let i = 0; i < 3; i++) FX.ring(FX.FIELD, ox, oy, 0.4, 4 + i * 2.5, 0.8, i ? C.mana : '#ffffff', 0.25, i * 0.12);
      FX.glow(FX.FIELD, ox, oy, 5, 0.7, '#eaf8ff');
      FX.shake(0.6);
      FX.flash('#ffffff', 0.5);
      A.sfx.lose();
    }
  }
  if (g && g.state === 'playing' && !paused) {
    ambient(g, dt * speed);
    if (dangerLevel(g) >= 1) A.sfx.heartbeat();
  }
  if (g && g.state === 'won' && !FX.calm && (fireworkT -= dt) <= 0) {
    firework();
    // A volley at first, then one now and then for as long as the screen stays up.
    fireworkT = nowT - endT < 3.5 ? 0.22 + Math.random() * 0.25 : 0.9 + Math.random() * 0.9;
  }
  orbPulse = Math.max(0, orbPulse - dt * 2.5);
  orbHurt = Math.max(0, orbHurt - dt * 2);
  portalPulse = Math.max(0, portalPulse - dt * 2.5);
  manaFlash = Math.max(0, manaFlash - dt * 2.5);
  manaShake = Math.max(0, manaShake - dt);
  FX.update(dtField, dt);
  driveMusic(g, dt);
  watchFrameRate(raw);
  toast.t -= dt;
  draw(nowT);
  requestAnimationFrame(frame);
}

/** Sheds particles when the device cannot keep up; a field starts at full again. */
function watchFrameRate(raw: number): void {
  if (raw > 0.25) return;
  frameMs = frameMs * 0.95 + raw * 1000 * 0.05;
  // Below 25 frames a second; a display held at 30 must not count as slow.
  slowFrames = frameMs > 40 ? slowFrames + 1 : Math.max(0, slowFrames - 1);
  if (slowFrames > 120 && FX.quality > 0.2) {
    FX.setQuality(FX.quality * 0.6, reducedMotion);
    slowFrames = 0;
  }
}

/** 1 when the monsters nearing the orb would break it, about half when they would not, else 0. */
function dangerLevel(g: G.Game): number {
  const near = g.monsters.filter((m) => m.hp > 0 && g.pathLength - m.dist <= ORB_WARN_TILES).sort((a, b) => b.dist - a.dist);
  if (!near.length) return 0;
  let left = g.mana;
  near.forEach((m, ahead) => (left -= G.orbCost(g, m, ahead)));
  return left < 0 ? 1 : 0.55;
}

function driveMusic(g: G.Game | null, dt: number): void {
  let mode: A.MusicState['mode'] = 'menu';
  let wantI = 0;
  let wantD = 0;
  let boss = false;
  if (g) {
    if (g.state !== 'playing') mode = 'off';
    else {
      mode = 'play';
      const n = g.monsters.length;
      // Calm between waves; a fight builds with the crowd and with how far the field has come.
      wantI = n === 0 && g.spawnQueue.length === 0 ? 0.08 : Math.min(1, 0.26 + (n / 30) * 0.5 + (g.nextWave / g.waves.length) * 0.3);
      wantD = dangerLevel(g);
      boss = g.monsters.some((m) => m.type === 'giant');
    }
  }
  intensity += (wantI - intensity) * Math.min(1, dt * 0.8);
  danger += (wantD - danger) * Math.min(1, dt * 2.5);
  A.music({ mode, field: g?.fieldIndex ?? 0, intensity, danger, boss, speed: paused ? 1 : speed, paused: paused && mode === 'play' });
}

function firework(): void {
  const L = computeLayout();
  const x = L.field.x + L.field.w * (0.1 + Math.random() * 0.8);
  const y = L.field.y + L.field.h * (0.08 + Math.random() * 0.5);
  const c = COLOR_HEX(G.COLORS[Math.floor(Math.random() * G.COLORS.length)]);
  const s = Math.max(50, L.field.w * 0.15);
  FX.glow(FX.UI, x, y, s * 0.9, 0.35, c);
  FX.ring(FX.UI, x, y, 2, s * 0.7, 0.5, c, 3);
  FX.sparks(FX.UI, x, y, 46, c, { speed: s * 2.6, life: 1.1, size: 2.4, gravity: s * 1.2, drag: 0.94 });
  FX.sparks(FX.UI, x, y, 14, '#ffffff', { speed: s * 1.4, life: 0.7, size: 1.6, gravity: s, drag: 0.93 });
  A.sfx.firework((x / W - 0.5) * 1.4);
}

/** The small things monsters and the portal give off while they are affected. */
function ambient(g: G.Game, dt: number): void {
  const q = FX.quality;
  for (const m of g.monsters) {
    const r = MONSTER_LOOK[m.type].size;
    const jx = (Math.random() - 0.5) * r * 1.6;
    if (m.poisonT > 0 && Math.random() < dt * 3 * q) FX.bubble(FX.FIELD, m.x + jx, m.y - r * 0.4, '#4fe06a', 0.1, 0.6, -0.8);
    if (m.slowT > 0 && Math.random() < dt * 2.5 * q) FX.sparks(FX.FIELD, m.x + jx, m.y, 1, '#bfe6ff', { speed: 0.4, life: 0.5, size: 0.04, gravity: 1.2 });
    if (m.regen > 0 && m.poisonT <= 0 && m.hp < m.maxHp && Math.random() < dt * 2.5 * q) FX.star(FX.FIELD, m.x + jx, m.y - r, 0.22, 0.45, '#7cf0a0');
    if (m.type === 'giant' && Math.random() < dt * 5 * q) FX.sparks(FX.FIELD, m.x + jx, m.y + jx * 0.5, 1, '#d8f2ff', { speed: 0.3, life: 0.8, size: 0.04, gravity: -0.7 });
  }
  if (Math.random() < dt * 6 * q) {
    const [sx, sy] = g.pathPoints[0];
    FX.implode(FX.FIELD, sx + 0.5, sy + 0.5, 1, '#d070f0', 0.8, 0.55, 0.05);
  }
}

function consumeEvents(g: G.Game): void {
  const ox = g.orb[0] + 0.5;
  const oy = g.orb[1] + 0.5;
  const sx = g.pathPoints[0][0] + 0.5;
  const sy = g.pathPoints[0][1] + 0.5;
  for (const ev of g.events) {
    switch (ev.type) {
      case 'shot':
        firedAt.set(tileIndex(ev.x, ev.y), fxT);
        A.sfx.shot(ev.gem, ev.grade, panAt(ev.x));
        break;
      case 'hit': {
        const pan = panAt(ev.x);
        hitFlash.set(ev.id, fxT);
        if (ev.trap) {
          // A trap strikes with a bolt to every monster it reaches.
          firedAt.set(tileIndex(ev.sx, ev.sy), fxT);
          FX.bolt(FX.FIELD, ev.sx, ev.sy, ev.x, ev.y, ev.color, 0.16, 0.05);
          A.sfx.trap(ev.gem, pan);
        }
        if (ev.ward) {
          FX.ring(FX.FIELD, ev.x, ev.y, 0.2, 0.55, 0.25, '#cfd8ff', 0.07);
          FX.sparks(FX.FIELD, ev.x, ev.y, 4, '#cfd8ff', { speed: 2.5, life: 0.25, size: 0.05 });
          A.sfx.ward(pan);
          break;
        }
        // Sparks carry on along the line of the shot.
        const away = Math.atan2(ev.y - ev.sy, ev.x - ev.sx);
        FX.sparks(FX.FIELD, ev.x, ev.y, ev.crit ? 10 : 4, ev.color, {
          speed: ev.crit ? 5.5 : 3,
          life: 0.3,
          size: ev.crit ? 0.09 : 0.06,
          angle: away,
          spread: ev.crit ? 6.3 : 1.7,
        });
        FX.glow(FX.FIELD, ev.x, ev.y, ev.crit ? 0.95 : 0.45, 0.18, ev.color);
        if (ev.crit) {
          FX.star(FX.FIELD, ev.x, ev.y, 0.8, 0.3, '#fff7c2');
          FX.ring(FX.FIELD, ev.x, ev.y, 0.1, 0.7, 0.25, '#ffe14d', 0.08);
          if (!ev.trap) FX.bolt(FX.FIELD, ev.sx, ev.sy, ev.x, ev.y, '#ffe14d', 0.12, 0.035);
          FX.shake(0.03);
          A.sfx.crit(pan);
        } else A.sfx.hit(pan);
        if (ev.splash) {
          FX.ring(FX.FIELD, ev.x, ev.y, 0.15, G.SPLASH_RADIUS, 0.3, '#ff7a3a', 0.13);
          FX.sparks(FX.FIELD, ev.x, ev.y, 5, '#ffb347', { speed: 3.5, life: 0.4, size: 0.05, gravity: 2 });
          A.sfx.splash(pan);
        }
        if (ev.slow) FX.shards(FX.FIELD, ev.x, ev.y, 2, '#bfe6ff', { speed: 1.6, life: 0.4, size: 0.06, gravity: 2 });
        if (ev.tear) FX.shards(FX.FIELD, ev.x, ev.y, 2, '#d6dbe8', { speed: 1.8, life: 0.45, size: 0.07, gravity: 5 });
        if (ev.poison) FX.bubble(FX.FIELD, ev.x, ev.y, '#4fe06a', 0.14, 0.5, -0.9);
        if (ev.leech && fxT - lastLeechMote > 0.1) {
          // Leeched mana drifts home to the orb.
          lastLeechMote = fxT;
          FX.mote(FX.FIELD, ev.x, ev.y, ox, oy, '#ff9a2e', 0.07, 2.5, () => (orbPulse = Math.max(orbPulse, 0.35)));
        }
        break;
      }
      case 'kill': {
        const look = MONSTER_LOOK[ev.monster];
        const sz = look.size;
        const big = ev.monster === 'giant';
        const pan = panAt(ev.x);
        FX.floatText(FX.FIELD, ev.x, ev.y - 0.2, `+${Math.round(ev.mana)}`, C.mana, 0.32, 0.9, -0.9);
        if (ev.points >= 0.5) FX.floatText(FX.FIELD, ev.x, ev.y + 0.15, `+${Math.round(ev.points)}`, C.gold, 0.26, 0.9, -0.7);
        // It bursts into its own colour, and its mana flies to the orb.
        FX.shards(FX.FIELD, ev.x, ev.y, 5 + sz * 30, look.col, { speed: 2.5 + sz * 5, life: 0.6, size: sz * 0.4, gravity: 4 });
        FX.sparks(FX.FIELD, ev.x, ev.y, 4 + sz * 24, shade(look.col, 0.45), { speed: 3 + sz * 6, life: 0.4, size: 0.06 });
        FX.ring(FX.FIELD, ev.x, ev.y, sz * 0.5, sz * 3.2, 0.35, look.col, 0.08);
        FX.glow(FX.FIELD, ev.x, ev.y, sz * 3.6, 0.25, look.col);
        for (let i = 0; i < (big ? 6 : 1); i++) {
          FX.mote(FX.FIELD, ev.x, ev.y, ox, oy, C.mana, 0.08, 3, () => {
            orbPulse = Math.max(orbPulse, 0.6);
            A.sfx.mana();
          }, i * 0.05);
        }
        if (fxT - combo.t > 1.6) combo.n = 0;
        combo = { n: combo.n + 1, t: fxT };
        if (big) {
          FX.ring(FX.FIELD, ev.x, ev.y, 0.3, 3.2, 0.6, '#d8f2ff', 0.2);
          FX.ring(FX.FIELD, ev.x, ev.y, 0.3, 2, 0.5, '#ffffff', 0.12, 0.08);
          FX.shake(0.3);
          FX.flash('#bfe6ff', 0.22);
          A.sfx.bigKill(pan);
        } else A.sfx.kill(pan, combo.n, sz);
        break;
      }
      case 'spawn':
        portalPulse = 1;
        FX.sparks(FX.FIELD, sx, sy, 3, '#e58cff', { speed: 2.2, life: 0.4, size: 0.05 });
        break;
      case 'banish':
        FX.floatText(FX.FIELD, ev.x, ev.y - 0.3, `−${ev.cost}`, C.danger, 0.4, 1.3, -0.6);
        FX.ring(FX.FIELD, ox, oy, 0.4, 2.4, 0.5, C.danger, 0.2);
        FX.ring(FX.FIELD, ox, oy, 0.4, 1.5, 0.4, '#ffffff', 0.1, 0.06);
        FX.sparks(FX.FIELD, ox, oy, 18, C.danger, { speed: 6, life: 0.6, size: 0.08 });
        // The monster is thrown back to the portal.
        FX.mote(FX.FIELD, ox, oy, sx, sy, C.danger, 0.12, 5, () => (portalPulse = 1));
        orbHurt = 1;
        FX.shake(0.22);
        FX.flash(C.danger, 0.3);
        A.sfx.banish(panAt(ev.x));
        break;
      case 'build':
        structBorn.set(ev.id, nowT);
        FX.realTime(() => {
          FX.ring(FX.FIELD, ev.x, ev.y, 0.2, 0.95, 0.35, ev.kind === 'trap' ? '#b9a5ff' : C.stoneHi, 0.09);
          FX.shards(FX.FIELD, ev.x, ev.y, 8, C.stone, { speed: 2.4, life: 0.5, size: 0.07, gravity: 6 });
          FX.sparks(FX.FIELD, ev.x, ev.y, 7, '#cfc8e6', { speed: 2, life: 0.35, size: 0.05 });
        });
        A.sfx.build(ev.kind === 'trap', panAt(ev.x));
        break;
      case 'combine':
        A.sfx.combine(ev.grade);
        break;
      case 'wave': {
        const boss = ev.monster === 'giant';
        const lastWave = ev.index === g.waves.length - 1;
        const info = G.MONSTER_INFO[ev.monster];
        banner = {
          title: lastWave ? 'Final wave' : `Wave ${ev.index + 1}`,
          sub: `${ev.count} × ${info.name} · ${info.trait}`,
          color: MONSTER_LOOK[ev.monster].col,
          t0: nowT,
        };
        portalPulse = 1;
        FX.ring(FX.FIELD, sx, sy, 0.3, boss ? 4 : 2.6, 0.7, '#d070f0', 0.16);
        FX.ring(FX.FIELD, sx, sy, 0.3, boss ? 2.6 : 1.6, 0.6, '#ff9ae8', 0.1, 0.1);
        FX.sparks(FX.FIELD, sx, sy, 16, '#e58cff', { speed: 4, life: 0.6, size: 0.06 });
        if (boss) FX.shake(0.12);
        A.sfx.wave(boss, lastWave);
        break;
      }
      case 'bonus':
        flash(`Field clear · pot paid +${Math.round(ev.mana)} mana`);
        orbPulse = 1;
        manaFlash = 1;
        FX.ring(FX.FIELD, ox, oy, 0.4, 2.2, 0.6, C.gold, 0.14);
        FX.implode(FX.FIELD, ox, oy, 24, C.gold, 3, 0.4, 0.07);
        A.sfx.bonus();
        break;
      case 'error':
        flash(ev.message);
        if (ev.message.includes('mana')) manaShake = 0.35;
        A.sfx.error();
        break;
    }
  }
  g.events.length = 0;
  // Dead monsters leave their flash entries behind.
  if (hitFlash.size > 600) for (const [id, t] of hitFlash) if (fxT - t > 1) hitFlash.delete(id);
}

// ------------------------------------------------------------------ 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;
  // A night sky: two slow auroras and twinkling stars.
  const far = Math.max(W, H);
  FX.light(ctx, W * (0.3 + 0.1 * Math.sin(time * 0.11)), H * 0.3, far * 0.6, '#3b2a7a', 0.55);
  FX.light(ctx, W * (0.72 + 0.1 * Math.cos(time * 0.09)), H * 0.64, far * 0.55, '#123a66', 0.55);
  const rng = G.makeRng(7);
  ctx.fillStyle = '#dfe6ff';
  for (let i = 0; i < 70; i++) {
    const x = rng() * W;
    const y = rng() * H;
    const a = 0.3 + 0.4 * Math.sin(time * (0.6 + rng() * 1.8) + rng() * 6.28);
    if (a <= 0.05) continue;
    ctx.globalAlpha = a;
    ctx.fillRect(x, y, 1.4, 1.4);
  }
  ctx.globalAlpha = 1;
  // 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 + Math.sin(time * 0.7 + i) * 6;
    const r = 10 + (i % 4) * 4;
    FX.light(ctx, x, y, r * 2.6, COLOR_HEX(c), 0.14);
    ctx.globalAlpha = 0.24;
    drawGem({ id: 0, mass: 1 << (i % 4), comp: { [c]: 1 }, kills: 0 }, x, y, r, false, false);
    ctx.globalAlpha = 1;
  }
  const titleSize = Math.min(54, W * 0.09, H * 0.1);
  // The title: gold with a light sweeping across it.
  ctx.font = `800 ${titleSize}px ${FONT}`;
  const tw = ctx.measureText('Gem Warden').width;
  FX.light(ctx, cx, H * 0.12, tw * 0.75, C.gold, 0.16 + 0.04 * Math.sin(time * 1.3));
  const sweep = ((time * 0.3) % 1.7) - 0.35;
  const tg = ctx.createLinearGradient(cx - tw / 2, 0, cx + tw / 2, 0);
  tg.addColorStop(0, C.gold);
  tg.addColorStop(clamp01(sweep - 0.14), C.gold);
  tg.addColorStop(clamp01(sweep), '#fffbe6');
  tg.addColorStop(clamp01(sweep + 0.14), C.gold);
  tg.addColorStop(1, C.gold);
  ctx.fillStyle = tg;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText('Gem Warden', cx, H * 0.12);
  // Six gems flank it, one of each colour and grade.
  const gs = titleSize * 0.3;
  if (W > tw + gs * 17) {
    G.COLORS.forEach((c, i) => {
      const gx = i < 3 ? cx - tw / 2 - gs * 2 - (2 - i) * gs * 2.5 : cx + tw / 2 + gs * 2 + (i - 3) * gs * 2.5;
      const gy = H * 0.12 + Math.sin(time * 1.6 + i * 1.1) * gs * 0.3;
      drawGem({ id: i + 0.5, mass: 1 << i, comp: { [c]: 1 }, kills: 0 }, gx, gy, gs, true, false);
    });
  }
  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();
    if (hover) FX.light(ctx, r.x + r.w / 2, r.y + r.h / 2, r.w * 0.7, C.gold, 0.1);
    drawMiniMap(f, { x: r.x + 8, y: r.y + 8, w: r.h - 16, h: r.h - 16 }, open, time + i * 1.7);
    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` + (progress.best[i] ? ` · best ${progress.best[i]}` : '') : '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) });
    else
      widgets.push({
        ...r,
        id: `field-${i}`,
        tap: () => {
          const n = (lockedTaps.get(i) ?? 0) + 1;
          lockedTaps.set(i, n);
          if (n >= 5) testOpen.add(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 - 120, y: H - 38, w: 112, h: 30 };
  button(sr, 'sound', soundLabel(), { tap: cycleSound, disabled: !soundAlive() });
}

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, time: number): 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();
  if (!open) return;
  FX.light(ctx, ox + (ex + 0.5) * t, oy + (ey + 0.5) * t, t * 3.2, C.mana, 0.5 + 0.2 * Math.sin(time * 2));
  // A light walks the path the monsters will take.
  let total = 0;
  for (let i = 1; i < f.path.length; i++) total += Math.abs(f.path[i][0] - f.path[i - 1][0]) + Math.abs(f.path[i][1] - f.path[i - 1][1]);
  let d = (time * 7) % total;
  for (let i = 1; i < f.path.length; i++) {
    const [ax, ay] = f.path[i - 1];
    const [bx, by] = f.path[i];
    const seg = Math.abs(bx - ax) + Math.abs(by - ay);
    if (d <= seg) {
      FX.light(ctx, ox + (ax + ((bx - ax) * d) / seg + 0.5) * t, oy + (ay + ((by - ay) * d) / seg + 0.5) * t, t * 2.4, '#ff9a8a', 0.95);
      break;
    }
    d -= seg;
  }
}

function drawPlay(g: G.Game, time: number): void {
  const L = computeLayout();
  renderBackground(L, g);
  const t = L.tile;
  // A shake moves the field and all that is on it; the panel stays put.
  const [shx, shy] = FX.shakeOffset();
  const fx = L.field.x + shx * t;
  const fy = L.field.y + shy * t;
  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;

  // Lights drift down the path, showing which way the monsters walk.
  const glints = Math.round(Math.max(3, g.pathLength / 9) * Math.min(1, FX.quality));
  for (let i = 0; i < glints; i++) {
    const [px, py] = G.pathPos(g, (time * 1.6 + (i * g.pathLength) / glints) % g.pathLength);
    FX.light(ctx, X(px), Y(py), t * 0.55, '#8f7fd0', 0.11);
  }
  drawPortal(X(g.pathPoints[0][0] + 0.5), Y(g.pathPoints[0][1] + 0.5), t, time);

  // 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.lineDashOffset = -time * 10;
      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;
  drawOrb(g, X(ox + 0.5), Y(oy + 0.5), t, time);
  const overflowing = overflow.t > 0 && overflow.amount >= 1;
  if (overflowing) {
    // A full orb throws away new mana; flash it so expanding the pool comes to mind.
    ctx.globalAlpha = FX.calm ? 1 : 0.55 + 0.45 * Math.sin(time * 10);
    ctx.strokeStyle = C.danger;
    ctx.lineWidth = Math.max(2, t * 0.1);
    ctx.beginPath();
    ctx.arc(X(ox + 0.5), Y(oy + 0.5), t * 0.95, 0, Math.PI * 2);
    ctx.stroke();
    ctx.globalAlpha = 1;
  }

  // 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);
    const cx = x + t / 2;
    const cy = y + t / 2;
    const born = structBorn.get(s.id);
    const pop = born === undefined ? 1 : backOut(clamp01((nowT - born) / 0.32));
    const fired = firedAt.get(s.y * G.COLS + s.x);
    // 1 at the moment it fires, gone a fifth of a second later.
    const kick = fired === undefined ? 0 : Math.max(0, 1 - (fxT - fired) / 0.2);
    const hex = s.gem ? G.gemColorHex(s.gem) : '';
    ctx.save();
    if (pop !== 1) {
      ctx.translate(cx, cy);
      ctx.scale(pop, pop);
      ctx.translate(-cx, -cy);
    }
    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(cx, cy, t * 0.3, 0, Math.PI * 2);
      ctx.fill();
      if (s.gem) {
        // The socket glows with its gem and flares when the tower fires.
        ctx.strokeStyle = hex;
        ctx.globalAlpha = 0.45 + 0.2 * Math.sin(time * 3 + s.id) + 0.35 * kick;
        ctx.lineWidth = Math.max(1, t * 0.05);
        ctx.beginPath();
        ctx.arc(cx, cy, t * 0.33, 0, Math.PI * 2);
        ctx.stroke();
        ctx.globalAlpha = 1;
      }
    } else {
      // A rune circle that turns slowly and blazes when the trap strikes.
      if (s.gem) FX.light(ctx, cx, cy, t * (0.7 + 0.5 * kick), hex, 0.25 + 0.6 * kick);
      ctx.strokeStyle = s.gem ? hex : C.stoneHi;
      ctx.globalAlpha = 0.75 + 0.25 * kick;
      ctx.lineWidth = Math.max(1, t * 0.06 * (1 + kick));
      ctx.beginPath();
      ctx.arc(cx, cy, 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(cx + Math.cos(a) * t * 0.36, cy + 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, cx, cy, t * (s.kind === 'trap' ? 0.24 : 0.27) * (1 + 0.3 * kick), true);
    ctx.restore();
    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();
  }

  for (const m of g.monsters) drawMonster(g, m, X, Y, t, time);
  drawFurthest(g, X, Y, t);

  // Monsters near the orb carry the mana left after they and every monster
  // ahead of them hit it: white while it stays covered, red once it busts.
  // Drawn after all monsters so none covers another's number.
  const nearOrb = g.monsters
    .filter((m) => m.hp > 0 && g.pathLength - m.dist <= ORB_WARN_TILES)
    .sort((a, b) => b.dist - a.dist);
  let manaLeft = g.mana;
  nearOrb.forEach((m, ahead) => {
    manaLeft -= G.orbCost(g, m, ahead);
    const left = Math.floor(manaLeft);
    const label = left < 0 ? `−${-left}` : `${left}`;
    const r = t * MONSTER_LOOK[m.type].size;
    ctx.font = `800 ${Math.max(10, t * 0.36)}px ${FONT}`;
    ctx.textAlign = 'center';
    ctx.lineWidth = 3;
    ctx.strokeStyle = '#000';
    ctx.strokeText(label, X(m.x), Y(m.y) - r - t * 0.22);
    ctx.fillStyle = left < 0 ? C.danger : '#fff';
    ctx.fillText(label, X(m.x), Y(m.y) - r - t * 0.22);
  });

  // Shots: a bright head drawing a fading streak behind it.
  ctx.save();
  ctx.lineCap = 'round';
  for (const p of g.shots) {
    let tr = trails.get(p);
    if (!tr) trails.set(p, (tr = []));
    if (!paused) {
      tr.push(p.x, p.y);
      if (tr.length > 12) tr.splice(0, 2);
    }
    ctx.globalCompositeOperation = 'lighter';
    ctx.strokeStyle = p.color;
    const n = tr.length / 2;
    for (let i = 1; i < n; i++) {
      ctx.globalAlpha = (i / n) * 0.7;
      ctx.lineWidth = Math.max(1, t * 0.13 * (i / n));
      ctx.beginPath();
      ctx.moveTo(X(tr[i * 2 - 2]), Y(tr[i * 2 - 1]));
      ctx.lineTo(X(tr[i * 2]), Y(tr[i * 2 + 1]));
      ctx.stroke();
    }
    ctx.globalAlpha = 1;
    FX.light(ctx, X(p.x), Y(p.y), Math.max(5, t * 0.34), p.color, 1);
  }
  ctx.restore();

  FX.draw({ ctx, ox: fx, oy: fy, unit: t }, FX.FIELD, FONT);

  // Fireflies over the grass.
  const flies = Math.round(fireflies.length * Math.min(1, FX.quality));
  for (let i = 0; i < flies; i++) {
    const f = fireflies[i];
    const a = 0.3 + 0.3 * Math.sin(time * 1.7 + f.phase * 3);
    FX.light(ctx, X(f.x + Math.sin(time * f.pace + f.phase) * 0.9), Y(f.y + Math.cos(time * f.pace * 0.7 + f.phase * 1.3) * 0.7), Math.max(2.5, t * 0.16), f.color, a);
  }

  // The edges of the field pulse red while the orb is about to be hit.
  if (danger > 0.03 && g.state === 'playing') {
    const F = L.field;
    const d = t * 1.6;
    ctx.globalAlpha = danger * (FX.calm ? 0.7 : 0.55 + 0.3 * Math.sin(time * 7));
    for (const [x0, y0, x1, y1, r] of [
      [F.x, 0, F.x + d, 0, { x: F.x, y: F.y, w: d, h: F.h }],
      [F.x + F.w, 0, F.x + F.w - d, 0, { x: F.x + F.w - d, y: F.y, w: d, h: F.h }],
      [0, F.y, 0, F.y + d, { x: F.x, y: F.y, w: F.w, h: d }],
      [0, F.y + F.h, 0, F.y + F.h - d, { x: F.x, y: F.y + F.h - d, w: F.w, h: d }],
    ] as [number, number, number, number, Rect][]) {
      const edge = ctx.createLinearGradient(x0, y0, x1, y1);
      edge.addColorStop(0, 'rgba(255,40,70,0.55)');
      edge.addColorStop(1, 'rgba(255,40,70,0)');
      ctx.fillStyle = edge;
      ctx.fillRect(r.x, r.y, r.w, r.h);
    }
    ctx.globalAlpha = 1;
  }
  const fl = FX.flashNow();
  if (fl) {
    ctx.globalAlpha = fl.alpha;
    ctx.fillStyle = fl.color;
    ctx.fillRect(L.field.x, L.field.y, L.field.w, L.field.h);
    ctx.globalAlpha = 1;
  }

  if (overflowing) {
    const label = `−${Math.round(overflow.amount)} lost, orb full`;
    const size = Math.max(11, t * 0.34);
    ctx.font = `800 ${size}px ${FONT}`;
    const half = ctx.measureText(label).width / 2 + 4;
    const lx = Math.max(L.field.x + half, Math.min(L.field.x + L.field.w - half, L.field.x + (ox + 0.5) * t));
    const ly = L.field.y + (oy < 2 ? (oy + 1.5) * t + size * 0.6 : (oy - 0.5) * t - size * 0.4);
    ctx.textAlign = 'center';
    ctx.lineWidth = 3;
    ctx.strokeStyle = '#000';
    ctx.strokeText(label, lx, ly);
    ctx.fillStyle = C.danger;
    ctx.fillText(label, lx, ly);
  }

  drawBanner(L);
  drawScore(g, L);
  drawHint(g, L);
  drawPanel(g, L);
  drawInfo(g, L);
  // On the result screen these go between the dimmed field and the text.
  if (g.state === 'playing') FX.draw({ ctx, ox: 0, oy: 0, unit: 1 }, FX.UI, FONT);

  // 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;
    // Rises into place as it appears.
    const rise = (1 - cubicOut(clamp01((2.2 - toast.t) / 0.18))) * size;
    const r = { x: L.field.x + L.field.w / 2 - tw / 2, y: L.field.y + L.field.h - size * 3.2 + rise, 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 && !pauseActed && g.state === 'playing') drawPauseFog(L, time);
  if (g.state !== 'playing') drawResult(g, L);

  // The field fades in from the night.
  const fade = 1 - (nowT - fieldT0) / 0.5;
  if (fade > 0) {
    ctx.globalAlpha = fade;
    ctx.fillStyle = C.night;
    ctx.fillRect(0, 0, W, H);
    ctx.globalAlpha = 1;
  }
}

/** A see-through fog over the whole game while paused. Only the pause button
 *  stays clear and lit; anything else the player does lifts the fog. */
function drawPauseFog(L: Layout, time: number): void {
  ctx.fillStyle = 'rgba(8,10,22,0.55)';
  ctx.fillRect(0, 0, W, H);
  const ps = Math.min(40, L.field.w / 10);
  text('Paused', L.field.x + L.field.w / 2, L.field.y + L.field.h / 2, ps, C.goldDim, 'center', 800);
  const w = widgets.find((wd) => wd.id === 'pause');
  if (!w) return;
  FX.light(ctx, w.x + w.w / 2, w.y + w.h / 2, Math.max(w.w, w.h) * 1.4, C.gold, 0.22 + 0.08 * Math.sin(time * 3));
  button(w, 'pause', 'Resume', { active: true, tap: w.tap });
}

/** The portal monsters come from: a dark hole in turning light that swells with every spawn. */
function drawPortal(cx: number, cy: number, t: number, time: number): void {
  const p = portalPulse;
  FX.light(ctx, cx, cy, t * (1.25 + 0.5 * p), '#a02fc0', 0.6 + 0.4 * p);
  ctx.fillStyle = '#05020a';
  ctx.beginPath();
  ctx.arc(cx, cy, t * 0.34, 0, Math.PI * 2);
  ctx.fill();
  ctx.save();
  ctx.globalCompositeOperation = 'lighter';
  ctx.lineCap = 'round';
  const arms = ['#ff6ad5', '#b04ae8', '#6a3bff'];
  for (let i = 0; i < 6; i++) {
    const r = t * (0.2 + i * 0.075) * (1 + 0.15 * p);
    const a = -time * (2.6 - i * 0.3) + i * 1.1;
    ctx.strokeStyle = arms[i % 3];
    ctx.globalAlpha = 0.75 - i * 0.08;
    ctx.lineWidth = Math.max(1, t * 0.05);
    ctx.beginPath();
    ctx.arc(cx, cy, r, a, a + 1.9);
    ctx.stroke();
  }
  ctx.restore();
}

/** The orb is a glass vessel: the mana inside stands as high as the pool is full. */
function drawOrb(g: G.Game, cx: number, cy: number, t: number, time: number): void {
  if (g.state === 'lost') {
    // What is left of it: a dark husk with cracks.
    ctx.fillStyle = '#0a0f1c';
    ctx.beginPath();
    ctx.arc(cx, cy, t * 0.5, 0, Math.PI * 2);
    ctx.fill();
    ctx.strokeStyle = '#2b3a58';
    ctx.lineWidth = Math.max(1, t * 0.05);
    ctx.stroke();
    ctx.beginPath();
    for (let i = 0; i < 5; i++) {
      const a = i * 1.31 + 0.4;
      ctx.moveTo(cx, cy);
      ctx.lineTo(cx + Math.cos(a + 0.5) * t * 0.25, cy + Math.sin(a + 0.5) * t * 0.25);
      ctx.lineTo(cx + Math.cos(a) * t * 0.5, cy + Math.sin(a) * t * 0.5);
    }
    ctx.stroke();
    return;
  }
  const fill = clamp01(g.mana / g.manaCap);
  const low = fill < 0.18;
  // A hard quick beat while the mana runs low.
  const beat = low ? Math.pow(Math.max(0, Math.sin(time * 9)), 6) * 0.1 : 0;
  const R = t * 0.6 * (1 + Math.sin(time * 2.2) * 0.04 + orbPulse * 0.16 + beat);
  const hue = low ? C.danger : C.mana;
  FX.light(ctx, cx, cy, R * (2.5 + orbPulse), hue, 0.55 + 0.3 * orbPulse);
  if (orbHurt > 0) FX.light(ctx, cx, cy, R * 3.4, C.danger, orbHurt);
  ctx.save();
  ctx.beginPath();
  ctx.arc(cx, cy, R, 0, Math.PI * 2);
  ctx.clip();
  ctx.fillStyle = '#071226';
  ctx.fillRect(cx - R, cy - R, R * 2, R * 2);
  const level = cy + R - 2 * R * (0.08 + 0.92 * fill);
  const wave = R * (0.05 + 0.12 * orbPulse);
  const lg = ctx.createLinearGradient(0, cy - R, 0, cy + R);
  lg.addColorStop(0, low ? '#ff9aa6' : '#bfeaff');
  lg.addColorStop(0.45, hue);
  lg.addColorStop(1, low ? '#5a1626' : C.manaDeep);
  ctx.fillStyle = lg;
  ctx.beginPath();
  ctx.moveTo(cx - R, cy + R);
  for (let i = 0; i <= 8; i++) ctx.lineTo(cx - R + (i / 8) * 2 * R, level + Math.sin(i * 0.9 + time * 3.2) * wave);
  ctx.lineTo(cx + R, cy + R);
  ctx.closePath();
  ctx.fill();
  // Slow currents turning inside.
  ctx.globalCompositeOperation = 'lighter';
  ctx.strokeStyle = 'rgba(255,255,255,0.22)';
  ctx.lineWidth = Math.max(1, R * 0.09);
  for (let i = 0; i < 3; i++) {
    const a = time * (0.9 + i * 0.5) + i * 2.1;
    ctx.beginPath();
    ctx.arc(cx, cy, R * (0.3 + i * 0.24), a, a + 1.5);
    ctx.stroke();
  }
  ctx.restore();
  // The glass: a rim and a highlight.
  ctx.strokeStyle = low ? '#ffb3bd' : '#cfeeff';
  ctx.globalAlpha = 0.7;
  ctx.lineWidth = Math.max(1, t * 0.04);
  ctx.beginPath();
  ctx.arc(cx, cy, R, 0, Math.PI * 2);
  ctx.stroke();
  ctx.globalAlpha = 1;
  ctx.fillStyle = 'rgba(255,255,255,0.5)';
  ctx.beginPath();
  ctx.ellipse(cx - R * 0.35, cy - R * 0.42, R * 0.24, R * 0.13, -0.6, 0, Math.PI * 2);
  ctx.fill();
  // The gold arc still reads the fill exactly; two lights circle on it.
  const ringR = t * 0.78 + (R - t * 0.6);
  ctx.strokeStyle = C.gold;
  ctx.lineWidth = Math.max(1.5, t * 0.07);
  ctx.beginPath();
  ctx.arc(cx, cy, ringR, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * fill);
  ctx.stroke();
  for (let i = 0; i < 2; i++) {
    const a = time * 1.4 + i * Math.PI;
    FX.light(ctx, cx + Math.cos(a) * ringR, cy + Math.sin(a) * ringR, Math.max(2.5, t * 0.17), C.gold, 0.9);
  }
}

function monsterPath(type: G.MonsterType, x: number, y: number, r: number, squash: number): void {
  if (type === 'brute') roundRect({ x: x - r * (1 + squash), y: y - r * (1 - squash), w: r * 2 * (1 + squash), h: r * 2 * (1 - squash) }, r * 0.35);
  else if (type === 'runner') diamond(x, y, r * 1.2);
  else {
    ctx.beginPath();
    ctx.ellipse(x, y, r * (1 + squash), r * (1 - squash), 0, 0, Math.PI * 2);
  }
}

function drawMonster(g: G.Game, m: G.Monster, X: (v: number) => number, Y: (v: number) => number, t: number, time: number): void {
  const wob = Math.sin(time * 9 + m.wobble) * t * 0.04;
  const x = X(m.x);
  const y = Y(m.y) + wob;
  // They grow as they step out of the portal.
  const r = t * MONSTER_LOOK[m.type].size * (m.dist < 0.5 ? 0.35 + 1.3 * m.dist : 1);
  const col = MONSTER_LOOK[m.type].col;
  const squash = Math.sin(time * 9 + m.wobble + 1.2) * 0.07;
  const startArmor = g.waves[m.wave]?.armor ?? 0;
  // Share of the starting armour left, so tearing shows as a thinning plate.
  const plate = startArmor > 0 ? Math.min(1, m.armor / startArmor) : 0;
  if (m.type === 'giant') FX.light(ctx, x, y, r * 2.5, '#9fd4ff', 0.24 + 0.07 * Math.sin(time * 2 + m.wobble));
  if (m.type === 'runner') {
    // Afterimages trail a runner along the path.
    ctx.fillStyle = col;
    for (let i = 2; i >= 1; i--) {
      const [px, py] = G.pathPos(g, m.dist - i * 0.24);
      ctx.globalAlpha = 0.34 / i;
      diamond(X(px), Y(py) + wob, r * 1.2 * (1 - i * 0.12));
      ctx.fill();
    }
    ctx.globalAlpha = 1;
  }
  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.3) : col;
  monsterPath(m.type, x, y, r, squash);
  ctx.fill();
  if (m.type === 'brute') {
    ctx.strokeStyle = '#d6dbe8';
    ctx.lineWidth = Math.max(0.5, t * 0.07 * plate);
    ctx.stroke();
  } else if (m.armor > 0.5 && plate > 0) {
    // A plate ring just inside the edge, under the ward and slow rings.
    const lw = Math.max(1, t * 0.07 * plate);
    ctx.strokeStyle = '#d6dbe8';
    ctx.lineWidth = lw;
    ctx.beginPath();
    ctx.arc(x, y, Math.max(1, r - lw / 2), 0, Math.PI * 2);
    ctx.stroke();
  }
  // A hit flashes the whole body white for a moment.
  const hitT = hitFlash.get(m.id);
  const hit = hitT === undefined ? 0 : 1 - (fxT - hitT) / 0.12;
  if (hit > 0) {
    ctx.globalAlpha = hit * 0.8;
    ctx.fillStyle = '#ffffff';
    monsterPath(m.type, x, y, r, squash);
    ctx.fill();
    ctx.globalAlpha = 1;
  }
  if (m.ward > 0) {
    // The ward turns around its bearer and 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.setLineDash([r * 0.7, r * 0.28]);
    ctx.lineDashOffset = -time * r * 2.5;
    ctx.beginPath();
    ctx.arc(x, y, r + t * 0.09, 0, Math.PI * 2);
    ctx.stroke();
    ctx.setLineDash([]);
  }
  if (m.regen > 0 && m.poisonT <= 0) plus(x, y - r * 1.05, Math.max(2, r * 0.35), '#d8fff0');
  if (m.slowT > 0) {
    // Frost: a ring with six ice spikes.
    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);
    for (let i = 0; i < 6; i++) {
      const a = (i / 6) * Math.PI * 2 + m.wobble;
      ctx.moveTo(x + Math.cos(a) * (r + t * 0.05), y + Math.sin(a) * (r + t * 0.05));
      ctx.lineTo(x + Math.cos(a) * (r + t * 0.15), y + Math.sin(a) * (r + t * 0.15));
    }
    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));
  }
}

/** Announces a wave across the field: its number, and who is coming. */
function drawBanner(L: Layout): void {
  if (!banner) return;
  const life = 1.9;
  const age = nowT - banner.t0;
  if (age > life) {
    banner = null;
    return;
  }
  const inK = clamp01(age / 0.3);
  const outK = clamp01((life - age) / 0.4);
  const F = L.field;
  const size = Math.max(13, Math.min(28, F.w / 18));
  const cy = F.y + F.h * 0.3;
  // Sweeps in from the left and out to the right.
  const slide = FX.calm ? 0 : (cubicOut(inK) - 1) * F.w * 0.35 + (1 - cubicOut(outK)) * F.w * 0.35;
  ctx.save();
  ctx.beginPath();
  ctx.rect(F.x, F.y, F.w, F.h);
  ctx.clip();
  ctx.globalAlpha = Math.min(inK, outK);
  const band = ctx.createLinearGradient(F.x, 0, F.x + F.w, 0);
  band.addColorStop(0, 'rgba(8,9,18,0)');
  band.addColorStop(0.3, 'rgba(8,9,18,0.35)');
  band.addColorStop(0.7, 'rgba(8,9,18,0.35)');
  band.addColorStop(1, 'rgba(8,9,18,0)');
  ctx.fillStyle = band;
  ctx.fillRect(F.x, cy - size * 1.25, F.w, size * 2.5);
  FX.light(ctx, F.x + F.w / 2 + slide, cy, size * 5, banner.color, 0.3);
  ctx.fillStyle = banner.color;
  ctx.fillRect(F.x + F.w * 0.2 + slide * 0.6, cy - size * 1.25, F.w * 0.6, 1.5);
  ctx.fillRect(F.x + F.w * 0.2 - slide * 0.6, cy + size * 1.25 - 1.5, F.w * 0.6, 1.5);
  text(banner.title, F.x + F.w / 2 + slide, cy - size * 0.32, size, '#ffffff', 'center', 800);
  text(banner.sub, F.x + F.w / 2 - slide * 0.5, cy + size * 0.6, fitText(banner.sub, F.w - 16, size * 0.5, 600), banner.color, 'center', 600);
  ctx.restore();
}

/** A kill multiplier as shown on the track: ×10, ×3.2, ×0.45. */
function multLabel(m: number): string {
  return `×${m >= 9.95 ? '10' : m >= 1 ? m.toFixed(1) : m.toFixed(2)}`;
}

/** A pin at the furthest point any monster has reached, with the kill
 *  multiplier there. It only moves forward. */
function drawFurthest(g: G.Game, X: (v: number) => number, Y: (v: number) => number, t: number): void {
  if (g.furthest <= 0) return;
  const lap = Math.floor(g.furthest / g.pathLength);
  const [px, py] = G.pathPos(g, g.furthest - lap * g.pathLength);
  const m = G.killMult(g, g.furthest);
  const col = m >= 1 ? C.gold : C.danger;
  const x = X(px);
  const y = Y(py);
  const r = t * 0.16;
  // A post with a round head, standing just above the path tile.
  ctx.strokeStyle = col;
  ctx.lineWidth = Math.max(1.5, t * 0.06);
  ctx.beginPath();
  ctx.moveTo(x, y);
  ctx.lineTo(x, y - t * 0.55);
  ctx.stroke();
  ctx.fillStyle = col;
  ctx.beginPath();
  ctx.arc(x, y - t * 0.55, r, 0, Math.PI * 2);
  ctx.fill();
  const label = multLabel(m);
  ctx.font = `800 ${Math.max(10, t * 0.34)}px ${FONT}`;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.lineWidth = 3;
  ctx.strokeStyle = '#000';
  ctx.strokeText(label, x, y - t * 0.95);
  ctx.fillStyle = col;
  ctx.fillText(label, x, y - t * 0.95);
}

/** Where the running score sits this frame, so the hint can step around it. */
let scoreBox: Rect = { x: 0, y: 0, w: 0, h: 0 };

/** The score as it would stand if the field were won now. */
function drawScore(g: G.Game, L: Layout): void {
  const sc = G.score(g, focusTime, noPause);
  const size = Math.max(10, Math.min(14, L.field.w / 46));
  const s = `Score ${num(sc.total)}`;
  const m = `${num(sc.base)} ×${sc.distance.toFixed(2)} ×${sc.forge.toFixed(2)} ×${sc.domination.toFixed(2)} ×${sc.focus.toFixed(2)} ×${sc.noPause} + ${num(sc.early)}`;
  const ms = fitText(m, L.field.w * 0.62, size * 0.8, 600);
  ctx.font = `700 ${size}px ${FONT}`;
  let tw = ctx.measureText(s).width;
  ctx.font = `600 ${ms}px ${FONT}`;
  tw = Math.max(tw, ctx.measureText(m).width) + 16;
  scoreBox = { x: L.field.x + L.field.w - tw - 6, y: L.field.y + 6, w: tw, h: size * 1.6 + ms * 1.5 };
  if (g.state !== 'playing') return;
  roundRect(scoreBox, 8);
  ctx.fillStyle = '#0d1020cc';
  ctx.fill();
  const cx = scoreBox.x + scoreBox.w / 2;
  text(s, cx, scoreBox.y + size * 0.95, size, C.gold, 'center', 700);
  // Health killed × distance × forge × domination × focus × no-pause + early kills.
  const low = sc.focus < 0.995 || sc.noPause < 2;
  text(m, cx, scoreBox.y + size * 1.6 + ms * 0.55, ms, low ? C.danger : C.textDim, 'center', 600);
}

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 };
  if (r.x + r.w > scoreBox.x - 4) r.y = scoreBox.y + scoreBox.h + 4;
  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
  // The bar shudders when a purchase is refused for lack of mana.
  const mb = { x: colA.x + Math.sin(nowT * 55) * manaShake * 12, y, w: colA.w, h: rowH * 0.8 };
  manaBar = mb;
  roundRect(mb, 6);
  ctx.fillStyle = '#0a0d18';
  ctx.fill();
  const frac = Math.max(0, Math.min(1, g.mana / g.manaCap));
  const filled = { x: mb.x, y: mb.y, w: Math.max(6, mb.w * frac), h: mb.h };
  const lowMana = frac < 0.18 && g.state === 'playing';
  const mg = ctx.createLinearGradient(mb.x, 0, mb.x + mb.w, 0);
  mg.addColorStop(0, lowMana ? '#6a1a2c' : C.manaDeep);
  mg.addColorStop(1, lowMana ? C.danger : C.mana);
  ctx.save();
  roundRect(filled, 6);
  ctx.fillStyle = mg;
  ctx.fill();
  ctx.clip();
  // A sheen runs along the mana; fresh mana lights the whole bar.
  const sheenX = mb.x + (((nowT * 0.3) % 1.5) - 0.25) * mb.w;
  const sheen = ctx.createLinearGradient(sheenX - mb.h * 2, 0, sheenX + mb.h * 2, 0);
  sheen.addColorStop(0, 'rgba(255,255,255,0)');
  sheen.addColorStop(0.5, 'rgba(255,255,255,0.28)');
  sheen.addColorStop(1, 'rgba(255,255,255,0)');
  ctx.fillStyle = sheen;
  ctx.fillRect(mb.x, mb.y, mb.w, mb.h);
  if (manaFlash > 0) {
    ctx.fillStyle = `rgba(255,255,255,${0.45 * manaFlash})`;
    ctx.fillRect(mb.x, mb.y, mb.w, mb.h);
  }
  ctx.restore();
  if (manaFlash > 0) FX.light(ctx, filled.x + filled.w, mb.y + mb.h / 2, mb.h * 1.6, '#eaf8ff', manaFlash);
  ctx.strokeStyle = manaShake > 0 || lowMana ? C.danger : C.panelEdge;
  roundRect(mb, 6);
  ctx.stroke();
  const pot = Math.round(g.bonusPot * g.manaMult);
  const ms = `${Math.floor(g.mana)} / ${g.manaCap} mana` + (pot > 0 ? ` · pot +${pot}` : '');
  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(MAX_FORGE_GRADE, 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 });
    // The narrow column leaves no room for a fourth button of a size a thumb can hit,
    // so the sound button goes into the space under the inventory when there is some.
    const free = cy - gap - (inv.y + invRows * cell + (invRows - 1) * gap) - gap;
    const own = free >= 40;
    if (own) {
      const side = Math.min(48, free);
      soundButton({ x: cr.x + cr.w - side, y: cy - gap - side, w: side, h: side });
    }
    const ay = colA.y + colA.h - rowH;
    if (ay >= y - 2) controlRow({ x: colA.x, y: ay, w: colA.w, h: rowH }, gap, !own);
    else controlRow({ x: colA.x, y, w: colA.w, h: Math.max(20, colA.y + colA.h - y) }, gap, !own);
  } 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, true);
  }
}

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 = Math.round(G.earlyBonus(g) * g.manaMult);
  button(r, 'next', 'Next wave', { sub: left > 0 ? `+${bonus}` : 'none left', disabled: left === 0, accent: C.manaDeep, tap: doNextWave });
}

function soundButton(r: Rect): void {
  button(r, 'sound', '', { tap: cycleSound });
  speakerIcon(r);
}

/** Speed, pause and Fields, plus the sound button as a narrow icon unless it has a place of its own. */
function controlRow(r: Rect, gap: number, withSound: boolean): void {
  const sw = withSound ? Math.min(r.h * 1.1, r.w * 0.16) : -gap;
  const w = (r.w - sw - gap * 3) / 3;
  if (withSound) soundButton({ x: r.x + (w + gap) * 3, y: r.y, w: sw, h: r.h });
  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;
    },
  });
}

/** A speaker with sound waves; a note beside it when the music plays, struck through when silent. */
function speakerIcon(r: Rect): void {
  const u = Math.min(r.w, r.h) * 0.2;
  const cx = r.x + r.w / 2 - u * 0.5;
  const cy = r.y + r.h / 2;
  ctx.save();
  const on = progress.sound && soundAlive();
  ctx.fillStyle = ctx.strokeStyle = on ? C.text : C.textDim;
  ctx.lineWidth = Math.max(1.2, u * 0.3);
  ctx.lineCap = 'round';
  ctx.beginPath();
  ctx.moveTo(cx - u * 1.2, cy - u * 0.5);
  ctx.lineTo(cx - u * 0.5, cy - u * 0.5);
  ctx.lineTo(cx + u * 0.4, cy - u * 1.2);
  ctx.lineTo(cx + u * 0.4, cy + u * 1.2);
  ctx.lineTo(cx - u * 0.5, cy + u * 0.5);
  ctx.lineTo(cx - u * 1.2, cy + u * 0.5);
  ctx.closePath();
  ctx.fill();
  if (!on) {
    ctx.strokeStyle = C.danger;
    ctx.beginPath();
    ctx.moveTo(cx + u * 0.9, cy - u * 0.7);
    ctx.lineTo(cx + u * 2.1, cy + u * 0.7);
    ctx.moveTo(cx + u * 2.1, cy - u * 0.7);
    ctx.lineTo(cx + u * 0.9, cy + u * 0.7);
    ctx.stroke();
  } else {
    ctx.beginPath();
    ctx.arc(cx + u * 0.5, cy, u * 0.9, -0.8, 0.8);
    ctx.stroke();
    if (progress.music) {
      ctx.beginPath();
      ctx.arc(cx + u * 0.5, cy, u * 1.8, -0.8, 0.8);
      ctx.stroke();
    }
  }
  ctx.restore();
}

/** How far from the orb, in tiles along the path, a monster starts showing its orb cost. */
const ORB_WARN_TILES = 4;

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: '#7fb4d6', 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;
}

/** Info cards sit bottom-left, or bottom-right when the pointer is over that
 *  corner, so a card never hides the tower a gem is being dropped on. */
function cardRect(L: Layout, w: number, h: number): Rect {
  const r = { x: L.field.x + 6, y: L.field.y + L.field.h - h - 6, w, h };
  const pad = L.tile;
  if (pointer.inside && inside(L.field, pointer.x, pointer.y) && pointer.x <= r.x + w + pad && pointer.y >= r.y - pad) {
    r.x = L.field.x + L.field.w - w - 6;
  }
  return r;
}

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)}%`]);
  else if (kind === 'trap' && (gem.comp.red ?? 0) > 0.005) lines.push(['Splash', 'none in traps']);
  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)]);
  lines.push(['Worth', `${+gem.mass.toFixed(2)} × G1`]);
  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 = cardRect(L, 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 at start', 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)}`]);
    const startArmor = g.waves[m.wave]?.armor ?? 0;
    if (startArmor > 0) lines.push(['Armour', m.armor < startArmor ? `${Math.round(m.armor)} of ${startArmor}` : String(startArmor)]);
    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 = cardRect(L, 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 = cardRect(L, 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 {
  const won = g.state === 'won';
  // The end plays out on the field first; then the screen dims and the result comes up.
  const since = nowT - endT - (won ? 0.35 : 1);
  const k = clamp01(since / 0.5);
  ctx.fillStyle = `rgba(5,6,12,${0.72 * k})`;
  ctx.fillRect(0, 0, W, H);
  // Fireworks burst over the dimmed field and behind the text.
  FX.draw({ ctx, ox: 0, oy: 0, unit: 1 }, FX.UI, FONT);
  if (k <= 0) return;
  const cx = L.field.x + L.field.w / 2;
  const size = Math.min(44, L.field.w / 9);
  const rowH = Math.max(15, size * 0.5);
  const bh = Math.max(34, size * 0.9);
  const rows = won ? 6 : 0;
  // Stack everything around the screen centre; the breakdown needs more room than the field.
  let y = H / 2 - (size * (won ? 2.6 : 2) + rows * rowH + bh) / 2;
  ctx.save();
  ctx.globalAlpha = k;
  const title = won ? 'Field defended!' : 'The orb shattered';
  // Sized to fit a narrow screen even at the top of its pop.
  const titleSize = fitText(title, (L.field.w - 12) / 1.03, size, 800) * (0.75 + 0.25 * backOut(k));
  FX.light(ctx, cx, y + size * 0.5, size * 5, won ? C.gold : C.danger, 0.22 + 0.06 * Math.sin(nowT * 2.5));
  text(title, cx, y + size * 0.5, titleSize, won ? C.gold : C.danger, 'center', 800);
  y += size * 1.2;
  if (won) {
    // The stars land one after another, each with a chime.
    const s = G.stars(g);
    for (let i = 0; i < 3; i++) {
      const sx = cx + (i - 1) * size * 1.1;
      const sy = y + size * 0.35;
      const at = (since - 0.35 - i * 0.32) / 0.3;
      const on = i < s && at > 0;
      if (on && starsShown === i) {
        starsShown++;
        A.sfx.star(i);
        FX.sparks(FX.UI, sx, sy, 14, C.gold, { speed: size * 4, life: 0.5, size: 2 });
        FX.star(FX.UI, sx, sy, size * 1.2, 0.45, '#fff8dc');
      }
      drawStar(sx, sy, size * 0.45 * (on ? backOut(clamp01(at)) * 0.4 + 0.6 : 1), on);
    }
    y += size * 0.9;
    const notes = `★ won   ${g.banished === 0 ? '★' : '☆'} nothing reached the orb   ${g.built <= 5 ? '★' : '☆'} five or fewer buildings`;
    text(notes, cx, y + size * 0.2, fitText(notes, L.field.w - 20, Math.max(10, size * 0.3), 500), C.textDim, 'center', 500);
    y += size * 0.7;
    const sc = G.score(g, focusTime, noPause);
    const bw = Math.min(360, L.field.w - 40);
    const lx = cx - bw / 2;
    const rx = cx + bw / 2;
    const fs = Math.max(11, Math.min(15, rowH * 0.7));
    const x2 = (v: number) => `×${v.toFixed(2)}`;
    const lines: [string, string, string][] = [
      ['Kills', 'health killed', num(sc.base)],
      ['Distance', 'how early they died, by health', x2(sc.distance)],
      ['Forge', `${num(sc.gems + g.buildMana)} mana in gems and buildings`, x2(sc.forge)],
      ['Domination', `${g.built} built`, x2(sc.domination)],
      ['Focus', `${sc.focus.toFixed(2)}× average speed`, x2(sc.focus)],
      ['No pause', noPause ? 'never played during a pause' : 'played during a pause', `×${sc.noPause}`],
      ['Early kills', `+ furthest monster at ${multLabel(sc.earlyMult)} · ${g.waves.length} waves`, num(sc.early)],
    ];
    roundRect({ x: lx - 10, y: y - 4, w: bw + 20, h: rowH * (lines.length + 1.2) + 8 }, 8);
    ctx.fillStyle = '#0b0e1aee';
    ctx.fill();
    lines.forEach(([label, note, v], i) => {
      const ry = y + rowH * (i + 0.5);
      text(label, lx, ry, fs, C.text, 'left', 700);
      text(note, lx + fs * 6.9, ry, fitText(note, bw - fs * 11.1, fs * 0.85, 500), C.textDim, 'left', 500);
      const low = (label === 'Focus' && sc.focus < 0.995) || (label === 'No pause' && sc.noPause < 2);
      text(v, rx, ry, fs, low ? C.danger : C.text, 'right', 700);
    });
    y += rowH * lines.length;
    ctx.strokeStyle = C.panelEdge;
    ctx.beginPath();
    ctx.moveTo(lx, y + 1);
    ctx.lineTo(rx, y + 1);
    ctx.stroke();
    // The total counts up.
    const counted = Math.round(sc.total * cubicOut(clamp01((since - 0.5) / 1.1)));
    const best = newBest ? 'new best!' : `best ${progress.best[g.fieldIndex]}`;
    text('Score', lx, y + rowH * 0.55, fs * 1.15, C.gold, 'left', 800);
    text(best, lx + fs * 6, y + rowH * 0.55, fs * 0.85, newBest ? C.gold : C.textDim, 'left', 600);
    text(num(counted), rx, y + rowH * 0.55, fs * 1.15, C.gold, 'right', 800);
    // The ? sits between the best note and the total and opens the formulas.
    const qs = Math.max(26, rowH * 1.1);
    if (k >= 0.7) button({ x: cx - qs / 2 + fs * 2, y: y + rowH * 0.55 - qs / 2, w: qs, h: qs }, 'formula', '?', { active: showFormula, tap: () => (showFormula = !showFormula) });
    y += rowH * 1.4;
  } else {
    const n = `Reached wave ${g.nextWave} of ${g.waves.length}`;
    text(n, cx, y + size * 0.2, Math.max(12, size * 0.4), C.textDim, 'center', 500);
    y += size * 0.8;
  }
  ctx.restore();
  if (k < 0.7) return;
  resultReady = true;
  const bw = Math.min(150, L.field.w * 0.3);
  const nextLabel = won ? (g.fieldIndex + 1 < G.FIELDS.length ? 'Next field' : 'Play again') : 'Retry';
  button({ x: cx - bw - 6, y, w: bw, h: bh }, 'again', nextLabel, { active: true, tap: afterGame });
  button({ x: cx + 6, y, w: bw, h: bh }, 'fields', 'Fields', {
    tap: () => {
      screen = 'menu';
      widgets = [];
    },
  });
  if (won && showFormula) drawFormula(g, L);
}

/** A whole number with thin spaces between thousands: 123 456. */
function num(v: number): string {
  return String(Math.round(v)).replace(/\B(?=(\d{3})+(?!\d))/g, '\u2009');
}

/** How the score is made, with this run's numbers filled in. A tap anywhere closes it. */
function drawFormula(g: G.Game, L: Layout): void {
  const sc = G.score(g, focusTime, noPause);
  const x2 = (v: number) => `×${v.toFixed(2)}`;
  const lines: [string, string][] = [
    ['Kills', 'health of every monster killed'],
    ['', `${num(sc.base)} health`],
    ['Distance', 'each kill’s 10^(1 − d), weighted by health'],
    ['', 'd: 0 at the portal, 1 at the orb, 2 there a lap later'],
    ['', `×10 at the portal, ×1 at the orb: ${x2(sc.distance)}`],
    ['Forge', '2 × (gems at forge cost + buildings) ÷ field mana'],
    ['', `2 × (${num(sc.gems)} + ${num(g.buildMana)}) ÷ ${num(sc.fieldMana)} = ${x2(sc.forge)}`],
    ['Domination', '1 + (15 − built)² ÷ 60, ×1 from 15 built'],
    ['', `1 + (15 − ${Math.min(15, g.built)})² ÷ 60 = ${x2(sc.domination)}`],
    ['Focus', 'game time ÷ real time, so faster speeds pay'],
    ['', `${clock(g.time)} ÷ ${clock(focusTime)} = ${x2(sc.focus)}`],
    ['', 'a pause counts once you play during it'],
    ['No pause', '×2, or ×1 once you play during a pause'],
    ['', `×${sc.noPause}`],
    ['Early kills', '1000 × waves × 10^(1 − d) of the furthest monster'],
    ['', `1000 × ${g.waves.length} × ${sc.earlyMult.toFixed(2)} = ${num(sc.early)}`],
    ['Score', 'kills × the multipliers above + early kills'],
    ['', `${num(sc.base)} × ${sc.distance.toFixed(2)} × ${sc.forge.toFixed(2)} × ${sc.domination.toFixed(2)} × ${sc.focus.toFixed(2)} × ${sc.noPause} + ${num(sc.early)} = ${num(sc.total)}`],
    ['', `Field mana ${num(sc.fieldMana)}: all its kills, no orange gems.`],
  ];
  const pad = 12;
  const w = Math.min(560, L.field.w - 16);
  const fs = Math.max(10, Math.min(14, w / 38));
  const lh = fs * 1.55;
  const h = lines.length * lh + pad * 2;
  const r = { x: L.field.x + L.field.w / 2 - w / 2, y: Math.max(4, H / 2 - h / 2), w, h };
  roundRect(r, 10);
  ctx.fillStyle = '#0b0e1afa';
  ctx.fill();
  ctx.strokeStyle = C.goldDim;
  ctx.lineWidth = 1;
  ctx.stroke();
  const labelW = fs * 7.3;
  lines.forEach(([label, line], i) => {
    const y = r.y + pad + lh * (i + 0.5);
    if (label) text(label, r.x + pad, y, fs, label === 'Score' ? C.gold : C.text, 'left', 700);
    const first = label !== '';
    const maxW = r.w - pad * 2 - labelW;
    text(line, r.x + pad + labelW, y, fitText(line, maxW, fs * (first ? 0.95 : 0.9), first ? 600 : 500), first ? C.text : C.textDim, 'left', first ? 600 : 500);
  });
  widgets.push({ ...r, id: 'formula-close', tap: () => (showFormula = false) });
}

/** Seconds as m:ss. */
function clock(sec: number): string {
  const s = Math.round(sec);
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
}

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

if (import.meta.env.DEV) {
  // For scripted checks against the dev server; not part of the built napplet.
  Object.assign(window, {
    __gw: {
      G,
      A,
      FX,
      start: startField,
      game: () => game,
      layout: computeLayout,
      widgets: () => widgets,
      set: (o: { speed?: number; paused?: boolean; wall?: number; focus?: number; noPause?: boolean }) => {
        speed = o.speed ?? speed;
        paused = o.paused ?? paused;
        wallTime = o.wall ?? wallTime;
        focusTime = o.focus ?? focusTime;
        noPause = o.noPause ?? noPause;
      },
      stats: () => ({ frameMs, quality: FX.quality, particles: FX.count(), intensity, danger, voices: A.voiceCount() }),
    },
  });
}

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