const { useState: useStateV, useMemo: useMemoV, useEffect: useEffectV } = React;

/* ============================================================
   DASHBOARD VIEW
============================================================ */
function DashboardView() {
  return (
    <>
      <Hero/>
      <div className="dash-row" style={{ display:'grid', gridTemplateColumns:'1.35fr 1fr', gap:18 }}>
        <Schedule/>
        <Announcements/>
      </div>
      <div className="dash-row" style={{ display:'grid', gridTemplateColumns:'1.35fr 1fr', gap:18 }}>
        <Files/>
        <Activity/>
      </div>
      <NewsBoard/>
      <ContactFooter/>
    </>
  );
}

/* ============================================================
   TIMETABLE VIEW
============================================================ */
function TimetableView() {
  return (
    <>
      <PageHeader
        eyebrow="Schedule"
        title="Timetable"
        lead="All classes, office hours and exam dates in one place. Filter by type or switch to the weekly view."
        action={
          <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
            <button style={btnGhost}>Export iCal</button>
            <button style={btnPrimary}>Subscribe to calendar <I.arrow s={12}/></button>
          </div>
        }
      />
      <WeekGrid/>
      <Schedule initialTab="week"/>
    </>
  );
}

function WeekGrid() {
  const days = ['Mon','Tue','Wed','Thu','Fri'];
  const hours = ['08','09','10','11','12','13','14','15','16','17','18'];
  const slots = [
    { day:1, h:8, span:1.5, code:'ELEC-DB', name:'Electronics Lab', type:'lab', tone:'oklch(0.94 0.05 240)', stroke:'oklch(0.5 0.12 240)' },
    { day:3, h:10.25, span:1.75, code:'STAT-DC', name:'Math. Statistics — lecture', type:'lecture', tone:'oklch(0.94 0.05 25)', stroke:'oklch(0.5 0.15 25)' },
    { day:3, h:12.25, span:1.75, code:'STAT-DC', name:'Math. Statistics — lab', type:'lab', tone:'oklch(0.93 0.04 145)', stroke:'oklch(0.4 0.1 145)' },
    { day:0, h:11.75, span:1.5, code:'PY-2', name:'Python — Data Mining', type:'lab', tone:'oklch(0.93 0.04 145)', stroke:'oklch(0.4 0.1 145)' },
    { day:4, h:9, span:1.5, code:'OR-DC', name:'Operations Research', type:'lecture', tone:'oklch(0.94 0.05 25)', stroke:'oklch(0.5 0.15 25)' },
    { day:1, h:13.5, span:1.5, code:'DIP-DB', name:'Diploma project', type:'project', tone:'oklch(0.94 0.04 290)', stroke:'oklch(0.45 0.12 290)' },
  ];
  return (
    <Card>
      <SectionLabel
        icon={<I.cal s={13}/>}
        action={<span className="mono" style={{ fontSize:11.5, color:'var(--muted)' }}>Even week · May 25 — 31</span>}
      >Weekly view</SectionLabel>
      <div className="scroll-x">
        <div style={{ minWidth:680, position:'relative' }}>
          <div style={{
            display:'grid', gridTemplateColumns:'48px repeat(5, 1fr)', gridAutoRows:'46px',
            border:'1px solid var(--line)', borderRadius:11, overflow:'hidden', background:'#FFF'
          }}>
            <div style={{ borderRight:'1px solid var(--line)', borderBottom:'1px solid var(--line)' }}></div>
            {days.map((d, i) => (
              <div key={i} style={{
                padding:'10px 12px', borderRight: i<4?'1px solid var(--line)':'none',
                borderBottom:'1px solid var(--line)', fontSize:12, fontWeight:600, color:'var(--ink)',
                background:'var(--surface-2)'
              }}>
                {d} <span style={{ color:'var(--muted)', fontWeight:400, marginLeft:6 }} className="mono">{25+i}</span>
              </div>
            ))}
            {hours.map((h, hi) => (
              <React.Fragment key={hi}>
                <div style={{ borderRight:'1px solid var(--line)', borderBottom: hi<hours.length-1?'1px solid var(--line-2)':'none', padding:'4px 6px', fontSize:10.5, color:'var(--muted)' }} className="mono">{h}:00</div>
                {days.map((_, di) => (
                  <div key={di} style={{
                    borderRight: di<4?'1px solid var(--line-2)':'none',
                    borderBottom: hi<hours.length-1?'1px solid var(--line-2)':'none',
                    position:'relative'
                  }}></div>
                ))}
              </React.Fragment>
            ))}
          </div>

          {/* overlay blocks */}
          <div style={{ position:'absolute', top:0, left:0, right:0, bottom:0, pointerEvents:'none' }}>
            <div style={{ display:'grid', gridTemplateColumns:'48px repeat(5,1fr)', height:'100%', position:'relative' }}>
              <div></div>
              {[0,1,2,3,4].map(di => (
                <div key={di} style={{ position:'relative' }}>
                  {slots.filter(s=>s.day===di).map((s, j) => (
                    <div key={j} style={{
                      position:'absolute',
                      top: 41 + (s.h-8)*46 + 3,
                      left: 4, right:4,
                      height: s.span*46 - 6,
                      background:s.tone,
                      border:`1px solid ${s.stroke}`,
                      borderRadius:8,
                      padding:'6px 9px',
                      fontSize:11.5,
                      color:s.stroke,
                      pointerEvents:'auto',
                      cursor:'pointer',
                      overflow:'hidden'
                    }}>
                      <div style={{ fontWeight:600, fontSize:12, color:'var(--ink)' }}>{s.name}</div>
                      <div style={{ marginTop:2 }} className="mono">{s.code} · {s.type}</div>
                    </div>
                  ))}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Card>
  );
}

/* ============================================================
   GRADES VIEW
============================================================ */
const gradesData = [
  { code:'STAT-DC', name:'Mathematical Statistics', ects:5, grade:null, status:'in progress', teacher:'Dr. K. Miller' },
  { code:'PY-2',    name:'Python — Data Mining', ects:4, grade:null, status:'in progress', teacher:'Dr. M. Collins' },
  { code:'ELEC-DB', name:'Electronics Laboratory', ects:3, grade:null, status:'in progress', teacher:'J. Sawyer, MSc' },
  { code:'OR-DC',   name:'Operations Research', ects:4, grade:null, status:'in progress', teacher:'Dr. B. Jenkins' },
  { code:'NET-DC',  name:'Computer Networks', ects:4, grade:null, status:'in progress', teacher:'Dr. R. Hayes' },
  { code:'DIP-DB',  name:'Diploma Project Seminar', ects:2, grade:null, status:'in progress', teacher:'Prof. A. Novak' },
  { code:'SE-LE',   name:'Software Engineering', ects:5, grade:4.5, status:'completed', teacher:'Dr. K. Adams' },
  { code:'DB-2',    name:'Databases II', ects:5, grade:5.0, status:'completed', teacher:'Dr. P. Winters' },
  { code:'ALG-DC',  name:'Algorithms & Data Structures', ects:6, grade:4.0, status:'completed', teacher:'Prof. T. Brooks' },
  { code:'NUM-DC',  name:'Numerical Methods', ects:3, grade:4.5, status:'completed', teacher:'Dr. E. Fontaine' },
  { code:'OS-LE',   name:'Operating Systems', ects:5, grade:3.5, status:'completed', teacher:'Prof. A. Novak' },
];

function GradesView() {
  const completed = gradesData.filter(g=>g.status==='completed');
  const avg = completed.reduce((s,g)=>s+g.grade*g.ects,0) / completed.reduce((s,g)=>s+g.ects,0);
  const ectsDone = completed.reduce((s,g)=>s+g.ects,0);
  return (
    <>
      <PageHeader
        eyebrow="Grades"
        title="Semester 6 · spring 2025/2026"
        lead="Current and completed courses. The weighted average includes final grades only."
      />
      <div className="stats-grid" style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:18 }}>
        <Stat label="Weighted average" big={avg.toFixed(2)} sub={`from ${completed.length} grades`}/>
        <Stat label="ECTS completed" big={ectsDone} sub={`/ ${gradesData.reduce((s,g)=>s+g.ects,0)} this semester`}/>
        <Stat label="In progress" big={gradesData.length-completed.length} sub="courses"/>
        <Stat label="Highest grade" big="5.0" sub="Databases II"/>
      </div>

      <Card>
        <SectionLabel icon={<I.list s={13}/>}>Course list</SectionLabel>
        <div className="scroll-x">
          <div style={{ minWidth:640, borderTop:'1px solid var(--line-2)' }}>
            <div style={{
              display:'grid', gridTemplateColumns:'90px 1fr 70px 70px 120px',
              gap:14, padding:'10px 6px', fontSize:11, fontWeight:600,
              color:'var(--muted)', letterSpacing:'.08em', textTransform:'uppercase',
              borderBottom:'1px solid var(--line)'
            }}>
              <span>Code</span><span>Course</span><span>ECTS</span><span>Grade</span><span>Status</span>
            </div>
            {gradesData.map((g, i) => (
              <div key={i} style={{
                display:'grid', gridTemplateColumns:'90px 1fr 70px 70px 120px',
                gap:14, padding:'12px 6px', alignItems:'center',
                borderBottom:'1px solid var(--line-2)'
              }}>
                <span className="mono" style={{ fontSize:11.5, color:'var(--muted)' }}>{g.code}</span>
                <div>
                  <div style={{ fontWeight:550, fontSize:14 }}>{g.name}</div>
                  <div style={{ fontSize:12, color:'var(--muted)' }}>{g.teacher}</div>
                </div>
                <span style={{ fontWeight:500 }}>{g.ects}</span>
                <span className="serif" style={{ fontSize:20, color: g.grade ? 'var(--ink)' : 'var(--muted)' }}>{g.grade ?? '—'}</span>
                <Pill tone={g.grade ? 'accent' : 'neutral'} size="xs">{g.status}</Pill>
              </div>
            ))}
          </div>
        </div>
      </Card>
    </>
  );
}

function Stat({ label, big, sub }) {
  return (
    <Card style={{ padding:'18px 20px' }}>
      <div style={{ fontSize:11, fontWeight:600, color:'var(--muted)', letterSpacing:'.14em', textTransform:'uppercase' }}>{label}</div>
      <div className="serif" style={{ fontSize:38, lineHeight:1.1, marginTop:4 }}>{big}</div>
      <div style={{ fontSize:12, color:'var(--muted)', marginTop:2 }}>{sub}</div>
    </Card>
  );
}

/* ============================================================
   COURSES VIEW
============================================================ */
function CoursesView() {
  const courses = gradesData.filter(g=>g.status==='in progress').map((g,i) => ({
    ...g,
    progress: [62, 48, 70, 34, 55, 40][i] || 50,
    next: ['lab — Tuesday','lecture — Wednesday','lab — Friday','lecture — Thursday','lab — Monday','seminar — Friday'][i] || '—'
  }));
  return (
    <>
      <PageHeader
        eyebrow="Courses"
        title="Active courses"
        lead="Course cards for the current semester. Each one links to the syllabus, materials and announcements."
      />
      <div className="courses-grid" style={{ display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:18 }}>
        {courses.map((c, i) => (
          <Card key={i} pad={0} style={{ overflow:'hidden', display:'flex', flexDirection:'column' }}>
            <div style={{ padding:'20px 22px 12px' }}>
              <div style={{ display:'flex', alignItems:'center', gap:8, fontSize:11, color:'var(--muted)' }}>
                <span className="mono">{c.code}</span><span>·</span><span>{c.ects} ECTS</span>
              </div>
              <h3 className="serif" style={{ margin:'4px 0 6px', fontSize:24, lineHeight:1.15 }}>{c.name}</h3>
              <div style={{ fontSize:12.5, color:'var(--muted)' }}>{c.teacher}</div>
            </div>
            <div style={{ padding:'0 22px 16px' }}>
              <div style={{ display:'flex', justifyContent:'space-between', fontSize:11, color:'var(--muted)', marginBottom:6 }}>
                <span>Semester progress</span><span>{c.progress}%</span>
              </div>
              <div style={{ height:6, background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:99, overflow:'hidden' }}>
                <div style={{ height:'100%', width:`${c.progress}%`, background:'linear-gradient(90deg, oklch(0.5 0.18 25), oklch(0.4 0.14 25))' }}></div>
              </div>
            </div>
            <div style={{ padding:'12px 22px', borderTop:'1px solid var(--line-2)', background:'var(--surface-2)', display:'flex', alignItems:'center', justifyContent:'space-between', flexWrap:'wrap', gap:8 }}>
              <div style={{ fontSize:12.5, color:'var(--ink-2)' }}><strong>Next:</strong> {c.next}</div>
              <div style={{ display:'flex', gap:4 }}>
                <button style={{ ...btnGhost, padding:'6px 10px', fontSize:12 }}>Syllabus</button>
                <button style={{ ...btnGhost, padding:'6px 10px', fontSize:12 }}>Materials</button>
              </div>
            </div>
          </Card>
        ))}
      </div>
    </>
  );
}

/* ============================================================
   FINANCE VIEW
============================================================ */
function FinanceView() {
  const tx = [
    { date:'May 14', label:'Tuition · spring semester — installment IV', amount:-720, status:'paid' },
    { date:'May 05', label:'Student ID — renewal', amount:-22, status:'paid' },
    { date:'Apr 14', label:'Tuition · spring semester — installment III', amount:-720, status:'paid' },
    { date:'Apr 02', label:'Merit scholarship', amount:1100, status:'received' },
    { date:'Mar 14', label:'Tuition · spring semester — installment II', amount:-720, status:'paid' },
    { date:'Feb 14', label:'Tuition · spring semester — installment I', amount:-720, status:'paid' },
  ];
  return (
    <>
      <PageHeader
        eyebrow="Finance"
        title="Billing account"
        lead="Balance, tuition installments and transaction history. Your personal account number is shown below."
        action={<button style={btnPrimary}>Pay now <I.arrow s={12}/></button>}
      />
      <div className="two-col" style={{ display:'grid', gridTemplateColumns:'1.2fr 1fr', gap:18 }}>
        <Card>
          <SectionLabel>Balance due</SectionLabel>
          <div className="serif" style={{ fontSize:'clamp(44px, 6vw, 64px)', lineHeight:1, letterSpacing:'-.02em' }}>720.00 <span style={{ color:'var(--muted)', fontSize:'0.5em' }}>EUR</span></div>
          <div style={{ marginTop:10, color:'var(--muted)', fontSize:13.5 }}>due · installment V <span className="mono">June 14</span></div>
          <div style={{ marginTop:16, padding:'12px 14px', background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:11 }}>
            <div style={{ fontSize:11, color:'var(--muted)', letterSpacing:'.1em', textTransform:'uppercase' }}>Personal account number (IBAN)</div>
            <div className="mono" style={{ fontSize:13.5, marginTop:4, color:'var(--ink)', wordBreak:'break-all' }}>EU00 0000 1111 2222 3333 4444</div>
          </div>
        </Card>
        <Card>
          <SectionLabel>Semester payment progress</SectionLabel>
          {[
            ['Inst. I', 720, 720],
            ['Inst. II', 720, 720],
            ['Inst. III', 720, 720],
            ['Inst. IV', 720, 720],
            ['Inst. V', 720, 0],
          ].map(([label, total, paid], i) => (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'64px 1fr 80px', alignItems:'center', gap:14, padding:'8px 0', borderTop: i===0?'none':'1px solid var(--line-2)' }}>
              <span style={{ fontSize:13, fontWeight:500 }}>{label}</span>
              <div style={{ height:6, background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:99 }}>
                <div style={{ height:'100%', width: `${(paid/total)*100}%`, background: paid===total ? 'var(--green)' : 'var(--accent)', borderRadius:99 }}></div>
              </div>
              <span className="mono" style={{ fontSize:12, color: paid===total?'var(--green)':'var(--accent-ink)', textAlign:'right' }}>
                {paid===total ? 'paid' : `${total} EUR`}
              </span>
            </div>
          ))}
        </Card>
      </div>
      <Card>
        <SectionLabel icon={<I.cash s={13}/>}>Transaction history</SectionLabel>
        <div className="scroll-x">
          <div style={{ minWidth:560 }}>
            {tx.map((t, i) => (
              <div key={i} style={{ display:'grid', gridTemplateColumns:'70px 1fr auto 110px', gap:14, alignItems:'center', padding:'12px 4px', borderTop: i===0?'none':'1px solid var(--line-2)' }}>
                <span className="mono" style={{ fontSize:11.5, color:'var(--muted)' }}>{t.date}</span>
                <span style={{ fontSize:13.5, fontWeight:500 }}>{t.label}</span>
                <span className="mono" style={{ fontSize:13.5, fontWeight:600, color: t.amount>0 ? 'var(--green)' : 'var(--ink)' }}>
                  {t.amount>0?'+':''}{t.amount.toFixed(2)} EUR
                </span>
                <Pill tone={t.amount>0?'accent':'neutral'} size="xs">{t.status}</Pill>
              </div>
            ))}
          </div>
        </div>
      </Card>
    </>
  );
}

