// verify.mjs — the check behind "Is Fire a Plasma?"
//
// The page rests on three checkable physics claims, all recomputed here from
// first principles and standard constants — nothing is asserted by hand:
//
//   (1) IONIZATION.  Thermal (Saha) ionization of a gas at candle-flame
//       temperature is negligible. Even the easiest-to-ionize common atoms
//       barely ionize; the bulk flame gases do not at all. So a flame's tiny
//       ion population (measured ~10^-8..10^-7 fraction) cannot be thermal —
//       it comes from CHEMI-ionization (a chemical route), and 10^-7 is a
//       HUNDRED THOUSAND times below the page's own 1% ionization yardstick
//       (claims pass 2026-10-13: no cited source draws a 1% plasma line; neon and
//       fluorescent tubes are plasmas far below it, Britannica)
//       (1e-2 / 1e-7 = 1e5). => not a plasma. (Label corrected 2026-08-01: this
//       comment and the check below both said "a million" while the assertion
//       they describe printed 1e5, and the page had inherited the wrong word.)
//   (2) THE YELLOW.  The luminous glow is INCANDESCENCE: a Planck (black-body)
//       spectrum from hot soot at ~1200 C. Its Wien peak and perceived colour
//       are recomputed here and must match the page.
//   (3) THE BLUE.  CH* emits blue light near 430 nm by CHEMILUMINESCENCE.
//       The cited OH* band near 310 nm is ultraviolet, not visible blue.
//       See Nori and Seitzman (2007), pp. 2, 4:
//       https://seitzman.gatech.edu/AIAA-2007-0466.pdf
//
// Run: node research/is-fire-a-plasma/verify.mjs
//
// Sources (see the page apparatus for the full list):
//   - Saha ionization equation (statistical mechanics; e.g. NIST ASD for chi).
//   - Calcote & King, and Fialkov, "Investigations on ions in flames" — flame
//     chemi-ionization CH+O->CHO(+)+e-, dominant ion H3O+, n_i/N ~ 1e-8..1e-7,
//     n_e ~ 1e11..1e12 /cm^3 in the reaction zone.
//   - Britannica "plasma": plasmas exist in neon and fluorescent tubes, whose
//     "degree of ionization ... is usually low"; it gives no 1% figure. The 1%
//     yardstick is the page's own choice.
//   - Candle soot incandescence: Nature Sci. Rep. 10:11364 (2020) (the ~1200 C
//     soot temperature is this page's assumed value; that paper does not state it),
//     laser-induced incandescence sizing of candle soot; candle-flame zone temps.
//   - Wyman, Sloan & Shirley (2013), "Simple Analytic Approximations to the CIE
//     XYZ Color Matching Functions", JCGT 2(2) — the CMF fit used for the colour.
//   - Emission bands: OH* ~306-310 nm, CH* ~430 nm (420-440), C2* Swan ~473/516/563 nm.

let pass = 0, fail = 0;
const checks = [];
function ok(name, cond, detail) {
  (cond ? pass++ : fail++);
  checks.push({ name, cond: !!cond, detail });
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  — ' + detail : ''}`);
}
const approx = (a, b, rel) => Math.abs(a - b) <= rel * Math.abs(b);

// ── CODATA constants ────────────────────────────────────────────────────────
const ME  = 9.1093837015e-31;   // electron mass, kg
const KB  = 1.380649e-23;       // Boltzmann, J/K
const H   = 6.62607015e-34;     // Planck, J s
const C   = 2.99792458e8;       // speed of light, m/s
const EV  = 1.602176634e-19;    // J per eV
const ATM = 101325;             // Pa
const WIEN_B = 2.897771955e-3;  // Wien displacement constant, m K

// First ionization energies (eV), NIST Atomic Spectra Database.
const SPECIES = {
  H:  { chi: 13.598434, g: 1, label: 'hydrogen (bulk-fuel proxy)' },
  Na: { chi: 5.139077,  g: 1, label: 'sodium (a pinch of salt)' },
  K:  { chi: 4.340664,  g: 1, label: 'potassium' },
  Cs: { chi: 3.893905,  g: 1, label: 'caesium (easiest common atom)' },
  N2: { chi: 15.581,    g: 1, label: 'nitrogen N2 (the air itself)' }, // molecular; g=1 order-of-mag only
};

