// engine.mjs: the arithmetic behind /strata/stair-rise-and-run/ ("One Inch Up, Two Across").
//
// Everything the page draws or states about a stair is computed here, in the reader's browser,
// and the same file is imported unchanged by verify-stair-rise-and-run.mjs.
//
// A stair is two numbers: R, the rise of one step, and G, the going (the tread, measured
// front edge to front edge), both in millimetres. Each authority on the page is a set of rules
// on (R, G). The historic ones are as Francois Blondel reported them in 1683, in his inches
// (pouces); the modern ones are as their codes print them.

// The Paris foot (pied du roi): the law of 19 frimaire an VIII (10 December 1799) makes the
// metre 443.296 lignes, and a pied is 144 lignes, so a pied is 144/443.296 m = 4500/13853 m.
export const PIED_MM = (4500 / 13853) * 1000; // 324.839...
export const POUCE_MM = PIED_MM / 12; // 27.070...
export const INCH_MM = 25.4;

// Blondel's rule: twice the rise plus the going makes the easy pace on the level, two pieds.
export const BLONDEL_PACE_MM = 24 * POUCE_MM; // 649.68...
export const blondelSum = (R, G) => 2 * R + G;
export const blondelGoing = (R) => BLONDEL_PACE_MM - 2 * R;
// His own table (Cours d'architecture, part 5, 1683, p. 693): rise and going in pouces.
export const BLONDEL_TABLE = [[1, 22], [2, 20], [3, 18], [4, 16], [5, 14], [6, 12], [7, 10], [8, 8], [9, 6]];

export const pitchDeg = (R, G) => (Math.atan2(R, G) * 180) / Math.PI;

const p = (x) => x * POUCE_MM;
const inch = (x) => x * INCH_MM;

// Each rule is [label, test(R, G)]. A region with no rules on one axis leaves that axis free.
// `rMin/rMax/gMin/gMax` are for drawing the box; `sum` is a 2R+G band; `pitchMax` in degrees.
export const AUTHORITIES = [
  {
    id: 'vitruvius', era: 'old', name: 'Vitruvius', when: 'probably written 30–20 BC',
    how: "temple steps: no higher than a dextans (10/12 of a foot), no lower than a dodrans (9/12); treads a foot and a half to two feet. Blondel's reading, his inches.",
    rMin: p(9), rMax: p(10), gMin: p(18), gMax: p(24),
  },
  {
    id: 'alberti', era: 'old', name: 'Alberti', when: 'written 1443–52, printed 1485',
    how: 'copied Vitruvius with sextans for dextans: no higher than 2/12 of a foot and no lower than 9/12. No step can do both.',
    rMin: p(9), rMax: p(2), gMin: p(18), gMax: p(24),
  },
  {
    id: 'palladio', era: 'old', name: 'Palladio', when: '1570',
    how: 'steps no more than six inches high and no less than four; treads never less than a foot nor more than a foot and a half.',
    rMin: p(4), rMax: p(6), gMin: p(12), gMax: p(18),
  },
  {
    id: 'scamozzi', era: 'old', name: 'Scamozzi', when: '1615',
    how: 'four or five inches of rise, and a foot or a little more of tread. (Blondel gives no upper figure for the tread; this box stops at 14 inches.)',
    rMin: p(4), rMax: p(5), gMin: p(12), gMax: p(14),
  },
  {
    id: 'savot', era: 'old', name: 'Savot', when: '1624 (words as printed in 1685)',
    how: 'stair treads a foot at least, and rise half a foot at most.',
    rMax: p(6), gMin: p(12),
  },
  {
    id: 'blondel', era: 'old', name: 'Blondel', when: '1683',
    how: 'twice the rise plus the going makes two feet (24 inches): each inch up is paid for with two inches across.',
    line: true,
  },
  {
    id: 'irc', era: 'new', name: 'IRC 2012', when: 'US houses',
    how: 'riser at most 7¾ in (196 mm); tread at least 10 in (254 mm). No minimum riser, no maximum tread.',
    rMax: inch(7.75), gMin: inch(10),
  },
  {
    id: 'ibc', era: 'new', name: 'IBC 2012', when: 'US other buildings',
    how: 'riser 4 to 7 in (102 to 178 mm); tread at least 11 in (279 mm).',
    rMin: inch(4), rMax: inch(7), gMin: inch(11),
  },
  {
    id: 'uk-private', era: 'new', name: 'UK private stair', when: 'Approved Document K, 2013',
    how: 'rise 150 to 220 mm, going 220 to 300 mm, pitch at most 42°, and 2R + G between 550 and 700 mm.',
    rMin: 150, rMax: 220, gMin: 220, gMax: 300, pitchMax: 42, sum: [550, 700],
  },
  {
    id: 'uk-utility', era: 'new', name: 'UK utility stair', when: 'Approved Document K, 2013',
    how: 'rise 150 to 190 mm, going 250 to 400 mm, and 2R + G between 550 and 700 mm.',
    rMin: 150, rMax: 190, gMin: 250, gMax: 400, sum: [550, 700],
  },
  {
    id: 'uk-general', era: 'new', name: 'UK general access stair', when: 'Approved Document K, 2013',
    how: 'rise 150 to 170 mm, going 250 to 400 mm, and 2R + G between 550 and 700 mm.',
    rMin: 150, rMax: 170, gMin: 250, gMax: 400, sum: [550, 700],
  },
];

