// hero-demo.jsx — 3-surface agent demo (Otis · Ren · Dax)
const { useState, useEffect, useRef, useCallback } = React;

const ROTATION_MS = 11000;

const SURFACES = [
  {
    id: 'teams',
    num: '01',
    agent: 'Otis',
    role: 'Documents · AR',
    label: 'Otis · Teams',
    platform: 'Microsoft Teams',
    platformColor: '#5B5FC7',
    glowColor: 'rgba(91, 95, 199, 0.20)',
    type: 'desktop',
    highlight: true,
    timeline: [
      { delay: 500,  type: 'agent', name: 'Otis', msg: 'New POD in.\nPRO# 4421 · Summit Industrial\nSigned: J. Martinez · 11:42 AM\nApprove to post to TruckMate?' },
      { delay: 3200, type: 'user',  name: 'D. Patel', msg: 'Approve' },
      { delay: 4400, type: 'typing' },
      { delay: 5800, type: 'agent', name: 'Otis', msg: 'Posted to AR. PRO# 4421 closed.\nInvoice ready.' },
    ],
  },
  {
    id: 'email',
    num: '02',
    agent: 'Dax',
    role: 'Customer Service · Intake',
    label: 'Dax · Email',
    platform: 'Email',
    platformColor: '#4A8FF5',
    glowColor: 'rgba(74, 143, 245, 0.18)',
    type: 'desktop',
    timeline: [
      { delay: 400,  type: 'email-in',   from: 'shipping@apexlogistics.com', name: 'Apex Logistics', subject: 'LTL quote request — Chicago, IL → Atlanta, GA' },
      { delay: 2000, type: 'typing' },
      { delay: 3600, type: 'quote-card', data: {
        total: '$1,847.00',
        lane: 'Chicago, IL 60607 → Atlanta, GA 30318',
        weight: '8 skids · 2,400 lbs',
        cls: 'Class 85 · NMFC 156600',
        transit: '2 business days · pickup Tue May 6',
        validity: 'Valid 7 days',
        ref: 'Q-0502-4421',
        breakdown: [
          ['Linehaul',          '$1,412.00'],
          ['Fuel surcharge (28.4%)',     '$401.00'],
          ['Liftgate at delivery',  '$95.00'],
          ['Discount (Apex tier)', '−$61.00'],
        ],
      } },
      { delay: 7200, type: 'user-email', name: 'Apex Logistics', msg: 'Looks good — please tender. PO# 88421. BOL to follow.' },
      { delay: 8600, type: 'typing' },
      { delay: 10000, type: 'agent-email', name: 'Dax', msg: 'Tendered in TruckMate. PRO# 4421-CHI · Pickup Tue 5/6 · 8a–12p window. BOL acknowledged on receipt.' },
    ],
  },
  {
    id: 'slack',
    num: '03',
    agent: 'Mira',
    role: 'AR · Accessorial Ops',
    label: 'Mira · Slack',
    platform: 'Slack',
    platformColor: '#611F69',
    glowColor: 'rgba(97, 31, 105, 0.18)',
    type: 'desktop',
    timeline: [
      { delay: 500,  type: 'agent',  name: 'Mira', msg: 'Detention filed.\nPRO# 4408 · 3h 34m on dock\nGate-in 09:14 → Gate-out 12:48\nPackage sent to ar@northgatedist.com.' },
      { delay: 4000, type: 'user',   name: 'D. Nguyen', msg: 'Response window?' },
      { delay: 5200, type: 'typing' },
      { delay: 6600, type: 'agent',  name: 'Mira', msg: '14 days. I’ll chase if no reply by May 15.' },
    ],
  },
  {
    id: 'sms',
    num: '04',
    agent: 'Ren',
    role: 'Scheduling · Dock Ops',
    label: 'Ren · SMS',
    platform: 'SMS',
    platformColor: '#30C15A',
    glowColor: 'rgba(48, 193, 90, 0.18)',
    type: 'phone',
    timeline: [
      { delay: 500,  type: 'user-sms',  msg: 'Need door 7, Heartland Freight, Thu 2pm' },
      { delay: 1700, type: 'typing' },
      { delay: 3000, type: 'agent-sms', msg: 'Booked.\nDoor 7 · Thu 2:00–3:30 PM\nPRO# HF-88421\nOpenDock updated.' },
      { delay: 5800, type: 'user-sms',  msg: 'Send dispatch the confirmation' },
      { delay: 6800, type: 'typing' },
      { delay: 8000, type: 'agent-sms', msg: 'Sent to dispatch@heartlandfreight.com ✓' },
    ],
  },
];

// ── Typing Indicator ──────────────────────────────────────────────
function TypingBubble({ color = '#999', dark = false }) {
  const bg = dark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.07)';
  const dotStyle = {
    width: 6, height: 6, borderRadius: '50%',
    background: color, display: 'inline-block',
  };
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '10px 14px', background: bg, borderRadius: 14 }}>
      <span className="dot-1" style={dotStyle}></span>
      <span className="dot-2" style={dotStyle}></span>
      <span className="dot-3" style={dotStyle}></span>
    </div>
  );
}

