/* Floating support bubble — Kath AI */
const KathAI = () => {
  const [open, setOpen] = React.useState(false);
  const [input, setInput] = React.useState('');
  const [messages, setMessages] = React.useState([
    { role: 'ai', text: '¡Hola! Soy Kath, tu asistente IA de Booster Block. ¿En qué proyecto estás pensando?' },
  ]);
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);

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

  const send = async () => {
    const q = input.trim();
    if (!q || busy) return;
    setInput('');
    const nextMessages = [...messages, { role: 'user', text: q }];
    setMessages(nextMessages);
    setBusy(true);
    try {
      // Pasa historial completo al endpoint real (Anthropic format)
      const apiMessages = nextMessages.map(m => ({
        role: m.role === 'ai' ? 'assistant' : 'user',
        content: m.text,
      }));
      const r = await fetch('/api/kath/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: apiMessages }),
      });
      const data = await r.json();
      if (!r.ok || !data.ok) throw new Error(data.error || 'Network error');
      setMessages(m => [...m, { role: 'ai', text: data.reply }]);
    } catch (e) {
      setMessages(m => [...m, { role: 'ai', text: 'Algo falló de mi lado. Escribinos a contact@boosterblock.io y un humano te responde 🙌' }]);
    }
    setBusy(false);
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  };

  return (
    <React.Fragment>
      {/* Bubble */}
      <button
        className={"kath-bubble" + (open ? " open" : "")}
        onClick={() => setOpen(o => !o)}
        aria-label={open ? "Cerrar chat" : "Habla con Kath AI"}
      >
        <span className="kath-bubble-pulse"/>
        {open ? <IconClose size={20}/> : (
          <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 12a8 8 0 0 1-11.5 7.2L3 21l1.8-6.5A8 8 0 1 1 21 12Z"/>
            <circle cx="9" cy="12" r="1" fill="currentColor" stroke="none"/>
            <circle cx="12" cy="12" r="1" fill="currentColor" stroke="none"/>
            <circle cx="15" cy="12" r="1" fill="currentColor" stroke="none"/>
          </svg>
        )}
        {!open && (
          <span className="kath-bubble-label">
            <span className="kath-bubble-dot"/>
            Habla con Kath AI
          </span>
        )}
      </button>

      {/* Window */}
      <div className={"kath-window" + (open ? " open" : "")} role="dialog" aria-label="Chat con Kath AI">
        <header className="kath-head">
          <div className="kath-avatar">
            <span className="kath-avatar-orbit"/>
            <span className="kath-avatar-core">K</span>
          </div>
          <div className="kath-id">
            <div className="kath-name">
              Kath AI
              <span className="kath-status"><span className="hero-chip-dot ok"/> En línea</span>
            </div>
            <div className="kath-role">Soporte · Booster Block</div>
          </div>
          <button className="kath-close" onClick={() => setOpen(false)} aria-label="Cerrar">
            <IconClose size={14}/>
          </button>
        </header>

        <div className="kath-messages" ref={scrollRef}>
          {messages.map((m, i) => (
            <div key={i} className={"kath-msg kath-msg-" + m.role}>
              {m.role === 'ai' && (
                <span className="kath-msg-avatar"><IconSparkle size={10}/></span>
              )}
              <div className="kath-msg-bubble">{m.text}</div>
            </div>
          ))}
          {busy && (
            <div className="kath-msg kath-msg-ai">
              <span className="kath-msg-avatar"><IconSparkle size={10}/></span>
              <div className="kath-msg-bubble kath-typing">
                <i/><i/><i/>
              </div>
            </div>
          )}
        </div>

        <div className="kath-suggest">
          {['¿Cuánto cuesta un MVP?', 'Quiero un agente IA', 'Necesito blockchain'].map((s, i) => (
            <button key={i} className="kath-suggest-chip" onClick={() => { setInput(s); }}>{s}</button>
          ))}
        </div>

        <form className="kath-input" onSubmit={(e) => { e.preventDefault(); send(); }}>
          <input
            type="text"
            placeholder="Escribe tu mensaje…"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={onKey}
            disabled={busy}
          />
          <button type="submit" className="kath-send" disabled={busy || !input.trim()} aria-label="Enviar">
            <IconArrowRight size={14}/>
          </button>
        </form>

        <footer className="kath-foot">
          <IconBolt size={10}/> Powered by Booster X · respuesta promedio &lt; 30s
        </footer>
      </div>
    </React.Fragment>
  );
};

Object.assign(window, { KathAI });
