// engine.mjs: the arithmetic behind /strata/why-are-bricks-that-size/ ("Two Headers and a Joint").
// Runs in the reader's browser and, unchanged, in verify-why-are-bricks-that-size.mjs.
// Every length is in millimetres. L = length, W = width (bed depth), H = height, j = joint.

// Brick formats as their sources state them. `src` names an entry in the page's source list;
// `joint` is the nominal joint the source gives (null when that source gives none).
// Filled from the sources in assay/sources/why-are-bricks-that-size.json.
const IN = 25.4;
export const FORMATS = [
  // modern standards and the sizes their industries publish
  { id: 'uk', short: 'UK', label: 'United Kingdom (BS 3921, now BS EN 771-1)', L: 215, W: 102.5, H: 65, joint: 10, bed: 10, src: 'bda', dx: 8, dy: 12 },
  { id: 'us', short: 'US modular', label: 'United States, modular (BIA Technical Note 10)', L: 7.625 * IN, W: 3.625 * IN, H: 2.25 * IN, joint: 0.375 * IN, src: 'tn10', dx: -8, anchor: 'end' },
  { id: 'de-nf', short: 'DE NF, China', label: 'Germany, Normalformat (NF)', L: 240, W: 115, H: 71, joint: 10, bed: 12.3, src: 'de', dx: -8, dy: -4, anchor: 'end' },
  { id: 'de-df', short: 'DE DF', label: 'Germany, Dünnformat (DF)', L: 240, W: 115, H: 52, joint: 10, bed: 10.5, src: 'de', hidden: true },
  { id: 'de-2df', short: 'DE 2DF', label: 'Germany, 2DF', L: 240, W: 115, H: 113, joint: 10, src: 'de', hidden: true },
  { id: 'cn', short: 'China', label: 'China (GB/T 5101)', L: 240, W: 115, H: 53, joint: 10, src: 'cn', hidden: true },
  { id: 'dk', short: 'Denmark', label: 'Denmark, Dansk normalformat', L: 228, W: 108, H: 54, joint: 12, bed: 12, src: 'dk', dx: -8, dy: 4, anchor: 'end' },
  { id: 'se', short: 'Sweden', label: 'Sweden, svenskt normalformat', L: 250, W: 120, H: 62, joint: null, src: 'se', dx: -8, dy: -4, anchor: 'end' },
  { id: 'ru', short: 'Russia', label: 'Russia, 1 NF (GOST 530-2012)', L: 250, W: 120, H: 65, joint: 10, bed: 12, src: 'ru', dx: 8, dy: 0 },
  { id: 'ru-14', short: 'RU 1.4 NF', label: 'Russia, 1.4 NF', L: 250, W: 120, H: 88, joint: 10, bed: 12, src: 'ru', hidden: true },
  { id: 'nl', short: 'NL Waal', label: 'Netherlands, Waalformaat', L: 210, W: 100, H: 50, joint: 10, bed: 10, src: 'nl', dx: -8, anchor: 'end' },
  { id: 'nl-dik', short: 'NL Waaldik', label: 'Netherlands, Waaldikformaat', L: 210, W: 100, H: 65, joint: 10, bed: 10, src: 'nl', hidden: true },
  { id: 'jp', short: 'Japan', label: 'Japan (JIS R 1250)', L: 210, W: 100, H: 60, joint: null, src: 'jp', dx: 8, dy: 12 },
  { id: 'in-mod', short: 'India modular', label: 'India, modular (IS 1077)', L: 190, W: 90, H: 90, joint: 10, src: 'in', dx: 8, dy: 10 },
  { id: 'in-non', short: 'India', label: 'India, non-modular (IS 1077)', L: 230, W: 110, H: 70, joint: null, src: 'in', hidden: true },
  { id: 'au', short: 'Australia, India', label: 'Australia', L: 230, W: 110, H: 76, joint: 10, src: 'au', lx: 124, ly: 234 },
  { id: 'za', short: 'South Africa', label: 'South Africa', L: 222, W: 106, H: 73, joint: 12, src: 'za', dx: 8, dy: 12 },
  // other formats in the same sources, which the sum does not fit
  { id: 'ru-07', short: 'RU 0.7 NF', label: 'Russia, 0.7 NF (GOST 530-2012)', L: 250, W: 85, H: 65, joint: 10, src: 'ru', kind: 'other', dx: 8, dy: 4 },
  { id: 'ru-13', short: 'RU 1.3 NF', label: 'Russia, 1.3 NF (GOST 530-2012)', L: 288, W: 138, H: 65, joint: 10, src: 'ru', kind: 'other', dx: -8, anchor: 'end' },
  { id: 'nl-limburg', short: 'Limburg', label: 'Netherlands, Limburgse steen', L: 240, W: 120, H: 65, joint: null, src: 'nl', kind: 'other', dx: 8, dy: 4 },
  { id: 'nl-groningen', short: 'Groningen', label: 'Netherlands, Groninger steen', L: 240, W: 120, H: 60, joint: null, src: 'nl', kind: 'other', hidden: true },
  { id: 'nl-moef', short: 'Moef', label: 'Netherlands, Moef', L: 215, W: 100, H: 65, joint: null, src: 'nl', kind: 'other', dx: -8, dy: -4, anchor: 'end' },
  { id: 'nl-brabant', short: 'Brabant', label: 'Netherlands, Brabantse steen', L: 180, W: 88, H: 53, joint: null, src: 'nl', kind: 'other', dx: 8, dy: 4 },
  // a three-to-one brick: bonds at thirds, L = 3W + 2j
  { id: 'us-norman', short: 'US Norman', label: 'United States, Norman (three widths long)', L: 11.625 * IN, W: 3.625 * IN, H: 2.25 * IN, joint: 0.375 * IN, n: 3, src: 'tn10', kind: 'three', dx: 8, dy: 4 },
  // four English rules, in inches, and the size an encyclopedia gave for one of them
  { id: 'e1571', short: '1571', label: 'London, Tylers and Bricklayers ordinance, 1571', L: 9 * IN, W: 4.25 * IN, H: 2.25 * IN, joint: null, src: 'tylers', kind: 'old', lx: 124, ly: 216 },
  { id: 'e1625', short: '1625', label: 'London, proclamation of Charles I, 1625', L: 9 * IN, W: 4.375 * IN, H: 2.25 * IN, joint: null, src: 'dowell', kind: 'old', lx: 124, ly: 222 },
  { id: 'e1725', short: '1725', label: 'Act of 1725 (12 Geo. I c. 35), place bricks', L: 9 * IN, W: 4.25 * IN, H: 2.5 * IN, joint: null, src: 'act1725', kind: 'old', hidden: true },
  { id: 'e1777', short: '1777', label: 'Act of 1777 (17 Geo. III c. 42), minimums, any part of England', L: 8.5 * IN, W: 4 * IN, H: 2.5 * IN, joint: null, src: 'act1777', kind: 'old', lx: 124, ly: 210 },
  { id: 'eb1911', short: 'EB 1911', label: 'what the 1911 Britannica says the 1625 size was', L: 9 * IN, W: 4.5 * IN, H: 3 * IN, joint: null, src: 'eb1911', kind: 'claimed', lx: 124, ly: 228 },
  // the ancient proportion: two widths long, and no joint
  { id: 'harappa', short: 'Harappa', label: 'Harappan brick, 7 × 14 × 28 cm (the 1:2:4 proportion)', L: 280, W: 140, H: 70, joint: null, src: 'kak', kind: 'ancient', dx: 8, dy: 4 },
  { id: 'eridu', short: 'Eridu', label: 'Eridu, Uruk period, 26 × 13 × 7 cm', L: 260, W: 130, H: 70, joint: null, src: 'hnaihen', kind: 'ancient', dx: 8, dy: 4 },
  // one row printed with no source
  { id: 'wp-cn', short: 'China as Wikipedia prints it', label: "China, as English Wikipedia's table prints it (240 × 155 × 53)", L: 240, W: 155, H: 53, joint: null, src: 'wp', kind: 'wrong', dx: -8, anchor: 'end' },
];
// The principal formats: every modern two-to-one format above that is not marked 'other'.
export const STANDARDS = FORMATS.filter((f) => !f.kind);

