// checkout-deprecation-clock.jsx
// "§ 03 · the deprecation clock", 14s loop on a 1920x1080 stage.
//
// A tear-off calendar pad. The top sheet is the old checkout.liquid
// template. Its days are crossed off faster and faster while the clock on
// the binding runs down to twelve, it is stamped DEPRECATED, then it tears
// along the perforation and drops out of frame. Printed on the sheet
// underneath are the four checkout extensibility surfaces, Purchase,
// Thank You, Order Status and Customer Account, which light up in turn.
// At the end a fresh old sheet settles back onto the pad, so the last
// frame hands straight back to the first.
//
// The only year shown, 2024, is the one the embedding page states.
//
// Timing map (seconds)
//   0.0 to 1.0    old sheet at rest, identical to the final frame
//   1.0 to 4.5    days crossed off, accelerating, binding clock runs down
//   4.7 to 5.0    DEPRECATED stamp slams down, the pad jolts
//   5.6 to 6.6    sheet peels from the left, pivoting on its top right corner
//   6.6 to 8.0    sheet lets go and falls out of frame
//   6.9 to 8.95   the four surfaces light up in turn
//   8.95 to 12.8  hold, one sheen passes over the tiles (reduced motion holds 12.0)
//   12.8 to 13.9  tiles dim, a fresh old sheet settles back onto the pad
//
// Note for the embed shell: killPlaybackChrome hides any wide absolutely
// positioned element near the bottom that contains an svg. The falling
// sheet passes through that zone, so it is built from divs only. The scan
// also runs once on the first commit, while Stage is still at scale(1), and
// at that size the lower row of tiles sits in the zone on any iframe under
// 520px tall. So the tiles are position relative inside one absolute grid
// whose top edge is high on the sheet, and no absolutely positioned element
// in the lower half has an svg inside it.

const CD_PALETTE = {
  cream:      '#f5f0e8',
  creamDk:    '#ebe4d6',
  paper:      '#fbf8f1',
  oldPaper:   '#eee3ca',
  oldPaperDk: '#e5d7b9',
  edgeA:      '#ece4d2',
  edgeB:      '#e0d4ba',
  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)',
  ink12:      'rgba(15,23,19,0.12)',
  ink06:      'rgba(15,23,19,0.06)',
  moss800:    '#27432f',
  moss700:    '#32553f',
  moss600:    '#3f6b54',
  moss500:    '#4d7e65',
  moss400:    '#6fa37a',
  moss300:    '#93b89a',
  moss200:    '#b8cdbb',
  moss100:    '#d7e1d4',
  amber:      '#cd8a4b',
};

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

// ─── Small helpers (prefixed, these are globals shared across scripts) ──
const cdClamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
const cdSpan = (t, a, b) => cdClamp((t - a) / (b - a));
const cdSmooth = (t) => { const x = cdClamp(t); return x * x * (3 - 2 * x); };
const cdEaseIn = (t) => { const x = cdClamp(t); return x * x * x; };
const cdMix = (a, b, t) => a + (b - a) * t;
function cdRand(i, seed) {
  const x = Math.sin(i * 12.9898 + seed * 78.233) * 43758.5453;
  return x - Math.floor(x);
}

// ─── Timing ─────────────────────────────────────────────────────────────
const CD_DUR = 14;
const CD_CROSS_A = 1.0, CD_CROSS_B = 4.5;
const CD_STAMP_A = 4.7, CD_STAMP_HIT = 5.0;
const CD_PEEL_A = 5.6, CD_DROP_A = 6.6, CD_GONE = 8.0;
const CD_MARKS_CLEAR = 8.5;  // crosses and stamp are wiped once the sheet is gone
const CD_LIGHT_A = 6.9, CD_LIGHT_STEP = 0.45, CD_LIGHT_LEN = 0.7;
const CD_SHEEN_A = 10.0, CD_SHEEN_B = 11.4;
const CD_RESET_A = 12.8, CD_RESET_B = 13.9;

// ─── Geometry (stage px) ────────────────────────────────────────────────
const CD_PAD_X = 310;
const CD_PAD_Y = 96;
const CD_PAD_W = 1300;
const CD_BIND_H = 72;
const CD_SHEET_TOP = CD_PAD_Y + CD_BIND_H;   // 168, top of the sheets
const CD_SHEET_H = 688;                      // sheets run to y 856
const CD_PERF_Y = 15;                        // perforation line, sheet coords
const CD_STUB_TUCK = 10;                     // stub tucks under the binding

