/* global React */
/* =====================================================
   VendusVinculo — tela "Vincular anúncios" (Catálogo-mestre, Fase A)
   -----------------------------------------------------
   Liga cada anúncio (ML hoje; Shopee/TikTok depois) a UM produto-mestre.
   Regra-mãe: a IA SUGERE, o lojista CONFIRMA. Na dúvida, não sugere — manda
   pro fluxo manual / "criar produto-mestre". Desvincular é sempre 1 clique.
===================================================== */
const { I, Chip, Btn, Card, Eyebrow, EmptyState, brl } = window.VendusAtoms;
const { useState, useEffect, useMemo } = React;

const MK = { mercado_livre: "Mercado Livre", shopee: "Shopee", tiktok: "TikTok Shop" };
const FAIXA_META = {
  alta:  { tone: "success", label: "Sugestão forte" },
  media: { tone: "warning", label: "Candidato" },
  baixa: { tone: "default", label: "Baixa confiança" },
};

// Traduz os sinais técnicos do matcher para linguagem de gente (sem jargão solto).
function traduzSinal(s) {
  if (s === "SKU igual") return "Mesmo SKU";
  if (s === "GTIN igual") return "Mesmo código de barras";
  if (s === "marca igual") return "Mesma marca";
  const mT = s.match(/^t[íi]tulo\s+(\d+)%$/i); if (mT) return `Nome ${mT[1]}% parecido`;
  const mZ = s.match(/^tamanho\s+(.+)$/i); if (mZ) return `Mesmo tamanho (${mZ[1]})`;
  return s;
}

// Selo "por que sugerimos isso" — explica os sinais que bateram em linguagem de gente.
function PorQue({ sinais }) {
  if (!sinais || !sinais.length) return null;
  return (
    <div style={{ display: "flex", gap: 5, flexWrap: "wrap", marginTop: 4 }}>
      {sinais.map((s, i) => <Chip key={i} tone="violet">{traduzSinal(s)}</Chip>)}
    </div>
  );
}

