// engine.mjs: the arithmetic behind "It Depends, and Here Is On What".
//
// Every number the page shows a reader is computed here, from published figures
// held separately in figures.json. This file holds NO empirical constants on
// purpose: the maths and the measurements are kept apart so that a reader (and
// the check at research/the-conditional-horse/verify.mjs, which imports this
// exact file) can see which is which. If a figure is wrong, figures.json is
// wrong. If a derivation is wrong, this file is wrong.
//
// Served live at /strata/the-conditional-horse/engine.mjs, and it is a module the
// page loads, not a copy of one.

'use strict';

/** Days in the mean Gregorian month. Used wherever a per-month rate meets a per-week cycle. */
export const DAYS_PER_MONTH = 30.436875;

// ─────────────────────────────────────────────────────────────────────────────
// 1. THE HOOF BUDGET  (why do horses need horseshoes)
//
// A hoof wall is not a fixed object. It is produced at the coronary band at some
// rate and destroyed at the ground at some other rate, and the whole question of
// whether a horse "needs" shoes is which of those two numbers is larger. Nothing
// here is subtle: it is a bathtub with a tap and a drain. The reason the popular
// answer is wrong is not that the arithmetic is hard, it is that the popular
// answer never states there are two numbers.
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Rates are in MILLIMETRES PER DAY, because that is the unit the measurement
 * papers report (Butler and Hintz 1977 onward), and converting a published
 * number before showing it to a reader is a small way of losing them.
 *
 * @param {object} o
 * @param {number} o.growthMmPerDay   horn produced at the coronary band
 * @param {number} o.wearMmPerDay     horn lost at the ground
 * @param {number} o.wallLengthMm     dorsal wall length, coronary band to ground
 * @param {number} o.cycleDays        the farriery interval being asked about
 */
export function hoofBudget({ growthMmPerDay, wearMmPerDay, wallLengthMm, cycleDays }) {
  const perDay = growthMmPerDay - wearMmPerDay;
  const net = perDay * DAYS_PER_MONTH;
  const overCycle = perDay * cycleDays;

  // How long before the whole capsule is new horn. This is the one figure in this
  // section that does not depend on wear at all, which is why it is the honest
  // headline: a hoof replaces itself whether or not anyone is looking at it.
  const capsuleDays = growthMmPerDay > 0 ? wallLengthMm / growthMmPerDay : Infinity;
  const capsuleMonths = capsuleDays / DAYS_PER_MONTH;

  // The threshold is 0.005 mm/day, which is a twentieth of the smallest published
  // growth rate and well inside every reported measurement error. Below it the
  // honest word is "level", not "surplus by a hair".
  let verdict;
  if (Math.abs(perDay) < 0.005) verdict = 'balanced';
  else if (perDay > 0) verdict = 'surplus';
  else verdict = 'deficit';

  return {
    netMmPerMonth: net,
    netMmPerDay: perDay,
    netMmOverCycle: overCycle,
    capsuleMonths,
    capsuleDays,
    verdict,
    // Days until the surplus reaches a given excess length, or until a deficit
    // eats a given depth of wall. Infinite when the budget is balanced.
    daysToReach(mm) {
      if (perDay === 0) return Infinity;
      return mm / Math.abs(perDay);
    },
  };
}

// ─────────────────────────────────────────────────────────────────────────────
// 2. THE VISUAL FIELD  (blinkers, fly masks, and everything else over the eyes)
//
// The field is modelled as arcs on a circle in the horizontal plane, 0 degrees
// straight ahead, angles increasing to the horse's right, wrapping at 360. Each
// eye contributes one arc centred on its own optical axis. The union of the two
// arcs is what the horse can see; the intersection is what it sees with both
// eyes at once; what is left over is blind.
//
// This is a real derivation and it is checkable: feed it a published monocular
// field and a published optical-axis divergence and see whether the union and
// the intersection come out at the published panoramic total and the published
// binocular overlap. If they do not, one of the three published numbers is wrong,
// and that is worth knowing.
// ─────────────────────────────────────────────────────────────────────────────

const TAU_DEG = 360;
const norm = (a) => ((a % TAU_DEG) + TAU_DEG) % TAU_DEG;

