// review-deck.jsx — server-backed spaced-repetition review.
// Reads the cards the mastery engine scheduled (review_cards, via the
// get_due_reviews RPC) and grades them with grade_review. These cards are
// created by record_attempt when you get a question wrong or flag low
// confidence, so this is the screen that finally surfaces that data.
//
// Self-contained: inline styles, no dependency on the ideas/lesson CSS.

const RV = {
  wrap:   { maxWidth: 720, margin: '0 auto', padding: '32px 20px', fontFamily: "'DM Sans', system-ui, sans-serif", color: '#2d3142' },
  eyebrow:{ fontSize: 12, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: '#8a8079' },
  h1:     { fontFamily: "'Outfit', sans-serif", fontWeight: 800, fontSize: 26, margin: '4px 0 18px' },
  card:   { background: '#fff', border: '1px solid #ece6da', borderRadius: 16, padding: 24, boxShadow: '0 6px 24px rgba(45,49,66,0.06)' },
  meta:   { display: 'flex', gap: 8, alignItems: 'center', marginBottom: 12, fontSize: 12, color: '#8a8079', fontWeight: 600 },
  chip:   { background: '#f4efe6', borderRadius: 999, padding: '3px 10px' },
  stem:   { fontSize: 18, fontWeight: 600, lineHeight: 1.5, margin: '6px 0 18px' },
  opt:    { display: 'block', width: '100%', textAlign: 'left', padding: '13px 16px', margin: '8px 0', borderRadius: 12, border: '1.5px solid #e5dccb', background: '#fff', fontSize: 15, cursor: 'pointer', fontFamily: 'inherit', color: 'inherit' },
  expl:   { marginTop: 16, padding: 14, borderRadius: 12, background: '#f7f4ee', fontSize: 14, lineHeight: 1.55 },
  footer: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 18 },
  cta:    { background: '#2d3142', color: '#fff', border: 'none', borderRadius: 12, padding: '12px 22px', fontWeight: 700, fontSize: 15, cursor: 'pointer', fontFamily: "'Outfit', sans-serif" },
  ghost:  { background: '#fff', color: '#2d3142', border: '1.5px solid #e5dccb', borderRadius: 12, padding: '12px 22px', fontWeight: 700, fontSize: 15, textDecoration: 'none', display: 'inline-block', fontFamily: "'Outfit', sans-serif" },
  prog:   { fontSize: 13, color: '#8a8079', fontWeight: 600 },
};

function rvPretty(t) {
  return (t || '').replace(/-/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); });
}

