/* Vooice — Outbound Call with scrubber + phases.
   New: play/pause, scrubber, "are you AI?" honesty handoff phase, animated read-back.
*/

const PHASES = [
  { id: 'dial',      label: 'Dialing',         start:   0, color: '#6A655C' },
  { id: 'connect',   label: 'Connected',       start: 2.4, color: '#0E0E0F' },
  { id: 'request',   label: 'Stating purpose', start: 6.4, color: '#0E0E0F' },
  { id: 'options',   label: 'Hearing options', start: 13.5,color: '#0E0E0F' },
  { id: 'readback',  label: 'Slot read-back',  start: 20.0,color: '#F04E23' },
  { id: 'honesty',   label: 'Are you AI?',     start: 30.0,color: '#F04E23' },
  { id: 'handoff',   label: 'Dialing user in', start: 36.0,color: '#F04E23' },
  { id: 'resume',    label: 'Resumed',         start: 44.0,color: '#7A8A6E' },
  { id: 'wrap',      label: 'Wrapping up',     start: 52.0,color: '#7A8A6E' },
  { id: 'closed',    label: 'Closed',          start: 58.0,color: '#7A8A6E' },
];

const SCRIPT_LINES_V2 = [
  { t: 0,    who: 'sys',    text: 'Outbound call placed → Bayview Hair Studio · +1 (415) 555-0142' },
  { t: 2.4,  who: 'sys',    text: 'Connected · 3 rings' },
  { t: 3.0,  who: 'callee', text: 'Bayview Hair Studio, this is Marcus, how can I help you?' },
  { t: 6.4,  who: 'vooice', text: "Hi Marcus — this is Vooice, calling on behalf of Jordan Reyes. Jordan would like to book a haircut sometime this week, ideally Wednesday or Thursday afternoon." },
  { t: 13.5, who: 'callee', text: 'Sure, let me check… we have Wednesday at 3:30 with Lina, or Thursday at 2 with Marcus — that\u2019s me.' },
  { t: 20.0, who: 'vooice', text: "Thursday at 2 with you works for Jordan's calendar. Could you confirm that's a 45-minute slot, and you're on the books as Marcus Wu?" },
  { t: 26.5, who: 'callee', text: 'Yep — wait, hold on. Are you, like, a real person?' },
  { t: 30.0, who: 'vooice', text: "Honest answer: I'm an AI assistant — Vooice — calling for Jordan. If it'd help, I can dial Jordan onto the line right now to confirm I'm working for them." },
  { t: 35.0, who: 'callee', text: "Yeah, please — that'd be great." },
  { t: 36.0, who: 'sys',    text: 'Dialing Jordan onto the line…' },
  { t: 39.5, who: 'sys',    text: 'Jordan joined · 3-way' },
  { t: 40.0, who: 'jordan', text: "Hey Marcus, yeah — Vooice is mine, she's good. Just go ahead with what she said." },
  { t: 43.5, who: 'callee', text: "Perfect, thanks Jordan. I'll book Thursday 2pm." },
  { t: 44.0, who: 'sys',    text: 'Jordan dropped off' },
  { t: 46.0, who: 'vooice', text: "Thanks Jordan. Marcus — confirming 45 minutes, Marcus Wu, Thursday at 2." },
  { t: 52.0, who: 'callee', text: 'All set. Phone for the reminder?' },
  { t: 55.0, who: 'vooice', text: "+1 (415) 555-0188 — that's Jordan's direct line. I'll add it to their calendar and send a confirmation." },
  { t: 60.0, who: 'callee', text: 'Great, see them Thursday.' },
  { t: 62.0, who: 'vooice', text: 'Thanks Marcus, have a good one.' },
];

const TOTAL_DUR = 65;

function CurrentLineV2(tSec) {
  let cur = SCRIPT_LINES_V2[0];
  for (const l of SCRIPT_LINES_V2) if (l.t <= tSec) cur = l;
  return cur;
}
function CurrentPhase(tSec) {
  let cur = PHASES[0];
  for (const p of PHASES) if (p.start <= tSec) cur = p;
  return cur;
}
function fmtClockV2(s) {
  const m = Math.floor(s / 60).toString().padStart(2, '0');
  const sec = Math.floor(s % 60).toString().padStart(2, '0');
  return `${m}:${sec}`;
}