// ── (1) Saha ionization fraction ────────────────────────────────────────────
// Single ionization in thermal equilibrium:
//   n_i n_e / n_0 = g (2 pi m_e k T / h^2)^{3/2} exp(-chi/kT),  g = 2 Z_i/Z_0.
// With n_e = n_i = x N and n_0 = (1-x) N and heavy density N = P/(kT):
//   x^2/(1-x) = S,  S = [ g (2 pi m_e k T / h^2)^{3/2} exp(-chi/kT) ] / N.
// (This SAME function is reimplemented verbatim in the page.)
function sahaFraction(T, chi_eV, g = 1, P = ATM) {
  const N = P / (KB * T);                                   // heavy-particle density, /m^3
  const quantum = Math.pow(2 * Math.PI * ME * KB * T / (H * H), 1.5); // /m^3
  const S = g * quantum * Math.exp(-(chi_eV * EV) / (KB * T)) / N;
  return (-S + Math.sqrt(S * S + 4 * S)) / 2;               // the physical root in [0,1]
}

// self-consistency: the quadratic root satisfies x^2/(1-x) = S
{
  const T = 3000, chi = 5.139077;
  const N = ATM / (KB * T);
  const S = SPECIES.Na.g * Math.pow(2 * Math.PI * ME * KB * T / (H * H), 1.5)
            * Math.exp(-(chi * EV) / (KB * T)) / N;
  const x = sahaFraction(T, chi);
  ok('Saha root solves x^2/(1-x)=S', approx(x * x / (1 - x), S, 1e-9),
     `x=${x.toExponential(3)}`);
}

// candle luminous zone ~1200 C = 1473 K; blue veil ~1400 C = 1673 K.
const T_CANDLE = 1473;
const T_BLUE   = 1673;

const xNa_candle = sahaFraction(T_CANDLE, SPECIES.Na.chi);
const xN2_candle = sahaFraction(T_CANDLE, SPECIES.N2.chi);
ok('bulk air (N2) is thermally un-ionized at flame temp (far below 1e-15)',
   xN2_candle < 1e-20, `x(N2,${T_CANDLE}K)=${xN2_candle.toExponential(2)}`);
ok('even sodium barely thermally ionizes at flame temp (< 1e-5)',
   xNa_candle < 1e-5, `x(Na,${T_CANDLE}K)=${xNa_candle.toExponential(2)}`);

// The measured flame ion fraction (chemi-ionization, NOT thermal): ~1e-8..1e-7.
// It must sit far above the bulk thermal value (so it can't be thermal) and far
// below the 1% yardstick.
const CHEMI_ION_FRACTION = 1e-7;         // representative measured value
const PLASMA_LINE = 1e-2;                // the page's own 1% yardstick (no cited source draws it)
ok('measured chemi-ion fraction >> bulk thermal (so not thermal in origin)',
   CHEMI_ION_FRACTION > 1e6 * xN2_candle, `chemi≈${CHEMI_ION_FRACTION} vs thermal≈${xN2_candle.toExponential(1)}`);
ok('measured chemi-ion fraction is ~1e5x below the 1% yardstick',
   CHEMI_ION_FRACTION < PLASMA_LINE / 1e4,
   `chemi≈1e-7, yardstick=${PLASMA_LINE} (ratio ${(PLASMA_LINE/CHEMI_ION_FRACTION).toExponential(0)})`);

// electron density at 1e-7 fraction, 1 atm, flame T -> ~1e11 /cm^3 (matches lit.)
{
  const N_cm3 = (ATM / (KB * T_BLUE)) / 1e6;       // heavy density per cm^3
  const ne = CHEMI_ION_FRACTION * N_cm3;
  ok('n_e at 1e-7 fraction lands in the measured 1e11..1e12 /cm^3 band',
     ne > 1e10 && ne < 1e13, `n_e≈${ne.toExponential(2)} /cm^3 (N=${N_cm3.toExponential(2)})`);
}

