/* Movimentações Financeiras */

function Movimentacoes({ ctx }) {
  const [filter, setFilter] = useState("all");
  const [period, setPeriod] = useState({ kind: "month" });
  const [editing, setEditing] = useState(null);
  const fileRef = useRef(null);

  const refDate = DEFAULT_REF_DATE;
  const all = ctx.state.finance;
  const inPeriodFn = (f) => inPeriod(f.date, period, refDate);
  const periodFinance = all.filter(inPeriodFn);

  const ins  = periodFinance.filter(f => f.kind === "in").reduce((s, f) => s + f.value, 0);
  const outs = periodFinance.filter(f => f.kind === "out").reduce((s, f) => s + f.value, 0);
  const saldo = ins - outs;
  // pendências agora vêm de sales / inputPurchases (não de finance)
  const aReceber = ctx.state.sales.reduce((s, x) => s + Math.max(0, x.total - x.paid), 0);
  const pendingSalesCount = ctx.state.sales.filter(s => s.paid < s.total).length;

  const filtered = periodFinance.filter(f => {
    if (filter === "all") return true;
    if (filter === "in") return f.kind === "in";
    if (filter === "out") return f.kind === "out";
    if (filter === "pending") return f.status === "a_receber";
    return true;
  }).sort((a, b) => b.date.localeCompare(a.date));

  // Chart data — últimos 14 dias do período (ou de DEFAULT_REF_DATE se período "all")
  const days = [];
  const r = periodRange(period, refDate);
  const baseEnd = r.end || refDate;
  for (let i = 13; i >= 0; i--) {
    const d = new Date(baseEnd); d.setDate(baseEnd.getDate() - i);
    const key = d.toISOString().slice(0, 10);
    const dayIn  = all.filter(f => f.date === key && f.kind === "in").reduce((s, f) => s + f.value, 0);
    const dayOut = all.filter(f => f.date === key && f.kind === "out").reduce((s, f) => s + f.value, 0);
    days.push({ label: d.toLocaleDateString("pt-BR", { day:"2-digit" }), inV: dayIn, outV: dayOut });
  }

  const onDelete = (f) => ctx.askConfirm({
    title: "Excluir lançamento?",
    message: `Excluir ${f.cat} · ${fmtBRL(f.value)}?`,
    detail: "Esta ação NÃO restaura estoque ou comissões previamente movidas.",
    danger: true,
    onConfirm: () => ctx.actions.deleteFinance(f.id),
  });

  const markPaid = (f) => {
    ctx.actions.updateFinance(f.id, { status: "confirmado" });
  };

  const doImport = async () => {
    const file = await pickFile(".json,.csv");
    if (!file) return;
    try {
      const text = await readFileAsText(file);
      let entries = [];
      if (file.name.endsWith(".json")) {
        const data = JSON.parse(text);
        if (Array.isArray(data)) entries = data;
        else if (Array.isArray(data.finance)) entries = data.finance;
      } else {
        // CSV: Data;Tipo;Categoria;Descrição;Status;Valor
        const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/).filter(Boolean);
        const sep = lines[0].includes(";") ? ";" : ",";
        const parseLine = (l) => {
          // simples — lida com aspas
          const out = []; let cur = "", q = false;
          for (const c of l) {
            if (c === '"') { q = !q; continue; }
            if (c === sep && !q) { out.push(cur); cur = ""; continue; }
            cur += c;
          }
          out.push(cur); return out;
        };
        for (let i = 1; i < lines.length; i++) {
          const cols = parseLine(lines[i]);
          if (cols.length < 6) continue;
          const [date, tipo, cat, ref, status, valor] = cols;
          const v = parseFloat((valor||"").replace(/[^\d.,-]/g,"").replace(",","."));
          if (!v || isNaN(v) || !date) continue;
          entries.push({
            date: date.slice(0,10),
            kind: /saída|saida|out/i.test(tipo) ? "out" : "in",
            cat: cat || "Outras Entradas",
            ref: ref || "—",
            value: Math.abs(v),
            status: /receb|pend|a.recebe/i.test(status) ? "a_receber" : "confirmado",
          });
        }
      }
      if (entries.length === 0) { ctx.pushToast("Nenhum lançamento válido encontrado"); return; }
      entries.forEach(en => ctx.actions.addFinance(en));
      ctx.pushToast(`${entries.length} lançamento(s) importado(s)`);
    } catch (err) {
      console.error(err);
      alert("Falha ao importar: " + err.message);
    }
  };

  const printList = () => {
    const r = periodRange(period, refDate);
    const logo = ctx.state.company.logo;
    const logoIsImage = logo && !/^data:application\/pdf/i.test(logo);
    const logoBlock = logoIsImage
      ? `<img src="${logo}" style="width:60px;height:60px;object-fit:contain;display:block;" />`
      : `<div style="width:60px;height:60px;background:#D4310B;color:white;border-radius:6px;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:30px;font-family:Helvetica,Arial,sans-serif;letter-spacing:-.04em;">P</div>`;
    const head = `
      <div style="display:flex;gap:18px;align-items:center;padding-bottom:14px;margin-bottom:20px;border-bottom:1.5px solid #222;">
        ${logoBlock}
        <div style="flex:1">
          <div style="font-weight:800;font-size:15px;letter-spacing:.04em;text-transform:uppercase;color:#111;line-height:1.2;">${ctx.state.company.name||""}</div>
          <div style="font-size:9.5px;line-height:1.55;color:#555;margin-top:5px;">
            ${ctx.state.company.cnpj ? "CNPJ "+ctx.state.company.cnpj : ""}
            ${(ctx.state.company.cnpj && ctx.state.company.address) ? "<br/>" : ""}
            ${ctx.state.company.address||""}
          </div>
        </div>
      </div>
      <h1 style="font-family:Helvetica,Arial,sans-serif;font-size:14px;text-transform:uppercase;letter-spacing:.1em;font-weight:700;margin:0 0 4px;color:#111;">Movimentações Financeiras</h1>
      <div style="font-size:10px;color:#666;font-family:'Courier New',monospace;letter-spacing:.04em;margin-bottom:14px;padding-bottom:10px;border-bottom:1px solid #ddd;display:flex;justify-content:space-between;gap:14px;">
        <span>Período: ${r.label}</span>
        <span>${filtered.length} lançamento(s) · Emitido em ${new Date().toLocaleString("pt-BR")}</span>
      </div>
      <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px;">
        ${[
          ["Entradas", fmtBRL(ins), "#15803D"],
          ["Saídas", fmtBRL(outs), "#B91C1C"],
          ["Saldo", fmtBRL(saldo), saldo>=0?"#111":"#B91C1C"],
          ["A receber", fmtBRL(aReceber), "#1E40AF"],
        ].map(([l,v,c]) => `<div style="border:1px solid #ddd;padding:10px 12px;"><div style="font-size:8.5px;color:#888;text-transform:uppercase;letter-spacing:.1em;font-weight:700;margin-bottom:3px;">${l}</div><div style="font-size:16px;font-weight:700;color:${c};letter-spacing:-.01em;">${v}</div></div>`).join("")}
      </div>
    `;
    const rows = filtered.map(f => `
      <tr>
        <td>${fmtDate(f.date)}</td>
        <td>${f.cat}</td>
        <td>${f.ref}</td>
        <td>${f.status === "confirmado" ? "Confirmado" : "A receber"}</td>
        <td class="num" style="color:${f.kind==="in"?"#15803D":"#B91C1C"};font-weight:700;">${f.kind==="in"?"+":"−"} ${fmtBRL(f.value)}</td>
      </tr>
    `).join("");
    const body = `<div style="padding:6px;">
      ${head}
      <table style="width:100%;border-collapse:collapse;font-size:10.5px;">
        <thead><tr>
          <th style="text-align:left;padding:7px 6px;font-size:9px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:.08em;border-bottom:1.5px solid #333;">Data</th>
          <th style="text-align:left;padding:7px 6px;font-size:9px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:.08em;border-bottom:1.5px solid #333;">Categoria</th>
          <th style="text-align:left;padding:7px 6px;font-size:9px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:.08em;border-bottom:1.5px solid #333;">Descrição</th>
          <th style="text-align:left;padding:7px 6px;font-size:9px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:.08em;border-bottom:1.5px solid #333;">Status</th>
          <th style="text-align:right;padding:7px 6px;font-size:9px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:.08em;border-bottom:1.5px solid #333;">Valor</th>
        </tr></thead>
        <tbody>${rows}</tbody>
      </table>
      <div style="margin-top:30px;padding-top:10px;border-top:1px solid #ddd;font-size:9px;color:#888;text-align:center;line-height:1.6;">
        Documento de controle interno · sem valor fiscal<br/>
        <span style="color:#222;font-weight:700;font-family:'Courier New',monospace;letter-spacing:.05em;">MOV-${new Date().getTime().toString(36).toUpperCase().slice(-6)}</span> · ${ctx.state.company.name||""} · ${new Date().toLocaleString("pt-BR")}
      </div>
    </div>`;
    const css = `
      @page { size: A4; margin: 12mm 10mm; }
      * { box-sizing: border-box; }
      html, body { margin:0; padding:0; }
      body { font-family: Helvetica, Arial, sans-serif; color:#222; font-size:11px; line-height:1.5; background:#f0f0f0; }
      .brand-bar { height:3px; background:#D4310B; }
      table { table-layout: auto; word-wrap: break-word; }
      table td { padding:6px; border-bottom:1px solid #eee; font-size:10.5px; color:#222; }
      tbody tr:last-child td { border-bottom:none; }
      .num { text-align:right; font-variant-numeric:tabular-nums; }
      .toolbar { position:sticky; top:0; background:#1A1A1A; color:white; padding:10px 14px; display:flex; gap:8px; align-items:center; z-index:50; }
      .toolbar h3 { margin:0; flex:1; font-size:13px; font-weight:600; }
      .toolbar button { background:white; color:#1A1A1A; border:none; padding:7px 12px; border-radius:6px; font-weight:600; font-size:12px; cursor:pointer; font-family:Helvetica,Arial,sans-serif; }
      .doc { background:white; max-width:760px; margin:14px auto; padding:22px 24px; box-shadow:0 4px 24px rgba(0,0,0,.12); }
      @media print { .toolbar { display:none !important; } body { background:white !important; padding:0 !important; } .doc { box-shadow:none !important; margin:0 !important; max-width:none !important; width:auto !important; padding:0 !important; } }
    `;
    const win = window.open("", "_blank", "width=1000,height=900");
    win.document.open();
    win.document.write(`<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><title>Movimentações — ${r.label}</title><style>${css}</style></head><body>
      <div class="toolbar"><h3>Movimentações — ${r.label}</h3><button onclick="window.print()">Imprimir / PDF</button><button onclick="window.close()" style="background:transparent;color:white;border:1px solid rgba(255,255,255,.4);">Fechar</button></div>
      <div class="doc"><div class="brand-bar" style="margin-bottom:14px;"></div>${body}</div></body></html>`);
    win.document.close();
  };

  return (
    <>
      <div className="page-head">
        <div>
          <h1>Movimentações Financeiras</h1>
          <p>Entradas, saídas, saldo e previsões</p>
        </div>
        <div className="page-head__actions">
          <PeriodPicker value={period} onChange={setPeriod} refDate={refDate} />
          <Button variant="secondary" icon={<Icons.Download size={14}/>} onClick={() => exportFinanceCsv(all, period)}>Exportar CSV</Button>
          <Button variant="secondary" icon={<Icons.Download size={14} style={{ transform:"rotate(180deg)" }}/>} onClick={doImport}>Importar</Button>
          <Button variant="secondary" icon={<Icons.Print size={14}/>} onClick={printList}>Imprimir / PDF</Button>
          <Button variant="primary" icon={<Icons.Plus size={14} strokeWidth={2.2}/>} onClick={() => setEditing("new")}>Lançar manual</Button>
        </div>
      </div>

      <div className="grid-4" style={{ marginBottom: 14 }}>
        <KPI tone="success" medal={<Icons.ArrowDown size={18} strokeWidth={2}/>} label="Entradas" value={fmtBRL(ins)} />
        <KPI tone="danger" medal={<Icons.ArrowUp size={18} strokeWidth={2}/>} label="Saídas" value={fmtBRL(outs)} />
        <KPI tone={saldo>=0 ? "brand" : "warning"} medal={<Icons.Wallet size={18} strokeWidth={2}/>} label="Saldo" value={fmtBRL(saldo)} sub="Soma do período" />
        <KPI tone="info" medal={<Icons.Calendar size={18} strokeWidth={2}/>} label="A receber" value={fmtBRL(aReceber)} sub={`${pendingSalesCount} venda(s) a prazo`} />
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"2fr 1fr", gap:14, marginBottom: 14 }}>
        <Card title="Fluxo de caixa — últimos 14 dias do período" subtitle="Entradas vs. saídas por dia">
          <DualBarChart data={days} />
          <div className="row" style={{ gap:18, marginTop:14, justifyContent:"center" }}>
            <LegendDot color="#15803D" label="Entradas" />
            <LegendDot color="#B91C1C" label="Saídas" />
          </div>
        </Card>

        <Card title="Distribuição" subtitle={periodRange(period, refDate).label}>
          <CategoryDistribution finance={periodFinance} />
        </Card>
      </div>

      <Card title="Lançamentos" subtitle={`${filtered.length} movimentações em ${periodRange(period, refDate).label}`} flush
        action={
          <Segmented options={[
            { value:"all", label:"Todos" },
            { value:"in", label:"Entradas" },
            { value:"out", label:"Saídas" },
            { value:"pending", label:"A receber" },
          ]} value={filter} onChange={setFilter} />
        }
      >
        {filtered.length === 0 ? (
          <div className="empty">
            <Icons.Wallet size={26} color="var(--ink-300)"/>
            <h4>Nenhum lançamento</h4>
            <p>Use "Lançar manual" ou registre operações nos PDVs.</p>
          </div>
        ) : (
        <table className="tbl">
          <thead>
            <tr>
              <th>Data</th>
              <th>Categoria</th>
              <th>Descrição / Referência</th>
              <th>Status</th>
              <th className="num">Valor</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(f => (
              <tr key={f.id}>
                <td>{fmtDate(f.date)}</td>
                <td>
                  <Chip tone={f.kind === "in" ? "success" : "danger"} dot>{f.cat}</Chip>
                </td>
                <td className="strong">{f.ref}</td>
                <td>
                  {f.status === "confirmado" ? <span className="muted" style={{ fontSize:12 }}>Confirmado</span> : <Chip tone="warning" dot>A receber</Chip>}
                </td>
                <td className={"num strong numeric"} style={{ color: f.kind === "in" ? "var(--success)" : "var(--danger)" }}>
                  {f.kind === "in" ? "+" : "−"} {fmtBRL(f.value)}
                </td>
                <td>
                  <div style={{ display:"flex", gap:2 }}>
                    {f.status === "a_receber" && <button className="icon-btn" title="Marcar como recebido" onClick={() => markPaid(f)}><Icons.Check /></button>}
                    <button className="icon-btn" title="Editar" onClick={() => setEditing(f)}><Icons.Edit /></button>
                    <button className="icon-btn" title="Excluir" onClick={() => onDelete(f)}><Icons.Trash /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        )}
      </Card>

      {editing && <FinanceModal
        ctx={ctx}
        initial={editing === "new" ? null : editing}
        onClose={() => setEditing(null)}
        onSave={(v, opts) => {
          if (editing === "new") ctx.actions.addFinance(v);
          else ctx.actions.updateFinance(editing.id, v);
          if (opts?.printReceipt) printFinanceReceipt(v, ctx.state.company);
          setEditing(null);
        }}
      />}
    </>
  );
}

