// Black Hole Research Lab — editable scene source (scene/lab_app.js).
// Rebuild the single-file HTML with:  python code/s13_build_lab.py
// Everything shown is read from the embedded JSON (#lab-data), which the build script fills from results/*.
const D = JSON.parse(document.getElementById('lab-data').textContent);
const THREE = window.THREE;
const K = D.constants;
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s).replace(/[&<>]/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[ch]));
const fmt = (v, n = 4) => (v === null || v === undefined || v === '' || Number.isNaN(+v)) ? '—' : (+v).toFixed(n);
const sci = (v, n = 2) => (+v).toExponential(n);

// ------------------------------------------------------------------ physics (pure functions; tested in scene/test_lab.mjs)
const Phys = {
  twoTerm: (c) => c / K.LV + K.Aopt * Math.cbrt(c),
  ahtLog: (c) => c / 9.08 + 0.439 * Math.log(c) - 0.896,
  lambdaFromSlit: (s) => 1 / (1 / 12 + s * s / 3),
  interp(rows, xk, yk, x) {
    if (x <= rows[0][xk]) return rows[0][yk];
    for (let i = 1; i < rows.length; i++) {
      if (x <= rows[i][xk]) { const a = rows[i - 1], b = rows[i]; return a[yk] + (b[yk] - a[yk]) * (x - a[xk]) / (b[xk] - a[xk]); }
    }
    return rows[rows.length - 1][yk];
  },
  // [HP] eq. (V): exact measure potential on the restricted domain 0 <= u < 1
  V: (u) => u <= 0.5 ? u * u : 0.25 - 0.5 * Math.log(2 * (1 - u)),
  dV: (u) => u <= 0.5 ? 2 * u : 0.5 / (1 - u),
  S(u, m2, b) { return Phys.V(u) - u * u + m2 * u * u + b * u * u * u * u; },
  dS(u, m2, b) { return Phys.dV(u) - 2 * u + 2 * m2 * u + 4 * b * u * u * u; },
  bisect(f, a, b, n = 60) { let fa = f(a); for (let i = 0; i < n; i++) { const m = 0.5 * (a + b), fm = f(m); if ((fa > 0) === (fm > 0)) { a = m; fa = fm; } else b = m; } return 0.5 * (a + b); },
  saddles(m2, b) {
    const out = []; const N = 4000; let u0 = 1e-6, f0 = Phys.dS(u0, m2, b);
    for (let i = 1; i <= N; i++) {
      const u1 = 1e-6 + (0.9999 - 1e-6) * i / N, f1 = Phys.dS(u1, m2, b);
      if ((f0 > 0) !== (f1 > 0)) { const r = Phys.bisect((u) => Phys.dS(u, m2, b), u0, u1); out.push({ u: r, S: Phys.S(r, m2, b), kind: f0 < 0 ? 'min' : 'max' }); }
      u0 = u1; f0 = f1;
    }
    return out;
  },
  thresholds(b) { // exact m2_min (saddle-node) and m2_c (degeneracy) for b < 0
    const m2of = (u) => (2 * u - Phys.dV(u) - 4 * b * u * u * u) / (2 * u);
    let best = 0.5, bv = -1e9;
    for (let i = 0; i <= 20000; i++) { const u = 0.5 + 0.4995 * i / 20000, v = m2of(u); if (v > bv) { bv = v; best = u; } }
    const umin = (m2) => Phys.bisect((u) => Phys.dS(u, m2, b), best, 1 - 1e-12);
    const m2c = Phys.bisect((m2) => Phys.S(umin(m2), m2, b), 1e-9 * (-b), bv * (1 - 1e-9));
    return { m2min: bv, usn: best, m2c, uc: umin(m2c) };
  },
  bOfQ4: (q4) => -4 * K.beta0 * K.beta0 * K.I + K.beta0 * q4,
  phase(m2, b) {
    if (b >= 0) return m2 >= 0 ? 'confined (u = 0); transition will be continuous' : (m2 > -b / 2 ? 'deconfined, ungapped (second-order branch)' : 'deconfined, gapped (beyond the Gross–Witten–Wadia point)');
    const t = Phys.thresholds(b);
    if (m2 > t.m2min) return 'T < T_min: only the confined saddle u = 0';
    if (m2 > t.m2c) return 'T_min < T < T_c: confined dominates; deconfined saddle metastable';
    if (m2 > 0) return 'T_c < T < T_H: deconfined dominates; confined metastable';
    return 'T > T_H: confined saddle unstable; deconfined only';
  },
};

// ------------------------------------------------------------------ stations
const ST = [
  { id: 'sources', n: 1, title: 'Source papers', color: 0x60a5fa, pos: [-11, 6], key: () => 'TeX + PDF, SHA-256 verified' },
  { id: 'code', n: 2, title: 'Code & notebook output', color: 0x34d399, pos: [-8.5, -3], key: () => `${D.checks.pass}/${D.checks.n} checks · ${D.validation.pass}/${D.validation.n} cross-checks` },
  { id: 'modular', n: 3, title: 'Modular bound', color: 0xfbbf24, pos: [-3.6, -9], key: () => `Λ_V = ${fmt(K.LV, 5)}` },
  { id: 'hp', n: 4, title: 'Hawking–Page competition', color: 0xf472b6, pos: [3.6, -9], key: () => `b = ${fmt(K.b, 2)} g⁴` },
  { id: 'ledger', n: 5, title: 'Evidence ledger', color: 0xa78bfa, pos: [8.5, -3], key: () => `${D.ledger.length} claims` },
  { id: 'timeline', n: 6, title: 'Research timeline', color: 0xfb923c, pos: [11, 6], key: () => `${D.timeline.length} real events` },
];
const state = { x: 0, z: 17, yaw: 0, pitch: -0.06, keys: {}, mode: '3d', open: null, fly: null, near: null, t: 0, s: K.xs, m2: 0.045, absb: 0.1, bpos: false, tl: 0, playing: false, drag: null, pad: {} };
const lab = { Phys, state, ST, D };
window.__lab = lab;

// ------------------------------------------------------------------ small 2D chart helper (white panel charts)
function chart(cv, o) {
  if (!cv || !cv.getContext) return;
  const g = cv.getContext('2d'); if (!g) return;
  const dpr = Math.min(window.devicePixelRatio || 1, 2), W = cv.clientWidth || 420, H = cv.clientHeight || 230;
  cv.width = W * dpr; cv.height = H * dpr; g.setTransform(dpr, 0, 0, dpr, 0, 0);
  g.fillStyle = '#fff'; g.fillRect(0, 0, W, H);
  const L = 52, R = 10, T = 22, B = 34, tx = o.xlog ? Math.log10 : (v) => v;
  const X = (v) => L + (tx(v) - tx(o.xlim[0])) / (tx(o.xlim[1]) - tx(o.xlim[0])) * (W - L - R);
  const Y = (v) => H - B - (v - o.ylim[0]) / (o.ylim[1] - o.ylim[0]) * (H - T - B);
  g.strokeStyle = '#9ca3af'; g.lineWidth = 1; g.strokeRect(L, T, W - L - R, H - T - B);
  g.fillStyle = '#111'; g.font = '11px system-ui,sans-serif'; g.textAlign = 'center';
  (o.xticks || []).forEach((v) => { const x = X(v); g.fillText(String(v), x, H - B + 13); g.beginPath(); g.moveTo(x, H - B); g.lineTo(x, H - B + 3); g.stroke(); });
  g.textAlign = 'right';
  (o.yticks || []).forEach((v) => { const y = Y(v); g.fillText(String(v), L - 5, y + 4); g.strokeStyle = '#e5e7eb'; g.beginPath(); g.moveTo(L, y); g.lineTo(W - R, y); g.stroke(); g.strokeStyle = '#9ca3af'; });
  g.textAlign = 'center'; g.fillText(o.xlabel || '', L + (W - L - R) / 2, H - 6);
  g.save(); g.translate(12, T + (H - T - B) / 2); g.rotate(-Math.PI / 2); g.fillText(o.ylabel || '', 0, 0); g.restore();
  g.textAlign = 'left'; g.font = 'bold 11.5px system-ui,sans-serif'; g.fillText(o.title || '', L, 14); g.font = '11px system-ui,sans-serif';
  g.save(); g.beginPath(); g.rect(L, T, W - L - R, H - T - B); g.clip();
  (o.series || []).forEach((s) => {
    g.strokeStyle = s.color; g.fillStyle = s.color; g.lineWidth = s.width || 1.6; g.setLineDash(s.dash || []);
    if (s.mode === 'pts') { s.x.forEach((xv, i) => { g.beginPath(); g.arc(X(xv), Y(s.y[i]), s.r || 3, 0, 6.3); s.open ? g.stroke() : g.fill(); }); }
    else { g.beginPath(); s.x.forEach((xv, i) => { const px = X(xv), py = Y(s.y[i]); i ? g.lineTo(px, py) : g.moveTo(px, py); }); g.stroke(); }
    g.setLineDash([]);
  });
  (o.vlines || []).forEach((v) => { g.strokeStyle = v.color || '#6b7280'; g.setLineDash([4, 3]); g.beginPath(); g.moveTo(X(v.x), T); g.lineTo(X(v.x), H - B); g.stroke(); g.setLineDash([]); });
  g.restore();
  let ly = T + 12; (o.series || []).forEach((s) => { if (!s.label) return; g.fillStyle = s.color; g.fillRect(o.legendX || L + 8, ly - 7, 10, 3); g.fillStyle = '#111'; g.fillText(s.label, (o.legendX || L + 8) + 14, ly - 2); ly += 13; });
}
const lin = (a, b, n) => Array.from({ length: n }, (_, i) => a + (b - a) * i / (n - 1));

