/* eslint-disable */
// Session view — drives a queue of cards through the chosen mode

const Session = ({ words, state, setState, mode, level, onExit }) => {
  // Build queue: due cards first, then new
  const queue = useMemo(() => {
    const levelWords = words.filter(w => w.cefr === level);
    const due = [];
    const fresh = [];
    levelWords.forEach(w => {
      const c = state.cards[w.id];
      if (!c) fresh.push(w);
      else if (window.SM2.isDue(c)) due.push(w);
    });
    // Shuffle fresh, sort due by oldest-due-first
    fresh.sort(() => Math.random() - 0.5);
    due.sort((a,b) => (state.cards[a.id]?.due||0) - (state.cards[b.id]?.due||0));
    return [...due, ...fresh].slice(0, 50);
  }, []); // freeze on mount

  const [idx, setIdx] = useState(0);
  const [enriched, setEnriched] = useState(null);
  const [loading, setLoading] = useState(true);
  const [studied, setStudied] = useState(0);
  const [correct, setCorrect] = useState(0);
  const [gradeReady, setGradeReady] = useState(false);
  const [poolTick, setPoolTick] = useState(0); // forces re-render when distractor pool grows

  // Prefetch a small distractor pool of common words at this level (for choice/listen modes)
  useEffect(() => {
    const levelWords = words.filter(w => w.cefr === level);
    const sample = levelWords.sort(() => Math.random() - 0.5).slice(0, 12);
    sample.forEach(w => {
      if (!window.getEnriched(w.id)) {
        window.enrichWord(w).then(() => setPoolTick(t => t + 1));
      }
    });
  }, []);

  const current = queue[idx];

  useEffect(() => {
    setGradeReady(false);
  }, [current?.id, mode]);

  // Enrich current + prefetch next
  useEffect(() => {
    if (!current) return;
    let cancelled = false;
    setLoading(true);
    setEnriched(window.getEnriched(current.id));
    window.enrichWord(current).then(e => {
      if (!cancelled) {
        setEnriched(e);
        setLoading(false);
      }
    });
    // Prefetch next 2
    [queue[idx+1], queue[idx+2]].filter(Boolean).forEach(w => {
      if (!window.getEnriched(w.id)) window.enrichWord(w);
    });
    return () => { cancelled = true; };
  }, [idx, current?.id]);

  const handleGrade = useCallback((grade) => {
    if (!current) return;
    const fn = window.SM2[grade];
    const newCard = fn(state.cards[current.id] || window.SM2.init());
    setGradeReady(false);

    setState(s => {
      let next = { ...s, cards: { ...s.cards, [current.id]: newCard }};
      next = window.VocabStore.recordReview(next, current.id);
      next = window.VocabStore.bumpStreak(next);
      return next;
    });

    setStudied(n => n+1);
    if (grade !== 'again') setCorrect(n => n+1);

    if (idx + 1 >= queue.length) {
      // Session complete — show summary handled below
      setIdx(idx + 1);
    } else {
      setIdx(idx + 1);
    }
  }, [current, idx, queue.length, state.cards, setState]);

  const toggleStar = () => {
    if (!current) return;
    setState(s => ({ ...s, starred: { ...s.starred, [current.id]: !s.starred[current.id] }}));
  };

  // Keyboard
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onExit();
      if (window.OxfordKeyboard.shouldHandleGradeShortcut(e, gradeReady)) {
        e.preventDefault();
        handleGrade(window.OxfordKeyboard.gradeForKey(e.key));
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [gradeReady, handleGrade, onExit]);

  // Empty queue
  if (queue.length === 0) {
    return <SessionEmpty onExit={onExit} level={level}/>;
  }

  // Session complete
  if (idx >= queue.length) {
    return <SessionDone studied={studied} correct={correct} streak={state.streak.count} onExit={onExit}/>;
  }

  const ModeComp = {
    flashcard: window.FlashcardMode,
    choice:    window.ChoiceMode,
    listen:    window.ListenMode,
    cloze:     window.ClozeMode,
  }[mode] || window.FlashcardMode;

  const starred = !!state.starred[current.id];
  const pool = words.filter(w => w.cefr === level);

  return (
    <div style={{ minHeight: '100vh', display:'flex', flexDirection:'column' }}>
      {/* Top bar */}
      <header style={{
        display:'flex', alignItems:'center', justifyContent:'space-between', gap:14,
        padding:'14px 22px', borderBottom:'1px solid var(--rule)',
        background: 'var(--paper-0)', position:'sticky', top:0, zIndex:10,
      }}>
        <button className="btn ghost" onClick={onExit} style={{ padding:'6px 12px', fontSize:13 }}>← Back</button>

        <div style={{ flex:1, display:'flex', alignItems:'center', gap:14, justifyContent:'center' }}>
          <span className="mono" style={{ fontSize:11, color:'var(--ink-faded)', letterSpacing:'0.1em' }}>
            {idx+1} / {queue.length}
          </span>
          <div style={{
            flex:1, maxWidth: 280, height: 6,
            background:'var(--rule-soft)', borderRadius:0, position:'relative', overflow:'hidden',
          }}>
            <div style={{
              position:'absolute', left:0, top:0, bottom:0,
              width: `${((idx)/queue.length)*100}%`,
              background:'var(--ink)',
              transition:'width 0.4s cubic-bezier(0.4,0,0.2,1)',
            }}/>
          </div>
          <span className="mono" style={{ fontSize:11, color:'var(--green-ok)' }}>
            ✓ {correct}
          </span>
        </div>

        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontSize:11, fontFamily:'var(--font-mono)', color:'var(--ink-faded)', textTransform:'uppercase', letterSpacing:'0.1em' }}>
            {modeLabel(mode)}
          </span>
        </div>
      </header>

      {/* Card area */}
      <main style={{ flex:1, padding:'28px 20px', display:'flex', alignItems:'center', justifyContent:'center' }}>
        {loading && !enriched ? (
          <LoadingCard word={current}/>
        ) : (
          <ModeComp
            key={current.id}
            word={enriched}
            pool={enriched ? words.map(w => window.getEnriched(w.id) || w).filter(w => w.cefr === level && w.zh) : []}
            onGrade={handleGrade}
            onGradeReadyChange={setGradeReady}
            onStar={toggleStar}
            starred={starred}
          />
        )}
      </main>

      {/* Hint footer */}
      <footer style={{ padding:'10px 20px', textAlign:'center', borderTop:'1px solid var(--rule-soft)', color:'var(--ink-ghost)', fontSize:11, fontFamily:'var(--font-mono)', letterSpacing:'0.08em', textTransform:'uppercase' }}>
        Esc to exit · after answer: 1 = Again · 2 = Hard · 3 = Good · 4 = Easy
      </footer>
    </div>
  );
};

