// ceiling-break.jsx · "§ 03 · ceiling break", the Wix to Shopify graduation moment
//
// 14s loop on a 1920x1080 stage, driven by the shared animations.jsx engine
// (Stage, useTime, Easing, interpolate).
//
//    0.0 to 1.0   a small moss shape rests on the floor of the old room
//    1.0 to 2.8   first test: it jumps, meets the ceiling, the line flexes
//    2.8 to 3.9   second test, harder: the line starts to crack
//    3.9 to 5.3   it squats, rises and presses; the ceiling bows and splinters
//    5.3          the ceiling gives way
//    5.3 to 7.5   it rises through the gap and settles in as the door of the
//                 storefront that has been waiting, in outline, above
//    7.6 to 8.6   the lights come on and the OPEN tag swings in
//    8.6 to 12.9  settled hold (11.5s is the frame held for reduced motion)
//   12.9 to 14.0  hand back: the store dims to outline, the ceiling heals and
//                 a fresh shape grows on the floor, matching frame zero
//
// Every top level name here is a global shared with the other text/babel
// scripts on the page, so each carries a CB prefix to stay clear of the engine.
// No box-shadow anywhere: the embed shell strips inline box-shadows, so depth
// comes from gradient layers instead.

const CB_PALETTE = {
  cream:     '#f5f0e8',
  creamDk:   '#ebe4d6',
  creamLt:   '#faf6ee',
  room:      '#e6ddcc',
  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)',
  ink06:     'rgba(15,23,19,0.06)',
  moss800:   '#26402f',
  moss700:   '#32553f',
  moss600:   '#3f6b54',
  moss500:   '#4d7e65',
  moss400:   '#6fa37a',
  moss300:   '#93b89a',
  moss200:   '#b8cdbb',
  moss100:   '#d7e1d4',
  amber:     '#cd8a4b',
  amberSoft: '#e2a568',
  amberGlow: 'rgba(205,138,75,0.34)',
};
const CB_FONTS = {
  display: '"Space Grotesk", system-ui, sans-serif',
  serif:   '"Instrument Serif", Georgia, serif',
  mono:    '"JetBrains Mono", ui-monospace, monospace',
};

// ── Small helpers ──────────────────────────────────────────────────────────
const cbClamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
const cbSmooth = (t) => { const x = cbClamp(t); return x * x * (3 - 2 * x); };
const cbMix = (a, b, t) => a + (b - a) * t;
const cbP = (t, a, b) => cbClamp((t - a) / (b - a));
// Fade in over fi seconds from a, hold, fade out over the last fo seconds before b.
const cbWindow = (t, a, b, fi, fo) =>
  cbSmooth((t - a) / fi) * (1 - cbSmooth((t - (b - fo)) / fo));
const cbRand = (i, seed) => {
  const x = Math.sin(i * 12.9898 + seed * 78.233) * 43758.5453;
  return x - Math.floor(x);
};
// Resting breath. Period 2s, so it reads zero at 0s, 1s and 14s alike.
const cbBreathe = (t) => 1 + 0.014 * Math.sin(t * Math.PI);
// Width that goes with a given vertical squash, so the shape keeps its mass.
const cbSx = (sy) => 1 + (1 - sy) * 0.75;

// ── Geometry (stage px) ────────────────────────────────────────────────────
const CB_CX = 960;
const CB_CEIL = 640;     // the old platform's ceiling
const CB_FLOOR = 990;    // floor of the old room
const CB_SIZE = 120;     // the shape at rest
// The storefront is drawn in its own coordinates (plinth at y 500) and lifted
// by CB_STORE_DY, which keeps it well clear of the ceiling at full bow.
const CB_STORE_DY = -60;
const CB_DOOR = { cx: 960, cy: 395 + CB_STORE_DY, w: 140, h: 210 };
const CB_WIN = [
  { x: 720, y: 290, w: 150, h: 150 },
  { x: 1050, y: 290, w: 150, h: 150 },
];

// ── Timing (seconds) ───────────────────────────────────────────────────────
const CB_DURATION = 14;
const CB_BREAK = 5.3;
const CB_PRESS_START = 4.45;
const CB_PRESS_PEAK = 96;     // how far the ceiling bows before it gives
const CB_PRESS_GROW = 0.28;   // the shape outgrows the room while it presses
const CB_HOLD = 11.5;         // settled frame, matches HOLD_MS in index.html

const cbStoreSolid = (t) => cbSmooth(cbP(t, 5.8, 7.2)) * (1 - cbSmooth(cbP(t, 13.1, 13.8)));
const cbLit = (t) => cbSmooth(cbP(t, 7.6, 8.4)) * (1 - cbSmooth(cbP(t, 12.9, 13.5)));

// ── The ceiling ────────────────────────────────────────────────────────────
// A hit: quick rise to the peak, then a damped spring back to level.
function cbImpact(t, tc, peak) {
  const x = t - tc;
  if (x < 0 || x > 1.2) return 0;
  if (x < 0.1) return peak * Easing.easeOutQuad(x / 0.1);
  const y = x - 0.1;
  return peak * Math.exp(-8 * y) * Math.cos(17 * y);
}

