// Live agent demo + Channels switcher
// Two interactive components used in the landing page.

const DEMO_SCRIPTS = [
  {
    biz: 'Lake Norman Dental',
    industry: 'Dental practice',
    location: 'Cornelius, NC',
    avatar: 'LN',
    accent: '#1B4BFF',
    msgs: [
      { who: 'them', t: 'Hi! Can I book a cleaning next week? New patient.' },
      { who: 'us', t: 'Welcome! We have Tue 3:40 PM, Wed 9:10 AM, or Thu 11:30 AM open. Want all three texted?' },
      { who: 'them', t: 'Wed 9:10. And how much without insurance?' },
      { who: 'us', t: 'New-patient cleaning + exam is $215 self-pay. Booked — confirmation + intake form sent.' },
    ],
    handoff: { tag: 'HUBSPOT', text: 'New patient · intake sent · front desk notified' },
  },
  {
    biz: 'Carolina Comfort HVAC',
    industry: 'HVAC contractor',
    location: 'Mooresville, NC',
    avatar: 'CC',
    accent: '#FF6A1A',
    msgs: [
      { who: 'them', t: 'My AC stopped overnight. Can someone come today?' },
      { who: 'us', t: 'Sorry to hear it. We have a 2 PM emergency slot in your zip — $89 diagnostic, waived if you book the repair.' },
      { who: 'them', t: 'Yes please. Older Trane, around 12 years.' },
      { who: 'us', t: 'Booked 2 PM. I\'ve flagged "aging system / possible replacement quote" for the tech.' },
    ],
    handoff: { tag: 'PIPEDRIVE', text: 'High-intent lead · est. ticket $4,200 · tech dispatched' },
  },
  {
    biz: 'Brightline Law',
    industry: 'Estate planning',
    location: 'Davidson, NC',
    avatar: 'BL',
    accent: '#0E1116',
    msgs: [
      { who: 'them', t: 'Do you handle revocable living trusts? What does it cost?' },
      { who: 'us', t: 'We do. Flat fee $2,800 for individuals, $3,400 for couples. Includes a will and POA.' },
      { who: 'them', t: 'I\'m married, two kids. Can we talk this week?' },
      { who: 'us', t: 'Yes — Thu 10 AM with Sarah works. She\'ll review your assets in the intake form before the call.' },
    ],
    handoff: { tag: 'SHEETS', text: 'Qualified · couple + minors · scheduled w/ Sarah' },
  },
];

