// launch-arch.jsx  ·  "§ 03 · the launch arch"  ·  Shopify store setup
//
// 14 second loop. Six moss green voussoirs (domain, theme, catalog, payments,
// email, analytics) are lowered onto a timber centering one at a time, left
// and right alternately from the springers up, the way a real arch is laid.
// The amber crown stone, LAUNCH, goes in last and locks the ring. The
// centering is then struck and the arch stands on its own, held by the stones
// pressing on each other rather than by mortar, and the opening lights up:
// the store is live. After a settled hold the stones lift away and the frame
// returns to the empty centering it started from, so the loop is seamless.
//
// Timing map (seconds)
//    0.00  empty frame: dashed slots, centering, ground, first caption
//    0.45  first stone appears; one every second, each lands 0.8s later
//    6.25  sixth stone lands
//    6.70  crown appears and hangs over the gap, drops at 7.75
//    8.10  SEAL: arch compresses, joints flash from crown to springers
//    8.90  centering struck (lowered and faded) by 9.70
//    9.40  live glow, headline completes, closing caption
//   10.50  settled hold until 13.00 (reduced motion holds LA_HOLD = 12.00)
//   13.00  outro: stones lift away, centering returns, back to frame 0
//
// The stage is often shown about 310px wide on a phone, so every string that
// has to be read is 50px or larger in stage units. Visible copy is plain
// text: no emoji and no long dashes.

const LA_PALETTE = {
  cream:     '#f5f0e8',
  creamLt:   '#faf6ed',
  creamDk:   '#ebe4d6',
  timber:    '#e6dbc6',
  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)',
  ink18:     'rgba(15,23,19,0.18)',
  ink12:     'rgba(15,23,19,0.12)',
  moss700:   '#32553f',
  moss600:   '#3f6b54',
  moss500:   '#4d7e65',
  moss400:   '#6fa37a',
  moss200:   '#b8cdbb',
  amber:     '#cd8a4b',
  amberSoft: '#e2a568',
  amberDeep: '#a5692f',
  amberGlow: 'rgba(205,138,75,0.35)',
};
const LA_FONTS = {
  display: '"Space Grotesk", system-ui, sans-serif',
  serif:   '"Instrument Serif", Georgia, serif',
  mono:    '"JetBrains Mono", ui-monospace, monospace',
};

// ── Small maths helpers (prefixed so they never collide with the engine) ──
const laClamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
const laRamp = (t, a, b) => laClamp((t - a) / (b - a));
const laEase = (t) => 1 - Math.pow(1 - t, 3);
const laEaseIn = (t) => t * t;
const laSmooth = (t) => t * t * (3 - 2 * t);
const laMix = (a, b, t) => a + (b - a) * t;
const laRand = (i, seed) => {
  const x = Math.sin(i * 12.9898 + seed * 78.233) * 43758.5453;
  return x - Math.floor(x);
};
const LA_DEG = Math.PI / 180;

// ── Timing ────────────────────────────────────────────────────────────────
const LA_HOLD = 12.0;            // settled frame held for reduced motion
const LA_STONE_T0 = 0.45;        // first stone appears
const LA_STONE_GAP = 1.0;        // one stone per second
const LA_APPEAR = 0.3;           // fade in while descending to the hang point
const LA_HANG = 0.22;            // brief hang so the label can be read
const LA_DROP = 0.28;            // gravity drop into the slot
const LA_CROWN_APPEAR = 6.7;
const LA_CROWN_HANG = 7.1;
const LA_CROWN_DROP = 7.75;
const LA_SEAL = 8.1;             // crown lands, ring is locked
const LA_STRIKE = 8.9;           // centering lowered away
const LA_STRIKE_END = 9.7;
const LA_LIVE = 9.4;             // opening lights up
const LA_OUT = 13.0;             // outro begins

// ── Geometry (stage units, 1920 x 1080) ───────────────────────────────────
const LA_CX = 960;               // arch centre, on the ground line
const LA_CY = 935;
const LA_RIN = 340;              // intrados radius
const LA_ROUT = 700;             // extrados radius
const LA_STEP = 25;              // each side stone spans 25 degrees
const LA_CROWN_HALF = 15;        // crown spans 75 to 105 degrees
const LA_CROWN_RIN = 322;        // keystone drops below the intrados
const LA_CROWN_ROUT = 746;       // and stands proud of the extrados
const LA_JOINT = 4;              // half the width of a dry joint

