// Flashcards + Quiz. If the guide is generated, read its cards/quiz from
// localStorage; otherwise show the static demo content.

function FlashcardScreen({ subjectId, guideId }) {
  const subjects = useSubjects();
  const subject = subjects.find((s) => s.id === subjectId) || { id: subjectId, name: '(unknown subject)' };
  const [generated, setGenerated] = React.useState(() => findGuideSync(guideId));
  React.useEffect(() => {
    if (generated) return;
    let cancelled = false;
    findGuide(guideId).then((g) => { if (!cancelled) setGenerated(g); });
    return () => { cancelled = true; };
  }, [guideId]);
  const guideMeta = generated;
  const guidePath = `/subject/${subjectId}/guide/${guideId}`;

  const cards = generated ? (generated.content?.flashcards || []) : [];
  const [idx, setIdx] = React.useState(0);
  const [flipped, setFlipped] = React.useState(false);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === ' ') { e.preventDefault(); setFlipped((f) => !f); }
      else if (e.key === 'ArrowRight') { setFlipped(false); setIdx((i) => Math.min(i + 1, cards.length - 1)); }
      else if (e.key === 'ArrowLeft')  { setFlipped(false); setIdx((i) => Math.max(i - 1, 0)); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [cards.length]);

  const card = cards[idx];
  const advance = () => { setFlipped(false); setIdx((i) => Math.min(i + 1, cards.length - 1)); };

  return (
    <Page>
      <PageHeader
        breadcrumb={[
          { label: 'Dashboard', to: '/' },
          subject ? { label: subject.name, to: `/subject/${subject.id}` } : 'Subject',
          guideMeta ? { label: guideMeta.title, to: guidePath } : 'Guide',
          'Flashcards',
        ]}
        sub={<span className="mono">{cards.length === 0 ? '0 cards' : `${idx + 1} / ${cards.length}`}</span>}
        actions={
          <>
            <button className="btn ghost small" onClick={() => { setIdx(0); setFlipped(false); }}>Restart</button>
            <button className="btn ghost small" onClick={() => navigate(guidePath)}>Exit</button>
          </>
        }
      />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '20px 40px', background: 'var(--paper)' }}>
        {cards.length === 0 ? (
          <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 10, padding: 22, textAlign: 'center', maxWidth: 400 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>No flashcards yet</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', margin: '6px 0 14px' }}>This guide doesn't have flashcards. Generate a guide from your own files to get cards.</div>
            <button className="btn blue small" onClick={() => navigate(subject ? `/subject/${subject.id}/upload` : '/')}>Upload files</button>
          </div>
        ) : (
          <>
            <div style={{ position: 'relative', width: 480, height: 280, cursor: 'pointer' }} onClick={() => setFlipped((f) => !f)}>
              <div style={{ position: 'absolute', inset: 0, background: 'white', borderRadius: 12, border: '1px solid var(--line)', transform: 'translate(8px, 10px) rotate(1.5deg)', opacity: 0.7 }} />
              <div style={{ position: 'absolute', inset: 0, background: 'white', borderRadius: 12, border: '1px solid var(--line)', transform: 'translate(4px, 5px) rotate(-1deg)', opacity: 0.85 }} />
              <div style={{ position: 'absolute', inset: 0, background: 'white', borderRadius: 12, border: '1px solid var(--line)', boxShadow: 'var(--shadow-l)', padding: '28px 32px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span className="chip">{subject?.name || 'Subject'}{guideMeta ? ` · ${guideMeta.title}` : ''}</span>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{flipped ? 'BACK' : 'FRONT'}</span>
                </div>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: 10, color: 'var(--ink-mute)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 10 }}>{flipped ? 'Answer' : 'Question'}</div>
                  <div className="display" style={{ fontSize: 22, lineHeight: 1.3, letterSpacing: '-0.01em' }}>
                    {flipped ? card.back : card.front}
                  </div>
                </div>
                <div style={{ textAlign: 'center', color: 'var(--ink-whisper)', fontSize: 10.5 }}>
                  <span className="kbd">Space</span> flip · <span className="kbd">←</span> <span className="kbd">→</span> nav
                </div>
              </div>
            </div>
            <div style={{ marginTop: 20, display: 'flex', gap: 6 }}>
              {[['Again','<1m','var(--coral)','1'],['Hard','6m','oklch(0.78 0.14 60)','2'],['Good','1d','var(--mint)','3'],['Easy','4d','var(--blue)','4']].map(([l,s,c,k]) => (
                <button key={l} onClick={advance} style={{ background: 'white', border: `1.5px solid ${c}`, borderRadius: 8, padding: '8px 16px', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1, minWidth: 76, position: 'relative' }}>
                  <span style={{ fontWeight: 600, fontSize: 12, color: c }}>{l}</span>
                  <span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-mute)' }}>{s}</span>
                  <span className="kbd" style={{ position: 'absolute', top: 3, right: 5, fontSize: 9 }}>{k}</span>
                </button>
              ))}
            </div>
            {idx === cards.length - 1 && (
              <div style={{ marginTop: 14, fontSize: 11, color: 'var(--ink-mute)' }}>
                Last card · <a onClick={(e) => { e.preventDefault(); navigate(`${guidePath}/quiz`); }} href="#" style={{ color: 'var(--blue-deep)', cursor: 'pointer' }}>switch to practice quiz</a>
              </div>
            )}
          </>
        )}
      </div>
    </Page>
  );
}

