/* global React, VendusAtoms, VendusCopilot */
/* Módulos de dados reais: Comparativos, Fluxo de caixa, Custos, Relatórios, Previsões.
   Todos leem dos dados já sincronizados (vendas, estratégico, produtos, análises). */
const { I, Chip, Btn, Card, Eyebrow, SectionTitle, AreaChart, Bars, Donut, EmptyState, brl, brlShort, pct } = window.VendusAtoms;
const { useState, useEffect, useMemo } = React;

const FIN_MES = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"];
const FIN_MES_LONGO = ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"];
function mKey(d) { const x = new Date(d); return x.getFullYear() + "-" + String(x.getMonth() + 1).padStart(2, "0"); }
function mLabel(k) { return FIN_MES[parseInt(k.split("-")[1], 10) - 1]; }
function deltaPct(a, b) { if (!b) return a > 0 ? 100 : 0; return ((a - b) / b) * 100; }

function FinPage({ eyebrow, title, sub, action, children }) {
  return (
    <div className="page fade-in">
      <div className="page-header">
        <div><Eyebrow>{eyebrow}</Eyebrow><h1 className="page-title">{title}</h1>{sub && <div className="page-sub">{sub}</div>}</div>
        {action}
      </div>
      {children}
    </div>
  );
}
function FinLoading() { return <Card padding={24}><div className="text-muted" style={{ fontSize: 14 }}>Carregando…</div></Card>; }
function DeltaChip({ v }) {
  const up = v >= 0;
  return <Chip tone={Math.abs(v) < 0.5 ? "default" : up ? "success" : "danger"} leading={<I name={up ? "trending-up" : "trending-down"} size={10} />}>{(up ? "+" : "") + v.toFixed(1).replace(".", ",")}%</Chip>;
}

/* ====================== COMPARATIVOS ====================== */
function RealComparatives() {
  const [sales, setSales] = useState(null);
  useEffect(() => { window.VendusCopilot.getSales().then(setSales); }, []);
  const orders = (sales && sales.orders) || [];
  const now = new Date();
  const prev = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const agg = (k) => {
    const os = orders.filter((o) => o.data && mKey(o.data) === k);
    const rb = os.reduce((s, o) => s + (+o.receita_bruta || 0), 0);
    const rl = os.reduce((s, o) => s + (+o.receita_liquida || 0), 0);
    return { receita: rb, liquido: rl, pedidos: os.length, ticket: os.length ? rb / os.length : 0 };
  };
  const cur = agg(mKey(now)), pre = agg(mKey(prev));
  const months = {};
  orders.forEach((o) => { if (o.data) { const k = mKey(o.data); months[k] = (months[k] || 0) + (+o.receita_liquida || 0); } });
  const bars = Object.keys(months).sort().slice(-6).map((k) => ({ label: mLabel(k), value: Math.round(months[k]), short: brlShort(months[k]) }));
  const cards = [
    ["Receita bruta", cur.receita, pre.receita, true],
    ["Receita líquida", cur.liquido, pre.liquido, true],
    ["Pedidos", cur.pedidos, pre.pedidos, false],
    ["Ticket médio", cur.ticket, pre.ticket, true],
  ];
  if (!sales) return <FinPage eyebrow="Lojas" title="Comparativos"><FinLoading /></FinPage>;
  return (
    <FinPage eyebrow="Lojas" title="Comparativos" sub={`${FIN_MES_LONGO[now.getMonth()]} vs ${FIN_MES_LONGO[prev.getMonth()]}`}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 16 }}>
        {cards.map(([l, a, b, money]) => (
          <Card key={l} padding={18}>
            <div className="text-faint" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".03em", fontWeight: 700 }}>{l}</div>
            <div className="font-display" style={{ fontSize: 22, fontWeight: 800, margin: "4px 0 6px" }}>{money ? brl(a) : Math.round(a)}</div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <DeltaChip v={deltaPct(a, b)} />
              <span className="text-faint" style={{ fontSize: 11 }}>antes: {money ? brl(b) : Math.round(b)}</span>
            </div>
          </Card>
        ))}
      </div>
      <Card>
        <SectionTitle title="Receita líquida por mês" sub="Últimos 6 meses" />
        {bars.length ? <Bars data={bars} height={200} /> : <div className="text-muted" style={{ fontSize: 13, padding: "20px 0" }}>Ainda não há meses suficientes para comparar.</div>}
      </Card>
    </FinPage>
  );
}

/* ====================== FLUXO DE CAIXA ====================== */
function RealCashflow() {
  const [cx, setCx] = useState(null);
  useEffect(() => { window.VendusCopilot.getCaixa(6).then(setCx); }, []);
  if (!cx) return <FinPage eyebrow="Financeiro" title="Fluxo de caixa"><FinLoading /></FinPage>;
  const now = new Date();
  const series = cx.series || [];
  const temMovimento = series.some((s) => s.entradas > 0 || s.saidas > 0);
  const saldo = cx.saldo_mes || 0;
  return (
    <FinPage eyebrow="Financeiro" title="Fluxo de caixa" sub={`Dinheiro que realmente entrou e saiu — recebimentos menos pagamentos. Mês de ${FIN_MES_LONGO[now.getMonth()]}.`}>
      {!temMovimento ? (
        <EmptyState icon="banknote" title="Sem movimento de caixa ainda" desc="Registre recebimentos em Contas a receber e pagamentos em Contas a pagar — o caixa real (o que entrou e saiu) aparece aqui." />
      ) : (
      <>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16, marginBottom: 16 }}>
        <Card padding={18}><div className="text-faint" style={{ fontSize: 11, fontWeight: 700 }}>ENTRADAS (recebidas)</div><div className="font-display" style={{ fontSize: 26, fontWeight: 800, color: "#4ADE80" }}>{brl(cx.entradas_mes)}</div><div className="text-faint" style={{ fontSize: 11.5, marginTop: 2 }}>repasses que caíram</div></Card>
        <Card padding={18}><div className="text-faint" style={{ fontSize: 11, fontWeight: 700 }}>SAÍDAS (pagas)</div><div className="font-display" style={{ fontSize: 26, fontWeight: 800, color: "#FF6A6A" }}>{brl(cx.saidas_mes)}</div><div className="text-faint" style={{ fontSize: 11.5, marginTop: 2 }}>contas + compras + antecipação</div></Card>
        <Card padding={18}><div className="text-faint" style={{ fontSize: 11, fontWeight: 700 }}>SALDO DO MÊS</div><div className="font-display" style={{ fontSize: 26, fontWeight: 800, color: saldo >= 0 ? "var(--primary)" : "#FF6A6A" }}>{brl(saldo)}</div><div className="text-faint" style={{ fontSize: 11.5, marginTop: 2 }}>entrou − saiu</div></Card>
      </div>
      <Card>
        <SectionTitle title="Saldo acumulado" sub="Dinheiro real ao longo dos meses (entradas − saídas)" />
        {series.length > 1
          ? <AreaChart height={220} series={[{ label: "Acumulado", values: series.map((s) => s.acumulado) }]} labels={series.map((s) => FIN_MES[parseInt(s.mes.split("-")[1], 10) - 1])} />
          : <div className="text-muted" style={{ fontSize: 13, padding: "20px 0" }}>Ainda há poucos meses com movimento para o gráfico.</div>}
      </Card>
      <div className="text-faint" style={{ fontSize: 12, marginTop: 12, lineHeight: 1.5 }}>
        Caixa é <b>dinheiro que se moveu</b> (recebimento/pagamento). É diferente do <b>Resultado</b> (lucro por competência) — veja a aba Resultado pra entender a diferença.
      </div>
      </>
      )}
    </FinPage>
  );
}