// The temperature at which THERMAL ionization would reach the 1% yardstick
// (monotonic in T, so a simple bisection converges).
function tempForPlasma(chi_eV, g = 1, target = PLASMA_LINE) {
  let lo = 500, hi = 60000;
  for (let i = 0; i < 200; i++) {
    const mid = 0.5 * (lo + hi);
    if (sahaFraction(mid, chi_eV, g) < target) lo = mid; else hi = mid;
  }
  return 0.5 * (lo + hi);
}
const T1_Na = tempForPlasma(SPECIES.Na.chi, 1);
const T1_N2 = tempForPlasma(SPECIES.N2.chi, 1);
ok('sodium needs thousands of K (well above any flame) to reach 1% ionized',
   T1_Na > 3000 && T1_Na < 8000, `T(Na->1%)≈${Math.round(T1_Na)} K`);
ok('air (N2) needs many thousands of K to reach 1% ionized',
   T1_N2 > 8000, `T(N2->1%)≈${Math.round(T1_N2)} K`);
// Added in the claims pass of 2026-10-13, for the page's caesium sentence: heat
// ionizes caesium at the candle temperature by about 1e-6 (the page used to say
// 1e-7), and caesium crosses 1% a little above 3,100 K, not thousands of K above
// every flame.
const xCs_candle = sahaFraction(T_CANDLE, SPECIES.Cs.chi);
const T1_Cs = tempForPlasma(SPECIES.Cs.chi, 1);
ok('caesium at the candle temperature is ionized ~1e-6 (between 5e-7 and 5e-6)',
   xCs_candle > 5e-7 && xCs_candle < 5e-6, `x(Cs,${T_CANDLE}K)=${xCs_candle.toExponential(2)}`);
ok('caesium reaches 1% ionized just over 3,100 K',
   T1_Cs > 3100 && T1_Cs < 3200, `T(Cs->1%)≈${Math.round(T1_Cs)} K`);

// ── (2) Incandescence: Planck spectrum, Wien peak, black-body colour ─────────
// Planck spectral radiance per wavelength (W m^-3 sr^-1), lambda in metres.
function planck(lambda, T) {
  const a = 2 * H * C * C / Math.pow(lambda, 5);
  const b = Math.exp(H * C / (lambda * KB * T)) - 1;
  return a / b;
}
// Wien peak (numeric max of Planck) must equal b/T.
function wienPeakNumeric(T) {
  let best = 0, bestL = 0;
  for (let nm = 100; nm <= 20000; nm += 1) {
    const v = planck(nm * 1e-9, T);
    if (v > best) { best = v; bestL = nm; }
  }
  return bestL; // nm
}
for (const T of [1000, 1473, 2000, 2856, 5778]) {
  const analytic = WIEN_B / T * 1e9;      // nm
  const numeric = wienPeakNumeric(T);
  ok(`Wien peak at ${T}K: numeric max matches b/T (${analytic.toFixed(0)} nm)`,
     Math.abs(numeric - analytic) <= 2, `numeric=${numeric} nm`);
}
// The candle's yellow soot peaks deep in the infrared; only the visible TAIL is
// what we see — the honest reason a 1200 C body looks dim-yellow, not "white".
{
  const peak = WIEN_B / T_CANDLE * 1e9;
  ok('candle soot (1200 C) Wien peak is in the infrared (>1500 nm)',
     peak > 1500, `${peak.toFixed(0)} nm`);
}