// Old sheet calendar grid (sheet coords)
const CD_DAYS = 28;
const CD_CELL_W = 150, CD_CELL_H = 78, CD_CELL_GAP = 12;
const CD_GRID_X = (CD_PAD_W - (7 * CD_CELL_W + 6 * CD_CELL_GAP)) / 2;  // 89
const CD_GRID_Y = 290;
const CD_GRID_W = 7 * CD_CELL_W + 6 * CD_CELL_GAP;                     // 1122
const CD_WEEKDAYS = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];

// New sheet surface tiles (sheet coords)
const CD_TILE_W = 582, CD_TILE_H = 262, CD_TILE_GAP = 24;
const CD_TILE_X0 = 56, CD_TILE_Y0 = 112;

const CD_SURFACES = [
  { num: '01', name: 'Purchase',         glyph: 'purchase' },
  { num: '02', name: 'Thank You',        glyph: 'thanks' },
  { num: '03', name: 'Order Status',     glyph: 'status' },
  { num: '04', name: 'Customer Account', glyph: 'account' },
];

// ─── Torn edge ──────────────────────────────────────────────────────────
// One ragged line shared by the falling sheet (its top edge) and the stub
// left under the binding (its bottom edge), so the two halves match.
const CD_JAG = (function () {
  const pts = [];
  const step = 20;
  const n = Math.ceil(CD_PAD_W / step);
  for (let i = 0; i <= n; i++) {
    const x = Math.min(CD_PAD_W, i * step);
    const base = i % 2 === 0 ? 6 : 15;
    pts.push([x, base + Math.round(cdRand(i, 3) * 9)]);
  }
  return pts;
})();

const CD_BODY_CLIP = 'polygon(' +
  CD_JAG.map((p) => p[0] + 'px ' + p[1] + 'px').join(', ') +
  ', ' + CD_PAD_W + 'px ' + CD_SHEET_H + 'px, 0px ' + CD_SHEET_H + 'px)';

const CD_STUB_CLIP = 'polygon(0px 0px, ' + CD_PAD_W + 'px 0px, ' +
  CD_JAG.slice().reverse().map((p) => p[0] + 'px ' + (p[1] + CD_STUB_TUCK) + 'px').join(', ') +
  ')';

// ─── Old sheet motion ───────────────────────────────────────────────────
// Peel: the left end drops while the sheet pivots on its top right corner.
// Fall: the right end lets go and the sheet drops with gravity. Rotation
// speed and translation are continuous across the hand-off at CD_DROP_A.
function cdSheetState(t) {
  if (t < CD_PEEL_A) return { show: true, opacity: 1, tx: 0, ty: 0, rot: 0, lift: 0 };
  if (t < CD_DROP_A) {
    const k = cdSpan(t, CD_PEEL_A, CD_DROP_A);
    return { show: true, opacity: 1, tx: 0, ty: 0, rot: -6 * k * k, lift: k };
  }
  if (t < CD_GONE) {
    const s = t - CD_DROP_A;
    return {
      show: true, opacity: 1,
      tx: -110 * s * s,
      ty: 600 * s * s,
      rot: -6 - 12 * s - 2 * s * s,
      lift: 1,
    };
  }
  if (t < CD_RESET_A) return { show: false, opacity: 0, tx: 0, ty: 0, rot: 0, lift: 0 };
  if (t < CD_RESET_B) {
    const k = cdSmooth(cdSpan(t, CD_RESET_A, CD_RESET_B));
    return { show: true, opacity: k, tx: 0, ty: -32 * (1 - k), rot: 0, lift: 0 };
  }
  return { show: true, opacity: 1, tx: 0, ty: 0, rot: 0, lift: 0 };
}

// Days are crossed off slowly at first, then faster: the clock running out.
function cdCrossTime(i) {
  return CD_CROSS_A + (CD_CROSS_B - CD_CROSS_A) * Math.pow(i / (CD_DAYS - 1), 0.62);
}

// The stamp lands at CD_STAMP_HIT and the whole pad takes the knock.
function cdJolt(t) {
  if (t < CD_STAMP_HIT || t > CD_STAMP_HIT + 0.6) return 0;
  const s = t - CD_STAMP_HIT;
  return 9 * Math.exp(-9 * s) * Math.sin(s * 42);
}

// ─── Film grain + vignette ──────────────────────────────────────────────
function CDFilmGrain() {
  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',
    }} />
  );
}

function CDVignette() {
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none',
      backgroundImage: 'radial-gradient(ellipse at center, rgba(0,0,0,0) 58%, rgba(40,30,15,0.10) 100%)',
    }} />
  );
}