/* ====================== CUSTOS ====================== */
function RealCosts() {
  const [sales, setSales] = useState(null);
  const [strat, setStrat] = useState(null);
  const [res, setRes] = useState(null);
  useEffect(() => { window.VendusCopilot.getSales().then(setSales); window.VendusCopilot.getStrategic().then(setStrat); window.VendusCopilot.getResultado().then(setRes); }, []);
  const k = (sales && sales.kpis) || {};
  const ads = strat && strat.ads ? strat.ads.custo : 0;
  const receita = k.receita_bruta || 0;
  // CMV + despesas operacionais (Fase 2) entram no retrato real de "pra onde vai o dinheiro".
  const cmv = res && res.cmv ? res.cmv.valor : 0;
  const despesas = res && res.despesas_operacionais ? res.despesas_operacionais.total : 0;
  const slices = [
    { label: "Custo da mercadoria (CMV)", value: cmv || 0, color: "#FB923C" },
    { label: "Comissão Mercado Livre", value: k.comissao || 0, color: "#EC4899" },
    { label: "Frete (você paga)", value: k.frete || 0, color: "#F472B6" },
    { label: "Impostos", value: k.impostos || 0, color: "#A78BFA" },
    { label: "Anúncios (Ads)", value: ads || 0, color: "#60A5FA" },
    { label: "Despesas (aluguel, embalagem…)", value: despesas || 0, color: "#FBBF24" },
  ].filter((s) => s.value > 0);
  const total = slices.reduce((s, x) => s + x.value, 0);
  const liquido = receita - total;
  const donutSlices = slices.concat([{ label: "Sobra (líquido)", value: Math.max(0, liquido), color: "#4ADE80" }]);
  if (!sales) return <FinPage eyebrow="Financeiro" title="Custos"><FinLoading /></FinPage>;
  return (
    <FinPage eyebrow="Financeiro" title="Custos" sub="Para onde vai o seu dinheiro (últimos pedidos sincronizados)">
      {total === 0 ? (
        <EmptyState icon="receipt" title="Sem custos para mostrar ainda" desc="Assim que houver vendas com taxas e Ads sincronizados, o detalhamento aparece aqui." />
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 16 }}>
          <Card>
            <div style={{ display: "flex", justifyContent: "center", marginBottom: 8 }}>
              <Donut slices={donutSlices} size={180} stroke={24} center={<div><div className="text-faint" style={{ fontSize: 10 }}>CUSTO TOTAL</div><div className="font-display" style={{ fontSize: 18, fontWeight: 700 }}>{brl(total)}</div></div>} />
            </div>
            <div className="text-faint" style={{ fontSize: 11.5, textAlign: "center" }}>{receita ? ((total / receita) * 100).toFixed(0) : 0}% da sua receita vira custo</div>
          </Card>
          <Card>
            <SectionTitle title="Detalhamento" sub="Quanto cada custo pesa na receita" />
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 8 }}>
              {donutSlices.map((s) => (
                <div key={s.label} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 13 }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 8 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: s.color }} />{s.label}</span>
                  <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <span className="text-faint" style={{ fontSize: 11.5 }}>{receita ? ((s.value / receita) * 100).toFixed(1) : 0}%</span>
                    <span className="font-display mono-numeric" style={{ fontWeight: 700 }}>{brl(s.value)}</span>
                  </span>
                </div>
              ))}
            </div>
          </Card>
        </div>
      )}
    </FinPage>
  );
}

