// thirty-day-ledger.jsx · "§ 03 · the thirty day ledger" 18s loop
// A Shopify care plan month at a glance, idealised (no dates, no client
// names, no metrics). A horizontal ledger scrolls day by day under a fixed
// "today" cursor: moss dots stack below each day as uptime pings, every
// seventh day blooms a concentric ring labelled apps, two days carry a
// security patch tick, day 17 raises the single amber incident and day 18
// clears it, and day 30 closes on a taller tick labelled report delivered.
// The strip then collapses so the whole month sits on one line, holds, and
// fades back to the empty page the loop opens on.
//
// Timeline (seconds)
//   0.0  to  1.3   page, rule, header and counter fade in, the line draws
//   1.0  to 11.0   the ledger scrolls; it slows around days 17 and 18 so the
//                  incident and its clearing each get about a second
//  11.0  to 12.2   short hold on the report delivered tick
//  12.2  to 13.9   the strip collapses until all 30 days fit on one line
//  13.9  to 16.7   settled month held (15.6 is the reduced motion frame)
//  16.7  to 17.6   everything fades; 17.6 to 18.0 is the empty opening frame

const T_PALETTE = {
  cream:    '#f5f0e8',
  creamDk:  '#ebe4d6',
  creamLt:  '#faf6ed',
  ink:      '#0f1713',
  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)',
  moss700:  '#32553f',
  moss600:  '#3f6b54',
  moss500:  '#4d7e65',
  moss400:  '#6fa37a',
  moss300:  '#93b89a',
  moss200:  '#b8cdbb',
  amber:    '#cd8a4b',
  amberSoft:'#e2a568',
  amberInk: '#a8642a', // the same amber, darkened only so the word reads on cream
};
const T_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 tClamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
const tLerp = (a, b, t) => a + (b - a) * t;
const tWin = (t, a, b) => tClamp((t - a) / (b - a));
const tSmooth = (t) => { const x = tClamp(t); return x * x * (3 - 2 * x); };
const tOut = (t) => { const x = tClamp(t); return 1 - Math.pow(1 - x, 3); };
const tInOut = (t) => {
  const x = tClamp(t);
  return x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;
};
// Gentle overshoot for pops; returns 0 at 0 and settles on 1.
const tBack = (t) => {
  const x = tClamp(t);
  const c1 = 1.4, c3 = c1 + 1;
  return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2);
};
const tPad2 = (n) => (n < 10 ? '0' + n : '' + n);

// ── Timeline ───────────────────────────────────────────────────────────
const T_DAYS = 30;
const T_SCROLL_START = 0.9;
const T_SCROLL_END = 11.0;
const T_RAMP = 0.7;        // seconds of ease in and ease out on the scroll
const T_P0 = -0.6;         // cursor position, in days (0 = day 1), at scroll start
const T_P1 = 29.5;         // cursor position at scroll end
const T_SLOW_AT = 16.5;    // slow down centred between day 17 and day 18
const T_SLOW_HALF = 1.6;   // half width of the slow zone, seconds
const T_SLOW_DEPTH = 0.8;  // speed falls to 20 percent at its centre
const T_COLLAPSE_A = 12.2;
const T_COLLAPSE_B = 13.9;
const T_HOLD = 15.6;       // settled frame; HOLD_MS and Stage reducedTime match it
const T_FADE_A = 16.7;
const T_FADE_B = 17.6;

// Travel speed, in days per second, chosen so the cursor lands exactly on
// T_P1 after the ramps and the slow zone have taken their share.
const T_BASE = (T_P1 - T_P0) /
  ((T_SCROLL_END - T_SCROLL_START) - T_SLOW_DEPTH * T_SLOW_HALF - T_RAMP);
// Centre time of the slow zone, solved so the cursor is at T_SLOW_AT there.
const T_SLOW_C = T_SCROLL_START + (T_SLOW_AT - T_P0) / T_BASE +
  T_SLOW_DEPTH * T_SLOW_HALF / 2 + T_RAMP / 2;