function cbPressP(t) { return cbP(t, CB_PRESS_START, CB_BREAK); }

function cbPressBulge(t) {
  if (t < CB_PRESS_START || t >= CB_BREAK) return 0;
  const p = cbPressP(t);
  return CB_PRESS_PEAK * (0.3 * Easing.easeOutCubic(p) + 0.7 * p * p);
}

function cbBulge(t) {
  if (t >= CB_BREAK) return 0;
  return cbImpact(t, 1.85, 26) + cbImpact(t, 3.35, 48) + cbPressBulge(t);
}

function cbCrack(t) {
  if (t < 3.35 || t >= CB_BREAK) return 0;
  if (t < CB_PRESS_START) return 0.32 * cbSmooth(cbP(t, 3.35, 3.5));
  return 0.32 + 0.68 * cbPressP(t);
}

function cbCeilingState(t) {
  if (t < CB_BREAK || t >= 13.8) {
    let sigma = 150;
    if (t >= CB_PRESS_START && t < CB_BREAK) {
      const grow = 1 + CB_PRESS_GROW * Easing.easeInOutSine(cbPressP(t));
      sigma = 0.55 * CB_SIZE * grow * 1.08 + 70;
    }
    return { broken: false, bulge: cbBulge(t), sigma, crack: cbCrack(t) };
  }
  // Broken. The torn ends start where the bow peaked, peel outward and settle.
  const x = t - CB_BREAK;
  const heal = 1 - Easing.easeInOutCubic(cbP(t, 13.0, 13.8));
  const gap = 160 * Easing.easeOutExpo(cbClamp(x / 0.35)) * heal;
  const lift = (58
    + (CB_PRESS_PEAK - 58) * (1 - Easing.easeOutCubic(cbClamp(x / 0.5)))
    + 10 * Math.exp(-6 * x) * Math.sin(20 * x)) * heal;
  return { broken: true, gap, lift, jag: gap / 160 };
}