// ------------------------------------------------------------------ panels
function readout(items) { return '<div class="read">' + items.map(([k, v]) => `<div><small>${k}</small><b>${v}</b></div>`).join('') + '</div>'; }
function viewer(id, files, first) {
  const names = Object.keys(files);
  return `<select id="${id}-sel">${names.map((n) => `<option${n === first ? ' selected' : ''}>${esc(n)}</option>`).join('')}</select><pre id="${id}-pre">${esc(files[first || names[0]] || '')}</pre>`;
}
function bindViewer(id, files) { const s = $(id + '-sel'); if (s) s.addEventListener('change', () => { $(id + '-pre').textContent = files[s.value] || ''; }); }

const PANELS = {
  sources() {
    const t2 = D.table2.map((r) => `<tr><td>${r.c}</td><td>${r.pc}</td><td>${r.D}</td><td>${sci(r.sig, 1)}</td><td>${r.ratio}</td><td>${fmt(r.rr, 6)}</td><td class="l">${r.impl}</td></tr>`).join('');
    const ser = D.series.map((r) => `<tr><td class="l">${r.s === 'a' ? 'a (tree)' : 'b (loop)'}</td><td>${r.n}</td><td>${esc(r.coeff)}</td><td>${r.exact ? 'exact' : 'float'}</td><td>${fmt(r.term, 5)}</td><td>${fmt(r.partial, 4)}</td></tr>`).join('');
    return `<p>Two papers, read from the local TeX and PDF copies; hashes match the manifests (${D.sources.manifest_ok ? 'all four files' : 'MISMATCH'}).</p>
    <table><tr><th class="l">ID</th><th class="l">Title</th><th class="l">Record</th><th class="l">SHA-256 (TeX)</th></tr>
    <tr><td class="l">[B]</td><td class="l">The Spinless Modular Bootstrap at Large Central Charge</td><td class="l">Hexagon 2611.00174v1</td><td class="l">${D.sources.sha.bootstrap.slice(0, 16)}…</td></tr>
    <tr><td class="l">[HP]</td><td class="l">The Hawking–Page Transition at Weak Coupling</td><td class="l">Hexagon 2611.00175v1</td><td class="l">${D.sources.sha.hp.slice(0, 16)}…</td></tr></table>
    <p class="note">Offline links (work when this file sits in the research package): <a href="sources/bootstrap.pdf">bootstrap.pdf</a> · <a href="sources/hawking_page.pdf">hawking_page.pdf</a> · <a href="sources.md">sources.md</a>. The TeX excerpts below are embedded, so they can be read in a sandboxed preview.</p>
    <h4>TeX source (embedded excerpts with original line numbers)</h4>${viewer('tex', D.tex, Object.keys(D.tex)[0])}
    <h4>[B] Table 2 as parsed from TeX — published inputs (24 rows)</h4>
    <table><tr><th>c</th><th>P<sub>max</sub>/c</th><th>Δ₁<sup>(∞)</sup></th><th>σ</th><th>c/Δ printed</th><th>recomputed</th><th class="l">impl.</th></tr>${t2}</table>
    <h4>[HP] Appendix B series at y<sub>H</sub> = 2 − √3 (coefficients are the paper's)</h4>
    <table><tr><th class="l">series</th><th>n</th><th>coefficient</th><th></th><th>term (recomputed)</th><th>partial sum</th></tr>${ser}</table>
    <h4>Historical comparison (values as quoted in the sources)</h4>
    <table><tr><th class="l">entry</th><th>Λ</th><th class="l">status</th><th class="l">quoted in</th></tr>${D.ladder.map((r) => `<tr><td class="l">${esc(r.entry)}</td><td>${fmt(r.Lambda, 4)}</td><td class="l">${esc(r.status)}</td><td class="l">${esc(r.source)}</td></tr>`).join('')}</table>`;
  },
  code() {
    const figs = Object.keys(D.figs);
    return `${readout([['paper-referenced checks', `${D.checks.pass}/${D.checks.n}`], ['cross-algorithm comparisons', `${D.validation.pass}/${D.validation.n}`], ['fresh functionals', D.meta.n_functionals], ['figures', figs.length]])}
    <p class="note">Real output of this session. The notebook was executed by an in-process executor because the sandbox forbids the local sockets a Jupyter kernel needs; see logs/s12_build_notebook.log.</p>
    <h4>Execution logs (verbatim)</h4>${viewer('log', D.logs, 's02_slope_endpoint.log')}
    <h4>Source code (verbatim)</h4>${viewer('src', D.code, 's02_slope_endpoint.py')}
    <h4>Checks by script</h4><table><tr><th class="l">script</th><th>passed</th></tr>${D.checks.by.map((r) => `<tr><td class="l">${esc(r[0])}</td><td>${r[1]}/${r[2]}</td></tr>`).join('')}</table>
    <h4>Figures produced by the notebook run</h4><div class="tabs">${figs.map((f, i) => `<button data-fig="${f}" class="${i ? '' : 'on'}">${i + 1}</button>`).join('')}</div>
    <img id="fig-img" alt="figure" src="${D.figs[figs[0]]}"><p id="fig-cap" class="note">${esc(D.captions[figs[0]] || '')}</p>`;
  },
  modular() {
    return `<p>Best large-c slope of the spinless bootstrap: Δ₁ ≤ c/Λ_V + o(c), 1/Λ_V = 1/12 + (x₁*)²/3, sinh πx₁* = 1 ([B] Thm 1). The surface in the room is the finite-difference solution of the slit-strip Dirichlet problem computed in this session.</p>
    <label>Slit position s = <span id="mb-sv"></span></label><input type="range" id="mb-s" min="0.2" max="0.36" step="0.0005" value="${state.s}">
    <div id="mb-read"></div><canvas class="chart" id="mb-c1"></canvas>
    <p class="note">γ_tip(s) is the square-root coefficient of U_s + L at the slit tip, from the Poisson integral derived in this reproduction (line) and finite differences (dots). It vanishes at s = arcsinh(1)/π (agreement ${sci(K.tangency_diff, 1)}). For s &lt; x₁* the method proves the weaker slope shown; for s &gt; x₁* the majorant rises above the Cardy line and proves nothing near the tip.</p>
    <h4>Finite-c drift of [B] Table 2</h4>
    <label>Central charge c = <span id="mb-cv"></span></label><input type="range" id="mb-c" min="0" max="1" step="0.001" value="0.6">
    <div class="tabs"><button id="mb-f1" class="on">c/Δ₁ vs c</button><button id="mb-f2">remainder</button><button id="mb-f3">fit windows</button><button id="mb-f4">order P</button></div>
    <div id="mb-read2"></div><canvas class="chart" id="mb-c2"></canvas>
    <p class="note" id="mb-note"></p>`;
  },
  hp() {
    return `<p>Polyakov-loop potential on the paper's restricted domain 0 ≤ u &lt; 1 with the exact gapped branch ([HP] eqs. V, Sfull): S/N² = V(u) − u² + m₁²u² + b u⁴. Lowering m₁² is heating. |b| is exaggerated so the structure is visible (at λ = 1 the paper's value is |b| = ${sci(K.absb_lambda1, 2)}).</p>
    <label>m₁² = <span id="hp-mv"></span> (temperature)</label><input type="range" id="hp-m" min="-0.04" max="0.09" step="0.0005" value="${state.m2}">
    <label>|b| = <span id="hp-bv"></span></label><input type="range" id="hp-b" min="0.005" max="0.3" step="0.005" value="${state.absb}">
    <div class="tabs"><button id="hp-neg" class="on">b &lt; 0 (paper's sign)</button><button id="hp-pos">b &gt; 0 (counterfactual)</button><button id="hp-tc">jump to T_c</button></div>
    <div id="hp-read"></div><canvas class="chart" id="hp-c1"></canvas>
    <p class="note">Solid: exact restricted-domain potential. Dashed: quartic truncation without the gapped branch — unbounded below for b &lt; 0, which is why a truncated or unrestricted picture is misleading.</p>
    <h4>Sign margin of the quartic coefficient</h4>
    <label>two-loop coefficient q₄(x_H) = <span id="hp-qv"></span></label><input type="range" id="hp-q" min="-6" max="15" step="0.01" value="${K.q4}">
    <div id="hp-read2"></div>
    <h4>Three temperatures (exact inversion through two loops, this work)</h4>
    <table><tr><th>λ</th><th>T_min</th><th>T_c</th><th>T_H</th><th>(T_H−T_c)/T_H</th><th>leading</th><th>jump u_c</th></tr>${D.temps.map((r) => `<tr><td>${r.lambda}</td><td>${fmt(r.Tmin, 7)}</td><td>${fmt(r.Tc, 7)}</td><td>${fmt(r.TH, 7)}</td><td>${sci(r.wc)}</td><td>${sci(r.wl)}</td><td>${fmt(r.uc, 4)}</td></tr>`).join('')}</table>
    <p class="note">Conditional statement: the transition is first order <i>if</i> b &lt; 0. b is assembled from the paper's microscopic inputs c₃ = 0.16821, Q₄ = 2.1222 and its two series; those were not recomputed here. Free Hagedorn point from our mode sum: x_H = 7 − 4√3, β₀ = ${fmt(K.beta0, 7)}, T_H⁰ = ${fmt(1 / K.beta0, 6)}.</p>`;
  },
  ledger() {
    const cnt = {}; D.ledger.forEach((x) => { cnt[x.cls] = (cnt[x.cls] || 0) + 1; });
    return `<p>${D.ledger.length} claims with paper location, paper status, what was done here and the verdict. Machine-readable version: <a href="claim_ledger.json">claim_ledger.json</a>.</p>
    ${readout([['independently reproduced', cnt.ok || 0], ['arithmetic from paper inputs', cnt.ar || 0], ['consistent / supported', cnt.co || 0], ['not verified here', cnt.no || 0]])}
    <div class="tabs" id="lg-tabs"><button data-f="all" class="on">all</button><button data-f="B">[B]</button><button data-f="H">[HP]</button><button data-f="ok">reproduced</button><button data-f="ar">arithmetic</button><button data-f="co">consistent</button><button data-f="no">not verified</button></div>
    <div id="lg-list"></div>
    <h4>What was not done</h4><p class="note">No certified two-sided bootstrap proof (the proofs of [B] Thm 3–5 were read, not re-proved; no interval arithmetic); the high-order runs behind Table 2 were not repeated; no three-loop computation of the [HP] coefficients; no Lean rerun — neither source ships a formal development and no Lean toolchain exists in this runtime.</p>`;
  },
  timeline() {
    return `<p>The ${D.timeline.length} events below were appended by the scripts while they ran (UTC wall-clock). Nothing is simulated; failures and changes of plan are included.</p>
    <div class="tabs"><button id="tl-play">▶ replay</button><button id="tl-prev">◀</button><button id="tl-next">▶</button><span id="tl-pos" style="align-self:center"></span></div>
    <input type="range" id="tl-s" min="0" max="${D.timeline.length - 1}" step="1" value="${state.tl}">
    <div id="tl-cur"></div><div id="tl-list"></div>`;
  },
};

