#!/usr/bin/env node
// verify-every-direction-at-once.mjs
//
// Re-derives everything /strata/every-direction-at-once/ prints, checks the three
// derivations of the braid against each other, checks the Legendre bridge, checks
// the rotor simulation against its own closed form, and checks the shipped page
// against all of it, including a real browser pass.
//
//   node verify-every-direction-at-once.mjs                # everything
//   node verify-every-direction-at-once.mjs --no-browser   # skip the DOM section
//
// Say so if you report a green run with --no-browser: that section is the only one
// that checks what a reader actually sees.

import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createServer } from 'node:http';

const ROOT = dirname(fileURLToPath(import.meta.url));
const R = (p) => join(ROOT, p);
const HERE = R('research/every-direction-at-once');

const G = await import(join(HERE, 'geometry.mjs'));
const L = await import(join(HERE, 'legendre.mjs'));
const B = await import(join(HERE, 'braid.mjs'));
const MAS = await import(join(HERE, 'mas.mjs'));
const N = await import(join(HERE, 'necking.mjs'));
const BP = await import(join(HERE, 'build-page.mjs'));

const DATA = JSON.parse(readFileSync(join(HERE, 'page.json'), 'utf8'));
const SRC = JSON.parse(readFileSync(join(HERE, 'sources.json'), 'utf8'));
const HTML = readFileSync(BP.PAGE, 'utf8');

let pass = 0;
let fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) pass++;
  else { fail++; console.log(`  FAIL  ${name}${detail ? ': ' + detail : ''}`); }
};
const near = (name, got, want, tol, unit = '') =>
  ok(name, Math.abs(got - want) <= tol, `got ${got}${unit}, want ${want}${unit} +/- ${tol}`);
const section = (s) => console.log(`\n${s}`);

const DEGM = G.THETA_M * G.DEG;

// ── 1. the angle, four ways, to the last bit ─────────────────────────────────
section('1. The angle');
const cf = G.closedForms();
near('arctan sqrt2 in degrees', cf.arctanRoot2, 54.735610317245346, 0);
ok('arccos(1/sqrt3) is bit-identical', cf.arccosInvRoot3 === cf.arctanRoot2,
  `${cf.arccosInvRoot3} vs ${cf.arctanRoot2}`);
ok('arcsin(sqrt(2/3)) is bit-identical', cf.arcsinRoot2over3 === cf.arctanRoot2);
ok('half the tetrahedral angle is bit-identical', cf.halfTetrahedral === cf.arctanRoot2);
near('cos^2 = 1/3', Math.cos(G.THETA_M) ** 2, 1 / 3, 1e-16);
near('sin^2 = 2/3', Math.sin(G.THETA_M) ** 2, 2 / 3, 1e-16);
near('tan^2 = 2', Math.tan(G.THETA_M) ** 2, 2, 1e-15);
const { d, m, s } = G.dms(DEGM);
ok('degrees, minutes, seconds', d === 54 && m === 44 && Math.abs(s - 8.197) < 0.001,
  `${d} ${m} ${s}`);

// ── 2. the cube, and the lattice that is one ─────────────────────────────────
section('2. The cube');
const cube = G.cubeAngles();
ok('the diagonal makes the same angle with all three edges',
  cube.toX === cube.toY && cube.toY === cube.toZ, `${cube.toX} ${cube.toY} ${cube.toZ}`);
near('and that angle is theta_m', cube.toX, DEGM, 0);
near('two diagonals meet at the tetrahedral angle', cube.tetrahedral, Math.acos(-1 / 3) * G.DEG, 0);
near('which is exactly twice theta_m', cube.tetrahedral, 2 * DEGM, 1e-13);
near('the {111} sidewall on a (100) wafer is the same angle', cube.siliconSidewall, DEGM, 0);
near('an etched pit widens by sqrt(2) per unit depth', DATA.lattice.pitWideningPerDepth, Math.SQRT2, 1e-15);
// a direction NOT equally shared must not give theta_m
ok('a non-diagonal direction does not give the angle',
  Math.abs(G.angleBetween([1, 1, 0], [0, 0, 1]) - DEGM) > 1, `${G.angleBetween([1, 1, 0], [0, 0, 1])}`);