function FinanceModal({ ctx, initial, onClose, onSave }) {
  const methods = (ctx?.state?.settings?.methods) || ["PIX","Dinheiro","Cartão","Boleto 14d","Prazo 30d"];
  const [kind, setKind] = useState(initial?.kind || "in");
  const [cat, setCat] = useState(initial?.cat || "Despesa Operacional");
  const [ref, setRef] = useState(initial?.ref || "");
  const [date, setDate] = useState(initial?.date || new Date().toISOString().slice(0,10));
  const [value, setValue] = useState(initial?.value ? String(initial.value) : "");
  const [status, setStatus] = useState(initial?.status || "confirmado");
  const [method, setMethod] = useState(initial?.method || methods[0] || "PIX");
  const [err, setErr] = useState({});

  const build = () => {
    const e = {};
    if (!ref.trim()) e.ref = "Informe a descrição";
    const v = parseFloat((value+"").replace(",", "."));
    if (!v || v <= 0) e.value = "Valor inválido";
    setErr(e);
    if (Object.keys(e).length) return null;
    return { kind, cat, ref: ref.trim(), date, value: v, status, method };
  };
  const submit = () => { const payload = build(); if (payload) onSave(payload); };
  const submitAndPrint = () => { const payload = build(); if (payload) onSave(payload, { printReceipt: true }); };

  const categoriesIn  = ["Venda Distribuidor","Retorno Picolezeiro","Outras Entradas"];
  const categoriesOut = ["Compra de Insumo","Comissão Picolezeiro","Produção","Despesa Operacional","Outras Saídas"];
  const cats = kind === "in" ? categoriesIn : categoriesOut;
  // ensure category is valid for kind
  useEffect(() => { if (!cats.includes(cat)) setCat(cats[0]); }, [kind]);

  return (
    <Modal title={initial ? "Editar lançamento" : "Novo lançamento"} subtitle="Entrada ou saída manual" onClose={onClose}
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button variant="secondary" icon={<Icons.Print size={14}/>} onClick={submitAndPrint}>
            {initial ? "Salvar e gerar comprovante" : "Lançar e gerar comprovante"}
          </Button>
          <Button variant="primary" onClick={submit}>{initial ? "Salvar" : "Lançar"}</Button>
        </>
      }
    >
      <Segmented options={[{value:"in", label:"Entrada (+)"},{value:"out", label:"Saída (−)"}]} value={kind} onChange={setKind} />
      <div style={{ height:14 }} />
      <div className="grid-2" style={{ gap:14 }}>
        <Field label="Categoria" required>
          <select className="select" value={cat} onChange={e => setCat(e.target.value)}>
            {cats.map(c => <option key={c}>{c}</option>)}
          </select>
        </Field>
        <Field label="Data" required>
          <input className="input" value={date} onChange={e => setDate(e.target.value)} placeholder="AAAA-MM-DD" />
        </Field>
        <Field label="Descrição / Referência" required error={err.ref} style={{ gridColumn:"span 2" }}>
          <input className="input" value={ref} onChange={e => setRef(e.target.value)} placeholder="Ex.: Conta de luz, Compra de polpa..." autoFocus />
        </Field>
        <Field label="Valor (R$)" required error={err.value}>
          <input className="input numeric" value={value} onChange={e => setValue(e.target.value.replace(/[^\d.,]/g,""))} placeholder="0,00" />
        </Field>
        <Field label="Forma de pagamento" required hint="Usada no comprovante e no histórico">
          <select className="select" value={method} onChange={e => setMethod(e.target.value)}>
            {methods.map(m => <option key={m}>{m}</option>)}
          </select>
        </Field>
        <Field label="Status" required style={{ gridColumn:"span 2" }}>
          <select className="select" value={status} onChange={e => setStatus(e.target.value)}>
            <option value="confirmado">{kind === "in" ? "Recebido" : "Pago"}</option>
            <option value="a_receber">{kind === "in" ? "A receber" : "A pagar"}</option>
          </select>
        </Field>
      </div>
    </Modal>
  );
}

