// ========================================================================
// movement.js
// ========================================================================

// movement.js — the watch's dimensions and its motion, in ONE place.
//
// Both the recipe (models.mjs) and the page (app.js) import this. That is the
// kit's rule and it is not a style preference: the recipe bakes a rest pose into
// the .glb and the page un-bakes it and drives it every frame, so a second copy
// of any number is two descriptions of one mechanism that disagree the moment
// either is touched. A separate *.motion.mjs would make it three.
//
// SCALE. 1 unit = 1 metre, so this thing is small: a real "18 size" pocket watch
// is about 50mm across the case and 15mm through. Every dimension below is a
// fraction of the case diameter and named for what it is a fraction OF, because
// a coefficient written against the wrong quantity is the single most repeated
// defect in this kit's history.

export const D = {
  caseD: 0.050,                    // outside diameter of the case band
};
D.caseR = D.caseD / 2;
D.bandH = D.caseD * 0.15;          // the straight middle of the case, 7.5mm
// HOW DEEP THE COVER IS, and it is not a lid — it is a shallow BOWL. The
// reference's cover is strongly domed and has real wall thickness; a flat one
// reads as foil. This also buys the hands room: at 0.075 the inner face at the
// hands' radius sat 0.45mm INSIDE the sweep of the second hand.
D.coverRise = D.caseD * 0.115;
// THE COVER'S OWN THICKNESS, and it is the whole reason the lid reads as metal
// rather than as foil. At 0.013 (0.65mm) the rim was a hairline you had to look
// for; a real hunter lid is a pressed shell you can see the edge of from across
// a table. 1.75mm, which on a 50mm case is what the photograph shows.
D.coverWall = D.caseD * 0.035;
// THE COVER IS NARROWER THAN THE BAND, so the case's edge stands proud of it —
// in the photograph you can see the band's rim outside the closed cover, which
// is what stops the case reading as one moulded lump.
D.coverR = D.caseR - D.caseD * 0.013;
// HOW FAR THE BEZEL STANDS ABOVE THE BAND, which is where the closed lid SEATS.
// The bezel and the cover both need this number and it belongs to the fixed one
// of the two: seating the lid on the band instead put it 0.45mm through the
// bezel it is supposed to rest on.
D.bezelProud = D.caseD * 0.009;
D.bezelW = D.caseD * 0.045;        // the polished ring around the crystal
D.crystalR = D.caseR - D.bezelW;
D.dialR = D.crystalR * 0.985;

// The dial, as fractions of the DIAL radius — these set the whole face.
D.trackOuter = 0.985;              // outside of the minute track
D.trackInner = 0.855;              // where the minute track stops
D.numOuter = 0.840;                // the Roman chapter ring
D.numInner = 0.620;
// THE APERTURE, MEASURED OFF THE REFERENCE rather than guessed. Side by side,
// the photograph's cut-away is roughly two thirds of the dial and mine was a
// little over half — which is why its movement reads as a mechanism and mine
// read as a scatter of small cogs in a lot of empty gold.
D.apertureR = 0.660;

// The pendant stack, upward from the case rim at 12 o'clock.
D.collarR = D.caseD * 0.075;       // the three stacked rings
D.collarH = D.caseD * 0.090;
D.bulbR = D.caseD * 0.115;         // the onion body
D.bulbH = D.caseD * 0.130;
D.crownR = D.caseD * 0.105;        // the fluted winding crown
D.crownH = D.caseD * 0.085;
D.crownFlutes = 20;
D.bowR = D.caseD * 0.150;          // the ring, measured to its CENTRELINE
D.bowWire = D.caseD * 0.022;

// THE HINGE IS AT SIX O'CLOCK, opposite the pendant. It was at twelve, which is
// where the bow and the crown are: the cover swung up THROUGH the pendant stack
// and read as opening from the top. A hunter's lid hinges away from its pendant
// so the thumb can lift the free edge under the crown. Its position is derived from the band, never typed
// beside it: two parts that meet have one line and it belongs to the fixed one.
D.hingeA = -Math.PI / 2;                       // at SIX o'clock
D.hingeR = D.caseR + D.caseD * 0.012;
D.hinge = [Math.cos(D.hingeA) * D.hingeR, D.bandH * 0.5, -Math.sin(D.hingeA) * D.hingeR];

/** Where the hands sit, so nothing re-derives it. */
export const GEO = {
  // HOW FAR THE WHOLE WATCH IS LIFTED so it stands on its rim. The recipe
  // translates by it and the page pivots about it, so it cannot live in either
  // — a hand rotating about y = 0 when the arbor is at y = 0.025 sweeps through
  // a 25mm circle instead of spinning on the spot.
  lift: D.caseR + D.caseD * 0.004,
  dialZ: D.bandH * 0.5 + D.caseD * 0.004,       // dial face, just inside the crystal
  handZ: D.bandH * 0.5 + D.caseD * 0.008,     // under the closed cover, measured
  // NINETY DEGREES, no more. It swung 261 degrees, which folds the lid right
  // back against the case and reads as a bin flipping open rather than as a
  // watch being opened.
  coverOpen: Math.PI * 0.5,
  // THE POSE THE .glb IS BAKED IN, and it is not a detail. A model page renders
  // the file as it stands — no rig, no animation — so a hunter baked SHUT is a
  // gold disc on its own page, with the dial, the applied numerals and the whole
  // movement hidden behind a lid nobody can open. The rest pose is the picture
  // everyone sees first, so it is the one worth choosing.
  restOpen: Math.PI * 0.5,
};

/** Hand angles for a time, in radians CLOCKWISE from 12. */
export function hands(hours, minutes, seconds = 0) {
  const m = minutes + seconds / 60;
  const h = (hours % 12) + m / 60;
  return { hour: (h / 12) * Math.PI * 2, minute: (m / 60) * Math.PI * 2, second: (seconds / 60) * Math.PI * 2 };
}

