// screens-timetable.jsx — Teacher's weekly timetable + today list + substitute request
// 1. TeacherTimetableScreen — Mon–Fri × 8 periods grid
// 2. TeacherTodayScheduleScreen — vertical "today" list with current period highlighted
// 3. TeacherSubstituteRequestScreen — request a sub for a leave day

const { useState: useStateTT, useMemo: useMemoTT } = React;

// Shared timetable data (Mrs. Reddy, Math, classes 8-B / 9-A / 10-C).
function buildTimetable() {
  const periods = [
    { p: 1, time: '8:00–8:45' },
    { p: 2, time: '8:45–9:30' },
    { p: 3, time: '9:30–10:15' },
    { p: 4, time: '10:30–11:15' }, // after morning assembly
    { p: 5, time: '11:15–12:00' },
    { p: 6, time: '12:00–12:45' },
    { p: 7, time: '1:30–2:15' },   // after lunch
    { p: 8, time: '2:15–3:00' },
  ];
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
  // Each cell: 'free' | { cls, sub, room }
  const grid = {
    Mon: ['8-B', null, '9-A', '8-B', '10-C', null, null, '9-A'],
    Tue: ['9-A', '8-B', null, '10-C', '8-B', null, '9-A', null],
    Wed: ['8-B', '9-A', null, '8-B', '10-C', null, '9-A', '10-C'],
    Thu: [null, '8-B', '10-C', null, '9-A', null, '8-B', null],
    Fri: ['10-C', null, '8-B', '9-A', null, null, '8-B', '10-C'],
  };
  const ROOMS = { '8-B': '204', '9-A': '301', '10-C': '402' };
  const expanded = days.map(d => ({
    day: d,
    periods: periods.map((p, i) => {
      const cls = grid[d][i];
      if (!cls) return { ...p, free: true };
      return { ...p, cls, sub: 'Math', room: ROOMS[cls] };
    }),
  }));
  return { days, periods, expanded };
}
const TIMETABLE = buildTimetable();

