// screens-lessonplan.jsx — Per-period lesson plan + resource library
// 1. TeacherLessonPlanScreen — Mon–Fri × period grid showing planned lessons
// 2. TeacherLessonPlanEditScreen — single-period editor (objectives, materials, outcome)
// 3. TeacherResourceLibraryScreen — saved worksheets, decks, video links

const { useState: useStateLP, useMemo: useMemoLP } = React;

// Mock plans keyed by `${day}-${period}` for current week.
function buildLessonPlans() {
  return {
    'Mon-1': { cls: '8-B', topic: 'Linear equations · Word problems', stage: 'practice', mins: 45, objective: 'Translate two-variable scenarios into equation form.', materials: 'Worksheet 7.4 · GeoGebra demo', outcome: 'Students solve 5 of 6 word problems independently.' },
    'Mon-3': { cls: '9-A', topic: 'Trigonometry · Ratios intro', stage: 'intro', mins: 45, objective: 'Define sin, cos, tan from a right-angled triangle.', materials: 'Slide deck · printed reference card', outcome: 'Students label ratios on 3 unmarked triangles.' },
    'Tue-1': { cls: '9-A', topic: 'Trig · Practice + recap', stage: 'practice', mins: 45 },
    'Wed-1': { cls: '8-B', topic: 'Linear eq · Test review', stage: 'review', mins: 45, objective: 'Walk through last week\'s test errors as a class.', materials: 'Marked papers · projector', outcome: 'Each student notes top 1 error type to focus on.' },
    'Wed-4': { cls: '8-B', topic: 'Geometry · Circle theorems', stage: 'intro', mins: 45 },
    'Thu-2': { cls: '8-B', topic: 'Geometry · Theorems applied', stage: 'practice', mins: 45 },
    'Fri-3': { cls: '8-B', topic: 'Geometry · Quiz', stage: 'assess', mins: 45 },
  };
}
const LESSON_PLANS = buildLessonPlans();

const STAGE_META = {
  intro:    { lab: 'INTRO',    bg: 'var(--info-50)',     clr: '#1E40AF' },
  practice: { lab: 'PRACTICE', bg: 'var(--p50)',         clr: 'var(--p700)' },
  review:   { lab: 'REVIEW',   bg: 'var(--warning-50)',  clr: 'var(--warning)' },
  assess:   { lab: 'ASSESS',   bg: 'var(--success-50)',  clr: 'var(--success)' },
};