function OutboundCall({ width = 1320, height = 880, onNavigate }) {
  const [tSec, setTSec] = React.useState(8);
  const [playing, setPlaying] = React.useState(true);
  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => setTSec(t => (t + 0.1) % TOTAL_DUR), 100);
    return () => clearInterval(id);
  }, [playing]);

  const line = CurrentLineV2(tSec);
  const phase = CurrentPhase(tSec);
  const speaking =
    tSec < 2.4 ? 'silent'
    : line.who === 'sys' ? 'silent'
    : line.who === 'jordan' ? 'callee'
    : line.who;

  const showReadback = tSec >= 20 && tSec < 26.5;
  const honestyMode  = tSec >= 26.5 && tSec < 36;
  const handoffMode  = tSec >= 36   && tSec < 44;
  const threeWay     = tSec >= 39.5 && tSec < 44;

  return (
    <div className="vc-root" style={{
      width, minHeight: height, background: VC_TOKENS.paper, color: VC_TOKENS.ink,
      display: 'grid',
      gridTemplateColumns: 'minmax(280px, 380px) minmax(0, 1fr) minmax(280px, 380px)',
      gridTemplateRows: 'auto 1fr 88px 60px',
      borderTop: `1px solid ${VC_TOKENS.line}`,
    }}>
      {/* HEADER — unified AppHeader */}
      <AppHeader
        onNavigate={onNavigate}
        current="outbound-call"
        crumbs={[{ label: 'OUTBOUND · LIVE' }]}
        status={`● ${fmtClockV2(tSec)} ON THE LINE`}
      />

      {/* LEFT — CALL SUBJECT */}
      <aside style={{
        borderRight: `1px solid ${VC_TOKENS.line}`,
        padding: 28, display: 'flex', flexDirection: 'column', gap: 22,
        background: VC_TOKENS.paper2,
      }}>
        <div>
          <Mono>CALLING</Mono>
          <div style={{ fontFamily: "'Inter Tight', sans-serif", fontSize: 28, fontWeight: 700, letterSpacing: '-0.025em', marginTop: 6 }}>
            Bayview Hair Studio
          </div>
          <div style={{ marginTop: 4, color: VC_TOKENS.ink3, fontSize: 14 }}>Hayes Valley · San Francisco</div>
        </div>

        <div>
          <div style={{ fontSize: 13, color: VC_TOKENS.ink3, marginBottom: 4 }}>On the line:</div>
          <Participant name="Marcus Wu" sub="Picked up · 3rd ring" speaking={speaking==='callee'} />
          {threeWay && <Participant name="Jordan Reyes" sub="Dialed in · live" speaking={line.who==='jordan'} accent />}
        </div>

        <div style={{ borderTop: `1px solid ${VC_TOKENS.lineSoft}`, paddingTop: 18 }}>
          <Mono>OBJECTIVE</Mono>
          <div style={{ fontSize: 16, fontWeight: 500, marginTop: 8, lineHeight: 1.4 }}>
            Book a 45-minute haircut, this week, <span style={{ background: VC_TOKENS.butter, padding: '0 4px' }}>Wed or Thu afternoon</span>.
          </div>
        </div>

        <FieldRow label="On behalf of">Jordan Reyes</FieldRow>
        <FieldRow label="Constraint">No 1–2pm (lunch hold)</FieldRow>
        <FieldRow label="Calendar">Google · primary</FieldRow>
        <FieldRow label="Callback #">+1 (415) 555‑0188</FieldRow>

        <div style={{ marginTop: 'auto' }}>
          <Mono>SAFETY</Mono>
          <div style={{ marginTop: 10, display:'flex', flexDirection:'column', gap: 8 }}>
            <SafetyItem on={honestyMode || handoffMode} hot={honestyMode} label="Honest about being AI" />
            <SafetyItem on label="Slot read-back before write" />
            <SafetyItem on label="Audit log recording" />
            <SafetyItem label="Voice clone of Jordan" off />
          </div>
        </div>
      </aside>

      {/* CENTER */}
      <main style={{ display: 'grid', gridTemplateRows: 'auto 1fr auto', background: VC_TOKENS.paper, minHeight: 0 }}>
        <div style={{ padding: '24px 40px 8px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom: 14 }}>
            <div>
              <Mono color={phase.color}>{phase.label.toUpperCase()}</Mono>
              <div style={{ fontSize: 13, color: VC_TOKENS.ink3, marginTop: 4 }}>
                {speaking === 'vooice' ? 'Vooice speaking' : speaking === 'callee' ? `${line.who === 'jordan' ? 'Jordan' : 'Marcus'} speaking` : 'Line silent'}
                {' · Deepgram Nova‑3 · 220ms endpoint'}
              </div>
            </div>
            <div style={{ display:'flex', gap: 16, alignItems:'center' }}>
              <Mono>LATENCY 312 ms</Mono>
              <Mono>JITTER 6 ms</Mono>
              <Mono>QUALITY ◼◼◼◼◻</Mono>
            </div>
          </div>
          <div style={{
            border: `1px solid ${VC_TOKENS.line}`,
            background: honestyMode ? VC_TOKENS.signalSoft : VC_TOKENS.paper2,
            padding: '18px 24px',
            transition: 'background 240ms ease',
          }}>
            <Waveform bars={96} height={108} speaker={speaking} color={VC_TOKENS.ink} accent={VC_TOKENS.signal} barWidth={3} gap={2} />
          </div>
        </div>

        {/* Transcript */}
        <div style={{ margin: '20px 40px 0', overflow: 'hidden', display: 'flex', flexDirection: 'column', gap: 12, minHeight: 0 }}>
          {SCRIPT_LINES_V2.filter(l => l.t <= tSec + 0.05).slice(-5).map((l, i, arr) => (
            <BubbleV2 key={l.t} line={l} isCurrent={i === arr.length - 1} tSec={tSec} />
          ))}
        </div>

        {/* Bottom — handoff */}
        <div style={{
          margin: '20px 40px 24px',
          display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 12, alignItems: 'stretch',
        }}>
          <HandoffPanelV2 honestyMode={honestyMode} handoffMode={handoffMode} />
          <BigButton variant="ghost" label="HOLD &amp; INTERVENE" sub="Park the call" />
          <BigButton variant="signal" label={handoffMode ? 'YOU\u2019RE ON THE LINE' : 'BRING ME IN'} sub={handoffMode ? 'Drop off when ready' : 'Dial me onto the line'} />
        </div>
      </main>

      {/* RIGHT — pending actions */}
      <aside style={{
        borderLeft: `1px solid ${VC_TOKENS.line}`,
        padding: 28, display: 'flex', flexDirection: 'column', gap: 14,
        background: VC_TOKENS.paper2, position: 'relative',
      }}>
        <Mono>PENDING ACTIONS</Mono>
        <div style={{ fontSize: 13, color: VC_TOKENS.ink3, marginTop: -8 }}>
          Vooice will not write to anything until the call ends and you confirm.
        </div>

        <ActionCard step="01" title="Calendar event" status={tSec > 46 ? 'ready' : 'pending'}
          rows={[['When','Thu Apr 9 · 2:00–2:45 PM'],['Where','Bayview Hair Studio'],['With','Marcus Wu'],['Notify','30 min before']]} />
        <ActionCard step="02" title="Contact update" status={tSec > 55 ? 'ready' : 'queued'}
          rows={[['Person','Marcus Wu'],['Tag','haircut · barber'],['Phone','+1 (415) 555‑0142']]} />
        <ActionCard step="03" title="Soft handoff" status={tSec > 60 ? 'ready' : 'queued'}
          rows={[['Channel','Telegram'],['Send','"Booked Thu 2pm w/ Marcus"']]} />

        <Popover visible={showReadback} title="SLOT READ-BACK" countdown="CONFIRM IN 4s"
          body={<>"Thursday <u>at 2</u> with <u>Marcus Wu</u>, 45 minutes — that's what I'm hearing. Confirming with Jordan's calendar before I commit."</>} />

        <Popover visible={honestyMode} title="HONESTY EVENT" countdown="VOOICE OWNS THIS"
          body={<>"Are you AI?" — Vooice answers truthfully and offers to dial Jordan onto the line. <em style={{color: VC_TOKENS.signal, fontStyle:'normal'}}>This rule never bends.</em></>} />

        <Popover visible={handoffMode && !threeWay} title="DIALING JORDAN" countdown="RINGING…"
          body={<>"I'm calling Jordan onto the line so you can verify I'm working for them. One moment, Marcus."</>} />
      </aside>

      {/* SCRUBBER */}
      <div style={{
        gridColumn: '1 / -1',
        borderTop: `1px solid ${VC_TOKENS.line}`,
        background: VC_TOKENS.paper2,
        display:'grid', gridTemplateColumns: '64px 1fr 220px',
        alignItems: 'center', gap: 16, padding: '0 20px',
      }}>
        <button onClick={() => setPlaying(p => !p)} style={{
          width: 40, height: 40, borderRadius:'50%', border:`1px solid ${VC_TOKENS.line}`,
          background: VC_TOKENS.ink, color: VC_TOKENS.paper, cursor:'pointer',
          fontSize: 14, fontWeight: 700,
        }}>{playing ? '❚❚' : '▶'}</button>
        <Scrubber tSec={tSec} dur={TOTAL_DUR} setT={setTSec} />
        <Mono color={VC_TOKENS.ink3}>{fmtClockV2(tSec)} / {fmtClockV2(TOTAL_DUR)}</Mono>
      </div>

      {/* FOOTER */}
      <div style={{
        gridColumn: '1 / -1',
        display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)',
        borderTop: `1px solid ${VC_TOKENS.line}`,
        background: VC_TOKENS.ink, color: VC_TOKENS.paper,
      }}>
        <Stat label="ROOM" value="lk_3F2A8B" />
        <Stat label="SIP TRUNK" value="twilio · sf · 04" />
        <Stat label="BRAIN" value="claude-sonnet-4.5" />
        <Stat label="VOICE" value="elevenlabs · turbo · ada" />
        <Stat label="AUDIT" value="lograg.vooice.app/c/3F2A8B" last />
      </div>
    </div>
  );
}

