/* app.jsx — cert selection screen on load, no "both", no in-Practice cert toggle */

const PROG_KEY_PREFIX='ccna_progress_v2_';
const CERT_KEY='ccna_cert_mode';

function defaultProg(){const ds={};(window.DOMAINS||[]).forEach(d=>ds[d.id]={answered:0,correct:0});return{totalAnswered:0,totalCorrect:0,domainStats:ds,missedIds:[],streak:0,lastStudied:null,sessionCount:0};}
function loadProg(examId){try{return JSON.parse(localStorage.getItem(PROG_KEY_PREFIX+examId))||defaultProg();}catch{return defaultProg();}}
function saveProg(examId,p){localStorage.setItem(PROG_KEY_PREFIX+examId,JSON.stringify(p));}
function updateProg(prog,session,finalAnswers){
  const p=JSON.parse(JSON.stringify(prog));
  const today=new Date().toDateString();const yesterday=new Date(Date.now()-86400000).toDateString();
  if(p.lastStudied!==today){p.streak=p.lastStudied===yesterday?p.streak+1:1;p.lastStudied=today;}
  session.questions.forEach(q=>{const ans=finalAnswers[q.id];if(!ans)return;p.totalAnswered++;if(!p.domainStats[q.d])p.domainStats[q.d]={answered:0,correct:0};p.domainStats[q.d].answered++;if(ans.correct){p.totalCorrect++;p.domainStats[q.d].correct++;p.missedIds=p.missedIds.filter(id=>id!==q.id);}else{if(!p.missedIds.includes(q.id))p.missedIds.push(q.id);}});
  p.sessionCount++;return p;
}

function buildSession(mode, domainId, tweaks, certMode){
  let pool=(window.Q||[]).filter(q=>q.exam===certMode);
  if(mode==='cli') pool=pool.filter(q=>q.type==='cli');
  else if(mode!=='full') pool=pool.filter(q=>q.type!=='cli');

  if(mode==='quick'){ const qs=pool.sort(()=>Math.random()-0.5).slice(0,10); return{questions:qs,label:'Quick Drill',timerEnabled:tweaks.timerOn,timerDuration:tweaks.timerMins}; }
  if(mode==='weak'){ const prog=loadProg();const missed=prog.missedIds||[];const mq=pool.filter(q=>missed.includes(q.id));const rest=pool.filter(q=>!missed.includes(q.id)).sort(()=>Math.random()-0.5);const qs=[...mq,...rest].slice(0,20);return{questions:qs.length?qs:pool.sort(()=>Math.random()-0.5).slice(0,10),label:'Weak Spot Review',timerEnabled:tweaks.timerOn,timerDuration:tweaks.timerMins}; }
  if(mode==='domain'){ const target=100; const domainPool=pool.filter(q=>q.d===domainId); const qs=domainPool.sort(()=>Math.random()-0.5).slice(0,target); const name=(window.DOMAINS||[]).find(d=>d.id===domainId)?.name||'Domain'; return{questions:qs.length?qs:pool.sort(()=>Math.random()-0.5).slice(0,10),label:`${name} — ${qs.length}q`,timerEnabled:tweaks.timerOn,timerDuration:tweaks.timerMins}; }
  if(mode==='cli'){ return{questions:pool.sort(()=>Math.random()-0.5),label:'CLI Drills',timerEnabled:false,timerDuration:0}; }
  return{questions:pool.sort(()=>Math.random()-0.5),label:'Full Session',timerEnabled:tweaks.timerOn,timerDuration:tweaks.timerMins};
}

