// ── ComprehensionExercisePage ─────────────────────────────────────────────────

function ComprehensionExercisePage({ chapterId, navigate }) {
  const [phase, setPhase] = React.useState('loading'); // loading | exercise | results | error
  const [exercise, setExercise] = React.useState(null);
  const [answers, setAnswers] = React.useState({});   // { [sequence_number]: chosen_index }
  const [results, setResults] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');
  const [startedAt] = React.useState(Date.now());

  React.useEffect(() => { loadExercise(); }, [chapterId]);

  async function loadExercise() {
    setPhase('loading');
    setError('');
    try {
      const r = await fetch(`/api/children/chapters/${chapterId}/exercise`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
      });
      const body = await r.json();
      if (!r.ok) throw new Error(body.error || 'Failed to load exercise');

      if (body.no_approved_questions) {
        setPhase('waiting');
        setError(body.message || 'No exercises ready yet');
        return;
      }

      setExercise(body);
      setAnswers({});
      setPhase('exercise');
    } catch (err) {
      setError(err.message || 'Could not load exercise');
      setPhase('error');
    }
  }

  async function handleSubmit() {
    if (!exercise) return;
    const orderedAnswers = exercise.questions.map((q) => answers[q.sequence_number] ?? -1);
    if (orderedAnswers.some((a) => a === -1)) return;

    setSubmitting(true);
    try {
      const r = await fetch(`/api/children/comprehension/${exercise.exercise_id}/submit`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ answers: orderedAnswers }),
      });
      const body = await r.json();
      if (!r.ok) throw new Error(body.error || 'Submit failed');
      setResults(body);
      setPhase('results');
    } catch (err) {
      setError(err.message || 'Submit failed');
    } finally {
      setSubmitting(false);
    }
  }

  function allAnswered() {
    if (!exercise) return false;
    return exercise.questions.every((q) => answers[q.sequence_number] !== undefined);
  }

  function formatTime(seconds) {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return m > 0 ? `${m} min ${s}s` : `${s}s`;
  }

  if (phase === 'loading') {
    return (
      <div className="child-shell">
        <div className="chapter-page-card">
          <button className="chapter-back-btn" onClick={() => navigate(`/chapter/${chapterId}`)}>← Back</button>
          <p className="child-loading" style={{ marginTop: '2rem' }}>Loading exercise…</p>
        </div>
      </div>
    );
  }

  if (phase === 'error') {
    return (
      <div className="child-shell">
        <div className="chapter-page-card">
          <button className="chapter-back-btn" onClick={() => navigate(`/chapter/${chapterId}`)}>← Back</button>
          <p className="subject-error" style={{ marginTop: '1.5rem' }}>{error}</p>
          <button className="child-login-btn" style={{ marginTop: '1rem' }} onClick={loadExercise}>Retry</button>
        </div>
      </div>
    );
  }

  if (phase === 'waiting') {
    return (
      <div className="child-shell">
        <div className="chapter-page-card">
          <button className="chapter-back-btn" onClick={() => navigate(`/chapter/${chapterId}`)}>← Back</button>
          <div style={{ textAlign: 'center', padding: '2rem 1rem' }}>
            <div style={{ fontSize: '2rem', marginBottom: '1rem' }}>📖</div>
            <p style={{ color: 'var(--text-muted)', marginBottom: '1.5rem' }}>{error}</p>
            <button
              className="child-login-btn"
              style={{ maxWidth: '240px', margin: '0 auto' }}
              onClick={async () => {
                try {
                  await fetch(`/api/children/chapters/${chapterId}/request-questions`, {
                    method: 'POST',
                    credentials: 'include',
                  });
                } catch (_) {}
              }}
            >
              Let Sudha know I'm waiting
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (phase === 'results' && results) {
    return (
      <div className="child-shell">
        <div className="chapter-page-card">
          <button className="chapter-back-btn" onClick={() => navigate(`/chapter/${chapterId}`)}>← Back</button>

          {results.level_up && (
            <div className="level-up-banner" style={{ marginBottom: '1.5rem' }}>
              {results.band_crossed
                ? `Band up! ${results.old_band} → ${results.new_band}`
                : `Level up! ${results.old_level} → ${results.new_level}`}
            </div>
          )}

          <div style={{ textAlign: 'center', marginBottom: '1.5rem' }}>
            <div style={{ fontSize: '2rem', fontWeight: 700, color: results.correct_count === results.total_questions ? 'var(--green)' : 'var(--text)' }}>
              {results.correct_count} / {results.total_questions} correct
            </div>
            <div style={{ color: 'var(--text-muted)', marginTop: '0.25rem', fontSize: '0.875rem' }}>
              Time: {formatTime(results.seconds_taken)}
            </div>
          </div>

          <div className="comp-results-list">
            {results.results.map((r) => (
              <div key={r.sequence_number} className={`comp-result-item ${r.is_correct ? 'comp-result-item--correct' : 'comp-result-item--wrong'}`}>
                <div className="comp-result-header">
                  <span className="comp-result-num">Q{r.sequence_number}</span>
                  <span className="comp-result-verdict">{r.is_correct ? '✓ Correct' : '✗ Incorrect'}</span>
                </div>
                {!r.is_correct && exercise && (() => {
                  const q = exercise.questions.find((q) => q.sequence_number === r.sequence_number);
                  return q ? (
                    <div className="comp-result-detail tamil-font">
                      <div>You chose: {q.options[r.chosen_index]}</div>
                      <div>Correct: {q.options[r.correct_index]}</div>
                    </div>
                  ) : null;
                })()}
                {r.explanation && (
                  <div className="comp-result-explanation tamil-font">{r.explanation}</div>
                )}
              </div>
            ))}
          </div>

          {!results.level_up && (
            <p style={{ textAlign: 'center', color: 'var(--text-muted)', margin: '1.5rem 0 0.5rem', fontSize: '0.9rem' }}>
              Try another exercise to practice more.
            </p>
          )}

          <button
            className="comp-submit-btn"
            style={{ marginTop: '1rem' }}
            onClick={loadExercise}
          >
            Next exercise
          </button>
        </div>
      </div>
    );
  }

  // Exercise phase
  if (!exercise) return null;

  return (
    <div className="child-shell">
      <div className="chapter-page-card comp-exercise-card">
        <button className="chapter-back-btn" onClick={() => navigate(`/chapter/${chapterId}`)}>← Back</button>

        <div style={{ marginBottom: '0.5rem', color: 'var(--text-muted)', fontSize: '0.875rem' }}>
          Level {exercise.level} · Reading Comprehension
        </div>

        <div className="comp-passage tamil-font">
          {exercise.passage}
        </div>

        <hr className="comp-divider" />

        <div className="comp-questions">
          {exercise.questions.map((q) => (
            <div key={q.sequence_number} className="comp-question-block">
              <div className="comp-question-header">
                Question {q.sequence_number} of {exercise.questions.length}
              </div>
              <div className="comp-question-text tamil-font">{q.question_text}</div>
              <div className="comp-options">
                {q.options.map((opt, i) => {
                  const selected = answers[q.sequence_number] === i;
                  return (
                    <button
                      key={i}
                      className={`comp-option-btn${selected ? ' comp-option-btn--selected' : ''}`}
                      onClick={() => setAnswers((prev) => ({ ...prev, [q.sequence_number]: i }))}
                    >
                      <span className="comp-option-letter">{String.fromCharCode(65 + i)}.</span>
                      <span className="comp-option-text tamil-font">{opt}</span>
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        {error && <p className="child-error">{error}</p>}

        <button
          className="comp-submit-btn"
          disabled={!allAnswered() || submitting}
          onClick={handleSubmit}
        >
          {submitting ? 'Submitting…' : 'Submit all answers'}
        </button>
      </div>
    </div>
  );
}