// ─────────────────────────────────────────────────────────────
// 1. Lesson plan grid
// ─────────────────────────────────────────────────────────────
function TeacherLessonPlanScreen({ nav, params }) {
  const tt = window.TIMETABLE || { days: ['Mon','Tue','Wed','Thu','Fri'], 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'},{p:5,time:'11:15–12:00'},{p:6,time:'12:00–12:45'},{p:7,time:'1:30–2:15'},{p:8,time:'2:15–3:00'}], expanded: [] };
  const days = tt.days;
  const periods = tt.periods;

  // Map day→periods for class lookup
  const cellClass = useMemoLP(() => {
    const m = {};
    if (tt.expanded && tt.expanded.length) {
      tt.expanded.forEach(d => d.periods.forEach(p => {
        if (!p.free) m[`${d.day}-${p.p}`] = p.cls;
      }));
    }
    return m;
  }, []);

  const plansFilledCount = useMemoLP(() => {
    return Object.keys(cellClass).filter(k => LESSON_PLANS[k]).length;
  }, [cellClass]);
  const totalTeachingPeriods = Object.keys(cellClass).length;

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="Lesson plans" onBack={() => nav.pop()}
        right={<button onClick={() => nav.push('teachResourceLibrary')} style={{ height: 32, padding: '0 12px', borderRadius: 8, background: 'var(--n50)', fontSize: 11, fontWeight: 700, fontFamily: 'var(--mono)', color: 'var(--n700)' }}><Icon name="bookmark" size={11}/> LIBRARY</button>}/>
      <div className="app-body" style={{ paddingTop: 4 }}>

        {/* Summary */}
        <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: '.08em', fontFamily: 'var(--mono)' }}>WEEK 11–15 MAR</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--n900)', marginTop: 2 }}>{plansFilledCount} of {totalTeachingPeriods} planned</div>
              <div style={{ fontSize: 11, color: totalTeachingPeriods - plansFilledCount > 0 ? 'var(--c600)' : 'var(--success)', marginTop: 2, fontFamily: 'var(--mono)', fontWeight: 700 }}>
                {totalTeachingPeriods - plansFilledCount > 0 ? `${totalTeachingPeriods - plansFilledCount} GAPS` : 'COMPLETE'}
              </div>
            </div>
            <button onClick={() => nav.push('teachLessonPlanEdit', { day: 'Wed', period: 4 })} className="btn-soft" style={{ height: 36, padding: '0 12px', fontSize: 12, fontWeight: 700 }}>
              <Icon name="plus" size={13}/> New
            </button>
          </div>
        </div>

        {/* Grid */}
        <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: 84, 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 key = `${d}-${p.p}`;
                      const cls = cellClass[key];
                      const plan = LESSON_PLANS[key];
                      if (!cls) return <td key={d} style={{ padding: 4, textAlign: 'center', color: 'var(--n300)', fontSize: 9 }}>—</td>;
                      const stage = plan && STAGE_META[plan.stage];
                      return (
                        <td key={d} style={{ padding: 3 }}>
                          <button onClick={() => nav.push('teachLessonPlanEdit', { day: d, period: p.p, cls })} style={{
                            display: 'block', width: '100%', padding: 6, borderRadius: 6,
                            background: plan ? (stage ? stage.bg : 'var(--n50)') : 'transparent',
                            color: plan ? (stage ? stage.clr : 'var(--n700)') : 'var(--n400)',
                            border: plan ? '1px solid transparent' : '1px dashed var(--n200)',
                            textAlign: 'left', fontFamily: 'inherit',
                          }}>
                            {plan ? (
                              <>
                                <div style={{ fontSize: 9, fontWeight: 800, fontFamily: 'var(--mono)', letterSpacing: '.04em' }}>{cls} · {stage ? stage.lab : ''}</div>
                                <div style={{ fontSize: 10, fontWeight: 600, marginTop: 3, lineHeight: 1.25, color: 'var(--n900)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{plan.topic.split('·')[0].trim()}</div>
                              </>
                            ) : (
                              <div style={{ fontSize: 10, textAlign: 'center', padding: '6px 0' }}>+ {cls}</div>
                            )}
                          </button>
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div className="row" style={{ gap: 10, marginTop: 10, fontSize: 10.5, color: 'var(--n500)', flexWrap: 'wrap', fontFamily: 'var(--mono)', fontWeight: 700 }}>
          {Object.entries(STAGE_META).map(([k, m]) => (
            <span key={k} className="row" style={{ gap: 4 }}>
              <div style={{ width: 10, height: 10, borderRadius: 3, background: m.bg, border: `1px solid ${m.clr}` }}/>
              <span>{m.lab}</span>
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. Lesson plan editor
// ─────────────────────────────────────────────────────────────
function TeacherLessonPlanEditScreen({ nav, params }) {
  const day = (params && params.day) || 'Wed';
  const period = (params && params.period) || 4;
  const cls = (params && params.cls) || '8-B';
  const key = `${day}-${period}`;
  const existing = LESSON_PLANS[key];
  const [topic, setTopic] = useStateLP(existing ? existing.topic : '');
  const [stage, setStage] = useStateLP(existing ? existing.stage : 'practice');
  const [mins, setMins] = useStateLP(existing ? existing.mins : 45);
  const [objective, setObjective] = useStateLP(existing ? (existing.objective || '') : '');
  const [materials, setMaterials] = useStateLP(existing ? (existing.materials || '') : '');
  const [outcome, setOutcome] = useStateLP(existing ? (existing.outcome || '') : '');
  const [savedToast, setSavedToast] = useStateLP(false);

  const suggestedResources = [
    { type: 'doc', title: 'Linear eq · Worksheet 7.4', meta: 'Saved · 4 KB' },
    { type: 'video', title: 'GeoGebra demo (5 min)', meta: 'youtube.com · ext' },
    { type: 'doc', title: 'Last term test paper', meta: 'PDF · 84 KB' },
    { type: 'link', title: 'NCERT Chapter 7 · pp. 92–98', meta: 'ncert.nic.in · ext' },
  ];

  const save = () => {
    setSavedToast(true);
    setTimeout(() => { setSavedToast(false); nav.pop(); }, 900);
  };

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title={existing ? 'Edit lesson plan' : 'New lesson plan'} onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 4, paddingBottom: 100 }}>
        <div className="card" style={{ padding: 12, background: '#fff', marginBottom: 12 }}>
          <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 }}>{period}</div>
              <div style={{ fontSize: 9, color: 'var(--n500)', fontFamily: 'var(--mono)', fontWeight: 700, marginTop: 2 }}>P</div>
            </div>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--n500)', fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>{day.toUpperCase()} · {mins}MIN</div>
              <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--n900)', marginTop: 2 }}>Class {cls} · Math</div>
            </div>
          </div>
        </div>

        <FieldT label="Topic" required>
          <input value={topic} onChange={(e) => setTopic(e.target.value)} placeholder="e.g. Linear equations · Word problems" style={{
            width: '100%', height: 44, padding: '0 12px', borderRadius: 12,
            border: '1px solid var(--n200)', background: '#fff', fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
          }}/>
        </FieldT>

        <FieldT label="Stage">
          <div className="row" style={{ gap: 6 }}>
            {Object.entries(STAGE_META).map(([id, m]) => (
              <button key={id} onClick={() => setStage(id)} style={{
                flex: 1, padding: '10px 4px', borderRadius: 10,
                background: stage === id ? m.bg : '#fff',
                color: stage === id ? m.clr : 'var(--n600)',
                border: stage === id ? `1px solid ${m.clr}` : '1px solid var(--n200)',
                fontSize: 10.5, fontWeight: 800, fontFamily: 'var(--mono)', letterSpacing: '.04em',
              }}>{m.lab}</button>
            ))}
          </div>
        </FieldT>

        <FieldT label="Learning objective">
          <textarea value={objective} onChange={(e) => setObjective(e.target.value)} rows={2} placeholder="One concrete thing students will be able to do…" style={{
            width: '100%', padding: 12, borderRadius: 12, border: '1px solid var(--n200)',
            fontSize: 13, fontFamily: 'inherit', resize: 'none',
          }}/>
        </FieldT>

        <FieldT label="Materials">
          <textarea value={materials} onChange={(e) => setMaterials(e.target.value)} rows={2} placeholder="Worksheet, slides, lab kit…" style={{
            width: '100%', padding: 12, borderRadius: 12, border: '1px solid var(--n200)',
            fontSize: 13, fontFamily: 'inherit', resize: 'none',
          }}/>
        </FieldT>

        <FieldT label="Expected outcome">
          <textarea value={outcome} onChange={(e) => setOutcome(e.target.value)} rows={2} placeholder="What success looks like by end of class…" style={{
            width: '100%', padding: 12, borderRadius: 12, border: '1px solid var(--n200)',
            fontSize: 13, fontFamily: 'inherit', resize: 'none',
          }}/>
        </FieldT>

        {/* Resource picker */}
        <FieldT label="Attach from library" right={<button onClick={() => nav.push('teachResourceLibrary')} style={{ fontSize: 11, color: 'var(--p600)', fontWeight: 600 }}>Browse →</button>}>
          <div className="col" style={{ gap: 6 }}>
            {suggestedResources.map((r, i) => {
              const ic = r.type === 'video' ? 'video' : r.type === 'link' ? 'link' : 'document';
              return (
                <button key={i} className="card row" style={{ padding: 10, gap: 10, background: '#fff', textAlign: 'left' }}>
                  <div style={{ width: 28, height: 28, borderRadius: 7, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={ic} size={14}/></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)' }}>{r.title}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 1, fontFamily: 'var(--mono)' }}>{r.meta}</div>
                  </div>
                  <Icon name="plus" size={14} style={{ color: 'var(--n400)' }}/>
                </button>
              );
            })}
          </div>
        </FieldT>
      </div>

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: '#fff', borderTop: '1px solid var(--n100)', padding: '12px 16px', display: 'flex', gap: 8 }}>
        <button onClick={() => nav.pop()} className="btn-outline" style={{ flex: 1, height: 46 }}>Cancel</button>
        <button onClick={save} className="btn" style={{ flex: 1.4, height: 46 }} disabled={!topic.trim()}>
          <Icon name="check" size={14}/> Save plan
        </button>
      </div>

      {savedToast && (
        <div style={{ position: 'absolute', bottom: 80, 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)' }}/> Plan saved · {day} P{period}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3. Resource library
// ─────────────────────────────────────────────────────────────
function TeacherResourceLibraryScreen({ nav }) {
  const RESOURCES = [
    { id: 'r1', type: 'doc',   sub: 'Math',    title: 'Linear eq · Worksheet 7.4',   meta: 'PDF · 4 KB · 12 students used' },
    { id: 'r2', type: 'doc',   sub: 'Math',    title: 'Mid-term · Sample paper',     meta: 'PDF · 84 KB · 28 used' },
    { id: 'r3', type: 'video', sub: 'Math',    title: 'GeoGebra · linear equations', meta: '5 min · youtube · saved' },
    { id: 'r4', type: 'deck',  sub: 'Math',    title: 'Trig ratios · slide deck',    meta: '12 slides · revised this week' },
    { id: 'r5', type: 'doc',   sub: 'Math',    title: 'Quadratic eq · Practice 8.1', meta: 'DOCX · 18 KB' },
    { id: 'r6', type: 'link',  sub: 'Math',    title: 'NCERT Ch. 7 (Linear eq)',     meta: 'ncert.nic.in · ext' },
    { id: 'r7', type: 'video', sub: 'Math',    title: 'Polya · word problem method', meta: '8 min · saved last term' },
    { id: 'r8', type: 'deck',  sub: 'Math',    title: 'Geometry · circle theorems',  meta: '8 slides · 9-A only' },
  ];
  const [filter, setFilter] = useStateLP('all');
  const [search, setSearch] = useStateLP('');

  const list = RESOURCES.filter(r => {
    if (filter !== 'all' && r.type !== filter) return false;
    if (search && !r.title.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });
  const META = {
    doc:   { ic: 'document',  bg: 'var(--p50)',         clr: 'var(--p600)' },
    deck:  { ic: 'list',      bg: 'var(--info-50)',     clr: '#1E40AF' },
    video: { ic: 'video',     bg: 'var(--c50)',         clr: 'var(--c600)' },
    link:  { ic: 'link',      bg: 'var(--success-50)',  clr: 'var(--success)' },
  };

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="Resource library" onBack={() => nav.pop()}
        right={<button style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center' }}><Icon name="plus" size={16}/></button>}/>
      <div className="app-body" style={{ paddingTop: 4 }}>

        {/* 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 resources…" style={{
            width: '100%', height: 40, paddingLeft: 36, paddingRight: 12, borderRadius: 12,
            border: '1px solid var(--n200)', background: '#fff', fontSize: 13, fontFamily: 'inherit',
          }}/>
        </div>

        <div className="row" style={{ gap: 6, marginBottom: 12, overflowX: 'auto', paddingBottom: 4 }}>
          {[
            { id: 'all', lab: 'All', n: RESOURCES.length },
            { id: 'doc', lab: 'Docs', n: RESOURCES.filter(r => r.type === 'doc').length },
            { id: 'deck', lab: 'Decks', n: RESOURCES.filter(r => r.type === 'deck').length },
            { id: 'video', lab: 'Videos', n: RESOURCES.filter(r => r.type === 'video').length },
            { id: 'link', lab: 'Links', n: RESOURCES.filter(r => r.type === 'link').length },
          ].map(f => (
            <button key={f.id} onClick={() => setFilter(f.id)} style={{
              padding: '7px 12px', borderRadius: 20, fontSize: 11.5, fontWeight: 700,
              background: filter === f.id ? 'var(--n900)' : '#fff',
              color: filter === f.id ? '#fff' : 'var(--n700)',
              border: '1px solid var(--n100)', whiteSpace: 'nowrap',
            }}>{f.lab} <span style={{ opacity: .6 }}>· {f.n}</span></button>
          ))}
        </div>

        <div className="col" style={{ gap: 6 }}>
          {list.map(r => {
            const m = META[r.type];
            return (
              <button key={r.id} className="card row" style={{ padding: 12, gap: 12, background: '#fff', textAlign: 'left' }}>
                <div style={{ width: 40, height: 40, borderRadius: 10, background: m.bg, color: m.clr, display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={m.ic} size={18}/></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{r.title}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 2, fontFamily: 'var(--mono)' }}>{r.meta}</div>
                </div>
                <button style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}><Icon name="more" size={14}/></button>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  LESSON_PLANS,
  TeacherLessonPlanScreen,
  TeacherLessonPlanEditScreen,
  TeacherResourceLibraryScreen,
});