// ── 3. the isotropic average, and the Jensen trap ────────────────────────────
section('3. The isotropic average');
const iso = G.isotropicMoments(2_000_000);
near('<cos^2> over the sphere is 1/3', iso.meanCos2, 1 / 3, 1e-9);
near('but the mean polar angle is 90 degrees', iso.meanThetaDeg, 90, 1e-8);
near('and the median polar angle is 90 degrees', iso.medianThetaDeg, 90, 0);
near('arccos(sqrt(<cos^2>)) is theta_m', iso.rmsAngleDeg, DEGM, 1e-8);
ok('the Jensen gap is the 35 degrees the page claims',
  Math.abs(iso.meanThetaDeg - iso.rmsAngleDeg - 35.264389682754654) < 1e-8,
  `${iso.meanThetaDeg - iso.rmsAngleDeg}`);

// ── 4. the braid: three derivations, one function ────────────────────────────
section('4. The braid');
near('the closed-form maximum is 2/(3 sqrt 3)', B.VOLUME_SHAPE_MAX, B.volumeShape(G.THETA_M), 1e-16);
near('the 20-million-step scan finds the same angle', DATA.braid.argmaxDeg, DEGM, 1e-6);
ok('and its error is no worse than the scan step',
  Math.abs(DATA.braid.argmaxErrorDeg) <= (90 / 20_000_000) * 4,
  `${DATA.braid.argmaxErrorDeg}`);
near('the axial share of the squared fibre length is exactly 1/3',
  B.axialShareOfSquaredLength(G.THETA_M), 1 / 3, 1e-16);

// The load-bearing claim: netting analysis and volume stationarity are the same
// function, not merely functions with the same root.
let worstNet = 0;
let worstLeg = 0;
let worstForce = 0;
let signFlips = 0;
let prevSign = null;
for (let i = 1; i < 900; i++) {
  const t = (i * Math.PI) / 1800;
  worstNet = Math.max(worstNet, Math.abs(B.dVolumeShape(t) - Math.sin(t) * B.nettingDemand(t).imbalance));
  worstLeg = Math.max(worstLeg, Math.abs(B.forceShape(t) - 2 * L.P[2](Math.cos(t))));
  worstForce = Math.max(worstForce, Math.abs(B.forceByNumericalDerivative(t) - B.forceShape(t)));
  const sg = Math.sign(B.forceShape(t));
  if (prevSign !== null && sg !== prevSign) signFlips++;
  prevSign = sg;
}
ok('dV/dtheta IS sin(theta) times the netting imbalance', worstNet < 1e-15, worstNet.toExponential(2));
ok('and the force law IS 2 P2(cos theta)', worstLeg < 1e-15, worstLeg.toExponential(2));
ok('the force law agrees with a numerical d/dL', worstForce < 1e-6, worstForce.toExponential(2));
ok('the actuator changes sign exactly once across the range', signFlips === 1, `${signFlips}`);
ok('it pulls below the angle', B.forceShape(0.6) > 0);
ok('it pushes above the angle', B.forceShape(1.3) < 0);
near('and does neither at it', B.forceShape(G.THETA_M), 0, 1e-15);

// the finger trap: pulling always narrows it
let monotone = true;
for (let i = 1; i <= 99; i++) {
  if (B.diameterFromLength(i / 100) >= B.diameterFromLength((i - 1) / 100)) monotone = false;
}
ok('pulling a sleeve longer always makes it thinner', monotone);

// the contraction table the page can print
for (const row of DATA.braid.contractionTable) {
  const t0 = (row.initialAngleDeg * Math.PI) / 180;
  near(`max contraction from ${row.initialAngleDeg} deg`, B.maxContraction(t0) * 100,
    row.maxContractionPct, 1e-6, '%');
}

// ── 5. the Legendre bridge ───────────────────────────────────────────────────
section('5. The Legendre bridge');
ok('sin^2 cos = (2/5)(P1 - P3) everywhere',
  DATA.legendre.worstShapeIdentityResidual < 1e-15,
  DATA.legendre.worstShapeIdentityResidual.toExponential(2));
ok("d/dx of (2/5)(P1 - P3) is -2 P2",
  DATA.legendre.worstDerivativeIdentityResidual < 1e-8,
  DATA.legendre.worstDerivativeIdentityResidual.toExponential(2));