const VCLS = { ok: 'v-ok', ar: 'v-ar', co: 'v-co', no: 'v-no' };
function ledgerList(f) {
  const rows = D.ledger.filter((x) => f === 'all' || x.id[0] === f || x.cls === f);
  $('lg-list').innerHTML = rows.map((x) => `<details class="claim"><summary>${x.id} · ${esc(x.location)} <span class="pill ${VCLS[x.cls]}">${esc(x.verdict)}</span></summary>
    <p><b>Claim.</b> ${esc(x.claim)}</p><p><b>Paper status.</b> ${esc(x.paper_status)}</p><p><b>Done here.</b> ${esc(x.what_was_done)}${x.second_method ? ' <b>Second method.</b> ' + esc(x.second_method) : ''}</p>
    <p><b>Result.</b> ${esc(x.quantitative_result)}</p>${x.scope_limit ? `<p class="note"><b>Scope limit.</b> ${esc(x.scope_limit)}</p>` : ''}<p class="note">Evidence: ${x.evidence.map(esc).join(', ')}</p></details>`).join('');
}

function updModular(which) {
  const s = state.s, g = Phys.interp(D.gamma, 's', 'g', s), u0 = Phys.interp(D.gamma, 's', 'u0', s);
  $('mb-sv').textContent = s.toFixed(4);
  const usable = s <= K.xs + 1e-9;
  $('mb-read').innerHTML = readout([['tip coefficient γ_tip(s)', (g >= 0 ? '+' : '') + g.toFixed(4)], ['U_s(0)', u0.toFixed(5)], ['slope if usable', usable ? 'Λ ≤ ' + Phys.lambdaFromSlit(s).toFixed(3) : 'no bound (s > x₁*)'], ['x₁* = arcsinh(1)/π', K.xs.toFixed(7)]]);
  chart($('mb-c1'), { title: 'Tip coefficient versus slit position', xlabel: 'slit position s', ylabel: 'γ_tip', xlim: [0.2, 0.36], ylim: [-0.34, 0.34], xticks: [0.2, 0.24, 0.28, 0.32, 0.36], yticks: [-0.3, -0.15, 0, 0.15, 0.3],
    series: [{ x: D.gamma.map((r) => r.s), y: D.gamma.map((r) => r.g), color: '#1d4ed8', label: 'Poisson integral (this work)' }, { x: D.fdgen.map((r) => r.s), y: D.fdgen.map((r) => r.g), color: '#d97706', mode: 'pts', label: 'finite differences' },
      { x: [s], y: [g], color: '#dc2626', mode: 'pts', r: 5, label: 'selected s' }], vlines: [{ x: K.xs }] });
  if (lab.setSlit) lab.setSlit(s);
  // drift part
  const cmin = Math.log(24), cmax = Math.log(2048), c = Math.exp(cmin + (cmax - cmin) * (+$('mb-c').value));
  let near = D.table2[0]; D.table2.forEach((r) => { if (Math.abs(Math.log(r.c) - Math.log(c)) < Math.abs(Math.log(near.c) - Math.log(c))) near = r; });
  $('mb-cv').textContent = c.toFixed(0);
  const tt = Phys.twoTerm(near.c);
  $('mb-read2').innerHTML = readout([['nearest Table 2 row', 'c = ' + near.c + ' (impl. ' + near.impl + ')'], ['published Δ₁(∞) ± σ', near.D + ' ± ' + sci(near.sig, 1)], ['c/Δ₁', fmt(near.rr, 5)], ['two-term law (Conj. 1a)', fmt(tt, 4)],
    ['remainder', fmt(near.D - tt, 4)], ['AHT log fit − data', fmt(Phys.ahtLog(near.c) - near.D, 4)], ['Λ_V − c/Δ₁', fmt(K.LV - near.rr, 4)], ['refit Λ (this work)', fmt(K.Lfit, 4)]]);
  const view = which || state.mbView || 'f1'; state.mbView = view;
  ['f1', 'f2', 'f3', 'f4'].forEach((k) => $('mb-' + k).classList.toggle('on', k === view));
  const cs = lin(Math.log(24), Math.log(2048), 80).map(Math.exp), cv = $('mb-c2');
  if (view === 'f1') {
    chart(cv, { title: 'Ratio c/Δ₁: published inputs, fresh finite-P output, two laws', xlabel: 'central charge c (log scale)', ylabel: 'c/Δ₁', xlog: true, xlim: [20, 2400], ylim: [6.6, 9.3], xticks: [24, 64, 256, 1024, 2048], yticks: [7, 7.5, 8, 8.5, 9],
      series: [{ x: cs, y: cs.map((v) => v / Phys.twoTerm(v)), color: '#1d4ed8', label: 'c/Λ_V + A_opt c^(1/3) (no fit)' }, { x: cs, y: cs.map((v) => v / Phys.ahtLog(v)), color: '#dc2626', dash: [5, 3], label: 'AHT log fit (as quoted in [B])' },
        { x: D.table2.map((r) => r.c), y: D.table2.map((r) => r.rr), color: '#111', mode: 'pts', label: '[B] Table 2 (input)' }, { x: D.freshBest.map((r) => r.c), y: D.freshBest.map((r) => r.ratio), color: '#059669', mode: 'pts', r: 4.5, label: 'fresh, finite P (this work)' },
        { x: [near.c], y: [near.rr], color: '#f59e0b', mode: 'pts', r: 6, open: true }], vlines: [{ x: near.c }] });
    $('mb-note').textContent = `Published points are inputs (not recomputed). Green points are this session's functionals at the largest order reached (P ≤ 64 for c ≥ 24): finite-order bounds, hence below the published P→∞ ratios.`;
  } else if (view === 'f2') {
    chart(cv, { title: 'Remainder Δ₁ − c/Λ_V − A_opt c^(1/3)', xlabel: 'central charge c (log scale)', ylabel: 'remainder', xlog: true, xlim: [20, 2400], ylim: [-0.3, 0.1], xticks: [24, 64, 256, 1024, 2048], yticks: [-0.3, -0.2, -0.1, 0, 0.1],
      series: [{ x: cs, y: cs.map(() => 0), color: '#1d4ed8', label: 'two-term law' }, { x: cs, y: cs.map((v) => Phys.ahtLog(v) - Phys.twoTerm(v)), color: '#dc2626', dash: [5, 3], label: 'AHT log fit' },
        { x: D.table2.map((r) => r.c), y: D.table2.map((r) => r.D - Phys.twoTerm(r.c)), color: '#111', mode: 'pts', label: '[B] Table 2' }], vlines: [{ x: near.c }] });
    $('mb-note').textContent = `The remainder is O(1) but still drifting (≈ ${fmt(K.r0, 3)} + ${fmt(K.r1, 2)} c^(-1/3)); A_opt = 0.27666 is a conjecture supported, not established, by these data.`;
  } else if (view === 'f3') {
    const xi = D.drift.map((_, i) => i);
    chart(cv, { title: 'Fitted slope on five windows of c', xlabel: 'window index: ' + D.drift.map((r, i) => `${i}=[${r.lo},${r.hi}]`).join(' '), ylabel: 'fitted Λ', xlim: [-0.4, 4.4], ylim: [8.98, 9.16], xticks: [0, 1, 2, 3, 4], yticks: [9, 9.04, 9.08, 9.12, 9.16],
      series: [{ x: xi, y: D.drift.map((r) => r.Llog), color: '#dc2626', label: 'c/Λ + γ log c + const' }, { x: xi, y: D.drift.map((r) => r.Lcube), color: '#1d4ed8', label: 'c/Λ + A c^(1/3) + const' },
        { x: [-0.4, 4.4], y: [K.LV, K.LV], color: '#111', dash: [2, 3], label: 'Λ_V' }] });
    $('mb-note').textContent = `A logarithmic form drifts from ${fmt(D.drift[0].Llog, 3)} to ${fmt(D.drift[3].Llog, 3)} as the window moves up; the c^(1/3) form moves from ${fmt(D.drift[0].Lcube, 3)} to ${fmt(D.drift[3].Lcube, 3)}.`;
  } else {
    const cc = [4, 12, 24, 64], col = { 4: '#1d4ed8', 12: '#059669', 24: '#d97706', 64: '#9333ea' };
    chart(cv, { title: 'Fresh order-P bounds: c/Δ₁(P) for four central charges', xlabel: 'order P', ylabel: 'c/Δ₁(P)', xlim: [0, 84], ylim: [3.7, 8.1], xticks: [0, 20, 40, 60, 80], yticks: [4, 5, 6, 7, 8],
      series: cc.map((c0) => { const rr = D.fresh.filter((r) => r.c === c0); return { x: rr.map((r) => r.P), y: rr.map((r) => r.ratio), color: col[c0], label: 'c = ' + c0 }; }), legendX: 250 });
    $('mb-note').textContent = `${D.meta.n_functionals} fresh extremal functionals, all verified nonnegative on [t₁, ∞) with g_vac = 0 and negative Cardy-mass fraction exactly 1/2. Exact optima recovered from above: Δ₁ − 1 = ${sci(K.ex4, 1)} (c = 4), Δ₁ − 2 = ${sci(K.ex12, 1)} (c = 12).`;
  }
}

