// ── ChapterActivityPage ───────────────────────────────────────────────────────

function ChapterActivityPage({ childId, chapterId, navigate }) {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');
  const [expandedIds, setExpandedIds] = React.useState(new Set());
  const [loadingMore, setLoadingMore] = React.useState(false);

  async function load(offset) {
    try {
      const r = await fetch(
        `/api/parents/children/${childId}/chapters/${chapterId}/activity?limit=20&offset=${offset}`,
        { credentials: 'include' }
      );
      const body = await r.json();
      if (!r.ok) throw new Error(body.error || 'Failed to load');
      if (offset === 0) {
        setData(body);
      } else {
        setData((prev) => ({
          ...prev,
          questions: [...prev.questions, ...body.questions],
          pagination: body.pagination,
        }));
      }
    } catch (err) {
      setError(err.message);
    }
  }

  React.useEffect(() => {
    load(0).finally(() => setLoading(false));
  }, [childId, chapterId]);

  async function loadMore() {
    if (!data) return;
    setLoadingMore(true);
    await load(data.pagination.offset + data.pagination.limit);
    setLoadingMore(false);
  }

  function toggleExpand(qId) {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      next.has(qId) ? next.delete(qId) : next.add(qId);
      return next;
    });
  }

  function timeAgo(dateStr) {
    if (!dateStr) return '';
    const diff = Date.now() - new Date(dateStr).getTime();
    const mins = Math.floor(diff / 60000);
    if (mins < 1) return 'just now';
    if (mins < 60) return `${mins}m ago`;
    const hrs = Math.floor(mins / 60);
    if (hrs < 24) return `${hrs}h ago`;
    return `${Math.floor(hrs / 24)}d ago`;
  }

  function statusBadge(q) {
    // Priority: challenge-won > revealed > eventually correct > correct first try > not yet correct
    if (q.ended_with_levelup_via_challenge) return { label: '⭐ won challenge', cls: 'badge--challenge' };
    if (q.has_reveal) return { label: '📖 revealed', cls: 'badge--reveal' };
    if (q.ended_with_flag && !q.was_eventually_correct) return { label: '⚑ flagged', cls: 'badge--flagged' };
    if (q.was_eventually_correct && q.total_attempts === 1) return { label: '✓ correct', cls: 'badge--correct' };
    if (q.was_eventually_correct) return { label: '✓ eventually correct', cls: 'badge--eventual' };
    return { label: '✗ not yet correct', cls: 'badge--wrong' };
  }

  if (loading) {
    return (
      <div className="parent-shell">
        <div className="parent-card">
          <button className="child-detail-back" onClick={() => navigate(`/child/${childId}`)}>← Back</button>
          <p className="parent-loading">Loading…</p>
        </div>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="parent-shell">
        <div className="parent-card">
          <button className="child-detail-back" onClick={() => navigate(`/child/${childId}`)}>← Back</button>
          <p className="parent-error">{error || 'Could not load'}</p>
        </div>
      </div>
    );
  }

  const { chapter, child, progress, pagination, questions } = data;

  return (
    <div className="parent-shell">
      <div className="parent-card">
        <button className="child-detail-back" onClick={() => navigate(`/child/${childId}`)}>
          ← Back to {child.display_name}'s overview
        </button>

        <div className="child-detail-header">
          <div className="child-detail-name">{chapter.subject_emoji} {chapter.subject_name} &gt; {chapter.name}</div>
          <div className="child-detail-meta">
            Level {progress.current_level} · {progress.band} · {progress.correct_count}/{progress.questions_answered} correct
          </div>
        </div>

        <div className="chap-activity-summary">
          Questions {child.display_name} has tried in this chapter
          <span className="chap-activity-count">
            {' '}(showing {questions.length} of {pagination.total_questions})
          </span>
        </div>

        {questions.length === 0 ? (
          <p className="dash-empty">No questions tried in this chapter yet.</p>
        ) : (
          questions.map((q) => (
            <QuestionCard
              key={q.question_id}
              q={q}
              childName={child.display_name}
              expanded={expandedIds.has(q.question_id)}
              onToggle={() => toggleExpand(q.question_id)}
              statusBadge={statusBadge(q)}
              timeAgo={timeAgo}
            />
          ))
        )}

        {pagination.has_more && (
          <button
            className="activity-load-more-btn"
            disabled={loadingMore}
            onClick={loadMore}
          >
            {loadingMore ? 'Loading…' : 'Load more'}
          </button>
        )}
      </div>
    </div>
  );
}

// ── QuestionCard ──────────────────────────────────────────────────────────────

function QuestionCard({ q, childName, expanded, onToggle, statusBadge, timeAgo }) {
  const cardRef = React.useRef(null);

  React.useEffect(() => {
    if (!expanded || !cardRef.current) return;
    if (typeof window.renderMathInElement !== 'function') return;
    try {
      window.renderMathInElement(cardRef.current, {
        delimiters: [{ left: '$$', right: '$$', display: true }, { left: '$', right: '$', display: false }],
        throwOnError: false,
      });
    } catch {}
  }, [expanded]);

  const preview = q.question_text.length > 80 ? q.question_text.slice(0, 80) + '…' : q.question_text;

  return (
    <div className={`q-card${expanded ? ' q-card--expanded' : ''}`} onClick={onToggle} ref={cardRef}>
      <div className="q-card-header">
        <div className="q-card-preview">{preview}</div>
        <span className={`q-status-badge ${statusBadge.cls}`}>{statusBadge.label}</span>
      </div>
      <div className="q-card-meta">
        {q.total_attempts} attempt{q.total_attempts !== 1 ? 's' : ''} · last {timeAgo(q.last_attempted_at)}
      </div>

      {expanded && (
        <div className="q-card-body" onClick={(e) => e.stopPropagation()}>
          <div className="attempt-detail-label">Full question</div>
          <div className="attempt-detail-question">{q.question_text}</div>

          {q.correct_answer_revealed && (
            <div className="attempt-detail-answer-box">
              <div className="attempt-detail-label">Stored correct answer</div>
              <div className="attempt-detail-answer">{q.correct_answer_revealed}</div>
              {q.explanation_revealed && (
                <div className="attempt-detail-explanation">{q.explanation_revealed}</div>
              )}
            </div>
          )}

          <div className="attempt-detail-label" style={{ marginTop: '0.75rem' }}>
            All attempts by {childName}
          </div>
          {q.attempts.map((att, i) => (
            <div key={att.attempt_id} className="attempt-detail-hist-row">
              <span className={`attempt-hist-icon attempt-icon--${att.is_correct ? 'correct' : 'wrong'}`}>
                {att.is_correct ? '✓' : '✗'}
              </span>
              <span className="attempt-hist-num">{i + 1}.</span>
              <span className="attempt-hist-answer">
                {att.typed_answer != null ? att.typed_answer : att.chosen_index != null ? `Option ${att.chosen_index + 1}` : '—'}
              </span>
              <span className="attempt-hist-time">{att.seconds_taken}s</span>
              <span className="attempt-hist-level">Lv {att.level_at_attempt}</span>
              {att.caused_level_up && <span className="attempt-tag attempt-tag--levelup">↑ up</span>}
            </div>
          ))}
        </div>
      )}

      <div className="q-card-toggle">{expanded ? '▲' : '▼'}</div>
    </div>
  );
}
