// Attendance + schedule views (teacher attendance, teacher & parent
// schedules) and their shared status constants. Split out of features-more.jsx.

// ── Teacher: Attendance ───────────────────────────────────────────────────────
const ATTEND_STATUSES = ["present","late","missed","tech_issue","pending"];
const ATTEND_LABELS   = { present:"Present", late:"Late", missed:"Missed", tech_issue:"Tech Issue", pending:"Pending", absent:"Absent" };
const ATTEND_COLOR    = { present:"var(--moss)", late:"var(--gold)", missed:"var(--coral)", tech_issue:"var(--sky)", pending:"var(--rule-bold)", absent:"var(--coral)" };

const fmtSessionDate = d => {
  if (!d) return "";
  try { return new Date(d + "T00:00:00").toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}); }
  catch { return d; }
};

const TeacherAttendance = ({ dark = false, go, session: _session }) => {
  const { data: initSessions, loading: loadingSessions } = useApi("/sessions-with-roster");
  const [allSessions, setAllSessions] = React.useState(null);
  const TEACHER_SESSIONS = allSessions ?? (Array.isArray(initSessions) ? initSessions : []);
  const [activeTab, setActiveTab] = React.useState("sessions");
  const [selectedSession, setSelectedSession] = React.useState(null);
  React.useEffect(() => {
    if (TEACHER_SESSIONS.length && !selectedSession)
      setSelectedSession(TEACHER_SESSIONS[0].id);
  }, [TEACHER_SESSIONS.length]);
  const [editRoster, setEditRoster] = React.useState(null);
  // Poll so a session auto-advances upcoming→live→done during class without a
  // manual refresh. Skip while the teacher is mid-edit so unsaved marks survive.
  React.useEffect(() => {
    const id = setInterval(() => {
      if (editRoster) return;
      apiFetch("/sessions-with-roster").then(r => r.ok ? r.json() : null).then(d => { if (Array.isArray(d)) setAllSessions(d); }).catch(()=>{});
    }, 45000);
    return () => clearInterval(id);
  }, [editRoster]);
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved] = React.useState({});

  const session = TEACHER_SESSIONS.find(s => s.id === selectedSession);
  const workingRoster = editRoster || (session ? session.roster : []);

  const cycleStatus = i => {
    const cycle = { present:"late", late:"missed", missed:"tech_issue", tech_issue:"pending", pending:"present", absent:"present" };
    setEditRoster(r => (r || session.roster).map((s, idx) => idx === i ? { ...s, status: cycle[s.status] || "present" } : s));
  };

  const saveSession = async () => {
    setSaving(true);
    try {
      const res = await apiFetch(`/sessions-with-roster/${selectedSession}/attendance`, {
        method: "POST",
        body: JSON.stringify({ roster: workingRoster.map(r => ({ student_id: r.student_id, status: r.status })) }),
      });
      if (res.ok) {
        const fresh = await apiFetch("/sessions-with-roster").then(r=>r.json());
        setAllSessions(fresh);
        setSaved(s => ({ ...s, [selectedSession]: true }));
        setEditRoster(null);
        if (window.showToast) {
          window.showToast({
            title: "Attendance Updated",
            message: `Attendance saved for ${session?.batch || "Session"}! Synced across all portals.`,
            type: "success"
          });
        }
      } else {
        if (window.showToast) window.showToast({ title: "Failed", message: "Could not save attendance.", type: "error" });
      }
    } catch (e) {
      if (window.showToast) window.showToast({ title: "Error", message: e.message || "Failed to save", type: "error" });
    }
    setSaving(false);
  };

  // Build per-student summary across all sessions
  const allStudents = [...new Set(TEACHER_SESSIONS.flatMap(s => s.roster.map(r => r.name)))];
  const studentSummary = allStudents.map(name => {
    const appearances = TEACHER_SESSIONS.filter(s => s.status !== "upcoming").flatMap(s => s.roster.filter(r => r.name === name));
    const present = appearances.filter(r => r.status === "present").length;
    const late    = appearances.filter(r => r.status === "late").length;
    const missed  = appearances.filter(r => r.status === "missed").length;
    const techIssue = appearances.filter(r => r.status === "tech_issue").length;
    const color = TEACHER_SESSIONS.flatMap(s => s.roster).find(r => r.name === name)?.color || "var(--coral)";
    const attended = present + late;
    const rate = appearances.length ? Math.round((attended / appearances.length) * 100) : 100;
    return { name, color, present, late, missed, techIssue, total: appearances.length, rate };
  }).sort((a, b) => a.rate - b.rate);

  const statusColor = s => ATTEND_COLOR[s] || "var(--ink-mute)";
  const statusBg    = s => ATTEND_COLOR[s] || "var(--ink-mute)";

  return (
    <Themed className={dark ? "theme-dark" : ""} style={{ width:"100%", height:"100%", display:"flex" }}>
      <TeacherSidebar active="/app/teacher/attendance" go={go} session={session}/>
      <div style={{ flex:1, display:"flex", flexDirection:"column", minWidth:0 }}>
        {/* Header */}
        <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 }}>Attendance</div>
            <div className="mono" style={{ fontSize:11, color:"var(--ink-mute)" }}>
              {TEACHER_SESSIONS.filter(s=>s.status!=="upcoming").length} sessions recorded
            </div>
          </div>
          <div style={{ flex:1 }}/>
          <Tabs items={["Sessions","By student"]} active={activeTab==="sessions"?"Sessions":"By student"} onChange={v => setActiveTab(v==="Sessions"?"sessions":"students")}/>
          <button onClick={() => go && go("/app/teacher/live")} className="btn btn-primary" style={{ padding:"6px 14px", fontSize:12 }}>
            {I.play({ size:14 })} Live class
          </button>
        </div>

        {activeTab === "sessions" ? (
          <div style={{ flex:1, display:"grid", gridTemplateColumns:"320px 1fr", overflow:"hidden" }}>
            {/* Session list */}
            <div style={{ borderRight:"var(--border-thin)", overflow:"auto", background:"var(--paper-card)" }}>
              {loadingSessions && !TEACHER_SESSIONS.length && (
                <div style={{ padding:32, textAlign:"center", color:"var(--ink-mute)", fontSize:13 }}>Loading sessions…</div>
              )}
              {!loadingSessions && !TEACHER_SESSIONS.length && (
                <div style={{ padding:32, textAlign:"center", color:"var(--ink-mute)", fontSize:13 }}>No sessions found. Add sessions in the Schedule tab first.</div>
              )}
              {TEACHER_SESSIONS.map(s => {
                const present = s.roster.filter(r=>r.status==="present"||r.status==="late").length;
                const rate = s.roster.length ? Math.round((present/s.roster.length)*100) : 0;
                return (
                  <div key={s.id} onClick={() => { setSelectedSession(s.id); setEditRoster(null); }} style={{
                    padding:"14px 18px", cursor:"pointer", borderBottom:"var(--border-thin)",
                    background: selectedSession===s.id ? "var(--paper-deep)" : "transparent",
                    borderLeft: selectedSession===s.id ? "3px solid var(--coral)" : "3px solid transparent",
                  }}>
                    <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:4 }}>
                      <div style={{ fontWeight:700, fontSize:13 }}>{s.batch} · {fmtSessionDate(s.day)}</div>
                      <span className="chip flat" style={{ fontSize:10, padding:"1px 7px", background: s.status==="live"?"var(--coral)":s.status==="done"?"var(--moss)":"var(--paper-deep)", color: s.status==="upcoming"?"var(--ink-mute)":"white" }}>
                        {s.status}
                      </span>
                    </div>
                    <div style={{ fontSize:12, color:"var(--ink-mute)", marginBottom:6 }}>{s.time} · {s.course}</div>
                    {s.status !== "upcoming" && (
                      <>
                        <div className="progress" style={{ height:4, marginBottom:4 }}>
                          <i style={{ width:`${rate}%`, background: rate>=80?"var(--moss)":"var(--gold)" }}/>
                        </div>
                        <div style={{ display:"flex", justifyContent:"space-between", fontSize:11, color:"var(--ink-mute)" }}>
                          <span>{present}/{s.roster.length} present</span>
                          <span style={{ fontWeight:700, color: rate>=80?"var(--moss)":"var(--gold)" }}>{rate}%</span>
                        </div>
                      </>
                    )}
                    {s.completion_remarks && (
                      <div style={{ fontSize:10, color:"var(--moss)", marginTop:3, fontWeight:600, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>
                        📝 {s.completion_remarks}
                      </div>
                    )}
                    {saved[s.id] && <div style={{ fontSize:10, color:"var(--moss)", marginTop:4, fontWeight:700 }}>✓ Attendance saved</div>}
                  </div>
                );
              })}
            </div>

            {/* Session detail / mark attendance */}
            {session && (
              <div style={{ overflow:"auto", padding:22, background:"var(--paper)" }}>
                <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:18 }}>
                  <div>
                    <div className="display" style={{ fontSize:20 }}>{session.batch} · {fmtSessionDate(session.day)}</div>
                    <div style={{ fontSize:13, color:"var(--ink-mute)", marginTop:2 }}>{session.time} · {session.course}</div>
                  </div>
                  <div style={{ display:"flex", gap:8, alignItems:"center" }}>
                    {editRoster && <span style={{ fontSize:11, color:"var(--gold)", fontWeight:700 }}>Unsaved changes</span>}
                    <button onClick={saveSession} disabled={saving} className="btn btn-primary" style={{ padding:"6px 14px", fontSize:12, opacity: saving ? .6 : 1 }}>{I.check({ size:14 })} {saving ? "Saving…" : "Save attendance"}</button>
                  </div>
                </div>

                {/* Summary chips */}
                <div style={{ display:"flex", gap:10, marginBottom:18 }}>
                  {ATTEND_STATUSES.map(st=>(
                    <div key={st} style={{ padding:"8px 16px", borderRadius:10, background:ATTEND_COLOR[st], color:"white", textAlign:"center", minWidth:68 }}>
                      <div className="display" style={{ fontSize:22 }}>{workingRoster.filter(r=>r.status===st).length}</div>
                      <div style={{ fontSize:10, opacity:.85 }}>{ATTEND_LABELS[st]}</div>
                    </div>
                  ))}
                  <div style={{ flex:1, display:"flex", alignItems:"center" }}>
                    <div style={{ width:"100%" }}>
                      <div style={{ display:"flex", justifyContent:"space-between", fontSize:12, fontWeight:700, marginBottom:6 }}>
                        <span>Attendance rate</span>
                        <span>{workingRoster.length ? Math.round((workingRoster.filter(r=>r.status==="present"||r.status==="late").length/workingRoster.length)*100) : 0}%</span>
                      </div>
                      <div className="progress" style={{ height:8 }}>
                        <i style={{ width:`${workingRoster.length ? Math.round((workingRoster.filter(r=>r.status==="present"||r.status==="late").length/workingRoster.length)*100) : 0}%`, background:"var(--moss)" }}/>
                      </div>
                    </div>
                  </div>
                </div>

                {session.completion_remarks && (
                  <div style={{
                    marginBottom: 18,
                    padding: "12px 16px",
                    background: "var(--paper-deep)",
                    border: "var(--border-thin)",
                    borderLeft: "4px solid var(--moss)",
                    borderRadius: 8,
                    fontSize: 13,
                    lineHeight: 1.5,
                  }}>
                    <div style={{ fontWeight: 700, fontSize: 11, color: "var(--moss)", textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 4 }}>
                      📝 Session Completion Remarks / Topics Covered
                    </div>
                    <div style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>
                      “{session.completion_remarks}”
                    </div>
                  </div>
                )}

                {/* Roster with editable status */}
                <div className="card-flat" style={{ padding:16 }}>
                  <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:12 }}>
                    <div className="mono" style={{ fontSize:10, color:"var(--ink-mute)", letterSpacing:".06em" }}>STUDENT ROSTER</div>
                    <div style={{ fontSize:11, color:"var(--ink-mute)" }}>Click a status pill to mark each student</div>
                  </div>
                  {workingRoster.map((s, i) => (
                    <div key={i} style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 0", borderTop: i ? "var(--border-thin)" : "none" }}>
                      <Avatar name={s.name[0]} color={s.color} size={32}/>
                      <div style={{ flex:1 }}>
                        <div style={{ fontWeight:700, fontSize:13 }}>{s.name}</div>
                        {/* mini sparkline of this student's last 4 sessions */}
                        <div style={{ display:"flex", gap:3, marginTop:4 }}>
                          {TEACHER_SESSIONS.filter(sess=>sess.status!=="upcoming").slice(0,4).map((sess,si)=>{
                            const entry = sess.roster.find(r=>r.name===s.name);
                            const st = entry ? entry.status : "absent";
                            return <div key={si} style={{ width:8, height:8, borderRadius:2, background:statusColor(st) }} title={`${fmtSessionDate(sess.day)}: ${ATTEND_LABELS[st]||st}`}/>;
                          })}
                          <span style={{ fontSize:10, color:"var(--ink-mute)", marginLeft:4 }}>last {TEACHER_SESSIONS.filter(s=>s.status!=="upcoming").length} sessions</span>
                        </div>
                      </div>
                      <div style={{ display:"flex", gap:5, flexWrap:"wrap" }}>
                        {ATTEND_STATUSES.map(st=>(
                          <button key={st} style={{
                            padding:"3px 9px", borderRadius:8, border:`1.5px solid ${s.status===st?statusBg(st):"var(--rule)"}`,
                            background: s.status===st ? statusBg(st) : "transparent",
                            color: s.status===st ? "white" : "var(--ink-mute)",
                            fontSize:11, fontWeight:700, cursor:"pointer",
                          }} onClick={() => setEditRoster(r => (r||session.roster).map((x,idx)=>idx===i?{...x,status:st}:x))}>
                            {ATTEND_LABELS[st]}
                          </button>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        ) : (
          /* By student view */
          <div style={{ flex:1, overflow:"auto", padding:22 }}>
            <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:14, marginBottom:22 }}>
              {[
                { l:"AVG ATTENDANCE",  v:`${Math.round(studentSummary.reduce((a,s)=>a+s.rate,0)/studentSummary.length)}%`, c:studentSummary.reduce((a,s)=>a+s.rate,0)/studentSummary.length >= 80?"var(--moss)":"var(--gold)" },
                { l:"PERFECT (100%)",  v:studentSummary.filter(s=>s.rate===100).length, c:"var(--moss)" },
                { l:"AT RISK (<75%)",  v:studentSummary.filter(s=>s.rate<75).length, c:"var(--coral)" },
              ].map(k=>(
                <div key={k.l} className="card-flat" style={{ padding:14 }}>
                  <div className="mono" style={{ fontSize:10, color:"var(--ink-mute)", letterSpacing:".06em" }}>{k.l}</div>
                  <div className="display" style={{ fontSize:32, marginTop:4, color:k.c }}>{k.v}</div>
                </div>
              ))}
            </div>

            {studentSummary.filter(s=>s.rate<75).length > 0 && (
              <div className="card-flat" style={{ padding:14, marginBottom:16, borderLeft:"3px solid var(--coral)", display:"flex", alignItems:"center", gap:12 }}>
                {I.bell({ size:16 })}
                <div style={{ flex:1 }}>
                  <div style={{ fontWeight:700, fontSize:13 }}>At-risk students</div>
                  <div style={{ fontSize:12, color:"var(--ink-mute)" }}>{studentSummary.filter(s=>s.rate<75).map(s=>s.name).join(", ")} — attendance below 75%</div>
                </div>
                <button className="btn btn-primary" style={{ padding:"6px 12px", fontSize:12 }}>{I.send({ size:14 })} Notify parents</button>
              </div>
            )}

            <table style={{ width:"100%", borderCollapse:"collapse", fontSize:13 }}>
              <thead>
                <tr style={{ textAlign:"left", color:"var(--ink-mute)" }}>
                  {["Student","Sessions","Present","Late","Missed","Tech Issue","Rate","Last 4 sessions",""].map(h=>(
                    <th key={h} style={{ padding:"8px 12px", fontWeight:600, fontSize:11, borderBottom:"var(--border-thin)" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {studentSummary.map((s,i)=>(
                  <tr key={i} style={{ borderTop: i?"var(--border-thin)":"none" }}>
                    <td style={{ padding:"12px" }}>
                      <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                        <Avatar name={s.name[0]} color={s.color} size={28}/>
                        <span style={{ fontWeight:700 }}>{s.name}</span>
                      </div>
                    </td>
                    <td style={{ padding:"12px", textAlign:"center" }}>{s.total}</td>
                    <td style={{ padding:"12px", textAlign:"center", color:"var(--moss)", fontWeight:700 }}>{s.present}</td>
                    <td style={{ padding:"12px", textAlign:"center", color:"var(--gold)", fontWeight:700 }}>{s.late}</td>
                    <td style={{ padding:"12px", textAlign:"center", color:"var(--coral)", fontWeight:700 }}>{s.missed}</td>
                    <td style={{ padding:"12px", textAlign:"center", color:"var(--sky)", fontWeight:700 }}>{s.techIssue}</td>
                    <td style={{ padding:"12px" }}>
                      <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                        <div className="progress" style={{ width:80, height:6 }}>
                          <i style={{ width:`${s.rate}%`, background: s.rate>=90?"var(--moss)":s.rate>=75?"var(--gold)":"var(--coral)" }}/>
                        </div>
                        <span style={{ fontWeight:700, fontSize:13, color: s.rate>=90?"var(--moss)":s.rate>=75?"var(--gold)":"var(--coral)" }}>{s.rate}%</span>
                      </div>
                    </td>
                    <td style={{ padding:"12px" }}>
                      <div style={{ display:"flex", gap:3 }}>
                        {TEACHER_SESSIONS.filter(sess=>sess.status!=="upcoming").slice(0,4).map((sess,si)=>{
                          const entry = sess.roster.find(r=>r.name===s.name);
                          const st = entry ? entry.status : "absent";
                          return (
                            <div key={si} title={`${fmtSessionDate(sess.day)}: ${ATTEND_LABELS[st]||st}`} style={{ width:12, height:20, borderRadius:3, background:statusColor(st), display:"flex", alignItems:"center", justifyContent:"center" }}>
                              <div style={{ width:4, height:4, borderRadius:"50%", background:"rgba(255,255,255,.7)" }}/>
                            </div>
                          );
                        })}
                      </div>
                    </td>
                    <td style={{ padding:"12px" }}>
                      <button className="btn btn-ghost" style={{ padding:"3px 8px", fontSize:11 }}>Message</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </Themed>
  );
};

// ── Parent: Schedule (read-only, child-filtered) ─────────────────────────────
// Shows only Maya's sessions (Batch C). No admin controls.

const ParentSchedule = ({ go, session }) => {
  const sid = session?.studentId;
  const { data: PARENT_SESSIONS, loading } = useApi(sid ? `/parent/sessions/${sid}` : "/parent/sessions/0");
  const [copied, setCopied] = React.useState(null);
  const copyLink = (link, id) => {
    navigator.clipboard?.writeText(link).catch(()=>{});
    setCopied(id);
    setTimeout(() => setCopied(null), 2000);
  };
  const statusStyle = s => ({
    today:    { bg:"var(--coral)",    label:"TODAY" },
    upcoming: { bg:"var(--moss)",     label:"UPCOMING" },
    done:     { bg:"var(--ink-mute)", label:"DONE" },
  }[s] || { bg:"var(--ink-mute)", label:"—" });
  const upcomingCount = PARENT_SESSIONS.filter(s => s.status === "upcoming" || s.status === "today").length;

  return (
    <div className="codeland" style={{ width:"100%", height:"100%", background:"var(--paper)", display:"flex", flexDirection:"column" }}>
      {/* Header */}
      <div style={{ padding:"14px 26px", borderBottom:"var(--border-thin)", background:"var(--paper-card)", display:"flex", alignItems:"center", gap:14 }}>
        <button onClick={() => go && go("/app/parent")} style={{ display:"flex", alignItems:"center", gap:6, background:"none", border:"none", cursor:"pointer", color:"var(--ink-soft)", fontSize:13, fontFamily:"var(--font-ui)" }}>
          {I.arrowL({ size:16 })} Back
        </button>
        <div style={{ width:1, height:20, background:"var(--rule)" }}/>
        <div>
          <div className="display" style={{ fontSize:20 }}>Class Schedule</div>
          <div className="mono" style={{ fontSize:10, color:"var(--ink-mute)" }}>Upcoming &amp; past sessions</div>
        </div>
        <div style={{ flex:1 }}/>
        {upcomingCount > 0
          ? <div className="chip" style={{ background:"var(--moss)", color:"white" }}>{I.check({ size:14 })} {upcomingCount} upcoming</div>
          : <div className="chip" style={{ background:"var(--paper-deep)", color:"var(--ink-mute)" }}>{I.check({ size:14 })} All caught up</div>
        }
      </div>

      {/* Session cards */}
      <div style={{ flex:1, overflow:"auto", padding:"24px 26px", display:"flex", flexDirection:"column", gap:14 }}>
        {loading && <Spinner/>}
        {!loading && PARENT_SESSIONS.length === 0 && (
          <div style={{ flex:1, display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", gap:16, padding:60, textAlign:"center" }}>
            <div style={{ width:64, height:64, borderRadius:999, background:"var(--paper-card)", border:"var(--border-thin)", display:"grid", placeItems:"center", color:"var(--ink-mute)" }}>
              {I.check({ size:28 })}
            </div>
            <div>
              <div className="display" style={{ fontSize:22 }}>You're all caught up!</div>
              <div style={{ fontSize:13, color:"var(--ink-mute)", marginTop:6 }}>No upcoming classes scheduled right now. Check back soon.</div>
            </div>
            <button onClick={() => go && go("/app/parent")} className="btn btn-ghost" style={{ padding:"8px 20px", fontSize:13 }}>
              {I.arrowL({ size:14 })} Back to home
            </button>
          </div>
        )}
        {!loading && PARENT_SESSIONS.length > 0 && PARENT_SESSIONS.map((s, i) => {
          const style = statusStyle(s.status);
          return (
            <div key={i} className="card" style={{ padding:0, overflow:"hidden", opacity: s.status==="done" ? 0.75 : 1 }}>
              <div style={{ display:"flex", alignItems:"stretch" }}>
                {/* Left accent + date */}
                <div style={{ width:100, background:"var(--paper-deep)", borderRight:"var(--border-thin)", padding:"18px 14px", display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", gap:4, flexShrink:0 }}>
                  <span style={{ fontSize:9, fontWeight:800, letterSpacing:".08em", color:style.bg, fontFamily:"var(--font-mono)" }}>{style.label}</span>
                  <div className="display" style={{ fontSize:15, textAlign:"center", lineHeight:1.2 }}>{s.date.split(", ")[0]}<br/><span style={{ fontSize:12, fontWeight:500 }}>{s.date.split(", ")[1]}</span></div>
                  <div className="mono" style={{ fontSize:10, color:"var(--ink-mute)", textAlign:"center" }}>{s.time.split(" – ")[0]}</div>
                </div>

                {/* Main content */}
                <div style={{ flex:1, padding:"16px 20px", display:"flex", alignItems:"center", gap:16 }}>
                  <div style={{ flex:1 }}>
                    <div className="display" style={{ fontSize:18 }}>{s.topic}</div>
                    <div style={{ fontSize:13, color:"var(--ink-mute)", marginTop:4 }}>
                      {s.time} · {s.teacher}
                    </div>
                    {s.note && (
                      <div style={{ marginTop:8, padding:"6px 12px", background:"var(--gold)", borderRadius:8, fontSize:12, fontWeight:600, display:"inline-flex", alignItems:"center", gap:6 }}>
                        📝 {s.note}
                      </div>
                    )}
                  </div>

                  {/* Actions */}
                  <div style={{ display:"flex", flexDirection:"column", gap:8, flexShrink:0 }}>
                    {s.status === "today" && (
                      <a href={normalizeUrl(s.meet)} target="_blank" rel="noopener noreferrer" style={{ textDecoration:"none" }}>
                        <button className="btn btn-primary" style={{ padding:"8px 20px", fontSize:13, width:"100%" }}>
                          {I.play({ size:14 })} Join class
                        </button>
                      </a>
                    )}
                    {s.status === "upcoming" && s.meet && (
                      <button onClick={() => copyLink(s.meet, i)} className="btn btn-ghost" style={{ padding:"6px 14px", fontSize:12 }}>
                        {copied===i ? "✓ Copied!" : `${I.upload({ size:13 })} Copy link`}
                      </button>
                    )}
                    {s.status === "done" && (
                      <span style={{ fontSize:12, color:"var(--ink-mute)", fontWeight:600 }}>
                        {I.check({ size:14 })} Completed
                      </span>
                    )}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ── Teacher: My Schedule (read-only, teacher-filtered) ────────────────────────
// Shows only the logged-in teacher's sessions. No admin edit controls.
const TeacherMySchedule = ({ dark = false, go, session }) => {
  const { data: initSessions, loading } = useApi("/schedule");
  const [sessions, setSessions] = React.useState(null);
  const [statusChanging, setStatusChanging] = React.useState(null);
  const allSessions = sessions ?? initSessions;
  const teacherName = session?.name || "";
  const TEACHER_MY_SESSIONS = allSessions.filter(s => !teacherName || s.teacher === teacherName);
  const days = [...new Set(TEACHER_MY_SESSIONS.map(s=>s.day))].sort();
  const fmtDay = d => { try { return new Date(d + "T00:00:00").toLocaleDateString("en-GB", { weekday:"short", day:"numeric", month:"short" }).toUpperCase(); } catch { return d.toUpperCase(); } };
  const statusColor = s => s==="live"?"var(--coral)":s==="done"?"var(--ink-mute)":s==="not_conducted"?"var(--gold)":"var(--moss)";

  const [ncSession, setNcSession] = React.useState(null);
  const [ncReason, setNcReason]   = React.useState("");
  const [ncSaving, setNcSaving]   = React.useState(false);
  const [ncError, setNcError]     = React.useState("");

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

  const { data: initRequests } = useApi("/schedule-requests");
  const { data: BATCHES }      = useApi("/batches");
  const { data: STUDENTS }     = useApi("/students");
  const [requests, setRequests] = React.useState(null);
  const [showReqModal, setShowReqModal] = React.useState(false);
  const [showMyRequests, setShowMyRequests] = React.useState(false);
  const [reqSessType, setReqSessType] = React.useState("batch");
  const [reqForm, setReqForm] = React.useState({ batch_id:"", student_id:"", day:"", time_start:"", time_end:"", timezone:"Asia/Kolkata", reason:"" });
  const [reqSaving, setReqSaving] = React.useState(false);
  const [reqError, setReqError] = React.useState("");

  const reqList = Array.isArray(requests ?? initRequests) ? (requests ?? initRequests) : [];
  const pendingReqCount = reqList.filter(r => r.status === "pending").length;

  const submitRequest = async e => {
    e.preventDefault();
    setReqSaving(true);
    setReqError("");
    if (reqSessType === "batch" && !reqForm.batch_id) {
      setReqError("Select a batch.");
      setReqSaving(false);
      return;
    }
    if (reqSessType === "individual" && !reqForm.student_id) {
      setReqError("Select a student.");
      setReqSaving(false);
      return;
    }
    if (!reqForm.day) {
      setReqError("Select a date.");
      setReqSaving(false);
      return;
    }
    if (!reqForm.time_start || !reqForm.time_end) {
      setReqError("Select start and end times.");
      setReqSaving(false);
      return;
    }
    if (!reqForm.reason.trim()) {
      setReqError("Please explain why this session is requested.");
      setReqSaving(false);
      return;
    }

    const payload = {
      batch_id: reqSessType === "batch" ? parseInt(reqForm.batch_id) : undefined,
      student_id: reqSessType === "individual" ? parseInt(reqForm.student_id) : undefined,
      day: reqForm.day,
      time_start: reqForm.time_start,
      time_end: reqForm.time_end,
      timezone: reqForm.timezone || "Asia/Kolkata",
      reason: reqForm.reason.trim(),
    };

    const res = await apiFetch("/schedule-requests", {
      method: "POST",
      body: JSON.stringify(payload),
    });
    const d = await res.json().catch(() => ({}));
    if (!res.ok) {
      setReqError(d.error || "Failed to submit session request.");
      setReqSaving(false);
      return;
    }

    const fresh = await apiFetch("/schedule-requests").then(r => r.json());
    setRequests(fresh);
    setReqForm({ batch_id: "", student_id: "", day: "", time_start: "", time_end: "", timezone: "Asia/Kolkata", reason: "" });
    setShowReqModal(false);
    setReqSaving(false);
    alert("Session request submitted! An admin will review your request.");
  };

  const submitNotConducted = async e => {
    e.preventDefault();
    setNcSaving(true);
    setNcError("");
    const res = await apiFetch(`/schedule/${ncSession.id}/not-conducted`, {
      method: "POST",
      body: JSON.stringify({ reason: ncReason || undefined }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      setNcError(data.error || "Failed to mark session not conducted.");
      setNcSaving(false);
      return;
    }
    const fresh = await apiFetch("/schedule").then(r=>r.json());
    setSessions(fresh);
    setNcSession(null);
    setNcReason("");
    setNcSaving(false);
    if (data.message) {
      alert(data.message);
    }
  };

  const markStatus = async (id, status) => {
    setStatusChanging(id);
    await apiFetch(`/schedule/${id}/status`, { method:"PATCH", body: JSON.stringify({ status }) });
    const fresh = await apiFetch("/schedule").then(r=>r.json());
    setSessions(fresh);
    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("/schedule").then(r => r.json());
      setSessions(fresh);
      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/schedule" 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 }}>My Schedule</div>
            <div className="mono" style={{ fontSize:11, color:"var(--ink-mute)" }}>{teacherName || "Teacher"} · {TEACHER_MY_SESSIONS.length} sessions{pendingReqCount ? ` · ${pendingReqCount} pending request${pendingReqCount===1?"":"s"}` : ""}</div>
          </div>
          <div style={{ flex:1 }}/>
          <div style={{ display:"flex", gap:10, alignItems:"center" }}>
            {[["live","var(--coral)"],["upcoming","var(--moss)"],["done","var(--ink-mute)"]].map(([l,c])=>(
              <span key={l} style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:12, color:"var(--ink-mute)" }}>
                <span style={{ width:8, height:8, borderRadius:"50%", background:c, display:"inline-block" }}/>{l}
              </span>
            ))}
            <button
              className="btn btn-ghost"
              onClick={() => setShowMyRequests(v => !v)}
              style={{ fontSize:12, padding:"5px 12px", border:"var(--border-thin)", marginLeft:6 }}
            >
              📋 Requests {pendingReqCount > 0 ? `(${pendingReqCount} pending)` : `(${reqList.length})`}
            </button>
            <button
              className="btn btn-primary"
              onClick={() => { setShowReqModal(true); setReqError(""); }}
              style={{ fontSize:12, padding:"6px 14px" }}
            >
              + Request session
            </button>
          </div>
        </div>

        <div style={{ flex:1, overflow:"auto", padding:22, display:"flex", flexDirection:"column", gap:20 }}>
          {showMyRequests && (
            <div className="card-flat" style={{ padding: 18, border: "var(--border-thin)", background: "var(--paper-card)" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>My Session Requests ({reqList.length})</div>
                <button
                  onClick={() => setShowMyRequests(false)}
                  style={{ background: "none", border: "none", color: "var(--ink-mute)", cursor: "pointer", fontSize: 18, lineHeight: 1 }}
                >
                  ×
                </button>
              </div>
              {!reqList.length ? (
                <div style={{ color: "var(--ink-mute)", fontSize: 13, textAlign: "center", padding: 16 }}>
                  You haven't submitted any session requests yet. Use "+ Request session" to propose extra or make-up classes.
                </div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 8, maxHeight: 320, overflowY: "auto" }}>
                  {reqList.map(r => (
                    <div
                      key={r.id}
                      style={{
                        padding: 12,
                        borderRadius: 8,
                        background: "var(--paper-deep)",
                        borderLeft: `4px solid ${r.status === "approved" ? "var(--moss)" : r.status === "rejected" ? "var(--coral)" : "var(--gold)"}`,
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        gap: 12,
                      }}
                    >
                      <div>
                        <div style={{ fontWeight: 700, fontSize: 13 }}>
                          {r.day} · {r.time_start} – {r.time_end} ({r.timezone || "Asia/Kolkata"})
                        </div>
                        <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 2 }}>
                          {r.batch_name ? `Batch: ${r.batch_name}` : r.student_name ? `1-on-1: ${r.student_name}` : "Session"} · Reason: {r.reason}
                        </div>
                        {r.admin_response && (
                          <div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 4 }}>
                            ↳ Admin Note: {r.admin_response}
                          </div>
                        )}
                        {r.session_id && (
                          <div className="mono" style={{ fontSize: 10, color: "var(--moss)", marginTop: 3 }}>
                            ✓ Scheduled as Session #{r.session_id}
                          </div>
                        )}
                      </div>
                      <div style={{ textAlign: "right", flexShrink: 0 }}>
                        <span style={{
                          display: "inline-block",
                          padding: "2px 8px",
                          borderRadius: 12,
                          fontSize: 10,
                          fontWeight: 700,
                          textTransform: "uppercase",
                          letterSpacing: ".05em",
                          background: r.status === "approved" ? "rgba(46,125,50,0.15)" : r.status === "rejected" ? "rgba(211,47,47,0.15)" : "rgba(245,124,0,0.15)",
                          color: r.status === "approved" ? "var(--moss)" : r.status === "rejected" ? "var(--coral)" : "var(--gold)",
                        }}>
                          {r.status}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Stats row */}
          <div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap:14 }}>
            {[
              { l:"MY BATCHES",   v:[...new Set(TEACHER_MY_SESSIONS.map(s=>s.batch))].length, c:"var(--sky)"   },
              { l:"THIS WEEK",    v:TEACHER_MY_SESSIONS.length, c:"var(--coral)" },
              { l:"LIVE NOW",     v:TEACHER_MY_SESSIONS.filter(s=>s.status==="live").length, c:"var(--coral)" },
              { l:"TOTAL STUDENTS", v:TEACHER_MY_SESSIONS.reduce((a,s)=>a+(s.students||0),0), c:"var(--moss)" },
            ].map(k=>(
              <div key={k.l} className="card-flat" style={{ padding:14 }}>
                <div className="mono" style={{ fontSize:10, color:"var(--ink-mute)", letterSpacing:".06em" }}>{k.l}</div>
                <div className="display" style={{ fontSize:28, marginTop:4, color:k.c }}>{k.v}</div>
              </div>
            ))}
          </div>

          {/* Sessions by day */}
          {days.map(day => (
            <div key={day}>
              <div className="mono" style={{ fontSize:11, color:"var(--ink-mute)", fontWeight:700, marginBottom:10, letterSpacing:".06em" }}>{fmtDay(day)}</div>
              <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
                {TEACHER_MY_SESSIONS.filter(s=>s.day===day).map(s => (
                  <div key={s.id} className="card-flat" style={{ padding:16, display:"grid", gridTemplateColumns:"100px 1fr 1fr auto", alignItems:"center", gap:16, borderLeft:`3px solid ${statusColor(s.status)}` }}>
                    <div>
                      <div style={{ fontWeight:700, fontSize:14 }}>{s.time}</div>
                      <div style={{ fontSize:11, color:"var(--ink-mute)" }}>–{s.end}</div>
                      {s.rescheduled_from && (
                        <div style={{ fontSize:10, color:"var(--gold)", marginTop:3, fontWeight:600 }} title={s.reschedule_reason ? `Reason: ${s.reschedule_reason}` : ""}>
                          ↳ From {s.rescheduled_from}
                        </div>
                      )}
                    </div>
                    <div>
                      <div style={{ fontWeight:700, fontSize:14 }}>{s.batch}</div>
                      <div style={{ fontSize:12, color:"var(--ink-mute)" }}>{s.course}</div>
                    </div>
                    <div style={{ fontSize:12, color:"var(--ink-soft)" }}>
                      <span className="chip flat" style={{ fontSize:10, marginRight:8 }}>{s.students} students</span>
                      <span className="chip flat" style={{ fontSize:10, background:statusColor(s.status), color:s.status==="not_conducted"?"black":"white" }}>{s.status==="not_conducted"?"not conducted":s.status}</span>
                    </div>
                    <div style={{ display:"flex", gap:6, alignItems:"center" }}>
                      {s.meet && s.status !== "done" && (
                        <a href={normalizeUrl(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:14 })} Join class
                        </a>
                      )}
                      {s.status === "done" && (
                        <button onClick={() => go && go("/app/teacher/attendance")} className="btn btn-ghost" style={{ padding:"6px 12px", fontSize:12 }}>
                          {I.check({ size:14 })} 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:13 }) : "📝"} Remarks
                        </button>
                      )}
                      {s.status !== "done" && s.status !== "not_conducted" && (
                        <button
                          type="button"
                          onClick={() => { setNcSession(s); setNcReason(""); setNcError(""); }}
                          className="btn btn-ghost"
                          style={{ padding:"4px 8px", fontSize:11, color:"var(--coral)" }}
                          title="Mark this session as not conducted"
                        >
                          Not conducted
                        </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>
        {ncSession && (
          <Modal title="Mark session not conducted" onClose={() => { setNcSession(null); setNcError(""); }}>
            <form onSubmit={submitNotConducted}>
              <div style={{ background: "var(--paper-deep)", border: "var(--border-thin)", borderRadius: 8, padding: 12, marginBottom: 14, fontSize: 13 }}>
                <div style={{ fontWeight: 700, marginBottom: 4 }}>
                  {ncSession.batch || "Class"} · {ncSession.day} ({ncSession.time})
                </div>
                {ncSession.series_id ? (
                  <div style={{ color: "var(--ink-soft)", fontSize: 12, lineHeight: 1.5 }}>
                    This session is part of a recurring series. Marking it not conducted will shift this session forward by 1 interval to serve as the make-up class, along with all subsequent sessions in the series. <strong>Total session count will remain constant.</strong>
                  </div>
                ) : (
                  <div style={{ color: "var(--ink-soft)", fontSize: 12, lineHeight: 1.5 }}>
                    This is a single standalone session (not part of a recurring series). It will be marked as not conducted without shifting any other sessions.
                  </div>
                )}
              </div>

              <FormField label="REASON (OPTIONAL)">
                <input
                  style={{ width: "100%", padding: "8px 12px", border: "var(--border-thin)", borderRadius: 6, background: "var(--paper-card)", color: "var(--ink)", fontSize: 13 }}
                  value={ncReason}
                  onChange={e => setNcReason(e.target.value)}
                  placeholder="e.g. Teacher unwell, holiday, technical outage"
                  autoFocus
                />
              </FormField>

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

              <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}>
                <button type="button" onClick={() => { setNcSession(null); setNcError(""); }} className="btn btn-ghost">
                  Cancel
                </button>
                <button type="submit" disabled={ncSaving} className="btn btn-primary" style={{ background: "var(--coral)" }}>
                  {ncSaving ? "Updating…" : ncSession.series_id ? "Reschedule series" : "Mark not conducted"}
                </button>
              </div>
            </form>
          </Modal>
        )}
        {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>
        )}
        {showReqModal && (
          <Modal title="Request a session" onClose={() => { setShowReqModal(false); setReqError(""); }}>
            <form onSubmit={submitRequest}>
              <div style={{ color: "var(--ink-soft)", fontSize: 12, marginBottom: 14, lineHeight: 1.5 }}>
                Propose an extra class, make-up session, or 1-on-1 review. An admin will review and schedule it into the master calendar.
              </div>

              <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
                {[["batch", "Batch class"], ["individual", "1-on-1 student"]].map(([t, l]) => (
                  <button
                    key={t}
                    type="button"
                    onClick={() => setReqSessType(t)}
                    style={{
                      flex: 1, padding: "8px 0", borderRadius: 8, border: "var(--border-thin)", fontSize: 12,
                      background: reqSessType === t ? "var(--coral)" : "var(--paper-deep)",
                      color: reqSessType === t ? "white" : "var(--ink-soft)",
                      cursor: "pointer",
                      fontWeight: 600
                    }}
                  >
                    {l}
                  </button>
                ))}
              </div>

              {reqSessType === "batch" ? (
                <FormField label="BATCH">
                  <select
                    required
                    style={{ width: "100%", padding: "8px 12px", border: "var(--border-thin)", borderRadius: 6, background: "var(--paper-card)", color: "var(--ink)", fontSize: 13 }}
                    value={reqForm.batch_id}
                    onChange={e => setReqForm(f => ({ ...f, batch_id: e.target.value }))}
                  >
                    <option value="">— select batch —</option>
                    {(BATCHES || []).map(b => <option key={b.id} value={b.id}>{b.name} ({b.course || b.course_name || ""})</option>)}
                  </select>
                </FormField>
              ) : (
                <FormField label="STUDENT (1-ON-1)">
                  <select
                    required
                    style={{ width: "100%", padding: "8px 12px", border: "var(--border-thin)", borderRadius: 6, background: "var(--paper-card)", color: "var(--ink)", fontSize: 13 }}
                    value={reqForm.student_id}
                    onChange={e => setReqForm(f => ({ ...f, student_id: e.target.value }))}
                  >
                    <option value="">— select student —</option>
                    {(STUDENTS || []).map(s => <option key={s.id} value={s.id}>{s.name} ({s.course || s.course_name || s.email || ""})</option>)}
                  </select>
                </FormField>
              )}

              <FormField label="PROPOSED DATE">
                <input
                  type="date"
                  required
                  style={{ width: "100%", padding: "8px 12px", border: "var(--border-thin)", borderRadius: 6, background: "var(--paper-card)", color: "var(--ink)", fontSize: 13 }}
                  value={reqForm.day}
                  onChange={e => setReqForm(f => ({ ...f, day: e.target.value }))}
                />
              </FormField>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                <FormField label="START TIME">
                  <input
                    type="time"
                    required
                    style={{ width: "100%", padding: "8px 12px", border: "var(--border-thin)", borderRadius: 6, background: "var(--paper-card)", color: "var(--ink)", fontSize: 13 }}
                    value={reqForm.time_start}
                    onChange={e => setReqForm(f => ({ ...f, time_start: e.target.value }))}
                  />
                </FormField>
                <FormField label="END TIME">
                  <input
                    type="time"
                    required
                    style={{ width: "100%", padding: "8px 12px", border: "var(--border-thin)", borderRadius: 6, background: "var(--paper-card)", color: "var(--ink)", fontSize: 13 }}
                    value={reqForm.time_end}
                    onChange={e => setReqForm(f => ({ ...f, time_end: e.target.value }))}
                  />
                </FormField>
              </div>

              <FormField label="TIMEZONE">
                <TimezoneSelect
                  id="teacher-req-session-tz"
                  value={reqForm.timezone || "Asia/Kolkata"}
                  onChange={e => setReqForm(f => ({ ...f, timezone: e.target.value }))}
                  triggerStyle={{ borderRadius: 6, background: "var(--paper-card)" }}
                />
              </FormField>

              <FormField label="REASON / TOPIC COVERED">
                <textarea
                  required
                  style={{ width: "100%", minHeight: 70, padding: "8px 12px", border: "var(--border-thin)", borderRadius: 6, background: "var(--paper-card)", color: "var(--ink)", fontSize: 13, resize: "vertical" }}
                  value={reqForm.reason}
                  onChange={e => setReqForm(f => ({ ...f, reason: e.target.value }))}
                  placeholder="e.g. Extra doubt clearing session for exam prep"
                />
              </FormField>

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

              <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}>
                <button
                  type="button"
                  onClick={() => { setShowReqModal(false); setReqError(""); }}
                  className="btn btn-ghost"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={reqSaving}
                  className="btn btn-primary"
                >
                  {reqSaving ? "Submitting…" : "Submit Request"}
                </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>
        )}
      </div>
    </Themed>
  );
};
