// wolf-chat.jsx — floating wolf chat (bottom-right). Talks via window.claude.complete
// with a scripted fallback. Exports: WolfChat

function buildWolfPrompt(lang, history, userMsg) {
  const facts = `
FATOS (não invente nada além disto):
- Eduardo Lima, engenheiro de inteligência artificial brasileiro. Site: canislupus.dev (nomeado pela constelação Lupus, o Lobo).
- Projeto principal: Lupus (v1.0), agente de terminal para explorar codebases desconhecidas. Retrieval híbrido (FAISS + BM25 + reranking CrossEncoder), 17 ferramentas orquestradas com LangGraph, camada FastAPI com streaming, abstração de provedores LLM. Projeto de estudos em desenvolvimento contínuo. GitHub: github.com/eduardo-ebdl/lupus
- Sales Report AI (finalizado): pipeline de relatórios de vendas com LLM em que os números são validados por código determinístico, não pelo modelo; guardrail + LLM-as-judge, prompt registry versionado com golden tests no CI e dashboard de observabilidade. GitHub: github.com/eduardo-ebdl/sales-report-ai
- SRAG Agent (finalizado): agente ReAct para vigilância epidemiológica no Azure Databricks; arquitetura Medallion, MLflow, conformidade LGPD. GitHub: github.com/eduardo-ebdl/srag-agent
- Visual Study Tool (finalizado): busca de imagens multi-fontes com ranking semântico CLIP, cache SQLite, UI Gradio.
- Stack: LangChain/LangGraph/LangSmith, Anthropic, FAISS, BM25, CrossEncoder, CLIP, Databricks, dbt, Airflow, FastAPI, Docker, AWS, Python, SQL, n8n, Power Automate.
- Formação: Tecnólogo em Big Data e Inteligência Artificial (Pontifícia Universidade Católica de Goiás, jan 2024 a jun 2026, conclusão em breve); Engenharia de Inteligência Artificial (Instituto Infnet, jan 2026 a dez 2029).
- Certificações concluídas: IBM AI Engineering (Coursera) e IBM Generative AI Engineering (Coursera). Outras formações: Formação AI Engineering (Indicium AI), Airflow, Databricks Fundamentals.
- Contato: eduardo.lima@canislupus.dev · github.com/eduardo-ebdl · linkedin.com/in/eduardoebdl`;

  const persona = lang === "pt"
    ? `Você é "Lupus", o assistente do portfólio do Eduardo. Tom: cordial, profissional, humilde e direto. Responda SEMPRE em português, em no máximo 3 frases curtas. PROIBIDO: linguagem canina (nada de uivos, "farejar", "matilha" etc.), travessões (—) e frases de efeito. No máximo um emoji ocasional. Se perguntarem algo fora do escopo do site, redirecione educadamente para os projetos ou o contato do Eduardo.`
    : `You are "Lupus", the assistant of Eduardo's portfolio. Tone: cordial, professional, humble and direct. ALWAYS answer in English, 3 short sentences max. FORBIDDEN: canine language (no howling, "sniffing", "pack" etc.), em dashes, and catchphrases. At most one occasional emoji. If asked something outside the site's scope, politely redirect to the projects or Eduardo's contact info.`;

  const transcript = history
    .map((m) => (m.role === "user" ? "Visitante: " : "Lupus: ") + m.text)
    .join("\n");

  return `${persona}\n${facts}\n\nCONVERSA ATÉ AGORA:\n${transcript}\nVisitante: ${userMsg}\n\nResponda como Lupus (apenas a resposta, sem prefixo):`;
}

