// engine.mjs: the arithmetic behind /strata/how-deep-can-fish-live/.
// Runs in the reader's browser and, unchanged, in the verifier (/checks/verify-how-deep-can-fish-live.mjs).
// No dependencies. Every constant below is copied from a named source; the verifier holds the
// results against independent libraries (TEOS-10 gsw, CoolProp) computed in
// research/how-deep-can-fish-live/reference.py.

// ── Pressure from depth: Saunders (1981), J. Phys. Oceanogr. 11:573-574, as in UNESCO/seawater `pres`.
export function pressureDbar(depthM, latDeg = 30) {
  const x = Math.sin(Math.abs(latDeg) * Math.PI / 180);
  const c1 = 5.92e-3 + x * x * 5.25e-3;
  return ((1 - c1) - Math.sqrt((1 - c1) ** 2 - 8.84e-6 * depthM)) / 4.42e-6;
}

// ── Seawater density: EOS-80 (Fofonoff & Millard 1983, UNESCO Tech. Pap. Mar. Sci. 44;
// Millero et al. 1980; Millero & Poisson 1981). Coefficients as in the `seawater` Python package
// 3.3.5 (library.smow, eos80.dens0, library.seck, eos80.dens). s in PSS-78, t in degrees C
// (IPTS-68; the 0.024% difference from ITS-90 is below anything this page shows), p in dbar.
function smow(t) {
  const a = [999.842594, 6.793952e-2, -9.095290e-3, 1.001685e-4, -1.120083e-6, 6.536332e-9];
  return a[0] + (a[1] + (a[2] + (a[3] + (a[4] + a[5] * t) * t) * t) * t) * t;
}
export function dens0(s, t) {
  const b = [8.24493e-1, -4.0899e-3, 7.6438e-5, -8.2467e-7, 5.3875e-9];
  const c = [-5.72466e-3, 1.0227e-4, -1.6546e-6];
  const d = 4.8314e-4;
  return smow(t) + (b[0] + (b[1] + (b[2] + (b[3] + b[4] * t) * t) * t) * t) * s
    + (c[0] + (c[1] + c[2] * t) * t) * s * Math.sqrt(s) + d * s * s;
}
export function secantBulkModulusBar(s, t, pDbar) {
  const p = pDbar / 10;
  const h = [3.239908, 1.43713e-3, 1.16092e-4, -5.77905e-7];
  const AW = h[0] + (h[1] + (h[2] + h[3] * t) * t) * t;
  const k = [8.50935e-5, -6.12293e-6, 5.2787e-8];
  const BW = k[0] + (k[1] + k[2] * t) * t;
  const e = [19652.21, 148.4206, -2.327105, 1.360477e-2, -5.155288e-5];
  const KW = e[0] + (e[1] + (e[2] + (e[3] + e[4] * t) * t) * t) * t;
  const j0 = 1.91075e-4;
  const i = [2.2838e-3, -1.0981e-5, -1.6078e-6];
  const A = AW + (i[0] + (i[1] + i[2] * t) * t + j0 * Math.sqrt(s)) * s;
  const m = [-9.9348e-7, 2.0816e-8, 9.1697e-10];
  const B = BW + (m[0] + (m[1] + m[2] * t) * t) * s;
  const f = [54.6746, -0.603459, 1.09987e-2, -6.1670e-5];
  const g = [7.944e-2, 1.6483e-2, -5.3009e-4];
  const K0 = KW + (f[0] + (f[1] + (f[2] + f[3] * t) * t) * t + (g[0] + (g[1] + g[2] * t) * t) * Math.sqrt(s)) * s;
  return K0 + (A + B * p) * p;
}
export function dens(s, t, pDbar) {
  return dens0(s, t) / (1 - (pDbar / 10) / secantBulkModulusBar(s, t, pDbar));
}

// The deep-water parcel the page uses: salinity 35, 2 degrees C.
export const DEEP = { s: 35, t: 2, lat: 30 };

// Fraction by which a parcel of deep seawater shrinks when carried from the surface to depthM,
// at constant temperature: 1 - rho(0)/rho(p).
export function waterShrink(depthM) {
  const p = pressureDbar(depthM, DEEP.lat);
  return 1 - dens(DEEP.s, DEEP.t, 0) / dens(DEEP.s, DEEP.t, p);
}

// Absolute pressure in atmospheres (the sea's gauge pressure plus one atmosphere of air).
export function atmospheres(depthM) {
  return (pressureDbar(depthM, DEEP.lat) * 1e4 + 101325) / 101325;
}