/* ============================================================
   PROFILE VIEW
============================================================ */
function ProfileView() {
  return (
    <>
      <PageHeader
        eyebrow="Account"
        title="Student profile"
        lead="Your personal details, contact information and notification preferences."
      />
      <div className="two-col" style={{ display:'grid', gridTemplateColumns:'320px 1fr', gap:18 }}>
        <Card>
          <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:14, padding:'8px 0 12px' }}>
            <Avatar initials={me.initials} size={96}/>
            <div style={{ textAlign:'center' }}>
              <div className="serif" style={{ fontSize:26 }}>{me.name}</div>
              <div style={{ fontSize:12.5, color:'var(--muted)', marginTop:2 }}>{me.programs[0]} · {me.programs[1]}</div>
              <div className="mono" style={{ fontSize:12, color:'var(--muted)', marginTop:6 }}>ID {me.album}</div>
            </div>
            <button style={{ ...btnGhost, width:'100%', justifyContent:'center' }}>Change profile photo</button>
          </div>
        </Card>
        <Card>
          <SectionLabel>Contact details</SectionLabel>
          {[
            ['School e-mail', me.email, true],
            ['Personal e-mail', 'name.surname@example.com', false],
            ['Phone', '+00 000 ··· 000', false],
            ['Mailing address', '12 Example St., Apt. 4, 00-000 City', false],
          ].map(([k,v,locked], i) => (
            <div key={i} className="kv-row" style={{ display:'grid', gridTemplateColumns:'180px 1fr auto', gap:14, padding:'12px 0', alignItems:'center', borderTop: i===0?'none':'1px solid var(--line-2)' }}>
              <span style={{ fontSize:12.5, color:'var(--muted)' }}>{k}</span>
              <span className="mono" style={{ fontSize:13.5, wordBreak:'break-word' }}>{v}</span>
              {locked
                ? <Pill tone="neutral" size="xs"><I.shield s={11}/> locked</Pill>
                : <button style={{ ...btnGhost, padding:'5px 10px', fontSize:12 }}>Edit</button>}
            </div>
          ))}
        </Card>
      </div>
      <Card>
        <SectionLabel>Notification preferences</SectionLabel>
        {[
          ['New announcements from lecturers', true, true],
          ['Upcoming midterms and exams', true, true],
          ['Timetable changes', true, true],
          ['School news', false, true],
          ['Push notifications in the mobile app', true, false],
        ].map(([label, emailOn, pushOn], i) => (
          <div key={i} style={{ display:'grid', gridTemplateColumns:'1fr 80px 80px', gap:14, alignItems:'center', padding:'10px 0', borderTop: i===0?'none':'1px solid var(--line-2)' }}>
            <span style={{ fontSize:13.5 }}>{label}</span>
            <Toggle on={emailOn} label="e-mail"/>
            <Toggle on={pushOn} label="push"/>
          </div>
        ))}
      </Card>
    </>
  );
}

