/* ============================================================
   HALO SMS — dashboards (role-aware home)
   ============================================================ */
(function () {
  const { useState, useEffect, h } = window.HReact;
  const D = window.HALO;

  function Stat({ icon, label, value, foot, tone }) {
    return h("div", { className: "stat" },
      h("div", { className: "l" }, icon && h(Icon, { name: icon }), label),
      h("div", { className: "v", style: tone ? { color: `var(--${tone})` } : null }, value),
      foot && h("div", { className: "d" }, foot));
  }

  function MiniBar({ paidPct, partPct }) {
    return h("div", { className: "bar" },
      h("i", { className: "paid", style: { width: paidPct + "%" } }),
      h("i", { className: "part", style: { width: partPct + "%" } }));
  }

  function Card({ title, sub, action, children, pad = true }) {
    return h("div", { className: "card" },
      (title || action) && h("div", { className: "card-h" },
        h("div", null, h("h3", null, title), sub && h("div", { className: "sub" }, sub)), action),
      h("div", { className: pad ? "card-pad" : "" }, children));
  }

  // fee aggregates
  function feeAgg() {
    let total = 0, paid = 0; D.students.forEach((s) => { total += s.fee.total; paid += s.fee.paid; });
    return { total, paid, out: total - paid, pct: Math.round((paid / total) * 100) };
  }

  function AdminDash({ navigate }) {
    const fa = feeAgg();
    const pending = D.students.filter((s) => s.results === "draft").length;
    const integrations = [
      { name: "Paystack", on: true, sub: "Payments live" },
      { name: "ZeptoMail", on: true, sub: "Email live" },
      { name: "SMS gateway", on: false, sub: "Not configured" },
      { name: "OpenRouter AI", on: true, sub: "Assignments & remarks" },
      { name: "Push", on: false, sub: "Not configured" },
    ];
    const audit = [
      ["Mr. Bello entered scores", "JSS 1A · Mathematics", "12 min ago"],
      ["Bursar recorded a payment", "₦82,500 · Chidinma Adebayo", "1 hr ago"],
      ["Principal published results", "SS2 Science · 2nd Term", "3 hrs ago"],
      ["Admin updated fee structure", "JSS 1 · 2nd Term", "Yesterday"],
    ];
    const events = [["09:00", "PTA meeting — assembly hall"], ["11:30", "Mid-term assessment briefing"], ["14:00", "Inter-house sports practice"]];

    return h("div", null,
      h("div", { className: "grid-4", style: { marginBottom: 18 } },
        h(Stat, { icon: "students", label: "Students enrolled", value: "412", foot: h("span", null, h("span", { className: "up" }, "+12"), " admitted this term") }),
        h(Stat, { icon: "card", label: "Fees collected · term", value: D.fmt(fa.paid), foot: h("span", null, D.fmt(fa.out), " outstanding") }),
        h(Stat, { icon: "filetext", label: "Results pending publish", value: String(pending) + " arms", tone: "warn-fg", foot: "JSS 1A · JSS 2B awaiting" }),
        h(Stat, { icon: "staff", label: "Staff active", value: "38", foot: "2 onboarding" })),
      h("div", { style: { display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16 }, className: "dash-cols" },
        h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
          h(Card, { title: "Fee collection", sub: D.session + " · " + D.term, action: h(Button, { kind: "quiet", size: "sm", iconRight: "chevright", onClick: () => navigate("finance") }, "Finance") },
            h("div", { style: { display: "flex", alignItems: "baseline", gap: 14, marginBottom: 14 } },
              h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 34, letterSpacing: "-0.02em" }, className: "naira" }, fa.pct + "%"),
              h("div", { className: "muted", style: { fontSize: 13 } }, "of expected revenue collected")),
            h(MiniBar, { paidPct: fa.pct, partPct: 8 }),
            h("div", { style: { display: "flex", gap: 22, marginTop: 16, flexWrap: "wrap" } },
              [["Collected", D.fmt(fa.paid), "ok"], ["Outstanding", D.fmt(fa.out), "bad"], ["Expected", D.fmt(fa.total), null]].map(([k, v, t]) =>
                h("div", { key: k, className: "kv" }, h("span", { className: "k" }, k), h("span", { className: "v naira", style: t ? { color: `var(--${t}-fg)` } : null }, v))))),
          h(Card, { title: "Recent activity", sub: "From the audit log", action: h(Button, { kind: "quiet", size: "sm", iconRight: "chevright", onClick: () => navigate("audit") }, "View all"), pad: false },
            h("div", null, audit.map((a, i) =>
              h("div", { key: i, style: { display: "flex", alignItems: "center", gap: 12, padding: "13px 20px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
                h("div", { style: { width: 8, height: 8, borderRadius: 99, background: "var(--brand)", flex: "none" } }),
                h("div", { style: { flex: 1 } }, h("div", { style: { fontSize: 14, fontWeight: 500 } }, a[0]), h("div", { className: "muted", style: { fontSize: 12.5 } }, a[1])),
                h("div", { className: "muted", style: { fontSize: 12 } }, a[2])))))),
        h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
          h(Card, { title: "Capability map", sub: "Integrations live" },
            h("div", { style: { display: "flex", flexDirection: "column", gap: 11 } },
              integrations.map((it) =>
                h("div", { key: it.name, style: { display: "flex", alignItems: "center", gap: 11 } },
                  h("span", { className: "chip " + (it.on ? "chip-ok" : "chip-neutral"), style: { width: 64, justifyContent: "center" } }, it.on ? "Live" : "Off"),
                  h("div", { style: { flex: 1 } }, h("div", { style: { fontSize: 13.5, fontWeight: 500 } }, it.name), h("div", { className: "muted", style: { fontSize: 12 } }, it.sub)))))),
          h(Card, { title: "Today", sub: "Wed, 11 June" },
            h("div", { style: { display: "flex", flexDirection: "column", gap: 13 } },
              events.map((e, i) =>
                h("div", { key: i, style: { display: "flex", gap: 12 } },
                  h("div", { className: "mono", style: { fontSize: 12.5, color: "var(--brand-strong)", width: 44, flex: "none", fontWeight: 600 } }, e[0]),
                  h("div", { style: { fontSize: 13.5 } }, e[1]))))))));
  }

  function SimpleDash({ role, navigate }) {
    const fa = feeAgg();
    const sets = {
      principal: { hi: "School overview", stats: [
        { icon: "filetext", label: "Results pending publish", value: "4 arms", tone: "warn-fg", foot: "Review & publish" },
        { icon: "card", label: "Collected · term", value: D.fmt(fa.paid), foot: D.fmt(fa.out) + " outstanding" },
        { icon: "students", label: "Enrolment", value: "412", foot: "across 14 arms" } ] },
      "subject-teacher": { hi: "My classes", stats: [
        { icon: "clipboard", label: "Score entry due", value: "3 arms", tone: "warn-fg", foot: "JSS 1A, JSS 2B, SS2 Sci" },
        { icon: "filetext", label: "Assignments to grade", value: "17", foot: "2 with AI suggestions" },
        { icon: "check", label: "Published", value: "1 arm", tone: "ok", foot: "SS2 Science" } ] },
      "class-teacher": { hi: "JSS 1A · my arm", stats: [
        { icon: "students", label: "Roster", value: "32", foot: "30 active · 2 new" },
        { icon: "clipboard", label: "Subjects complete", value: "7 / 9", tone: "warn-fg", foot: "Basic Science incomplete" },
        { icon: "pencil", label: "Remarks written", value: "24 / 32", foot: "8 remaining" } ] },
      bursar: { hi: "Finance desk", stats: [
        { icon: "card", label: "Today's payments", value: D.fmt(412500), tone: "ok", foot: "14 transactions" },
        { icon: "wallet", label: "Outstanding", value: D.fmt(fa.out), tone: "bad", foot: "63 students owing" },
        { icon: "check", label: "Pending approvals", value: "2", tone: "warn-fg", foot: "Awaiting second sign-off" } ] },
    };
    const cfg = sets[role] || sets.principal;
    return h("div", null,
      h("div", { className: "grid-3", style: { marginBottom: 18 } }, cfg.stats.map((s, i) => h(Stat, { key: i, ...s }))),
      h(Card, { title: role === "bursar" ? "Outstanding by class" : "Results status by arm", sub: D.session + " · " + D.term, pad: false },
        h("div", null, D.CLASSES.map((c, i) => {
          const inClass = D.students.filter((s) => s.cls === c);
          const t = inClass.reduce((a, s) => a + s.fee.total, 0), p = inClass.reduce((a, s) => a + s.fee.paid, 0);
          const pct = t ? Math.round((p / t) * 100) : 0;
          const draft = inClass.some((s) => s.results === "draft");
          return h("div", { key: c, style: { display: "flex", alignItems: "center", gap: 14, padding: "14px 20px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
            h("div", { style: { width: 110, fontWeight: 600, fontSize: 14 } }, c),
            role === "bursar"
              ? h("div", { style: { flex: 1 } }, h(MiniBar, { paidPct: pct, partPct: 6 }))
              : h("div", { style: { flex: 1 } }, h("span", { className: "muted", style: { fontSize: 13 } }, inClass.length + " students")),
            role === "bursar"
              ? h("span", { className: "naira", style: { fontSize: 13.5, color: "var(--bad-fg)", fontWeight: 600 } }, D.fmt(t - p))
              : h(StatusChip, { state: draft ? "draft" : (inClass.some(s=>s.results==="published") ? "published" : "none") }));
        }))));
  }

  function Dashboard({ role, navigate }) {
    const hello = { admin: "Good morning", principal: "Good morning", bursar: "Good morning", "class-teacher": "Good morning", "subject-teacher": "Good morning" }[role] || "Welcome";
    return h("div", { className: "page-pad wide" },
      h("div", { style: { display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 22, flexWrap: "wrap" } },
        h("div", null,
          h("div", { className: "eyebrow", style: { marginBottom: 7 } }, D.session + " · " + D.term),
          h("h1", { style: { fontSize: 28 } }, hello + ", " + D.IDENTITY.name.split(" ")[1] || "")),
        role === "admin" && h(Button, { kind: "primary", icon: "plus", onClick: () => navigate("students:new") }, "Admit student")),
      role === "admin" ? h(AdminDash, { navigate }) : h(SimpleDash, { role, navigate }));
  }

  window.Dashboard = Dashboard;
})();
