// screens-admin.jsx — Term-level admin for class teachers
// 1. TeacherLeaveApplyScreen — apply for leave (auto-cascades to sub-request flow)
// 2. TeacherExamScheduleScreen — read-only formal school exam slots
// 3. TeacherReportPublishScreen — bulk-publish report cards at end of term

const { useState: useStateAD, useMemo: useMemoAD } = React;

// ─────────────────────────────────────────────────────────────
// 1. Apply for leave
// ─────────────────────────────────────────────────────────────
function TeacherLeaveApplyScreen({ nav }) {
  const [from, setFrom] = useStateAD('2025-03-20');
  const [to, setTo] = useStateAD('2025-03-21');
  const [type, setType] = useStateAD('CL'); // CL/SL/EL/HD
  const [reason, setReason] = useStateAD('');
  const [substitute, setSubstitute] = useStateAD('handle-via-sub-request');
  const [savedToast, setSavedToast] = useStateAD(false);

  const balance = { CL: { used: 4, total: 12 }, SL: { used: 1, total: 6 }, EL: { used: 0, total: 15 } };
  const days = useMemoAD(() => {
    if (!from || !to) return 0;
    const a = new Date(from), b = new Date(to);
    const diff = Math.round((b - a) / (1000 * 60 * 60 * 24)) + 1;
    return Math.max(1, diff);
  }, [from, to]);

  const save = () => {
    setSavedToast(true);
    setTimeout(() => {
      setSavedToast(false);
      if (substitute === 'handle-via-sub-request') {
        nav.replace('teachSubstituteRequest');
      } else {
        nav.pop();
      }
    }, 1100);
  };

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="Apply for leave" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 4 }}>

        {/* Balance card */}
        <div className="card" style={{ padding: 14, background: '#fff', marginBottom: 12 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 8 }}>Leave balance · 24–25</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
            {Object.entries(balance).map(([k, b]) => (
              <div key={k} style={{ padding: 10, borderRadius: 10, background: 'var(--n50)', textAlign: 'center' }}>
                <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--n900)', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{b.total - b.used}</div>
                <div style={{ fontSize: 9.5, color: 'var(--n500)', fontFamily: 'var(--mono)', fontWeight: 700, marginTop: 4, letterSpacing: '.04em' }}>{k} LEFT</div>
                <div style={{ fontSize: 9, color: 'var(--n400)', fontFamily: 'var(--mono)', marginTop: 2 }}>of {b.total}</div>
              </div>
            ))}
          </div>
        </div>

        <FieldT label="Leave type" required>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {[
              { id: 'CL', lab: 'Casual' },
              { id: 'SL', lab: 'Sick' },
              { id: 'EL', lab: 'Earned' },
              { id: 'HD', lab: 'Half-day' },
            ].map(t => (
              <button key={t.id} onClick={() => setType(t.id)} style={{
                padding: '8px 14px', borderRadius: 10,
                background: type === t.id ? 'var(--p600)' : '#fff',
                color: type === t.id ? '#fff' : 'var(--n700)',
                border: type === t.id ? '1px solid var(--p600)' : '1px solid var(--n200)',
                fontSize: 12, fontWeight: 700,
              }}>{t.lab}</button>
            ))}
          </div>
        </FieldT>

        <div className="row" style={{ gap: 10, marginBottom: 14 }}>
          <FieldT label="From" style={{ flex: 1, marginBottom: 0 }}>
            <input type="date" value={from} onChange={(e) => setFrom(e.target.value)} style={{
              width: '100%', height: 44, padding: '0 12px', borderRadius: 12,
              border: '1px solid var(--n200)', background: '#fff', fontSize: 13, fontFamily: 'inherit',
            }}/>
          </FieldT>
          <FieldT label="To" style={{ flex: 1, marginBottom: 0 }}>
            <input type="date" value={to} onChange={(e) => setTo(e.target.value)} style={{
              width: '100%', height: 44, padding: '0 12px', borderRadius: 12,
              border: '1px solid var(--n200)', background: '#fff', fontSize: 13, fontFamily: 'inherit',
            }}/>
          </FieldT>
        </div>

        <div className="card" style={{ padding: 12, background: 'var(--info-50)', border: '1px solid rgba(37,99,235,.2)', marginBottom: 14 }}>
          <div className="row" style={{ gap: 10 }}>
            <Icon name="calendar" size={16} style={{ color: '#1E40AF', flexShrink: 0 }}/>
            <div style={{ fontSize: 12, color: 'var(--n800)', lineHeight: 1.45 }}>{days} working day{days === 1 ? '' : 's'} · uses {days} {type} day{days === 1 ? '' : 's'}</div>
          </div>
        </div>

        <FieldT label="Reason for HOD">
          <textarea value={reason} onChange={(e) => setReason(e.target.value)} rows={3} placeholder="Brief reason…" style={{
            width: '100%', padding: 12, borderRadius: 12, border: '1px solid var(--n200)',
            fontSize: 13, fontFamily: 'inherit', resize: 'none',
          }}/>
        </FieldT>

        <FieldT label="Class coverage">
          <ListCard>
            {[
              { id: 'handle-via-sub-request', lab: 'Find a substitute now', sub: 'Opens substitute request after applying' },
              { id: 'hod-arrange', lab: 'Let HOD arrange', sub: "I'll trust the system" },
              { id: 'cover-self', lab: 'Cover via remote/recorded', sub: 'Send recorded lesson + worksheet' },
            ].map((opt, i, a) => (
              <button key={opt.id} onClick={() => setSubstitute(opt.id)} className="row" style={{
                width: '100%', padding: 12, gap: 12, textAlign: 'left',
                borderBottom: i < a.length - 1 ? '1px solid var(--n100)' : 'none',
                background: substitute === opt.id ? 'var(--p50)' : 'transparent',
              }}>
                <div style={{ width: 22, height: 22, borderRadius: '50%', border: '2px solid ' + (substitute === opt.id ? 'var(--p600)' : 'var(--n300)'), background: substitute === opt.id ? 'var(--p600)' : '#fff', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  {substitute === opt.id && <div style={{ width: 8, height: 8, background: '#fff', borderRadius: '50%' }}/>}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--n900)' }}>{opt.lab}</div>
                  <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1 }}>{opt.sub}</div>
                </div>
              </button>
            ))}
          </ListCard>
        </FieldT>

        <button onClick={save} className="btn-primary" style={{ height: 48, width: '100%', marginTop: 8 }} disabled={!reason.trim()}>
          <Icon name="send" size={14}/> Submit to HOD
        </button>
      </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)' }}/> Leave submitted · {substitute === 'handle-via-sub-request' ? 'opening sub request…' : 'awaiting HOD approval'}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. Formal exam schedule (read-only · published by school admin)