/* Gera um comprovante imprimível (HTML) para um lançamento manual.
   Mesmo estilo do printList — header com logo, dados da empresa, bloco do lançamento e rodapé. */
function printFinanceReceipt(entry, company) {
  const isIn = entry.kind === "in";
  const titulo = isIn ? "COMPROVANTE DE RECEBIMENTO" : "COMPROVANTE DE PAGAMENTO";
  const statusLabel = entry.status === "confirmado"
    ? (isIn ? "Recebido" : "Pago")
    : (isIn ? "A receber" : "A pagar");
  const logoIsImage = company?.logo && !/^data:application\/pdf/i.test(company.logo);
  const logoBlock = logoIsImage
    ? `<img src="${company.logo}" style="width:64px;height:64px;object-fit:contain;display:block;border-radius:8px;background:white;" />`
    : `<div style="width:64px;height:64px;background:#D4310B;color:white;border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:32px;font-family:Helvetica,Arial,sans-serif;letter-spacing:-.04em;">P</div>`;
  const docId = "MOV-" + (entry.id || Date.now().toString(36)).toString().toUpperCase().slice(-8);
  const emittedAt = new Date().toLocaleString("pt-BR");
  const valueColor = isIn ? "#15803D" : "#B91C1C";
  const accentColor = isIn ? "#15803D" : "#B91C1C";

  const body = `
    <div style="padding:6px;">
      <div style="display:flex;gap:18px;align-items:center;padding-bottom:14px;margin-bottom:22px;border-bottom:1.5px solid #222;">
        ${logoBlock}
        <div style="flex:1">
          <div style="font-weight:800;font-size:15px;letter-spacing:.04em;text-transform:uppercase;color:#111;line-height:1.2;">${company?.name||""}</div>
          <div style="font-size:9.5px;line-height:1.55;color:#555;margin-top:5px;">
            ${company?.cnpj ? "CNPJ "+company.cnpj : ""}
            ${(company?.cnpj && company?.address) ? "<br/>" : ""}
            ${company?.address||""}
            ${company?.phone ? "<br/>"+company.phone : ""}
          </div>
        </div>
        <div style="text-align:right;">
          <div style="font-size:9px;color:#888;text-transform:uppercase;letter-spacing:.1em;font-weight:700;">Documento</div>
          <div style="font-family:'Courier New',monospace;font-size:12px;font-weight:700;color:#111;letter-spacing:.06em;margin-top:3px;">${docId}</div>
        </div>
      </div>

      <h1 style="font-family:Helvetica,Arial,sans-serif;font-size:18px;text-transform:uppercase;letter-spacing:.12em;font-weight:700;margin:0 0 4px;color:${accentColor};">${titulo}</h1>
      <div style="font-size:10px;color:#666;font-family:'Courier New',monospace;letter-spacing:.04em;margin-bottom:24px;padding-bottom:12px;border-bottom:1px solid #ddd;">
        Emitido em ${emittedAt}
      </div>

      <table style="width:100%;border-collapse:collapse;font-size:11px;margin-bottom:24px;">
        <tbody>
          <tr><td style="padding:8px 0;color:#888;text-transform:uppercase;font-size:9.5px;letter-spacing:.08em;font-weight:700;width:160px;">Categoria</td><td style="padding:8px 0;color:#111;font-weight:600;">${entry.cat||"—"}</td></tr>
          <tr><td style="padding:8px 0;color:#888;text-transform:uppercase;font-size:9.5px;letter-spacing:.08em;font-weight:700;border-top:1px solid #eee;">Descrição</td><td style="padding:8px 0;color:#111;border-top:1px solid #eee;">${entry.ref||"—"}</td></tr>
          <tr><td style="padding:8px 0;color:#888;text-transform:uppercase;font-size:9.5px;letter-spacing:.08em;font-weight:700;border-top:1px solid #eee;">Data</td><td style="padding:8px 0;color:#111;border-top:1px solid #eee;">${fmtDate(entry.date)}</td></tr>
          <tr><td style="padding:8px 0;color:#888;text-transform:uppercase;font-size:9.5px;letter-spacing:.08em;font-weight:700;border-top:1px solid #eee;">Forma de pagamento</td><td style="padding:8px 0;color:#111;border-top:1px solid #eee;font-weight:600;">${entry.method||"—"}</td></tr>
          <tr><td style="padding:8px 0;color:#888;text-transform:uppercase;font-size:9.5px;letter-spacing:.08em;font-weight:700;border-top:1px solid #eee;">Status</td><td style="padding:8px 0;color:#111;border-top:1px solid #eee;">${statusLabel}</td></tr>
        </tbody>
      </table>

      <div style="padding:18px 22px;background:#FAFAFA;border:1px solid #ddd;border-left:4px solid ${accentColor};border-radius:4px;display:flex;justify-content:space-between;align-items:center;">
        <div>
          <div style="font-size:9.5px;color:#888;text-transform:uppercase;letter-spacing:.1em;font-weight:700;margin-bottom:4px;">${isIn ? "Valor recebido" : "Valor pago"}</div>
          <div style="font-size:11px;color:#666;">${entry.method||""}</div>
        </div>
        <div style="font-size:26px;font-weight:800;color:${valueColor};letter-spacing:-.02em;font-family:Helvetica,Arial,sans-serif;">
          ${isIn ? "+" : "−"} ${fmtBRL(entry.value)}
        </div>
      </div>

      <div style="margin-top:40px;display:grid;grid-template-columns:1fr 1fr;gap:40px;">
        <div style="text-align:center;">
          <div style="border-top:1px solid #333;padding-top:6px;font-size:9.5px;color:#666;letter-spacing:.06em;text-transform:uppercase;font-weight:600;">Emissor</div>
          <div style="font-size:11px;color:#111;margin-top:2px;">${company?.name||""}</div>
        </div>
        <div style="text-align:center;">
          <div style="border-top:1px solid #333;padding-top:6px;font-size:9.5px;color:#666;letter-spacing:.06em;text-transform:uppercase;font-weight:600;">${isIn ? "Pagador" : "Beneficiário"}</div>
          <div style="font-size:11px;color:#111;margin-top:2px;">${entry.ref||"—"}</div>
        </div>
      </div>

      <div style="margin-top:40px;padding-top:10px;border-top:1px solid #ddd;font-size:9px;color:#888;text-align:center;line-height:1.6;">
        Documento de controle interno · sem valor fiscal<br/>
        <span style="color:#222;font-weight:700;font-family:'Courier New',monospace;letter-spacing:.05em;">${docId}</span> · ${company?.name||""} · ${emittedAt}
      </div>
    </div>`;

  const css = `
    @page { size: A4; margin: 14mm 12mm; }
    * { box-sizing: border-box; }
    html, body { margin:0; padding:0; }
    body { font-family: Helvetica, Arial, sans-serif; color:#222; font-size:11px; line-height:1.5; background:#f0f0f0; }
    .brand-bar { height:3px; background:${accentColor}; }
    .toolbar { position:sticky; top:0; background:#1A1A1A; color:white; padding:10px 14px; display:flex; gap:8px; align-items:center; z-index:50; }
    .toolbar h3 { margin:0; flex:1; font-size:13px; font-weight:600; }
    .toolbar button { background:white; color:#1A1A1A; border:none; padding:7px 12px; border-radius:6px; font-weight:600; font-size:12px; cursor:pointer; font-family:Helvetica,Arial,sans-serif; }
    .doc { background:white; max-width:680px; margin:14px auto; padding:26px 30px; box-shadow:0 4px 24px rgba(0,0,0,.12); }
    @media print { .toolbar { display:none !important; } body { background:white !important; padding:0 !important; } .doc { box-shadow:none !important; margin:0 !important; max-width:none !important; width:auto !important; padding:0 !important; } }
  `;
  const win = window.open("", "_blank", "width=900,height=900");
  win.document.open();
  win.document.write(`<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><title>${titulo} — ${docId}</title><style>${css}</style></head><body>
    <div class="toolbar"><h3>${titulo} — ${docId}</h3><button onclick="window.print()">Imprimir / PDF</button><button onclick="window.close()" style="background:transparent;color:white;border:1px solid rgba(255,255,255,.4);">Fechar</button></div>
    <div class="doc"><div class="brand-bar" style="margin-bottom:14px;"></div>${body}</div></body></html>`);
  win.document.close();
}

