// Widget de chat "Habla con Ana" — conecta con el backend Flask en /api/chat

const BACKEND_URL = "http://localhost:5050";

function ChatWidget() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { role: "assistant", content: "¡Hola! Soy Ana García. ¿Tienes alguna pregunta sobre mi experiencia o proyectos?" }
  ]);
  const [input, setInput] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const bottomRef = React.useRef(null);

  React.useEffect(() => {
    if (open && bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, open]);

  async function sendMessage() {
    const text = input.trim();
    if (!text || loading) return;

    const newMessages = [...messages, { role: "user", content: text }];
    setMessages(newMessages);
    setInput("");
    setLoading(true);

    try {
      const res = await fetch(`${BACKEND_URL}/api/chat`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: text, history: newMessages.slice(1) }),
      });
      const data = await res.json();
      setMessages(prev => [...prev, { role: "assistant", content: data.reply || "Sin respuesta." }]);
    } catch {
      setMessages(prev => [...prev, { role: "assistant", content: "Lo siento, hubo un error. Intenta de nuevo." }]);
    } finally {
      setLoading(false);
    }
  }

  function handleKey(e) {
    if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(); }
  }

  return (
    <div style={{ position: "fixed", bottom: 100, right: 24, zIndex: 9999, fontFamily: "Geist, sans-serif" }}>
      {/* Panel de chat */}
      {open && (
        <div style={{
          width: 340, height: 480, marginBottom: 12,
          background: "#1a1033", border: "1px solid #7165E3",
          borderRadius: 20, display: "flex", flexDirection: "column",
          boxShadow: "0 20px 60px rgba(113,101,227,0.3)",
          overflow: "hidden",
        }}>
          {/* Header */}
          <div style={{
            background: "linear-gradient(135deg, #7165E3, #9d8fef)",
            padding: "14px 18px", display: "flex", alignItems: "center", gap: 10,
          }}>
            <img src="assets/profile.jpg" alt="Ana"
              style={{ width: 36, height: 36, borderRadius: "50%", objectFit: "cover", border: "2px solid white" }} />
            <div>
              <div style={{ color: "white", fontWeight: 700, fontSize: 14 }}>Ana García</div>
              <div style={{ color: "rgba(255,255,255,0.8)", fontSize: 11 }}>Data Analyst · Responde en segundos</div>
            </div>
            <button onClick={() => setOpen(false)}
              style={{ marginLeft: "auto", background: "none", border: "none", color: "white", fontSize: 18, cursor: "pointer", lineHeight: 1 }}>
              ×
            </button>
          </div>

          {/* Mensajes */}
          <div style={{ flex: 1, overflowY: "auto", padding: "14px 14px 0", display: "flex", flexDirection: "column", gap: 10 }}>
            {messages.map((msg, i) => (
              <div key={i} style={{
                alignSelf: msg.role === "user" ? "flex-end" : "flex-start",
                maxWidth: "82%",
                background: msg.role === "user" ? "#7165E3" : "#2d1f5e",
                color: "white", borderRadius: msg.role === "user" ? "16px 16px 4px 16px" : "16px 16px 16px 4px",
                padding: "10px 14px", fontSize: 13, lineHeight: 1.5,
              }}>
                {msg.content}
              </div>
            ))}
            {loading && (
              <div style={{
                alignSelf: "flex-start", background: "#2d1f5e", color: "#9d8fef",
                borderRadius: "16px 16px 16px 4px", padding: "10px 14px", fontSize: 13,
              }}>
                Escribiendo...
              </div>
            )}
            <div ref={bottomRef} />
          </div>

          {/* Input */}
          <div style={{ padding: 12, display: "flex", gap: 8, borderTop: "1px solid #2d1f5e" }}>
            <input
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={handleKey}
              placeholder="Escribe tu pregunta..."
              disabled={loading}
              style={{
                flex: 1, background: "#2d1f5e", border: "1px solid #7165E3",
                borderRadius: 12, padding: "8px 12px", color: "white",
                fontSize: 13, outline: "none",
              }}
            />
            <button onClick={sendMessage} disabled={loading || !input.trim()}
              style={{
                background: "#7165E3", border: "none", borderRadius: 12,
                width: 38, height: 38, cursor: "pointer", display: "flex",
                alignItems: "center", justifyContent: "center",
                opacity: (loading || !input.trim()) ? 0.5 : 1,
              }}>
              <svg width="16" height="16" fill="white" viewBox="0 0 24 24">
                <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* Botón flotante */}
      <button onClick={() => setOpen(o => !o)}
        style={{
          width: 56, height: 56, borderRadius: "50%",
          background: "linear-gradient(135deg, #7165E3, #9d8fef)",
          border: "none", cursor: "pointer", display: "flex",
          alignItems: "center", justifyContent: "center",
          boxShadow: "0 4px 20px rgba(113,101,227,0.5)",
          transition: "transform 0.2s",
        }}
        onMouseEnter={e => e.currentTarget.style.transform = "scale(1.1)"}
        onMouseLeave={e => e.currentTarget.style.transform = "scale(1)"}
      >
        {open
          ? <svg width="22" height="22" fill="white" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
          : <svg width="22" height="22" fill="white" viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>
        }
      </button>
    </div>
  );
}
