// engine.mjs: the geometry behind /strata/why-are-basalt-columns-hexagonal/ ("Six Before Anything Cools").
// Runs in the reader's browser and, unchanged, in verify-why-are-basalt-columns-hexagonal.mjs.
//
// Two machines, both exact about what they count:
//   1. a crack network in the unit square, built by splitting cells with straight cracks that end on
//      older cracks (every new junction is a T), whose junctions can then be pulled into Ys;
//   2. the Voronoi cells of points scattered on a torus (a square whose edges wrap round), for
//      points thrown at random and for points that keep a minimum distance apart.
// Corners are counted from the geometry, never from bookkeeping: a vertex is a corner of a cell
// unless the cell's boundary runs straight through it.

// ---------- a small seeded generator, so every picture can be drawn again ----------
export function rng(seed) {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6D2B79F5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// ---------- 1. the crack network ----------
// A network is { V: [{x,y}], cells: [[vertex ids, counter-clockwise]], junctions: Map id -> info }.
// Every vertex that is not a corner of the square frame is a junction where three crack segments meet.

export function square() {
  return { V: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], cells: [[0, 1, 2, 3]], frame: 4 };
}

export function area(net, c) {
  const p = net.cells[c];
  let s = 0;
  for (let i = 0; i < p.length; i++) {
    const a = net.V[p[i]], b = net.V[p[(i + 1) % p.length]];
    s += a.x * b.y - b.x * a.y;
  }
  return s / 2;
}

function centroid(net, c) {
  const p = net.cells[c];
  let cx = 0, cy = 0, A = 0;
  for (let i = 0; i < p.length; i++) {
    const a = net.V[p[i]], b = net.V[p[(i + 1) % p.length]];
    const k = a.x * b.y - b.x * a.y;
    A += k; cx += (a.x + b.x) * k; cy += (a.y + b.y) * k;
  }
  return { x: cx / (3 * A), y: cy / (3 * A) };
}

// the turn at vertex i of cell c, as sin of the angle between the incoming and outgoing edges
export function turn(net, c, i) {
  const p = net.cells[c], n = p.length;
  const a = net.V[p[(i - 1 + n) % n]], b = net.V[p[i]], d = net.V[p[(i + 1) % n]];
  const ux = b.x - a.x, uy = b.y - a.y, vx = d.x - b.x, vy = d.y - b.y;
  return (ux * vy - uy * vx) / (Math.hypot(ux, uy) * Math.hypot(vx, vy));
}

export const STRAIGHT = 1e-9; // |sin(turn)| below this, and the boundary runs straight through

export function corners(net, c) {
  const p = net.cells[c];
  let k = 0;
  for (let i = 0; i < p.length; i++) if (Math.abs(turn(net, c, i)) > STRAIGHT) k++;
  return k;
}

// Split cell c with the straight crack through point o in direction (dx,dy). The crack runs to the
// cell's own boundary at both ends and stops there, so each end is a new T (or meets the frame).
// Returns false if the line passes too close to an existing vertex (the caller draws again).
export function split(net, c, o, dx, dy) {
  const p = net.cells[c], n = p.length;
  const hits = [];
  for (let i = 0; i < n; i++) {
    const a = net.V[p[i]], b = net.V[p[(i + 1) % n]];
    const ex = b.x - a.x, ey = b.y - a.y;
    const den = dx * ey - dy * ex;
    if (Math.abs(den) < 1e-14) continue;
    const s = ((a.x - o.x) * ey - (a.y - o.y) * ex) / den; // along the crack
    const t = ((a.x - o.x) * dy - (a.y - o.y) * dx) / den; // along the edge
    if (t > -1e-12 && t < 1 + 1e-12) hits.push({ i, s, t, x: a.x + t * ex, y: a.y + t * ey, len: Math.hypot(ex, ey) });
  }
  if (hits.length !== 2) return false;
  for (const h of hits) if (h.t * h.len < 1e-4 || (1 - h.t) * h.len < 1e-4) return false; // too near a vertex
  if (Math.abs(hits[0].s - hits[1].s) < 1e-4) return false;
  hits.sort((u, v) => u.i - v.i);
  const ids = hits.map((h) => { net.V.push({ x: h.x, y: h.y }); return net.V.length - 1; });
  // the neighbour across each cut edge gains the new vertex on its own copy of that edge
  hits.forEach((h, k) => {
    const a = p[h.i], b = p[(h.i + 1) % n];
    for (let q = 0; q < net.cells.length; q++) {
      if (q === c) continue;
      const r = net.cells[q];
      for (let j = 0; j < r.length; j++) {
        if (r[j] === b && r[(j + 1) % r.length] === a) { r.splice(j + 1, 0, ids[k]); j = r.length; q = net.cells.length; }
      }
    }
  });
  const [h0, h1] = hits;
  const A = p.slice(0, h0.i + 1).concat([ids[0], ids[1]], p.slice(h1.i + 1));
  const B = [ids[0]].concat(p.slice(h0.i + 1, h1.i + 1), [ids[1]]);
  net.cells[c] = A;
  net.cells.push(B);
  return true;
}

