// screens-homework.jsx — Teacher homework module
// Hub (active · to grade · drafts · past) + create/edit + submissions list + grade view + analytics.
// Real-world flows: publish, set due/late policy, attach files, send reminders, return for resubmission, bulk grade.

const { useState: useStateH, useMemo: useMemoH, useEffect: useEffectH } = React;

// ─────────────────────────────────────────────────────────────
// TEACHER CONTEXT — drives "your classes" filter
// ─────────────────────────────────────────────────────────────
const TEACHER_HW_CONTEXT = {
  name: 'Sneha Reddy', short: 'Mrs. Reddy',
  classes: [
    { id: '8B', label: 'Class 8-B', students: 32 },
    { id: '9A', label: 'Class 9-A', students: 28 },
    { id: '10C', label: 'Class 10-C', students: 30 },
  ],
};

const SUBJECT_META = {
  Mathematics:    { ic: 'target',    clr: 'var(--p600)',   bg: 'var(--p50)' },
  Science:        { ic: 'flask',     clr: 'var(--success)',bg: 'var(--success-50)' },
  English:        { ic: 'book-open', clr: '#1E40AF',       bg: 'var(--info-50)' },
  Hindi:          { ic: 'book-open', clr: 'var(--c600)',   bg: 'var(--c50)' },
  'Social Studies': { ic: 'globe',   clr: '#92400E',       bg: '#FEF3C7' },
  History:        { ic: 'history',   clr: '#92400E',       bg: '#FEF3C7' },
  Civics:         { ic: 'megaphone', clr: '#7C3AED',       bg: '#F3E8FF' },
};
function subMeta(s) { return SUBJECT_META[s] || { ic: 'document', clr: 'var(--n700)', bg: 'var(--n50)' }; }

// ─────────────────────────────────────────────────────────────
// HOMEWORK DATA — covers all real-world states
// ─────────────────────────────────────────────────────────────
//   state: 'draft' | 'scheduled' | 'active' | 'closed' | 'past'
//   Submission states per student:
//     'pending' | 'submitted' | 'late' | 'graded' | 'returned' | 'absent'
function buildHwSubmissions(hwId, classId, total, mix) {
  const cls = TEACHER_HW_CONTEXT.classes.find(c => c.id === classId);
  const N = cls ? cls.students : 32;
  const names = ['Aarav', 'Diya', 'Kavya', 'Vihaan', 'Ananya', 'Reyansh', 'Saanvi', 'Arjun', 'Ishika', 'Vivaan',
    'Myra', 'Aditya', 'Aanya', 'Krishna', 'Tara', 'Rohan', 'Pari', 'Atharv', 'Nyra', 'Kabir',
    'Zara', 'Veer', 'Riya', 'Ayaan', 'Anika', 'Dhruv', 'Sara', 'Ahaan', 'Mira', 'Yash', 'Inaya', 'Kian'];
  const surnames = ['Reddy', 'Sharma', 'Mehta', 'Iyer', 'Nair', 'Kapoor', 'Joshi', 'Singh', 'Patel', 'Khan'];
  const list = [];
  for (let i = 0; i < N; i++) {
    const seed = Math.abs(Math.sin((hwId.charCodeAt(0) || 1) * (i + 1) * 13)) ;
    const r = (seed * 1000) % 1;
    const name = names[i % names.length] + ' ' + surnames[(i * 3) % surnames.length].charAt(0) + '.';
    let st;
    if (mix === 'mostly_done') st = r < 0.6 ? 'graded' : r < 0.8 ? 'submitted' : r < 0.92 ? 'late' : 'pending';
    else if (mix === 'in_progress') st = r < 0.42 ? 'submitted' : r < 0.55 ? 'late' : r < 0.62 ? 'returned' : r < 0.96 ? 'pending' : 'absent';
    else if (mix === 'all_done') st = r < 0.85 ? 'graded' : 'submitted';
    else st = r < 0.45 ? 'submitted' : r < 0.60 ? 'late' : r < 0.75 ? 'graded' : 'pending';
    const score = (st === 'graded') ? Math.round(50 + r * 49) : null;
    const submittedH = (st === 'submitted' || st === 'late' || st === 'graded' || st === 'returned')
      ? Math.round(2 + r * 70) : null;
    const files = (st === 'submitted' || st === 'late' || st === 'graded' || st === 'returned')
      ? Math.max(1, Math.round(r * 3)) : 0;
    list.push({ id: `s${i}`, name, state: st, score, submittedHoursAgo: submittedH, files });
  }
  return list;
}

const HW_RAW = [
  // Active — currently open, kids submitting
  { id: 'h1', subject: 'Mathematics', title: 'Linear equations · Ex 7.3 (Q1–Q12)',
    classId: '8B', state: 'active', publishedOn: '2026-05-05', dueOn: '2026-05-09', dueLabel: 'Tomorrow 11:59 PM',
    points: 20, mix: 'in_progress',
    description: 'Solve all 12 problems. Show working in your notebook, then upload a clear photo of each page. Late submissions accepted up to 24 hours with –20%.',
    attachments: [{ name: 'Ex-7-3-handout.pdf', size: '480 KB', kind: 'PDF' }],
    rubric: null, allowLate: true, latePolicy: '24h · –20%', resubmit: false,
    instructions: ['Show working clearly', 'Use blue or black pen', 'Photograph each page', 'Upload as one combined PDF (preferred)'],
  },
  { id: 'h2', subject: 'Science', title: 'Lab report · Photosynthesis experiment',
    classId: '8B', state: 'active', publishedOn: '2026-05-04', dueOn: '2026-05-10', dueLabel: 'Sat · 10 May',
    points: 30, mix: 'in_progress',
    description: 'Write a 2-page lab report on the leaf disc photosynthesis experiment we did on Tuesday. Use the IB-style format: Aim, Hypothesis, Method, Observations, Conclusion.',
    attachments: [
      { name: 'lab-report-template.docx', size: '24 KB', kind: 'DOCX' },
      { name: 'rubric.pdf', size: '88 KB', kind: 'PDF' },
    ],
    rubric: [
      { name: 'Hypothesis quality', weight: 5 },
      { name: 'Method clarity', weight: 8 },
      { name: 'Data & graphs', weight: 8 },
      { name: 'Conclusion & evaluation', weight: 9 },
    ],
    allowLate: true, latePolicy: '48h · –10%/day', resubmit: true,
    instructions: ['Min 2 pages', 'Include at least 1 data table & 1 graph', 'Cite sources', 'Run a Grammarly/spell check'],
  },
  { id: 'h3', subject: 'English', title: 'Essay · "A hero in my life" (500 words)',
    classId: '9A', state: 'active', publishedOn: '2026-05-03', dueOn: '2026-05-12', dueLabel: 'Mon · 12 May',
    points: 25, mix: 'fresh',
    description: 'Write a 500-word personal essay on a real-life hero — anyone outside film and sport. Focus on the qualities that make them heroic, with at least two specific examples.',
    attachments: [{ name: 'essay-rubric.pdf', size: '120 KB', kind: 'PDF' }],
    rubric: [
      { name: 'Thesis & focus', weight: 6 },
      { name: 'Examples & evidence', weight: 8 },
      { name: 'Structure & flow', weight: 6 },
      { name: 'Language & mechanics', weight: 5 },
    ],
    allowLate: true, latePolicy: '48h · –15%', resubmit: true,
    instructions: ['Word count: 450–550', 'Use first person', 'No filmstars/cricketers', 'Submit as DOC or PDF'],
  },
  // To grade — closed, awaiting grading
  { id: 'h4', subject: 'Mathematics', title: 'Algebra worksheet · Practice set 7.2',
    classId: '8B', state: 'closed', publishedOn: '2026-04-28', dueOn: '2026-05-04', dueLabel: 'Closed Mon',
    points: 15, mix: 'mostly_done',
    description: 'Complete worksheet 7.2 — focus on word problems. Show all working clearly.',
    attachments: [{ name: 'worksheet-7-2.pdf', size: '210 KB', kind: 'PDF' }],
    rubric: null, allowLate: false, latePolicy: 'Not allowed', resubmit: false,
    instructions: ['Show every step', 'Box your final answer', 'Use ruler for tables'],
  },
  { id: 'h5', subject: 'Social Studies', title: 'Map work · Indian rivers',
    classId: '9A', state: 'closed', publishedOn: '2026-04-30', dueOn: '2026-05-06', dueLabel: 'Closed Wed',
    points: 10, mix: 'mostly_done',
    description: 'Mark and label all major Indian rivers on the outline map. Use blue for rivers, green for tributaries.',
    attachments: [{ name: 'india-outline.pdf', size: '64 KB', kind: 'PDF' }],
    rubric: null, allowLate: false, latePolicy: 'Not allowed', resubmit: false,
    instructions: ['Use sketchpens, not crayon', 'Label clearly', 'Submit physical sheet'],
  },
  // Drafts — being prepared
  { id: 'h6', subject: 'Mathematics', title: 'Trigonometry · Ratios & angles practice',
    classId: '10C', state: 'draft', publishedOn: null, dueOn: null, dueLabel: 'Not set',
    points: 25, mix: 'fresh',
    description: 'Practice problems on basic trig ratios.',
    attachments: [], rubric: null, allowLate: true, latePolicy: '24h · –20%', resubmit: false,
    instructions: [],
  },
  { id: 'h7', subject: 'Science', title: 'Chapter 6 reading questions',
    classId: '8B', state: 'draft', publishedOn: null, dueOn: null, dueLabel: 'Not set',
    points: 0, mix: 'fresh',
    description: '',
    attachments: [], rubric: null, allowLate: true, latePolicy: '24h · –20%', resubmit: false,
    instructions: [],
  },
  // Scheduled — set, not yet released
  { id: 'h8', subject: 'English', title: 'Comprehension · Chapter 4',
    classId: '9A', state: 'scheduled', publishedOn: '2026-05-12', dueOn: '2026-05-15', dueLabel: 'Releases Mon · 12 May',
    points: 15, mix: 'fresh',
    description: 'Read Chapter 4 of the prose textbook and answer questions A–F.',
    attachments: [], rubric: null, allowLate: true, latePolicy: '24h · –10%', resubmit: false,
    instructions: [],
  },
  // Past — fully graded and returned
  { id: 'h9', subject: 'Science', title: 'Chapter 5 worksheet · States of matter',
    classId: '8B', state: 'past', publishedOn: '2026-04-15', dueOn: '2026-04-22', dueLabel: 'Returned 25 Apr',
    points: 20, mix: 'all_done',
    description: 'Worksheet on states of matter and changes of state.',
    attachments: [{ name: 'states-of-matter.pdf', size: '180 KB', kind: 'PDF' }],
    rubric: null, allowLate: false, latePolicy: 'Not allowed', resubmit: false,
    instructions: [], avgPct: 78,
  },
  { id: 'h10', subject: 'English', title: 'Reading comprehension · Chapter 3',
    classId: '9A', state: 'past', publishedOn: '2026-04-08', dueOn: '2026-04-15', dueLabel: 'Returned 18 Apr',
    points: 15, mix: 'all_done',
    description: 'Reading comprehension questions on the assigned passage.',
    attachments: [], rubric: null, allowLate: true, latePolicy: '24h · –10%', resubmit: false,
    instructions: [], avgPct: 84,
  },
];

