/* === PHYSL 210 — Simulated Exam (exam-paper layout) === */
const { useState: useSE } = React;

const EXAMS = [
  { id:'mid1', name:'1st Mid-term Exam', weight:'15%', mins:45, nQ:10, hue:46,
    cover:['cell','blood','nms'], date:'May 28 / Jun 1', term:'Spring',
    desc:'Cell, Blood and Nerve/Muscle/Synapse physiology.' },
  { id:'spring', name:'Spring Term Exam', weight:'35%', mins:60, nQ:14, hue:25,
    cover:['cell','blood','nms','cns','ans','ss','cardio'], date:'Jun 25 / 26', term:'Spring', feature:true,
    desc:'Cumulative — all first-term material, Cell through Cardiovascular.' },
  { id:'mid2', name:'2nd Mid-term Exam', weight:'15%', mins:45, nQ:10, hue:70,
    cover:['gi','resp'], date:'Jul 20 / 21', term:'Summer',
    desc:'Gastrointestinal and Respiratory physiology.' },
  { id:'summer', name:'Summer Term Exam', weight:'35%', mins:60, nQ:14, hue:278,
    cover:['gi','resp','renal','repro','endo'], date:'Aug 24 / 25', term:'Summer',
    desc:'Cumulative — all second-term material, GI through Endocrine.' },
];

/* join each exam to its schedule entry so days-until / done state come from the
   single source of truth in data-schedule.jsx (never hard-coded here) */
const EXAM_SCHED = {};
try { (typeof SCHEDULE !== 'undefined' ? SCHEDULE : []).forEach(t => t.items.forEach(it => { if (it.kind === 'exam') EXAM_SCHED[it.title] = it; })); } catch (e) {}
function examDays(ex) { const si = EXAM_SCHED[ex.name]; return si ? schDaysUntil(si.start) : null; }
function examStatus(ex) { const si = EXAM_SCHED[ex.name]; return si ? schStatus(si) : 'upcoming'; }

function buildExam(ex) {
  // Fixed papers (imported real exams) carry their own ordered question set — sit them as-is.
  if (ex.questions && ex.questions.length) return ex.questions;
  const pool = [];
  // tag each question with its source module so exam answers attribute correctly
  ex.cover.forEach(id => tagModule(QUESTIONS[id]||[], id).forEach(q => pool.push(q)));
  return [...pool].sort(() => Math.random()-0.5).slice(0, ex.nQ);
}

/* coverage chips — one small module emblem per covered topic */
function CoverChips({ cover }) {
  return (
    <div className="exam-cov">
      {cover.map(id => {
        const m = MOD_BY_ID[id]; if (!m) return null;
        const c = modColor(m.hue);
        return <span key={id} className="cov-chip" style={{ background:c.bg, color:c.ink }} title={m.name}><ModuleGlyph m={m} size={17} color={c.ink} /></span>;
      })}
    </div>
  );
}

function PreExam({ ex, onStart, onBack }) {
  const c = modColor(ex.hue);
  return (
    <div className="page fade" style={{ maxWidth:720 }}>
      <button className="crumb" onClick={onBack}>← All exams</button>
      <div className="panel" style={{ padding:'38px 40px' }}>
        <div className="tag" style={{ background:c.bg, color:c.ink }}>{ex.term} term · {ex.date}</div>
        <h1 className="page-title" style={{ fontSize:34, marginTop:14 }}>{ex.name}</h1>
        <p className="page-sub" style={{ marginTop:8 }}>{ex.desc}</p>

        <div className="pe-stats">
          {[['Questions', ex.nQ],['Time limit', `${ex.mins} min`],['Weight', ex.weight]].map(([k,v]) => (
            <div key={k} className="pe-stat">
              <div className="stat-num pe-stat-num" style={{ color:c.ink }}>{v}</div>
              <div className="pe-stat-lbl">{k}</div>
            </div>
          ))}
        </div>

        <div className="explain" style={{ background:`color-mix(in oklch, ${c.ink} 11%, var(--surface))`, borderColor:`color-mix(in oklch, ${c.ink} 26%, transparent)` }}>
          <b>Exam conditions.</b> Closed book. A countdown timer runs once you begin — the exam auto-submits at zero. You can flag and revisit questions before submitting. This is practice; your score won’t be recorded.
        </div>

        <div style={{ display:'flex', gap:12, marginTop:24 }}>
          <button className="btn btn-lg btn-ghost" onClick={onBack}>Not yet</button>
          <button className="btn btn-lg btn-primary" onClick={onStart}>Begin exam →</button>
        </div>
      </div>
    </div>
  );
}

