/* === PHYSL 210 — Practice (question bank) === */
const { useState: useSP, useEffect: useEP } = React;

/* course vs textbook question sources (textbook items carry .src==='textbook' + .cite) */
const TB_Q = (typeof TEXTBOOK_QUESTIONS !== 'undefined') ? TEXTBOOK_QUESTIONS : {};
function courseQs(id)   { return (QUESTIONS[id] || []).filter(q => !q.src || q.src === 'course'); }
function textbookQs(id) { return (TB_Q[id] || []); }
function qsFor(id, source) {
  if (source === 'course')   return courseQs(id);
  if (source === 'textbook') return textbookQs(id);
  return courseQs(id).concat(textbookQs(id));
}
function countFor(id, source) { return qsFor(id, source).length; }

function pickN(arr, n) { return [...arr].sort(() => Math.random()-0.5).slice(0, n); }
function buildMixed(n, source) {
  const all = [];
  // tag each question with its module id so mixed-set answers attribute correctly
  MODULES.forEach(m => tagModule(qsFor(m.id, source), m.id).forEach(q => all.push(q)));
  return pickN(all, n);
}

/* lifetime accuracy for a module's questions (combined sources) */
function qAccuracy(id) {
  try {
    const q = (liveStats().modules[id] || {}).q || {};
    return q.attempts ? { att: q.attempts, pct: Math.round((q.correct || 0) / q.attempts * 100) } : { att: 0, pct: 0 };
  } catch (e) { return { att: 0, pct: 0 }; }
}

const SRC_LABEL = { course:'Course', textbook:'Textbook', both:'Course + Textbook' };