const laPt = (r, aDeg) => [
  LA_CX + r * Math.cos(aDeg * LA_DEG),
  LA_CY - r * Math.sin(aDeg * LA_DEG),
];

// A voussoir outline between angles a2 < a1 and radii rin < rout. Joint
// faces are pulled in by LA_JOINT so a cream gap shows between stones; a face
// that sits on the ground (bed) gets no gap. `rough` jitters the outline a
// few pixels for a hand dressed edge. `inset` returns a drafted margin line.
function laStonePath(a1, a2, rin, rout, bed1, bed2, rough, seed, inset) {
  const pad = inset || 0;
  const g1 = (bed1 ? 0 : LA_JOINT) + pad;
  const g2 = (bed2 ? 0 : LA_JOINT) + pad;
  const ri = rin + pad;
  const ro = rout - pad;
  const ang1 = (r) => a1 - Math.asin(g1 / r) / LA_DEG;
  const ang2 = (r) => a2 + Math.asin(g2 / r) / LA_DEG;
  let k = 0;
  const jit = (amp) => (rough ? (laRand(seed * 131 + k++, 3) - 0.5) * 2 * amp : 0);
  const pts = [];
  const N_OUT = 10, N_IN = 8, N_J = 4;
  for (let n = 0; n <= N_OUT; n++) {
    const corner = n === 0 || n === N_OUT;
    pts.push(laPt(ro + jit(corner ? 1.2 : 3.2), laMix(ang1(ro), ang2(ro), n / N_OUT)));
  }
  for (let n = 1; n < N_J; n++) {
    const r = laMix(ro, ri, n / N_J);
    const off = bed2 ? 0 : jit(1.6) / r / LA_DEG;
    pts.push(laPt(r, ang2(r) + off));
  }
  for (let n = 0; n <= N_IN; n++) {
    const corner = n === 0 || n === N_IN;
    pts.push(laPt(ri + jit(corner ? 1.0 : 2.2), laMix(ang2(ri), ang1(ri), n / N_IN)));
  }
  for (let n = 1; n < N_J; n++) {
    const r = laMix(ri, ro, n / N_J);
    const off = bed1 ? 0 : jit(1.6) / r / LA_DEG;
    pts.push(laPt(r, ang1(r) + off));
  }
  return 'M' + pts.map((p) => p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' L') + ' Z';
}

// Fall order is the order the page lists them. Left and right alternate from
// the springers up; the crown is last.
const LA_STONE_DEFS = [
  { label: 'domain',    side: 'L', tier: 0 },
  { label: 'theme',     side: 'R', tier: 0 },
  { label: 'catalog',   side: 'L', tier: 1 },
  { label: 'payments',  side: 'R', tier: 1 },
  { label: 'email',     side: 'L', tier: 2 },
  { label: 'analytics', side: 'R', tier: 2 },
  { label: 'LAUNCH',    crown: true },
];

// Label centres: the widest upright 56px box that clears each stone by 14px,
// solved offline for this geometry against Space Grotesk 600 at 50px (left
// side; the right side mirrors). Widest label, "payments", is 239px in a
// 278px slot; "analytics" is 219px in a 234px slot.
const LA_LABEL_LEFT = [[452, 823], [508, 615], [680, 411]];