// Grow a network of m cracks. Cells are picked with weight area^2 (big ones crack first, as a drying
// sheet does), and each crack runs near the cell's middle, across its longest direction. The picture
// depends on these choices; the corner count proved on the page does not.
export function crackNetwork(m, seed = 1) {
  const R = rng(seed), net = square();
  let guard = 0;
  while (net.cells.length < m + 1 && guard++ < 50 * (m + 1)) {
    const w = net.cells.map((_, c) => area(net, c) ** 2), tot = w.reduce((s, x) => s + x, 0);
    let u = R() * tot, c = 0;
    while (c < w.length - 1 && u > w[c]) u -= w[c++];
    const g = centroid(net, c);
    // longest direction: principal axis of the cell's vertices
    let sxx = 0, syy = 0, sxy = 0;
    for (const v of net.cells[c]) { const X = net.V[v].x - g.x, Y = net.V[v].y - g.y; sxx += X * X; syy += Y * Y; sxy += X * Y; }
    const axis = 0.5 * Math.atan2(2 * sxy, sxx - syy);
    const th = axis + Math.PI / 2 + (R() - 0.5) * 0.9;
    const jit = Math.sqrt(area(net, c)) * 0.18;
    const o = { x: g.x + (R() - 0.5) * jit, y: g.y + (R() - 0.5) * jit };
    split(net, c, o, Math.cos(th), Math.sin(th));
  }
  return net;
}

// Every junction, classified from the geometry: T if one of the cells meeting there sees a straight
// line through it, Y if none does. Frame vertices (on the square's edge) are listed separately.
export function junctions(net) {
  const at = new Map();
  net.cells.forEach((p, c) => p.forEach((v, i) => { if (!at.has(v)) at.set(v, []); at.get(v).push({ c, i }); }));
  const out = { T: [], Y: [], frame: [], corner4: [] };
  for (const [v, list] of at) {
    if (v < 4) { out.corner4.push(v); continue; }
    const P = net.V[v];
    const onFrame = P.x < 1e-12 || P.y < 1e-12 || P.x > 1 - 1e-12 || P.y > 1 - 1e-12;
    if (onFrame) { out.frame.push(v); continue; }
    const straight = list.filter(({ c, i }) => Math.abs(turn(net, c, i)) <= STRAIGHT);
    (straight.length ? out.T : out.Y).push({ v, through: straight.map((s) => s.c), cells: list.map((s) => s.c) });
  }
  return out;
}

export function tally(net) {
  const F = net.cells.length;
  let C = 0;
  const hist = {};
  for (let c = 0; c < F; c++) { const k = corners(net, c); C += k; hist[k] = (hist[k] || 0) + 1; }
  const J = junctions(net);
  return { F, C, mean: C / F, hist, T: J.T.length, Y: J.Y.length, frame: J.frame.length };
}

// The count the page proves. Each interior junction gives a corner to every cell that meets there
// except, at a T, the one whose side runs straight through it: 3 corners at a Y, 2 at a T. Each frame
// junction gives 2, and the square's own corners 1 each. So C = 3Y + 2T + 2(frame) + 4 exactly.
export function predictedCorners({ T, Y, frame }) { return 3 * Y + 2 * T + 2 * frame + 4; }

