/* ============================================================
   HALO SMS — Assignments (52 list, 53 create+AI, 54 grade,
   55 submit, 56 feedback)
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;

  const asChip = (st) => st === "published" ? h("span", { className: "chip chip-ok" }, h("span", { className: "d" }), "Published")
    : st === "draft" ? h("span", { className: "chip chip-warn" }, h("span", { className: "d" }), "Draft")
    : h("span", { className: "chip chip-neutral" }, h("span", { className: "d" }), "Closed");

  /* ---------------- LIST (52) ---------------- */
  function AssignmentList({ navigate, list, role }) {
    const isStudent = role === "student";
    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { eyebrow: "Assignments · " + D.STRUCTURE.activeTerm, title: isStudent ? "My assignments" : "Assignments", sub: isStudent ? "Submit your work and see feedback" : "Create, publish and grade",
        actions: !isStudent && h(Button, { kind: "primary", icon: "plus", onClick: () => navigate("assignments:new") }, "Create assignment") }),
      h("div", { className: "grid-2" }, list.map((a) => h("button", { key: a.id, onClick: () => navigate("assignments:" + (isStudent ? "submit:" : "grade:") + a.id), style: { textAlign: "left", border: "none", background: "none", padding: 0 } },
        h("div", { className: "card", style: { padding: 18, height: "100%" } },
          h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10 } },
            h("div", null, h("div", { className: "eyebrow", style: { marginBottom: 6 } }, a.subject + " · " + a.arm), h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 16, letterSpacing: "-0.01em" } }, a.title)),
            asChip(a.state)),
          h("div", { className: "muted", style: { fontSize: 13, margin: "10px 0 14px", lineHeight: 1.5 } }, a.instructions.slice(0, 90) + "…"),
          h("div", { className: "row", style: { justifyContent: "space-between", borderTop: "1px solid var(--line-soft)", paddingTop: 12 } },
            h("span", { className: "row", style: { gap: 7, fontSize: 12.5, color: "var(--ink-500)" } }, h(Icon, { name: "calendar", style: { fontSize: 14 } }), "Due " + new Date(a.due).toLocaleDateString("en-NG", { day: "numeric", month: "short" })),
            isStudent ? h("span", { className: "tag" }, a.type) : h("span", { className: "muted", style: { fontSize: 12.5 } }, a.submitted + "/" + a.total + " in · " + a.graded + " graded")))))));
    return h(window.DesktopScreen, { title: "Assignments" }, body);
  }

  /* ---------------- CREATE + AI (53) ---------------- */
  function AssignmentCreate({ navigate, onCreate }) {
    const [arm, setArm] = useState("SS2 Science");
    const [subject, setSubject] = useState(D.subjectsForArm("SS2 Science")[0]);
    const [type, setType] = useState("Theory");
    const [title, setTitle] = useState("");
    const [topic, setTopic] = useState("");
    const [instructions, setInstructions] = useState("");
    const [due, setDue] = useState("2026-06-16");
    const [points, setPoints] = useState("20");
    const [aiBusy, setAiBusy] = useState(false);
    const [ai, setAi] = useState(false);

    function aiDraft() {
      if (!topic.trim()) { toast("Enter a topic for the AI to draft from", "bad"); return; }
      setAiBusy(true);
      setTimeout(() => {
        setTitle(topic.replace(/(^|\s)\S/g, (m) => m.toUpperCase()) + (type === "Objective" ? " — Objective Quiz" : " — Problem Set"));
        setInstructions("This assignment covers " + topic + ". " + (type === "Objective"
          ? "Answer all 15 multiple-choice questions. The quiz is auto-graded on submission; you'll see your score immediately."
          : "Attempt all questions, showing full working where required. Submit as typed text or a clear photo of your workbook. Marks are awarded for method as well as the final answer.") + " Submissions close at 11:59pm on the due date; late work loses 10%.");
        setAi(true); setAiBusy(false); toast("AI draft inserted — review and edit");
      }, 1000);
    }
    function publish(state) {
      if (!title.trim()) { toast("Give the assignment a title", "bad"); return; }
      onCreate({ id: "as-" + Date.now(), arm, subject, type, title, instructions, due, points: Number(points), state, submitted: 0, total: D.rosterForArm(arm, D.students).length || 24, graded: 0 });
      toast(state === "published" ? "Assignment published" : "Saved as draft"); navigate("assignments");
    }
    const body = h("div", { className: "page-pad", style: { maxWidth: 860 } },
      h(window.PageHead, { back: { label: "Back to assignments", onClick: () => navigate("assignments") }, eyebrow: "New assignment", title: "Create assignment",
        actions: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: () => publish("draft") }, "Save draft"), h(Button, { kind: "primary", icon: "check", onClick: () => publish("published") }, "Publish")) }),
      h("div", { className: "card", style: { padding: "4px 24px" } },
        h(window.FSection, { step: "01", title: "Basics", desc: "Which class, subject and type of assignment." },
          h("div", { className: "formgrid" },
            window.Fld("Class / arm", {}, h(Select, { value: arm, onChange: (e) => { setArm(e.target.value); setSubject(D.subjectsForArm(e.target.value)[0]); } }, ["JSS 1A", "JSS 2B", "Primary 4", "SS2 Science", "SS3 Arts"].map((a) => h("option", { key: a }, a)))),
            window.Fld("Subject", {}, h(Select, { value: subject, onChange: (e) => setSubject(e.target.value) }, D.subjectsForArm(arm).map((s) => h("option", { key: s }, s)))),
            window.Fld("Type", {}, h(Segmented, { value: type, onChange: setType, options: [{ value: "Theory", label: "Theory" }, { value: "Objective", label: "Objective" }] })),
            window.Fld("Due date", {}, h(Input, { type: "date", value: due, onChange: (e) => setDue(e.target.value) })),
            window.Fld("Points", {}, h(Input, { value: points, onChange: (e) => setPoints(e.target.value.replace(/[^0-9]/g, "")) })))),
        h(window.FSection, { step: "02", title: "Draft with AI", desc: "Enter a topic and let AI draft a title + instructions. You stay in control — edit anything before publishing." },
          h("div", null,
            h("div", { className: "row", style: { gap: 10, alignItems: "flex-end" } },
              h("div", { style: { flex: 1 } }, h(Field, { label: "Topic" }, h(Input, { value: topic, onChange: (e) => setTopic(e.target.value), placeholder: "e.g. photosynthesis and the leaf" }))),
              h(Button, { kind: "ghost", icon: "star", disabled: aiBusy, onClick: aiDraft }, aiBusy ? "Drafting…" : "AI draft")))),
        h(window.FSection, { step: "03", title: "Content", desc: "The title and instructions students will see." },
          h("div", { style: { display: "flex", flexDirection: "column", gap: 14 } },
            window.Fld("Title", { req: true }, h(Input, { value: title, onChange: (e) => { setTitle(e.target.value); setAi(false); } })),
            h(Field, { label: "Instructions", hint: ai ? null : "What students must do" }, h(React.Fragment, null,
              ai && h("span", { className: "chip chip-info", style: { marginBottom: 8 } }, h(Icon, { name: "star" }), "AI suggested — review before publishing"),
              h(Textarea, { value: instructions, onChange: (e) => { setInstructions(e.target.value); setAi(false); }, style: { minHeight: 130 } }))))),
        h("div", { style: { display: "flex", justifyContent: "flex-end", gap: 10, padding: "18px 0" } },
          h(Button, { kind: "ghost", onClick: () => publish("draft") }, "Save draft"), h(Button, { kind: "primary", icon: "check", onClick: () => publish("published") }, "Publish"))));
    return h(window.DesktopScreen, { title: "Create assignment" }, body);
  }

  /* ---------------- GRADE (54) ---------------- */
  function AssignmentGrade({ assignment: a, navigate, students }) {
    const roster = D.rosterForArm(a.arm, students);
    const rnd = D.seeded(a.id + "grade");
    const subs = roster.map((s, i) => ({ s, submitted: i < a.submitted, late: rnd() < 0.15, score: null }));
    const [sel, setSel] = useState(subs.find((x) => x.submitted)?.s.id);
    const [scores, setScores] = useState({});
    const [aiBusy, setAiBusy] = useState(null);
    const cur = subs.find((x) => x.s.id === sel);
    const objective = a.type === "Objective";

    function aiSuggest(id) { setAiBusy(id); setTimeout(() => { setScores((p) => ({ ...p, [id]: { score: Math.round(a.points * (0.6 + rnd() * 0.35)), ai: true, feedback: "Solid attempt. Working is mostly clear; tighten the final step and state units. Good understanding of the core method." } })); setAiBusy(null); toast("AI suggested a grade — confirm or adjust"); }, 900); }

    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { back: { label: "All assignments", onClick: () => navigate("assignments") }, eyebrow: a.subject + " · " + a.arm, title: a.title, sub: a.submitted + " of " + a.total + " submitted · " + a.points + " pts" }),
      objective
        ? h("div", { className: "card" },
            h("div", { className: "card-h" }, h("h3", null, "Objective — auto-graded"), h("span", { className: "chip chip-ok" }, h(Icon, { name: "check" }), "Auto")),
            h("div", { className: "tablewrap" }, h("table", { className: "data" },
              h("thead", null, h("tr", null, h("th", null, "Student"), h("th", { className: "num" }, "Score"), h("th", { className: "num" }, "%"), h("th", null, "Status"))),
              h("tbody", null, subs.filter((x) => x.submitted).map(({ s }) => { const sc = Math.round(a.points * (0.5 + D.seeded(s.id + a.id)() * 0.5)); return 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", style: { fontWeight: 700 } }, sc + "/" + a.points),
                h("td", { className: "num" }, Math.round(sc / a.points * 100) + "%"),
                h("td", null, h("span", { className: "chip chip-ok" }, h("span", { className: "d" }), "Graded"))); })))))
        : h("div", { style: { display: "grid", gridTemplateColumns: "280px 1fr", gap: 16, alignItems: "start" }, className: "det-cols" },
            h("div", { className: "card" }, h("div", { className: "card-h", style: { padding: "12px 16px" } }, h("h3", { style: { fontSize: 14 } }, "Submissions")),
              h("div", { style: { maxHeight: 460, overflowY: "auto" }, className: "scroll" }, subs.map(({ s, submitted, late }, i) => h("button", { key: s.id, onClick: () => submitted && setSel(s.id), disabled: !submitted,
                style: { display: "flex", alignItems: "center", gap: 10, padding: "11px 16px", width: "100%", textAlign: "left", border: "none", borderTop: i ? "1px solid var(--line-soft)" : "none", background: sel === s.id ? "var(--brand-soft)" : "transparent", opacity: submitted ? 1 : 0.5 } },
                h(Avatar, { name: s.first + " " + s.surname, size: 30 }),
                h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13, color: sel === s.id ? "var(--brand-strong)" : "inherit" } }, s.surname + ", " + s.first), h("div", { className: "muted", style: { fontSize: 11 } }, submitted ? (late ? "Submitted late" : "Submitted") : "Not submitted")),
                scores[s.id] ? h("span", { className: "chip chip-ok" }, scores[s.id].score) : submitted ? h("span", { className: "tag" }, "Grade") : null))) ),
            !cur ? h("div", { className: "card", style: { padding: 40 } }, h(EmptyState, { icon: "clipboard", title: "Select a submission" }, "Pick a student who has submitted to grade their work."))
            : h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
                h("div", { className: "card", style: { padding: 18 } },
                  h("div", { className: "row", style: { gap: 12, marginBottom: 14 } }, h(Avatar, { name: cur.s.first + " " + cur.s.surname, size: 40, variant: "brand" }), h("div", null, h("div", { style: { fontWeight: 700, fontSize: 15 } }, cur.s.first + " " + cur.s.surname), h("div", { className: "muted", style: { fontSize: 12.5 } }, cur.late ? "Submitted late" : "Submitted on time"))),
                  h("div", { style: { padding: 14, borderRadius: 11, background: "var(--surface-2)", fontSize: 13.5, lineHeight: 1.6, color: "var(--ink-700)" } },
                    h("div", { className: "eyebrow", style: { marginBottom: 7 } }, "Submitted work"),
                    "Answer: The quadratic factorises to (x − 3)(x + 5) = 0, giving x = 3 or x = −5. I checked by expanding back to x² + 2x − 15. ",
                    h("div", { style: { marginTop: 10, display: "flex", gap: 8 } }, h("span", { className: "tag" }, h(Icon, { name: "camera" }), " workbook_p3.jpg"), h("span", { className: "tag" }, h(Icon, { name: "camera" }), " workbook_p4.jpg")))),
                h("div", { className: "card", style: { padding: 18 } },
                  h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 } }, h("h3", { style: { fontSize: 15 } }, "Grade & feedback"), h(Button, { kind: "ghost", size: "sm", icon: "star", disabled: aiBusy === cur.s.id, onClick: () => aiSuggest(cur.s.id) }, aiBusy === cur.s.id ? "Analysing…" : "AI suggest")),
                  (scores[cur.s.id] && scores[cur.s.id].ai) && h("span", { className: "chip chip-info", style: { marginBottom: 10 } }, h(Icon, { name: "star" }), "AI suggested — confirm or adjust"),
                  h("div", { className: "row", style: { gap: 12, marginBottom: 12 } }, h(Field, { label: "Score" }, h("div", { className: "row", style: { gap: 8 } }, h(Input, { value: scores[cur.s.id] ? String(scores[cur.s.id].score) : "", onChange: (e) => setScores((p) => ({ ...p, [cur.s.id]: { ...(p[cur.s.id] || {}), score: Number(e.target.value.replace(/[^0-9]/g, "")), ai: false } })), style: { width: 90 } }), h("span", { className: "muted" }, "/ " + a.points)))),
                  h(Field, { label: "Feedback" }, h(Textarea, { value: scores[cur.s.id] ? scores[cur.s.id].feedback || "" : "", onChange: (e) => setScores((p) => ({ ...p, [cur.s.id]: { ...(p[cur.s.id] || {}), feedback: e.target.value, ai: false } })), placeholder: "Comments for the student…", style: { minHeight: 90 } })),
                  h(Button, { kind: "primary", icon: "check", style: { marginTop: 12 }, onClick: () => toast("Grade confirmed & returned to " + cur.s.first) }, "Confirm & return"))) ));
    return h(window.DesktopScreen, { title: "Grade assignment" }, body);
  }

  /* ---------------- STUDENT SUBMIT (55) + FEEDBACK (56) ---------------- */
  function AssignmentSubmit({ assignment: a, navigate }) {
    const [text, setText] = useState("");
    const [files, setFiles] = useState([]);
    const [done, setDone] = useState(a.id === "as-04"); // closed one already graded
    const graded = a.id === "as-04";

    if (graded) return h("div", { className: "familywrap", style: { maxWidth: 480, margin: "0 auto", padding: "20px 16px" } },
      h(Button, { kind: "quiet", icon: "arrowleft", onClick: () => navigate("assignments"), style: { marginBottom: 12 } }, "Back"),
      h("div", { className: "card", style: { padding: 20, marginBottom: 14 } },
        h("div", { className: "eyebrow", style: { marginBottom: 6 } }, a.subject), h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 18 } }, a.title),
        h("div", { className: "row", style: { gap: 8, marginTop: 12 } }, h("span", { className: "chip chip-ok" }, h(Icon, { name: "check" }), "Graded"))),
      h("div", { className: "card", style: { padding: 20, textAlign: "center", marginBottom: 14 } },
        h("div", { className: "eyebrow" }, "Your score"), h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 44, color: "var(--ok-fg)", margin: "6px 0" } }, "22", h("span", { style: { fontSize: 22, color: "var(--ink-400)" } }, "/25"))),
      h("div", { className: "card", style: { padding: 18 } }, h("div", { className: "eyebrow", style: { marginBottom: 8 } }, "Teacher's feedback"),
        h("p", { style: { fontSize: 14, lineHeight: 1.6 } }, "Excellent lab report — clear diagrams and a well-reasoned conclusion. Next time, quantify the experimental error. Well done."),
        h("div", { className: "muted", style: { fontSize: 12, marginTop: 10, fontFamily: "var(--fs-mono)" } }, "— Mr. Bello")));

    if (done) return h("div", { className: "familywrap", style: { maxWidth: 480, margin: "0 auto", padding: "20px 16px" } },
      h("div", { className: "card", style: { padding: 30, textAlign: "center" } },
        h("div", { style: { width: 54, height: 54, borderRadius: 15, background: "var(--ok-bg)", color: "var(--ok-fg)", display: "grid", placeItems: "center", fontSize: 26, margin: "0 auto 14px" } }, h(Icon, { name: "check" })),
        h("h2", { style: { fontSize: 20 } }, "Submitted!"), h("p", { className: "muted", style: { fontSize: 14, marginTop: 8, lineHeight: 1.55 } }, "Your work for “" + a.title + "” is in. You'll see your grade and feedback here once " + a.subject + " is marked."),
        h(Button, { kind: "primary", block: true, style: { marginTop: 18 }, onClick: () => navigate("assignments") }, "Back to assignments")));

    return h("div", { className: "familywrap", style: { maxWidth: 480, margin: "0 auto", padding: "20px 16px" } },
      h(Button, { kind: "quiet", icon: "arrowleft", onClick: () => navigate("assignments"), style: { marginBottom: 12 } }, "Back"),
      h("div", { className: "card", style: { padding: 20, marginBottom: 14 } },
        h("div", { className: "eyebrow", style: { marginBottom: 6 } }, a.subject + " · due " + new Date(a.due).toLocaleDateString("en-NG", { day: "numeric", month: "short" })),
        h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 19 } }, a.title),
        h("p", { style: { fontSize: 14, lineHeight: 1.6, marginTop: 10, color: "var(--ink-700)" } }, a.instructions)),
      h("div", { className: "card", style: { padding: 18 } },
        h(Field, { label: "Your answer" }, h(Textarea, { value: text, onChange: (e) => setText(e.target.value), placeholder: "Type your answer here…", style: { minHeight: 120 } })),
        h("div", { style: { marginTop: 14 } }, h(Field, { label: "Attach photos", hint: "Snap your workbook" },
          h("div", { className: "row", style: { gap: 8, flexWrap: "wrap" } }, files.map((f) => h("span", { key: f, className: "tag" }, h(Icon, { name: "camera" }), " " + f)),
            h("button", { className: "btn btn-ghost btn-sm", onClick: () => setFiles([...files, "photo_" + (files.length + 1) + ".jpg"]) }, h(Icon, { name: "camera" }), "Add photo")))),
        h(Button, { kind: "primary", block: true, size: "lg", icon: "check", style: { marginTop: 16 }, disabled: !text && files.length === 0, onClick: () => { setDone(true); toast("Assignment submitted"); } }, "Submit assignment")));
  }

  function Assignments({ params, navigate, students, role }) {
    const [list, setList] = useState(() => D.ASSIGNMENTS.map((a) => ({ ...a })));
    const visible = role === "student" ? list.filter((a) => a.state !== "draft") : list;
    const [p0, p1] = params;
    if (p0 === "new") return h(AssignmentCreate, { navigate, onCreate: (a) => setList((p) => [a, ...p]) });
    if (p0 === "grade") { const a = list.find((x) => x.id === p1); return a ? h(AssignmentGrade, { assignment: a, navigate, students }) : h(AssignmentList, { navigate, list: visible, role }); }
    if (p0 === "submit") { const a = list.find((x) => x.id === p1); return a ? h(AssignmentSubmit, { assignment: a, navigate }) : h(AssignmentList, { navigate, list: visible, role }); }
    if (role === "student") return h(AssignmentList, { navigate, list: visible, role });
    return h(AssignmentList, { navigate, list: visible, role });
  }

  window.Assignments = Assignments;
  window.AssignmentSubmit = AssignmentSubmit;
})();
