// formulation-stack.jsx: "§ 03 · the formulation stack" (the Clean Shelf Method)
//
// 14s loop. Five translucent layers descend one at a time into an apothecary
// jar on a shelf and stack bottom up: conversion, AOV, retention, LTV, brand
// equity. Brand equity lands last as the amber crown, a band of light runs up
// through the stack to show it compounding the four below, the lid settles and
// the frame holds. Then the lid lifts, the layers clear top down, and the empty
// jar hands back to the first frame.
//
// Beats, in seconds
//   0.0 to 0.8     empty jar, "Formulated bottom up."
//   0.8 to 9.3     one layer every 1.8s: fall 0.85s, land, settle 0.5s
//   9.6 to 10.7    light sweeps up through all five layers
//   10.3 to 11.6   crown glow rises, lid settles, "Five layers. No shortcut."
//   11.6 to 12.6   hold (the reduced motion frame is 12.0)
//   12.6 to 13.8   lid lifts, layers clear top down, the opening line returns
//   13.8 to 14.0   identical to 0.0, so the loop point is invisible
//
// Reads the playhead through useTime() from animations.jsx. Everything else in
// here is prefixed FS / fs so nothing collides with the engine's globals.

const FS_PALETTE = {
  cream:     '#f5f0e8',
  creamDk:   '#ebe4d6',
  creamLt:   '#faf6ed',
  paper:     '#fffdf7',
  ink:       '#0f1713',
  ink70:     'rgba(15,23,19,0.70)',
  ink55:     'rgba(15,23,19,0.55)',
  ink40:     'rgba(15,23,19,0.40)',
  ink25:     'rgba(15,23,19,0.25)',
  ink15:     'rgba(15,23,19,0.15)',
  ink08:     'rgba(15,23,19,0.08)',
  moss700:   '#32553f',
  moss600:   '#3f6b54',
  moss500:   '#4d7e65',
  moss400:   '#6fa37a',
  moss300:   '#93b89a',
  moss200:   '#b8cdbb',
  moss100:   '#d7e1d4',
  amber:     '#cd8a4b',
  amberSoft: '#e2a568',
};

const FS_FONTS = {
  display: '"Space Grotesk", system-ui, sans-serif',
  serif:   '"Instrument Serif", Georgia, serif',
  mono:    '"JetBrains Mono", ui-monospace, monospace',
};

// ── Helpers ─────────────────────────────────────────────────────────────
const fsClamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
const fsSmooth = (t) => { const x = fsClamp(t); return x * x * (3 - 2 * x); };
// 0 to 1 across [start, start + dur], smoothstepped
const fsRamp = (t, start, dur) => fsSmooth((t - start) / dur);
// One cycle every 1.75s: eight whole cycles per 14s loop, so it never seams.
const fsWave = (t, phase = 0) => 0.5 + 0.5 * Math.sin((t / 1.75) * Math.PI * 2 + phase);

// ── Timing ──────────────────────────────────────────────────────────────
const FS_DROP0      = 0.8;   // first layer starts to fall
const FS_DROP_GAP   = 1.8;   // one layer every 1.8s
const FS_FALL       = 0.85;  // fall time
const FS_SETTLE     = 0.5;   // squash and settle after landing
const FS_SWEEP_IN   = 9.6;
const FS_SWEEP_OUT  = 10.7;
const FS_GLOW_IN    = 10.3;
const FS_LID_IN     = 10.6;
const FS_LID_FALL   = 0.55;
const FS_OUT        = 12.6;  // outro begins
const FS_CLEAR0     = 12.75; // top layer starts to clear
const FS_CLEAR_GAP  = 0.13;
const FS_CLEAR_DUR  = 0.5;
const FS_FADE       = 0.35;  // caption crossfade
const FS_SHIFT      = 22;    // caption travel, px

const fsDropStart = (i) => FS_DROP0 + i * FS_DROP_GAP;
const fsLandAt    = (i) => fsDropStart(i) + FS_FALL;
const fsClearAt   = (i) => FS_CLEAR0 + (FS_LAYERS.length - 1 - i) * FS_CLEAR_GAP;

