// spectra.mjs — the single source of truth for the flame-test bench.
// Both the page (public/strata/fireworks-colors/index.html) and the offline
// proof (research/fireworks-colors/verify.mjs) import THIS file, so the colour
// you see on screen is computed by the exact code the verifier checks.
//
// Two honest ideas live here:
//   1. The emission features are REAL wavelengths (nm), sourced in facts.md
//      (NIST Atomic Spectra Database for atomic lines; pyrotechnic-flame
//      spectroscopy — Douda, Conkling — for molecular band heads).
//   2. The swatch colour is not hand-picked. It is DERIVED from those
//      wavelengths by the CIE 1931 2° standard observer: each feature lights up
//      three colour-matching functions, whose weighted values sum to an XYZ
//      tristimulus, and XYZ maps to sRGB. Change the wavelengths and the colour
//      changes; that is the whole point.

// ---------------------------------------------------------------------------
// CIE 1931 2° colour-matching functions — Wyman, Sloan & Shirley (2013),
// "Simple Analytic Approximations to the CIE XYZ Color Matching Functions,"
// JCGT 2(2). The multi-lobe piecewise-Gaussian fit. Named as an approximation
// (max abs error in the fit is small and bounded in the paper); we do not claim
// it is the tabulated CMF to the last digit, only a faithful, citable stand-in.
function gauss(x, mu, s1, s2) {
  const t = (x - mu) * (x < mu ? s1 : s2);
  return Math.exp(-0.5 * t * t);
}
export function cieX(l) {
  return 1.056 * gauss(l, 599.8, 0.0264, 0.0323)
       + 0.362 * gauss(l, 442.0, 0.0624, 0.0374)
       - 0.065 * gauss(l, 501.1, 0.0490, 0.0382);
}
export function cieY(l) {
  return 0.821 * gauss(l, 568.8, 0.0213, 0.0247)
       + 0.286 * gauss(l, 530.9, 0.0613, 0.0322);
}
export function cieZ(l) {
  return 1.217 * gauss(l, 437.0, 0.0845, 0.0278)
       + 0.681 * gauss(l, 459.0, 0.0385, 0.0725);
}

// A spectrum = list of {nm, w} emission features (w = relative radiant weight).
// Sum the observer's response across them to get the tristimulus XYZ.
export function spectrumToXYZ(features) {
  let X = 0, Y = 0, Z = 0;
  for (const f of features) {
    if (f.w <= 0) continue;
    X += f.w * cieX(f.nm);
    Y += f.w * cieY(f.nm);
    Z += f.w * cieZ(f.nm);
  }
  return { X, Y, Z };
}

// XYZ -> sRGB (D65). Linear matrix, then gamut-map any negative channel by
// desaturating toward white, then normalise to the brightest channel and apply
// the sRGB transfer curve. Emission lines are vivid and over-bright, so we
// preserve hue and push to full display brightness rather than to a fixed
// luminance — a flame is what you SEE, not a calibrated luminance.
export function xyzToSRGB({ X, Y, Z }) {
  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;
  // Desaturate out-of-gamut colours by adding the deficit equally (toward white).
  const m = Math.min(r, g, b);
  if (m < 0) { r -= m; g -= m; b -= m; }
  // Normalise so the brightest primary is 1 (preserves chromaticity).
  const mx = Math.max(r, g, b, 1e-9);
  r /= mx; g /= mx; b /= mx;
  const enc = (c) => c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
  return [enc(r), enc(g), enc(b)].map((c) => Math.round(255 * Math.max(0, Math.min(1, c))));
}