// Seconds of travel lost, up to time t, to the start ramp, the end ramp and
// the slow zone. Each is a raised cosine, so all three integrate in closed
// form and the scroll speed never jumps.
function tLost(t) {
  let lost = 0;
  const a = tClamp(t - T_SCROLL_START, 0, T_RAMP);
  lost += 0.5 * a + (T_RAMP / (2 * Math.PI)) * Math.sin(Math.PI * a / T_RAMP);
  const e = tClamp(t - (T_SCROLL_END - T_RAMP), 0, T_RAMP);
  lost += 0.5 * e - (T_RAMP / (2 * Math.PI)) * Math.sin(Math.PI * e / T_RAMP);
  const s = tClamp(t - T_SLOW_C, -T_SLOW_HALF, T_SLOW_HALF);
  lost += T_SLOW_DEPTH * (0.5 * (s + T_SLOW_HALF) +
    (T_SLOW_HALF / (2 * Math.PI)) * Math.sin(Math.PI * s / T_SLOW_HALF));
  return lost;
}
// Cursor position in days at time t. Monotonic, so each day has one reach time.
function tCursor(t) {
  const tt = tClamp(t, T_SCROLL_START, T_SCROLL_END);
  return T_P0 + T_BASE * ((tt - T_SCROLL_START) - tLost(tt));
}
// The second at which the cursor reaches each day, found by bisection once.
const T_REACH = (function () {
  const out = [];
  for (let i = 0; i < T_DAYS; i++) {
    let lo = T_SCROLL_START, hi = T_SCROLL_END;
    for (let n = 0; n < 48; n++) {
      const mid = (lo + hi) / 2;
      if (tCursor(mid) < i) lo = mid; else hi = mid;
    }
    out.push(hi);
  }
  return out;
})();

// ── Events (zero based day index) ──────────────────────────────────────
const T_APPS = [6, 13, 20, 27];   // days 7, 14, 21, 28
const T_PATCH = [9, 23];          // days 10 and 24
const T_INCIDENT = 16;            // day 17
const T_CLEARED = 17;             // day 18
const T_REPORT = 29;              // day 30
const T_MISSED_DAY = 16;          // the incident day shows one hollow ping
const T_MISSED_DOT = 2;
const T_KEY_DAYS = [0, 6, 13, 20, 27, 29]; // day numbers kept once collapsed

// ── Layout (stage units, 1920 x 1080) ──────────────────────────────────
const T_W = 1920;
const T_H = 1080;
const T_LINE_Y = 590;
const T_CURSOR_X = 1240;
const T_GAP = 130;                         // day spacing while scrolling
const T_FULL_L = 160;
const T_FULL_R = 1760;
const T_FULL_GAP = (T_FULL_R - T_FULL_L) / (T_DAYS - 1);
const T_TIER_A = T_LINE_Y - 140;           // apps and patch labels
const T_TIER_B = T_LINE_Y - 270;           // incident and cleared labels
const T_REPORT_H = 250;                    // the taller closing tick
const T_REPORT_LABEL_Y = T_LINE_Y - 246;
const T_RING_R = [20, 36, 52];
const T_CAPTION_Y = 948;

function tDayX(i, P, k) {
  return tLerp(T_CURSOR_X + (i - P) * T_GAP, T_FULL_L + i * T_FULL_GAP, k);
}
function tCursorX(P, k) {
  return tLerp(T_CURSOR_X, T_FULL_L + P * T_FULL_GAP, k);
}
// Soft fade near the left and right stage edges for anything that scrolls.
function tEdge(x) {
  return tSmooth(x / 110) * tSmooth((T_W - x) / 110);
}
function tGlobal(t) {
  return 1 - tSmooth(tWin(t, T_FADE_A, T_FADE_B));
}
function tCheck(cx, cy, s) {
  return 'M ' + (cx - 0.95 * s) + ' ' + (cy + 0.05 * s) +
    ' L ' + (cx - 0.3 * s) + ' ' + (cy + 0.7 * s) +
    ' L ' + (cx + 1.0 * s) + ' ' + (cy - 0.65 * s);
}