function WolfChat({ t, lang, C, open, setOpen }) {
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const scrollRef = React.useRef(null);
  const greeted = React.useRef(false);

  React.useEffect(() => {
    if (open && !greeted.current) {
      greeted.current = true;
      setMessages([{ role: "wolf", text: t.wolf.greeting }]);
    }
  }, [open]);

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

  async function send() {
    const msg = input.trim();
    if (!msg || thinking) return;
    setInput("");
    const history = messages;
    setMessages((m) => [...m, { role: "user", text: msg }]);
    setThinking(true);
    let reply;
    try {
      const prompt = buildWolfPrompt(lang, history, msg);
      if (window.WOLF_API_URL) {
        // Production backend (e.g. a Vercel serverless function). See README.
        const res = await fetch(window.WOLF_API_URL, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ lang, history, message: msg, prompt }),
        });
        if (!res.ok) throw new Error("backend " + res.status);
        const data = await res.json();
        reply = data.reply || data.text || "";
      } else if (window.claude && window.claude.complete) {
        // Available inside the design preview environment.
        reply = await window.claude.complete(prompt);
      } else {
        // No backend wired yet — friendly placeholder.
        reply = lang === "pt"
          ? "O assistente ainda está sendo treinado e entra no ar em breve. Por enquanto, dá uma olhada nos projetos acima ou fale comigo pelos links de contato. 🌌"
          : "The assistant is still in training and goes live soon. Meanwhile, take a look at the projects above or reach me through the contact links. 🌌";
      }
    } catch (e) {
      reply = t.wolf.error;
    }
    setThinking(false);
    setMessages((m) => [...m, { role: "wolf", text: (reply || "").trim() }]);
  }

  const mono = "'JetBrains Mono', monospace";
  const vp = useViewport();

  return (
    <div style={{ position: "fixed", right: vp.mobile ? 16 : 24, bottom: vp.mobile ? 16 : 24, left: vp.mobile ? 16 : "auto", zIndex: 90, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 14 }}>
      {open && (
        <div style={{ width: vp.mobile ? "100%" : 350, height: vp.mobile ? "min(70vh, 520px)" : 480, background: "#fff", border: `1px solid ${C.line}`, borderRadius: 18, boxShadow: "0 24px 70px rgba(14,23,38,0.22)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
          {/* header */}
          <div style={{ background: "linear-gradient(150deg, #0a0f1c, #1b2940)", padding: "14px 18px", display: "flex", alignItems: "center", gap: 12 }}>
            <LupusConstellation size={24} stroke="#60a5fa" strokeWidth={5} lineOpacity={0.85} starColor="#e8edf6"></LupusConstellation>
            <div style={{ flexGrow: 1 }}>
              <div style={{ color: "#e8edf6", fontSize: 15, fontWeight: 600 }}>{t.wolf.chatTitle}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: mono, fontSize: 10.5, color: "#8b9bb4" }}>
                <span style={{ width: 6, height: 6, borderRadius: 99, background: "#fbbf24", display: "inline-block" }}></span>
                {t.wolf.chatStatus}
              </div>
            </div>
            <button
              onClick={() => setOpen(false)}
              style={{ background: "none", border: "none", color: "#8b9bb4", fontSize: 20, cursor: "pointer", padding: 4, lineHeight: 1 }}
              aria-label="Fechar"
            >×</button>
          </div>
          {/* messages */}
          <div ref={scrollRef} style={{ flexGrow: 1, overflowY: "auto", padding: "16px 16px 8px 16px", display: "flex", flexDirection: "column", gap: 10, background: "#fafbfd" }}>
            {messages.map((m, i) => (
              <div
                key={i}
                style={{
                  maxWidth: "82%",
                  alignSelf: m.role === "user" ? "flex-end" : "flex-start",
                  background: m.role === "user" ? "#0e1726" : "#fff",
                  color: m.role === "user" ? "#f2f5fa" : C.text,
                  border: m.role === "user" ? "none" : `1px solid ${C.line}`,
                  borderRadius: m.role === "user" ? "14px 14px 4px 14px" : "14px 14px 14px 4px",
                  padding: "10px 14px",
                  fontSize: 14,
                  lineHeight: 1.55,
                }}
              >
                {m.text}
              </div>
            ))}
            {thinking && (
              <div style={{ alignSelf: "flex-start", fontFamily: mono, fontSize: 12, color: C.faint, padding: "6px 4px" }}>
                ◌ {t.wolf.thinking}
              </div>
            )}
          </div>
          {/* input */}
          <div style={{ display: "flex", gap: 8, padding: 12, borderTop: `1px solid ${C.line}`, background: "#fff" }}>
            <input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") send(); }}
              placeholder={t.wolf.placeholder}
              style={{ flexGrow: 1, border: `1px solid ${C.line}`, borderRadius: 10, padding: "10px 13px", fontSize: 14, outline: "none", fontFamily: "inherit", color: C.text, background: "#fafbfd" }}
            />
            <button
              onClick={send}
              style={{ background: "#0e1726", color: "#fff", border: "none", borderRadius: 10, padding: "0 16px", fontSize: 15, cursor: "pointer" }}
              aria-label="Enviar"
            >↑</button>
          </div>
        </div>
      )}
      {/* floating button */}
      <button
        onClick={() => setOpen(!open)}
        style={{
          width: 58, height: 58, borderRadius: 99, border: "none", cursor: "pointer",
          alignSelf: "flex-end",
          background: "linear-gradient(150deg, #0e1726, #22335a)",
          boxShadow: "0 10px 30px rgba(14,23,38,0.35), 0 0 0 1px rgba(96,165,250,0.25)",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}
        aria-label="Falar com o Lupus"
      >
        <LupusConstellation size={30} stroke="#60a5fa" strokeWidth={4} lineOpacity={0.9} starColor="#e8edf6"></LupusConstellation>
      </button>
    </div>
  );
}

Object.assign(window, { WolfChat });
