// screens-attendance.jsx — Class-teacher attendance flow
// 1. TeacherAttendanceMarkScreen — daily roster with P / A / Late / Leave toggles
// 2. TeacherAttendanceHistoryScreen — month grid + per-student % + low-attendance flag
// 3. TeacherAttendancePeriodCheckinScreen — subject-teacher per-period check-in
// All three reuse CLASS_8B_STUDENTS (from screens-assessments.jsx via window).

const { useState: useStateAtt, useMemo: useMemoAtt } = React;

// State palette: 4 attendance codes (CBSE convention).
const ATT_STATES = {
  P:  { lab: 'Present', short: 'P', bg: 'var(--success-50)', clr: 'var(--success)', border: 'rgba(16,185,129,.35)' },
  A:  { lab: 'Absent',  short: 'A', bg: 'var(--c50)',        clr: 'var(--c600)',    border: 'rgba(239,68,68,.35)'  },
  L:  { lab: 'Late',    short: 'L', bg: '#FEF3C7',           clr: 'var(--warning)', border: 'rgba(217,119,6,.35)'  },
  E:  { lab: 'Leave',   short: 'E', bg: 'var(--info-50)',    clr: '#1E40AF',        border: 'rgba(37,99,235,.35)'  },
};

// Deterministic baseline so re-renders feel stable.
function buildAttRoster(date) {
  const seed = (date || '').split('').reduce((s, c) => s + c.charCodeAt(0), 13);
  return (window.CLASS_8B_STUDENTS || []).map((name, i) => {
    const r = (Math.sin(seed * 91 + i * 13) * 10000) % 1;
    const x = (r + 1) % 1;
    let state = 'P';
    if (x < 0.06) state = 'A';
    else if (x < 0.10) state = 'L';
    else if (x < 0.12) state = 'E';
    return {
      id: 's' + (i + 1).toString().padStart(2, '0'),
      name,
      initial: name[0],
      clr: ['', 'coral', 'green', 'sky', 'violet'][i % 5],
      pct: 78 + ((i * 17) % 22),
      state,
      reason: '',
    };
  });
}