// ---------------------------------------------------------------------------
// The emitters. Each `features` entry is a real wavelength with a relative
// weight chosen to reflect the dominant visual contribution; `kind` is 'line'
// (sharp atomic line) or 'band' (molecular band head — the real emission is a
// band envelope, drawn with a finite width on the spectrum plot). Wavelengths
// are sourced in facts.md.
export const EMITTERS = [
  {
    id: 'sodium', name: 'Sodium', salt: 'NaNO₃ / Na salts', sym: 'Na', named: 'yellow',
    note: 'A single atomic doublet — the famous sodium D-line. So intense it swamps every other colour, which is exactly why pyrotechnicians treat sodium as a contaminant to keep OUT of reds and blues.',
    emitter: 'atomic Na',
    features: [
      { nm: 589.00, w: 1.00, kind: 'line' },  // D2  588.995 nm
      { nm: 589.59, w: 0.55, kind: 'line' },  // D1  589.592 nm
    ],
  },
  {
    id: 'lithium', name: 'Lithium', salt: 'Li₂CO₃', sym: 'Li', named: 'red',
    note: 'A clean atomic line in the deep red. Lithium gives a true spectral crimson but is expensive, so most firework reds use strontium instead.',
    emitter: 'atomic Li',
    features: [
      { nm: 670.79, w: 1.00, kind: 'line' },  // 2P->2S doublet 670.776/670.791
      { nm: 610.36, w: 0.18, kind: 'line' },
    ],
  },
  {
    id: 'strontium', name: 'Strontium', salt: 'Sr(NO₃)₂ / SrCO₃', sym: 'Sr', named: 'red',
    note: 'The workhorse red. The colour is NOT bare strontium atoms — it is the molecule strontium monochloride (SrCl) and strontium hydroxide (SrOH) glowing in red BANDS. This molecular origin is the honest part the colour-key charts skip.',
    emitter: 'SrCl / SrOH bands',
    features: [
      { nm: 605.0, w: 0.45, kind: 'band', width: 6 },  // SrOH
      { nm: 623.9, w: 1.00, kind: 'band', width: 6 },  // SrCl
      { nm: 661.4, w: 0.70, kind: 'band', width: 7 },  // SrCl
      { nm: 674.5, w: 0.50, kind: 'band', width: 7 },  // SrCl
    ],
  },
  {
    id: 'calcium', name: 'Calcium', salt: 'CaCO₃ / CaCl₂', sym: 'Ca', named: 'orange',
    note: 'Calcium monochloride (CaCl) bands sit a little shorter than strontium’s, giving brick-orange. Calcium is often added to deepen and brighten a red rather than used alone.',
    emitter: 'CaCl bands',
    features: [
      { nm: 593.0, w: 0.80, kind: 'band', width: 6 },
      { nm: 603.0, w: 1.00, kind: 'band', width: 6 },
      { nm: 618.0, w: 0.60, kind: 'band', width: 6 },
      { nm: 621.0, w: 0.55, kind: 'band', width: 6 },
    ],
  },
  {
    id: 'barium', name: 'Barium', salt: 'Ba(NO₃)₂', sym: 'Ba', named: 'green',
    note: 'Green comes from barium monochloride (BaCl) bands clustered around 505–535 nm. Pure barium green needs a chlorine donor in the mix; without it the colour drifts.',
    emitter: 'BaCl bands',
    features: [
      { nm: 507.0, w: 0.70, kind: 'band', width: 5 },
      { nm: 513.8, w: 1.00, kind: 'band', width: 5 },
      { nm: 524.1, w: 0.85, kind: 'band', width: 5 },
      { nm: 532.0, w: 0.60, kind: 'band', width: 5 },
    ],
  },
  {
    id: 'copper', name: 'Copper', salt: 'CuCl (from Cu + Cl donor)', sym: 'Cu', named: 'blue',
    note: 'The hard colour. Copper monochloride (CuCl) emits blue bands around 420–460 nm, and its colour depends on flame conditions. Copper(I) iodide is another blue emitter. Use the heat slider: past its illustrative 1200 °C threshold, the spectrum and glow fade while RGB stays fixed and the glow remains visible. Blue needs careful flame tuning.',
    emitter: 'CuCl bands',
    modelFalloffAtC: 1200,        // Illustrative slider threshold, not a material limit (facts.md)
    features: [
      { nm: 428.5, w: 0.85, kind: 'band', width: 5 },
      { nm: 435.5, w: 1.00, kind: 'band', width: 5 },
      { nm: 443.4, w: 0.90, kind: 'band', width: 5 },
      { nm: 448.0, w: 0.75, kind: 'band', width: 5 },
      { nm: 465.1, w: 0.55, kind: 'band', width: 5 },
    ],
  },
  {
    id: 'potassium', name: 'Potassium', salt: 'KNO₃ / KClO₄', sym: 'K', named: 'violet',
    note: 'A faint lilac-violet in this simplified swatch. Potassium’s strong far-red lines (766/770 nm) are weakly perceived but can shift a flame’s colour. This model omits them and uses the violet pair near 404 nm. Potassium compounds also serve as oxidisers.',
    emitter: 'atomic K',
    features: [
      { nm: 404.41, w: 1.00, kind: 'line' },
      { nm: 404.72, w: 0.90, kind: 'line' },
      { nm: 766.49, w: 0.0, kind: 'line', omitted: true },  // Far-red contribution omitted by this model
      { nm: 769.90, w: 0.0, kind: 'line', omitted: true },
    ],
  },
];

// Illustrative copper intensity fall-off. The 1200 °C threshold and curve are
// chosen model settings, not a measured CuCl decomposition limit or survival
// fraction. Other emitters are held constant; their real thermal chemistry
// is not modelled here. Returns a 0..1 relative intensity factor.
export function survivalFraction(emitter, tempC) {
  if (!emitter.modelFalloffAtC) return 1;
  const T0 = emitter.modelFalloffAtC;
  if (tempC <= T0) return 1;
  // Model factor reaches one half 150 °C above the chosen threshold.
  return 1 / (1 + Math.exp((tempC - (T0 + 150)) / 90));
}

// The colour of an emitter at a given flame temperature.
export function emitterColor(emitter, tempC = 1000) {
  const surv = survivalFraction(emitter, tempC);
  const feats = emitter.features.map((f) => ({ nm: f.nm, w: f.w * surv }));
  return { rgb: xyzToSRGB(spectrumToXYZ(feats)), survival: surv };
}

// Coarse hue name from an sRGB triple, used by the verifier to assert that the
// computed colour lands in the qualitative bin the chemistry predicts.
export function hueName([r, g, b]) {
  const mx = Math.max(r, g, b), mn = Math.min(r, g, b);
  if (mx < 24) return 'black';
  if (mx - mn < 18) return 'white';
  let h;
  if (mx === r) h = ((g - b) / (mx - mn)) % 6;
  else if (mx === g) h = (b - r) / (mx - mn) + 2;
  else h = (r - g) / (mx - mn) + 4;
  h = ((h * 60) + 360) % 360;
  if (h < 18 || h >= 330) return 'red';
  if (h < 45) return 'orange';
  if (h < 70) return 'yellow';
  if (h < 165) return 'green';
  if (h < 200) return 'cyan';
  if (h < 255) return 'blue';
  if (h < 290) return 'violet';
  return 'magenta';
}
