// AI Agent chat — guides visitors through services and captures their info.
// Uses window.claude.complete() to power the conversation.

function AIAgentChat({ accent, fg, muted, dim, panel, deep, dark, warn }) {
  const [messages, setMessages] = React.useState([
    {
      role: "agent",
      content: "Hola, soy Nova — el agente IA de Yeiko. Estoy acá para entender qué necesita tu operación y guiarte a la solución correcta. ¿Empezamos con tu nombre y de qué se trata el proyecto?",
    },
  ]);
  const [input, setInput] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [collected, setCollected] = React.useState({});
  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 newMsgs = [...messages, { role: "user", content: text }];
    setMessages(newMsgs);
    setInput("");
    setBusy(true);

    try {
      const apiMessages = newMsgs.map(m => ({
        role: m.role === "agent" ? "assistant" : "user",
        content: m.content,
      }));
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: apiMessages }),
      });
      if (!res.ok) throw new Error("chat http " + res.status);
      const data = await res.json();
      const reply = data.reply;
      setMessages(prev => [...prev, { role: "agent", content: reply }]);
    } catch (e) {
      setMessages(prev => [...prev, {
        role: "agent",
        content: "Tuve un problema para conectar. Mientras tanto, podés escribir directamente a yeikonovah@gmail.com — Yeiko responde en menos de 24h.",
      }]);
    } finally {
      setBusy(false);
    }
  };

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

  const quickPrompts = [
    "Quiero automatizar un proceso manual",
    "Necesito una plataforma a medida",
    "Tengo problemas de infraestructura",
    "¿Cuánto cuesta un proyecto?",
  ];

  return (
    <div style={{
      border: `1px solid ${dim}`,
      background: deep,
      display: "flex",
      flexDirection: "column",
      minHeight: 480,
      maxHeight: 560,
    }}>
      {/* Header */}
      <div style={{
        padding: "12px 18px",
        borderBottom: `1px solid ${dim}`,
        display: "flex", justifyContent: "space-between", alignItems: "center",
        fontSize: 11, color: muted,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{
            display: "inline-block", width: 9, height: 9, borderRadius: 99,
            background: accent, boxShadow: `0 0 8px ${accent}`,
            animation: "pulse 2s ease-in-out infinite",
          }}></span>
          <span style={{ color: fg, fontWeight: 500 }}>nova_agent.live</span>
          <span style={{ color: muted }}>· powered by claude</span>
        </div>
        <span style={{ color: accent }}>● online</span>
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{
        flex: 1,
        overflowY: "auto",
        padding: "20px 22px",
        display: "flex",
        flexDirection: "column",
        gap: 16,
      }}>
        {messages.map((m, i) => (
          <div key={i} style={{
            display: "flex",
            flexDirection: "column",
            gap: 4,
            alignItems: m.role === "user" ? "flex-end" : "flex-start",
            maxWidth: "100%",
          }}>
            <div style={{
              fontSize: 10, color: muted,
              textTransform: "uppercase", letterSpacing: "0.1em",
            }}>
              {m.role === "user" ? "// you" : <><span style={{ color: accent }}>●</span> nova</>}
            </div>
            <div style={{
              fontFamily: "'Inter Tight', sans-serif",
              fontSize: 14.5,
              lineHeight: 1.5,
              padding: "10px 14px",
              border: `1px solid ${dim}`,
              background: m.role === "user" ? panel : "transparent",
              color: fg,
              maxWidth: "88%",
              whiteSpace: "pre-wrap",
            }}>{m.content}</div>
          </div>
        ))}
        {busy && (
          <div style={{ display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-start" }}>
            <div style={{ fontSize: 10, color: muted, textTransform: "uppercase", letterSpacing: "0.1em" }}>
              <span style={{ color: accent }}>●</span> nova
            </div>
            <div style={{
              padding: "10px 14px",
              border: `1px solid ${dim}`,
              fontSize: 14, color: muted,
              fontFamily: "'JetBrains Mono', monospace",
            }}>
              <span style={{ animation: "blink 1s steps(2) infinite" }}>▮</span>{" "}
              <span>analizando</span>
              <span style={{ animation: "blink 1.4s steps(3) infinite" }}>...</span>
            </div>
          </div>
        )}
      </div>

      {/* Quick prompts */}
      {messages.length <= 1 && !busy && (
        <div style={{
          padding: "0 22px 12px",
          display: "flex", flexWrap: "wrap", gap: 6,
        }}>
          {quickPrompts.map(q => (
            <button key={q} onClick={() => { setInput(q); }} style={{
              padding: "6px 10px",
              border: `1px solid ${dim}`,
              background: "transparent",
              color: muted,
              fontSize: 11,
              fontFamily: "'JetBrains Mono', monospace",
              cursor: "pointer",
            }}>{q}</button>
          ))}
        </div>
      )}

      {/* Input */}
      <div style={{
        borderTop: `1px solid ${dim}`,
        padding: "12px 16px",
        display: "flex", gap: 10, alignItems: "center",
        background: panel,
      }}>
        <span style={{ color: accent, fontSize: 13 }}>$</span>
        <input
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={onKeyDown}
          disabled={busy}
          placeholder="contale a Nova qué necesitás..."
          style={{
            flex: 1,
            background: "transparent",
            border: "none",
            outline: "none",
            color: fg,
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 13,
            padding: "6px 0",
          }}
        />
        <button onClick={send} disabled={busy || !input.trim()} style={{
          padding: "8px 14px",
          background: accent,
          color: dark ? "#0A0C0A" : "#0A0C0A",
          border: "none",
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 11,
          fontWeight: 600,
          letterSpacing: "0.05em",
          cursor: busy || !input.trim() ? "not-allowed" : "pointer",
          opacity: busy || !input.trim() ? 0.5 : 1,
        }}>send ↵</button>
      </div>
    </div>
  );
}

window.AIAgentChat = AIAgentChat;