// ── Backdrop and grain ─────────────────────────────────────────────────
function TBackdrop() {
  return (
    <div style={{
      position: 'absolute', left: 0, top: 0, width: T_W, height: T_H,
      background: `radial-gradient(ellipse at 50% 45%, ${T_PALETTE.creamLt} 0%, ${T_PALETTE.cream} 55%, ${T_PALETTE.creamDk} 100%)`,
    }}/>
  );
}

function TFilmGrain({ opacity = 0.06 }) {
  return (
    <div style={{
      position: 'absolute', left: 0, top: 0, width: T_W, height: T_H,
      pointerEvents: 'none', mixBlendMode: 'multiply', opacity,
      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='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.06  0 0 0 0 0.06  0 0 0 0 0.06  0 0 0 0.55 0'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>")`,
      backgroundSize: '220px 220px',
    }}/>
  );
}

// ── Event marks drawn on the line (SVG) ────────────────────────────────
function tEventMarks(i, x, since, time, sc) {
  const Y = T_LINE_Y;
  const C = T_PALETTE;
  const out = [];

  if (T_APPS.indexOf(i) >= 0) {
    // weekly app compatibility scan: three rings bloom out and settle
    out.push(<circle key={'af' + i} cx={x} cy={Y} r={T_RING_R[0] * sc * tOut(since / 0.6)}
      fill={C.moss200} opacity={0.45}/>);
    for (let j = 0; j < 3; j++) {
      const p = tOut((since - j * 0.09) / 0.75);
      if (p <= 0) continue;
      out.push(<circle key={'ar' + i + 'r' + j} cx={x} cy={Y} r={T_RING_R[j] * sc * p}
        fill="none" stroke={C.moss500} strokeWidth={[3.5, 3, 2.5][j]}
        opacity={[0.95, 0.7, 0.45][j] * tClamp(p * 2)}/>);
    }
    const b = tClamp(since / 1.1);
    if (b < 1) {
      out.push(<circle key={'ab' + i} cx={x} cy={Y} r={(28 + 70 * tOut(b)) * sc}
        fill="none" stroke={C.moss400} strokeWidth={2} opacity={0.6 * (1 - b)}/>);
    }
    out.push(<circle key={'ac' + i} cx={x} cy={Y} r={7 * sc * tBack(since / 0.3)} fill={C.moss700}/>);
  }

  if (T_PATCH.indexOf(i) >= 0) {
    // security patch: a stem rises and a check mark pops on top
    const h = 66 * sc;
    out.push(<line key={'ps' + i} x1={x} y1={Y} x2={x} y2={Y - h * tOut(since / 0.3)}
      stroke={C.moss700} strokeWidth={5} strokeLinecap="round"/>);
    const pop = tBack((since - 0.16) / 0.32);
    if (pop > 0) {
      const cy = Y - h;
      const r = 21 * sc;
      out.push(<circle key={'pc' + i} cx={x} cy={cy} r={r * pop} fill={C.moss700}/>);
      out.push(<path key={'pk' + i} d={tCheck(x, cy, r * 0.5)} fill="none"
        stroke={C.creamLt} strokeWidth={4.5 * sc} strokeLinecap="round" strokeLinejoin="round"
        opacity={tClamp((pop - 0.5) * 2)}/>);
    }
  }

  if (i === T_INCIDENT) {
    // the one amber incident: alert ripples until the next day clears it,
    // then it stays on the line as a quiet amber mark
    const clearAt = T_REACH[T_CLEARED];
    const active = 1 - tSmooth(tWin(time, clearAt, clearAt + 0.5));
    const pop = tBack(since / 0.3);
    const lead = tClamp(since / 0.2);
    for (let n = 0; n < 2; n++) {
      const ph = ((since + n * 0.45) % 0.9) / 0.9;
      const a = 0.6 * (1 - ph) * active * lead;
      if (a > 0.01) {
        out.push(<circle key={'ir' + n} cx={x} cy={Y} r={(20 + 64 * ph) * sc}
          fill="none" stroke={C.amber} strokeWidth={3} opacity={a}/>);
      }
    }
    const breathe = 0.5 + 0.5 * Math.sin(since * 6.5);
    out.push(<circle key="ih" cx={x} cy={Y} r={48 * sc * pop} fill="url(#tdl-amber-halo)"
      opacity={(0.55 + 0.35 * breathe) * active + 0.4 * (1 - active)}/>);
    out.push(<circle key="io" cx={x} cy={Y} r={30 * sc} fill="none" stroke={C.amber}
      strokeWidth={2.5} opacity={0.7 * (1 - active)}/>);
    out.push(<circle key="id" cx={x} cy={Y} r={17 * sc * pop} fill={C.amber}/>);
    const lp = tOut((since - 0.08) / 0.35);
    const yTop = T_TIER_B + 40, yBot = Y - 26 * sc;
    if (lp > 0) {
      out.push(<line key="il" x1={x} y1={yBot} x2={x} y2={yBot - (yBot - yTop) * lp}
        stroke={C.amber} strokeWidth={2.5} strokeLinecap="round"/>);
    }
  }

  if (i === T_CLEARED) {
    const pop = tBack(since / 0.3);
    const r = 17 * sc;
    out.push(<circle key="cd" cx={x} cy={Y} r={r * pop} fill={C.moss600}/>);
    if (pop > 0.5) {
      out.push(<path key="ck" d={tCheck(x, Y, r * 0.55)} fill="none" stroke={C.creamLt}
        strokeWidth={4 * sc} strokeLinecap="round" strokeLinejoin="round"
        opacity={tClamp((pop - 0.5) * 2)}/>);
    }
    const lp = tOut((since - 0.08) / 0.35);
    const yTop = T_TIER_B + 40, yBot = Y - 26 * sc;
    if (lp > 0) {
      out.push(<line key="cl" x1={x} y1={yBot} x2={x} y2={yBot - (yBot - yTop) * lp}
        stroke={C.moss600} strokeWidth={2.5} strokeLinecap="round"/>);
    }
  }

  if (i === T_REPORT) {
    // month close: the taller tick, a small report sheet on top
    const H = T_REPORT_H;
    out.push(<line key="rs" x1={x} y1={Y} x2={x} y2={Y - H * tOut(since / 0.65)}
      stroke={C.moss700} strokeWidth={6} strokeLinecap="round"/>);
    const pop = tBack((since - 0.5) / 0.32);
    if (pop > 0) {
      out.push(
        <g key="rd" transform={`translate(${x} ${Y - H}) scale(${pop})`}>
          <rect x={-19} y={-50} width={38} height={48} rx={4} fill={C.moss700}/>
          <line x1={-10} y1={-38} x2={10} y2={-38} stroke={C.creamLt} strokeWidth={3} strokeLinecap="round"/>
          <line x1={-10} y1={-29} x2={10} y2={-29} stroke={C.creamLt} strokeWidth={3} strokeLinecap="round"/>
          <line x1={-10} y1={-20} x2={3} y2={-20} stroke={C.creamLt} strokeWidth={3} strokeLinecap="round"/>
        </g>
      );
    }
    const b = tClamp((since - 0.6) / 1.0);
    if (b > 0 && b < 1) {
      out.push(<circle key="rb" cx={x} cy={Y - H - 25} r={30 + 50 * tOut(b)} fill="none"
        stroke={C.moss400} strokeWidth={2} opacity={0.55 * (1 - b)}/>);
    }
  }

  return out;
}

