// verify.mjs — the physics behind the stratum
// "The Drop That Shatters Itself" (/strata/the-drop-that-shatters-itself/).
//
// A Prince Rupert's drop survives a hammer blow on its bulbous head but bursts
// into powder when its thin tail is snipped. The cause is a real, frozen-in
// stress field: a surface layer in COMPRESSION of up to ~700 MPa (≈525 MPa on
// the head, up to ~700 MPa on the tail) balancing a TENSILE core. A crack that
// reaches the tension field runs and bifurcates within the measured soda-lime
// fracture-front speed range of 1,450–1,900 m/s.
//
// SOURCES for the asserted numbers:
//   [1] Aben, Anton, Õis, Viswanathan, Chandrasekar & Chaudhri,
//       "On the extraordinary strength of Prince Rupert's drops,"
//       Appl. Phys. Lett. 109, 231903 (2016).
//       → surface compression ≈525 MPa (head), up to ~700 MPa (tail),
//         by integrated (3-D) photoelasticity with a red-LED polariscope.
//   [2] Chandrasekar & Chaudhri, "The explosive disintegration of Prince
//       Rupert's drops," Phil. Mag. B 70(6), 1195–1218 (1994), high-speed photog.
//       → measured fracture-front speed range 1,450–1,900 m/s, with branching.
//   [3] Sundaram & Tippur, "Dynamic fracture of soda-lime glass," JMPS (2018),
//       and terminal-crack-velocity literature.
//       → soda-lime longitudinal wave ≈5,400 m/s; cracks seldom exceed ~0.6·Rayleigh,
//         with instability possible above ~0.4·Rayleigh. No universal branching threshold.
//   [4] Janusonis et al., "Ultrafast magnetoelastic probing of surface acoustic
//       transients," Physical Review B 94, 024415 (2016), p. 024415-3.
//       https://pure.mpg.de/rest/items/item_2321440_5/component/file_2323036/content
//       → soda-lime Rayleigh wave ≈3,100 m/s.
//   [5] Chaudhri, "Self-Sustained Fracture Waves in Soda-Lime Glass,"
//       Materials Science Forum 662, 95–104 (2010).
//       https://doi.org/10.4028/www.scientific.net/MSF.662.95
//       → fracture-wave speed ~1,700±100 m/s (soda-lime), preliminary
//         ~1,300±100 m/s (lead glass); lead longitudinal sound 4,800 m/s.
//   Handbook (representative, named on the page): stress-optic coefficient
//   C ≈ 2.6e-12 Pa^-1, red light λ = 630 nm, Young's modulus E ≈ 70 GPa,
//   fracture toughness K_Ic ≈ 0.75 MPa·m^0.5 for soda-lime glass.
//
// This script checks selected arithmetic and key figures in the shipped HTML,
// then executes the inline controls in a simulated DOM. It does not validate every
// prose occurrence, render the canvas, or independently validate the source measurements.
//
//   run:  node research/the-drop-that-shatters-itself/verify.mjs
//
// No dependencies; node: builtins only.

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

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── sourced constants (identical to the page's inline script) ───────────────
const MPS_TO_MPH = 2.2369362920544;
const C_AIR      = 343;      // speed of sound in air, m/s (20 C)
const C_RAYLEIGH = 3100;     // Rayleigh (surface) wave, soda-lime glass, m/s  [4]
const C_LONG     = 5400;     // longitudinal (sound) wave, soda-lime glass, m/s [3]
const RAY_CAP    = 0.6;      // approximate speed ceiling, not a branching threshold [3]
const C_LEAD_LONG = 4800;    // lead-glass longitudinal sound, m/s [5]
const V_LO       = 1450;     // crack-front / bifurcation velocity band, m/s      [2]
const V_HI       = 1900;
const V_DEF      = 1700;     // page default
const SIG_HEAD   = 525e6;    // surface compression, head, Pa                     [1]
const SIG_TAIL   = 700e6;    // surface compression, tail, Pa                     [1]
const C_OPTIC    = 2.6e-12;  // relative stress-optic coefficient, Pa^-1 (soda-lime)
const LAMBDA     = 630e-9;   // red LED wavelength, m
const E_GLASS    = 70e9;     // Young's modulus of soda-lime glass, Pa
const KIC        = 0.75e6;   // fracture toughness, Pa·m^0.5
const GC         = KIC * KIC / E_GLASS;            // fracture energy, J/m^2
const GLASS_WAVE = { soda: 1700, lead: 1300 };     // fracture-wave speed by comp.  [5]

// ── derived quantities (mirror the page functions exactly) ──────────────────
const traverseUs   = (Lmm, v) => (Lmm / 1000) / v * 1e6;
const machAir      = (v) => v / C_AIR;
const fracRayleigh = (v) => v / C_RAYLEIGH;
const fracLong     = (v) => v / C_LONG;
const energyDens   = (sig) => sig * sig / (2 * E_GLASS);
const fringeOrder  = (sig, dM) => C_OPTIC * dM * sig / LAMBDA;
const surfPerVol   = (sig) => energyDens(sig) / GC;

// ── 1. crack-front speed → mph, and the "faster than sound" claim ───────────
console.log('\n— the crack front: fast vs AIR, subsonic in GLASS —');
{
  const mphLo = V_LO * MPS_TO_MPH, mphHi = V_HI * MPS_TO_MPH;
  ok(`1,450 m/s ≈ ${Math.round(mphLo)} mph`, approx(Math.round(mphLo), 3244, 0), `(source: ≈3,200 mph)`);
  ok(`1,900 m/s ≈ ${Math.round(mphHi)} mph`, approx(Math.round(mphHi), 4250, 0), `(source: ≈4,300 mph)`);
  ok('whole band lands in the source range ≈3,200–4,300 mph',
     Math.round(mphLo) >= 3200 && Math.round(mphLo) <= 3300 &&
     Math.round(mphHi) >= 4200 && Math.round(mphHi) <= 4300);

  // Mach vs air across the band
  ok(`Mach vs air: ${machAir(V_LO).toFixed(1)}–${machAir(V_HI).toFixed(1)} (supersonic in air)`,
     machAir(V_LO) > 4 && machAir(V_HI) > 5 && machAir(V_HI) < 6,
     `default 1700 → Mach ${machAir(V_DEF).toFixed(2)}`);

  // fraction of Rayleigh across the band; the 0.6 comparison is approximate
  ok(`v/Rayleigh: ${fracRayleigh(V_LO).toFixed(2)}–${fracRayleigh(V_HI).toFixed(2)} — SUBSONIC in glass`,
     fracRayleigh(V_LO) > 0 && fracRayleigh(V_HI) < 1,
     `approximate comparison 0.6·${C_RAYLEIGH}=${RAY_CAP * C_RAYLEIGH} m/s`);
  ok('0.6 times Rayleigh is 1,860 m/s, below the measured upper endpoint; not a strict bound',
     RAY_CAP * C_RAYLEIGH === 1860 && V_HI > RAY_CAP * C_RAYLEIGH);
  ok('the soda-lime band is subsonic against longitudinal sound', fracLong(V_HI) < 1);
  ok(`v/longitudinal at default: ${fracLong(V_DEF).toFixed(2)} (well below 1)`,
     approx(fracLong(V_DEF), 0.315, 0.005));
  ok('the front is faster than sound in AIR yet slower than sound in GLASS',
     machAir(V_DEF) > 1 && fracLong(V_DEF) < 1 && fracRayleigh(V_DEF) < 1);
}

// ── 2. default formula line: t = L/v at L=40 mm, v=1700 ─────────────────────
console.log('\n— default formula line (L = 40 mm, v = 1700 m/s) —');
{
  ok(`t = 0.040/1700 = ${traverseUs(40, V_DEF).toFixed(1)} µs`, approx(traverseUs(40, V_DEF), 23.5, 0.05));
  ok(`v/c_air = 1700/343 = ${machAir(V_DEF).toFixed(2)}`, approx(machAir(V_DEF), 4.96, 0.005));
  ok(`v/c_Rayleigh = 1700/3100 = ${fracRayleigh(V_DEF).toFixed(2)}`, approx(fracRayleigh(V_DEF), 0.55, 0.005));
  // range of traverse times shown as the length slider moves
  ok(`traverse range 30–70 mm at 1700 m/s: ${traverseUs(30, V_DEF).toFixed(1)}–${traverseUs(70, V_DEF).toFixed(1)} µs`,
     approx(traverseUs(30, V_DEF), 17.6, 0.1) && approx(traverseUs(70, V_DEF), 41.2, 0.1));
}

// ── 3. Layer 2a: uniform-path stress-optic arithmetic, separate from the drawing ───────────────
console.log('\nStress-optic law N = C·d·Δσ/λ (illustrative calculation)');
{
  const Nhead = fringeOrder(SIG_HEAD, 1e-3);
  const Ntail = fringeOrder(SIG_TAIL, 1e-3);
  ok(`700 MPa over 1 mm → ${Ntail.toFixed(2)} fringes`, approx(Ntail, 2.89, 0.01));
  ok(`525 MPa over 1 mm → ${Nhead.toFixed(2)} fringes`, approx(Nhead, 2.17, 0.01));
  // round-trip: fringe order back to stress must return the input
  const back = Ntail * LAMBDA / (C_OPTIC * 1e-3);
  ok('round-trip N → Δσ recovers 700 MPa', approx(back, SIG_TAIL, 1), `${(back / 1e6).toFixed(1)} MPa`);
  ok('a few fringes across ~1 mm already implies hundreds of MPa',
     Ntail > 2 && Ntail < 4 && back > 500e6);
}

// ── 4. Layer 2b: stored strain energy and the "why it powders" balance ──────
console.log('\n— stored energy u = σ²/2E, and new fracture surface u/G꜀ —');
{
  ok(`G꜀ = K_Ic²/E = ${GC.toFixed(2)} J/m² (≈8)`, approx(GC, 8.04, 0.05));
  const uHead = energyDens(SIG_HEAD), uTail = energyDens(SIG_TAIL);
  ok(`u(700 MPa) = ${(uTail / 1e6).toFixed(2)} MJ/m³`, approx(uTail / 1e6, 3.50, 0.01));
  ok(`u(525 MPa) = ${(uHead / 1e6).toFixed(2)} MJ/m³`, approx(uHead / 1e6, 1.97, 0.01));
  const sv = surfPerVol(SIG_TAIL);
  ok(`u/G꜀ = ${(sv / 1e6).toFixed(2)} m² of new surface per cm³`, approx(sv / 1e6, 0.44, 0.005),
     `= ${Math.round(sv).toLocaleString('en-US')} m²/m³`);
  ok('uniform uniaxial energy estimate scales as the square of the stress',
     approx(energyDens(SIG_HEAD) / energyDens(SIG_TAIL), (SIG_HEAD / SIG_TAIL) ** 2, 1e-12));
}

// ── 5. composition dependence of the fracture-wave speed ────────────────────
console.log('\nFracture-wave speed depends on composition [Chaudhri 2010]');
{
  ok('soda-lime ≈ 1,700 ± 100 m/s', GLASS_WAVE.soda === 1700);
  ok('lead glass ≈ 1,300 ± 100 m/s (slower)', GLASS_WAVE.lead === 1300 && GLASS_WAVE.lead < GLASS_WAVE.soda);
}

// ── 6. read the shipped HTML and assert the SAME key figures appear ─────────
console.log('\n— the shipped page contains the same key figures —');
{
  const here = dirname(fileURLToPath(import.meta.url));
  const htmlPath = join(here, '..', '..', 'public', 'strata', 'the-drop-that-shatters-itself', 'index.html');
  let html = '';
  try { html = readFileSync(htmlPath, 'utf8'); }
  catch (e) { ok('index.html is readable', false, String(e)); }
  const has = (s) => html.includes(s);

  // the two headline, sourced figures
  ok('page states head compression 525 MPa', has('525 MPa'));
  ok('page states tail compression 700 MPa', has('700 MPa'));
  ok('page states measured interior tension ~300–400 MPa (Aben 2016)', has('300–400 MPa'));
  ok('page states crack band 1,450–1,900 m/s', has('1,450–1,900 m/s'));
  // the load-bearing "subsonic in glass" correction
  ok('page states air = 343 m/s', has('343'));
  ok('page states soda-lime Rayleigh ≈ 3,100 m/s and uses it in the script',
     has('≈3,100 m/s') && /var C_RAYLEIGH\s*=\s*3100;/.test(html));
  ok('page states longitudinal ≈ 5,400 m/s', has('5,400') || has('5400'));
  ok('page states the approximate 0.6-times comparison (~1,860 m/s)', has('1,860') && has('approximate ceiling'));
  // the default formula-line numbers (static in the HTML)
  ok('page shows default t = 23.5 µs', has('23.5 µs'));
  ok('page shows default v/c_air = 4.96', has('4.96'));
  ok('static formula uses 1700/3100 = 0.55 for soda-lime',
     /id="formula-line"[^>]*>\s*t =[^<]*1700\/3100 = 0\.55/.test(html));
  // layer 2 constants and results
  ok('page shows stress-optic C ≈ 2.6×10⁻¹²', has('2.6'));
  ok('page shows red light λ = 630 nm', has('630 nm'));
  ok('page shows E ≈ 70 GPa', has('70 GPa'));
  ok('page shows G꜀ ≈ 8 J/m² and K_Ic ≈ 0.75 MPa', has('8 J/m²') && has('0.75 MPa'));
  ok('page shows 0.44 m² of new surface per cm³', has('0.44 m²'));
  // composition
  ok('page shows soda-lime ≈1,700 and lead ≈1,300 m/s', has('1,700') && has('1,300'));
  // the corrected history (Rupert did NOT invent them)
  ok('page dates: brought to England 1660', has('1660'));
  ok('page dates: Royal Society 1661', has('1661'));
  ok('page dates: Micrographia 1665', has('1665'));
  ok('page names the attribution correction (not invented by Rupert)',
     /did\s+<em>not<\/em>\s+invent|did not invent/i.test(html));
  // the refused conflations / unverified figure
  ok('page refuses the Gorilla-Glass "same process" conflation', /chemically/i.test(html) && has('ion exchange'));
  ok('page qualifies traditional side/rear tempering and laminated alternatives',
     has('windows have traditionally used thermally tempered glass') && has('some use laminated glass instead'));
  ok('page flags the uncited 664.3 kN figure', has('664.3'));
  // sources present
  ok('page cites Aben et al. 2016 (APL 109, 231903)', has('231903') && has('Aben'));
  ok('page cites Chandrasekar & Chaudhri 1994', has('Chandrasekar') && has('1994'));
  ok('page cites Chaudhri 2010 for composition and Janusonis 2016 for Rayleigh speed',
     has('10.4028/www.scientific.net/MSF.662.95') && has('024415-3'));
  // load-bearing closing tags
  ok('closing </script></body></html> present', /<\/script>\s*<\/body>\s*<\/html>/.test(html));
  // Execute the actual inline controls without rendering images or claiming browser coverage.
  console.log('\nSelected runtime behavior in a simulated DOM');
  const inline = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)]
    .map(m => m[1]).find(s => s.includes('function updateReadouts'));
  function loadPage(reduce) {
    const elements = new Map();
    let nextFrame = null;
    function el(id) {
      if (!elements.has(id)) {
        const tag = html.match(new RegExp('<input id="' + id + '"[^>]*>'))?.[0] || '';
        const attribute = name => tag.match(new RegExp(name + '="([^"]*)"'))?.[1] || '';
        elements.set(id, {
          textContent: '', innerHTML: '', value: attribute('value'), min: attribute('min'), max: attribute('max'),
          handlers: {}, clientWidth: 700,
          addEventListener(name, fn) { this.handlers[name] = fn; },
          setAttribute() {}, removeAttribute() {}, getContext() { return null; },
          click() { this.handlers.click?.({}); }
        });
      }
      return elements.get(id);
    }
    const radios = ['soda', 'lead'].map(value => ({ ...el(value), value, checked: value === 'soda' }));
    const document = { getElementById: el, querySelector: el, getElementsByName: () => radios, addEventListener() {} };
    const window = { matchMedia: () => ({ matches: reduce }), addEventListener() {}, devicePixelRatio: 1 };
    runInNewContext(inline, {
      document, window,
      requestAnimationFrame(fn) { nextFrame = fn; return 1; },
      cancelAnimationFrame() { nextFrame = null; }
    }, { timeout: 2000 });
    return {
      el,
      select(value) {
        radios.forEach(r => { r.checked = r.value === value; });
        radios.find(r => r.checked).handlers.change();
      },
      input(id, value) { el(id).value = String(value); el(id).handlers.input(); },
      tick(now) { const fn = nextFrame; nextFrame = null; fn(now); }
    };
  }
  try {
    const page = loadPage(true);
    ok('default runtime: 1700 m/s, 23.5 microseconds, soda-lime Rayleigh ratio 0.55',
      page.el('ro-speed').textContent === '1,700 m/s' &&
      page.el('formula-line').textContent.includes('23.5 µs') &&
      page.el('formula-line').textContent.includes('1700/3100 = 0.55'));
    page.select('lead');
    ok('selecting lead sets 1300 m/s and the 1200 to 1400 m/s slider range',
      page.el('ro-speed').textContent === '1,300 m/s' && +page.el('vel').value === 1300 &&
      +page.el('vel').min === 1200 && +page.el('vel').max === 1400 &&
      page.el('vel-now').textContent === '1,300 m/s');
    ok('lead at 40 mm: 30.8 microseconds and its 4800 m/s longitudinal sound reference',
      page.el('formula-line').textContent.includes('30.8 µs') &&
      page.el('formula-line').textContent.includes('1300/4800 = 0.27') &&
      page.el('ro-mach-sub').textContent.includes('lead glass') &&
      !page.el('formula-line').textContent.includes('Rayleigh'));
    for (const v of [1200, 1400]) {
      page.input('vel', v);
      ok(`lead endpoint ${v} m/s: traversal and sound comparison update`,
        page.el('formula-line').textContent.includes(`${traverseUs(40, v).toFixed(1)} µs`) &&
        page.el('formula-line').textContent.includes(`${v}/4800 = ${(v / C_LEAD_LONG).toFixed(2)}`));
    }
    page.select('lead');
    page.input('len', 70);
    ok('length control uses selected lead speed: 70 mm / 1300 m/s = 53.8 microseconds',
      page.el('formula-line').textContent.includes('53.8 µs'));
    page.el('btn-tail').click();
    ok('tail readout reports repeated branching without a speed threshold',
      page.el('ro-event-sub').innerHTML.includes('70.0 mm of 70 mm') &&
      page.el('ro-event-sub').innerHTML.includes('53.8 µs · repeated branching') &&
      !page.el('ro-event-sub').innerHTML.includes('0.6'));
    page.select('soda');
    ok('returning to soda-lime restores 1700 m/s and the 1450 to 1900 m/s range',
      +page.el('vel').value === 1700 && +page.el('vel').min === 1450 && +page.el('vel').max === 1900 &&
      page.el('vel-hint').textContent.includes('within that range'));
    for (const v of [1450, 1900]) {
      page.input('vel', v);
      ok(`soda-lime endpoint ${v} m/s: runtime Rayleigh ratio ${(v / C_RAYLEIGH).toFixed(2)}`,
        page.el('formula-line').textContent.includes(`${v}/3100 = ${(v / C_RAYLEIGH).toFixed(2)}`));
    }
    page.input('path', 2);
    ok('the separate optical calculation doubles fringe order at twice the path',
      page.el('optic-line').textContent.includes('N = 5.78') &&
      page.el('optic-line').textContent.includes('Δσ = 700 MPa'));
    const animation = loadPage(false);
    animation.el('btn-tail').click();
    animation.tick(0);
    animation.tick(375);
    const quarter = animation.el('ro-event-sub').innerHTML;
    animation.tick(750);
    const half = animation.el('ro-event-sub').innerHTML;
    animation.tick(1500);
    ok('animation uses elapsed time with steady progress at quarter, half and full duration',
      quarter.includes('front at 10.0 mm') && half.includes('front at 20.0 mm') &&
      animation.el('ro-event-sub').innerHTML.includes('front at 40.0 mm') &&
      animation.el('ro-event').textContent === 'disintegrated into powder');
  } catch (e) {
    ok('inline controls execute in the simulated DOM', false, String(e));
  }

}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