function Toggle({ on, label }) {
  const [v, setV] = useStateV(on);
  return (
    <button onClick={()=>setV(!v)} style={{ display:'flex', alignItems:'center', gap:8, fontSize:12, color:'var(--muted)', minHeight:32 }}>
      <span style={{ width:30, height:18, borderRadius:99, background: v?'var(--accent)':'var(--line)', position:'relative', transition:'background .15s', flexShrink:0 }}>
        <span style={{ position:'absolute', top:2, left: v?14:2, width:14, height:14, borderRadius:99, background:'#FFF', transition:'left .15s', boxShadow:'0 1px 2px rgba(0,0,0,.2)' }}></span>
      </span>
      {label}
    </button>
  );
}

/* ============================================================
   ANNOUNCEMENTS VIEW
============================================================ */
function AnnouncementsView() {
  return (
    <>
      <PageHeader eyebrow="Communication" title="Announcements" lead="All messages from your lecturers, grouped by course."/>
      <Announcements/>
      <NewsBoard/>
    </>
  );
}

/* ============================================================
   DOCUMENTS VIEW
============================================================ */
function DocumentsView() {
  const [q, setQ] = useStateV('');
  const filteredGroups = fileGroups.map(g => ({
    ...g,
    items: g.items.filter(f => f.name.toLowerCase().includes(q.toLowerCase()))
  })).filter(g => g.items.length>0);
  return (
    <>
      <PageHeader eyebrow="Files" title="Documents" lead="Course materials, presentations and handouts — grouped by course."/>
      <Card>
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'4px 4px 14px', flexWrap:'wrap' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, padding:'8px 12px', background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:10, flex:1, minWidth:200 }}>
            <I.search/>
            <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Search files by name…" style={{ background:'transparent', border:0, outline:'none', flex:1, fontSize:13.5, color:'var(--ink)', minWidth:0 }}/>
            {q && <button onClick={()=>setQ('')} style={{ fontSize:11, color:'var(--muted)' }}>clear</button>}
          </div>
          <div style={{ display:'flex', gap:2, padding:2, background:'var(--surface-2)', borderRadius:8, border:'1px solid var(--line)' }}>
            {['All','PDF','PPT','Code'].map((l, i) => (
              <button key={i} style={{ padding:'4px 10px', fontSize:12, fontWeight: i===0?600:450, borderRadius:6, background: i===0?'#FFF':'transparent', color: i===0?'var(--ink)':'var(--muted)', minHeight:28 }}>{l}</button>
            ))}
          </div>
        </div>
        {filteredGroups.map((g, i) => <FileGroup key={i} group={g} defaultOpen/>)}
        {filteredGroups.length===0 && (
          <div style={{ padding:'40px 16px', textAlign:'center', color:'var(--muted)', fontSize:13 }}>
            No files match "{q}".
          </div>
        )}
      </Card>
    </>
  );
}