function updHP() {
  const b = (state.bpos ? 1 : -1) * state.absb, m2 = state.m2;
  $('hp-mv').textContent = m2.toFixed(4); $('hp-bv').textContent = state.absb.toFixed(3);
  $('hp-neg').classList.toggle('on', !state.bpos); $('hp-pos').classList.toggle('on', state.bpos);
  const sd = Phys.saddles(m2, b), mins = sd.filter((x) => x.kind === 'min'), maxs = sd.filter((x) => x.kind === 'max');
  let gm = { u: 0, S: 0 }; mins.forEach((x) => { if (x.S < gm.S) gm = x; });
  const items = [['phase', Phys.phase(m2, b)], ['global minimum u', gm.u.toFixed(4)], ['S/N² there', gm.S.toExponential(2)], ['unstable saddle u_s', maxs.length ? maxs[0].u.toFixed(4) : '—']];
  if (!state.bpos) { const t = Phys.thresholds(b); items.push(['m² at T_min (exact | leading)', t.m2min.toFixed(5) + ' | ' + (state.absb / 2).toFixed(5)], ['m² at T_c (exact | leading)', t.m2c.toFixed(5) + ' | ' + (state.absb / 4).toFixed(5)], ['jump at T_c: u_c', t.uc.toFixed(4)], ['latent heat ≈ (3/2)u_c² N²/R', (1.5 * t.uc * t.uc).toFixed(4)]); }
  $('hp-read').innerHTML = readout(items);
  const us = lin(0, 0.84, 170), Sv = us.map((u) => 100 * Phys.S(u, m2, b)), Tr = us.map((u) => 100 * (m2 * u * u + b * u * u * u * u));
  const lo = Math.min(-0.6, Math.max(-3, Math.min(...Sv) * 1.3)), hi = Math.max(0.8, Math.min(3, Math.max(...Sv.slice(0, 110)) * 1.3));
  chart($('hp-c1'), { title: '10² × S(u)/N²', xlabel: 'Polyakov loop u = |u₁|', ylabel: '10² S/N²', xlim: [0, 0.84], ylim: [lo, hi], xticks: [0, 0.2, 0.4, 0.5, 0.6, 0.8], yticks: [Math.round(lo * 10) / 10, 0, Math.round(hi * 10) / 10],
    series: [{ x: us, y: Sv, color: '#be185d', label: 'exact restricted domain', width: 2 }, { x: us, y: Tr, color: '#6b7280', dash: [4, 3], label: 'quartic only (no gapped branch)' }, { x: [gm.u], y: [100 * gm.S], color: '#1d4ed8', mode: 'pts', r: 5, label: 'global minimum' }], vlines: [{ x: 0.5 }] });
  const q = +$('hp-q').value, bq = Phys.bOfQ4(q);
  $('hp-qv').textContent = q.toFixed(2);
  $('hp-read2').innerHTML = readout([['b / g⁴', bq.toFixed(3)], ['sign ⇒ order', bq < 0 ? 'b < 0 ⇒ first order' : 'b > 0 ⇒ continuous'], ['paper inputs', 'q₄ = ' + K.q4.toFixed(3) + ', b = ' + K.b.toFixed(2)], ['b = 0 at q₄', K.q4crit.toFixed(2)], ['margin from paper value', (K.q4crit - K.q4).toFixed(2)], ['re-summed here', 'q₄ = ' + K.q4here.toFixed(4)]]);
  if (lab.setHP) lab.setHP(m2, b, gm.u);
}

