// scenes-v4-b.jsx — Lead Delta steps 4-6 + AllScenes wiring
// Reads helpers (W, H, STEPS, etc.) from window, set by scenes-v4.jsx.

// ── Step 4: QUALIFICATION ──
// Concentric rings, 5 tick markers with score tickers, final composite "87"

function StepQualify({ time }) {
  const dur = STEPS[3].dur;
  const t = time - STEPS[3].start;
  if (t < 0 || t >= dur) return null;
  const op = stepOpacity(t, dur);

  const cx = CX, cy = STAGE_CY;
  const ticks = [
    { label: 'INSURANCE', score: 92, angle: -90 },
    { label: 'LIABILITY', score: 85, angle: -18 },
    { label: 'EVIDENCE',  score: 90, angle:  54 },
    { label: 'INJURY',    score: 74, angle: 126 },
    { label: 'STATUTE',   score: 46, angle: 198 },
  ];
  const ringRadii = [90, 165, 240, 320];
  const tickR = 340;

  // Phase 1 (0–1.6s): rings draw outward
  // Phase 2 (1.6–6s): ticks activate one at a time, ~0.9s each (radial line + score tick)
  // Phase 3 (6–8s): composite "87" appears in center

  // Core (becomes invisible during phase 3)
  const compositeStart = 3.5;
  const corePresent = t < compositeStart + 0.2;
  const coreOpacity = clamp((compositeStart + 0.2 - t) / 0.4, 0, 1);
  const corePulse = 0.7 + 0.3 * Math.sin(t * 3);

  // Rings
  const ringEls = ringRadii.map((r, i) => {
    const start = 0.1 + i * 0.25;
    const lt = clamp((t - start) / 0.5, 0, 1);
    if (lt <= 0) return null;
    return (
      <circle key={`ring${i}`} cx={cx} cy={cy} r={r * lt}
              fill="none" stroke="rgba(255,255,255,0.32)" strokeWidth={0.8}
              opacity={lt * 0.9} />
    );
  });

  // Ticks
  const tickStart = 0.7;
  const tickInterval = 0.5;
  const tickEls = [];
  ticks.forEach((tk, i) => {
    const ts = tickStart + i * tickInterval;
    const activeT = clamp((t - ts) / 0.7, 0, 1);
    if (activeT <= 0) return;
    const a = (tk.angle * Math.PI) / 180;
    const tx = cx + Math.cos(a) * tickR;
    const ty = cy + Math.sin(a) * tickR;
    // Radial line drawing
    const drawT = clamp((t - ts) / 0.4, 0, 1);
    const innerR = 28;
    const innerX = cx + Math.cos(a) * innerR;
    const innerY = cy + Math.sin(a) * innerR;
    const ex = innerX + (tx - innerX) * drawT;
    const ey = innerY + (ty - innerY) * drawT;
    // Score ticker
    const scoreT = clamp((t - ts - 0.2) / 0.6, 0, 1);
    const score = Math.round(scoreT * tk.score);
    // Tick mark dot
    const dotR = 3 * activeT;
    // Label position offset slightly outside
    const labelOffsetR = 40;
    const lx = cx + Math.cos(a) * (tickR + labelOffsetR);
    const ly = cy + Math.sin(a) * (tickR + labelOffsetR);
    // Determine text-anchor based on angle
    const cosA = Math.cos(a);
    const anchor = cosA > 0.3 ? 'start' : cosA < -0.3 ? 'end' : 'middle';
    tickEls.push(
      <g key={`tk${i}`} opacity={activeT}>
        <line x1={innerX} y1={innerY} x2={ex} y2={ey}
              stroke="white" strokeWidth={0.9} opacity={0.65} />
        <circle cx={tx} cy={ty} r={dotR} fill="white"
                style={{ filter: 'drop-shadow(0 0 5px rgba(255,255,255,0.8))' }} />
        <text x={lx} y={ly - 24}
              textAnchor={anchor}
              fill="rgba(255,255,255,0.7)"
              fontFamily="Oxanium, monospace" fontSize={20}
              fontWeight={600} letterSpacing="0.22em">
          {tk.label}
        </text>
        <text x={lx} y={ly + 28}
              textAnchor={anchor}
              fill="white"
              fontFamily="Oxanium, monospace" fontSize={42}
              fontWeight={700} letterSpacing="0.02em">
          {score}
        </text>
      </g>
    );
  });

  // Composite final "87" — pops out from center
  let composite = null;
  if (t >= compositeStart) {
    const ct = clamp((t - compositeStart) / 0.6, 0, 1);
    const flashT = clamp((t - compositeStart) / 0.5, 0, 1);
    // Bouncy pop-out: starts tiny (0), overshoots to ~1.15, settles to 1
    const scale = Easing.easeOutBack(ct);
    // Shockwave ring expanding outward
    const ringT = clamp((t - compositeStart) / 0.8, 0, 1);
    composite = (
      <g>
        {/* Shockwave ring */}
        {ringT < 1 && (
          <circle cx={cx} cy={cy} r={20 + ringT * 130}
                  fill="none" stroke="white"
                  strokeWidth={1.5}
                  opacity={(1 - ringT) * 0.7} />
        )}
        {/* Bright center flash */}
        {flashT < 1 && (
          <circle cx={cx} cy={cy} r={30 * (1 - flashT * 0.4)}
                  fill="white" opacity={(1 - flashT) * 0.85} />
        )}
        {/* The 87, scaled from center */}
        <g transform={`translate(${cx} ${cy}) scale(${scale}) translate(${-cx} ${-cy})`}
           style={{ filter: 'drop-shadow(0 0 22px rgba(255,255,255,0.85))' }}>
          <text x={cx} y={cy + 40}
                textAnchor="middle"
                fill="white"
                fontFamily="Oxanium, monospace" fontSize={200}
                fontWeight={700}
                opacity={ct}>
            87
          </text>
        </g>
      </g>
    );
  }

  return (
    <g opacity={op}>
      <StepHeader
        eyebrow="QUALIFICATION"
        h1="Every case scored across five dimensions."
        h2="Insurance coverage. Liability. Evidence. Injury severity. Statute of limitations. Evaluated in real time, during the call."
        opacity={1}
      />
      {ringEls}
      {tickEls}
      {/* Core dot */}
      {corePresent && (
        <g opacity={coreOpacity}>
          <circle cx={cx} cy={cy} r={6 * corePulse} fill="white" opacity={0.25} />
          <circle cx={cx} cy={cy} r={4} fill="white"
                  style={{ filter: 'drop-shadow(0 0 8px rgba(255,255,255,0.9))' }} />
        </g>
      )}
      {composite}
    </g>
  );
}