// ── the going train ─────────────────────────────────────────────────────────
//
// ONE NUMBER DRIVES EVERYTHING, and it is seconds. A watch is a gear train, so
// every wheel's angle is that one value times a ratio — the hands are not
// animated alongside the wheels, they are geared to them, which is the whole
// reason the hour hand cannot drift away from the minute hand.
//
// `turns` is revolutions per second of elapsed time, signed for the direction
// the wheel actually runs: meshed wheels turn OPPOSITE ways, and a train drawn
// with every wheel spinning the same way is the thing everybody notices and
// nobody can name.
const SPEC = [
  //  name          r (of aperture)   where it sits            teeth  turns/s
  { name: "centreWheel", r: 0.30, at: [0, 0], teeth: 48 },
  { name: "thirdWheel", r: 0.235, at: [0.44, 0.30], teeth: 36 },
  { name: "fourthWheel", r: 0.205, at: [-0.42, -0.34], teeth: 32 },
  { name: "escapeWheel", r: 0.135, at: [0.30, -0.46], teeth: 15 },
  // EVERY WHEEL BELOW IS PLACED BY WHAT IT MESHES WITH, at a bearing, rather
  // than by a typed coordinate. Two gears mesh when their centres are one pitch
  // radius apart EACH, so deriving the position from `mesh` + `at` makes that
  // true by construction — and a pair that merely sits near another pair is the
  // thing that reads as ornament instead of as a mechanism.
  { name: "barrelWheel", r: 0.25, mesh: "centreWheel", bearing: 180, teeth: 40 },
  { name: "idlerWheel", r: 0.155, mesh: "thirdWheel", bearing: -52, teeth: 20 },
  { name: "crownWheel", r: 0.135, mesh: "barrelWheel", bearing: 84, teeth: 18 },
  { name: "ratchetWheel", r: 0.115, mesh: "fourthWheel", bearing: -74, teeth: 15 },
  { name: "centrePinion", r: 0.072, mesh: "centreWheel", bearing: -108, teeth: 10 },
  { name: "escapePinion", r: 0.062, mesh: "escapeWheel", bearing: 26, teeth: 8 },
  // A SECOND LAYER, to fill the middle. A skeleton dial is cut away so you can
  // see a mechanism, and a mechanism with daylight round it is a diagram. These
  // sit slightly deeper than the going train (see `tier`), which is what a real
  // movement does — the motion work runs under the dial, not beside it.
  { name: "minuteWheel", r: 0.235, mesh: "centreWheel", bearing: 68, teeth: 30, tier: 1 },
  { name: "hourWheel", r: 0.255, mesh: "minuteWheel", bearing: 168, teeth: 34, tier: 1 },
  { name: "setWheel", r: 0.195, mesh: "centreWheel", bearing: -62, teeth: 26, tier: 1 },
  { name: "castleWheel", r: 0.165, mesh: "setWheel", bearing: -8, teeth: 22, tier: 1 },
  { name: "clickWheel", r: 0.150, mesh: "barrelWheel", bearing: -74, teeth: 20, tier: 1 },
  { name: "transferWheel", r: 0.185, mesh: "fourthWheel", bearing: 52, teeth: 24, tier: 1 },
  { name: "crownPinion", r: 0.115, mesh: "crownWheel", bearing: 150, teeth: 15, tier: 1 },
  { name: "sweepWheel", r: 0.175, mesh: "idlerWheel", bearing: 118, teeth: 19, tier: 1 },
  { name: "detentWheel", r: 0.140, mesh: "ratchetWheel", bearing: 132, teeth: 19, tier: 1 },
  // OUT TO THE RIM. Varying sizes deliberately — a field of equal discs reads as
  // a pattern, and it is the mix of a big slow wheel against a small quick one
  // that makes a movement look like it is doing something.
  { name: "rimWheelA", r: 0.155, mesh: "centreWheel", bearing: 118, teeth: 27, tier: 1 },
  { name: "rimWheelB", r: 0.125, mesh: "thirdWheel", bearing: 62, teeth: 17, tier: 1 },
  { name: "rimWheelC", r: 0.235, mesh: "transferWheel", bearing: -108, teeth: 31, tier: 1 },
  { name: "rimWheelD", r: 0.098, mesh: "escapeWheel", bearing: -96, teeth: 13, tier: 1 },
  { name: "rimWheelE", r: 0.135, mesh: "clickWheel", bearing: 226, teeth: 22, tier: 1 },
  { name: "rimWheelF", r: 0.088, mesh: "idlerWheel", bearing: 12, teeth: 12, tier: 1 },
  { name: "rimWheelG", r: 0.125, mesh: "setWheel", bearing: -128, teeth: 19, tier: 1 },
  { name: "rimWheelH", r: 0.112, mesh: "sweepWheel", bearing: 40, teeth: 15, tier: 1 },
];

/**
 * Resolve every `mesh` into a POSITION and a SPEED, once, where both halves see it.
 *
 * Speed used to be typed per wheel and that was wrong twice over. Two meshed
 * wheels turn in OPPOSITE directions at rates inversely proportional to their
 * radii — that is what meshing means — so typing it invites a train where
 * neighbours drift the same way, which everybody notices and nobody can name.
 * Derived from the graph, it cannot be inconsistent.
 *
 * THE RANGE IS COMPRESSED ON PURPOSE, and this is the one honest liberty here.
 * A real going train spans four orders of magnitude: with true ratios the
 * escape wheel is a blur while the barrel turns once every eight hours, so half
 * the movement looks broken and the other half looks frozen. `1/r` keeps the
 * relative sense — small wheels genuinely faster, meshed pairs genuinely
 * opposed — inside a range where every wheel is visibly turning. The HANDS are
 * not part of this: they run on real clock time.
 */
const DISPLAY = 0.0055;         // revolutions per second, times 1/r

export const TRAIN = (() => {
  const out = [];
  for (const w of SPEC) {
    if (!w.mesh) {
      // The hand-placed four have no neighbour to take a direction from, so they
      // alternate: four wheels all drifting the same way reads as a conveyor.
      out.push({ ...w, turns: (out.length % 2 ? -1 : 1) * (DISPLAY / w.r) });
      continue;
    }
    const host = out.find((x) => x.name === w.mesh);
    if (!host) throw new Error(`TRAIN: ${w.name} meshes with ${w.mesh}, which is not placed yet`);
    const a = (w.bearing * Math.PI) / 180;
    const d = host.r + w.r;                       // one pitch radius each: that IS meshing
    out.push({
      ...w,
      at: [host.at[0] + Math.cos(a) * d, host.at[1] + Math.sin(a) * d],
      // Opposite the wheel it runs against, and faster in proportion as it is
      // smaller. Both fall out of the same line.
      turns: -Math.sign(host.turns) * (DISPLAY / w.r),
    });
  }
  return out;
})();

/** The balance: a harmonic oscillator at 2.5 Hz, which is 5 beats a second. */
export const balanceAt = (t, amp = 1.15) => Math.sin(t * Math.PI * 5) * amp;
export const BALANCE = { r: 0.40, at: [-0.30, 0.44] };

/** Every driven angle at time `t` seconds, from one value. */
export function poseAt(t, open = 0) {
  const h = hands(10, 9, t);
  const wheels = {};
  for (const w of TRAIN) wheels[w.name] = w.turns * t * Math.PI * 2;
  return { ...h, wheels, balance: balanceAt(t), open };
}

// A hand SPINS: its boss sits on the arbor it turns about. The cover is carried
// round an AXIS at its own edge that it is nowhere near the middle of. No
// measurement can tell those two apart — that is why the kit makes the author
// say which, and why `spin` is opt-in.
export const RIG = {
  drive: { t: { from: 0, to: 60, steps: 24 } },
  rest: { t: 0, open: 0 },
  moving: {
    hourHand: ({ t }) => ({ rot: [0, 0, -hands(10, 9, t).hour], spin: [0, 0, GEO.handZ] }),
    minuteHand: ({ t }) => ({ rot: [0, 0, -hands(10, 9, t).minute], spin: [0, 0, GEO.handZ] }),
    secondHand: ({ t }) => ({ rot: [0, 0, -hands(10, 9, t).second], spin: [0, 0, GEO.handZ] }),
    crown: ({ t }) => ({ rot: [0, 0, t * 0.4], spin: [0, D.caseR + D.collarH + D.bulbH, 0] }),
  },
  pinAxis: [0, 0, 1],
};


// ========================================================================
// dial.js
// ========================================================================

// dial.js — the watch face, drawn as a texture rather than modelled.
//
// A dial is PRINTED. Its numerals, its minute track and its guilloche are
// pigment and engraving on a flat disc, not geometry, and the kit's own rule is
// that anatomy is shape and pattern is paint. The face is also the one part of
// this watch with clean planar UVs, so it is where a texture can go at all.
//
// The whole chapter ring is I, V and X — three glyphs made of straight strokes —
// which is why a dial that would need a font renderer for Arabic numerals is
// tractable here in fifty lines.

import { D } from "./movement.js";

// ── a stroke font, in a box x ∈ [-0.5, 0.5], y ∈ [0, 1] ─────────────────────
//
// Serifs are not decoration: a seriffed I is what makes "III" read as three
// strokes rather than one wide bar at the size a dial is actually seen.
// THE MAP'S OWN RESOLUTION, because every soft edge below is measured in
// TEXELS and a softness written in glyph units is a different blur at every
// size. The field's dx spans -1..1 across the texture, so one texel is 2/size,
// and a glyph unit is `size * (numOuter - numInner)` of that.
export const DIAL_TEX = 2048;

// THE CHAPTER RING'S TYPE, in one place because it is now set twice — as the
// shadow in the map and as the metal on the dial. Both were 0.82/0.104 and the
// applied version came out heavier than the ink it replaced: geometry adds a
// half-stroke of round cap at each end AND a chamfer, none of which a painted
// stroke has, so the same numbers draw a bolder letter.
export const NUM_SIZE = 0.64;      // of the chapter band's height
export const NUM_WEIGHT = 0.048;   // stroke half-width, in glyph units
const TEXEL = 2 / DIAL_TEX;