near('P2 at the magic angle is zero', L.P[2](Math.cos(G.THETA_M)), 0, 1e-16);
near('P2 and P3 are orthogonal', DATA.legendre.orthogonality_2_3, 0, 1e-9);
near('and <P2,P2> is 2/(2n+1) = 0.4', DATA.legendre.orthogonality_2_2, 0.4, 1e-8);
ok('the recurrence reproduces the explicit P3', DATA.legendre.recurrenceAgrees < 1e-14);
// the identity P'_{n+1} - P'_{n-1} = (2n+1) P_n at n = 2, by finite difference
{
  let worst = 0;
  const h = 1e-6;
  for (let i = 0; i <= 500; i++) {
    const x = -0.99 + (1.98 * i) / 500;
    const dP3 = (L.P[3](x + h) - L.P[3](x - h)) / (2 * h);
    const dP1 = (L.P[1](x + h) - L.P[1](x - h)) / (2 * h);
    worst = Math.max(worst, Math.abs(dP3 - dP1 - 5 * L.P[2](x)));
  }
  ok("the standard identity P3' - P1' = 5 P2 holds", worst < 1e-8, worst.toExponential(2));
}

// ── 6. the metal ─────────────────────────────────────────────────────────────
section('6. The metal');
near('the zero-extension direction, in closed form', N.zeroExtensionAngle(0.5) * G.DEG, DEGM, 1e-15);
near('and by bisection, owing nothing to the algebra',
  N.zeroExtensionByBisection(0.5) * G.DEG, DEGM, 1e-12);
near('a line at the magic angle is not stretched at all', N.lineExtension(G.THETA_M, 0.5), 0, 1e-16);
ok('a line at 45 degrees IS stretched', N.lineExtension(Math.PI / 4, 0.5) > 0.2);
ok('an elastic Poisson ratio moves the angle a long way',
  Math.abs(N.zeroExtensionAngle(0.3) * G.DEG - DEGM) > 6,
  `${N.zeroExtensionAngle(0.3) * G.DEG}`);
near('the complementary angle is 35.26 degrees', 90 - DEGM, 35.264389682754654, 1e-12);
near("Clark and Cowey's dual: least fibre per unit volume, by scan",
  DATA.necking.leastFibreScanDeg, DEGM, 1e-4);

// ── 7. the rotor ─────────────────────────────────────────────────────────────
section('7. The rotor');
{
  let worstA = 0;
  for (let i = 0; i <= 1000; i++) {
    worstA = Math.max(worstA, Math.abs(MAS.rotorCoefficients(G.THETA_M, (Math.PI * i) / 1000).A));
  }
  ok('the rotor-period average vanishes at the magic angle for EVERY orientation',
    worstA < 1e-15, worstA.toExponential(2));
  // and does not, at a neighbouring angle
  let worstOff = 0;
  for (let i = 0; i <= 1000; i++) {
    worstOff = Math.max(worstOff, Math.abs(MAS.rotorCoefficients(G.THETA_M + 0.05, (Math.PI * i) / 1000).A));
  }
  ok('half a degree away it emphatically does not', worstOff > 0.05, worstOff.toExponential(2));
}
for (const [tr, bp, g] of [[0.4, 0.9, 0.7], [1.0, 0.2, 0], [1.4, 1.4, 5], [0.2, 2.8, 1]]) {
  const q = MAS.averageByQuadrature(tr, bp, g, 200_000);
  near(`quadrature = closed form at (${tr}, ${bp})`, q, MAS.rotorCoefficients(tr, bp).A, 1e-10);
  near(`closed form = P2 scaling at (${tr}, ${bp})`, MAS.rotorCoefficients(tr, bp).A,
    MAS.predictedAverage(tr, bp), 1e-15);
}
// The simulated static pattern spans -delta/2 to +delta, so 3 delta / 2 exactly.
// Measured at 5% of the peak it comes out slightly SHORT of that, and it should:
// the pattern's tall edge is at -delta/2 and its far shoulder at +delta carries
// much less intensity, so the last sliver of the span sits under the threshold.
// The check is therefore that the measurement is just under the closed form, not
// that it equals it. Anything over the closed form would be a real fault.
{
  const SP = DATA.rotor.simulation;
  const ratio = DATA.rotor.staticWidthHz / DATA.rotor.staticSpanClosedFormHz;
  ok('the static powder pattern spans just under 3 delta / 2',
    ratio > 0.99 && ratio <= 1.0, `ratio ${ratio.toFixed(5)}`);
  ok('and the closed-form span is 1.5 times the anisotropy',
    DATA.rotor.staticSpanClosedFormHz === 1.5 * SP.anisoHz);
  // the tall edge really is at -delta/2: recompute the peak position here
  const sp = MAS.powderSpectrum({ thetaRdeg: 0, spinHz: 0, ...SP });
  let peakAt = 0;
  let peak = -Infinity;
  for (let i = 0; i < sp.amp.length; i++) if (sp.amp[i] > peak) { peak = sp.amp[i]; peakAt = sp.freq[i]; }
  near('and the tall edge of the pattern sits at -delta/2',
    peakAt, -SP.anisoHz / 2, 3 * DATA.rotor.fftBinHz, ' Hz');
}
// the width really tracks |P2|
for (const row of DATA.rotor.sweep) {
  if (row.ratioOverP2 === null) continue;
  ok(`width/static tracks |P2| at ${row.angleDeg.toFixed(2)} deg (ratio ${row.ratioOverP2.toFixed(3)})`,
    row.ratioOverP2 > 0.98 && row.ratioOverP2 < 1.05, `${row.ratioOverP2}`);
}
ok('at the magic angle the residual width is the chosen line broadening and nothing more',
  Math.abs(DATA.rotor.magicWidthHz - DATA.rotor.lorentzianFloorHz) < 2 * DATA.rotor.fftBinHz,
  `${DATA.rotor.magicWidthHz} vs ${DATA.rotor.lorentzianFloorHz} Hz`);
