// verify-why-denim-fades.mjs — the geometry and the chemistry behind the stratum
// "The Blue Around a White Core" (/strata/why-denim-fades/).
//
// The thing the page corrects: people assume indigo is dissolved evenly INTO the
// cotton, the way a stain soaks a paper towel — so when denim fades they imagine
// the colour "leaving" the fibre. Two true, less-known facts dissolve the mystery:
//
//   (1) BONDING. Indigo is a VAT dye. It is applied as a colourless, water-soluble
//       reduced form (leuco-indigo), let into the fibre, then re-oxidised in air
//       back to the BLUE, water-INSOLUBLE pigment, which is now mechanically
//       trapped inside the fibre — held in its own crystal by intermolecular
//       hydrogen bonds and pi-pi stacking, NOT by a covalent bond to the cellulose.
//       A REACTIVE dye is the opposite: it forms a true covalent C–O bond to the
//       cellulose hydroxyl. (Honest nuance: there are weak physical/H-bond
//       interactions between any dye and the fibre surface; the load-bearing,
//       checkable distinction is "mechanically trapped, not COVALENTLY bonded.")
//
//   (2) RING DYEING. Denim warp yarn is characteristically "ring-dyed": the indigo
//       occupies an outer ANNULUS of the yarn, leaving an undyed WHITE CORE.
//
// Put (1)+(2) together and fading is no longer mysterious: abrasion at high-stress
// geometry (knees, the phone/wallet ghost, the seat) sands the thin dyed ring off
// the surface and exposes the white core that was there the whole time. The blue
// was in the outer yarn; the core stayed white.
//
// What this script PROVES, offline, from the equations the page animates:
//
//   A. The ring-dye area geometry is EXACT. For a circular cross-section of radius
//      R with a dyed ring of depth d measured inward from the surface, the dyed
//      fraction of the cross-sectional AREA is
//            f_area(d/R) = 1 - (1 - d/R)^2 .
//      The page displays this number live as you drag the ring depth. We recompute
//      it from scratch by NUMERICAL INTEGRATION over the disc (Monte-Carlo +
//      analytic annulus area) and confirm both routes agree and match the closed
//      form the page shows — so the headline figures (d/R=0.25 -> 43.8% dyed area;
//      reactive d/R=1.00 -> 100%) are derived, not asserted.
//
//   B. The asymmetry that makes fading dramatic: a ring covers 100% of the visible
//      SURFACE (the whole perimeter) at ANY positive depth, yet a SHALLOW ring is
//      a SMALL fraction of the area. So a thin blue coat reads as fully blue until
//      abrasion breaks through it — then the disproportionately large white core
//      shows. We verify surface coverage = 100% for every d>0 while area fraction
//      stays well below 100% for a shallow ring.
//
//   C. The abrasion -> whitening map the page paints is monotone and reaches pure
//      white EXACTLY when cumulative wear depth a equals the as-dyed ring depth d0
//      (vat / ring-dyed), but NEVER reaches white for a through-dyed reactive yarn
//      within the same wear range — the two fade curves the page draws.
//
//   D. The bonding claim is categorical, not numerical: it is checked as the
//      vat-vs-reactive contrast (mechanical trapping vs covalent C–O bond), and
//      asserted only at the strength the sources support.
//
//   run:  node research/why-denim-fades/verify-why-denim-fades.mjs
//
// No dependencies. Every NUMBER the page displays is recomputed here.

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;

// ── A. Ring-dye area fraction: closed form vs from-scratch integration ───────
// Closed form the PAGE shows:
const fAreaClosed = (dOverR) => {
  const core = Math.max(0, 1 - dOverR);        // (R-d)/R, clamped
  return 1 - core * core;                       // 1 - ((R-d)/R)^2
};

// From scratch #1 — analytic annulus area / disc area.
// disc area = pi R^2; white core radius = R-d, core area = pi (R-d)^2;
// dyed (ring) area = pi R^2 - pi (R-d)^2 ; fraction = 1 - ((R-d)/R)^2. Independent of R.
const fAreaAnnulus = (dOverR, R) => {
  const rCore = Math.max(0, R - dOverR * R);
  const aDisc = Math.PI * R * R;
  const aRing = aDisc - Math.PI * rCore * rCore;
  return aRing / aDisc;
};