/** An arc as [start, end] going clockwise from start; may wrap past 360. */
export function arcFrom(centreDeg, widthDeg) {
  const w = Math.min(widthDeg, TAU_DEG);
  return [norm(centreDeg - w / 2), norm(centreDeg - w / 2) + w];
}

/** Break a possibly-wrapping arc into one or two non-wrapping [start,end] pieces in [0,360). */
export function unwrap([s, e]) {
  const start = norm(s);
  const end = start + (e - s);
  if (end <= TAU_DEG) return [[start, end]];
  return [[start, TAU_DEG], [0, end - TAU_DEG]];
}

/** Union of a list of arcs, returned as sorted, merged, non-wrapping pieces. */
export function unionArcs(arcs) {
  const pieces = arcs.flatMap(unwrap).filter(([s, e]) => e > s).sort((a, b) => a[0] - b[0]);
  const out = [];
  for (const p of pieces) {
    const last = out[out.length - 1];
    if (last && p[0] <= last[1] + 1e-9) last[1] = Math.max(last[1], p[1]);
    else out.push([p[0], p[1]]);
  }
  return out;
}

/** Intersection of two arcs, as non-wrapping pieces. */
export function intersectArcs(a, b) {
  const A = unwrap(a), B = unwrap(b), out = [];
  for (const [as, ae] of A) for (const [bs, be] of B) {
    const s = Math.max(as, bs), e = Math.min(ae, be);
    if (e > s + 1e-9) out.push([s, e]);
  }
  return unionArcs(out);
}

/** Total angular extent of a list of non-overlapping pieces. */
export function extent(pieces) {
  return pieces.reduce((t, [s, e]) => t + (e - s), 0);
}

/** Subtract a list of arcs from a list of pieces. */
export function subtractArcs(pieces, cuts) {
  let cur = pieces.map(([s, e]) => [s, e]);
  for (const cut of cuts) {
    for (const [cs, ce] of unwrap(cut)) {
      const next = [];
      for (const [s, e] of cur) {
        if (ce <= s + 1e-9 || cs >= e - 1e-9) { next.push([s, e]); continue; }
        if (cs > s + 1e-9) next.push([s, Math.min(cs, e)]);
        if (ce < e - 1e-9) next.push([Math.max(ce, s), e]);
      }
      cur = next;
    }
  }
  return unionArcs(cur);
}

/**
 * Build the horse's horizontal visual field from two eyes.
 * @param {number} monocularDeg      angular width of one eye's field
 * @param {number} axisDivergenceDeg angle between straight ahead and one eye's optical axis
 */
export function visualField(monocularDeg, axisDivergenceDeg) {
  const right = arcFrom(axisDivergenceDeg, monocularDeg);
  const left = arcFrom(-axisDivergenceDeg, monocularDeg);
  const seen = unionArcs([right, left]);
  const both = intersectArcs(right, left);
  // The binocular wedge in front and the (usually smaller) one behind, told apart
  // by which side of the head they sit on.
  const front = both.filter(([s, e]) => {
    const mid = (s + e) / 2;
    return mid < 90 || mid > 270;
  });
  const rear = both.filter(([s, e]) => {
    const mid = (s + e) / 2;
    return mid >= 90 && mid <= 270;
  });
  return {
    right, left,
    seen,
    panoramicDeg: extent(seen),
    blindDeg: TAU_DEG - extent(seen),
    binocularDeg: extent(both),
    binocularFrontDeg: extent(front),
    binocularRearDeg: extent(rear),
    blindPieces: subtractArcs([[0, TAU_DEG]], seen),
  };
}

/**
 * THE THREE NUMBERS THAT DO NOT CLOSE.
 *
 * Two laterally placed eyes, each with a monocular field of M degrees, overlapping
 * by B degrees in front, see a total of
 *
 *     T = 2M - B
 *
 * which is the same statement as T = M + 2A above, since B = M - 2A. So the three
 * figures that textbooks and reviews print side by side about the horse are not
 * three independent measurements. Any two of them fix the third, and a reader can
 * check whether the published set is possible. It is not: the canonical panoramic
 * total is larger than the canonical monocular field and binocular overlap can
 * produce, by tens of degrees.
 *
 * This is arithmetic, not an opinion about horses, which is why it is here rather
 * than in a paragraph.
 */
