// Central de Inteligência — loop de aprendizado contínuo.
// Ver docs/CENTRAL_INTELIGENCIA.md.

function ScreenLearning() {
  const toast = useToast();
  const [dash, setDash] = React.useState(null);
  const [clusters, setClusters] = React.useState([]);
  const [statusFilter, setStatusFilter] = React.useState("aberto");
  const [selected, setSelected] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  const loadDash = () => api("/api/admin/learning/dashboard").then(setDash).catch(() => {});
  const loadClusters = () => api("/api/admin/learning/clusters?status=" + statusFilter).then((r) => setClusters(r || [])).catch(() => {});
  React.useEffect(() => { loadDash(); }, []);
  React.useEffect(() => { loadClusters(); }, [statusFilter]);
  const refresh = () => { loadDash(); loadClusters(); };

  const recluster = () => {
    setBusy(true);
    api("/api/admin/learning/recluster", { method: "POST" })
      .then((r) => { toast({ title: "Histórico reprocessado", msg: (r.processed || 0) + " perguntas agrupadas", kind: "success" }); refresh(); })
      .catch((e) => toast({ title: "Falha", msg: e.message, kind: "error" }))
      .finally(() => setBusy(false));
  };

  const Stat = ({ label, value, color }) => (
    <div className="card" style={{ flex: "1 1 150px", padding: 14 }}>
      <div style={{ fontSize: 22, fontWeight: 700, color: color || "var(--t1)" }}>{value != null ? value : "—"}</div>
      <div style={{ fontSize: 11.5, color: "var(--t3)" }}>{label}</div>
    </div>
  );

  return (
    <div className="page" data-screen-label="Central de Inteligência">
      <div className="page-header">
        <div>
          <h1><span className="h1-icon"><i className="fas fa-lightbulb"></i></span> Central de Inteligência</h1>
          <p className="sub">Perguntas que a IA <strong>não respondeu bem</strong>, agrupadas por assunto. Resolva uma vez → nunca mais falha.</p>
        </div>
        <div className="page-header-actions">
          <button className="btn btn-soft" onClick={recluster} disabled={busy}>
            {busy ? <><i className="fas fa-circle-notch fa-spin"></i> Processando…</> : <><i className="fas fa-sync"></i> Reprocessar histórico</>}
          </button>
        </div>
      </div>

      <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 16 }}>
        <Stat label="Assuntos sem boa resposta" value={dash && dash.clusters_abertos} color="var(--or)" />
        <Stat label="Perguntas afetadas" value={dash && dash.perguntas_sem_resposta} />
        <Stat label="Sugestões prontas" value={dash && dash.sugestoes_pendentes} color="var(--gr)" />
        <Stat label="Fallbacks (24h)" value={dash && dash.fallbacks_24h} color="var(--rd)" />
        <Stat label="Resolvidos" value={dash && dash.resolvidos} color="var(--gr)" />
      </div>

      <div className="subtabs" style={{ background: "var(--bg2)", marginBottom: 12 }}>
        {["aberto", "resolvido", "ignorado", "todos"].map((s) => (
          <button key={s} className={"tab" + (statusFilter === s ? " active" : "")} onClick={() => setStatusFilter(s)}>
            {s === "aberto" ? "Abertos" : s === "resolvido" ? "Resolvidos" : s === "ignorado" ? "Ignorados" : "Todos"}
          </button>
        ))}
      </div>

      {clusters.length === 0 ? (
        <div className="card" style={{ textAlign: "center", padding: 30, color: "var(--t3)" }}>
          Nenhum assunto neste filtro. Clique em <strong>Reprocessar histórico</strong> para agrupar as perguntas.
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {clusters.map((c) => (
            <div key={c.id} className="card" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, padding: "12px 14px", cursor: "pointer" }} onClick={() => setSelected(c.id)}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {c.status === "aberto" && <i className="fas fa-fire" style={{ color: "var(--rd)", marginRight: 6 }}></i>}
                  {c.titulo_canonico}
                </div>
                <div style={{ fontSize: 11.5, color: "var(--t3)" }}>
                  <strong>{c.ocorrencias}</strong> {c.ocorrencias === 1 ? "pessoa" : "pessoas"} · conf. {c.confianca_media != null ? Number(c.confianca_media).toFixed(2) : "—"}
                  {c.tem_sugestao > 0 && <span className="badge b-gr" style={{ marginLeft: 8 }}>sugestão pronta</span>}
                </div>
              </div>
              <i className="fas fa-chevron-right" style={{ color: "var(--t3)" }}></i>
            </div>
          ))}
        </div>
      )}

      {selected && <ClusterModal id={selected} onClose={() => setSelected(null)} onChanged={refresh} />}
    </div>
  );
}