const cbPathOf = (pts) =>
  pts.map((p, i) => `${i ? 'L' : 'M'} ${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');

// Stroke paths (one, or two once torn) plus the room fill underneath them.
function cbCeilPaths(c, off) {
  const Y = CB_CEIL + off;
  if (!c.broken) {
    const pts = [];
    for (let x = 0; x <= 1920; x += 16) {
      const d = Math.abs(x - CB_CX) / c.sigma;
      pts.push([x, Y - c.bulge * Math.exp(-d * d * d)]);
    }
    const line = cbPathOf(pts);
    return { strokes: [line], fill: `${line} L 1920 1080 L 0 1080 Z` };
  }
  const reach = 260;
  const tipL = CB_CX - c.gap;
  const tipR = CB_CX + c.gap;
  const liftAt = (dist) => { const k = cbClamp(1 - dist / reach); return c.lift * k * k; };
  const left = [];
  for (let x = 0; x < tipL; x += 16) left.push([x, Y - liftAt(tipL - x)]);
  left.push([tipL, Y - c.lift]);
  const right = [[tipR, Y - c.lift]];
  for (let x = 1920; x > tipR; x -= 16) right.splice(1, 0, [x, Y - liftAt(x - tipR)]);
  const fill = `${cbPathOf(left)} L ${tipL.toFixed(1)} ${Y} L ${tipR.toFixed(1)} ${Y} `
    + right.map((p) => `L ${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ')
    + ' L 1920 1080 L 0 1080 Z';
  // A torn end: a small jag at each tip, sized by how far the gap has opened.
  const j = c.jag;
  const ty = Y - c.lift;
  const leftStroke = off === 0
    ? [...left, [tipL - 12 * j, ty - 14 * j], [tipL + 3 * j, ty - 30 * j]]
    : left;
  const rightStroke = off === 0
    ? [[tipR - 3 * j, ty - 30 * j], [tipR + 12 * j, ty - 14 * j], ...right]
    : right;
  return { strokes: [cbPathOf(leftStroke), cbPathOf(rightStroke)], fill };
}

// Hairline breaks across the line, inner ones first.
const CB_BREAKS = [
  { dx: -46, at: 0.0 }, { dx: 54, at: 0.12 }, { dx: -112, at: 0.45 },
  { dx: 120, at: 0.55 }, { dx: -176, at: 0.75 }, { dx: 184, at: 0.86 },
];
// Strain ticks that flash above the point of contact, kept to flat angles so
// they stay under the storefront even at full bow.
const CB_STRAIN = [-160, -136, -44, -20];

function cbStrainAlpha(t) {
  const flash = (tc) => { const x = t - tc; return x < 0 || x > 0.45 ? 0 : 1 - x / 0.45; };
  let a = Math.max(flash(1.85) * 0.7, flash(3.35));
  if (t >= CB_PRESS_START && t < CB_BREAK) {
    const p = cbPressP(t);
    a = Math.max(a, (0.35 + 0.65 * p) * (0.78 + 0.22 * Math.sin(t * 40)));
  }
  return a;
}

// Flakes that drop from the ceiling beside the shape on each hit.
const CB_DUST = Array.from({ length: 16 }, (_, i) => ({
  t0: i < 5 ? 1.88 : i < 11 ? 3.38 : 4.7 + (i - 11) * 0.12,
  dx: (cbRand(i, 8) < 0.5 ? -1 : 1) * (84 + cbRand(i, 9) * 110),
  size: 7 + cbRand(i, 10) * 6,
  vx: (cbRand(i, 11) - 0.5) * 70,
}));

function CBRoom({ t }) {
  const c = cbCeilingState(t);
  const main = cbCeilPaths(c, 0);
  const slab = cbCeilPaths(c, 18);
  const apexY = c.broken ? CB_CEIL : CB_CEIL - c.bulge;
  const strain = c.broken ? 0 : cbStrainAlpha(t);

  return (
    <svg width="1920" height="1080" viewBox="0 0 1920 1080"
      style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      <defs>
        <pattern id="cb-hatch" width="22" height="22" patternUnits="userSpaceOnUse"
          patternTransform="rotate(45)">
          <line x1="0" y1="0" x2="0" y2="22" stroke={CB_PALETTE.ink06} strokeWidth="3" />
        </pattern>
      </defs>

      {/* the old room */}
      <path d={main.fill} fill={CB_PALETTE.room} />
      <path d={main.fill} fill="url(#cb-hatch)" />
      <line x1="0" y1={CB_FLOOR} x2="1920" y2={CB_FLOOR}
        stroke={CB_PALETTE.ink25} strokeWidth="4" />

      {/* falling flakes */}
      {CB_DUST.map((d, i) => {
        const x = t - d.t0;
        if (x < 0 || x > 0.9 || t >= CB_BREAK + 0.5) return null;
        const px = CB_CX + d.dx + d.vx * x;
        const py = CB_CEIL + 14 + 0.5 * 1500 * x * x;
        return (
          <rect key={i} x={px - d.size / 2} y={py - d.size / 2} width={d.size} height={d.size}
            fill={CB_PALETTE.ink} opacity={0.55 * (1 - x / 0.9)}
            transform={`rotate(${x * 240 + i * 20} ${px} ${py})`} />
        );
      })}

      {/* the ceiling: a thin underside line and the heavy line itself */}
      {slab.strokes.map((d, i) => (
        <path key={`s${i}`} d={d} fill="none" stroke={CB_PALETTE.ink25} strokeWidth="4"
          strokeLinecap="round" strokeLinejoin="round" />
      ))}
      {main.strokes.map((d, i) => (
        <path key={`m${i}`} d={d} fill="none" stroke={CB_PALETTE.ink} strokeWidth="12"
          strokeLinecap="round" strokeLinejoin="round" opacity="0.9" />
      ))}

      {/* hairline breaks */}
      {!c.broken && CB_BREAKS.map((b, i) => {
        const k = cbClamp((c.crack - b.at) / 0.25);
        if (k <= 0) return null;
        const x = CB_CX + b.dx;
        const d = Math.abs(b.dx) / c.sigma;
        const y = CB_CEIL - c.bulge * Math.exp(-d * d * d);
        const h = 34 * k;
        return (
          <path key={`b${i}`} fill="none" stroke={CB_PALETTE.cream} strokeWidth="5"
            strokeLinecap="round" strokeLinejoin="round"
            d={`M ${x - 4} ${y - h / 2} L ${x + 5} ${y - h / 6} L ${x - 5} ${y + h / 6} L ${x + 4} ${y + h / 2 + 10 * k}`} />
        );
      })}

      {/* strain ticks above the point of contact */}
      {strain > 0.01 && CB_STRAIN.map((deg, i) => {
        const a = (deg * Math.PI) / 180;
        const r0 = 50;
        const r1 = r0 + 30 + 24 * strain;
        return (
          <line key={`k${i}`}
            x1={CB_CX + Math.cos(a) * r0} y1={apexY - 8 + Math.sin(a) * r0}
            x2={CB_CX + Math.cos(a) * r1} y2={apexY - 8 + Math.sin(a) * r1}
            stroke={CB_PALETTE.ink} strokeWidth="6" strokeLinecap="round"
            opacity={0.6 * strain} />
        );
      })}
    </svg>
  );
}

// ── The shape ──────────────────────────────────────────────────────────────
function cbJump(s, t, a, b, sy0, sMax, s1) {
  const k = cbP(t, a, b);
  const travel = 0.5 * k + 0.5 * Easing.easeOutQuad(k);
  const sy = k < 0.35
    ? cbMix(sy0, sMax, Easing.easeOutQuad(k / 0.35))
    : cbMix(sMax, s1, Easing.easeInOutSine((k - 0.35) / 0.65));
  s.h = CB_SIZE * sy;
  s.w = CB_SIZE * cbSx(sy);
  s.top = cbMix(CB_FLOOR - CB_SIZE * sy0, CB_CEIL, travel);
}

function cbSquashUp(s, t, a, b, s1, depth) {
  const sy = s1 - depth * Math.sin(Math.PI * cbP(t, a, b));
  s.h = CB_SIZE * sy;
  s.w = CB_SIZE * cbSx(sy);
  s.top = CB_CEIL - Math.max(0, cbBulge(t));
}

function cbFall(s, t, a, b, s1) {
  const k = cbP(t, a, b);
  const sy = 1 + (s1 - 1) * (1 - k) + 0.05 * Math.sin(Math.PI * k);
  const bottom = cbMix(CB_CEIL + CB_SIZE * s1, CB_FLOOR, Easing.easeInQuad(k));
  s.h = CB_SIZE * sy;
  s.w = CB_SIZE * cbSx(sy);
  s.top = bottom - s.h;
}

// Where the press leaves the shape at the instant the ceiling gives.
const CB_PRESS_END = {
  w: CB_SIZE * (1 + CB_PRESS_GROW) * 1.08,
  h: CB_SIZE * (1 + CB_PRESS_GROW) * 0.9,
};
CB_PRESS_END.cy = CB_CEIL - CB_PRESS_PEAK + CB_PRESS_END.h / 2;

// Through the gap, a little past the door, then down into the door frame.
const CB_RISE_T = [CB_BREAK, 5.55, 6.3, 6.7, 7.5];
const CB_RISE_EASE = [Easing.easeOutQuad, Easing.easeInOutSine, Easing.linear, Easing.easeInOutCubic];
const cbRiseW = interpolate(CB_RISE_T, [CB_PRESS_END.w, 126, 150, 150, CB_DOOR.w], CB_RISE_EASE);
const cbRiseH = interpolate(CB_RISE_T, [CB_PRESS_END.h, 196, 150, 150, CB_DOOR.h], CB_RISE_EASE);
const cbRiseY = interpolate([CB_BREAK, 6.3, 7.5], [CB_PRESS_END.cy, CB_DOOR.cy - 55, CB_DOOR.cy],
  [Easing.easeOutCubic, Easing.easeInOutCubic]);
const cbRiseRTop = interpolate([6.7, 7.5], [36, 70], Easing.easeInOutCubic);
const cbRiseRBot = interpolate([6.7, 7.5], [36, 6], Easing.easeInOutCubic);

function cbMainShape(t) {
  const S = CB_SIZE;
  const s = { cx: CB_CX, w: S, h: S, top: CB_FLOOR - S, opacity: 1, rTop: 36, rBot: 36, door: 0, glass: 0, inRoom: true };
  const pose = (sy) => { s.h = S * sy; s.w = S * cbSx(sy); };
  const onFloor = () => { s.top = CB_FLOOR - s.h; };

  if (t < 1.0) {
    const b = cbBreathe(t);
    s.w = S * b; s.h = S / b; onFloor();
  } else if (t < 1.3) {                       // first test
    pose(1 - 0.16 * Easing.easeInOutSine(cbP(t, 1.0, 1.3))); onFloor();
  } else if (t < 1.85) {
    cbJump(s, t, 1.3, 1.85, 0.84, 1.16, 1.04);
  } else if (t < 2.05) {
    cbSquashUp(s, t, 1.85, 2.05, 1.04, 0.2);
  } else if (t < 2.5) {
    cbFall(s, t, 2.05, 2.5, 1.04);
  } else if (t < 2.75) {
    pose(1 - 0.14 * Math.sin(Math.PI * cbP(t, 2.5, 2.75))); onFloor();
  } else if (t < 2.95) {                      // second test, harder
    pose(1 - 0.2 * Easing.easeInOutSine(cbP(t, 2.75, 2.95))); onFloor();
  } else if (t < 3.35) {
    cbJump(s, t, 2.95, 3.35, 0.8, 1.2, 1.05);
  } else if (t < 3.6) {
    cbSquashUp(s, t, 3.35, 3.6, 1.05, 0.24);
  } else if (t < 3.85) {
    cbFall(s, t, 3.6, 3.85, 1.05);
  } else if (t < 4.15) {                      // deep squat
    pose(1 - 0.26 * Easing.easeOutQuad(cbP(t, 3.85, 4.15))); onFloor();
  } else if (t < CB_PRESS_START) {
    cbJump(s, t, 4.15, CB_PRESS_START, 0.74, 1.22, 1.0);
  } else if (t < CB_BREAK) {                  // press until it gives
    const p = cbPressP(t);
    const settle = Easing.easeOutQuad(Math.min(1, p / 0.18));
    const grow = 1 + CB_PRESS_GROW * Easing.easeInOutSine(p);
    s.w = S * grow * (1 + 0.08 * settle);
    s.h = S * grow * (1 - 0.1 * settle);
    s.top = CB_CEIL - cbPressBulge(t);
    s.cx += Math.sin(t * 70) * 22 * p * p * (1 - p);
  } else if (t < 13.6) {                      // through, up, and into the door
    s.w = cbRiseW(t);
    s.h = cbRiseH(t);
    s.top = cbRiseY(t) - s.h / 2;
    s.rTop = cbRiseRTop(t);
    s.rBot = cbRiseRBot(t);
    s.door = cbSmooth(cbP(t, 6.9, 7.6));
    s.glass = s.door * cbLit(t);
    s.opacity = 1 - cbSmooth(cbP(t, 13.0, 13.6));
    s.inRoom = false;
  } else {
    s.opacity = 0;
    s.inRoom = false;
  }
  return s;
}

// The next shape, grown on the floor during the hand back so 14s equals 0s.
function cbNewcomer(t) {
  if (t < 13.3) return null;
  const S = CB_SIZE;
  const k = Easing.easeOutBack(cbP(t, 13.3, CB_DURATION));
  const b = cbBreathe(t);
  const h = S * k / b;
  return {
    cx: CB_CX, w: S * k * b, h, top: CB_FLOOR - h,
    opacity: cbSmooth(cbP(t, 13.3, 13.65)),
    rTop: 36, rBot: 36, door: 0, glass: 0, inRoom: true,
  };
}

function CBFloorShadow({ s }) {
  if (!s || !s.inRoom || s.opacity <= 0.01) return null;
  const height = Math.max(0, CB_FLOOR - (s.top + s.h));
  const k = cbClamp(1 - height / 340);
  const w = s.w * (0.55 + 0.45 * k) + 24;
  return (
    <div style={{
      position: 'absolute', left: s.cx - w / 2, top: CB_FLOOR - 10,
      width: w, height: 20, borderRadius: '50%',
      background: 'radial-gradient(ellipse, rgba(15,23,19,0.32), rgba(15,23,19,0) 70%)',
      opacity: k * s.opacity, pointerEvents: 'none',
    }} />
  );
}

function CBShapeBody({ s }) {
  if (!s || s.opacity <= 0.01 || s.w < 1 || s.h < 1) return null;
  return (
    <div style={{
      position: 'absolute',
      left: s.cx - s.w / 2, top: s.top,
      width: s.w, height: s.h,
      borderRadius: `${s.rTop}px ${s.rTop}px ${s.rBot}px ${s.rBot}px`,
      overflow: 'hidden',
      opacity: s.opacity,
      background: `radial-gradient(ellipse at 38% 28%, ${CB_PALETTE.moss400}, ${CB_PALETTE.moss600} 78%)`,
      pointerEvents: 'none',
    }}>
      {/* door finish, takes over as it docks */}
      <div style={{
        position: 'absolute', inset: 0, opacity: s.door,
        background: `linear-gradient(180deg, ${CB_PALETTE.moss600}, ${CB_PALETTE.moss700})`,
      }} />
      {/* lower rim shade */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at 72% 88%, rgba(15,23,19,0.30), rgba(15,23,19,0) 62%)',
      }} />
      {/* soft highlight */}
      <div style={{
        position: 'absolute', left: '16%', top: '10%', width: '40%', height: '24%',
        borderRadius: '50%', opacity: 1 - 0.6 * s.door,
        background: 'radial-gradient(ellipse, rgba(255,255,255,0.48), rgba(255,255,255,0) 70%)',
      }} />
      {/* door glass and handle, lit once the store opens */}
      <div style={{
        position: 'absolute', left: '20%', right: '20%', top: '13%', height: '40%',
        borderRadius: '42px 42px 4px 4px', opacity: s.glass,
        background: `linear-gradient(180deg, ${CB_PALETTE.amberSoft}, ${CB_PALETTE.amber})`,
      }} />
      <div style={{
        position: 'absolute', right: '14%', top: '60%', width: 16, height: 16,
        borderRadius: '50%', opacity: s.glass, background: CB_PALETTE.amberSoft,
      }} />
    </div>
  );
}