export function fieldConsistency({ panoramicDeg, monocularDeg, binocularDeg }) {
  const impliedPanoramic = 2 * monocularDeg - binocularDeg;
  return {
    impliedPanoramic,
    residualDeg: panoramicDeg - impliedPanoramic,
    // What each figure would have to be for the other two to stand.
    monocularNeededForPanoramic: (panoramicDeg + binocularDeg) / 2,
    binocularNeededForPanoramic: 2 * monocularDeg - panoramicDeg,
    axisDivergenceImplied: (monocularDeg - binocularDeg) / 2,
    closes: Math.abs(panoramicDeg - impliedPanoramic) < 1e-9,
  };
}

/**
 * Apply a device that removes arcs from the field.
 * @param {{seen:Array}} field  the output of visualField
 * @param {Array} cuts          arcs the device removes, as [centre, width] pairs
 */
export function wearDevice(field, cuts) {
  const cutArcs = cuts.map(([c, w]) => arcFrom(c, w));
  const left = subtractArcs(field.seen, cutArcs);
  return {
    seen: left,
    panoramicDeg: extent(left),
    lostDeg: extent(field.seen) - extent(left),
    blindPieces: subtractArcs([[0, TAU_DEG]], left),
  };
}

// ─────────────────────────────────────────────────────────────────────────────
// 3. THE SLEEP BUDGET  (why do horses sleep standing up)
//
// A horse can hold slow-wave sleep on its feet and cannot hold the paradoxical
// (REM) stage there, because that stage abolishes the postural muscle tone the
// standing posture is made of. So the day divides into sleep that standing can
// buy and sleep that it cannot, and the second kind has a floor.
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Two numbers, and the question of whether they can both be true.
 *
 * Paradoxical sleep happens only lying down, so the minutes of it a horse gets
 * are bounded above by the minutes it spends recumbent. That is not a model, it
 * is an inequality, and running the published figures through it is what this
 * section is for: the recumbency threshold the welfare literature uses and the
 * paradoxical-sleep durations the same literature reports cannot both stand.
 *
 * `occupancy` is the load-bearing output: the fraction of every minute lying
 * down that would have to be paradoxical sleep for the stated need to be met.
 * Over 1 is arithmetically impossible. Under 1 but high is a claim nobody has
 * checked, and the page says which is which.
 *
 * @param {number} o.remNeedMin      paradoxical sleep a horse is said to need per 24 h
 * @param {number} o.recumbentMin    minutes per 24 h actually spent lying down
 * @param {number} o.remBoutMin      length of one paradoxical bout
 */
export function sleepBudget({ remNeedMin, recumbentMin, remBoutMin }) {
  const remPossibleMin = Math.min(remNeedMin, recumbentMin);
  const shortfallMin = Math.max(0, remNeedMin - recumbentMin);
  const occupancy = recumbentMin > 0 ? remNeedMin / recumbentMin : Infinity;
  return {
    remPossibleMin,
    shortfallMin,
    occupancy,
    feasible: occupancy <= 1,
    boutsNeeded: remBoutMin > 0 ? remNeedMin / remBoutMin : Infinity,
    // The recumbency that would make the stated need merely possible, with no
    // time lying down spent doing anything else at all.
    recumbentFloorMin: remNeedMin,
    equivalentDaysLostPerWeek: remNeedMin > 0 ? (shortfallMin * 7) / remNeedMin : 0,
  };
}

// ─────────────────────────────────────────────────────────────────────────────
// 4. TWO VOICES AT ONCE  (why do horses neigh)
//
// A whinny is biphonic: two independent fundamental frequencies sounding
// together. The claim a reader can check here is not about horses at all, it is
// about arithmetic: a sound made by ONE source has a spectrum whose peaks are all
// integer multiples of a single fundamental. A sound made by TWO independent
// sources does not, and no choice of fundamental can make it so. That is the
// difference a spectrogram of a whinny shows, and it is why "two frequencies at
// once" is a measurable statement rather than a poetic one.
// ─────────────────────────────────────────────────────────────────────────────