// Air. Boyle's law says a pocket of air shrinks by the pressure ratio. Real air is stiffer at
// these pressures, so the page also shows CoolProp's real-gas density ratio (air, 2 degrees C),
// tabulated every 500 m by research/how-deep-can-fish-live/reference.py and interpolated here.
export const AIR_RATIO_COOLPROP = [
  [0, 1], [500, 51.83], [1000, 103.4], [1500, 153.13], [2000, 198.75], [2500, 239.19], [3000, 274.44],
  [3500, 305.06], [4000, 331.77], [4500, 355.25], [5000, 376.09], [5500, 394.75], [6000, 411.6], [6500, 426.95],
  [7000, 441.03], [7500, 454.01], [8000, 466.07], [8500, 477.31], [9000, 487.84], [9500, 497.75], [10000, 507.11],
  [10500, 515.97], [11000, 524.39],
];
export function airBoyle(depthM) { return atmospheres(depthM); }
export function airReal(depthM) {
  const T = AIR_RATIO_COOLPROP;
  if (depthM <= 0) return 1;
  for (let k = 1; k < T.length; k++) {
    if (depthM <= T[k][0]) {
      const [z0, r0] = T[k - 1], [z1, r1] = T[k];
      return r0 + (r1 - r0) * (depthM - z0) / (z1 - z0);
    }
  }
  return T[T.length - 1][1];
}

// ── The fish. Generated from research/how-deep-can-fish-live/digitized.json (digitize.py), which reads
// the points off the published figures; the verifier holds these against that file and against the
// equations printed in the 2014 figure.
export const SEAWATER_MOSM = 1100;   // Yancey et al. 2014: "seawater’s 1,100 mOsmol/kg"
// Yancey et al. 2014, Fig. 3: twelve points for bathyal and abyssal teleosts, 500 to 3,000 m (depth m, mOsm/kg).
export const PRE2014 = [[502, 389], [502, 362], [795, 391], [1306, 462], [1306, 435], [1854, 506], [2091, 523], [2109, 508], [2109, 496], [2200, 540], [2873, 561], [3000, 637]];
// Yancey et al. 2014, abstract: five hadal snailfish (Notoliparis kermadecensis) from 7,000 m.
export const KERMADEC_2014 = [7000, 991];
// Yancey 2025 (figshare), Fig. 1, "modified from Linley et al. 2016": hadal snailfish not in the 2014 figure.
export const LATER_SNAILFISH = [
  { depth: 6453, osm: 984, who: "Kermadec snailfish", note: "legend: 2014" },
  { depth: 6941, osm: 1011, who: "Mariana snailfish", note: "legend: 2016" },
  { depth: 7085, osm: 1017, who: "Mariana snailfish", note: "legend: 2016" },
  { depth: 7197, osm: 1025, who: "Kermadec snailfish", note: "legend: 2014" },
  { depth: 7482, osm: 1039, who: "Mariana snailfish", note: "legend: 2016" },
  { depth: 7492, osm: 1063, who: "Kermadec snailfish", note: "legend: 2014" },
  { depth: 7898, osm: 1059, who: "Mariana snailfish", note: "legend: 2016" },
];
// The same figure: rattails and eelpouts from the trenches (not snailfish).
export const OTHER_FAMILIES = [
  { depth: 3564, osm: 588, who: "Kermadec rattail", note: "legend: 2014" },
  { depth: 4203, osm: 725, who: "Kermadec rattail", note: "legend: 2014" },
  { depth: 4440, osm: 660, who: "Mariana rattail", note: "legend: 2016" },
  { depth: 5258, osm: 754, who: "Mariana rattail", note: "legend: 2016" },
  { depth: 4822, osm: 692, who: "Kermadec eelpout (zoarcid)", note: "legend: 2014" },
  { depth: 5057, osm: 861, who: "Kermadec eelpout (zoarcid)", note: "legend: 2014" },
  { depth: 5057, osm: 838, who: "Kermadec eelpout (zoarcid)", note: "legend: 2014" },
];