const SERIF = 0.125;   // shorter: a capsule serif at 0.17 read as a dumbbell end
const GLYPH = {
  I: { w: 0.34, seg: [[0, 0, 0, 1], [-SERIF, 0, SERIF, 0], [-SERIF, 1, SERIF, 1]] },
  V: { w: 0.86, seg: [[-0.36, 1, 0, 0.02], [0.36, 1, 0, 0.02],
                      [-0.36 - SERIF * 0.7, 1, -0.36 + SERIF * 0.7, 1],
                      [0.36 - SERIF * 0.7, 1, 0.36 + SERIF * 0.7, 1]] },
  X: { w: 0.86, seg: [[-0.36, 1, 0.36, 0], [0.36, 1, -0.36, 0],
                      [-0.36 - SERIF * 0.6, 1, -0.36 + SERIF * 0.6, 1],
                      [0.36 - SERIF * 0.6, 1, 0.36 + SERIF * 0.6, 1],
                      [-0.36 - SERIF * 0.6, 0, -0.36 + SERIF * 0.6, 0],
                      [0.36 - SERIF * 0.6, 0, 0.36 + SERIF * 0.6, 0]] },
};

/** Traditional dial numbering — IIII at four, not IV. Every real dial does this. */
export const HOURS = ["XII", "I", "II", "III", "IIII", "V", "VI", "VII", "VIII", "IX", "X", "XI"];

const segDist = (px, py, [x0, y0, x1, y1]) => {
  const dx = x1 - x0, dy = y1 - y0;
  const t = Math.max(0, Math.min(1, ((px - x0) * dx + (py - y0) * dy) / (dx * dx + dy * dy || 1e-9)));
  return Math.hypot(px - (x0 + dx * t), py - (y0 + dy * t));
};

/**
 * Lay `text` out in glyph space and return its segments, placed.
 *
 * ONE LAYOUT, because the numerals are now drawn twice — once as ink in the
 * normal map and once as applied metal on the dial — and two copies of a
 * layout is two things to keep in step. This is the shape the kit keeps
 * punishing: a mechanism described twice disagrees the moment either moves.
 */
export function layout(text) {
  const chars = [...text].map((c) => GLYPH[c]);
  const gap = 0.10;
  const total = chars.reduce((s, g) => s + g.w, 0) + gap * (chars.length - 1);
  const out = [];
  let x = -total / 2;
  for (const g of chars) {
    const cx = x + g.w / 2;
    for (const seg of g.seg) {
      // The glyph's own box is squeezed to its advance width, exactly as the
      // painter does it — `(px - cx) / g.w * 0.86` inverted.
      out.push(seg.map((v, k) => (k % 2 === 0 ? cx + (v * g.w) / 0.86 : v)));
    }
    x += g.w + gap;
  }
  return out;
}

/** Ink coverage of `text` at glyph-space (px, py), 0..1. */
function textAt(text, px, py, stroke, softScale = 0.18) {
  let best = 1e9;
  for (const seg of layout(text)) best = Math.min(best, segDist(px, py, seg));
  // A SOFT EDGE OF ABOUT A TEXEL AND A HALF, and it used to be `stroke * 0.55`.
  // That is 0.058 glyph units — 0.23mm on a 45mm dial, or TEN TEXELS at 2048 —
  // so every numeral was drawn with a quarter-millimetre gradient round it and
  // read as a blurred stamp rather than as printing. The softness has to be a
  // property of the SAMPLING GRID, not of the stroke it is softening.
  const soft = (TEXEL / softScale) * 1.5;
  return Math.max(0, Math.min(1, (stroke - best) / soft + 0.5));
}

/**
 * The dial's tone/height field over the FACE's own square, u,v ∈ [0,1].
 *
 * Radius is normalised so r = 1 at the dial's edge, which lets every band below
 * be written as the fraction of the dial it actually is — the coefficients are
 * against the dial radius and say so.
 */
export function dialField(u, v) {
  // TEXTURE V RUNS DOWNWARD. Taking dy = (v - 0.5) put XII at six o'clock and,
  // because negating one axis is a REFLECTION and not a rotation, mirrored every
  // numeral with it: "VI" came out reading "IV". A dial that is upside down is
  // obvious; a dial that is upside down AND mirrored looks like a font bug.
  const dx = (u - 0.5) * 2, dy = (0.5 - v) * 2;
  const r = Math.hypot(dx, dy);
  const th = Math.atan2(dx, dy);            // 0 at 12 o'clock, clockwise
  let tone = 0.62, height = 0;

  // CONCENTRIC GUILLOCHE. Fine turned rings over the whole face — the thing
  // that makes a gold dial read as engraved metal instead of painted card.
  // FREQUENCY IS BOUNDED BY THE TEXEL, not by taste. At 210 rings the map has
  // fewer than two texels a cycle across most of the face and it moires — the
  // rings beat against the sampling grid and read as watered silk. Half that,
  // and it reads as turning.
  const RINGS = 88;
  height += Math.sin(r * RINGS) * 0.05;
  tone += Math.sin(r * RINGS) * 0.035;

  // The minute track: a fine ring, a tick a minute, a longer one every five.
  if (r > D.trackInner && r < D.trackOuter) {
    const m = th / (Math.PI * 2) * 60;
    const five = Math.round(m) % 5 === 0;
    // ARC LENGTH, not angle: a tick is a constant WIDTH on the dial, so the
    // angular tolerance has to shrink as the radius grows or the marks fan out.
    const arc = Math.abs(m - Math.round(m)) * (Math.PI * 2 / 60) * r;
    const half = five ? 0.011 : 0.005;
    const inner = D.trackOuter - (D.trackOuter - D.trackInner) * (five ? 0.95 : 0.5);
    if (r > inner) {
      // Antialiased across the tick's EDGE, in texels. A hard `arc < half` test
      // steps a tick on or off between one texel and the next, which is what
      // made the minute bars look chewed.
      const ink = Math.max(0, Math.min(1, (half - arc) / (TEXEL * 0.9) + 0.5));
      if (ink > 0) { tone = tone * (1 - ink) + 0.02 * ink; height = Math.max(height, ink * 0.5); }
    }
  }
  // The two hairlines that fence the track, as on the reference.
  for (const rr of [D.trackOuter, D.trackInner]) {
    const ink = Math.max(0, Math.min(1, (0.0035 - Math.abs(r - rr)) / (TEXEL * 0.9) + 0.5));
    if (ink > 0) { tone = tone * (1 - ink) + 0.05 * ink; height = Math.max(height, ink * 0.4); }
  }

  // THE CHAPTER RING. Each numeral stands radially, base toward the centre, so
  // the sample is rotated to 12 o'clock and tested in the glyph's own box.
  if (r > D.numInner - 0.02 && r < D.numOuter + 0.02) {
    const hgt = D.numOuter - D.numInner;
    const i = Math.round(th / (Math.PI * 2) * 12);
    const a = (((i % 12) + 12) % 12) / 12 * Math.PI * 2;
    // Rotate the sample so this hour's numeral is at the top.
    const rx = dx * Math.cos(a) - dy * Math.sin(a);
    const ry = dx * Math.sin(a) + dy * Math.cos(a);
    // THE ROTATED POINT IS THE GLYPH SPACE. A numeral stands on a flat
    // baseline — a chord, not an arc — so the local coordinates are just rx and
    // ry. Measuring a radius and an angle instead wraps every stroke around the
    // dial and smears the numerals tangentially, which reads as a bad font.
    // Drawn at 0.82 of the band's height, centred in it. At full height "XII"
    // spans 15 degrees of arc, which is exactly half the hour spacing, so
    // consecutive numerals touched.
    const size = hgt * NUM_SIZE;
    const gy = (ry - D.numInner - hgt * (1 - NUM_SIZE) / 2) / size;
    const gx = rx / size;
    if (gy > -0.12 && gy < 1.12) {
      // A SHADOW, NOT THE NUMERAL. The numerals are applied metal now — real
      // geometry standing off the dial, so they can have their own material and
      // catch the light, which paint cannot do at any texture resolution. What
      // stays in the map is the faint darkening under them, which is what an
      // applied index actually leaves on a dial.
      const ink = textAt(HOURS[((i % 12) + 12) % 12], gx, gy, NUM_WEIGHT * 1.12, hgt * NUM_SIZE);
      if (ink > 0) { tone -= ink * 0.16; height -= ink * 0.10; }
    }
  }
  return { tone: Math.max(0, Math.min(1, tone)), height };
}


