/* ============================================================
   HALO SMS — Calendar (72) + Notifications (73 inbox/compose, 74 prefs)
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;

  const EV_TONE = { Exam: "bad", Meeting: "info", Activity: "warn", Academic: "ok", Holiday: "info" };

  /* ---------------- CALENDAR (72) ---------------- */
  function Calendar({ navigate, role, events, onAdd }) {
    const canManage = role === "admin" || role === "principal";
    const [add, setAdd] = useState(false);
    // June 2026: 1 June = Monday
    const year = 2026, month = 5; // June (0-indexed)
    const firstDay = new Date(year, month, 1).getDay(); // 1 = Mon
    const offset = (firstDay + 6) % 7; // make Monday=0
    const daysIn = 30;
    const byDate = {}; events.forEach((e) => { (byDate[e.date] = byDate[e.date] || []).push(e); });
    const cells = [];
    for (let i = 0; i < offset; i++) cells.push(null);
    for (let d = 1; d <= daysIn; d++) cells.push(d);
    const sorted = events.slice().sort((a, b) => a.date.localeCompare(b.date));

    const grid = h("div", { className: "card", style: { padding: 16 } },
      h("div", { style: { display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 6, marginBottom: 8 } }, ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map((d) => h("div", { key: d, className: "eyebrow", style: { textAlign: "center", fontSize: 10 } }, d))),
      h("div", { style: { display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 6 } }, cells.map((d, i) => {
        if (!d) return h("div", { key: "e" + i });
        const ds = `2026-06-${String(d).padStart(2, "0")}`;
        const evs = byDate[ds] || []; const isToday = d === 9;
        return h("div", { key: d, style: { minHeight: 76, borderRadius: 10, border: "1px solid " + (isToday ? "var(--brand)" : "var(--line)"), background: isToday ? "var(--brand-soft)" : "var(--surface)", padding: 7 } },
          h("div", { style: { fontSize: 12, fontWeight: isToday ? 700 : 500, color: isToday ? "var(--brand-strong)" : "var(--ink-500)", marginBottom: 4 } }, d),
          evs.slice(0, 2).map((e) => h("div", { key: e.id, title: e.title, style: { fontSize: 10.5, fontWeight: 600, padding: "2px 5px", borderRadius: 5, marginBottom: 3, background: `var(--${EV_TONE[e.type]}-bg)`, color: `var(--${EV_TONE[e.type]}-fg)`, overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis" } }, e.title)),
          evs.length > 2 && h("div", { style: { fontSize: 10, color: "var(--ink-400)" } }, "+" + (evs.length - 2) + " more")); })));

    const upcoming = h("div", { className: "card" },
      h("div", { className: "card-h" }, h("h3", null, "Upcoming"), h("span", { className: "muted", style: { fontSize: 12.5 } }, sorted.length + " events")),
      h("div", { style: { maxHeight: 420, overflowY: "auto" }, className: "scroll" }, sorted.map((e, i) => h("div", { key: e.id, style: { display: "flex", gap: 12, padding: "13px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
        h("div", { style: { textAlign: "center", width: 42, flex: "none" } }, h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 18, lineHeight: 1 } }, new Date(e.date).getDate()), h("div", { className: "muted", style: { fontSize: 10.5, textTransform: "uppercase" } }, "Jun")),
        h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13.5 } }, 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)))));

    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { eyebrow: "June 2026 · " + D.STRUCTURE.activeTerm, title: "School calendar", sub: "Term events, exams and holidays",
        actions: canManage && h(Button, { kind: "primary", icon: "plus", onClick: () => setAdd(true) }, "Add event") }),
      h("div", { style: { display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16, alignItems: "start" }, className: "det-cols" }, grid, upcoming),
      add && h(AddEvent, { onClose: () => setAdd(false), onSave: (ev) => { onAdd(ev); setAdd(false); toast("Event added to calendar"); } }));
    return h(window.DesktopScreen, { title: "Calendar" }, body);
  }
  function AddEvent({ onClose, onSave }) {
    const [title, setTitle] = useState(""); const [date, setDate] = useState("2026-06-18"); const [time, setTime] = useState("09:00"); const [type, setType] = useState("Activity"); const [desc, setDesc] = useState("");
    return h(Modal, { icon: "calendar", title: "Add calendar event", onClose,
      footer: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: onClose }, "Cancel"), h(Button, { kind: "primary", icon: "check", onClick: () => { if (!title.trim()) { toast("Add a title", "bad"); return; } onSave({ id: "ev-" + Date.now(), title, date, time, type, desc }); } }, "Add event")) },
      h("div", { style: { display: "flex", flexDirection: "column", gap: 14 } },
        h(Field, { label: "Title", required: true }, h(Input, { value: title, onChange: (e) => setTitle(e.target.value), placeholder: "e.g. Speech & prize-giving day" })),
        h("div", { className: "formgrid" }, h(Field, { label: "Date" }, h(Input, { type: "date", value: date, onChange: (e) => setDate(e.target.value) })), h(Field, { label: "Time" }, h(Input, { type: "time", value: time, onChange: (e) => setTime(e.target.value) }))),
        h(Field, { label: "Type" }, h(Select, { value: type, onChange: (e) => setType(e.target.value) }, D.EVENT_TYPES.map((t) => h("option", { key: t }, t)))),
        h(Field, { label: "Description" }, h(Textarea, { value: desc, onChange: (e) => setDesc(e.target.value) }))));
  }

  /* ---------------- NOTIFICATIONS (73 inbox/compose, 74 prefs) ---------------- */
  function Notifications({ params, navigate, role }) {
    const [tab, setTab] = useState("inbox");
    const [notices, setNotices] = useState(() => D.NOTICES.map((n) => ({ ...n })));
    const [matrix, setMatrix] = useState(() => D.NOTIF_MATRIX.map((m) => ({ ...m })));
    const canCompose = role === "admin" || role === "principal";
    const view = params[0] || tab;

    const tabs = h("div", { className: "seg", style: { marginBottom: 18 } },
      h("button", { className: view === "inbox" ? "on" : "", onClick: () => navigate("notices") }, "Inbox"),
      canCompose && h("button", { className: view === "compose" ? "on" : "", onClick: () => navigate("notices:compose") }, "Compose"),
      h("button", { className: view === "prefs" ? "on" : "", onClick: () => navigate("notices:prefs") }, "Preferences"));

    let inner;
    if (view === "compose" && canCompose) inner = h(Compose, { onSend: () => { toast("Announcement sent"); navigate("notices"); } });
    else if (view === "prefs") inner = h(Prefs, { matrix, setMatrix });
    else inner = h(Inbox, { notices, setNotices });

    const body = h("div", { className: "page-pad", style: { maxWidth: 820 } },
      h(window.PageHead, { eyebrow: "Notifications", title: "Notifications", sub: notices.filter((n) => n.unread).length + " unread" }),
      tabs, inner);
    return h(window.DesktopScreen, { title: "Notifications" }, body);
  }
  function Inbox({ notices, setNotices }) {
    const tone = { Academic: "ok", Meeting: "info", Finance: "warn", Activity: "info" };
    return h("div", { className: "card" }, notices.length === 0
      ? h(EmptyState, { icon: "bell", title: "No notifications" }, "School announcements and alerts will appear here.")
      : notices.map((n, i) => h("div", { key: n.id, onClick: () => setNotices((p) => p.map((x) => x.id === n.id ? { ...x, unread: false } : x)),
          style: { display: "flex", gap: 13, padding: "15px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none", cursor: "pointer", background: n.unread ? "var(--brand-soft)" : "transparent" } },
          h("div", { style: { width: 38, height: 38, borderRadius: 10, flex: "none", display: "grid", placeItems: "center", background: `var(--${tone[n.type] || "info"}-bg)`, color: `var(--${tone[n.type] || "info"}-fg)` } }, h(Icon, { name: n.type === "Finance" ? "card" : n.type === "Meeting" ? "users" : n.type === "Activity" ? "star" : "filetext" })),
          h("div", { style: { flex: 1 } },
            h("div", { style: { display: "flex", justifyContent: "space-between", gap: 10 } }, h("span", { style: { fontWeight: 600, fontSize: 14.5 } }, n.title), h("span", { className: "muted", style: { fontSize: 12, flex: "none" } }, n.time)),
            h("p", { style: { fontSize: 13, color: "var(--ink-600)", margin: "4px 0 8px", lineHeight: 1.5 } }, n.body),
            h("div", { className: "row", style: { gap: 7 } }, h("span", { className: "muted", style: { fontSize: 12 } }, n.from), h("span", { style: { color: "var(--ink-300)" } }, "·"), n.channels.map((c) => h("span", { key: c, className: "tag", style: { fontSize: 10.5 } }, c)))),
          n.unread && h("span", { style: { width: 8, height: 8, borderRadius: 99, background: "var(--brand)", flex: "none", marginTop: 6 } }))));
  }
  function Compose({ onSend }) {
    const [audience, setAudience] = useState("All parents"); const [title, setTitle] = useState(""); const [body, setBody] = useState("");
    const [channels, setChannels] = useState({ inapp: true, email: true, sms: false });
    const audiences = ["All parents", "All staff", "Whole school", "A specific class", "Owing parents"];
    return h("div", { className: "card", style: { padding: 22 } },
      h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
        h(Field, { label: "Audience" }, h(Select, { value: audience, onChange: (e) => setAudience(e.target.value) }, audiences.map((a) => h("option", { key: a }, a)))),
        h(Field, { label: "Title", required: true }, h(Input, { value: title, onChange: (e) => setTitle(e.target.value), placeholder: "Announcement title" })),
        h(Field, { label: "Message" }, h(Textarea, { value: body, onChange: (e) => setBody(e.target.value), placeholder: "Write your announcement…", style: { minHeight: 120 } })),
        h(Field, { label: "Send via", hint: "SMS respects quiet hours (8pm–7am)" }, h("div", { className: "row", style: { gap: 10, flexWrap: "wrap" } },
          [["inapp", "In-app"], ["email", "Email"], ["sms", "SMS"]].map(([k, lbl]) => h("button", { key: k, type: "button", onClick: () => setChannels({ ...channels, [k]: !channels[k] }),
            style: { display: "flex", alignItems: "center", gap: 8, padding: "9px 14px", borderRadius: 10, border: "1px solid " + (channels[k] ? "var(--brand)" : "var(--line)"), background: channels[k] ? "var(--brand-soft)" : "var(--surface)", color: channels[k] ? "var(--brand-strong)" : "var(--ink-600)", fontWeight: 600, fontSize: 13.5 } },
            h("span", { className: "checkbox" + (channels[k] ? " on" : ""), style: { width: 17, height: 17 } }, h(Icon, { name: "check" })), lbl)))),
        channels.sms && 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, "SMS reaches ~248 recipients and uses your SMS credits. Reserved for important notices.")),
        h("div", { style: { display: "flex", justifyContent: "flex-end", gap: 10 } }, h(Button, { kind: "ghost" }, "Save draft"), h(Button, { kind: "primary", icon: "bell", onClick: () => { if (!title.trim()) { toast("Add a title", "bad"); return; } onSend(); } }, "Send announcement"))));
  }
  function Prefs({ matrix, setMatrix }) {
    const toggle = (i, k) => setMatrix((p) => p.map((row, j) => j === i ? { ...row, [k]: !row[k] } : row));
    return h("div", { className: "card" },
      h("div", { className: "card-h" }, h("div", null, h("h3", null, "Notification preferences"), h("div", { className: "sub" }, "Choose how you're notified for each event")), h("span", { className: "muted", style: { fontSize: 12.5 } }, "Quiet hours 8pm–7am")),
      h("div", { className: "tablewrap" }, h("table", { className: "data" },
        h("thead", null, h("tr", null, h("th", null, "Event"), h("th", { style: { textAlign: "center" } }, "In-app"), h("th", { style: { textAlign: "center" } }, "Email"), h("th", { style: { textAlign: "center" } }, "SMS"))),
        h("tbody", null, matrix.map((row, i) => h("tr", { key: row.event, style: { cursor: "default" } },
          h("td", { style: { fontWeight: 500 } }, row.event),
          ["inapp", "email", "sms"].map((k) => h("td", { key: k, style: { textAlign: "center" } }, h("div", { style: { display: "inline-flex" } }, h(Toggle, { on: row[k], onChange: () => toggle(i, k) }))))))))));
  }

  window.Calendar = Calendar;
  window.Notifications = Notifications;
})();