// ── SMS Mockup ────────────────────────────────────────────────────
function SMSMockup({ messages, showTyping, agent = 'Ren' }) {
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, showTyping]);

  return (
    <div style={{ width: '100%', height: '100%', background: '#F2F2F7', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* iOS Header */}
      <div style={{ flexShrink: 0, background: 'rgba(242,242,247,0.95)', borderBottom: '1px solid rgba(0,0,0,0.1)', padding: '10px 0 8px' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'linear-gradient(135deg, #30C15A, #25A34A)', margin: '0 auto 4px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 16, fontWeight: 700, fontFamily: "'Geist', -apple-system, sans-serif" }}>{agent[0]}</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#000', fontFamily: "'Geist', -apple-system, sans-serif" }}>{agent}</div>
          <div style={{ fontSize: 11, color: '#8E8E93', fontFamily: "'Geist', -apple-system, sans-serif" }}>Echo agent · SMS</div>
        </div>
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '16px 12px', display: 'flex', flexDirection: 'column', gap: 6, scrollbarWidth: 'none', msOverflowStyle: 'none', minHeight: 0 }}>
        <div style={{ textAlign: 'center', color: '#8E8E93', fontSize: 10, marginBottom: 8, fontFamily: "'Geist', -apple-system, sans-serif", textTransform: 'uppercase', letterSpacing: '0.04em' }}>Today 11:38 AM</div>
        {messages.map((m, i) => {
          const isUser = m.type === 'user-sms';
          return (
            <div key={i} className="msg-reveal" style={{ display: 'flex', justifyContent: isUser ? 'flex-end' : 'flex-start', width: '100%' }}>
              <div style={{
                background: isUser ? '#007AFF' : '#E5E5EA',
                color: isUser ? '#fff' : '#000',
                borderRadius: isUser ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
                padding: '9px 13px',
                maxWidth: '78%',
                fontSize: 13,
                lineHeight: 1.45,
                whiteSpace: 'pre-line',
                fontFamily: "'Geist', -apple-system, BlinkMacSystemFont, sans-serif",
                wordBreak: 'break-word',
              }}>
                {m.msg}
              </div>
            </div>
          );
        })}
        {showTyping && (
          <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
            <TypingBubble color="#30C15A" />
          </div>
        )}
      </div>

      {/* Input */}
      <div style={{ flexShrink: 0, padding: '8px 10px', borderTop: '1px solid rgba(0,0,0,0.08)', background: '#F2F2F7', display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ flex: 1, background: '#fff', border: '1px solid rgba(0,0,0,0.15)', borderRadius: 18, padding: '7px 12px', color: '#C7C7CC', fontSize: 13, fontFamily: "'Geist', -apple-system, sans-serif" }}>iMessage</div>
        <div style={{ width: 30, height: 30, borderRadius: '50%', background: '#E5E5EA', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="#8E8E93"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
        </div>
      </div>
    </div>
  );
}