// ── Live agent demo: cycles industries with staggered message reveal ──
function LiveAgentDemo() {
  const [idx, setIdx] = React.useState(0);
  const [shown, setShown] = React.useState(1); // # of messages visible
  const [showHandoff, setShowHandoff] = React.useState(false);
  const script = DEMO_SCRIPTS[idx];

  React.useEffect(() => {
    setShown(1);
    setShowHandoff(false);
    const total = script.msgs.length;
    const timers = [];
    for (let i = 2; i <= total; i++) {
      timers.push(setTimeout(() => setShown(i), (i - 1) * 1400));
    }
    timers.push(setTimeout(() => setShowHandoff(true), total * 1400 + 200));
    // advance after dwell
    timers.push(setTimeout(() => setIdx((idx + 1) % DEMO_SCRIPTS.length), total * 1400 + 3800));
    return () => timers.forEach(clearTimeout);
  }, [idx]);

  const demoStyles = {
    card: {
      background: TOKEN.paper, border: `1px solid ${TOKEN.hair}`,
      padding: 24, position: 'relative',
      fontFamily: '"IBM Plex Sans", system-ui, sans-serif',
    },
    head: {
      display: 'flex', alignItems: 'center', gap: 12,
      paddingBottom: 16, borderBottom: `1px solid ${TOKEN.hair}`,
    },
    avatar: {
      width: 38, height: 38, background: script.accent, color: '#fff',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: '"IBM Plex Mono", monospace', fontWeight: 600, fontSize: 14,
      letterSpacing: 0.5, transition: 'background .4s ease',
    },
    name: { fontWeight: 600, fontSize: 14, letterSpacing: -0.2, color: TOKEN.ink },
    sub: { fontSize: 11.5, color: TOKEN.mute, letterSpacing: -0.1, marginTop: 2 },
    pill: {
      marginLeft: 'auto', padding: '4px 8px', background: TOKEN.ink, color: TOKEN.paper,
      fontFamily: '"IBM Plex Mono", monospace', fontSize: 10, fontWeight: 500, letterSpacing: 1,
    },
  };

  return (
    <div style={demoStyles.card}>
      <CornerMark where="tl"/><CornerMark where="tr"/><CornerMark where="bl"/><CornerMark where="br"/>

      <div style={demoStyles.head}>
        <div style={demoStyles.avatar}>{script.avatar}</div>
        <div>
          <div style={demoStyles.name}>{script.biz}</div>
          <div style={demoStyles.sub}>
            {script.industry} · {script.location}
          </div>
        </div>
        <div style={demoStyles.pill}>● LIVE</div>
      </div>

      <div style={{ minHeight: 320 }}>
        {script.msgs.slice(0, shown).map((m, i) => (
          <DemoBubble key={`${idx}-${i}`} who={m.who} text={m.t} accent={script.accent} typing={i === shown - 1 && i > 0}/>
        ))}
      </div>

      <div style={{
        marginTop: 16, padding: '12px 14px',
        background: showHandoff ? TOKEN.ink : TOKEN.paperDeep,
        color: showHandoff ? TOKEN.paper : TOKEN.mute,
        display: 'flex', alignItems: 'center', gap: 12,
        transition: 'all .5s ease',
        opacity: showHandoff ? 1 : 0.6,
      }}>
        <span style={{
          fontFamily: '"IBM Plex Mono", monospace', fontSize: 10, fontWeight: 600,
          letterSpacing: 1, padding: '3px 6px',
          background: showHandoff ? TOKEN.orange : 'transparent',
          color: showHandoff ? '#fff' : TOKEN.mute,
          border: showHandoff ? 'none' : `1px solid ${TOKEN.hair}`,
        }}>↗ {script.handoff.tag}</span>
        <span style={{ fontSize: 13, letterSpacing: -0.1 }}>{script.handoff.text}</span>
      </div>

      {/* industry tabs (clickable) */}
      <div style={{
        marginTop: 16, display: 'flex', gap: 0,
        borderTop: `1px solid ${TOKEN.hair}`, paddingTop: 12,
      }}>
        {DEMO_SCRIPTS.map((s, i) => (
          <button key={s.biz} onClick={() => setIdx(i)} style={{
            flex: 1, background: 'transparent', border: 'none',
            padding: '6px 4px', cursor: 'pointer', textAlign: 'left',
            borderTop: i === idx ? `2px solid ${TOKEN.orange}` : `2px solid transparent`,
            transition: 'all .25s ease', marginTop: -13, paddingTop: 12,
          }}>
            <Mono color={i === idx ? TOKEN.ink : TOKEN.mute} size={10}>
              0{i+1} · {s.industry}
            </Mono>
          </button>
        ))}
      </div>
    </div>
  );
}

function DemoBubble({ who, text, accent, typing }) {
  const isUs = who === 'us';
  const [t, setT] = React.useState('');
  React.useEffect(() => {
    if (!typing) { setT(text); return; }
    let i = 0;
    const id = setInterval(() => {
      i++;
      setT(text.slice(0, i));
      if (i >= text.length) clearInterval(id);
    }, 14);
    return () => clearInterval(id);
  }, [text, typing]);

  return (
    <div style={{
      display: 'flex', justifyContent: isUs ? 'flex-end' : 'flex-start',
      margin: '12px 0', animation: 'demo-in .35s ease both',
    }}>
      <div style={{
        maxWidth: '82%', padding: '10px 14px',
        background: isUs ? accent : '#fff',
        color: isUs ? '#fff' : TOKEN.ink,
        border: isUs ? 'none' : `1px solid ${TOKEN.hair}`,
        fontSize: 14, lineHeight: 1.45, letterSpacing: -0.1,
      }}>{t}{typing && t.length < text.length && <span style={{ opacity: 0.5 }}>▍</span>}</div>
    </div>
  );
}