// The failures of one stair against one authority, as short phrases. [] means it passes.
// Blondel is a line, so he is judged by how far the stair's pace is from his two feet,
// and never "passes" or "fails": see `offBlondel`.
export function failures(a, R, G) {
  const f = [];
  if (a.line) return f;
  if (a.rMin != null && a.rMax != null && a.rMin > a.rMax) f.push('no rise satisfies both limits');
  if (a.rMin != null && R < a.rMin - 1e-9) f.push(`rise under ${fmt(a.rMin)} mm`);
  if (a.rMax != null && R > a.rMax + 1e-9) f.push(`rise over ${fmt(a.rMax)} mm`);
  if (a.gMin != null && G < a.gMin - 1e-9) f.push(`going under ${fmt(a.gMin)} mm`);
  if (a.gMax != null && G > a.gMax + 1e-9) f.push(`going over ${fmt(a.gMax)} mm`);
  if (a.pitchMax != null && pitchDeg(R, G) > a.pitchMax + 1e-9) f.push(`steeper than ${a.pitchMax}°`);
  if (a.sum) {
    const s = blondelSum(R, G);
    if (s < a.sum[0] - 1e-9) f.push(`2R + G under ${a.sum[0]} mm`);
    if (s > a.sum[1] + 1e-9) f.push(`2R + G over ${a.sum[1]} mm`);
  }
  return f;
}
export const passes = (a, R, G) => !a.line && failures(a, R, G).length === 0;
export const offBlondel = (R, G) => blondelSum(R, G) - BLONDEL_PACE_MM;

// Every authority's verdict on one stair, for the readout.
export function assess(R, G) {
  return AUTHORITIES.map((a) => ({ id: a.id, name: a.name, line: !!a.line, pass: passes(a, R, G), why: failures(a, R, G) }));
}

// The corner a box code allows at its steepest: highest rise with shortest going.
export function steepestCorner(a) {
  if (a.rMax == null || a.gMin == null) return null;
  return { R: a.rMax, G: a.gMin, sum: blondelSum(a.rMax, a.gMin), off: offBlondel(a.rMax, a.gMin), pitch: pitchDeg(a.rMax, a.gMin) };
}

// Where Blondel's line leaves the UK private box at its 42° cap: R/G = tan 42°, 2R + G = pace.
export function blondelAtPitch(deg) {
  const t = Math.tan((deg * Math.PI) / 180);
  const G = BLONDEL_PACE_MM / (2 * t + 1);
  return { R: t * G, G };
}

// The stretch of Blondel's line that each authority admits, found by scanning R in 0.01 mm steps.
export function blondelSegment(a, from = 0, to = BLONDEL_PACE_MM / 2, step = 0.01) {
  let lo = null, hi = null;
  for (let R = from; R <= to + 1e-9; R += step) {
    const G = blondelGoing(R);
    if (G < 0) break;
    if (passes(a, R, G)) { if (lo == null) lo = R; hi = R; }
  }
  return lo == null ? null : { rFrom: lo, rTo: hi, gFrom: blondelGoing(lo), gTo: blondelGoing(hi) };
}

export const fmt = (x, d = 0) => (Math.round(x * 10 ** d) / 10 ** d).toFixed(d);

// The region an authority admits, as a polygon in (G, R) inside the plotted window, by clipping
// the window against each of its rules in turn (Sutherland-Hodgman). Empty array = no stair at all.
export const WINDOW = { gMax: 700, rMax: 300 };
export function regionPolygon(a, win = WINDOW) {
  if (a.line) return [];
  let poly = [[0, 0], [win.gMax, 0], [win.gMax, win.rMax], [0, win.rMax]]; // [G, R]
  const planes = []; // each: f(G, R) >= 0 keeps the point
  if (a.rMin != null) planes.push((g, r) => r - a.rMin);
  if (a.rMax != null) planes.push((g, r) => a.rMax - r);
  if (a.gMin != null) planes.push((g, r) => g - a.gMin);
  if (a.gMax != null) planes.push((g, r) => a.gMax - g);
  if (a.sum) { planes.push((g, r) => 2 * r + g - a.sum[0]); planes.push((g, r) => a.sum[1] - 2 * r - g); }
  if (a.pitchMax != null) { const t = Math.tan((a.pitchMax * Math.PI) / 180); planes.push((g, r) => t * g - r); }
  for (const f of planes) {
    const out = [];
    for (let i = 0; i < poly.length; i++) {
      const P = poly[i], Q = poly[(i + 1) % poly.length];
      const fp = f(P[0], P[1]), fq = f(Q[0], Q[1]);
      if (fp >= 0) out.push(P);
      if ((fp >= 0) !== (fq >= 0)) { const s = fp / (fp - fq); out.push([P[0] + s * (Q[0] - P[0]), P[1] + s * (Q[1] - P[1])]); }
    }
    poly = out;
    if (!poly.length) break;
  }
  return poly;
}
export function polygonArea(poly) {
  let s = 0;
  for (let i = 0; i < poly.length; i++) { const [x1, y1] = poly[i], [x2, y2] = poly[(i + 1) % poly.length]; s += x1 * y2 - x2 * y1; }
  return Math.abs(s) / 2;
}