function laBuildStone(def, idx) {
  let a1, a2, rin = LA_RIN, rout = LA_ROUT;
  if (def.crown) {
    a1 = 90 + LA_CROWN_HALF; a2 = 90 - LA_CROWN_HALF;
    rin = LA_CROWN_RIN; rout = LA_CROWN_ROUT;
  } else if (def.side === 'L') {
    a1 = 180 - def.tier * LA_STEP; a2 = a1 - LA_STEP;
  } else {
    a2 = def.tier * LA_STEP; a1 = a2 + LA_STEP;
  }
  const bed1 = a1 === 180;
  const bed2 = a2 === 0;
  const c = laPt((rin + rout) / 2, (a1 + a2) / 2);
  let lx, ly;
  if (def.crown) { lx = LA_CX; ly = 330; }
  else {
    const p = LA_LABEL_LEFT[def.tier];
    lx = def.side === 'L' ? p[0] : 2 * LA_CX - p[0];
    ly = p[1];
  }
  // Where dust kicks up on landing: the joint the stone comes down onto.
  const mid = (LA_RIN + LA_ROUT) / 2;
  const seats = def.crown
    ? [laPt(mid, a1), laPt(mid, a2)]
    : [laPt(mid, def.side === 'L' ? a1 : a2)];
  return {
    label: def.label,
    crown: !!def.crown,
    idx,
    dir: def.crown ? 0 : (def.side === 'L' ? -1 : 1),
    cx: c[0], cy: c[1], lx, ly, seats,
    rough: laStonePath(a1, a2, rin, rout, bed1, bed2, true, idx + 1, 0),
    clean: laStonePath(a1, a2, rin, rout, bed1, bed2, false, idx + 1, 0),
    inset: laStonePath(a1, a2, rin, rout, bed1, bed2, false, idx + 1, 11),
  };
}
const LA_STONES = LA_STONE_DEFS.map(laBuildStone);
const LA_CROWN = LA_STONES[6];

const laStart = (s) => (s.crown ? LA_CROWN_APPEAR : LA_STONE_T0 + s.idx * LA_STONE_GAP);
const laLand = (s) => (s.crown ? LA_SEAL : laStart(s) + LA_APPEAR + LA_HANG + LA_DROP);
// Outro: the crown lifts first, then the rest in reverse order, all gone
// before 13.95 so the wrap to frame 0 has nothing left to snap.
const laOutStart = (s) => LA_OUT + 0.1 + (6 - s.idx) * 0.06;

function laStoneState(s, t) {
  const start = laStart(s);
  const land = laLand(s);
  if (t < start) return null;
  let dy = 0, rot = 0, op = 1;
  if (s.crown) {
    // Hangs at -160 so the whole keystone, top edge included, stays about
    // 17px inside the frame even at the peak of the small lift (-170).
    if (t < LA_CROWN_HANG) {
      const p = laEase(laRamp(t, start, LA_CROWN_HANG));
      op = p; dy = laMix(-254, -160, p);
    } else if (t < LA_CROWN_DROP) {
      const q = laRamp(t, LA_CROWN_HANG, LA_CROWN_DROP);
      dy = -160 - 10 * Math.sin(Math.PI * q);         // a small lift before the drop
    } else if (t < land) {
      const q = laRamp(t, LA_CROWN_DROP, land);
      dy = -160 * (1 - q * q * q);
    } else {
      const tau = t - land;
      dy = -5 * Math.exp(-tau * 12) * Math.abs(Math.sin(tau * Math.PI / 0.11));
    }
  } else {
    const r0 = 7 * s.dir;
    const hangAt = start + LA_APPEAR;
    const dropAt = hangAt + LA_HANG;
    if (t < hangAt) {
      const p = laEase(laRamp(t, start, hangAt));
      op = p; dy = laMix(-220, -150, p); rot = r0 * laMix(1, 0.6, p);
    } else if (t < dropAt) {
      const q = laSmooth(laRamp(t, hangAt, dropAt));
      dy = laMix(-150, -138, q); rot = r0 * laMix(0.6, 0.5, q);
    } else if (t < land) {
      const e = laEaseIn(laRamp(t, dropAt, land));
      dy = laMix(-138, 0, e); rot = r0 * 0.5 * (1 - e);
    } else {
      const tau = t - land;
      const k = Math.exp(-tau * 10);
      dy = -7 * k * Math.abs(Math.sin(tau * Math.PI / 0.14));
      rot = s.dir * 1.2 * k * Math.sin(tau * 26);
    }
  }
  const o0 = laOutStart(s);
  if (t >= o0) {
    const q = laSmooth(laRamp(t, o0, o0 + 0.45));
    op *= 1 - q; dy -= 28 * q;
  }
  return { dy, rot, op };
}

// The whole ring compresses a touch toward the ground when the crown lands.
function laSquash(t) {
  const tau = t - LA_SEAL;
  if (tau < 0 || tau > 1.4) return 0;
  return 0.012 * Math.exp(-tau * 5) * Math.sin(Math.PI * tau / 0.14);
}

// ── Film grain ────────────────────────────────────────────────────────────
function LAFilmGrain() {
  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.4' 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',
    }} />
  );
}