/* ====================== PREVISÕES E PROJEÇÕES ====================== */
function RealForecasts() {
  const [strat, setStrat] = useState(null);
  const [prods, setProds] = useState(null);
  useEffect(() => { window.VendusCopilot.getStrategic().then(setStrat); window.VendusCopilot.getProducts().then(setProds); }, []);
  const b = (strat && strat.base) || {};
  const cen = (strat && strat.cenarios) || {};
  const serie = (strat && strat.serie_mensal) || [];
  const baixo = (prods || []).filter((p) => (p.estoque ?? 0) < 10).sort((a, b2) => (a.estoque ?? 0) - (b2.estoque ?? 0)).slice(0, 10);
  // gráfico: histórico + projeção realista
  const hist = serie.map((x) => x.receita / 1000);
  const ult = hist.length ? hist[hist.length - 1] : (b.receita_liquida_90d || 0) / 3000;
  const alvoMes = ((cen.realista && cen.realista.receita_90d) || (b.receita_liquida_90d || 0)) / 3000;
  const proj = [1, 2, 3].map((i) => ult + (alvoMes - ult) * (i / 3));
  const chartVals = hist.concat(proj);
  const labels = serie.map((x) => FIN_MES[parseInt(x.mes.split("-")[1], 10) - 1]).concat(["+30d", "+60d", "+90d"]);
  if (!strat) return <FinPage eyebrow="Análises" title="Previsões e Projeções"><FinLoading /></FinPage>;
  if (!strat.conectado || !strat.base) return <FinPage eyebrow="Análises" title="Previsões e Projeções"><EmptyState icon="trending-up" title="Sem histórico suficiente" desc="As projeções aparecem quando houver vendas registradas." /></FinPage>;
  return (
    <FinPage eyebrow="Análises" title="Previsões e Projeções" sub="Estimativas a partir dos seus últimos 90 dias — são hipóteses, não promessas">
      <Card style={{ marginBottom: 16 }}>
        <SectionTitle title="Projeção de receita (90 dias)" sub="Histórico real + tendência" />
        <AreaChart height={220} series={[{ label: "Receita", values: chartVals }]} />
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
          {labels.map((m, i) => <span key={i} style={{ fontSize: 10, color: i >= serie.length ? "var(--primary)" : "var(--fg-3)", fontFamily: "Space Grotesk", fontWeight: i >= serie.length ? 700 : 400 }}>{m}</span>)}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginTop: 16 }}>
          {[["Pessimista", cen.pessimista, "#FF6A6A"], ["Realista", cen.realista, "var(--primary)"], ["Otimista", cen.otimista, "#4ADE80"]].map(([l, c, cor]) => (
            <div key={l} style={{ background: "var(--bg-elev)", borderRadius: 10, padding: "10px 12px" }}>
              <div className="text-faint" style={{ fontSize: 11 }}>{l} (90d)</div>
              <div className="font-display mono-numeric" style={{ fontSize: 16, fontWeight: 800, color: cor }}>{brl(c && c.receita_90d)}</div>
              {c && c.lucro_90d != null && <div className="text-faint" style={{ fontSize: 10.5 }}>lucro ~{brl(c.lucro_90d)}</div>}
            </div>
          ))}
        </div>
      </Card>

      <Card>
        <SectionTitle title="Risco de ruptura de estoque" sub="Produtos com estoque baixo — reponha para não perder vendas" />
        {baixo.length === 0 ? (
          <div className="text-muted" style={{ fontSize: 13, padding: "12px 0" }}>Nenhum produto com estoque crítico agora. 👍</div>
        ) : (
          <table className="tbl" style={{ marginTop: 8 }}>
            <thead><tr><th>Produto</th><th className="num">Estoque</th></tr></thead>
            <tbody>
              {baixo.map((p) => (
                <tr key={p.ml_item_id}>
                  <td style={{ maxWidth: 420, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.titulo}</td>
                  <td className="num"><Chip tone={(p.estoque ?? 0) < 5 ? "danger" : "warning"}>{p.estoque ?? 0} un.</Chip></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>
    </FinPage>
  );
}

/* ====================== RELATÓRIOS ====================== */
const REL_SKILL = {
  copiloto: { l: "Diagnóstico do Copiloto", ic: "sparkles", tone: "orange" },
  qualidade: { l: "Score de qualidade", ic: "gauge", tone: "violet" },
  estrategico: { l: "Plano estratégico", ic: "activity", tone: "success" },
  ads: { l: "Anúncios", ic: "megaphone", tone: "info" },
  desempenho: { l: "Desempenho", ic: "trending-up", tone: "info" },
  margem: { l: "Margem", ic: "percent", tone: "info" },
  conteudo: { l: "Conteúdo", ic: "image", tone: "info" },
};
function fmtDataLonga(d) {
  if (!d) return "";
  const dt = new Date(d);
  return dt.toLocaleDateString("pt-BR", { day: "2-digit", month: "long", year: "numeric" }) + " às " + dt.toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" });
}
function RealReports() {
  const [list, setList] = useState(null);
  const [open, setOpen] = useState(null);
  useEffect(() => { window.VendusCopilot.getAnalysesHistory().then(setList); }, []);
  if (!list) return <FinPage eyebrow="Análises" title="Relatórios"><FinLoading /></FinPage>;
  return (
    <FinPage eyebrow="Análises" title="Relatórios" sub="Histórico das análises da sua loja — abra e exporte em PDF">
      {list.length === 0 ? (
        <EmptyState icon="file-text" title="Nenhum relatório ainda" desc="Os relatórios são as análises do Copiloto, Score e Modo Estratégico. Rode uma análise (no Piloto) para o primeiro aparecer aqui." />
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {list.map((a) => {
            const s = REL_SKILL[a.skill] || { l: a.skill, ic: "file-text", tone: "default" };
            return (
              <Card key={a.id} className="card-hover" padding={16} onClick={() => setOpen(a)} style={{ cursor: "pointer" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ width: 38, height: 38, borderRadius: 10, background: "var(--bg-elev)", display: "grid", placeItems: "center", color: "var(--primary)", flexShrink: 0 }}><I name={s.ic} size={17} /></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}><span style={{ fontWeight: 700, fontSize: 13.5 }}>{s.l}</span><Chip tone="default">{a.periodo}</Chip></div>
                    <div className="text-muted" style={{ fontSize: 12.5, marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.resumo || "—"}</div>
                  </div>
                  <span className="text-faint" style={{ fontSize: 11, flexShrink: 0 }}>{new Date(a.created_at).toLocaleDateString("pt-BR")}</span>
                  <I name="chevron-right" size={16} className="text-faint" />
                </div>
              </Card>
            );
          })}
        </div>
      )}
      {open && <ReportView analise={open} onClose={() => setOpen(null)} />}
    </FinPage>
  );
}
function ReportView({ analise, onClose }) {
  const s = REL_SKILL[analise.skill] || { l: analise.skill };
  const f = analise.findings;
  const findings = Array.isArray(f && f.findings) ? f.findings : Array.isArray(f) ? f : null;
  const dimensoes = f && Array.isArray(f.dimensoes) ? f.dimensoes : null;
  const plano = f && f.plano ? f.plano : null;
  return (
    <div className="report-backdrop" onClick={onClose}>
      <div className="report-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="report-toolbar" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 20px", borderBottom: "1px solid var(--border)" }}>
          <span style={{ fontWeight: 700 }}>{s.l}</span>
          <div style={{ display: "flex", gap: 8 }}>
            <Btn variant="secondary" size="sm" onClick={() => window.print()}><I name="printer" size={13} /> Exportar PDF</Btn>
            <Btn variant="ghost" size="sm" onClick={onClose}><I name="x" size={14} /></Btn>
          </div>
        </div>
        <div id="vendus-report" style={{ padding: 24, overflowY: "auto" }}>
          <div style={{ fontWeight: 800, fontSize: 20, fontFamily: "Space Grotesk" }}>Vendus · {s.l}</div>
          <div className="text-muted" style={{ fontSize: 12.5, marginBottom: 16 }}>{fmtDataLonga(analise.created_at)} · período: {analise.periodo}</div>
          {analise.resumo && <p style={{ fontSize: 14, lineHeight: 1.6, marginBottom: 18 }}>{analise.resumo}</p>}

          {findings && findings.map((x, i) => (
            <div key={i} style={{ borderLeft: "3px solid var(--primary)", paddingLeft: 12, marginBottom: 14 }}>
              <div style={{ fontWeight: 700, fontSize: 14 }}>{i + 1}. {x.titulo}</div>
              {x.o_que_significa && <div className="text-muted" style={{ fontSize: 12.5, margin: "4px 0" }}>{x.o_que_significa}</div>}
              {x.o_que_fazer && <div style={{ fontSize: 12.5, fontWeight: 600 }}>→ {x.o_que_fazer}</div>}
              {x.impacto && <div className="text-faint" style={{ fontSize: 11.5, marginTop: 2 }}>Impacto: {x.impacto}</div>}
            </div>
          ))}

          {dimensoes && (
            <div>
              {f.score_geral != null && <div style={{ fontWeight: 800, fontSize: 28, fontFamily: "Space Grotesk" }}>{f.score_geral}/100 <span style={{ fontSize: 14, fontWeight: 600 }}>{f.nota_texto || ""}</span></div>}
              <div style={{ marginTop: 10 }}>{dimensoes.map((d) => (
                <div key={d.chave} style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, padding: "4px 0", borderBottom: "1px solid var(--border)" }}>
                  <span>{d.nome}</span><span style={{ fontWeight: 700 }}>{d.status === "sem_dado" ? "—" : d.score}</span>
                </div>
              ))}</div>
            </div>
          )}

          {plano && (
            <div>
              {["d30", "d60", "d90"].map((kk) => (plano[kk] || []).length > 0 && (
                <div key={kk} style={{ marginBottom: 12 }}>
                  <div style={{ fontWeight: 700, fontSize: 13 }}>{kk === "d30" ? "Próximos 30 dias" : kk === "d60" ? "Até 60 dias" : "Até 90 dias"}</div>
                  {(plano[kk] || []).map((it, i) => <div key={i} style={{ fontSize: 12.5, padding: "2px 0" }}>• {it}</div>)}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ====================== FORNECEDORES + COMPRAS (cadastro) ====================== */
function FinModal({ title, onClose, children, footer }) {
  return (
    <div className="report-backdrop" onClick={onClose}>
      <div className="modal-sheet" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 480, width: "100%" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "14px 18px", borderBottom: "1px solid var(--border)" }}>
          <span style={{ fontWeight: 700, fontSize: 15 }}>{title}</span>
          <button onClick={onClose} style={{ background: "transparent", border: 0, color: "var(--fg-2)", cursor: "pointer" }}><I name="x" size={18} /></button>
        </div>
        <div style={{ padding: 18, maxHeight: "70vh", overflowY: "auto" }}>{children}</div>
        {footer && <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, padding: "0 18px 18px" }}>{footer}</div>}
      </div>
    </div>
  );
}
function Inp({ label, value, onChange, placeholder, type }) {
  return (
    <label style={{ display: "block", marginBottom: 12 }}>
      <div className="text-muted" style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>{label}</div>
      <input className="input" type={type || "text"} value={value == null ? "" : value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} style={{ width: "100%" }} />
    </label>
  );
}

function RealSuppliers() {
  const [list, setList] = useState(null);
  const [editing, setEditing] = useState(null);
  function load() { window.VendusCopilot.getSuppliers().then(setList); }
  useEffect(() => { load(); }, []);
  async function salvar() {
    if (!editing.nome || !editing.nome.trim()) { window.vendusToast && window.vendusToast("Informe o nome do fornecedor.", { icon: "alert-triangle", tone: "warning" }); return; }
    const r = await window.VendusCopilot.saveSupplier(editing);
    if (r.ok) { setEditing(null); load(); window.vendusToast && window.vendusToast("Fornecedor salvo.", { icon: "check-check", tone: "success" }); }
    else window.vendusToast && window.vendusToast(r.error, { icon: "alert-triangle", tone: "danger" });
  }
  async function excluir(s) {
    if (!window.confirm(`Excluir o fornecedor "${s.nome}"?`)) return;
    const r = await window.VendusCopilot.deleteSupplier(s.id);
    if (r.ok) load(); else window.vendusToast && window.vendusToast(r.error, { icon: "alert-triangle", tone: "danger" });
  }
  if (!list) return <FinPage eyebrow="Financeiro" title="Fornecedores"><FinLoading /></FinPage>;
  return (
    <FinPage eyebrow="Financeiro" title="Fornecedores" sub="Seus fornecedores e contatos"
      action={<Btn variant="primary" onClick={() => setEditing({})}><I name="plus" size={14} /> Novo fornecedor</Btn>}>
      {list.length === 0 ? (
        <EmptyState icon="users" title="Nenhum fornecedor cadastrado" desc="Cadastre seus fornecedores para registrar compras e organizar contatos." cta="Novo fornecedor" onCta={() => setEditing({})} />
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px,1fr))", gap: 12 }}>
          {list.map((s) => (
            <Card key={s.id} padding={16}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{s.nome}</div>
                  {s.contato && <div className="text-muted" style={{ fontSize: 12.5 }}>{s.contato}</div>}
                  <div className="text-faint" style={{ fontSize: 11.5, marginTop: 4, lineHeight: 1.5 }}>
                    {s.telefone && <div>📞 {s.telefone}</div>}
                    {s.email && <div>✉ {s.email}</div>}
                    {s.cnpj && <div>CNPJ: {s.cnpj}</div>}
                  </div>
                </div>
                <div style={{ display: "flex", gap: 4 }}>
                  <button onClick={() => setEditing(s)} title="Editar" style={{ background: "transparent", border: 0, color: "var(--fg-3)", cursor: "pointer" }}><I name="pencil" size={14} /></button>
                  <button onClick={() => excluir(s)} title="Excluir" style={{ background: "transparent", border: 0, color: "#FF6A6A", cursor: "pointer" }}><I name="trash-2" size={14} /></button>
                </div>
              </div>
              {s.observacao && <div className="text-faint" style={{ fontSize: 11.5, marginTop: 8, borderTop: "1px solid var(--border)", paddingTop: 8 }}>{s.observacao}</div>}
            </Card>
          ))}
        </div>
      )}
      {editing && (
        <FinModal title={editing.id ? "Editar fornecedor" : "Novo fornecedor"} onClose={() => setEditing(null)}
          footer={<><Btn variant="ghost" onClick={() => setEditing(null)}>Cancelar</Btn><Btn variant="primary" onClick={salvar}><I name="check" size={13} /> Salvar</Btn></>}>
          <Inp label="Nome *" value={editing.nome} onChange={(v) => setEditing({ ...editing, nome: v })} placeholder="Ex.: Distribuidora ABC" />
          <Inp label="Contato (pessoa)" value={editing.contato} onChange={(v) => setEditing({ ...editing, contato: v })} />
          <Inp label="Telefone" value={editing.telefone} onChange={(v) => setEditing({ ...editing, telefone: v })} />
          <Inp label="E-mail" value={editing.email} onChange={(v) => setEditing({ ...editing, email: v })} />
          <Inp label="CNPJ" value={editing.cnpj} onChange={(v) => setEditing({ ...editing, cnpj: v })} />
          <Inp label="Observação" value={editing.observacao} onChange={(v) => setEditing({ ...editing, observacao: v })} />
        </FinModal>
      )}
    </FinPage>
  );
}

const COMPRA_STATUS = { pedido: { l: "Pedido", t: "warning" }, recebido: { l: "Recebido", t: "success" }, cancelado: { l: "Cancelado", t: "default" } };
function RealPurchases() {
  const [list, setList] = useState(null);
  const [prods, setProds] = useState([]);
  const [sups, setSups] = useState([]);
  const [add, setAdd] = useState(null);
  function load() { window.VendusCopilot.getPurchases().then(setList); }
  useEffect(() => { load(); window.VendusCopilot.getProducts().then(setProds); window.VendusCopilot.getSuppliers().then(setSups); }, []);
  async function salvar() {
    const q = Math.round(Number(add.quantidade) || 0);
    if (!add.produto_nome) { window.vendusToast && window.vendusToast("Escolha o produto.", { icon: "alert-triangle", tone: "warning" }); return; }
    if (q <= 0) { window.vendusToast && window.vendusToast("Informe a quantidade.", { icon: "alert-triangle", tone: "warning" }); return; }
    const r = await window.VendusCopilot.savePurchase(add);
    if (r.ok) { setAdd(null); load(); window.vendusToast && window.vendusToast(add.status === "recebido" ? "Compra registrada e estoque atualizado." : "Compra registrada.", { icon: "check-check", tone: "success" }); }
    else window.vendusToast && window.vendusToast(r.error, { icon: "alert-triangle", tone: "danger" });
  }
  async function mudar(p, status) {
    if (status === "recebido" && !window.confirm("Receber esta compra? O estoque e o custo do produto serão atualizados.")) return;
    const r = await window.VendusCopilot.updatePurchaseStatus(p.id, status);
    if (r.ok) { load(); if (status === "recebido") window.vendusToast && window.vendusToast("Estoque atualizado!", { icon: "package", tone: "success" }); }
    else window.vendusToast && window.vendusToast(r.error, { icon: "alert-triangle", tone: "danger" });
  }
  async function excluir(p) { if (!window.confirm("Excluir esta compra?")) return; const r = await window.VendusCopilot.deletePurchase(p.id); if (r.ok) load(); }
  function pickProduct(id) {
    const pr = prods.find((x) => x.ml_item_id === id);
    setAdd({ ...add, ml_item_id: id, produto_nome: pr ? pr.titulo : id, _pid: id, custo_unit: add.custo_unit || (pr && pr.custo) || "" });
  }
  const q = Math.round(Number(add && add.quantidade) || 0); const cu = Number(String(add && add.custo_unit).replace(",", ".")) || 0;
  if (!list) return <FinPage eyebrow="Financeiro" title="Compras de estoque"><FinLoading /></FinPage>;
  return (
    <FinPage eyebrow="Financeiro" title="Compras de estoque" sub="Registre reposições — ao receber, o estoque e o custo do produto são atualizados"
      action={<Btn variant="primary" onClick={() => setAdd({ status: "pedido", data: new Date().toISOString().slice(0, 10) })}><I name="plus" size={14} /> Nova compra</Btn>}>
      {list.length === 0 ? (
        <EmptyState icon="shopping-bag" title="Nenhuma compra registrada" desc="Registre uma compra de estoque. Ao marcar como recebida, o Vendus soma a quantidade ao estoque e atualiza o custo do produto." cta="Nova compra" onCta={() => setAdd({ status: "pedido", data: new Date().toISOString().slice(0, 10) })} />
      ) : (
        <Card padding={0}>
          <table className="tbl">
            <thead><tr><th>Produto</th><th>Fornecedor</th><th className="num">Qtd</th><th className="num">Custo un.</th><th className="num">Total</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {list.map((p) => {
                const st = COMPRA_STATUS[p.status] || COMPRA_STATUS.pedido;
                return (
                  <tr key={p.id}>
                    <td style={{ maxWidth: 240, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.produto_nome || "—"}</td>
                    <td className="text-muted">{p.fornecedor_nome || "—"}</td>
                    <td className="num mono-numeric">{p.quantidade}</td>
                    <td className="num mono-numeric">{brl(p.custo_unit)}</td>
                    <td className="num mono-numeric font-display" style={{ fontWeight: 700 }}>{brl(p.total)}</td>
                    <td><Chip tone={st.t}>{st.l}</Chip></td>
                    <td className="num" style={{ whiteSpace: "nowrap" }}>
                      {p.status === "pedido" && <Btn size="sm" variant="ghost" onClick={() => mudar(p, "recebido")} title="Marcar recebida (atualiza estoque)"><I name="package-check" size={13} /> Receber</Btn>}
                      <button onClick={() => excluir(p)} title="Excluir" style={{ background: "transparent", border: 0, color: "#FF6A6A", cursor: "pointer", marginLeft: 6 }}><I name="trash-2" size={13} /></button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      )}
      {add && (
        <FinModal title="Nova compra" onClose={() => setAdd(null)}
          footer={<><Btn variant="ghost" onClick={() => setAdd(null)}>Cancelar</Btn><Btn variant="primary" onClick={salvar}><I name="check" size={13} /> Registrar</Btn></>}>
          <label style={{ display: "block", marginBottom: 12 }}>
            <div className="text-muted" style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>Produto *</div>
            <select className="input" value={add._pid || ""} onChange={(e) => pickProduct(e.target.value)} style={{ width: "100%" }}>
              <option value="">Selecione…</option>
              {prods.map((pr) => <option key={pr.ml_item_id} value={pr.ml_item_id}>{pr.titulo}</option>)}
            </select>
          </label>
          <label style={{ display: "block", marginBottom: 12 }}>
            <div className="text-muted" style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>Fornecedor</div>
            <select className="input" value={add.supplier_id || ""} onChange={(e) => setAdd({ ...add, supplier_id: e.target.value || undefined })} style={{ width: "100%" }}>
              <option value="">— (opcional) —</option>
              {sups.map((s) => <option key={s.id} value={s.id}>{s.nome}</option>)}
            </select>
          </label>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Inp label="Quantidade" type="number" value={add.quantidade} onChange={(v) => setAdd({ ...add, quantidade: v })} />
            <Inp label="Custo unitário (R$)" value={add.custo_unit} onChange={(v) => setAdd({ ...add, custo_unit: v })} placeholder="0,00" />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Inp label="Data" type="date" value={add.data} onChange={(v) => setAdd({ ...add, data: v })} />
            <label style={{ display: "block", marginBottom: 12 }}>
              <div className="text-muted" style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>Situação</div>
              <select className="input" value={add.status} onChange={(e) => setAdd({ ...add, status: e.target.value })} style={{ width: "100%" }}>
                <option value="pedido">Pedido (não recebido)</option>
                <option value="recebido">Recebido (atualiza estoque)</option>
              </select>
            </label>
          </div>
          <Inp label="Observação" value={add.observacao} onChange={(v) => setAdd({ ...add, observacao: v })} />
          {q > 0 && cu > 0 && <div className="text-faint" style={{ fontSize: 12, marginTop: 4 }}>Total: <b>{brl(q * cu)}</b>{add.status === "recebido" ? " · ao registrar, +" + q + " no estoque" : ""}</div>}
        </FinModal>
      )}
    </FinPage>
  );
}

/* ====================== CONTAS A PAGAR (Financeiro Fase 1) ====================== */
const CAT_PAGAR = [
  ["estoque", "Estoque"], ["embalagem", "Embalagem"], ["aluguel", "Aluguel"], ["internet", "Internet"],
  ["salario", "Salário"], ["ads", "Anúncios"], ["imposto", "Imposto"], ["outro", "Outro"],
];
const CAT_LABEL = Object.fromEntries(CAT_PAGAR);
const METODOS = [["", "—"], ["pix", "Pix"], ["boleto", "Boleto"], ["cartao", "Cartão"], ["transferencia", "Transferência"], ["outro", "Outro"]];
const hojeStr = () => new Date().toISOString().slice(0, 10);
function fmtData(d) { if (!d) return "—"; const [a, m, dia] = String(d).slice(0, 10).split("-"); return `${dia}/${m}/${a.slice(2)}`; }

function RealContasPagar() {
  const [list, setList] = useState(null);
  const [sups, setSups] = useState([]);
  const [filtro, setFiltro] = useState("todas"); // todas | aberto | atrasadas | pagas
  const [novo, setNovo] = useState(null);   // form de novo lançamento
  const [pagar, setPagar] = useState(null); // { lanc } modal de pagamento
  const [hist, setHist] = useState(null);   // { lanc, movimentos }
  const [nLojas, setNLojas] = useState(1);
  function load() { window.VendusCopilot.getLancamentos("pagar").then(setList); }
  useEffect(() => { load(); window.VendusCopilot.getSuppliers().then(setSups); window.VendusCopilot.getAccounts().then((a) => setNLojas(a.length)); }, []);

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

  async function salvarNovo() {
    const v = Number(String(novo.valor_total).replace(",", ".")) || 0;
    if (v <= 0) { toast("Informe um valor maior que zero.", "warning", "alert-triangle"); return; }
    const r = await window.VendusCopilot.saveLancamento({
      descricao: novo.descricao || null, categoria: novo.categoria || "outro", valor_total: novo.valor_total,
      vencimento: novo.vencimento || null, fornecedor_id: novo.fornecedor_id || undefined,
      recorrencia: novo.recorrencia ? "mensal" : null, negocio: !!novo.negocio,
    });
    if (r.ok) { setNovo(null); load(); toast(novo.recorrencia ? "Conta recorrente criada ✓" : "Conta criada ✓"); }
    else toast(r.error || "Não consegui salvar.", "danger", "alert-triangle");
  }
  async function registrarPagamento() {
    const v = Number(String(pagar.valor).replace(",", ".")) || 0;
    if (v <= 0) { toast("Informe um valor maior que zero.", "warning", "alert-triangle"); return; }
    const r = await window.VendusCopilot.pagarLancamento({ lancamento_id: pagar.lanc.id, valor: pagar.valor, data: pagar.data || hojeStr(), metodo: pagar.metodo || undefined, observacao: pagar.observacao || undefined });
    if (r.ok) { setPagar(null); load(); toast(r.status === "pago" ? "Conta quitada ✓ — em dia" : `Pagamento registrado · falta ${brl(r.falta)}`); }
    else toast(r.error || "Não consegui registrar.", "danger", "alert-triangle");
  }
  async function excluir(l) {
    if (!window.confirm(`Excluir "${l.descricao || CAT_LABEL[l.categoria]}"? Os pagamentos registrados nela também somem.`)) return;
    const r = await window.VendusCopilot.deleteLancamento(l.id);
    if (r.ok) load(); else toast(r.error || "Não consegui excluir.", "danger", "alert-triangle");
  }
  async function verPagamentos(l) {
    const movs = await window.VendusCopilot.getMovimentos(l.id);
    setHist({ lanc: l, movimentos: movs });
  }
  async function excluirMovimento(m) {
    if (!window.confirm("Excluir este pagamento? O status da conta volta a recalcular.")) return;
    const r = await window.VendusCopilot.deleteMovimento(m.id);
    if (r.ok) { const movs = await window.VendusCopilot.getMovimentos(hist.lanc.id); setHist({ ...hist, movimentos: movs }); load(); }
    else toast(r.error, "danger", "alert-triangle");
  }

  const itens = list || [];
  const abertos = itens.filter((l) => l.status !== "pago");
  const totalAberto = abertos.reduce((s, l) => s + (l.falta || 0), 0);
  const atrasadas = itens.filter((l) => l.atrasado);
  const em7dias = abertos.filter((l) => l.vencimento && !l.atrasado && String(l.vencimento).slice(0, 10) <= new Date(Date.now() + 7 * 864e5).toISOString().slice(0, 10));
  const proximos7 = em7dias.reduce((s, l) => s + (l.falta || 0), 0);

  const filtrados = itens.filter((l) => {
    if (filtro === "aberto") return l.status !== "pago";
    if (filtro === "atrasadas") return l.atrasado;
    if (filtro === "pagas") return l.status === "pago";
    return true;
  }).sort((a, b) => {
    if (a.atrasado !== b.atrasado) return a.atrasado ? -1 : 1;            // atrasadas primeiro
    return String(a.vencimento || "9999").localeCompare(String(b.vencimento || "9999")); // vencimento mais próximo
  });

  const stChip = (l) => {
    if (l.status === "pago") return { t: "success", txt: "Pago" };
    if (l.atrasado) return { t: "danger", txt: l.status === "parcial" ? "Parcial · atrasado" : "Atrasado" };
    if (l.status === "parcial") return { t: "warning", txt: "Parcial" };
    return { t: "default", txt: "Aberto" };
  };

  if (!list) return <FinPage eyebrow="Financeiro" title="Contas a pagar"><FinLoading /></FinPage>;
  const faltaSel = pagar ? pagar.lanc.falta : 0;
  const vPagar = pagar ? (Number(String(pagar.valor).replace(",", ".")) || 0) : 0;

  return (
    <FinPage eyebrow="Financeiro" title="Contas a pagar" sub="O que você tem pra pagar — com pagamento parcial, vencimento e status. Compras de estoque entram aqui também."
      action={<Btn variant="primary" onClick={() => setNovo({ categoria: "outro", data: hojeStr() })}><I name="plus" size={14} /> Nova conta</Btn>}>

      {/* Resumo */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginBottom: 16 }}>
        {[
          { rot: "A pagar (em aberto)", val: brl(totalAberto), cor: "var(--fg-1)" },
          { rot: "Atrasadas", val: atrasadas.length + (atrasadas.length === 1 ? " conta" : " contas"), cor: atrasadas.length ? "#FF6A6A" : "var(--fg-1)", sub: atrasadas.length ? brl(atrasadas.reduce((s, l) => s + l.falta, 0)) + " vencido" : "nada vencido" },
          { rot: "Vence em 7 dias", val: brl(proximos7), cor: proximos7 > 0 ? "#FB923C" : "var(--fg-1)", sub: em7dias.length + (em7dias.length === 1 ? " conta" : " contas") },
        ].map((c) => (
          <Card key={c.rot} padding={14}>
            <div className="text-faint" style={{ fontSize: 11 }}>{c.rot}</div>
            <div className="font-display mono-numeric" style={{ fontSize: 22, fontWeight: 800, color: c.cor, marginTop: 2 }}>{c.val}</div>
            {c.sub && <div className="text-faint" style={{ fontSize: 11, marginTop: 2 }}>{c.sub}</div>}
          </Card>
        ))}
      </div>

      {itens.length === 0 ? (
        <EmptyState icon="receipt" title="Nenhuma conta a pagar" desc="Cadastre uma conta (aluguel, embalagem, fornecedor…) ou registre uma compra de estoque — ela entra aqui automaticamente." cta="Nova conta" onCta={() => setNovo({ categoria: "outro", data: hojeStr() })} />
      ) : (
        <>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 12 }}>
            {[["todas", `Todas (${itens.length})`], ["aberto", `Em aberto (${abertos.length})`], ["atrasadas", `Atrasadas (${atrasadas.length})`], ["pagas", `Pagas (${itens.length - abertos.length})`]].map(([k, l]) => (
              <button key={k} 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>
          <Card padding={0}>
            <table className="tbl">
              <thead><tr><th>Conta</th><th>Categoria</th><th>Vencimento</th><th className="num">Valor</th><th className="num">Pago</th><th className="num">Falta</th><th>Status</th><th></th></tr></thead>
              <tbody>
                {filtrados.map((l) => { const st = stChip(l); return (
                  <tr key={l.id}>
                    <td style={{ maxWidth: 230 }}>
                      <div style={{ fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{l.descricao || CAT_LABEL[l.categoria] || "Conta"}</div>
                      {(l.fornecedor_nome || l.compra_id || l.recorrente) && <div className="text-faint" style={{ fontSize: 11 }}>{l.fornecedor_nome || ""}{l.compra_id ? " · compra de estoque" : ""}{l.recorrente ? " · mensal" : ""}</div>}
                    </td>
                    <td className="text-muted" style={{ fontSize: 12 }}>{CAT_LABEL[l.categoria] || l.categoria}</td>
                    <td className="text-muted" style={{ fontSize: 12.5 }}>{fmtData(l.vencimento)}</td>
                    <td className="num mono-numeric">{brl(l.valor_total)}</td>
                    <td className="num mono-numeric" style={{ color: l.valor_pago > 0 ? "#4ADE80" : "var(--fg-3)" }}>{l.valor_pago > 0 ? brl(l.valor_pago) : "—"}</td>
                    <td className="num mono-numeric font-display" style={{ fontWeight: 700, color: l.falta > 0 ? "var(--fg-1)" : "var(--fg-3)" }}>{l.falta > 0 ? brl(l.falta) : "—"}</td>
                    <td><Chip tone={st.t}>{st.txt}</Chip></td>
                    <td className="num" style={{ whiteSpace: "nowrap" }}>
                      {l.status !== "pago" && <Btn size="sm" variant="ghost" onClick={() => setPagar({ lanc: l, valor: "", data: hojeStr() })} title="Registrar pagamento"><I name="banknote" size={13} /> Pagar</Btn>}
                      {l.n_pagamentos > 0 && <button onClick={() => verPagamentos(l)} title="Ver pagamentos" style={{ background: "transparent", border: 0, color: "var(--fg-2)", cursor: "pointer", marginLeft: 4 }}><I name="list" size={14} /></button>}
                      <button onClick={() => excluir(l)} title="Excluir" style={{ background: "transparent", border: 0, color: "#FF6A6A", cursor: "pointer", marginLeft: 6 }}><I name="trash-2" size={13} /></button>
                    </td>
                  </tr>
                ); })}
                {filtrados.length === 0 && <tr><td colSpan={8} style={{ padding: 22, textAlign: "center" }} className="text-muted">Nenhuma conta neste filtro.</td></tr>}
              </tbody>
            </table>
          </Card>
        </>
      )}

      {/* Nova conta */}
      {novo && (
        <FinModal title="Nova conta a pagar" onClose={() => setNovo(null)}
          footer={<><Btn variant="ghost" onClick={() => setNovo(null)}>Cancelar</Btn><Btn variant="primary" onClick={salvarNovo}><I name="check" size={13} /> Salvar</Btn></>}>
          <Inp label="Descrição" value={novo.descricao} onChange={(v) => setNovo({ ...novo, descricao: v })} placeholder="Ex.: Aluguel da loja" />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <label style={{ display: "block", marginBottom: 12 }}>
              <div className="text-muted" style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>Categoria</div>
              <select className="input" value={novo.categoria} onChange={(e) => setNovo({ ...novo, categoria: e.target.value })} style={{ width: "100%" }}>
                {CAT_PAGAR.map(([k, l]) => <option key={k} value={k}>{l}</option>)}
              </select>
            </label>
            <Inp label="Valor (R$)" value={novo.valor_total} onChange={(v) => setNovo({ ...novo, valor_total: v })} placeholder="0,00" />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Inp label="Vencimento" type="date" value={novo.vencimento} onChange={(v) => setNovo({ ...novo, vencimento: v })} />
            <label style={{ display: "block", marginBottom: 12 }}>
              <div className="text-muted" style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>Fornecedor</div>
              <select className="input" value={novo.fornecedor_id || ""} onChange={(e) => setNovo({ ...novo, fornecedor_id: e.target.value || undefined })} style={{ width: "100%" }}>
                <option value="">— (opcional) —</option>
                {sups.map((s) => <option key={s.id} value={s.id}>{s.nome}</option>)}
              </select>
            </label>
          </div>
          <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", marginTop: 2 }}>
            <input type="checkbox" checked={!!novo.recorrencia} onChange={(e) => setNovo({ ...novo, recorrencia: e.target.checked })} style={{ accentColor: "var(--primary)", width: 16, height: 16 }} />
            <span style={{ fontSize: 12.5 }}>Repetir todo mês (aluguel, internet…) — gera a conta do mês automaticamente</span>
          </label>
          {nLojas > 1 && (
            <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", marginTop: 8 }}>
              <input type="checkbox" checked={!!novo.negocio} onChange={(e) => setNovo({ ...novo, negocio: e.target.checked })} style={{ accentColor: "var(--primary)", width: 16, height: 16 }} />
              <span style={{ fontSize: 12.5 }}>Despesa do negócio (vale pra todas as lojas) — entra uma vez em "Todas as lojas", não em cada loja</span>
            </label>
          )}
        </FinModal>
      )}

      {/* Registrar pagamento */}
      {pagar && (
        <FinModal title="Registrar pagamento" onClose={() => setPagar(null)}
          footer={<><Btn variant="ghost" onClick={() => setPagar(null)}>Cancelar</Btn><Btn variant="primary" onClick={registrarPagamento}><I name="check" size={13} /> Registrar</Btn></>}>
          <div style={{ background: "var(--bg-elev)", borderRadius: 10, padding: 12, marginBottom: 14 }}>
            <div style={{ fontWeight: 600, fontSize: 13 }}>{pagar.lanc.descricao || CAT_LABEL[pagar.lanc.categoria]}</div>
            <div className="text-muted" style={{ fontSize: 12.5, marginTop: 2 }}>Valor {brl(pagar.lanc.valor_total)} · pago {brl(pagar.lanc.valor_pago)} · <b>falta {brl(faltaSel)}</b></div>
          </div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 10 }}>
            <div style={{ flex: 1 }}><Inp label="Valor a pagar (R$)" value={pagar.valor} onChange={(v) => setPagar({ ...pagar, valor: v })} placeholder="0,00" /></div>
            <Btn variant="ghost" onClick={() => setPagar({ ...pagar, valor: String(faltaSel).replace(".", ",") })} style={{ marginBottom: 12 }}>Pagar tudo</Btn>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Inp label="Data" type="date" value={pagar.data} onChange={(v) => setPagar({ ...pagar, data: v })} />
            <label style={{ display: "block", marginBottom: 12 }}>
              <div className="text-muted" style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>Método</div>
              <select className="input" value={pagar.metodo || ""} onChange={(e) => setPagar({ ...pagar, metodo: e.target.value || undefined })} style={{ width: "100%" }}>
                {METODOS.map(([k, l]) => <option key={k} value={k}>{l}</option>)}
              </select>
            </label>
          </div>
          {vPagar > faltaSel + 0.009 && (
            <div style={{ fontSize: 12, color: "#FB923C", marginTop: 2 }}>⚠ Esse valor passa do que falta ({brl(vPagar - faltaSel)} a mais). Pode ser juros/acréscimo? A conta será quitada e o excedente fica anotado.</div>
          )}
        </FinModal>
      )}

      {/* Histórico de pagamentos */}
      {hist && (
        <FinModal title="Pagamentos desta conta" onClose={() => setHist(null)}
          footer={<Btn variant="ghost" onClick={() => setHist(null)}>Fechar</Btn>}>
          {hist.movimentos.length === 0 ? <div className="text-muted" style={{ fontSize: 13 }}>Nenhum pagamento ainda.</div> : (
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {hist.movimentos.map((m) => (
                <div key={m.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: "var(--bg-elev)", borderRadius: 9, padding: "9px 12px" }}>
                  <div>
                    <div className="mono-numeric" style={{ fontWeight: 700 }}>{brl(m.valor)}</div>
                    <div className="text-faint" style={{ fontSize: 11 }}>{fmtData(m.data)}{m.metodo ? " · " + m.metodo : ""}{m.observacao ? " · " + m.observacao : ""}</div>
                  </div>
                  <button onClick={() => excluirMovimento(m)} title="Excluir pagamento" style={{ background: "transparent", border: 0, color: "#FF6A6A", cursor: "pointer" }}><I name="trash-2" size={13} /></button>
                </div>
              ))}
            </div>
          )}
        </FinModal>
      )}
    </FinPage>
  );
}

/* ====================== RESULTADO (Financeiro Fase 2 — lucro real + Caixa × Resultado) ====================== */
function LinhaConta({ rotulo, valor, sinal, forte, cor }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "7px 0", borderTop: forte ? "1px solid var(--border)" : "none", marginTop: forte ? 4 : 0 }}>
      <span style={{ fontSize: forte ? 14 : 13, fontWeight: forte ? 700 : 500, color: "var(--fg-1)" }}>{sinal ? <span className="text-faint" style={{ marginRight: 6 }}>{sinal}</span> : null}{rotulo}</span>
      <span className="font-display mono-numeric" style={{ fontSize: forte ? 20 : 14, fontWeight: forte ? 800 : 600, color: cor || "var(--fg-1)" }}>{brl(valor)}</span>
    </div>
  );
}
function RealResultado() {
  const [r, setR] = useState(null);
  useEffect(() => { window.VendusCopilot.getResultado().then(setR); }, []);
  if (!r) return <FinPage eyebrow="Financeiro" title="Resultado"><FinLoading /></FinPage>;
  const mes = FIN_MES_LONGO[parseInt((r.competencia || "").split("-")[1], 10) - 1] || "este mês";
  const lucro = r.resultado || 0;
  const lucroCor = lucro > 0 ? "#4ADE80" : lucro < 0 ? "#FF6A6A" : "var(--fg-1)";
  const semVenda = (r.receita_liquida || 0) === 0;

  return (
    <FinPage eyebrow="Financeiro" title="Resultado" sub={`O lucro real de ${mes} — receita líquida menos o custo do que vendeu e suas despesas.`}>
      {semVenda ? (
        <EmptyState icon="bar-chart-3" title={`Sem vendas em ${mes} ainda`} desc="Quando houver vendas no mês, o lucro real (depois do custo da mercadoria e das despesas) aparece aqui." />
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 16 }}>
          {/* Resultado do mês — a conta aberta */}
          <Card>
            <SectionTitle title="Resultado do mês" sub="Lucro real (regime de competência)" />
            <div style={{ marginTop: 8 }}>
              <LinhaConta rotulo="Receita líquida" valor={r.receita_liquida} />
              <LinhaConta rotulo="Custo da mercadoria (CMV)" valor={-(r.cmv.valor || 0)} sinal="−" cor="#FCA5A5" />
              <LinhaConta rotulo="Despesas operacionais" valor={-(r.despesas_operacionais.total || 0)} sinal="−" cor="#FCA5A5" />
              <LinhaConta rotulo="Lucro real" valor={lucro} forte cor={lucroCor} />
            </div>
            {r.cmv.incompleto && (
              <div className="banner" style={{ marginTop: 14 }}>
                <I name="alert-triangle" size={16} className="text-orange" />
                <div className="text-muted" style={{ fontSize: 12.5, lineHeight: 1.5 }}>
                  <b>CMV parcial.</b> Falta o custo de {r.cmv.itens_sem_custo} {r.cmv.itens_sem_custo === 1 ? "item que vendeu" : "itens que venderam"} ({r.cmv.pct_vendas_sem_custo}% das vendas). Cadastre os custos em <b>Produtos</b> pra o lucro ficar completo.
                </div>
              </div>
            )}
            {r.despesas_operacionais.sem_despesas && (
              <div className="text-faint" style={{ fontSize: 11.5, marginTop: 10 }}>Você ainda não lançou despesas neste mês. Lance aluguel, embalagem etc. em <b>Contas a pagar</b> pra o lucro ficar completo.</div>
            )}
            {r.cmv.estimado && <div className="text-faint" style={{ fontSize: 11, marginTop: 6 }}>Alguns custos de pedidos antigos são estimados (pelo valor atual do produto).</div>}
          </Card>

          {/* Caixa × Resultado — o explicador da divergência */}
          <Card>
            <SectionTitle title="Caixa × Resultado" sub="Por que o que sobrou no banco é diferente do lucro" />
            <div className="text-muted" style={{ fontSize: 13, lineHeight: 1.6, marginTop: 10 }}>
              Seu <b>lucro</b> em {mes} foi <b style={{ color: lucroCor }}>{brl(lucro)}</b> — é quanto a operação rendeu, contando o custo do que você <i>vendeu</i>.
              {r.caixa.compras_estoque > 0 ? (
                <> Mas no <b>caixa</b> você ainda pagou <b>{brl(r.caixa.compras_estoque)}</b> em <b>estoque</b> este mês: esse dinheiro sai agora, mas só vira custo (e mexe no lucro) <b>conforme você vende</b>. Por isso o caixa aperta antes do lucro aparecer.</>
              ) : (
                <> Quando você comprar estoque, o dinheiro sai do caixa na hora, mas só vira custo no lucro conforme vende — é normal os dois números divergirem.</>
              )}
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 14 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}><span className="text-muted">Pago este mês (saídas, inclui estoque)</span><span className="mono-numeric font-display" style={{ fontWeight: 700 }}>{brl(r.caixa.saidas_efetivadas)}</span></div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}><span className="text-muted">Compras de estoque do mês</span><span className="mono-numeric font-display" style={{ fontWeight: 700 }}>{brl(r.caixa.compras_estoque)}</span></div>
            </div>
            <div className="text-faint" style={{ fontSize: 11, marginTop: 12, lineHeight: 1.5 }}>Os repasses a receber dos marketplaces (Mercado Livre, Shopee…) entram numa próxima atualização — aí o caixa fica completo.</div>
          </Card>
        </div>
      )}
    </FinPage>
  );
}