/**
 * Where hour `i`'s numeral sits on the dial, in DIAL-RADIUS units.
 *
 * Returns segments as [x0, y0, x1, y1] with the dial's centre at the origin and
 * r = 1 at its edge — the same frame `dialField` works in, derived by inverting
 * the same rotation rather than re-deriving it.
 */
export function hourSegments(i) {
  const hgt = D.numOuter - D.numInner;
  const size = hgt * NUM_SIZE;
  const a = ((i % 12) + 12) % 12 / 12 * Math.PI * 2;
  const cos = Math.cos(a), sin = Math.sin(a);
  return layout(HOURS[((i % 12) + 12) % 12]).map(([x0, y0, x1, y1]) => {
    const pt = (gx, gy) => {
      const rx = gx * size;
      const ry = gy * size + D.numInner + hgt * (1 - NUM_SIZE) / 2;
      // Rotate BACK by a: the field rotates the sample to twelve o'clock, so
      // the numeral goes the other way.
      return [rx * cos + ry * sin, -rx * sin + ry * cos];
    };
    return [...pt(x0, y0), ...pt(x1, y1)];
  });
}

/** The stroke half-width of an applied numeral, in dial-radius units. */
export const NUM_STROKE = NUM_WEIGHT * (D.numOuter - D.numInner) * NUM_SIZE;


// ========================================================================
// guilloche.js
// ========================================================================

// guilloche.js — the engine-turned pattern on the case covers.
//
// The back of the reference is one texture's worth of work and no geometry's:
// a field of clous de Paris (hobnail — a diagonal lattice of tiny pyramids), a
// border of beading inside a scalloped arcade, and an ornate lobed cartouche
// framing a plain octagonal plate left blank for an engraving.
//
// All of it is PATTERN, so all of it is paint. Modelling a hobnail field is
// forty thousand pyramids for something a normal map states exactly, and the
// kit's own rule — anatomy is shape, pattern is paint — settles it. Beading is
// the one arguable case, and it loses: at 50mm the beads are 0.4mm across.

const TAU = Math.PI * 2;

/** Distance from a point to a rounded n-gon of radius r, centred at the origin. */
function polyDist(x, y, n, r, rot = 0) {
  const a = Math.atan2(y, x) + rot;
  const seg = TAU / n;
  const k = Math.abs(((a % seg) + seg) % seg - seg / 2);
  return Math.hypot(x, y) * Math.cos(k) / Math.cos(seg / 2) - r;
}

/**
 * The cover's tone/height over its own square, u,v ∈ [0,1], r = 1 at the rim.
 *
 * `plain` gives the inside of the front cover, which on a real hunter is
 * polished blank — the pattern is on the outside only, and putting it on both
 * is the commonest way a modelled watch looks like a novelty tin.
 */
export function backField(u, v, plain = false) {
  const dx = (u - 0.5) * 2, dy = (0.5 - v) * 2;
  const r = Math.hypot(dx, dy);
  let tone = 0.55, height = 0;
  if (r > 1) return { tone: 0.5, height: 0 };
  if (plain) return { tone: 0.62 + Math.sin(r * 40) * 0.02, height: 0 };

  // THE HOBNAIL FIELD. Two crossed sine lattices at 45 degrees make a grid of
  // pyramids; multiplying them (rather than adding) is what gives points
  // instead of corrugations.
  if (r < 0.80) {
    const s = 92;    // coarse enough that a pyramid survives the texel grid
    const a = Math.sin((dx + dy) * s), b = Math.sin((dx - dy) * s);
    const hob = a * b;
    height += hob * 0.14;
    tone += hob * 0.05;
  }

  // The beaded border and the scalloped arcade outside it.
  if (r > 0.80 && r < 0.985) {
    const th = Math.atan2(dy, dx);
    const beads = 96;
    const k = Math.cos(th * beads);
    if (r > 0.905 && r < 0.955) {                       // the bead ring
      const across = 1 - Math.abs(r - 0.930) / 0.025;
      const bump = Math.max(0, k) * across;
      height += bump * 0.9; tone += bump * 0.22;
    }
    if (r > 0.83 && r < 0.90) {                         // the arcade
      const arch = Math.max(0, Math.cos(th * 48));
      const across = 1 - Math.abs(r - 0.865) / 0.035;
      height += arch * across * 0.7; tone += arch * across * 0.18;
    }
    if (Math.abs(r - 0.975) < 0.012) { height += 0.5; tone += 0.12; }   // the outer bead
  }

  // THE CARTOUCHE: a lobed frame around a plain octagonal plate. The plate is
  // what an owner has their initials cut into, so it is the one part of the
  // whole cover that is deliberately smooth.
  const cr = 0.40;   // measured against the reference: its cartouche is far bigger
  const oct = polyDist(dx, dy * 1.20, 8, cr * 0.62, 0.39);
  if (oct < 0) { return { tone: 0.80, height: 0.22 }; }                  // the blank plate
  if (oct < 0.055) { return { tone: 0.58, height: 0.22 - oct * 3 }; }    // its raised rim
  // A CHAIN OF ROUND LOBES, not a modulated radius. Wobbling the radius by
  // cos(16th) makes the spikes of a sunburst; a scalloped frame is N small
  // CIRCLES sitting on a ring, and the difference is the whole character of it.
  const lobes = 14;
  let d = 1e9;
  for (let i = 0; i < lobes; i++) {
    const a = (i / lobes) * TAU + 0.11;
    const lx = Math.cos(a) * cr, ly = Math.sin(a) * cr * 1.14;
    d = Math.min(d, Math.hypot(dx - lx, dy * 1.16 - ly) - cr * 0.205);
  }
  if (d < 0.02) {
    const t = Math.min(1, (0.02 - d) / 0.04);
    height += t * 1.5; tone += t * 0.30;
  }
  return { tone: Math.max(0, Math.min(1, tone)), height };
}

export const frontInsideField = (u, v) => backField(u, v, true);


// ========================================================================
// models.mjs
// ========================================================================

// models.mjs — a gold pocket watch, modelled from a photograph.
//
// The case is almost nothing but surfaces of revolution, which is what makes
// this asset worth having: a lathe profile's DIRECTION is its facing, and a
// reversed one renders as INVISIBLE rather than as wrong. Every revolved part
// here declares `expect: { radial: "z" }` so the gate can say so.
//
// IT FACES +Z. The dial looks down +Z, so 12 o'clock is +Y and the case's axis
// of revolution is Z.
//
// LOOK AT IT WITH A ZOOM, or you will debug geometry that is already correct:
//
//   node ../../../packages/modelkit/tools/preview.mjs watch --models=./models.mjs \
//        --zoom=0.35 --elev=0.35 --spin=0.6
//
// The preview frames a subject at 1.6x its largest dimension, which is tuned for
// things the size of furniture. On a 50mm watch that puts the lens close enough
// that the frame is a magnified sliver of the case rim, and it looks exactly like
// a broken lathe. I diagnosed it as reversed winding (it was, separately), then
// as a dead material, then as the camera — and only reading the band's rings out
// of the buffer settled it: nine rings, 64 vertices each, radii 24.1 to 25.0mm,
// which is a watch case and not a sliver. Measure the geometry before believing
// a picture of it.

import * as THREE from "three";
import { stitch, merge, tint, facet, sit, patch, extrude, lathe } from "antics-modelkit";
import { D, GEO, TRAIN, BALANCE } from "./movement.js";
import { dialField, DIAL_TEX, hourSegments, NUM_STROKE } from "./dial.js";
import { backField } from "./guilloche.js";
import { surface } from "antics-modelkit/texture";