// ── SVG defs ──────────────────────────────────────────────────────────────
function LADefs() {
  return (
    <defs>
      <radialGradient id="laMossFill" gradientUnits="userSpaceOnUse" cx={LA_CX} cy={LA_CY} r={720}>
        <stop offset="0.46" stopColor={LA_PALETTE.moss700} />
        <stop offset="0.72" stopColor={LA_PALETTE.moss600} />
        <stop offset="0.98" stopColor={LA_PALETTE.moss500} />
      </radialGradient>
      <linearGradient id="laAmberFill" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stopColor={LA_PALETTE.amberSoft} />
        <stop offset="1" stopColor={LA_PALETTE.amber} />
      </linearGradient>
      <radialGradient id="laVoidFill" gradientUnits="userSpaceOnUse" cx={LA_CX} cy={LA_CY} r={440}>
        <stop offset="0" stopColor={LA_PALETTE.amber} stopOpacity="0.55" />
        <stop offset="0.55" stopColor={LA_PALETTE.amber} stopOpacity="0.2" />
        <stop offset="1" stopColor={LA_PALETTE.amber} stopOpacity="0" />
      </radialGradient>
      <radialGradient id="laHaloFill">
        <stop offset="0" stopColor={LA_PALETTE.amber} stopOpacity="0.5" />
        <stop offset="1" stopColor={LA_PALETTE.amber} stopOpacity="0" />
      </radialGradient>
      <clipPath id="laCountClip">
        <rect x={1480} y={100} width={262} height={164} />
      </clipPath>
    </defs>
  );
}

// ── Ground line with hatched footings under the springers ─────────────────
const LA_HATCH = (() => {
  let d = '';
  for (let x = 240; x <= 660; x += 20) d += `M${x} ${LA_CY + 3} l-14 18 `;
  for (let x = 1260; x <= 1680; x += 20) d += `M${x} ${LA_CY + 3} l-14 18 `;
  return d;
})();

function LAGround() {
  return (
    <g>
      <line x1={140} y1={LA_CY} x2={1780} y2={LA_CY} stroke={LA_PALETTE.ink40} strokeWidth={2} />
      <path d={LA_HATCH} stroke={LA_PALETTE.ink18} strokeWidth={2} fill="none" />
      <path d={`M${LA_CX} ${LA_CY + 8} v14 M${LA_CX - 7} ${LA_CY + 15} h14`} stroke={LA_PALETTE.ink25} strokeWidth={2} />
    </g>
  );
}

// ── Timber centering: the temporary frame the stones are laid on ──────────
const LA_RIB = `M${LA_CX - 320} ${LA_CY} A320 320 0 0 1 ${LA_CX + 320} ${LA_CY} ` +
  `L${LA_CX + 296} ${LA_CY} A296 296 0 0 0 ${LA_CX - 296} ${LA_CY} Z`;
const LA_LAGGING = (() => {
  let d = '';
  for (let a = 6; a <= 174; a += 6) {
    const p = laPt(321, a), q = laPt(337, a);
    d += `M${p[0].toFixed(1)} ${p[1].toFixed(1)} L${q[0].toFixed(1)} ${q[1].toFixed(1)} `;
  }
  return d;
})();
const LA_TIMBERS = [
  [LA_CX, LA_CY - 296, LA_CX, LA_CY - 74],               // king post
  [LA_CX - 150, LA_CY - 253, LA_CX - 150, LA_CY - 74],   // side posts
  [LA_CX + 150, LA_CY - 253, LA_CX + 150, LA_CY - 74],
  [LA_CX - 150, LA_CY - 74, LA_CX - 262, LA_CY - 140],   // braces
  [LA_CX + 150, LA_CY - 74, LA_CX + 262, LA_CY - 140],
  [LA_CX - 304, LA_CY - 66, LA_CX + 304, LA_CY - 66],    // tie beam
  [LA_CX - 284, LA_CY - 60, LA_CX - 284, LA_CY - 12],    // legs
  [LA_CX + 284, LA_CY - 60, LA_CX + 284, LA_CY - 12],
];

