// screens-gradebook.jsx — Class-teacher consolidated marks view
// 1. TeacherGradeBookScreen — students × assessments matrix with sums + percentile
// 2. TeacherReportCardScreen — per-student term summary across all subjects
// 3. TeacherCompareAssessmentsScreen — side-by-side comparison of any two

const { useState: useStateGB, useMemo: useMemoGB } = React;

// Build a column = assessment, row = student matrix.
function buildGradeBook() {
  const students = (window.CLASS_8B_STUDENTS || []).slice(0, 24); // viewport-friendly
  const cols = [
    { id: 'a1', sub: 'Math', title: 'Linear eq · Practice', max: 24, when: '12 Mar', wt: 1 },
    { id: 'a2', sub: 'Math', title: 'Mid-term', max: 100, when: '5 Mar', wt: 3 },
    { id: 'a3', sub: 'Math', title: 'Mental math 4', max: 20, when: '28 Feb', wt: 1 },
    { id: 'a4', sub: 'Math', title: 'Geometry', max: 30, when: '20 Feb', wt: 1.5 },
    { id: 'a5', sub: 'Math', title: 'Algebra surprise', max: 15, when: '14 Feb', wt: 1 },
    { id: 'a6', sub: 'Math', title: 'Unit test 3', max: 50, when: '8 Feb', wt: 2 },
  ];
  const grid = students.map((name, si) => {
    const r = (j) => ((Math.sin(si * 31 + j * 13) * 10000) % 1 + 1) % 1;
    return cols.map((c, j) => {
      const x = r(j);
      if (x < 0.04) return null; // absent
      const pct = 0.42 + r(j + 100) * 0.55;
      return Math.round(pct * c.max);
    });
  });
  // Weighted average per student (out of 100)
  const totals = grid.map((row) => {
    let acc = 0, wt = 0;
    row.forEach((v, j) => {
      if (v == null) return;
      acc += (v / cols[j].max) * cols[j].wt;
      wt += cols[j].wt;
    });
    return wt ? Math.round((acc / wt) * 100) : 0;
  });
  // Rank
  const ranked = [...totals].map((t, i) => ({ i, t })).sort((a, b) => b.t - a.t);
  const ranks = students.map((_, i) => ranked.findIndex(r => r.i === i) + 1);
  return { students, cols, grid, totals, ranks };
}
const GRADEBOOK = buildGradeBook();