function CategoryDistribution({ finance }) {
  // group outs by category
  const groups = {};
  finance.filter(f => f.kind === "out").forEach(f => {
    groups[f.cat] = (groups[f.cat] || 0) + f.value;
  });
  const total = Object.values(groups).reduce((s, x) => s + x, 0);
  const colors = ["#D4310B", "#1A1A1A", "#A3A3A6", "#6B6B70", "#E04A1F"];
  const entries = Object.entries(groups).sort((a,b)=>b[1]-a[1]);

  if (total === 0) return <div className="empty"><p>Sem saídas no período.</p></div>;

  const segments = entries.map(([cat, v], i) => ({ value: v, color: colors[i % colors.length], label: cat }));

  return (
    <div style={{ display:"flex", alignItems:"center", gap:14, padding:"4px 0 14px" }}>
      <Donut size={120} segments={segments} />
      <div style={{ display:"flex", flexDirection:"column", gap:10, flex:1, minWidth:0 }}>
        {segments.slice(0,5).map((s, i) => (
          <div key={i} style={{ display:"flex", alignItems:"center", gap:8, minWidth: 0 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: s.color, flexShrink: 0 }} />
            <span style={{ fontSize:11.5, color:"var(--ink-700)", flex:1, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{s.label}</span>
            <strong className="numeric" style={{ fontSize:11.5 }}>{Math.round(s.value / total * 100)}%</strong>
          </div>
        ))}
      </div>
    </div>
  );
}

function DualBarChart({ data }) {
  const max = Math.max(...data.flatMap(d => [d.inV, d.outV]), 1);
  return (
    <div style={{ display:"flex", alignItems:"flex-end", gap:6, height: 200, padding:"4px 0" }}>
      {data.map((d, i) => (
        <div key={i} style={{ flex:1, display:"flex", flexDirection:"column", alignItems:"center", gap:6, height:"100%" }}>
          <div style={{ flex:1, display:"flex", alignItems:"flex-end", gap:2, width:"100%" }}>
            <div style={{ flex:1, height: ((d.inV / max) * 100) + "%", background:"#15803D", borderRadius: "3px 3px 0 0", minHeight: d.inV > 0 ? 2 : 0 }} />
            <div style={{ flex:1, height: ((d.outV / max) * 100) + "%", background:"#B91C1C", borderRadius: "3px 3px 0 0", minHeight: d.outV > 0 ? 2 : 0, opacity:.85 }} />
          </div>
          <div style={{ fontSize:10, color:"var(--ink-400)" }}>{d.label}</div>
        </div>
      ))}
    </div>
  );
}

function LegendDot({ color, label }) {
  return (
    <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:12, color:"var(--ink-700)" }}>
      <span style={{ width:10, height:10, borderRadius:3, background: color }} />{label}
    </span>
  );
}

window.Movimentacoes = Movimentacoes;