// ── Step 5: LEAD MANAGEMENT ──
// A single lead profile is scanned, then team members add tasks, comments,
// escalation timers, and document uploads.

// Shared layout so the lead card persists across the Step 5 → Step 6 boundary.
// Portrait layout: card centered horizontally, top of stage zone.
const LEAD_CARD = { x: (W - 820) / 2, y: STAGE_TOP + 30, w: 820, h: 560 };

function LeadProfileCard({ status, scanT = 1, cursor = null, files = [], activeTab = 'files' }) {
  const { x, y, w, h } = LEAD_CARD;
  const isSigned = status === 'SIGNED';
  const pillBg = isSigned ? '#fff' : 'rgba(255,255,255,0.06)';
  const pillStroke = isSigned ? '#fff' : 'rgba(255,255,255,0.55)';
  const pillFg = isSigned ? '#000' : '#fff';

  // ── Geometry ───────────────────────────────────────────────────────────
  // Header block: 0 → 76
  // Divider at 80
  // Case info rows: 96 → 184
  // Tab divider at 198, tab labels at 218
  // Files content: 240 → 304
  const dividerTopY = y + 110;
  const rowY        = y + 144;
  const rowH        = 38;
  const tabDivY     = y + 320;
  const tabY        = y + 354;
  const filesY      = y + 392;

  const rows = [
    ['SOURCE',    'Inbound call · Apr 24'],
    ['INCIDENT',  'Auto collision · I-405'],
    ['INSURANCE', 'State Farm'],
    ['STATUTE',   '2 yrs (exp Aug 2027)'],
  ];

  // Status pill — top-right, aligned with the name
  const pillW = 150, pillH = 38;
  const pillX = x + w - pillW - 22;
  const pillY = y + 28;
  const pillCx = pillX + pillW / 2;
  const pillCy = pillY + pillH / 2;

  // Tabs — right-aligned; FILES active
  const tabs = [
    { id: 'files',    label: 'FILES' },
    { id: 'notes',    label: 'NOTES' },
    { id: 'activity', label: 'ACTIVITY' },
  ];
  const tabW = 78;
  const tabBarRight = x + w - 14;
  const tabBarLeft  = tabBarRight - tabs.length * tabW;

  return (
    <g>
      <rect x={x} y={y} width={w} height={h} rx={6}
            fill="rgba(0,0,0,0.82)" stroke="white" strokeWidth={1.1} />

      {/* Avatar */}
      <circle cx={x + 42} cy={y + 54} r={24}
              fill="rgba(255,255,255,0.1)" stroke="white" strokeWidth={1} />
      <text x={x + 42} y={y + 62} textAnchor="middle"
            fill="white" fontFamily="Oxanium, monospace" fontSize={22}
            fontWeight={700} letterSpacing="0.08em">RM</text>

      {/* Name */}
      <text x={x + 78} y={y + 50}
            fill="white" fontFamily="Inter, system-ui, sans-serif" fontSize={32}
            fontWeight={500}>Roberto Mendes</text>

      {/* Score — rounded box below the name (replaces lead number) */}
      <g>
        <rect x={x + 78} y={y + 64} width={72} height={30} rx={6}
              fill="rgba(255,255,255,0.06)" stroke="white" strokeWidth={1.1} />
        <text x={x + 78 + 36} y={y + 86} textAnchor="middle"
              fill="white" fontFamily="Oxanium, monospace" fontSize={22}
              fontWeight={500} letterSpacing="0.04em">87</text>
      </g>

      {/* Lead # removed — score box sits here instead */}

      {/* Status pill — top right (click target in Step 6) */}
      <g style={isSigned ? { filter: 'drop-shadow(0 0 12px rgba(255,255,255,0.9))' } : null}>
        <rect x={pillX} y={pillY} width={pillW} height={pillH} rx={4}
              fill={pillBg} stroke={pillStroke} strokeWidth={1.3} />
        <text x={pillCx} y={pillY + 25} textAnchor="middle"
              fill={pillFg} fontFamily="Oxanium, monospace" fontSize={20}
              fontWeight={700} letterSpacing="0.24em">{status}</text>
      </g>

      {/* Divider above case info */}
      <line x1={x + 22} y1={dividerTopY} x2={x + w - 22} y2={dividerTopY}
            stroke="rgba(255,255,255,0.18)" strokeWidth={1} />

      {/* Case info rows */}
      {rows.map(([k, v], i) => (
        <g key={k}>
          <text x={x + 22} y={rowY + i * rowH}
                fill="rgba(255,255,255,0.55)"
                fontFamily="Oxanium, monospace" fontSize={16}
                fontWeight={600} letterSpacing="0.22em">{k}</text>
          <text x={x + w - 22} y={rowY + i * rowH} textAnchor="end"
                fill="white"
                fontFamily="Inter, system-ui, sans-serif" fontSize={24}
                fontWeight={400}>{v}</text>
        </g>
      ))}

      {/* Tab bar — evenly spaced across full width */}
      <line x1={x} y1={tabDivY} x2={x + w} y2={tabDivY}
            stroke="rgba(255,255,255,0.18)" strokeWidth={1} />
      {tabs.map((tb, i) => {
        const slotW = (w - 44) / tabs.length;
        const tcx = x + 22 + slotW * (i + 0.5);
        const isActive = tb.id === activeTab;
        return (
          <g key={tb.id}>
            <text x={tcx} y={tabY} textAnchor="middle"
                  fill={isActive ? 'white' : 'rgba(255,255,255,0.42)'}
                  fontFamily="Oxanium, monospace" fontSize={18}
                  fontWeight={isActive ? 700 : 500} letterSpacing="0.24em">{tb.label}</text>
            {isActive && (
              <line x1={tcx - 36} y1={tabY + 10} x2={tcx + 36} y2={tabY + 10}
                    stroke="white" strokeWidth={1.5} />
            )}
          </g>
        );
      })}

      {/* Tab content area */}
      <g>
        {activeTab === 'files' && (
          <g>
            {files.length === 0 && (
              <text x={x + w / 2} y={filesY + 28} textAnchor="middle"
                    fill="rgba(255,255,255,0.32)" fontFamily="Inter, system-ui, sans-serif"
                    fontSize={22} fontWeight={400} fontStyle="italic">
                Awaiting documents…
              </text>
            )}
            {files.map((f, i) => (
              <g key={i} transform={`translate(${x + 22}, ${filesY + i * 36})`}>
                <rect x={0} y={0} width={20} height={24} rx={2}
                      fill="rgba(255,255,255,0.08)" stroke="white" strokeWidth={0.9} />
                <polyline points="14,0 20,6 14,6 14,0" fill="rgba(255,255,255,0.18)" stroke="white" strokeWidth={0.7} />
                <text x={32} y={18}
                      fill="white"
                      fontFamily="Inter, system-ui, sans-serif" fontSize={22}
                      fontWeight={400}>{f.name}</text>
                <text x={w - 44} y={18} textAnchor="end"
                      fill="rgba(255,255,255,0.55)"
                      fontFamily="Oxanium, monospace" fontSize={18}
                      fontWeight={500} letterSpacing="0.08em">{f.size}</text>
              </g>
            ))}
          </g>
        )}
        {activeTab === 'activity' && (
          <g>
            <text x={x + w / 2} y={filesY + 28} textAnchor="middle"
                  fill="rgba(255,255,255,0.38)" fontFamily="Inter, system-ui, sans-serif"
                  fontSize={22} fontWeight={400} fontStyle="italic">
              Team feed shown in workspace →
            </text>
          </g>
        )}
      </g>
      {/* Scanning beam */}
      {scanT > 0 && scanT < 1 && (
        <g opacity={0.85}>
          <line x1={x + 4} y1={y + scanT * h} x2={x + w - 4} y2={y + scanT * h}
                stroke="white" strokeWidth={1.2}
                style={{ filter: 'drop-shadow(0 0 10px rgba(255,255,255,0.95))' }} />
        </g>
      )}
      {/* Cursor pointer (used in Step 6) */}
      {cursor && (
        <g transform={`translate(${cursor.x}, ${cursor.y})`} opacity={cursor.op ?? 1}>
          <path d="M0 0 L0 16 L4 12 L7 19 L10 18 L7 11 L13 11 Z"
                fill="white" stroke="black" strokeWidth={0.8} />
        </g>
      )}
    </g>
  );
}