// ── Teams Mockup ──────────────────────────────────────────────────
// Authentic Microsoft Teams chrome: light theme, left rail, channel list, posts.
function TeamsMockup({ messages, showTyping, agent = 'Otis', channelName = 'ar-team', userName = 'D. Patel', userInitials = 'DP' }) {
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, showTyping]);

  const TEAMS_PURPLE = '#5B5FC7';
  const TEAMS_PURPLE_LIGHT = '#E8EBFA';

  const railIcons = [
    { label: 'Activity', icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg> },
    { label: 'Chat',     icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg> },
    { label: 'Teams',    icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>, active: true },
    { label: 'Calendar', icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg> },
  ];

  return (
    <div style={{ display: 'flex', height: '100%', fontFamily: "'Geist', 'Geist', 'Inter', system-ui, sans-serif", overflow: 'hidden', background: '#F5F5F5' }}>
      {/* Left app rail (Teams icons) */}
      <div className="demo-sidebar demo-sidebar--teams-rail" style={{ width: 56, background: '#EBEBEB', display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '10px 0', flexShrink: 0, borderRight: '1px solid #E0E0E0' }}>
        {railIcons.map(r => (
          <div key={r.label} style={{
            width: 44, height: 44, borderRadius: 6,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: r.active ? TEAMS_PURPLE : '#605E5C',
            background: r.active ? '#fff' : 'transparent',
            position: 'relative',
            marginBottom: 4,
          }}>
            {r.active && <div style={{ position: 'absolute', left: -2, top: 8, bottom: 8, width: 3, borderRadius: 2, background: TEAMS_PURPLE }} />}
            {r.icon}
          </div>
        ))}
      </div>

      {/* Channel sidebar */}
      <div className="demo-sidebar demo-sidebar--teams" style={{ width: 220, background: '#F5F5F5', display: 'flex', flexDirection: 'column', flexShrink: 0, borderRight: '1px solid #E0E0E0' }}>
        <div style={{ padding: '12px 16px 8px' }}>
          <div style={{ fontWeight: 600, fontSize: 14, color: '#252423' }}>Teams</div>
        </div>
        <div style={{ padding: '0 8px', flex: 1, overflow: 'hidden' }}>
          <div style={{ padding: '6px 8px', display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
            <div style={{ width: 28, height: 28, borderRadius: 4, background: TEAMS_PURPLE, color: '#fff', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>EC</div>
            <span style={{ fontSize: 13, color: '#252423', fontWeight: 600 }}>Echo Carrier Ops</span>
          </div>
          {[
            { name: 'general' },
            { name: 'dispatch' },
            { name: channelName, active: true, badge: 1 },
            { name: 'safety' },
          ].map((c) => (
            <div key={c.name} style={{
              padding: '6px 8px 6px 36px', fontSize: 13,
              color: c.active ? '#252423' : '#424242',
              background: c.active ? '#E1DFDD' : 'transparent',
              borderRadius: 4,
              display: 'flex', alignItems: 'center', gap: 6,
              fontWeight: c.active ? 600 : 400,
              marginBottom: 1,
            }}>
              <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</span>
              {c.badge && <span style={{ background: TEAMS_PURPLE, borderRadius: 8, padding: '1px 6px', fontSize: 10, color: '#fff', fontWeight: 600 }}>{c.badge}</span>}
            </div>
          ))}
        </div>
      </div>

      {/* Main channel pane */}
      <div style={{ flex: 1, background: '#fff', display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <div style={{ padding: '12px 20px', borderBottom: '1px solid #E0E0E0', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ color: '#252423', fontWeight: 700, fontSize: 14 }}>{channelName}</span>
          <span style={{ color: '#605E5C', fontSize: 12 }}>· Posts</span>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 6, alignItems: 'center' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: '#107C10' }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#107C10', display: 'inline-block' }}/>
              Otis · online
            </span>
          </div>
        </div>

        <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 16, scrollbarWidth: 'none', minHeight: 0 }}>
          {messages.map((m, i) => {
            const isAgent = m.type === 'agent';
            const initials = isAgent ? agent[0] : userInitials;
            return (
              <div key={i} className="msg-reveal" style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <div style={{ width: 32, height: 32, borderRadius: '50%', background: isAgent ? TEAMS_PURPLE : '#0078D4', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 12, fontWeight: 600 }}>
                  {initials}
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
                    <span style={{ color: '#252423', fontWeight: 700, fontSize: 13 }}>{m.name}</span>
                    {isAgent && <span style={{ background: TEAMS_PURPLE_LIGHT, color: TEAMS_PURPLE, fontSize: 10, padding: '1px 7px', borderRadius: 3, fontWeight: 600 }}>BOT</span>}
                    <span style={{ color: '#605E5C', fontSize: 11 }}>11:{42 + i} AM</span>
                  </div>
                  {isAgent ? (
                    <div style={{
                      background: '#fff',
                      border: `1px solid ${TEAMS_PURPLE_LIGHT}`,
                      borderLeft: `3px solid ${TEAMS_PURPLE}`,
                      borderRadius: 4,
                      padding: '10px 14px',
                      color: '#252423', fontSize: 13, lineHeight: 1.55, whiteSpace: 'pre-line', wordBreak: 'break-word',
                    }}>
                      {m.msg}
                    </div>
                  ) : (
                    <div style={{ color: '#252423', fontSize: 13, lineHeight: 1.55, whiteSpace: 'pre-line', wordBreak: 'break-word' }}>{m.msg}</div>
                  )}
                </div>
              </div>
            );
          })}
          {showTyping && (
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <div style={{ width: 32, height: 32, borderRadius: '50%', background: TEAMS_PURPLE, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 12, fontWeight: 600 }}>{agent[0]}</div>
              <TypingBubble color={TEAMS_PURPLE} />
            </div>
          )}
        </div>

        <div style={{ padding: '12px 20px 16px', borderTop: '1px solid #E0E0E0', flexShrink: 0 }}>
          <div style={{ border: '1px solid #E0E0E0', borderRadius: 4, padding: '10px 14px', color: '#605E5C', fontSize: 12, background: '#fff' }}>Type a new message</div>
        </div>
      </div>
    </div>
  );
}

// ── Email Mockup (Microsoft Outlook) ─────────────────────────────
function EmailMockup({ messages, showTyping }) {
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, showTyping]);

  const emailIn = messages.find(m => m.type === 'email-in');
  const thread = messages.filter(m => m.type !== 'email-in');

  const OUTLOOK_BLUE = '#0078D4';
  const OUTLOOK_BLUE_DARK = '#106EBE';
  const OUTLOOK_BG = '#FAF9F8';
  const OUTLOOK_BORDER = '#EDEBE9';
  const TEXT_PRIMARY = '#201F1E';
  const TEXT_SECONDARY = '#605E5C';

  // Folders w/ icons (Outlook nav rail)
  const folders = [
    { name: 'Inbox', count: 3, active: true, icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg> },
    { name: 'Sent Items',  icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg> },
    { name: 'Drafts',      icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> },
    { name: 'Archive',     icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg> },
  ];

  const inboxList = [
    { from: 'Apex Logistics', subject: emailIn?.subject || 'Rate quote — CHI to ATL', preview: 'Hi — can you provide a rate quote?', time: '11:42 AM', unread: true, active: true },
    { from: 'Northgate Distribution', subject: 'PRO# 4408 — detention notice', preview: 'Driver was held 3h 34m at the dock…', time: '10:18 AM' },
    { from: 'Heartland Freight', subject: 'Confirming Thursday dock booking', preview: 'Dispatch confirms Door 7, 2:00 PM…', time: '9:04 AM' },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: OUTLOOK_BG, fontFamily: "'Geist', 'Geist', 'Inter', system-ui, sans-serif", overflow: 'hidden', color: TEXT_PRIMARY }}>
      {/* Outlook header bar */}
      <div style={{ height: 44, background: OUTLOOK_BLUE, display: 'flex', alignItems: 'center', padding: '0 16px', gap: 14, flexShrink: 0 }}>
        {/* Outlook waffle + logo */}
        <svg width="14" height="14" viewBox="0 0 24 24" fill="#fff"><circle cx="4" cy="4" r="2"/><circle cx="12" cy="4" r="2"/><circle cx="20" cy="4" r="2"/><circle cx="4" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="20" cy="12" r="2"/><circle cx="4" cy="20" r="2"/><circle cx="12" cy="20" r="2"/><circle cx="20" cy="20" r="2"/></svg>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="#fff"><path d="M21.5 4h-19A1.5 1.5 0 0 0 1 5.5v13A1.5 1.5 0 0 0 2.5 20h19a1.5 1.5 0 0 0 1.5-1.5v-13A1.5 1.5 0 0 0 21.5 4zM12 14.5L3.7 8.5h16.6L12 14.5z"/></svg>
          <span style={{ color: '#fff', fontWeight: 600, fontSize: 14, letterSpacing: 0.1 }}>Outlook</span>
        </div>
        {/* Search */}
        <div style={{ flex: 1, maxWidth: 360, background: 'rgba(255,255,255,0.15)', border: '1px solid rgba(255,255,255,0.25)', borderRadius: 4, padding: '5px 10px', color: 'rgba(255,255,255,0.85)', fontSize: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
          Search
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 14, color: '#fff' }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" opacity="0.9"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" opacity="0.9"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
          <div style={{ width: 26, height: 26, borderRadius: '50%', background: '#FFB900', color: OUTLOOK_BLUE_DARK, fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>JC</div>
        </div>
      </div>

      {/* 3-pane body */}
      <div style={{ display: 'flex', flex: 1, minHeight: 0 }}>
        {/* Left: folder rail */}
        <div className="demo-sidebar demo-sidebar--outlook-folders" style={{ width: 180, background: OUTLOOK_BG, borderRight: `1px solid ${OUTLOOK_BORDER}`, flexShrink: 0, display: 'flex', flexDirection: 'column' }}>
          {/* New mail button */}
          <div style={{ padding: '12px 12px 10px' }}>
            <div style={{ background: OUTLOOK_BLUE, color: '#fff', padding: '7px 14px', borderRadius: 4, fontSize: 12, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 7 }}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
              New mail
            </div>
          </div>
          {/* Folders */}
          <div style={{ padding: '4px 6px', flex: 1 }}>
            <div style={{ fontSize: 10, color: TEXT_SECONDARY, padding: '6px 10px', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>Favorites</div>
            {folders.map(f => (
              <div key={f.name} style={{
                padding: '6px 10px', fontSize: 12,
                color: f.active ? OUTLOOK_BLUE : TEXT_PRIMARY,
                background: f.active ? '#EFF6FC' : 'transparent',
                borderLeft: f.active ? `3px solid ${OUTLOOK_BLUE}` : '3px solid transparent',
                borderRadius: 2,
                display: 'flex', alignItems: 'center', gap: 8,
                fontWeight: f.active ? 600 : 400,
                marginBottom: 1,
              }}>
                <span style={{ color: f.active ? OUTLOOK_BLUE : TEXT_SECONDARY, display: 'flex' }}>{f.icon}</span>
                <span style={{ flex: 1 }}>{f.name}</span>
                {f.count && <span style={{ fontSize: 10, color: f.active ? OUTLOOK_BLUE : TEXT_SECONDARY, fontWeight: 600 }}>{f.count}</span>}
              </div>
            ))}
          </div>
          {/* Bottom: Dax agent presence */}
          <div style={{ borderTop: `1px solid ${OUTLOOK_BORDER}`, padding: '10px 12px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 24, height: 24, borderRadius: '50%', background: OUTLOOK_BLUE, color: '#fff', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>D</div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 11, color: TEXT_PRIMARY, fontWeight: 600 }}>Dax · Agent</div>
                <div style={{ fontSize: 10, color: '#107C10' }}>● Online</div>
              </div>
            </div>
          </div>
        </div>

        {/* Middle: message list */}
        <div className="demo-sidebar demo-sidebar--outlook-list" style={{ width: 240, background: '#fff', borderRight: `1px solid ${OUTLOOK_BORDER}`, flexShrink: 0, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ padding: '10px 14px 8px', borderBottom: `1px solid ${OUTLOOK_BORDER}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: TEXT_PRIMARY }}>Inbox</span>
            <span style={{ fontSize: 11, color: TEXT_SECONDARY }}>By date ▾</span>
          </div>
          <div style={{ overflowY: 'auto', flex: 1, scrollbarWidth: 'none' }}>
            {inboxList.map((it, i) => (
              <div key={i} style={{
                padding: '10px 14px',
                borderBottom: `1px solid ${OUTLOOK_BORDER}`,
                background: it.active ? '#EFF6FC' : 'transparent',
                borderLeft: it.active ? `3px solid ${OUTLOOK_BLUE}` : '3px solid transparent',
                cursor: 'default',
              }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 2 }}>
                  <span style={{ fontSize: 12, color: TEXT_PRIMARY, fontWeight: it.unread ? 700 : 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 130 }}>{it.from}</span>
                  <span style={{ fontSize: 10, color: it.unread ? OUTLOOK_BLUE : TEXT_SECONDARY, fontWeight: it.unread ? 600 : 400, flexShrink: 0, marginLeft: 6 }}>{it.time}</span>
                </div>
                <div style={{ fontSize: 11.5, color: it.unread ? TEXT_PRIMARY : TEXT_SECONDARY, fontWeight: it.unread ? 600 : 400, marginBottom: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.subject}</div>
                <div style={{ fontSize: 11, color: TEXT_SECONDARY, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.preview}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Right: reading pane */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, background: '#fff' }}>
          {/* Subject + actions */}
          <div style={{ padding: '14px 22px 12px', borderBottom: `1px solid ${OUTLOOK_BORDER}`, flexShrink: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 600, color: TEXT_PRIMARY, marginBottom: 6, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{emailIn?.subject || 'Rate quote — CHI to ATL'}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, fontSize: 11, color: TEXT_SECONDARY }}>
              {['Reply', 'Reply all', 'Forward', 'Archive', 'Delete'].map(a => (
                <span key={a} style={{ color: a === 'Reply' ? OUTLOOK_BLUE : TEXT_SECONDARY, fontWeight: a === 'Reply' ? 600 : 400 }}>{a}</span>
              ))}
            </div>
          </div>

          {/* Thread */}
          <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '16px 22px', display: 'flex', flexDirection: 'column', gap: 14, scrollbarWidth: 'none', minHeight: 0 }}>
            {emailIn && (
              <div className="msg-reveal" style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <div style={{ width: 32, height: 32, borderRadius: '50%', background: '#FFB900', color: TEXT_PRIMARY, fontSize: 12, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>A</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 4, gap: 8 }}>
                    <div>
                      <span style={{ fontSize: 13, fontWeight: 600, color: TEXT_PRIMARY }}>Apex Logistics</span>
                      <span style={{ fontSize: 11, color: TEXT_SECONDARY, marginLeft: 8 }}>&lt;{emailIn.from}&gt;</span>
                    </div>
                    <span style={{ fontSize: 11, color: TEXT_SECONDARY, flexShrink: 0 }}>11:42 AM</span>
                  </div>
                  <div style={{ fontSize: 12, color: '#3B3A39', lineHeight: 1.65 }}>
                    Hi team,<br /><br />
                    Need a rate on the below. Pickup ready Tue 5/6.<br /><br />
                    <span style={{ display: 'inline-block', background: '#F3F2F1', borderLeft: `2px solid ${OUTLOOK_BORDER}`, padding: '8px 12px', marginTop: 2, fontSize: 11.5, lineHeight: 1.65 }}>
                      Origin: Chicago, IL 60607<br />
                      Dest: Atlanta, GA 30318<br />
                      8 skids · ~2,400 lbs · Class 85<br />
                      Liftgate at delivery (residential receiver)
                    </span><br /><br />
                    Thanks,<br />
                    Sarah · Apex Shipping
                  </div>
                </div>
              </div>
            )}
            {thread.map((m, i) => {
              if (m.type === 'quote-card') return (
                <div key={i} className="msg-reveal" style={{ marginLeft: 44, border: `1px solid #C7E0F4`, borderRadius: 4, overflow: 'hidden', background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
                  <div style={{ background: OUTLOOK_BLUE, padding: '8px 14px', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V7"/><path d="M3 7l9 6 9-6"/></svg>
                    <span style={{ color: '#fff', fontWeight: 600, fontSize: 11, letterSpacing: 0.3 }}>LTL RATE QUOTE</span>
                    <span style={{ marginLeft: 'auto', background: 'rgba(255,255,255,0.18)', color: '#fff', fontSize: 10, padding: '2px 7px', borderRadius: 3, fontWeight: 600 }}>DAX · auto · TruckMate</span>
                  </div>
                  <div style={{ padding: '14px 18px 16px', background: '#F3F9FD' }}>
                    {/* Lane summary */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', columnGap: 14, rowGap: 4, marginBottom: 12 }}>
                      {[['Lane', m.data.lane], ['Load', m.data.weight], ['Class', m.data.cls], ['Transit', m.data.transit]].map(([k, v]) => (
                        <React.Fragment key={k}>
                          <span style={{ fontSize: 11, color: TEXT_SECONDARY, fontWeight: 600 }}>{k}</span>
                          <span style={{ fontSize: 11.5, color: TEXT_PRIMARY }}>{v}</span>
                        </React.Fragment>
                      ))}
                    </div>

                    {/* Charge breakdown */}
                    <div style={{ borderTop: `1px solid #DCE9FF`, paddingTop: 10 }}>
                      {m.data.breakdown.map(([label, amt]) => (
                        <div key={label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0', fontSize: 11.5, color: TEXT_PRIMARY }}>
                          <span style={{ color: amt.startsWith('−') ? '#107C10' : TEXT_SECONDARY }}>{label}</span>
                          <span style={{ fontWeight: 500, color: amt.startsWith('−') ? '#107C10' : TEXT_PRIMARY, fontVariantNumeric: 'tabular-nums' }}>{amt}</span>
                        </div>
                      ))}
                    </div>

                    {/* Total */}
                    <div style={{ borderTop: `1px solid #DCE9FF`, marginTop: 8, paddingTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                      <span style={{ fontSize: 11, color: TEXT_SECONDARY, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.04 }}>Total</span>
                      <span style={{ fontSize: 22, fontWeight: 700, color: TEXT_PRIMARY, fontVariantNumeric: 'tabular-nums' }}>{m.data.total}</span>
                    </div>

                    {/* Footer chips */}
                    <div style={{ display: 'flex', gap: 6, marginTop: 12, flexWrap: 'wrap' }}>
                      <span style={{ background: '#fff', border: `1px solid ${OUTLOOK_BORDER}`, borderRadius: 3, padding: '3px 8px', fontSize: 10.5, color: TEXT_SECONDARY }}>{m.data.validity}</span>
                      <span style={{ background: '#fff', border: `1px solid ${OUTLOOK_BORDER}`, borderRadius: 3, padding: '3px 8px', fontSize: 10.5, color: TEXT_SECONDARY, fontFamily: 'monospace' }}>Ref {m.data.ref}</span>
                    </div>
                  </div>
                </div>
              );
              const isAgent = m.type === 'agent-email';
              return (
                <div key={i} className="msg-reveal" style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <div style={{ width: 32, height: 32, borderRadius: '50%', background: isAgent ? OUTLOOK_BLUE : '#FFB900', color: isAgent ? '#fff' : TEXT_PRIMARY, fontSize: 12, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    {isAgent ? 'D' : 'A'}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 4, gap: 8, flexWrap: 'wrap' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span style={{ fontSize: 13, fontWeight: 600, color: TEXT_PRIMARY }}>{m.name}</span>
                        {isAgent && <span style={{ background: '#EFF6FC', color: OUTLOOK_BLUE, fontSize: 10, padding: '1px 7px', borderRadius: 3, fontWeight: 600 }}>AGENT</span>}
                      </div>
                      <span style={{ fontSize: 11, color: TEXT_SECONDARY }}>11:{45 + i} AM</span>
                    </div>
                    <div style={{ color: '#3B3A39', fontSize: 12, lineHeight: 1.6, wordBreak: 'break-word' }}>{m.msg}</div>
                  </div>
                </div>
              );
            })}
            {showTyping && (
              <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                <div style={{ width: 32, height: 32, borderRadius: '50%', background: OUTLOOK_BLUE, color: '#fff', fontSize: 12, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>D</div>
                <TypingBubble color={OUTLOOK_BLUE} />
              </div>
            )}
          </div>

          {/* Reply box */}
          <div style={{ padding: '12px 22px 16px', borderTop: `1px solid ${OUTLOOK_BORDER}`, flexShrink: 0 }}>
            <div style={{ border: `1px solid ${OUTLOOK_BORDER}`, borderRadius: 4, padding: '10px 14px', color: TEXT_SECONDARY, fontSize: 12, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span>Reply or forward</span>
              <span style={{ color: OUTLOOK_BLUE, fontSize: 11, fontWeight: 600 }}>Send ▸</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Slack Mockup ──────────────────────────────────────────────────
function SlackMockup({ messages, showTyping }) {
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, showTyping]);

  return (
    <div style={{ display: 'flex', height: '100%', background: '#FFFFFF', fontFamily: "'Geist', 'Inter', system-ui, sans-serif", overflow: 'hidden' }}>
      {/* Workspace sidebar */}
      <div className="demo-sidebar demo-sidebar--slack" style={{ width: 200, background: '#3F0E40', flexShrink: 0, display: 'flex', flexDirection: 'column', color: '#fff' }}>
        <div style={{ padding: '14px 16px 12px', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
          <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 2 }}>Maritime Ontario</div>
          <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.55)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#2BAC76', display: 'inline-block' }} />
            J. Carter
          </div>
        </div>
        <div style={{ padding: '10px 8px', flex: 1 }}>
          <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)', textTransform: 'uppercase', letterSpacing: '0.04em', padding: '4px 8px' }}>Channels</div>
          {[
            { name: 'general' },
            { name: 'dispatch' },
            { name: 'ar-ops', active: true },
            { name: 'driver-pool' },
          ].map((c) => (
            <div key={c.name} style={{
              padding: '5px 10px', borderRadius: 4, fontSize: 12,
              background: c.active ? '#1164A3' : 'transparent',
              color: c.active ? '#fff' : 'rgba(255,255,255,0.78)',
              display: 'flex', alignItems: 'center', gap: 6, marginBottom: 1,
            }}>
              <span style={{ opacity: 0.7 }}>#</span>{c.name}
            </div>
          ))}
        </div>
        <div style={{ borderTop: '1px solid rgba(255,255,255,0.06)', padding: '8px 12px' }}>
          <div style={{ fontSize: 10, color: '#A284D0', fontWeight: 600 }}>Mira — Agent</div>
          <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.45)' }}>Active</div>
        </div>
      </div>

      {/* Channel */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, background: '#fff' }}>
        <div style={{ padding: '12px 18px', borderBottom: '1px solid #E8E8E8', flexShrink: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: '#1D1C1D', display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ color: '#9A9A9A' }}>#</span>ar-ops
          </div>
          <div style={{ fontSize: 11, color: '#888', marginTop: 1 }}>Detention &amp; accessorial — Mira’s channel</div>
        </div>

        <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '14px 18px', display: 'flex', flexDirection: 'column', gap: 14, scrollbarWidth: 'none', minHeight: 0 }}>
          {messages.map((m, i) => {
            const isAgent = m.type === 'agent';
            return (
              <div key={i} className="msg-reveal" style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <div style={{ width: 32, height: 32, borderRadius: 6, background: isAgent ? '#611F69' : '#3A3A3A', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 11, fontWeight: 700 }}>
                  {isAgent ? 'M' : (m.name?.[0] || '?')}
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 2, flexWrap: 'wrap' }}>
                    <span style={{ color: '#1D1C1D', fontWeight: 700, fontSize: 13 }}>{m.name}</span>
                    {isAgent && <span style={{ background: '#F4ECFA', color: '#611F69', fontSize: 9, padding: '1px 6px', borderRadius: 3, fontFamily: 'monospace', fontWeight: 600 }}>APP</span>}
                    <span style={{ color: '#9A9A9A', fontSize: 10 }}>10:{14 + i * 4} AM</span>
                  </div>
                  <div style={{ color: '#1D1C1D', fontSize: 13, lineHeight: 1.55, whiteSpace: 'pre-line', wordBreak: 'break-word' }}>{m.msg}</div>
                </div>
              </div>
            );
          })}
          {showTyping && (
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <div style={{ width: 32, height: 32, borderRadius: 6, background: '#611F69', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 11, fontWeight: 700 }}>M</div>
              <TypingBubble color="#611F69" />
            </div>
          )}
        </div>

        <div style={{ padding: '10px 18px 14px', flexShrink: 0 }}>
          <div style={{ background: '#fff', border: '1px solid #E0E0E0', borderRadius: 8, padding: '9px 12px', color: '#9A9A9A', fontSize: 12 }}>Message #ar-ops</div>
        </div>
      </div>
    </div>
  );
}

// ── Device Frames ─────────────────────────────────────────────────
function PhoneFrame({ children }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      background: '#1C1C1E',
      borderRadius: 44,
      overflow: 'hidden',
      boxShadow: '0 0 0 1px rgba(255,255,255,0.08), 0 32px 80px rgba(0,0,0,0.5), 0 8px 24px rgba(0,0,0,0.3)',
      display: 'flex', flexDirection: 'column',
      position: 'relative',
    }}>
      {/* Dynamic island */}
      <div style={{ position: 'absolute', top: 12, left: '50%', transform: 'translateX(-50%)', width: 96, height: 28, background: '#000', borderRadius: 20, zIndex: 10 }}></div>
      {/* Status bar */}
      <div style={{ height: 50, background: '#F2F2F7', flexShrink: 0, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', padding: '0 20px 8px' }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: '#000', fontFamily: "'Geist', -apple-system, sans-serif" }}>9:41</span>
        <div style={{ display: 'flex', gap: 5, alignItems: 'center' }}>
          <svg width="14" height="10" viewBox="0 0 14 10" fill="#000"><rect x="0" y="3.5" width="2.5" height="6.5" rx="0.8"/><rect x="3.5" y="2" width="2.5" height="8" rx="0.8"/><rect x="7" y="0.5" width="2.5" height="9.5" rx="0.8"/><rect x="10.5" y="0.5" width="2.5" height="9.5" rx="0.8" opacity="0.3"/></svg>
          <svg width="14" height="10" viewBox="0 0 16 12" fill="#000"><path d="M8 2.5C10.5 2.5 12.7 3.5 14.3 5.1L15.5 3.9C13.6 2 11 0.8 8 0.8C5 0.8 2.4 2 0.5 3.9L1.7 5.1C3.3 3.5 5.5 2.5 8 2.5Z"/><path d="M8 5.5C9.7 5.5 11.2 6.2 12.2 7.3L13.4 6.1C12.1 4.8 10.1 4 8 4C5.9 4 3.9 4.8 2.6 6.1L3.8 7.3C4.8 6.2 6.3 5.5 8 5.5Z"/><circle cx="8" cy="10" r="1.8"/></svg>
          <div style={{ display: 'flex', gap: 1, alignItems: 'center' }}>
            <div style={{ width: 20, height: 10, border: '1.5px solid #000', borderRadius: 2.5, position: 'relative', display: 'flex', alignItems: 'center', padding: '0 2px' }}>
              <div style={{ flex: 1, height: 6, background: '#000', borderRadius: 1 }}></div>
            </div>
          </div>
        </div>
      </div>
      <div style={{ flex: 1, overflow: 'hidden', minHeight: 0 }}>{children}</div>
      {/* Home indicator */}
      <div style={{ height: 28, background: '#F2F2F7', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <div style={{ width: 100, height: 4, background: '#000', borderRadius: 2, opacity: 0.2 }}></div>
      </div>
    </div>
  );
}

function DesktopWindow({ platformColor, children }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      borderRadius: 10,
      overflow: 'hidden',
      boxShadow: '0 0 0 1px rgba(0,0,0,0.12), 0 24px 60px rgba(0,0,0,0.25)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ height: 36, background: '#2A2A2A', display: 'flex', alignItems: 'center', padding: '0 14px', gap: 8, flexShrink: 0 }}>
        <div style={{ display: 'flex', gap: 6 }}>
          {['#FF5F57','#FFBD2E','#28C840'].map((c, i) => (
            <div key={i} style={{ width: 11, height: 11, borderRadius: '50%', background: c }}></div>
          ))}
        </div>
        <div style={{ flex: 1, textAlign: 'center' }}>
          <span style={{ color: 'rgba(255,255,255,0.35)', fontSize: 11, fontFamily: 'monospace', letterSpacing: '0.04em' }}>Echo · Agents</span>
        </div>
      </div>
      <div style={{ flex: 1, overflow: 'hidden', minHeight: 0 }}>{children}</div>
    </div>
  );
}

// ── Main HeroDemo ─────────────────────────────────────────────────
function HeroDemo({ activeIdx: controlledIdx, onSelect, hideTabs = false } = {}) {
  const [internalIdx, setInternalIdx] = useState(0);
  const isControlled = typeof controlledIdx === 'number';
  const activeIdx = isControlled ? controlledIdx : internalIdx;
  const setActiveIdx = (i) => { if (isControlled) onSelect?.(i); else setInternalIdx(i); };
  const [displayedMessages, setDisplayedMessages] = useState([]);
  const [showTyping, setShowTyping] = useState(false);
  const [progress, setProgress] = useState(0);
  const [fading, setFading] = useState(false);
  const timeoutsRef = useRef([]);
  const rafRef = useRef(null);
  const startRef = useRef(null);
  const autoRef = useRef(null);

  const surface = SURFACES[activeIdx];

  const clearAll = useCallback(() => {
    timeoutsRef.current.forEach(clearTimeout);
    timeoutsRef.current = [];
    if (rafRef.current) cancelAnimationFrame(rafRef.current);
    if (autoRef.current) clearTimeout(autoRef.current);
  }, []);

  const startProgress = useCallback(() => {
    startRef.current = performance.now();
    const tick = () => {
      const pct = Math.min(((performance.now() - startRef.current) / ROTATION_MS) * 100, 100);
      setProgress(pct);
      if (pct < 100) rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
  }, []);

  const playTimeline = useCallback((surf) => {
    surf.timeline.forEach((item) => {
      const t = setTimeout(() => {
        if (item.type === 'typing') {
          setShowTyping(true);
        } else {
          setShowTyping(false);
          setDisplayedMessages(prev => [...prev, item]);
        }
      }, item.delay);
      timeoutsRef.current.push(t);
    });
  }, []);

  const goTo = useCallback((idx) => {
    clearAll();
    setFading(true);
    setTimeout(() => {
      setActiveIdx(idx);
      setDisplayedMessages([]);
      setShowTyping(false);
      setProgress(0);
      setFading(false);
      playTimeline(SURFACES[idx]);
      startProgress();
      // Only auto-advance when the demo is uncontrolled (standalone usage)
      if (!isControlled) {
        autoRef.current = setTimeout(() => goTo((idx + 1) % SURFACES.length), ROTATION_MS);
      }
    }, 300);
  }, [clearAll, playTimeline, startProgress, isControlled]);

  // First-mount initialization
  useEffect(() => {
    playTimeline(SURFACES[activeIdx]);
    startProgress();
    if (!isControlled) {
      autoRef.current = setTimeout(() => goTo((activeIdx + 1) % SURFACES.length), ROTATION_MS);
    }
    return clearAll;
  }, []);

  // React to external selection changes (controlled mode)
  useEffect(() => {
    if (!isControlled) return;
    // Skip the very first render (handled by the init effect above)
    clearAll();
    setFading(true);
    const t = setTimeout(() => {
      setDisplayedMessages([]);
      setShowTyping(false);
      setProgress(0);
      setFading(false);
      playTimeline(SURFACES[controlledIdx]);
      startProgress();
    }, 300);
    return () => clearTimeout(t);
  }, [controlledIdx]);

  const renderContent = () => {
    const props = { messages: displayedMessages, showTyping };
    switch (surface.id) {
      case 'sms':   return <SMSMockup {...props} agent={surface.agent} />;
      case 'teams': return <TeamsMockup {...props} agent={surface.agent} channelName="ar-team" userName="D. Patel" userInitials="DP" />;
      case 'email': return <EmailMockup {...props} />;
      case 'slack': return <SlackMockup {...props} />;
      default: return null;
    }
  };

  const isPhone = surface.type === 'phone';

  return (
    <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 24 }}>
      {/* Surface tabs (hidden in controlled mode — agent cards replace them) */}
      {!hideTabs && (
      <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
        {SURFACES.map((s, i) => {
          const active = i === activeIdx;
          return (
            <button key={s.id} onClick={() => goTo(i)} style={{
              padding: '8px 18px', borderRadius: 8, border: `1px solid ${active ? s.platformColor : 'var(--hairline)'}`,
              background: active ? `${s.platformColor}1a` : 'var(--bg)',
              color: active ? s.platformColor : 'var(--muted)',
              fontFamily: 'var(--ff-mono)', fontSize: 10, letterSpacing: '0.1em',
              cursor: 'pointer', transition: 'all 0.25s cubic-bezier(0.4,0,0.2,1)',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              {active && <span style={{ width: 6, height: 6, borderRadius: '50%', background: s.platformColor, animation: 'pulse 2s ease-in-out infinite', display: 'inline-block' }}></span>}
              {s.num} · {s.agent} · {s.platform}
            </button>
          );
        })}
      </div>
      )}

      {/* Device */}
      <div style={{
        opacity: fading ? 0 : 1,
        transform: fading ? 'scale(0.97) translateY(8px)' : 'scale(1) translateY(0)',
        transition: 'opacity 0.3s cubic-bezier(0.4,0,0.2,1), transform 0.3s cubic-bezier(0.4,0,0.2,1)',
        display: 'flex', justifyContent: 'center',
        position: 'relative',
      }}>
        {/* Glow behind device */}
        <div style={{
          position: 'absolute', inset: -40, borderRadius: '50%', pointerEvents: 'none',
          background: `radial-gradient(ellipse at center, ${surface.glowColor} 0%, transparent 70%)`,
          transition: 'background 0.8s',
          zIndex: 0,
        }} />

        <div className="demo-device-frame" style={{
          position: 'relative', zIndex: 1,
          width: isPhone ? 320 : '100%',
          height: isPhone ? 640 : 560,
          maxWidth: isPhone ? 320 : 1080,
        }}>
          {isPhone
            ? <PhoneFrame>{renderContent()}</PhoneFrame>
            : <DesktopWindow platformColor={surface.platformColor}>{renderContent()}</DesktopWindow>
          }
        </div>
      </div>

      {/* Progress dots */}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'center', alignItems: 'center' }}>
        {SURFACES.map((s, i) => {
          const active = i === activeIdx;
          return (
            <button key={s.id} onClick={() => goTo(i)} style={{ background: 'none', border: 'none', padding: 4, cursor: 'pointer' }}>
              <div style={{
                height: 4, width: active ? 28 : 4, borderRadius: 2,
                background: active ? s.platformColor : 'var(--hairline)',
                transition: 'all 0.4s cubic-bezier(0.4,0,0.2,1)',
                overflow: 'hidden', position: 'relative',
              }}>
                {active && (
                  <div style={{
                    position: 'absolute', left: 0, top: 0, bottom: 0,
                    width: `${progress}%`,
                    background: 'rgba(255,255,255,0.5)',
                    transition: 'width 0.1s linear',
                  }} />
                )}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { HeroDemo, ECHO_SURFACES: SURFACES });
