/* Admin → Gradebook: teacher grade entry + behavior/mood feedback.
   Feeds the parent app's Grades and Safety & Wellbeing screens. */
function GradebookScreen() {
  const MOODS = {
    happy: { label:'Happy', icon:'smile', bg:'var(--success-100)', fg:'var(--success-600)' },
    calm:  { label:'Calm',  icon:'meh',   bg:'var(--info-100)',    fg:'var(--info-500)' },
    tired: { label:'Tired', icon:'cloud', bg:'var(--warning-100)', fg:'var(--warning-600)' },
    upset: { label:'Upset', icon:'frown', bg:'var(--danger-100)',  fg:'var(--danger-600)' },
  };
  const [rows, setRows] = React.useState([
    { n:'EJ Hatten',     id:'KMS-1042', c:'green', pct:91, mood:'happy', fb:null },
    { n:'James Walker',  id:'KMS-0911', c:'navy',  pct:84, mood:'calm',  fb:null },
    { n:'Sophia Perez',  id:'KMS-1188', c:'gold',  pct:96, mood:'happy', fb:null },
    { n:'Liam Carter',   id:'KMS-0733', c:'blue',  pct:78, mood:'tired', fb:null },
    { n:'Ava Mitchell',  id:'KMS-1276', c:'red',   pct:88, mood:'calm',  fb:null },
    { n:'Noah Bennett',  id:'KMS-1305', c:'cyan',  pct:72, mood:'upset', fb:null },
  ]);
  const letter = (p) => p>=93?'A':p>=90?'A-':p>=87?'B+':p>=83?'B':p>=80?'B-':p>=77?'C+':p>=73?'C':p>=70?'C-':'D';
  const gColor = (p) => p>=90?'var(--success-500)':p>=80?'var(--blue-500)':p>=70?'var(--warning-600)':'var(--danger-500)';
  const setPct = (i,v) => setRows(rs => rs.map((r,j)=> j===i ? { ...r, pct: Math.max(0, Math.min(100, parseInt(v||0))) } : r));
  const cycleMood = (i) => {
    const order = ['happy','calm','tired','upset'];
    setRows(rs => rs.map((r,j)=> j===i ? { ...r, mood: order[(order.indexOf(r.mood)+1)%order.length] } : r));
  };
  const feedback = (i, kind) => {
    setRows(rs => rs.map((r,j)=> j===i ? { ...r, fb:kind } : r));
    const r = rows[i];
    jlToast((kind==='pos'?'Praise':'Note') + ' sent to ' + r.n + '\u2019s parent', { icon: kind==='pos'?'thumbs-up':'flag', color: kind==='pos'?'#1F9D57':'#F0B540' });
  };
  const classAvg = Math.round(rows.reduce((s,r)=>s+r.pct,0)/rows.length);
  const honor = rows.filter(r=>r.pct>=90).length;
  const atRisk = rows.filter(r=>r.pct<75).length;
  const moodCounts = ['happy','calm','tired','upset'].map(m => ({ m, n: rows.filter(r=>r.mood===m).length }));

  return (
    <div style={{ padding:'22px 28px 40px', height:'100%', overflowY:'auto', boxSizing:'border-box' }}>
      {/* toolbar */}
      <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:16 }}>
        <select style={gbSel}><option>Period 3 · Mathematics · Grade 6</option><option>Period 1 · Mathematics · Grade 6</option><option>Period 5 · Pre-Algebra · Grade 7</option></select>
        <select style={{ ...gbSel, width:170 }}><option>Quarter 4</option><option>Quarter 3</option><option>Full Year</option></select>
        <button onClick={()=>jlToast('New assignment added to gradebook', { icon:'file-plus' })} style={gbBtnGhost}><Icon name="file-plus" size={16} color="var(--gray-600)" />New Assignment</button>
        <button onClick={()=>jlToast('Grades posted · parents notified', { icon:'send-horizontal' })} style={{ ...gbBtnGold, marginLeft:'auto' }}><Icon name="send-horizontal" size={16} color="var(--on-gold)" />Post Grades</button>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1.55fr 1fr', gap:16 }}>
        {/* gradebook table */}
        <Panel title="Gradebook" action={<Pill bg="var(--blue-100)" fg="var(--blue-600)">{rows.length} students</Pill>} pad={false}>
          <div style={{ display:'grid', gridTemplateColumns:'1.7fr .8fr .7fr 1fr 1.3fr', padding:'11px 18px', background:'var(--gray-50)', fontSize:11, fontWeight:800, letterSpacing:'.05em', textTransform:'uppercase', color:'var(--gray-500)' }}>
            <span>Student</span><span>Grade %</span><span>Letter</span><span>Mood</span><span style={{ textAlign:'right' }}>Quick Feedback</span>
          </div>
          {rows.map((r,i) => {
            const mood = MOODS[r.mood];
            return (
              <div key={r.id} style={{ display:'grid', gridTemplateColumns:'1.7fr .8fr .7fr 1fr 1.3fr', alignItems:'center', padding:'10px 18px', borderTop:'1px solid var(--gray-100)', fontSize:13.5 }}>
                <span style={{ display:'flex', alignItems:'center', gap:10, minWidth:0 }}>
                  <Avatar initials={r.n.split(' ').map(w=>w[0]).join('')} color={r.c} size={32} />
                  <span style={{ minWidth:0 }}>
                    <span style={{ display:'block', fontWeight:700, color:'var(--ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{r.n}</span>
                    <span style={{ fontSize:11.5, color:'var(--gray-400)', fontFamily:'var(--font-mono)' }}>{r.id}</span>
                  </span>
                </span>
                <span>
                  <input value={r.pct} onChange={e=>setPct(i, e.target.value)} type="number" style={{ width:54, border:'1px solid var(--gray-200)', borderRadius:8, padding:'7px 8px', fontSize:13.5, fontFamily:'var(--font-mono)', fontWeight:700, color:'var(--ink)', outline:'none', textAlign:'center' }} />
                </span>
                <span style={{ fontWeight:800, color:gColor(r.pct), fontFamily:'var(--font-mono)' }}>{letter(r.pct)}</span>
                <span>
                  <button onClick={()=>cycleMood(i)} title="Tap to cycle" style={{ display:'inline-flex', alignItems:'center', gap:6, background:mood.bg, color:mood.fg, border:0, borderRadius:'999px', padding:'5px 11px', fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'var(--font-sans)' }}>
                    <Icon name={mood.icon} size={14} color={mood.fg} />{mood.label}
                  </button>
                </span>
                <span style={{ justifySelf:'end', display:'flex', gap:7 }}>
                  <button onClick={()=>feedback(i,'pos')} title="Send praise" style={{ ...gbIcon, background: r.fb==='pos'?'var(--success-500)':'#fff', borderColor: r.fb==='pos'?'var(--success-500)':'var(--gray-200)' }}><Icon name="thumbs-up" size={15} color={r.fb==='pos'?'#fff':'var(--success-500)'} /></button>
                  <button onClick={()=>feedback(i,'watch')} title="Flag for attention" style={{ ...gbIcon, background: r.fb==='watch'?'var(--warning-500)':'#fff', borderColor: r.fb==='watch'?'var(--warning-500)':'var(--gray-200)' }}><Icon name="flag" size={15} color={r.fb==='watch'?'#fff':'var(--warning-600)'} /></button>
                  <button onClick={()=>jlToast('Message '+r.n+'\u2019s parent', { icon:'message-circle' })} style={{ ...gbIcon, background:'#fff', borderColor:'var(--gray-200)' }}><Icon name="message-circle" size={15} color="var(--blue-500)" /></button>
                </span>
              </div>
            );
          })}
        </Panel>

        {/* right rail */}
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          <Panel title="Class Summary">
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:10, padding:'6px 0 4px' }}>
              {[
                { n:classAvg+'%', l:'Class avg', c:gColor(classAvg) },
                { n:honor, l:'Honor roll', c:'var(--success-500)' },
                { n:atRisk, l:'At risk', c:'var(--danger-500)' },
              ].map((s,i)=>(
                <div key={i} style={{ background:'var(--gray-50)', borderRadius:12, padding:'13px 8px', textAlign:'center' }}>
                  <div style={{ fontSize:22, fontWeight:800, color:s.c, fontFamily:'var(--font-mono)' }}>{s.n}</div>
                  <div style={{ fontSize:11.5, fontWeight:600, color:'var(--gray-500)', marginTop:2 }}>{s.l}</div>
                </div>
              ))}
            </div>
          </Panel>

          <Panel title="Wellbeing Today">
            <div style={{ padding:'6px 0 2px', display:'flex', flexDirection:'column', gap:10 }}>
              {moodCounts.map(({m,n}) => {
                const mood = MOODS[m];
                const pct = Math.round((n/rows.length)*100);
                return (
                  <div key={m}>
                    <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:5 }}>
                      <Icon name={mood.icon} size={15} color={mood.fg} />
                      <span style={{ fontSize:13, fontWeight:700, color:'var(--ink)', flex:1 }}>{mood.label}</span>
                      <span style={{ fontSize:12.5, color:'var(--gray-500)', fontWeight:700 }}>{n}</span>
                    </div>
                    <div style={{ height:7, borderRadius:'999px', background:'var(--gray-100)', overflow:'hidden' }}>
                      <div style={{ width:pct+'%', height:'100%', borderRadius:'999px', background:mood.fg }} />
                    </div>
                  </div>
                );
              })}
              <div style={{ display:'flex', alignItems:'flex-start', gap:9, marginTop:4, background:'var(--info-100)', borderRadius:10, padding:'10px 12px' }}>
                <Icon name="sparkles" size={15} color="var(--info-500)" style={{ marginTop:1 }} />
                <span style={{ fontSize:12, color:'var(--info-500)', lineHeight:1.45 }}>Noah Bennett has logged “upset” 3 days running — consider a counselor check-in.</span>
              </div>
            </div>
          </Panel>
        </div>
      </div>
    </div>
  );
}
const gbSel = { border:'1px solid var(--gray-200)', borderRadius:10, padding:'10px 12px', fontSize:13.5, fontFamily:'var(--font-sans)', color:'var(--ink)', background:'#fff', outline:'none', fontWeight:600 };
const gbBtnGhost = { display:'flex', alignItems:'center', gap:7, background:'#fff', color:'var(--gray-700)', border:'1px solid var(--gray-200)', borderRadius:10, padding:'10px 14px', fontWeight:700, fontSize:13.5, cursor:'pointer', fontFamily:'var(--font-sans)' };
const gbBtnGold = { display:'flex', alignItems:'center', gap:7, background:'var(--gold-400)', color:'var(--on-gold)', border:0, borderRadius:10, padding:'10px 16px', fontWeight:700, fontSize:13.5, cursor:'pointer', fontFamily:'var(--font-sans)', boxShadow:'var(--shadow-gold)' };
const gbIcon = { width:34, height:34, borderRadius:9, border:'1px solid var(--gray-200)', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', background:'#fff' };
Object.assign(window, { GradebookScreen });