// ── Channels switcher: same conversation, three channel-appropriate skins ──
const CHANNELS = [
  { id: 'web', label: 'Website widget', detail: 'Drop-in chat · 1 script tag', kbd: 'WEB' },
  { id: 'sms', label: 'SMS', detail: 'Twilio · your business number', kbd: 'SMS' },
  { id: 'email', label: 'Email autoresponder', detail: 'support@ / info@ triage', kbd: 'EML' },
];

function ChannelDemo() {
  const [ch, setCh] = React.useState('web');

  const channelStyles = {
    wrap: { display: 'grid', gridTemplateColumns: '280px 1fr', gap: 0, border: `1px solid ${TOKEN.hair}`, background: TOKEN.paper },
    side: { borderRight: `1px solid ${TOKEN.hair}`, padding: 24 },
    tab: (active) => ({
      display: 'block', width: '100%', textAlign: 'left',
      padding: '14px 16px', marginBottom: 4, background: active ? TOKEN.ink : 'transparent',
      color: active ? TOKEN.paper : TOKEN.ink, border: 'none', cursor: 'pointer',
      transition: 'all .18s ease',
    }),
    stage: { padding: 32, minHeight: 460, background: TOKEN.paperDeep, position: 'relative' },
  };

  return (
    <div style={channelStyles.wrap}>
      <div style={channelStyles.side}>
        <Mono>Select channel</Mono>
        <div style={{ marginTop: 16 }}>
          {CHANNELS.map(c => (
            <button key={c.id} onClick={() => setCh(c.id)} style={channelStyles.tab(ch === c.id)}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span style={{
                  fontFamily: '"IBM Plex Mono", monospace', fontSize: 10, opacity: 0.6, letterSpacing: 1,
                }}>{c.kbd}</span>
                <span style={{
                  fontFamily: '"IBM Plex Sans", system-ui', fontSize: 15, fontWeight: 500, letterSpacing: -0.2,
                }}>{c.label}</span>
              </div>
              <div style={{
                fontSize: 12, marginTop: 4, opacity: 0.7, letterSpacing: -0.1,
              }}>{c.detail}</div>
            </button>
          ))}
        </div>

        <div style={{ marginTop: 28, paddingTop: 20, borderTop: `1px solid ${TOKEN.hair}` }}>
          <Mono>Same agent</Mono>
          <p style={{ marginTop: 10, fontSize: 13, color: TOKEN.mute, lineHeight: 1.55, letterSpacing: -0.1 }}>
            One knowledge base, one persona, one set of guardrails. Channel chrome adapts; the brain doesn't.
          </p>
        </div>
      </div>

      <div style={channelStyles.stage}>
        <CornerMark where="tl"/><CornerMark where="tr"/><CornerMark where="bl"/><CornerMark where="br"/>
        {ch === 'web' && <WebStage/>}
        {ch === 'sms' && <SMSStage/>}
        {ch === 'email' && <EmailStage/>}
      </div>
    </div>
  );
}

