// Ask 8/0 — focused on-page agent.
// Calls the server at /api/ask (Vercel serverless function). The system
// prompt, rules, and Anthropic API key live server-side and are never
// shipped to the browser.
//
// Edit copy in /assets/js/agent/booking.txt for the booking card.
// Edit rules + knowledge in /api/agent/rules.md and /api/agent/knowledge.md.

const STARTER_PROMPTS = [
  'What does 8/0 actually do?',
  'How does the layer handle schema drift?',
  'What does onboarding look like for a carrier?',
  'Is this SOC 2 compliant?',
  'Tell me about the team.',
];

function AskAgent() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { role: 'assistant', text: "I'm 8/0 — the on-page assistant for EightbyZero. Ask me about the layer, the team, how integrations work, or what a demo looks like." },
  ]);
  const [input, setInput] = React.useState('');
  const [thinking, setThinking] = React.useState(false);
  const [booking, setBooking] = React.useState({});
  const inputRef = React.useRef(null);
  const scrollRef = React.useRef(null);

  // Load booking UI config (the only thing still client-side — it's
  // just labels + the calendar URL).
  React.useEffect(() => {
    fetch('/assets/js/agent/booking.txt', { cache: 'no-store' })
      .then(r => r.ok ? r.text() : '')
      .then(text => {
        const out = {};
        text.split('\n').forEach(line => {
          const t = line.trim();
          if (!t || t.startsWith('#')) return;
          const m = t.match(/^([a-z_]+)\s*:\s*"?([^"]*)"?\s*$/i);
          if (m) out[m[1]] = m[2];
        });
        setBooking(out);
      })
      .catch(() => setBooking({}));
  }, []);

  React.useEffect(() => {
    const handler = () => setOpen(true);
    window.addEventListener('ask-agent:open', handler);
    return () => window.removeEventListener('ask-agent:open', handler);
  }, []);
  React.useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages, thinking]);
  React.useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 60);
  }, [open]);
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  const send = async (text) => {
    const t = (text ?? input).trim();
    if (!t || thinking) return;
    const nextMessages = [...messages, { role: 'user', text: t }];
    setMessages(nextMessages);
    setInput('');
    setThinking(true);
    try {
      const r = await fetch('/api/ask', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userMessage: t,
          messages: nextMessages,  // server trims history to last 6 turns
        }),
      });
      const data = await r.json().catch(() => ({}));
      const raw = (data.reply || '').trim();
      const bookIntent = /\[BOOK_DEMO\]/i.test(raw);
      const cleaned = raw.replace(/\[BOOK_DEMO\]/ig, '').trim() ||
        "Sorry — I didn't get an answer back. Try again in a moment, or email connect@eightbyzero.com.";
      setMessages(m => [
        ...m,
        { role: 'assistant', text: cleaned },
        ...(bookIntent ? [{ role: 'booking' }] : []),
      ]);
    } catch (err) {
      setMessages(m => [...m, { role: 'assistant', text: "Something went wrong on my end. Email connect@eightbyzero.com and the team will get you a real answer." }]);
    } finally {
      setThinking(false);
    }
  };

  return (
    <>
      {open && (
        <div onClick={() => setOpen(false)} style={{
          position: 'fixed', inset: 0,
          background: 'rgba(0, 0, 0, 0.45)',
          backdropFilter: 'blur(2px)',
          WebkitBackdropFilter: 'blur(2px)',
          zIndex: 998,
          animation: 'agent-fade 240ms var(--ease-out)',
        }}/>
      )}

      <aside style={{
        position: 'fixed',
        top: 0, right: 0, bottom: 0,
        width: 'min(440px, 92vw)',
        background: 'var(--ebz-ink-700)',
        borderLeft: '1px solid var(--border-2)',
        boxShadow: '-24px 0 48px -8px rgba(0,0,0,0.55)',
        zIndex: 999,
        transform: open ? 'translateX(0)' : 'translateX(105%)',
        transition: 'transform 260ms var(--ease-out)',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{
          flex: '0 0 auto',
          padding: '16px 20px',
          borderBottom: '1px solid var(--border-1)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          background: 'rgba(0,0,0,0.18)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%',
              background: 'var(--accent)',
              animation: 'console-pulse 1.6s var(--ease-out) infinite',
            }}/>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-2)', letterSpacing: '0.08em' }}>
              ask <span className="bn"><span style={{ color: 'var(--accent)' }}>8</span><span style={{ color: 'var(--fg-1)' }}>/</span><span style={{ color: 'var(--accent)' }}>0</span></span>
            </span>
          </div>
          <button onClick={() => setOpen(false)} aria-label="Close" style={{
            background: 'transparent', border: 'none', color: 'var(--fg-3)',
            fontSize: 20, lineHeight: 1, padding: 4, cursor: 'pointer',
            fontFamily: 'var(--font-mono)',
          }}>×</button>
        </div>

        <div ref={scrollRef} style={{
          flex: '1 1 auto', overflowY: 'auto',
          padding: '20px',
          display: 'flex', flexDirection: 'column', gap: 16,
          fontSize: 14, lineHeight: 1.6,
        }}>
          {messages.map((m, i) => {
            if (m.role === 'booking') return <BookingCard key={i} booking={booking}/>;
            return (
              <div key={i} style={{
                display: 'flex', flexDirection: 'column', gap: 6,
                alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
                maxWidth: '92%',
              }}>
                <div style={{
                  fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em',
                  textTransform: 'uppercase',
                  color: m.role === 'user' ? 'var(--fg-3)' : 'var(--accent)',
                  textAlign: m.role === 'user' ? 'right' : 'left',
                }}>{m.role === 'user' ? 'you' : 'agent'}</div>
                <div style={{
                  color: m.role === 'user' ? 'var(--fg-1)' : 'var(--fg-2)',
                  whiteSpace: 'pre-wrap',
                  padding: m.role === 'user' ? '10px 14px' : 0,
                  background: m.role === 'user' ? 'var(--bg-elev-1)' : 'transparent',
                  border: m.role === 'user' ? '1px solid var(--border-1)' : 'none',
                  borderRadius: 4,
                }}>{m.text}</div>
              </div>
            );
          })}

          {thinking && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignSelf: 'flex-start' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--accent)' }}>agent</div>
              <div style={{ color: 'var(--fg-3)', fontFamily: 'var(--font-mono)', fontSize: 12 }}>
                thinking<span className="agent-dots"></span>
              </div>
            </div>
          )}

          {messages.length === 1 && !thinking && (
            <div style={{
              marginTop: 8,
              borderTop: '1px solid var(--border-1)',
              paddingTop: 16,
              display: 'flex', flexDirection: 'column', gap: 8,
            }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>try</div>
              {STARTER_PROMPTS.map(p => (
                <button key={p} onClick={() => send(p)} style={{
                  textAlign: 'left',
                  background: 'transparent',
                  border: '1px solid var(--border-1)',
                  color: 'var(--fg-2)',
                  padding: '10px 12px',
                  borderRadius: 4,
                  fontSize: 13, fontFamily: 'var(--font-sans)',
                  cursor: 'pointer',
                  letterSpacing: '-0.005em',
                  transition: 'border-color 120ms, color 120ms',
                }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.color = 'var(--fg-1)'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-1)'; e.currentTarget.style.color = 'var(--fg-2)'; }}
                >{p}</button>
              ))}
            </div>
          )}
        </div>

        <form onSubmit={(e) => { e.preventDefault(); send(); }} style={{
          flex: '0 0 auto',
          padding: 16,
          borderTop: '1px solid var(--border-1)',
          background: 'rgba(0,0,0,0.18)',
          display: 'flex', gap: 8, alignItems: 'stretch',
        }}>
          <input
            ref={inputRef}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Ask anything about 8/0…"
            disabled={thinking}
            style={{
              flex: 1, padding: '12px 14px',
              background: 'var(--bg)',
              border: '1px solid var(--border-2)',
              borderRadius: 4,
              color: 'var(--fg-1)',
              fontFamily: 'var(--font-sans)',
              fontSize: 14, letterSpacing: '-0.005em',
              outline: 'none',
            }}
            onFocus={e => e.target.style.borderColor = 'var(--accent)'}
            onBlur={e => e.target.style.borderColor = 'var(--border-2)'}
          />
          <button type="submit" disabled={thinking || !input.trim()} style={{
            padding: '0 18px',
            background: thinking || !input.trim() ? 'transparent' : 'var(--accent)',
            color: thinking || !input.trim() ? 'var(--fg-3)' : '#052D1E',
            border: thinking || !input.trim() ? '1px solid var(--border-2)' : '1px solid var(--accent)',
            borderRadius: 4,
            fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
            letterSpacing: '-0.005em',
            cursor: thinking || !input.trim() ? 'default' : 'pointer',
          }}>{thinking ? '…' : 'Ask →'}</button>
        </form>

        <div style={{
          flex: '0 0 auto',
          padding: '8px 16px 14px',
          background: 'rgba(0,0,0,0.18)',
          fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.06em',
          color: 'var(--fg-4)', textAlign: 'center',
        }}>
          Answers are AI-generated. For specifics, email connect@eightbyzero.com.
        </div>
      </aside>

      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes agent-fade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes agent-caret {
          0%, 49%   { opacity: 0.9; }
          50%, 100% { opacity: 0; }
        }
        .agent-dots::after {
          content: '';
          display: inline-block;
          width: 18px; text-align: left;
          animation: agent-dots 1.2s steps(4, end) infinite;
        }
        @keyframes agent-dots {
          0%   { content: ''; }
          25%  { content: '.'; }
          50%  { content: '..'; }
          75%  { content: '...'; }
          100% { content: ''; }
        }
      `}}/>
    </>
  );
}

function BookingCard({ booking }) {
  const title    = booking.title    || 'Book a demo · 20 minutes';
  const subtitle = booking.subtitle || 'Pick a time on the team calendar.';
  const btn      = booking.button_label   || 'Open the calendar →';
  const fall     = booking.fallback_label || 'Or email connect@eightbyzero.com';
  const email    = booking.fallback_email || 'connect@eightbyzero.com';
  const url      = booking.calendar_url   || `mailto:${email}?subject=Demo`;
  const isReal   = url && !url.includes('REPLACE_ME');
  return (
    <div style={{
      padding: 20,
      border: '1px solid rgba(16, 200, 128, 0.40)',
      borderLeft: '3px solid var(--accent)',
      background: 'linear-gradient(90deg, rgba(16, 200, 128, 0.08), var(--bg-elev-1) 70%)',
      borderRadius: 4,
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--accent)' }}>
          Booking
        </div>
        <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--fg-1)', letterSpacing: '-0.01em' }}>{title}</div>
        <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.55, marginTop: 2 }}>{subtitle}</div>
      </div>
      <a href={isReal ? url : `mailto:${email}?subject=Demo`} target="_blank" rel="noopener" style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        padding: '12px 16px',
        background: 'var(--accent)', color: '#052D1E',
        textDecoration: 'none',
        borderRadius: 4,
        fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700,
        letterSpacing: '-0.005em',
      }}>{btn}</a>
      <a href={`mailto:${email}?subject=Demo`} style={{
        fontSize: 12, color: 'var(--fg-3)', textAlign: 'center',
        textDecoration: 'none', borderBottom: '1px solid var(--border-1)', paddingBottom: 2, alignSelf: 'center',
      }}>{fall}</a>
    </div>
  );
}

const LAUNCHER_PROMPTS = [
  'Ask 8/0 anything…',
  'How does 8/0 handle Workday drift?',
  'What\'s your security posture?',
  'How fast is implementation?',
  'Tell me about the team.',
  'Can I book a demo?',
];
function AskAgentLauncher({ style }) {
  const [idx, setIdx] = React.useState(0);
  const [fading, setFading] = React.useState(false);
  React.useEffect(() => {
    const t = setInterval(() => {
      setFading(true);
      setTimeout(() => {
        setIdx(i => (i + 1) % LAUNCHER_PROMPTS.length);
        setFading(false);
      }, 700);
    }, 5400);
    return () => clearInterval(t);
  }, []);

  const open = () => window.dispatchEvent(new Event('ask-agent:open'));

  const onKeyDown = (e) => {
    if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(); return; }
    if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) {
      open();
      setTimeout(() => {
        const real = document.querySelector('aside input[placeholder^="Ask anything"]');
        if (real) { real.focus(); real.value = e.key; real.dispatchEvent(new Event('input', { bubbles: true })); }
      }, 80);
    }
  };

  return (
    <div role="button" tabIndex={0} onClick={open} onKeyDown={onKeyDown}
      aria-label="Ask 8/0 — open the on-page assistant"
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 10,
        height: 36, padding: '0 10px 0 12px',
        width: 320,
        background: 'rgba(16,200,128,0.06)',
        color: 'var(--fg-2)',
        border: '1px solid rgba(16,200,128,0.30)',
        borderRadius: 6,
        fontFamily: 'var(--font-sans)',
        fontSize: 13, fontWeight: 400,
        letterSpacing: '-0.005em',
        cursor: 'text',
        whiteSpace: 'nowrap',
        transition: 'background 180ms var(--ease-out), border-color 180ms var(--ease-out)',
        outline: 'none',
        ...style,
      }}
      onMouseEnter={e => { e.currentTarget.style.background = 'rgba(16,200,128,0.12)'; e.currentTarget.style.borderColor = 'rgba(16,200,128,0.55)'; }}
      onMouseLeave={e => { e.currentTarget.style.background = 'rgba(16,200,128,0.06)'; e.currentTarget.style.borderColor = 'rgba(16,200,128,0.30)'; }}
      onFocus={e =>     { e.currentTarget.style.background = 'rgba(16,200,128,0.12)'; e.currentTarget.style.borderColor = 'rgba(16,200,128,0.70)'; }}
      onBlur={e =>      { e.currentTarget.style.background = 'rgba(16,200,128,0.06)'; e.currentTarget.style.borderColor = 'rgba(16,200,128,0.30)'; }}
    >
      <span style={{
        width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)',
        flexShrink: 0, opacity: 0.7,
      }}/>
      <span style={{
        flex: 1, minWidth: 0,
        overflow: 'hidden', textOverflow: 'ellipsis',
        color: 'var(--fg-3)',
        opacity: fading ? 0 : 1,
        transition: 'opacity 700ms var(--ease-out)',
      }}>{LAUNCHER_PROMPTS[idx]}</span>
      <span style={{
        width: 18, height: 18, borderRadius: 3,
        border: '1px solid rgba(255,255,255,0.18)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }} aria-hidden="true">
        <svg width="7" height="8" viewBox="0 0 7 8" style={{ display: 'block' }}>
          <path d="M 1 1 L 6 4 L 1 7 Z" fill="rgba(232,243,236,0.55)"/>
        </svg>
      </span>
    </div>
  );
}

window.AskAgent = AskAgent;
window.AskAgentLauncher = AskAgentLauncher;
