// 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 t = time - STEPS[3].start;
  if (t < -0.4 || t >= STEP_DUR + 0.4) return null;
  const op = stepOpacity(t, STEP_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 = [40, 75, 110, 145];
  const tickR = 175;

  // 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 = 6.0;
  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 = 1.8;
  const tickInterval = 0.85;
  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 = 14;
    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 = 36;
    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 - 4}
              textAnchor={anchor}
              fill="rgba(255,255,255,0.6)"
              fontFamily="Oxanium, monospace" fontSize={9}
              fontWeight={600} letterSpacing="0.22em">
          {tk.label}
        </text>
        <text x={lx} y={ly + 14}
              textAnchor={anchor}
              fill="white"
              fontFamily="Oxanium, monospace" fontSize={22}
              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 + 22}
                textAnchor="middle"
                fill="white"
                fontFamily="Oxanium, monospace" fontSize={84}
                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.
const LEAD_CARD = { x: 70, y: STAGE_TOP + 8, w: 360, h: 308 };

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 + 80;
  const rowY        = y + 100;
  const rowH        = 22;
  const tabDivY     = y + 200;
  const tabY        = y + 218;
  const filesY      = y + 244;

  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 = 96, pillH = 26;
  const pillX = x + w - pillW - 14;
  const pillY = y + 22;
  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 + 30} cy={y + 38} r={16}
              fill="rgba(255,255,255,0.1)" stroke="white" strokeWidth={1} />
      <text x={x + 30} y={y + 43} textAnchor="middle"
            fill="white" fontFamily="Oxanium, monospace" fontSize={11}
            fontWeight={700} letterSpacing="0.08em">RM</text>

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

      {/* Score — rounded box below the name (replaces lead number) */}
      <g>
        <rect x={x + 56} y={y + 42} width={56} height={22} rx={5}
              fill="rgba(255,255,255,0.06)" stroke="white" strokeWidth={1.1} />
        <text x={x + 56 + 28} y={y + 58} textAnchor="middle"
              fill="white" fontFamily="Oxanium, monospace" fontSize={13}
              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={3}
              fill={pillBg} stroke={pillStroke} strokeWidth={1.2} />
        <text x={pillCx} y={pillY + 17} textAnchor="middle"
              fill={pillFg} fontFamily="Oxanium, monospace" fontSize={10.5}
              fontWeight={700} letterSpacing="0.24em">{status}</text>
      </g>

      {/* Divider above case info */}
      <line x1={x + 16} y1={dividerTopY} x2={x + w - 16} 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 + 16} y={rowY + i * rowH}
                fill="rgba(255,255,255,0.5)"
                fontFamily="Oxanium, monospace" fontSize={8.5}
                fontWeight={600} letterSpacing="0.22em">{k}</text>
          <text x={x + w - 16} y={rowY + i * rowH} textAnchor="end"
                fill="white"
                fontFamily="Inter, system-ui, sans-serif" fontSize={12.5}
                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 - 32) / tabs.length;
        const tcx = x + 16 + 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={9.5}
                  fontWeight={isActive ? 700 : 500} letterSpacing="0.24em">{tb.label}</text>
            {isActive && (
              <line x1={tcx - 26} y1={tabY + 7} x2={tcx + 26} y2={tabY + 7}
                    stroke="white" strokeWidth={1.5} />
            )}
          </g>
        );
      })}

      {/* Tab content area */}
      <g>
        {activeTab === 'files' && (
          <g>
            {files.length === 0 && (
              <text x={x + w / 2} y={filesY + 22} textAnchor="middle"
                    fill="rgba(255,255,255,0.32)" fontFamily="Inter, system-ui, sans-serif"
                    fontSize={11.5} fontWeight={400} fontStyle="italic">
                Awaiting documents…
              </text>
            )}
            {files.map((f, i) => (
              <g key={i} transform={`translate(${x + 16}, ${filesY + i * 22})`}>
                <rect x={0} y={0} width={14} height={16} rx={1.5}
                      fill="rgba(255,255,255,0.08)" stroke="white" strokeWidth={0.9} />
                <polyline points="10,0 14,4 10,4 10,0" fill="rgba(255,255,255,0.18)" stroke="white" strokeWidth={0.7} />
                <text x={22} y={12}
                      fill="white"
                      fontFamily="Inter, system-ui, sans-serif" fontSize={11.5}
                      fontWeight={400}>{f.name}</text>
                <text x={w - 32} y={12} textAnchor="end"
                      fill="rgba(255,255,255,0.55)"
                      fontFamily="Oxanium, monospace" fontSize={9}
                      fontWeight={500} letterSpacing="0.08em">{f.size}</text>
              </g>
            ))}
          </g>
        )}
        {activeTab === 'activity' && (
          <g>
            <text x={x + w / 2} y={filesY + 22} textAnchor="middle"
                  fill="rgba(255,255,255,0.38)" fontFamily="Inter, system-ui, sans-serif"
                  fontSize={11.5} 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 + 18, avY = y + 18, avR = 14;
  return (
    <g opacity={appearT}>
      <rect x={x} y={y} width={w} height={h} rx={5}
            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 + 4} textAnchor="middle"
            fill="white" fontFamily="Oxanium, monospace" fontSize={9}
            fontWeight={700} letterSpacing="0.08em">{item.by}</text>
      <ActivityBody item={item} t={t} x={x + 44} y={y} w={w - 44} h={h} />
    </g>
  );
}