// Augment with submissions
const HW_ALL = HW_RAW.map(h => {
  const subs = buildHwSubmissions(h.id, h.classId, null, h.mix);
  const submitted = subs.filter(s => s.state !== 'pending' && s.state !== 'absent').length;
  const graded = subs.filter(s => s.state === 'graded').length;
  const pending = subs.filter(s => s.state === 'pending').length;
  const late = subs.filter(s => s.state === 'late').length;
  const toGrade = subs.filter(s => s.state === 'submitted' || s.state === 'late').length;
  return { ...h, _subs: subs, _stats: { total: subs.length, submitted, graded, pending, late, toGrade } };
});

// ─────────────────────────────────────────────────────────────
// helpers
// ─────────────────────────────────────────────────────────────
function StateChipHw({ state }) {
  const cfg = {
    draft:     { lab: 'DRAFT',     bg: 'var(--n100)', clr: 'var(--n700)' },
    scheduled: { lab: 'SCHEDULED', bg: 'var(--info-50)', clr: '#1E40AF' },
    active:    { lab: 'ACTIVE',    bg: 'var(--success-50)', clr: 'var(--success)' },
    closed:    { lab: 'TO GRADE',  bg: '#FEF3C7', clr: 'var(--warning)' },
    past:      { lab: 'RETURNED',  bg: 'var(--p50)', clr: 'var(--p600)' },
  }[state] || { lab: state, bg: 'var(--n100)', clr: 'var(--n700)' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontSize: 9, fontWeight: 800, letterSpacing: '.08em',
      padding: '4px 8px', borderRadius: 99, background: cfg.bg, color: cfg.clr, fontFamily: 'var(--mono)',
    }}>{cfg.lab}</span>
  );
}

function SubStateChip({ state }) {
  const cfg = {
    pending:   { lab: 'Pending',   bg: 'var(--n100)', clr: 'var(--n600)' },
    submitted: { lab: 'Submitted', bg: 'var(--success-50)', clr: 'var(--success)' },
    late:      { lab: 'Late',      bg: '#FEF3C7', clr: 'var(--warning)' },
    graded:    { lab: 'Graded',    bg: 'var(--p50)', clr: 'var(--p600)' },
    returned:  { lab: 'Returned',  bg: 'var(--info-50)', clr: '#1E40AF' },
    absent:    { lab: 'Absent',    bg: 'var(--c50)', clr: 'var(--c600)' },
  }[state] || { lab: state, bg: 'var(--n100)', clr: 'var(--n600)' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontSize: 9.5, fontWeight: 800, letterSpacing: '.04em',
      padding: '3px 8px', borderRadius: 99, background: cfg.bg, color: cfg.clr,
    }}>{cfg.lab}</span>
  );
}

function FileChip({ kind }) {
  const c = {
    PDF:  { bg: 'var(--info-50)', clr: '#1E40AF' },
    DOCX: { bg: 'var(--p50)', clr: 'var(--p600)' },
    DOC:  { bg: 'var(--p50)', clr: 'var(--p600)' },
    JPG:  { bg: 'var(--c50)', clr: 'var(--c600)' },
    PNG:  { bg: 'var(--c50)', clr: 'var(--c600)' },
  }[kind] || { bg: 'var(--n100)', clr: 'var(--n700)' };
  return (
    <span style={{ fontSize: 9, fontWeight: 800, padding: '2px 6px', borderRadius: 4, background: c.bg, color: c.clr, fontFamily: 'var(--mono)' }}>{kind}</span>
  );
}