function LACentering({ t }) {
  let dy = 0, op = 1;
  if (t >= LA_STRIKE && t < LA_OUT + 0.2) {
    const q = laRamp(t, LA_STRIKE, LA_STRIKE_END);
    dy = 80 * laEaseIn(q); op = 1 - laSmooth(q);
  } else if (t >= LA_OUT + 0.2) {
    const q = laRamp(t, LA_OUT + 0.2, LA_OUT + 0.9);
    dy = 80 * (1 - laEase(q)); op = laSmooth(q);
  }
  if (op < 0.005) return null;
  const wedge = (x) => `M${x - 20} ${LA_CY} L${x + 20} ${LA_CY} L${x + 20} ${LA_CY - 12} L${x - 20} ${LA_CY - 6} Z`;
  return (
    <g transform={`translate(0 ${dy.toFixed(2)})`} opacity={op * 0.95}>
      {LA_TIMBERS.map((b, i) => (
        <line key={'o' + i} x1={b[0]} y1={b[1]} x2={b[2]} y2={b[3]} stroke={LA_PALETTE.ink25} strokeWidth={15} strokeLinecap="butt" />
      ))}
      {LA_TIMBERS.map((b, i) => (
        <line key={'i' + i} x1={b[0]} y1={b[1]} x2={b[2]} y2={b[3]} stroke={LA_PALETTE.timber} strokeWidth={11} strokeLinecap="butt" />
      ))}
      <path d={LA_RIB} fill={LA_PALETTE.timber} stroke={LA_PALETTE.ink25} strokeWidth={2} />
      <path d={LA_LAGGING} stroke={LA_PALETTE.ink25} strokeWidth={4} fill="none" />
      <path d={wedge(LA_CX - 284) + ' ' + wedge(LA_CX + 284)} fill={LA_PALETTE.timber} stroke={LA_PALETTE.ink25} strokeWidth={2} />
    </g>
  );
}

// ── Dashed slots: where each stone will sit ───────────────────────────────
function laGhostAlpha(s, t) {
  const land = laLand(s), o0 = laOutStart(s);
  return 1 - laRamp(t, land, land + 0.25) * (1 - laRamp(t, o0, o0 + 0.45));
}

function LAGhosts({ t }) {
  return (
    <g>
      {LA_STONES.map((s) => {
        const a = laGhostAlpha(s, t);
        if (a < 0.01) return null;
        if (!s.crown) {
          return (
            <path key={s.idx} d={s.clean} opacity={a}
              fill={LA_PALETTE.ink} fillOpacity={0.025}
              stroke={LA_PALETTE.ink25} strokeWidth={2.5} strokeDasharray="14 10" />
          );
        }
        // The crown slot is amber from frame 0 and pulses while it waits.
        const pulse = laRamp(t, 6.1, 6.5) * (1 - laRamp(t, LA_SEAL - 0.15, LA_SEAL))
          * (0.5 + 0.5 * Math.sin((t - 6.1) * Math.PI * 2.4));
        return (
          <path key={s.idx} d={s.clean} opacity={a}
            fill={LA_PALETTE.amber} fillOpacity={0.06 + 0.12 * pulse}
            stroke={LA_PALETTE.amber} strokeOpacity={0.6 + 0.4 * pulse}
            strokeWidth={2.5 + 1.5 * pulse} strokeDasharray="14 10" />
        );
      })}
    </g>
  );
}

// ── A stone: drawn twice, a soft shadow pass under all bodies, then body ──
function LAStone({ s, t, pass }) {
  const st = laStoneState(s, t);
  if (!st || st.op < 0.005) return null;
  const tf = `translate(0 ${st.dy.toFixed(2)}) rotate(${st.rot.toFixed(3)} ${s.cx.toFixed(1)} ${s.cy.toFixed(1)})`;
  if (pass === 'shadow') {
    return (
      <g transform={tf} opacity={st.op}>
        <path d={s.rough} transform="translate(6 10)" fill={LA_PALETTE.ink} opacity={0.1} />
      </g>
    );
  }
  const crown = s.crown;
  return (
    <g transform={tf} opacity={st.op}>
      <path d={s.rough}
        fill={crown ? 'url(#laAmberFill)' : 'url(#laMossFill)'}
        stroke={crown ? LA_PALETTE.amberDeep : LA_PALETTE.moss700}
        strokeWidth={2.5} strokeLinejoin="round" />
      <path d={s.inset} fill="none"
        stroke={crown ? 'rgba(15,23,19,0.22)' : 'rgba(184,205,187,0.42)'}
        strokeWidth={2} strokeLinejoin="round" />
      <text x={s.lx} y={s.ly + (crown ? 22 : 14)} textAnchor="middle"
        fontFamily={LA_FONTS.display} fontWeight={crown ? 700 : 600}
        fontSize={crown ? 62 : 50}
        fill={crown ? LA_PALETTE.ink : LA_PALETTE.cream}
        style={{ letterSpacing: crown ? '0.06em' : '-0.01em' }}>
        {s.label}
      </text>
    </g>
  );
}