// Pull T junction v into a Y: move it a short way off the straight line, away from the crack that
// ends there. Neighbouring junctions on the same straight line may stop being straight as a result;
// the count above does not care which, it only asks what the geometry is.
export function pullToY(net, j, frac = 0.3) {
  const v = j.v, P = net.V[v];
  const c = j.through[0], p = net.cells[c], i = p.indexOf(v), n = p.length;
  const a = net.V[p[(i - 1 + n) % n]], b = net.V[p[(i + 1) % n]];
  // inward normal of cell c (counter-clockwise cell: interior on the left of a->b)
  let nx = -(b.y - a.y), ny = b.x - a.x;
  const L = Math.hypot(nx, ny); nx /= L; ny /= L;
  const d = frac * Math.min(Math.hypot(P.x - a.x, P.y - a.y), Math.hypot(P.x - b.x, P.y - b.y), Math.sqrt(Math.abs(area(net, c))) * 0.5);
  P.x += nx * d; P.y += ny * d;
}

export function clone(net) { return { V: net.V.map((v) => ({ ...v })), cells: net.cells.map((p) => p.slice()), frame: net.frame }; }

// Simple polygon test (no two non-adjacent edges cross), for the verifier.
export function simple(net, c) {
  const p = net.cells[c].map((v) => net.V[v]), n = p.length;
  const X = (a, b, c2, d) => {
    const o = (p1, p2, p3) => Math.sign((p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x));
    return o(a, b, c2) * o(a, b, d) < 0 && o(c2, d, a) * o(c2, d, b) < 0;
  };
  for (let i = 0; i < n; i++) for (let j = i + 2; j < n; j++) {
    if (i === 0 && j === n - 1) continue;
    if (X(p[i], p[(i + 1) % n], p[j], p[(j + 1) % n])) return false;
  }
  return true;
}

// ---------- 2. Voronoi cells on a torus ----------
// Points in the unit torus. For each point, clip a square by the perpendicular bisectors to nearby
// points (and their wrapped copies); the number of edges left is the number of sides of its cell.

export function poissonPoints(n, seed = 1) {
  const R = rng(seed), P = [];
  for (let i = 0; i < n; i++) P.push({ x: R(), y: R() });
  return P;
}

// Random sequential adsorption: throw discs of diameter d at random, keep each only if it overlaps
// none already kept. phi is the fraction of the area the discs cover once n are placed.
export function hardcorePoints(n, phi, seed = 1) {
  const R = rng(seed), d = Math.sqrt((4 * phi) / (Math.PI * n)), P = [];
  const G = Math.max(1, Math.floor(1 / d)), cell = 1 / G, grid = Array.from({ length: G * G }, () => []);
  let tries = 0;
  while (P.length < n && tries++ < 400 * n) {
    const x = R(), y = R(), gx = Math.floor(x / cell) % G, gy = Math.floor(y / cell) % G;
    let ok = true;
    for (let ix = -1; ix <= 1 && ok; ix++) for (let iy = -1; iy <= 1 && ok; iy++) {
      for (const q of grid[((gx + ix + G) % G) * G + ((gy + iy + G) % G)]) {
        let dx = Math.abs(x - q.x), dy = Math.abs(y - q.y);
        if (dx > 0.5) dx = 1 - dx; if (dy > 0.5) dy = 1 - dy;
        if (dx * dx + dy * dy < d * d) { ok = false; break; }
      }
    }
    if (ok) { const q = { x, y }; P.push(q); grid[gx * G + gy].push(q); }
  }
  return P;
}

function clip(poly, nx, ny, c) { // keep n.x <= c
  const out = [];
  for (let i = 0; i < poly.length; i++) {
    const a = poly[i], b = poly[(i + 1) % poly.length];
    const fa = nx * a.x + ny * a.y - c, fb = nx * b.x + ny * b.y - c;
    if (fa <= 0) out.push(a);
    if ((fa < 0 && fb > 0) || (fa > 0 && fb < 0)) { const t = fa / (fa - fb); out.push({ x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) }); }
  }
  return out;
}

