/* ANISAN — DRE (Demonstrativo de Resultado). Receitas RECEBIDAS e despesas
   PAGAS, classificadas pelo plano de contas, em colunas mês a mês ao longo do
   ano. Grupos expansíveis; linhas de resultado calculadas. */

const DRE_MESES = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"];
const dreZero = () => new Array(12).fill(0);
const dreAdd = (a, b) => a.map((v, i) => v + (b[i] || 0));
const dreSum = (a) => a.reduce((s, v) => s + v, 0);
const dreFmt = (n) => { n = Math.round(Number(n) || 0); return n === 0 ? "–" : n.toLocaleString("pt-BR"); };

/* Helper global reutilizável: arrays mensais (12) do DRE de uma unidade/ano.
   Usado pelo DRE e pelo Histórico (análise vertical do resultado operacional). */
window.dreMensal = (data, unit, year) => {
  const Z = () => new Array(12).fill(0);
  const add = (a, b) => a.map((v, i) => v + (b[i] || 0));
  const { rec, desp } = window.dreEntries(data, unit, year);
  const recLeaf = window.dreApplyManual(window.dreLeafMonths(rec.filter(e => String(e.plano).startsWith("3"))), data, year);
  const despLeaf = window.dreApplyManual(window.dreLeafMonths(desp), data, year);
  const nodeMonths = (node, leafMap) => node.leaf ? (leafMap[node.code] || Z()) : node.children.reduce((acc, ch) => add(acc, nodeMonths(ch, leafMap)), Z());
  const recTree = window.PLANO_RECEITAS.map(g => ({ children: g.contas.map(c => ({ code: c.code, leaf: true })) }));
  const despTree = window.PLANO_DESPESAS.map(g => ({ code: g.code, children: g.subs.map(s => ({ children: s.contas.map(c => ({ code: c.code, leaf: true })) })) }));
  const groupMonths = (code) => { const g = despTree.find(x => x.code === code); return g ? nodeMonths(g, despLeaf) : Z(); };
  const receita = recTree.reduce((acc, g) => add(acc, nodeMonths(g, recLeaf)), Z());
  const custos = groupMonths("4"), fixas = groupMonths("5"), invest = groupMonths("6");
  const margem = receita.map((v, i) => v - custos[i]);
  const operacional = margem.map((v, i) => v - fixas[i]);
  return { receita, custos, fixas, invest, margem, operacional };
};

/* Override manual do DRE por ANO, no nível da conta-folha:
   data.dreManual[ano][codigo][mes] = valor. Célula ≠0 sobrescreve o sistema;
   vazia/0 mantém o valor do sistema. Aplica sobre um leafMap {code:[12]}. */
window.dreApplyManual = (leafMap, data, year) => {
  const man = (data.dreManual || {})[String(year)] || {};
  const codes = Object.keys(man);
  if (!codes.length) return leafMap;
  const out = {};
  Object.keys(leafMap).forEach((code) => { out[code] = leafMap[code].slice(); });
  codes.forEach((code) => {
    const ov = man[code] || [];
    const base = (out[code] || new Array(12).fill(0)).slice();
    for (let i = 0; i < 12; i++) { const o = Number(ov[i]) || 0; if (o !== 0) base[i] = o; }
    out[code] = base;
  });
  return out;
};

