/* global React, Icon */
const { useState, useRef, useEffect } = React;

function AIChat() {
  const [open, setOpen] = useState(false);
  const [messages, setMessages] = useState([
    { role: "assistant", content: "¡Hola! Soy el agente AI de Contarte. Puedo ayudarte con dudas de contabilidad, CFDI, SAT o sobre nuestros planes. ¿En qué te ayudo?" }
  ]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const scrollRef = useRef(null);

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

  const send = async (text) => {
    const q = (text ?? input).trim();
    if (!q || busy) return;
    const next = [...messages, { role: "user", content: q }];
    setMessages(next);
    setInput("");
    setBusy(true);
    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ message: q })
      });
      if (!res.ok) throw new Error("HTTP " + res.status);
      const data = await res.json();
      const reply = (data && data.reply ? String(data.reply) : "").trim();
      if (!reply) throw new Error("empty reply");
      setMessages([...next, { role: "assistant", content: reply }]);
    } catch (e) {
      setMessages([...next, { role: "assistant", content: "Ups, tuve un problema al responder. Intenta de nuevo en un momento." }]);
    } finally {
      setBusy(false);
    }
  };

  const suggestions = [
    "¿Qué plan me conviene?",
    "¿Qué es CFDI 4.0?",
    "¿Cómo conecto el SAT?"
  ];

  return (
    <>
      {/* CTA section — lives between Trust and Pricing */}
      <section className="section ai-cta-section" id="ai-cta">
        <div className="container">
          <div className="ai-cta">
            <div className="ai-cta-left">
              <div className="ai-badge">
                <span className="ai-pulse"/>
                <Icon name="sparkle" size={13}/>
                <span>Agente AI · nuevo</span>
              </div>
              <h2>Chatea con nuestro agente AI sobre contarte.mx o tu contabilidad.</h2>
              <p>Resuelve dudas de CFDI, SAT, cobros o planes en segundos. 100% gratis, sin registro — responde en español, al instante.</p>
              <div className="ai-cta-actions">
                <button className="btn btn-primary btn-lg" onClick={() => setOpen(true)}>
                  <Icon name="message" size={16}/> Abrir chat
                </button>
                <div className="ai-suggestions">
                  {suggestions.map(s => (
                    <button key={s} className="ai-chip" onClick={() => { setOpen(true); setTimeout(() => send(s), 50); }}>
                      {s}
                    </button>
                  ))}
                </div>
              </div>
            </div>
            <div className="ai-cta-right" aria-hidden="true">
              <AIPreview/>
            </div>
          </div>
        </div>
      </section>

      {/* Floating launcher (always visible) */}
      {!open && (
        <button className="ai-launcher" onClick={() => setOpen(true)} aria-label="Abrir chat AI">
          <span className="ai-pulse"/>
          <Icon name="sparkle" size={18}/>
          <span className="ai-launcher-label">Chatea con AI</span>
        </button>
      )}

      {/* Chat window */}
      {open && (
        <div className="ai-window" role="dialog" aria-label="Chat con agente AI">
          <div className="ai-window-head">
            <div className="ai-window-title">
              <div className="ai-avatar"><Icon name="sparkle" size={14}/></div>
              <div>
                <b>Agente AI · Contarte</b>
                <span>En línea · responde al instante</span>
              </div>
            </div>
            <button className="ai-close" onClick={() => setOpen(false)} aria-label="Cerrar">
              <Icon name="x" size={16}/>
            </button>
          </div>
          <div className="ai-window-body" ref={scrollRef}>
            {messages.map((m, i) => (
              <div key={i} className={`ai-msg ${m.role}`}>
                {m.role === "assistant" && <div className="ai-avatar sm"><Icon name="sparkle" size={11}/></div>}
                <div className="ai-bubble">{m.content}</div>
              </div>
            ))}
            {busy && (
              <div className="ai-msg assistant">
                <div className="ai-avatar sm"><Icon name="sparkle" size={11}/></div>
                <div className="ai-bubble ai-typing"><i/><i/><i/></div>
              </div>
            )}
          </div>
          <form className="ai-window-input" onSubmit={e => { e.preventDefault(); send(); }}>
            <input
              value={input}
              onChange={e => setInput(e.target.value)}
              placeholder="Escribe tu pregunta…"
              disabled={busy}
              autoFocus
            />
            <button type="submit" className="btn btn-primary btn-sm" disabled={busy || !input.trim()}>
              <Icon name="arrow-right" size={14}/>
            </button>
          </form>
        </div>
      )}
    </>
  );
}

function AIPreview() {
  return (
    <div className="ai-preview">
      <div className="ai-preview-head">
        <div className="ai-avatar"><Icon name="sparkle" size={13}/></div>
        <div>
          <b>Agente AI · Contarte</b>
          <span>En línea</span>
        </div>
      </div>
      <div className="ai-preview-body">
        <div className="ai-msg user"><div className="ai-bubble">¿Qué plan me conviene si facturo 200 CFDI al mes?</div></div>
        <div className="ai-msg assistant">
          <div className="ai-avatar sm"><Icon name="sparkle" size={11}/></div>
          <div className="ai-bubble">Con 200 CFDI/mes te recomiendo <b>Profesional</b> ($3,600/año). Incluye 500 CFDI, cobros en línea y colaboración con tu contador.</div>
        </div>
        <div className="ai-msg user"><div className="ai-bubble">¿Y si mi contador trabaja desde otra ciudad?</div></div>
        <div className="ai-msg assistant">
          <div className="ai-avatar sm"><Icon name="sparkle" size={11}/></div>
          <div className="ai-bubble">Sin problema — ambos entran al mismo expediente en vivo. Tu contador ve lo mismo que tú.</div>
        </div>
      </div>
    </div>
  );
}

window.AIChat = AIChat;