function WebStage() {
  return (
    <div style={{
      maxWidth: 380, marginLeft: 'auto', background: '#fff',
      border: `1px solid ${TOKEN.hair}`, boxShadow: '0 30px 80px -30px rgba(14,17,22,0.18)',
      fontFamily: '"IBM Plex Sans", system-ui',
    }}>
      <div style={{
        background: TOKEN.ink, color: TOKEN.paper, padding: '14px 16px',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{ width: 28, height: 28, background: TOKEN.orange, fontWeight: 600, fontSize: 12, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>LN</div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Lake Norman Dental</div>
          <div style={{ fontSize: 11, opacity: 0.7 }}>Typically replies in 4 sec</div>
        </div>
      </div>
      <div style={{ padding: 16 }}>
        <div style={{ padding: '10px 12px', background: TOKEN.paperDeep, fontSize: 13.5, marginBottom: 10 }}>Hi! Can I book a cleaning next week?</div>
        <div style={{ padding: '10px 12px', background: TOKEN.blue, color: '#fff', fontSize: 13.5, marginLeft: 24 }}>Welcome! Wed 9:10 AM works — want me to text confirmation?</div>
        <div style={{ display: 'flex', gap: 6, marginTop: 14 }}>
          <Pill primary>Confirm Wed 9:10</Pill>
          <Pill>Other times</Pill>
        </div>
      </div>
    </div>
  );
}

function SMSStage() {
  return (
    <div style={{
      maxWidth: 320, marginLeft: 'auto', background: '#000', borderRadius: 36, padding: 8,
      fontFamily: '"IBM Plex Sans", system-ui',
    }}>
      <div style={{ background: TOKEN.paper, borderRadius: 28, padding: 18, minHeight: 380 }}>
        <div style={{ textAlign: 'center', paddingBottom: 12, borderBottom: `1px solid ${TOKEN.hair}` }}>
          <div style={{ fontSize: 12, color: TOKEN.mute, letterSpacing: -0.1 }}>+1 (704) 555-0142</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: TOKEN.ink, marginTop: 2 }}>Lake Norman Dental</div>
        </div>
        <div style={{ marginTop: 16 }}>
          <SMSBub side="them" text="Hi! Can I book a cleaning next week?"/>
          <SMSBub side="us" text="Wed 9:10 AM open. Reply YES to confirm — we'll text the address."/>
          <SMSBub side="them" text="YES"/>
          <SMSBub side="us" text="Confirmed ✓ 13851 Statesville Rd. New patient form sent."/>
        </div>
      </div>
    </div>
  );
}
function SMSBub({ side, text }) {
  const us = side === 'us';
  return (
    <div style={{ display: 'flex', justifyContent: us ? 'flex-end' : 'flex-start', marginBottom: 6 }}>
      <div style={{
        maxWidth: '80%', padding: '8px 12px', borderRadius: 18,
        background: us ? '#007AFF' : '#E9E9EB',
        color: us ? '#fff' : '#000', fontSize: 13.5, lineHeight: 1.35,
      }}>{text}</div>
    </div>
  );
}

function EmailStage() {
  return (
    <div style={{
      maxWidth: 520, marginLeft: 'auto', background: '#fff',
      border: `1px solid ${TOKEN.hair}`, fontFamily: '"IBM Plex Sans", system-ui',
    }}>
      <div style={{ padding: '14px 18px', borderBottom: `1px solid ${TOKEN.hair}` }}>
        <Mono size={10}>FROM</Mono>
        <div style={{ fontSize: 13, fontWeight: 600, color: TOKEN.ink, marginTop: 2 }}>support@lknortho.com</div>
        <Mono size={10} style={{ marginTop: 8, display: 'block' }}>SUBJECT</Mono>
        <div style={{ fontSize: 14, color: TOKEN.ink, marginTop: 2 }}>Re: New patient cleaning</div>
      </div>
      <div style={{ padding: 18, fontSize: 13.5, lineHeight: 1.6, color: TOKEN.ink, letterSpacing: -0.05 }}>
        <p style={{ margin: '0 0 12px' }}>Hi Jamie,</p>
        <p style={{ margin: '0 0 12px' }}>Thanks for reaching out. We have <b>Wed 9:10 AM</b>, <b>Thu 11:30 AM</b>, or <b>Fri 2:00 PM</b> available next week for a new-patient cleaning and exam.</p>
        <p style={{ margin: '0 0 12px' }}>Reply with your preferred time and I'll send the new-patient intake form (~5 min) along with directions.</p>
        <p style={{ margin: '0 0 6px' }}>— Lake Norman Dental Agent</p>
        <Mono size={9} style={{ marginTop: 16, display: 'block' }}>Reply detected · forwarded to scheduler@lknortho.com</Mono>
      </div>
    </div>
  );
}

function Pill({ children, primary }) {
  return (
    <span style={{
      padding: '6px 12px', fontSize: 12, fontWeight: 500,
      background: primary ? TOKEN.blue : '#fff',
      color: primary ? '#fff' : TOKEN.ink,
      border: primary ? 'none' : `1px solid ${TOKEN.hair}`,
      letterSpacing: -0.1,
    }}>{children}</span>
  );
}

Object.assign(window, { LiveAgentDemo, ChannelDemo });