function ActivityItem({ item, t, x, y, w, h, appearT }) {
  const isDoc = item.kind === 'upload';
  const avX = x + 26, avY = y + 28, avR = 20;
  return (
    <g opacity={appearT}>
      <rect x={x} y={y} width={w} height={h} rx={6}
            fill={isDoc ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.025)'}
            stroke={isDoc ? 'white' : 'rgba(255,255,255,0.32)'}
            strokeWidth={isDoc ? 1.3 : 1}
            style={isDoc ? { filter: 'drop-shadow(0 0 8px rgba(255,255,255,0.35))' } : null} />
      <circle cx={avX} cy={avY} r={avR}
              fill="rgba(255,255,255,0.1)" stroke="white" strokeWidth={1} />
      <text x={avX} y={avY + 6} textAnchor="middle"
            fill="white" fontFamily="Oxanium, monospace" fontSize={18}
            fontWeight={700} letterSpacing="0.08em">{item.by}</text>
      <ActivityBody item={item} t={t} x={x + 60} y={y} w={w - 60} h={h} />
    </g>
  );
}

function ActivityBody({ item, t, x, y, w }) {
  if (item.kind === 'task') {
    return (
      <g>
        <text x={x} y={y + 24} fill="rgba(255,255,255,0.55)"
              fontFamily="Oxanium, monospace" fontSize={17}
              fontWeight={600} letterSpacing="0.22em">TASK · {item.name.toUpperCase()}</text>
        <g transform={`translate(${x}, ${y + 44})`}>
          <rect x={0} y={0} width={18} height={18} rx={3}
                fill="transparent" stroke="white" strokeWidth={1.2} />
        </g>
        <text x={x + 28} y={y + 60}
              fill="white" fontFamily="Inter, system-ui, sans-serif" fontSize={24}
              fontWeight={400}>{item.title}</text>
        <g transform={`translate(${x + w - 160}, ${y + 44})`}>
          <rect x={0} y={0} width={144} height={26} rx={4}
                fill="rgba(255,255,255,0.08)" stroke="rgba(255,255,255,0.5)" strokeWidth={1} />
          <text x={72} y={18} textAnchor="middle"
                fill="white" fontFamily="Oxanium, monospace" fontSize={15}
                fontWeight={600} letterSpacing="0.16em">{item.meta}</text>
        </g>
      </g>
    );
  }
  if (item.kind === 'comment') {
    return (
      <g>
        <text x={x} y={y + 24} fill="rgba(255,255,255,0.55)"
              fontFamily="Oxanium, monospace" fontSize={17}
              fontWeight={600} letterSpacing="0.22em">COMMENT · {item.name.toUpperCase()}</text>
        <g transform={`translate(${x}, ${y + 42})`}>
          <IconStroke d={ICON.comment} size={26} />
        </g>
        <text x={x + 32} y={y + 60}
              fill="white" fontFamily="Inter, system-ui, sans-serif" fontSize={24}
              fontWeight={400} fontStyle="italic">&ldquo;{item.title}&rdquo;</text>
      </g>
    );
  }
  if (item.kind === 'timer') {
    const totalSec = Math.max(0, 4 * 3600 - Math.floor(Math.max(0, t) * 600));
    const hh = String(Math.floor(totalSec / 3600)).padStart(2, '0');
    const mm = String(Math.floor((totalSec % 3600) / 60)).padStart(2, '0');
    const ss = String(totalSec % 60).padStart(2, '0');
    const pulse = 0.5 + 0.5 * Math.sin(t * 4);
    return (
      <g>
        <text x={x} y={y + 24} fill="rgba(255,255,255,0.55)"
              fontFamily="Oxanium, monospace" fontSize={17}
              fontWeight={600} letterSpacing="0.22em">ESCALATION · {item.name.toUpperCase()}</text>
        <g transform={`translate(${x}, ${y + 42})`}>
          <IconStroke d={ICON.timer} size={26} />
        </g>
        <text x={x + 32} y={y + 60}
              fill="white" fontFamily="Inter, system-ui, sans-serif" fontSize={24}
              fontWeight={400}>{item.title}</text>
        <text x={x + w - 12} y={y + 62} textAnchor="end"
              fill="white" fontFamily="Oxanium, monospace" fontSize={32}
              fontWeight={300} letterSpacing="0.08em"
              style={{ filter: `drop-shadow(0 0 ${4 + pulse * 4}px rgba(255,255,255,${0.45 + pulse * 0.4}))` }}>
          {hh}:{mm}:{ss}
        </text>
      </g>
    );
  }
  if (item.kind === 'upload') {
    const prog = clamp(Math.max(0, t) / 1.2, 0, 1);
    const done = prog >= 1;
    const barW = w - 76 - 24;
    return (
      <g>
        <text x={x} y={y + 18} fill="white"
              fontFamily="Oxanium, monospace" fontSize={15.2}
              fontWeight={700} letterSpacing="0.24em">DOCUMENT UPLOAD · {item.name.toUpperCase()}</text>
        {/* PDF tile */}
        <g transform={`translate(${x}, ${y + 28})`}>
          <rect x={0} y={0} width={56} height={64} rx={3}
                fill="rgba(255,255,255,0.1)" stroke="white" strokeWidth={1.2} />
          <polyline points="40,0 56,0 56,16 40,16" fill="rgba(255,255,255,0.2)" stroke="white" strokeWidth={1} />
          <line x1={40} y1={0} x2={40} y2={16} stroke="white" strokeWidth={1} />
          <line x1={40} y1={16} x2={56} y2={16} stroke="white" strokeWidth={1} />
          <text x={20} y={38} textAnchor="middle"
                fill="white" fontFamily="Oxanium, monospace" fontSize={16}
                fontWeight={700} letterSpacing="0.14em">PDF</text>
          <line x1={8} y1={48} x2={48} y2={48} stroke="rgba(255,255,255,0.55)" strokeWidth={1} />
          <line x1={8} y1={54} x2={36} y2={54} stroke="rgba(255,255,255,0.55)" strokeWidth={1} />
        </g>
        <text x={x + 70} y={y + 50}
              fill="white" fontFamily="Inter, system-ui, sans-serif" fontSize={24}
              fontWeight={500}>{item.title}</text>
        <text x={x + 70} y={y + 68}
              fill="rgba(255,255,255,0.6)" fontFamily="Inter, system-ui, sans-serif" fontSize={17.6}
              fontWeight={400}>{item.meta} · Police report · Attached to case file</text>
        <g transform={`translate(${x + 70}, ${y + 78})`}>
          <rect x={0} y={0} width={barW} height={5} rx={2.5}
                fill="rgba(255,255,255,0.1)" stroke="rgba(255,255,255,0.3)" strokeWidth={0.6} />
          <rect x={0} y={0} width={barW * prog} height={5} rx={2.5}
                fill="white" />
        </g>
        {done && (
          <g transform={`translate(${x + w - 28}, ${y + 36})`}>
            <circle cx={0} cy={0} r={11} fill="white" />
            <path d="M-5,0 L-1,4 L5,-4" stroke="black" strokeWidth={1.8} fill="none" />
          </g>
        )}
      </g>
    );
  }
  return null;
}

