// 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) {
  const tones = {'#1d4ed8':'#91ccdf','#9333ea':'#cd9cde','#059669':'#82d0a8','#be185d':'#f2b37e','#dc2626':'#ff9a86','#d97706':'#e6b16e','#6b7280':'#a1b2bd'};
  const color = c => tones[c] || c;
  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 = '#101a22'; 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 = '#627882'; g.lineWidth = 1; g.strokeRect(L, T, W - L - R, H - T - B);
  g.fillStyle = '#e0eceb'; 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 = '#2a3b44'; g.beginPath(); g.moveTo(L, y); g.lineTo(W - R, y); g.stroke(); g.strokeStyle = '#627882'; });
  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 = color(s.color); g.fillStyle = color(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 || '#9badb3'; 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 = color(s.color); g.fillRect(o.legendX || L + 8, ly - 7, 10, 3); g.fillStyle = '#e0eceb'; 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">Open the original PDFs and source record in the offline reader: <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">The original session executed the notebook in process. An independent replay in a fresh Jupyter kernel produced all 11 figures.</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 wireframe beside this planet shows 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, numerically checked for nonnegativity on [t₁, ∞), vanishing vacuum action and a negative Cardy-mass fraction of 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; $('app').classList.add('station'); $('panel').inert = 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();
  }
}
// Orbital navigation and illustrations. Quantitative charts continue to use the embedded research tables.
const A = JSON.parse($('orbit-assets').textContent);
const view = $('view'), app = $('app'), overlay = document.createElement('canvas');
overlay.id = 'map2d'; overlay.setAttribute('aria-label','Orbital map of the six research stations');overlay.tabIndex=0;
view.parentNode.insertBefore(overlay,view.nextSibling);
const shortNames=['Source papers','Notebook','Modular bound','Hawking–Page','Evidence ledger','Timeline'];
const placements=[[.43,.245,-14,.81],[.50,.69,3,.63],[.89,.23,-4,1.10],[.84,.67,4,1.44],[.45,.54,-20,.43],[.975,.49,-18,.70]];
const portrait=[[.14,.355,-14,.6],[.09,.62,3,.44],[.86,.30,-4,.68],[.83,.676,4,.78],[.24,.7,-20,.34],[.955,.53,-18,.45]];
const homeZ=48, fov=43, cameraFactor=Math.tan(fov*Math.PI/360);
const motionQuery=window.matchMedia?.('(prefers-reduced-motion: reduce)');
let paused=Boolean(motionQuery?.matches), travel=null, dirty=true, renderer=null,T3=null,last=0, hudClock=0;
Object.assign(state,{x:0,y:0,z:homeZ,yaw:0,pitch:0,t:0});
function setMotion(value){
  paused=value;app.classList.toggle('paused',paused);
  const label=paused?'Resume ambient motion':'Pause ambient motion';
  $('motion').textContent=paused?'▷':'Ⅱ';$('motion').setAttribute('aria-label',label);$('motion').title=label;dirty=true;
}
function randomSeed(seed){return ()=>{seed=(Math.imul(1664525,seed)+1013904223)>>>0;return seed/4294967296;};}
function texture(uri){
  if(!uri||typeof Image==='undefined')return new THREE.Texture();
  const tex=new THREE.Texture();const im=new Image();im.onload=()=>{tex.image=im;tex.needsUpdate=true;dirty=true;};im.src=uri;tex.colorSpace=THREE.SRGBColorSpace;return tex;
}
function stroke(points,color,opacity,loop=false){
  const geometry=new THREE.BufferGeometry().setFromPoints(points);
  const material=new THREE.LineBasicMaterial({color,transparent:true,opacity,depthWrite:false});
  return loop?new THREE.LineLoop(geometry,material):new THREE.Line(geometry,material);
}
function starCloud(count,kind,seed){
  const random=randomSeed(seed),pos=[],colors=[],sizes=[],phase=[];
  const palette=[new THREE.Color('#bacbd9'),new THREE.Color('#f5dfc6'),new THREE.Color('#95afb9'),new THREE.Color('#e8eff0')];
  for(let i=0;i<count;i++){
    const a=random()*Math.PI*2,b=random(),c=palette[Math.floor(random()*palette.length)];
    if(kind==='stars'){
      const r=135+random()*75,y=b*2-1,lat=Math.sqrt(1-y*y);pos.push(r*lat*Math.cos(a),r*y,r*lat*Math.sin(a));
      sizes.push(.48+Math.pow(random(),4)*2.7);
    }else{
      const r=1.33+b*.70;
      pos.push(r*Math.cos(a),(random()-.5)*.11,r*Math.sin(a));sizes.push(.90+random()*1.4);
    }
    colors.push(c.r,c.g,c.b);phase.push(random()*6.28);
  }
  const g=new THREE.BufferGeometry();
  for(const [name,array,n] of [['position',pos,3],['tint',colors,3],['radius',sizes,1],['phase',phase,1]])g.setAttribute(name,new THREE.Float32BufferAttribute(array,n));
  const mat=new THREE.ShaderMaterial({transparent:true,depthWrite:false,blending:THREE.AdditiveBlending,uniforms:{clock:{value:0},density:{value:kind==='stars'?.88:.63},pixel:{value:Math.min(window.devicePixelRatio||1,1.7)}},
    vertexShader:'attribute vec3 tint; attribute float radius,phase; varying vec3 col; varying float pulse; uniform float clock,pixel; void main(){col=tint;pulse=.77+.23*sin(phase+.68*clock);vec4 mv=modelViewMatrix*vec4(position,1.); gl_Position=projectionMatrix*mv;gl_PointSize=pixel*radius;}',
    fragmentShader:'varying vec3 col;varying float pulse;uniform float density; void main(){float d=length(gl_PointCoord-.5)*2.; if(d>1.)discard;gl_FragColor=vec4(col,pulse*density*(1.-smoothstep(.12,1.,d)));}'});
  return new THREE.Points(g,mat);
}
function ringBands(){
  const group=new THREE.Group();
  const random=randomSeed(777);
  for(let j=0;j<24;j++){
    const inner=1.22+j*.027;
    const ring=new THREE.Mesh(new THREE.RingGeometry(inner,inner+.01+random()*.022,122),new THREE.MeshBasicMaterial({color:new THREE.Color().setHSL(.10,.19,.39+random()*.28),opacity:.27+random()*.25,transparent:true,side:THREE.DoubleSide,depthWrite:false}));
    ring.rotation.x=Math.PI/2;group.add(ring);
  }
  return group;
}
function build3D(){
  const scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(fov,1,.07,420);
  scene.background=new THREE.Color('#080e16');
  const sky=new THREE.Mesh(new THREE.SphereGeometry(260,48,24),new THREE.MeshBasicMaterial({map:texture(A.sky),color:0xffffff,side:THREE.BackSide,depthWrite:false}));sky.renderOrder=-10;scene.add(sky);
  const stars=starCloud(12800,'stars',9001);stars.renderOrder=-8;scene.add(stars);
  const disk=new THREE.Sprite(new THREE.SpriteMaterial({map:texture(A.accretion),transparent:true,depthWrite:false,toneMapped:false}));disk.renderOrder=-3;
  const accretionClock={value:0};
  const diskOrbits=texture(A.diskOrbits),plasma=texture(A.plasma);
  diskOrbits.colorSpace=THREE.NoColorSpace;
  plasma.colorSpace=THREE.NoColorSpace;
  plasma.wrapS=THREE.RepeatWrapping;
  // Disk-space longitude makes a single stream follow the direct band and its lensed images.
  disk.material.onBeforeCompile=shader=>{
    shader.uniforms.accretionTime=accretionClock;
    shader.uniforms.diskOrbits={value:diskOrbits};
    shader.uniforms.plasma={value:plasma};
    const uniforms=`uniform float accretionTime;
uniform sampler2D diskOrbits;
uniform sampler2D plasma;
`;
    const flow=`
      vec3 orbit = texture2D(diskOrbits, vMapUv).rgb;
      vec2 direction = orbit.rg * 2.0 - 1.0;
      float mask = smoothstep(0.018, 0.96, length(direction));
      if (mask > 0.001) {
        float longitude = atan(direction.y, direction.x) * 0.1591549431;
        float radius = orbit.b;
        float t = mod(accretionTime, 32.0);
        float fast = texture2D(plasma, vec2(longitude - t / 16.0, radius)).r;
        float slow = texture2D(plasma, vec2(longitude + 0.247 - t / 32.0, radius)).r;
        float density = mix(fast, slow, smoothstep(0.19, 0.81, radius)) - 0.5;
        float signal = density * mask;
        diffuseColor.rgb *= exp2(vec3(2.9, 4.1, 5.3) * signal);
        diffuseColor.a = clamp(diffuseColor.a * exp2(0.75 * signal), 0.0, 1.0);
      }
    `;
    shader.fragmentShader=uniforms+shader.fragmentShader.replace('#include <map_fragment>','#include <map_fragment>\n'+flow);
  };
  scene.add(disk);
  const sun=new THREE.DirectionalLight('#fff0d8',2.9);sun.position.set(-26,17,14);scene.add(sun);
  scene.add(new THREE.AmbientLight('#98afc6',.37));
  const worlds=[],picks=[],dusts=[];
  const shell=new THREE.SphereGeometry(1,56,32);
  for(let i=0;i<6;i++){
    const root=new THREE.Group(),planet=new THREE.Mesh(shell,new THREE.MeshStandardMaterial({map:texture(A.surfaces[i]),roughness:.93,metalness:0}));
    planet.userData.station=ST[i].id;planet.rotation.z=(i-2)*.12;root.add(planet);picks.push(planet);
    const belt=new THREE.Group();belt.rotation.set(.36,0,-.25+i*.08);
    const dust=starCloud(i===3?1250:430,'dust',500+i);belt.add(dust);dusts.push(dust);
    if(i===3)belt.add(ringBands());
    root.add(belt);scene.add(root);worlds.push(root);
  }
  // A finite-difference field at station 3 and the restricted-domain potential at station 4.
  const field=D.field,cols=field.y.length,points=[],sr=3.7,up=1.1;
  for(let i=0;i<field.x.length;i+=5){
    const row=[];for(let j=0;j<field.y.length;j++)row.push(new THREE.Vector3(field.x[i]*.43,field.U[i*cols+j]*up,field.y[j]*sr));
    const line=stroke(row,0x81dbd1,.61);points.push(line);
  }
  const fieldGroup=new THREE.Group();fieldGroup.add(...points);scene.add(fieldGroup);fieldGroup.visible=false;
  const slit=new THREE.Mesh(new THREE.SphereGeometry(.09,12,8),new THREE.MeshBasicMaterial({color:0xffc38a}));fieldGroup.add(slit);
  lab.setSlit=s=>{slit.position.set(s*.43, .12,0);dirty=true;};
  const phaseCurve=stroke(Array.from({length:101},()=>new THREE.Vector3()),0xf7bf91,.95);scene.add(phaseCurve);phaseCurve.visible=false;
  lab.setHP=(m,b)=>{const attr=phaseCurve.geometry.attributes.position;
    for(let i=0;i<attr.count;i++){const u=.92*i/(attr.count-1);attr.setXYZ(i,(u-.46)*5,Math.max(-1,Math.min(2,Phys.S(u,m,b)*8)),0);}
    attr.needsUpdate=true;phaseCurve.geometry.computeBoundingSphere();dirty=true;
  };
  lab.setTimeline=i=>{worlds[5].children[1].rotation.y=i/Math.max(1,D.timeline.length-1)*Math.PI*2;dirty=true;};
  const result={scene,camera,disk,accretionClock,stars,sky,worlds,picks,dusts,fieldGroup,phaseCurve};lab.three=result;return result;
}
lab.build3D=build3D;
function anchor(nx,ny,z,w,h){
  const half=(homeZ-z)*cameraFactor;
  return new THREE.Vector3((nx*2-1)*half*w/h,(1-ny*2)*half,z);
}
function framing(){
  const w=view.clientWidth||800,h=view.clientHeight||600,small=w<=720;
  return {w,h,small,cx:small?.54:.673,cy:small?.49:.435,diskWidth:small?Math.min(w*1.05,h*.79):Math.min(w*.685,h*1.02)};
}
function layout(){
  const {w,h,small,cx,cy,diskWidth}=framing(),positions=small?portrait:placements;
  const label=$('target-label');label.style.left=(cx*w-diskWidth*.29)+'px';label.style.top=(cy*h+diskWidth*.18)+'px';
  positions.forEach(([nx,ny,z,s],i)=>{
    const point=anchor(nx,ny,z,w,h);ST[i].world=point;ST[i].pos=[point.x,point.z];ST[i].radius=s;
    if(T3){T3.worlds[i].position.copy(point);T3.worlds[i].scale.setScalar(s);}
  });
  if(T3){
    const {camera,disk}=T3;camera.aspect=w/h;camera.updateProjectionMatrix();renderer.setSize(w,h,false);
    disk.position.copy(anchor(cx,cy,-29,w,h));const ww=diskWidth*2*(homeZ+29)*cameraFactor/h;disk.scale.set(ww,ww*870/1440,1);
    T3.fieldGroup.position.copy(ST[2].world).add(new THREE.Vector3(-1.5,-1.5,.5));
    T3.phaseCurve.position.copy(ST[3].world).add(new THREE.Vector3(-1.4,-1.9,.7));
  }
  if(state.open==='modular')updModular();if(state.open==='hp')updHP();dirty=true;
}
function init3D(){
  try{renderer=window.__LAB_FAKE_RENDERER__||new THREE.WebGLRenderer({canvas:view,antialias:true,powerPreference:'low-power'});renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,1.65));renderer.outputColorSpace=THREE.SRGBColorSpace;T3=build3D();state.mode='3d';}
  catch(e){renderer=null;T3=null;state.mode='2d';state.whyNot3d=e.message;}
}
function setMode(mode){
  state.mode=mode==='3d'&&renderer?'3d':'2d';const map=state.mode==='2d';app.classList.toggle('map',map);
  $('mode-badge').textContent=map?'2D map':'3D';$('btn-map').textContent=map?(renderer?'3D view':'2D map'):'2D map';overlay.style.display=map?'block':'none';layout();
}
const mapPoints=[[.18,.27],[.52,.19],[.81,.29],[.82,.65],[.46,.73],[.16,.60]],mapImages=[];
if(typeof Image!=='undefined'){const im=new Image();im.onload=()=>{dirty=true;};im.src=A.worlds;mapImages.push(im);}
function mapPosition(st){
  const {w,h,small}=framing(),space=Math.max(100,h-(small?166:149)-70);
  return [mapPoints[st.n-1][0]*w,62+mapPoints[st.n-1][1]*space];
}
function draw2D(){
  const g=overlay.getContext('2d');if(!g)return;
  const {w,h,small}=framing(),d=Math.min(window.devicePixelRatio||1,1.6);
  if(overlay.width!==Math.round(w*d)||overlay.height!==Math.round(h*d)){overlay.width=Math.round(w*d);overlay.height=Math.round(h*d);}
  g.setTransform(d,0,0,d,0,0);g.fillStyle='#09121b';g.fillRect(0,0,w,h);
  const random=randomSeed(272);for(let i=0;i<300;i++){g.fillStyle=i%8?'#687c86':'#a0adb1';g.globalAlpha=.35+random()*.5;g.fillRect(random()*w,random()*h,1,1);}g.globalAlpha=1;
  const centerX=w*.49,centerY=(mapPosition(ST[1])[1]+mapPosition(ST[4])[1])*.5;
  for(let i=1;i<=4;i++){g.strokeStyle='#263a40';g.beginPath();g.ellipse(centerX,centerY,w*(.10+i*.09),Math.max(17,h*(.025+i*.043)),-.12,0,Math.PI*2);g.stroke();}
  g.fillStyle='#ebc499';g.textAlign='center';g.font='11px monospace';g.fillText('ORBITAL MAP',centerX,centerY);
  ST.forEach((st,i)=>{const [x,y]=mapPosition(st);const size=small?47:70;
    if(mapImages[0]?.complete&&mapImages[0].naturalWidth){const im=mapImages[0],cw=im.width/3,ch=im.height/2;g.drawImage(im,(i%3)*cw,Math.floor(i/3)*ch,cw,ch,x-size/2,y-size*.385,size,size*.77);}
    else{g.fillStyle='#839da5';g.beginPath();g.arc(x,y,9,0,Math.PI*2);g.fill();}
    g.font=(small?'9':'11')+'px monospace';g.fillStyle=state.open===st.id?'#e4b783':'#d0dcdb';g.fillText(shortNames[i],x,y+size*.43);});
}
function nearest(){let best=null,dist=Infinity;for(const s of ST){if(!s.world)continue;const d=Math.hypot(s.world.x-state.x,s.world.y-state.y,s.world.z-state.z);if(d<dist){dist=d;best=s;}}return dist<11?best:null;}
function flight(x,y,z,yaw=0,pitch=0){
  travel={from:[state.x,state.y,state.z,state.yaw,state.pitch],to:[x,y,z,yaw,pitch],t:0};
  if(paused){[state.x,state.y,state.z,state.yaw,state.pitch]=travel.to;travel=null;}dirty=true;
}
function goTo(id,open=true){
  const st=ST.find(s=>s.id===id);if(!st)return;
  const small=framing().small,p=st.world,dist=st.radius*(small?9.5:8);
  const dx=small?0:dist*cameraFactor*(framing().w/framing().h)*.36;
  flight(p.x+dx,p.y+(small?-dist*.17:0),p.z+dist);
  if(open)openPanel(id);app.classList.remove('flying');dirty=true;
}
function closePanel(){state.open=null;state.playing=false;$('panel').classList.add('closed');$('panel').classList.remove('wide');$('panel').inert=true;app.classList.remove('station');app.classList.remove('flying');flight(0,0,homeZ);document.querySelectorAll('#stations button').forEach(b=>b.classList.remove('on'));}
lab.closePanel=closePanel;lab.goTo=goTo;lab.openPanel=openPanel;
function tick(dt){
  if(!paused)state.t+=dt;
  if(travel){travel.t=Math.min(1,travel.t+dt/1.2);const k=travel.t**2*(3-2*travel.t),v=travel.from.map((a,i)=>a+(travel.to[i]-a)*k);[state.x,state.y,state.z,state.yaw,state.pitch]=v;if(travel.t>=1)travel=null;dirty=true;}
  const k=state.keys,p=state.pad,speed=(k.shift?27:10)*dt;
  const forward=Number(Boolean(k.w||k.arrowup||p.f))-Number(Boolean(k.s||k.arrowdown||p.b));const side=Number(Boolean(k.d||p.r))-Number(Boolean(k.a||p.l));
  if(forward||side||k.arrowright||k.arrowleft){travel=null;app.classList.add('flying');state.yaw+=(Number(Boolean(k.arrowleft))-Number(Boolean(k.arrowright)))*1.7*dt;state.x+=(-Math.sin(state.yaw)*forward+Math.cos(state.yaw)*side)*speed;state.z+=(-Math.cos(state.yaw)*forward-Math.sin(state.yaw)*side)*speed;state.y+=Math.sin(state.pitch)*forward*speed;dirty=true;}
  if(state.playing){state.tlClock=(state.tlClock||0)+dt;if(state.tlClock>.7){state.tlClock=0;if(state.tl<D.timeline.length-1)state.tl++;else state.playing=false;if(state.open==='timeline')updTimeline();}}
  if(!paused||dirty){
    if(state.mode==='3d'&&renderer){
      T3.camera.position.set(state.x,state.y,state.z);T3.camera.rotation.order='YXZ';T3.camera.rotation.set(state.pitch,state.yaw,0,'YXZ');T3.sky.position.copy(T3.camera.position);T3.stars.position.copy(T3.camera.position).multiplyScalar(.85);T3.stars.material.uniforms.clock.value=state.t;T3.accretionClock.value=state.t;
      T3.worlds.forEach((w,i)=>{w.children[0].rotation.y=state.t*(.052+i*.004);T3.dusts[i].rotation.y=state.t*(.09+i*.012);T3.dusts[i].material.uniforms.clock.value=state.t;});
      T3.fieldGroup.visible=state.open==='modular';T3.phaseCurve.visible=state.open==='hp';renderer.render(T3.scene,T3.camera);
    }else draw2D();
    hudClock+=dt;if(hudClock>.14||dirty){hudClock=0;const bearing=Math.round(((-state.yaw*180/Math.PI)%360+360)%360);$('bearing').textContent='Bearing '+String(bearing).padStart(3,'0')+'°';const n=nearest();$('hud').textContent=n&&!state.open?'E · '+n.title:'';}
    dirty=false;
  }
}
lab.tick=tick;
function selectAt(cx,cy,el){
  const r=el.getBoundingClientRect(),x=cx-r.left,y=cy-r.top;
  if(state.mode==='2d'){const s=ST.find(st=>{const [px,py]=mapPosition(st);return Math.hypot(x-px,y-py)<38;});if(s)goTo(s.id);return;}
  if(!T3)return;const ray=new THREE.Raycaster();ray.setFromCamera(new THREE.Vector2(x/r.width*2-1,1-y/r.height*2),T3.camera);const hit=ray.intersectObjects(T3.picks,false)[0];if(hit)goTo(hit.object.userData.station);
}
function bindPointer(el){
  el.addEventListener('pointerdown',e=>{state.drag={x:e.clientX,y:e.clientY,moved:0};el.setPointerCapture?.(e.pointerId);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.x=e.clientX;d.y=e.clientY;d.moved+=Math.abs(dx)+Math.abs(dy);if(d.moved>4&&state.mode==='3d'){travel=null;app.classList.add('flying');state.yaw-=dx*.0045;state.pitch=Math.max(-1.25,Math.min(1.25,state.pitch-dy*.0035));dirty=true;}});
  el.addEventListener('pointerup',e=>{const d=state.drag;state.drag=null;if(d&&d.moved<6)selectAt(e.clientX,e.clientY,el);});el.addEventListener('pointercancel',()=>{state.drag=null;});
}
bindPointer(view);bindPointer(overlay);
window.addEventListener('keydown',e=>{
  if($('paper-reader')?.open||['INPUT','SELECT','TEXTAREA'].includes(e.target?.tagName))return;
  const k=e.key.toLowerCase();state.keys[k]=true;if(e.shiftKey)state.keys.shift=true;
  if(k>='1'&&k<='6')goTo(ST[+k-1].id);else if(k==='e'){const s=nearest();if(s)goTo(s.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(k.startsWith('arrow')&&e.target?.tagName==='CANVAS')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',()=>{layout();if(state.open)goTo(state.open,false);});
document.querySelectorAll('#pad button').forEach(b=>{b.addEventListener('pointerdown',e=>{e.preventDefault();b.setPointerCapture?.(e.pointerId);state.pad[b.dataset.mv]=true;});for(const evt of ['pointerup','pointercancel'])b.addEventListener(evt,()=>{state.pad[b.dataset.mv]=false;});});
ST.forEach((st,i)=>{const b=document.createElement('button');b.dataset.st=st.id;b.title=st.title+' · '+st.key();b.setAttribute('aria-label',st.n+' '+st.title);b.style.setProperty('--i',i);
  b.innerHTML='<i class="planet-thumb" aria-hidden="true"></i><span class="station-code">Orbit 0'+st.n+'</span><span class="station-name">'+shortNames[i]+'</span>';
  const art=b.querySelector('.planet-thumb');art.style.backgroundImage='url("'+A.worlds+'")';art.style.backgroundPosition=(i%3)*50+'% '+Math.floor(i/3)*100+'%';
  b.addEventListener('click',()=>goTo(st.id));$('stations').appendChild(b);});
$('identity').addEventListener('click',closePanel);$('panel-close').addEventListener('click',closePanel);$('enter').addEventListener('click',()=>goTo('sources'));$('panel-size').addEventListener('click',()=>{$('panel').classList.toggle('wide');setTimeout(layout,240);});
$('btn-map').addEventListener('click',()=>setMode(state.mode==='3d'?'2d':'3d'));$('motion').addEventListener('click',()=>setMotion(!paused));motionQuery?.addEventListener('change',e=>setMotion(e.matches));
$('btn-help').addEventListener('click',()=>$('help').classList.toggle('hidden'));$('help-close').addEventListener('click',()=>$('help').classList.add('hidden'));
$('headline').innerHTML='<div class="metric"><small>Modular bound · Λᵥ</small><b>'+fmt(K.LV,5)+'</b></div><div class="metric"><small>Hagedorn point · TᴴR</small><b>'+fmt(1/K.beta0,5)+'</b></div>';
init3D();setMotion(paused);setMode(state.mode);
function loop(ts){const dt=Math.min(.06,(ts-last)/1000||.016);last=ts;if(!document.hidden)tick(dt);window.requestAnimationFrame(loop);}
window.requestAnimationFrame(loop);