// ── The storefront that waits above ────────────────────────────────────────
const CB_DOOR_PATH = 'M 890 500 L 890 360 A 70 70 0 0 1 1030 360 L 1030 500 Z';

function cbAwningPath() {
  let d = 'M 680 184 L 1240 184 L 1240 240';
  for (let i = 7; i >= 0; i--) d += ` A 35 35 0 0 1 ${680 + i * 70} 240`;
  return `${d} Z`;
}
const CB_AWNING_PATH = cbAwningPath();
const CB_STRIPES = Array.from({ length: 8 }, (_, i) => {
  const x0 = 680 + i * 70;
  const x1 = x0 + 70;
  return { d: `M ${x0} 184 L ${x1} 184 L ${x1} 240 A 35 35 0 0 1 ${x0} 240 Z`, dark: i % 2 === 0 };
});
const CB_PRODUCTS = [
  { at: 8.0, el: (fill) => (<g fill={fill}><rect x="742" y="362" width="30" height="63" rx="6" /><rect x="750" y="344" width="14" height="22" rx="3" /></g>), fill: CB_PALETTE.moss600 },
  { at: 8.2, el: (fill) => (<rect x="786" y="383" width="42" height="42" rx="4" fill={fill} />), fill: CB_PALETTE.moss500 },
  { at: 8.4, el: (fill) => (<rect x="838" y="373" width="24" height="52" rx="9" fill={fill} />), fill: CB_PALETTE.moss700 },
];

