/* ANISAN — Livro diário. Registro CRONOLÓGICO (somente leitura) de todas as
   operações financeiras: receitas (entradas) + despesas variáveis e fixas
   (saídas). Cada linha é datada pela DATA DO MOVIMENTO (recebimento/pagamento se
   realizado; senão previsão/vencimento). Respeita o filtro de Período do topo e
   a unidade ativa (ou Consolidado). Não edita nada — as operações são criadas/
   pagas nas abas de origem (Faturamento / Despesas variáveis / Despesas fixas). */

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

  const [tipo, setTipo] = React.useState("todas");        // todas | entrada | saida
  const [statusF, setStatusF] = React.useState("todas");  // todas | realizadas | pendentes
  const [busca, setBusca] = React.useState("");
  const [recentePrimeiro, setRecentePrimeiro] = React.useState(false); // ordem de exibição

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

  const SectionTitle = window.SectionTitle, StatCard = window.StatCard, Select = window.Select;
  const units = cons ? D.units : [unit];

  // ---- Coleta de operações (receitas + compras + fixas lançadas) ----
  const ops = [];
  units.forEach((u) => {
    (data.receitas[u] || []).forEach((r) => ops.push({
      _u: u, key: "rec_" + u + "_" + r.id, tipo: "entrada", origem: "Receita",
      name: r.name, plano: r.plano, value: Number(r.value) || 0,
      realizado: !!r.recebido, status: r.recebido ? "Recebido" : "A receber",
      dataRaw: r.recebido ? r.recebimento : r.prev, conta: r.conta || "", bucket: r.bucket || "",
    }));
    (data.compras[u] || []).forEach((c) => ops.push({
      _u: u, key: "cmp_" + u + "_" + c.id, tipo: "saida", origem: "Despesa variável",
      name: c.name, plano: c.plano, value: Number(c.value) || 0,
      realizado: !!c.paid, status: c.paid ? "Pago" : "Pendente",
      dataRaw: c.paid ? c.pagamento : c.venc, conta: c.conta || "", bucket: c.bucket || "",
    }));
    const fx = data.despesasFixasLancadas[u] || {};
    Object.keys(fx).forEach((mk) => (fx[mk] || []).forEach((c) => ops.push({
      _u: u, key: "fix_" + u + "_" + mk + "_" + c.id, tipo: "saida", origem: "Despesa fixa",
      name: c.name, plano: c.plano, value: Number(c.value) || 0,
      realizado: !!c.paid, status: c.paid ? "Pago" : "Pendente",
      dataRaw: c.paid ? c.pagamento : c.venc, conta: c.conta || "", bucket: c.bucket || "",
    })));
    // Transferências INTERNAS (mesma unidade): 2 linhas por transferência (saída da
    // origem + entrada no destino). Saldo-neutro para a unidade → não afeta a DRE.
    (data.transferencias || []).filter((t) => t.unidade === u).forEach((t) => {
      const rotO = (t.oConta || "conta") + "/" + window.bucketLabel(t.oBucket), rotD = (t.dConta || "conta") + "/" + window.bucketLabel(t.dBucket);
      ops.push({ _u: u, key: "tr_o_" + t.id, tipo: "saida", origem: "Transferência interna", name: "Transferência → " + rotD, plano: "", value: Number(t.value) || 0, realizado: true, status: "Transferido", dataRaw: t.data, conta: t.oConta || "", bucket: t.oBucket || "" });
      ops.push({ _u: u, key: "tr_d_" + t.id, tipo: "entrada", origem: "Transferência interna", name: "Transferência ← " + rotO, plano: "", value: Number(t.value) || 0, realizado: true, status: "Transferido", dataRaw: t.data, conta: t.dConta || "", bucket: t.dBucket || "" });
    });
  });

  // ---- Normaliza data + aplica filtros ----
  const q = busca.trim().toLowerCase();
  const linhas = ops
    .map((o) => Object.assign({ iso: window.ddmmToISO(o.dataRaw) }, o))
    .filter((o) => window.dateInRange(o.dataRaw, period))
    .filter((o) => tipo === "todas" || o.tipo === tipo)
    .filter((o) => statusF === "todas" || (statusF === "realizadas" ? o.realizado : !o.realizado))
    .filter((o) => !q || (o.name || "").toLowerCase().includes(q) || (window.planoLabel(o.plano) || "").toLowerCase().includes(q));

  // ordem cronológica (asc); sem data vai para o fim
  linhas.sort((a, b) => {
    const ai = a.iso || "9999-12-31", bi = b.iso || "9999-12-31";
    if (ai !== bi) return ai < bi ? -1 : 1;
    return (a.tipo === b.tipo) ? 0 : (a.tipo === "entrada" ? -1 : 1);
  });

  // Resultado ACUMULADO ao longo do tempo (entradas − saídas), na ordem cronológica.
  let acc = 0;
  linhas.forEach((o) => { acc += o.tipo === "entrada" ? o.value : -o.value; o.acum = acc; });

  const totalEnt = linhas.reduce((s, o) => s + (o.tipo === "entrada" ? o.value : 0), 0);
  const totalSai = linhas.reduce((s, o) => s + (o.tipo === "saida" ? o.value : 0), 0);
  const resultado = totalEnt - totalSai;

  const exibidas = recentePrimeiro ? linhas.slice().reverse() : linhas;

  // ---- estilos ----
  const th = { fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--muted-2)", textAlign: "left", padding: "0 12px 10px", whiteSpace: "nowrap", position: "sticky", top: 0, background: "var(--surface)", borderBottom: "1px solid var(--hairline)" };
  const td = { padding: "10px 12px", fontFamily: "var(--font-body)", fontSize: 13, color: "var(--paper)", borderBottom: "1px solid var(--hairline)", verticalAlign: "top" };
  const pill = (bg, cor) => ({ display: "inline-block", fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.04em", textTransform: "uppercase", color: cor, background: bg, borderRadius: "var(--radius-pill)", padding: "2px 8px", whiteSpace: "nowrap" });
  const filtroBtn = (ativo) => ({ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.03em", padding: "7px 13px", borderRadius: "var(--radius-pill)", border: "1px solid " + (ativo ? "var(--brass)" : "var(--hairline-strong)"), background: ativo ? "rgba(201,162,75,0.13)" : "transparent", color: ativo ? "var(--paper)" : "var(--muted)", cursor: "pointer", whiteSpace: "nowrap" });

  const Grupo = ({ value, set, opts }) => (
    <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
      {opts.map((o) => <button key={o.v} onClick={() => set(o.v)} style={filtroBtn(value === o.v)}>{o.l}</button>)}
    </div>
  );

  return (
    <div style={{ padding: mobile ? "18px 14px 40px" : "26px 32px 48px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap", marginBottom: 18 }}>
        <SectionTitle style={{ margin: 0 }} meta={cons ? "todas as unidades" : "Unidade " + unit}>Livro diário</SectionTitle>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted-2)" }}>{linhas.length} {linhas.length === 1 ? "operação" : "operações"}</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr 1fr" : "repeat(3, 1fr)", gap: 12, marginBottom: 18 }}>
        <StatCard label="Entradas" value={window.BRL(totalEnt)} accent="var(--jade)" />
        <StatCard label="Saídas" value={window.BRL(totalSai)} accent="var(--clay)" />
        <StatCard label="Resultado" value={window.BRL(resultado)} accent={resultado >= 0 ? "var(--jade)" : "var(--clay)"} />
      </div>

      {/* filtros */}
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", alignItems: "center", marginBottom: 14 }}>
        <Grupo value={tipo} set={setTipo} opts={[{ v: "todas", l: "Todas" }, { v: "entrada", l: "Entradas" }, { v: "saida", l: "Saídas" }]} />
        <Grupo value={statusF} set={setStatusF} opts={[{ v: "todas", l: "Todos status" }, { v: "realizadas", l: "Realizadas" }, { v: "pendentes", l: "Pendentes" }]} />
        <span style={{ display: "flex", alignItems: "center", gap: 9, flex: "1 1 200px", minWidth: 0, background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: "var(--radius-pill)", padding: "8px 13px" }}>
          <i data-lucide="search" style={{ width: 15, height: 15, strokeWidth: 1.7, color: "var(--muted-2)" }}></i>
          <input value={busca} onChange={(e) => setBusca(e.target.value)} placeholder="Buscar por descrição ou classificação…" style={{ flex: 1, minWidth: 0, background: "transparent", border: "none", outline: "none", color: "var(--paper)", fontFamily: "var(--font-body)", fontSize: 13 }} />
        </span>
        <button onClick={() => setRecentePrimeiro((v) => !v)} style={filtroBtn(false)} title="Inverter ordem cronológica">
          <i data-lucide={recentePrimeiro ? "arrow-down-wide-narrow" : "arrow-up-wide-narrow"} style={{ width: 13, height: 13, strokeWidth: 1.8, verticalAlign: "-2px", marginRight: 6 }}></i>
          {recentePrimeiro ? "Recente primeiro" : "Mais antigo primeiro"}
        </button>
      </div>

      {/* tabela cronológica */}
      <div style={{ border: "1px solid var(--hairline)", borderRadius: "var(--radius)", overflow: "auto", background: "var(--surface)" }}>
        <table style={{ width: "100%", minWidth: 720, borderCollapse: "collapse" }}>
          <thead>
            <tr>
              <th style={th}>Data</th>
              <th style={th}>Operação</th>
              {cons && <th style={th}>Unidade</th>}
              <th style={th}>Conta</th>
              <th style={th}>Status</th>
              <th style={{ ...th, textAlign: "right" }}>Valor</th>
              <th style={{ ...th, textAlign: "right" }}>Acum.</th>
            </tr>
          </thead>
          <tbody>
            {exibidas.map((o) => {
              const ent = o.tipo === "entrada";
              const cor = ent ? "var(--jade)" : "var(--clay)";
              const contaTxt = o.conta ? (o.conta + (o.bucket ? " · " + window.bucketLabel(o.bucket) : "")) : "—";
              return (
                <tr key={o.key}>
                  <td style={{ ...td, fontFamily: "var(--font-mono)", fontSize: 12, whiteSpace: "nowrap", color: o.iso ? "var(--paper)" : "var(--muted-2)" }}>{o.iso ? window.dateLabel(o.iso) : "sem data"}</td>
                  <td style={td}>
                    <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <i data-lucide={ent ? "arrow-down-left" : "arrow-up-right"} style={{ width: 14, height: 14, strokeWidth: 1.9, color: cor, flexShrink: 0 }}></i>
                      <span style={{ minWidth: 0 }}>
                        <span style={{ display: "block", color: "var(--paper)" }}>{o.name || "—"}</span>
                        <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 9.5, color: "var(--sand)", marginTop: 1 }}>{o.origem}{window.planoLabel(o.plano) ? " · " + window.planoLabel(o.plano) : ""}</span>
                      </span>
                    </span>
                  </td>
                  {cons && <td style={{ ...td, whiteSpace: "nowrap" }}><span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: "50%", background: D.accents[o._u] }}></span>{o._u}</span></td>}
                  <td style={{ ...td, fontSize: 12, color: "var(--muted)", whiteSpace: "nowrap" }}>{contaTxt}</td>
                  <td style={td}><span style={o.realizado ? pill("var(--fill-positive)", "var(--jade)") : pill("var(--fill-accent)", "var(--brass)")}>{o.status}</span></td>
                  <td style={{ ...td, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 13, color: cor, whiteSpace: "nowrap" }}>{ent ? "+" : "−"} {window.BRL(o.value)}</td>
                  <td style={{ ...td, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12, color: o.acum >= 0 ? "var(--muted)" : "var(--clay)", whiteSpace: "nowrap" }}>{window.BRL(o.acum)}</td>
                </tr>
              );
            })}
            {exibidas.length === 0 && (
              <tr><td colSpan={cons ? 7 : 6} style={{ ...td, textAlign: "center", color: "var(--muted-2)", padding: "22px 12px" }}>Nenhuma operação no período/filtro selecionado.</td></tr>
            )}
          </tbody>
        </table>
      </div>

      <p style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "var(--muted-2)", lineHeight: 1.6, margin: "14px 2px 0", maxWidth: 760 }}>
        Registro cronológico de todas as operações (receitas, despesas variáveis e fixas) no período selecionado. Datado pelo dia do movimento — recebimento/pagamento quando realizado, senão previsão/vencimento. Somente leitura; edite nas abas de origem. “Acum.” = resultado acumulado (entradas − saídas) ao longo do tempo.
      </p>
    </div>
  );
}

window.LivroDiario = LivroDiario;