/** Harmonic stack: amplitudes 1/n at n*f0, n = 1..nHarm, clipped at Nyquist. */
export function harmonicPeaks(f0, nHarm, nyquist) {
  const out = [];
  for (let n = 1; n <= nHarm; n++) {
    const f = n * f0;
    if (f >= nyquist) break;
    out.push({ f, a: 1 / n });
  }
  return out;
}

/**
 * The spectrum of two independent sources passing through one nonlinear system:
 * both harmonic stacks, plus the sum and difference combination tones that a
 * single source cannot produce.
 */
export function biphonicPeaks(f0, g0, nHarm, nyquist, order = 2) {
  const peaks = new Map();
  const add = (f, a) => {
    if (f <= 0 || f >= nyquist) return;
    const k = Math.round(f * 100) / 100;
    peaks.set(k, Math.max(peaks.get(k) ?? 0, a));
  };
  for (const p of harmonicPeaks(f0, nHarm, nyquist)) add(p.f, p.a);
  for (const p of harmonicPeaks(g0, nHarm, nyquist)) add(p.f, p.a * 0.8);
  for (let m = 1; m <= order; m++) {
    for (let n = 1; n <= order; n++) {
      add(m * f0 + n * g0, 0.25 / (m * n));
      add(Math.abs(m * f0 - n * g0), 0.25 / (m * n));
    }
  }
  return [...peaks.entries()].map(([f, a]) => ({ f, a })).sort((x, y) => x.f - y.f);
}

/**
 * THE ONE-SOURCE TEST, and the two conditions it has to impose.
 *
 * The obvious test is "is there a fundamental whose integer multiples land on
 * every peak", and on its own it is useless, because there almost always is one:
 * drop far enough down and 400 Hz and 1100 Hz are both multiples of 100, or of 4,
 * or of 1. The escape hatch is a fundamental so low that almost none of its
 * harmonics are actually present, and the spectrum is mostly holes.
 *
 * So the test has two conditions, both stated so a reader can argue with them:
 *
 *   FIT      every observed peak lies within `tolerance` of an integer multiple
 *            of the candidate fundamental, and
 *   COVERAGE at least `minCoverage` of that fundamental's own harmonics below the
 *            highest observed peak are actually occupied by one.
 *
 * Candidates are the observed peaks themselves and their integer submultiples up
 * to `maxSubharmonic`, which is how a genuinely missing fundamental is still
 * allowed to win. A single voice passes both conditions easily. Two voices at a
 * ratio that is not small-integer fail COVERAGE at every candidate that passes
 * FIT, and that failure is the measurable content of "two voices at once".
 *
 * @returns {{bestF0:number, worstRelError:number, coverage:number, oneSource:boolean}}
 */
export function oneSourceTest(peaks, { tolerance = 0.03, minCoverage = 0.5, maxSubharmonic = 6 } = {}) {
  if (!peaks.length) return { bestF0: NaN, worstRelError: Infinity, coverage: 0, oneSource: false };
  const fmax = Math.max(...peaks.map((p) => p.f));
  const candidates = new Set();
  for (const p of peaks) {
    for (let k = 1; k <= maxSubharmonic; k++) candidates.add(p.f / k);
  }
  let best = { bestF0: NaN, worstRelError: Infinity, coverage: 0, oneSource: false };
  for (const f of candidates) {
    if (f <= 0) continue;
    let worst = 0, ok = true;
    for (const p of peaks) {
      const n = Math.round(p.f / f);
      if (n < 1) { ok = false; break; }
      const err = Math.abs(p.f - n * f) / p.f;
      if (err > worst) worst = err;
      if (worst > tolerance) { ok = false; break; }
    }
    if (!ok) continue;
    const slots = Math.floor(fmax / f + 1e-9);
    let filled = 0;
    for (let n = 1; n <= slots; n++) {
      const target = n * f;
      if (peaks.some((p) => Math.abs(p.f - target) / target <= tolerance)) filled++;
    }
    const coverage = slots ? filled / slots : 0;
    const passes = coverage >= minCoverage;
    // Prefer a candidate that passes; among those, the one with the best coverage.
    const better = passes
      ? (!best.oneSource || coverage > best.coverage)
      : (!best.oneSource && coverage > best.coverage);
    if (better) best = { bestF0: f, worstRelError: worst, coverage, oneSource: passes };
  }
  return best;
}