// ── Statistics, from scratch so the reader's browser needs nothing.
// Regularized incomplete beta by continued fraction (Numerical Recipes, betacf), for Student's t.
function lgamma(x) {
  const c = [76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5];
  let y = x, tmp = x + 5.5; tmp -= (x + 0.5) * Math.log(tmp);
  let ser = 1.000000000190015; for (const cj of c) ser += cj / ++y;
  return -tmp + Math.log(2.5066282746310005 * ser / x);
}
function betacf(a, b, x) {
  const EPS = 3e-14, FPMIN = 1e-300; let qab = a + b, qap = a + 1, qam = a - 1, c = 1, d = 1 - qab * x / qap;
  if (Math.abs(d) < FPMIN) d = FPMIN; d = 1 / d; let h = d;
  for (let m = 1; m <= 300; m++) {
    const m2 = 2 * m; let aa = m * (b - m) * x / ((qam + m2) * (a + m2));
    d = 1 + aa * d; if (Math.abs(d) < FPMIN) d = FPMIN; c = 1 + aa / c; if (Math.abs(c) < FPMIN) c = FPMIN; d = 1 / d; h *= d * c;
    aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
    d = 1 + aa * d; if (Math.abs(d) < FPMIN) d = FPMIN; c = 1 + aa / c; if (Math.abs(c) < FPMIN) c = FPMIN; d = 1 / d;
    const del = d * c; h *= del; if (Math.abs(del - 1) < EPS) break;
  }
  return h;
}
function ibeta(a, b, x) {
  if (x <= 0) return 0; if (x >= 1) return 1;
  const bt = Math.exp(lgamma(a + b) - lgamma(a) - lgamma(b) + a * Math.log(x) + b * Math.log(1 - x));
  return x < (a + 1) / (a + b + 2) ? bt * betacf(a, b, x) / a : 1 - bt * betacf(b, a, 1 - x) / b;
}
// P(T <= t) for Student's t with df degrees of freedom.
export function tCdf(t, df) {
  const p = 0.5 * ibeta(df / 2, 0.5, df / (df + t * t));
  return t >= 0 ? 1 - p : p;
}
// The two-sided 95% critical value, by bisection.
export function t975(df) {
  let lo = 0, hi = 100;
  for (let k = 0; k < 200; k++) { const mid = (lo + hi) / 2; if (tCdf(mid, df) < 0.975) lo = mid; else hi = mid; }
  return (lo + hi) / 2;
}

// Ordinary least squares, osm = a + b * depth.
export function fit(points) {
  const n = points.length, xb = points.reduce((s, p) => s + p[0], 0) / n, yb = points.reduce((s, p) => s + p[1], 0) / n;
  let sxx = 0, sxy = 0; for (const [x, y] of points) { sxx += (x - xb) ** 2; sxy += (x - xb) * (y - yb); }
  const b = sxy / sxx, a = yb - b * xb;
  let rss = 0; for (const [x, y] of points) rss += (y - a - b * x) ** 2;
  const s = Math.sqrt(rss / (n - 2));
  return { n, a, b, xb, sxx, s, t: t975(n - 2) };
}
// Depth at which the fitted line reaches seawater, and its 95% interval (Fieller's method: every depth
// at which seawater lies inside the 95% confidence band of the line). null ends mean the interval is open.
export function crossing(F, y0 = SEAWATER_MOSM) {
  const { n, a, b, xb, sxx, s, t } = F, x0 = (y0 - a) / b;
  // (a + b x - y0)^2 = t^2 s^2 (1/n + (x - xb)^2 / sxx), a quadratic in u = x - xb
  const c0 = a + b * xb - y0, k = t * t * s * s;
  const A = b * b - k / sxx, B = 2 * b * c0, C = c0 * c0 - k / n;
  const disc = B * B - 4 * A * C;
  if (A <= 0 || disc < 0) return { depth: x0, lo: null, hi: null };
  const r1 = (-B - Math.sqrt(disc)) / (2 * A) + xb, r2 = (-B + Math.sqrt(disc)) / (2 * A) + xb;
  return { depth: x0, lo: Math.min(r1, r2), hi: Math.max(r1, r2) };
}
// What the line predicts for one more fish at depth x, with its 95% prediction interval.
export function predict(F, x) {
  const { n, a, b, xb, sxx, s, t } = F;
  return { osm: a + b * x, pm: t * s * Math.sqrt(1 + 1 / n + (x - xb) ** 2 / sxx) };
}

// The four sets of fish the page lets the line see.
export const SETS = {
  before: { label: 'the twelve shallow points', points: () => PRE2014 },
  kermadec: { label: '+ the Kermadec snailfish, 7,000 m', points: () => [...PRE2014, KERMADEC_2014] },
  snailfish: { label: '+ more snailfish to 7,900 m', points: () => [...PRE2014, KERMADEC_2014, ...LATER_SNAILFISH.map(p => [p.depth, p.osm])] },
  snailonly: { label: 'the snailfish alone', points: () => [KERMADEC_2014, ...LATER_SNAILFISH.map(p => [p.depth, p.osm])] },
  all: { label: '+ rattails and eelpouts', points: () => [...PRE2014, KERMADEC_2014, ...LATER_SNAILFISH.map(p => [p.depth, p.osm]), ...OTHER_FAMILIES.map(p => [p.depth, p.osm])] },
};

// Where fish have actually been found, deepest records. Each from a named source (see the page).
export const RECORDS = [
  { depth: 8370, what: 'Abyssobrotula galatheae, open trawl, Puerto Rico Trench, 1970', status: 'contested' },
  { depth: 8336, what: 'a juvenile snailfish on video, Izu-Ogasawara Trench, 2022 expedition', status: 'filmed' },
  { depth: 8178, what: 'Mariana snailfish (Pseudoliparis swirei), deepest of its range', status: 'range' },
  { depth: 8145, what: 'the "ethereal snailfish", Mariana Trench', status: 'filmed' },
  { depth: 8022, what: 'two Pseudoliparis belyaevi in a trap, Japan Trench', status: 'caught' },
];