// ── Seal effects ──────────────────────────────────────────────────────────
// Each joint lights up in turn, crown outward to the ground: the load path.
const LA_JOINTS = [
  { a: 105, k: 0 }, { a: 75, k: 0 },
  { a: 130, k: 1 }, { a: 50, k: 1 },
  { a: 155, k: 2 }, { a: 25, k: 2 },
  { a: 180, k: 3 }, { a: 0, k: 3 },
];

function LAJointFlash({ t }) {
  if (t < LA_SEAL || t > LA_SEAL + 1.8) return null;
  return (
    <g>
      {LA_JOINTS.map((j, i) => {
        const t0 = LA_SEAL + 0.04 + j.k * 0.11;
        if (t < t0) return null;
        const e = laEase(laRamp(t, t0, t0 + 0.08)) * Math.exp(-Math.max(0, t - t0 - 0.08) * 4);
        if (e < 0.01) return null;
        const p = laPt(LA_RIN - 4, j.a), q = laPt(LA_ROUT + 6, j.a);
        return (
          <g key={i} opacity={e}>
            <line x1={p[0]} y1={p[1]} x2={q[0]} y2={q[1]} stroke={LA_PALETTE.amberGlow} strokeWidth={20} strokeLinecap="round" />
            <line x1={p[0]} y1={p[1]} x2={q[0]} y2={q[1]} stroke={LA_PALETTE.amberSoft} strokeWidth={5} strokeLinecap="round" />
          </g>
        );
      })}
    </g>
  );
}

function LAShock({ t }) {
  if (t < LA_SEAL) return null;
  const q = laRamp(t, LA_SEAL, LA_SEAL + 0.9);
  if (q >= 1) return null;
  return (
    <circle cx={LA_CROWN.cx} cy={LA_CROWN.cy} r={40 + 360 * laEase(q)}
      fill="none" stroke={LA_PALETTE.amber}
      strokeWidth={4 * (1 - q) + 0.5} opacity={0.55 * (1 - q)} />
  );
}

function LACrownHalo({ t }) {
  if (t < LA_SEAL) return null;
  const out = 1 - laSmooth(laRamp(t, LA_OUT, LA_OUT + 0.4));
  const burst = Math.exp(-(t - LA_SEAL) * 2.2);
  const settle = laSmooth(laRamp(t, LA_SEAL, LA_SEAL + 0.6));
  const a = laClamp((0.85 * burst + 0.3 * settle) * out);
  if (a < 0.005) return null;
  return <circle cx={LA_CROWN.cx} cy={LA_CROWN.cy} r={300} fill="url(#laHaloFill)" opacity={a} />;
}

// Dust kicked out of the joint a stone lands on.
function LADust({ t }) {
  const out = [];
  LA_STONES.forEach((s) => {
    const tau = t - laLand(s);
    if (tau < 0 || tau > 0.75) return;
    const q = tau / 0.75;
    s.seats.forEach((seat, si) => {
      const n = s.crown ? 12 : 9;
      for (let j = 0; j < n; j++) {
        const seed = s.idx * 50 + si * 20 + j;
        const ang = (laRand(seed, 5) * 2 - 1) * Math.PI;
        const sp = 70 + 110 * laRand(seed, 6);
        const x = seat[0] + Math.cos(ang) * sp * tau;
        const y = seat[1] + Math.sin(ang) * sp * tau * 0.6 + 160 * tau * tau;
        const r = (3 + 4 * laRand(seed, 7)) * (1 - 0.4 * q);
        out.push(
          <circle key={seed} cx={x.toFixed(1)} cy={y.toFixed(1)} r={r.toFixed(2)}
            fill={s.crown ? LA_PALETTE.amber : LA_PALETTE.ink}
            opacity={(s.crown ? 0.5 : 0.28) * (1 - q)} />
        );
      }
    });
  });
  return <g>{out}</g>;
}

