/* ============================================================
   HALO SMS — Attendance (37 mark, 38 history) + Timetable (39/40)
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;
  const ARMS = ["JSS 1A", "JSS 2B", "Primary 4", "SS2 Science", "SS3 Arts"];
  const MARKS = [["present", "P", "ok"], ["absent", "A", "bad"], ["late", "L", "warn"], ["excused", "E", "info"]];

  /* ---------------- ATTENDANCE — MARK (37) ---------------- */
  function AttendanceMark({ navigate, students }) {
    const [arm, setArm] = useState("JSS 1A");
    const [date, setDate] = useState("2026-06-09");
    const roster = D.rosterForArm(arm, students);
    const [marks, setMarks] = useState(() => seed(roster));
    function seed(r) { const m = {}; const rnd = D.seeded(arm + "att"); r.forEach((s) => { const x = rnd(); m[s.id] = x < 0.82 ? "present" : x < 0.9 ? "absent" : x < 0.96 ? "late" : "excused"; }); return m; }
    function reArm(a) { setArm(a); const r = D.rosterForArm(a, students); setMarks(seed(r)); }
    const counts = MARKS.map(([k]) => roster.filter((s) => marks[s.id] === k).length);

    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { eyebrow: "Attendance · " + D.STRUCTURE.activeTerm, title: "Daily register", sub: "Mark the class register, then save",
        actions: h(React.Fragment, null, h(Button, { kind: "ghost", icon: "chart", onClick: () => navigate("attendance:history") }, "History"), h(Button, { kind: "primary", icon: "check", onClick: () => toast("Register saved for " + arm) }, "Save register")) }),
      h("div", { className: "card", style: { padding: 16, marginBottom: 14, display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" } },
        h("div", { className: "field", style: { gap: 4 } }, h("label", { style: { fontSize: 12 } }, "Class / arm"), h("select", { className: "select", style: { width: 170, height: 40 }, value: arm, onChange: (e) => reArm(e.target.value) }, ARMS.map((a) => h("option", { key: a }, a)))),
        h("div", { className: "field", style: { gap: 4 } }, h("label", { style: { fontSize: 12 } }, "Date"), h("input", { type: "date", className: "input", style: { width: 170, height: 40 }, value: date, onChange: (e) => setDate(e.target.value) })),
        h("div", { style: { flex: 1 } }),
        h("div", { className: "row", style: { gap: 8 } }, MARKS.map(([k, , tone], i) => h("div", { key: k, style: { textAlign: "center", padding: "4px 12px", borderRadius: 9, background: `var(--${tone}-bg)`, border: `1px solid var(--${tone}-line)` } },
          h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 18, color: `var(--${tone}-fg)` } }, counts[i]), h("div", { style: { fontSize: 10.5, color: `var(--${tone}-fg)`, textTransform: "capitalize" } }, k))))),
      roster.length === 0
        ? h("div", { className: "card" }, h(EmptyState, { icon: "users", title: "No students in this arm" }, "Admit students to mark attendance."))
        : h("div", { className: "card" },
            h("div", { style: { display: "flex", justifyContent: "space-between", padding: "12px 18px", borderBottom: "1px solid var(--line)" } },
              h("span", { className: "muted", style: { fontSize: 12.5 } }, roster.length + " students"),
              h("div", { className: "row", style: { gap: 6 } }, h("span", { className: "muted", style: { fontSize: 12 } }, "Set all:"), MARKS.map(([k, lbl, tone]) => h("button", { key: k, onClick: () => { const m = {}; roster.forEach((s) => m[s.id] = k); setMarks(m); }, className: "btn btn-quiet btn-sm", style: { color: `var(--${tone}-fg)` } }, lbl)))),
            h("div", null, roster.map((s, i) => h("div", { key: s.id, style: { display: "flex", alignItems: "center", gap: 12, padding: "10px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
              h(Avatar, { name: s.first + " " + s.surname, size: 32 }),
              h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 14 } }, s.surname + ", " + s.first), h("div", { className: "muted", style: { fontSize: 12 } }, s.adm)),
              h("div", { className: "seg" }, MARKS.map(([k, lbl, tone]) => h("button", { key: k, onClick: () => setMarks({ ...marks, [s.id]: k }), className: marks[s.id] === k ? "on" : "",
                style: marks[s.id] === k ? { background: `var(--${tone}-bg)`, color: `var(--${tone}-fg)`, fontWeight: 700 } : null, title: k }, lbl)))))) ));
    return h(window.DesktopScreen, { title: "Attendance" }, body);
  }

  /* ---------------- ATTENDANCE — HISTORY (38) ---------------- */
  function AttendanceHistory({ navigate, students }) {
    const [arm, setArm] = useState("JSS 1A");
    const roster = D.rosterForArm(arm, students);
    const rnd = D.seeded(arm + "hist");
    const rows = roster.map((s) => { const total = 62; const late = 2; const present = 48 + Math.floor(rnd() * 11); const absent = total - present - late; return { s, present, absent, late, total, pct: Math.round(present / total * 100) }; });
    const avg = rows.length ? Math.round(rows.reduce((a, r) => a + r.pct, 0) / rows.length) : 0;
    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { back: { label: "Back to register", onClick: () => navigate("attendance") }, eyebrow: "Attendance", title: "History & summary", sub: D.STRUCTURE.activeTerm + " · feeds the report sheet" }),
      h("div", { className: "card", style: { padding: 16, marginBottom: 14, display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap" } },
        h("select", { className: "select", style: { width: 180, height: 40 }, value: arm, onChange: (e) => setArm(e.target.value) }, ARMS.map((a) => h("option", { key: a }, a))),
        h("div", { style: { flex: 1 } }),
        h("div", { className: "row", style: { gap: 8 } }, h("span", { className: "muted", style: { fontSize: 13 } }, "Class average attendance"), h("span", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 22, color: avg >= 85 ? "var(--ok-fg)" : "var(--warn-fg)" } }, avg + "%"))),
      h("div", { className: "card" }, h("div", { className: "tablewrap" }, h("table", { className: "data" },
        h("thead", null, h("tr", null, h("th", null, "Student"), h("th", { className: "num" }, "Present"), h("th", { className: "num" }, "Absent"), h("th", { className: "num" }, "Late"), h("th", { className: "num" }, "Rate"), h("th", null, ""))),
        h("tbody", null, rows.map(({ s, present, absent, late, total, pct }) => h("tr", { key: s.id, style: { cursor: "default" } },
          h("td", null, h("div", { className: "cellname" }, h(Avatar, { name: s.first + " " + s.surname, size: 30 }), h("div", null, h("div", { className: "nm", style: { fontSize: 13.5 } }, s.surname + ", " + s.first)))),
          h("td", { className: "num" }, present + "/" + total),
          h("td", { className: "num", style: { color: absent > 8 ? "var(--bad-fg)" : "inherit" } }, absent),
          h("td", { className: "num" }, late),
          h("td", { className: "num", style: { fontWeight: 700, color: pct >= 85 ? "var(--ok-fg)" : "var(--warn-fg)" } }, pct + "%"),
          h("td", { style: { width: 120 } }, h("div", { className: "bar", style: { width: 100 } }, h("i", { className: pct >= 85 ? "paid" : "part", style: { width: pct + "%" } }))))))))));
    return h(window.DesktopScreen, { title: "Attendance history" }, body);
  }

  function Attendance({ params, navigate, students }) {
    if (params[0] === "history") return h(AttendanceHistory, { navigate, students });
    return h(AttendanceMark, { navigate, students });
  }

  /* ---------------- TIMETABLE (39 view / 40 edit) ---------------- */
  function Timetable({ params, navigate, role }) {
    const canEdit = (role === "admin" || role === "principal");
    const editing = params[0] === "edit" && canEdit;
    const [arm, setArm] = useState(role === "class-teacher" ? "JSS 1A" : "SS2 Science");
    const [grid, setGrid] = useState(() => D.buildTimetable(arm));
    const [pick, setPick] = useState(null); // {day, period}
    function reArm(a) { setArm(a); setGrid(D.buildTimetable(a)); }

    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { eyebrow: "Timetable · " + D.STRUCTURE.activeTerm, title: editing ? "Edit timetable" : "Timetable", sub: arm,
        actions: canEdit && h(Button, { kind: editing ? "primary" : "ghost", icon: editing ? "check" : "pencil", onClick: () => { if (editing) { toast("Timetable saved"); navigate("timetable"); } else navigate("timetable:edit"); } }, editing ? "Save timetable" : "Edit") }),
      h("div", { className: "card", style: { padding: 14, marginBottom: 14 } }, h("select", { className: "select", style: { width: 200, height: 40 }, value: arm, onChange: (e) => reArm(e.target.value) }, ["JSS 1A", "JSS 2B", "Primary 4", "SS2 Science", "SS3 Arts"].map((a) => h("option", { key: a }, a)))),
      h("div", { className: "card", style: { overflow: "hidden" } }, h("div", { style: { overflowX: "auto" } },
        h("table", { className: "data", style: { minWidth: 720 } },
          h("thead", null, h("tr", null, h("th", { style: { width: 92 } }, "Time"), D.DAYS.map((d) => h("th", { key: d }, d)))),
          h("tbody", null, D.PERIODS.map((p) => p.isBreak
            ? h("tr", { key: p.id, style: { cursor: "default" } }, h("td", { className: "mono", style: { fontSize: 11.5, color: "var(--ink-500)" } }, p.label), h("td", { colSpan: 5, style: { textAlign: "center", background: "var(--surface-2)", color: "var(--ink-500)", fontSize: 12.5, fontWeight: 500, letterSpacing: ".04em" } }, p.name))
            : h("tr", { key: p.id, style: { cursor: "default" } },
                h("td", { className: "mono", style: { fontSize: 11.5, color: "var(--ink-500)" } }, p.label),
                D.DAYS.map((d) => { const cell = grid[d][p.id]; return h("td", { key: d, style: { padding: 6 } },
                  h("button", { onClick: () => editing && setPick({ day: d, period: p.id }), disabled: !editing,
                    style: { width: "100%", textAlign: "left", padding: "8px 10px", borderRadius: 9, border: "1px solid " + (editing ? "var(--line)" : "transparent"), background: cell ? "var(--brand-soft)" : "var(--surface-2)", cursor: editing ? "pointer" : "default" } },
                    cell ? h(React.Fragment, null, h("div", { style: { fontWeight: 600, fontSize: 12.5, color: "var(--brand-strong)" } }, cell.subject), h("div", { className: "muted", style: { fontSize: 11 } }, cell.teacher)) : h("span", { className: "muted", style: { fontSize: 12 } }, editing ? "+ Assign" : "—"))); }))))) )),
      pick && h(AssignCell, { arm, ...pick, current: grid[pick.day][pick.period], onClose: () => setPick(null), onSet: (val) => { setGrid((g) => ({ ...g, [pick.day]: { ...g[pick.day], [pick.period]: val } })); setPick(null); toast("Period updated"); } }));
    return h(window.DesktopScreen, { title: "Timetable" }, body);
  }
  function AssignCell({ arm, day, period, current, onClose, onSet }) {
    const [subject, setSubject] = useState(current ? current.subject : D.subjectsForArm(arm)[0]);
    const [teacher, setTeacher] = useState(current ? current.teacher : "Mr. Bello");
    const teachers = ["Mr. Bello", "Mrs. Eze", "Mrs. Adeyinka", "Mr. Bakare", "Mr. Nwachukwu", "Mrs. Yusuf", "Mrs. Ibrahim", "Mrs. Adebayo"];
    return h(Modal, { icon: "calendar", title: day + " · period assignment", onClose,
      footer: h(React.Fragment, null, current && h(Button, { kind: "danger-soft", onClick: () => onSet(null) }, "Clear"), h("div", { style: { flex: 1 } }), h(Button, { kind: "ghost", onClick: onClose }, "Cancel"), h(Button, { kind: "primary", onClick: () => onSet({ subject, teacher }) }, "Set period")) },
      h("div", { style: { display: "flex", flexDirection: "column", gap: 14 } },
        h(Field, { label: "Subject" }, h(Select, { value: subject, onChange: (e) => setSubject(e.target.value) }, D.subjectsForArm(arm).map((s) => h("option", { key: s }, s)))),
        h(Field, { label: "Teacher" }, h(Select, { value: teacher, onChange: (e) => setTeacher(e.target.value) }, teachers.map((t) => h("option", { key: t }, t))))));
  }

  window.Attendance = Attendance;
  window.Timetable = Timetable;
})();