// ─── Corner chrome ──────────────────────────────────────────────────────
function CDCornerChrome() {
  const t = useTime();
  const pulse = 0.5 + 0.5 * Math.sin((t / CD_DUR) * Math.PI * 2 * 14);
  const label = {
    fontFamily: CD_FONTS.mono,
    fontSize: 22,
    letterSpacing: '0.16em',
    textTransform: 'uppercase',
    color: CD_PALETTE.ink40,
    whiteSpace: 'nowrap',
  };
  return (
    <>
      <div style={{ position: 'absolute', left: 64, top: 40, display: 'flex', alignItems: 'center', gap: 14, ...label }}>
        <div style={{
          width: 10, height: 10, borderRadius: 5,
          backgroundColor: CD_PALETTE.moss500,
          opacity: 0.4 + 0.6 * pulse,
        }} />
        <span>§ 03 · checkout extensibility</span>
      </div>
      <div style={{ position: 'absolute', right: 64, top: 40, ...label }}>
        vol. 01 · shopify plus
      </div>
      <div style={{ position: 'absolute', left: 64, bottom: 40, ...label }}>
        fig. 01 · the deprecation clock
      </div>
    </>
  );
}

// ─── Pad base: soft floor shadow and the sheets stacked below ───────────
function CDPadBase() {
  return (
    <>
      <div style={{
        position: 'absolute',
        left: CD_PAD_X - 140, top: CD_PAD_Y + 30,
        width: CD_PAD_W + 280, height: CD_BIND_H + CD_SHEET_H + 120,
        backgroundImage: 'radial-gradient(ellipse at 50% 55%, rgba(15,23,19,0.16) 0%, rgba(15,23,19,0.06) 46%, rgba(15,23,19,0) 70%)',
        pointerEvents: 'none',
      }} />
      <div style={{
        position: 'absolute',
        left: CD_PAD_X + 14, top: CD_SHEET_TOP + 12,
        width: CD_PAD_W - 28, height: CD_SHEET_H,
        backgroundColor: CD_PALETTE.edgeB,
        borderRadius: '0 0 6px 6px',
      }} />
      <div style={{
        position: 'absolute',
        left: CD_PAD_X + 6, top: CD_SHEET_TOP + 6,
        width: CD_PAD_W - 12, height: CD_SHEET_H,
        backgroundColor: CD_PALETTE.edgeA,
        borderRadius: '0 0 4px 4px',
        borderBottom: `1px solid ${CD_PALETTE.ink12}`,
      }} />
    </>
  );
}

// ─── New sheet: the four surfaces printed underneath ────────────────────
const CD_GLYPHS = {
  purchase: {
    strokes: [
      'M16 6 H154 A10 10 0 0 1 164 16 V104 A10 10 0 0 1 154 114 H16 A10 10 0 0 1 6 104 V16 A10 10 0 0 1 16 6 Z',
      'M26 30 H144',
      'M26 52 H112',
    ],
    fills: [
      'M32 72 H138 A8 8 0 0 1 146 80 V90 A8 8 0 0 1 138 98 H32 A8 8 0 0 1 24 90 V80 A8 8 0 0 1 32 72 Z',
    ],
  },
  thanks: {
    strokes: [
      'M51 48 A34 34 0 1 1 119 48 A34 34 0 1 1 51 48 Z',
      'M69 49 L81 61 L102 37',
      'M40 108 H130',
    ],
    fills: [],
  },
  status: {
    strokes: [
      'M31 44 H74 M96 44 H139',
      'M139 44 A11 11 0 1 1 161 44 A11 11 0 1 1 139 44 Z',
      'M20 84 H118',
      'M20 106 H84',
    ],
    fills: [
      'M9 44 A11 11 0 1 1 31 44 A11 11 0 1 1 9 44 Z',
      'M74 44 A11 11 0 1 1 96 44 A11 11 0 1 1 74 44 Z',
    ],
  },
  account: {
    strokes: [
      'M24 38 A18 18 0 1 1 60 38 A18 18 0 1 1 24 38 Z',
      'M12 106 C12 72 72 72 72 106',
      'M94 34 H160',
      'M94 60 H144',
      'M94 86 H160',
    ],
    fills: [],
  },
};