function StepTeam({ time }) {
  const dur = STEPS[4].dur;
  const t = time - STEPS[4].start;
  if (t < 0 || t >= dur) return null;
  const op = stepOpacity(t, dur);

  const scanT = clamp(t / 1.4, 0, 1);

  const feedX = 70;
  const feedY = LEAD_CARD.y + LEAD_CARD.h + 60;
  const feedW = W - 140;

  const items = [
    { kind: 'task',    appear: 1.0, by: 'AP', name: 'A. Patel',
      title: 'Order ER medical records', meta: 'DUE APR 28' },
    { kind: 'comment', appear: 2.3, by: 'SK', name: 'S. Kim',
      title: 'Spoke with adjuster — liability accepted.' },
    { kind: 'timer',   appear: 3.6, by: 'JC', name: 'J. Chen',
      title: 'SLA: first contact with client' },
    { kind: 'upload',  appear: 5.0, by: 'MR', name: 'M. Rivera',
      title: 'PoliceReport_I405.pdf', meta: '2.4 MB' },
  ];

  const itemH = it => it.kind === 'upload' ? 140 : 88;
  const gap = 18;
  let yCursor = feedY + 56;
  items.forEach(it => { it.slotY = yCursor; yCursor += itemH(it) + gap; });

  return (
    <g opacity={op}>
      <StepHeader
        eyebrow="LEAD MANAGEMENT"
        h1="Every lead, fully owned."
        h2="Your team works the lead together — tasks, comments, escalation timers and case docs all live on the lead itself."
        opacity={1}
      />
      <LeadProfileCard status="ACTIVE" scanT={scanT} activeTab="activity"
                       files={t >= 7.9 ? [{ name: 'PoliceReport_I405.pdf', size: '2.4 MB' }] : []} />
      <text x={feedX} y={feedY + 22}
            fill="rgba(255,255,255,0.55)"
            fontFamily="Oxanium, monospace" fontSize={20}
            fontWeight={600} letterSpacing="0.24em">
        ACTIVITY
      </text>
      <line x1={feedX} y1={feedY + 34} x2={feedX + feedW} y2={feedY + 34}
            stroke="rgba(255,255,255,0.18)" strokeWidth={1} />
      {items.map((it, i) => {
        const aT = clamp((t - it.appear) / 0.45, 0, 1);
        if (aT <= 0) return null;
        const ih = itemH(it);
        const slideOff = (1 - Easing.easeOutCubic(aT)) * 14;
        return (
          <g key={i} transform={`translate(0, ${slideOff})`}>
            <ActivityItem item={it} t={t - it.appear} x={feedX} y={it.slotY} w={feedW} h={ih} appearT={aT} />
          </g>
        );
      })}
    </g>
  );
}