// TAKEN OFF THE PHOTOGRAPH, not picked. Sampled over 11,809 points inside the
// case: median #c1ac7a, p90 #fae4c2, and the highlights run to white. A metal's
// base colour is its REFLECTANCE, so it wants the tint the metal imposes and not
// the pale average a warm room produced — gold's published reflectance is
// (1.00, 0.77, 0.34), warmed slightly toward this plating.
const GOLD = 0xf5c86e;
const GOLD_DARK = 0xb08a3c;
const DIAL = 0xe8cf92;      // the silvered-gold face
const INK = 0x161310;       // blued-black hands and numerals

// THE CASE LATHES ABOUT Z, so every profile in it is [radius, z]. This file used
// to carry its own lathe and a paragraph explaining which way the sine had to
// go; the sign was wrong twice, and once it was wrong IN that paragraph. The
// kit's `lathe` derives it — it builds the rings, measures the widest one, and
// rebuilds the other way round if it came out facing the axis — so a profile can
// be written in whichever direction the shape reads in and there is no
// convention left in this file to get wrong.
const OPEN = { capStart: false, capEnd: false };

const band = () => {
  const R = D.caseR, h = D.bandH / 2, w = D.caseD * 0.018;
  // The photograph's band is not a plain cylinder: it carries a pair of shallow
  // steps where the covers meet it, which is what gives the edge its jewellery
  // look instead of reading as a tin.
  const s = D.caseD * 0.008;
  return lathe([
    [R - w, -h], [R - s, -h], [R, -h + s],
    [R, -s * 1.6], [R * 0.995, 0], [R, s * 1.6],
    [R, h - s], [R - s, h], [R - w, h],
  ], { axis: "z", segments: 64, ...OPEN });
};

/**
 * A domed cover with PLANAR UVs, so an engine-turned pattern can be printed on
 * it. `dir` is +1 for the front cover, -1 for the back.
 *
 * Built directly rather than through `lathe` for the same reason the dial is:
 * a lathe's UVs are arc length, which wraps a cartouche round the rim.
 */
const dome = (dir, { R = D.coverR, rise = D.coverRise, wall = D.coverWall, rings = 30, seg = 96 } = {}) => {
  const h = D.bandH / 2;
  const pos = [], uv = [], idx = [];
  // A SHELL, NOT A SKIN. The cover is drawn twice — an outer face and an inner
  // face a wall apart — and closed with a rim band between them. A single
  // surface has no edge, so a closed watch read as foil pressed over the case,
  // and there was nothing for the second hand to be inside of.
  // A CONSTANT-THICKNESS SHELL: the inner face is the outer one moved a wall
  // TOWARD the watch. It used to be `h + wall + (rise - wall) * f`, which at the
  // rim is dir*(h + wall) — a wall in FRONT of the outer face. The two surfaces
  // were swapped, so every normal on the lid pointed the wrong way and you could
  // see straight through it from a grazing angle. Measured: 49.2% of its
  // triangles facing inward, which is exactly half, which is the tell that one
  // of two equal shells is reversed rather than that something is subtly off.
  // THE INNER FACE IS THE REFERENCE, because that is the face that CLOSES ONTO
  // THE CASE — a lid meets the band with its inside, and its outside is a wall
  // further out. Making the OUTER face the reference instead put the inner
  // surface a wall below the band top, straight through the bezel, and back
  // inside the sweep of the hands.
  const seat = h + D.bezelProud;              // the lid closes onto the BEZEL
  const zIn = (t) => dir * (seat + rise * (1 - (1 - t) ** 2));
  const zOut = (t) => dir * (seat + wall + rise * (1 - (1 - t) ** 2));
  const ring = (rr, z, u0) => {
    const base = pos.length / 3;
    for (let i = 0; i <= seg; i++) {
      const a = (i / seg) * Math.PI * 2;
      const x = Math.cos(a) * rr, y = Math.sin(a) * rr;
      pos.push(x, y, z(rr / R));
      uv.push(0.5 + x / (2 * R), 0.5 - y / (2 * R));
    }
    return base;
  };
  const rowsOut = [], rowsIn = [];
  for (let k = 0; k <= rings; k++) {
    const rr = Math.max(R * 0.012, R * (1 - k / rings));
    rowsOut.push(ring(rr, (t) => zOut(1 - rr / R), 0));
  }
  for (let k = 0; k <= rings; k++) {
    const rr = Math.max(R * 0.012, R * (1 - k / rings));
    rowsIn.push(ring(rr, () => zIn(1 - rr / R), 0));
  }
  const quads = (rows, flip) => {
    for (let k = 0; k < rows.length - 1; k++) {
      for (let i = 0; i < seg; i++) {
        const a = rows[k] + i, b = a + 1, c = rows[k + 1] + i, d = c + 1;
        if (flip) idx.push(a, c, b, b, c, d); else idx.push(a, b, c, b, d, c);
      }
    }
  };
  quads(rowsOut, dir < 0);
  quads(rowsIn, dir > 0);
  // The rim: joins the two faces at the outside edge, and is the thing you SEE.
  for (let i = 0; i < seg; i++) {
    const a = rowsOut[0] + i, b = a + 1, c = rowsIn[0] + i, d = c + 1;
    if (dir > 0) idx.push(a, c, b, b, c, d); else idx.push(a, b, c, b, d, c);
  }
  const g = new THREE.BufferGeometry();
  g.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3));
  g.setAttribute("uv", new THREE.Float32BufferAttribute(uv, 2));
  g.setIndex(idx);
  g.computeVertexNormals();
  return g;
};

/** The hinge lug: the little block at SIX o'clock the cover swings on. */
const hingeLug = () => {
  const w = D.caseD * 0.055, t = D.caseD * 0.030, hh = D.caseD * 0.028;
  const g = extrude([[-w / 2, -hh / 2], [w / 2, -hh / 2], [w / 2, hh / 2], [-w / 2, hh / 2]],
    { depth: t });
  g.rotateX(Math.PI / 2);
  g.translate(0, -(D.caseR - D.caseD * 0.004), 0);
  return g;
};

const bezel = () => {
  const R = D.caseR, h = D.bandH / 2, ri = D.crystalR, s = D.caseD * 0.006;
  return lathe([
    [R - D.caseD * 0.018, h], [R - s * 0.5, h], [R - s, h + D.bezelProud * 0.8],
    [ri + s * 0.9, h + D.bezelProud], [ri, h + s * 0.7], [ri, h + s * 0.2],
  ], { axis: "z", segments: 64, ...OPEN });
};

const crystal = () => {
  const R = D.crystalR, h = D.bandH / 2 + D.caseD * 0.006, rise = D.caseD * 0.012;
  const N = 12, prof = [];
  for (let i = 0; i <= N; i++) {
    const t = i / N;
    prof.push([R * (1 - t), h + rise * (1 - (1 - t) ** 2)]);
  }
  return lathe(prof, { axis: "z", segments: 64, ...OPEN });
};

// ── the pendant stack, at 12 o'clock ────────────────────────────────────────
//
// The photograph reads, bottom to top: three stacked collar rings off the case
// rim, an onion-shaped bulb, the fluted winding crown, and a bow ring that
// ENCIRCLES the crown rather than sitting above it. Each is lathed about Y —
// the pendant's own axis, and the case's is Z — then laid onto the case; a part
// drawn about one axis and placed about another is the "one number, read twice"
// trap, so the placement is a single translate.
//
// These used to be drawn about Z and rotated a quarter turn onto Y, because the
// file's lathe only knew one axis. `lathe` takes the axis, so the rotate is
// gone and with it the comment that had to explain which way rotateX(-90) sends
// +Z. A part built in the frame it lives in has no conversion to get wrong.

const collar = () => {
  const r = D.collarR, h = D.collarH, b = h / 3;
  const prof = [];
  // Three beads. Each is a squat barrel, and they overlap by a third of a bead
  // so the merged part stays ONE closed shell rather than three touching ones.
  for (let i = 0; i < 3; i++) {
    const y0 = i * b * 0.9;
    prof.push([r * 0.72, y0], [r, y0 + b * 0.45], [r * 0.72, y0 + b * 0.9]);
  }
  return lathe([[r * 0.6, -h * 0.15], ...prof, [r * 0.6, h * 0.95]], { segments: 32, ...OPEN });
};