// ── Jar geometry (stage is 1920 x 1080) ─────────────────────────────────
const FS_CX      = 1330;              // jar centre line
const FS_RX      = 320;               // interior half width
const FS_RY      = 30;                // perspective of every ellipse
const FS_WALL    = 12;                // glass thickness
const FS_L       = FS_CX - FS_RX;     // interior left wall
const FS_R       = FS_CX + FS_RX;     // interior right wall
const FS_ORX     = FS_RX + FS_WALL;   // outer half width
const FS_ORY     = FS_RY + 2;
const FS_OL      = FS_CX - FS_ORX;
const FS_OR      = FS_CX + FS_ORX;
const FS_RIM_Y   = 318;               // mouth of the jar
const FS_FLOOR_Y = 920;               // interior floor
const FS_BASE    = 22;                // thick glass base
const FS_SHELF_Y = FS_FLOOR_Y + FS_BASE + FS_ORY + 2;

// ── Left column ─────────────────────────────────────────────────────────
const FS_COL_X     = 140;
const FS_EYEBROW_Y = 290;
const FS_SLIDE_Y   = 384;
const FS_PIPS_Y    = 700;

// ── The five layers, bottom up ──────────────────────────────────────────
const FS_LAYERS = [
  { idx: '01', name: 'Conversion',   note: 'the page has to close',
    h: 104, face: '#32553f', faceA: 0.86, top: '#4d7e65', topA: 0.92, text: '#faf6ed' },
  { idx: '02', name: 'AOV',          note: 'routines, not discounts',
    h: 104, face: '#3f6b54', faceA: 0.82, top: '#6fa37a', topA: 0.90, text: '#0f1713' },
  { idx: '03', name: 'Retention',    note: 'the second purchase',
    h: 104, face: '#6fa37a', faceA: 0.72, top: '#93b89a', topA: 0.88, text: '#0f1713' },
  { idx: '04', name: 'LTV',          note: 'refills and membership',
    h: 104, face: '#93b89a', faceA: 0.68, top: '#b8cdbb', topA: 0.88, text: '#0f1713' },
  { idx: '05', name: 'Brand equity', note: 'the crown that compounds',
    h: 124, face: '#cd8a4b', faceA: 0.86, top: '#e2a568', topA: 0.95, text: '#0f1713', crown: true },
];

// Resting position of each layer: bottom (yb) and top surface (yt).
const FS_REST = (() => {
  let yb = FS_FLOOR_Y;
  return FS_LAYERS.map((layer) => {
    const rest = { yb, yt: yb - layer.h };
    yb -= layer.h;
    return rest;
  });
})();
const FS_STACK_TOP = FS_REST[FS_REST.length - 1].yt;
const FS_FALL_FROM = FS_RIM_Y - 120; // every layer's bottom starts here

// A cylinder slice: front face from the top surface down to the bottom arc.
function fsSlicePath(yt, yb, rx = FS_RX, ry = FS_RY) {
  const l = FS_CX - rx;
  const r = FS_CX + rx;
  return `M ${l} ${yt} L ${l} ${yb} A ${rx} ${ry} 0 0 0 ${r} ${yb} `
       + `L ${r} ${yt} A ${rx} ${ry} 0 0 1 ${l} ${yt} Z`;
}

// Where layer i is at time t, or null when it is not on screen.
function fsLayerState(i, t) {
  const s = fsDropStart(i);
  if (t < s) return null;
  const layer = FS_LAYERS[i];
  const rest = FS_REST[i];

  const fadeIn = fsRamp(t, s, 0.3);
  const clear = fsRamp(t, fsClearAt(i), FS_CLEAR_DUR);
  const alpha = fadeIn * (1 - clear);
  if (alpha <= 0.001) return null;

  // Falls under gravity, so it lands at full speed...
  const p = fsClamp((t - s) / FS_FALL);
  const offset = -(rest.yb - FS_FALL_FROM) * (1 - p * p);

  // ...then squashes against the layer below and settles.
  const since = t - s - FS_FALL;
  const u = fsClamp(since / FS_SETTLE);
  const squash = since >= 0 && u < 1
    ? 0.12 * Math.sin(u * Math.PI * 2) * Math.pow(1 - u, 1.5)
    : 0;

  const sink = 10 * clear;
  const yb = rest.yb + offset + sink;
  const yt = yb - layer.h * (1 - squash);
  const landed = fsRamp(t, s + FS_FALL + 0.05, 0.4);
  const flash = since >= 0 ? fsClamp(1 - since / 0.5) : 0;
  return { yb, yt, alpha, landed, flash };
}

// ── Paper, grain, vignette ──────────────────────────────────────────────
function FSPaper() {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: `radial-gradient(ellipse at 52% 46%, ${FS_PALETTE.creamLt} 0%, ${FS_PALETTE.cream} 58%, ${FS_PALETTE.creamDk} 100%)`,
    }}/>
  );
}