// From scratch #2 — Monte-Carlo: sample points uniformly in the disc, count how
// many fall in the outer ring (r > R-d). This recomputes the fraction with NO
// reference to the algebra above — a genuine independent check.
function fAreaMonteCarlo(dOverR, R, N, rng) {
  let inRing = 0, inDisc = 0;
  const rCore = (1 - dOverR) * R;
  for (let i = 0; i < N; i++) {
    // uniform in the bounding square [-R,R]^2, keep those inside the disc
    const x = (rng() * 2 - 1) * R;
    const y = (rng() * 2 - 1) * R;
    const r2 = x * x + y * y;
    if (r2 <= R * R) {
      inDisc++;
      if (r2 > rCore * rCore) inRing++;
    }
  }
  return inRing / inDisc;
}
// small deterministic PRNG (mulberry32) so the check is reproducible
function mulberry32(seed) {
  let a = seed >>> 0;
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

console.log('\n— A. dyed-area fraction f = 1 - (1 - d/R)^2 (closed form vs integration) —');
const ringCases = [0.10, 0.15, 0.20, 0.25, 0.30, 0.50, 1.00];
for (const dr of ringCases) {
  const closed = fAreaClosed(dr);
  const annulus = fAreaAnnulus(dr, 7.5e-3);            // any R works (here ~7.5 micron-ish, units cancel)
  const mc = fAreaMonteCarlo(dr, 1.0, 400000, mulberry32(12345 + Math.round(dr * 100)));
  ok(`d/R=${dr.toFixed(2)}  closed=${(closed * 100).toFixed(1)}%  annulus=${(annulus * 100).toFixed(1)}%  MC=${(mc * 100).toFixed(1)}%`,
     approx(closed, annulus, 1e-12) && approx(closed, mc, 0.01),
     `Δ_MC=${(Math.abs(closed - mc) * 100).toFixed(2)}%`);
}

// Pinned headline values the page prints verbatim (regression guard):
ok('PAGE value: d/R=0.25 -> dyed area = 43.8%', approx(fAreaClosed(0.25), 0.4375, 5e-4), `${(fAreaClosed(0.25) * 100).toFixed(1)}%`);
ok('PAGE value: d/R=0.20 -> dyed area = 36.0%', approx(fAreaClosed(0.20), 0.36, 5e-4), `${(fAreaClosed(0.20) * 100).toFixed(1)}%`);
ok('PAGE value: reactive d/R=1.00 -> dyed area = 100.0%', approx(fAreaClosed(1.00), 1.0, 1e-9), `${(fAreaClosed(1.00) * 100).toFixed(1)}%`);

// ── B. The asymmetry: 100% surface coverage at any depth, small area when thin ─
console.log('\n— B. surface coverage vs area fraction (why a thin coat reads solid) —');
// Surface coverage = perimeter covered by the ring. As long as d>0, the ring
// touches the entire perimeter -> 100% coverage, independent of depth.
const surfaceCoverage = (dOverR) => (dOverR > 0 ? 1 : 0);
for (const dr of [0.10, 0.25]) {
  ok(`d/R=${dr.toFixed(2)}: surface coverage 100%, but only ${(fAreaClosed(dr) * 100).toFixed(0)}% of the area is dyed`,
     surfaceCoverage(dr) === 1 && fAreaClosed(dr) < 0.5,
     `area=${(fAreaClosed(dr) * 100).toFixed(1)}%`);
}

// ── C. Abrasion -> whitening map; vat reaches white, reactive does not ───────
// Model (named on the page as an idealization): abrasion removes depth a from the
// surface. The remaining dyed-ring thickness at a worn spot is max(0, d0 - a).
// Apparent surface-blue at that spot = remaining ring fraction = clamp((d0 - a)/d0).
// For a REACTIVE (through-dyed) yarn, removing depth a just exposes more dyed
// material: apparent blue stays ~1 over the same wear range (no white core to hit).
console.log('\n— C. fade curve: apparent surface blue vs cumulative wear a —');
const d0 = 0.25;                                  // as-dyed ring depth (vat / ring-dyed)
const vatBlue = (a) => Math.max(0, Math.min(1, (d0 - a) / d0));
const reactiveBlue = (a) => Math.max(0.82, 1 - 0.12 * Math.min(a, 1)); // page model: slight thinning
const wears = [0.0, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30];
let prev = Infinity, monotone = true;
for (const a of wears) {
  const vb = vatBlue(a);
  if (vb > prev + 1e-12) monotone = false;
  prev = vb;
}
ok('vat fade curve is monotone non-increasing in wear', monotone);
ok('vat fabric goes pure WHITE exactly when wear a reaches the ring depth d0=0.25',
   approx(vatBlue(d0), 0, 1e-12) && vatBlue(d0 - 1e-6) > 0, `blue(a=d0)=${vatBlue(d0).toFixed(3)}`);
ok('reactive (through-dyed) stays blue over the same wear (never whitens)',
   approx(reactiveBlue(0.30), 0.964, 1e-12), `blue(a=0.30)=${reactiveBlue(0.30).toFixed(3)}`);
ok('at equal heavy wear a=0.20, vat is far paler than reactive',
   vatBlue(0.20) < 0.25 && approx(reactiveBlue(0.20), 0.976, 1e-12),
   `vat=${vatBlue(0.20).toFixed(2)} vs reactive=${reactiveBlue(0.20).toFixed(3)}`);

// ── D. The bonding claim, stated at the strength the sources support ──────────
console.log('\n— D. bonding: vat (mechanical) vs reactive (covalent) —');
// These are categorical facts, recorded here so the page asserts nothing stronger.
const bonding = {
  vatIndigo:   { covalentToFibre: false, mechanism: 'reduced->infused->reoxidised; insoluble pigment mechanically trapped, held by H-bonds + pi-stacking in its own crystal' },
  reactiveDye: { covalentToFibre: true,  mechanism: 'forms a true covalent C–O bond to a cellulose hydroxyl' },
};
ok('vat indigo: NOT covalently bonded to the fibre (mechanically trapped)', bonding.vatIndigo.covalentToFibre === false);
ok('reactive dye: IS covalently bonded to the fibre (C–O bond)', bonding.reactiveDye.covalentToFibre === true);
ok('the checkable distinction is the COVALENT bond, not "no interaction at all"',
   bonding.vatIndigo.mechanism.includes('H-bonds') && bonding.reactiveDye.mechanism.includes('covalent'));

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