function updTimeline() {
  const i = state.tl, e = D.timeline[i];
  $('tl-pos').textContent = `${i + 1} / ${D.timeline.length}`; $('tl-s').value = i;
  $('tl-play').textContent = state.playing ? '❚❚ pause' : '▶ replay';
  $('tl-cur').innerHTML = `<div class="ev cur"><small>${esc(e.t)} · ${esc(e.kind)}</small><br><b>${esc(e.title)}</b><br>${esc(e.detail || '')}${e.outputs ? '<br><small>outputs: ' + e.outputs.slice(0, 6).map(esc).join(', ') + '</small>' : ''}</div>`;
  $('tl-list').innerHTML = D.timeline.map((x, k) => `<div class="ev${k === i ? ' cur' : ''}"><small>${esc(x.t.slice(11, 19))} · ${esc(x.kind)}</small> ${esc(x.title)}</div>`).join('');
  if (lab.setTimeline) lab.setTimeline(i);
}

function openPanel(id) {
  const st = ST.find((s) => s.id === id); if (!st) return;
  state.open = id; state.playing = false;
  $('panel-title').textContent = `${st.n} · ${st.title}`;
  $('panel-body').innerHTML = PANELS[id]();
  $('panel').classList.remove('closed');
  $('panel-body').scrollTop = 0;
  document.querySelectorAll('#stations button').forEach((b) => b.classList.toggle('on', b.dataset.st === id));
  const on = (el, ev, fn) => { const e = $(el); if (e) e.addEventListener(ev, fn); };
  if (id === 'sources') bindViewer('tex', D.tex);
  if (id === 'code') {
    bindViewer('log', D.logs); bindViewer('src', D.code);
    document.querySelectorAll('#panel-body [data-fig]').forEach((b) => b.addEventListener('click', () => { $('fig-img').src = D.figs[b.dataset.fig]; $('fig-cap').textContent = D.captions[b.dataset.fig] || ''; document.querySelectorAll('#panel-body [data-fig]').forEach((x) => x.classList.toggle('on', x === b)); }));
  }
  if (id === 'modular') {
    on('mb-s', 'input', (e) => { state.s = +e.target.value; updModular(); }); on('mb-c', 'input', () => updModular());
    ['f1', 'f2', 'f3', 'f4'].forEach((k) => on('mb-' + k, 'click', () => updModular(k))); updModular();
  }
  if (id === 'hp') {
    on('hp-m', 'input', (e) => { state.m2 = +e.target.value; updHP(); }); on('hp-b', 'input', (e) => { state.absb = +e.target.value; updHP(); }); on('hp-q', 'input', updHP);
    on('hp-neg', 'click', () => { state.bpos = false; updHP(); }); on('hp-pos', 'click', () => { state.bpos = true; updHP(); });
    on('hp-tc', 'click', () => { state.bpos = false; state.m2 = Phys.thresholds(-state.absb).m2c; $('hp-m').value = state.m2; updHP(); }); updHP();
  }
  if (id === 'ledger') { document.querySelectorAll('#lg-tabs button').forEach((b) => b.addEventListener('click', () => { document.querySelectorAll('#lg-tabs button').forEach((x) => x.classList.toggle('on', x === b)); ledgerList(b.dataset.f); })); ledgerList('all'); }
  if (id === 'timeline') {
    on('tl-s', 'input', (e) => { state.tl = +e.target.value; state.playing = false; updTimeline(); });
    on('tl-prev', 'click', () => { state.tl = Math.max(0, state.tl - 1); updTimeline(); }); on('tl-next', 'click', () => { state.tl = Math.min(D.timeline.length - 1, state.tl + 1); updTimeline(); });
    on('tl-play', 'click', () => { state.playing = !state.playing; if (state.playing && state.tl >= D.timeline.length - 1) state.tl = 0; state.tlClock = 0; updTimeline(); }); updTimeline();
  }
}
function closePanel() { state.open = null; state.playing = false; $('panel').classList.add('closed'); document.querySelectorAll('#stations button').forEach((b) => b.classList.remove('on')); }
function goTo(id, open = true) {
  const st = ST.find((s) => s.id === id); if (!st) return;
  const dx = 0 - st.pos[0], dz = 4 - st.pos[1], len = Math.hypot(dx, dz) || 1, back = 5.2;   // stand between the station and the room centre (0, 4)
  const tx = st.pos[0] + dx / len * back, tz = st.pos[1] + dz / len * back;
  state.fly = { x0: state.x, z0: state.z, yaw0: state.yaw, x1: tx, z1: tz, yaw1: Math.atan2(-(st.pos[0] - tx), -(st.pos[1] - tz)), t: 0 };
  if (open) openPanel(id);
}
lab.openPanel = openPanel; lab.closePanel = closePanel; lab.goTo = goTo;