function AnuncioCard({ a, mestres, busy, onVincular, onCriar }) {
  const [escolher, setEscolher] = useState(false);
  const [sel, setSel] = useState("");
  const melhor = a.melhor;
  const fm = melhor ? FAIXA_META[melhor.faixa] || FAIXA_META.baixa : null;

  const opcoes = useMemo(() => {
    const q = (sel || "").toLowerCase();
    return (mestres || []).filter((m) => !q || (m.titulo || "").toLowerCase().includes(q)).slice(0, 8);
  }, [mestres, sel]);

  return (
    <Card padding={16} style={{ marginBottom: 10 }}>
      <div style={{ display: "flex", gap: 14, alignItems: "flex-start", flexWrap: "wrap" }}>
        {/* Anúncio */}
        <div style={{ flex: "1 1 280px", minWidth: 240 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 3 }}>
            <Chip tone="default">{MK[a.marketplace] || "Mercado Livre"}</Chip>
            {a.possivel_kit && <span title="Parece um kit/combo. Kits entram numa etapa à parte — por enquanto, pule este."><Chip tone="warning">possível kit</Chip></span>}
          </div>
          <div style={{ fontWeight: 600, fontSize: 13.5, lineHeight: 1.35 }}>{a.titulo}</div>
          <div className="text-faint" style={{ fontSize: 11.5, marginTop: 3 }}>
            {a.sku ? `SKU ${a.sku} · ` : ""}{brl(a.preco)}{a.estoque != null ? ` · ${a.estoque} un.` : ""}
          </div>
          {a.possivel_kit && <div className="text-muted" style={{ fontSize: 11.5, marginTop: 6, lineHeight: 1.45 }}>Parece um kit/combo. Kits entram numa etapa à parte — por enquanto, pule este.</div>}
        </div>

        {/* Sugestão + ações */}
        <div style={{ flex: "1 1 320px", minWidth: 280 }}>
          {melhor ? (
            <div style={{ background: "var(--bg-elev)", borderRadius: 10, padding: 12 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 2 }}>
                <Chip tone={fm.tone}>{fm.label}</Chip>
                <span className="text-faint" style={{ fontSize: 11 }}>sugestão da IA</span>
              </div>
              <div style={{ fontWeight: 600, fontSize: 13, marginTop: 4 }}>{melhor.titulo}</div>
              <PorQue sinais={melhor.sinais} />
              <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 10 }}>
                <Btn size="sm" variant="primary" disabled={busy} onClick={() => onVincular(a, melhor.mestre_id, melhor.faixa)}><I name="check" size={13} /> Confirmar</Btn>
                <Btn size="sm" variant="ghost" disabled={busy} onClick={() => setEscolher((v) => !v)}><I name="search" size={13} /> Escolher outro</Btn>
                <Btn size="sm" variant="ghost" disabled={busy} onClick={() => onCriar(a)}><I name="plus" size={13} /> Criar produto</Btn>
              </div>
            </div>
          ) : (
            <div style={{ background: "var(--bg-elev)", borderRadius: 10, padding: 12 }}>
              <div className="text-muted" style={{ fontSize: 12.5, lineHeight: 1.5 }}>
                Não achamos par no seu catálogo. Crie o produto a partir deste anúncio
                (você junta com outro igual depois, se aparecer).
              </div>
              <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 10 }}>
                <Btn size="sm" variant="primary" disabled={busy} onClick={() => onCriar(a)}><I name="plus" size={13} /> Criar produto</Btn>
                <Btn size="sm" variant="ghost" disabled={busy} onClick={() => setEscolher((v) => !v)}><I name="search" size={13} /> Escolher outro</Btn>
              </div>
            </div>
          )}

          {escolher && (
            <div style={{ marginTop: 10, border: "1px solid var(--border)", borderRadius: 10, padding: 10 }}>
              <input className="input" placeholder="Buscar no seu catálogo…" value={sel} onChange={(e) => setSel(e.target.value)} style={{ width: "100%", marginBottom: 8 }} />
              {(mestres || []).length === 0 ? (
                <div className="text-faint" style={{ fontSize: 12 }}>Seu catálogo está vazio. Use "Criar produto".</div>
              ) : opcoes.length === 0 ? (
                <div className="text-faint" style={{ fontSize: 12 }}>Nenhum produto com esse nome.</div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 4, maxHeight: 200, overflowY: "auto" }}>
                  {opcoes.map((m) => (
                    <button key={m.id} disabled={busy} onClick={() => onVincular(a, m.id, "manual")} className="navbtn" style={{ textAlign: "left", padding: "7px 9px", borderRadius: 8, fontSize: 12.5 }}>
                      <b>{m.titulo}</b>{m.marca ? <span className="text-faint"> · {m.marca}</span> : ""}{m.sku_interno ? <span className="text-faint"> · {m.sku_interno}</span> : ""}
                    </button>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </Card>
  );
}

function VinculoPage({ store }) {
  const [sug, setSug] = useState(null);     // { anuncios, total, vinculados, sem_vinculo }
  const [mestres, setMestres] = useState([]);
  const [busy, setBusy] = useState(false);
  const [filtro, setFiltro] = useState("todos"); // todos | alta | media | sem

  function load() {
    window.VendusCopilot.getVinculoSugestoes().then(setSug);
    window.VendusCopilot.getMestres().then(setMestres);
  }
  useEffect(() => { load(); }, []);

  function toast(msg, tone, icon) { window.vendusToast && window.vendusToast(msg, { icon: icon || "check-check", tone: tone || "success" }); }

  async function vincular(a, mestreId, faixa, lote) {
    setBusy(true);
    const r = await window.VendusCopilot.vincular({ ml_item_id: a.ml_item_id, produto_mestre_id: mestreId, confianca: faixa, lote });
    setBusy(false);
    if (r.ok) { if (!lote) { toast("Anúncio vinculado ✓"); load(); } return true; }
    toast(r.error || "Não consegui vincular.", "danger", "alert-triangle"); return false;
  }

  async function criar(a) {
    setBusy(true);
    const r = await window.VendusCopilot.vincular({ ml_item_id: a.ml_item_id, criar: { titulo: a.titulo, sku_interno: a.sku, preco_cheio: a.preco, estoque: a.estoque }, confianca: "manual" });
    setBusy(false);
    if (r.ok) { toast("Produto criado e anúncio vinculado ✓"); load(); }
    else toast(r.error || "Não consegui criar.", "danger", "alert-triangle");
  }

  // Lote: confirma todas as sugestões fortes (com revisão = confirm nativo + resumo)
  const anuncios = (sug && sug.anuncios) || [];
  const altos = anuncios.filter((a) => a.melhor && a.melhor.faixa === "alta");
  const semCand = anuncios.filter((a) => !a.melhor);

  async function confirmarLoteAlta() {
    if (!altos.length) return;
    if (!window.confirm(`Vamos vincular ${altos.length} anúncio(s) às suas sugestões fortes. Você pode desfazer qualquer um depois. Confirmar?`)) return;
    setBusy(true);
    let ok = 0;
    for (const a of altos) { const r = await vincular(a, a.melhor.mestre_id, "alta", true); if (r) ok++; }
    setBusy(false);
    toast(`${ok} anúncios vinculados ✓`);
    load();
  }

  async function criarTodosSemCandidato() {
    if (!semCand.length) return;
    if (!window.confirm(`Criar ${semCand.length} produto(s) a partir dos anúncios sem par?\n\nIsso cria um produto por anúncio — depois você funde os repetidos em 1 clique.`)) return;
    setBusy(true);
    let ok = 0;
    for (const a of semCand) {
      const r = await window.VendusCopilot.vincular({ ml_item_id: a.ml_item_id, criar: { titulo: a.titulo, sku_interno: a.sku, preco_cheio: a.preco, estoque: a.estoque }, confianca: "manual" });
      if (r.ok) ok++;
    }
    setBusy(false);
    toast(`${ok} produtos criados ✓`);
    load();
  }

  const filtrados = anuncios.filter((a) => {
    if (filtro === "alta") return a.melhor && a.melhor.faixa === "alta";
    if (filtro === "media") return a.melhor && a.melhor.faixa === "media";
    if (filtro === "sem") return !a.melhor;
    return true;
  });

  const total = sug ? sug.total : 0;
  const vinculados = sug ? sug.vinculados : 0;
  const pct = total > 0 ? Math.round((vinculados / total) * 100) : 0;

  if (store && !store.connected) {
    return <div className="page fade-in"><EmptyState icon="link" title="Conecte sua loja para vincular anúncios" desc="Assim que o Mercado Livre estiver conectado, seus anúncios aparecem aqui para vincular ao catálogo." /></div>;
  }

  return (
    <div className="page fade-in">
      <div className="page-header">
        <div>
          <Eyebrow>Catálogo</Eyebrow>
          <h1 className="page-title" style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            Vincular anúncios
            <span title="Você vende o mesmo produto com nomes diferentes em cada loja. Aqui você diz pro Vendus que eles são o mesmo, pra saber de verdade qual produto mais vende." style={{ display: "inline-flex", color: "var(--fg-3)", cursor: "help" }}><I name="help-circle" size={16} /></span>
          </h1>
          <div className="page-sub">Junte os anúncios que são o mesmo produto — assim suas análises somam tudo num lugar só, em vez de mostrar o mesmo item várias vezes.</div>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "flex-end", alignItems: "center" }}>
          {altos.length > 0 && <Btn variant="primary" disabled={busy} onClick={confirmarLoteAlta}><I name="check-check" size={14} /> Confirmar todas as sugestões fortes ({altos.length})</Btn>}
          {semCand.length > 0 && <Btn variant="secondary" disabled={busy} onClick={criarTodosSemCandidato}><I name="plus" size={14} /> Criar produtos dos {semCand.length} sem par</Btn>}
        </div>
      </div>

      {/* Onboarding: muitos anúncios sem par → tira o lojista do zero */}
      {sug && semCand.length >= 5 && vinculados === 0 && (
        <div className="banner" style={{ marginBottom: 14 }}>
          <I name="sparkles" size={18} className="text-orange" />
          <div className="text-muted" style={{ fontSize: 13, flex: 1, lineHeight: 1.5 }}>
            <b>Comece rápido:</b> crie um produto pra cada anúncio e depois junte os que forem iguais. Isso cria um produto por anúncio — depois você funde os repetidos em 1 clique.
          </div>
        </div>
      )}

      {/* Progresso */}
      <Card padding={16} style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
          <div style={{ fontWeight: 600, fontSize: 13 }}>{pct === 100 && total > 0 ? "Tudo vinculado 🎉 Suas análises agora somam por produto." : `${vinculados} de ${total} anúncios vinculados`}</div>
          <div className="mono-numeric text-muted" style={{ fontSize: 12.5 }}>{pct}%</div>
        </div>
        <div style={{ height: 7, borderRadius: 99, background: "var(--bg-elev)", overflow: "hidden" }}>
          <div style={{ width: pct + "%", height: "100%", background: "var(--primary)", transition: "width .3s" }} />
        </div>
      </Card>

      {!sug ? <Card padding={24}><div className="text-muted">Procurando os pares dos seus anúncios…</div></Card>
        : anuncios.length === 0 ? (
          total === 0
            ? <EmptyState icon="package" title="Nenhum anúncio ainda" desc="Sincronize sua loja nas Configurações pra puxar o catálogo." />
            : <EmptyState icon="check-check" title="Tudo vinculado 🎉" desc="Nenhum anúncio solto. Tudo já está somando por produto." />
        ) : (
        <>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 12 }}>
            {[
              ["todos", `Todos (${anuncios.length})`, "Todos os anúncios ainda sem produto no seu catálogo."],
              ["alta", `Sugestões fortes (${altos.length})`, "Bate por código, SKU ou nome quase igual. Confira e confirme."],
              ["media", `Candidatos (${anuncios.filter(a=>a.melhor&&a.melhor.faixa==="media").length})`, "Parecidos pelo nome. Dê uma olhada antes de confirmar — pode ser outro tamanho/versão."],
              ["sem", `Sem candidato (${semCand.length})`, "Não achamos par. Crie o produto ou escolha um da sua lista."],
            ].map(([k, l, tip]) => (
              <button key={k} title={tip} onClick={() => setFiltro(k)} style={{ padding: "6px 11px", borderRadius: 9, fontSize: 12, fontWeight: 600, cursor: "pointer", border: "1px solid " + (filtro === k ? "var(--primary)" : "var(--border)"), background: filtro === k ? "rgba(249,115,22,.12)" : "transparent", color: filtro === k ? "var(--primary)" : "var(--fg-2)" }}>{l}</button>
            ))}
          </div>
          {filtrados.map((a) => (
            <AnuncioCard key={a.ml_item_id} a={a} mestres={mestres} busy={busy} onVincular={(an, mid, fx) => vincular(an, mid, fx)} onCriar={criar} />
          ))}
          {filtrados.length === 0 && <Card padding={24}><div className="text-muted" style={{ textAlign: "center" }}>Nenhum anúncio neste filtro.</div></Card>}
        </>
      )}
    </div>
  );
}

window.VendusVinculo = { VinculoPage };