function ReviewDeck() {
  const [status, setStatus] = React.useState('loading'); // loading|signedout|empty|reviewing|done|error
  const [cards, setCards]   = React.useState([]);
  const [idx, setIdx]       = React.useState(0);
  const [picked, setPicked] = React.useState(null);
  const [feedback, setFeedback] = React.useState(null);   // {interval} after grading
  const [reviewed, setReviewed] = React.useState(0);
  const cardRef = React.useRef(null);

  React.useEffect(function () {
    let alive = true;
    const db = window.HSC && window.HSC.supabase;
    const auth = window.HSC && window.HSC.auth;
    if (!db || !auth || !auth.ready) { setStatus('error'); return; }
    auth.ready.then(function () {
      if (!alive) return;
      if (!(auth.getUser && auth.getUser())) { setStatus('signedout'); return; }
      db.rpc('get_due_reviews', { p_limit: 20 }).then(function (r) {
        if (!alive) return;
        if (r.error) { setStatus('error'); return; }
        const data = (r.data || []).filter(function (c) { return c && Array.isArray(c.options) && c.options.length; });
        setCards(data);
        setStatus(data.length ? 'reviewing' : 'empty');
      }, function () { if (alive) setStatus('error'); });
    });
    return function () { alive = false; };
  }, []);

  const card = cards[idx];

  // Render any LaTeX in the current card.
  React.useEffect(function () {
    if (cardRef.current && window.renderMathInElement) {
      try {
        window.renderMathInElement(cardRef.current, {
          delimiters: [{ left: '$$', right: '$$', display: true }, { left: '$', right: '$', display: false }],
          throwOnError: false,
        });
      } catch (e) {}
    }
  }, [idx, picked, status]);

  function choose(i) {
    if (picked !== null || !card) return;
    setPicked(i);
    const correct = i === card.correct_index;
    const db = window.HSC && window.HSC.supabase;
    if (db) {
      db.rpc('grade_review', { p_question_id: card.id, p_grade: correct ? 2 : 0 })
        .then(function (r) {
          const row = r && r.data && r.data[0];
          setFeedback({ interval: row ? row.interval_days : null, correct: correct });
        }, function () { setFeedback({ interval: null, correct: correct }); });
    } else {
      setFeedback({ interval: null, correct: correct });
    }
  }

  function next() {
    setReviewed(function (n) { return n + 1; });
    setPicked(null);
    setFeedback(null);
    if (idx + 1 >= cards.length) setStatus('done');
    else setIdx(idx + 1);
  }

  if (status === 'loading') return <div style={RV.wrap}><p style={{ color: '#8a8079' }}>Loading your review deck…</p></div>;

  if (status === 'signedout') return (
    <div style={RV.wrap}>
      <div style={RV.eyebrow}>Spaced repetition</div>
      <h1 style={RV.h1}>Your review deck</h1>
      <div style={RV.card}>
        <p style={{ marginTop: 0, color: '#5a5650' }}>Log in to review the questions your practice has scheduled for today.</p>
        <a style={RV.ghost} href="auth/login.html">Log in</a>
      </div>
    </div>
  );

  if (status === 'error') return (
    <div style={RV.wrap}><div style={RV.card}><p style={{ margin: 0, color: '#8a8079' }}>Couldn't load your review deck. Please refresh.</p></div></div>
  );

  if (status === 'empty' || status === 'done') return (
    <div style={RV.wrap}>
      <div style={RV.eyebrow}>Spaced repetition</div>
      <h1 style={RV.h1}>{status === 'done' ? 'Review complete' : 'All caught up'}</h1>
      <div style={RV.card}>
        <p style={{ marginTop: 0, color: '#5a5650' }}>
          {status === 'done'
            ? 'You reviewed ' + reviewed + ' card' + (reviewed === 1 ? '' : 's') + '. Nice work — they\'re rescheduled for later.'
            : 'Nothing due right now. Cards are added automatically when you miss a question in a quiz or lesson; come back when some fall due.'}
        </p>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <a style={RV.ghost} href="weekly-quiz.html">Take the weekly challenge</a>
          <a style={RV.ghost} href="mastery.html">View your mastery map</a>
        </div>
      </div>
    </div>
  );

  // reviewing
  const opts = card.options || [];
  return (
    <div style={RV.wrap} ref={cardRef}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div>
          <div style={RV.eyebrow}>Spaced repetition</div>
          <h1 style={RV.h1}>Your review deck</h1>
        </div>
        <div style={RV.prog}>{idx + 1} / {cards.length}</div>
      </div>

      <div style={RV.card}>
        <div style={RV.meta}>
          <span style={RV.chip}>{rvPretty(card.subject)}</span>
          <span style={RV.chip}>{rvPretty(card.topic)}</span>
        </div>
        <div style={RV.stem}>{card.stem}</div>

        {opts.map(function (opt, i) {
          let style = Object.assign({}, RV.opt);
          if (picked !== null) {
            if (i === card.correct_index) { style.borderColor = '#6b9b7c'; style.background = '#eef5ef'; }
            else if (i === picked) { style.borderColor = '#c47b8a'; style.background = '#f9eef0'; }
            else { style.opacity = 0.6; }
            style.cursor = 'default';
          }
          return (
            <button key={i} style={style} onClick={function () { choose(i); }} disabled={picked !== null}>
              <strong style={{ marginRight: 8 }}>{String.fromCharCode(65 + i)}</strong>{opt}
            </button>
          );
        })}

        {picked !== null && (
          <div style={RV.expl}>
            <strong>{feedback && feedback.correct ? '✓ Correct.' : '✗ Not quite.'}</strong>
            {card.explanation ? ' ' + card.explanation : ''}
            {feedback && feedback.interval ? <div style={{ marginTop: 8, color: '#8a8079' }}>Next review in {feedback.interval} day{feedback.interval === 1 ? '' : 's'}.</div> : null}
          </div>
        )}

        <div style={RV.footer}>
          <a style={{ ...RV.prog, textDecoration: 'none', color: '#8a8079' }} href="mastery.html">Exit to mastery map</a>
          {picked !== null && (
            <button style={RV.cta} onClick={next}>{idx + 1 >= cards.length ? 'Finish' : 'Next card'}</button>
          )}
        </div>
      </div>
    </div>
  );
}

window.ReviewDeck = ReviewDeck;