function DRE({ unit }) {
  const store = window.useStore();
  const D = window.ANISAN_DATA;
  const data = store.data;
  const cons = window.isCons(unit);
  const mobile = window.useIsMobile();

  const thisYear = (window.todayISO ? window.todayISO() : "2026-01-01").slice(0, 4);
  const [year, setYear] = React.useState(parseInt(thisYear, 10));
  const [open, setOpen] = React.useState({});
  const [pct, setPct] = React.useState(false);   // análise vertical (% da receita do mês)
  const [editar, setEditar] = React.useState(false);

  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const { rec, desp } = window.dreEntries(data, unit, year);
  const all = [...rec, ...desp];
  const isAcerto = (p) => p === "13.99" || p === "99.98";
  // mapas do SISTEMA (derivados do livro) e mapas EFETIVOS (com override manual).
  const recLeafSys = window.dreLeafMonths(rec.filter(e => String(e.plano).startsWith("3")));
  const despLeafSys = window.dreLeafMonths(desp);
  const entradaLeafSys = window.dreLeafMonths(all.filter(e => String(e.plano).startsWith("7.1")));
  const acertoLeafSys = window.dreLeafMonths(all.filter(e => isAcerto(e.plano)));
  const recLeaf = window.dreApplyManual(recLeafSys, data, year);
  const despLeaf = window.dreApplyManual(despLeafSys, data, year);
  const entradaLeaf = window.dreApplyManual(entradaLeafSys, data, year);
  const acertoLeaf = window.dreApplyManual(acertoLeafSys, data, year);
  // valor do sistema por código (para o placeholder dos campos de edição).
  const sysByCode = Object.assign({}, recLeafSys, despLeafSys, entradaLeafSys, acertoLeafSys);
  const usePct = pct && !editar;   // edição sempre em R$

  const toggleEdit = () => { setEditar(e => { const ne = !e; if (ne) setOpen(o => Object.assign({}, o, { __rec: true, __c4: true, __c5: true, __c6: true, __e71: true, __c72: true, __acerto: true })); return ne; }); };
  // grava data.dreManual[ano][codigo][mes]
  const setManual = (code, i, raw) => store.set(d => {
    d.dreManual = d.dreManual || {};
    d.dreManual[String(year)] = d.dreManual[String(year)] || {};
    const o = d.dreManual[String(year)];
    o[code] = (o[code] || []).slice(0, 12); while (o[code].length < 12) o[code].push(0);
    o[code][i] = window.parseBRL(raw);
  }, "dreManual");
  const ovVal = (code, i) => { const a = ((data.dreManual || {})[String(year)] || {})[code] || []; return Number(a[i]) || 0; };

  const nodeMonths = (node, leafMap) => node.leaf ? (leafMap[node.code] || dreZero()) : node.children.reduce((acc, ch) => dreAdd(acc, nodeMonths(ch, leafMap)), dreZero());

  // árvores
  const recTree = window.PLANO_RECEITAS.map(g => ({ code: g.code, label: g.code + " · " + g.name, children: g.contas.map(c => ({ code: c.code, label: c.code + " · " + c.name, leaf: true })) }));
  const despTree = window.PLANO_DESPESAS.map(g => ({ code: g.code, label: g.code + " · " + g.name, children: g.subs.map(s => ({ code: s.code, label: s.code + " · " + s.name, children: s.contas.map(c => ({ code: c.code, label: c.code + " · " + c.name, leaf: true })) })) }));

  // totais por grupo de despesa
  const groupMonths = (code) => { const g = despTree.find(x => x.code === code); return g ? nodeMonths(g, despLeaf) : dreZero(); };
  const receita = recTree.reduce((acc, g) => dreAdd(acc, nodeMonths(g, recLeaf)), dreZero());
  const custos = groupMonths("4");
  const fixas = groupMonths("5");
  const invest = groupMonths("6");
  const saidas = groupMonths("7.2");
  const entradas = window.PLANO_NAO_OP_ENTRADAS.contas.reduce((acc, c) => dreAdd(acc, entradaLeaf[c.code] || dreZero()), dreZero());
  const acerto = window.PLANO_ACERTO.reduce((acc, c) => dreAdd(acc, acertoLeaf[c.code] || dreZero()), dreZero());
  const margem = receita.map((v, i) => v - custos[i]);
  const operacional = margem.map((v, i) => v - fixas[i]);
  const liquido = operacional.map((v, i) => v - invest[i] + entradas[i] - saidas[i]);

  const toggle = (code) => setOpen(o => ({ ...o, [code]: !o[code] }));

  // ---- rendering helpers ----
  const C1 = mobile ? 168 : 226;          // largura coluna 1
  const CW = 76;                           // largura coluna de mês
  // formata um valor de célula: em R$ ou como % da RECEITA daquele mês (análise vertical)
  const fmtMonth = (v, i) => {
    if (!usePct) return dreFmt(v);
    const denom = receita[i];
    if (!denom) return "–";
    const p = (v / denom) * 100;
    if (Math.abs(p) < 0.05) return "–";
    return (Math.round(p * 10) / 10).toLocaleString("pt-BR", { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + "%";
  };
  const fmtAnual = (arr) => {
    if (!usePct) return dreFmt(dreSum(arr));
    const denom = dreSum(receita);
    if (!denom) return "–";
    const p = (dreSum(arr) / denom) * 100;
    if (Math.abs(p) < 0.05) return "–";
    return (Math.round(p * 10) / 10).toLocaleString("pt-BR", { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + "%";
  };
  const cell = (v, color, i) => (
    <td key={i} style={{ width: CW, minWidth: CW, textAlign: "right", padding: "0 10px", fontFamily: "var(--font-mono)", fontSize: 11.5, color: color || (v < 0 ? "var(--clay)" : (v > 0 ? "var(--paper)" : "var(--muted-2)")), whiteSpace: "nowrap" }}>{fmtMonth(v, i)}</td>
  );
  // célula editável (modo edição, linhas-folha): input NÃO-controlado (o DOM mantém
  // o texto digitado, sem round-trip por parseBRL que zerava estados intermediários).
  // onChange grava o número no store (subtotais ao vivo); vazio/0 → volta ao sistema.
  const editCell = (code, i) => {
    const ov = ovVal(code, i);
    const sys = (sysByCode[code] || [])[i] || 0;
    return (
      <td key={i} style={{ width: CW, minWidth: CW, padding: "2px 4px" }}>
        <input
          key={year + "-" + code + "-" + i}
          defaultValue={ov ? String(ov).replace(".", ",") : ""}
          placeholder={sys ? dreFmt(sys) : "–"} inputMode="decimal"
          onChange={(e) => setManual(code, i, e.target.value)}
          style={{ width: "100%", textAlign: "right", background: "var(--ink)", border: "1px solid " + (ov ? "var(--brass)" : "var(--hairline)"), borderRadius: 6, color: ov ? "var(--paper)" : "var(--muted)", fontFamily: "var(--font-mono)", fontSize: 11, padding: "4px 6px", outline: "none" }} />
      </td>
    );
  };
  const anualCell = (arr, color, bold) => (
    <td style={{ width: 92, minWidth: 92, textAlign: "right", padding: "0 14px", position: "sticky", right: 0, background: "var(--surface)", fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: bold ? 600 : 500, color: color || (dreSum(arr) < 0 ? "var(--clay)" : "var(--paper)"), whiteSpace: "nowrap", borderLeft: "1px solid var(--hairline-strong)" }}>{fmtAnual(arr)}</td>
  );
  const label1 = (text, opts = {}) => (
    <td style={{ width: C1, minWidth: C1, position: "sticky", left: 0, zIndex: 2, background: opts.bg || "var(--surface)", padding: opts.pad || "0 14px", borderRight: "1px solid var(--hairline-strong)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 7, paddingLeft: (opts.indent || 0) * 14 }}>
        {opts.toggleable && <i data-lucide={opts.opened ? "chevron-down" : "chevron-right"} style={{ width: 13, height: 13, strokeWidth: 2, color: "var(--muted)", flexShrink: 0 }}></i>}
        <span style={{ fontFamily: opts.mono ? "var(--font-mono)" : "var(--font-body)", fontSize: opts.size || 12.5, fontWeight: opts.weight || 400, letterSpacing: opts.track || 0, textTransform: opts.upper ? "uppercase" : "none", color: opts.color || "var(--paper)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{text}</span>
      </div>
    </td>
  );

  const rows = [];
  const dataRow = (key, arr, opts) => (
    <tr key={key} onClick={opts.onClick} style={{ height: opts.h || 33, background: opts.bg || "transparent", cursor: opts.onClick ? "pointer" : "default", borderTop: opts.borderTop || "1px solid var(--hairline)" }}>
      {label1(opts.label, { indent: opts.indent, toggleable: opts.toggleable, opened: opts.opened, bg: opts.bg, weight: opts.weight, color: opts.color, size: opts.size, upper: opts.upper, track: opts.track, mono: opts.mono })}
      {(editar && opts.editCode) ? arr.map((v, i) => editCell(opts.editCode, i)) : arr.map((v, i) => cell(v, opts.cellColor, i))}
      {anualCell(arr, opts.anualColor || opts.cellColor, opts.bold)}
    </tr>
  );

  // monta as linhas de uma árvore (grupo → sub → folhas), respeitando expand
  const pushTreeRows = (nodes, leafMap, baseIndent, accentColor) => {
    nodes.forEach((g) => {
      const gm = nodeMonths(g, leafMap);
      if (dreSum(gm) === 0 && !open[g.code]) {
        // grupo sem valor: ainda mostra a linha do grupo (cinza), sem expandir
      }
      const gOpen = !!open[g.code];
      rows.push(dataRow(g.code, gm, { label: g.label, indent: baseIndent, toggleable: true, opened: gOpen, onClick: () => toggle(g.code), weight: 500, color: dreSum(gm) === 0 ? "var(--muted)" : "var(--paper)", mono: false }));
      if (!gOpen) return;
      (g.children || []).forEach((s) => {
        if (s.leaf) {
          const sm = leafMap[s.code] || dreZero();
          rows.push(dataRow(s.code, sm, { label: s.label, indent: baseIndent + 1, color: dreSum(sm) === 0 ? "var(--muted-2)" : "var(--muted)", size: 11.5, mono: true, editCode: s.code }));
        } else {
          const sm = nodeMonths(s, leafMap);
          const sOpen = !!open[s.code];
          rows.push(dataRow(s.code, sm, { label: s.label, indent: baseIndent + 1, toggleable: true, opened: sOpen, onClick: () => toggle(s.code), color: dreSum(sm) === 0 ? "var(--muted-2)" : "var(--muted)", size: 12 }));
          if (!sOpen) return;
          (s.children || []).forEach((c) => {
            const cm = leafMap[c.code] || dreZero();
            rows.push(dataRow(c.code, cm, { label: c.label, indent: baseIndent + 2, color: "var(--muted-2)", size: 11, mono: true, editCode: c.code }));
          });
        }
      });
    });
  };

  // RECEITAS
  rows.push(dataRow("__rec", receita, { label: "RECEITAS (recebidas)", weight: 600, upper: true, track: "0.04em", size: 12, bg: "var(--fill-positive)", color: "var(--jade)", cellColor: "var(--jade)", anualColor: "var(--jade)", bold: true, borderTop: "none", h: 38, toggleable: true, opened: !!open.__rec, onClick: () => toggle("__rec") }));
  if (open.__rec) pushTreeRows(recTree, recLeaf, 1, "var(--jade)");

  // CUSTOS VARIÁVEIS (4)
  rows.push(dataRow("__c4", custos.map(v => -v), { label: "(–) Custos variáveis", weight: 500, color: "var(--paper)", cellColor: "var(--clay)", anualColor: "var(--clay)", h: 36, toggleable: true, opened: !!open.__c4, onClick: () => toggle("__c4"), borderTop: "1px solid var(--hairline-strong)" }));
  if (open.__c4) pushTreeRows([despTree.find(g => g.code === "4")], despLeaf, 1);

  // MARGEM
  rows.push(dataRow("__margem", margem, { label: "= Margem de contribuição", weight: 600, color: "var(--paper)", bg: "var(--surface-2)", bold: true, h: 36, borderTop: "1px solid var(--hairline-strong)" }));

  // DESPESAS FIXAS (5)
  rows.push(dataRow("__c5", fixas.map(v => -v), { label: "(–) Despesas fixas", weight: 500, color: "var(--paper)", cellColor: "var(--clay)", anualColor: "var(--clay)", h: 36, toggleable: true, opened: !!open.__c5, onClick: () => toggle("__c5"), borderTop: "1px solid var(--hairline)" }));
  if (open.__c5) pushTreeRows([despTree.find(g => g.code === "5")], despLeaf, 1);

  // RESULTADO OPERACIONAL
  rows.push(dataRow("__op", operacional, { label: "= Resultado operacional", weight: 600, color: "var(--paper)", bg: "var(--surface-2)", bold: true, h: 36, borderTop: "1px solid var(--hairline-strong)" }));

  // INVESTIMENTOS (6)
  rows.push(dataRow("__c6", invest.map(v => -v), { label: "(–) Investimentos", weight: 500, color: "var(--paper)", cellColor: "var(--clay)", anualColor: "var(--clay)", h: 36, toggleable: true, opened: !!open.__c6, onClick: () => toggle("__c6"), borderTop: "1px solid var(--hairline)" }));
  if (open.__c6) pushTreeRows([despTree.find(g => g.code === "6")], despLeaf, 1);

  // MOVIMENTAÇÕES NÃO OPERACIONAIS (7)
  rows.push(dataRow("__m7", entradas.map((v, i) => v - saidas[i]), { label: "7 · Movimentações não operacionais", upper: true, weight: 600, size: 11, track: "0.04em", color: "var(--muted)", bg: "var(--surface-2)", h: 32, mono: true, borderTop: "1px solid var(--hairline-strong)" }));
  // (+) Entradas não operacionais (7.1)
  rows.push(dataRow("__e71", entradas, { label: "(+) Entradas não operacionais", weight: 500, color: "var(--paper)", cellColor: "var(--jade)", anualColor: "var(--jade)", h: 36, toggleable: true, opened: !!open.__e71, onClick: () => toggle("__e71"), borderTop: "1px solid var(--hairline)" }));
  if (open.__e71) window.PLANO_NAO_OP_ENTRADAS.contas.forEach((c) => { const cm = entradaLeaf[c.code] || dreZero(); rows.push(dataRow(c.code, cm, { label: c.code + " · " + c.name, indent: 1, color: "var(--muted-2)", size: 11, mono: true, cellColor: "var(--jade)", editCode: c.code })); });
  // (–) Saídas não operacionais (7.2)
  rows.push(dataRow("__c72", saidas.map(v => -v), { label: "(–) Saídas não operacionais", weight: 500, color: "var(--paper)", cellColor: "var(--clay)", anualColor: "var(--clay)", h: 36, toggleable: true, opened: !!open.__c72, onClick: () => toggle("__c72"), borderTop: "1px solid var(--hairline)" }));
  if (open.__c72) { const g72 = despTree.find(g => g.code === "7.2"); const leaves72 = (g72.children[0] && g72.children[0].children) || []; leaves72.forEach((c) => { const cm = despLeaf[c.code] || dreZero(); rows.push(dataRow(c.code, cm, { label: c.label, indent: 1, color: "var(--muted-2)", size: 11, mono: true, cellColor: "var(--clay)", editCode: c.code })); }); }

  // RESULTADO LÍQUIDO
  rows.push(dataRow("__liq", liquido, { label: "= RESULTADO LÍQUIDO", weight: 700, upper: true, track: "0.04em", size: 12.5, color: "var(--paper)", bg: "var(--fill-accent)", bold: true, h: 42, anualColor: dreSum(liquido) < 0 ? "var(--clay)" : "var(--brass)", cellColor: null, borderTop: "1px solid var(--hairline-strong)" }));

  // ACERTO DE CAIXA (memorando — fora do resultado)
  rows.push(dataRow("__acerto", acerto, { label: "Acerto de caixa (memo)", weight: 500, color: "var(--muted)", size: 12, toggleable: true, opened: !!open.__acerto, onClick: () => toggle("__acerto"), cellColor: "var(--muted)", anualColor: "var(--muted)", h: 34, borderTop: "1px solid var(--hairline)" }));
  if (open.__acerto) window.PLANO_ACERTO.forEach((c) => { const cm = acertoLeaf[c.code] || dreZero(); rows.push(dataRow(c.code, cm, { label: c.code + " · " + c.name, indent: 1, color: "var(--muted-2)", size: 11, mono: true, cellColor: "var(--muted)", anualColor: "var(--muted)", editCode: c.code })); });

  const SectionTitle = window.SectionTitle, Button = window.Button, Badge = window.Badge, Panel = window.Panel;

  const recAno = dreSum(receita), despAno = dreSum(custos) + dreSum(fixas) + dreSum(invest) + dreSum(saidas), liqAno = dreSum(liquido);

  return (
    <div style={{ padding: mobile ? "18px 12px 40px" : "26px 32px 48px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12, marginBottom: 18 }}>
        <SectionTitle style={{ margin: 0 }} meta={cons ? "todas as unidades" : "Unidade " + unit}>DRE · Demonstrativo de Resultado</SectionTitle>
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
          <button onClick={toggleEdit} style={{ display: "flex", alignItems: "center", gap: 7, background: editar ? "var(--brass)" : "var(--surface)", border: "1px solid " + (editar ? "var(--brass)" : "var(--hairline-strong)"), borderRadius: "var(--radius-pill)", padding: "8px 15px", cursor: "pointer", color: editar ? "var(--ink)" : "var(--paper)", fontFamily: "var(--font-mono)", fontSize: 11.5, letterSpacing: "0.04em", fontWeight: 500 }}>
            <i data-lucide={editar ? "check" : "pencil"} style={{ width: 14, height: 14, strokeWidth: 2 }}></i>
            {editar ? "Concluir edição" : "Editar valores"}
          </button>
          <button onClick={() => setPct(p => !p)} style={{ display: "flex", alignItems: "center", gap: 7, background: pct ? "var(--brass)" : "var(--surface)", border: "1px solid " + (pct ? "var(--brass)" : "var(--hairline-strong)"), borderRadius: "var(--radius-pill)", padding: "8px 15px", cursor: editar ? "not-allowed" : "pointer", opacity: editar ? 0.4 : 1, color: pct ? "var(--ink)" : "var(--paper)", fontFamily: "var(--font-mono)", fontSize: 11.5, letterSpacing: "0.04em", fontWeight: 500 }} disabled={editar}>
            <i data-lucide="percent" style={{ width: 14, height: 14, strokeWidth: 2 }}></i>
            {pct ? "% da receita" : "Análise vertical"}
          </button>
          <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: "var(--radius-pill)", padding: "5px 6px" }}>
            <button onClick={() => setYear(y => y - 1)} style={dreNav}><i data-lucide="chevron-left" style={{ width: 16, height: 16, strokeWidth: 1.8 }}></i></button>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: "0.04em", color: "var(--paper)", minWidth: 56, textAlign: "center" }}>{year}</span>
            <button onClick={() => setYear(y => y + 1)} style={dreNav}><i data-lucide="chevron-right" style={{ width: 16, height: 16, strokeWidth: 1.8 }}></i></button>
          </div>
        </div>
      </div>

      {/* KPIs do ano */}
      <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "repeat(3, 1fr)", gap: 12, marginBottom: 18 }}>
        <div style={dreKpi}><span style={dreKpiLbl}>Receita recebida {year}</span><span style={{ ...dreKpiVal, color: "var(--jade)" }}>{window.BRL(recAno)}</span></div>
        <div style={dreKpi}><span style={dreKpiLbl}>Despesa paga {year}</span><span style={{ ...dreKpiVal, color: "var(--clay)" }}>{window.BRL(despAno)}</span></div>
        <div style={dreKpi}><span style={dreKpiLbl}>Resultado líquido {year}</span><span style={{ ...dreKpiVal, color: liqAno < 0 ? "var(--clay)" : "var(--brass)" }}>{liqAno < 0 ? "− " : ""}{window.BRL(Math.abs(liqAno))}</span></div>
      </div>

      <Panel title="Por mês" action={<Badge accent={pct ? "var(--jade)" : "var(--brass)"} variant="tint">{pct ? "% da receita do mês" : "valores em R$"}</Badge>} style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ borderCollapse: "collapse", width: "100%", minWidth: C1 + CW * 12 + 92 }}>
            <thead>
              <tr style={{ height: 40, background: "var(--surface-2)" }}>
                {label1("Conta", { bg: "var(--surface-2)", weight: 600, upper: true, size: 10.5, track: "0.08em", color: "var(--muted)", mono: true })}
                {DRE_MESES.map((m, i) => (
                  <th key={m} style={{ width: CW, minWidth: CW, textAlign: "right", padding: "0 10px", fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.04em", textTransform: "uppercase", color: i === (new Date()).getMonth() && year === (new Date()).getFullYear() ? "var(--brass)" : "var(--muted)", fontWeight: 500 }}>{m}</th>
                ))}
                <th style={{ width: 92, minWidth: 92, textAlign: "right", padding: "0 14px", position: "sticky", right: 0, background: "var(--surface-2)", fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--paper)", fontWeight: 600, borderLeft: "1px solid var(--hairline-strong)" }}>Anual</th>
              </tr>
            </thead>
            <tbody>{rows}</tbody>
          </table>
        </div>
      </Panel>

      <p style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "var(--muted-2)", lineHeight: 1.6, margin: "16px 2px 0", maxWidth: 760 }}>
        Considera apenas <b style={{ color: "var(--muted)", fontWeight: 500 }}>receitas recebidas</b> (aba Faturamento) e <b style={{ color: "var(--muted)", fontWeight: 500 }}>despesas pagas</b> (Compras / Despesas fixas), por mês de recebimento/pagamento. {editar ? "Em edição: preencha qualquer conta-folha; vazio usa o valor do sistema (mostrado como placeholder). Apague para voltar ao sistema." : "Use “Editar valores” para sobrescrever manualmente qualquer conta em qualquer ano."}ras/pagamentos e Despesas fixas), pela data de recebimento/pagamento. Clique num grupo para abrir as subcontas do plano de contas. No modo <b style={{ color: "var(--muted)", fontWeight: 500 }}>Análise vertical</b>, cada valor vira % da receita daquele mês (a coluna Anual usa a receita do ano), mostrando o impacto de cada conta no faturamento.
      </p>
    </div>
  );
}

const dreNav = { width: 28, height: 28, borderRadius: "50%", background: "none", border: "none", display: "grid", placeItems: "center", cursor: "pointer", color: "var(--muted)" };
const dreKpi = { display: "flex", flexDirection: "column", gap: 5, background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: "var(--radius-tile)", padding: "14px 17px" };
const dreKpiLbl = { fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--muted)" };
const dreKpiVal = { fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500 };

window.DRE = DRE;