// ------------------------------------------------------------------ 3D scene
function labelTexture(lines, color, w = 512, h = 256) {
  const cv = document.createElement('canvas'); cv.width = w; cv.height = h; const g = cv.getContext('2d');
  if (g) {
    g.fillStyle = 'rgba(8,12,28,0.92)'; g.fillRect(0, 0, w, h); g.strokeStyle = color; g.lineWidth = 8; g.strokeRect(4, 4, w - 8, h - 8);
    g.textAlign = 'center'; g.fillStyle = color; g.font = 'bold 44px system-ui,sans-serif'; g.fillText(lines[0], w / 2, 70);
    g.fillStyle = '#ffffff'; g.font = 'bold 38px system-ui,sans-serif'; g.fillText(lines[1] || '', w / 2, 132);
    g.fillStyle = '#dbe4ff'; g.font = '30px system-ui,sans-serif'; g.fillText(lines[2] || '', w / 2, 190); g.fillText(lines[3] || '', w / 2, 230);
  }
  const t = new THREE.CanvasTexture(cv); t.colorSpace = THREE.SRGBColorSpace; return t;
}
function build3D() {
  const scene = new THREE.Scene(); scene.background = new THREE.Color(0x0c1226); scene.fog = new THREE.Fog(0x0c1226, 30, 70);
  const hex = (c) => '#' + c.toString(16).padStart(6, '0');
  scene.add(new THREE.HemisphereLight(0xdfe8ff, 0x20263c, 1.25));
  const sun = new THREE.DirectionalLight(0xffffff, 1.6); sun.position.set(6, 14, 10); scene.add(sun);
  const floor = new THREE.Mesh(new THREE.CircleGeometry(34, 72), new THREE.MeshStandardMaterial({ color: 0x1a2342, roughness: 0.9, metalness: 0.05 })); floor.rotation.x = -Math.PI / 2; scene.add(floor);
  const grid = new THREE.GridHelper(68, 68, 0x5b6fb5, 0x2c3a6e); grid.position.y = 0.01; scene.add(grid);
  // centrepiece: black hole with photon ring and accretion disc (decorative), plus a data headline sprite
  const bh = new THREE.Group(); bh.position.set(0, 4.2, -2.5);
  bh.add(new THREE.Mesh(new THREE.SphereGeometry(1.5, 48, 32), new THREE.MeshBasicMaterial({ color: 0x000000 })));
  const ring = new THREE.Mesh(new THREE.TorusGeometry(1.62, 0.05, 12, 96), new THREE.MeshBasicMaterial({ color: 0xffe8a3 })); bh.add(ring);
  const disc = new THREE.Mesh(new THREE.RingGeometry(2.0, 4.2, 96, 1), new THREE.MeshBasicMaterial({ color: 0xff9d3c, side: THREE.DoubleSide, transparent: true, opacity: 0.75 })); disc.rotation.x = -1.25; bh.add(disc);
  const disc2 = new THREE.Mesh(new THREE.RingGeometry(4.2, 5.2, 96, 1), new THREE.MeshBasicMaterial({ color: 0xc2410c, side: THREE.DoubleSide, transparent: true, opacity: 0.45 })); disc2.rotation.x = -1.25; bh.add(disc2);
  scene.add(bh);
  const head = new THREE.Sprite(new THREE.SpriteMaterial({ map: labelTexture(['Independent reproduction', `Λ_V = ${fmt(K.LV, 5)}   b = ${fmt(K.b, 2)} g⁴`, `${D.checks.pass}/${D.checks.n} checks · ${D.validation.pass}/${D.validation.n} cross-checks`, 'walk to a station or press 1–6'], '#ffd166', 1024, 256) }));
  head.scale.set(11, 2.75, 1); head.position.set(0, 8.4, -2.5); scene.add(head);
  const picks = []; const groups = {};
  ST.forEach((st) => {
    const g = new THREE.Group(); g.position.set(st.pos[0], 0, st.pos[1]); g.rotation.y = Math.atan2(-st.pos[0], 4 - st.pos[1]); scene.add(g); groups[st.id] = g;
    const base = new THREE.Mesh(new THREE.CylinderGeometry(2.3, 2.5, 0.25, 40), new THREE.MeshStandardMaterial({ color: st.color, roughness: 0.5, emissive: st.color, emissiveIntensity: 0.25 })); base.position.y = 0.125; g.add(base);
    const lamp = new THREE.PointLight(st.color, 30, 14, 2); lamp.position.set(0, 3.2, 1.2); g.add(lamp);
    const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: labelTexture([`${st.n}`, st.title, st.key(), 'click · E · key ' + st.n], hex(st.color)) })); sp.scale.set(4.4, 2.2, 1); sp.position.set(0, 5.1, 0); g.add(sp);
    const pick = new THREE.Mesh(new THREE.CylinderGeometry(2.4, 2.4, 6.2, 16), new THREE.MeshBasicMaterial({ visible: false })); pick.position.y = 3.1; pick.userData.station = st.id; g.add(pick); picks.push(pick);
  });
  const std = (c, e = 0.15) => new THREE.MeshStandardMaterial({ color: c, roughness: 0.55, emissive: c, emissiveIntensity: e });
  // 1 sources: two slabs with the paper titles
  [['The Spinless Modular', 'Bootstrap at Large c', '2611.00174v1', '[B]'], ['The Hawking–Page', 'Transition at Weak Coupling', '2611.00175v1', '[HP]']].forEach((L, i) => {
    const m = new THREE.Mesh(new THREE.BoxGeometry(1.7, 2.3, 0.12), new THREE.MeshStandardMaterial({ map: labelTexture([L[3], L[0], L[1], L[2]], '#93c5fd'), roughness: 0.6 })); m.position.set(i ? 1.0 : -1.0, 1.75, 0); m.rotation.y = i ? -0.25 : 0.25; groups.sources.add(m);
  });
  // 2 code: terminal slab with real log lines
  const tcv = document.createElement('canvas'); tcv.width = 768; tcv.height = 512; const tg = tcv.getContext('2d');
  if (tg) { tg.fillStyle = '#04110b'; tg.fillRect(0, 0, 768, 512); tg.fillStyle = '#6ee7b7'; tg.font = '19px ui-monospace,Menlo,monospace'; D.terminal.slice(0, 22).forEach((l, i) => tg.fillText(l.slice(0, 66), 14, 30 + i * 22)); }
  const ttex = new THREE.CanvasTexture(tcv); ttex.colorSpace = THREE.SRGBColorSpace;
  const term = new THREE.Mesh(new THREE.BoxGeometry(3.4, 2.3, 0.14), new THREE.MeshBasicMaterial({ map: ttex })); term.position.set(0, 1.8, 0); groups.code.add(term);
  // 3 modular: the finite-difference potential surface U(x, y) with slits and a movable slit marker
  const F = D.field, nx = F.x.length, ny = F.y.length, sg = new THREE.BufferGeometry(), pos = [], col = [], idx = [], cA = new THREE.Color(0x3b1d8f), cB = new THREE.Color(0xfde047), cc = new THREE.Color();
  const SX = 1.9, SY = 2.6, SZ = 1.0;
  for (let i = 0; i < nx; i++) for (let j = 0; j < ny; j++) { const u = F.U[i * ny + j]; pos.push(F.x[i] * SX, 1.9 + u * SZ + 0.9, -F.y[j] * SY); cc.copy(cA).lerp(cB, Math.max(0, Math.min(1, 1 + u / 2.2))); col.push(cc.r, cc.g, cc.b); }
  for (let i = 0; i < nx - 1; i++) for (let j = 0; j < ny - 1; j++) { const a = i * ny + j, b = a + ny; idx.push(a, b, a + 1, b, b + 1, a + 1); }
  sg.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); sg.setAttribute('color', new THREE.Float32BufferAttribute(col, 3)); sg.setIndex(idx); sg.computeVertexNormals();
  groups.modular.add(new THREE.Mesh(sg, new THREE.MeshStandardMaterial({ vertexColors: true, side: THREE.DoubleSide, roughness: 0.7 })));
  const slitMat = new THREE.LineBasicMaterial({ color: 0xffffff });
  [1, -1].forEach((sgn) => { const pts = []; for (let k = 0; k <= 20; k++) { const x = sgn * (K.xs + (1.2 - K.xs) * k / 20); pts.push(new THREE.Vector3(x * SX, 2.8 - 2 * Math.PI / 3 * Math.abs(x) * SZ + 0.02, 0)); } groups.modular.add(new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), slitMat)); });
  const marker = new THREE.Mesh(new THREE.SphereGeometry(0.09, 16, 12), new THREE.MeshBasicMaterial({ color: 0xff3b3b })); groups.modular.add(marker);
  const marker2 = marker.clone(); groups.modular.add(marker2);
  lab.setSlit = (s) => { const y = 2.8 - 2 * Math.PI / 3 * s * SZ + 0.05; marker.position.set(s * SX, y, 0); marker2.position.set(-s * SX, y, 0); };
  lab.setSlit(state.s);
  // 4 hp: live potential curve with the global minimum as a ball
  const NP = 120, cg = new THREE.BufferGeometry(); cg.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(NP * 3), 3));
  const curve = new THREE.Line(cg, new THREE.LineBasicMaterial({ color: 0xffffff })); groups.hp.add(curve);
  const wall = new THREE.Mesh(new THREE.PlaneGeometry(0.03, 2.6), new THREE.MeshBasicMaterial({ color: 0xf9a8d4, side: THREE.DoubleSide })); wall.position.set(-1.6 + 0.5 * 3.8, 2.0, 0); groups.hp.add(wall);
  const axis = new THREE.Mesh(new THREE.BoxGeometry(3.4, 0.03, 0.03), std(0xffffff, 0.6)); axis.position.set(0, 1.9, 0); groups.hp.add(axis);
  const ball = new THREE.Mesh(new THREE.SphereGeometry(0.13, 20, 14), new THREE.MeshStandardMaterial({ color: 0x38bdf8, emissive: 0x38bdf8, emissiveIntensity: 0.8 })); groups.hp.add(ball);
  lab.setHP = (m2, b, ug) => {
    const p = cg.attributes.position; const amp = 0.6 / Math.max(0.02, Math.abs(b));
    for (let i = 0; i < NP; i++) { const u = 0.84 * i / (NP - 1); p.setXYZ(i, -1.6 + u * 3.8, 1.9 + Math.max(-0.9, Math.min(1.6, Phys.S(u, m2, b) * amp)), 0); }
    p.needsUpdate = true; ball.position.set(-1.6 + ug * 3.8, 1.9 + Math.max(-0.9, Math.min(1.6, Phys.S(ug, m2, b) * amp)) + 0.13, 0);
  };
  lab.setHP(state.m2, -state.absb, 0);
  // 5 ledger: one tile per claim, coloured by verdict
  const vc = { ok: 0x4ade80, ar: 0x60a5fa, co: 0xfbbf24, no: 0xf87171 };
  D.ledger.forEach((x, i) => { const m = new THREE.Mesh(new THREE.BoxGeometry(0.42, 0.42, 0.1), std(vc[x.cls], 0.35)); m.position.set(-1.5 + (i % 7) * 0.5, 3.4 - Math.floor(i / 7) * 0.5, 0); groups.ledger.add(m); });
  // 6 timeline: one bead per real event on a rising helix
  const beads = []; D.timeline.forEach((e, i) => { const a = i * 0.42, m = new THREE.Mesh(new THREE.SphereGeometry(0.09, 12, 8), std(0xfb923c, 0.3)); m.position.set(Math.cos(a) * 1.3, 0.7 + i * 0.065, Math.sin(a) * 1.3); groups.timeline.add(m); beads.push(m); });
  lab.setTimeline = (k) => beads.forEach((m, i) => { m.scale.setScalar(i === k ? 2.4 : 1); m.material.emissiveIntensity = i <= k ? 1.0 : 0.15; m.material.color.setHex(i === k ? 0xffffff : 0xfb923c); });
  lab.setTimeline(state.tl);
  const camera = new THREE.PerspectiveCamera(68, 1, 0.1, 200);
  lab.three = { scene, camera, picks, bh, disc, disc2, ring };
  return lab.three;
}
lab.build3D = build3D;

