// 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 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 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);
  };

  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 }}>Recap</button>
                        : !s.meet && <button className="btn btn-ghost" onClick={() => go && go("/app/teacher/schedule")} style={{ padding: "6px 12px", fontSize: 12 }}>Prepare</button>}
                      {s.status !== "done" ? (
                        <button
                          disabled={statusChanging === s.id}
                          onClick={() => markStatus(s.id, "done")}
                          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 className="chip flat" style={{ fontSize: 11 }}>{b.students} students</span>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  </Themed>
  );
};

const TeacherLive = ({ dark = false, go, session }) => {
  const tid = session?.teacherId;
  const { data: dash } = useApi(tid ? `/teacher/dashboard/${tid}` : "/teacher/dashboard/0", {});
  const firstBatchId = (dash.batches || [])[0]?.id;
  const { data: LIVE_ROSTER } = useApi(firstBatchId ? `/students?batch=${firstBatchId}` : "/students");
  const [roster, setRoster] = React.useState([]);
  React.useEffect(() => {
    if (LIVE_ROSTER.length)
      setRoster(LIVE_ROSTER.map((s, i) => ({ ...s, status: i === 5 ? "absent" : i === 2 ? "late" : "present", hand: i === 1 })));
  }, [LIVE_ROSTER.length]);
  const [saved, setSaved] = React.useState(false);
  const [timer, setTimer] = React.useState(23 * 60 + 14);
  React.useEffect(() => {
    const id = setInterval(() => setTimer(t => t + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const fmt = s => `${String(Math.floor(s/60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`;
  const cycleStatus = (i) => {
    const cycle = { present: "late", late: "absent", absent: "present" };
    setRoster(r => r.map((s, idx) => idx === i ? { ...s, status: cycle[s.status] } : s));
  };
  const statusColor = s => s === "present" ? "var(--moss)" : s === "late" ? "var(--gold)" : "var(--ink-mute)";
  const present = roster.filter(s => s.status !== "absent").length;

  return (
    <Themed className={dark ? "theme-dark" : ""} style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 18px", background: "var(--paper-card)", borderBottom: "var(--border-thin)" }}>
        <span className="chip" style={{ background: "var(--coral)", color: "white", border: "1.5px solid var(--coral-deep)" }}>● REC · {fmt(timer)}</span>
        <div className="display" style={{ fontSize: 18 }}>{(dash.batches || [])[0]?.name || "Live Class"} · {(dash.batches || [])[0]?.course || ""}</div>
        <span className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>{roster.length} students · Google Meet</span>
        <div style={{ flex: 1 }}/>
        <button className="btn btn-ghost" style={{ padding: "6px 12px" }}>Share screen</button>
        <button onClick={() => go && go("/app/teacher/attendance")} className="btn btn-ghost" style={{ padding: "6px 12px", fontSize: 12 }}>{I.check({ size: 14 })} Attendance</button>
        <button onClick={() => { setSaved(true); setTimeout(() => go && go("/app/teacher/attendance"), 1200); }} className="btn" style={{ padding: "6px 14px", background: "var(--ink)", color: "var(--paper)", fontSize: 13 }}>
          {saved ? "✓ Saved — redirecting…" : "End class & save"}
        </button>
      </div>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 14, padding: 14, background: "var(--paper)", minHeight: 0 }}>
        {/* Left: presenter view */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12, minHeight: 0 }}>
          <div className="card-flat" style={{ flex: 1, padding: 14, background: "var(--paper-card)", display: "flex", flexDirection: "column" }}>
            <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)", marginBottom: 8 }}>SHARING · turtle.py</div>
            <pre className="mono" style={{ margin: 0, padding: 14, flex: 1, background: "oklch(0.18 0.02 250)", color: "oklch(0.92 0.01 250)", borderRadius: 10, fontSize: 13, lineHeight: 1.6, border: "var(--border)" }}>
{`for side in range(4):
    t.forward(100)
    t.right(90)`}
            </pre>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(8, 1fr)", gap: 6 }}>
            {roster.map((s, i) => (
              <div key={i} style={{ aspectRatio: "1", borderRadius: 10, background: s.color, border: "var(--border)", position: "relative", display: "grid", placeItems: "center", color: "white", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 14, opacity: s.status === "absent" ? 0.4 : 1 }}>
                {s.name[0]}
                <div style={{ position: "absolute", bottom: 4, left: 0, right: 0, fontSize: 8, padding: "1px 4px", background: "rgba(0,0,0,0.6)", borderRadius: 4, textAlign: "center", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.name.split(" ")[0]}</div>
                {s.status === "absent" && <div style={{ position: "absolute", top: 4, right: 4, width: 8, height: 8, borderRadius: "50%", background: "var(--coral)", border: "1px solid white" }}/>}
              </div>
            ))}
          </div>
        </div>

        {/* Right: live attendance + quick actions */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12, minHeight: 0 }}>
          <div className="card-flat" style={{ padding: 16, flex: 1, overflow: "auto" }}>
            <SectionHead eyebrow="LIVE ATTENDANCE · click to change"
              title="In class now"
              action={
                <span className="chip flat" style={{ fontSize: 10, background: present >= roster.length * 0.8 ? "var(--moss)" : "var(--gold)", color: "white" }}>
                  {present}/{roster.length}
                </span>
              }
            />
            <div style={{ marginBottom: 10 }}>
              <div className="progress" style={{ height: 6 }}>
                <i style={{ width: `${(present/roster.length)*100}%`, background: present >= roster.length * 0.8 ? "var(--moss)" : "var(--gold)" }}/>
              </div>
              <div style={{ display: "flex", gap: 14, marginTop: 6, fontSize: 11, color: "var(--ink-mute)" }}>
                <span style={{ color: "var(--moss)" }}>● {roster.filter(s=>s.status==="present").length} present</span>
                <span style={{ color: "var(--gold)" }}>● {roster.filter(s=>s.status==="late").length} late</span>
                <span style={{ color: "var(--ink-mute)" }}>● {roster.filter(s=>s.status==="absent").length} absent</span>
              </div>
            </div>
            {roster.map((s, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderTop: i ? "var(--border-thin)" : "none" }}>
                <button onClick={() => cycleStatus(i)} style={{ width: 10, height: 10, borderRadius: "50%", background: statusColor(s.status), border: `2px solid ${statusColor(s.status)}`, cursor: "pointer", flexShrink: 0, outline: "none", padding: 0 }} title={`Click to cycle: ${s.status}`}/>
                <Avatar name={s.name[0]} color={s.color} size={26}/>
                <div style={{ flex: 1, fontSize: 13, fontWeight: 600, opacity: s.status === "absent" ? 0.5 : 1 }}>
                  {s.name}
                  {s.hand && <span className="chip flat" style={{ marginLeft: 6, fontSize: 10, padding: "1px 6px", background: "var(--coral)", color: "white" }}>✋ hand up</span>}
                </div>
                <button onClick={() => cycleStatus(i)} style={{ padding: "2px 8px", borderRadius: 6, border: "1px solid var(--rule)", background: "transparent", fontSize: 10, fontWeight: 700, cursor: "pointer", color: statusColor(s.status), fontFamily: "var(--font-mono)" }}>
                  {s.status}
                </button>
                {s.status !== "absent" && <span className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>+{s.xp} XP</span>}
              </div>
            ))}
          </div>

          <div className="card-flat" style={{ padding: 16 }}>
            <SectionHead eyebrow="IN CLASS" title="Quick actions"/>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
              {[
                ["Pop quiz", I.puzzle, "var(--coral)", "/app/teacher/quizzes"],
                ["Code race", I.bolt, "var(--gold)", null],
                ["Hand raise", I.hand, "var(--sky)", null],
                ["Share doc", I.upload, "var(--moss)", null],
              ].map(([label, ic, c, path]) => (
                <button key={label} onClick={() => path && go && go(path)} className="btn btn-ghost" style={{ padding: "10px 12px", fontSize: 12, justifyContent: "flex-start", background: "var(--paper-deep)", border: "var(--border-thin)" }}>
                  <span style={{ color: c }}>{ic({ size: 16 })}</span>{label}
                </button>
              ))}
            </div>
          </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 });

