/* ============================================================
   HALO SMS — Report Sheet (the signature element)
   Shared render: principal / class teacher / parent / student.
   ============================================================ */
(function () {
  const { h } = window.HReact;
  const D = window.HALO;

  // synthesise a subject set for students without authored result data
  function synth(student) {
    const base = student.avg || 70;
    const names = student.cls.startsWith("SS")
      ? (student.department === "Arts"
        ? ["English Language","Mathematics","Literature","Government","Economics","C.R.S.","History","Geography"]
        : ["English Language","Mathematics","Physics","Chemistry","Biology","Further Maths","Geography","Agric. Science"])
      : ["Mathematics","English Language","Basic Science","Civic Education","Social Studies","Computer Studies","Agric. Science","C.R.S.","Cultural & Creative Arts"];
    let seed = student.id.charCodeAt(student.id.length - 1);
    const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
    return {
      studentId: student.id, term: D.term, session: D.session, state: student.results,
      subjects: names.map((n, i) => {
        const total = Math.max(38, Math.min(95, Math.round(base + (rnd() * 22 - 11))));
        const exam = Math.round(total * 0.6), ca = total - exam, ca1 = Math.round(ca / 2), ca2 = ca - ca1;
        const [grade, remark] = D.gradeOf(total);
        return { name: n, ca1, ca2, exam, total, grade, remark, pos: (i % 9) + 1, avg: Math.round((base - 4) * 10) / 10 };
      }),
      affective: [["Punctuality",4],["Neatness",4],["Politeness",5],["Honesty",4],["Attentiveness",4],["Leadership",3]],
      psychomotor: [["Handwriting",4],["Sports",4],["Drawing & Painting",3],["Music",4],["Handling Tools",4]],
      attendance: { present: 56, total: 62 },
      classTeacherRemark: "A capable student who applies effort consistently. With sustained focus, even stronger results are within reach.",
      principalRemark: "A good result. Well done.",
    };
  }
  function resultFor(student) {
    if (student.id === "st-142") return D.resultPublished;
    if (student.id === "st-148") return D.resultDraft;
    return synth(student);
  }

  function Rating({ value }) {
    return h("span", { style: { display: "inline-flex", gap: 3 } },
      [1,2,3,4,5].map((n) => h("span", { key: n, style: { width: 9, height: 9, borderRadius: 2,
        background: value ? (n <= value ? "var(--brand)" : "var(--surface-3)") : "var(--surface-3)" } })));
  }

  function ReportSheet({ student, onBack, role }) {
    const r = resultFor(student);
    const draft = r.state !== "published";
    const valid = r.subjects.filter((s) => !s.absent && s.total != null);
    const termAvg = valid.length ? Math.round((valid.reduce((a, s) => a + s.total, 0) / valid.length) * 10) / 10 : null;
    const overall = termAvg != null ? D.gradeOf(termAvg)[0][0] : "—";
    const cum = termAvg != null ? Math.round((termAvg - 1.6) * 10) / 10 : null;
    const spine = draft ? "var(--warn)" : "var(--ok)";
    const fullName = [student.surname, student.first, student.middle].filter(Boolean).join(" ");

    return h("div", { className: "page-pad", style: { maxWidth: 920 } },
      h("div", { className: "wrap-actions noprint", style: { justifyContent: "space-between", marginBottom: 18 } },
        h(Button, { kind: "quiet", icon: "arrowleft", onClick: onBack }, "Back to student"),
        h("div", { className: "row" },
          draft && h("span", { className: "chip chip-warn" }, h("span", { className: "d" }), "Draft — not visible to parents"),
          h(Button, { kind: "ghost", icon: "printer", onClick: () => window.print() }, "Print / PDF"))),

      h("div", { className: "report-sheet card", style: { position: "relative", overflow: "hidden", boxShadow: "var(--shadow-lg)" } },
        h("div", { style: { position: "absolute", left: 0, top: 0, bottom: 0, width: 7, background: spine } }),
        // header
        h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 18, padding: "26px 30px 18px 34px" } },
          h("div", { style: { display: "flex", gap: 14, alignItems: "center" } },
            h("div", { className: "logo", style: { width: 48, height: 48, fontSize: 21, borderRadius: 13 } }, D.BRANDS[document.documentElement.getAttribute("data-brand")].short),
            h("div", null,
              h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 20, letterSpacing: "-0.02em" } }, D.BRANDS[document.documentElement.getAttribute("data-brand")].name),
              h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 2 } }, D.BRANDS[document.documentElement.getAttribute("data-brand")].motto))),
          h("div", { style: { textAlign: "right" } },
            h("div", { className: "eyebrow" }, "Terminal Report Sheet"),
            h("div", { style: { fontSize: 13, marginTop: 4, fontWeight: 500 } }, r.session + " · " + r.term),
            h("div", { style: { marginTop: 8 } }, h(StatusChip, { state: draft ? "draft" : "published" })))),
        h("div", { className: "divider" }),
        // student strip
        h("div", { style: { display: "flex", alignItems: "center", gap: 18, padding: "18px 30px 18px 34px", flexWrap: "wrap" } },
          h(Avatar, { name: student.first + " " + student.surname, size: 56 }),
          h("div", { style: { flex: 1, minWidth: 180 } },
            h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 23, letterSpacing: "-0.02em" } }, fullName),
            h("div", { className: "muted", style: { fontSize: 13, marginTop: 3 } },
              h("span", { className: "mono" }, student.adm), " · ", student.cls, student.department !== "—" ? " · " + student.department : "")),
          h("div", { style: { display: "flex", gap: 26 } },
            [["Class size", student.ofN], ["Age", ageOf(student.dob)], ["Gender", student.gender]].map(([k, v]) =>
              h("div", { key: k, className: "kv" }, h("span", { className: "k" }, k), h("span", { className: "v" }, v))))),
        // subjects table
        h("div", { className: "tablewrap" },
          h("table", { className: "data", style: { minWidth: 640 } },
            h("thead", null, h("tr", null,
              ["Subject","CA1 /20","CA2 /20","Exam /60","Total","Grade","Pos.","Class avg","Remark"].map((c, i) =>
                h("th", { key: c, className: i >= 1 && i <= 7 ? "num" : "" }, c)))),
            h("tbody", null, r.subjects.map((s, i) =>
              h("tr", { key: i, style: { cursor: "default" } },
                h("td", { style: { fontWeight: 600 } }, s.name),
                s.absent
                  ? h(React.Fragment, null,
                      h("td", { className: "num muted", colSpan: 3, style: { textAlign: "center", fontStyle: "italic" } }, "Absent"),
                      h("td", { className: "num muted" }, "—"))
                  : h(React.Fragment, null,
                      h("td", { className: "num" }, s.ca1), h("td", { className: "num" }, s.ca2),
                      h("td", { className: "num" }, s.exam),
                      h("td", { className: "num", style: { fontWeight: 700 } }, s.total)),
                h("td", { className: "num", style: { fontWeight: 700, color: s.absent ? "var(--ink-400)" : (s.total >= 75 ? "var(--ok-fg)" : s.total < 50 ? "var(--bad-fg)" : "inherit") } }, s.grade),
                h("td", { className: "num muted" }, s.pos === "—" ? "—" : ordinal(s.pos)),
                h("td", { className: "num muted" }, s.absent ? "—" : s.avg),
                h("td", { className: "muted", style: { fontSize: 13 } }, s.remark))))),
        // summary band
        h("div", { style: { display: "flex", gap: 14, padding: "18px 30px 18px 34px", background: "var(--surface-2)", borderTop: "1px solid var(--line)", flexWrap: "wrap" } },
          summ("Term average", termAvg == null ? "—" : termAvg.toFixed(1), draft),
          summ("Position", student.position ? ordinal(student.position) : "—", false, student.ofN ? "of " + student.ofN : ""),
          summ("Cumulative avg", cum == null ? "—" : cum.toFixed(1), false),
          h("div", { style: { flex: 1 } }),
          h("div", { style: { textAlign: "center", minWidth: 88 } },
            h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 42, lineHeight: 1, color: draft ? "var(--ink-400)" : "var(--ok-fg)" } }, draft ? "··" : overall),
            h("div", { className: "eyebrow", style: { marginTop: 6 } }, "Overall grade"))),
        // affective / psychomotor / attendance
        !draft && h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 0, borderTop: "1px solid var(--line)" }, className: "rep-grids" },
          ratingCol("Affective traits", r.affective),
          ratingCol("Psychomotor skills", r.psychomotor),
          h("div", { style: { padding: "18px 24px" } },
            h("div", { className: "eyebrow", style: { marginBottom: 12 } }, "Attendance"),
            h("div", { style: { display: "flex", alignItems: "baseline", gap: 8 } },
              h("span", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 30 }, className: "tnum" }, r.attendance.present),
              h("span", { className: "muted", style: { fontSize: 14 } }, "of " + r.attendance.total + " days")),
            h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 6 } }, Math.round(r.attendance.present / r.attendance.total * 100) + "% present this term"),
            h("div", { style: { marginTop: 16 } }, h("div", { className: "eyebrow", style: { marginBottom: 8 } }, "Rating key"),
              h("div", { className: "muted", style: { fontSize: 12, lineHeight: 1.7 } }, "5 Excellent · 4 Good · 3 Fair · 2 Weak · 1 Poor")))),
        // remarks
        !draft && h("div", { style: { borderTop: "1px solid var(--line)", padding: "20px 30px 24px 34px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }, className: "rep-remarks" },
          remark("Class teacher's remark", r.classTeacherRemark, "Mrs. Ngozi Eze"),
          remark("Principal's remark", r.principalRemark, "Mr. Adewale Okonkwo")),
        draft && h("div", { style: { borderTop: "1px solid var(--line)", padding: "20px 34px" } },
          h("div", { className: "consequence" }, h("span", { className: "ic" }, h(Icon, { name: "info" })),
            h("div", null, h("b", null, "This result is still a draft."), " Scores for some subjects are missing or marked absent, and affective/attendance summaries appear only once published. Parents and students cannot see it yet."))))));
  }

  function summ(k, v, dim, suf) {
    return h("div", { className: "kv", style: { minWidth: 92 } },
      h("span", { className: "k" }, k),
      h("span", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 26, letterSpacing: "-0.01em", color: dim ? "var(--ink-400)" : "inherit" }, className: "tnum" },
        v, suf && h("span", { style: { fontSize: 14, fontWeight: 500, color: "var(--ink-500)", fontFamily: "var(--fs-body)" } }, " " + suf)));
  }
  function ratingCol(title, rows) {
    return h("div", { style: { padding: "18px 24px", borderRight: "1px solid var(--line)" } },
      h("div", { className: "eyebrow", style: { marginBottom: 12 } }, title),
      h("div", { style: { display: "flex", flexDirection: "column", gap: 9 } },
        rows.map(([k, v]) => h("div", { key: k, style: { display: "flex", justifyContent: "space-between", alignItems: "center" } },
          h("span", { style: { fontSize: 13 } }, k), h(Rating, { value: v })))));
  }
  function remark(title, text, who) {
    return h("div", null,
      h("div", { className: "eyebrow", style: { marginBottom: 8 } }, title),
      h("div", { style: { fontSize: 14, lineHeight: 1.6, fontStyle: text ? "normal" : "italic", color: text ? "inherit" : "var(--ink-400)" } }, text || "Awaiting remark"),
      h("div", { className: "muted", style: { fontSize: 12, marginTop: 8, fontFamily: "var(--fs-mono)" } }, "— " + who));
  }
  function ordinal(n) { const s = ["th","st","nd","rd"], v = n % 100; return n + (s[(v - 20) % 10] || s[v] || s[0]); }
  function ageOf(dob) { return Math.floor((Date.now() - new Date(dob)) / 3.156e10) + " yrs"; }

  window.ReportSheet = ReportSheet;
  window.resultFor = resultFor;
})();
