/* ============================================================
   HALO SMS — Parent & Student apps (mobile-first)
   Reuses the shared ReportSheet. Demonstrates fee-gate +
   student-login-disabled state.
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;
  const FEE_GATE = 100; // % paid required to view results (configurable)

  const EV_TONE = { Exam: "bad", Meeting: "info", Activity: "warn", Academic: "ok", Holiday: "info" };
  function MobileEvents() {
    const sorted = D.EVENTS.slice().sort((a, b) => a.date.localeCompare(b.date));
    return h("div", null,
      h("div", { className: "eyebrow", style: { marginBottom: 10 } }, "June 2026 · this term"),
      sorted.map((e) => h("div", { key: e.id, className: "card", style: { padding: 14, marginBottom: 10, display: "flex", gap: 13 } },
        h("div", { style: { textAlign: "center", width: 40, flex: "none" } }, h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 19, lineHeight: 1 } }, new Date(e.date).getDate()), h("div", { className: "muted", style: { fontSize: 10, textTransform: "uppercase" } }, "Jun")),
        h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 14 } }, e.title), h("div", { className: "muted", style: { fontSize: 12, marginTop: 2 } }, e.time + " · " + e.desc)),
        h("span", { className: "chip chip-" + EV_TONE[e.type], style: { alignSelf: "flex-start" } }, e.type))));
  }

  function Frame({ title, tabs, active, onTab, children, sub }) {
    return h("div", { className: "familywrap", style: { maxWidth: 440, margin: "0 auto", height: "100%", display: "flex", flexDirection: "column", background: "var(--paper)", borderLeft: "1px solid var(--line)", borderRight: "1px solid var(--line)" } },
      h("div", { style: { display: "flex", alignItems: "center", gap: 12, padding: "14px 18px", borderBottom: "1px solid var(--line)", background: "var(--surface)", position: "sticky", top: 0, zIndex: 5 } },
        h("div", { style: { flex: 1 } }, h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 18 } }, title), sub && h("div", { className: "muted", style: { fontSize: 12 } }, sub)),
        h("button", { className: "iconbtn", style: { width: 36, height: 36 } }, h(Icon, { name: "bell" }), h("span", { className: "dot" }))),
      h("div", { className: "scroll", style: { flex: 1, overflowY: "auto", padding: "16px 16px 24px" } }, children),
      h("div", { style: { display: "flex", borderTop: "1px solid var(--line)", background: "var(--surface)" } },
        tabs.map((t) => h("button", { key: t.id, onClick: () => onTab(t.id),
          style: { flex: 1, border: "none", background: "none", display: "flex", flexDirection: "column", alignItems: "center", gap: 3, padding: "9px 0 11px",
            color: active === t.id ? "var(--brand)" : "var(--ink-500)", fontSize: 10.5, fontWeight: 500 } },
          h(Icon, { name: t.icon, style: { fontSize: 21 } }), t.label))));
  }

  function ChildSwitcher({ kids, sel, onSel }) {
    const [open, setOpen] = useState(false);
    const cur = kids.find((k) => k.id === sel);
    return h("div", { style: { position: "relative", marginBottom: 16 } },
      h("button", { onClick: () => setOpen(!open), style: { width: "100%", display: "flex", alignItems: "center", gap: 12, padding: 12, borderRadius: 14, background: "var(--surface)", border: "1px solid var(--line)" } },
        h(Avatar, { name: cur.first + " " + cur.surname, size: 40, variant: "accent" }),
        h("div", { style: { flex: 1, textAlign: "left" } }, h("div", { style: { fontWeight: 600, fontSize: 15 } }, cur.first + " " + cur.surname), h("div", { className: "muted", style: { fontSize: 12.5 } }, cur.cls + " · " + cur.adm)),
        h("span", { className: "chip chip-neutral" }, kids.length + " children"), h(Icon, { name: "chevdown", style: { color: "var(--ink-400)" } })),
      open && h(Menu, { style: { left: 0, right: 0, top: 70 }, onClose: () => setOpen(false) },
        h("div", { className: "mlabel" }, "Switch child"),
        kids.map((k) => h("button", { key: k.id, className: "mitem" + (k.id === sel ? " sel" : ""), onClick: () => { onSel(k.id); setOpen(false); } },
          h(Avatar, { name: k.first + " " + k.surname, size: 30, variant: "accent" }),
          h("span", { style: { flex: 1 } }, k.first + " " + k.surname, h("span", { className: "sub" }, k.cls)),
          k.id === sel && h("span", { className: "tick" }, h(Icon, { name: "check" }))))));
  }

  function FeeCard({ kid, onPay }) {
    const st = D.feeStatus(kid); const out = kid.fee.total - kid.fee.paid; const pct = Math.round(kid.fee.paid / kid.fee.total * 100);
    return h("div", { style: { borderRadius: 18, padding: 18, color: "var(--on-brand)", background: "linear-gradient(150deg, var(--brand), var(--brand-strong))", boxShadow: "var(--shadow)" } },
      h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" } },
        h("div", { className: "eyebrow", style: { color: "rgba(255,255,255,.8)" } }, "Fee balance · " + D.term),
        h("span", { className: "chip", style: { background: "rgba(255,255,255,.2)", color: "#fff", border: "none" } }, st === "paid" ? "Fully paid" : st === "partial" ? "Part-paid" : "Owing")),
      h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 34, marginTop: 8 }, className: "naira" }, D.fmt(out)),
      h("div", { style: { fontSize: 12.5, opacity: .85, marginTop: 2 } }, st === "paid" ? "No outstanding fees — thank you" : D.fmt(kid.fee.paid) + " paid of " + D.fmt(kid.fee.total)),
      h("div", { style: { height: 7, borderRadius: 99, background: "rgba(255,255,255,.25)", marginTop: 14, overflow: "hidden" } }, h("div", { style: { height: "100%", width: pct + "%", background: "#fff", borderRadius: 99 } })),
      st !== "paid" && h("button", { onClick: onPay, style: { marginTop: 14, width: "100%", border: "none", borderRadius: 11, padding: 12, background: "#fff", color: "var(--brand-strong)", fontWeight: 700, fontSize: 14.5, fontFamily: "inherit" } }, "Pay fees"));
  }

  function ListCard({ icon, title, sub, right, onClick }) {
    return h("button", { onClick, style: { width: "100%", display: "flex", alignItems: "center", gap: 12, padding: 14, borderRadius: 14, background: "var(--surface)", border: "1px solid var(--line)", textAlign: "left", marginBottom: 10 } },
      h("div", { style: { width: 38, height: 38, borderRadius: 10, background: "var(--brand-soft)", color: "var(--brand-strong)", display: "grid", placeItems: "center", flex: "none" } }, h(Icon, { name: icon })),
      h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 14.5 } }, title), sub && h("div", { className: "muted", style: { fontSize: 12.5 } }, sub)),
      right || h(Icon, { name: "chevright", style: { color: "var(--ink-400)" } }));
  }

  function PayFlow({ kid, onClose, onPaid }) {
    const [step, setStep] = useState("amount");
    const [amt, setAmt] = useState(String(kid.fee.total - kid.fee.paid));
    if (step === "done") return h(Modal, { icon: "check", iconTone: "ok", title: "Payment successful", onClose,
      footer: h(Button, { kind: "primary", onClick: () => { onPaid(Number(amt)); } }, "Done") },
      h("p", { style: { fontSize: 14, color: "var(--ink-600)", lineHeight: 1.6 } }, "You paid ", h("b", { className: "naira" }, D.fmt(Number(amt))), " towards ", kid.first + "'s", " fees. A receipt has been sent to your email and the balance is updated."));
    if (step === "checkout") return h(Modal, { icon: "card", title: "Confirm payment", onClose,
      footer: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: () => setStep("amount") }, "Back"), h(Button, { kind: "primary", onClick: () => setStep("done") }, "Pay " + D.fmt(Number(amt)))) },
      h("div", { style: { background: "var(--surface-2)", borderRadius: 12, padding: 16, fontSize: 13.5 } },
        [["Student", kid.first + " " + kid.surname], ["Term", D.term], ["Amount", D.fmt(Number(amt))], ["Channel", "Paystack · card"]].map(([k, v]) =>
          h("div", { key: k, style: { display: "flex", justifyContent: "space-between", padding: "5px 0" } }, h("span", { className: "muted" }, k), h("span", { style: { fontWeight: 600 }, className: "naira" }, v)))));
    return h(Modal, { icon: "wallet", title: "Pay " + kid.first + "'s fees", onClose,
      footer: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: onClose }, "Cancel"), h(Button, { kind: "primary", disabled: !Number(amt), onClick: () => setStep("checkout") }, "Continue")) },
      h("p", { style: { fontSize: 13.5, color: "var(--ink-600)", marginBottom: 14 } }, "Outstanding balance is ", h("b", { className: "naira" }, D.fmt(kid.fee.total - kid.fee.paid)), ". Pay any amount — installments are welcome."),
      h(Field, { label: "Amount to pay" }, h(Input, { value: amt, onChange: (e) => setAmt(e.target.value.replace(/[^0-9]/g, "")), lead: "₦" })));
  }

  function ParentApp({ roster, upsertStudent }) {
    const [tab, setTab] = useState("home");
    const kids = [D.studentById("st-142"), D.studentById("st-088")].map((k) => roster.find((r) => r.id === k.id) || k);
    const [sel, setSel] = useState("st-142");
    const [pay, setPay] = useState(false);
    const [viewReport, setViewReport] = useState(false);
    const kid = kids.find((k) => k.id === sel);
    const pctPaid = Math.round(kid.fee.paid / kid.fee.total * 100);
    const gated = pctPaid < FEE_GATE;

    const tabs = [{ id: "home", icon: "home", label: "Home" }, { id: "results", icon: "filetext", label: "Results" }, { id: "pay", icon: "card", label: "Pay" }, { id: "calendar", icon: "calendar", label: "Events" }, { id: "more", icon: "more", label: "More" }];

    if (viewReport) return h("div", { style: { height: "100%", overflowY: "auto" }, className: "scroll" }, h(window.ReportSheet, { student: kid, role: "parent", onBack: () => setViewReport(false) }));

    let body;
    if (tab === "home") body = h("div", null,
      h(ChildSwitcher, { kids, sel, onSel: setSel }),
      h(FeeCard, { kid, onPay: () => setPay(true) }),
      h("div", { style: { margin: "18px 0 10px" }, className: "eyebrow" }, "This term"),
      h(ListCard, { icon: "filetext", title: D.term + " result", sub: gated ? "Locked until fees are settled" : "Published · tap to view",
        right: h(StatusChip, { state: gated ? "owing" : "published", label: gated ? "Locked" : "Published" }), onClick: () => setTab("results") }),
      h(ListCard, { icon: "calendar", title: "Next event", sub: "PTA meeting · Fri 13 June, 9:00am", onClick: () => setTab("calendar") }),
      h(ListCard, { icon: "card", title: "Recent payment", sub: pctPaid > 0 ? D.fmt(kid.fee.paid) + " received" : "No payments yet", onClick: () => setPay(true) }));
    else if (tab === "results") body = h("div", null,
      h(ChildSwitcher, { kids, sel, onSel: setSel }),
      gated
        ? h("div", { className: "card", style: { padding: 4 } }, h(EmptyState, { icon: "lock", title: "Results available once fees are settled",
            action: h(Button, { kind: "primary", icon: "card", onClick: () => setPay(true) }, "Pay " + D.fmt(kid.fee.total - kid.fee.paid)) },
            kid.first + "'s " + D.term + " result is ready. Your school releases results when fees reach " + FEE_GATE + "%. You've paid " + pctPaid + "% — settle the balance to unlock it instantly."))
        : h(React.Fragment, null,
            h("div", { className: "card", style: { padding: 16, marginBottom: 12, display: "flex", gap: 14, alignItems: "center" } },
              h("div", { style: { textAlign: "center" } }, h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 30, color: "var(--ok-fg)" } }, kid.grade || "—"), h("div", { className: "eyebrow" }, "Grade")),
              h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600 } }, "Term average " + (kid.avg ? kid.avg.toFixed(1) : "—")),
                h("div", { className: "muted", style: { fontSize: 13 } }, kid.position ? "Position " + kid.position + " of " + kid.ofN : "")),
              h(StatusChip, { state: "published" })),
            h(Button, { kind: "primary", block: true, icon: "filetext", onClick: () => setViewReport(true) }, "Open full report sheet")));
    else if (tab === "pay") body = h("div", null, h(ChildSwitcher, { kids, sel, onSel: setSel }), h(FeeCard, { kid, onPay: () => setPay(true) }),
      h("div", { style: { margin: "18px 0 10px" }, className: "eyebrow" }, "Fee breakdown"),
      h("div", { className: "card", style: { padding: 16 } }, ["Tuition","Development levy","Books & materials"].map((it, i) =>
        h("div", { key: it, style: { display: "flex", justifyContent: "space-between", padding: "8px 0", borderTop: i ? "1px solid var(--line-soft)" : "none", fontSize: 14 } },
          h("span", { className: "muted" }, it), h("span", { className: "naira" }, D.fmt([110000,45000,30000][i]))))));
    else if (tab === "calendar") body = h(MobileEvents, null);
    else body = h("div", null,
      h(ListCard, { icon: "shield", title: "Account & security", sub: D.IDENTITY.email }),
      h(ListCard, { icon: "bell", title: "Notification preferences", sub: "SMS reserved for important events" }),
      h(ListCard, { icon: "swap", title: "Switch to staff view", sub: "You're also a class teacher", right: h("span", { className: "chip chip-info" }, "2 roles") }));

    return h(React.Fragment, null,
      h(Frame, { title: "Hello, Folake", sub: kids.length + " children · " + D.BRANDS[document.documentElement.getAttribute("data-brand")].name, tabs, active: tab, onTab: setTab }, body),
      pay && h(PayFlow, { kid, onClose: () => setPay(false), onPaid: (amount) => { upsertStudent({ ...kid, fee: { ...kid.fee, paid: Math.min(kid.fee.total, kid.fee.paid + amount) } }); setPay(false); toast("Payment of " + D.fmt(amount) + " received"); } }));
  }

  function StudentApp({ roster }) {
    const brand = document.documentElement.getAttribute("data-brand");
    const [tab, setTab] = useState("home");
    const [viewReport, setViewReport] = useState(false);
    const [openAssign, setOpenAssign] = useState(null);
    // demonstrate student-login-disabled for a nursery/primary school
    if (brand === "little-stars")
      return h(Frame, { title: "Student", tabs: [{ id: "home", icon: "home", label: "Home" }], active: "home", onTab: () => {} },
        h(EmptyState, { icon: "lock", title: "Student accounts are turned off" }, "This school keeps student logins disabled for its age group. Parents access results and fees on their child's behalf from the parent app."));

    const me = roster.find((r) => r.id === "st-088") || D.studentById("st-088");
    const tabs = [{ id: "home", icon: "home", label: "Home" }, { id: "assignments", icon: "clipboard", label: "Work" }, { id: "results", icon: "filetext", label: "Results" }, { id: "calendar", icon: "calendar", label: "Events" }];
    if (viewReport) return h("div", { style: { height: "100%", overflowY: "auto" }, className: "scroll" }, h(window.ReportSheet, { student: me, role: "student", onBack: () => setViewReport(false) }));
    if (openAssign) return h("div", { style: { height: "100%", overflowY: "auto" }, className: "scroll" }, h(window.AssignmentSubmit, { assignment: openAssign, navigate: () => setOpenAssign(null) }));

    let body;
    if (tab === "home") body = h("div", null,
      h("div", { className: "card", style: { padding: 16, marginBottom: 14, display: "flex", gap: 14, alignItems: "center" } },
        h(Avatar, { name: me.first + " " + me.surname, size: 46, variant: "brand" }),
        h("div", null, h("div", { style: { fontWeight: 700, fontSize: 16 } }, me.first + " " + me.surname), h("div", { className: "muted", style: { fontSize: 13 } }, me.cls + " · " + me.department))),
      h("div", { style: { margin: "4px 0 10px" }, className: "eyebrow" }, "Today"),
      h(ListCard, { icon: "clipboard", title: "Mathematics assignment", sub: "Due tomorrow · not submitted", right: h(StatusChip, { state: "draft", label: "Due" }), onClick: () => setTab("assignments") }),
      h(ListCard, { icon: "filetext", title: D.term + " result", sub: "Published · tap to view", right: h(StatusChip, { state: "published" }), onClick: () => setTab("results") }),
      // student sees own fee balance — READ ONLY, no pay button
      h("div", { className: "card", style: { padding: 16, marginTop: 4 } },
        h("div", { className: "eyebrow", style: { marginBottom: 6 } }, "My fee balance"),
        h("div", { style: { display: "flex", alignItems: "baseline", gap: 8 } },
          h("span", { className: "naira", style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 24 } }, D.fmt(me.fee.total - me.fee.paid)), h(StatusChip, { state: D.feeStatus(me) })),
        h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 6 } }, "Fees are handled by your parent or guardian.")));
    else if (tab === "assignments") body = h("div", null,
      h("div", { className: "eyebrow", style: { marginBottom: 10 } }, "My assignments"),
      D.ASSIGNMENTS.filter((a) => a.arm === me.cls && a.state !== "draft").map((a) => {
        const graded = a.id === "as-04";
        return h(ListCard, { key: a.id, icon: graded ? "check" : "clipboard", title: a.title, sub: a.subject + " · due " + new Date(a.due).toLocaleDateString("en-NG", { day: "numeric", month: "short" }),
          right: h(StatusChip, { state: graded ? "published" : "draft", label: graded ? "Graded" : "Due" }), onClick: () => setOpenAssign(a) });
      }));
    else if (tab === "results") body = h("div", null,
      h("div", { className: "card", style: { padding: 16, marginBottom: 12, display: "flex", gap: 14, alignItems: "center" } },
        h("div", { style: { textAlign: "center" } }, h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 30, color: "var(--ok-fg)" } }, me.grade), h("div", { className: "eyebrow" }, "Grade")),
        h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600 } }, "Term average " + me.avg.toFixed(1)), h("div", { className: "muted", style: { fontSize: 13 } }, "Position " + me.position + " of " + me.ofN)),
        h(StatusChip, { state: "published" })),
      h(Button, { kind: "primary", block: true, icon: "filetext", onClick: () => setViewReport(true) }, "Open full report sheet"));
    else body = h(MobileEvents, null);

    return h(Frame, { title: "Hi, " + me.first, sub: me.cls + " · " + D.BRANDS[brand].name, tabs, active: tab, onTab: setTab }, body);
  }

  window.ParentApp = ParentApp;
  window.StudentApp = StudentApp;
})();