// ─────────────────────────────────────────────────────────────
// 1. Grade book matrix
// ─────────────────────────────────────────────────────────────
function TeacherGradeBookScreen({ nav }) {
  const cls = '8-B';
  const [highlight, setHighlight] = useStateGB('top'); // 'top' | 'bottom' | 'improved' | null
  const { students, cols, grid, totals, ranks } = GRADEBOOK;

  // Column averages
  const colAvg = cols.map((c, j) => {
    const vals = grid.map(row => row[j]).filter(v => v != null);
    return vals.length ? Math.round((vals.reduce((s, x) => s + x, 0) / vals.length / c.max) * 100) : 0;
  });

  const rowClass = (i) => {
    if (highlight === 'top' && ranks[i] <= 5) return { background: 'rgba(16,185,129,.06)' };
    if (highlight === 'bottom' && totals[i] < 50) return { background: 'rgba(239,68,68,.06)' };
    return null;
  };

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title={`Grade book · ${cls}`} onBack={() => nav.pop()}
        right={<button style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--n50)', display: 'grid', placeItems: 'center' }} title="Export"><Icon name="download" size={16}/></button>}/>
      <div className="app-body" style={{ paddingTop: 4 }}>

        {/* Summary */}
        <div className="card" style={{ padding: 14, marginBottom: 12, background: '#fff' }}>
          <div className="spread">
            <div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'var(--mono)' }}>Math · Term 2 · Mrs. Reddy</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>
                {Math.round(totals.reduce((s, x) => s + x, 0) / totals.length)}<span style={{ fontSize: 14, color: 'var(--n500)', fontWeight: 600 }}> /100 avg</span>
              </div>
            </div>
            <button onClick={() => nav.push('teachCompareAssessments')} className="btn-soft" style={{ height: 32, padding: '0 12px', fontSize: 11, fontWeight: 700 }}>Compare →</button>
          </div>
          <div className="row" style={{ gap: 6, marginTop: 12 }}>
            {[
              { id: 'top', lab: 'Top 5', clr: 'var(--success)' },
              { id: 'bottom', lab: 'Below 50%', clr: 'var(--c600)' },
              { id: null, lab: 'Clear', clr: 'var(--n500)' },
            ].map(f => (
              <button key={String(f.id)} onClick={() => setHighlight(f.id)} style={{
                padding: '6px 10px', borderRadius: 16, fontSize: 11, fontWeight: 700,
                background: highlight === f.id ? f.clr : 'var(--n50)',
                color: highlight === f.id ? '#fff' : 'var(--n700)',
                fontFamily: 'var(--mono)', letterSpacing: '.04em',
              }}>{f.lab}</button>
            ))}
          </div>
        </div>

        {/* Matrix */}
        <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 8px', textAlign: 'left', position: 'sticky', left: 0, background: 'var(--n50)', borderBottom: '1px solid var(--n200)', minWidth: 90, fontWeight: 700, color: 'var(--n700)' }}>Student</th>
                  <th style={{ padding: '8px 6px', borderBottom: '1px solid var(--n200)', minWidth: 32, fontWeight: 700, color: 'var(--n500)', fontSize: 9 }}>RNK</th>
                  {cols.map(c => (
                    <th key={c.id} style={{ padding: '6px 4px', minWidth: 50, color: 'var(--n700)', fontWeight: 700, borderBottom: '1px solid var(--n200)' }}>
                      <div style={{ fontSize: 9, color: 'var(--n400)' }}>{c.when}</div>
                      <div style={{ fontSize: 10 }}>{c.title.split(' ')[0]}</div>
                      <div style={{ fontSize: 9, color: 'var(--n400)' }}>/{c.max}</div>
                    </th>
                  ))}
                  <th style={{ padding: '8px 6px', borderBottom: '1px solid var(--n200)', background: 'var(--p50)', color: 'var(--p700)', fontWeight: 800 }}>%</th>
                </tr>
              </thead>
              <tbody>
                {students.map((name, si) => (
                  <tr key={si} style={{ borderBottom: '1px solid var(--n100)', ...rowClass(si) }}>
                    <td style={{ padding: '7px 8px', position: 'sticky', left: 0, background: highlight && (highlight === 'top' && ranks[si] <= 5 ? 'rgba(16,185,129,.06)' : highlight === 'bottom' && totals[si] < 50 ? 'rgba(239,68,68,.06)' : '#fff') || '#fff', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, color: 'var(--n900)' }}>
                      <button onClick={() => nav.push('teachStudentProfile', { id: 's' + (si+1).toString().padStart(2,'0') })} style={{ background: 'transparent', textAlign: 'left', padding: 0 }}>{name.split(' ')[0]} {name.split(' ')[1]?.[0]}.</button>
                    </td>
                    <td style={{ padding: '7px 6px', textAlign: 'center', fontWeight: 700, color: ranks[si] <= 3 ? 'var(--success)' : 'var(--n500)' }}>{ranks[si]}</td>
                    {grid[si].map((v, j) => {
                      const c = cols[j];
                      const pct = v == null ? null : Math.round((v / c.max) * 100);
                      const clr = v == null ? 'var(--n300)' : pct >= 75 ? 'var(--success)' : pct >= 50 ? 'var(--n800)' : 'var(--c600)';
                      return (
                        <td key={j} style={{ padding: '7px 4px', textAlign: 'center', color: clr, fontWeight: v == null ? 500 : 700 }}>
                          {v == null ? '—' : v}
                        </td>
                      );
                    })}
                    <td style={{ padding: '7px 6px', textAlign: 'center', background: 'var(--p50)', color: totals[si] >= 75 ? 'var(--success)' : totals[si] >= 50 ? 'var(--p700)' : 'var(--c600)', fontWeight: 800 }}>{totals[si]}</td>
                  </tr>
                ))}
                <tr style={{ background: 'var(--n50)', borderTop: '2px solid var(--n200)' }}>
                  <td style={{ padding: '8px 8px', position: 'sticky', left: 0, background: 'var(--n50)', fontWeight: 800, color: 'var(--n700)', fontFamily: 'inherit', fontSize: 11 }}>Class avg</td>
                  <td/>
                  {colAvg.map((a, j) => (
                    <td key={j} style={{ padding: '8px 4px', textAlign: 'center', fontWeight: 800, color: 'var(--n700)' }}>{a}%</td>
                  ))}
                  <td style={{ padding: '8px 6px', background: 'var(--p100)', textAlign: 'center', fontWeight: 800, color: 'var(--p700)' }}>{Math.round(totals.reduce((s,x)=>s+x,0)/totals.length)}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        {/* Tips */}
        <div className="card" style={{ padding: 12, marginTop: 12, background: 'var(--info-50)', border: '1px solid rgba(37,99,235,.2)' }}>
          <div className="row" style={{ gap: 10 }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: '#1E40AF', color: '#fff', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="info" size={14}/></div>
            <div style={{ fontSize: 11.5, color: 'var(--n800)', lineHeight: 1.45 }}>Tap any student name to drill in. Mid-term carries 3× weight; tap <b>Compare</b> for side-by-side movement between any two assessments.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. Report card (single student · all subjects)
// ─────────────────────────────────────────────────────────────
function TeacherReportCardScreen({ nav, params }) {
  const id = (params && params.id) || 's01';
  const stu = (window.findRosterStudent && window.findRosterStudent(id)) || (window.ROSTER && window.ROSTER[0]) || { name: 'Aarav Reddy', initial: 'A', clr: '', roll: 1 };

  const subjects = useMemoGB(() => [
    { sub: 'Mathematics',    teacher: 'Mrs. Reddy',  pct: 78, grade: 'A',  remark: 'Strong on linear equations; revise quadratics.' },
    { sub: 'Science',        teacher: 'Mr. Iyer',    pct: 82, grade: 'A',  remark: 'Excellent lab work. Theory needs more practice.' },
    { sub: 'English',        teacher: 'Mrs. Nair',   pct: 71, grade: 'B+', remark: 'Comprehension strong; writing needs structure.' },
    { sub: 'Hindi',          teacher: 'Mr. Bhat',    pct: 64, grade: 'B',  remark: 'Vocabulary improving; grammar needs work.' },
    { sub: 'Social Studies', teacher: 'Mrs. Menon',  pct: 75, grade: 'A',  remark: 'Map work outstanding.' },
    { sub: 'Computer Sci.',  teacher: 'Mr. Raju',    pct: 88, grade: 'A+', remark: 'Top of class. Nominate for tech fest.' },
  ], []);
  const overall = Math.round(subjects.reduce((s, x) => s + x.pct, 0) / subjects.length);
  const attendance = 91;
  const remarks = subjects.filter(s => s.pct < 70).length === 0
    ? 'Consistent performer with strong analytical skills. Encourage participation in inter-school olympiads.'
    : 'Solid overall but Hindi and English written work needs focused practice.';

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

      <div className="app-body" style={{ paddingTop: 4 }}>
        {/* Header card — looks like a report card */}
        <div className="card" style={{ padding: 0, background: '#fff', overflow: 'hidden', marginBottom: 12 }}>
          <div style={{ background: 'var(--p600)', color: '#fff', padding: '14px 16px' }}>
            <div className="row" style={{ gap: 12 }}>
              <div className={`av av-56 ${stu.clr}`} style={{ background: 'rgba(255,255,255,.18)', color: '#fff', fontSize: 22 }}>{stu.initial || stu.name?.[0]}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 17, fontWeight: 800, letterSpacing: '-.01em' }}>{stu.name}</div>
                <div style={{ fontSize: 11, opacity: .85, marginTop: 2, fontFamily: 'var(--mono)', fontWeight: 600 }}>ROLL {stu.roll || 1} · 8-B · DPS HYDERABAD</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 9.5, fontWeight: 700, opacity: .85, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>TERM 2 · 24–25</div>
                <div style={{ fontSize: 26, fontWeight: 800, fontVariantNumeric: 'tabular-nums', letterSpacing: '-.02em', lineHeight: 1, marginTop: 4 }}>{overall}%</div>
              </div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', borderTop: '1px solid var(--n100)' }}>
            {[
              { lab: 'GRADE', val: overall >= 85 ? 'A+' : overall >= 75 ? 'A' : overall >= 60 ? 'B+' : 'B' },
              { lab: 'RANK', val: '4 / 32' },
              { lab: 'ATT', val: attendance + '%' },
            ].map((c, i) => (
              <div key={i} style={{ padding: 12, textAlign: 'center', borderRight: i < 2 ? '1px solid var(--n100)' : 'none' }}>
                <div style={{ fontSize: 9.5, fontWeight: 700, color: 'var(--n500)', fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>{c.lab}</div>
                <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--n900)', fontVariantNumeric: 'tabular-nums', marginTop: 4, lineHeight: 1 }}>{c.val}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Subjects table */}
        <SectionLabel label="Subjects"/>
        <div className="card" style={{ padding: 0, background: '#fff', overflow: 'hidden' }}>
          {subjects.map((s, i) => (
            <div key={s.sub} style={{ padding: 12, borderBottom: i < subjects.length - 1 ? '1px solid var(--n100)' : 'none' }}>
              <div className="spread">
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{s.sub}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 1, fontFamily: 'var(--mono)' }}>{s.teacher}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 16, fontWeight: 800, color: s.pct >= 75 ? 'var(--success)' : s.pct >= 60 ? 'var(--n900)' : 'var(--c600)', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{s.pct}%</div>
                  <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 2, fontFamily: 'var(--mono)' }}>{s.grade}</div>
                </div>
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--n600)', marginTop: 6, lineHeight: 1.45, paddingLeft: 0, borderLeft: '2px solid var(--n100)', paddingLeft: 8 }}>{s.remark}</div>
            </div>
          ))}
        </div>

        {/* Class teacher remark */}
        <SectionLabel label="Class teacher remark" right={<button style={{ fontSize: 11, color: 'var(--p600)', fontWeight: 600 }}>Edit</button>}/>
        <div className="card" style={{ padding: 14, background: '#fff' }}>
          <div style={{ fontSize: 12.5, color: 'var(--n800)', lineHeight: 1.5 }}>{remarks}</div>
          <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--n100)', fontSize: 11, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>— Mrs. Sneha Reddy, Class teacher · 8-B</div>
        </div>

        {/* Action footer */}
        <div className="row" style={{ gap: 8, marginTop: 16 }}>
          <button onClick={() => nav.pop()} className="btn-soft" style={{ flex: 1, height: 46, fontSize: 13, fontWeight: 700 }}>Save draft</button>
          <button onClick={() => nav.push('teachReportPublish')} className="btn-primary" style={{ flex: 2, height: 46, fontSize: 13, fontWeight: 700 }}>Publish to parent →</button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3. Compare two assessments side-by-side