// ─────────────────────────────────────────────────────────────
// 1. Mark attendance (homeroom · daily)
// ─────────────────────────────────────────────────────────────
function TeacherAttendanceMarkScreen({ nav, params }) {
  const cls = (params && params.cls) || '8-B';
  const period = (params && params.period) || null; // null = homeroom
  const today = 'Wed · 12 Mar';
  const [roster, setRoster] = useStateAtt(() => buildAttRoster(today + cls));
  const [search, setSearch] = useStateAtt('');
  const [reasonFor, setReasonFor] = useStateAtt(null); // {id, state} when prompting
  const [reasonText, setReasonText] = useStateAtt('');
  const [savedToast, setSavedToast] = useStateAtt(false);

  const setState = (id, st) => {
    setRoster(rs => rs.map(r => r.id === id ? { ...r, state: st } : r));
    if (st === 'A' || st === 'E') {
      const stu = roster.find(r => r.id === id);
      if (stu) { setReasonFor({ id, state: st }); setReasonText(stu.reason || ''); }
    }
  };
  const markAllPresent = () => setRoster(rs => rs.map(r => ({ ...r, state: 'P', reason: '' })));
  const saveReason = () => {
    if (!reasonFor) return;
    setRoster(rs => rs.map(r => r.id === reasonFor.id ? { ...r, reason: reasonText } : r));
    setReasonFor(null); setReasonText('');
  };

  const counts = useMemoAtt(() => {
    return roster.reduce((acc, r) => { acc[r.state] = (acc[r.state] || 0) + 1; return acc; }, { P: 0, A: 0, L: 0, E: 0 });
  }, [roster]);
  const total = roster.length;
  const presentPct = Math.round((counts.P / total) * 100);

  const filtered = roster.filter(r => !search || r.name.toLowerCase().includes(search.toLowerCase()));
  const absent = roster.filter(r => r.state === 'A');

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title={period ? `Period ${period} attendance` : 'Mark attendance'} onBack={() => nav.pop()}
        right={<button onClick={markAllPresent} style={{ height: 32, padding: '0 12px', borderRadius: 8, background: 'var(--success-50)', color: 'var(--success)', fontSize: 11, fontWeight: 700, fontFamily: 'var(--mono)', letterSpacing: '.04em' }}>ALL PRESENT</button>}/>

      <div className="app-body" style={{ paddingTop: 4 }}>
        {/* Context strip */}
        <div className="card" style={{ padding: 14, marginBottom: 12, background: '#fff' }}>
          <div className="spread" style={{ alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'var(--mono)' }}>{today}</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--n900)', marginTop: 2 }}>Class {cls} · Math</div>
              <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{total} students · Room 204</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--success)', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{presentPct}%</div>
              <div style={{ fontSize: 10, color: 'var(--n500)', marginTop: 2, fontFamily: 'var(--mono)' }}>PRESENT</div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 6, marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--n100)' }}>
            {Object.entries(ATT_STATES).map(([k, st]) => (
              <div key={k} style={{ background: st.bg, color: st.clr, padding: '8px 4px', borderRadius: 8, textAlign: 'center' }}>
                <div style={{ fontSize: 16, fontWeight: 800, fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{counts[k] || 0}</div>
                <div style={{ fontSize: 9.5, fontWeight: 700, marginTop: 3, letterSpacing: '.04em' }}>{st.lab.toUpperCase()}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Search */}
        <div style={{ position: 'relative', marginBottom: 10 }}>
          <Icon name="search" size={16} style={{ position: 'absolute', left: 12, top: 12, color: 'var(--n400)' }}/>
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search students…" style={{
            width: '100%', height: 40, paddingLeft: 36, paddingRight: 12, borderRadius: 12,
            border: '1px solid var(--n200)', background: '#fff', fontSize: 13, fontFamily: 'inherit',
          }}/>
        </div>

        {/* Roster */}
        <div className="col" style={{ gap: 6 }}>
          {filtered.map(s => {
            const st = ATT_STATES[s.state];
            return (
              <div key={s.id} className="card" style={{ padding: 10, background: '#fff' }}>
                <div className="row" style={{ gap: 10 }}>
                  <div className={`av av-36 ${s.clr}`} style={{ flexShrink: 0 }}>{s.initial}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{s.name}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 1, fontFamily: 'var(--mono)' }}>
                      Term · {s.pct}% {s.pct < 75 && <span style={{ color: 'var(--c600)', fontWeight: 700 }}>· at risk</span>}
                    </div>
                    {s.reason && <div style={{ fontSize: 11, color: st.clr, marginTop: 2 }}>{st.lab}: {s.reason}</div>}
                  </div>
                  <div className="row" style={{ gap: 4, flexShrink: 0 }}>
                    {Object.keys(ATT_STATES).map(k => {
                      const ss = ATT_STATES[k];
                      const active = s.state === k;
                      return (
                        <button key={k} onClick={() => setState(s.id, k)} style={{
                          width: 32, height: 32, borderRadius: 8,
                          background: active ? ss.clr : '#fff',
                          color: active ? '#fff' : ss.clr,
                          border: `1px solid ${active ? ss.clr : ss.border}`,
                          fontSize: 12, fontWeight: 800, fontFamily: 'var(--mono)',
                          transition: 'all .12s',
                        }}>{ss.short}</button>
                      );
                    })}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Save */}
        <div style={{ marginTop: 16, display: 'grid', gap: 8 }}>
          {absent.length > 0 && (
            <div style={{ background: 'var(--c50)', border: '1px solid rgba(239,68,68,.2)', borderRadius: 12, padding: 12 }}>
              <div className="spread">
                <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--c700)' }}>{absent.length} absent · auto-SMS to parents</div>
                <Toggle value={true} onChange={() => {}}/>
              </div>
              <div style={{ fontSize: 10.5, color: 'var(--c700)', opacity: .8, marginTop: 4 }}>{absent.slice(0,3).map(a => a.name.split(' ')[0]).join(', ')}{absent.length > 3 ? ` +${absent.length - 3} more` : ''}</div>
            </div>
          )}
          <button onClick={() => { setSavedToast(true); setTimeout(() => { setSavedToast(false); nav.pop(); }, 900); }} className="btn-primary" style={{ height: 48 }}>
            Save attendance · {today}
          </button>
        </div>
      </div>

      {/* Reason sheet */}
      {reasonFor && (
        <div onClick={() => setReasonFor(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(15,18,30,.45)', zIndex: 80, display: 'flex', alignItems: 'flex-end' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: '#fff', width: '100%', borderRadius: '20px 20px 0 0', padding: 20 }}>
            <div style={{ width: 44, height: 5, borderRadius: 4, background: 'var(--n200)', margin: '0 auto 14px' }}/>
            <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--n900)' }}>Reason ({ATT_STATES[reasonFor.state].lab})</div>
            <div style={{ fontSize: 12, color: 'var(--n500)', marginTop: 2, marginBottom: 12 }}>Optional but useful for the parent SMS</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 6, marginBottom: 10 }}>
              {(reasonFor.state === 'E'
                ? ['Sick leave','Family function','Medical appt.','Approved by HOD']
                : ['No reason given','Sick','Bus delay','Family emergency']
              ).map(r => (
                <button key={r} onClick={() => setReasonText(r)} style={{
                  padding: '10px 12px', borderRadius: 10,
                  background: reasonText === r ? 'var(--p50)' : 'var(--n50)',
                  color: reasonText === r ? 'var(--p700)' : 'var(--n700)',
                  fontSize: 11.5, fontWeight: 600, textAlign: 'left',
                  border: reasonText === r ? '1px solid var(--p600)' : '1px solid transparent',
                }}>{r}</button>
              ))}
            </div>
            <textarea value={reasonText} onChange={(e) => setReasonText(e.target.value)} rows={2} placeholder="Or type a custom note…" style={{
              width: '100%', padding: 10, borderRadius: 10, border: '1px solid var(--n200)',
              fontSize: 13, fontFamily: 'inherit', resize: 'none',
            }}/>
            <button onClick={saveReason} className="btn-primary" style={{ height: 44, marginTop: 12, width: '100%' }}>Save</button>
          </div>
        </div>
      )}

      {savedToast && (
        <div style={{ position: 'absolute', bottom: 32, left: 16, right: 16, background: 'var(--n900)', color: '#fff', padding: '12px 14px', borderRadius: 12, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 10, boxShadow: '0 12px 32px rgba(0,0,0,.25)', zIndex: 70 }}>
          <Icon name="check" size={16} style={{ color: 'var(--success)' }}/> Attendance saved · {counts.A} parent SMS queued
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. Attendance history (month grid + flagged students)
// ─────────────────────────────────────────────────────────────
function TeacherAttendanceHistoryScreen({ nav, params }) {
  const cls = (params && params.cls) || '8-B';
  const [view, setView] = useStateAtt('grid'); // 'grid' | 'flag'
  const [month, setMonth] = useStateAtt('March 2025');

  // 22 working days × 32 students grid (deterministic).
  const days = Array.from({ length: 22 }, (_, i) => i + 1);
  const students = (window.CLASS_8B_STUDENTS || []).slice(0, 18); // viewport-friendly
  const grid = useMemoAtt(() => students.map((name, si) => {
    return days.map(d => {
      const r = (Math.sin(si * 31 + d * 7) * 10000) % 1;
      const x = (r + 1) % 1;
      if (x < 0.05) return 'A';
      if (x < 0.08) return 'L';
      if (x < 0.10) return 'E';
      return 'P';
    });
  }), []);
  const studentPct = grid.map(row => Math.round((row.filter(c => c === 'P' || c === 'L').length / row.length) * 100));
  const flagged = students.map((name, i) => ({ name, pct: studentPct[i], absent: grid[i].filter(c => c === 'A').length }))
    .filter(s => s.pct < 75)
    .sort((a, b) => a.pct - b.pct);

  const overallPct = Math.round(studentPct.reduce((s, x) => s + x, 0) / studentPct.length);

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="Attendance history" onBack={() => nav.pop()}
        right={<button style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}><Icon name="download" size={16}/></button>}/>

      <div className="app-body" style={{ paddingTop: 4 }}>
        {/* Summary card */}
        <div className="card" style={{ padding: 14, background: '#fff', marginBottom: 12 }}>
          <div className="spread" style={{ alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'var(--mono)' }}>Class {cls} · {month}</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', marginTop: 4, fontVariantNumeric: 'tabular-nums', letterSpacing: '-.02em' }}>{overallPct}%</div>
              <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1 }}>22 working days · 32 students</div>
            </div>
            <button onClick={() => { /* prev month */ }} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 10px', borderRadius: 8, background: 'var(--n50)', fontSize: 11, fontWeight: 700, color: 'var(--n700)', fontFamily: 'var(--mono)' }}>
              <Icon name="chev-l" size={12}/> {month}
            </button>
          </div>
        </div>

        {/* Tabs */}
        <div className="row" style={{ gap: 6, marginBottom: 12 }}>
          {[
            { id: 'grid', lab: 'Day grid' },
            { id: 'flag', lab: `Below 75%${flagged.length ? ` · ${flagged.length}` : ''}` },
          ].map(tb => (
            <button key={tb.id} onClick={() => setView(tb.id)} style={{
              flex: 1, padding: '10px 10px', borderRadius: 10,
              background: view === tb.id ? 'var(--n900)' : '#fff',
              color: view === tb.id ? '#fff' : 'var(--n700)',
              fontSize: 12, fontWeight: 700,
              border: '1px solid var(--n100)',
            }}>{tb.lab}</button>
          ))}
        </div>

        {view === 'grid' && (
          <div className="card" style={{ padding: 0, background: '#fff', overflow: 'hidden' }}>
            <div style={{ overflowX: 'auto' }}>
              <table style={{ borderCollapse: 'collapse', fontSize: 10, fontFamily: 'var(--mono)', minWidth: '100%' }}>
                <thead>
                  <tr>
                    <th style={{ padding: '8px 8px', textAlign: 'left', position: 'sticky', left: 0, background: 'var(--n50)', borderBottom: '1px solid var(--n100)', minWidth: 110 }}>Student</th>
                    {days.map(d => (
                      <th key={d} style={{ padding: '6px 4px', minWidth: 18, color: 'var(--n500)', fontWeight: 700, borderBottom: '1px solid var(--n100)' }}>{d}</th>
                    ))}
                    <th style={{ padding: '8px 8px', borderBottom: '1px solid var(--n100)' }}>%</th>
                  </tr>
                </thead>
                <tbody>
                  {students.map((name, si) => (
                    <tr key={si} style={{ borderBottom: '1px solid var(--n100)' }}>
                      <td style={{ padding: '6px 8px', position: 'sticky', left: 0, background: '#fff', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, color: 'var(--n800)' }}>{name.split(' ')[0]} {name.split(' ')[1]?.[0]}.</td>
                      {grid[si].map((c, ci) => {
                        const st = ATT_STATES[c];
                        return (
                          <td key={ci} style={{ padding: 0, textAlign: 'center' }}>
                            <div style={{ width: 16, height: 16, margin: '2px auto', borderRadius: 3, background: c === 'P' ? 'var(--success-50)' : st.bg, color: st.clr, fontSize: 8, fontWeight: 800, display: 'grid', placeItems: 'center' }}>{c === 'P' ? '' : c}</div>
                          </td>
                        );
                      })}
                      <td style={{ padding: '6px 8px', fontWeight: 800, color: studentPct[si] < 75 ? 'var(--c600)' : 'var(--n800)' }}>{studentPct[si]}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="row" style={{ padding: '10px 12px', borderTop: '1px solid var(--n100)', gap: 12, fontSize: 10, color: 'var(--n500)', fontFamily: 'var(--mono)', flexWrap: 'wrap' }}>
              {Object.entries(ATT_STATES).map(([k, st]) => (
                <div key={k} className="row" style={{ gap: 4 }}>
                  <div style={{ width: 12, height: 12, borderRadius: 3, background: k === 'P' ? 'var(--success-50)' : st.bg, color: st.clr, fontSize: 8, fontWeight: 800, display: 'grid', placeItems: 'center' }}>{k === 'P' ? '' : k}</div>
                  <span>{st.lab}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {view === 'flag' && (
          <div>
            {flagged.length === 0 ? (
              <div className="card" style={{ padding: 28, textAlign: 'center', background: '#fff' }}>
                <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--success-50)', color: 'var(--success)', display: 'grid', placeItems: 'center', margin: '0 auto 12px' }}>
                  <Icon name="check" size={24}/>
                </div>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--n900)' }}>No students below 75%</div>
                <div style={{ fontSize: 12, color: 'var(--n500)', marginTop: 4 }}>All students meet exam-eligibility threshold.</div>
              </div>
            ) : (
              <div className="col" style={{ gap: 8 }}>
                <div style={{ background: 'var(--warning-50)', border: '1px solid rgba(217,119,6,.25)', borderRadius: 12, padding: 12, marginBottom: 4 }}>
                  <div className="row" style={{ gap: 10 }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--warning)', color: '#fff', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="alert" size={16}/></div>
                    <div>
                      <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{flagged.length} students below CBSE 75% threshold</div>
                      <div style={{ fontSize: 11, color: 'var(--n600)', marginTop: 2 }}>Notify parents · flag for HOD review · exam ineligibility risk.</div>
                    </div>
                  </div>
                </div>
                {flagged.map((s, i) => (
                  <button key={i} onClick={() => nav.push('teachStudentProfile', { id: 's' + (i+1).toString().padStart(2,'0'), name: s.name })} className="card row" style={{ padding: 12, gap: 10, background: '#fff', textAlign: 'left' }}>
                    <div className="av av-40">{s.name[0]}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{s.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2, fontFamily: 'var(--mono)' }}>{s.absent} days absent this term</div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--c600)', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{s.pct}%</div>
                      <div style={{ fontSize: 10, color: 'var(--c600)', fontWeight: 700, fontFamily: 'var(--mono)', marginTop: 2 }}>AT RISK</div>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3. Period check-in (subject teacher)
// ─────────────────────────────────────────────────────────────
function TeacherAttendancePeriodCheckinScreen({ nav, params }) {
  const day = (params && params.day) || 'Wed · 12 Mar';
  const grid = [
    { p: 1, time: '8:00–8:45', cls: '8-B', sub: 'Math', state: 'done', present: 31, total: 32 },
    { p: 2, time: '8:45–9:30', cls: '9-A', sub: 'Math', state: 'done', present: 26, total: 28 },
    { p: 3, time: '9:30–10:15', cls: '—',   sub: 'Free',  state: 'free' },
    { p: 4, time: '10:30–11:15', cls: '8-B', sub: 'Math', state: 'live', present: null, total: 32 },
    { p: 5, time: '11:15–12:00', cls: '10-C', sub: 'Math', state: 'pending', present: null, total: 30 },
    { p: 6, time: '12:00–12:45', cls: '—',   sub: 'Lunch', state: 'free' },
    { p: 7, time: '1:30–2:15', cls: '9-A', sub: 'Math', state: 'pending', present: null, total: 28 },
    { p: 8, time: '2:15–3:00', cls: '10-C', sub: 'Math', state: 'pending', present: null, total: 30 },
  ];
  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="Period attendance" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 4 }}>
        <div className="card" style={{ padding: 14, marginBottom: 12 }}>
          <div className="spread">
            <div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'var(--mono)' }}>{day}</div>
              <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--n900)', marginTop: 2 }}>5 of 6 teaching periods</div>
            </div>
            <button onClick={() => nav.push('teachTimetable')} className="btn-ghost" style={{ fontSize: 12, fontWeight: 600 }}>Full week →</button>
          </div>
        </div>

        <div className="col" style={{ gap: 8 }}>
          {grid.map(p => {
            const isLive = p.state === 'live';
            const isFree = p.state === 'free';
            const isDone = p.state === 'done';
            const accent = isLive ? 'var(--p600)' : isDone ? 'var(--success)' : isFree ? 'var(--n300)' : 'var(--warning)';
            return (
              <button key={p.p} disabled={isFree}
                onClick={() => nav.push('teachAttendanceMark', { cls: p.cls, period: p.p })}
                className="card" style={{
                  padding: 14, background: '#fff', textAlign: 'left',
                  opacity: isFree ? .55 : 1, cursor: isFree ? 'default' : 'pointer',
                  position: 'relative', overflow: 'hidden',
                  border: isLive ? '1px solid var(--p600)' : '1px solid var(--n100)',
                }}>
                {!isFree && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 4, background: accent }}/>}
                <div className="row" style={{ gap: 12 }}>
                  <div style={{ width: 44, textAlign: 'center', flexShrink: 0 }}>
                    <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{p.p}</div>
                    <div style={{ fontSize: 9, color: 'var(--n500)', fontFamily: 'var(--mono)', fontWeight: 700, marginTop: 2 }}>PERIOD</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="spread">
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{isFree ? p.sub : `${p.cls} · ${p.sub}`}</div>
                        <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 1, fontFamily: 'var(--mono)' }}>{p.time}</div>
                      </div>
                      {isDone && <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--success)', fontFamily: 'var(--mono)' }}>{p.present}/{p.total}</div>}
                      {isLive && <span className="pill" style={{ background: 'var(--success-50)', color: 'var(--success)', fontSize: 9.5, fontWeight: 800, fontFamily: 'var(--mono)', letterSpacing: '.08em' }}>● LIVE</span>}
                      {p.state === 'pending' && <span className="pill pill-s" style={{ background: 'var(--warning-50)', color: 'var(--warning)', fontSize: 9.5, fontFamily: 'var(--mono)', fontWeight: 700 }}>PENDING</span>}
                      {isFree && <span style={{ fontSize: 10, color: 'var(--n400)', fontFamily: 'var(--mono)', fontWeight: 700 }}>—</span>}
                    </div>
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  TeacherAttendanceMarkScreen,
  TeacherAttendanceHistoryScreen,
  TeacherAttendancePeriodCheckinScreen,
});