// ── The ledger strip: rule, month line, ticks, pings, marks (SVG) ──────
function TStrip({ time, P, k, sc, xs, intro }) {
  const C = T_PALETTE;
  const Y = T_LINE_Y;
  const pad = tLerp(64, 40, k);
  const lineStart = xs[0] - pad;
  const lineEnd = xs[T_DAYS - 1] + pad;
  const cursor = tCursorX(P, k);
  const solidTo = tLerp(Math.min(cursor, lineEnd), lineEnd, k);
  const reveal = tLerp(lineStart, T_W + 40, tOut(tWin(time, 0.35, 1.3)));
  const curA = tSmooth(tWin(time, 0.6, 1.2)) *
    (1 - tSmooth(tWin(time, T_COLLAPSE_A, T_COLLAPSE_A + 0.6)));
  const pingY0 = Y + tLerp(68, 56, k);
  const pitch = tLerp(30, 24, k);
  const dotR = tLerp(9, 7.5, k);

  let days = [];
  let marks = [];
  for (let i = 0; i < T_DAYS; i++) {
    const x = xs[i];
    if (x < -260 || x > T_W + 260) continue;
    const since = time - T_REACH[i];
    if (since < 0) {
      days.push(<line key={'f' + i} x1={x} y1={Y - 9} x2={x} y2={Y + 9}
        stroke={C.ink25} strokeWidth={3} strokeLinecap="round"/>);
      continue;
    }
    const tick = tBack(since / 0.25);
    days.push(<line key={'t' + i} x1={x} y1={Y - 15 * tick} x2={x} y2={Y + 15 * tick}
      stroke={C.moss600} strokeWidth={4} strokeLinecap="round"/>);
    for (let j = 0; j < 4; j++) {
      const p = tBack((since - 0.06 - j * 0.1) / 0.26);
      if (p <= 0) continue;
      const cy = pingY0 + j * pitch;
      if (i === T_MISSED_DAY && j === T_MISSED_DOT) {
        days.push(<circle key={'p' + i + 'd' + j} cx={x} cy={cy} r={dotR * p * 0.86}
          fill="none" stroke={C.ink40} strokeWidth={2.5}/>);
      } else {
        days.push(<circle key={'p' + i + 'd' + j} cx={x} cy={cy} r={dotR * p}
          fill={C.moss500} opacity={1 - j * 0.12}/>);
      }
    }
    marks = marks.concat(tEventMarks(i, x, since, time, sc));
  }

  // small arrow between the incident and cleared labels
  const sinceClear = time - T_REACH[T_CLEARED];
  let arrow = null;
  if (sinceClear > 0) {
    const xm = (xs[T_INCIDENT] + xs[T_CLEARED]) / 2;
    const ay = T_TIER_B + 4;
    arrow = (
      <path d={'M ' + (xm - 12) + ' ' + ay + ' L ' + (xm + 12) + ' ' + ay +
        ' M ' + (xm + 4) + ' ' + (ay - 8) + ' L ' + (xm + 12) + ' ' + ay +
        ' L ' + (xm + 4) + ' ' + (ay + 8)}
        fill="none" stroke={C.ink40} strokeWidth={3} strokeLinecap="round" strokeLinejoin="round"
        opacity={tSmooth(tWin(sinceClear, 0.2, 0.5))}/>
    );
  }

  const solidEnd = Math.min(solidTo, reveal);
  const dashA = Math.max(lineStart, solidTo);
  const dashB = Math.min(lineEnd, reveal);

  return (
    <svg width={T_W} height={T_H} viewBox={'0 0 ' + T_W + ' ' + T_H}
      style={{ position: 'absolute', left: 0, top: 0 }}>
      <defs>
        <linearGradient id="tdl-edge-grad" x1="0" y1="0" x2={T_W} y2="0" gradientUnits="userSpaceOnUse">
          <stop offset="0" stopColor="#000"/>
          <stop offset="0.06" stopColor="#fff"/>
          <stop offset="0.94" stopColor="#fff"/>
          <stop offset="1" stopColor="#000"/>
        </linearGradient>
        <mask id="tdl-edge" maskUnits="userSpaceOnUse" x="0" y="0" width={T_W} height={T_H}>
          <rect x="0" y="0" width={T_W} height={T_H} fill="url(#tdl-edge-grad)"/>
        </mask>
        <radialGradient id="tdl-amber-halo">
          <stop offset="0" stopColor={C.amber} stopOpacity="0.55"/>
          <stop offset="0.6" stopColor={C.amberSoft} stopOpacity="0.22"/>
          <stop offset="1" stopColor={C.amberSoft} stopOpacity="0"/>
        </radialGradient>
      </defs>

      {/* today cursor, behind the strip */}
      {curA > 0.01 && (
        <line x1={cursor} y1={Y - 215} x2={cursor} y2={Y + 255}
          stroke={C.moss300} strokeWidth={2} opacity={0.7 * curA}/>
      )}

      <g mask="url(#tdl-edge)">
        {/* the ledger rule the month is written on */}
        <line x1={70} y1={Y} x2={T_W - 70} y2={Y} stroke={C.ink15} strokeWidth={2}
          opacity={tSmooth(tWin(time, 0.15, 0.9))}/>
        <g opacity={intro}>
          {dashB > dashA && (
            <line x1={dashA} y1={Y} x2={dashB} y2={Y} stroke={C.ink40} strokeWidth={3}
              strokeDasharray="10 12" opacity={0.7}/>
          )}
          {solidEnd > lineStart && (
            <line x1={lineStart} y1={Y} x2={solidEnd} y2={Y} stroke={C.moss600} strokeWidth={5}
              strokeLinecap="round"/>
          )}
          {days}
          {marks}
          {arrow}
        </g>
      </g>

      {curA > 0.01 && (
        <path d={'M ' + (cursor - 11) + ' ' + (Y - 228) + ' L ' + (cursor + 11) + ' ' + (Y - 228) +
          ' L ' + cursor + ' ' + (Y - 213) + ' Z'} fill={C.moss400} opacity={curA}/>
      )}
    </svg>
  );
}

