/* === PHYSL 210 — Home (dashboard) === */

/* at-a-glance snapshot from the live stats store + loaded banks (runtime totals) */
function homeSnapshot() {
  try {
    const TBQ = (typeof TEXTBOOK_QUESTIONS !== 'undefined') ? TEXTBOOK_QUESTIONS : {};
    const st = liveStats();
    let totalItems = 0, attempted = 0, weakest = null;
    MODULES.forEach(m => {
      const mm = moduleMastery(m.id);              // shared definition (questions + cards)
      totalItems += mm.total; attempted += mm.attempted;
      if (mm.attempted > 0 && mm.total > 0) {      // only rank modules actually started
        if (!weakest || mm.pct < weakest.pct) weakest = { m, pct: mm.pct };
      }
    });
    const src = st.bySource || {};
    const accAtt = ((src.course||{}).attempts||0) + ((src.textbook||{}).attempts||0);
    const accCor = ((src.course||{}).correct||0) + ((src.textbook||{}).correct||0);
    return {
      streak: currentStreak(st),
      accuracy: accAtt ? Math.round(accCor/accAtt*100) : null,
      explored: totalItems ? Math.round(attempted/totalItems*100) : 0,
      weakest,
      hasActivity: attempted > 0 || accAtt > 0,
    };
  } catch (e) { return { streak:0, accuracy:null, explored:0, weakest:null, hasActivity:false }; }
}

function SnapStat({ value, suffix, label, accent, mark, sub, onClick }) {
  const shown = useCountUp(Number(value) || 0);
  return (
    <div className={`snap-card${onClick ? ' snap-link' : ''}`} onClick={onClick}
      role={onClick ? 'button' : undefined} tabIndex={onClick ? 0 : undefined}
      onKeyDown={onClick ? (e)=>{ if(e.key==='Enter'||e.key===' '){ e.preventDefault(); onClick(); } } : undefined}>
      <div className="snap-top">
        {mark}
        <span className="snap-num" style={{ color: accent || 'var(--ink)' }}>
          {value == null ? '—' : <>{shown}{suffix && <span style={{ fontSize:18 }}>{suffix}</span>}</>}
        </span>
      </div>
      {sub ? <div className="snap-sub" style={{ color: accent || 'var(--ink)' }}>{sub}</div> : null}
      <div className="snap-lbl">{label}</div>
    </div>
  );
}

