/* Grades — real-time grade sync by subject */
function GradesScreen({ onNav, onBack }) {
  const baseSubjects = [
    { subj:'Mathematics', teacher:'Mr. Allen',   icon:'calculator',   tint:'var(--blue-100)',    ic:'var(--blue-500)',    grade:'A-', pct:91, trend:'up' },
    { subj:'Science',      teacher:'Ms. Rivera',  icon:'flask-conical',tint:'var(--gold-100)',    ic:'var(--gold-600)',    grade:'B+', pct:88, trend:'up' },
    { subj:'English (ELA)',teacher:'Mrs. Johnson',icon:'book-open',    tint:'var(--success-100)', ic:'var(--success-500)', grade:'B',  pct:84, trend:'down' },
    { subj:'Social Studies',teacher:'Mr. Diaz',   icon:'globe',        tint:'var(--info-100)',    ic:'var(--info-500)',    grade:'A',  pct:95, trend:'flat' },
    { subj:'Art',          teacher:'Ms. Park',    icon:'palette',      tint:'var(--danger-100)',  ic:'var(--danger-500)',  grade:'A',  pct:97, trend:'flat' },
  ];
  const letterFor = (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 [live, setLive] = React.useState({});
  React.useEffect(() => {
    const read = () => { try { const all = JSON.parse(localStorage.getItem('jl_grades') || '{}'); setLive(all[jlChild().id] || {}); } catch(e){} };
    read();
    const onStore = (e) => { if (e.key === 'jl_grades') read(); };
    window.addEventListener('storage', onStore);
    const iv = setInterval(read, 1500);
    return () => { window.removeEventListener('storage', onStore); clearInterval(iv); };
  }, []);
  const subjects = baseSubjects.map(s => { const p = live[s.subj]; return p!=null ? { ...s, pct:p, grade:letterFor(p) } : s; });
  const es = window.JL_LANG === 'es';
  const SUBJ_ES = { 'Mathematics':'Matemáticas', 'Science':'Ciencias', 'English (ELA)':'Inglés (ELA)', 'Social Studies':'Estudios Sociales', 'Art':'Arte', 'Math':'Mate', 'ELA':'ELA' };
  const sName = (s) => es ? (SUBJ_ES[s] || s) : s;
  const recent = [
    { title:'Fractions Quiz', subj:'Math', score:'18/20', grade:'A-', bg:'var(--success-100)', fg:'var(--success-600)', when:'Graded today' },
    { title:'Reading Response', subj:'ELA', score:'C+', grade:'C+', bg:'var(--warning-100)', fg:'var(--warning-600)', when:'Graded yesterday' },
    { title:'Lab Report', subj:'Science', score:'27/30', grade:'B+', bg:'var(--success-100)', fg:'var(--success-600)', when:'Graded May 28' },
  ];
  const gradeColor = (g) => g.startsWith('A') ? 'var(--success-500)' : g.startsWith('B') ? 'var(--blue-500)' : g.startsWith('C') ? 'var(--warning-600)' : 'var(--danger-500)';
  const trendIcon = { up:'trending-up', down:'trending-down', flat:'minus' };
  const trendColor = { up:'var(--success-500)', down:'var(--danger-500)', flat:'var(--gray-400)' };

  return (
    <div style={{ background:'var(--gray-50)', minHeight:'100%' }}>
      <PushBar titleKey="t_grades" onBack={onBack} />
      <div style={{ padding:'14px 18px 40px' }}>

        {/* GPA hero */}
        <div style={{ background:'var(--color-grad-hero)', borderRadius:18, padding:'18px', color:'#fff', boxShadow:'var(--shadow-navy)' }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <div>
              <div style={{ fontSize:10, fontWeight:800, letterSpacing:'.1em', color:'rgba(255,255,255,.7)' }}>OVERALL GPA · QUARTER 4</div>
              <div style={{ fontSize:40, fontWeight:800, letterSpacing:'-.02em', lineHeight:1, marginTop:6, fontFamily:'var(--font-mono)' }}>{jlChild().gpa}</div>
              <Pill bg="rgba(255,255,255,.18)" fg="#fff" style={{ marginTop:10 }}><Icon name="trending-up" size={13} color="var(--success-tint)" />{jlChild().gpaTrend}</Pill>
            </div>
            <div style={{ textAlign:'right' }}>
              <div style={{ fontSize:10, fontWeight:800, letterSpacing:'.1em', color:'rgba(255,255,255,.7)' }}>HONOR ROLL</div>
              <span style={{ display:'inline-flex', width:54, height:54, borderRadius:14, background:'rgba(255,255,255,.16)', alignItems:'center', justifyContent:'center', marginTop:8 }}>
                <Icon name="medal" size={28} color="var(--gold-400)" />
              </span>
            </div>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:7, marginTop:14, fontSize:11.5, color:'rgba(255,255,255,.72)' }}>
            <span className="jl-pulse" style={{ width:7, height:7, borderRadius:'999px', background:'var(--success-tint)' }} />
            {es ? 'Sincronizado · actualizado hace 2 min' : 'Live sync · updated 2 min ago from PowerSchool'}
          </div>
        </div>

        {/* by subject */}
        <SectionLabel>{jlT('l_by_subject')}</SectionLabel>
        <div style={{ display:'flex', flexDirection:'column', gap:11 }}>
          {subjects.map((s,i) => (
            <button key={i} onClick={()=>jlToast('Opening ' + s.subj + ' breakdown…', { icon:'book-open' })} style={{ width:'100%', display:'flex', alignItems:'center', gap:13, background:'#fff', border:'1px solid var(--gray-200)', borderRadius:14, padding:'14px 15px', boxShadow:'var(--shadow-sm)', cursor:'pointer', fontFamily:'var(--font-sans)', textAlign:'left' }}>
              <span style={{ width:42, height:42, borderRadius:11, background:s.tint, display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}>
                <Icon name={s.icon} size={20} color={s.ic} />
              </span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:15, fontWeight:700, color:'var(--ink)' }}>{sName(s.subj)}</div>
                <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{s.teacher} · {s.pct}%</div>
              </div>
              <Icon name={trendIcon[s.trend]} size={16} color={trendColor[s.trend]} />
              <div style={{ fontSize:22, fontWeight:800, color:gradeColor(s.grade), minWidth:38, textAlign:'right', fontFamily:'var(--font-mono)' }}>{s.grade}</div>
            </button>
          ))}
        </div>

        {/* recently graded */}
        <SectionLabel action={<span onClick={()=>onNav('activities')} style={{ fontSize:12, fontWeight:700, color:'var(--blue-500)', cursor:'pointer' }}>{es?'Tareas':'Assignments'}</span>}>{es?'Calificado recientemente':'Recently Graded'}</SectionLabel>
        <div style={cardWrap}>
          {recent.map((r,i) => (
            <React.Fragment key={i}>
              {i>0 && <Divider />}
              <div style={{ display:'flex', alignItems:'center', gap:12, padding:'13px 14px' }}>
                <span style={{ width:38, height:38, borderRadius:10, background:r.bg, display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto', fontSize:13.5, fontWeight:800, color:r.fg, fontFamily:'var(--font-mono)' }}>{r.grade}</span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:14.5, fontWeight:700, color:'var(--ink)' }}>{r.title}</div>
                  <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{sName(r.subj)} · {es ? (r.when==='Graded today'?'Calificado hoy':r.when==='Graded yesterday'?'Calificado ayer':r.when.replace('Graded','Calificado')) : r.when}</div>
                </div>
                <div style={{ fontSize:14, fontWeight:700, color:'var(--gray-600)', fontFamily:'var(--font-mono)' }}>{r.score}</div>
              </div>
            </React.Fragment>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { GradesScreen });