function CDGlyph({ kind, light }) {
  const g = CD_GLYPHS[kind];
  const n = g.strokes.length;
  const lag = 0.3;
  return (
    <svg
      width="170" height="120" viewBox="0 0 170 120"
      style={{ position: 'absolute', right: 40, top: 32, overflow: 'visible' }}
    >
      {g.fills.map((d, j) => (
        <path key={'gf' + j} d={d} fill={CD_PALETTE.moss100} />
      ))}
      {g.strokes.map((d, j) => (
        <path key={'gs' + j} d={d} fill="none" stroke={CD_PALETTE.moss100}
          strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" />
      ))}
      {g.fills.map((d, j) => (
        <path key={'f' + j} d={d} fill={CD_PALETTE.moss500} opacity={light} />
      ))}
      {g.strokes.map((d, j) => {
        const p = cdClamp(light * (1 + lag * (n - 1)) - lag * j);
        if (p <= 0.001) return null;
        return (
          <path key={'s' + j} d={d} pathLength="100" fill="none"
            stroke={CD_PALETTE.moss600} strokeWidth="4.5"
            strokeLinecap="round" strokeLinejoin="round"
            strokeDasharray="100 100" strokeDashoffset={100 * (1 - p)} />
        );
      })}
    </svg>
  );
}

function CDSurfaceTile({ surface, index, t }) {
  const col = index % 2;
  const x = CD_TILE_X0 + col * (CD_TILE_W + CD_TILE_GAP);

  const a = CD_LIGHT_A + index * CD_LIGHT_STEP;
  const on = cdSmooth(cdSpan(t, a, a + CD_LIGHT_LEN));
  const off = cdSmooth(cdSpan(t, CD_RESET_A, CD_RESET_A + 0.7));
  const light = on * (1 - off);
  const pop = off > 0 ? 0 : Math.sin(Math.PI * on) * 0.022;
  const pulse = 0.55 + 0.45 * Math.sin((t * 0.9 + index * 0.25) * Math.PI * 2);

  // One moss sheen crosses all four tiles, left to right, during the hold.
  const sheenOn = t > CD_SHEEN_A && t < CD_SHEEN_B;
  const sheenX = cdMix(-460, CD_PAD_W + 460, cdSmooth(cdSpan(t, CD_SHEEN_A, CD_SHEEN_B))) - x;

  return (
    <div style={{
      position: 'relative',
      width: CD_TILE_W, height: CD_TILE_H,
      borderRadius: 12, overflow: 'hidden',
      backgroundColor: CD_PALETTE.paper,
      transform: `scale(${1 + pop})`,
      transformOrigin: 'center center',
    }}>
      {/* Lit wash */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `linear-gradient(135deg, ${CD_PALETTE.moss100} 0%, rgba(215,225,212,0) 70%)`,
        opacity: light * 0.85,
      }} />
      {/* Borders, unlit then lit */}
      <div style={{
        position: 'absolute', inset: 0, borderRadius: 12,
        border: `2px solid ${CD_PALETTE.moss200}`,
      }} />
      <div style={{
        position: 'absolute', inset: 0, borderRadius: 12,
        border: `3px solid ${CD_PALETTE.moss500}`,
        opacity: light,
      }} />

      {/* Number + live dot */}
      <div style={{
        position: 'absolute', left: 38, top: 30,
        fontFamily: CD_FONTS.mono, fontWeight: 500,
        fontSize: 36, lineHeight: 1, letterSpacing: '0.04em',
        color: CD_PALETTE.moss600,
        opacity: cdMix(0.35, 1, light),
      }}>
        {surface.num}
      </div>
      <div style={{
        position: 'absolute', left: 100, top: 31,
        width: 34, height: 34, borderRadius: 17,
        backgroundImage: 'radial-gradient(circle, rgba(111,163,122,0.55) 0%, rgba(111,163,122,0) 70%)',
        opacity: light * pulse,
      }} />
      <div style={{
        position: 'absolute', left: 110, top: 41,
        width: 14, height: 14, borderRadius: 7,
        backgroundColor: CD_PALETTE.moss500,
        opacity: light * (0.6 + 0.4 * pulse),
      }} />

      <CDGlyph kind={surface.glyph} light={light} />

      {/* Surface name */}
      <div style={{
        position: 'absolute', left: 36, bottom: 32,
        fontFamily: CD_FONTS.display, fontWeight: 600,
        fontSize: 58, lineHeight: 1, letterSpacing: '-0.025em',
        color: CD_PALETTE.ink,
        opacity: cdMix(0.38, 1, light),
        whiteSpace: 'nowrap',
      }}>
        {surface.name}
      </div>

      {sheenOn && (
        <div style={{
          position: 'absolute', top: -40, left: sheenX,
          width: 220, height: CD_TILE_H + 80,
          backgroundImage: 'linear-gradient(90deg, rgba(111,163,122,0) 0%, rgba(111,163,122,0.20) 50%, rgba(111,163,122,0) 100%)',
          transform: 'skewX(-18deg)',
          pointerEvents: 'none',
        }} />
      )}
    </div>
  );
}