// ── Sub-components ──────────────────────────────────────────

function Participant({ name, sub, speaking, accent }) {
  return (
    <div style={{
      display:'flex', alignItems:'center', gap: 10, padding: '8px 0',
      opacity: speaking ? 1 : 0.85,
    }}>
      <div style={{ position:'relative' }}>
        <Avatar name={name} size={36} bg={accent ? VC_TOKENS.signal : VC_TOKENS.ink2} />
        {speaking && (
          <span style={{
            position:'absolute', inset:-3, border:`2px solid ${VC_TOKENS.signal}`,
            borderRadius:'50%', animation:'vc-ping 1.4s ease-out infinite',
          }} />
        )}
      </div>
      <div>
        <div style={{ fontWeight: 600 }}>{name}</div>
        <Mono color={VC_TOKENS.ink3}>{sub}</Mono>
      </div>
    </div>
  );
}

function BubbleV2({ line, isCurrent, tSec }) {
  if (line.who === 'sys') {
    return (
      <div style={{ textAlign:'center', display:'flex', alignItems:'center', gap: 12 }}>
        <span style={{ flex: 1, height: 1, background: VC_TOKENS.lineSoft }} />
        <Mono color={VC_TOKENS.ink3}>{line.text}</Mono>
        <span style={{ flex: 1, height: 1, background: VC_TOKENS.lineSoft }} />
      </div>
    );
  }
  const isVoo    = line.who === 'vooice';
  const isJordan = line.who === 'jordan';
  const align = isVoo ? 'flex-start' : 'flex-end';

  let text = line.text;
  if (isCurrent && isVoo) {
    const since = Math.max(0, tSec - line.t);
    const targetChars = Math.min(line.text.length, Math.floor(since * 22));
    text = line.text.slice(0, targetChars);
  }

  const bg = isVoo ? VC_TOKENS.ink : isJordan ? VC_TOKENS.signalSoft : VC_TOKENS.paper2;
  const fg = isVoo ? VC_TOKENS.paper : VC_TOKENS.ink;

  return (
    <div style={{ display:'flex', flexDirection: 'column', alignItems: align }}>
      <div style={{ display:'flex', alignItems:'center', gap: 8, marginBottom: 6 }}>
        {isVoo ? <VLogo size={14} /> : <Avatar name={isJordan ? 'Jordan Reyes' : 'Marcus Wu'} size={20} bg={isJordan ? VC_TOKENS.signal : VC_TOKENS.ink2} />}
        <Mono color={VC_TOKENS.ink3}>{isVoo ? 'VOOICE' : isJordan ? 'JORDAN (DIALED IN)' : 'MARCUS'} · {fmtClockV2(line.t)}</Mono>
      </div>
      <div style={{
        maxWidth: '78%', padding: '14px 18px', background: bg, color: fg,
        border: !isVoo ? `1px solid ${VC_TOKENS.line}` : 'none',
        fontSize: 16, lineHeight: 1.45, fontWeight: isCurrent ? 500 : 400,
      }}>
        {text}
        {isCurrent && isVoo && text.length < line.text.length && (
          <span style={{
            display:'inline-block', width: 8, height: 16, marginLeft: 2,
            background: VC_TOKENS.signal, verticalAlign: '-2px',
            animation: 'vc-cursor 0.8s steps(1) infinite',
          }} />
        )}
      </div>
    </div>
  );
}

