// Floating chatbot — calls /api/chat (proxied to Claude API server-side).

function useIsMobile(breakpoint = 600) {
  const [isMobile, setIsMobile] = React.useState(() => window.innerWidth < breakpoint);
  React.useEffect(() => {
    const check = () => setIsMobile(window.innerWidth < breakpoint);
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, [breakpoint]);
  return isMobile;
}

function Chatbot({ open, onClose, accent = '#e8a84a' }) {
  const isMobile = useIsMobile();
  const [messages, setMessages] = React.useState([
    { role: 'assistant', content: "Ask me anything about eCash, drivechains, BIP 300/301, or the hardfork launch." },
  ]);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, busy]);

  const send = async () => {
    const text = input.trim();
    if (!text || busy) return;
    const next = [...messages, { role: 'user', content: text }];
    setMessages(next);
    setInput('');
    setBusy(true);
    try {
      const response = await fetch('https://ecash.onrender.com/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: next }),
      });
      if (!response.ok) {
        const err = await response.json().catch(() => ({}));
        throw new Error(err.error || `HTTP ${response.status}`);
      }
      const data = await response.json();
      setMessages([...next, { role: 'assistant', content: data.content }]);
    } catch (e) {
      setMessages([...next, { role: 'assistant', content: `[error: ${e.message}]` }]);
    }
    setBusy(false);
  };

  if (!open) return null;

  const containerStyle = isMobile ? {
    position: 'fixed',
    left: 0, right: 0, bottom: 0,
    width: '100%',
    height: '72vh',
    borderRadius: '12px 12px 0 0',
  } : {
    position: 'fixed',
    right: 'clamp(8px, 2vw, 24px)',
    bottom: 'clamp(80px, 15vh, 96px)',
    width: 'clamp(280px, 85vw, 380px)',
    height: 'clamp(320px, 60vh, 520px)',
    borderRadius: 6,
  };

  return (
    <div style={{
      ...containerStyle,
      background: '#0d0d0f', border: '1px solid #26262a',
      boxShadow: '0 20px 60px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.02)',
      display: 'flex', flexDirection: 'column', zIndex: 1000,
      fontFamily: '"JetBrains Mono", ui-monospace, monospace',
      color: '#d4d4d8', overflow: 'hidden',
    }}>
      {/* header */}
      <div style={{
        padding: 'clamp(8px, 2vh, 10px) clamp(10px, 2.5vw, 14px)',
        borderBottom: '1px solid #26262a',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontSize: 'clamp(9px, 2.5vw, 11px)', letterSpacing: '0.08em', textTransform: 'uppercase', color: '#71717a',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: accent, boxShadow: `0 0 8px ${accent}` }} />
          <span>ecash.info · ask</span>
        </div>
        <button onClick={onClose} style={{
          background: 'none', border: 'none', color: '#71717a', cursor: 'pointer',
          fontSize: 'clamp(12px, 3vw, 14px)', padding: 2, lineHeight: 1,
        }}>×</button>
      </div>

      {/* messages */}
      <div ref={scrollRef} style={{
        flex: 1, overflowY: 'auto', padding: 'clamp(10px, 2vh, 14px)',
        display: 'flex', flexDirection: 'column', gap: 'clamp(8px, 1.5vh, 12px)', 
        fontSize: 'clamp(11px, 2.5vw, 13px)', lineHeight: 1.5,
      }}>
        {messages.map((m, i) => (
          <div key={i} style={{
            display: 'flex', flexDirection: 'column', gap: 3,
            alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
            maxWidth: '85%',
          }}>
            <div style={{
              fontSize: 'clamp(8px, 2vw, 10px)', color: m.role === 'user' ? '#52525b' : accent,
              letterSpacing: '0.1em', textTransform: 'uppercase',
            }}>
              {m.role === 'user' ? '> you' : '< ecash'}
            </div>
            <div style={{
              color: m.role === 'user' ? '#a1a1aa' : '#e4e4e7',
              whiteSpace: 'pre-wrap', wordBreak: 'break-word',
            }}>{m.content}</div>
          </div>
        ))}
        {busy && (
          <div style={{ alignSelf: 'flex-start', fontSize: 'clamp(8px, 2vw, 10px)', color: accent, letterSpacing: '0.1em' }}>
            {'< ecash typing'}<BlinkDots />
          </div>
        )}
      </div>

      {/* input */}
      <div style={{
        borderTop: '1px solid #26262a', padding: 'clamp(8px, 1.5vh, 10px) clamp(10px, 2vw, 12px)',
        display: 'flex', gap: 'clamp(6px, 1.5vw, 8px)', alignItems: 'center',
      }}>
        <span style={{ color: accent, fontSize: 'clamp(11px, 2.5vw, 13px)' }}>$</span>
        <input
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && send()}
          placeholder="type a question..."
          disabled={busy}
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            color: '#e4e4e7', fontFamily: 'inherit', fontSize: 'clamp(11px, 2.5vw, 13px)',
          }}
        />
        <button onClick={send} disabled={busy || !input.trim()} style={{
          background: 'none', border: '1px solid #26262a', color: accent,
          padding: 'clamp(3px, 1vh, 4px) clamp(6px, 1.5vw, 10px)', fontSize: 'clamp(8px, 2vw, 10px)', borderRadius: 3, cursor: 'pointer',
          fontFamily: 'inherit', letterSpacing: '0.1em', textTransform: 'uppercase',
          opacity: busy || !input.trim() ? 0.4 : 1,
        }}>send</button>
      </div>
    </div>
  );
}

function BlinkDots() {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setN(x => (x + 1) % 4), 400);
    return () => clearInterval(id);
  }, []);
  return <span>{'.'.repeat(n)}</span>;
}

window.Chatbot = Chatbot;
window.BlinkDots = BlinkDots;