function CBStore({ t }) {
  const solid = cbStoreSolid(t);
  const lit = cbLit(t);
  const outline = 0.6 * (1 - solid);
  const off = 1 - cbSmooth(cbP(t, 12.9, 13.5));

  // OPEN tag: drops in, swings, settles long before the held frame.
  const tagIn = cbSmooth(cbP(t, 8.3, 8.6));
  const tx = Math.max(0, t - 8.3);
  const swing = 18 * Math.exp(-3.2 * tx) * Math.cos(7 * tx);

  const dash = { fill: 'none', stroke: CB_PALETTE.moss500, strokeWidth: 4, strokeDasharray: '14 12' };

  return (
    <svg width="1920" height="1080" viewBox="0 0 1920 1080"
      style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      <defs>
        <linearGradient id="cb-win-glow" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={CB_PALETTE.amberSoft} stopOpacity="0.95" />
          <stop offset="100%" stopColor={CB_PALETTE.amber} stopOpacity="0.45" />
        </linearGradient>
        <radialGradient id="cb-plinth-glow">
          <stop offset="0%" stopColor={CB_PALETTE.amber} stopOpacity="0.5" />
          <stop offset="100%" stopColor={CB_PALETTE.amber} stopOpacity="0" />
        </radialGradient>
        <clipPath id="cb-win-clip">
          <rect x={CB_WIN[1].x} y={CB_WIN[1].y} width={CB_WIN[1].w} height={CB_WIN[1].h} rx="8" />
        </clipPath>
      </defs>

      <g transform={`translate(0 ${CB_STORE_DY})`}>
      {/* warm pool under the store once it opens */}
      <ellipse cx="960" cy="512" rx="420" ry="64" fill="url(#cb-plinth-glow)" opacity={lit} />

      {/* waiting: the store in dashed outline */}
      {outline > 0.01 && (
        <g opacity={outline}>
          <rect x="640" y="500" width="640" height="14" rx="7" {...dash} />
          <rect x="700" y="220" width="520" height="280" {...dash} />
          {CB_WIN.map((w, i) => (
            <rect key={i} x={w.x} y={w.y} width={w.w} height={w.h} rx="8" {...dash} />
          ))}
          <path d={CB_DOOR_PATH} {...dash} />
          <rect x="670" y="166" width="580" height="18" rx="4" {...dash} />
          <path d={CB_AWNING_PATH} {...dash} />
        </g>
      )}

      {/* built: the store in full */}
      {solid > 0.01 && (
        <g opacity={solid}>
          <rect x="640" y="500" width="640" height="14" rx="7" fill={CB_PALETTE.moss600} />
          <rect x="700" y="220" width="520" height="280" fill={CB_PALETTE.creamLt}
            stroke={CB_PALETTE.moss600} strokeWidth="6" />
          {CB_WIN.map((w, i) => (
            <g key={i}>
              <rect x={w.x} y={w.y} width={w.w} height={w.h} rx="8" fill={CB_PALETTE.creamDk}
                stroke={CB_PALETTE.moss600} strokeWidth="5" />
              <line x1={w.x + 8} y1="425" x2={w.x + w.w - 8} y2="425"
                stroke={CB_PALETTE.moss300} strokeWidth="4" />
            </g>
          ))}
          <path d={CB_DOOR_PATH} fill={CB_PALETTE.moss800} fillOpacity="0.2"
            stroke={CB_PALETTE.moss600} strokeWidth="5" />
          <rect x="670" y="166" width="580" height="18" rx="4" fill={CB_PALETTE.moss700} />
          {CB_STRIPES.map((st, i) => (
            <path key={i} d={st.d} fill={st.dark ? CB_PALETTE.moss500 : CB_PALETTE.creamLt} />
          ))}
          <path d={CB_AWNING_PATH} fill="none" stroke={CB_PALETTE.moss600} strokeWidth="4"
            strokeLinejoin="round" />
        </g>
      )}

      {/* open: lights, stock on the shelf, the tag */}
      {lit > 0.01 && (
        <g>
          {CB_WIN.map((w, i) => (
            <rect key={i} x={w.x + 3} y={w.y + 3} width={w.w - 6} height={w.h - 6} rx="6"
              fill="url(#cb-win-glow)" opacity={lit * 0.85} />
          ))}
          {CB_PRODUCTS.map((pr, i) => {
            const k = cbSmooth(cbP(t, pr.at, pr.at + 0.4));
            if (k <= 0.01) return null;
            return (
              <g key={i} opacity={k * off} transform={`translate(0 ${(1 - k) * 14})`}>
                {pr.el(pr.fill)}
              </g>
            );
          })}
          {tagIn > 0.01 && (
            <g clipPath="url(#cb-win-clip)" opacity={tagIn * off}>
              <g transform={`translate(0 ${(1 - tagIn) * -26}) rotate(${swing} 1125 290)`}>
                <line x1="1125" y1="290" x2="1125" y2="322" stroke={CB_PALETTE.ink55} strokeWidth="3" />
                <rect x="1058" y="322" width="134" height="62" rx="8" fill={CB_PALETTE.amber} />
                <text x="1125" y="369" textAnchor="middle" fontFamily={CB_FONTS.mono}
                  fontWeight="600" fontSize="44" letterSpacing="2" fill={CB_PALETTE.creamLt}>
                  OPEN
                </text>
              </g>
            </g>
          )}
        </g>
      )}
      </g>
    </svg>
  );
}