function CDNewSheet() {
  const t = useTime();
  const eyebrow = {
    position: 'absolute', top: 54,
    fontFamily: CD_FONTS.mono, fontWeight: 500,
    fontSize: 44, lineHeight: 1, letterSpacing: '0.14em',
    textTransform: 'uppercase',
    whiteSpace: 'nowrap',
  };
  return (
    <div style={{
      position: 'absolute', left: CD_PAD_X, top: CD_SHEET_TOP,
      width: CD_PAD_W, height: CD_SHEET_H,
      backgroundColor: CD_PALETTE.paper,
      backgroundImage: `radial-gradient(${CD_PALETTE.ink06} 1.6px, rgba(15,23,19,0) 2.2px)`,
      backgroundSize: '28px 28px',
      overflow: 'hidden',
    }}>
      <div style={{ ...eyebrow, left: CD_TILE_X0, color: CD_PALETTE.moss600 }}>
        checkout extensibility
      </div>
      <div style={{ ...eyebrow, right: CD_TILE_X0, color: CD_PALETTE.ink40 }}>
        4 surfaces
      </div>
      {/* Same 2x2 layout as before, but the tiles are in flow inside one
          absolute grid at y 112, so the shell's chrome scan never hides
          the lower row (see the note at the top of this file). */}
      <div style={{
        position: 'absolute', left: CD_TILE_X0, top: CD_TILE_Y0,
        display: 'grid',
        gridTemplateColumns: `${CD_TILE_W}px ${CD_TILE_W}px`,
        gridAutoRows: `${CD_TILE_H}px`,
        gap: CD_TILE_GAP,
      }}>
        {CD_SURFACES.map((s, i) => (
          <CDSurfaceTile key={s.num} surface={s} index={i} t={t} />
        ))}
      </div>
    </div>
  );
}

// ─── Stub: the ragged strip of old paper left under the binding ─────────
function CDStub() {
  const box = {
    position: 'absolute',
    left: CD_PAD_X, top: CD_SHEET_TOP - CD_STUB_TUCK,
    width: CD_PAD_W, height: CD_STUB_TUCK + 30,
    clipPath: CD_STUB_CLIP, WebkitClipPath: CD_STUB_CLIP,
  };
  return (
    <>
      {/* a hairline of shade under the torn edge */}
      <div style={{ ...box, top: box.top + 3, backgroundColor: 'rgba(15,23,19,0.13)' }} />
      <div style={{ ...box, backgroundColor: CD_PALETTE.oldPaper }} />
    </>
  );
}

// ─── Old sheet: checkout.liquid calendar page ───────────────────────────
function CDCrossBar({ x1, y1, x2, y2, k }) {
  if (k <= 0.001) return null;
  const dx = x2 - x1, dy = y2 - y1;
  const len = Math.sqrt(dx * dx + dy * dy);
  const ang = (Math.atan2(dy, dx) * 180) / Math.PI;
  return (
    <div style={{
      position: 'absolute', left: x1, top: y1 - 3.5,
      width: Math.max(7, len * k), height: 7, borderRadius: 4,
      backgroundColor: CD_PALETTE.ink70,
      transform: `rotate(${ang}deg)`,
      transformOrigin: '3.5px 3.5px',
    }} />
  );
}