/**
 * THE HARMONIC LOCK TEST, which is what actually works on a real animal call.
 *
 * The static peak test above is clean on a synthesised tone and unreliable on a
 * real whinny, because a real call slides in pitch, so its peaks smear and a low
 * enough fundamental can be fitted to a noisy peak list by luck. That was tried
 * here and it is reported on the page as the instrument's own limit rather than
 * quietly dropped.
 *
 * What survives the move to real audio is a statement about TIME. Track the
 * strongest component in a low band and the strongest in a high band, frame by
 * frame, and take their ratio. If both belong to one source, the high one is a
 * harmonic of the low one and the ratio is an INTEGER in every frame, and stays
 * that integer however wildly the pitch slides, because the whole harmonic stack
 * slides with it. Two independent sources have no such constraint and their ratio
 * wanders.
 *
 * So the discriminant is the mean distance from the ratio to the nearest whole
 * number. It is near zero for one voice however much vibrato it carries, and it
 * is large for two. Nothing about it is horse-specific: it is a property of
 * harmonic series.
 */
export function harmonicLock(samples, sampleRate, {
  windowSize = 2048, hop = 512, lowBand = [200, 900], highBand = [900, 4500],
  from = 0, to = Infinity, minRms = 0.01,
} = {}) {
  const startS = Math.max(0, Math.floor(from * sampleRate));
  const endS = Math.min(samples.length, Math.ceil(to * sampleRate));
  const frames = [];
  for (let s = startS; s + windowSize <= endS; s += hop) {
    const seg = samples.subarray ? samples.subarray(s, s + windowSize) : samples.slice(s, s + windowSize);
    let rms = 0;
    for (let i = 0; i < seg.length; i++) rms += seg[i] * seg[i];
    rms = Math.sqrt(rms / seg.length);
    if (rms < minRms) continue;
    const mag = magnitudeSpectrum(seg);
    const df = sampleRate / (mag.length * 2);
    const strongestIn = (lo, hi) => {
      let bi = -1, bv = 0;
      for (let i = 1; i < mag.length - 1; i++) {
        const f = i * df;
        if (f < lo || f > hi) continue;
        if (mag[i] > mag[i - 1] && mag[i] >= mag[i + 1] && mag[i] > bv) { bv = mag[i]; bi = i; }
      }
      if (bi < 0) return null;
      const a = mag[bi - 1], b = mag[bi], c = mag[bi + 1];
      const d = (a - c) / (2 * (a - 2 * b + c) || 1e-12);
      return { f: (bi + d) * df, a: b };
    };
    const lo = strongestIn(lowBand[0], lowBand[1]);
    const hi = strongestIn(highBand[0], highBand[1]);
    if (!lo || !hi) continue;
    const ratio = hi.f / lo.f;
    frames.push({
      t: s / sampleRate, f0: lo.f, g0: hi.f, ratio,
      deviation: Math.abs(ratio - Math.round(ratio)), rms,
    });
  }
  if (!frames.length) {
    return { frames, n: 0, meanDeviation: NaN, ratioMin: NaN, ratioMax: NaN, locked: false };
  }
  const devs = frames.map((f) => f.deviation);
  const ratios = frames.map((f) => f.ratio);
  const meanDeviation = devs.reduce((a, b) => a + b, 0) / devs.length;
  return {
    frames, n: frames.length, meanDeviation,
    ratioMin: Math.min(...ratios), ratioMax: Math.max(...ratios),
    // A single harmonic stack cannot drift off a whole number. The threshold is a
    // choice, and it is stated on the page: an eighth of the way to the next
    // integer, which is thirty times the worst a clean synthetic voice produces
    // and comfortably under what two independent voices produce.
    locked: meanDeviation < 0.125,
  };
}

