/* ============================================================
   Screen: Attendance — weekly homeroom register
   ============================================================ */
(function () {
  const DB = window.DB;
  const CODES = {
    P: { label: "Present", color: "var(--stable)", soft: "var(--stable-soft)", line: "var(--stable-line)" },
    L: { label: "Late", color: "oklch(0.5 0.15 55)", soft: "var(--watch-soft)", line: "var(--watch-line)" },
    A: { label: "Absent", color: "var(--critical)", soft: "var(--critical-soft)", line: "var(--critical-line)" },
    E: { label: "Excused", color: "var(--info)", soft: "oklch(0.95 0.03 230)", line: "oklch(0.84 0.07 230)" },
    S: { label: "School activity", color: "oklch(0.5 0.14 300)", soft: "oklch(0.95 0.03 300)", line: "oklch(0.85 0.07 300)" },
  };
  const ORDER = ["P", "L", "A", "E", "S"];
  const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri"];
  const WEEKS = [
    { id: "w8", label: "2 – 6 Jun", sub: "Week 8 · current" },
    { id: "w7", label: "26 – 30 May", sub: "Week 7" },
    { id: "w6", label: "19 – 23 May", sub: "Week 6" },
  ];
  const NOTES = {
    "S-101": "Parent contacted re: Monday absence — no response yet.",
    "S-102": "Morning check-in plan active (behaviour contract).",
    "S-105": "Medical appointments Tue/Thu — excused, on file.",
  };

  // deterministic mark per student/week/session (FNV-1a hash for good spread)
  function gen(sid, weekId, i) {
    const att = DB.student(sid).attendance;
    const str = sid + "|" + weekId + "|" + i;
    let h = 2166136261;
    for (let k = 0; k < str.length; k++) { h ^= str.charCodeAt(k); h = Math.imul(h, 16777619) >>> 0; }
    const r = h % 100;
    if (att >= 93) return r < 90 ? "P" : r < 96 ? "L" : "S";
    if (att >= 85) return r < 74 ? "P" : r < 85 ? "L" : r < 93 ? "S" : "A";
    return r < 52 ? "P" : r < 68 ? "L" : r < 84 ? "A" : r < 93 ? "E" : "S";
  }

  function Attendance({ role }) {
    const teacher = role === "teacher";
    const [cls, setCls] = React.useState(teacher ? "C" : "A");
    const [week, setWeek] = React.useState("w8");
    const [edits, setEdits] = React.useState({});
    const [noteFor, setNoteFor] = React.useState(null);

    const students = DB.STUDENTS.filter((s) => s.cls === cls);
    const key = (sid, i) => sid + "-" + week + "-" + i;
    const mark = (sid, i) => edits[key(sid, i)] || gen(sid, week, i);
    const cycle = (sid, i) => {
      const cur = mark(sid, i); const next = ORDER[(ORDER.indexOf(cur) + 1) % ORDER.length];
      setEdits((e) => ({ ...e, [key(sid, i)]: next }));
    };

    // weekly stats
    const sessions = DAYS.length * 2;
    const rowStats = (sid) => {
      let p = 0, a = 0, l = 0;
      for (let i = 0; i < sessions; i++) { const m = mark(sid, i); if (m === "P" || m === "S") p++; if (m === "A") a++; if (m === "L") l++; }
      return { pct: Math.round((p / sessions) * 100), a, l };
    };
    const totals = students.reduce((acc, s) => { const r = rowStats(s.id); acc.pct += r.pct; acc.a += r.a; acc.l += r.l; return acc; }, { pct: 0, a: 0, l: 0 });
    const avgPct = Math.round(totals.pct / students.length);
    const wIdx = WEEKS.findIndex((w) => w.id === week);

    return (
      <div className="screen">
        <div className="between" style={{ marginBottom: 16 }}>
          <div>
            <h2 style={{ fontSize: 19 }}>{t("Attendance register")}</h2>
            <p className="muted" style={{ fontSize: 13, marginTop: 4 }}>{t("Weekly homeroom register · AM & PM sessions. Click any mark to amend it.")}</p>
          </div>
          <button className="btn btn-sm" onClick={() => window.toast(t("Week register exported (PDF)"))}><Icon name="download" size={14} />{t("Export week")}</button>
        </div>

        {/* toolbar */}
        <div className="toolbar" style={{ marginBottom: 14 }}>
          <div className="seg">
            {["A", "B", "C", "D"].filter((c) => !teacher || c === "C").map((c) => (
              <button key={c} className={cls === c ? "on" : ""} onClick={() => setCls(c)}>{t("Class")} {c}</button>
            ))}
          </div>
          <div className="week-nav">
            <button className="icon-btn" disabled={wIdx >= WEEKS.length - 1} onClick={() => setWeek(WEEKS[Math.min(WEEKS.length - 1, wIdx + 1)].id)}><Icon name="chevronL" size={16} /></button>
            <div className="week-label"><span style={{ fontWeight: 600, fontSize: 13 }}>{WEEKS[wIdx].label}</span><span className="mono faint" style={{ fontSize: 10.5 }}>{t(WEEKS[wIdx].sub)}</span></div>
            <button className="icon-btn" disabled={wIdx <= 0} onClick={() => setWeek(WEEKS[Math.max(0, wIdx - 1)].id)}><Icon name="chevronR" size={16} /></button>
          </div>
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 16 }}>
            <span className="att-stat"><span className="mono" style={{ fontSize: 18, fontWeight: 600, color: avgPct < 90 ? "var(--watch)" : "var(--stable)" }}>{avgPct}%</span><span className="eyebrow">{t("present")}</span></span>
            <span className="att-stat"><span className="mono" style={{ fontSize: 18, fontWeight: 600, color: "var(--critical)" }}>{totals.a}</span><span className="eyebrow">{t("absences")}</span></span>
            <span className="att-stat"><span className="mono" style={{ fontSize: 18, fontWeight: 600, color: "oklch(0.5 0.15 55)" }}>{totals.l}</span><span className="eyebrow">{t("lates")}</span></span>
          </div>
        </div>

        {/* legend */}
        <div className="row wrap" style={{ gap: 14, marginBottom: 14 }}>
          {ORDER.map((c) => (
            <span key={c} className="row" style={{ gap: 6 }}>
              <span className="att-key" style={{ color: CODES[c].color, background: CODES[c].soft, borderColor: CODES[c].line }}>{c}</span>
              <span style={{ fontSize: 11.5, color: "var(--muted)" }}>{t(CODES[c].label)}</span>
            </span>
          ))}
        </div>

        {/* register */}
        <div className="panel" style={{ overflow: "hidden" }}>
          <div style={{ overflowX: "auto" }}>
            <table className="tbl reg-tbl">
              <thead>
                <tr>
                  <th rowSpan="2" style={{ minWidth: 180 }}>{t("Student")}</th>
                  {DAYS.map((d) => <th key={d} colSpan="2" className="reg-day">{t(d)}</th>)}
                  <th rowSpan="2" className="num">{t("Week")}</th>
                  <th rowSpan="2" className="num">{t("Term")}</th>
                  <th rowSpan="2" style={{ width: 44 }}></th>
                </tr>
                <tr>
                  {DAYS.map((d) => [<th key={d + "am"} className="reg-sess">AM</th>, <th key={d + "pm"} className="reg-sess">PM</th>])}
                </tr>
              </thead>
              <tbody>
                {students.map((s) => {
                  const r = rowStats(s.id);
                  const hasNote = NOTES[s.id];
                  return (
                    <tr key={s.id}>
                      <td>
                        <div className="row" style={{ gap: 9 }}>
                          <Avatar name={s.name} color={s.avatar} size={24} />
                          <span style={{ fontWeight: 500, fontSize: 12.5, whiteSpace: "nowrap" }}>{s.name}</span>
                        </div>
                      </td>
                      {Array.from({ length: sessions }).map((_, i) => {
                        const m = mark(s.id, i);
                        return (
                          <td key={i} className="reg-cell">
                            <button className="att-mark" style={{ color: CODES[m].color, background: CODES[m].soft, borderColor: CODES[m].line }} onClick={() => cycle(s.id, i)} title={t(CODES[m].label)}>{m}</button>
                          </td>
                        );
                      })}
                      <td className="num" style={{ color: r.pct < 85 ? "var(--critical)" : r.pct < 92 ? "var(--watch)" : "var(--ink-2)", fontWeight: 600 }}>{r.pct}%</td>
                      <td className="num muted">{s.attendance}%</td>
                      <td style={{ textAlign: "center" }}>
                        <button className={"note-btn" + (hasNote ? " has" : "")} onClick={() => setNoteFor(noteFor === s.id ? null : s.id)} title={hasNote ? t(hasNote) : t("Add note")}>
                          <Icon name="note" size={14} />
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        {/* note popover (inline) */}
        {noteFor ? (
          <div className="note-pop">
            <div className="between" style={{ marginBottom: 8 }}>
              <div className="row" style={{ gap: 8 }}><Avatar name={DB.student(noteFor).name} color={DB.student(noteFor).avatar} size={22} /><b style={{ fontSize: 13 }}>{DB.student(noteFor).name}</b></div>
              <button className="icon-btn" onClick={() => setNoteFor(null)}><Icon name="close" size={16} /></button>
            </div>
            <div className="eyebrow" style={{ marginBottom: 6 }}>{t("Homeroom note")}</div>
            <p style={{ fontSize: 12.5, lineHeight: 1.5 }}>{NOTES[noteFor] ? t(NOTES[noteFor]) : t("No note recorded for this student this week.")}</p>
          </div>
        ) : null}
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.attendance = Attendance;
})();
