// app.mjs: the instruments on /strata/loschmidts-paradox/. Every gas here is engine.mjs, the same
// bytes verify-loschmidts-paradox.mjs imports; every measured number is data/results.json, which
// research/arrow-of-time/measure.mjs wrote and the verifier recomputes.
import * as E from './engine.mjs';

const $ = (id) => document.getElementById(id);
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
const DPR = () => Math.min(devicePixelRatio || 1, 2);
const css = (v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim();
const fmt = (x, d = 0) => x.toLocaleString('en-GB', { minimumFractionDigits: d, maximumFractionDigits: d });
const SIGMA = E.DEFAULTS.sigma;

function setupCanvas(cv, aspect) {
  const w = cv.clientWidth, h = Math.round(w * aspect);
  cv.style.height = h + 'px';
  cv.width = Math.round(w * DPR()); cv.height = Math.round(h * DPR());
  const ctx = cv.getContext('2d'); ctx.setTransform(DPR(), 0, 0, DPR(), 0, 0);
  return { ctx, w, h };
}

// Each disk keeps the colour of where it started: left edge amber, the middle of the box teal.
function startColour(x0) {
  const f = Math.max(0, Math.min(1, x0 / 0.5));
  const a = [255, 178, 84], b = [96, 206, 214];
  return `rgb(${a.map((c, j) => Math.round(c + f * (b[j] - c))).join(',')})`;
}

function farthest(xs, ys, x0, y0) { return E.maxSeparation(xs, ys, x0, y0); }

function drawBox(cv, xs, ys, x0, opts = {}) {
  const { ctx, w } = setupCanvas(cv, 1);
  ctx.fillStyle = css('--well'); ctx.fillRect(0, 0, w, w);
  ctx.strokeStyle = css('--grid'); ctx.lineWidth = 1; ctx.setLineDash([4, 5]);
  ctx.beginPath(); ctx.moveTo(w / 2, 0); ctx.lineTo(w / 2, w); ctx.stroke(); ctx.setLineDash([]);
  const r = (SIGMA / 2) * w;
  if (opts.ghostX) {
    ctx.strokeStyle = 'rgba(200,210,225,.45)'; ctx.lineWidth = 1;
    for (let i = 0; i < opts.ghostX.length; i++) { ctx.beginPath(); ctx.arc(opts.ghostX[i] * w, opts.ghostY[i] * w, r, 0, Math.PI * 2); ctx.stroke(); }
  }
  for (let i = 0; i < xs.length; i++) {
    ctx.fillStyle = startColour(x0[i]);
    // draw periodic copies near the edges so a disk crossing the wall is not cut in half
    for (const dx of [-1, 0, 1]) for (const dy of [-1, 0, 1]) {
      const cx = (xs[i] + dx) * w, cy = (ys[i] + dy) * w;
      if (cx < -r || cx > w + r || cy < -r || cy > w + r) continue;
      ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.fill();
    }
  }
  if (opts.mark != null) {
    ctx.strokeStyle = '#fff'; ctx.lineWidth = 2;
    ctx.beginPath(); ctx.arc(xs[opts.mark] * w, ys[opts.mark] * w, r + 4, 0, Math.PI * 2); ctx.stroke();
  }
}

// ── 1. The box ────────────────────────────────────────────────────────────────────────────────
const B = { mode: 'int', gas: null, init: null, trace: [], playing: false, nudged: null, reversals: 0 };
const NUDGE_DISK = 0;

function resetBox() {
  B.init = E.initial();
  B.gas = B.mode === 'int' ? new E.IntGas(B.init) : new E.FloatGas(B.init);
  B.trace = [[0, 1]]; B.nudged = null; B.reversals = 0; B.autoStop = true; B.passedZero = false;
  setPlaying(false); renderBox();
}
function setPlaying(p) {
  B.playing = p; $('b-play').textContent = p ? 'Pause' : 'Run';
  $('b-play').setAttribute('aria-pressed', String(p));
  if (p) requestAnimationFrame(tick);
}
// Returns true if it stopped at t = 0 on the way back, so the reader sees the start state itself
// (the moment the reversed gas is exactly home) rather than a frame either side of it.
function stepBox(n) {
  for (let k = 0; k < n; k++) {
    B.gas.step(1);
    if (B.gas.t % 10 === 0) B.trace.push([B.gas.t, E.leftFraction(B.gas.xs())]);
    if (B.gas.t === 0 && (B.gas._dir || 1) < 0 && !B.passedZero) { B.passedZero = true; return true; }
  }
  return false;
}
function tick() {
  if (!B.playing) return;
  if (stepBox(Number($('b-speed').value))) { setPlaying(false); renderBox(); return; }
  // The first run stops by itself once the gas has spread, so the reader can take the next move.
  if (B.autoStop && B.gas.t >= 2000) { B.autoStop = false; setPlaying(false); renderBox(); $('b-hint').hidden = false; return; }
  renderBox();
  requestAnimationFrame(tick);
}
function renderBox() {
  const g = B.gas, xs = g.xs(), ys = g.ys();
  drawBox($('b-cv'), xs, ys, B.init.x, { mark: B.nudged });
  const lf = E.leftFraction(xs), far = farthest(xs, ys, B.init.x, B.init.y) / SIGMA;
  const dir = (g._dir || 1) > 0 ? 'forward' : 'backward';
  $('b-out').innerHTML =
    `<span class="mono">t = ${fmt(g.t)} steps</span>, running <b>${dir}</b>, ` +
    `<b class="hot">${fmt(lf * 100, 1)}%</b> of disks in the left half. ` +
    `Farthest any disk is from where it began: <b>${far < 1e-9 ? '0 (every disk exactly home, to the bit)' : far < 0.01 ? far.toExponential(1) + ' diameters' : fmt(far, 2) + ' diameters'}</b>.` +
    (B.nudged != null ? ` <span class="small">(One disk, ringed, was moved ${B.mode === 'int' ? 'one grid step' : 'by 2⁻³² of the box'}.)</span>` : '');
  drawTrace();
}
function drawTrace() {
  const cv = $('b-plot'); const { ctx, w, h } = setupCanvas(cv, 0.34);
  const pad = { l: 40, r: 10, t: 10, b: 26 };
  const ts = B.trace.map(p => p[0]);
  let t0 = Math.min(0, ...ts), t1 = Math.max(100, ...ts);
  if (t1 - t0 < 1000) t1 = t0 + 1000;
  const X = t => pad.l + (t - t0) / (t1 - t0) * (w - pad.l - pad.r);
  const Y = f => pad.t + (1 - (f - 0.3) / 0.7) * (h - pad.t - pad.b);
  ctx.clearRect(0, 0, w, h);
  ctx.font = '10px "Martian Mono", monospace'; ctx.fillStyle = css('--dim'); ctx.strokeStyle = css('--grid'); ctx.lineWidth = 1;
  for (const f of [0.5, 1]) { ctx.beginPath(); ctx.moveTo(pad.l, Y(f)); ctx.lineTo(w - pad.r, Y(f)); ctx.stroke(); ctx.fillText(f === 1 ? 'all' : 'half', 2, Y(f) + 3); }
  ctx.beginPath(); ctx.moveTo(X(0), pad.t); ctx.lineTo(X(0), h - pad.b); ctx.stroke();
  ctx.fillText('t = 0', X(0) + 3, h - 12);
  ctx.textAlign = 'right'; ctx.fillText(`${fmt(t1)} steps`, w - pad.r, h - 12); if (t0 < 0) { ctx.textAlign = 'left'; ctx.fillText(`${fmt(t0)}`, pad.l, h - 12); }
  ctx.textAlign = 'left';
  // the trace is drawn in the order it was lived, so a reversed run doubles back over itself
  ctx.strokeStyle = css('--hot'); ctx.lineWidth = 1.4; ctx.beginPath();
  B.trace.forEach(([t, f], i) => { i ? ctx.lineTo(X(t), Y(f)) : ctx.moveTo(X(t), Y(f)); });
  ctx.stroke();
}

$('b-play').addEventListener('click', () => setPlaying(!B.playing));
$('b-rev').addEventListener('click', () => { B.gas.reverse(); B.passedZero = B.gas.t <= 0; B.reversals++; B.trace.push([B.gas.t, E.leftFraction(B.gas.xs())]); renderBox(); });
$('b-nudge').addEventListener('click', () => {
  B.gas.nudge(NUDGE_DISK, B.mode === 'int' ? 1 : 1 / E.L);
  B.nudged = NUDGE_DISK; renderBox();
});
$('b-reset').addEventListener('click', resetBox);
$('b-mode').addEventListener('change', (e) => { B.mode = e.target.value; resetBox(); });
$('b-step').addEventListener('click', () => { stepBox(500); renderBox(); });

// ── 2. There and back ─────────────────────────────────────────────────────────────────────────
const TB = { running: false };
function tbLabel() { $('tb-Tv').textContent = `${fmt(Number($('tb-T').value))} steps`; }
function runThereAndBack() {
  if (TB.running) return;
  const T = Number($('tb-T').value), how = $('tb-how').value;
  const init = E.initial();
  const gas = how === 'float' ? new E.FloatGas(init) : new E.IntGas(init);
  let phase = 0, done = 0; TB.running = true; $('tb-go').disabled = true;
  const CHUNK = 150;
  const work = () => {
    const n = Math.min(CHUNK, T - done); gas.step(n); done += n;
    $('tb-out').textContent = `${phase ? 'coming back' : 'going out'}: ${fmt(done)} of ${fmt(T)} steps…`;
    if (done >= T) {
      if (phase === 0) {
        if (how.startsWith('k')) gas.nudge(NUDGE_DISK, 2 ** Number(how.slice(1)));
        gas.reverse(); phase = 1; done = 0;
      } else {
        gas.reverse(); TB.running = false; $('tb-go').disabled = false; report(gas, init, T, how); return;
      }
    }
    setTimeout(work, 0);
  };
  work();
}
function report(gas, init, T, how) {
  const xs = gas.xs(), ys = gas.ys();
  const far = farthest(xs, ys, init.x, init.y), lf = E.leftFraction(xs);
  const same = how === 'none' && gas.key && gas.key() === new E.IntGas(init).key();
  const failed = far > SIGMA;
  drawBox($('tb-cv'), xs, ys, init.x, { ghostX: init.x, ghostY: init.y, mark: how.startsWith('k') ? NUDGE_DISK : null });
  const what = { none: 'exact integers, untouched', float: 'ordinary floating point, untouched' }[how] ||
    `exact integers, one disk moved ${how === 'k0' ? 'one grid step' : '2^' + how.slice(1) + ' grid steps'} at the turn`;
  $('tb-out').innerHTML = `Out ${fmt(T)} steps and back, ${what}: ` +
    (same ? `<b class="ok">every position and every velocity is identical to the start, all ${init.N * 4} integers</b>.` :
      `the farthest disk is <b class="${failed ? 'bad' : 'ok'}">${far < 1e-6 ? far.toExponential(1) : fmt(far / SIGMA, 2)}${far < 1e-6 ? ' of the box' : ' diameters'}</b> from home; ` +
      `${fmt(lf * 100, 1)}% of disks are back in the left half. ` +
      (failed ? `<b class="bad">It did not come back</b> (the test: every disk within one diameter of where it began).` : `<b class="ok">It came back</b> (every disk within one diameter).`));
}
$('tb-T').addEventListener('input', tbLabel);
$('tb-go').addEventListener('click', runThereAndBack);

// ── 3. The measured horizon ───────────────────────────────────────────────────────────────────
async function horizonChart() {
  const R = await (await fetch('./data/results.json')).json();
  const cv = $('h-cv'); const { ctx, w, h } = setupCanvas(cv, 0.62);
  const pad = { l: 52, r: 70, t: 14, b: 40 };
  const X = k => pad.l + (k / 24) * (w - pad.l - pad.r);
  const Y = T => pad.t + (1 - T / 4000) * (h - pad.t - pad.b);
  ctx.clearRect(0, 0, w, h);
  ctx.font = '10px "Martian Mono", monospace'; ctx.fillStyle = css('--dim'); ctx.strokeStyle = css('--grid'); ctx.lineWidth = 1;
  for (let T = 0; T <= 4000; T += 1000) { ctx.beginPath(); ctx.moveTo(pad.l, Y(T)); ctx.lineTo(w - pad.r, Y(T)); ctx.stroke(); ctx.fillText(fmt(T), 4, Y(T) + 3); }
  for (const k of R.KS) ctx.fillText(k === 0 ? '1' : `2^${k}`, X(k) - 8, h - pad.b + 14);
  ctx.fillText('size of the nudge, in grid steps (2^32 steps = the box)', pad.l, h - 6);
  ctx.fillText('horizon, steps', pad.l + 4, pad.t + 10);
  const cols = ['#ffab5e', '#8fd3ff', '#86cf94', '#e79ad8', '#e8d36a'];
  R.rows.forEach((r, i) => {
    const c = cols[i % cols.length];
    // the pre-registered prediction: a line of slope -1/rate through this seed's mean point
    const ks = R.KS, Ts = ks.map(k => r.horizons[k]);
    const mk = ks.reduce((a, b) => a + b) / ks.length, mT = Ts.reduce((a, b) => a + b) / Ts.length;
    ctx.strokeStyle = c; ctx.globalAlpha = 0.45; ctx.setLineDash([4, 4]); ctx.beginPath();
    ctx.moveTo(X(0), Y(mT + r.stepsPerBitPredicted * (0 - mk))); ctx.lineTo(X(24), Y(mT + r.stepsPerBitPredicted * (24 - mk))); ctx.stroke();
    ctx.setLineDash([]); ctx.globalAlpha = 1; ctx.fillStyle = c;
    ks.forEach((k, j) => { ctx.beginPath(); ctx.arc(X(k) + (i - 2) * 3, Y(Ts[j]), 3, 0, Math.PI * 2); ctx.fill(); });
    // floating point, drawn at the right edge
    ctx.fillRect(w - pad.r + 14 + i * 4, Y(r.floatHorizon) - 1, 10, 2.5);
  });
  ctx.fillStyle = css('--dim'); ctx.fillText('float', w - pad.r + 16, pad.t + 8);
  const tbl = R.rows.map((r, i) => `<tr><td><span style="display:inline-block;width:.7em;height:.7em;border-radius:50%;background:${cols[i % cols.length]};margin-right:.35em"></span>${r.seed}</td><td>${fmt(r.rateBitsPerStep * 1000, 1)}</td><td>${fmt(-r.stepsPerBitPredicted, 0)}</td><td>${fmt(-r.stepsPerBitMeasured, 0)}</td><td class="${r.pass ? 'ok' : 'bad'}">${fmt(r.ratio, 2)} ${r.pass ? 'held' : 'missed'}</td><td>${fmt(r.horizons[0])}</td><td class="${r.floatLaterThanK0 ? 'ok' : 'bad'}">${fmt(r.floatHorizon)}</td></tr>`).join('');
  $('h-table').innerHTML = `<thead><tr><th>seed</th><th>bits gained per 1,000 steps</th><th>predicted steps lost per doubling</th><th>measured</th><th>ratio</th><th>horizon, 1-step nudge</th><th>horizon, float</th></tr></thead><tbody>${tbl}</tbody>`;
}

// ── 4. Kelvin's sentence, tested ──────────────────────────────────────────────────────────────
async function kelvinTable() {
  const K = await (await fetch('./data/kelvin.json')).json();
  const mean = (a) => a.reduce((x, y) => x + y, 0) / a.length;
  const rows = K.NS.map((N, i) => {
    const teq = mean(K.sizes[i].TeqColl);
    const cells = (d) => K.cells.filter(c => c.delta === d);
    const pk = (d) => mean(cells(d).map(c => c.peak[i]));
    const dd = (d) => mean(cells(d).map(c => c.Dcoll[i]));
    return `<tr><td>${fmt(N)}</td><td>${fmt(teq, 1)}</td>${K.DELTAS.map(d => `<td>${fmt(pk(d) * 100, 1)}% <span class="small">at ${fmt(dd(d), 1)}</span></td>`).join('')}</tr>`;
  }).join('');
  $('k-table').innerHTML = `<thead><tr><th>disks</th><th>collisions to equalise</th>${K.DELTAS.map(d => `<th>every disk off by up to 2<sup>−${d}</sup> of its width: best share regained, and when (collisions)</th>`).join('')}</tr></thead><tbody>${rows}</tbody>`;
}

// ── wiring ───────────────────────────────────────────────────────────────────────────────────
resetBox(); tbLabel();
kelvinTable().catch(e => { $('k-table').innerHTML = `<caption>could not load data/kelvin.json: ${e.message}</caption>`; });
horizonChart().catch(e => { $('h-table').innerHTML = `<caption>could not load data/results.json: ${e.message}</caption>`; });
if (!reduce) setPlaying(true);
let rt; addEventListener('resize', () => { clearTimeout(rt); rt = setTimeout(() => { renderBox(); horizonChart(); }, 150); });