function ActionCard({ step, title, status, rows }) {
  const palette = {
    pending: { fg: VC_TOKENS.ink3, label: 'PENDING' },
    queued:  { fg: VC_TOKENS.ink3, label: 'QUEUED' },
    ready:   { fg: VC_TOKENS.sage, label: 'READY TO WRITE' },
  }[status];
  return (
    <div style={{
      border: `1px solid ${palette.fg === VC_TOKENS.sage ? VC_TOKENS.sage : VC_TOKENS.line}`,
      background: VC_TOKENS.paper, padding: '12px 14px',
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 8 }}>
        <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
          <Mono color={VC_TOKENS.signal}>{step}</Mono>
          <span style={{ fontWeight: 600, fontSize: 14 }}>{title}</span>
        </div>
        <Mono color={palette.fg}>{palette.label}</Mono>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap: 3 }}>
        {rows.map(([k,v]) => (
          <div key={k} style={{ display:'flex', justifyContent:'space-between', fontSize: 12.5 }}>
            <span style={{ color: VC_TOKENS.ink3 }}>{k}</span>
            <span style={{ color: VC_TOKENS.ink, fontWeight: 500 }}>{v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function SafetyItem({ label, on, off, hot }) {
  const color = off ? VC_TOKENS.ink3 : hot ? VC_TOKENS.signal : VC_TOKENS.sage;
  return (
    <div style={{ display:'flex', alignItems:'center', gap: 10, fontSize: 13 }}>
      <span style={{
        width: 14, height: 14, border: `1.5px solid ${color}`,
        display:'inline-flex', alignItems:'center', justifyContent:'center',
        background: off ? 'transparent' : color, color: VC_TOKENS.paper, fontSize: 10,
        animation: hot ? 'vc-blink 1.2s steps(1) infinite' : 'none',
      }}>{off ? '×' : '✓'}</span>
      <span style={{ color: off ? VC_TOKENS.ink3 : VC_TOKENS.ink, textDecoration: off ? 'line-through' : 'none', fontWeight: hot ? 600 : 400 }}>{label}</span>
    </div>
  );
}

function HandoffPanelV2({ honestyMode, handoffMode }) {
  if (handoffMode) {
    return (
      <div style={{
        border: `1px solid ${VC_TOKENS.signal}`, background: VC_TOKENS.signal, color: VC_TOKENS.paper,
        padding: '12px 16px', display:'flex', alignItems:'center', gap: 16,
      }}>
        <RingingRing size={14} color={VC_TOKENS.paper} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 700 }}>You're being dialed in.</div>
          <div style={{ fontSize: 12, opacity: 0.9 }}>Vooice will keep talking until you pick up. Drop off whenever.</div>
        </div>
        <Mono color={VC_TOKENS.paper}>3-WAY</Mono>
      </div>
    );
  }
  if (honestyMode) {
    return (
      <div style={{
        border: `1px solid ${VC_TOKENS.signal}`, background: VC_TOKENS.signalSoft,
        padding: '12px 16px', display:'flex', alignItems:'center', gap: 16,
      }}>
        <RingingRing size={14} color={VC_TOKENS.signal} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 700 }}>Marcus asked if she's AI. She said yes.</div>
          <div style={{ fontSize: 12, color: VC_TOKENS.ink2 }}>She's offering to dial you in. Auto-accept in 3s if no input.</div>
        </div>
        <Tag tone="signal">HONESTY</Tag>
      </div>
    );
  }
  return (
    <div style={{
      border: `1px solid ${VC_TOKENS.line}`, background: VC_TOKENS.paper2,
      padding: '12px 16px', display:'flex', alignItems:'center', gap: 16,
    }}>
      <RingingRing size={14} color={VC_TOKENS.signal} />
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>Call going smoothly.</div>
        <div style={{ fontSize: 12, color: VC_TOKENS.ink3 }}>If Marcus asks "are you AI?", I'll answer truthfully and offer to dial you in.</div>
      </div>
      <Tag tone="ghost">AUTO</Tag>
    </div>
  );
}