// ── Break effects ──────────────────────────────────────────────────────────
const CB_SHARDS = Array.from({ length: 14 }, (_, i) => {
  const side = i % 2 === 0 ? -1 : 1;
  return {
    x0: CB_CX + side * (10 + cbRand(i, 1) * 110),
    y0: CB_CEIL - 74 + cbRand(i, 2) * 40,
    vx: side * (160 + cbRand(i, 3) * 560),
    vy: -(420 + cbRand(i, 4) * 620),
    len: 24 + cbRand(i, 5) * 36,
    rot0: (cbRand(i, 6) - 0.5) * 50,
    spin: (cbRand(i, 7) - 0.5) * 760,
  };
});

function CBShards({ t }) {
  const x = t - CB_BREAK;
  if (x < 0 || x > 1.3) return null;
  const a = 1 - cbSmooth(x / 1.3);
  return (
    <svg width="1920" height="1080" viewBox="0 0 1920 1080"
      style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {CB_SHARDS.map((sh, i) => {
        const px = sh.x0 + sh.vx * x;
        const py = sh.y0 + sh.vy * x + 0.5 * 1500 * x * x;
        return (
          <rect key={i} x={px - sh.len / 2} y={py - 6} width={sh.len} height="12" rx="3"
            fill={CB_PALETTE.ink} opacity={0.85 * a}
            transform={`rotate(${sh.rot0 + sh.spin * x} ${px} ${py})`} />
        );
      })}
    </svg>
  );
}