// ── Text layers (HTML) ─────────────────────────────────────────────────
function TLabel({ x, y, text, lines, color, size, anchor, opacity, rise }) {
  if (opacity < 0.01) return null;
  const tx = anchor === 'right' ? '-100%' : anchor === 'left' ? '0%' : '-50%';
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: `translate(${tx}, -50%) translateY(${rise}px)`,
      fontFamily: T_FONTS.display, fontWeight: 600, fontSize: size,
      lineHeight: 1, letterSpacing: '-0.015em', color, opacity,
      whiteSpace: 'nowrap',
      textAlign: anchor === 'right' ? 'right' : anchor === 'left' ? 'left' : 'center',
    }}>
      {lines ? lines.map((l, n) => <div key={n}>{l}</div>) : text}
    </div>
  );
}

function TDayNumbers({ time, k, xs, intro }) {
  const size = 44;
  const y = T_LINE_Y + 212;
  return xs.map((x, i) => {
    if (x < -120 || x > T_W + 120) return null;
    const since = time - T_REACH[i];
    const lit = since >= 0 ? 0.42 + 0.4 * tSmooth(since / 0.3) : 0.3;
    const keep = T_KEY_DAYS.indexOf(i) >= 0 ? 1 : 1 - k;
    const a = lit * tEdge(x) * intro * keep;
    if (a < 0.01) return null;
    return (
      <div key={'n' + i} style={{
        position: 'absolute', left: x, top: y, transform: 'translate(-50%, -50%)',
        fontFamily: T_FONTS.mono, fontWeight: 500, fontSize: size, lineHeight: 1,
        letterSpacing: '0.02em', color: T_PALETTE.ink, opacity: a, whiteSpace: 'nowrap',
      }}>
        {tPad2(i + 1)}
      </div>
    );
  });
}