// UK joint limits (NHBC Standards, chapter 6.1): not less than 6 mm nor more than 15 mm.
export const JMIN = 6, JMAX = 15;

// The joint every format is judged against when its source names none.
export const DEFAULT_JOINT = 10;

// How far the rule misses: a header course lays two headers and one joint (2W + j) where the
// stretcher course lays one stretcher (L). Zero means the two courses agree exactly.
export function residual(L, W, j = DEFAULT_JOINT) {
  return L - 2 * W - j;
}

// The general form: a brick n widths long, with n - 1 joints between the widths.
export function residualN(L, W, j = DEFAULT_JOINT, n = 2) {
  return L - n * W - (n - 1) * j;
}

// The joint the rule implies: what the joint would have to be for two headers to fill one stretcher.
export function impliedJoint(L, W) {
  return L - 2 * W;
}

// A mason laying English bond keeps the stretcher courses' perpends at `j` and may open or close
// the header courses' perpends. Two headers and their joint then fill one stretcher and its joint
// when 2(W + jh) = L + j, so jh = (L + j)/2 - W. The mismatch is absorbed if jh lies within
// [jmin, jmax]; otherwise the courses drift.
export function headerPerpToAbsorb(L, W, j = DEFAULT_JOINT) {
  return (L + j) / 2 - W;
}
export function absorbable(L, W, j, jmin, jmax) {
  const jh = headerPerpToAbsorb(L, W, j);
  return { jh, ok: jh >= jmin - 1e-9 && jh <= jmax + 1e-9 };
}

