/* global React, window */
// =====================================================================
// KnowledgeView — RAG / knowledge de windmar-marketing.
// knowledge_docs vive en public → funciona YA (sin cambios de schema).
// Búsqueda FTS vía RPC search_knowledge + browse de docs recientes.
// =====================================================================
(function () {
  const { useState, useEffect } = React;

  function KnowledgeView({ lang = "es" }) {
    const [q, setQ] = useState("");
    const [docs, setDocs] = useState(null);
    const [results, setResults] = useState(null);
    const [searching, setSearching] = useState(false);

    useEffect(() => { if (window.wm?.ready) window.wm.knowledgeBrowse().then(setDocs); }, []);

    async function run(e) {
      e?.preventDefault();
      if (!q.trim() || !window.wm?.ready) return;
      setSearching(true);
      const r = await window.wm.knowledgeSearch(q.trim());
      setResults(r || []); setSearching(false);
    }

    if (!window.wm?.ready) return <div style={{ padding: 16, color: "var(--wm-fg-muted)" }}>Sin conexión a windmar-marketing.</div>;

    return (
      <div style={{ padding: "4px 2px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
          <window.Icon name="book-open" size={20} />
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>{lang === "es" ? "Knowledge · RAG" : "Knowledge · RAG"}</h2>
          <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--wm-fg-muted)" }}>windmar-marketing · knowledge_docs</span>
        </div>

        <form onSubmit={run} style={{ display: "flex", gap: 8, marginBottom: 18 }}>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder={lang === "es" ? "Buscar en el conocimiento… (ej. founder ad, price match, VPP)" : "Search knowledge…"}
            style={{ flex: 1, padding: "10px 12px", border: "1px solid var(--op-line)", borderRadius: 10, fontSize: 14 }} />
          <button type="submit" style={{ padding: "10px 18px", background: "var(--wm-blue)", color: "#fff", border: 0, borderRadius: 10, fontWeight: 700, cursor: "pointer" }}>
            {searching ? "…" : (lang === "es" ? "Buscar" : "Search")}
          </button>
        </form>

        {results !== null && (
          <div style={{ marginBottom: 24 }}>
            <h3 style={{ fontSize: 13, fontWeight: 800, color: "var(--wm-fg-muted)", textTransform: "uppercase" }}>{results.length} {lang === "es" ? "resultados" : "results"}</h3>
            {results.map((r, i) => (
              <div key={i} style={{ padding: "10px 0", borderTop: "1px solid var(--op-line)" }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{r.title || r.source_path}</div>
                <div style={{ fontSize: 12, color: "var(--wm-fg-muted)", marginTop: 3 }}>{(r.snippet || r.content || "").slice(0, 240)}</div>
              </div>
            ))}
            {!results.length && <div style={{ color: "var(--wm-fg-muted)", fontSize: 13, padding: 8 }}>Sin coincidencias.</div>}
          </div>
        )}

        <h3 style={{ fontSize: 14, fontWeight: 800, margin: "0 0 10px" }}><window.Icon name="files" size={16} /> {lang === "es" ? "Docs recientes en el cerebro" : "Recent docs"}</h3>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 10 }}>
          {(docs || []).map((d, i) => (
            <div key={i} style={{ background: "var(--op-card,#fff)", border: "1px solid var(--op-line)", borderRadius: 10, padding: "10px 12px" }}>
              <div style={{ fontWeight: 700, fontSize: 13, lineHeight: 1.3 }}>{d.title}</div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 6 }}>
                <span style={{ fontSize: 10, color: "var(--wm-fg-muted)" }}>{d.source_type}</span>
                {(d.tags || []).slice(0, 4).map((t, j) => (
                  <span key={j} style={{ fontSize: 10, background: "rgba(29,66,155,0.08)", color: "var(--wm-blue)", padding: "1px 7px", borderRadius: 8 }}>{t}</span>
                ))}
              </div>
            </div>
          ))}
          {docs === null && <div style={{ color: "var(--wm-fg-muted)", fontSize: 13 }}>Cargando…</div>}
          {docs && !docs.length && <div style={{ color: "var(--wm-fg-muted)", fontSize: 13 }}>Sin docs.</div>}
        </div>
      </div>
    );
  }
  window.KnowledgeView = KnowledgeView;
})();