ok('which is a collapse of more than a hundredfold',
  DATA.rotor.staticWidthHz / DATA.rotor.magicWidthHz > 100,
  `${(DATA.rotor.staticWidthHz / DATA.rotor.magicWidthHz).toFixed(0)}x`);
// the FFT itself, against a signal whose transform is known
{
  const n = 1024;
  const re = new Float64Array(n);
  const im = new Float64Array(n);
  for (let k = 0; k < n; k++) { re[k] = Math.cos((2 * Math.PI * 37 * k) / n); im[k] = Math.sin((2 * Math.PI * 37 * k) / n); }
  MAS.fft(re, im);
  let peak = 0;
  let at = -1;
  for (let k = 0; k < n; k++) { const mgn = Math.hypot(re[k], im[k]); if (mgn > peak) { peak = mgn; at = k; } }
  ok('the FFT puts a pure tone in the right bin', at === 37, `bin ${at}`);
  near('with the right amplitude', peak, n, 1e-6);
}

// ── 8. the shipped page ──────────────────────────────────────────────────────
section('8. The shipped page');
{
  const grab = (id) => {
    const mm = HTML.match(new RegExp(`<script id="${id}"[^>]*>([\\s\\S]*?)</script>`));
    return mm ? mm[1] : null;
  };
  const dataBlock = grab('aw-data');
  const engineBlock = grab('aw-engine');
  ok('the page carries a data block', !!dataBlock && dataBlock.trim().length > 100);
  ok('the page carries an engine block', !!engineBlock && engineBlock.trim().length > 1000);
  ok('the shipped data is exactly what build-page would ship now',
    dataBlock.trim() === JSON.stringify(BP.shippedData(DATA), null, 1).trim());
  ok('the shipped engine is byte-identical to the transform of the modules',
    engineBlock.trim() === BP.engineSource().trim());
  ok('the engine really is built from all five modules', BP.MODULES.length === 5, BP.MODULES.join(','));
  for (const mod of BP.MODULES) {
    const head = readFileSync(join(HERE, mod), 'utf8').split('\n')[0];
    ok(`${mod} is present in the inlined engine`, engineBlock.includes(head.replace('// ', '// ')));
  }
  ok('no module syntax survived the transform',
    !/^\s*(import|export)\s/m.test(engineBlock), 'an import or export leaked through');

  // head hygiene the loom asks for
  ok('canonical is set', HTML.includes('<link rel="canonical" href="https://artwaste.land/strata/every-direction-at-once/" />'));
  ok('JSON-LD is present', HTML.includes('"@type":"Article"'));
  ok('the way-out footer is present', HTML.includes('class="aw-wayout"'));
  ok('the home banner is mounted once', (HTML.match(/media\/home-banner\.js/g) || []).length === 1);
  // The page must END properly, and its last inline script must be CLOSED. The
  // house backfills (placard, plain card, nearby layers) append their own blocks
  // after the scripts, so this cannot demand they be adjacent.
  ok('the document closes', /<\/body>\s*<\/html>\s*$/.test(HTML));
  ok('every script tag is closed',
    (HTML.match(/<script\b/g) || []).length === (HTML.match(/<\/script>/g) || []).length,
    `${(HTML.match(/<script\b/g) || []).length} open, ${(HTML.match(/<\/script>/g) || []).length} closed`);
  ok('no em dash in the page', !HTML.includes(String.fromCharCode(0x2014)), 'found U+2014');

  // the prose must not out-claim the sources
  ok('the page attributes the prior survey', /Horgan and Murphy/.test(HTML));
  ok('the page names the Shadwick quote', /Shadwick/.test(HTML));
  ok('the page says the Gorter attribution is second-hand', /second-hand/.test(HTML));
  ok('the page says the McKibben story is reported, not established', /reported, not established/.test(HTML));
  ok('sources.json records what was deliberately left out', Array.isArray(SRC.notCited) && SRC.notCited.length >= 4);
  ok('every sources.json entry says whether it was read',
    ['priorArt', 'biology', 'actuators', 'engineering', 'resonance', 'plasticity']
      .every((k) => SRC[k].every((e) => typeof e.read === 'string' && e.read.length > 0)));
}