/** Frames of magnitude spectrum, for drawing. Returns log-scaled magnitudes in [0,1]. */
export function spectrogram(samples, sampleRate, { windowSize = 1024, hop = 256, maxHz = 5000, from = 0, to = Infinity } = {}) {
  const startS = Math.max(0, Math.floor(from * sampleRate));
  const endS = Math.min(samples.length, Math.ceil(to * sampleRate));
  const df = sampleRate / windowSize;
  const bins = Math.min(Math.floor(maxHz / df), windowSize >> 1);
  const cols = [];
  for (let s = startS; s + windowSize <= endS; s += hop) {
    const seg = samples.subarray ? samples.subarray(s, s + windowSize) : samples.slice(s, s + windowSize);
    const mag = magnitudeSpectrum(seg);
    const col = new Float32Array(bins);
    for (let i = 0; i < bins; i++) col[i] = mag[i];
    cols.push(col);
  }
  let top = 0;
  for (const c of cols) for (let i = 0; i < c.length; i++) if (c[i] > top) top = c[i];
  const floorDb = -60;
  for (const c of cols) {
    for (let i = 0; i < c.length; i++) {
      const db = 20 * Math.log10((c[i] + 1e-12) / (top + 1e-12));
      c[i] = Math.max(0, Math.min(1, (db - floorDb) / -floorDb));
    }
  }
  return { cols, bins, df, hopSeconds: hop / sampleRate, maxHz: bins * df };
}

/**
 * Decode a 16-bit PCM WAV into mono float samples. Deliberately tiny and
 * dependency-free: it runs unchanged in the page and in the check, so the numbers
 * a reader watches appear and the numbers the check asserts come off the same
 * bytes through the same code.
 */
export function decodeWav(buffer) {
  const dv = new DataView(buffer.buffer ? buffer.buffer : buffer,
    buffer.byteOffset ?? 0, buffer.byteLength ?? buffer.length);
  const tag = (o) => String.fromCharCode(dv.getUint8(o), dv.getUint8(o + 1), dv.getUint8(o + 2), dv.getUint8(o + 3));
  if (tag(0) !== 'RIFF' || tag(8) !== 'WAVE') throw new Error('decodeWav: not a RIFF/WAVE file');
  let off = 12, fmt = null, dataOff = -1, dataLen = 0;
  while (off + 8 <= dv.byteLength) {
    const id = tag(off), size = dv.getUint32(off + 4, true);
    if (id === 'fmt ') {
      fmt = {
        format: dv.getUint16(off + 8, true), channels: dv.getUint16(off + 10, true),
        rate: dv.getUint32(off + 12, true), bits: dv.getUint16(off + 22, true),
      };
    } else if (id === 'data') { dataOff = off + 8; dataLen = size; }
    off += 8 + size + (size % 2);
  }
  if (!fmt || dataOff < 0) throw new Error('decodeWav: missing fmt or data chunk');
  if (fmt.bits !== 16) throw new Error('decodeWav: only 16-bit PCM is supported, got ' + fmt.bits);
  const frames = Math.floor(dataLen / 2 / fmt.channels);
  const out = new Float64Array(frames);
  for (let i = 0; i < frames; i++) {
    let acc = 0;
    for (let c = 0; c < fmt.channels; c++) acc += dv.getInt16(dataOff + (i * fmt.channels + c) * 2, true) / 32768;
    out[i] = acc / fmt.channels;
  }
  return { sampleRate: fmt.rate, channels: fmt.channels, samples: out };
}

/** A voice that slides in pitch, for the controls the check runs. */
export function synthVibrato({ sampleRate, seconds, voices, }) {
  const n = Math.round(sampleRate * seconds);
  const out = new Float64Array(n);
  const phases = voices.map(() => 0);
  for (let i = 0; i < n; i++) {
    let v = 0;
    voices.forEach((voice, k) => {
      const { f0, depth = 0, rateHz = 5, phase = 0, harmonics = 8, gain = 1 } = voice;
      const f = f0 * (1 + depth * Math.sin(2 * Math.PI * rateHz * i / sampleRate + phase));
      phases[k] += (2 * Math.PI * f) / sampleRate;
      for (let h = 1; h <= harmonics; h++) {
        if (f * h >= sampleRate / 2) break;
        v += (gain / h) * Math.sin(phases[k] * h);
      }
    });
    out[i] = v;
  }
  let peak = 0;
  for (let i = 0; i < n; i++) peak = Math.max(peak, Math.abs(out[i]));
  if (peak > 0) for (let i = 0; i < n; i++) out[i] /= peak;
  return out;
}

// ── a small radix-2 FFT, so the page can do this to a real recording ──────────