// ─────────────────────────────────────────────────────────────
// 1. Weekly timetable
// ─────────────────────────────────────────────────────────────
function TeacherTimetableScreen({ nav }) {
  const { days, periods, expanded } = TIMETABLE;
  const [view, setView] = useStateTT('week'); // 'week' | 'day'
  const [selectedDay, setSelectedDay] = useStateTT('Wed');

  // Stats
  const totalLoad = days.reduce((s, d) => s + expanded.find(e => e.day === d).periods.filter(p => !p.free).length, 0);
  const perClass = useMemoTT(() => {
    const map = {};
    expanded.forEach(d => d.periods.forEach(p => { if (!p.free) map[p.cls] = (map[p.cls] || 0) + 1; }));
    return map;
  }, []);

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="Timetable" onBack={() => nav.pop()}
        right={<button onClick={() => nav.push('teachSubstituteRequest')} style={{ height: 32, padding: '0 10px', borderRadius: 8, background: 'var(--n50)', fontSize: 11, fontWeight: 700, fontFamily: 'var(--mono)', color: 'var(--n700)' }}>+ SUB</button>}/>

      <div className="app-body" style={{ paddingTop: 4 }}>
        {/* Tabs */}
        <div className="row" style={{ gap: 6, marginBottom: 12 }}>
          {[{ id: 'week', lab: 'Week' }, { id: 'day', lab: 'By day' }].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 === 'week' && (
          <>
            <div className="card" style={{ padding: 0, background: '#fff', overflow: 'hidden' }}>
              <div style={{ overflowX: 'auto' }}>
                <table style={{ borderCollapse: 'collapse', fontSize: 10.5, fontFamily: 'var(--mono)', minWidth: '100%' }}>
                  <thead>
                    <tr style={{ background: 'var(--n50)' }}>
                      <th style={{ padding: '8px 6px', position: 'sticky', left: 0, background: 'var(--n50)', borderBottom: '1px solid var(--n200)', minWidth: 36, fontWeight: 700, color: 'var(--n500)', fontSize: 9 }}>P</th>
                      {days.map(d => (
                        <th key={d} style={{ padding: '8px 6px', borderBottom: '1px solid var(--n200)', minWidth: 56, color: 'var(--n700)', fontWeight: 800 }}>{d}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {periods.map((p, pi) => (
                      <tr key={p.p} style={{ borderBottom: '1px solid var(--n100)' }}>
                        <td style={{ padding: '6px 6px', position: 'sticky', left: 0, background: '#fff', textAlign: 'center', fontWeight: 700, color: 'var(--n700)', borderRight: '1px solid var(--n100)' }}>
                          <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--n900)' }}>{p.p}</div>
                          <div style={{ fontSize: 8, color: 'var(--n400)', marginTop: 1 }}>{p.time.split('–')[0]}</div>
                        </td>
                        {days.map(d => {
                          const cell = expanded.find(e => e.day === d).periods[pi];
                          if (cell.free) return <td key={d} style={{ padding: 4, textAlign: 'center', color: 'var(--n300)', fontSize: 9 }}>—</td>;
                          return (
                            <td key={d} style={{ padding: 4 }}>
                              <button onClick={() => nav.push('teachLessonPlan', { day: d, period: p.p, cls: cell.cls })} style={{
                                display: 'block', width: '100%', padding: '6px 4px', borderRadius: 6,
                                background: 'var(--p50)', color: 'var(--p700)',
                                fontFamily: 'var(--mono)', fontWeight: 800, fontSize: 10.5,
                                border: '1px solid rgba(79,70,229,.12)', textAlign: 'center',
                              }}>
                                {cell.cls}<div style={{ fontSize: 8, color: 'var(--p600)', fontWeight: 600, marginTop: 1, opacity: .8 }}>R{cell.room}</div>
                              </button>
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            <SectionLabel label="Load distribution"/>
            <div className="card" style={{ padding: 14, background: '#fff' }}>
              <div className="row" style={{ gap: 16 }}>
                <div>
                  <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', fontVariantNumeric: 'tabular-nums', letterSpacing: '-.02em', lineHeight: 1 }}>{totalLoad}</div>
                  <div style={{ fontSize: 10, color: 'var(--n500)', marginTop: 3, fontFamily: 'var(--mono)', fontWeight: 700 }}>PERIODS / WEEK</div>
                </div>
                <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>
                  {Object.entries(perClass).map(([cls, n]) => (
                    <div key={cls} style={{ padding: 8, borderRadius: 8, background: 'var(--n50)', textAlign: 'center' }}>
                      <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--n900)' }}>{n}</div>
                      <div style={{ fontSize: 10, color: 'var(--n500)', fontFamily: 'var(--mono)', marginTop: 2 }}>Class {cls}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </>
        )}

        {view === 'day' && (
          <>
            <div className="row" style={{ gap: 6, marginBottom: 10, overflowX: 'auto', paddingBottom: 4 }}>
              {days.map(d => (
                <button key={d} onClick={() => setSelectedDay(d)} style={{
                  padding: '8px 14px', borderRadius: 10, fontSize: 12, fontWeight: 700,
                  background: selectedDay === d ? 'var(--p600)' : '#fff',
                  color: selectedDay === d ? '#fff' : 'var(--n700)',
                  border: '1px solid var(--n100)', flexShrink: 0,
                }}>{d}</button>
              ))}
            </div>
            <div className="col" style={{ gap: 8 }}>
              {expanded.find(e => e.day === selectedDay).periods.map(p => p.free ? (
                <div key={p.p} className="row" style={{ padding: '10px 14px', gap: 12, opacity: .55 }}>
                  <div style={{ width: 36, textAlign: 'center', fontFamily: 'var(--mono)', fontSize: 12, fontWeight: 700, color: 'var(--n400)' }}>P{p.p}</div>
                  <div style={{ fontSize: 12, color: 'var(--n400)' }}>—</div>
                  <div style={{ flex: 1 }}/>
                  <div style={{ fontSize: 11, color: 'var(--n400)', fontFamily: 'var(--mono)' }}>{p.time}</div>
                </div>
              ) : (
                <button key={p.p} onClick={() => nav.push('teachLessonPlan', { day: selectedDay, period: p.p, cls: p.cls })} className="card row" style={{ padding: 12, gap: 12, background: '#fff', textAlign: 'left' }}>
                  <div style={{ width: 36, textAlign: 'center', flexShrink: 0 }}>
                    <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--n900)' }}>{p.p}</div>
                    <div style={{ fontSize: 9, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>P</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Class {p.cls} · {p.sub}</div>
                    <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2, fontFamily: 'var(--mono)' }}>{p.time} · Room {p.room}</div>
                  </div>
                  <Icon name="chev-r" size={16} style={{ color: 'var(--n400)' }}/>
                </button>
              ))}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. Today's schedule (vertical · with progress)
// ─────────────────────────────────────────────────────────────
function TeacherTodayScheduleScreen({ nav }) {
  const today = TIMETABLE.expanded.find(e => e.day === 'Wed') || TIMETABLE.expanded[0];
  const currentPeriod = 4; // 10:30–11:15
  const upcoming = today.periods.filter(p => !p.free && p.p > currentPeriod).slice(0, 3);

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, zIndex: 60 }}><StatusBar dark/></div>
      <div className="app-body no-pad">
        <div className="head-grad" style={{ paddingTop: 56, paddingBottom: 18 }}>
          <button onClick={() => nav.pop()} style={{ width: 40, height: 40, borderRadius: 12, background: 'rgba(255,255,255,.18)', color: '#fff', display: 'grid', placeItems: 'center', marginBottom: 14 }}><Icon name="chev-l" size={20}/></button>
          <div style={{ fontSize: 11, fontWeight: 700, opacity: .85, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>WED · 12 MAR · TODAY</div>
          <div style={{ fontSize: 24, fontWeight: 800, marginTop: 4, letterSpacing: '-.02em' }}>5 teaching periods</div>
          <div style={{ fontSize: 12.5, opacity: .85, marginTop: 4 }}>{upcoming.length} more before lunch</div>
        </div>

        <div style={{ padding: 16 }}>
          <div className="col" style={{ gap: 8 }}>
            {today.periods.map(p => {
              const isFree = p.free;
              const isPast = p.p < currentPeriod;
              const isCurrent = p.p === currentPeriod;
              const accent = isCurrent ? 'var(--p600)' : isPast ? 'var(--success)' : isFree ? 'var(--n300)' : 'var(--warning)';
              return (
                <div key={p.p} className="card" style={{
                  padding: 12, background: '#fff',
                  border: isCurrent ? '1px solid var(--p600)' : '1px solid var(--n100)',
                  position: 'relative', overflow: 'hidden',
                  opacity: isFree ? .5 : isPast ? .65 : 1,
                }}>
                  {!isFree && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 4, background: accent }}/>}
                  <div className="row" style={{ gap: 12 }}>
                    <div style={{ width: 56, textAlign: 'center', flexShrink: 0 }}>
                      <div style={{ fontSize: 11, color: 'var(--n500)', fontFamily: 'var(--mono)', fontWeight: 700 }}>P{p.p}</div>
                      <div style={{ fontSize: 11, color: 'var(--n400)', marginTop: 2, fontFamily: 'var(--mono)' }}>{p.time.split('–')[0]}</div>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="spread">
                        <div>
                          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{isFree ? 'Free / Lunch' : `Class ${p.cls} · ${p.sub}`}</div>
                          <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2, fontFamily: 'var(--mono)' }}>{p.time}{!isFree ? ' · Room ' + p.room : ''}</div>
                        </div>
                        {isCurrent && <span className="pill" style={{ background: 'var(--success-50)', color: 'var(--success)', fontSize: 9, fontWeight: 800, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>● LIVE</span>}
                        {isPast && <Icon name="check" size={14} style={{ color: 'var(--success)' }}/>}
                      </div>
                      {!isFree && !isPast && (
                        <div className="row" style={{ gap: 6, marginTop: 8 }}>
                          <button onClick={() => nav.push('teachAttendanceMark', { cls: p.cls, period: p.p })} className="btn-soft" style={{ height: 28, padding: '0 10px', fontSize: 11, fontWeight: 700 }}>Mark attendance</button>
                          <button onClick={() => nav.push('teachLessonPlan', { day: 'Wed', period: p.p, cls: p.cls })} className="btn-ghost" style={{ height: 28, padding: '0 10px', fontSize: 11, fontWeight: 600, color: 'var(--p600)' }}>Lesson plan →</button>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3. Substitute request
// ─────────────────────────────────────────────────────────────
function TeacherSubstituteRequestScreen({ nav, params }) {
  const [date, setDate] = useStateTT('2025-03-20');
  const [reason, setReason] = useStateTT('Personal');
  const [note, setNote] = useStateTT('');
  const [periods, setPeriods] = useStateTT(() => new Set([1, 2, 4, 5])); // pre-select my teaching periods that day
  const [savedToast, setSavedToast] = useStateTT(false);
  const [matched, setMatched] = useStateTT(false);

  const togglePeriod = (p) => setPeriods(s => {
    const n = new Set(s);
    if (n.has(p)) n.delete(p); else n.add(p);
    return n;
  });

  const candidates = [
    { name: 'Mr. Bhat', sub: 'Hindi', match: 'Available P1, P2, P4, P5', score: 'Best match', clr: 'var(--success)' },
    { name: 'Mrs. Menon', sub: 'Social Studies', match: 'Available P1, P2 only', score: 'Partial', clr: 'var(--warning)' },
    { name: 'Mr. Iyer', sub: 'Science', match: 'Same subject family · P4, P5', score: 'Subject match', clr: 'var(--p600)' },
  ];

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="Request substitute" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 4 }}>
        <FieldT label="Leave date" required>
          <input type="date" value={date} onChange={(e) => setDate(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="Reason" required>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {['Personal', 'Sick', 'Medical', 'Family emergency', 'Training', 'Half-day'].map(r => (
              <button key={r} onClick={() => setReason(r)} style={{
                padding: '8px 14px', borderRadius: 20,
                background: reason === r ? 'var(--p50)' : 'var(--n50)',
                color: reason === r ? 'var(--p700)' : 'var(--n700)',
                border: reason === r ? '1px solid var(--p600)' : '1px solid transparent',
                fontSize: 11.5, fontWeight: 600,
              }}>{r}</button>
            ))}
          </div>
        </FieldT>

        <FieldT label="Periods needing cover · 4 selected">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 6 }}>
            {[1,2,3,4,5,6,7,8].map(p => {
              const sel = periods.has(p);
              const free = [3, 6].includes(p); // pretend these are my free periods
              return (
                <button key={p} onClick={() => !free && togglePeriod(p)} disabled={free} style={{
                  padding: '12px 8px', borderRadius: 10,
                  background: free ? 'var(--n50)' : sel ? 'var(--p600)' : '#fff',
                  color: free ? 'var(--n400)' : sel ? '#fff' : 'var(--n700)',
                  border: free ? '1px dashed var(--n200)' : sel ? '1px solid var(--p600)' : '1px solid var(--n200)',
                  fontSize: 12, fontWeight: 800, fontFamily: 'var(--mono)',
                }}>
                  P{p}{free && <div style={{ fontSize: 8, fontWeight: 600, opacity: .7, marginTop: 2 }}>free</div>}
                </button>
              );
            })}
          </div>
        </FieldT>

        <FieldT label="Note for sub teacher">
          <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={3} placeholder="What to cover, where notes are, etc." style={{
            width: '100%', padding: 12, borderRadius: 12, border: '1px solid var(--n200)',
            fontSize: 13, fontFamily: 'inherit', resize: 'none',
          }}/>
        </FieldT>

        {!matched ? (
          <button onClick={() => setMatched(true)} className="btn-primary" style={{ height: 48, width: '100%', marginTop: 8 }}>
            <Icon name="search" size={16}/> Find available teachers
          </button>
        ) : (
          <>
            <SectionLabel label="Candidate substitutes" hint="Sorted by availability + subject affinity. School policy requires HOD approval."/>
            <div className="col" style={{ gap: 8 }}>
              {candidates.map((c, i) => (
                <div key={i} className="card" style={{ padding: 12, background: '#fff' }}>
                  <div className="row" style={{ gap: 12 }}>
                    <div className="av av-44">{c.name.split(' ')[1][0]}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="spread">
                        <div>
                          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{c.name}</div>
                          <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1 }}>{c.sub}</div>
                        </div>
                        <span className="pill" style={{ background: 'transparent', color: c.clr, fontSize: 10, fontWeight: 700, fontFamily: 'var(--mono)' }}>{c.score.toUpperCase()}</span>
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--n600)', marginTop: 4 }}>{c.match}</div>
                    </div>
                    <button onClick={() => { setSavedToast(true); setTimeout(() => { setSavedToast(false); nav.pop(); }, 900); }} className="btn-soft" style={{ height: 32, padding: '0 12px', fontSize: 11, fontWeight: 700 }}>Request</button>
                  </div>
                </div>
              ))}
            </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)' }}/> Sub request sent · awaiting HOD approval
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  TIMETABLE,
  TeacherTimetableScreen,
  TeacherTodayScheduleScreen,
  TeacherSubstituteRequestScreen,
});