function CDDayGrid() {
  const t = useTime();
  const live = t < CD_MARKS_CLEAR;
  const cells = [];
  for (let i = 0; i < CD_DAYS; i++) {
    const c = i % 7;
    const r = Math.floor(i / 7);
    const x = CD_GRID_X + c * (CD_CELL_W + CD_CELL_GAP);
    const y = CD_GRID_Y + r * (CD_CELL_H + CD_CELL_GAP);
    const ct = cdCrossTime(i);
    const k1 = live ? cdSpan(t, ct, ct + 0.09) : 0;
    const k2 = live ? cdSpan(t, ct + 0.06, ct + 0.16) : 0;
    const j = (s) => (cdRand(i, s) - 0.5) * 10;
    cells.push(
      <div key={i} style={{
        position: 'absolute', left: x, top: y,
        width: CD_CELL_W, height: CD_CELL_H,
        borderRadius: 6,
        border: `2px solid ${CD_PALETTE.ink12}`,
        backgroundColor: `rgba(15,23,19,${0.025 + 0.05 * k1})`,
        boxSizing: 'border-box',
      }}>
        <div style={{
          position: 'absolute', left: 12, top: 8,
          fontFamily: CD_FONTS.mono, fontWeight: 500,
          fontSize: 26, lineHeight: 1,
          color: CD_PALETTE.ink40,
        }}>
          {i + 1}
        </div>
        <CDCrossBar x1={28 + j(1)} y1={16 + j(2)} x2={124 + j(3)} y2={60 + j(4)} k={k1} />
        <CDCrossBar x1={124 + j(5)} y1={16 + j(6)} x2={28 + j(7)} y2={60 + j(8)} k={k2} />
      </div>
    );
  }
  return (
    <>
      {CD_WEEKDAYS.map((d, c) => (
        <div key={'wd' + c} style={{
          position: 'absolute',
          left: CD_GRID_X + c * (CD_CELL_W + CD_CELL_GAP), top: 246,
          width: CD_CELL_W, textAlign: 'center',
          fontFamily: CD_FONTS.mono, fontWeight: 500,
          fontSize: 24, lineHeight: 1, letterSpacing: '0.1em',
          color: CD_PALETTE.ink40,
        }}>
          {d}
        </div>
      ))}
      {cells}
    </>
  );
}

function CDStamp() {
  const t = useTime();
  if (t < CD_STAMP_A || t >= CD_MARKS_CLEAR) return null;
  const k = cdSpan(t, CD_STAMP_A, CD_STAMP_HIT);
  const fall = cdEaseIn(k);
  const settle = t > CD_STAMP_HIT ? Math.exp(-14 * (t - CD_STAMP_HIT)) * 0.04 : 0;
  const scale = cdMix(1.9, 1, fall) * (1 - settle);
  const rot = cdMix(-15, -8, fall);
  const opacity = 0.9 * cdSmooth(cdSpan(t, CD_STAMP_A, CD_STAMP_A + 0.14));
  return (
    <div style={{
      position: 'absolute', left: CD_PAD_W / 2, top: CD_GRID_Y + 174,
      transform: `translate(-50%, -50%) rotate(${rot}deg) scale(${scale})`,
      opacity,
      mixBlendMode: 'multiply',
      pointerEvents: 'none',
    }}>
      <div style={{
        position: 'relative',
        border: `10px solid ${CD_PALETTE.amber}`,
        borderRadius: 14,
        padding: '18px 44px 12px',
      }}>
        <div style={{
          position: 'absolute', inset: 8,
          border: `3px solid ${CD_PALETTE.amber}`,
          borderRadius: 6,
          opacity: 0.8,
        }} />
        <div style={{
          fontFamily: CD_FONTS.display, fontWeight: 700,
          fontSize: 112, lineHeight: 1, letterSpacing: '0.06em',
          color: CD_PALETTE.amber,
          whiteSpace: 'nowrap',
        }}>
          DEPRECATED
        </div>
      </div>
    </div>
  );
}

function CDOldSheet() {
  const t = useTime();
  const s = cdSheetState(t);
  if (!s.show) return null;
  return (
    <div style={{
      position: 'absolute', left: CD_PAD_X, top: CD_SHEET_TOP,
      width: CD_PAD_W, height: CD_SHEET_H,
      clipPath: CD_BODY_CLIP, WebkitClipPath: CD_BODY_CLIP,
      backgroundImage: `linear-gradient(180deg, ${CD_PALETTE.oldPaper} 0%, ${CD_PALETTE.oldPaperDk} 100%)`,
      transform: `translate(${s.tx}px, ${s.ty}px) rotate(${s.rot}deg)`,
      transformOrigin: `${CD_PAD_W}px ${CD_PERF_Y}px`,
      opacity: s.opacity,
      willChange: 'transform, opacity',
    }}>
      {/* Header */}
      <div style={{
        position: 'absolute', left: CD_GRID_X, top: 54,
        fontFamily: CD_FONTS.mono, fontWeight: 500,
        fontSize: 30, lineHeight: 1, letterSpacing: '0.16em',
        textTransform: 'uppercase',
        color: CD_PALETTE.ink55,
        whiteSpace: 'nowrap',
      }}>
        legacy template
      </div>
      <div style={{
        position: 'absolute', left: CD_GRID_X - 3, top: 98,
        fontFamily: CD_FONTS.mono, fontWeight: 600,
        fontSize: 88, lineHeight: 1, letterSpacing: '-0.01em',
        color: CD_PALETTE.ink,
        whiteSpace: 'nowrap',
      }}>
        checkout.liquid
      </div>
      <div style={{
        position: 'absolute', right: CD_GRID_X, top: 46,
        fontFamily: CD_FONTS.serif, fontStyle: 'italic', fontWeight: 400,
        fontSize: 150, lineHeight: 1, letterSpacing: '-0.02em',
        color: CD_PALETTE.moss700,
        whiteSpace: 'nowrap',
      }}>
        2024
      </div>
      <div style={{
        position: 'absolute', left: CD_GRID_X, top: 222,
        width: CD_GRID_W, height: 2,
        backgroundColor: CD_PALETTE.ink12,
      }} />

      <CDDayGrid />
      <CDStamp />

      {/* Shade on the lifting side while it peels */}
      {s.lift > 0 && (
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `linear-gradient(100deg, rgba(15,23,19,${(0.14 * s.lift).toFixed(3)}) 0%, rgba(15,23,19,0) 55%)`,
        }} />
      )}
    </div>
  );
}