function QuizScreen({ subjectId, guideId }) {
  const subjects = useSubjects();
  const subject = subjects.find((s) => s.id === subjectId) || { id: subjectId, name: '(unknown subject)' };
  const [generated, setGenerated] = React.useState(() => findGuideSync(guideId));
  React.useEffect(() => {
    if (generated) return;
    let cancelled = false;
    findGuide(guideId).then((g) => { if (!cancelled) setGenerated(g); });
    return () => { cancelled = true; };
  }, [guideId]);
  const guideMeta = generated;
  const guidePath = `/subject/${subjectId}/guide/${guideId}`;

  const questions = generated ? (generated.content?.quiz || []) : [];
  const [idx, setIdx] = React.useState(0);
  const [picks, setPicks] = React.useState([]); // index per question
  const [revealed, setRevealed] = React.useState(false);
  const [showHint, setShowHint] = React.useState(false);

  const q = questions[idx];
  const pick = picks[idx];
  const isCorrect = pick === q?.correctIndex;
  const score = picks.reduce((n, p, i) => n + (p === questions[i]?.correctIndex ? 1 : 0), 0);
  const answered = picks.filter((p) => p != null).length;

  const choose = (i) => {
    if (revealed) return;
    setPicks((arr) => {
      const next = arr.slice();
      next[idx] = i;
      return next;
    });
  };
  const submit = () => setRevealed(true);
  const nextQ = () => {
    setRevealed(false);
    setShowHint(false);
    setIdx((i) => Math.min(i + 1, questions.length - 1));
  };
  const prevQ = () => {
    setRevealed(false);
    setShowHint(false);
    setIdx((i) => Math.max(i - 1, 0));
  };

  return (
    <Page>
      <PageHeader
        breadcrumb={[
          { label: 'Dashboard', to: '/' },
          subject ? { label: subject.name, to: `/subject/${subject.id}` } : 'Subject',
          guideMeta ? { label: guideMeta.title, to: guidePath } : 'Guide',
          'Practice quiz',
        ]}
        sub={<span className="mono">{questions.length === 0 ? '0 questions' : `${answered} of ${questions.length} answered · ${score}/${questions.length}`}</span>}
        actions={<button className="btn ghost small" onClick={() => navigate(guidePath)}>Exit</button>}
      />
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 40px' }}>
        <div style={{ maxWidth: 580, margin: '0 auto' }}>
          {questions.length === 0 ? (
            <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 10, padding: 22, textAlign: 'center' }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>No quiz yet</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', margin: '6px 0 14px' }}>This guide doesn't have a quiz. Generate one from your own files.</div>
              <button className="btn blue small" onClick={() => navigate(subject ? `/subject/${subject.id}/upload` : '/')}>Upload files</button>
            </div>
          ) : (
            <>
              <div style={{ display: 'flex', gap: 3, marginBottom: 16 }}>
                {questions.map((_, i) => {
                  const p = picks[i];
                  const correct = p != null && p === questions[i].correctIndex;
                  const wrong = p != null && p !== questions[i].correctIndex;
                  const fill = correct ? 'var(--mint)' : wrong ? 'var(--coral)' : i === idx ? 'var(--ink)' : 'var(--line)';
                  return <div key={i} style={{ flex: 1, height: 4, borderRadius: 2, background: fill }} />;
                })}
              </div>
              <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-mute)' }}>Question {idx + 1} of {questions.length} · Multiple choice</div>
              <h2 className="display" style={{ fontSize: 20, margin: '4px 0 14px', lineHeight: 1.3 }}>{q.question}</h2>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 16 }}>
                {(q.options || []).map((opt, i) => {
                  const sel = pick === i;
                  const isAnswer = revealed && i === q.correctIndex;
                  const isWrong = revealed && sel && i !== q.correctIndex;
                  const border = isAnswer ? 'var(--mint)' : isWrong ? 'var(--coral)' : sel ? 'var(--blue)' : 'var(--line)';
                  const bg = isAnswer ? 'oklch(0.95 0.04 160)' : isWrong ? 'var(--coral-soft)' : sel ? 'var(--blue-wash)' : 'white';
                  return (
                    <div key={i} onClick={() => choose(i)} style={{
                      padding: '10px 12px', borderRadius: 8, background: bg,
                      border: `1.5px solid ${border}`,
                      display: 'flex', alignItems: 'center', gap: 10,
                      cursor: revealed ? 'default' : 'pointer', fontSize: 12.5,
                    }}>
                      <div style={{ width: 20, height: 20, borderRadius: 10, background: sel || isAnswer ? border : 'white', border: `1.5px solid ${border}`, color: 'white', display: 'grid', placeItems: 'center', fontSize: 9.5, fontWeight: 600, fontFamily: 'var(--font-mono)' }}>
                        {isAnswer ? '✓' : isWrong ? '✗' : sel ? '●' : String.fromCharCode(65 + i)}
                      </div>
                      {opt}
                    </div>
                  );
                })}
              </div>

              {q.hint && !revealed && (
                <div style={{ padding: 12, background: 'var(--paper)', borderRadius: 8, border: '1px dashed var(--line)', marginBottom: 14 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-mute)' }}>💡 Hint</div>
                    {!showHint && <button className="btn ghost small" onClick={() => setShowHint(true)}>Show</button>}
                  </div>
                  {showHint && <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', marginTop: 6 }}>{q.hint}</div>}
                </div>
              )}

              {revealed && (
                <div style={{ padding: 12, background: isCorrect ? 'oklch(0.95 0.04 160)' : 'var(--coral-soft)', borderRadius: 8, border: `1px solid ${isCorrect ? 'var(--mint)' : 'var(--coral)'}`, marginBottom: 14 }}>
                  <div style={{ fontSize: 11.5, fontWeight: 600 }}>{isCorrect ? '✓ Correct' : '✗ Not quite'}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', marginTop: 4 }}>
                    Correct answer: <b>{q.options[q.correctIndex]}</b>
                  </div>
                </div>
              )}

              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <button className="btn ghost small" onClick={prevQ} disabled={idx === 0} style={{ opacity: idx === 0 ? 0.4 : 1 }}>← Previous</button>
                {!revealed
                  ? <button className="btn blue" onClick={submit} disabled={pick == null} style={{ opacity: pick == null ? 0.4 : 1 }}>Check answer</button>
                  : idx < questions.length - 1
                    ? <button className="btn blue" onClick={nextQ}>Next →</button>
                    : <button className="btn blue" onClick={() => navigate(guidePath)}>Finish ({score}/{questions.length})</button>
                }
              </div>
            </>
          )}
        </div>
      </div>
    </Page>
  );
}

Object.assign(window, { FlashcardScreen, QuizScreen });
