/* ============================================================
   HALO SMS — Finance part 1: dashboard (41), record payment (42),
   invoices (43) + detail (44), receipt (49), reversal (50)
   Shared helpers used: PageHead, DesktopScreen, ConfirmModal.
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;
  const F = window.HALO.fmt;

  const payChip = (st) => st === "posted" ? h("span", { className: "chip chip-ok" }, h("span", { className: "d" }), "Posted")
    : st === "pending" ? h("span", { className: "chip chip-warn" }, h("span", { className: "d" }), "Pending")
    : h("span", { className: "chip chip-bad" }, h("span", { className: "d" }), "Reversed");

  function nameOf(id, students) { const s = (students || D.students).find((x) => x.id === id) || D.studentById(id); return s ? s.first + " " + s.surname : id; }

  /* ---------------- DASHBOARD (41) ---------------- */
  function FinanceDashboard({ navigate, students, payments }) {
    const agg = D.financeAgg(students);
    const todays = payments.filter((p) => p.state === "posted").reduce((a, p) => a + p.amount, 0);
    const pending = payments.filter((p) => p.state === "pending");
    const defaulters = students.filter((s) => D.feeStatus(s) === "owing").slice(0, 6);
    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { eyebrow: "Finance · " + D.STRUCTURE.activeTerm, title: "Finance desk", sub: D.STRUCTURE.session,
        actions: h(Button, { kind: "primary", icon: "card", onClick: () => navigate("record") }, "Record payment") }),
      h("div", { className: "grid-4", style: { marginBottom: 18 } },
        statTile("card", "Today's payments", F(todays), payments.filter((p) => p.state === "posted").length + " posted", "ok"),
        statTile("wallet", "Outstanding", F(agg.outstanding), agg.pct + "% collected", "bad"),
        statTile("tag", "Discounted", F(agg.discounted), D.DISCOUNTS.length + " this term", null),
        statTile("check", "Pending approvals", String(pending.length), "Awaiting sign-off", pending.length ? "warn" : "ok")),
      h("div", { style: { display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16, alignItems: "start" }, className: "det-cols" },
        h("div", { className: "card" },
          h("div", { className: "card-h" }, h("h3", null, "Today's payments"), h(Button, { kind: "quiet", size: "sm", iconRight: "chevright", onClick: () => navigate("reports") }, "Reports")),
          h("div", { className: "tablewrap" }, h("table", { className: "data" },
            h("thead", null, h("tr", null, h("th", null, "Time"), h("th", null, "Student"), h("th", { className: "num" }, "Amount"), h("th", null, "Channel"), h("th", null, "Status"))),
            h("tbody", null, payments.map((p) => h("tr", { key: p.id, onClick: () => navigate("invoices:" + p.studentId), style: { cursor: "pointer" } },
              h("td", { className: "mono", style: { fontSize: 12.5 } }, p.time),
              h("td", null, nameOf(p.studentId, students)),
              h("td", { className: "num", style: { fontWeight: 600 } }, F(p.amount)),
              h("td", null, h("span", { className: "tag" }, p.channel)),
              h("td", null, payChip(p.state))))))),
        h("div", { className: "card" },
          h("div", { className: "card-h" }, h("h3", null, "Top defaulters"), h("span", { className: "muted", style: { fontSize: 12.5 } }, "Owing")),
          h("div", null, defaulters.length === 0 ? h("div", { className: "card-pad muted", style: { fontSize: 13.5 } }, "No outstanding balances 🎉")
            : defaulters.map((s, i) => h("div", { key: s.id, onClick: () => navigate("invoices:" + s.id), style: { display: "flex", alignItems: "center", gap: 11, padding: "11px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none", cursor: "pointer" } },
                h(Avatar, { name: s.first + " " + s.surname, size: 30 }),
                h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13.5 } }, s.surname + ", " + s.first), h("div", { className: "muted", style: { fontSize: 12 } }, s.cls)),
                h("span", { className: "naira", style: { fontWeight: 600, fontSize: 13.5, color: "var(--bad-fg)" } }, F(s.fee.total - s.fee.paid)))))))));
    return h(window.DesktopScreen, { title: "Finance" }, body);
  }
  function statTile(icon, label, value, foot, tone) {
    return h("div", { className: "stat" }, h("div", { className: "l" }, h(Icon, { name: icon }), label),
      h("div", { className: "v", style: tone ? { color: `var(--${tone}-fg)` } : null }, value),
      foot && h("div", { className: "d" }, foot));
  }

  /* ---------------- RECORD PAYMENT (42) ---------------- */
  function RecordPayment({ navigate, students, upsertStudent, onPosted, preselect }) {
    const [sel, setSel] = useState(preselect || null);
    const [q, setQ] = useState("");
    const student = sel && students.find((s) => s.id === sel);
    const [amount, setAmount] = useState("");
    const [channel, setChannel] = useState("Transfer");
    const [ref, setRef] = useState("");
    const [receipt, setReceipt] = useState(null);

    if (receipt) return h(window.DesktopScreen, { title: "Receipt" }, h(Receipt, { ...receipt, navigate }));

    let body;
    if (!student) {
      const list = students.filter((s) => D.feeStatus(s) !== "paid").filter((s) => q === "" || (s.first + " " + s.surname + " " + s.adm).toLowerCase().includes(q.toLowerCase()));
      body = h("div", { className: "page-pad", style: { maxWidth: 760 } },
        h(window.PageHead, { eyebrow: "Finance", title: "Record payment", sub: "Select the student to record a payment for" }),
        h("div", { className: "card" },
          h("div", { style: { padding: 14, borderBottom: "1px solid var(--line)" } }, h("div", { className: "searchbox" }, h(Icon, { name: "search" }), h("input", { placeholder: "Search student name or admission no.", value: q, onChange: (e) => setQ(e.target.value) }))),
          h("div", { style: { maxHeight: 460, overflowY: "auto" }, className: "scroll" }, list.map((s, i) => {
            const inv = D.invoiceFor(s);
            return h("div", { key: s.id, onClick: () => { setSel(s.id); setAmount(String(inv.balance)); }, style: { display: "flex", alignItems: "center", gap: 12, padding: "12px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none", cursor: "pointer" } },
              h(Avatar, { name: s.first + " " + s.surname, size: 34 }),
              h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 14 } }, s.surname + ", " + s.first), h("div", { className: "muted", style: { fontSize: 12 } }, s.cls + " · " + s.adm)),
              h("span", { className: "naira", style: { fontWeight: 600, fontSize: 13.5, color: "var(--bad-fg)" } }, F(inv.balance)),
              h("span", { className: "chip " + (D.feeStatus(s) === "partial" ? "chip-warn" : "chip-bad") }, D.feeStatus(s) === "partial" ? "Part-paid" : "Owing")); }))));
      return h(window.DesktopScreen, { title: "Record payment" }, body);
    }

    const inv = D.invoiceFor(student);
    const amt = Number(amount || 0);
    function submit() {
      if (!amt || amt <= 0) { toast("Enter a payment amount", "bad"); return; }
      if (!ref.trim() && channel !== "Cash") { toast("Add a payment reference", "bad"); return; }
      const newPaid = Math.min(student.fee.total, student.fee.paid + amt);
      upsertStudent({ ...student, fee: { ...student.fee, paid: newPaid } });
      const rec = { student, amount: amt, channel, reference: ref || "CASH", balance: student.fee.total - newPaid, date: new Date() };
      onPosted && onPosted(rec);
      setReceipt(rec);
    }
    body = h("div", { className: "page-pad", style: { maxWidth: 760 } },
      h(window.PageHead, { back: { label: "Choose another student", onClick: () => { setSel(null); setAmount(""); setRef(""); } }, eyebrow: "Record payment", title: student.first + " " + student.surname, sub: student.cls + " · " + student.adm }),
      h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }, className: "det-cols" },
        h("div", { className: "card" },
          h("div", { className: "card-h" }, h("h3", null, "Outstanding invoice"), h("span", { className: "chip " + (D.feeStatus(student) === "partial" ? "chip-warn" : "chip-bad") }, D.feeStatus(student) === "partial" ? "Part-paid" : "Owing")),
          h("div", { className: "card-pad" },
            inv.items.map(([n, a], i) => h("div", { key: n, style: { display: "flex", justifyContent: "space-between", padding: "7px 0", borderTop: i ? "1px solid var(--line-soft)" : "none", fontSize: 13.5 } }, h("span", { className: "muted" }, n), h("span", { className: "naira" }, F(a)))),
            h("div", { style: { display: "flex", justifyContent: "space-between", marginTop: 12, paddingTop: 12, borderTop: "2px solid var(--line)" } }, h("span", { style: { fontWeight: 600 } }, "Balance due"), h("span", { className: "naira", style: { fontWeight: 700, color: "var(--bad-fg)" } }, F(inv.balance))))),
        h("div", { className: "card", style: { padding: 20 } },
          h("h3", { style: { fontSize: 16, marginBottom: 16 } }, "Payment details"),
          h("div", { style: { display: "flex", flexDirection: "column", gap: 14 } },
            window.Fld("Amount", { hint: "Any installment is allowed" }, h(window.Input, { value: amount, lead: "₦", onChange: (e) => setAmount(e.target.value.replace(/[^0-9]/g, "")) })),
            window.Fld("Channel", {}, h(window.Segmented, { value: channel, onChange: setChannel, options: D.CHANNELS.map((c) => ({ value: c, label: c })) })),
            window.Fld("Reference", { hint: channel === "Cash" ? "Optional for cash" : "Transaction / receipt reference" }, h(window.Input, { value: ref, onChange: (e) => setRef(e.target.value), placeholder: "e.g. TRF-552190" })),
            h("div", { className: "consequence", style: { background: "var(--info-bg)", borderColor: "var(--info-line)", color: "var(--info-fg)" } }, h(Icon, { name: "info", style: { fontSize: 16 } }), h("div", null, "New balance after this payment: ", h("b", { className: "naira" }, F(Math.max(0, inv.balance - amt))))),
            h(Button, { kind: "primary", size: "lg", block: true, icon: "check", onClick: submit }, "Record " + F(amt || 0))))));
    return h(window.DesktopScreen, { title: "Record payment" }, body);
  }

  function Receipt({ student, amount, channel, reference, balance, date, navigate }) {
    const brand = D.BRANDS[document.documentElement.getAttribute("data-brand")];
    return h("div", { className: "page-pad", style: { maxWidth: 560 } },
      h("div", { className: "wrap-actions noprint", style: { justifyContent: "space-between", marginBottom: 16 } },
        h(Button, { kind: "quiet", icon: "arrowleft", onClick: () => navigate("invoices:" + student.id) }, "View invoice"),
        h("div", { className: "row" }, h(Button, { kind: "ghost", icon: "printer", onClick: () => window.print() }, "Print"), h(Button, { kind: "primary", icon: "card", onClick: () => navigate("record") }, "New payment"))),
      h("div", { className: "card", style: { overflow: "hidden" } },
        h("div", { style: { padding: "22px 24px", display: "flex", justifyContent: "space-between", alignItems: "flex-start", borderBottom: "1px solid var(--line)" } },
          h("div", { className: "row", style: { gap: 12 } }, h("div", { className: "logo" }, brand.short), h("div", null, h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 15 } }, brand.name), h("div", { className: "muted", style: { fontSize: 12 } }, "Official payment receipt"))),
          h("span", { className: "chip chip-ok" }, h(Icon, { name: "check" }), "Paid")),
        h("div", { style: { padding: 24, textAlign: "center" } },
          h("div", { className: "eyebrow" }, "Amount received"),
          h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 40, letterSpacing: "-0.02em", margin: "6px 0" }, className: "naira" }, F(amount))),
        h("div", { style: { padding: "0 24px 22px" } },
          [["Student", student.first + " " + student.surname], ["Class", student.cls], ["Admission no.", student.adm], ["Channel", channel], ["Reference", reference], ["Date", date.toLocaleString("en-NG", { dateStyle: "medium", timeStyle: "short" })], ["New balance", F(balance)]].map(([k, v], i) =>
            h("div", { key: k, style: { display: "flex", justifyContent: "space-between", padding: "9px 0", borderTop: i ? "1px solid var(--line-soft)" : "none", fontSize: 13.5 } }, h("span", { className: "muted" }, k), h("span", { style: { fontWeight: 500 }, className: k === "Reference" || k === "Admission no." ? "mono" : "naira" }, v))),
          h("div", { className: "muted", style: { fontSize: 11.5, textAlign: "center", marginTop: 16 } }, "Receipt no. RCP-" + Date.now().toString().slice(-8) + " · Generated by Halo SMS"))));
  }

  window.FinanceDashboard = FinanceDashboard;
  window.RecordPayment = RecordPayment;
  window.financeNameOf = nameOf;
  window.payChip = payChip;
})();