function CDOldSheetShadow() {
  const t = useTime();
  if (t < CD_PEEL_A || t >= CD_GONE) return null;
  const s = cdSheetState(t);
  const fall = cdSpan(t, CD_DROP_A, CD_GONE);
  return (
    <div style={{
      position: 'absolute', left: CD_PAD_X, top: CD_SHEET_TOP + CD_PERF_Y,
      width: CD_PAD_W, height: CD_SHEET_H - CD_PERF_Y,
      backgroundColor: CD_PALETTE.ink,
      opacity: 0.18 * s.lift * (1 - 0.6 * fall),
      filter: 'blur(26px)',
      transform: `translate(${s.tx + 16 * s.lift}px, ${s.ty + 30 * s.lift + 50 * fall}px) rotate(${s.rot}deg)`,
      transformOrigin: `${CD_PAD_W}px 0px`,
      pointerEvents: 'none',
    }} />
  );
}

// Perforation holes, shown only while the old sheet is whole.
function CDPerforation() {
  const t = useTime();
  const s = cdSheetState(t);
  let op;
  if (t < CD_PEEL_A) op = 1;
  else if (t < CD_RESET_A) op = 1 - cdSpan(t, CD_PEEL_A, CD_PEEL_A + 0.18);
  else op = s.opacity;
  if (op < 0.01) return null;
  return (
    <div style={{
      position: 'absolute',
      left: CD_PAD_X, top: CD_SHEET_TOP + CD_PERF_Y - 4 + (t >= CD_RESET_A ? s.ty : 0),
      width: CD_PAD_W, height: 8,
      backgroundImage: 'radial-gradient(circle, rgba(15,23,19,0.22) 3.2px, rgba(15,23,19,0) 3.8px)',
      backgroundSize: '20px 8px',
      backgroundRepeat: 'repeat-x',
      opacity: op,
      pointerEvents: 'none',
    }} />
  );
}

// ─── Binding with the deprecation clock ─────────────────────────────────
// The minute hand makes four turns while the days are crossed off, so the
// hour hand walks from eight to twelve. It rewinds while the pad resets.
function CDBinding() {
  const t = useTime();
  const spin = Easing.easeInOutCubic(cdSpan(t, CD_CROSS_A, CD_CROSS_B));
  const rewind = cdSmooth(cdSpan(t, CD_RESET_A, CD_RESET_B));
  const minute = 1440 * spin * (1 - rewind);
  const hour = -120 + minute / 12;
  const bw = CD_PAD_W + 28;
  const cx = bw / 2;
  const cy = CD_BIND_H / 2;
  const ticks = [];
  for (let i = 0; i < 12; i++) {
    const a = (i / 12) * Math.PI * 2;
    const r1 = i % 3 === 0 ? 20 : 23;
    ticks.push(
      <line key={'tk' + i}
        x1={cx + Math.sin(a) * r1} y1={cy - Math.cos(a) * r1}
        x2={cx + Math.sin(a) * 26} y2={cy - Math.cos(a) * 26}
        stroke={CD_PALETTE.moss800} strokeWidth={i % 3 === 0 ? 3 : 1.6} strokeLinecap="round" />
    );
  }
  const ring = (x) => (
    <g key={'ring' + x}>
      <circle cx={x} cy={cy} r="15" fill={CD_PALETTE.creamDk} />
      <circle cx={x} cy={cy + 2} r="11" fill="rgba(15,23,19,0.22)" />
      <circle cx={x} cy={cy} r="15" fill="none" stroke={CD_PALETTE.moss800} strokeWidth="3" />
    </g>
  );
  return (
    <div style={{
      position: 'absolute', left: CD_PAD_X - 14, top: CD_PAD_Y,
      width: bw, height: CD_BIND_H,
      borderRadius: '16px 16px 6px 6px',
      backgroundImage: `linear-gradient(180deg, ${CD_PALETTE.moss600} 0%, ${CD_PALETTE.moss700} 55%, ${CD_PALETTE.moss800} 100%)`,
    }}>
      <div style={{
        position: 'absolute', left: 22, right: 22, top: 7, height: 2,
        borderRadius: 1, backgroundColor: 'rgba(255,255,255,0.14)',
      }} />
      <svg width={bw} height={CD_BIND_H} viewBox={`0 0 ${bw} ${CD_BIND_H}`}
        style={{ position: 'absolute', left: 0, top: 0 }}>
        {ring(bw * 0.18)}
        {ring(bw * 0.82)}
        <circle cx={cx} cy={cy} r="30" fill={CD_PALETTE.cream} stroke={CD_PALETTE.moss800} strokeWidth="3" />
        {ticks}
        <line x1={cx} y1={cy} x2={cx} y2={cy - 14}
          transform={`rotate(${hour} ${cx} ${cy})`}
          stroke={CD_PALETTE.ink} strokeWidth="5" strokeLinecap="round" />
        <line x1={cx} y1={cy} x2={cx} y2={cy - 22}
          transform={`rotate(${minute} ${cx} ${cy})`}
          stroke={CD_PALETTE.ink} strokeWidth="3.2" strokeLinecap="round" />
        <circle cx={cx} cy={cy} r="3.6" fill={CD_PALETTE.moss800} />
      </svg>
    </div>
  );
}