/* ============================================================
   ENROLLMENT VIEW
============================================================ */
function EnrollmentView() {
  const courses = [
    { id:1, code:'ML-DC', name:'Machine Learning', ects:5, slots:8, total:24, teacher:'Dr. M. Collins', tone:'green' },
    { id:2, code:'CRY-DC', name:'Applied Cryptography', ects:4, slots:2, total:18, teacher:'Dr. P. Winters', tone:'warn' },
    { id:3, code:'WEB-DC', name:'Web Applications — Vue/Next', ects:4, slots:15, total:24, teacher:'P. Cook, MSc', tone:'green' },
    { id:4, code:'UX-DC', name:'UX/UI Design', ects:3, slots:0, total:20, teacher:'A. Ross, MSc', tone:'red' },
    { id:5, code:'CV-DC', name:'Computer Vision', ects:5, slots:6, total:18, teacher:'Prof. T. Brooks', tone:'green' },
  ];
  const [selected, setSelected] = useStateV(new Set([1,3]));
  const toggle = (id) => {
    const n = new Set(selected);
    n.has(id) ? n.delete(id) : n.add(id);
    setSelected(n);
  };
  const selectedCourses = courses.filter(c=>selected.has(c.id));
  const ects = selectedCourses.reduce((s,c)=>s+c.ects,0);

  return (
    <>
      <PageHeader
        eyebrow="Online enrollment"
        title="Elective course selection"
        lead="Winter semester 2026/2027. Pick at least 12 ECTS — the deadline is June 14, 11:59 PM."
        action={
          <div style={{ textAlign:'right' }}>
            <div className="serif" style={{ fontSize:34, lineHeight:1 }}>{ects} <span style={{ fontSize:18, color:'var(--muted)' }}>/ 12 ECTS</span></div>
            <div style={{ fontSize:12, color:'var(--muted)' }}>{selectedCourses.length} courses selected</div>
          </div>
        }
      />
      <Card>
        <SectionLabel
          icon={<I.edit s={13}/>}
          action={<button style={{ ...btnPrimary, opacity: ects>=12?1:.5, pointerEvents: ects>=12?'auto':'none' }}>Confirm selection <I.arrow s={12}/></button>}
        >Available courses</SectionLabel>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {courses.map(c => {
            const isSel = selected.has(c.id);
            const full = c.slots===0;
            const slotsTone = c.tone==='red' ? 'warn' : c.tone==='warn' ? 'info' : 'accent';
            return (
              <div key={c.id} className="class-row" style={{
                display:'grid', gridTemplateColumns:'40px 1fr auto auto', gap:14, alignItems:'center',
                padding:'14px 16px',
                background: isSel ? 'oklch(0.96 0.04 25)' : 'var(--surface-2)',
                border: `1px solid ${isSel?'oklch(0.85 0.08 25)':'var(--line)'}`,
                borderRadius:11, cursor: full ? 'not-allowed' : 'pointer',
                opacity: full ? .55 : 1,
              }} onClick={()=>!full && toggle(c.id)}>
                <span style={{
                  width:22, height:22, borderRadius:6,
                  border: `1.5px solid ${isSel?'var(--accent)':'var(--line)'}`,
                  background: isSel ? 'var(--accent)' : '#FFF',
                  color:'#FFF', display:'inline-flex', alignItems:'center', justifyContent:'center'
                }}>{isSel && <I.check s={13}/>}</span>
                <div>
                  <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                    <span className="mono" style={{ fontSize:10.5, color:'var(--muted)', background:'#FFF', padding:'1px 6px', borderRadius:5, border:'1px solid var(--line)' }}>{c.code}</span>
                    <span style={{ fontWeight:600, fontSize:14.5 }}>{c.name}</span>
                  </div>
                  <div style={{ fontSize:12, color:'var(--muted)', marginTop:3 }}>{c.teacher} · {c.ects} ECTS</div>
                </div>
                <Pill tone={slotsTone} size="xs">
                  {full ? 'full' : `${c.slots}/${c.total} open`}
                </Pill>
                <button style={{ color:'var(--muted)', padding:6 }} onClick={(e)=>e.stopPropagation()}><I.arrow/></button>
              </div>
            );
          })}
        </div>
      </Card>
    </>
  );
}