function PracticePage({ focus, go }) {
  const [source, setSource] = useSP('course'); // 'course' | 'textbook' | 'both'
  const [mixCount, setMixCount] = useSP(10);
  /* focus is a module id (string) or a per-topic launch { mod, topicId } from the Lessons page */
  const focusMod   = (focus && typeof focus === 'object') ? focus.mod : focus;
  const focusTopic = (focus && typeof focus === 'object') ? focus.topicId : null;
  const topicLabel = (mod, id) => ((typeof TOPICS !== 'undefined' && (TOPICS[mod] || []).find(t => t.id === id)) || {}).label || 'Topic';
  /* one topic's questions, combined across course + textbook + class sources */
  const buildTopicQuiz = (mod, id) => {
    if (typeof topicQuestions !== 'function' || !MOD_BY_ID[mod]) return null;
    const qs = topicQuestions(mod, id);
    return qs.length ? { qs, title: `${MOD_BY_ID[mod].name} · ${topicLabel(mod, id)}`, accent: modColor(MOD_BY_ID[mod].hue).ink, mod } : null;
  };
  const [quiz, setQuiz] = useSP(() => {
    if (!focusMod || !MOD_BY_ID[focusMod]) return null;
    if (focusTopic) return buildTopicQuiz(focusMod, focusTopic);
    return { qs: tagModule(qsFor(focusMod, 'course'), focusMod), title: MOD_BY_ID[focusMod].name, accent: modColor(MOD_BY_ID[focusMod].hue).ink, mod: focusMod };
  });

  useEP(() => {
    if (focusTopic && MOD_BY_ID[focusMod]) {
      const q = buildTopicQuiz(focusMod, focusTopic);
      if (q) setQuiz(q);
    } else if (focusMod && MOD_BY_ID[focusMod]) {
      const qs = tagModule(qsFor(focusMod, source), focusMod);
      if (qs.length) setQuiz({ qs, title: MOD_BY_ID[focusMod].name, accent: modColor(MOD_BY_ID[focusMod].hue).ink, mod: focusMod });
    }
  }, [focus, source]);

  if (quiz) return (
    <div className="page fade">
      <QuizRunner questions={quiz.qs} mode="practice" title={quiz.title} accent={quiz.accent} moduleId={quiz.mod} onExit={() => setQuiz(null)} />
    </div>
  );

  const startModule = (m) => { const qs = tagModule(qsFor(m.id, source), m.id); if (qs.length) setQuiz({ qs, title: m.name, accent: modColor(m.hue).ink, mod: m.id }); };
  const startMixed = () => { const qs = buildMixed(mixCount, source); if (qs.length) setQuiz({ qs, title:`Mixed bank · ${SRC_LABEL[source]}`, accent:'var(--coral)', mod:null }); };

  // bank totals (runtime)
  const totalCourse = MODULES.reduce((n, m) => n + courseQs(m.id).length, 0);
  const totalTextbook = MODULES.reduce((n, m) => n + textbookQs(m.id).length, 0);
  const totalForSrc = source === 'course' ? totalCourse : source === 'textbook' ? totalTextbook : totalCourse + totalTextbook;

  // overall accuracy for the selected source
  const bs = liveStats().bySource || {};
  const accFor = (() => {
    const pick = source === 'course' ? [bs.course] : source === 'textbook' ? [bs.textbook] : [bs.course, bs.textbook];
    const att = pick.reduce((n, s) => n + ((s||{}).attempts || 0), 0);
    const cor = pick.reduce((n, s) => n + ((s||{}).correct || 0), 0);
    return att ? Math.round(cor / att * 100) : null;
  })();

  // rows: weakest started modules first, then untouched, then any with no questions for this source
  const rows = MODULES.map(m => ({ m, count: countFor(m.id, source), ms: moduleMastery(m.id), acc: qAccuracy(m.id) }));
  rows.sort((a, b) => {
    const grp = (r) => r.count === 0 ? 2 : (r.ms.attempted > 0 ? 0 : 1);
    const ga = grp(a), gb = grp(b);
    if (ga !== gb) return ga - gb;
    if (ga === 0) return a.ms.pct - b.ms.pct;          // weakest first among started
    return 0;
  });

  const srcSeg = (
    <div className="seg" title="Choose which questions to practice">
      {['course','textbook','both'].map(s => (
        <button key={s} className={source===s?'on':''} onClick={() => setSource(s)}>{s==='both' ? 'Both' : SRC_LABEL[s]}</button>
      ))}
    </div>
  );

  return (
    <div className="page fade">
      <div className="page-head">
        <div className="page-eyebrow">Practice</div>
        <h1 className="page-title">Question bank</h1>
      </div>

      <div className="bank-top">
        {/* bank summary + source toggle */}
        <div className="panel bank-summary">
          <div className="bank-counts">
            <span className="bank-count-num" style={{ color:'var(--coral)' }}>{totalForSrc}</span>
            <div>
              <div style={{ fontFamily:'Quicksand', fontWeight:600, fontSize:16 }}>{SRC_LABEL[source]} questions</div>
              <div className="bank-count-split">{totalCourse} course · {totalTextbook} textbook{accFor != null ? <> · <b style={{ color:'var(--p-mint-i)' }}>{accFor}% accuracy</b></> : ''}</div>
            </div>
          </div>
          {srcSeg}
          {source !== 'course' && <div style={{ fontSize:12.5, color:'var(--muted)' }}>Textbook items are labeled with their Vander’s chapter &amp; question number.</div>}
        </div>

        {/* mixed drill — hero action */}
        <div className="panel bank-mixed">
          <div className="page-eyebrow" style={{ color:'var(--coral-deep)' }}>Mixed drill</div>
          <div style={{ fontSize:13.5, color:'var(--ink-soft)', lineHeight:1.45 }}>Random {SRC_LABEL[source]} questions from every module — best for cumulative review.</div>
          <div className="seg" style={{ background:'var(--surface)' }}>
            {[10,20,40].map(n => <button key={n} className={mixCount===n?'on':''} onClick={() => setMixCount(n)}>{n} Q</button>)}
          </div>
          <button className="btn btn-md btn-primary" onClick={startMixed}>Start drill →</button>
        </div>
      </div>

      {/* per-module table */}
      <div className="bank-table">
        <div className="bank-head">
          <span>Module</span>
          <span style={{ textAlign:'right' }}>Questions</span>
          <span className="bank-col-acc">Accuracy</span>
          <span style={{ textAlign:'right' }}>Mastery</span>
        </div>
        {rows.map(({ m, count, ms, acc }) => {
          const c = modColor(m.hue);
          const empty = count === 0;
          return (
            <div key={m.id} className={`bank-row${empty ? ' is-empty' : ''}`}
              onClick={empty ? undefined : () => startModule(m)}
              role={empty ? undefined : 'button'} tabIndex={empty ? undefined : 0}
              onKeyDown={empty ? undefined : (e)=>{ if(e.key==='Enter'||e.key===' '){ e.preventDefault(); startModule(m); } }}>
              <div className="bank-mod">
                <div className="mod-emblem" style={{ width:38, height:38, borderRadius:11, background:c.bg, color:c.ink }}><ModuleGlyph m={m} size={20} color={c.ink} /></div>
                <div style={{ minWidth:0 }}>
                  <div className="bank-mod-name">{m.name}</div>
                  {m.current && <span className="tag" style={{ background:'var(--coral)', color:'#fff', marginTop:3 }}>This week</span>}
                </div>
              </div>
              <div style={{ textAlign:'right' }}>
                <div className="bank-cell-num" style={{ color: empty ? 'var(--muted)' : 'var(--ink)' }}>{count}</div>
                <div className="bank-cell-lbl">questions</div>
              </div>
              <div className="bank-col-acc bank-acc">
                {acc.att
                  ? <><div className="bank-cell-lbl" style={{ color:c.ink, fontFamily:'Quicksand', fontSize:14, fontWeight:700 }}>{acc.pct}%</div><AnimatedBar pct={acc.pct} color={c.ink} track="var(--line-soft)" height={6} /></>
                  : <span className="bank-cell-lbl">not attempted</span>}
              </div>
              <div className="bank-mastery" style={{ justifyContent:'flex-end' }}>
                {ms.attempted
                  ? <MiniRing pct={ms.pct} color={c.ink} />
                  : <span className="bank-cell-lbl">{empty ? '—' : 'new'}</span>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
window.PracticePage = PracticePage;