function FSGrain() {
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none',
      opacity: 0.07, mixBlendMode: 'multiply',
      backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='220' height='220'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='1.3' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.14  0 0 0 0 0.12  0 0 0 0 0.08  0 0 0 1 0'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>")`,
      backgroundSize: '220px 220px',
    }}/>
  );
}

// ── Corner chrome ───────────────────────────────────────────────────────
function FSChrome({ t }) {
  const pulse = fsWave(t);
  const label = {
    fontFamily: FS_FONTS.mono, fontSize: 24, fontWeight: 500,
    letterSpacing: '0.18em', textTransform: 'uppercase',
    color: FS_PALETTE.ink40, whiteSpace: 'nowrap',
  };
  return (
    <>
      <div style={{ position: 'absolute', left: 64, top: 58, ...label }}>
        § 03 · formulation stack
      </div>
      <div style={{
        position: 'absolute', right: 64, top: 58,
        display: 'flex', alignItems: 'center', gap: 14, ...label,
      }}>
        <span>fig. 2 · bottom up</span>
        <span style={{
          display: 'inline-block', width: 12, height: 12, borderRadius: 6,
          background: FS_PALETTE.moss500, opacity: 0.35 + 0.65 * pulse,
        }}/>
      </div>
      <div style={{
        position: 'absolute', left: 64, right: 64, top: 108, height: 2,
        background: FS_PALETTE.ink08,
      }}/>
    </>
  );
}