const bulb = () => {
  const R = D.bulbR, h = D.bulbH, N = 14, prof = [];
  for (let i = 0; i <= N; i++) {
    const t = i / N;
    // An onion: widest a third of the way up, tucked in at both ends.
    prof.push([R * Math.sin(Math.PI * (0.18 + t * 0.74)) ** 0.75, t * h]);
  }
  return lathe(prof, { segments: 32, ...OPEN });
};

const crown = () => {
  const R = D.crownR, h = D.crownH, n = D.crownFlutes;
  // FLUTED, so it is not a surface of revolution — the radius is a function of
  // the angle. Built directly rather than through `lathe`, which is why it does
  // not (and must not) declare `radial`: its widest ring alternates in and out.
  const rings = [];
  const at = (t, rr) => ({
    verts: Array.from({ length: n * 2 }, (_, a) => {
      const th = (a / (n * 2)) * Math.PI * 2;
      const flute = 1 - 0.13 * (0.5 - 0.5 * Math.cos(th * n));
      return new THREE.Vector3(Math.cos(th) * rr * flute, t, -Math.sin(th) * rr * flute);
    }),
    center: new THREE.Vector3(0, t, 0), t: 0,
  });
  rings.push(at(0, R * 0.82), at(h * 0.12, R), at(h * 0.82, R), at(h, R * 0.86), at(h * 1.06, R * 0.5));
  rings.forEach((r, i) => { r.t = i / (rings.length - 1); });
  return stitch(rings, { capStart: false });
};

/** The bow: a wire ring standing in the case's own plane, encircling the crown. */
const bow = () => {
  const R = D.bowR, w = D.bowWire;
  const g = patch(40, 14, (u, v) => {
    const a = u * Math.PI * 2, b = v * Math.PI * 2;
    // An OVAL, not a circle: the photograph's bow is wider than it is tall.
    const cx = Math.cos(a) * R * 1.18, cy = Math.sin(a) * R;
    const nx = Math.cos(a), ny = Math.sin(a);
    return {
      x: cx + nx * Math.cos(b) * w,
      y: cy + ny * Math.cos(b) * w,
      z: Math.sin(b) * w,
    };
  }, { closedU: true, flip: true });   // the gate measured this one inside-out
  return g;
};

// ── the dial and the hands ──────────────────────────────────────────────────

/**
 * The dial: an annulus with PLANAR UVs, so the printed face can be a decal.
 *
 * A `lathe` gives arc-length UVs, which is right for a band and useless for a
 * face — the numerals would smear round the ring. This is built directly so u,v
 * are the face's own square, which is what `dialField` is written in and what
 * `tile: false` means.
 */
const dialPlate = () => {
  const R = D.dialR, ri = R * D.apertureR, N = 128;
  const pos = [], uv = [], nor = [], idx = [];
  for (let ring = 0; ring < 2; ring++) {
    const rr = ring === 0 ? ri : R;
    for (let i = 0; i <= N; i++) {
      const a = (i / N) * Math.PI * 2;
      const x = Math.cos(a) * rr, y = Math.sin(a) * rr;
      pos.push(x, y, GEO.dialZ);
      nor.push(0, 0, 1);
      // v RUNS DOWN, which is glTF's convention and the field's. The top of the
      // dial is v = 0.
      //
      // This was `0.5 + y` for a while, and that was me tuning the MODEL to
      // satisfy a renderer rather than fixing the renderer: `preview` builds a
      // DataTexture (flipY false) and the loader built a Texture (flipY true),
      // so the two disagreed by a flip and only one of them could be right.
      // Compensating here made the preview look correct and shipped a .glb with
      // XII at six o'clock — correct in this kit and upside down in Blender.
      uv.push(0.5 + x / (2 * R), 0.5 - y / (2 * R));
    }
  }
  for (let i = 0; i < N; i++) {
    const a = i, b = i + 1, c = i + N + 1, d = i + N + 2;
    idx.push(a, c, b, b, c, d);
  }
  const g = new THREE.BufferGeometry();
  g.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3));
  g.setAttribute("normal", new THREE.Float32BufferAttribute(nor, 3));
  g.setAttribute("uv", new THREE.Float32BufferAttribute(uv, 2));
  g.setIndex(idx);
  return g;
};

/**
 * A hand, drawn flat in XY and standing at `z`.
 *
 * The reference carries three, and they are NOT the same shape: an ornate
 * pierced hour, a slimmer pierced minute, and a plain needle for the seconds
 * that runs almost to the minute track.
 */
const hand = (len, wide, z, tail) => {
  const pts = [
    [0, -tail], [wide * 0.55, -tail * 0.4], [wide * 0.5, len * 0.12],
    [wide * 0.95, len * 0.30], [wide * 0.42, len * 0.46],
    [wide * 0.80, len * 0.66], [wide * 0.3, len * 0.82], [0, len],
  ];
  const outline = [...pts, ...pts.slice(1, -1).reverse().map(([x, y]) => [-x, y])];
  // `extrude` takes [[x, y], ...] and an OPTIONS BAG. Handing it Vector2s makes
  // every destructure undefined, and handing it a NUMBER as the second argument
  // leaves `depth` at its 0.2 default — 200mm of hand on a 50mm watch, which
  // rendered as a black bar three times the width of the case.
  const g = extrude(outline, { depth: D.caseD * 0.006 });
  g.translate(0, 0, z);
  return g;
};

const needle = (len, z) => {
  const w = D.caseD * 0.0045;
  const g = extrude([[-w, -len * 0.22], [w, -len * 0.22], [w * 0.35, len], [-w * 0.35, len]],
    { depth: D.caseD * 0.004 });
  g.translate(0, 0, z);
  return g;
};

// ── the movement, seen through the skeleton aperture ────────────────────────

/**
 * A clock wheel: a toothed rim, crossings cut out of it, and a hub.
 *
 * The teeth are the point. A smooth disc reads as a washer, and the reference's
 * whole character is that you can count the teeth through the dial — so the
 * outline is walked tooth by tooth rather than approximated by a fine circle.
 */
const wheel = (radius, teeth, thick, { crossings = 5, hub = 0.22, ringPts = 14 } = {}) => {
  const pts = [];
  const root = radius * 0.90, tip = radius;
  for (let i = 0; i < teeth; i++) {
    const a0 = (i / teeth) * Math.PI * 2;
    const step = (Math.PI * 2) / teeth;
    // A trapezoidal tooth: up the flank, across the tip, down, then the gap.
    pts.push([Math.cos(a0) * root, Math.sin(a0) * root]);
    pts.push([Math.cos(a0 + step * 0.18) * tip, Math.sin(a0 + step * 0.18) * tip]);
    pts.push([Math.cos(a0 + step * 0.40) * tip, Math.sin(a0 + step * 0.40) * tip]);
    pts.push([Math.cos(a0 + step * 0.58) * root, Math.sin(a0 + step * 0.58) * root]);
  }
  // CROSSINGS — the openings a real wheel is pierced with, which is what makes
  // it read as horology rather than as machinery. They are holes in the same
  // extrude, so the wheel stays one part.
  const holes = [];
  for (let i = 0; i < crossings; i++) {
    const a = (i / crossings) * Math.PI * 2 + 0.3;
    const rc = radius * 0.55, rr = radius * 0.26;
    const ring = [];
    for (let k = 0; k < ringPts; k++) {
      const b = (k / ringPts) * Math.PI * 2;
      ring.push([Math.cos(a) * rc + Math.cos(b) * rr, Math.sin(a) * rc + Math.sin(b) * rr]);
    }
    holes.push(ring.reverse());
  }
  const g = extrude(pts, { depth: thick, holes });
  const boss = lathe([[radius * hub, -thick * 0.5], [radius * hub, thick * 1.6],
    [radius * hub * 0.45, thick * 1.6]], { axis: "z", segments: 20, ...OPEN });
  return merge([g, boss]);
};