/* ============================================================
   APP
============================================================ */
function App() {
  const [active, setActive] = useStateV('dashboard');
  const [menuOpen, setMenuOpen] = useStateV(false);

  useEffectV(()=> { window.scrollTo({ top:0, behavior:'smooth' }); }, [active]);

  const select = (id) => { setActive(id); setMenuOpen(false); };

  const views = {
    dashboard: <DashboardView/>,
    timetable: <TimetableView/>,
    grades: <GradesView/>,
    courses: <CoursesView/>,
    finance: <FinanceView/>,
    profile: <ProfileView/>,
    announcements: <AnnouncementsView/>,
    documents: <DocumentsView/>,
    enrollment: <EnrollmentView/>,
  };

  return (
    <div style={{ display:'flex', minHeight:'100vh' }}>
      <Sidebar active={active} onSelect={select} open={menuOpen} onClose={()=>setMenuOpen(false)}/>
      <div className={`backdrop${menuOpen ? ' show' : ''}`} onClick={()=>setMenuOpen(false)}></div>
      <main style={{ flex:1, minWidth:0 }}>
        <TopBar active={active} onMenu={()=>setMenuOpen(true)} onSelect={select}/>
        <div className="main-pad" style={{ padding:'24px 32px 56px', display:'flex', flexDirection:'column', gap:18, maxWidth:1400, margin:'0 auto' }} key={active}>
          {views[active] || <DashboardView/>}
          <div style={{ textAlign:'center', color:'var(--muted)', fontSize:11.5, padding:'14px 0 0' }}>
            School · student portal · v3.0 redesign · © 2026
          </div>
        </div>
      </main>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