// Amber builds under the press, flashes at the break, then clears.
function CBBurstGlow({ t }) {
  if (t < CB_PRESS_START || t > 6.2) return null;
  const pre = t < CB_BREAK ? Math.pow(cbPressP(t), 2) * 0.5 : 0;
  const flash = t >= CB_BREAK ? 1 - cbSmooth((t - CB_BREAK) / 0.85) : 0;
  return (
    <div style={{
      position: 'absolute', left: CB_CX - 380, top: 590 - 380, width: 760, height: 760,
      borderRadius: '50%', pointerEvents: 'none',
      background: `radial-gradient(circle, ${CB_PALETTE.amberGlow} 0%, rgba(205,138,75,0) 65%)`,
      opacity: Math.max(pre, flash),
    }} />
  );
}

function CBBurstRing({ t }) {
  const x = t - CB_BREAK;
  if (x < 0 || x > 0.9) return null;
  const p = x / 0.9;
  return (
    <svg width="1920" height="1080" viewBox="0 0 1920 1080"
      style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      <circle cx={CB_CX} cy="590" r={60 + 400 * Easing.easeOutCubic(p)} fill="none"
        stroke={CB_PALETTE.amber} strokeWidth={2 + 10 * (1 - p)} opacity={0.8 * (1 - p)} />
    </svg>
  );
}

// Slow motes in the headroom once there is headroom to drift in.
const CB_MOTES = Array.from({ length: 12 }, (_, i) => ({
  x: i % 2 === 0 ? 200 + cbRand(i, 4) * 420 : 1310 + cbRand(i, 4) * 420,
  ph: cbRand(i, 5),
  sp: 0.09 + cbRand(i, 6) * 0.07,
  r: 4 + cbRand(i, 7) * 4,
}));

function CBMotes({ t }) {
  const env = cbWindow(t, 5.6, 13.4, 1.2, 0.8);
  if (env <= 0.001) return null;
  return (
    <svg width="1920" height="1080" viewBox="0 0 1920 1080"
      style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {CB_MOTES.map((m, i) => {
        const u = (m.ph + (t - CB_BREAK) * m.sp) % 1;
        return (
          <circle key={i}
            cx={m.x + Math.sin(t * 0.9 + m.ph * 9) * 14} cy={610 - u * 480} r={m.r}
            fill={CB_PALETTE.moss400} opacity={env * Math.sin(Math.PI * u) * 0.5} />
        );
      })}
    </svg>
  );
}

// ── Words ──────────────────────────────────────────────────────────────────
function CBLabels({ t }) {
  const wixA = 0.62 - 0.3 * cbSmooth(cbP(t, 5.5, 6.5)) + 0.3 * cbSmooth(cbP(t, 13.0, 13.8));
  const shopA = 0.3 + 0.7 * cbSmooth(cbP(t, 7.6, 8.4)) - 0.7 * cbSmooth(cbP(t, 13.0, 13.8));
  const base = {
    position: 'absolute', left: 120,
    fontFamily: CB_FONTS.display, fontWeight: 600, fontSize: 96,
    letterSpacing: '-0.035em', lineHeight: 1, whiteSpace: 'nowrap',
    pointerEvents: 'none',
  };
  return (
    <>
      <div style={{ ...base, top: 300, color: CB_PALETTE.moss700, opacity: shopA }}>Shopify</div>
      <div style={{ ...base, top: 762, color: CB_PALETTE.ink, opacity: wixA }}>Wix</div>
    </>
  );
}