/** The balance wheel: a plain rim on two arms, with a hairspring coiled over it. */
const balanceWheel = (radius, thick) => {
  const rim = lathe([
    [radius, 0], [radius, thick], [radius * 0.86, thick], [radius * 0.86, 0],
  ], { axis: "z", segments: 40, ...OPEN });
  const arm = extrude([[-radius * 0.06, -radius * 0.9], [radius * 0.06, -radius * 0.9],
    [radius * 0.06, radius * 0.9], [-radius * 0.06, radius * 0.9]], { depth: thick * 0.7 });
  const arm2 = arm.clone(); arm2.rotateZ(Math.PI / 2);
  // NO HAIRSPRING. An Archimedean coil of 4.5 turns is a self-INTERSECTING
  // outline, and `extrude` wants a simple polygon: it triangulated into 358
  // degenerate faces. A spring wants to be swept along its path as a tube, not
  // extruded as an outline — and at this scale it sits under the balance cock
  // where nothing can see it, so it is not worth the geometry.
  return merge([rim, arm, arm2]);
};

/** A bridge: a rounded plate with screw bosses, spanning part of the movement. */
const bridge = (pts, thick, r) => {
  const out = [];
  for (const [x, y] of pts) {
    for (let k = 0; k < 12; k++) {
      const a = (k / 12) * Math.PI * 2;
      out.push([x + Math.cos(a) * r, y + Math.sin(a) * r]);
    }
  }
  // The convex hull of the discs — a plate with rounded ends, which is the
  // shape every cock and bridge in a watch actually is.
  const hull = (ps) => {
    const s = [...ps].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
    const half = (arr) => {
      const h = [];
      for (const p of arr) {
        while (h.length > 1 && (h[h.length - 1][0] - h[h.length - 2][0]) * (p[1] - h[h.length - 2][1])
          - (h[h.length - 1][1] - h[h.length - 2][1]) * (p[0] - h[h.length - 2][0]) <= 0) h.pop();
        h.push(p);
      }
      return h;
    };
    return [...half(s).slice(0, -1), ...half(s.reverse()).slice(0, -1)];
  };
  return extrude(hull(out), { depth: thick });
};

/**
 * APPLIED NUMERALS: the chapter ring as metal, not as paint.
 *
 * A texture carries colour and a normal map, and roughness and metalness are
 * properties of a MATERIAL — so a painted numeral is exactly as shiny as the
 * dial it is painted on, at any resolution. The only way for the numerals to
 * catch the light differently from the face is for them to be their own part,
 * which is also what a fine watch does: applied indices are little pieces of
 * metal pinned to the dial.
 *
 * The segments come from `dial.js`, inverted out of the same rotation the
 * painter uses, so the metal lands where the ink used to be.
 */
const appliedNumerals = () => {
  const R = D.dialR, w = NUM_STROKE * R, t = D.caseD * 0.0045;
  const bits = [];
  for (let i = 0; i < 12; i++) {
    for (const [x0, y0, x1, y1] of hourSegments(i)) {
      const ax = x0 * R, ay = y0 * R, bx = x1 * R, by = y1 * R;
      const len = Math.hypot(bx - ax, by - ay);
      // A BEVEL, because a flat-topped bar has one highlight and a chamfered one
      // has three — the top and both facets — which is most of what makes an
      // applied index read as jewellery rather than as a sticker.
      const g = extrude([[-len / 2 - w, -w], [len / 2 + w, -w], [len / 2 + w, w], [-len / 2 - w, w]],
        { depth: t, bevel: w * 0.4 });
      g.rotateZ(Math.atan2(by - ay, bx - ax));
      g.translate((ax + bx) / 2, (ay + by) / 2, GEO.dialZ + t * 0.55);
      bits.push(g);
    }
  }
  return merge(bits);
};