// ── Live: the opening fills with warm light once the centering is gone ────
const LA_VOID = `M${LA_CX - LA_RIN} ${LA_CY} A${LA_RIN} ${LA_RIN} 0 0 1 ${LA_CX + LA_RIN} ${LA_CY} Z`;
const laLiveAlpha = (t) =>
  laSmooth(laRamp(t, LA_LIVE, LA_LIVE + 0.8)) * (1 - laSmooth(laRamp(t, LA_OUT, LA_OUT + 0.4)));

function LALiveGlow({ t }) {
  const a = laLiveAlpha(t);
  if (a < 0.005) return null;
  const breathe = 0.88 + 0.12 * Math.sin((t - LA_LIVE) * Math.PI * 1.2);
  return (
    <g>
      <path d={LA_VOID} fill="url(#laVoidFill)" opacity={a * breathe} />
      <ellipse cx={LA_CX} cy={LA_CY + 6} rx={430} ry={24} fill={LA_PALETTE.amber} opacity={0.14 * a} />
    </g>
  );
}

function LALiveText({ t }) {
  const a = laEase(laRamp(t, LA_LIVE + 0.3, LA_LIVE + 1.0)) * (1 - laSmooth(laRamp(t, LA_OUT, LA_OUT + 0.35)));
  if (a < 0.005) return null;
  const pulse = 0.5 + 0.5 * Math.sin((t - LA_LIVE) * Math.PI * 2);
  return (
    <g opacity={a} transform={`translate(0 ${(16 * (1 - a)).toFixed(2)})`}>
      <circle cx={822} cy={826} r={18 + 16 * pulse} fill={LA_PALETTE.amberGlow} opacity={0.25 + 0.6 * (1 - pulse)} />
      <circle cx={822} cy={826} r={16} fill={LA_PALETTE.amber} />
      <text x={866} y={870} fontFamily={LA_FONTS.serif} fontStyle="italic" fontWeight={400}
        fontSize={200} fill={LA_PALETTE.amberDeep} style={{ letterSpacing: '-0.01em' }}>
        live
      </text>
    </g>
  );
}

// ── Headline (top left): line one throughout, the rest once it stands ─────
function LAHeadline({ t }) {
  const a = laSmooth(laRamp(t, 9.6, 10.3)) * (1 - laSmooth(laRamp(t, LA_OUT, LA_OUT + 0.35)));
  const line = (y, content) => (
    <text x={88} y={y} fontFamily={LA_FONTS.display} fontWeight={600} fontSize={64}
      fill={LA_PALETTE.ink} style={{ letterSpacing: '-0.03em' }}>
      {content}
    </text>
  );
  return (
    <g>
      <text x={88} y={84} fontFamily={LA_FONTS.mono} fontWeight={500} fontSize={18}
        fill={LA_PALETTE.moss600} style={{ letterSpacing: '0.2em' }}>
        {'§ 03 · THE LAUNCH ARCH'}
      </text>
      {line(160, 'Seven stones.')}
      {a > 0.005 && (
        <g opacity={a} transform={`translate(0 ${(12 * (1 - a)).toFixed(2)})`}>
          {line(236, 'One store')}
          {line(312, [
            'that ',
            <tspan key="s" fontFamily={LA_FONTS.serif} fontStyle="italic" fontWeight={400} fill={LA_PALETTE.moss600}>stands.</tspan>,
          ])}
        </g>
      )}
    </g>
  );
}

// ── Counter (top right): stones in place, rolls like an odometer ──────────
const LA_COUNT_EVENTS = LA_STONES.map((s, i) => ({ t: laLand(s), v: i + 1 }))
  .concat([{ t: LA_OUT + 0.45, v: 0 }]);

function laCountAt(t) {
  let v = 0, prev = 0, at = -100;
  for (let i = 0; i < LA_COUNT_EVENTS.length; i++) {
    const e = LA_COUNT_EVENTS[i];
    if (t >= e.t) { prev = v; v = e.v; at = e.t; }
  }
  return { v, prev, since: t - at };
}