function HomePage({ go, user }) {
  const hr = new Date().getHours();
  const greet = hr < 12 ? 'GOOD MORNING' : hr < 18 ? 'GOOD AFTERNOON' : 'GOOD EVENING';
  const name = (user || STUDENT);   // logged-in username (e.g. shahzaib/haddeya/aliya), shown in the greeting

  const focusMod = (typeof SCH_FOCUS !== 'undefined' && MOD_BY_ID[SCH_FOCUS]) || MODULES.find(m => m.current) || MODULES[0];
  const fc = modColor(focusMod.hue);

  const nextEx = (typeof SCH_NEXT_EXAM !== 'undefined' && SCH_NEXT_EXAM) ? SCH_NEXT_EXAM : null;
  const exMeta = (nextEx && typeof EXAMS !== 'undefined') ? EXAMS.find(e => e.name === nextEx.title) : null;
  const exDays = nextEx ? schDaysUntil(nextEx.start) : null;

  const snap = homeSnapshot();

  // contextual study actions — tied to where the student actually is
  const drill = snap.weakest
    ? { icon:'practice', sec:'practice', title:'Drill weakest topic', sub:`${snap.weakest.m.name} · ${snap.weakest.pct}% mastered`, act:() => go('practice', snap.weakest.m.id) }
    : { icon:'practice', sec:'practice', title:'Practice questions', sub:'By topic or a mixed set', act:() => go('practice') };
  const actions = [
    { icon:'lessons', sec:'lessons', title:'Resume lesson', sub:focusMod.name, act:() => go('lessons', focusMod.id) },
    drill,
    { icon:'cards', sec:'cards', title:'Recall flashcards', sub:focusMod.name, act:() => go('cards', focusMod.id) },
  ];
  const secOf = (key) => SECTIONS.find(s => s.key === key) || { bg:'var(--coral-tint)', ink:'var(--coral-deep)' };

  return (
    <div className="page fade">
      <div className="home-top">
        {/* welcome / pick up where you left off */}
        <div className="home-hero">
          <div style={{ fontSize:14.5, fontWeight:700, color:'var(--coral-deep)', letterSpacing:'.3px' }}>{greet}, {name.toUpperCase()}</div>
          <div className="disp" style={{ fontSize:38, fontWeight:700, letterSpacing:'-1.2px', margin:'8px 0 0', lineHeight:1.05 }}>
            Pick up where<br/>you left off.
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:12, marginTop:18 }}>
            <div className="mod-emblem" style={{ width:46, height:46, background:fc.bg, color:fc.ink }}><ModuleGlyph m={focusMod} size={25} color={fc.ink} /></div>
            <div>
              <div className="page-eyebrow" style={{ color:fc.ink }}>This week · {focusMod.chapter}</div>
              <div className="disp" style={{ fontSize:20, fontWeight:600, lineHeight:1.1, marginTop:1 }}>{focusMod.name}</div>
            </div>
          </div>
          <div style={{ display:'flex', gap:12, marginTop:'auto', paddingTop:26, flexWrap:'wrap' }}>
            <button className="btn btn-lg btn-primary" onClick={() => go('lessons', focusMod.id)}>Resume lesson →</button>
            <button className="btn btn-lg btn-ghost" onClick={() => go('practice', focusMod.id)}>Practice this topic</button>
          </div>
        </div>

        {/* up next exam — wired to the schedule + exam bank (no hard-coded counts) */}
        {nextEx && (
          <div className="panel home-upnext" onClick={() => go('exam')}
            role="button" tabIndex={0} onKeyDown={(e)=>{ if(e.key==='Enter'||e.key===' '){ e.preventDefault(); go('exam'); } }}>
            <div className="tag" style={{ alignSelf:'flex-start', background:'var(--p-sky)', color:'var(--p-sky-i)' }}>Up next</div>
            <div className="disp" style={{ fontSize:24, fontWeight:600, margin:'16px 0 4px', lineHeight:1.12 }}>{nextEx.title}</div>
            <div style={{ fontSize:13.5, color:'var(--muted)', lineHeight:1.5 }}>
              {schRange(nextEx.start, nextEx.end)} · worth {nextEx.weight}{exMeta ? ` · ${exMeta.nQ} questions · ${exMeta.mins} min` : ''}
            </div>
            {exMeta && <div className="upnext-cover">
              {exMeta.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>}
            <div style={{ marginTop:'auto', display:'flex', alignItems:'baseline', gap:8, paddingTop:18 }}>
              <span className="stat-num" style={{ fontSize:44, color:'var(--coral)' }}>{exDays != null ? Math.max(0, exDays) : '—'}</span>
              <span style={{ fontSize:15, fontWeight:600, color:'var(--muted)' }}>days away</span>
            </div>
          </div>
        )}
      </div>

      {/* at-a-glance snapshot */}
      <div className="home-snap">
        <SnapStat value={snap.streak} suffix={snap.streak === 1 ? ' day' : ' days'} label="Study streak"
          accent="var(--coral-deep)" mark={<StreakMark size={20} color="var(--coral-deep)" />} />
        <SnapStat value={snap.accuracy} suffix="%" label="Overall accuracy" accent="var(--p-mint-i)" />
        <SnapStat value={snap.explored} suffix="%" label="Course explored" accent="var(--p-sky-i)" />
        {snap.weakest
          ? <SnapStat value={snap.weakest.pct} suffix="%" label="Weakest — tap to drill" accent={modColor(snap.weakest.m.hue).ink}
              sub={snap.weakest.m.name} onClick={() => go('practice', snap.weakest.m.id)} />
          : <SnapStat value={null} label="Weakest module" sub="Start practicing" />}
      </div>

      {/* continue studying — contextual jump-back-in */}
      <div className="page-eyebrow" style={{ margin:'30px 0 0' }}>Continue studying</div>
      <div className="home-continue">
        {actions.map((a, i) => {
          const sec = secOf(a.sec);
          return (
            <button key={i} className="cont-card" onClick={a.act}>
              <div className="icon-badge" style={{ width:46, height:46, borderRadius:14, background:sec.bg }}>{Icons[a.icon](sec.ink)}</div>
              <div style={{ minWidth:0 }}>
                <div className="cont-title">{a.title}</div>
                <div className="cont-sub">{a.sub}</div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}
window.HomePage = HomePage;