function TEventLabels({ time, k, xs, intro }) {
  const C = T_PALETTE;
  const size = tLerp(56, 50, k);
  const enter = (since, a, b) => tSmooth(tWin(since, a, b));
  const out = [];

  T_APPS.forEach((i) => {
    const e = enter(time - T_REACH[i], 0.22, 0.55);
    if (e <= 0) return;
    out.push(<TLabel key={'la' + i} x={xs[i]} y={T_TIER_A} text="apps" color={C.moss700}
      size={size} anchor="center" opacity={e * tEdge(xs[i]) * intro} rise={(1 - e) * 14}/>);
  });
  T_PATCH.forEach((i) => {
    const e = enter(time - T_REACH[i], 0.3, 0.6);
    if (e <= 0) return;
    out.push(<TLabel key={'lp' + i} x={xs[i]} y={T_TIER_A} text="patch" color={C.moss700}
      size={size} anchor="center" opacity={e * tEdge(xs[i]) * intro} rise={(1 - e) * 14}/>);
  });

  const xm = (xs[T_INCIDENT] + xs[T_CLEARED]) / 2;
  const e1 = enter(time - T_REACH[T_INCIDENT], 0.2, 0.5);
  if (e1 > 0) {
    out.push(<TLabel key="li" x={xm - 26} y={T_TIER_B} text="incident" color={C.amberInk}
      size={size} anchor="right" opacity={e1 * tEdge(xm) * intro} rise={(1 - e1) * 14}/>);
  }
  const e2 = enter(time - T_REACH[T_CLEARED], 0.2, 0.5);
  if (e2 > 0) {
    out.push(<TLabel key="lc" x={xm + 26} y={T_TIER_B} text="cleared" color={C.moss600}
      size={size} anchor="left" opacity={e2 * tEdge(xm) * intro} rise={(1 - e2) * 14}/>);
  }

  const xr = xs[T_REPORT];
  const e3 = enter(time - T_REACH[T_REPORT], 0.55, 0.95);
  if (e3 > 0) {
    out.push(<TLabel key="lr" x={xr - 44} y={T_REPORT_LABEL_Y} lines={['report', 'delivered']}
      color={C.moss700} size={size} anchor="right" opacity={e3 * tEdge(xr) * intro}
      rise={(1 - e3) * 14}/>);
  }
  return out;
}