const modeLabel = (m) => ({
  flashcard:'Flashcard',choice:'Choice',listen:'Listening',cloze:'Cloze',
})[m] || m;

const LoadingCard = ({ word }) => (
  <PaperCard rotate={-0.4} style={{ width:'100%', maxWidth:640, minHeight: 400, padding:'52px 48px', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:14 }}>
    <CEFRChip level={word.cefr}/>
    <div className="serif" style={{ fontSize:64, fontWeight:500, lineHeight:1, opacity:0.85 }}>{word.word}</div>
    <div style={{ fontSize:12, fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'0.2em', color:'var(--ink-faded)' }}>{word.pos}</div>
    <div style={{ marginTop:18, display:'flex', gap:6, alignItems:'center', color:'var(--ink-faded)', fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.1em' }}>
      <span className="loading-dot"/>
      <span className="loading-dot" style={{ animationDelay:'0.15s' }}/>
      <span className="loading-dot" style={{ animationDelay:'0.3s' }}/>
      <span style={{ marginLeft:8 }}>looking up definition</span>
    </div>
    <style>{`
      .loading-dot { width:6px;height:6px;border-radius:50%;background:var(--ink-faded);display:inline-block;animation: bounce 1s infinite; }
      @keyframes bounce { 0%,80%,100%{transform:translateY(0);opacity:0.4;} 40%{transform:translateY(-4px);opacity:1;} }
    `}</style>
  </PaperCard>
);

const SessionEmpty = ({ onExit, level }) => (
  <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', padding: 20 }}>
    <PaperCard style={{ padding:'48px 56px', textAlign:'center', maxWidth:520 }}>
      <div className="marginalia" style={{ fontSize:36, marginBottom:8 }}>All caught up ✓</div>
      <h2 className="serif" style={{ fontSize:28, fontWeight:500, margin:'8px 0 6px' }}>No cards due in {level}</h2>
      <p style={{ color:'var(--ink-soft)', fontSize:14, lineHeight:1.5, margin:'0 auto 24px', maxWidth:380 }}>
        Come back later for spaced reviews — or pick another level to keep learning.
      </p>
      <button className="btn primary" onClick={onExit}>Back to dashboard</button>
    </PaperCard>
  </div>
);

const SessionDone = ({ studied, correct, streak, onExit }) => {
  const pct = studied ? Math.round((correct/studied)*100) : 0;
  return (
    <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}>
      <PaperCard style={{ padding:'48px 56px', textAlign:'center', maxWidth:560, position:'relative' }}>
        <span className="stamp" style={{ position:'absolute', top:24, right:24, color:'var(--green-ok)', transform:'rotate(8deg)' }}>Complete</span>
        <div className="marginalia" style={{ fontSize:32, color:'var(--red-stamp)' }}>good work</div>
        <h2 className="serif" style={{ fontSize:34, fontWeight:500, margin:'8px 0 4px' }}>Session complete</h2>
        <div style={{ color:'var(--ink-faded)', fontSize:13, fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'0.15em' }}>
          {new Date().toLocaleDateString()}
        </div>

        <hr className="rule-double" style={{ margin:'24px 0' }}/>

        <div style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:20 }}>
          <SummaryStat label="Studied" value={studied}/>
          <SummaryStat label="Correct" value={`${pct}%`}/>
          <SummaryStat label="Streak" value={`${streak} 🔥`}/>
        </div>

        <div style={{ marginTop:32, display:'flex', gap:10, justifyContent:'center' }}>
          <button className="btn ghost" onClick={onExit}>Done</button>
          <button className="btn primary" onClick={() => location.reload()}>Another session</button>
        </div>
      </PaperCard>
    </div>
  );
};

const SummaryStat = ({ label, value }) => (
  <div>
    <div style={{ fontSize:11, fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'0.18em', color:'var(--ink-faded)' }}>{label}</div>
    <div className="serif" style={{ fontSize:36, fontWeight:500, marginTop:4 }}>{value}</div>
  </div>
);

window.Session = Session;