// ─── Captions ───────────────────────────────────────────────────────────
// The first caption is fully up at t=0 and again at t=14, so the seam is
// invisible.
const CD_CAPTIONS = [
  {
    lead: 'The clock', key: 'runs out.',
    op: (t) => (t < 5.0 ? 1
      : t < 5.45 ? 1 - cdSmooth(cdSpan(t, 5.0, 5.45))
      : cdSmooth(cdSpan(t, 13.3, 13.9))),
  },
  {
    lead: 'Old surface', key: 'out.',
    op: (t) => cdSmooth(cdSpan(t, 5.6, 6.0)) * (1 - cdSmooth(cdSpan(t, 8.2, 8.6))),
  },
  {
    lead: 'Four new surfaces', key: 'in.',
    op: (t) => cdSmooth(cdSpan(t, 8.7, 9.1)) * (1 - cdSmooth(cdSpan(t, 12.7, 13.1))),
  },
];

function CDCaptions() {
  const t = useTime();
  return (
    <>
      {CD_CAPTIONS.map((c, i) => {
        const op = c.op(t);
        if (op < 0.01) return null;
        return (
          <div key={'cap' + i} style={{
            position: 'absolute', left: 0, right: 0, top: 900,
            textAlign: 'center', lineHeight: 1,
            whiteSpace: 'nowrap',
            opacity: op,
            transform: `translateY(${(1 - op) * 14}px)`,
            pointerEvents: 'none',
          }}>
            <span style={{
              fontFamily: CD_FONTS.display, fontWeight: 600,
              fontSize: 68, letterSpacing: '-0.03em',
              color: CD_PALETTE.ink,
            }}>
              {c.lead}{' '}
            </span>
            <span style={{
              fontFamily: CD_FONTS.serif, fontStyle: 'italic', fontWeight: 400,
              fontSize: 80, letterSpacing: '-0.01em',
              color: CD_PALETTE.moss600,
            }}>
              {c.key}
            </span>
          </div>
        );
      })}
    </>
  );
}

// ─── Main scene ─────────────────────────────────────────────────────────
function DeprecationClockScene() {
  const t = useTime();
  const jolt = cdJolt(t);
  return (
    <>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `radial-gradient(ellipse at 50% 42%, ${CD_PALETTE.cream} 0%, ${CD_PALETTE.creamDk} 100%)`,
      }} />

      <div style={{
        position: 'absolute', left: 0, top: 0, width: 1920, height: 1080,
        transform: `translateY(${jolt.toFixed(2)}px)`,
      }}>
        <CDPadBase />
        <CDNewSheet />
        <CDStub />
        <CDOldSheetShadow />
        <CDOldSheet />
        <CDPerforation />
        <CDBinding />
      </div>

      <CDCaptions />
      <CDCornerChrome />
      <CDVignette />
      <CDFilmGrain />
    </>
  );
}

Object.assign(window, {
  DeprecationClockScene,
  CD_PALETTE,
  CD_FONTS,
});