/* ===== CERT SELECTION SCREEN (initial choice) ===== */
function CertSelectScreen({onPick}){
  const exams = window.EXAMS || [];
  return(
    <div className="cert-select-screen">
      <div className="cs-content">
        <div className="cs-brand">
          <span className="b-host">study</span><span className="b-sep">@</span><span className="b-path">cyberstudy</span>
          <span className="b-cursor"> ▌</span>
        </div>
        <h1 className="cs-title">Choose your certification track</h1>
        <p className="cs-sub">Sets your question pool, concept topics, and progress tracking. You can switch any time by clicking the badge in the top bar.</p>
        <div className="cs-options">
          {exams.map(e => (
            <button key={e.id} className="cs-card" onClick={()=>onPick(e.id)}>
              <div className="cs-card-label">{e.label}</div>
              <div className="cs-card-sub">{e.sub}</div>
              <div className="cs-card-desc">{e.description}</div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ===== NOTES VIEW ===== */
function NotesView({setView,setLearnTopic}){
  const notes=window.useNotes?window.useNotes():[];
  const byTopic={};
  notes.forEach(n=>{(byTopic[n.topicId]=byTopic[n.topicId]||{title:n.topicTitle,items:[]}).items.push(n);});
  const topicIds=Object.keys(byTopic);
  return(
    <div>
      <div className="home-header">
        <div className="home-h1"><span className="ps1">$</span> <span className="cmd">show notes --all</span></div>
        <div className="home-sub">{notes.length} note{notes.length===1?'':'s'} across {topicIds.length} topic{topicIds.length===1?'':'s'} — click any topic to jump back</div>
      </div>
      {notes.length===0
        ?<div className="empty-msg" style={{padding:'40px 20px'}}>
           No notes yet. Open <span style={{color:'var(--green)'}}>Learn Mode</span>, highlight a passage, click “✎ Add note.”
         </div>
        :topicIds.map(tid=>{const grp=byTopic[tid];return(
          <div key={tid} style={{marginBottom:'22px'}}>
            <div className="sec-label">
              <span className="notes-item-topic" onClick={()=>{setLearnTopic&&setLearnTopic(tid);setView('learn');}}>{grp.title}</span>
              <span style={{color:'var(--fg-mute)',marginLeft:'auto',fontSize:'10px'}}>{grp.items.length} note{grp.items.length===1?'':'s'}</span>
            </div>
            <div className="notes-list">
              {grp.items.map(n=>(
                <div key={n.id} className="notes-item">
                  <div className="notes-item-hl">“{n.selectedText}”</div>
                  <div className="notes-item-txt">{n.note}</div>
                  <div className="notes-item-meta">
                    <span>{new Date(n.createdAt).toLocaleDateString()}{n.updatedAt?' · edited':''}</span>
                    <button className="btn btn-ghost btn-sm" style={{marginLeft:'auto'}} onClick={()=>{setLearnTopic&&setLearnTopic(n.topicId);setView('learn');}}>Open topic →</button>
                    <button className="btn btn-ghost btn-sm btn-danger" onClick={()=>{if(confirm('Delete this note?'))window.deleteNote(n.id);}}>Delete</button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        );})
      }
    </div>
  );
}

/* ===== TOPBAR ===== */
function TopBar({activeTab,setView,prog,streak,certMode,onSwitchCert}){
  const acc=prog.totalAnswered>0?Math.round((prog.totalCorrect/prog.totalAnswered)*100):0;
  return(
    <div className="topbar">
      <button className="brand" onClick={onSwitchCert} title="Switch certification">
        <span className="b-host">{certMode?(window.getExamLabel?window.getExamLabel(certMode):certMode).toLowerCase():'—'}</span><span className="b-sep">@</span><span className="b-path">cyberstudy</span>
        <span className="b-cursor"> ▌</span>
      </button>
      <div className="nav-tabs">
        {[['home','Home'],['learn','Learn'],['practice','Practice'],['progress','Progress'],['final-exam','Final Exam'],['notes','Notes']].map(([v,l])=>(
          <button key={v} className={`nav-tab ${activeTab===v?'active':''}`} onClick={()=>setView(v)}>{l}</button>
        ))}
      </div>
      <div className="nav-right">
        {streak>0&&<span className="streak-badge">🔥 {streak}d</span>}
        {prog.totalAnswered>0&&<span>{acc}% acc · {prog.totalAnswered}q</span>}
      </div>
    </div>
  );
}

/* ===== HOME VIEW ===== */
function HomeView({prog,setView,onStart,certMode}){
  const acc=prog.totalAnswered>0?Math.round((prog.totalCorrect/prog.totalAnswered)*100):0;
  const mastered=Object.values(prog.domainStats).filter(s=>s.answered>0&&Math.round((s.correct/s.answered)*100)>=80).length;
  const pool=(window.Q||[]).filter(q=>q.exam===certMode);
  return(
    <div>
      <div className="home-header">
        <div className="home-h1"><span className="ps1">$</span> <span className="cmd">show dashboard</span></div>
        <div className="home-sub">{pool.filter(q=>q.type!=='cli').length} {window.getExamLabel?window.getExamLabel(certMode):certMode.toUpperCase()} questions loaded · 6 domains</div>
      </div>
      <div className="stats-row">
        <div className="stat-card"><div className="stat-k">Total Answered</div><div className="stat-v cyan">{prog.totalAnswered||'—'}</div></div>
        <div className="stat-card"><div className="stat-k">Accuracy</div><div className={`stat-v ${acc>=70?'green':'amber'}`}>{prog.totalAnswered>0?`${acc}%`:'—'}</div></div>
        <div className="stat-card"><div className="stat-k">Streak</div><div className="stat-v amber">{prog.streak>0?`${prog.streak}d`:'—'}</div></div>
        <div className="stat-card"><div className="stat-k">Domains ≥80%</div><div className="stat-v green">{mastered}/6</div></div>
      </div>
      <div className="sec-label">Quick Actions</div>
      <div className="session-grid">
        <button className="session-btn" onClick={()=>setView('learn')}><div className="sb-icon">📖</div><div className="sb-title">Learn Mode</div><div className="sb-desc">Concept pages, diagrams, NetworkChuck videos</div></button>
        {pool.some(q=>q.type==='cli')&&<button className="session-btn" onClick={()=>onStart('cli')}><div className="sb-icon">💻</div><div className="sb-title">CLI Drills</div><div className="sb-desc">Practice Cisco IOS commands in a real terminal</div></button>}
        <button className="session-btn" onClick={()=>setView('progress')}><div className="sb-icon">📊</div><div className="sb-title">Progress</div><div className="sb-desc">{prog.missedIds.length>0?`${prog.missedIds.length} missed questions to review`:'Track mastery by domain'}</div></button>
        <button className="session-btn" onClick={()=>setView('notes')}><div className="sb-icon">✎</div><div className="sb-title">Notes</div><div className="sb-desc">Your highlights and margin notes from Learn mode</div></button>
      </div>
      <div className="sec-label">Domain Overview</div>
      <div className="domain-list">
        {(window.DOMAINS||[]).map(d=>{const s=prog.domainStats[d.id]||{answered:0,correct:0};const qs=pool.filter(q=>q.d===d.id&&q.type!=='cli').length;const progressPct=qs>0?Math.min(100,Math.round((s.answered/qs)*100)):0;return(
          <button key={d.id} className="domain-row" onClick={()=>onStart&&onStart('domain',d.id)} style={{font:'inherit',color:'inherit'}}>
            <span className="dom-num" style={{color:`var(--d${d.id})`}}>{d.id}</span>
            <span className="dom-name">{d.name}</span>
            <div className="dom-bar"><div className="dom-fill" style={{width:`${progressPct}%`,background:`var(--d${d.id})`}}/></div>
            <span className="dom-pct">{s.answered>0?`${s.answered}/${qs}`:`${qs}q`}</span>
          </button>);})}
      </div>
    </div>
  );
}

/* ===== PRACTICE VIEW ===== */
function PracticeView({certMode,prog,onStart}){
  const [selDomain,setSelDomain]=React.useState(null);
  const pool=(window.Q||[]).filter(q=>q.exam===certMode);
  const cliCount=pool.filter(q=>q.type==='cli').length;
  const weakCount=prog.missedIds.length;

  return(
    <div>
      <div className="home-header">
        <div className="home-h1"><span className="ps1">$</span> <span className="cmd">configure-session</span></div>
        <div className="home-sub">{pool.filter(q=>q.type!=='cli').length} {window.getExamLabel?window.getExamLabel(certMode):certMode.toUpperCase()} questions · {cliCount} CLI drills in pool</div>
      </div>

      <div className="sec-label">Session Type</div>
      <div className="session-grid">
        <button className="session-btn" onClick={()=>onStart('quick')}>
          <div className="sb-icon">⚡</div>
          <div className="sb-title">Quick Drill</div>
          <div className="sb-desc">10 random questions</div>
        </button>
        <button className="session-btn" onClick={()=>onStart('weak')} style={{borderColor:weakCount>0?'var(--amber)':''}}>
          <div className="sb-icon">🎯</div>
          <div className="sb-title">Weak Spot Review</div>
          <div className="sb-desc">{weakCount>0?`${weakCount} missed to tackle`:'Practice areas you struggle with'}</div>
        </button>
        {cliCount>0&&<button className="session-btn" onClick={()=>onStart('cli')}>
          <div className="sb-icon">💻</div>
          <div className="sb-title">CLI Drills</div>
          <div className="sb-desc">{cliCount} Cisco IOS simulations</div>
        </button>}
        <button className="session-btn" onClick={()=>onStart('full')}>
          <div className="sb-icon">📋</div>
          <div className="sb-title">Full Session</div>
          <div className="sb-desc">All {pool.length} questions, randomized</div>
        </button>
      </div>

      <div className="sec-label" style={{marginTop:'22px'}}>Domain Focus</div>
      <div className="domain-list">
        {(window.DOMAINS||[]).map(d=>{
          const qs=pool.filter(q=>q.d===d.id&&q.type!=='cli').length;
          const cqs=pool.filter(q=>q.d===d.id&&q.type==='cli').length;
          const s=prog.domainStats[d.id]||{answered:0,correct:0};
          const progressPct = qs>0 ? Math.min(100, Math.round((s.answered/qs)*100)) : 0;
          const isSel=selDomain===d.id;
          return(
            <button key={d.id} className="domain-row" style={{borderColor:isSel?`var(--d${d.id})`:''}}
              onClick={()=>setSelDomain(isSel?null:d.id)}>
              <span className="dom-num" style={{color:`var(--d${d.id})`}}>{d.id}</span>
              <span className="dom-name">{d.name}<span style={{fontSize:'10px',color:'var(--fg-mute)',marginLeft:'8px'}}>{qs}q{cqs>0?` · ${cqs} CLI`:''}</span></span>
              <div className="dom-bar"><div className="dom-fill" style={{width:`${progressPct}%`,background:`var(--d${d.id})`}}/></div>
              <span className="dom-pct">{s.answered>0?`${s.answered}/${qs}`:''}</span>
            </button>
          );
        })}
      </div>
      {selDomain&&(
        <div style={{marginTop:'12px',display:'flex',gap:'8px'}}>
          <button className="btn btn-primary" onClick={()=>{onStart('domain',selDomain);setSelDomain(null);}}>
            Start Domain {selDomain} →
          </button>
          <button className="btn btn-ghost btn-sm" onClick={()=>setSelDomain(null)}>Cancel</button>
        </div>
      )}
    </div>
  );
}

/* ===== PROGRESS VIEW ===== */
function ProgressView({prog,onStart}){
  const acc=prog.totalAnswered>0?Math.round((prog.totalCorrect/prog.totalAnswered)*100):0;
  const missed=(window.Q||[]).filter(q=>prog.missedIds.includes(q.id));
  return(
    <div>
      <div className="home-header">
        <div className="home-h1"><span className="ps1">$</span> <span className="cmd">show progress --all</span></div>
        <div className="home-sub">Session #{prog.sessionCount} · Last studied: {prog.lastStudied||'never'}</div>
      </div>
      <div className="progress-grid">
        <div>
          <div className="sec-label">Domain Mastery</div>
          <div className="domain-list">
            {(window.DOMAINS||[]).map(d=>{const s=prog.domainStats[d.id]||{answered:0,correct:0};const pct=s.answered>0?Math.round((s.correct/s.answered)*100):0;return(
              <div key={d.id} className="domain-row" style={{cursor:'default'}}>
                <span className="dom-num" style={{color:`var(--d${d.id})`}}>{d.id}</span>
                <span className="dom-name">{d.name}</span>
                <div className="dom-bar"><div className="dom-fill" style={{width:`${pct}%`,background:`var(--d${d.id})`}}/></div>
                <span className="dom-pct">{s.answered>0?`${pct}% (${s.answered}q)`:'—'}</span>
              </div>);})}
          </div>
          <div style={{marginTop:'16px',display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:'8px'}}>
            <div className="stat-card"><div className="stat-k">Total Answered</div><div className="stat-v cyan">{prog.totalAnswered}</div></div>
            <div className="stat-card"><div className="stat-k">Overall Accuracy</div><div className={`stat-v ${acc>=70?'green':'amber'}`}>{prog.totalAnswered>0?`${acc}%`:'—'}</div></div>
            <div className="stat-card"><div className="stat-k">Study Streak</div><div className="stat-v amber">{prog.streak>0?`${prog.streak}d`:'—'}</div></div>
            <div className="stat-card"><div className="stat-k">Need Review</div><div className="stat-v" style={{color:'var(--red)'}}>{prog.missedIds.length}</div></div>
          </div>
        </div>
        <div>
          <div className="sec-label">Missed Questions ({missed.length})</div>
          {missed.length===0?<div className="empty-msg">No missed questions yet!</div>
            :<div className="missed-list">{missed.map(q=>(
              <div key={q.id} className="missed-item" onClick={()=>onStart('domain',q.d)}>
                <span style={{color:`var(--d${q.d})`,fontSize:'10px',textTransform:'uppercase',letterSpacing:'0.06em',marginRight:'6px'}}>D{q.d}</span>
                {q.stem.slice(0,80)}{q.stem.length>80?'…':''}
              </div>))}
            </div>}
          {missed.length>0&&<button className="btn btn-primary btn-sm" style={{marginTop:'10px'}} onClick={()=>onStart('weak')}>Review Missed →</button>}
        </div>
      </div>
    </div>
  );
}

/* ===== TWEAKS ===== */
function AppTweaks({tweaks,setTweak,certMode,onSwitchCert}){
  return(
    <window.TweaksPanel>
      <window.TweakSection title="Certification">
        <div style={{fontSize:'13px',color:'var(--fg-dim)',marginBottom:'8px'}}>Currently studying: <span style={{color:'var(--green)',fontWeight:600}}>{certMode==='ccnp'?'CCNP Enterprise':'CCNA 200-301'}</span></div>
        <window.TweakButton label="Switch Certification" onClick={onSwitchCert}/>
      </window.TweakSection>
      <window.TweakSection title="Questions">
        <window.TweakToggle label="Timer" value={tweaks.timerOn} onChange={v=>setTweak('timerOn',v)}/>
        {tweaks.timerOn&&<window.TweakSlider label="Timer (min)" min={15} max={120} step={5} value={tweaks.timerMins} onChange={v=>setTweak('timerMins',v)}/>}
      </window.TweakSection>
      <window.TweakSection title="Appearance">
        <window.TweakRadio label="Accent" value={tweaks.accent} onChange={v=>setTweak('accent',v)} options={['green','cyan','amber']}/>
        <window.TweakRadio label="Size" value={tweaks.fontSize} onChange={v=>setTweak('fontSize',v)} options={['sm','md','lg']}/>
      </window.TweakSection>
      <window.TweakSection title="Danger Zone">
        <window.TweakButton label="Reset Progress" onClick={()=>{if(confirm('Reset progress for this cert?')){const cert=localStorage.getItem('ccna_cert_mode')||'ccna';saveProg(cert,defaultProg());location.reload();}}}/>
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

/* ===== ROOT APP ===== */
function App(){
  const[view,setView]=React.useState('home');
  const[certMode,setCertModeState]=React.useState(()=>localStorage.getItem(CERT_KEY));
  const[session,setSession]=React.useState(null);
  const[finalAnswers,setFinalAnswers]=React.useState(null);
  const[prog,setProg]=React.useState(()=>loadProg(localStorage.getItem(CERT_KEY)||'ccna'));

  // Re-load progress when cert changes so each track has its own stats
  React.useEffect(()=>{ if(certMode) setProg(loadProg(certMode)); },[certMode]);

  function pickCert(c){
    if(c){localStorage.setItem(CERT_KEY,c);}else{localStorage.removeItem(CERT_KEY);}
    setCertModeState(c);
  }

  const{useTweaks}=window;
  const TWEAK_DEFAULTS=/*EDITMODE-BEGIN*/{
    "timerOn": false,
    "timerMins": 45,
    "accent": "green",
    "fontSize": "md"
  }/*EDITMODE-END*/;
  const[tweaks,setTweak]=useTweaks(TWEAK_DEFAULTS);

  React.useEffect(()=>{
    const root=document.documentElement;
    if(tweaks.accent==='cyan'){root.style.setProperty('--green','var(--cyan)');root.style.setProperty('--green-bg','var(--cyan-bg)');}
    else if(tweaks.accent==='amber'){root.style.setProperty('--green','var(--amber)');root.style.setProperty('--green-bg','var(--amber-bg)');}
    else{root.style.removeProperty('--green');root.style.removeProperty('--green-bg');}
    document.body.style.fontSize=tweaks.fontSize==='sm'?'13px':tweaks.fontSize==='lg'?'15px':'14px';
  },[tweaks.accent,tweaks.fontSize]);

  // No cert chosen yet → show selection screen
  if(!certMode) return <CertSelectScreen onPick={pickCert}/>;

  function startSession(mode,domainId){
    const s=buildSession(mode,domainId,tweaks,certMode);
    setSession(s);setFinalAnswers(null);setView('running');
  }
  // Records a single answered question immediately (so progress saves even if user exits mid-session)
  function handleAnswer(q, correct){
    setProg(prev => {
      const newProg = JSON.parse(JSON.stringify(prev));
      const today = new Date().toDateString();
      const yesterday = new Date(Date.now()-86400000).toDateString();
      if (newProg.lastStudied !== today) {
        newProg.streak = newProg.lastStudied === yesterday ? newProg.streak+1 : 1;
        newProg.lastStudied = today;
      }
      newProg.totalAnswered++;
      if (!newProg.domainStats[q.d]) newProg.domainStats[q.d] = {answered:0, correct:0};
      newProg.domainStats[q.d].answered++;
      if (correct) {
        newProg.totalCorrect++;
        newProg.domainStats[q.d].correct++;
        newProg.missedIds = newProg.missedIds.filter(id => id !== q.id);
      } else {
        if (!newProg.missedIds.includes(q.id)) newProg.missedIds.push(q.id);
      }
      saveProg(certMode, newProg);
      return newProg;
    });
  }
  function handleComplete(answers){
    setProg(prev => { const np = {...prev, sessionCount: (prev.sessionCount||0)+1}; saveProg(certMode, np); return np; });
    setFinalAnswers(answers);setView('results');
  }
  function handleRetry(){
    setFinalAnswers(null);setView('running');
    setSession(s=>({...s,questions:[...s.questions].sort(()=>Math.random()-0.5)}));
  }
  function switchCert(){pickCert(null);setView('home');}

  const activeTab=view==='running'||view==='results'?'practice':view==='home'?'home':view;

  const renderView=()=>{
    if(view==='home')   return <HomeView prog={prog} setView={setView} onStart={startSession} certMode={certMode}/>;
    if(view==='practice') return <PracticeView certMode={certMode} prog={prog} onStart={startSession}/>;
    if(view==='running'&&session) return <window.QuizMode session={session} onComplete={handleComplete} onAnswer={handleAnswer} onExit={()=>setView('practice')}/>;
    if(view==='results'&&session&&finalAnswers) return <window.QuizResults session={session} finalAnswers={finalAnswers} onHome={()=>setView('home')} onRetry={handleRetry}/>;
    if(view==='learn')    return <window.LearnMode onExit={()=>setView('home')} certMode={certMode}/>;
    if(view==='notes')    return <NotesView setView={setView} setLearnTopic={t=>{window.__learnTopic=t;}}/>;
    if(view==='progress') return <ProgressView prog={prog} onStart={startSession}/>;
    if(view==='final-exam') return <window.FinalExamMode onExit={()=>setView('home')}/>;
    return <HomeView prog={prog} setView={setView} onStart={startSession} certMode={certMode}/>;
  };

  return(
    <div className="app">
      <TopBar activeTab={activeTab} setView={v=>{if(['practice','home','learn','progress','notes','final-exam'].includes(v))setView(v);}} prog={prog} streak={prog.streak} certMode={certMode} onSwitchCert={switchCert}/>
      <main>{renderView()}</main>
      <AppTweaks tweaks={tweaks} setTweak={setTweak} certMode={certMode} onSwitchCert={switchCert}/>
    </div>
  );
}

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