function ActivityBody({ item, t, x, y, w }) {
  if (item.kind === 'task') {
    return (
      <g>
        <text x={x} y={y + 16} fill="rgba(255,255,255,0.5)"
              fontFamily="Oxanium, monospace" fontSize={8.5}
              fontWeight={600} letterSpacing="0.22em">TASK · {item.name.toUpperCase()}</text>
        <g transform={`translate(${x}, ${y + 30})`}>
          <rect x={0} y={0} width={14} height={14} rx={2}
                fill="transparent" stroke="white" strokeWidth={1.2} />
        </g>
        <text x={x + 22} y={y + 42}
              fill="white" fontFamily="Inter, system-ui, sans-serif" fontSize={13}
              fontWeight={400}>{item.title}</text>
        <g transform={`translate(${x + w - 100}, ${y + 30})`}>
          <rect x={0} y={0} width={88} height={18} rx={3}
                fill="rgba(255,255,255,0.08)" stroke="rgba(255,255,255,0.5)" strokeWidth={1} />
          <text x={44} y={13} textAnchor="middle"
                fill="white" fontFamily="Oxanium, monospace" fontSize={9}
                fontWeight={600} letterSpacing="0.2em">{item.meta}</text>
        </g>
      </g>
    );
  }
  if (item.kind === 'comment') {
    return (
      <g>
        <text x={x} y={y + 16} fill="rgba(255,255,255,0.5)"
              fontFamily="Oxanium, monospace" fontSize={8.5}
              fontWeight={600} letterSpacing="0.22em">COMMENT · {item.name.toUpperCase()}</text>
        <g transform={`translate(${x}, ${y + 30})`}>
          <IconStroke d={ICON.comment} size={14} />
        </g>
        <text x={x + 22} y={y + 42}
              fill="white" fontFamily="Inter, system-ui, sans-serif" fontSize={13}
              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 + 16} fill="rgba(255,255,255,0.5)"
              fontFamily="Oxanium, monospace" fontSize={8.5}
              fontWeight={600} letterSpacing="0.22em">ESCALATION · {item.name.toUpperCase()}</text>
        <g transform={`translate(${x}, ${y + 30})`}>
          <IconStroke d={ICON.timer} size={14} />
        </g>
        <text x={x + 22} y={y + 42}
              fill="white" fontFamily="Inter, system-ui, sans-serif" fontSize={13}
              fontWeight={400}>{item.title}</text>
        <text x={x + w - 12} y={y + 42} textAnchor="end"
              fill="white" fontFamily="Oxanium, monospace" fontSize={16}
              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={9.5}
              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={10}
                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={15}
              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={11}
              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.4 || t >= dur + 0.4) return null;
  const op = stepOpacity(t, dur);

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

  const feedX = LEAD_CARD.x + LEAD_CARD.w + 36;
  const feedY = LEAD_CARD.y;
  const feedW = W - feedX - 60;

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

  const itemH = it => it.kind === 'upload' ? 104 : 60;
  const gap = 12;
  let yCursor = feedY + 38;
  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 + 18}
            fill="rgba(255,255,255,0.55)"
            fontFamily="Oxanium, monospace" fontSize={9}
            fontWeight={600} letterSpacing="0.24em">
        ACTIVITY
      </text>
      <line x1={feedX} y1={feedY + 26} x2={feedX + feedW} y2={feedY + 26}
            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.4 || t >= dur + 0.4) 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 - 62;
  const endY = LEAD_CARD.y + 35;
  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 - 62} cy={LEAD_CARD.y + 35}
              r={6 + clickRingT * 24}
              fill="none" stroke="white" strokeWidth={1.2}
              opacity={1 - clickRingT} />
    );
  }

  // Branches — extend from the right edge of the lead card (mid-height)
  const rootX = LEAD_CARD.x + LEAD_CARD.w;
  const rootY = LEAD_CARD.y + LEAD_CARD.h / 2;
  const branches = [
    { dx: 110, dy: -70, kind: 'sms',
      title: 'SMS', body: 'Welcome to firm. Retainer link sent.',
      icon: ICON.sms },
    { dx: 110, dy:   0, kind: 'email',
      title: 'EMAIL', body: 'Your case file. What happens next.',
      icon: ICON.email },
    { dx: 110, dy:  70, kind: 'cal',
      title: 'CALENDAR', body: 'Follow-up call: Apr 30, 2pm',
      icon: ICON.cal },
  ];
  const branchStart = 1.9;
  const branchEls = [];
  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 = rootX + b.dx;
    const ty = rootY + b.dy;
    const cardW = 240, cardH = 50;
    const ax = rootX;
    const ay = rootY;
    const bx = tx;
    const by = ty;
    const midX = (ax + bx) / 2;
    const ex = ax + (midX - ax) * lineT;
    const ey = ay;
    const ex2 = lineT > 0.5 ? midX : ex;
    const ey2 = lineT > 0.5 ? ay + (by - ay) * (lineT - 0.5) * 2 : ey;
    const ex3 = lineT > 0.5 ? midX + (bx - midX) * clamp((lineT - 0.5) * 2, 0, 1) : ex2;
    const ey3 = ey2;
    branchEls.push(
      <g key={`br${i}`}>
        <polyline points={`${ax},${ay} ${ex},${ey} ${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 - cardH / 2} width={cardW} height={cardH} rx={6}
              fill="rgba(0,0,0,0.85)" stroke="white" strokeWidth={1.1} />
        <g transform={`translate(${tx + 12}, ${ty - 10})`}>
          <IconStroke d={b.icon} size={18} />
        </g>
        <text x={tx + 40} y={ty - 6}
              fill="rgba(255,255,255,0.55)"
              fontFamily="Oxanium, monospace" fontSize={8.5}
              fontWeight={600} letterSpacing="0.22em">{b.title}</text>
        <text x={tx + 40} y={ty + 11}
              fill="white"
              fontFamily="Inter, system-ui, sans-serif" fontSize={11}
              fontWeight={400}>
          {bodyShown}
          {typeT < 1 && Math.floor(t * 6) % 2 === 0 ? <tspan>▌</tspan> : null}
        </text>
      </g>
    );
  });

  // Timeline — placed to the RIGHT of the lead card so it does not overlap.
  const timelineY = STAGE_TOP + STAGE_H - 70;
  const timelineX = LEAD_CARD.x + LEAD_CARD.w + 40;
  const timelineW = W - timelineX - 40;
  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 - 18}, ${timelineY - 60})`} opacity={dt}>
            <rect x={0} y={0} width={36} height={36} rx={5}
                  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(8, 8)">
              <IconStroke d={d.icon} size={20} />
            </g>
          </g>
          <line x1={dx} y1={timelineY - 24} x2={dx} y2={timelineY - 6}
                stroke="rgba(255,255,255,0.45)" strokeWidth={0.8} opacity={dt} />
          <circle cx={dx} cy={timelineY} r={5 * dt} fill="white"
                  style={{ filter: `drop-shadow(0 0 6px rgba(255,255,255,0.8))` }} />
          <text x={dx} y={timelineY + 22} textAnchor="middle"
                fill="rgba(255,255,255,0.7)"
                fontFamily="Oxanium, monospace" fontSize={11}
                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;