function BigButton({ label, sub, variant = 'ghost' }) {
  const isSignal = variant === 'signal';
  return (
    <button style={{
      padding: '12px 20px',
      background: isSignal ? VC_TOKENS.signal : 'transparent',
      color: isSignal ? VC_TOKENS.paper : VC_TOKENS.ink,
      border: `1px solid ${isSignal ? VC_TOKENS.signal : VC_TOKENS.line}`,
      cursor: 'pointer', textAlign: 'left', minWidth: 200,
    }}>
      <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase' }}
        dangerouslySetInnerHTML={{ __html: label }} />
      <div style={{ fontSize: 12, opacity: 0.7, marginTop: 2 }}>{sub}</div>
    </button>
  );
}

function Stat({ label, value, last }) {
  return (
    <div style={{ padding: '14px 20px', borderRight: last ? 'none' : `1px solid #2a2724`, display:'flex', flexDirection:'column', gap: 4 }}>
      <Mono color={VC_TOKENS.ink3} size={9}>{label}</Mono>
      <Mono color={VC_TOKENS.paper} size={11} weight={500}>{value}</Mono>
    </div>
  );
}

// ── Animated popover ─────────────────────────────────
function Popover({ visible, title, countdown, body }) {
  const [render, setRender] = React.useState(visible);
  const [show, setShow] = React.useState(visible);
  React.useEffect(() => {
    if (visible) { setRender(true); requestAnimationFrame(() => setShow(true)); }
    else { setShow(false); const t = setTimeout(() => setRender(false), 320); return () => clearTimeout(t); }
  }, [visible]);
  if (!render) return null;
  return (
    <div style={{
      position:'absolute', left: -40, top: 240, width: 380,
      background: VC_TOKENS.ink, color: VC_TOKENS.paper,
      border: `1px solid ${VC_TOKENS.ink}`, padding: '16px 18px',
      boxShadow: `8px 8px 0 ${VC_TOKENS.signal}`, zIndex: 50,
      opacity: show ? 1 : 0,
      transform: show ? 'translateX(0) rotate(-0.6deg)' : 'translateX(-30px) rotate(-3deg)',
      transition: 'opacity 280ms ease, transform 320ms cubic-bezier(.2,.9,.3,1.2)',
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 10 }}>
        <Mono color={VC_TOKENS.signal}>{title}</Mono>
        <Mono color={VC_TOKENS.paper}>{countdown}</Mono>
      </div>
      <div style={{ fontSize: 14, lineHeight: 1.5 }}>{body}</div>
    </div>
  );
}