function TTodayLabel({ time, P, k }) {
  const a = tSmooth(tWin(time, 0.6, 1.2)) *
    (1 - tSmooth(tWin(time, T_COLLAPSE_A, T_COLLAPSE_A + 0.6)));
  if (a < 0.01) return null;
  return (
    <div style={{
      position: 'absolute', left: tCursorX(P, k), top: T_LINE_Y + 284,
      transform: 'translate(-50%, -50%)', paddingLeft: '0.24em',
      fontFamily: T_FONTS.mono, fontWeight: 500, fontSize: 44, lineHeight: 1,
      letterSpacing: '0.24em', textTransform: 'uppercase',
      color: T_PALETTE.moss500, opacity: 0.85 * a, whiteSpace: 'nowrap',
    }}>
      today
    </div>
  );
}

function THeader({ time, P }) {
  const C = T_PALETTE;
  const a = tSmooth(tWin(time, 0.25, 0.95));
  if (a < 0.01) return null;
  const started = P >= 0;
  const n = Math.max(1, Math.min(T_DAYS, Math.floor(P) + 1));
  const bump = started ? 1 - tOut((time - T_REACH[n - 1]) / 0.28) : 0;
  return (
    <>
      <div style={{ position: 'absolute', left: 96, top: 70, opacity: a }}>
        <div style={{
          fontFamily: T_FONTS.mono, fontWeight: 500, fontSize: 30, lineHeight: 1,
          letterSpacing: '0.22em', textTransform: 'uppercase', color: C.ink40, whiteSpace: 'nowrap',
        }}>
          § 03 · the thirty day ledger
        </div>
        <div style={{
          fontFamily: T_FONTS.serif, fontStyle: 'italic', fontSize: 58, lineHeight: 1,
          color: C.moss600, marginTop: 16, whiteSpace: 'nowrap',
        }}>
          an idealised month
        </div>
      </div>
      <div style={{ position: 'absolute', right: 96, top: 52, opacity: a, textAlign: 'right' }}>
        <div style={{
          fontFamily: T_FONTS.mono, fontWeight: 500, fontSize: 44, lineHeight: 1,
          letterSpacing: '0.24em', textTransform: 'uppercase', color: C.ink55,
        }}>
          day
        </div>
        <div style={{
          display: 'flex', alignItems: 'baseline', justifyContent: 'flex-end',
          gap: 14, marginTop: 8,
        }}>
          <span style={{
            display: 'inline-block',
            fontFamily: T_FONTS.display, fontWeight: 700, fontSize: 150, lineHeight: 0.9,
            letterSpacing: '-0.03em', color: C.ink, fontVariantNumeric: 'tabular-nums',
            transform: `translateY(${bump * 12}px)`,
            opacity: started ? 1 - 0.35 * bump : 0.35,
          }}>
            {tPad2(n)}
          </span>
          <span style={{
            fontFamily: T_FONTS.mono, fontWeight: 500, fontSize: 44, lineHeight: 1,
            color: C.ink40, letterSpacing: '0.04em', whiteSpace: 'nowrap',
          }}>
            {'/ ' + T_DAYS}
          </span>
        </div>
      </div>
    </>
  );
}