// ------------------------------------------------------------------ rendering, 2D fallback, input
const view = $('view');
let renderer = null, T3 = null;
function init3D() {
  try {
    if (!THREE) throw new Error('three.js missing');
    renderer = window.__LAB_FAKE_RENDERER__ || new THREE.WebGLRenderer({ canvas: view, antialias: true, powerPreference: 'high-performance' });   // the fake renderer is a test hook (scene/test_lab.mjs)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); renderer.outputColorSpace = THREE.SRGBColorSpace;
    T3 = build3D(); state.mode = '3d';
  } catch (err) { renderer = null; T3 = null; state.mode = '2d'; state.whyNot3d = String(err && err.message || err); }
}
function setMode(m) {
  if (m === '3d' && !renderer) { $('hud').textContent = 'WebGL is not available here — staying in the 2D map. ' + (state.whyNot3d || ''); m = '2d'; }
  state.mode = m; $('mode-badge').textContent = m === '3d' ? '3D' : '2D map'; $('btn-map').textContent = m === '3d' ? '2D map' : (renderer ? '3D view' : '2D map');
  resize();
}
function resize() {
  const w = view.clientWidth || window.innerWidth || 800, h = view.clientHeight || window.innerHeight || 600;
  if (renderer) { renderer.setSize(w, h, false); T3.camera.aspect = w / h; T3.camera.fov = w / h < 0.9 ? 82 : 68; T3.camera.updateProjectionMatrix(); }

  if (state.open === 'modular') updModular(); if (state.open === 'hp') updHP();
}
const overlay = document.createElement('canvas');   // used for the 2D map when WebGL owns #view
overlay.id = 'map2d'; overlay.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:none;background:#0c1226;touch-action:none';
view.parentNode.insertBefore(overlay, view.nextSibling);
function mapXY(cv) { const w = cv.clientWidth || 800, h = cv.clientHeight || 600, sc = Math.min(w / 34, (h - 60) / 36); return { w, h, sc, X: (x) => w / 2 + x * sc, Z: (z) => (h + 40) / 2 + (z - 3) * sc }; }
function draw2D() {
  const cv = overlay, g = overlay.getContext('2d'); if (!g) return;
  const d = Math.min(window.devicePixelRatio || 1, 2), M = mapXY(cv);
  if (cv.width !== Math.round(M.w * d)) { cv.width = Math.round(M.w * d); cv.height = Math.round(M.h * d); }
  g.setTransform(d, 0, 0, d, 0, 0); g.fillStyle = '#0c1226'; g.fillRect(0, 0, M.w, M.h);
  g.strokeStyle = '#26335f'; g.lineWidth = 1; for (let k = -16; k <= 16; k += 2) { g.beginPath(); g.moveTo(M.X(k), M.Z(-14)); g.lineTo(M.X(k), M.Z(20)); g.stroke(); g.beginPath(); g.moveTo(M.X(-16), M.Z(k + 3)); g.lineTo(M.X(16), M.Z(k + 3)); g.stroke(); }
  g.fillStyle = '#000'; g.beginPath(); g.arc(M.X(0), M.Z(-2.5), 1.5 * M.sc, 0, 6.3); g.fill(); g.strokeStyle = '#ffb347'; g.lineWidth = 3; g.beginPath(); g.arc(M.X(0), M.Z(-2.5), 2.6 * M.sc, 0, 6.3); g.stroke();
  g.textAlign = 'center'; g.fillStyle = '#ffd166'; g.font = 'bold 12px system-ui,sans-serif'; g.fillText(`Λ_V = ${fmt(K.LV, 5)} · b = ${fmt(K.b, 2)} g⁴`, M.X(0), M.Z(-2.5) + 3.4 * M.sc + 10);
  ST.forEach((st) => {
    const x = M.X(st.pos[0]), z = M.Z(st.pos[1]), col = '#' + st.color.toString(16).padStart(6, '0');
    g.fillStyle = col; g.globalAlpha = state.open === st.id ? 1 : 0.8; g.beginPath(); g.arc(x, z, 2.2 * M.sc, 0, 6.3); g.fill(); g.globalAlpha = 1;
    g.fillStyle = '#0b1020'; g.font = `bold ${Math.max(13, 1.6 * M.sc)}px system-ui,sans-serif`; g.fillText(String(st.n), x, z + 5);
    g.fillStyle = '#fff'; g.font = 'bold 12px system-ui,sans-serif'; g.fillText(st.title, x, z + 2.2 * M.sc + 14); g.fillStyle = '#c7d2fe'; g.font = '11px system-ui,sans-serif'; g.fillText(st.key(), x, z + 2.2 * M.sc + 28);
  });
  const ax = M.X(state.x), az = M.Z(state.z); g.save(); g.translate(ax, az); g.rotate(-state.yaw); g.fillStyle = '#38bdf8'; g.beginPath(); g.moveTo(0, -11); g.lineTo(7, 8); g.lineTo(-7, 8); g.closePath(); g.fill(); g.restore();
}
function nearest() { let best = null, bd = 1e9; ST.forEach((st) => { const d = Math.hypot(st.pos[0] - state.x, st.pos[1] - state.z); if (d < bd) { bd = d; best = st; } }); return bd < 5.6 ? best : null; }
function tick(dt) {
  state.t += dt;
  if (state.fly) { const f = state.fly; f.t = Math.min(1, f.t + dt / 0.9); const e = f.t * f.t * (3 - 2 * f.t); state.x = f.x0 + (f.x1 - f.x0) * e; state.z = f.z0 + (f.z1 - f.z0) * e; let dy = f.yaw1 - f.yaw0; dy = Math.atan2(Math.sin(dy), Math.cos(dy)); state.yaw = f.yaw0 + dy * e; state.pitch *= (1 - e * 0.2); if (f.t >= 1) state.fly = null; }
  else {
    const k = state.keys, p = state.pad, sp = (k.shift ? 9 : 4.5) * dt;
    const fw = ((k.w || k.arrowup || p.f) ? 1 : 0) - ((k.s || k.arrowdown || p.b) ? 1 : 0), sd = ((k.d || p.r) ? 1 : 0) - ((k.a || p.l) ? 1 : 0), tr = ((k.arrowright) ? 1 : 0) - ((k.arrowleft) ? 1 : 0);
    state.yaw -= tr * 1.6 * dt;
    if (fw || sd) { const sy = Math.sin(state.yaw), cy = Math.cos(state.yaw); state.x += (-sy * fw + cy * sd) * sp; state.z += (-cy * fw - sy * sd) * sp; const r = Math.hypot(state.x, state.z); if (r > 30) { state.x *= 30 / r; state.z *= 30 / r; } }
  }
  if (state.playing) { state.tlClock = (state.tlClock || 0) + dt; if (state.tlClock > 0.7) { state.tlClock = 0; if (state.tl < D.timeline.length - 1) { state.tl++; } else state.playing = false; if (state.open === 'timeline') updTimeline(); } }
  const n = nearest(); if (n !== state.near) { state.near = n; if (!state.hudLock) $('hud').textContent = n ? `Press E or click: ${n.n} · ${n.title} — ${n.key()}` : ''; }
  if (state.mode === '3d' && renderer) {
    overlay.style.display = 'none';
    const c = T3.camera; c.position.set(state.x, 1.75, state.z); c.rotation.order = 'YXZ'; c.rotation.y = state.yaw; c.rotation.x = state.pitch;
    T3.disc.rotation.z += dt * 0.25; T3.disc2.rotation.z -= dt * 0.12; renderer.render(T3.scene, c);
  } else { overlay.style.display = 'block'; draw2D(); }
}
lab.tick = tick;