const CB_CAPTIONS = [
  { text: 'the old ceiling',   top: 676, a: 0.3,  b: 5.25, fi: 0.5,  fo: 0.35, color: CB_PALETTE.ink70 },
  { text: 'breaking through',  top: 536, a: 5.35, b: 8.1,  fi: 0.35, fo: 0.4,  color: CB_PALETTE.moss600 },
  { text: 'into the headroom', top: 300, a: 8.2,  b: 13.3, fi: 0.5,  fo: 0.4,  color: CB_PALETTE.moss700 },
];

function CBCaptions({ t }) {
  return (
    <>
      {CB_CAPTIONS.map((c, i) => {
        const a = cbWindow(t, c.a, c.b, c.fi, c.fo);
        if (a <= 0.01) return null;
        const rise = 1 - cbSmooth((t - c.a) / c.fi);
        return (
          <div key={i} style={{
            position: 'absolute', right: 80, top: c.top,
            transform: `translateY(${rise * 16}px)`,
            fontFamily: CB_FONTS.serif, fontStyle: 'italic', fontWeight: 400,
            fontSize: 76, lineHeight: 1, letterSpacing: '-0.01em',
            color: c.color, opacity: a, whiteSpace: 'nowrap', textAlign: 'right',
            pointerEvents: 'none',
          }}>
            {c.text}
          </div>
        );
      })}
    </>
  );
}

// ── Paper, grain, folio ────────────────────────────────────────────────────
function CBBackdrop({ t }) {
  const solid = cbStoreSolid(t);
  const lit = cbLit(t);
  return (
    <>
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse at 50% 30%, ${CB_PALETTE.creamLt} 0%, ${CB_PALETTE.cream} 55%, ${CB_PALETTE.creamDk} 100%)`,
      }} />
      <div style={{
        position: 'absolute', left: CB_CX - 620, top: -70 + CB_STORE_DY, width: 1240, height: 800,
        borderRadius: '50%', pointerEvents: 'none',
        background: 'radial-gradient(ellipse, rgba(215,225,212,0.95) 0%, rgba(215,225,212,0) 62%)',
        opacity: 0.45 + 0.55 * solid,
      }} />
      <div style={{
        position: 'absolute', left: CB_CX - 620, top: -70 + CB_STORE_DY, width: 1240, height: 800,
        borderRadius: '50%', pointerEvents: 'none',
        background: `radial-gradient(ellipse, ${CB_PALETTE.amberGlow} 0%, rgba(205,138,75,0) 60%)`,
        opacity: lit * 0.8 * (0.93 + 0.07 * Math.sin(t * 1.7)),
      }} />
    </>
  );
}

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

function CBFilmGrain() {
  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 CBFolio() {
  const mono = {
    position: 'absolute', fontFamily: CB_FONTS.mono, fontSize: 24,
    letterSpacing: '0.14em', color: CB_PALETTE.ink40, textTransform: 'uppercase',
    pointerEvents: 'none', whiteSpace: 'nowrap',
  };
  return (
    <>
      <div style={{ ...mono, left: 64, top: 52 }}>§ 03 · ceiling break</div>
      <div style={{ ...mono, left: 64, bottom: 44 }}>fig. 01 · wix to shopify</div>
    </>
  );
}

// ── Scene ──────────────────────────────────────────────────────────────────
function CeilingBreakScene() {
  const t = useTime();
  const main = cbMainShape(t);
  const fresh = cbNewcomer(t);

  // A short jolt when the ceiling gives.
  const jolt = t >= CB_BREAK && t < CB_BREAK + 0.4 ? 9 * (1 - (t - CB_BREAK) / 0.4) : 0;
  const shakeX = Math.sin(t * 95) * jolt;
  const shakeY = Math.cos(t * 83) * jolt * 0.6;

  return (
    <>
      <CBBackdrop t={t} />
      <div style={{ position: 'absolute', inset: 0, transform: `translate(${shakeX}px, ${shakeY}px)` }}>
        <CBMotes t={t} />
        <CBStore t={t} />
        <CBRoom t={t} />
        <CBLabels t={t} />
        <CBBurstGlow t={t} />
        <CBFloorShadow s={main} />
        <CBFloorShadow s={fresh} />
        <CBShapeBody s={main} />
        <CBShapeBody s={fresh} />
        <CBShards t={t} />
        <CBBurstRing t={t} />
        <CBCaptions t={t} />
      </div>
      <CBVignette />
      <CBFilmGrain />
      <CBFolio />
    </>
  );
}

Object.assign(window, {
  CeilingBreakScene,
  CB_PALETTE,
  CB_FONTS,
  CB_DURATION,
  CB_HOLD,
});