function ClusterModal({ id, onClose, onChanged }) {
  const toast = useToast();
  const [data, setData] = React.useState(null);
  const [answer, setAnswer] = React.useState("");
  const [tags, setTags] = React.useState("");
  const [publishAs, setPublishAs] = React.useState("contexto_direto");
  const [busy, setBusy] = React.useState(null);

  const load = () => api("/api/admin/learning/clusters/" + id).then((d) => {
    setData(d);
    if (d.sugestao) setAnswer(d.sugestao.resposta_sugerida || "");
  }).catch((e) => toast({ title: "Falha ao carregar", msg: e.message, kind: "error" }));
  React.useEffect(() => { load(); }, [id]);

  const research = () => {
    setBusy("research");
    api("/api/admin/learning/clusters/" + id + "/research", { method: "POST" })
      .then((r) => { setAnswer(r.resposta || ""); toast({ title: "IA pesquisou a base", msg: r.gap ? "Lacuna: pouco conteúdo" : "Resposta sugerida gerada", kind: r.gap ? "info" : "success" }); load(); })
      .catch((e) => toast({ title: "Falha na pesquisa", msg: e.message, kind: "error" }))
      .finally(() => setBusy(null));
  };
  const publish = () => {
    if ((answer || "").trim().length < 10) { toast({ title: "Resposta muito curta", kind: "info" }); return; }
    setBusy("publish");
    api("/api/admin/learning/clusters/" + id + "/publish", { method: "POST", body: { publish_as: publishAs, answer, tags } })
      .then(() => { toast({ title: "Publicado e indexado", msg: "A IA já responde isso.", kind: "success" }); onChanged(); onClose(); })
      .catch((e) => toast({ title: "Falha ao publicar", msg: e.message, kind: "error" }))
      .finally(() => setBusy(null));
  };
  const ignore = () => {
    api("/api/admin/learning/clusters/" + id + "/ignore", { method: "POST" })
      .then(() => { toast({ title: "Marcado como ignorado", kind: "info" }); onChanged(); onClose(); })
      .catch((e) => toast({ title: "Falha", msg: e.message, kind: "error" }));
  };

  const ev = (data && data.sugestao && data.sugestao.evidencias) || [];

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal modal-wide modal-tall" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h3><i className="fas fa-lightbulb"></i> {data ? data.cluster.titulo_canonico : "Carregando…"}</h3>
          <button type="button" className="icon-btn" onClick={onClose}><i className="fas fa-times"></i></button>
        </div>
        <div className="modal-body">
          {!data ? (
            <div style={{ textAlign: "center", padding: 30, color: "var(--t3)" }}><i className="fas fa-circle-notch fa-spin"></i> Carregando…</div>
          ) : (
            <>
              <div style={{ fontSize: 12, color: "var(--t3)", marginBottom: 10 }}>
                <strong>{data.cluster.ocorrencias}</strong> ocorrência(s) · status <strong>{data.cluster.status}</strong>
              </div>

              <div className="field">
                <label>Como as pessoas perguntam ({data.variacoes.length})</label>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                  {data.variacoes.slice(0, 20).map((v, i) => (
                    <span key={i} className="badge b-mut" style={{ fontSize: 11 }}>{v.pergunta}</span>
                  ))}
                </div>
              </div>

              <div className="field">
                <label>
                  Resposta sugerida
                  <button type="button" className="btn btn-soft btn-sm" style={{ marginLeft: "auto" }} onClick={research} disabled={busy === "research"}>
                    {busy === "research" ? <><i className="fas fa-circle-notch fa-spin"></i> Pesquisando…</> : <><i className="fas fa-magnifying-glass"></i> IA pesquisar na base</>}
                  </button>
                </label>
                <textarea className="input" value={answer} onChange={(e) => setAnswer(e.target.value)}
                  style={{ minHeight: 160, fontSize: 13, lineHeight: 1.6 }}
                  placeholder="Clique em 'IA pesquisar na base' para gerar uma sugestão, ou escreva a resposta manualmente." />
                {data.sugestao && data.sugestao.confianca != null && (
                  <span className="hint">Confiança da pesquisa: <strong>{Number(data.sugestao.confianca).toFixed(2)}</strong>{Number(data.sugestao.confianca) < 0.45 && " — pouca evidência na base, talvez falte conteúdo."}</span>
                )}
              </div>

              {ev.length > 0 && (
                <div className="field">
                  <label>Evidências encontradas</label>
                  <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                    {ev.slice(0, 5).map((e, i) => (
                      <div key={i} style={{ fontSize: 11.5, color: "var(--t2)", borderLeft: "2px solid var(--b1)", paddingLeft: 8 }}>
                        <strong>{Number(e.similarity).toFixed(2)}</strong> · {(e.snippet || "").slice(0, 160)}…
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <div className="field">
                <label>Tags (opcional — pra casar a pergunta)</label>
                <input className="input" value={tags} onChange={(e) => setTags(e.target.value)} placeholder="deixe vazio pra gerar automático" />
              </div>

              <div className="field">
                <label>Publicar como</label>
                <select className="input" value={publishAs} onChange={(e) => setPublishAs(e.target.value)}>
                  <option value="contexto_direto">Contexto Direto (resposta garantida)</option>
                  <option value="faq">FAQ / Conhecimento (indexado na busca)</option>
                </select>
              </div>
            </>
          )}
        </div>
        <div className="modal-foot">
          <button type="button" className="btn btn-ghost btn-sm" onClick={ignore}><i className="fas fa-ban"></i> Ignorar</button>
          <button type="button" className="btn btn-ghost" onClick={onClose}>Fechar</button>
          <button type="button" className="btn btn-primary" onClick={publish} disabled={busy === "publish" || !data}>
            {busy === "publish" ? <><i className="fas fa-circle-notch fa-spin"></i> Publicando…</> : <><i className="fas fa-check"></i> Aprovar e publicar</>}
          </button>
        </div>
      </div>
    </div>
  );
}

window.ScreenLearning = ScreenLearning;