function selectAt(cx, cy, target) {
  const rect = target.getBoundingClientRect(), px = cx - rect.left, py = cy - rect.top;
  if (state.mode === '3d' && renderer) {
    const ray = new THREE.Raycaster(); ray.setFromCamera(new THREE.Vector2(px / rect.width * 2 - 1, -(py / rect.height) * 2 + 1), T3.camera);
    const hit = ray.intersectObjects(T3.picks, false)[0]; if (hit) goTo(hit.object.userData.station);
  } else {
    const M = mapXY(target); let done = false;
    ST.forEach((st) => { if (!done && Math.hypot(M.X(st.pos[0]) - px, M.Z(st.pos[1]) - py) < 2.6 * M.sc + 6) { goTo(st.id); done = true; } });
  }
}
function bindPointer(el) {
  el.addEventListener('pointerdown', (e) => { state.drag = { x: e.clientX, y: e.clientY, moved: 0 }; if (el.setPointerCapture) { try { el.setPointerCapture(e.pointerId); } catch (_) {} } if (el.focus) el.focus(); });
  el.addEventListener('pointermove', (e) => { const d = state.drag; if (!d) return; const dx = e.clientX - d.x, dy = e.clientY - d.y; d.moved += Math.abs(dx) + Math.abs(dy); d.x = e.clientX; d.y = e.clientY; state.fly = null; state.yaw -= dx * 0.0045; state.pitch = Math.max(-1.1, Math.min(1.1, state.pitch - dy * 0.0035)); });
  const up = (e) => { const d = state.drag; state.drag = null; if (d && d.moved < 6) selectAt(e.clientX, e.clientY, el); };
  el.addEventListener('pointerup', up); el.addEventListener('pointercancel', () => { state.drag = null; });
}
bindPointer(view); bindPointer(overlay);
window.addEventListener('keydown', (e) => {
  const tag = (e.target && e.target.tagName) || ''; if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return;
  const k = e.key.toLowerCase(); state.keys[k] = true; if (e.shiftKey) state.keys.shift = true;
  if (k === 'e' || k === 'enter') { const n = nearest(); if (n) goTo(n.id); }
  else if (k >= '1' && k <= '6') goTo(ST[+k - 1].id);
  else if (k === 'escape') { closePanel(); $('help').classList.add('hidden'); }
  else if (k === 'm') setMode(state.mode === '3d' ? '2d' : '3d');
  else if (k === 'h' || k === '?') $('help').classList.toggle('hidden');
  if (['arrowup', 'arrowdown', 'arrowleft', 'arrowright', ' '].includes(k)) e.preventDefault();
});
window.addEventListener('keyup', (e) => { state.keys[e.key.toLowerCase()] = false; if (!e.shiftKey) state.keys.shift = false; });
window.addEventListener('blur', () => { state.keys = {}; state.pad = {}; });
window.addEventListener('resize', resize);
document.querySelectorAll('#pad button').forEach((b) => {
  const set = (v) => (e) => { state.pad[b.dataset.mv] = v; if (e && e.preventDefault) e.preventDefault(); };
  b.addEventListener('pointerdown', set(true)); b.addEventListener('pointerup', set(false)); b.addEventListener('pointerleave', set(false)); b.addEventListener('pointercancel', set(false));
});
const nav = $('stations');
ST.forEach((st) => { const b = document.createElement('button'); b.textContent = `${st.n} ${st.title}`; b.dataset.st = st.id; b.title = st.key(); b.addEventListener('click', () => goTo(st.id)); nav.appendChild(b); });
$('panel-close').addEventListener('click', closePanel);
$('panel-size').addEventListener('click', () => { $('panel').classList.toggle('wide'); setTimeout(resize, 220); });
$('btn-map').addEventListener('click', () => setMode(state.mode === '3d' ? '2d' : '3d'));
$('btn-help').addEventListener('click', () => $('help').classList.toggle('hidden'));
$('help-close').addEventListener('click', () => $('help').classList.add('hidden'));
$('headline').innerHTML = `<b>Λ_V = ${fmt(K.LV, 5)}</b> endpoint solved 3 ways · refit of Table 2: Λ = ${fmt(K.Lfit, 4)} · <b>b = ${fmt(K.b, 2)} g⁴</b>, sign margin ${fmt(K.q4crit - K.q4, 1)} · ${D.checks.pass}/${D.checks.n} checks, ${D.validation.pass}/${D.validation.n} cross-checks. <span style="color:#aab4d4">WASD + drag, E or 1–6 to open a station.</span>`;

init3D(); setMode(state.mode);
if ((view.clientWidth || 800) / (view.clientHeight || 600) < 0.9) { state.z = 24; }
let last = 0;
function loop(ts) { const dt = Math.min(0.05, (ts - last) / 1000 || 0.016); last = ts; try { tick(dt); } catch (err) { $('hud').textContent = 'render error: ' + err.message; state.hudLock = true; } window.requestAnimationFrame(loop); }
window.requestAnimationFrame(loop);