// Returns, for each point, its cell polygon (in unwrapped coordinates around the point) and its sides.
export function voronoiTorus(P) {
  const n = P.length, G = Math.max(1, Math.floor(Math.sqrt(n / 2))), grid = Array.from({ length: G * G }, () => []);
  P.forEach((p, i) => grid[Math.min(G - 1, Math.floor(p.x * G)) * G + Math.min(G - 1, Math.floor(p.y * G))].push(i));
  const cells = [];
  for (let i = 0; i < n; i++) {
    const p = P[i];
    let poly = [{ x: p.x - 0.5, y: p.y - 0.5 }, { x: p.x + 0.5, y: p.y - 0.5 }, { x: p.x + 0.5, y: p.y + 0.5 }, { x: p.x - 0.5, y: p.y + 0.5 }];
    const gx = Math.min(G - 1, Math.floor(p.x * G)), gy = Math.min(G - 1, Math.floor(p.y * G));
    for (let ring = 0; ring <= G; ring++) {
      // points within `ring` grid cells are all at least ring/G away beyond it; stop once the cell is inside that
      let rmax = 0;
      for (const q of poly) rmax = Math.max(rmax, Math.hypot(q.x - p.x, q.y - p.y));
      if (ring >= 2 && 2 * rmax < (ring - 1) / G) break;
      const seen = new Set();
      for (let ix = -ring; ix <= ring; ix++) for (let iy = -ring; iy <= ring; iy++) {
        if (Math.max(Math.abs(ix), Math.abs(iy)) !== ring) continue;
        const key = (((gx + ix) % G) + G) % G * G + ((((gy + iy) % G) + G) % G);
        if (seen.has(key)) continue; seen.add(key);
        for (const j of grid[key]) {
          if (j === i) continue;
          const q = P[j];
          for (let wx = -1; wx <= 1; wx++) for (let wy = -1; wy <= 1; wy++) {
            const qx = q.x + wx, qy = q.y + wy;
            const nx = qx - p.x, ny = qy - p.y;
            if (Math.hypot(nx, ny) > 2 * rmax + 1e-12) continue;
            poly = clip(poly, nx, ny, (nx * (qx + p.x) + ny * (qy + p.y)) / 2);
          }
        }
      }
      if (ring === G) break;
    }
    // merge vertices closer than 1e-10 (degenerate slivers)
    const clean = poly.filter((a, k) => { const b = poly[(k + 1) % poly.length]; return Math.hypot(a.x - b.x, a.y - b.y) > 1e-10; });
    cells.push({ poly: clean, sides: clean.length });
  }
  return cells;
}

export function stats(sides) {
  const n = sides.length, hist = {};
  let s = 0, s2 = 0;
  for (const k of sides) { hist[k] = (hist[k] || 0) + 1; s += k; }
  const mean = s / n;
  for (const k of sides) s2 += (k - mean) ** 2;
  return { n, mean, mu2: s2 / n, hist, hex: (hist[6] || 0) / n };
}

// Mean corners for a network in which a fraction t of the junctions are T: 6 - 2t, in the limit of
// many cells (each junction is shared by three cells and gives 3 corners at a Y, 2 at a T; a network
// of trivalent junctions has half as many cells as junctions).
export const meanFromT = (t) => 6 - 2 * t;
export const tFromMean = (m) => (6 - m) / 2;

// P. Calka (2003), Table 1: the share of cells with k sides in the Voronoi diagram of an infinite
// random (Poisson) scatter of points in the plane, k = 3..9 (his values, obtained by Monte Carlo).
export const CALKA = { 3: 0.011240, 4: 0.106838, 5: 0.25946, 6: 0.29473, 7: 0.19877, 8: 0.0897, 9: 0.0295 };
export const POISSON_HEX = CALKA[6];

// The yardsticks the page quotes: mean spread of sides over `draws` scatters of n points.
export function spread(phi, n = 3000, draws = 8) {
  let hex = 0, mu2 = 0, got = 0;
  for (let s = 1; s <= draws; s++) {
    const P = phi ? hardcorePoints(n, phi, s) : poissonPoints(n, s);
    const st = stats(voronoiTorus(P).map((c) => c.sides));
    hex += st.hex; mu2 += st.mu2; got += P.length;
  }
  return { phi, hex: hex / draws, mu2: mu2 / draws, sigma: Math.sqrt(mu2 / draws), n: got / draws };
}
