// Teacher Dashboard — clean SaaS, dense
// Two screens: Classes overview, Live session (compact)

const TEACHER_NAV = [
  ["Classes",    I.users,     "/app/teacher"],
  ["Schedule",   I.calendar,  "/app/teacher/schedule"],
  ["Attendance", I.check,     "/app/teacher/attendance"],
  ["Content",    I.video,     "/app/teacher/content"],
  ["Quizzes",    I.puzzle,    "/app/teacher/quizzes"],
  ["Homework",   I.book,      "/app/teacher/homework"],
  ["Award XP",   I.star,      "/app/teacher/xp"],
  ["Analytics",  I.chart,     "/app/teacher/analytics"],
  ["Messages",   I.send,      "/app/teacher/messages"],
];

const TeacherSidebar = ({ active = "/app/teacher", go, session }) => (
  <div style={{
    width: 200, padding: 18, borderRight: "var(--border-thin)",
    background: "var(--paper-card)", display: "flex", flexDirection: "column", gap: 16,
    flexShrink: 0,
  }}>
    <div className="display" style={{ fontSize: 18, letterSpacing: "-0.03em" }}>
      <span style={{ color: "var(--coral)" }}>Epiq</span>Minds
      <span style={{ color: "var(--ink-mute)", fontSize: 11, marginLeft: 6, fontWeight: 500 }}>educator</span>
    </div>
    <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
      {TEACHER_NAV.map(([label, ic, path]) => (
        <button key={label} onClick={() => go && go(path)} style={{
          display: "flex", alignItems: "center", gap: 10,
          padding: "8px 10px", borderRadius: 10, border: "none",
          background: active === path ? "var(--paper-deep)" : "transparent",
          color: active === path ? "var(--ink)" : "var(--ink-soft)",
          fontWeight: active === path ? 700 : 500,
          fontSize: 13, cursor: "pointer", textAlign: "left",
        }}>
          {ic({ size: 16 })} {label}
        </button>
      ))}
    </div>
    <div style={{ flex: 1 }}/>
    <div className="card-flat" style={{ padding: 10, fontSize: 12 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <Avatar name={(session?.name || "T")[0]} color="var(--coral)" size={28}/>
        <div>
          <div style={{ fontWeight: 700, fontSize: 12 }}>{session?.name || "Teacher"}</div>
          <div style={{ fontSize: 10, color: "var(--ink-mute)" }}>{session?.email || "educator"}</div>
        </div>
      </div>
    </div>
  </div>
);

const TeacherHome = ({ dark = false, go, session }) => {
  const tid = session?.teacherId;
  const { data: dash, loading, refetch } = useApi(tid ? `/teacher/dashboard/${tid}` : "/teacher/dashboard/0", {});
  const [localSessions, setLocalSessions] = React.useState(null);
  const [statusChanging, setStatusChanging] = React.useState(null);
  const [viewRemarks, setViewRemarks] = React.useState(null);
  const teacher   = dash.teacher   || {};
  const stats     = dash.stats     || {};
  const rawSessions = localSessions ?? (dash.todaySessions || []);
  const grading   = dash.gradingQueue  || [];
  const batches   = dash.batches       || [];
  const today = new Date().toISOString().slice(0, 10);
  const todayLabel = new Date().toLocaleDateString("en-GB", { weekday:"short", day:"numeric", month:"short" });
  const todaySessions = rawSessions.filter(s => s.day === today);

  const [doneSession, setDoneSession] = React.useState(null);
  const [doneRemarks, setDoneRemarks] = React.useState("");
  const [doneSaving, setDoneSaving]   = React.useState(false);
  const [doneError, setDoneError]     = React.useState("");

  const markStatus = async (id, status) => {
    setStatusChanging(id);
    await apiFetch(`/schedule/${id}/status`, { method:"PATCH", body: JSON.stringify({ status }) });
    const fresh = await apiFetch(tid ? `/teacher/dashboard/${tid}` : "/teacher/dashboard/0").then(r=>r.json());
    setLocalSessions(fresh.todaySessions || []);
    setStatusChanging(null);
  };

  const submitCompleteSession = async (e) => {
    e.preventDefault();
    if (!doneRemarks.trim()) {
      setDoneError("Completion remarks are required.");
      return;
    }
    setDoneSaving(true);
    setDoneError("");
    try {
      const res = await apiFetch(`/schedule/${doneSession.id}/status`, {
        method: "PATCH",
        body: JSON.stringify({ status: "done", completion_remarks: doneRemarks.trim() }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        setDoneError(d.error || "Failed to mark session as done.");
        setDoneSaving(false);
        return;
      }
      const fresh = await apiFetch(tid ? `/teacher/dashboard/${tid}` : "/teacher/dashboard/0").then(r => r.json());
      setLocalSessions(fresh.todaySessions || []);
      setDoneSession(null);
      setDoneRemarks("");
      setDoneSaving(false);
    } catch {
      setDoneError("Something went wrong updating session status.");
      setDoneSaving(false);
    }
  };

  if (loading) return <Spinner />;
  return (
  <Themed className={dark ? "theme-dark" : ""} style={{ width: "100%", height: "100%", display: "flex" }}>
    <TeacherSidebar active="/app/teacher" go={go} session={session}/>
    <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 12, padding: "12px 22px",
        borderBottom: "var(--border-thin)", background: "var(--paper-card)",
      }}>
        <div>
          <div className="display" style={{ fontSize: 22 }}>Classes</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>{teacher.name || session?.name || "—"} · {todayLabel}</div>
        </div>
        <div style={{ flex: 1 }}/>
        <div className="card-flat" style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 10px", width: 220, background: "var(--paper-deep)" }}>
          {I.search({ size: 14 })}
          <input placeholder="Search students…" style={{ border: "none", outline: "none", background: "transparent", fontSize: 13, fontFamily: "var(--font-ui)", color: "var(--ink)", width: "100%" }}/>
        </div>
        <button className="btn btn-primary" onClick={() => go && go("/app/teacher/schedule")} style={{ padding: "8px 14px" }}>{I.calendar({ size: 14 })} My schedule</button>
      </div>

      <div style={{ padding: 22, background: "var(--paper)", flex: 1, overflow: "auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 18 }}>
          <Stat icon={I.users({ size: 16 })} label="My students" value={stats.totalStudents ?? 0} sub={`across ${stats.batches ?? 0} batches`} accent="var(--coral)"/>
          <Stat icon={I.calendar({ size: 16 })} label="Sessions today" value={todaySessions.length} sub={rawSessions.length + " total this week"} accent="var(--moss)"/>
          <Stat icon={I.book({ size: 16 })} label="Pending grading" value={stats.pendingGrading ?? 0} sub="homework submissions" accent="var(--gold)"/>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18 }}>
          <div className="card-flat" style={{ padding: 18 }}>
            <SectionHead eyebrow={`TODAY · ${todaySessions.length} SESSIONS`} title="Today's Schedule"/>
            {todaySessions.length === 0 ? (
              <div style={{ padding: "32px 0", textAlign: "center", color: "var(--ink-mute)" }}>
                <div style={{ fontSize: 28, marginBottom: 8 }}>🎉</div>
                <div style={{ fontWeight: 700 }}>No classes today</div>
                <div style={{ fontSize: 13, marginTop: 4 }}>Check your full schedule for the week</div>
                <button onClick={() => go && go("/app/teacher/schedule")} className="btn btn-ghost" style={{ marginTop: 12, padding: "6px 14px", fontSize: 12 }}>{I.calendar({ size: 13 })} View schedule</button>
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {todaySessions.map((s, i) => (
                  <div key={s.id || i} className="card-flat" style={{ padding: 14, display: "grid", gridTemplateColumns: "110px 1fr auto", alignItems: "center", gap: 14, borderLeft: `3px solid ${s.status === "live" ? "var(--coral)" : s.status === "done" ? "var(--moss)" : "var(--rule)"}` }}>
                    <div>
                      <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)" }}>{s.status?.toUpperCase()}</div>
                      <div style={{ fontWeight: 700, fontSize: 13 }}>{s.time}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-mute)" }}>–{s.end}</div>
                    </div>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 14 }}>{s.batch}</div>
                      <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{s.course} · {s.students} students</div>
                    </div>
                    <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
                      {s.meet && s.status !== "done" && (
                        <a href={s.meet} target="_blank" rel="noreferrer" className="btn btn-primary" style={{ padding: "6px 14px", fontSize: 12, textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4 }}>
                          {I.play({ size: 13 })} Join class
                        </a>
                      )}
                      {s.status === "done" && (
                        <button className="btn btn-ghost" onClick={() => go && go("/app/teacher/attendance")} style={{ padding: "6px 12px", fontSize: 12 }}>{I.check({ size: 13 })} Attendance</button>
                      )}
                      {s.status === "done" && s.completion_remarks && (
                        <button
                          type="button"
                          onClick={() => setViewRemarks(s)}
                          className="btn btn-ghost"
                          style={{ padding: "6px 12px", fontSize: 12, display: "inline-flex", alignItems: "center", gap: 4 }}
                          title="View completion remarks"
                        >
                          {I.book ? I.book({ size: 12 }) : "📝"} Remarks
                        </button>
                      )}
                      {s.status !== "done" ? (
                        <button
                          disabled={statusChanging === s.id}
                          onClick={() => {
                            setDoneSession(s);
                            setDoneRemarks(s.completion_remarks || "");
                            setDoneError("");
                          }}
                          style={{ padding:"4px 10px", borderRadius:6, border:"1.5px solid var(--moss)", background:"transparent", color:"var(--moss)", cursor:"pointer", fontSize:11, fontWeight:600, opacity: statusChanging===s.id ? .5 : 1 }}
                        >
                          {statusChanging === s.id ? "…" : "✓ Complete"}
                        </button>
                      ) : (
                        <button
                          disabled={statusChanging === s.id}
                          onClick={() => markStatus(s.id, "upcoming")}
                          style={{ padding:"4px 10px", borderRadius:6, border:"1.5px solid var(--rule-bold)", background:"transparent", color:"var(--ink-mute)", cursor:"pointer", fontSize:11, fontWeight:600 }}
                        >
                          Reopen
                        </button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="card-flat" style={{ padding: 18 }}>
              <SectionHead eyebrow="NEEDS YOUR EYES" title="Grading queue"/>
              {grading.filter(g => !g.grade).length === 0 ? (
                <div style={{ padding: "18px 0", textAlign: "center", color: "var(--ink-mute)", fontSize: 13 }}>
                  <div style={{ fontSize: 22, marginBottom: 6 }}>✅</div>
                  All caught up! No pending submissions.
                </div>
              ) : (
                grading.filter(g => !g.grade).slice(0, 5).map((g, i) => (
                  <div key={g.id || i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 0", borderTop: i ? "var(--border-thin)" : "none" }}>
                    <Avatar name={g.student[0]} color={g.color} size={32}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 700, fontSize: 13 }}>{g.student}</div>
                      <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{g.hw} · {g.submitted}</div>
                    </div>
                    <button className="btn btn-ghost" onClick={() => go && go("/app/teacher/homework")} style={{ padding: "4px 10px", fontSize: 11 }}>Open</button>
                  </div>
                ))
              )}
            </div>

            <div className="card-flat" style={{ padding: 18 }}>
              <SectionHead eyebrow="MY BATCHES" title="Overview"/>
              {batches.length === 0 ? (
                <div style={{ padding: "12px 0", color: "var(--ink-mute)", fontSize: 13 }}>No batches assigned yet.</div>
              ) : (
                batches.map((b, i) => (
                  <div key={b.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 0", borderTop: i ? "var(--border-thin)" : "none" }}>
                    <div style={{ width: 36, height: 36, borderRadius: 10, background: ["var(--coral)","var(--sky)","var(--moss)","var(--plum)"][i % 4], display: "grid", placeItems: "center", color: "white", fontWeight: 700, fontSize: 13 }}>{b.name[0]}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 700, fontSize: 13 }}>{b.name}</div>
                      <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{b.course}</div>
                    </div>
                    <span style={{ fontSize: 10, fontWeight: 700, padding: "2px 8px", borderRadius: 999, background: "var(--plum-deep)", color: "white" }}>{b.students} students</span>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
      {doneSession && (
        <Modal title="Complete session" onClose={() => { setDoneSession(null); setDoneError(""); }}>
          <form onSubmit={submitCompleteSession}>
            <div style={{ background: "var(--paper-deep)", border: "var(--border-thin)", borderRadius: 8, padding: 12, marginBottom: 14, fontSize: 13 }}>
              <div style={{ fontWeight: 700, marginBottom: 4 }}>
                {doneSession.batch || "Class"} · {doneSession.day} ({doneSession.time})
              </div>
              <div style={{ color: "var(--ink-soft)", fontSize: 12, lineHeight: 1.5 }}>
                Please provide session completion remarks or a summary of topics covered before marking this session as done.
              </div>
            </div>

            <FormField label="COMPLETION REMARKS *">
              <textarea
                required
                rows={4}
                style={{ width: "100%", padding: "8px 12px", border: "var(--border-thin)", borderRadius: 6, background: "var(--paper-card)", color: "var(--ink)", fontSize: 13, resize: "vertical", boxSizing: "border-box" }}
                value={doneRemarks}
                onChange={e => setDoneRemarks(e.target.value)}
                placeholder="e.g. Completed Chapter 4 exercises, introduced loops. Students completed mini-project."
                autoFocus
              />
            </FormField>

            {doneError && <div style={{ color: "var(--coral)", fontSize: 13, margin: "8px 0" }}>{doneError}</div>}

            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}>
              <button type="button" onClick={() => { setDoneSession(null); setDoneError(""); }} className="btn btn-ghost">
                Cancel
              </button>
              <button type="submit" disabled={doneSaving || !doneRemarks.trim()} className="btn btn-primary" style={{ background: "var(--moss)" }}>
                {doneSaving ? "Saving…" : "Mark as done"}
              </button>
            </div>
          </form>
        </Modal>
      )}
      {viewRemarks && (
        <Modal
          title="Session Completion Remarks"
          onClose={() => setViewRemarks(null)}
        >
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div style={{ background: "var(--paper-deep)", border: "var(--border-thin)", borderRadius: 8, padding: 14 }}>
              <div style={{ fontWeight: 700, fontSize: 15 }}>
                {viewRemarks.batch || "Class"} · {viewRemarks.course || "—"}
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 4 }}>
                <strong>Session date:</strong> {viewRemarks.day} ({viewRemarks.time}–{viewRemarks.end})
              </div>
            </div>

            <FormField label="COMPLETION REMARKS">
              <div style={{
                fontSize: 13,
                color: "var(--ink)",
                lineHeight: 1.6,
                whiteSpace: "pre-wrap",
                background: "var(--paper-card)",
                border: "var(--border-thin)",
                borderRadius: 6,
                padding: "10px 12px",
              }}>
                {viewRemarks.completion_remarks}
              </div>
            </FormField>

            <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
              <button
                type="button"
                onClick={() => setViewRemarks(null)}
                className="btn btn-ghost"
                style={{ padding: "8px 16px", fontSize: 13 }}
              >
                Close
              </button>
            </div>
          </div>
        </Modal>
      )}
  </Themed>
  );
};

// Live launchpad — the teacher's "what's happening now / next" view. Driven by
// real session data + the auto-advancing lifecycle: a class shows as Live during
// its scheduled window with a one-click Join Meet + jump to attendance marking.
const TeacherLive = ({ dark = false, go, session }) => {
  const { data: initSessions, loading } = useApi("/sessions-with-roster");
  const [sessions, setSessions] = React.useState(null);
  const all = Array.isArray(sessions ?? initSessions) ? (sessions ?? initSessions) : [];
  // Poll so a class flips to "live" automatically during its scheduled time.
  React.useEffect(() => {
    const id = setInterval(() => {
      apiFetch("/sessions-with-roster").then(r => r.ok ? r.json() : null).then(d => { if (Array.isArray(d)) setSessions(d); }).catch(() => {});
    }, 45000);
    return () => clearInterval(id);
  }, []);

  const live = all.filter(s => s.status === "live");
  const upcoming = all.filter(s => s.status === "upcoming")
    .sort((a, b) => String(a.day).localeCompare(String(b.day))).slice(0, 8);
  const join = (s) => { if (s.meet) window.open(s.meet, "_blank"); };

  const card = (s, isLive) => (
    <div key={s.id} className="card-flat" style={{ padding: 16, display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap",
      borderLeft: isLive ? "3px solid var(--coral)" : "3px solid transparent" }}>
      <div style={{ flex: 1, minWidth: 180 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <span style={{ fontWeight: 700, fontSize: 15 }}>{s.batch}</span>
          <span className="chip flat" style={{ fontSize: 9, padding: "1px 7px", textTransform: "uppercase",
            background: isLive ? "var(--coral)" : "var(--paper-deep)", color: isLive ? "white" : "var(--ink-mute)" }}>{isLive ? "● live" : "upcoming"}</span>
        </div>
        <div style={{ fontSize: 12, color: "var(--ink-mute)", marginTop: 3 }}>{s.course} · {fmtSessionDate(s.day)} · {s.time}</div>
        <div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 2 }}>{(s.roster || []).length} student{(s.roster || []).length === 1 ? "" : "s"}</div>
      </div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
        {s.meet
          ? <button onClick={() => join(s)} className="btn btn-primary" style={{ padding: "8px 16px", fontSize: 13 }}>{I.play({ size: 14 })} Join Google Meet</button>
          : <span style={{ fontSize: 11, color: "var(--ink-mute)", alignSelf: "center" }}>No meet link</span>}
        <button onClick={() => go && go("/app/teacher/attendance")} className="btn btn-ghost" style={{ padding: "8px 14px", fontSize: 13 }}>{I.check({ size: 14 })} Mark attendance</button>
      </div>
    </div>
  );

  const emptyBox = (text, cta) => (
    <div className="card-flat" style={{ padding: 20, color: "var(--ink-mute)", fontSize: 13 }}>
      {text}{cta && <> <a onClick={() => go && go("/app/teacher/schedule")} style={{ color: "var(--coral)", cursor: "pointer", fontWeight: 700 }}>{cta}</a></>}
    </div>
  );

  return (
    <Themed className={dark ? "theme-dark" : ""} style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 22px", background: "var(--paper-card)", borderBottom: "var(--border-thin)" }}>
        <div>
          <div className="display" style={{ fontSize: 22 }}>Live</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>{live.length} live now · {upcoming.length} upcoming</div>
        </div>
        <div style={{ flex: 1 }}/>
        <button onClick={() => go && go("/app/teacher/schedule")} className="btn btn-ghost" style={{ padding: "6px 12px", fontSize: 12 }}>Schedule</button>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: 22, background: "var(--paper)" }}>
        <div style={{ maxWidth: 820, margin: "0 auto", display: "flex", flexDirection: "column", gap: 18 }}>
          <div>
            <SectionHead eyebrow="HAPPENING NOW" title="Live classes"/>
            {loading && !all.length ? emptyBox("Loading sessions…")
              : live.length ? <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>{live.map(s => card(s, true))}</div>
              : emptyBox("No class is live right now. A class turns “live” automatically during its scheduled time.")}
          </div>
          <div>
            <SectionHead eyebrow="COMING UP" title="Upcoming sessions"/>
            {upcoming.length ? <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>{upcoming.map(s => card(s, false))}</div>
              : emptyBox("No upcoming sessions.", "Schedule one →")}
          </div>
        </div>
      </div>
    </Themed>
  );
};

// ── Teacher: Award XP ─────────────────────────────────────────────────────────
const T_CATEGORY_ORDER = ["Engagement","Completion","Assessment","Difficulty","Bonus"];

const TeacherAwardXP = ({ dark = false, go, session }) => {
  const { data: initStudents } = useApi("/students");
  const { data: initCriteria } = useApi("/admin/xp-criteria");
  const { data: initAwards, loading: loadA } = useApi("/admin/xp-awards");

  const [students, setStudents]   = React.useState(null);
  const [criteria, setCriteria]   = React.useState(null);
  const [awards,   setAwards]     = React.useState(null);
  const [form, setForm]           = React.useState({ student_id:"", mode:"criteria", criteria_id:"", custom_reason:"", custom_pts:"" });
  const [awarding, setAwarding]   = React.useState(false);
  const [msg, setMsg]             = React.useState("");

  const stuList  = students ?? initStudents;
  const critList = criteria ?? initCriteria;
  const logList  = awards   ?? initAwards;

  const refresh = () => {
    apiFetch("/admin/xp-awards").then(r=>r.json()).then(setAwards);
  };

  const selectedCrit = form.criteria_id ? critList.find(c => c.id === parseInt(form.criteria_id)) : null;

  const submit = async e => {
    e.preventDefault(); setMsg(""); setAwarding(true);
    const isCustom = form.mode === "custom";
    const points   = isCustom ? parseInt(form.custom_pts) : (selectedCrit ? selectedCrit.points : 0);
    const reason   = isCustom ? form.custom_reason : (selectedCrit ? selectedCrit.label : "");
    if (!form.student_id || !points || !reason) { setMsg("Please fill all fields."); setAwarding(false); return; }
    const res = await apiFetch("/admin/xp-award", { method:"POST", body: JSON.stringify({
      student_id: parseInt(form.student_id), points, reason,
      criteria_id: !isCustom && selectedCrit ? selectedCrit.id : null,
    })});
    if (!res.ok) { const d=await res.json(); setMsg(d.error||"Failed"); setAwarding(false); return; }
    setMsg(`+${points} XP awarded!`);
    setForm({ student_id:"", mode:"criteria", criteria_id:"", custom_reason:"", custom_pts:"" });
    setAwarding(false); refresh();
  };

  const fmtTime = ts => { try { return new Date(ts).toLocaleDateString("en-GB",{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}); } catch { return ts; } };

  return (
    <Themed className={dark?"theme-dark":""} style={{ width:"100%", height:"100%", display:"flex" }}>
      <TeacherSidebar active="/app/teacher/xp" go={go} session={session}/>
      <div style={{ flex:1, display:"flex", flexDirection:"column", minWidth:0, background:"var(--paper)" }}>
        <div style={{ display:"flex", alignItems:"center", gap:12, padding:"12px 22px", borderBottom:"var(--border-thin)", background:"var(--paper-card)" }}>
          <div>
            <div className="display" style={{ fontSize:20 }}>Award XP</div>
            <div className="mono" style={{ fontSize:10, color:"var(--ink-mute)" }}>Reward students with XP for achievements</div>
          </div>
        </div>
        <div style={{ flex:1, overflow:"auto", padding:22, display:"grid", gridTemplateColumns:"380px 1fr", gap:20, alignItems:"start" }}>

          {/* Award form */}
          <div className="card-flat" style={{ padding:22 }}>
            <SectionHead eyebrow="GIVE POINTS" title="Award XP to a student"/>
            <form onSubmit={submit}>
              <FormField label="STUDENT">
                <select required style={selectStyle} value={form.student_id} onChange={e=>setForm(f=>({...f,student_id:e.target.value}))}>
                  <option value="">— select student —</option>
                  {stuList.map(s => <option key={s.id} value={s.id}>{s.name}{s.xp != null ? ` · ${s.xp} XP` : ""}</option>)}
                </select>
              </FormField>

              <FormField label="METHOD">
                <div style={{ display:"flex", gap:8 }}>
                  {[["criteria","From criteria"],["custom","Custom"]].map(([v,l]) => (
                    <button key={v} type="button"
                      onClick={() => setForm(f=>({...f,mode:v,criteria_id:"",custom_reason:"",custom_pts:""}))}
                      style={{ flex:1, padding:"8px 0", borderRadius:8, border:"var(--border-thin)", fontSize:12,
                        background: form.mode===v ? "var(--coral)" : "var(--paper-deep)",
                        color: form.mode===v ? "white" : "var(--ink-soft)", cursor:"pointer", fontWeight:600 }}>
                      {l}
                    </button>
                  ))}
                </div>
              </FormField>

              {form.mode === "criteria" ? (
                <>
                  <FormField label="CRITERIA">
                    <select required style={selectStyle} value={form.criteria_id} onChange={e=>setForm(f=>({...f,criteria_id:e.target.value}))}>
                      <option value="">— select criteria —</option>
                      {T_CATEGORY_ORDER.map(cat => {
                        const rows = critList.filter(r => r.category === cat && r.enabled);
                        if (!rows.length) return null;
                        return (
                          <optgroup key={cat} label={cat}>
                            {rows.map(r => <option key={r.id} value={r.id}>{r.label} (+{r.points} XP)</option>)}
                          </optgroup>
                        );
                      })}
                    </select>
                  </FormField>
                  {selectedCrit && (
                    <div style={{ padding:"9px 14px", borderRadius:9, background:"var(--paper-deep)", marginBottom:14, display:"flex", alignItems:"center", gap:10 }}>
                      <span style={{ fontWeight:800, color:"var(--moss)", fontFamily:"var(--font-mono)", fontSize:16 }}>+{selectedCrit.points}</span>
                      <span style={{ fontSize:12, color:"var(--ink-mute)" }}>XP · {selectedCrit.category}</span>
                    </div>
                  )}
                </>
              ) : (
                <>
                  <FormField label="REASON">
                    <input required style={inputStyle} value={form.custom_reason} onChange={e=>setForm(f=>({...f,custom_reason:e.target.value}))} placeholder="e.g. Exceptional effort today"/>
                  </FormField>
                  <FormField label="POINTS">
                    <input required type="number" min="1" max="500" style={inputStyle} value={form.custom_pts} onChange={e=>setForm(f=>({...f,custom_pts:e.target.value}))} placeholder="e.g. 15"/>
                  </FormField>
                </>
              )}

              {msg && <div style={{ color: msg.startsWith("+") ? "var(--moss)" : "var(--coral)", fontSize:13, marginBottom:10, fontWeight:700 }}>{msg}</div>}
              <button type="submit" disabled={awarding} className="btn btn-primary" style={{ width:"100%", padding:"11px 0", fontSize:14 }}>
                {awarding ? "Awarding…" : "Award XP"}
              </button>
            </form>
          </div>

          {/* Recent award log */}
          <div className="card-flat" style={{ padding:20 }}>
            <SectionHead eyebrow="RECENT" title="Award log"/>
            {loadA ? <Spinner/> : logList.length === 0 ? (
              <div style={{ fontSize:13, color:"var(--ink-mute)", padding:"12px 0" }}>No awards yet.</div>
            ) : (
              <div style={{ display:"flex", flexDirection:"column" }}>
                {logList.slice(0,20).map((a,i) => (
                  <div key={a.id} style={{ display:"flex", alignItems:"flex-start", gap:12, padding:"10px 0", borderTop: i?"var(--border-thin)":"none" }}>
                    <div style={{ width:38, height:38, borderRadius:9, background:"var(--moss)", display:"grid", placeItems:"center", flexShrink:0 }}>
                      <span style={{ color:"white", fontSize:12, fontWeight:800, fontFamily:"var(--font-mono)" }}>+{a.points}</span>
                    </div>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontWeight:700, fontSize:13 }}>{a.student}</div>
                      <div style={{ fontSize:12, color:"var(--ink-soft)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{a.reason}</div>
                      <div className="mono" style={{ fontSize:10, color:"var(--ink-mute)", marginTop:2 }}>{fmtTime(a.awarded_at)} · by {a.awarded_by || "system"}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </Themed>
  );
};

Object.assign(window, { TeacherHome, TeacherLive, TeacherAwardXP });

