// The interactive product demo — 3 styles: chat, timeline, workflow, terminal
function DemoPanel({ demo, t }) {
  if (demo === 'timeline') return <TimelineDemo t={t}/>;
  if (demo === 'workflow') return <WorkflowDemo t={t}/>;
  if (demo === 'terminal') return <TerminalDemo t={t}/>;
  return <ChatDemo t={t}/>;
}

function PanelFrame({ children, label, status = 'live' }) {
  return (
    <div style={{
      background: 'var(--bg-elev)',
      border: '1px solid var(--border-strong)',
      borderRadius: 'var(--radius-lg)',
      boxShadow: '0 1px 0 color-mix(in oklch, white 8%, transparent) inset, 0 40px 80px -30px color-mix(in oklch, var(--ink) 40%, transparent), 0 0 0 1px var(--border)',
      overflow: 'hidden',
      position: 'relative',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '11px 16px',
        borderBottom: '1px solid var(--border)',
        background: 'color-mix(in oklch, var(--ink) 2%, var(--bg-elev))',
        fontFamily: 'var(--font-mono)',
        fontSize: 11, color: 'var(--ink-faint)',
        letterSpacing: '0.02em',
      }}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <div style={{ display: 'flex', gap: 5 }}>
            <span style={{ width: 9, height: 9, borderRadius: 9, background: '#E6694A' }}/>
            <span style={{ width: 9, height: 9, borderRadius: 9, background: '#E9B64C' }}/>
            <span style={{ width: 9, height: 9, borderRadius: 9, background: '#5FB360' }}/>
          </div>
          <span style={{ marginLeft: 10 }}>{label}</span>
        </div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{
            width: 7, height: 7, borderRadius: 7,
            background: status === 'live' ? '#3FBA63' : '#C0C5CE',
            boxShadow: status === 'live' ? '0 0 0 3px color-mix(in oklch, #3FBA63 22%, transparent)' : 'none',
            animation: 'pulse 2s infinite',
          }}/>
          <span>{status === 'live' ? 'agent·actif' : 'idle'}</span>
        </div>
      </div>
      {children}
    </div>
  );
}

// ============ CHAT ============
function ChatDemo({ t }) {
  const [step, setStep] = useState(0);
  const messages = t.chat_messages;
  useEffect(() => {
    if (step >= messages.length) return;
    const d = messages[step].role === 'user' ? 1200 : 1800;
    const id = setTimeout(() => setStep(s => s + 1), d);
    return () => clearTimeout(id);
  }, [step]);
  useEffect(() => {
    const id = setInterval(() => setStep(0), 18000);
    return () => clearInterval(id);
  }, []);
  return (
    <PanelFrame label="sms · (514) 555-CASTOR">
      <div style={{ padding: '20px 20px 24px', minHeight: 420, display: 'flex', flexDirection: 'column', gap: 10, background: 'color-mix(in oklch, var(--ink) 1.5%, var(--bg-elev))' }}>
        {messages.slice(0, step).map((m, i) => (
          <ChatBubble key={i} {...m}/>
        ))}
        {step < messages.length && messages[step].role === 'agent' && (
          <div style={{ alignSelf: 'flex-start', padding: '10px 14px', background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 14, display: 'inline-flex', gap: 4 }}>
            <Dot/><Dot delay={150}/><Dot delay={300}/>
          </div>
        )}
      </div>
    </PanelFrame>
  );
}

function ChatBubble({ role, text, meta }) {
  const isUser = role === 'user';
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: isUser ? 'flex-end' : 'flex-start', animation: 'fadein 320ms ease both' }}>
      <div style={{
        maxWidth: '80%',
        padding: '10px 14px',
        background: isUser ? 'var(--brand)' : 'var(--bg-elev)',
        color: isUser ? 'white' : 'var(--ink)',
        border: isUser ? 'none' : '1px solid var(--border)',
        borderRadius: 16,
        borderBottomRightRadius: isUser ? 4 : 16,
        borderBottomLeftRadius: isUser ? 16 : 4,
        fontFamily: 'var(--font-ui)',
        fontSize: 14, lineHeight: 1.45,
        boxShadow: isUser ? '0 4px 14px -4px var(--glow)' : 'none',
      }}>{text}</div>
      {meta && <span style={{ fontSize: 11, color: 'var(--ink-faint)', marginTop: 4, fontFamily: 'var(--font-mono)' }}>{meta}</span>}
    </div>
  );
}
function Dot({ delay = 0 }) {
  return <span style={{
    display: 'inline-block', width: 6, height: 6, borderRadius: 6,
    background: 'var(--ink-soft)',
    animation: `bounce 1.1s ${delay}ms infinite ease-in-out`,
  }}/>;
}