// ── Step 6: AUTOMATION & SYNC ──
// Core "LEAD STATUS: SIGNED" → 3 branches (SMS, EMAIL, CAL) → timeline → CRM cube fills.

function StepWorkflow({ time }) {
  const dur = STEPS[5].dur;
  const t = time - STEPS[5].start;
  if (t < 0 || t >= dur) return null;
  const op = stepOpacity(t, dur);

  // Phases:
  //   0.0 – 0.8s : lead card holds (carries over from step 5, status still ACTIVE)
  //   0.8 – 1.5s : cursor flies in toward the status pill
  //   1.5 – 1.8s : click — status flashes from ACTIVE → SIGNED
  //   1.8 – 4.5s : branches grow from card's right edge
  //   4.5 – end  : follow-up timeline below

  const clickAt = 1.5;
  const status = t >= clickAt ? 'SIGNED' : 'ACTIVE';

  // Cursor — start off-screen bottom-right, settle on status pill
  const cursorStart = 0.8;
  const cursorT = clamp((t - cursorStart) / 0.7, 0, 1);
  const cursorEnd = clamp((t - clickAt - 0.4) / 0.5, 0, 1); // fade out after click
  const startX = LEAD_CARD.x + LEAD_CARD.w + 240;
  const startY = LEAD_CARD.y + 240;
  // Click target: status pill at top-right of the lead card
  const endX = LEAD_CARD.x + LEAD_CARD.w - 97;
  const endY = LEAD_CARD.y + 47;
  const cx = lerp(startX, endX, Easing.easeInOutCubic(cursorT));
  const cy = lerp(startY, endY, Easing.easeInOutCubic(cursorT));
  const cursorOp = cursorT * (1 - cursorEnd);
  // Click ring
  let clickRing = null;
  const clickRingT = clamp((t - clickAt) / 0.45, 0, 1);
  if (clickRingT > 0 && clickRingT < 1) {
    clickRing = (
      <circle cx={LEAD_CARD.x + LEAD_CARD.w - 97} cy={LEAD_CARD.y + 47}
              r={10 + clickRingT * 32}
              fill="none" stroke="white" strokeWidth={1.4}
              opacity={1 - clickRingT} />
    );
  }

  // Branches — pop DOWN from the bottom edge of the lead card as a 3-col row
  const branches = [
    { kind: 'sms',
      title: 'SMS', body: 'Welcome to firm. Retainer link sent.',
      icon: ICON.sms },
    { kind: 'email',
      title: 'EMAIL', body: 'Your case file. What happens next.',
      icon: ICON.email },
    { kind: 'cal',
      title: 'CALENDAR', body: 'Follow-up call: Apr 30, 2pm',
      icon: ICON.cal },
  ];
  const branchStart = 1.9;
  const branchEls = [];
  const rowGap = 16;
  const cardW = (LEAD_CARD.w - rowGap * 2) / 3;
  const cardH = 150;
  const rowY = LEAD_CARD.y + LEAD_CARD.h + 60;
  const trunkY = LEAD_CARD.y + LEAD_CARD.h;
  const trunkMidY = trunkY + 30;
  branches.forEach((b, i) => {
    const startT = branchStart + i * 0.22;
    const lineT = clamp((t - startT) / 0.5, 0, 1);
    if (lineT <= 0) return;
    const tx = LEAD_CARD.x + i * (cardW + rowGap);
    const ty = rowY;
    const ax = LEAD_CARD.x + LEAD_CARD.w / 2;
    const ay = trunkY;
    const bx = tx + cardW / 2;
    const by = ty;
    // L-shape: down → over → down
    const ey1 = ay + (trunkMidY - ay) * clamp(lineT * 2, 0, 1);
    const ex2 = lineT > 0.5 ? ax + (bx - ax) * clamp((lineT - 0.5) * 2, 0, 1) : ax;
    const ey2 = trunkMidY;
    const ex3 = lineT > 0.66 ? bx : ex2;
    const ey3 = lineT > 0.66 ? trunkMidY + (by - trunkMidY) * clamp((lineT - 0.66) * 3, 0, 1) : ey2;
    branchEls.push(
      <g key={`br${i}`}>
        <polyline points={`${ax},${ay} ${ax},${ey1} ${ex2},${ey2} ${ex3},${ey3}`}
                  fill="none" stroke="white" strokeWidth={1} opacity={0.55} />
      </g>
    );
    const cardT = clamp((t - startT - 0.3) / 0.4, 0, 1);
    if (cardT <= 0) return;
    const typeT = clamp((t - startT - 0.5) / 0.7, 0, 1);
    const bodyShown = b.body.slice(0, Math.floor(b.body.length * typeT));
    branchEls.push(
      <g key={`brc${i}`} opacity={cardT}>
        <rect x={tx} y={ty} width={cardW} height={cardH} rx={6}
              fill="rgba(0,0,0,0.85)" stroke="white" strokeWidth={1.1} />
        <g transform={`translate(${tx + 16}, ${ty + 14})`}>
          <IconStroke d={b.icon} size={32} />
        </g>
        <text x={tx + 58} y={ty + 32}
              fill="rgba(255,255,255,0.65)"
              fontFamily="Oxanium, monospace" fontSize={16}
              fontWeight={600} letterSpacing="0.22em">{b.title}</text>
        <foreignObject x={tx + 16} y={ty + 50} width={cardW - 32} height={cardH - 56}>
          <div style={{
            color: 'white',
            fontFamily: 'Inter, system-ui, sans-serif',
            fontSize: 17,
            fontWeight: 400,
            lineHeight: 1.3,
          }}>
            {bodyShown}
            {typeT < 1 && Math.floor(t * 6) % 2 === 0 ? '▍' : ''}
          </div>
        </foreignObject>
      </g>
    );
  });

  // Timeline — placed BELOW the branch cards.
  const timelineY = rowY + cardH + 160;
  const timelineX = 70;
  const timelineW = W - 140;
  const days = [
    { label: 'DAY 0', pos: 0.0, icon: ICON.sms   },
    { label: 'DAY 1', pos: 1/3, icon: ICON.email },
    { label: 'DAY 5', pos: 2/3, icon: ICON.sms   },
    { label: 'DAY 7', pos: 1.0, icon: ICON.email },
  ];
  const trackAppear = 4.6;
  const timelineEls = [];
  if (t >= trackAppear) {
    const trackT = clamp((t - trackAppear) / 0.4, 0, 1);
    timelineEls.push(
      <line key="track" x1={timelineX} y1={timelineY}
            x2={timelineX + timelineW * trackT} y2={timelineY}
            stroke="rgba(255,255,255,0.3)" strokeWidth={1} />
    );
  }
  if (t >= trackAppear + 0.4) {
    days.forEach((d, i) => {
      const dt = clamp((t - trackAppear - 0.4 - i * 0.4) / 0.4, 0, 1);
      if (dt <= 0) return;
      const dx = timelineX + timelineW * d.pos;
      timelineEls.push(
        <g key={`dy${i}`}>
          <g transform={`translate(${dx - 40}, ${timelineY - 105})`} opacity={dt}>
            <rect x={0} y={0} width={80} height={80} rx={9}
                  fill="rgba(0,0,0,0.85)" stroke="white" strokeWidth={1.1}
                  style={{ filter: `drop-shadow(0 0 ${6 * dt}px rgba(255,255,255,0.5))` }} />
            <g transform="translate(20, 20)">
              <IconStroke d={d.icon} size={40} />
            </g>
          </g>
          <line x1={dx} y1={timelineY - 25} x2={dx} y2={timelineY - 8}
                stroke="rgba(255,255,255,0.45)" strokeWidth={0.8} opacity={dt} />
          <circle cx={dx} cy={timelineY} r={6 * dt} fill="white"
                  style={{ filter: `drop-shadow(0 0 6px rgba(255,255,255,0.8))` }} />
          <text x={dx} y={timelineY + 32} textAnchor="middle"
                fill="rgba(255,255,255,0.7)"
                fontFamily="Oxanium, monospace" fontSize={22}
                fontWeight={600} letterSpacing="0.22em"
                opacity={dt}>{d.label}</text>
        </g>
      );
    });
  }

  return (
    <g opacity={op}>
      <StepHeader
        eyebrow="AUTOMATED FOLLOW-UP"
        h1="Sign the lead, the cadence starts."
        h2="Status flips to SIGNED — and Lead Delta fires the SMS, email and calendar cadence automatically."
        opacity={1}
      />
      <LeadProfileCard status={status} activeTab="files"
                       files={[
                         { name: 'PoliceReport_I405.pdf', size: '2.4 MB' },
                         { name: 'ER_intake_form.pdf', size: '1.1 MB' },
                       ]}
                       cursor={cursorOp > 0.01 ? { x: cx, y: cy, op: cursorOp } : null} />
      {clickRing}
      {branchEls}
      {timelineEls}
    </g>
  );
}


// ── AllScenes — orchestrator ──

function AllScenes() {
  const time = useTime();
  // Subtle vignette overlay handled by container; just render scenes here.
  return (
    <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`}
         style={{ display: 'block' }}>
      <defs>
        <radialGradient id="vg" cx="50%" cy="50%" r="70%">
          <stop offset="0%" stopColor="#0a0a0a" />
          <stop offset="100%" stopColor="#000" />
        </radialGradient>
      </defs>
      <rect width={W} height={H} fill="url(#vg)" />
      <AmbientField time={time} />
      <StepProblem time={time} />
      <StepPlatform time={time} />
      <StepProfile time={time} />
      <StepQualify time={time} />
      <StepTeam time={time} />
      <StepWorkflow time={time} />
      <ClosingFrame time={time} />
    </svg>
  );
}

window.AllScenes = AllScenes;