// Captions: few words, large, one at a time. Plain divs only (no svg) so the
// shell's chrome remover never mistakes a caption for a playback bar.
const T_CAPTIONS = [
  { from: 1.1, to: 3.2, text: 'every dot, an uptime ping', glyph: 'dot' },
  { from: 3.45, to: 5.7, text: 'every ring, a weekly app scan', glyph: 'ring' },
  { from: T_REACH[T_CLEARED] + 0.4, to: 10.3, text: 'one incident, caught and cleared', glyph: 'amber' },
  { from: 13.3, to: 99, text: 'a month, collapsed into a single line.', glyph: null },
];

function TGlyph({ kind }) {
  const C = T_PALETTE;
  if (kind === 'dot') {
    return <div style={{ width: 22, height: 22, borderRadius: '50%', background: C.moss500, flexShrink: 0 }}/>;
  }
  if (kind === 'amber') {
    return <div style={{ width: 24, height: 24, borderRadius: '50%', background: C.amber, flexShrink: 0 }}/>;
  }
  if (kind === 'ring') {
    return (
      <div style={{
        width: 36, height: 36, borderRadius: '50%', border: `3px solid ${C.moss500}`,
        boxSizing: 'border-box', display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <div style={{ width: 14, height: 14, borderRadius: '50%', border: `2.5px solid ${C.moss500}`, boxSizing: 'border-box' }}/>
      </div>
    );
  }
  return null;
}

function TCaptions({ time }) {
  return T_CAPTIONS.map((c, n) => {
    const inA = tSmooth(tWin(time, c.from, c.from + 0.45));
    const outA = 1 - tSmooth(tWin(time, c.to - 0.4, c.to));
    const a = inA * outA;
    if (a < 0.01) return null;
    return (
      <div key={'c' + n} style={{
        position: 'absolute', left: 0, top: T_CAPTION_Y, width: T_W,
        transform: `translateY(-50%) translateY(${(1 - inA) * 14}px)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 22,
        opacity: a, pointerEvents: 'none',
      }}>
        {c.glyph && <TGlyph kind={c.glyph}/>}
        <span style={{
          fontFamily: T_FONTS.serif, fontStyle: 'italic', fontSize: 62, lineHeight: 1.1,
          color: T_PALETTE.moss600, letterSpacing: '-0.005em', whiteSpace: 'nowrap',
        }}>
          {c.text}
        </span>
      </div>
    );
  });
}

// ── Scene ──────────────────────────────────────────────────────────────
function ThirtyDayLedgerScene() {
  const time = useTime();
  const P = tCursor(time);
  const k = tInOut(tWin(time, T_COLLAPSE_A, T_COLLAPSE_B));
  const sc = tLerp(1, 0.76, k);
  const g = tGlobal(time);
  const intro = tSmooth(tWin(time, 0.3, 1.1));
  const xs = [];
  for (let i = 0; i < T_DAYS; i++) xs.push(tDayX(i, P, k));

  return (
    <>
      <TBackdrop/>
      <div style={{ position: 'absolute', left: 0, top: 0, width: T_W, height: T_H, opacity: g }}>
        <TStrip time={time} P={P} k={k} sc={sc} xs={xs} intro={intro}/>
        <TDayNumbers time={time} k={k} xs={xs} intro={intro}/>
        <TEventLabels time={time} k={k} xs={xs} intro={intro}/>
        <TTodayLabel time={time} P={P} k={k}/>
        <THeader time={time} P={P}/>
        <TCaptions time={time}/>
      </div>
      <TFilmGrain opacity={0.06}/>
    </>
  );
}

Object.assign(window, { ThirtyDayLedgerScene, T_PALETTE, T_FONTS, T_HOLD });