// ── SVG defs ────────────────────────────────────────────────────────────
function FSDefs() {
  const stackClip = `M ${FS_L} ${FS_STACK_TOP} L ${FS_L} ${FS_FLOOR_Y} `
    + `A ${FS_RX} ${FS_RY} 0 0 0 ${FS_R} ${FS_FLOOR_Y} L ${FS_R} ${FS_STACK_TOP} `
    + `A ${FS_RX} ${FS_RY} 0 0 0 ${FS_L} ${FS_STACK_TOP} Z`;
  // Open to the sky so falling layers show, closed at the floor so nothing
  // ever pokes through the bottom of the jar.
  const jarClip = `M ${FS_L} -400 L ${FS_L} ${FS_FLOOR_Y} `
    + `A ${FS_RX} ${FS_RY} 0 0 0 ${FS_R} ${FS_FLOOR_Y} L ${FS_R} -400 Z`;
  return (
    <defs>
      {FS_LAYERS.map((layer, i) => (
        <linearGradient key={i} id={`fs-face-${i}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor={layer.top} stopOpacity={layer.faceA * 0.92}/>
          <stop offset="1" stopColor={layer.face} stopOpacity={layer.faceA}/>
        </linearGradient>
      ))}
      <linearGradient id="fs-cyl" x1="0" y1="0" x2="1" y2="0">
        <stop offset="0"    stopColor="#0f1713" stopOpacity="0.22"/>
        <stop offset="0.16" stopColor="#0f1713" stopOpacity="0"/>
        <stop offset="0.28" stopColor="#ffffff" stopOpacity="0.12"/>
        <stop offset="0.42" stopColor="#ffffff" stopOpacity="0"/>
        <stop offset="0.8"  stopColor="#0f1713" stopOpacity="0"/>
        <stop offset="1"    stopColor="#0f1713" stopOpacity="0.26"/>
      </linearGradient>
      <linearGradient id="fs-glass-back" x1="0" y1="0" x2="1" y2="0">
        <stop offset="0"    stopColor="#ffffff" stopOpacity="0.45"/>
        <stop offset="0.18" stopColor="#d7e1d4" stopOpacity="0.24"/>
        <stop offset="0.5"  stopColor="#d7e1d4" stopOpacity="0.14"/>
        <stop offset="0.82" stopColor="#d7e1d4" stopOpacity="0.24"/>
        <stop offset="1"    stopColor="#ffffff" stopOpacity="0.40"/>
      </linearGradient>
      <linearGradient id="fs-glass-front" x1="0" y1="0" x2="1" y2="0">
        <stop offset="0"    stopColor="#ffffff" stopOpacity="0.30"/>
        <stop offset="0.07" stopColor="#ffffff" stopOpacity="0.06"/>
        <stop offset="0.5"  stopColor="#ffffff" stopOpacity="0"/>
        <stop offset="0.9"  stopColor="#ffffff" stopOpacity="0.05"/>
        <stop offset="1"    stopColor="#ffffff" stopOpacity="0.24"/>
      </linearGradient>
      <linearGradient id="fs-hl" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0"    stopColor="#ffffff" stopOpacity="0"/>
        <stop offset="0.15" stopColor="#ffffff" stopOpacity="0.75"/>
        <stop offset="0.75" stopColor="#ffffff" stopOpacity="0.5"/>
        <stop offset="1"    stopColor="#ffffff" stopOpacity="0"/>
      </linearGradient>
      <linearGradient id="fs-sweep" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0"   stopColor="#fffdf7" stopOpacity="0"/>
        <stop offset="0.5" stopColor="#fffdf7" stopOpacity="0.6"/>
        <stop offset="1"   stopColor="#fffdf7" stopOpacity="0"/>
      </linearGradient>
      <linearGradient id="fs-lid-top" x1="0" y1="0" x2="1" y2="1">
        <stop offset="0" stopColor="#ffffff" stopOpacity="0.85"/>
        <stop offset="1" stopColor="#d7e1d4" stopOpacity="0.55"/>
      </linearGradient>
      <radialGradient id="fs-knob" cx="0.38" cy="0.32" r="0.75">
        <stop offset="0"   stopColor="#93b89a"/>
        <stop offset="0.7" stopColor="#3f6b54"/>
        <stop offset="1"   stopColor="#32553f"/>
      </radialGradient>
      <radialGradient id="fs-glow" cx="0.5" cy="0.5" r="0.5">
        <stop offset="0"    stopColor="#cd8a4b" stopOpacity="0.42"/>
        <stop offset="0.45" stopColor="#e2a568" stopOpacity="0.16"/>
        <stop offset="1"    stopColor="#e2a568" stopOpacity="0"/>
      </radialGradient>
      <radialGradient id="fs-shadow" cx="0.5" cy="0.5" r="0.5">
        <stop offset="0" stopColor="#0f1713" stopOpacity="0.24"/>
        <stop offset="1" stopColor="#0f1713" stopOpacity="0"/>
      </radialGradient>
      <clipPath id="fs-stack-clip"><path d={stackClip}/></clipPath>
      <clipPath id="fs-jar-clip"><path d={jarClip}/></clipPath>
    </defs>
  );
}

// ── Shelf ───────────────────────────────────────────────────────────────
function FSShelf() {
  const x1 = 900;
  const x2 = 1760;
  return (
    <g>
      <rect x={x1} y={FS_SHELF_Y} width={x2 - x1} height={18} fill={FS_PALETTE.creamDk}/>
      <rect x={x1} y={FS_SHELF_Y + 18} width={x2 - x1} height={22} fill={FS_PALETTE.ink08} opacity={0.5}/>
      <line x1={x1} y1={FS_SHELF_Y} x2={x2} y2={FS_SHELF_Y} stroke={FS_PALETTE.ink25} strokeWidth={2}/>
      <line x1={x1} y1={FS_SHELF_Y + 18} x2={x2} y2={FS_SHELF_Y + 18} stroke={FS_PALETTE.ink15} strokeWidth={1.5}/>
      <ellipse cx={FS_CX} cy={FS_SHELF_Y + 2} rx={FS_ORX + 70} ry={18} fill="url(#fs-shadow)"/>
    </g>
  );
}

// ── Crown glow, behind the jar ──────────────────────────────────────────
function FSCrownGlow({ t }) {
  const env = fsRamp(t, FS_GLOW_IN, 0.7) * (1 - fsRamp(t, FS_OUT, 0.5));
  if (env <= 0.001) return null;
  return (
    <ellipse
      cx={FS_CX} cy={FS_STACK_TOP + 20} rx={540} ry={240}
      fill="url(#fs-glow)" opacity={env * (0.85 + 0.15 * fsWave(t))}
    />
  );
}

// ── Jar, back half (drawn before the layers) ────────────────────────────
function FSJarBack() {
  const bottom = FS_FLOOR_Y + FS_BASE;
  const body = `M ${FS_OL} ${FS_RIM_Y} L ${FS_OL} ${bottom} `
    + `A ${FS_ORX} ${FS_ORY} 0 0 0 ${FS_OR} ${bottom} L ${FS_OR} ${FS_RIM_Y} `
    + `A ${FS_ORX} ${FS_ORY} 0 0 0 ${FS_OL} ${FS_RIM_Y} Z`;
  return (
    <g>
      <path d={body} fill="url(#fs-glass-back)"/>
      <ellipse cx={FS_CX} cy={FS_FLOOR_Y} rx={FS_RX} ry={FS_RY}
        fill="rgba(63,107,84,0.08)" stroke={FS_PALETTE.ink15} strokeWidth={1.5}/>
      {/* back halves of the rim */}
      <path d={`M ${FS_OL} ${FS_RIM_Y} A ${FS_ORX} ${FS_ORY} 0 0 1 ${FS_OR} ${FS_RIM_Y}`}
        fill="none" stroke={FS_PALETTE.ink40} strokeWidth={2.5}/>
      <path d={`M ${FS_L} ${FS_RIM_Y} A ${FS_RX} ${FS_RY} 0 0 1 ${FS_R} ${FS_RIM_Y}`}
        fill="none" stroke={FS_PALETTE.ink15} strokeWidth={1.5}/>
    </g>
  );
}

// ── One layer ───────────────────────────────────────────────────────────
function FSSlice({ i, st }) {
  const d = fsSlicePath(st.yt, st.yb);
  const layer = FS_LAYERS[i];
  return (
    <g opacity={st.alpha}>
      <path d={d} fill={`url(#fs-face-${i})`}/>
      <path d={d} fill="url(#fs-cyl)"/>
      <ellipse cx={FS_CX} cy={st.yt} rx={FS_RX} ry={FS_RY} fill={layer.top} fillOpacity={layer.topA}/>
      {st.flash > 0 && (
        <ellipse cx={FS_CX} cy={st.yt} rx={FS_RX} ry={FS_RY} fill={FS_PALETTE.paper} opacity={0.45 * st.flash}/>
      )}
      {/* meniscus: a thin light line along the front edge of the surface */}
      <path d={`M ${FS_L} ${st.yt} A ${FS_RX} ${FS_RY} 0 0 0 ${FS_R} ${st.yt}`}
        fill="none" stroke="#ffffff" strokeOpacity={0.4} strokeWidth={2}/>
    </g>
  );
}

// ── Light running up through the finished stack ─────────────────────────
function FSSweep({ t }) {
  if (t < FS_SWEEP_IN || t > FS_SWEEP_OUT) return null;
  const p = (t - FS_SWEEP_IN) / (FS_SWEEP_OUT - FS_SWEEP_IN);
  const eased = fsSmooth(p);
  const y = FS_FLOOR_Y + 40 + (FS_STACK_TOP - 40 - (FS_FLOOR_Y + 40)) * eased;
  return (
    <g clipPath="url(#fs-stack-clip)">
      <rect x={FS_L} y={y - 75} width={FS_RX * 2} height={150}
        fill="url(#fs-sweep)" opacity={Math.sin(Math.PI * p)}/>
    </g>
  );
}

// ── Jar, front half (drawn over the layers) ─────────────────────────────
function FSJarFront() {
  const bottom = FS_FLOOR_Y + FS_BASE;
  const body = `M ${FS_OL} ${FS_RIM_Y} L ${FS_OL} ${bottom} `
    + `A ${FS_ORX} ${FS_ORY} 0 0 0 ${FS_OR} ${bottom} L ${FS_OR} ${FS_RIM_Y} `
    + `A ${FS_ORX} ${FS_ORY} 0 0 1 ${FS_OL} ${FS_RIM_Y} Z`;
  const base = `M ${FS_OL} ${FS_FLOOR_Y} L ${FS_OL} ${bottom} `
    + `A ${FS_ORX} ${FS_ORY} 0 0 0 ${FS_OR} ${bottom} L ${FS_OR} ${FS_FLOOR_Y} `
    + `A ${FS_ORX} ${FS_ORY} 0 0 1 ${FS_OL} ${FS_FLOOR_Y} Z`;
  const outline = `M ${FS_OL} ${FS_RIM_Y} L ${FS_OL} ${bottom} `
    + `A ${FS_ORX} ${FS_ORY} 0 0 0 ${FS_OR} ${bottom} L ${FS_OR} ${FS_RIM_Y}`;
  const hlTop = FS_RIM_Y + 50;
  const hlH = FS_FLOOR_Y - FS_RIM_Y - 110;
  return (
    <g>
      <path d={base} fill="rgba(147,184,154,0.20)"/>
      <path d={body} fill="url(#fs-glass-front)"/>
      {/* inner walls and the front of the floor */}
      <line x1={FS_L} y1={FS_RIM_Y} x2={FS_L} y2={FS_FLOOR_Y} stroke={FS_PALETTE.ink15} strokeWidth={1.5}/>
      <line x1={FS_R} y1={FS_RIM_Y} x2={FS_R} y2={FS_FLOOR_Y} stroke={FS_PALETTE.ink15} strokeWidth={1.5}/>
      <path d={`M ${FS_L} ${FS_FLOOR_Y} A ${FS_RX} ${FS_RY} 0 0 0 ${FS_R} ${FS_FLOOR_Y}`}
        fill="none" stroke={FS_PALETTE.ink25} strokeWidth={1.5}/>
      {/* glass highlights */}
      <rect x={FS_OL + 24} y={hlTop} width={22} height={hlH} rx={11} fill="url(#fs-hl)"/>
      <rect x={FS_OL + 56} y={hlTop + 40} width={7} height={hlH - 80} rx={3.5} fill="url(#fs-hl)" opacity={0.6}/>
      <rect x={FS_OR - 42} y={hlTop + 20} width={10} height={hlH - 40} rx={5} fill="url(#fs-hl)" opacity={0.35}/>
      {/* silhouette and front halves of the rim */}
      <path d={outline} fill="none" stroke={FS_PALETTE.ink40} strokeWidth={2.5} strokeLinejoin="round"/>
      <path d={`M ${FS_OL} ${FS_RIM_Y} A ${FS_ORX} ${FS_ORY} 0 0 0 ${FS_OR} ${FS_RIM_Y}`}
        fill="none" stroke={FS_PALETTE.ink40} strokeWidth={2.5}/>
      <path d={`M ${FS_L} ${FS_RIM_Y} A ${FS_RX} ${FS_RY} 0 0 0 ${FS_R} ${FS_RIM_Y}`}
        fill="none" stroke={FS_PALETTE.ink25} strokeWidth={1.5}/>
    </g>
  );
}

// ── Lid: settles once the crown is in, lifts away for the loop ──────────
function FSLid({ t }) {
  if (t < FS_LID_IN) return null;
  const p = fsClamp((t - FS_LID_IN) / FS_LID_FALL);
  const v = fsClamp((t - FS_LID_IN - FS_LID_FALL) / 0.4);
  const bounce = p >= 1 ? 9 * Math.sin(Math.PI * v) * (1 - v) : 0;
  const out = fsClamp((t - FS_OUT) / 0.6);
  const dy = -150 * (1 - p * p) - bounce - 160 * out * out;
  const alpha = fsRamp(t, FS_LID_IN, 0.3) * (1 - fsSmooth(out));
  if (alpha <= 0.001) return null;

  const top = FS_RIM_Y - 16 + dy;
  const bot = FS_RIM_Y + 4 + dy;
  const lrx = FS_ORX + 16;
  const lry = FS_ORY + 3;
  const neckTop = top - 40;
  const knobY = neckTop - 30;
  return (
    <g opacity={alpha}>
      <path d={fsSlicePath(top, bot, lrx, lry)} fill="rgba(255,253,247,0.62)"
        stroke={FS_PALETTE.ink40} strokeWidth={2}/>
      <ellipse cx={FS_CX} cy={top} rx={lrx} ry={lry} fill="url(#fs-lid-top)"
        stroke={FS_PALETTE.ink25} strokeWidth={2}/>
      <rect x={FS_CX - 24} y={neckTop} width={48} height={42} rx={8}
        fill="rgba(255,253,247,0.75)" stroke={FS_PALETTE.ink40} strokeWidth={2}/>
      <circle cx={FS_CX} cy={knobY} r={34} fill="url(#fs-knob)"
        stroke={FS_PALETTE.moss700} strokeOpacity={0.45} strokeWidth={2}/>
      <ellipse cx={FS_CX - 11} cy={knobY - 12} rx={10} ry={6} fill="#ffffff" opacity={0.45}/>
    </g>
  );
}

// ── Sparkles over the sealed jar (hold phase only) ──────────────────────
const FS_SPARKS = [
  { x: FS_CX - 300, y: FS_RIM_Y - 74,  s: 20, phase: 0.0 },
  { x: FS_CX + 312, y: FS_RIM_Y - 52,  s: 15, phase: 2.1 },
  { x: FS_CX + 150, y: FS_RIM_Y - 158, s: 24, phase: 4.2 },
];

function FSSparkles({ t }) {
  const env = fsRamp(t, 10.9, 0.4) * (1 - fsRamp(t, FS_OUT, 0.35));
  if (env <= 0.001) return null;
  return (
    <g>
      {FS_SPARKS.map((sp, i) => {
        const k = env * (0.55 + 0.45 * fsWave(t, sp.phase));
        const s = sp.s;
        const d = `M 0 ${-s} Q 0 0 ${s} 0 Q 0 0 0 ${s} Q 0 0 ${-s} 0 Q 0 0 0 ${-s} Z`;
        return (
          <path key={i} d={d} fill={FS_PALETTE.amber} opacity={k}
            transform={`translate(${sp.x} ${sp.y}) scale(${0.6 + 0.4 * k})`}/>
        );
      })}
    </g>
  );
}

// ── Labels inside the jar ───────────────────────────────────────────────
function FSCrownIcon({ color }) {
  return (
    <svg width="48" height="40" viewBox="0 0 48 40" style={{ display: 'block', flexShrink: 0 }}>
      <path d="M 3 36 L 3 10 L 14 22 L 24 4 L 34 22 L 45 10 L 45 36 Z"
        fill={color} fillOpacity={0.88} strokeLinejoin="round"/>
    </svg>
  );
}

function FSJarLabels({ states }) {
  return (
    <>
      {states.map((st, i) => {
        if (!st || st.landed <= 0.001) return null;
        const layer = FS_LAYERS[i];
        const cy = (st.yt + st.yb) / 2 + FS_RY * 0.55;
        const op = st.alpha * st.landed;
        const lift = (1 - st.landed) * 14;
        return (
          <React.Fragment key={i}>
            <div style={{
              position: 'absolute', left: FS_L + 46, top: cy,
              transform: `translateY(-50%) translateY(${lift}px)`,
              opacity: op,
              display: 'flex', alignItems: 'center', gap: 16,
              fontFamily: FS_FONTS.display, fontWeight: 700, fontSize: 62,
              letterSpacing: '-0.03em', lineHeight: 1,
              color: layer.text, whiteSpace: 'nowrap',
            }}>
              {layer.crown && <FSCrownIcon color={layer.text}/>}
              <span>{layer.name}</span>
            </div>
            <div style={{
              position: 'absolute', right: 1920 - (FS_R - 44), top: cy,
              transform: `translateY(-50%) translateY(${lift}px)`,
              opacity: op * 0.8,
              fontFamily: FS_FONTS.serif, fontStyle: 'italic', fontSize: 60,
              lineHeight: 1, color: layer.text, whiteSpace: 'nowrap',
            }}>
              {layer.idx}
            </div>
          </React.Fragment>
        );
      })}
    </>
  );
}

// ── Left column: eyebrow, the caption for the current beat, progress ────
function FSEyebrow() {
  return (
    <>
      <div style={{
        position: 'absolute', left: FS_COL_X, top: FS_EYEBROW_Y,
        fontFamily: FS_FONTS.mono, fontSize: 44, fontWeight: 500,
        letterSpacing: '0.14em', textTransform: 'uppercase',
        color: FS_PALETTE.moss600, whiteSpace: 'nowrap', lineHeight: 1,
      }}>
        The Clean Shelf Method
      </div>
      <div style={{
        position: 'absolute', left: FS_COL_X, top: FS_EYEBROW_Y + 60,
        width: 64, height: 3, background: FS_PALETTE.moss400,
      }}/>
    </>
  );
}

function FSHeadline({ a, b, opacity, shift }) {
  if (opacity <= 0.001) return null;
  return (
    <div style={{
      position: 'absolute', left: FS_COL_X, top: FS_SLIDE_Y,
      opacity, transform: `translateY(${shift}px)`, whiteSpace: 'nowrap',
    }}>
      <div style={{
        fontFamily: FS_FONTS.display, fontWeight: 700, fontSize: 104,
        letterSpacing: '-0.04em', lineHeight: 1, color: FS_PALETTE.ink,
      }}>
        {a}
      </div>
      <div style={{
        fontFamily: FS_FONTS.serif, fontStyle: 'italic', fontWeight: 400,
        fontSize: 120, letterSpacing: '-0.02em', lineHeight: 1.05,
        color: FS_PALETTE.moss600, marginTop: 6,
      }}>
        {b}
      </div>
    </div>
  );
}

function FSLayerSlide({ layer, opacity, shift }) {
  if (opacity <= 0.001) return null;
  return (
    <div style={{
      position: 'absolute', left: FS_COL_X, top: FS_SLIDE_Y,
      opacity, transform: `translateY(${shift}px)`, whiteSpace: 'nowrap',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 18,
        fontFamily: FS_FONTS.mono, fontSize: 44, fontWeight: 500,
        letterSpacing: '0.2em', textTransform: 'uppercase',
        color: FS_PALETTE.moss500, lineHeight: 1,
      }}>
        <span style={{
          display: 'inline-block', width: 38, height: 38, borderRadius: 8,
          background: layer.face,
        }}/>
        <span>Layer {layer.idx}</span>
      </div>
      <div style={{
        fontFamily: FS_FONTS.display, fontWeight: 700, fontSize: 100,
        letterSpacing: '-0.04em', lineHeight: 1, color: FS_PALETTE.ink,
        marginTop: 26,
      }}>
        {layer.name}
      </div>
      <div style={{
        fontFamily: FS_FONTS.serif, fontStyle: 'italic', fontWeight: 400,
        fontSize: 66, lineHeight: 1.1, color: FS_PALETTE.moss600,
        marginTop: 14,
      }}>
        {layer.note}
      </div>
    </div>
  );
}

// Crossfade window: fades in from `start`, out from `end`.
function fsSlide(t, start, end) {
  const inP = fsRamp(t, start, FS_FADE);
  const outP = fsRamp(t, end, FS_FADE);
  return { opacity: inP * (1 - outP), shift: (1 - inP) * FS_SHIFT - outP * FS_SHIFT };
}

function FSNarrative({ t }) {
  // The opening line straddles the loop point: out at 0.95s, back in at 13.4s.
  const intro = t < 7
    ? { opacity: 1 - fsRamp(t, 0.95, FS_FADE), shift: -FS_SHIFT * fsRamp(t, 0.95, FS_FADE) }
    : { opacity: fsRamp(t, 13.4, FS_FADE), shift: FS_SHIFT * (1 - fsRamp(t, 13.4, FS_FADE)) };
  const finale = fsSlide(t, 10.3, 13.05);
  return (
    <>
      <FSHeadline a="Formulated" b="bottom up." {...intro}/>
      {FS_LAYERS.map((layer, i) => {
        const start = fsDropStart(i) + 0.5;
        const end = i < FS_LAYERS.length - 1 ? fsDropStart(i + 1) + 0.25 : 10.0;
        const w = fsSlide(t, start, end);
        return <FSLayerSlide key={i} layer={layer} {...w}/>;
      })}
      <FSHeadline a="Five layers." b="No shortcut." {...finale}/>
    </>
  );
}

function FSPips({ t }) {
  return (
    <div style={{
      position: 'absolute', left: FS_COL_X, top: FS_PIPS_Y,
      display: 'flex', gap: 14,
    }}>
      {FS_LAYERS.map((layer, i) => {
        const fill = fsRamp(t, fsLandAt(i), 0.35) * (1 - fsRamp(t, fsClearAt(i), FS_CLEAR_DUR));
        return (
          <div key={i} style={{
            position: 'relative', width: 100, height: 18, borderRadius: 9,
            background: FS_PALETTE.ink08, overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', left: 0, top: 0, height: 18,
              width: `${fill * 100}%`, borderRadius: 9, background: layer.face,
            }}/>
          </div>
        );
      })}
    </div>
  );
}

// ── Scene root ──────────────────────────────────────────────────────────
function FormulationStackScene() {
  const t = useTime();
  const states = FS_LAYERS.map((_, i) => fsLayerState(i, t));
  return (
    <>
      <FSPaper/>

      <svg width="1920" height="1080" viewBox="0 0 1920 1080"
        style={{ position: 'absolute', left: 0, top: 0, overflow: 'visible', pointerEvents: 'none' }}>
        <FSDefs/>
        <FSShelf/>
        <FSCrownGlow t={t}/>
        <FSJarBack/>
        <g clipPath="url(#fs-jar-clip)">
          {states.map((st, i) => (st ? <FSSlice key={i} i={i} st={st}/> : null))}
        </g>
        <FSSweep t={t}/>
        <FSJarFront/>
        <FSLid t={t}/>
        <FSSparkles t={t}/>
      </svg>

      <FSJarLabels states={states}/>

      <FSEyebrow/>
      <FSNarrative t={t}/>
      <FSPips t={t}/>

      <FSChrome t={t}/>
      <FSGrain/>
    </>
  );
}

Object.assign(window, { FormulationStackScene, FS_PALETTE, FS_FONTS });