// ─────────────────────────────────────────────────────────────
function TeacherExamScheduleScreen({ nav }) {
  const exams = [
    { id: 'e1', cls: '8-B', sub: 'Hindi',          date: 'Mon · 17 Mar', slot: '9:00 – 11:00 AM', room: 'Hall A', invigilate: false, mine: false },
    { id: 'e2', cls: '8-B', sub: 'Mathematics',    date: 'Wed · 19 Mar', slot: '9:00 – 12:00 PM', room: 'Hall A', invigilate: true, mine: true },
    { id: 'e3', cls: '8-B', sub: 'Science',        date: 'Fri · 21 Mar', slot: '9:00 – 11:30 AM', room: 'Hall B', invigilate: false, mine: false },
    { id: 'e4', cls: '8-B', sub: 'English',        date: 'Mon · 24 Mar', slot: '9:00 – 11:30 AM', room: 'Hall A', invigilate: true, mine: false },
    { id: 'e5', cls: '8-B', sub: 'Social Studies', date: 'Wed · 26 Mar', slot: '9:00 – 11:30 AM', room: 'Hall A', invigilate: false, mine: false },
    { id: 'e6', cls: '8-B', sub: 'Computer Sci.',  date: 'Fri · 28 Mar', slot: '10:00 – 11:30 AM', room: 'Lab 2', invigilate: false, mine: false },
    { id: 'e7', cls: '9-A', sub: 'Mathematics',    date: 'Sat · 22 Mar', slot: '9:00 – 12:00 PM', room: 'Hall C', invigilate: true, mine: true },
  ];
  const [tab, setTab] = useStateAD('all'); // 'all' | 'mine' | 'invigilate'
  const list = exams.filter(e => {
    if (tab === 'mine') return e.mine;
    if (tab === 'invigilate') return e.invigilate;
    return true;
  });

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="Term 2 · Final exams" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 4 }}>
        <div className="card" style={{ padding: 12, background: 'var(--warning-50)', border: '1px solid rgba(217,119,6,.25)', marginBottom: 12 }}>
          <div className="row" style={{ gap: 10 }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--warning)', color: '#fff', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="alert" size={14}/></div>
            <div style={{ fontSize: 11.5, color: 'var(--n800)', lineHeight: 1.45 }}>Read-only: published by Principal Office on 5 Mar. <b>Exam-eligibility cut-off (75% attendance) closes Sat 15 Mar.</b></div>
          </div>
        </div>

        <div className="row" style={{ gap: 6, marginBottom: 12 }}>
          {[
            { id: 'all', lab: `All · ${exams.length}` },
            { id: 'mine', lab: `My subject · ${exams.filter(e => e.mine).length}` },
            { id: 'invigilate', lab: `I invigilate · ${exams.filter(e => e.invigilate).length}` },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              flex: 1, padding: '10px 6px', borderRadius: 10,
              background: tab === t.id ? 'var(--n900)' : '#fff',
              color: tab === t.id ? '#fff' : 'var(--n700)',
              fontSize: 11, fontWeight: 700,
              border: '1px solid var(--n100)',
            }}>{t.lab}</button>
          ))}
        </div>

        <div className="col" style={{ gap: 8 }}>
          {list.map(e => (
            <div key={e.id} className="card" style={{
              padding: 12, background: '#fff',
              border: e.mine ? '1px solid var(--p600)' : '1px solid var(--n100)',
              position: 'relative', overflow: 'hidden',
            }}>
              {e.mine && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 4, background: 'var(--p600)' }}/>}
              <div className="row" style={{ gap: 12 }}>
                <div style={{ width: 60, textAlign: 'center', flexShrink: 0, padding: '6px 4px', borderRadius: 8, background: 'var(--n50)' }}>
                  <div style={{ fontSize: 9, color: 'var(--n500)', fontFamily: 'var(--mono)', fontWeight: 700 }}>{e.date.split('·')[0].trim().toUpperCase()}</div>
                  <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--n900)', fontFamily: 'var(--mono)' }}>{e.date.split('·')[1].trim().split(' ')[0]}</div>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="spread">
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{e.sub}</div>
                      <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1, fontFamily: 'var(--mono)' }}>Class {e.cls} · {e.slot}</div>
                      <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1, fontFamily: 'var(--mono)' }}>Room {e.room}</div>
                    </div>
                    <div className="col" style={{ gap: 4, alignItems: 'flex-end' }}>
                      {e.mine && <span className="pill" style={{ background: 'var(--p50)', color: 'var(--p700)', fontSize: 9.5, fontWeight: 800, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>MINE</span>}
                      {e.invigilate && <span className="pill" style={{ background: 'var(--warning-50)', color: 'var(--warning)', fontSize: 9.5, fontWeight: 800, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>INVIGILATE</span>}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3. Bulk publish report cards
// ─────────────────────────────────────────────────────────────
function TeacherReportPublishScreen({ nav }) {
  const roster = (window.ROSTER || []).slice(0, 24);
  const [included, setIncluded] = useStateAD(() => new Set(roster.map(s => s.id)));
  const [done, setDone] = useStateAD(false);
  const [confirm, setConfirm] = useStateAD(false);

  const toggle = (id) => setIncluded(s => {
    const n = new Set(s);
    if (n.has(id)) n.delete(id); else n.add(id);
    return n;
  });

  const ready = roster.filter(s => included.has(s.id));
  const excluded = roster.filter(s => !included.has(s.id));

  if (done) {
    return (
      <div className="app screen-in" style={{ background: 'var(--n50)' }}>
        <StatusBar/>
        <div className="app-body" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '80vh', flexDirection: 'column', textAlign: 'center', padding: 24 }}>
          <div style={{ width: 80, height: 80, borderRadius: '50%', background: 'var(--success-50)', color: 'var(--success)', display: 'grid', placeItems: 'center', marginBottom: 18 }}>
            <Icon name="check" size={40}/>
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', letterSpacing: '-.02em' }}>Reports published</div>
          <div style={{ fontSize: 13, color: 'var(--n500)', marginTop: 6, lineHeight: 1.5 }}>{ready.length} report cards sent to parents.<br/>{excluded.length} held back for re-grade.</div>
          <button onClick={() => nav.pop()} className="btn-primary" style={{ height: 46, marginTop: 22, padding: '0 20px' }}>← Back to grade book</button>
        </div>
      </div>
    );
  }

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="Publish report cards" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 4, paddingBottom: 100 }}>

        <div className="card" style={{ padding: 14, background: 'var(--warning-50)', border: '1px solid rgba(217,119,6,.25)', marginBottom: 12 }}>
          <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)' }}>This sends reports to parents — partially reversible</div>
              <div style={{ fontSize: 11, color: 'var(--n600)', marginTop: 2, lineHeight: 1.45 }}>Parents see the report immediately. You have a 1-hour window to recall before WhatsApp digest goes out.</div>
            </div>
          </div>
        </div>

        <div className="card" style={{ padding: 14, background: '#fff', marginBottom: 12 }}>
          <div className="spread">
            <div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.06em', fontFamily: 'var(--mono)' }}>SUMMARY</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--n900)', marginTop: 2 }}>{ready.length} ready · {excluded.length} on hold</div>
            </div>
            <div className="row" style={{ gap: 6 }}>
              <button onClick={() => setIncluded(new Set(roster.map(s => s.id)))} className="btn-soft" style={{ height: 30, padding: '0 10px', fontSize: 11, fontWeight: 700 }}>All</button>
              <button onClick={() => setIncluded(new Set())} className="btn-ghost" style={{ height: 30, padding: '0 10px', fontSize: 11, fontWeight: 700, color: 'var(--n600)' }}>None</button>
            </div>
          </div>
        </div>

        <SectionLabel label={`Roster · tap to exclude`}/>
        <div className="col" style={{ gap: 4 }}>
          {roster.map(s => {
            const inc = included.has(s.id);
            return (
              <button key={s.id} onClick={() => toggle(s.id)} className="card row" style={{
                padding: 10, gap: 10, background: '#fff',
                opacity: inc ? 1 : .5, textAlign: 'left',
              }}>
                <div className={`av av-32 ${s.clr}`} style={{ flexShrink: 0 }}>{s.initial}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{s.name}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>Roll {s.roll} · Avg {s.avgPct}%</div>
                </div>
                <div style={{
                  width: 22, height: 22, borderRadius: 6,
                  background: inc ? 'var(--success)' : 'var(--n100)',
                  color: '#fff',
                  display: 'grid', placeItems: 'center',
                  border: inc ? 'none' : '1px solid var(--n200)',
                }}>
                  {inc && <Icon name="check" size={12}/>}
                </div>
              </button>
            );
          })}
        </div>
      </div>

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: '#fff', borderTop: '1px solid var(--n100)', padding: '12px 16px' }}>
        {!confirm ? (
          <button onClick={() => setConfirm(true)} className="btn-primary" style={{ height: 48, width: '100%' }} disabled={ready.length === 0}>
            <Icon name="send" size={14}/> Publish {ready.length} report cards
          </button>
        ) : (
          <div className="row" style={{ gap: 8 }}>
            <button onClick={() => setConfirm(false)} className="btn-outline" style={{ flex: 1, height: 48 }}>Cancel</button>
            <button onClick={() => setDone(true)} className="btn" style={{ flex: 1.4, height: 48, background: 'var(--c600)' }}>
              Confirm · publish to {ready.length} parents
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  TeacherLeaveApplyScreen,
  TeacherExamScheduleScreen,
  TeacherReportPublishScreen,
});