// ─────────────────────────────────────────────────────────────
// 1) Teacher Homework Hub
// ─────────────────────────────────────────────────────────────
function TeacherHomeworkHubScreen({ nav, params }) {
  const initialTab = (params && params.tab) || 'active';
  const [tab, setTab] = useStateH(initialTab);
  const [classFilter, setClassFilter] = useStateH('all');
  const [search, setSearch] = useStateH('');

  const filtered = useMemoH(() => {
    let list = HW_ALL.filter(h => {
      if (tab === 'active' && h.state !== 'active' && h.state !== 'scheduled') return false;
      if (tab === 'to_grade' && h.state !== 'closed') return false;
      if (tab === 'draft' && h.state !== 'draft') return false;
      if (tab === 'past' && h.state !== 'past') return false;
      if (classFilter !== 'all' && h.classId !== classFilter) return false;
      if (search) {
        const q = search.toLowerCase();
        if (!h.title.toLowerCase().includes(q) && !h.subject.toLowerCase().includes(q)) return false;
      }
      return true;
    });
    return list;
  }, [tab, classFilter, search]);

  const counts = {
    active: HW_ALL.filter(h => h.state === 'active' || h.state === 'scheduled').length,
    to_grade: HW_ALL.filter(h => h.state === 'closed').length,
    draft: HW_ALL.filter(h => h.state === 'draft').length,
    past: HW_ALL.filter(h => h.state === 'past').length,
  };

  const stats = useMemoH(() => {
    const live = HW_ALL.filter(h => h.state === 'active').length;
    const toGrade = HW_ALL.filter(h => h.state === 'closed').reduce((s, h) => s + h._stats.toGrade, 0);
    const drafts = HW_ALL.filter(h => h.state === 'draft').length;
    const subsToday = HW_ALL.flatMap(h => h._subs).filter(s => s.submittedHoursAgo !== null && s.submittedHoursAgo < 24).length;
    return { live, toGrade, drafts, subsToday };
  }, []);

  return (
    <div className="app screen-in">
      <StatusBar/>
      <div style={{ background: '#fff', padding: '52px 20px 0' }}>
        <div className="spread" style={{ marginBottom: 12 }}>
          <button onClick={() => nav.pop()} style={{ width: 40, height: 40, borderRadius: 12, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}>
            <Icon name="chev-l" size={18}/>
          </button>
          <div style={{ flex: 1, textAlign: 'center' }}>
            <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--n900)' }}>Homework</div>
            <div style={{ fontSize: 10.5, color: 'var(--n500)', fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>
              {TEACHER_HW_CONTEXT.short.toUpperCase()} · {TEACHER_HW_CONTEXT.classes.length} CLASSES
            </div>
          </div>
          <button onClick={() => nav.push('teachCreateHomework')} className="btn-sm" style={{ background: 'var(--p600)', color: '#fff', height: 36, padding: '0 12px', fontSize: 12, fontWeight: 700, borderRadius: 10, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <Icon name="plus" size={14}/> New
          </button>
        </div>

        {/* Stat strip */}
        <div className="card-flat" style={{ padding: 12, display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8, marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--success)', fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums' }}>{stats.live}</div>
            <div style={{ fontSize: 9, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>LIVE</div>
          </div>
          <div>
            <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--warning)', fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums' }}>{stats.toGrade}</div>
            <div style={{ fontSize: 9, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>TO GRADE</div>
          </div>
          <div>
            <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--n900)', fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums' }}>{stats.drafts}</div>
            <div style={{ fontSize: 9, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>DRAFTS</div>
          </div>
          <div>
            <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--p600)', fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums' }}>{stats.subsToday}</div>
            <div style={{ fontSize: 9, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>TODAY</div>
          </div>
        </div>

        {/* Class chips */}
        <div className="row" style={{ gap: 6, overflowX: 'auto', paddingBottom: 10, marginLeft: -4, paddingLeft: 4 }}>
          <button onClick={() => setClassFilter('all')} style={{
            flexShrink: 0, padding: '6px 12px', borderRadius: 99, fontSize: 11, fontWeight: 700,
            background: classFilter === 'all' ? 'var(--n900)' : 'var(--n50)',
            color: classFilter === 'all' ? '#fff' : 'var(--n700)',
          }}>All classes</button>
          {TEACHER_HW_CONTEXT.classes.map(c => (
            <button key={c.id} onClick={() => setClassFilter(c.id)} style={{
              flexShrink: 0, padding: '6px 12px', borderRadius: 99, fontSize: 11, fontWeight: 700,
              background: classFilter === c.id ? 'var(--n900)' : 'var(--n50)',
              color: classFilter === c.id ? '#fff' : 'var(--n700)',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>{c.label}<span style={{ fontSize: 9, opacity: .6, fontFamily: 'var(--mono)' }}>{c.students}</span></button>
          ))}
        </div>

        {/* Tabs */}
        <div className="row" style={{ gap: 6, overflowX: 'auto', paddingBottom: 12, borderBottom: '1px solid var(--n100)' }}>
          {[
            { id: 'active',    lab: 'Active' },
            { id: 'to_grade',  lab: 'To grade' },
            { id: 'draft',     lab: 'Drafts' },
            { id: 'past',      lab: 'Past' },
          ].map(x => (
            <button key={x.id} onClick={() => setTab(x.id)} style={{
              flexShrink: 0, padding: '8px 14px', borderRadius: 10, fontSize: 12, fontWeight: 700,
              background: tab === x.id ? 'var(--n900)' : 'transparent',
              color: tab === x.id ? '#fff' : 'var(--n600)',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {x.lab}
              <span style={{ display: 'inline-grid', placeItems: 'center', minWidth: 18, height: 18, padding: '0 5px', borderRadius: 99, fontSize: 9.5, fontWeight: 800,
                background: tab === x.id ? 'rgba(255,255,255,.2)' : 'var(--n100)',
                color: tab === x.id ? '#fff' : 'var(--n600)' }}>{counts[x.id]}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="app-body" style={{ paddingTop: 12 }}>
        {/* Search */}
        <div className="row" style={{ gap: 8, padding: '0 4px 8px' }}>
          <div style={{ flex: 1, position: 'relative' }}>
            <Icon name="search" size={14} style={{ position: 'absolute', left: 12, top: 12, color: 'var(--n400)' }}/>
            <input
              type="text" value={search} onChange={(e) => setSearch(e.target.value)}
              placeholder="Search homework or subject…"
              style={{
                width: '100%', height: 38, padding: '0 12px 0 32px',
                border: '1.5px solid var(--n100)', borderRadius: 10, fontSize: 13, fontFamily: 'inherit',
              }}/>
          </div>
        </div>

        {filtered.length === 0 ? (
          <div className="card" style={{ padding: 28, textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: 'var(--n50)', display: 'grid', placeItems: 'center', margin: '0 auto 12px', color: 'var(--n400)' }}>
              <Icon name="document" size={26}/>
            </div>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--n900)' }}>
              {tab === 'draft' ? 'No drafts yet' : tab === 'past' ? 'No past homework' : 'Nothing matches'}
            </div>
            <div style={{ fontSize: 12, color: 'var(--n500)', marginTop: 4 }}>
              {tab === 'draft' ? 'Tap + New to start one.' : 'Try clearing filters.'}
            </div>
            {tab === 'draft' && (
              <button onClick={() => nav.push('teachCreateHomework')} className="btn-sm" style={{ marginTop: 14, background: 'var(--p600)', color: '#fff', height: 36, padding: '0 16px', fontSize: 12, fontWeight: 700, borderRadius: 10 }}>
                <Icon name="plus" size={14}/> New homework
              </button>
            )}
          </div>
        ) : (
          <div className="col" style={{ gap: 10 }}>
            {filtered.map(h => <HwHubCard key={h.id} hw={h} nav={nav}/>)}
          </div>
        )}
      </div>
    </div>
  );
}

function HwHubCard({ hw, nav }) {
  const meta = subMeta(hw.subject);
  const cls = TEACHER_HW_CONTEXT.classes.find(c => c.id === hw.classId);
  const onCardTap = () => {
    if (hw.state === 'draft' || hw.state === 'scheduled') {
      nav.push('teachCreateHomework', { editingId: hw.id });
    } else {
      nav.push('teachHomeworkSubmissions', { hwId: hw.id });
    }
  };
  const submitPct = Math.round((hw._stats.submitted / hw._stats.total) * 100);

  return (
    <button onClick={onCardTap} className="card" style={{ padding: 14, textAlign: 'left', width: '100%', display: 'block', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: meta.clr }}/>
      <div className="spread" style={{ marginBottom: 4 }}>
        <div className="row" style={{ gap: 8 }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: meta.bg, color: meta.clr, display: 'grid', placeItems: 'center' }}>
            <Icon name={meta.ic} size={16}/>
          </div>
          <div>
            <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>
              {hw.subject.toUpperCase()} · {cls?.label}
            </div>
            <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--n900)', marginTop: 2, lineHeight: 1.25 }}>{hw.title}</div>
          </div>
        </div>
        <StateChipHw state={hw.state}/>
      </div>

      <div className="row" style={{ gap: 12, marginTop: 10, fontSize: 11, color: 'var(--n500)', flexWrap: 'wrap' }}>
        <span className="row" style={{ gap: 4 }}><Icon name="clock" size={12}/>{hw.dueLabel}</span>
        {hw.points > 0 && <span className="row" style={{ gap: 4 }}><Icon name="target" size={12}/>{hw.points} pts</span>}
        {hw.attachments.length > 0 && <span className="row" style={{ gap: 4 }}><Icon name="paperclip" size={12}/>{hw.attachments.length}</span>}
        {hw.rubric && <span className="row" style={{ gap: 4 }}><Icon name="clipboard" size={12}/>Rubric</span>}
      </div>

      {(hw.state === 'active' || hw.state === 'closed' || hw.state === 'past') && (
        <div style={{ marginTop: 12, paddingTop: 10, borderTop: '1px dashed var(--n100)' }}>
          {hw.state === 'active' && (
            <>
              <div className="spread" style={{ marginBottom: 6 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--n800)' }}>{hw._stats.submitted} / {hw._stats.total} submitted</div>
                <div style={{ fontSize: 11, color: 'var(--n500)', fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums' }}>{submitPct}%</div>
              </div>
              <div style={{ height: 5, borderRadius: 99, background: 'var(--n100)', overflow: 'hidden' }}>
                <div style={{ width: `${submitPct}%`, height: '100%', background: meta.clr, borderRadius: 99 }}/>
              </div>
              {hw._stats.late > 0 && <div style={{ fontSize: 10.5, color: 'var(--warning)', marginTop: 6, fontWeight: 700 }}>● {hw._stats.late} late submission{hw._stats.late > 1 ? 's' : ''}</div>}
            </>
          )}
          {hw.state === 'closed' && (
            <div className="row" style={{ gap: 8, alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--warning)' }}>{hw._stats.toGrade} awaiting your grade</div>
                <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 2 }}>{hw._stats.pending} did not submit · {hw._stats.graded} already graded</div>
              </div>
              <Icon name="chev-r" size={18} style={{ color: 'var(--n400)' }}/>
            </div>
          )}
          {hw.state === 'past' && (
            <div className="row" style={{ gap: 8, alignItems: 'center', justifyContent: 'space-between' }}>
              <div className="row" style={{ gap: 14 }}>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--p600)', fontFamily: 'var(--mono)' }}>{hw.avgPct || 78}%</div>
                  <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>CLASS AVG</div>
                </div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--n900)', fontFamily: 'var(--mono)' }}>{hw._stats.graded}</div>
                  <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>GRADED</div>
                </div>
              </div>
              <button onClick={(e) => { e.stopPropagation(); nav.push('teachHomeworkAnalytics', { hwId: hw.id }); }} className="btn-sm" style={{ background: 'var(--p50)', color: 'var(--p600)', height: 30, padding: '0 12px', fontSize: 11, fontWeight: 700, borderRadius: 8 }}>
                Analytics →
              </button>
            </div>
          )}
        </div>
      )}

      {hw.state === 'draft' && (
        <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px dashed var(--n100)' }}>
          <div style={{ fontSize: 11, color: 'var(--n500)' }}>
            {hw.description ? 'Resume editing → publish when ready' : 'Title set · add details and questions'}
          </div>
        </div>
      )}

      {hw.state === 'scheduled' && (
        <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px dashed var(--n100)' }}>
          <div className="row" style={{ gap: 6, alignItems: 'center' }}>
            <Icon name="clock" size={12} style={{ color: '#1E40AF' }}/>
            <div style={{ fontSize: 11, color: '#1E40AF', fontWeight: 700 }}>Auto-releases on {hw.publishedOn}</div>
          </div>
        </div>
      )}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// 2) Create / Edit Homework
// ─────────────────────────────────────────────────────────────
function TeacherCreateHomeworkScreen({ nav, params }) {
  const editingId = params && params.editingId;
  const editing = editingId ? HW_ALL.find(h => h.id === editingId) : null;
  const isNew = !editing;

  const [title, setTitle]         = useStateH(editing?.title || '');
  const [subject, setSubject]     = useStateH(editing?.subject || 'Mathematics');
  const [classId, setClassId]     = useStateH(editing?.classId || '8B');
  const [description, setDesc]    = useStateH(editing?.description || '');
  const [points, setPoints]       = useStateH(editing?.points || 20);
  const [dueDate, setDueDate]     = useStateH(editing?.dueOn || '');
  const [allowLate, setAllowLate] = useStateH(editing ? editing.allowLate : true);
  const [latePenalty, setLatePenalty] = useStateH(editing?.latePolicy || '24h · –20%');
  const [allowResubmit, setResubmit] = useStateH(editing ? editing.resubmit : false);
  const [hasRubric, setHasRubric] = useStateH(editing && editing.rubric ? true : false);
  const [files, setFiles]         = useStateH(editing?.attachments || []);
  const [instr, setInstr]         = useStateH(editing?.instructions || []);
  const [newInstr, setNewInstr]   = useStateH('');
  const [scheduling, setScheduling] = useStateH(false);

  const subjects = ['Mathematics', 'Science', 'English', 'Hindi', 'Social Studies', 'History', 'Civics'];

  const addInstr = () => {
    if (!newInstr.trim()) return;
    setInstr([...instr, newInstr.trim()]);
    setNewInstr('');
  };
  const addFile = (kind) => {
    const samples = {
      PDF: { name: `worksheet-${files.length + 1}.pdf`, size: '230 KB', kind: 'PDF' },
      DOCX: { name: `template-${files.length + 1}.docx`, size: '64 KB', kind: 'DOCX' },
      JPG: { name: `reference-${files.length + 1}.jpg`, size: '410 KB', kind: 'JPG' },
    };
    setFiles([...files, samples[kind]]);
  };

  const subMetaCur = subMeta(subject);
  const isPublishable = !!title && !!description && !!dueDate && !!points;

  const onSave = () => nav.replace('teachHomework', { tab: 'draft' });
  const onPublish = () => nav.replace('teachHomework', { tab: 'active' });

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader
        title={isNew ? 'New homework' : editing.state === 'draft' ? 'Edit draft' : 'Edit homework'}
        onBack={() => nav.pop()}
        right={!isNew && editing.state === 'active' && <button className="btn-sm" style={{ background: 'var(--c50)', color: 'var(--c600)', height: 32, padding: '0 12px', fontSize: 11, fontWeight: 700, borderRadius: 8 }}>Close early</button>}
      />

      <div className="app-body" style={{ paddingBottom: 100 }}>
        {/* Editing-state banner */}
        {!isNew && editing.state !== 'draft' && (
          <div className="card-flat" style={{ padding: 12, marginBottom: 12, background: 'var(--info-50)', borderColor: 'var(--info-50)' }}>
            <div className="row" style={{ gap: 10, alignItems: 'flex-start' }}>
              <Icon name="info" size={16} style={{ color: '#1E40AF', marginTop: 1 }}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: '#1E40AF' }}>This homework is already {editing.state === 'active' ? 'live' : editing.state}.</div>
                <div style={{ fontSize: 11, color: 'var(--n600)', marginTop: 2 }}>
                  Changes to questions or due date will notify all students.
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Title */}
        <div className="card" style={{ padding: 0 }}>
          <div style={{ padding: '14px 14px 8px' }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)' }}>HOMEWORK TITLE</div>
          </div>
          <input type="text" value={title} onChange={(e) => setTitle(e.target.value)}
            placeholder="e.g. Linear equations · Ex 7.3 (Q1–Q12)"
            style={{
              width: '100%', padding: '4px 14px 14px',
              border: 'none', outline: 'none', fontSize: 17, fontWeight: 700, color: 'var(--n900)', background: 'transparent', fontFamily: 'inherit',
            }}/>
          <div style={{ borderTop: '1px solid var(--n100)', padding: 14 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 8 }}>DESCRIPTION</div>
            <textarea value={description} onChange={(e) => setDesc(e.target.value)}
              placeholder="What should students do? Include any context they need."
              style={{
                width: '100%', minHeight: 90, padding: 10,
                border: '1.5px solid var(--n100)', borderRadius: 10, fontSize: 13, fontFamily: 'inherit', resize: 'vertical',
              }}/>
          </div>
        </div>

        {/* Subject + class */}
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 8 }}>SUBJECT</div>
          <div className="row" style={{ gap: 6, overflowX: 'auto', paddingBottom: 4, marginBottom: 14, marginLeft: -2, paddingLeft: 2 }}>
            {subjects.map(s => {
              const m = subMeta(s);
              const sel = subject === s;
              return (
                <button key={s} onClick={() => setSubject(s)} style={{
                  flexShrink: 0, padding: '8px 12px', borderRadius: 99, fontSize: 12, fontWeight: 700,
                  background: sel ? m.bg : 'var(--n50)',
                  color: sel ? m.clr : 'var(--n600)',
                  border: sel ? `1.5px solid ${m.clr}` : '1.5px solid transparent',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  <Icon name={m.ic} size={14}/> {s}
                </button>
              );
            })}
          </div>

          <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 8 }}>CLASS</div>
          <div className="row" style={{ gap: 6, flexWrap: 'wrap' }}>
            {TEACHER_HW_CONTEXT.classes.map(c => {
              const sel = classId === c.id;
              return (
                <button key={c.id} onClick={() => setClassId(c.id)} style={{
                  padding: '8px 12px', borderRadius: 99, fontSize: 12, fontWeight: 700,
                  background: sel ? 'var(--n900)' : 'var(--n50)',
                  color: sel ? '#fff' : 'var(--n700)',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  {c.label} <span style={{ fontSize: 9.5, opacity: .65, fontFamily: 'var(--mono)' }}>{c.students}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Due date + points + late policy */}
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 8 }}>DUE DATE & POINTS</div>
          <div className="row" style={{ gap: 8, marginBottom: 12 }}>
            <div style={{ flex: 1 }}>
              <input type="date" value={dueDate} onChange={(e) => setDueDate(e.target.value)}
                style={{ width: '100%', height: 42, padding: '0 12px', border: '1.5px solid var(--n100)', borderRadius: 10, fontSize: 13, fontFamily: 'inherit' }}/>
            </div>
            <div style={{ width: 100 }}>
              <input type="number" value={points} onChange={(e) => setPoints(parseInt(e.target.value) || 0)}
                placeholder="Points"
                style={{ width: '100%', height: 42, padding: '0 12px', border: '1.5px solid var(--n100)', borderRadius: 10, fontSize: 13, fontFamily: 'inherit', textAlign: 'center' }}/>
            </div>
          </div>

          <div style={{ paddingTop: 12, borderTop: '1px solid var(--n100)' }}>
            <div className="spread" style={{ marginBottom: 6 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Allow late submissions</div>
              <Toggle on={allowLate} onClick={() => setAllowLate(!allowLate)}/>
            </div>
            {allowLate && (
              <div className="row" style={{ gap: 6, flexWrap: 'wrap', marginTop: 8 }}>
                {['24h · –20%', '48h · –10%/day', '72h · no penalty', 'Until I close it'].map(p => (
                  <button key={p} onClick={() => setLatePenalty(p)} style={{
                    padding: '6px 10px', borderRadius: 99, fontSize: 11, fontWeight: 700,
                    background: latePenalty === p ? 'var(--p50)' : 'var(--n50)',
                    color: latePenalty === p ? 'var(--p600)' : 'var(--n600)',
                    border: latePenalty === p ? '1.5px solid var(--p600)' : '1.5px solid transparent',
                    fontFamily: 'var(--mono)',
                  }}>{p}</button>
                ))}
              </div>
            )}
          </div>

          <div style={{ paddingTop: 12, borderTop: '1px solid var(--n100)', marginTop: 12 }}>
            <div className="spread">
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Allow resubmission</div>
                <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>Students can revise after grading</div>
              </div>
              <Toggle on={allowResubmit} onClick={() => setResubmit(!allowResubmit)}/>
            </div>
          </div>

          <div style={{ paddingTop: 12, borderTop: '1px solid var(--n100)', marginTop: 12 }}>
            <div className="spread">
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Schedule release</div>
                <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>Auto-publish at a specific date/time</div>
              </div>
              <Toggle on={scheduling} onClick={() => setScheduling(!scheduling)}/>
            </div>
            {scheduling && (
              <input type="datetime-local" defaultValue=""
                style={{ marginTop: 10, width: '100%', height: 42, padding: '0 12px', border: '1.5px solid var(--n100)', borderRadius: 10, fontSize: 13, fontFamily: 'inherit' }}/>
            )}
          </div>
        </div>

        {/* Attachments */}
        <div className="card" style={{ padding: 14 }}>
          <div className="spread" style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)' }}>ATTACHMENTS · {files.length}</div>
            <div className="row" style={{ gap: 6 }}>
              <button onClick={() => addFile('PDF')} style={{ padding: '6px 10px', borderRadius: 8, background: 'var(--info-50)', color: '#1E40AF', fontSize: 10.5, fontWeight: 700 }}>+ PDF</button>
              <button onClick={() => addFile('DOCX')} style={{ padding: '6px 10px', borderRadius: 8, background: 'var(--p50)', color: 'var(--p600)', fontSize: 10.5, fontWeight: 700 }}>+ DOCX</button>
              <button onClick={() => addFile('JPG')} style={{ padding: '6px 10px', borderRadius: 8, background: 'var(--c50)', color: 'var(--c600)', fontSize: 10.5, fontWeight: 700 }}>+ Image</button>
            </div>
          </div>
          {files.length === 0 ? (
            <div style={{
              border: '1.5px dashed var(--n200)', borderRadius: 12, padding: 20, textAlign: 'center',
              background: 'var(--n50)',
            }}>
              <Icon name="paperclip" size={20} style={{ color: 'var(--n400)' }}/>
              <div style={{ fontSize: 12, color: 'var(--n500)', marginTop: 6 }}>Add reference materials students will need</div>
              <div style={{ fontSize: 10, color: 'var(--n400)', marginTop: 2, fontFamily: 'var(--mono)' }}>PDF · DOCX · IMG · MAX 20 MB</div>
            </div>
          ) : (
            <div className="col" style={{ gap: 6 }}>
              {files.map((f, i) => (
                <div key={i} className="row card-flat" style={{ padding: 10, gap: 10, alignItems: 'center' }}>
                  <FileChip kind={f.kind}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.name}</div>
                    <div style={{ fontSize: 10, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>{f.size}</div>
                  </div>
                  <button onClick={() => setFiles(files.filter((_, j) => j !== i))} style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--n50)', color: 'var(--n500)', display: 'grid', placeItems: 'center' }}>
                    <Icon name="x" size={14}/>
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Instructions */}
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 8 }}>INSTRUCTIONS</div>
          <div className="col" style={{ gap: 6, marginBottom: 8 }}>
            {instr.map((line, i) => (
              <div key={i} className="row" style={{ gap: 8, alignItems: 'flex-start' }}>
                <div style={{ width: 18, height: 18, borderRadius: 6, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 800, fontFamily: 'var(--mono)', flexShrink: 0, marginTop: 2 }}>{i + 1}</div>
                <div style={{ flex: 1, fontSize: 13, color: 'var(--n800)', lineHeight: 1.5 }}>{line}</div>
                <button onClick={() => setInstr(instr.filter((_, j) => j !== i))} style={{ width: 22, height: 22, borderRadius: 6, color: 'var(--n400)', display: 'grid', placeItems: 'center' }}>
                  <Icon name="x" size={12}/>
                </button>
              </div>
            ))}
          </div>
          <div className="row" style={{ gap: 6 }}>
            <input type="text" value={newInstr} onChange={(e) => setNewInstr(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && addInstr()}
              placeholder="Add an instruction…"
              style={{ flex: 1, height: 38, padding: '0 12px', border: '1.5px solid var(--n100)', borderRadius: 10, fontSize: 13, fontFamily: 'inherit' }}/>
            <button onClick={addInstr} disabled={!newInstr.trim()} style={{
              height: 38, padding: '0 14px', borderRadius: 10,
              background: newInstr.trim() ? 'var(--n900)' : 'var(--n100)',
              color: newInstr.trim() ? '#fff' : 'var(--n400)',
              fontSize: 12, fontWeight: 700,
            }}>Add</button>
          </div>
        </div>

        {/* Rubric */}
        <div className="card" style={{ padding: 14 }}>
          <div className="spread" style={{ marginBottom: hasRubric ? 10 : 0 }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Use rubric for grading</div>
              <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>Break the score down by criteria</div>
            </div>
            <Toggle on={hasRubric} onClick={() => setHasRubric(!hasRubric)}/>
          </div>
          {hasRubric && (
            <button className="btn btn-outline" style={{ width: '100%', height: 42, fontSize: 12 }}>
              <Icon name="plus" size={14}/> Configure rubric criteria
            </button>
          )}
        </div>

        {/* Preview hero */}
        <div className="card" style={{ padding: 14, background: subMetaCur.bg, border: 'none' }}>
          <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '.08em', fontFamily: 'var(--mono)', color: subMetaCur.clr }}>
            {subject.toUpperCase()} · {TEACHER_HW_CONTEXT.classes.find(c => c.id === classId)?.label.toUpperCase()}
          </div>
          <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--n900)', marginTop: 4, lineHeight: 1.25 }}>
            {title || 'Homework title'}
          </div>
          <div className="row" style={{ gap: 14, marginTop: 10, fontSize: 11, color: 'var(--n600)', flexWrap: 'wrap' }}>
            <span className="row" style={{ gap: 4 }}><Icon name="clock" size={12}/>{dueDate || 'No due date'}</span>
            <span className="row" style={{ gap: 4 }}><Icon name="target" size={12}/>{points} pts</span>
            <span className="row" style={{ gap: 4 }}><Icon name="users" size={12}/>{TEACHER_HW_CONTEXT.classes.find(c => c.id === classId)?.students} students</span>
          </div>
        </div>
      </div>

      {/* Bottom CTAs */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        background: '#fff', borderTop: '1px solid var(--n100)',
        padding: '12px 16px',
      }}>
        {isNew ? (
          <button onClick={onSave} disabled={!title} className="btn" style={{ width: '100%', height: 46, opacity: title ? 1 : .5 }}>
            <Icon name="check" size={14}/> Save draft
          </button>
        ) : (
          <div className="row" style={{ gap: 8 }}>
            <button onClick={onSave} className="btn btn-outline" style={{ flex: 1, height: 46 }}>
              Save changes
            </button>
            {(editing.state === 'draft' || editing.state === 'scheduled') && (
              <button onClick={onPublish} disabled={!isPublishable} className="btn" style={{ flex: 1.4, height: 46, opacity: isPublishable ? 1 : .5 }}>
                <Icon name="send" size={14}/> Publish to class
              </button>
            )}
            {editing.state === 'active' && (
              <button onClick={() => nav.push('teachHomeworkSubmissions', { hwId: editing.id })} className="btn" style={{ flex: 1.4, height: 46 }}>
                View submissions <Icon name="arrow-right" size={14}/>
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// Toggle helper
function Toggle({ on, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 44, height: 26, borderRadius: 99, padding: 2,
      background: on ? 'var(--p600)' : 'var(--n200)',
      transition: 'background .15s ease',
      display: 'flex', alignItems: 'center',
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: '50%', background: '#fff',
        transform: on ? 'translateX(18px)' : 'translateX(0)',
        transition: 'transform .15s ease', boxShadow: '0 1px 3px rgba(0,0,0,.15)',
      }}/>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// 3) Submissions list (per assignment)
// ─────────────────────────────────────────────────────────────
function TeacherHomeworkSubmissionsScreen({ nav, params }) {
  const hw = HW_ALL.find(h => h.id === (params && params.hwId)) || HW_ALL[0];
  const [filter, setFilter] = useStateH('all');
  const [search, setSearch] = useStateH('');
  const [sheet, setSheet] = useStateH(null);
  const meta = subMeta(hw.subject);
  const cls = TEACHER_HW_CONTEXT.classes.find(c => c.id === hw.classId);

  const visible = useMemoH(() => {
    let list = [...hw._subs];
    if (filter !== 'all') list = list.filter(s => s.state === filter);
    if (search) {
      const q = search.toLowerCase();
      list = list.filter(s => s.name.toLowerCase().includes(q));
    }
    list.sort((a, b) => {
      const order = { submitted: 0, late: 1, returned: 2, pending: 3, graded: 4, absent: 5 };
      return (order[a.state] || 9) - (order[b.state] || 9);
    });
    return list;
  }, [filter, search, hw]);

  const counts = {
    all: hw._subs.length,
    submitted: hw._subs.filter(s => s.state === 'submitted').length,
    late: hw._subs.filter(s => s.state === 'late').length,
    pending: hw._subs.filter(s => s.state === 'pending').length,
    graded: hw._subs.filter(s => s.state === 'graded').length,
  };

  const avg = (() => {
    const graded = hw._subs.filter(s => s.state === 'graded' && s.score !== null);
    if (!graded.length) return null;
    return Math.round(graded.reduce((s, x) => s + x.score, 0) / graded.length);
  })();

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader
        title="Submissions"
        onBack={() => nav.pop()}
        right={<button onClick={() => nav.push('teachHomeworkAnalytics', { hwId: hw.id })} style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}>
          <Icon name="zap" size={16} style={{ color: 'var(--p600)' }}/>
        </button>}
      />

      <div className="app-body">
        {/* Context card */}
        <div className="card" style={{ padding: 14, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: meta.clr }}/>
          <div style={{ fontSize: 9.5, fontWeight: 700, color: meta.clr, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>
            {hw.subject.toUpperCase()} · {cls?.label.toUpperCase()}
          </div>
          <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--n900)', marginTop: 4, lineHeight: 1.25 }}>{hw.title}</div>
          <div className="row" style={{ gap: 14, marginTop: 10, fontSize: 11, color: 'var(--n500)', flexWrap: 'wrap' }}>
            <span className="row" style={{ gap: 4 }}><Icon name="clock" size={12}/>{hw.dueLabel}</span>
            <span className="row" style={{ gap: 4 }}><Icon name="target" size={12}/>{hw.points} pts</span>
            <span className="row" style={{ gap: 4 }}><Icon name="users" size={12}/>{hw._stats.total}</span>
          </div>

          <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px dashed var(--n100)', display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>
            <div>
              <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--n900)', fontFamily: 'var(--mono)' }}>{hw._stats.submitted}</div>
              <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>SUBMITTED</div>
            </div>
            <div>
              <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--warning)', fontFamily: 'var(--mono)' }}>{hw._stats.toGrade}</div>
              <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>TO GRADE</div>
            </div>
            <div>
              <div style={{ fontSize: 17, fontWeight: 800, color: avg !== null ? 'var(--p600)' : 'var(--n400)', fontFamily: 'var(--mono)' }}>
                {avg !== null ? `${avg}%` : '—'}
              </div>
              <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>CLASS AVG</div>
            </div>
          </div>
        </div>

        {/* Action row */}
        {hw._stats.pending > 0 && (
          <button onClick={() => setSheet('remind')} className="card-flat row" style={{ padding: 12, gap: 10, alignItems: 'center', textAlign: 'left', background: 'var(--c50)', borderColor: 'var(--c50)' }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: '#fff', color: 'var(--c600)', display: 'grid', placeItems: 'center' }}>
              <Icon name="bell" size={16}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--c700)' }}>{hw._stats.pending} students haven't submitted</div>
              <div style={{ fontSize: 11, color: 'var(--n600)', marginTop: 2 }}>Send a polite nudge to them and their parents</div>
            </div>
            <Icon name="chev-r" size={18} style={{ color: 'var(--c600)' }}/>
          </button>
        )}

        {/* Search + filter */}
        <div className="row" style={{ gap: 8 }}>
          <div style={{ flex: 1, position: 'relative' }}>
            <Icon name="search" size={14} style={{ position: 'absolute', left: 12, top: 12, color: 'var(--n400)' }}/>
            <input
              type="text" value={search} onChange={(e) => setSearch(e.target.value)}
              placeholder="Search students…"
              style={{
                width: '100%', height: 38, padding: '0 12px 0 32px',
                border: '1.5px solid var(--n100)', borderRadius: 10, fontSize: 13, fontFamily: 'inherit',
              }}/>
          </div>
        </div>

        <div className="row" style={{ gap: 6, overflowX: 'auto', paddingBottom: 4, marginLeft: -2, paddingLeft: 2 }}>
          {[
            { id: 'all',       lab: 'All',       clr: 'var(--n900)' },
            { id: 'submitted', lab: 'Submitted', clr: 'var(--success)' },
            { id: 'late',      lab: 'Late',      clr: 'var(--warning)' },
            { id: 'pending',   lab: 'Pending',   clr: 'var(--n600)' },
            { id: 'graded',    lab: 'Graded',    clr: 'var(--p600)' },
          ].map(f => (
            <button key={f.id} onClick={() => setFilter(f.id)} style={{
              flexShrink: 0, padding: '6px 12px', borderRadius: 99, fontSize: 11, fontWeight: 700,
              background: filter === f.id ? f.clr : 'var(--n50)',
              color: filter === f.id ? '#fff' : 'var(--n700)',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {f.lab} <span style={{ fontSize: 9.5, fontFamily: 'var(--mono)', opacity: filter === f.id ? .8 : .5 }}>{counts[f.id]}</span>
            </button>
          ))}
        </div>

        {/* List */}
        {visible.length === 0 ? (
          <div className="card" style={{ padding: 24, textAlign: 'center' }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n800)' }}>No matches</div>
            <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 4 }}>Try clearing the filters above</div>
          </div>
        ) : (
          <div className="col" style={{ gap: 6 }}>
            {visible.map(s => (
              <button
                key={s.id}
                onClick={() => (s.state === 'submitted' || s.state === 'late' || s.state === 'graded' || s.state === 'returned')
                  ? nav.push('teachGradeHomework', { hwId: hw.id, studentId: s.id })
                  : null}
                disabled={s.state === 'pending' || s.state === 'absent'}
                className="row card" style={{ padding: 12, gap: 12, alignItems: 'center', textAlign: 'left',
                  opacity: (s.state === 'pending' || s.state === 'absent') ? .65 : 1,
                }}>
                <div className="av av-44" style={{
                  background: s.state === 'graded' ? 'var(--p50)' : s.state === 'late' ? 'var(--c50)' : s.state === 'pending' ? 'var(--n100)' : 'var(--success-50)',
                  color: s.state === 'graded' ? 'var(--p600)' : s.state === 'late' ? 'var(--c600)' : s.state === 'pending' ? 'var(--n400)' : 'var(--success)',
                }}>{s.name.charAt(0)}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="spread">
                    <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{s.name}</div>
                    <SubStateChip state={s.state}/>
                  </div>
                  <div className="row" style={{ gap: 10, marginTop: 4, fontSize: 10.5, color: 'var(--n500)' }}>
                    {s.submittedHoursAgo !== null && (
                      <span className="row" style={{ gap: 4 }}>
                        <Icon name="clock" size={11}/>
                        {s.submittedHoursAgo < 24 ? `${s.submittedHoursAgo}h ago` : `${Math.round(s.submittedHoursAgo / 24)}d ago`}
                      </span>
                    )}
                    {s.files > 0 && <span className="row" style={{ gap: 4 }}><Icon name="paperclip" size={11}/>{s.files}</span>}
                    {s.state === 'pending' && <span style={{ color: 'var(--c600)' }}>No submission yet</span>}
                    {s.state === 'absent' && <span style={{ color: 'var(--c600)' }}>Marked absent</span>}
                  </div>
                </div>
                {s.state === 'graded' && (
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--p600)', fontFamily: 'var(--mono)' }}>{s.score}%</div>
                    <div style={{ fontSize: 9, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>SCORE</div>
                  </div>
                )}
                {(s.state === 'submitted' || s.state === 'late') && <Icon name="chev-r" size={16} style={{ color: 'var(--n400)' }}/>}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Bottom CTA */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        background: '#fff', borderTop: '1px solid var(--n100)',
        padding: '12px 16px',
      }}>
        {hw._stats.toGrade > 0 ? (
          <button
            onClick={() => {
              const next = hw._subs.find(s => s.state === 'submitted' || s.state === 'late');
              if (next) nav.push('teachGradeHomework', { hwId: hw.id, studentId: next.id });
            }}
            className="btn"
            style={{ width: '100%', height: 46 }}>
            <Icon name="edit" size={14}/> Start grading · {hw._stats.toGrade} left
          </button>
        ) : (
          <button
            onClick={() => nav.push('teachHomeworkAnalytics', { hwId: hw.id })}
            className="btn"
            style={{ width: '100%', height: 46 }}>
            <Icon name="zap" size={14}/> View class analytics
          </button>
        )}
      </div>

      {/* Reminder sheet */}
      {sheet === 'remind' && (
        <>
          <div className="sheet-backdrop" onClick={() => setSheet(null)}/>
          <div className="sheet sheet-up">
            <div className="sheet-handle"/>
            <div style={{ padding: '16px 20px 8px' }}>
              <div className="spread">
                <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--n900)' }}>Send reminder</div>
                <button onClick={() => setSheet(null)} style={{ width: 32, height: 32, borderRadius: 10, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}><Icon name="x" size={16}/></button>
              </div>
              <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{hw._stats.pending} students · {hw.title}</div>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: '8px 20px' }}>
              <div className="col" style={{ gap: 8 }}>
                {[
                  { ic: 'message', lab: 'In-app notification', sub: 'Free · arrives instantly' },
                  { ic: 'whatsapp', lab: 'WhatsApp parents', sub: 'Sends to mapped parent number' },
                  { ic: 'mail', lab: 'Email students + parents', sub: 'Logs in school dashboard' },
                ].map((m, i) => (
                  <button key={i} onClick={() => setSheet(null)} className="row" style={{ width: '100%', padding: 14, borderRadius: 12, gap: 12, background: '#fff', border: '1.5px solid var(--n100)', textAlign: 'left' }}>
                    <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center' }}><Icon name={m.ic} size={18}/></div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{m.lab}</div>
                      <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1 }}>{m.sub}</div>
                    </div>
                    <Icon name="chev-r" size={16} style={{ color: 'var(--n400)' }}/>
                  </button>
                ))}
              </div>
              <textarea placeholder="Add a personal note (optional)" defaultValue={`Hi! Just a reminder — "${hw.title}" is due ${hw.dueLabel.toLowerCase()}. Please submit on time. — ${TEACHER_HW_CONTEXT.short}`}
                style={{ width: '100%', marginTop: 12, padding: 12, borderRadius: 12, border: '1.5px solid var(--n100)', fontSize: 13, minHeight: 80, fontFamily: 'inherit', resize: 'none' }}/>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 4) Grade individual submission
// ─────────────────────────────────────────────────────────────
function TeacherGradeHomeworkScreen({ nav, params }) {
  const hw = HW_ALL.find(h => h.id === (params && params.hwId)) || HW_ALL[0];
  const stu = hw._subs.find(s => s.id === (params && params.studentId)) || hw._subs[0];

  const [score, setScore] = useStateH(stu.score !== null ? stu.score : Math.round(hw.points * 0.75));
  const [comment, setComment] = useStateH('');
  const [feedback, setFeedback] = useStateH(null);
  const [rubricScores, setRubricScores] = useStateH({});

  const cls = TEACHER_HW_CONTEXT.classes.find(c => c.id === hw.classId);
  const isLate = stu.state === 'late';
  const isGraded = stu.state === 'graded';
  const meta = subMeta(hw.subject);

  // Find prev/next ungraded
  const queue = hw._subs.filter(s => s.state === 'submitted' || s.state === 'late');
  const idx = queue.findIndex(s => s.id === stu.id);
  const next = queue[idx + 1];
  const total = queue.length;

  const onSubmitGrade = () => {
    if (next) {
      nav.replace('teachGradeHomework', { hwId: hw.id, studentId: next.id });
    } else {
      nav.replace('teachHomeworkSubmissions', { hwId: hw.id });
    }
  };

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader
        title={isGraded ? 'Review submission' : `Grade · ${idx + 1} of ${total || 1}`}
        onBack={() => nav.pop()}
        right={<button style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}><Icon name="more" size={18}/></button>}
      />

      <div className="app-body" style={{ paddingBottom: 100 }}>
        {/* Student header */}
        <div className="card" style={{ padding: 14 }}>
          <div className="row" style={{ gap: 12 }}>
            <div className="av av-56" style={{ background: 'var(--p50)', color: 'var(--p600)', fontSize: 22, fontWeight: 800 }}>{stu.name.charAt(0)}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--n900)' }}>{stu.name}</div>
              <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{cls?.label} · Roll #{stu.id.replace('s', '')}</div>
              <div className="row" style={{ gap: 8, marginTop: 6, alignItems: 'center', flexWrap: 'wrap' }}>
                <SubStateChip state={stu.state}/>
                {stu.submittedHoursAgo !== null && (
                  <span style={{ fontSize: 10.5, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>
                    Submitted {stu.submittedHoursAgo < 24 ? `${stu.submittedHoursAgo}h ago` : `${Math.round(stu.submittedHoursAgo / 24)}d ago`}
                  </span>
                )}
              </div>
            </div>
          </div>
          {isLate && (
            <div className="card-flat row" style={{ padding: 10, gap: 10, marginTop: 10, background: '#FEF3C7', borderColor: '#FEF3C7' }}>
              <Icon name="info" size={14} style={{ color: 'var(--warning)' }}/>
              <div style={{ flex: 1, fontSize: 11, color: '#92400E' }}>
                <b>Submitted late.</b> Penalty: {hw.latePolicy}.
              </div>
            </div>
          )}
        </div>

        {/* Assignment context */}
        <div className="card-flat" style={{ padding: 12 }}>
          <div className="row" style={{ gap: 10 }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: meta.bg, color: meta.clr, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <Icon name={meta.ic} size={14}/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 9.5, fontWeight: 700, color: meta.clr, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>{hw.subject.toUpperCase()}</div>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{hw.title}</div>
            </div>
            <div style={{ fontSize: 11, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>{hw.points} pts</div>
          </div>
        </div>

        {/* Submission preview */}
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 10 }}>STUDENT'S SUBMISSION</div>
          <div className="col" style={{ gap: 8 }}>
            {Array.from({ length: stu.files }).map((_, i) => (
              <div key={i} className="row" style={{ padding: 10, borderRadius: 10, background: 'var(--n50)', gap: 10, alignItems: 'center' }}>
                <FileChip kind={['JPG', 'PDF', 'JPG'][i % 3]}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)' }}>page-{i + 1}.{['jpg', 'pdf', 'jpg'][i % 3]}</div>
                  <div style={{ fontSize: 10, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>{[840, 320, 1200][i % 3]} KB</div>
                </div>
                <button style={{ width: 28, height: 28, borderRadius: 8, background: '#fff', color: 'var(--p600)', display: 'grid', placeItems: 'center' }}>
                  <Icon name="eye" size={14}/>
                </button>
              </div>
            ))}
            {stu.files === 0 && (
              <div style={{ padding: 16, textAlign: 'center', borderRadius: 10, background: 'var(--n50)' }}>
                <div style={{ fontSize: 12, color: 'var(--n500)' }}>No file attachments — text only submission</div>
              </div>
            )}
          </div>

          {/* Mock student note */}
          <div style={{ marginTop: 12, padding: 12, borderLeft: '3px solid var(--p600)', background: 'var(--p50)', borderRadius: '0 10px 10px 0' }}>
            <div style={{ fontSize: 9.5, fontWeight: 700, color: 'var(--p600)', letterSpacing: '.06em', fontFamily: 'var(--mono)' }}>STUDENT NOTE</div>
            <div style={{ fontSize: 12.5, color: 'var(--n800)', marginTop: 4, lineHeight: 1.5 }}>
              {[
                'Submitted on time! Q9 was tricky — I tried two methods.',
                "Sorry it's a bit late — was unwell yesterday.",
                'Used the rubric template you shared. Hope the graphs are clear enough.',
                'Q3(b) — please check my approach, I think there are two valid answers.',
              ][parseInt(stu.id.replace('s', '')) % 4]}
            </div>
          </div>

          <button className="btn-sm btn-soft" style={{ marginTop: 10, width: '100%', height: 36, fontSize: 12 }}>
            <Icon name="edit" size={14}/> Annotate submission
          </button>
        </div>

        {/* Rubric (if any) */}
        {hw.rubric && (
          <div className="card" style={{ padding: 14 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 10 }}>RUBRIC GRADING</div>
            <div className="col" style={{ gap: 12 }}>
              {hw.rubric.map((r, i) => {
                const v = rubricScores[i] !== undefined ? rubricScores[i] : Math.round(r.weight * 0.7);
                return (
                  <div key={i}>
                    <div className="spread" style={{ marginBottom: 6 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{r.name}</div>
                      <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--p600)', fontFamily: 'var(--mono)' }}>{v} / {r.weight}</div>
                    </div>
                    <div className="row" style={{ gap: 4, flexWrap: 'wrap' }}>
                      {Array.from({ length: r.weight + 1 }).map((_, n) => (
                        <button key={n} onClick={() => setRubricScores({ ...rubricScores, [i]: n })} style={{
                          width: 30, height: 30, borderRadius: 8,
                          background: v === n ? 'var(--p600)' : 'var(--n50)',
                          color: v === n ? '#fff' : 'var(--n700)',
                          fontSize: 11, fontWeight: 800, fontFamily: 'var(--mono)',
                        }}>{n}</button>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* Score */}
        {!hw.rubric && (
          <div className="card" style={{ padding: 14 }}>
            <div className="spread" style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)' }}>OVERALL SCORE</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--p600)', fontFamily: 'var(--mono)' }}>{score} / {hw.points}</div>
            </div>
            <input type="range" min="0" max={hw.points} value={score} onChange={(e) => setScore(parseInt(e.target.value))}
              style={{ width: '100%', accentColor: 'var(--p600)', marginBottom: 8 }}/>
            <div className="row" style={{ gap: 6, flexWrap: 'wrap' }}>
              {[0, Math.round(hw.points * 0.5), Math.round(hw.points * 0.7), Math.round(hw.points * 0.85), hw.points].map(p => (
                <button key={p} onClick={() => setScore(p)} style={{
                  padding: '6px 10px', borderRadius: 8, fontSize: 11, fontWeight: 700,
                  background: score === p ? 'var(--p600)' : 'var(--n50)',
                  color: score === p ? '#fff' : 'var(--n700)',
                  fontFamily: 'var(--mono)',
                }}>{p}</button>
              ))}
            </div>
          </div>
        )}

        {/* Comment */}
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 8 }}>FEEDBACK FOR STUDENT</div>
          <textarea value={comment} onChange={(e) => setComment(e.target.value)}
            placeholder="Specific, constructive feedback…"
            style={{ width: '100%', minHeight: 100, padding: 12, borderRadius: 10, border: '1.5px solid var(--n100)', fontSize: 13, fontFamily: 'inherit', resize: 'vertical' }}/>
          <div className="row" style={{ gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
            {['Great work!', 'Show more working', 'Check question 4 again', 'Excellent presentation'].map(s => (
              <button key={s} onClick={() => setComment(comment ? comment + ' ' + s : s)} style={{
                padding: '5px 10px', borderRadius: 99, fontSize: 10.5, fontWeight: 600,
                background: 'var(--n50)', color: 'var(--n700)', border: '1px dashed var(--n200)',
              }}>+ {s}</button>
            ))}
          </div>
        </div>

        {/* Feedback action */}
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--n500)', letterSpacing: '.06em', fontFamily: 'var(--mono)', marginBottom: 10 }}>NEXT STEP</div>
          <div className="col" style={{ gap: 6 }}>
            {[
              { id: 'mark', ic: 'check', lab: 'Mark as graded', sub: 'Final · student sees their score' },
              ...(hw.resubmit ? [{ id: 'return', ic: 'history', lab: 'Return for resubmission', sub: 'Student can revise and re-submit' }] : []),
              { id: 'flag', ic: 'flame', lab: 'Flag for follow-up', sub: 'Discuss in next class · not visible to student' },
            ].map(opt => (
              <button key={opt.id} onClick={() => setFeedback(opt.id)} className="row" style={{
                width: '100%', padding: 12, borderRadius: 10, gap: 12, alignItems: 'center', textAlign: 'left',
                background: feedback === opt.id ? 'var(--p50)' : '#fff',
                border: feedback === opt.id ? '1.5px solid var(--p600)' : '1.5px solid var(--n100)',
              }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: feedback === opt.id ? 'var(--p600)' : 'var(--n50)', color: feedback === opt.id ? '#fff' : 'var(--n600)', display: 'grid', placeItems: 'center' }}>
                  <Icon name={opt.ic} size={16}/>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{opt.lab}</div>
                  <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{opt.sub}</div>
                </div>
                {feedback === opt.id && <Icon name="check" size={16} style={{ color: 'var(--p600)' }}/>}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Bottom CTA */}
      <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 btn-outline" style={{ flex: 1, height: 46 }}>
          Save & exit
        </button>
        <button onClick={onSubmitGrade} className="btn" style={{ flex: 1.6, height: 46 }}>
          {next ? <>Save · grade next <Icon name="arrow-right" size={14}/></> : <><Icon name="check" size={14}/> Finish grading</>}
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 5) Class analytics for a homework
// ─────────────────────────────────────────────────────────────
function TeacherHomeworkAnalyticsScreen({ nav, params }) {
  const hw = HW_ALL.find(h => h.id === (params && params.hwId)) || HW_ALL.find(h => h.state === 'past') || HW_ALL[0];
  const meta = subMeta(hw.subject);
  const cls = TEACHER_HW_CONTEXT.classes.find(c => c.id === hw.classId);

  const stats = useMemoH(() => {
    const graded = hw._subs.filter(s => s.state === 'graded' && s.score !== null);
    const scores = graded.map(s => s.score);
    if (!scores.length) return null;
    const avg = Math.round(scores.reduce((a, b) => a + b, 0) / scores.length);
    const sorted = [...scores].sort((a, b) => a - b);
    const median = sorted[Math.floor(sorted.length / 2)];
    const top = Math.max(...scores);
    const low = Math.min(...scores);
    const onTime = hw._subs.filter(s => s.state === 'submitted' || s.state === 'graded').length;
    const lateCount = hw._subs.filter(s => s.state === 'late').length;
    const noSub = hw._subs.filter(s => s.state === 'pending' || s.state === 'absent').length;

    // Distribution
    const buckets = [0, 0, 0, 0, 0]; // <40, 40-59, 60-74, 75-89, 90+
    scores.forEach(s => {
      if (s < 40) buckets[0]++;
      else if (s < 60) buckets[1]++;
      else if (s < 75) buckets[2]++;
      else if (s < 90) buckets[3]++;
      else buckets[4]++;
    });

    // Top + struggling
    const sortedByScore = graded.slice().sort((a, b) => b.score - a.score);
    const topStu = sortedByScore.slice(0, 3);
    const lowStu = sortedByScore.slice(-3).reverse();

    return { avg, median, top, low, onTime, lateCount, noSub, buckets, topStu, lowStu, gradedCount: graded.length };
  }, [hw]);

  if (!stats) {
    return (
      <div className="app screen-in">
        <StatusBar/>
        <NavHeader title="Class analytics" onBack={() => nav.pop()}/>
        <div className="app-body">
          <div className="card" style={{ padding: 28, textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: 'var(--n50)', display: 'grid', placeItems: 'center', margin: '0 auto 12px', color: 'var(--n400)' }}>
              <Icon name="zap" size={26}/>
            </div>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--n900)' }}>No graded submissions yet</div>
            <div style={{ fontSize: 12, color: 'var(--n500)', marginTop: 4 }}>Analytics appear after you've graded a few students.</div>
          </div>
        </div>
      </div>
    );
  }

  const completionPct = Math.round((stats.onTime + stats.lateCount) / hw._subs.length * 100);
  const maxBucket = Math.max(...stats.buckets);

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader
        title="Class analytics"
        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">
        {/* Context */}
        <div className="card" style={{ padding: 14, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: meta.clr }}/>
          <div style={{ fontSize: 9.5, fontWeight: 700, color: meta.clr, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>
            {hw.subject.toUpperCase()} · {cls?.label.toUpperCase()}
          </div>
          <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--n900)', marginTop: 4, lineHeight: 1.25 }}>{hw.title}</div>
          <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 6, fontFamily: 'var(--mono)' }}>{hw.dueLabel} · {hw._subs.length} students</div>
        </div>

        {/* Top stats */}
        <div className="card-flat" style={{ padding: 14, display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8 }}>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--p600)', fontFamily: 'var(--mono)' }}>{stats.avg}%</div>
            <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>AVERAGE</div>
          </div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--success)', fontFamily: 'var(--mono)' }}>{stats.top}%</div>
            <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>TOP</div>
          </div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', fontFamily: 'var(--mono)' }}>{stats.median}%</div>
            <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>MEDIAN</div>
          </div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--c600)', fontFamily: 'var(--mono)' }}>{stats.low}%</div>
            <div style={{ fontSize: 9.5, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.04em' }}>LOWEST</div>
          </div>
        </div>

        {/* Completion */}
        <div className="card" style={{ padding: 14 }}>
          <div className="spread" style={{ marginBottom: 8 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Completion rate</div>
            <div style={{ fontSize: 14, fontWeight: 800, color: completionPct >= 80 ? 'var(--success)' : 'var(--warning)', fontFamily: 'var(--mono)' }}>{completionPct}%</div>
          </div>
          <div style={{ height: 10, borderRadius: 99, background: 'var(--n100)', overflow: 'hidden', display: 'flex' }}>
            <div style={{ width: `${(stats.onTime / hw._subs.length) * 100}%`, background: 'var(--success)' }}/>
            <div style={{ width: `${(stats.lateCount / hw._subs.length) * 100}%`, background: 'var(--warning)' }}/>
          </div>
          <div className="row" style={{ gap: 14, marginTop: 10, fontSize: 11, color: 'var(--n600)', flexWrap: 'wrap' }}>
            <span className="row" style={{ gap: 4 }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--success)' }}/>
              {stats.onTime} on time
            </span>
            <span className="row" style={{ gap: 4 }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--warning)' }}/>
              {stats.lateCount} late
            </span>
            <span className="row" style={{ gap: 4 }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--n200)' }}/>
              {stats.noSub} no submission
            </span>
          </div>
        </div>

        {/* Score distribution */}
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)', marginBottom: 12 }}>Score distribution</div>
          <div className="col" style={{ gap: 8 }}>
            {[
              { lab: '90%+',    count: stats.buckets[4], clr: 'var(--success)' },
              { lab: '75–89%',  count: stats.buckets[3], clr: '#65A30D' },
              { lab: '60–74%',  count: stats.buckets[2], clr: 'var(--warning)' },
              { lab: '40–59%',  count: stats.buckets[1], clr: '#EA580C' },
              { lab: '< 40%',   count: stats.buckets[0], clr: 'var(--c600)' },
            ].map((b, i) => (
              <div key={i} className="row" style={{ gap: 10, alignItems: 'center' }}>
                <div style={{ width: 56, fontSize: 11, fontWeight: 700, color: 'var(--n700)', fontFamily: 'var(--mono)' }}>{b.lab}</div>
                <div style={{ flex: 1, height: 22, borderRadius: 6, background: 'var(--n50)', overflow: 'hidden', position: 'relative' }}>
                  <div style={{
                    width: maxBucket > 0 ? `${(b.count / maxBucket) * 100}%` : '0%',
                    height: '100%', background: b.clr, transition: 'width .4s ease',
                    display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 8,
                  }}>
                    {b.count > 0 && (
                      <span style={{ fontSize: 10, fontWeight: 800, color: '#fff', fontFamily: 'var(--mono)' }}>{b.count}</span>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Top performers */}
        {stats.topStu.length > 0 && (
          <div className="card" style={{ padding: 14 }}>
            <div className="spread" style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Top performers</div>
              <Icon name="trophy" size={16} style={{ color: '#854D0E' }}/>
            </div>
            <div className="col" style={{ gap: 8 }}>
              {stats.topStu.map((s, i) => (
                <button key={s.id} onClick={() => nav.push('teachGradeHomework', { hwId: hw.id, studentId: s.id })} className="row" style={{ width: '100%', padding: 10, gap: 12, borderRadius: 10, background: i === 0 ? '#FEFCE8' : 'var(--n50)', textAlign: 'left' }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: i === 0 ? '#854D0E' : 'var(--n200)', color: i === 0 ? '#fff' : 'var(--n700)', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 800, fontFamily: 'var(--mono)' }}>{i + 1}</div>
                  <div className="av av-32" style={{ background: 'var(--p50)', color: 'var(--p600)', fontSize: 13 }}>{s.name.charAt(0)}</div>
                  <div style={{ flex: 1, fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{s.name}</div>
                  <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--success)', fontFamily: 'var(--mono)' }}>{s.score}%</div>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Struggling */}
        {stats.lowStu.length > 0 && (
          <div className="card" style={{ padding: 14, background: 'var(--c50)', borderColor: 'var(--c50)' }}>
            <div className="spread" style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--c700)' }}>May need support</div>
              <Icon name="info" size={16} style={{ color: 'var(--c600)' }}/>
            </div>
            <div className="col" style={{ gap: 8 }}>
              {stats.lowStu.map((s) => (
                <button key={s.id} onClick={() => nav.push('teachGradeHomework', { hwId: hw.id, studentId: s.id })} className="row" style={{ width: '100%', padding: 10, gap: 12, borderRadius: 10, background: '#fff', textAlign: 'left' }}>
                  <div className="av av-32" style={{ background: 'var(--c50)', color: 'var(--c600)', fontSize: 13 }}>{s.name.charAt(0)}</div>
                  <div style={{ flex: 1, fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{s.name}</div>
                  <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--c600)', fontFamily: 'var(--mono)' }}>{s.score}%</div>
                  <Icon name="chev-r" size={14} style={{ color: 'var(--n400)' }}/>
                </button>
              ))}
            </div>
            <button className="btn-sm" style={{ marginTop: 10, width: '100%', background: '#fff', color: 'var(--c700)', height: 36, fontSize: 12, fontWeight: 700, borderRadius: 10, border: '1.5px solid var(--c200, #FCA5A5)' }}>
              <Icon name="message" size={14}/> Message these students
            </button>
          </div>
        )}

        {/* Submission timeline insight */}
        <div className="card-flat" style={{ padding: 12, background: 'var(--info-50)', borderColor: 'var(--info-50)' }}>
          <div className="row" style={{ gap: 10, alignItems: 'flex-start' }}>
            <Icon name="clock" size={16} style={{ color: '#1E40AF', marginTop: 1 }}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#1E40AF' }}>Insight</div>
              <div style={{ fontSize: 11.5, color: 'var(--n700)', marginTop: 4, lineHeight: 1.5 }}>
                {Math.round(stats.onTime / hw._subs.length * 100)}% submitted on time — typical for this class is 75%. Consider keeping the same due-day cadence.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Export
// ─────────────────────────────────────────────────────────────
Object.assign(window, {
  TeacherHomeworkHubScreen,
  TeacherCreateHomeworkScreen,
  TeacherHomeworkSubmissionsScreen,
  TeacherGradeHomeworkScreen,
  TeacherHomeworkAnalyticsScreen,
});
