// General ledger (Accounting tab)
function glLeaves(nodes, acc) {
  nodes.forEach((n) => {
    if (n.children) glLeaves(n.children, acc);
    else acc.push(n.code + " · " + n.name);
  });
  return acc;
}
const GL_MONTHS = { Jan: "01", Feb: "02", Mar: "03", Apr: "04", May: "05", Jun: "06", Jul: "07", Aug: "08", Sep: "09", Oct: "10", Nov: "11", Dec: "12" };
function glIso(pretty) {
  // "Jun 12" -> "2026-06-12"
  const m = pretty.split(" ");
  return "2026-" + (GL_MONTHS[m[0]] || "01") + "-" + String(m[1] || "1").padStart(2, "0");
}

function GeneralLedger() {
  const { useState } = React;
  const accounts = glLeaves(D.coa, []);
  const [acct, setAcct] = useState("1011 · Operating account · First National");
  const [period, setPeriod] = useState("All");

  // gather rows: seeded history + posted journal lines
  const rows = [];
  D.glExtra.forEach((r) => { if (r.acct === acct) rows.push({ date: r.date, ref: r.ref, memo: r.memo, debit: r.debit, credit: r.credit }); });
  D.journal.forEach((e) => {
    if (e.status !== "Posted") return;
    e.lines.forEach((l) => {
      if (l.acct === acct) rows.push({ date: glIso(e.date), ref: e.id, memo: e.memo, debit: l.debit, credit: l.credit });
    });
  });
  rows.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));

  // running balance over ALL rows (so period filters still show true balances)
  const code = acct.split(" ")[0];
  const debitNormal = code[0] === "1" || code[0] === "5";
  const opening = D.glOpenings[acct] || 0;
  let bal = opening;
  const withBal = rows.map((r) => {
    bal += debitNormal ? (r.debit - r.credit) : (r.credit - r.debit);
    return { ...r, balance: bal };
  });
  const closing = bal;

  const inPeriod = (r) =>
    period === "All" ? true :
    period === "June" ? r.date >= "2026-06-01" :
    period === "May" ? (r.date >= "2026-05-01" && r.date <= "2026-05-31") :
    r.date < "2026-05-01";
  const visible = withBal.filter(inPeriod);
  const totD = visible.reduce((s, r) => s + r.debit, 0);
  const totC = visible.reduce((s, r) => s + r.credit, 0);

  const balMoney = (n) => (debitNormal ? money(n) : money(Math.abs(n)));

  return (
    <><div className="toolbar page-toolbar">
        <div className="toolbar-left">
          <div style={{ width: 340 }}>
            <SearchSelect options={accounts} value={acct} onChange={setAcct} placeholder={T("gl.chooseAnAccount")} />
          </div>
          <Chips active={period} onChange={setPeriod} options={[
            { id: "All", label: T("gl.allTime") }, { id: "June", label: TV("June") },
            { id: "May", label: TV("May") }, { id: "Earlier", label: T("gl.earlier") }
          ]} />
        </div>
      </div>
    <section className="card">

      <div className="gl-sum">
        <div className="gl-cell"><small>{T("gl.openingBalance")}</small><b className="mono">{balMoney(opening)}</b></div>
        <div className="gl-cell"><small>{T("je.debits")}{period !== "All" ? " · " + TV(period) : ""}</small><b className="mono">{money(totD)}</b></div>
        <div className="gl-cell"><small>{T("je.credits")}{period !== "All" ? " · " + TV(period) : ""}</small><b className="mono">{money(totC)}</b></div>
        <div className="gl-cell close"><small>{T("gl.closingBalance")}</small><b className="mono">{balMoney(closing)}</b></div>
      </div>

      <DataTable rowKey={(r) => r.date + r.ref + r.memo} rows={visible}
        empty={T("gl.noMovements")} cols={[
        { k: "date", label: T("common.date"), w: "100px", render: (r) => <span className="dim mono" style={{ fontSize: 12 }}>{prettyDate(r.date)}</span> },
        { k: "ref", label: T("common.ref"), w: "100px", render: (r) => <span className="mono strong">{r.ref}</span> },
        { k: "memo", label: T("common.description"), render: (r) => <span style={{ color: "var(--ink)" }}>{r.memo}</span> },
        { k: "debit", label: T("je.debit"), align: "right", w: "110px", render: (r) => r.debit ? <span className="mono strong">{money(r.debit)}</span> : <span className="dim">—</span> },
        { k: "credit", label: T("je.credit"), align: "right", w: "110px", render: (r) => r.credit ? <span className="mono strong">{money(r.credit)}</span> : <span className="dim">—</span> },
        { k: "balance", label: T("acct.balance"), align: "right", w: "120px", render: (r) => <span className="mono" style={{ fontWeight: 600 }}>{balMoney(r.balance)}</span> }
      ]} />
    </section></>
  );
}
window.GeneralLedger = GeneralLedger;
window.glIso = glIso;