/** In-place iterative radix-2 Cooley-Tukey. re/im are Float64Array of length 2^k. */
export function fft(re, im) {
  const n = re.length;
  if ((n & (n - 1)) !== 0) throw new Error('fft: length must be a power of two');
  for (let i = 1, j = 0; i < n; i++) {
    let bit = n >> 1;
    for (; j & bit; bit >>= 1) j ^= bit;
    j ^= bit;
    if (i < j) {
      let t = re[i]; re[i] = re[j]; re[j] = t;
      t = im[i]; im[i] = im[j]; im[j] = t;
    }
  }
  for (let len = 2; len <= n; len <<= 1) {
    const ang = (-2 * Math.PI) / len;
    const wr = Math.cos(ang), wi = Math.sin(ang);
    for (let i = 0; i < n; i += len) {
      let cr = 1, ci = 0;
      for (let k = 0; k < len / 2; k++) {
        const ur = re[i + k], ui = im[i + k];
        const vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;
        const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
        re[i + k] = ur + vr; im[i + k] = ui + vi;
        re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
        const ncr = cr * wr - ci * wi;
        ci = cr * wi + ci * wr; cr = ncr;
      }
    }
  }
}

/** Magnitude spectrum of a real signal, Hann-windowed, length must be a power of two. */
export function magnitudeSpectrum(samples) {
  const n = samples.length;
  const re = new Float64Array(n), im = new Float64Array(n);
  for (let i = 0; i < n; i++) {
    const w = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (n - 1));
    re[i] = samples[i] * w;
  }
  fft(re, im);
  const half = n >> 1;
  const mag = new Float64Array(half);
  for (let i = 0; i < half; i++) mag[i] = Math.hypot(re[i], im[i]) / half;
  return mag;
}

/** Local maxima above a fraction of the strongest peak, as {f, a} in Hz. */
export function spectralPeaks(mag, sampleRate, { floorRatio = 0.05, maxPeaks = 40, minHz = 30 } = {}) {
  const df = sampleRate / (mag.length * 2);
  let top = 0;
  for (let i = 0; i < mag.length; i++) if (mag[i] > top) top = mag[i];
  const out = [];
  for (let i = 1; i < mag.length - 1; i++) {
    const f = i * df;
    if (f < minHz) continue;
    if (mag[i] > mag[i - 1] && mag[i] >= mag[i + 1] && mag[i] >= top * floorRatio) {
      // parabolic interpolation for a sub-bin estimate
      const a = mag[i - 1], b = mag[i], c = mag[i + 1];
      const d = (a - c) / (2 * (a - 2 * b + c) || 1e-12);
      out.push({ f: (i + d) * df, a: b });
    }
  }
  out.sort((x, y) => y.a - x.a);
  return out.slice(0, maxPeaks).sort((x, y) => x.f - y.f);
}

/** Synthesise one or two voices, for the demonstration and for the check. */
export function synth({ sampleRate, seconds, voices, nHarm = 8 }) {
  const n = Math.round(sampleRate * seconds);
  const out = new Float64Array(n);
  for (const { f0, gain = 1 } of voices) {
    for (let h = 1; h <= nHarm; h++) {
      const f = f0 * h;
      if (f >= sampleRate / 2) break;
      const amp = (gain / h) * 0.5;
      for (let i = 0; i < n; i++) out[i] += amp * Math.sin((2 * Math.PI * f * i) / sampleRate);
    }
  }
  let peak = 0;
  for (let i = 0; i < n; i++) peak = Math.max(peak, Math.abs(out[i]));
  if (peak > 0) for (let i = 0; i < n; i++) out[i] /= peak;
  return out;
}

// ─────────────────────────────────────────────────────────────────────────────
// 5. THE SIGHT LINE  (why do police use horses)
//
// Similar triangles, and nothing else. An eye at height E looking over an
// obstacle of height H at horizontal distance d1 reaches the ground at
// d = d1 * E / (E - H). When E <= H the expression has no positive solution,
// which is the whole content of the section: a person standing in a crowd of
// people their own height cannot see over it at any distance, and there is no
// amount of leaning that fixes it.
// ─────────────────────────────────────────────────────────────────────────────