function LACounter({ t }) {
  const { v, prev, since } = laCountAt(t);
  const rolling = since < 0.35;
  const k = laEase(laClamp(since / 0.35));
  const X = 1716, Y = 236;
  const num = (n, y, op, key) => (
    <text key={key} x={X} y={y} textAnchor="end" opacity={op}
      fontFamily={LA_FONTS.serif} fontStyle="italic" fontWeight={400} fontSize={170}
      fill={n === 7 ? LA_PALETTE.amber : LA_PALETTE.moss600}>
      {String(n)}
    </text>
  );
  return (
    <g>
      <text x={1832} y={84} textAnchor="end" fontFamily={LA_FONTS.mono} fontWeight={500} fontSize={18}
        fill={LA_PALETTE.ink40} style={{ letterSpacing: '0.2em' }}>
        STONES IN PLACE
      </text>
      <g clipPath="url(#laCountClip)">
        {rolling && num(prev, Y - 60 * k, 1 - k, 'prev')}
        {num(v, rolling ? Y + 60 * (1 - k) : Y, rolling ? k : 1, 'cur')}
      </g>
      <text x={1832} y={Y} textAnchor="end" fontFamily={LA_FONTS.display} fontWeight={500} fontSize={52}
        fill={LA_PALETTE.ink55}>
        of 7
      </text>
    </g>
  );
}

// ── Caption track (bottom centre) ─────────────────────────────────────────
// The first caption wraps the loop: it fades in at 13.5 and is still up at 0.
const LA_CAPTIONS = [
  { text: 'Six stones carry the build.', from: 13.5, to: 5.9, wrap: true },
  { text: 'The crown goes in last.', from: 6.35, to: 8.0 },
  { text: 'No mortar. The stones hold each other.', from: 9.9, to: LA_OUT },
];

function laCaptionAlpha(c, t) {
  const F = 0.35;
  if (c.wrap) {
    if (t >= c.from) return laSmooth(laRamp(t, c.from, c.from + F));
    return 1 - laSmooth(laRamp(t, c.to, c.to + F));
  }
  return laSmooth(laRamp(t, c.from, c.from + F)) * (1 - laSmooth(laRamp(t, c.to, c.to + F)));
}

function LACaptions({ t }) {
  return (
    <g>
      {LA_CAPTIONS.map((c, i) => {
        const a = laCaptionAlpha(c, t);
        if (a < 0.005) return null;
        return (
          <text key={i} x={LA_CX} y={1012} textAnchor="middle" opacity={a}
            transform={`translate(0 ${(8 * (1 - a)).toFixed(2)})`}
            fontFamily={LA_FONTS.serif} fontStyle="italic" fontWeight={400} fontSize={52}
            fill={LA_PALETTE.ink70}>
            {c.text}
          </text>
        );
      })}
    </g>
  );
}

function LAFolio() {
  return (
    <text x={88} y={1036} fontFamily={LA_FONTS.mono} fontWeight={500} fontSize={16}
      fill={LA_PALETTE.ink40} style={{ letterSpacing: '0.14em' }}>
      {'FIG. 01 · SEVEN STONES, ONE STORE'}
    </text>
  );
}

// ── Scene root ────────────────────────────────────────────────────────────
function LaunchArchScene() {
  const t = useTime();
  const sq = laSquash(t);
  const squash = `translate(0 ${LA_CY}) scale(1 ${(1 - sq).toFixed(5)}) translate(0 ${-LA_CY})`;
  return (
    <>
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse at 50% 45%, ${LA_PALETTE.creamLt} 0%, ${LA_PALETTE.cream} 55%, ${LA_PALETTE.creamDk} 100%)`,
      }} />
      <svg width="1920" height="1080" viewBox="0 0 1920 1080"
        style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
        <LADefs />
        <LAGround />
        <LALiveGlow t={t} />
        <LACrownHalo t={t} />
        <LAShock t={t} />
        <LACentering t={t} />
        <g transform={squash}>
          <LAGhosts t={t} />
          {LA_STONES.map((s) => <LAStone key={'s' + s.idx} s={s} t={t} pass="shadow" />)}
          {LA_STONES.map((s) => <LAStone key={'b' + s.idx} s={s} t={t} pass="body" />)}
          <LAJointFlash t={t} />
        </g>
        <LADust t={t} />
        <LALiveText t={t} />
        <LAHeadline t={t} />
        <LACounter t={t} />
        <LACaptions t={t} />
        <LAFolio />
      </svg>
      <LAFilmGrain />
    </>
  );
}

Object.assign(window, {
  LaunchArchScene,
  LA_PALETTE,
  LA_FONTS,
  LA_HOLD,
});