export const MODELS = {
  watch() {
    const parts = [];
    // THE PROPERTY IS `metallic`, NOT `metalness`. The preview reads
    // `part.metallic ?? 0`, so `metalness: 1` was dropped in silence and every
    // gold surface here was being rendered as a dielectric. An option bag that
    // ignores a key it does not know gets QUIETER, which reads as better.
    const push = (name, geometry, color, extra = {}) => {
      // EXTRUDE RETURNS NON-INDEXED GEOMETRY, and the writer emits an index
      // accessor regardless — over an empty array, so its `min` is null and the
      // Khronos validator rejects the whole file with ARRAY_TYPE_MISMATCH. Seven
      // parts were in that state: every hand, both bridges and the hinge.
      //
      // An IDENTITY index rather than `weld()`: welding merges the duplicated
      // corners an extrude carries on purpose, and re-deriving normals from the
      // welded result rounds off every hard edge these parts are made of.
      if (!geometry.index) {
        geometry.setIndex([...Array(geometry.attributes.position.count).keys()]);
      }
      parts.push({ name, geometry, color, metallic: 1, roughness: 0.16, ...extra });
    };

    push("band", band(), GOLD, { expect: { radial: "z" } });
    // A NARROW TRIPLE, AND A QUIET NORMAL. Engine-turning on gold is one metal
    // catching the light two ways, not two metals: at strength 1.0 the relief
    // scattered the normals so hard that most of the cover reflected the dark
    // half of the environment and came out near-black, and a ramp running
    // #6b4a17 to #fff0cf painted a bronze-to-cream gradient over it. The kit's
    // own note applies — how loud a texture is, is the distance between its
    // colours, and `strength` is the RELIEF alone.
    const caseSkin = (key) => surface(backField, [0xd9ad5e, 0xeecb84, 0xf8dfa8, 0xfff3d6],
      { key, tile: false, size: 512, normalSize: 512, strength: 0.14 });
    push("backCover", dome(-1), 0xfff0d0, { metallic: 0.88, roughness: 0.34, texture: caseSkin("watch-back") });
    push("hingeLug", hingeLug(), GOLD);
    push("bezel", bezel(), GOLD, { expect: { radial: "z" } });
    // `tile: false` is the declaration that this map spans its UVs exactly
    // once. It is a face, not a repeating material, and its edges have no
    // business matching — which is precisely the case the kit added the flag for.
    push("dial", dialPlate(), 0xffffff, {
      metallic: 0.25, roughness: 0.45,
      texture: surface(dialField, [0x141008, 0x8d7038, 0xd8b877, 0xf3e0b4],
        { key: "watch-dial", tile: false, size: DIAL_TEX, normalSize: 512, strength: 0.55 }),
    });

    push("numerals", appliedNumerals(), 0x20283c, { metallic: 1, roughness: 0.10 });

    // The pendant stack rides at 12 o'clock, on top of the case rim. Every piece
    // is drawn about its own axis at the origin and lifted by ONE expression, so
    // "where it is drawn" and "where it is placed" cannot become two numbers.
    const stackY = D.caseR - D.caseD * 0.01;
    const lift = (g, dy) => { g.translate(0, stackY + dy, 0); return g; };
    push("collar", lift(collar(), 0), GOLD);
    push("bulb", lift(bulb(), D.collarH * 0.9), GOLD);
    const crownY = D.collarH * 0.9 + D.bulbH * 0.92;
    push("crown", lift(crown(), crownY), GOLD);
    const bg = bow();
    bg.translate(0, stackY + crownY + D.crownH * 0.42, 0);
    push("bow", bg, GOLD);

    // Hands. The seconds needle is longest, then the minute, then the hour —
    // read straight off the photograph, where the hour is the ornate short one.
    // BLUED STEEL IS STEEL. These were 0x161310 at metalness 0.3 — a nearly
    // black dielectric, which has almost no specular and no reflection to give,
    // so they took no light at ANY angle. A metal's base colour IS its
    // reflectance: to be dark AND shiny it has to be a real metal with a dark
    // tint, not a dark paint. Blued steel is a thin oxide over bright steel.
    const STEEL = { metallic: 1, roughness: 0.13 };   // dark, but still a metal
    const HAND = 0x14161c;   // the photograph's hands are black, not blued
    push("hourHand", hand(D.dialR * 0.52, D.caseD * 0.022, GEO.handZ, D.dialR * 0.10), HAND, STEEL);
    push("minuteHand", hand(D.dialR * 0.78, D.caseD * 0.017, GEO.handZ + D.caseD * 0.004, D.dialR * 0.12), HAND, STEEL);
    push("secondHand", needle(D.dialR * 0.90, GEO.handZ + D.caseD * 0.008), 0x1b2028, STEEL);

    // ── the movement, behind the dial ──────────────────────────────────────
    //
    // Everything here lives inside the aperture and is sized as a fraction of
    // IT, not of the case: the skeleton is a hole in the dial and the train has
    // to fit that hole whatever the case does.
    const ap = D.dialR * D.apertureR;
    const mz = GEO.dialZ - D.caseD * 0.010;
    const plateThick = D.caseD * 0.004;

    // A DISC, not a tube. Both profile points sat at the same RADIUS, which
    // lathes a cylinder wall with no floor — so the aperture had nothing behind
    // it and the "white mainplate" was the background, seen straight through the
    // watch. A profile that does not change radius is not a plate.
    // AND `expect` IS NOT OPTIONAL HERE, which the kit's lathe is what told us.
    // Every point of this profile is at the same z, so the part is a flat
    // annulus: it bounds no solid, there is no outward, and the radial check has
    // nothing to measure. It faces the viewer, at +Z, and until now nothing in
    // the pipeline had ever asked which way it pointed — it survived only
    // because it is drawn double-sided.
    const mainplate = lathe([[ap * 0.99, mz], [ap * 0.5, mz], [0.0006, mz]],
      { axis: "z", segments: 64, ...OPEN, expect: [0, 0, 1] });
    // NOT METALLIC. A flat plate facing the camera with metalness 1 mirrors the
    // environment's bright ceiling straight back and comes out WHITE — the
    // aperture read as a hole cut in paper. Gilt brass is a rougher, part-metal
    // surface, and the movement only has depth if its floor is darker than the
    // wheels standing on it.
    // AND THE SAME DECLARATION ON THE PART, so the gate asks the question too.
    // `lathe` checks it at build time and the gate checks the geometry that
    // arrives; they are two places the plate could stop facing the viewer.
    push("mainplate", mainplate, 0x8a6b28,
      { metallic: 0.55, roughness: 0.52, doubleSided: true, expect: [0, 0, 1] });

    for (const w of TRAIN) {
      // THE BACK TIER PAYS LESS. Those wheels sit behind the going train, mostly
      // occluded, and each crossing is a 14-sided hole cut through a polygon —
      // the walls of which are most of a wheel's triangles. Three coarser
      // openings instead of five fine ones is invisible back there and is a
      // third of the asset's geometry.
      const g = wheel(ap * w.r, w.teeth, plateThick * 0.55,
        w.tier ? { crossings: 3, ringPts: 9 } : {});
      // TWO TIERS, and the deeper one is not a cheat: a real movement runs its
      // motion work UNDER the dial, behind the going train. Stacking them all on
      // one plane would have them fighting for the same space and reading as a
      // flat collage rather than as something with depth in it.
      const z = w.tier ? mz + plateThick * 0.05 : mz + plateThick * 0.75;
      g.translate(ap * w.at[0], ap * w.at[1], z);
      push(w.name, g, w.tier ? 0xc9a55c : 0xf0c878, { metallic: 1, roughness: w.tier ? 0.30 : 0.20 });
    }

    const bal = balanceWheel(ap * BALANCE.r, plateThick * 0.5);
    bal.translate(ap * BALANCE.at[0], ap * BALANCE.at[1], mz + plateThick * 2.2);
    push("balance", bal, 0xe8e2d2, { metallic: 0.9, roughness: 0.22 });

    // Two bridges over the train, and the balance cock over the balance. Drawn
    // from the same wheel positions the train uses, so a wheel that moves takes
    // its bridge with it instead of leaving it behind.
    const bz = mz + plateThick * 1.6;
    const cock = bridge([[ap * BALANCE.at[0], ap * BALANCE.at[1]], [ap * 0.05, ap * 0.72]],
      plateThick * 0.7, ap * 0.085);
    cock.translate(0, 0, bz + plateThick * 1.4);
    push("balanceCock", cock, GOLD, { roughness: 0.3 });
    const tb = bridge([[ap * 0.44, ap * 0.30], [ap * 0.30, ap * -0.46], [ap * 0.62, ap * -0.05]],
      plateThick * 0.7, ap * 0.075);
    tb.translate(0, 0, bz);
    push("trainBridge", tb, GOLD, { roughness: 0.3 });

    // Jewels: the ruby bearings the wheels run in. Tiny, and the only red in the
    // whole asset, which is exactly why they read.
    // FIVE, NOT TWENTY-SEVEN. One jewel per wheel turned the movement into a
    // rash of red dots; a real skeleton shows the going train's bearings and
    // nothing else, and they read BECAUSE they are the only red in the asset.
    const jewels = [[0, 0], ...TRAIN.slice(1, 4).map((w) => w.at), BALANCE.at].map(([x, y]) => {
      // `at` places it, and the winding is measured BEFORE the move: the radial
      // check is about the axis through the origin, and a jewel sits twelve of
      // its own radii off it.
      return lathe([[ap * 0.055, 0], [ap * 0.055, plateThick * 0.5], [ap * 0.03, plateThick * 0.5]],
        { axis: "z", segments: 14, ...OPEN, at: [ap * x, ap * y, bz + plateThick * 1.0] });
    });
    push("jewels", merge(jewels), 0x9e1f3a, { metallic: 0.2, roughness: 0.15 });

    // THE FRONT COVER, which is the thing the demo opens. It is drawn CLOSED,
    // at the position it occupies when shut, and the hinge is a line on the case
    // rather than a number typed next to the cover — two parts that meet have
    // one line and it belongs to the fixed one.
    push("frontCover", dome(1), 0xfff0d0, { metallic: 0.88, roughness: 0.34, texture: caseSkin("watch-front") });

    // NO CRYSTAL IN THE ASSET, and this is a kit limitation rather than a
    // choice. A part descriptor carries colour, metalness and roughness and has
    // no notion of TRANSPARENCY, so the glass came out as an opaque white disc
    // covering the dial, the hands and the whole movement — strictly worse than
    // leaving it out, since the reference's crystal is invisible. The `crystal()`
    // profile is kept above for whenever the descriptor can say "glass".

    // IT STANDS ON ITS RIM, as it does in the photograph propped against the
    // box. Built centred on the origin, half of it was below the ground plane
    // and every default preview angle framed it edge-on — which I read as
    // broken geometry twice before measuring the rings and finding them exact.
    //
    // AND THE LIFT MOVES THE AXIS, which is what `expect: "radial"` is declared
    // about. Parts declared their axis at the origin and were then translated
    // out from under it, so the check measured the case about a line running
    // through its own rim and reported the bezel 22-of-68 inward — a false
    // positive my own writer guard threw on. The lift is ONE number, applied to
    // the geometry and named in the declaration, so the two cannot drift.
    const LIFT = GEO.lift;
    for (const part of parts) part.geometry.translate(0, LIFT, 0);
    for (const part of parts) {
      if (part.expect && part.expect.radial) part.expect = { radial: "z", at: [0, LIFT, 0] };
    }

    // BAKE THE LID OPEN. The hinge is derived from the same constants the demo
    // pivots about, so the baked pose and the driven one cannot disagree — and
    // the page subtracts `restOpen` to get back to shut.
    const lid = parts.find((p) => p.name === "frontCover");
    if (lid) {
      const hx = 0, hy = LIFT - D.caseR, hz = D.bandH * 0.5;
      lid.geometry.translate(-hx, -hy, -hz);
      lid.geometry.rotateX(GEO.restOpen);
      lid.geometry.translate(hx, hy, hz);
    }

    return { parts, category: "prop", front: "bezel", stands: true };
  },
};