// ============ TIMELINE ============
function TimelineDemo({ t }) {
  const [active, setActive] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setActive(a => (a + 1) % t.timeline.length), 2200);
    return () => clearInterval(id);
  }, [t.timeline.length]);
  return (
    <PanelFrame label={t.timeline_label}>
      <div style={{ padding: 24, background: 'var(--bg-elev)', minHeight: 440 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--ink-faint)', marginBottom: 18, letterSpacing: '0.12em' }}>
          TRACE · {new Date().toLocaleDateString('fr-CA')} · 14:02:11 EST
        </div>
        <div style={{ position: 'relative' }}>
          <div style={{ position: 'absolute', left: 10, top: 0, bottom: 0, width: 1.5, background: 'var(--border-strong)' }}/>
          {t.timeline.map((step, i) => {
            const done = i < active;
            const running = i === active;
            return (
              <div key={i} style={{ display: 'flex', gap: 16, paddingBottom: 18, position: 'relative' }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 22,
                  background: done ? 'var(--brand)' : 'var(--bg-elev)',
                  border: `1.5px solid ${done || running ? 'var(--brand)' : 'var(--border-strong)'}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0, zIndex: 1,
                  transition: 'all 300ms ease',
                  boxShadow: running ? '0 0 0 4px var(--glow)' : 'none',
                }}>
                  {done && <Check size={11} color="white"/>}
                  {running && <span style={{ width: 7, height: 7, borderRadius: 7, background: 'var(--brand)', animation: 'pulse 1.2s infinite' }}/>}
                </div>
                <div style={{ flex: 1, opacity: running || done ? 1 : 0.4, transition: 'opacity 300ms' }}>
                  <div style={{ fontFamily: 'var(--font-ui)', fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{step.title}</div>
                  <div style={{ fontFamily: 'var(--font-ui)', fontSize: 13, color: 'var(--ink-soft)', marginTop: 2 }}>{step.desc}</div>
                  {step.meta && <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--accent-ink)', marginTop: 6, letterSpacing: '0.05em' }}>{step.meta}</div>}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </PanelFrame>
  );
}

// ============ WORKFLOW ============
function WorkflowDemo({ t }) {
  return (
    <PanelFrame label={t.workflow_label}>
      <div style={{ padding: 26, background: 'var(--bg-elev)', minHeight: 460, position: 'relative' }}>
        <svg viewBox="0 0 640 460" style={{ width: '100%', height: 'auto' }}>
          <defs>
            <marker id="arr" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto">
              <path d="M0,0 L10,5 L0,10 z" fill="var(--ink-faint)"/>
            </marker>
            <linearGradient id="agentGrad" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0%" stopColor="var(--brand)" stopOpacity="0.15"/>
              <stop offset="100%" stopColor="var(--brand)" stopOpacity="0.02"/>
            </linearGradient>
          </defs>
          <WFNode x={20} y={40} w={140} label={t.wf_input_1} sub="SMS · Courriel"/>
          <WFNode x={20} y={130} w={140} label={t.wf_input_2} sub="CRM · Docs"/>
          <WFNode x={20} y={220} w={140} label={t.wf_input_3} sub="API · Webhooks"/>
          <g>
            <rect x={240} y={90} width={180} height={170} rx={14}
              fill="url(#agentGrad)"
              stroke="var(--brand)" strokeWidth="1.2"/>
            <rect x={240} y={90} width={180} height={170} rx={14}
              fill="none"
              stroke="var(--brand)" strokeWidth="0.5" opacity="0.4" strokeDasharray="2 4"/>
            <text x={330} y={118} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fill="var(--brand)" letterSpacing="0.2em">CASTOR · AGENT</text>
            <text x={330} y={152} textAnchor="middle" fontFamily="var(--font-display)" fontSize="17" fontWeight="600" fill="var(--ink)" letterSpacing="-0.01em">{t.wf_agent_t1}</text>
            <text x={330} y={178} textAnchor="middle" fontFamily="var(--font-ui)" fontSize="12" fill="var(--ink-soft)">{t.wf_agent_t2}</text>
            <text x={330} y={200} textAnchor="middle" fontFamily="var(--font-ui)" fontSize="12" fill="var(--ink-soft)">{t.wf_agent_t3}</text>
            <text x={330} y={234} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9.5" fill="var(--accent-ink)" letterSpacing="0.08em">▢ chiffré · anonymisé · QC</text>
          </g>
          <WFNode x={480} y={40} w={140} label={t.wf_output_1} sub="2 min"/>
          <WFNode x={480} y={130} w={140} label={t.wf_output_2} sub="auto"/>
          <WFNode x={480} y={220} w={140} label={t.wf_output_3} sub="24/7"/>
          {[60, 150, 240].map((y, i) => (
            <path key={`l${i}`} d={`M160 ${y + 20} C 200 ${y + 20}, 200 175, 240 175`} fill="none" stroke="var(--ink-faint)" strokeWidth="1.2" markerEnd="url(#arr)" opacity="0.6"/>
          ))}
          {[60, 150, 240].map((y, i) => (
            <path key={`r${i}`} d={`M420 175 C 460 175, 460 ${y + 20}, 480 ${y + 20}`} fill="none" stroke="var(--ink-faint)" strokeWidth="1.2" markerEnd="url(#arr)" opacity="0.6"/>
          ))}
          <g transform="translate(20 330)">
            <rect x={0} y={0} width={600} height={100} rx={12} fill="color-mix(in oklch, var(--ink) 2.5%, var(--bg-elev))" stroke="var(--border)"/>
            <text x={20} y={24} fontFamily="var(--font-mono)" fontSize="9.5" fill="var(--ink-faint)" letterSpacing="0.15em">● LIVE · 7 DERNIERS JOURS</text>
            {[['142', t.wf_m1], ['3.2min', t.wf_m2], ['98%', t.wf_m3], ['0', t.wf_m4]].map(([v, l], i) => (
              <g key={i} transform={`translate(${20 + i * 150} 40)`}>
                <text fontFamily="var(--font-display)" fontSize="24" fontWeight="500" fill="var(--ink)" letterSpacing="-0.02em">{v}</text>
                <text y={24} fontFamily="var(--font-ui)" fontSize="11" fill="var(--ink-soft)">{l}</text>
              </g>
            ))}
          </g>
        </svg>
      </div>
    </PanelFrame>
  );
}

function WFNode({ x, y, w, label, sub }) {
  return (
    <g>
      <rect x={x} y={y} width={w} height={52} rx={10} fill="var(--bg-elev)" stroke="var(--border-strong)" strokeWidth="1"/>
      <text x={x + w/2} y={y + 22} textAnchor="middle" fontFamily="var(--font-ui)" fontSize="13" fontWeight="500" fill="var(--ink)">{label}</text>
      <text x={x + w/2} y={y + 40} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9.5" fill="var(--ink-faint)" letterSpacing="0.05em">{sub}</text>
    </g>
  );
}

// ============ TERMINAL ============
function TerminalDemo({ t }) {
  const [idx, setIdx] = useState(0);
  const lines = t.terminal;
  useEffect(() => {
    if (idx >= lines.length) {
      const r = setTimeout(() => setIdx(0), 4000);
      return () => clearTimeout(r);
    }
    const id = setTimeout(() => setIdx(i => i + 1), 600 + Math.random() * 500);
    return () => clearTimeout(id);
  }, [idx]);
  return (
    <PanelFrame label="castor-agent · terminal">
      <div style={{
        padding: 22, background: '#0A0D14', minHeight: 440,
        fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.75,
        color: '#D6D9DE', position: 'relative', overflow: 'hidden',
      }}>
        <div aria-hidden style={{ position: 'absolute', inset: 0, background: 'linear-gradient(transparent 50%, rgba(255,255,255,0.015) 50%)', backgroundSize: '100% 4px', pointerEvents: 'none' }}/>
        {lines.slice(0, idx).map((line, i) => (
          <div key={i} style={{ animation: 'fadein 200ms ease both', position: 'relative' }}>
            {line.type === 'cmd' && <><span style={{ color: '#6BC57A' }}>❯</span> <span style={{ color: '#6B97E0' }}>castor</span> <span style={{ color: '#F3F4F6' }}>{line.text}</span></>}
            {line.type === 'out' && <span style={{ color: '#A6ADBB' }}>{line.text}</span>}
            {line.type === 'ok' && <span style={{ color: '#6BC57A' }}>✓ {line.text}</span>}
            {line.type === 'tag' && <span style={{ color: '#E9B64C' }}>[ {line.text} ]</span>}
          </div>
        ))}
        {idx < lines.length && <span style={{ color: '#6B97E0', animation: 'blink 1s infinite' }}>▊</span>}
      </div>
    </PanelFrame>
  );
}

Object.assign(window, { DemoPanel, ChatDemo, TimelineDemo, WorkflowDemo, TerminalDemo, PanelFrame, ChatBubble });