/**
 * The binary result, which is the one that matters. A crowd has a head-top plane.
 * You are either above it or you are not, and if you are not there is no distance,
 * no angle and no amount of leaning that puts you above it.
 */
export function crowdPlane({ eyeHeightM, crowdHeadHeightM, helmetM = 0 }) {
  const eye = eyeHeightM;
  const clearance = eye - crowdHeadHeightM;
  const silhouette = Math.max(0, eye + helmetM + 0.115 - crowdHeadHeightM);
  return {
    eyeHeightM: eye,
    clearanceM: clearance,
    seesOver: clearance > 0,
    // How much of you stands above the crowd's head-top plane, which is what
    // someone at a distance has to detect. Eye to crown is taken as 11.5 cm.
    visibleSilhouetteM: silhouette,
  };
}

/**
 * A TOY, and labelled one wherever it appears. Treat a crowd as people of head
 * height h at mean spacing s = 1/sqrt(density). A sight line from eye height e
 * down to the ground at distance d runs below head height over its last
 * d*h/e metres, so the ground at d is visible only if that stretch is clear:
 *
 *     d_max = s * e / h
 *
 * It has never been validated against a real crowd. Its value is that it gives a
 * much less impressive answer than the head-plane result above, and the gap
 * between the two is the honest shape of the whole section.
 */
export function groundVisionDepth({ eyeHeightM, crowdHeadHeightM, densityPerM2 }) {
  const spacing = 1 / Math.sqrt(Math.max(densityPerM2, 1e-6));
  return { spacingM: spacing, depthM: (spacing * eyeHeightM) / crowdHeadHeightM };
}

export function sightLine({ eyeHeightM, obstacleHeightM, nearestObstacleM }) {
  if (eyeHeightM <= obstacleHeightM) {
    return { seesGroundAtM: Infinity, canSeeOver: false, clearanceM: eyeHeightM - obstacleHeightM };
  }
  return {
    seesGroundAtM: (nearestObstacleM * eyeHeightM) / (eyeHeightM - obstacleHeightM),
    canSeeOver: true,
    clearanceM: eyeHeightM - obstacleHeightM,
  };
}

/**
 * How many rows of a crowd stand between you and the first patch of ground you
 * can see, given rows every `rowSpacingM` metres starting at `nearestObstacleM`.
 */
export function rowsBlocked({ eyeHeightM, obstacleHeightM, nearestObstacleM, rowSpacingM }) {
  const s = sightLine({ eyeHeightM, obstacleHeightM, nearestObstacleM });
  if (!s.canSeeOver) return Infinity;
  return Math.max(0, Math.ceil((s.seesGroundAtM - nearestObstacleM) / rowSpacingM));
}

/** How far away a head at height E is still above a crowd of height H (flat ground, ignoring curvature). */
export function visibleAboveCrowd({ eyeHeightM, crowdHeightM }) {
  return eyeHeightM > crowdHeightM;
}

// ─────────────────────────────────────────────────────────────────────────────
// 6. THE MANE TABLE  (why do horses have manes)
//
// No model, just bookkeeping over a comparative table, because that is all the
// evidence supports. The summary this returns is the finding.
// ─────────────────────────────────────────────────────────────────────────────

export function maneSummary(rows) {
  const total = rows.length;
  const erect = rows.filter((r) => r.mane === 'erect').length;
  const falling = rows.filter((r) => r.mane === 'falling').length;
  const variable = rows.filter((r) => r.mane === 'variable').length;
  const withForelock = rows.filter((r) => r.forelock === 'present').length;
  const unsourced = rows.filter((r) => !r.source || !String(r.source).trim()).map((r) => r.common);
  const contested = rows.filter((r) => r.tier === 'contested').map((r) => r.common);
  return { total, erect, falling, variable, withForelock, unsourced, contested };
}

/** Bookkeeping over the evidence audit: how many of the standard explanations have ever been tested. */
export function evidenceSummary(rows) {
  const n = rows.length;
  const tested = rows.filter((r) => r.tier === 'tested').length;
  const indirect = rows.filter((r) => r.tier === 'indirect').length;
  const untested = rows.filter((r) => r.tier === 'untested').length;
  return { n, tested, indirect, untested };
}