// ── Scrubber with phase markers ──────────────────────
function Scrubber({ tSec, dur, setT }) {
  const trackRef = React.useRef(null);
  const onClick = e => {
    const r = trackRef.current.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width;
    setT(Math.max(0, Math.min(dur, x * dur)));
  };
  return (
    <div style={{ display:'flex', flexDirection:'column', gap: 6, padding: '14px 0' }}>
      <div ref={trackRef} onClick={onClick} style={{
        position:'relative', height: 32, cursor:'pointer',
      }}>
        {/* Phase blocks */}
        {PHASES.map((p, i) => {
          const next = PHASES[i+1];
          const start = p.start / dur;
          const end = (next ? next.start : dur) / dur;
          return (
            <div key={p.id} style={{
              position:'absolute', left: `${start*100}%`, width: `${(end-start)*100}%`,
              top: 6, height: 20,
              background: i % 2 === 0 ? VC_TOKENS.paper : VC_TOKENS.paper3,
              borderLeft: `1px solid ${VC_TOKENS.line}`,
            }}>
              <Mono color={p.color} size={9} style={{ position:'absolute', left: 6, top: 4, whiteSpace:'nowrap', pointerEvents:'none' }}>
                {p.label}
              </Mono>
            </div>
          );
        })}
        {/* Playhead */}
        <div style={{
          position:'absolute', left: `${(tSec/dur)*100}%`, top: 0, bottom: 0,
          width: 2, background: VC_TOKENS.signal, transform:'translateX(-1px)',
          pointerEvents:'none',
        }}>
          <div style={{ position:'absolute', top: -4, left: -5, width: 12, height: 12, borderRadius:'50%', background: VC_TOKENS.signal }} />
        </div>
      </div>
    </div>
  );
}

window.OutboundCall = OutboundCall;