/* ====================== CONTAS A RECEBER (Financeiro Fase 3 — repasses + Antecipe) ====================== */
const MK_NOME = { mercado_livre: "Mercado Livre", shopee: "Shopee", tiktok: "TikTok Shop" };
function RealContasReceber() {
  const [data, setData] = useState(null);
  const [receber, setReceber] = useState(null); // modal { marketplace, valor, data, antecipado, taxa, metodo }
  function load() { window.VendusCopilot.getRecebiveis().then(setData); }
  useEffect(() => { load(); }, []);
  function toast(msg, tone, icon) { window.vendusToast && window.vendusToast(msg, { icon: icon || "check-check", tone: tone || "success" }); }

  async function registrar() {
    const v = Number(String(receber.valor).replace(",", ".")) || 0;
    if (v <= 0) { toast("Informe o valor recebido.", "warning", "alert-triangle"); return; }
    if (receber.antecipado && !(Number(String(receber.taxa).replace(",", ".")) > 0)) { toast("Informe a taxa da antecipação.", "warning", "alert-triangle"); return; }
    const r = await window.VendusCopilot.receberLote({ marketplace: receber.marketplace, valor: receber.valor, data: receber.data, antecipado: !!receber.antecipado, taxa_antecipacao: receber.taxa, metodo: receber.metodo || undefined, observacao: receber.observacao || undefined });
    if (r.ok) {
      setReceber(null); load();
      const extra = r.excedente > 0 ? ` (R$ ${r.excedente.toFixed(2).replace(".", ",")} a mais do que tinha pra conciliar — fica como crédito)` : "";
      toast(receber.antecipado ? `Recebido ✓ líquido ${brl(r.liquido)} (taxa ${brl(r.taxa)})${extra}` : `Recebimento de ${r.n_pedidos} pedido(s) conciliado ✓${extra}`);
    } else toast(r.error || "Não consegui registrar.", "danger", "alert-triangle");
  }

  if (!data) return <FinPage eyebrow="Financeiro" title="Contas a receber"><FinLoading /></FinPage>;
  const linhas = data.por_marketplace || [];
  const hist = data.historico || [];

  return (
    <FinPage eyebrow="Financeiro" title="Contas a receber" sub="O que os marketplaces têm pra te repassar. Quando o dinheiro cair, registre o recebimento (em lote) — e use o Antecipe se antecipou.">
      <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 12, marginBottom: 16 }}>
        <Card padding={14}><div className="text-faint" style={{ fontSize: 11 }}>A receber (em aberto)</div><div className="font-display mono-numeric" style={{ fontSize: 22, fontWeight: 800, color: "#4ADE80", marginTop: 2 }}>{brl(data.total)}</div></Card>
        <Card padding={14}><div className="text-faint" style={{ fontSize: 11 }}>Previsto pra próxima semana</div><div className="font-display mono-numeric" style={{ fontSize: 22, fontWeight: 800, marginTop: 2 }}>{brl(data.proxima_semana)}</div></Card>
      </div>

      {linhas.length === 0 ? (
        <EmptyState icon="hand-coins" title="Nada a receber no momento" desc="Conforme suas vendas forem sincronizadas, o valor que cada marketplace tem pra te repassar aparece aqui." />
      ) : (
        <Card padding={0} style={{ marginBottom: 16 }}>
          <table className="tbl">
            <thead><tr><th>Marketplace</th><th className="num">Pedidos</th><th>Previsão</th><th className="num">A receber</th><th></th></tr></thead>
            <tbody>
              {linhas.map((l) => (
                <tr key={l.marketplace}>
                  <td style={{ fontWeight: 500 }}>{MK_NOME[l.marketplace] || l.marketplace}</td>
                  <td className="num mono-numeric">{l.n_pedidos}</td>
                  <td className="text-muted" style={{ fontSize: 12.5 }}>{l.previsao ? <>{fmtData(l.previsao)} {l.previsao_estimada && <span className="text-faint">(estimada)</span>}</> : "a definir"}</td>
                  <td className="num mono-numeric font-display" style={{ fontWeight: 700, color: "#4ADE80" }}>{brl(l.a_receber)}</td>
                  <td className="num"><Btn size="sm" variant="primary" onClick={() => setReceber({ marketplace: l.marketplace, valor: String(l.a_receber).replace(".", ","), data: hojeStr(), antecipado: false })}><I name="hand-coins" size={13} /> Registrar recebimento</Btn></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {hist.length > 0 && (
        <Card padding={0}>
          <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--border)", fontWeight: 700, fontSize: 13 }}>Recebimentos registrados</div>
          <table className="tbl">
            <thead><tr><th>Marketplace</th><th>Data</th><th className="num">Recebido</th><th className="num">Líquido</th><th></th></tr></thead>
            <tbody>
              {hist.map((h) => (
                <tr key={h.id}>
                  <td>{MK_NOME[h.marketplace] || h.marketplace}</td>
                  <td className="text-muted" style={{ fontSize: 12.5 }}>{fmtData(h.data)}</td>
                  <td className="num mono-numeric">{brl(h.valor)}</td>
                  <td className="num mono-numeric font-display" style={{ fontWeight: 700 }}>{brl(h.liquido)}</td>
                  <td>{h.antecipado ? <Chip tone="violet">antecipado · taxa {brl(h.taxa)}</Chip> : <span className="text-faint" style={{ fontSize: 11.5 }}>prazo normal</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {receber && (
        <FinModal title="Registrar recebimento" onClose={() => setReceber(null)}
          footer={<><Btn variant="ghost" onClick={() => setReceber(null)}>Cancelar</Btn><Btn variant="primary" onClick={registrar}><I name="check" size={13} /> Registrar</Btn></>}>
          <div className="text-muted" style={{ fontSize: 12.5, marginBottom: 12, lineHeight: 1.5 }}>Quanto caiu de <b>{MK_NOME[receber.marketplace] || receber.marketplace}</b>? Vou conciliar com os pedidos pendentes (dos mais antigos pros mais novos).</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Inp label="Valor recebido (R$)" value={receber.valor} onChange={(v) => setReceber({ ...receber, valor: v })} placeholder="0,00" />
            <Inp label="Data" type="date" value={receber.data} onChange={(v) => setReceber({ ...receber, data: v })} />
          </div>
          <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", margin: "4px 0 10px" }}>
            <input type="checkbox" checked={!!receber.antecipado} onChange={(e) => setReceber({ ...receber, antecipado: e.target.checked })} style={{ accentColor: "var(--primary)", width: 16, height: 16 }} />
            <span style={{ fontSize: 12.5 }}>Foi antecipado (Shopee Antecipe e afins) — recebe antes, paga uma taxa</span>
          </label>
          {receber.antecipado && (
            <>
              <Inp label="Taxa da antecipação (R$)" value={receber.taxa} onChange={(v) => setReceber({ ...receber, taxa: v })} placeholder="o quanto o marketplace cobrou" />
              <div className="text-faint" style={{ fontSize: 11.5, marginTop: -6, marginBottom: 8 }}>Informe o valor que o marketplace cobrou — varia e muda, então não chuto. Entra como custo no caixa e no resultado.</div>
            </>
          )}
        </FinModal>
      )}
    </FinPage>
  );
}

window.VendusFinanceiro = { RealComparatives, RealCashflow, RealCosts, RealForecasts, RealReports, RealSuppliers, RealPurchases, RealContasPagar, RealResultado, RealContasReceber };