// Black-body perceived colour via Wyman/Sloan/Shirley (2013) CIE-XYZ CMF fit.
function gauss(x, mu, s1, s2) { const t = (x - mu) / (x < mu ? s1 : s2); return Math.exp(-0.5 * t * t); }
function cmf(lnm) {
  const X = 1.056 * gauss(lnm, 599.8, 37.9, 31.0) + 0.362 * gauss(lnm, 442.0, 16.0, 26.7) - 0.065 * gauss(lnm, 501.1, 20.4, 26.2);
  const Y = 0.821 * gauss(lnm, 568.8, 46.9, 40.5) + 0.286 * gauss(lnm, 530.9, 16.3, 31.1);
  const Z = 1.217 * gauss(lnm, 437.0, 11.8, 36.0) + 0.681 * gauss(lnm, 459.0, 26.0, 13.8);
  return [X, Y, Z];
}
function blackbodyRGB(T) {
  let X = 0, Y = 0, Z = 0;
  for (let nm = 360; nm <= 830; nm += 1) {
    const I = planck(nm * 1e-9, T);
    const [cx, cy, cz] = cmf(nm);
    X += I * cx; Y += I * cy; Z += I * cz;
  }
  const s = X + Y + Z; X /= s; Y /= s; Z /= s;                 // chromaticity
  // XYZ -> linear sRGB (D65)
  let r =  3.2406 * X - 1.5372 * Y - 0.4986 * Z;
  let g = -0.9689 * X + 1.8758 * Y + 0.0415 * Z;
  let b =  0.0557 * X - 0.2040 * Y + 1.0570 * Z;
  r = Math.max(0, r); g = Math.max(0, g); b = Math.max(0, b);
  const m = Math.max(r, g, b) || 1; r /= m; g /= m; b /= m;    // normalise to a hue
  const enc = v => Math.round(255 * (v <= 0.0031308 ? 12.92 * v : 1.055 * Math.pow(v, 1 / 2.4) - 0.055));
  return [enc(r), enc(g), enc(b)];
}
// The colour must move red -> orange -> yellow -> white as T rises (R>=G>=B, gap closes).
{
  const cool = blackbodyRGB(1000);    // deep red ember
  const candle = blackbodyRGB(1473);  // orange-yellow
  const hot = blackbodyRGB(3000);     // near white
  ok('1000 K reads as a red ember (R dominant, B suppressed)',
     cool[0] >= 200 && cool[2] < cool[0] * 0.55, `rgb(${cool})`);
  // A single 1200 C soot temperature is a deep orange-amber, NOT bright yellow:
  // a candle looks yellower, so its brightest soot runs hotter than this
  // (1200 C is an assumed starting value, not a measurement).
  ok('1473 K (candle) reads deep orange-amber (R saturated, G moderate, B~0)',
     candle[0] >= 250 && candle[1] > 80 && candle[1] < 160 && candle[2] < 40, `rgb(${candle})`);
  ok('3000 K trends toward white (blue channel climbs vs candle)',
     hot[2] > candle[2], `rgb(${hot}) vs candle rgb(${candle})`);
}

// ── (3) Chemiluminescence band positions (nm) ───────────────────────────────
const BANDS = { 'OH*': 309, 'CH*': 431, 'C2* Swan (green head)': 516, 'C2* Swan (blue-green head)': 473 };
ok('OH* is in the UV (< 380 nm), invisible to the eye', BANDS['OH*'] < 380, `${BANDS['OH*']} nm`);
ok('CH* sits in the blue-violet (410-450 nm) — the flame-base colour',
   BANDS['CH*'] >= 410 && BANDS['CH*'] <= 450, `${BANDS['CH*']} nm`);
ok('C2* Swan heads fall in 470-520 nm (blue-green)',
   BANDS['C2* Swan (blue-green head)'] >= 470 && BANDS['C2* Swan (green head)'] <= 520, 'ok');

// ── report ──────────────────────────────────────────────────────────────────
console.log(`\n${pass}/${pass + fail} checks passed.`);
console.log('\nKey numbers the page must reproduce:');
console.log(`  x(N2 thermal, ${T_CANDLE}K)   = ${xN2_candle.toExponential(2)}   (bulk air: not ionized)`);
console.log(`  x(Na thermal, ${T_CANDLE}K)   = ${xNa_candle.toExponential(2)}   (even the easy atom: trace)`);
console.log(`  measured flame ion fraction  ≈ 1e-7        (from chemistry, not heat)`);
console.log(`  1% yardstick (the page's own) = 1e-2  → flame is ~1e5x below it`);
console.log(`  T for Na -> 1% ionized       ≈ ${Math.round(T1_Na)} K`);
console.log(`  T for N2 -> 1% ionized       ≈ ${Math.round(T1_N2)} K`);
console.log(`  Wien peak @ 1473 K           = ${(WIEN_B / T_CANDLE * 1e9).toFixed(0)} nm (infrared; we see the tail)`);
console.log(`  black-body colour @1000/1473/3000 K = rgb(${blackbodyRGB(1000)}) / rgb(${blackbodyRGB(1473)}) / rgb(${blackbodyRGB(3000)})`);

if (fail > 0) { console.error(`\n${fail} CHECK(S) FAILED`); process.exit(1); }