function ExamPage() {
  const [stage, setStage] = useSE('list');   // 'list' | 'brief' | 'run'
  const [ex, setEx] = useSE(null);
  const [qs, setQs] = useSE([]);
  const open = (e) => { setEx(e); setStage('brief'); };

  if (stage === 'run' && ex) return (
    <div className="page fade">
      <QuizRunner questions={qs} mode="exam" title={ex.name} accent={modColor(ex.hue).ink}
        timeLimit={ex.mins*60} onExit={() => setStage('list')} />
    </div>
  );

  if (stage === 'brief' && ex) return (
    <PreExam ex={ex} onBack={() => setStage('list')} onStart={() => { setQs(buildExam(ex)); setStage('run'); }} />
  );

  // first not-yet-sat exam headlines the page; the rest stack below as a sitting list
  const hero = EXAMS.find(e => examStatus(e) !== 'done') || EXAMS.find(e => e.feature) || EXAMS[0];
  const rest = EXAMS.filter(e => e !== hero);
  const hc = modColor(hero.hue);
  const hDays = examDays(hero);
  const hDone = examStatus(hero) === 'done';

  return (
    <div className="page fade">
      <div className="page-head">
        <div className="page-eyebrow">Simulated Exam</div>
        <h1 className="page-title">Exam papers</h1>
        <p className="page-sub">Sit a timed paper under exam conditions. Each mirrors the real weighting and coverage so you know where you stand before the day.</p>
      </div>

      {/* headline exam — the next one you'll sit */}
      <div className="exam-hero" onClick={() => open(hero)} role="button" tabIndex={0}
        onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(hero); } }}>
        <div className="exam-accent" style={{ background:hc.ink }} />
        <div className="exam-hero-top">
          <div className="exam-eyebrow" style={{ color:hc.ink }}>{hero.term} term · {hero.date}{hero.feature ? ' · cumulative' : ''}</div>
          {hDone
            ? <span className="tag" style={{ background:'oklch(0.93 0.04 165)', color:'var(--p-mint-i)' }}>✓ Sat</span>
            : (hDays != null && hDays > 0)
              ? <div className="exam-days"><div className="exam-days-num" style={{ color:'var(--coral-deep)' }}>{hDays}</div><div className="exam-days-lbl">days away</div></div>
              : <span className="tag" style={{ background:'var(--coral)', color:'#fff' }}>Open now</span>}
        </div>
        <div className="exam-title">{hero.name}</div>
        <div style={{ fontSize:14.5, color:'var(--ink-soft)', lineHeight:1.5, maxWidth:560 }}>{hero.desc}</div>
        <CoverChips cover={hero.cover} />
        <div className="exam-foot">
          <div className="exam-foot-meta">
            <span style={{ fontVariantNumeric:'tabular-nums' }}>{hero.nQ} questions</span><span style={{ color:'var(--line)' }}>·</span>
            <span>{hero.mins} min</span><span style={{ color:'var(--line)' }}>·</span>
            <span style={{ color:hc.ink }}>{hero.weight} of grade</span><span style={{ color:'var(--line)' }}>·</span>
            <span style={{ color:'var(--muted)' }}>closed book</span>
          </div>
          <span className="btn btn-md btn-primary">Begin exam →</span>
        </div>
      </div>

      {/* the remaining papers */}
      <div className="page-eyebrow" style={{ margin:'30px 0 0' }}>Other papers</div>
      <div className="exam-list">
        {rest.map(e => {
          const c = modColor(e.hue);
          const days = examDays(e);
          const done = examStatus(e) === 'done';
          return (
            <div key={e.id} className="exam-paper" onClick={() => open(e)} role="button" tabIndex={0}
              onKeyDown={(ev) => { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); open(e); } }}>
              <div className="exam-paper-stripe" style={{ background:c.ink }} />
              <div className="mod-emblem" style={{ width:44, height:44, fontSize:16, borderRadius:12, background:c.bg, color:c.ink }}>{Icons.exam(c.ink)}</div>
              <div className="exam-paper-main">
                <div style={{ display:'flex', alignItems:'center', gap:10, flexWrap:'wrap' }}>
                  <span className="exam-paper-title">{e.name}</span>
                  <span className="tag" style={{ background:c.bg, color:c.ink }}>{e.weight}</span>
                </div>
                <div className="exam-paper-meta">{e.nQ} questions · {e.mins} min · {e.desc}</div>
              </div>
              {done
                ? <span className="tag" style={{ background:'oklch(0.93 0.04 165)', color:'var(--p-mint-i)' }}>✓ Sat</span>
                : (days != null && days > 0)
                  ? <div className="exam-paper-days"><div className="stat-num" style={{ fontSize:22, color:'var(--coral-deep)' }}>{days}</div><div style={{ fontSize:11, color:'var(--muted)', fontWeight:600 }}>days</div></div>
                  : <span style={{ color:'var(--muted)', fontSize:20 }}>›</span>}
            </div>
          );
        })}
      </div>
    </div>
  );
}
window.ExamPage = ExamPage;
Object.assign(window, { EXAMS });
