// Trial balance (Accounting tab)
function TrialBalance() {
  const groups = D.coa.map((root) => {
    const leaves = [];
    (function walk(n) {
      if (n.children) n.children.forEach(walk);
      else leaves.push(n);
    })(root);
    const rows = leaves.map((l) => ({
      code: l.code, name: l.name,
      debit: l.balance > 0 ? l.balance : 0,
      credit: l.balance < 0 ? -l.balance : 0
    }));
    return {
      name: root.name,
      rows,
      debit: rows.reduce((s, r) => s + r.debit, 0),
      credit: rows.reduce((s, r) => s + r.credit, 0)
    };
  });
  const totD = groups.reduce((s, g) => s + g.debit, 0);
  const totC = groups.reduce((s, g) => s + g.credit, 0);
  const balanced = Math.round(totD - totC) === 0;

  return (
    <><div className="toolbar page-toolbar">
        <span className="dim" style={{ fontSize: 13 }}>{T("tb.asOf", { date: "Jun 13, 2026" })}</span>
        <span className={"je-balance " + (balanced ? "ok" : "bad")}>
          <span className="je-diff">
            {balanced ? <Icon name="check" size={13} stroke={2.4} /> : <Icon name="alert" size={13} />}
            {balanced ? T("je.balanced") : T("tb.outOfBalance", { amount: money(Math.abs(totD - totC)) })}
          </span>
        </span>
      </div>
    <section className="card">
      <div className="tb">
        <div className="tb-row head">
          <span>{T("acct.code")}</span><span>{T("acct.account")}</span><span>{T("je.debit")}</span><span>{T("je.credit")}</span>
        </div>
        {groups.map((g) => (
          <React.Fragment key={g.name}>
            <div className="tb-row group">
              <span></span><span>{TV(g.name)}</span>
              <span className="mono">{g.debit ? money(g.debit) : ""}</span>
              <span className="mono">{g.credit ? money(g.credit) : ""}</span>
            </div>
            {g.rows.map((r) => (
              <div key={r.code} className="tb-row">
                <span className="mono dim">{r.code}</span>
                <span>{TV(r.name)}</span>
                <span className="mono">{r.debit ? money(r.debit) : "—"}</span>
                <span className="mono">{r.credit ? money(r.credit) : "—"}</span>
              </div>
            ))}
          </React.Fragment>
        ))}
        <div className="tb-row total">
          <span></span><span>{T("common.total")}</span>
          <span className="mono">{money(totD)}</span>
          <span className="mono">{money(totC)}</span>
        </div>
      </div>
    </section></>
  );
}
window.TrialBalance = TrialBalance;