// ─────────────────────────────────────────────────────────────
function TeacherCompareAssessmentsScreen({ nav }) {
  const { students, cols, grid } = GRADEBOOK;
  const [aIdx, setAIdx] = useStateGB(1); // mid-term
  const [bIdx, setBIdx] = useStateGB(0); // linear eq
  const a = cols[aIdx], b = cols[bIdx];

  const rows = students.map((name, si) => {
    const av = grid[si][aIdx];
    const bv = grid[si][bIdx];
    const ap = av == null ? null : Math.round((av / a.max) * 100);
    const bp = bv == null ? null : Math.round((bv / b.max) * 100);
    return { name, ap, bp, delta: (ap != null && bp != null) ? bp - ap : null };
  });
  const movers = [...rows].filter(r => r.delta != null).sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta));
  const improved = movers.filter(r => r.delta > 0).slice(0, 3);
  const regressed = movers.filter(r => r.delta < 0).slice(0, 3);

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

        {/* Picker */}
        <div className="row" style={{ gap: 8, marginBottom: 12 }}>
          {[{ idx: aIdx, set: setAIdx, lab: 'A · Earlier', clr: 'var(--n700)', bg: 'var(--n50)' },
            { idx: bIdx, set: setBIdx, lab: 'B · Later',   clr: 'var(--p700)', bg: 'var(--p50)' }].map((p, i) => (
            <div key={i} style={{ flex: 1, padding: 12, borderRadius: 12, background: p.bg, border: `1px solid ${p.clr === 'var(--p700)' ? 'rgba(79,70,229,.2)' : 'var(--n100)'}` }}>
              <div style={{ fontSize: 9.5, fontWeight: 700, color: p.clr, fontFamily: 'var(--mono)', letterSpacing: '.06em', marginBottom: 4 }}>{p.lab}</div>
              <select value={p.idx} onChange={(e) => p.set(parseInt(e.target.value, 10))} style={{
                width: '100%', padding: 0, border: 'none', background: 'transparent', fontSize: 13, fontWeight: 700, color: 'var(--n900)', fontFamily: 'inherit', outline: 'none',
              }}>
                {cols.map((c, j) => <option key={c.id} value={j}>{c.title}</option>)}
              </select>
              <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 2, fontFamily: 'var(--mono)' }}>{cols[p.idx].when} · /{cols[p.idx].max}</div>
            </div>
          ))}
        </div>

        {/* Movers */}
        <SectionLabel label="Biggest movers"/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 12 }}>
          {[
            { lab: 'IMPROVED', list: improved, clr: 'var(--success)', bg: 'var(--success-50)', sign: '+' },
            { lab: 'REGRESSED', list: regressed, clr: 'var(--c600)', bg: 'var(--c50)', sign: '' },
          ].map(box => (
            <div key={box.lab} className="card" style={{ padding: 12, background: '#fff' }}>
              <div style={{ fontSize: 9.5, fontWeight: 700, color: box.clr, fontFamily: 'var(--mono)', letterSpacing: '.06em', marginBottom: 8 }}>{box.lab}</div>
              {box.list.length === 0 ? (
                <div style={{ fontSize: 11, color: 'var(--n500)' }}>—</div>
              ) : box.list.map((r, i) => (
                <div key={i} className="row" style={{ marginBottom: i < box.list.length - 1 ? 6 : 0, gap: 6 }}>
                  <div style={{ flex: 1, minWidth: 0, fontSize: 11.5, fontWeight: 600, color: 'var(--n800)' }}>{r.name.split(' ')[0]} {r.name.split(' ')[1]?.[0]}.</div>
                  <div style={{ fontSize: 12, fontWeight: 800, color: box.clr, fontFamily: 'var(--mono)' }}>{box.sign}{r.delta}</div>
                </div>
              ))}
            </div>
          ))}
        </div>

        {/* Per-student row chart */}
        <SectionLabel label={`All students · ${a.title.split(' ')[0]} → ${b.title.split(' ')[0]}`}/>
        <div className="card" style={{ padding: 10, background: '#fff' }}>
          {rows.map((r, i) => (
            <div key={i} className="row" style={{ padding: '6px 4px', gap: 10, borderBottom: i < rows.length - 1 ? '1px solid var(--n100)' : 'none' }}>
              <div style={{ width: 86, fontSize: 11, fontWeight: 600, color: 'var(--n800)', flexShrink: 0 }}>{r.name.split(' ')[0]} {r.name.split(' ')[1]?.[0]}.</div>
              <div style={{ flex: 1, position: 'relative', height: 18 }}>
                {r.ap != null && (
                  <div style={{ position: 'absolute', left: `${r.ap}%`, top: 4, transform: 'translateX(-50%)', width: 10, height: 10, borderRadius: '50%', background: 'var(--n300)' }}/>
                )}
                {r.bp != null && (
                  <div style={{ position: 'absolute', left: `${r.bp}%`, top: 4, transform: 'translateX(-50%)', width: 10, height: 10, borderRadius: '50%', background: 'var(--p600)', boxShadow: '0 0 0 2px #fff' }}/>
                )}
                {r.ap != null && r.bp != null && (
                  <div style={{ position: 'absolute', left: `${Math.min(r.ap, r.bp)}%`, top: 8, height: 2, width: `${Math.abs(r.bp - r.ap)}%`, background: r.delta > 0 ? 'var(--success)' : 'var(--c500)' }}/>
                )}
              </div>
              <div style={{ width: 38, textAlign: 'right', fontSize: 11.5, fontWeight: 700, fontFamily: 'var(--mono)', color: r.delta == null ? 'var(--n400)' : r.delta > 0 ? 'var(--success)' : r.delta < 0 ? 'var(--c600)' : 'var(--n500)' }}>
                {r.delta == null ? '—' : (r.delta > 0 ? '+' : '') + r.delta}
              </div>
            </div>
          ))}
        </div>

        <div className="row" style={{ marginTop: 12, gap: 10, fontSize: 10.5, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>
          <div className="row" style={{ gap: 4 }}><div style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--n300)' }}/><span>{a.title.split(' ')[0]}</span></div>
          <div className="row" style={{ gap: 4 }}><div style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--p600)' }}/><span>{b.title.split(' ')[0]}</span></div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  GRADEBOOK,
  TeacherGradeBookScreen,
  TeacherReportCardScreen,
  TeacherCompareAssessmentsScreen,
});