// ── 9. the browser ───────────────────────────────────────────────────────────
if (process.argv.includes('--no-browser')) {
  section('9. The browser: SKIPPED (--no-browser)');
} else {
  section('9. The browser');
  let chromium = null;
  try { ({ chromium } = await import('playwright')); } catch { /* reported below */ }
  if (!chromium) {
    console.log('  SKIP  playwright not installed (npm install --no-save playwright)');
  } else {
    const { existsSync } = await import('node:fs');
    const EXE = ['/opt/pw-browsers/chromium-1194/chrome-linux/chrome', '/opt/pw-browsers/chromium/chrome-linux/chrome']
      .find((p) => existsSync(p));
    const server = createServer((req, res) => {
      const p = join(R('public'), decodeURIComponent(req.url.split('?')[0]));
      const f = p.endsWith('/') ? join(p, 'index.html') : p;
      try {
        res.writeHead(200, { 'content-type': f.endsWith('.html') ? 'text/html' : 'application/octet-stream' });
        res.end(readFileSync(f));
      } catch { res.writeHead(404); res.end('no'); }
    });
    await new Promise((r) => server.listen(8244, r));
    const browser = await chromium.launch(EXE ? { executablePath: EXE } : {});
    const errs = [];
    for (const w of [390, 768, 1440]) {
      const page = await browser.newPage({ viewport: { width: w, height: 900 } });
      page.on('pageerror', (e) => errs.push(`${w}px: ${e.message}`));
      page.on('console', (msg) => { if (msg.type() === 'error') errs.push(`${w}px console: ${msg.text()}`); });
      await page.goto('http://127.0.0.1:8244/strata/every-direction-at-once/', { waitUntil: 'networkidle' });
      await page.waitForTimeout(600);
      const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
      ok(`no horizontal overflow at ${w}px`, over <= 1, `${over}px`);
      const rows = await page.$$eval('#sweepTbl tbody tr', (r) => r.length);
      ok(`the sweep table renders every row at ${w}px`, rows === DATA.rotor.sweep.length, `${rows}`);

      if (w === 1440) {
        // the engine in the reader's browser must reproduce the page's own claims
        const live = await page.evaluate(() => {
          const M = window.MAGIC;
          const RAD = Math.PI / 180;
          const sc = M.argmaxByScan ? null : undefined;
          return {
            angle: M.angleBetween([1, 1, 1], [0, 0, 1]),
            tet: M.angleBetween([1, 1, 1], [-1, -1, 1]),
            share: M.axialShareOfSquaredLength(M.THETA_M),
            fBelow: M.forceShape(30 * RAD),
            fAbove: M.forceShape(70 * RAD),
            fAt: M.forceShape(M.THETA_M),
            neck: M.zeroExtensionAngle(0.5) * M.DEG,
            p2: M.P2(Math.cos(M.THETA_M)),
            _sc: sc,
          };
        });
        near('the BROWSER computes the cube angle', live.angle, DEGM, 1e-12);
        near('the BROWSER computes the tetrahedral angle', live.tet, 2 * DEGM, 1e-12);
        near('the BROWSER gets the one-third share', live.share, 1 / 3, 1e-15);
        ok('the BROWSER agrees the muscle pulls below the angle', live.fBelow > 0);
        ok('the BROWSER agrees it pushes above the angle', live.fAbove < 0);
        near('and does neither at it', live.fAt, 0, 1e-15);
        near('the BROWSER finds the necking angle', live.neck, DEGM, 1e-12);
        near('and P2 is zero there', live.p2, 0, 1e-15);

        // the rotor instrument must actually collapse when moved to the angle
        const collapse = await page.evaluate((deg) => {
          const M = window.MAGIC;
          const OPT = { anisoHz: 10000, nBeta: 96, nGamma: 8, nT: 2048, swHz: 60000, lbHz: 150 };
          const STATIC_OPT = { anisoHz: 10000, nBeta: 512, nGamma: 1, nT: 2048, swHz: 60000, lbHz: 150 };
          const st = M.powderSpectrum(Object.assign({ thetaRdeg: 0, spinHz: 0 }, STATIC_OPT));
          // a smooth static powder has one tall edge and no comb: count local maxima
          let bumps = 0;
          for (let i = 1; i < st.amp.length - 1; i++) {
            if (st.amp[i] > 0.2 && st.amp[i] >= st.amp[i - 1] && st.amp[i] > st.amp[i + 1]) bumps++;
          }
          const mg = M.powderSpectrum(Object.assign({ thetaRdeg: deg, spinHz: 25000 }, OPT));
          const off = M.powderSpectrum(Object.assign({ thetaRdeg: 40, spinHz: 25000 }, OPT));
          return {
            staticW: M.widthAtFraction(st, 0.05),
            magicW: M.widthAtFraction(mg, 0.05),
            offW: M.widthAtFraction(off, 0.05),
            bumps,
          };
        }, DEGM);
        ok('the BROWSER static pattern is about 15 kHz wide',
          Math.abs(collapse.staticW - 15000) < 900, `${collapse.staticW.toFixed(0)} Hz`);
        ok('the BROWSER collapses it more than tenfold at the magic angle',
          collapse.staticW / collapse.magicW > 10,
          `${collapse.staticW.toFixed(0)} -> ${collapse.magicW.toFixed(0)} Hz`);
        ok('the BROWSER static powder is one smooth edge, not a comb of grid artefacts',
          collapse.bumps <= 2, `${collapse.bumps} local maxima above 20% of peak`);
        ok('the BROWSER brings it back, scaled, off the angle',
          collapse.offW > 3 * collapse.magicW && collapse.offW < collapse.staticW,
          `${collapse.offW.toFixed(0)} Hz`);

        // the instruments respond to a reader
        await page.fill('#bTheta', '30').catch(() => {});
        await page.$eval('#bTheta', (el) => { el.value = '30'; el.dispatchEvent(new Event('input')); });
        await page.waitForTimeout(150);
        const below = await page.textContent('#braidOut');
        ok('below the angle the braid readout says it shortens', /shortens/.test(below), below.slice(0, 120));
        await page.$eval('#bTheta', (el) => { el.value = '75'; el.dispatchEvent(new Event('input')); });
        await page.waitForTimeout(150);
        const above = await page.textContent('#braidOut');
        ok('above the angle it says it lengthens', /lengthens/.test(above), above.slice(0, 120));

        await page.click('#rMagic');
        await page.waitForTimeout(400);
        const rot = await page.textContent('#rotOut');
        ok('the rotor readout announces the anisotropy is gone', /anisotropy is gone/.test(rot), rot.slice(0, 140));

        await page.$eval('#nPoisson', (el) => { el.value = '0.3'; el.dispatchEvent(new Event('input')); });
        await page.waitForTimeout(150);
        const neck = await page.textContent('#neckOut');
        ok('the necking readout moves the angle off 54.74 when nu leaves one half',
          /The metal never mattered/.test(neck), neck.slice(0, 140));

        // the hero number is the computed one, not a typed one
        const hero = await page.textContent('#heroNum');
        ok('the hero number is printed from the data block',
          hero.startsWith('54.735610317245'), hero);
      }
      await page.close();
    }
    await browser.close();
    await new Promise((r) => server.close(r));
    ok('no JavaScript errors in any viewport', errs.length === 0, errs.join(' | '));
  }
}

console.log(`\n${pass}/${pass + fail} checks pass`);
process.exit(fail ? 1 : 0);