// The band of lengths a bricklayer can bond without cutting, for a given width, if every perpend
// may be anything in [jmin, jmax]: L + js = 2(W + jh) with js, jh in range gives
// L in [2W + 2 jmin - jmax, 2W + 2 jmax - jmin].
export function bondBand(W, jmin, jmax) {
  return [2 * W + 2 * jmin - jmax, 2 * W + 2 * jmax - jmin];
}

// ---- walls -----------------------------------------------------------------------------------
// A wall face is drawn from a corner at x = 0 rightwards, `len` mm long, `courses` high.
// Each course is a list of pieces {x0, x1, kind}; kind is 'S' (stretcher face), 'H' (header
// face), 'C' (queen closer) or 'E' (the end of the return wall's brick, seen as a header).
// A perpend is the centre of a vertical joint between two pieces.

function run(start, pitch, width, kind, len, pieces) {
  for (let x = start; x < len; x += pitch) pieces.push({ x0: x, x1: Math.min(x + width, len), kind, cut: x + width > len });
}

// English bond: courses alternate all-stretchers and all-headers. The header course turns the
// corner with the return wall's stretcher end (width W), then a queen closer of (W - j)/2, which
// is what puts every header perpend a quarter brick from a stretcher perpend when L = 2W + j.
// `jh` is the header courses' perpend (defaults to j: nobody adjusts anything).
export function englishBond({ L, W, H, j, jh = j, len, courses }) {
  const out = [];
  const q = (W - j) / 2;
  for (let c = 0; c < courses; c++) {
    const pieces = [];
    if (c % 2 === 0) run(0, L + j, L, 'S', len, pieces);
    else {
      pieces.push({ x0: 0, x1: W, kind: 'E' });
      pieces.push({ x0: W + j, x1: W + j + q, kind: 'C' });
      run(W + j + q + jh, W + jh, W, 'H', len, pieces);
    }
    out.push({ y0: c * (H + j), y1: c * (H + j) + H, pieces });
  }
  return out;
}

// Stretcher bond (a half-brick wall): every course is stretchers; alternate courses start with
// the return wall's stretcher end, so their perpends sit L - W from the course below's. Half
// bond wants that to be half a stretcher-and-joint, (L + j)/2, which is again L = 2W + j.
export function stretcherBond({ L, W, H, j, len, courses }) {
  const out = [];
  for (let c = 0; c < courses; c++) {
    const pieces = [];
    if (c % 2 === 0) run(0, L + j, L, 'S', len, pieces);
    else {
      pieces.push({ x0: 0, x1: W, kind: 'E' });
      run(W + j, L + j, L, 'S', len, pieces);
    }
    out.push({ y0: c * (H + j), y1: c * (H + j) + H, pieces });
  }
  return out;
}

// Perpends of a course: midpoints between consecutive pieces that are both inside the wall.
export function perpends(course) {
  const p = [];
  for (let i = 1; i < course.pieces.length; i++) {
    const a = course.pieces[i - 1], b = course.pieces[i];
    if (a.cut) break;
    p.push((a.x1 + b.x0) / 2);
  }
  return p;
}

// Lap: for each perpend in course c (c >= 1), the distance to the nearest perpend in course c - 1.
// A lap below the joint width means the two vertical joints overlap: a straight joint.
export function laps(courses) {
  const res = [];
  for (let c = 1; c < courses.length; c++) {
    const below = perpends(courses[c - 1]);
    for (const x of perpends(courses[c])) {
      let d = Infinity;
      for (const y of below) d = Math.min(d, Math.abs(x - y));
      if (d < Infinity) res.push({ course: c, x, lap: d });
    }
  }
  return res;
}

// The first place along a wall where a lap falls below `limit` (default: the joint, a straight joint).
export function firstBelow(lapList, limit) {
  let best = null;
  for (const l of lapList) if (l.lap < limit && (!best || l.x < best.x)) best = l;
  return best;
}

// Course heights: how many courses of H + bed joint make a round module.
export function coursesTo(H, bed, module) {
  return module / (H + bed);
}
