// ── ChildDetailPage ────────────────────────────────────────────────────────────

function ChildDetailPage({ childId, navigate }) {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');
  const [resolvingId, setResolvingId] = React.useState(null);
  const [correctingId, setCorrectingId] = React.useState(null);
  const [correctionInput, setCorrectionInput] = React.useState('');
  const [expandedAttempts, setExpandedAttempts] = React.useState(new Set());
  const [attemptDetails, setAttemptDetails] = React.useState({});
  const [moreAttempts, setMoreAttempts] = React.useState([]);
  const [morePagination, setMorePagination] = React.useState(null);
  const [loadingMore, setLoadingMore] = React.useState(false);

  async function load() {
    setLoading(true);
    setError('');
    try {
      const r = await fetch(`/api/parents/children/${childId}/activity`, { credentials: 'include' });
      const body = await r.json();
      if (!r.ok) throw new Error(body.error || 'Failed to load');
      setData(body);
    } catch (err) {
      setError(err.message || 'Could not load child activity');
    } finally {
      setLoading(false);
    }
  }

  React.useEffect(() => { load(); }, [childId]);

  async function resolveFlag(flagId, action, correctedAnswer) {
    setResolvingId(flagId);
    try {
      const body = { action };
      if (action === 'corrected') body.corrected_answer = correctedAnswer;
      const r = await fetch(`/api/parents/flags/${flagId}/resolve`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      if (!r.ok) throw new Error();
      setCorrectingId(null);
      setCorrectionInput('');
      await load();
    } catch {
      // show nothing — just re-enable buttons
    } finally {
      setResolvingId(null);
    }
  }

  async function toggleAttemptExpand(attemptId) {
    const next = new Set(expandedAttempts);
    if (next.has(attemptId)) {
      next.delete(attemptId);
    } else {
      next.add(attemptId);
      if (!attemptDetails[attemptId]) {
        try {
          const r = await fetch(`/api/parents/children/${childId}/attempts/${attemptId}`, { credentials: 'include' });
          const body = await r.json();
          if (r.ok) setAttemptDetails((prev) => ({ ...prev, [attemptId]: body }));
        } catch {}
      }
    }
    setExpandedAttempts(next);
  }

  async function loadMoreAttempts() {
    const offset = 20 + moreAttempts.length;
    setLoadingMore(true);
    try {
      const r = await fetch(`/api/parents/children/${childId}/activity/more?limit=20&offset=${offset}`, { credentials: 'include' });
      const body = await r.json();
      if (r.ok) {
        setMoreAttempts((prev) => [...prev, ...body.attempts]);
        setMorePagination(body.pagination);
      }
    } catch {}
    finally { setLoadingMore(false); }
  }

  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`;
  }

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

  if (error) {
    return (
      <div className="parent-shell">
        <div className="parent-card">
          <button className="child-detail-back" onClick={() => navigate('')}>← Back</button>
          <p className="parent-error">{error}</p>
        </div>
      </div>
    );
  }

  const { child, per_chapter, recent_attempts, flag_queue = [], reveal_log = [], daily_activity = [] } = data;

  const celebrations = flag_queue.filter((f) => f.is_celebration);
  const needsAttention = flag_queue.filter((f) => !f.is_celebration);

  const revealsThisWeek = reveal_log.filter(
    (r) => Date.now() - new Date(r.revealed_at).getTime() < 7 * 24 * 60 * 60 * 1000
  ).length;

  function flagTypeLabel(f) {
    if (f.flag_type === 'repeat') return 'Reported as seen before';
    if (f.flag_type === 'broken') return 'Reported as broken or incomplete';
    if (f.flag_type === 'challenge') {
      if (f.validator_verdict === 'child_wrong') return 'Answer challenge — student incorrect';
      if (f.validator_verdict === 'unclear') return 'Answer challenge — unclear';
      return 'Answer challenge';
    }
    return f.flag_type;
  }

  return (
    <div className="parent-shell">
      <div className="parent-card">
        <button className="child-detail-back" onClick={() => navigate('')}>← Back</button>

        <div className="child-detail-header">
          <div className="child-detail-name">{child.display_name}</div>
          <div className="child-detail-meta">Class {child.class_number} · {child.board}</div>
        </div>

        {/* ── Section A: Celebrations ── */}
        {celebrations.length > 0 && (
          <div className="detail-section celebration-section">
            <div className="detail-section-title">⭐ {child.display_name} challenged a question and was right</div>
            {celebrations.map((f) => (
              <div key={f.flag_id} className="flag-card flag-card--celebration">
                <div className="flag-card-preview">{f.question_text_preview}</div>
                <div className="flag-card-meta">{f.chapter_name} · {timeAgo(f.flagged_at)}</div>
                {f.validator_reasoning && (
                  <div className="flag-card-validator">Senior teacher: {f.validator_reasoning}</div>
                )}
                {f.validator_suggested_answer && (
                  <div className="flag-card-suggested">Suggested answer: <strong>{f.validator_suggested_answer}</strong></div>
                )}

                {correctingId === f.flag_id ? (
                  <div className="correction-inline">
                    <input
                      className="parent-input"
                      type="text"
                      value={correctionInput}
                      onChange={(e) => setCorrectionInput(e.target.value)}
                      placeholder="Corrected answer"
                      style={{ marginBottom: '0.5rem' }}
                    />
                    <div className="flag-card-actions">
                      <button
                        className="flag-action-btn flag-action-btn--keep"
                        disabled={resolvingId === f.flag_id || !correctionInput.trim()}
                        onClick={() => resolveFlag(f.flag_id, 'corrected', correctionInput.trim())}
                      >Save correction</button>
                      <button className="flag-action-btn flag-action-btn--dismiss" onClick={() => setCorrectingId(null)}>Cancel</button>
                    </div>
                  </div>
                ) : (
                  <div className="flag-card-actions">
                    <button
                      className="flag-action-btn flag-action-btn--keep"
                      disabled={resolvingId === f.flag_id}
                      onClick={() => { setCorrectingId(f.flag_id); setCorrectionInput(f.validator_suggested_answer || ''); }}
                    >✓ Correct the question</button>
                    <button
                      className="flag-action-btn flag-action-btn--deactivate"
                      disabled={resolvingId === f.flag_id}
                      onClick={() => resolveFlag(f.flag_id, 'deactivated')}
                    >Deactivate</button>
                    <button
                      className="flag-action-btn flag-action-btn--dismiss"
                      disabled={resolvingId === f.flag_id}
                      onClick={() => resolveFlag(f.flag_id, 'dismissed')}
                    >Dismiss validator</button>
                  </div>
                )}
                <div className="flag-help-text">
                  Correct = update stored answer · Deactivate = remove question · Dismiss = trust original answer
                </div>
              </div>
            ))}
          </div>
        )}

        {/* ── Section B: Flags needing attention ── */}
        {needsAttention.length > 0 && (
          <div className="detail-section">
            <div className="detail-section-title">Needs your attention ({needsAttention.length})</div>
            {needsAttention.map((f) => (
              <div key={f.flag_id} className="flag-card">
                <div className="flag-card-type-label">{flagTypeLabel(f)}</div>
                <div className="flag-card-preview">{f.question_text_preview}</div>
                <div className="flag-card-meta">
                  {f.chapter_name} · {timeAgo(f.flagged_at)}
                  {f.wrong_attempts_before_flag > 0 && ` · Tried ${f.wrong_attempts_before_flag}× before flagging`}
                </div>
                {f.note && <div className="flag-card-note">"{f.note}"</div>}
                {f.validator_reasoning && (
                  <div className="flag-card-validator">Senior teacher: {f.validator_reasoning}</div>
                )}
                <div className="flag-card-actions">
                  <button className="flag-action-btn flag-action-btn--keep" disabled={resolvingId === f.flag_id}
                    onClick={() => resolveFlag(f.flag_id, 'kept_active')}>Keep active</button>
                  <button className="flag-action-btn flag-action-btn--deactivate" disabled={resolvingId === f.flag_id}
                    onClick={() => resolveFlag(f.flag_id, 'deactivated')}>Deactivate</button>
                  <button className="flag-action-btn flag-action-btn--dismiss" disabled={resolvingId === f.flag_id}
                    onClick={() => resolveFlag(f.flag_id, 'dismissed')}>Dismiss</button>
                </div>
                <div className="flag-help-text">Deactivate = remove from app · Keep/Dismiss = clear the flag</div>
              </div>
            ))}
          </div>
        )}

        {/* ── Section C: Per-chapter progress ── */}
        <div className="detail-section">
          <div className="detail-section-title">Chapters</div>
          {per_chapter.length === 0 ? (
            <p className="dash-empty">No chapter activity yet.</p>
          ) : (
            per_chapter.map((ch) => (
              <button
                key={ch.chapter_id}
                className="chapter-progress-row chapter-progress-row--tappable"
                onClick={() => navigate(`/child/${childId}/chapter/${ch.chapter_id}`)}
              >
                <div className="chapter-progress-info">
                  <div className="chapter-progress-name">{ch.subject_emoji} {ch.chapter_name}</div>
                  <div className="chapter-progress-sub">
                    {ch.correct_count}/{ch.questions_answered} correct · {Math.round(ch.accuracy * 100)}%
                  </div>
                </div>
                <div className="chapter-progress-right">
                  <div className="chapter-level-badge">{ch.band} · Lv {ch.current_level}</div>
                  <div className="chapter-time">{timeAgo(ch.last_seen_at)} →</div>
                </div>
              </button>
            ))
          )}
        </div>

        {/* ── Section D: Last 7 days ── */}
        <div className="detail-section">
          <div className="detail-section-title">Last 7 days</div>
          <DailyActivityGrid dailyActivity={daily_activity} />
        </div>

        {/* ── Section E: Recent activity ── */}
        <div className="detail-section">
          <div className="detail-section-title">
            Recent activity
            {revealsThisWeek > 0 && (
              <span className="reveals-week-badge"> · {revealsThisWeek} reveal{revealsThisWeek > 1 ? 's' : ''} this week</span>
            )}
          </div>
          {recent_attempts.length === 0 ? (
            <p className="dash-empty">No attempts yet.</p>
          ) : (
            [...recent_attempts, ...moreAttempts].map((a) => (
              <AttemptRow
                key={a.attempt_id}
                attempt={a}
                childName={child.display_name}
                expanded={expandedAttempts.has(a.attempt_id)}
                detail={attemptDetails[a.attempt_id] || null}
                onToggle={() => toggleAttemptExpand(a.attempt_id)}
                timeAgo={timeAgo}
              />
            ))
          )}
          {(morePagination ? morePagination.has_more : recent_attempts.length === 20) && (
            <button
              className="activity-load-more-btn"
              disabled={loadingMore}
              onClick={loadMoreAttempts}
            >
              {loadingMore ? 'Loading…' : 'Show more'}
            </button>
          )}
        </div>

      </div>
    </div>
  );
}

// ── AttemptRow ────────────────────────────────────────────────────────────────

function AttemptRow({ attempt: a, childName, expanded, detail, onToggle, timeAgo }) {
  const detailRef = React.useRef(null);

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

  return (
    <div className={`attempt-row attempt-row--tappable${expanded ? ' attempt-row--expanded' : ''}`} onClick={onToggle}>
      <div className={`attempt-icon attempt-icon--${a.is_correct ? 'correct' : 'wrong'}`}>
        {a.is_correct ? '✓' : '✗'}
      </div>
      <div className="attempt-info" style={{ width: '100%' }}>
        <div className="attempt-chapter">{a.chapter_name}</div>
        <div className="attempt-preview">{a.question_text_preview}</div>
        {(a.caused_level_up || a.is_flagged) && (
          <div className="attempt-tags">
            {a.caused_level_up && <span className="attempt-tag attempt-tag--levelup">↑ leveled up</span>}
            {a.is_flagged && <span className="attempt-tag attempt-tag--flagged">⚐ flagged</span>}
          </div>
        )}

        {expanded && (
          <div className="attempt-detail" ref={detailRef} onClick={(e) => e.stopPropagation()}>
            {!detail ? (
              <p className="attempt-detail-loading">Loading…</p>
            ) : (
              <React.Fragment>
                <div className="attempt-detail-label">Full question</div>
                <div className="attempt-detail-question">{detail.question.question_text}</div>

                <div className="attempt-detail-row">
                  <span className="attempt-detail-label">{childName} typed:</span>
                  <span className="attempt-detail-value">
                    {detail.this_attempt.typed_answer != null
                      ? detail.this_attempt.typed_answer
                      : detail.this_attempt.chosen_index != null
                        ? `Option ${detail.this_attempt.chosen_index + 1}`
                        : '—'}
                  </span>
                </div>
                <div className="attempt-detail-row">
                  <span className="attempt-detail-label">Time taken:</span>
                  <span className="attempt-detail-value">{detail.this_attempt.seconds_taken}s</span>
                </div>
                <div className="attempt-detail-row">
                  <span className="attempt-detail-label">At level:</span>
                  <span className="attempt-detail-value">{detail.this_attempt.level_at_attempt}</span>
                </div>

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

                {detail.question.all_attempts_by_this_child.length > 1 && (
                  <div className="attempt-detail-history">
                    <div className="attempt-detail-label">All attempts by {childName}</div>
                    {detail.question.all_attempts_by_this_child.map((att, i) => (
                      <div key={att.attempt_id} className={`attempt-detail-hist-row${att.attempt_id === detail.this_attempt.attempt_id ? ' attempt-detail-hist-row--current' : ''}`}>
                        <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>
                        {att.attempt_id === detail.this_attempt.attempt_id && (
                          <span className="attempt-hist-current-marker">← this</span>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </React.Fragment>
            )}
          </div>
        )}
      </div>
      <div className="attempt-time" style={{ flexShrink: 0 }}>
        {a.seconds_taken != null ? `${a.seconds_taken}s` : ''}
        <br />{timeAgo(a.attempted_at)}
        <br /><span className="attempt-expand-hint">{expanded ? '▲' : '▼'}</span>
      </div>
    </div>
  );
}

// ── DailyActivityGrid ─────────────────────────────────────────────────────────

function formatDuration(seconds) {
  if (!seconds || seconds <= 0) return '';
  if (seconds < 60) return `${seconds}s`;
  const minutes = Math.round(seconds / 60);
  if (minutes < 60) return `${minutes}m`;
  const hours = Math.floor(minutes / 60);
  const rem = minutes % 60;
  return rem === 0 ? `${hours}h` : `${hours}h ${rem}m`;
}

function DailyActivityGrid({ dailyActivity }) {
  // Build last 7 calendar days in IST (descending)
  const days = [];
  const now = new Date();
  // Shift to IST: UTC+5:30
  const istOffset = 5.5 * 60 * 60 * 1000;
  const todayIST = new Date(now.getTime() + istOffset);
  todayIST.setUTCHours(0, 0, 0, 0);

  for (let i = 0; i < 7; i++) {
    const d = new Date(todayIST.getTime() - i * 24 * 60 * 60 * 1000);
    // YYYY-MM-DD string to match DB date
    const dateStr = d.toISOString().slice(0, 10);
    days.push(dateStr);
  }

  // Index activity by date
  const byDate = {};
  for (const row of dailyActivity) {
    const dateStr = typeof row.attempt_date === 'string'
      ? row.attempt_date.slice(0, 10)
      : new Date(row.attempt_date).toISOString().slice(0, 10);
    if (!byDate[dateStr]) byDate[dateStr] = [];
    byDate[dateStr].push(row);
  }

  const DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

  function formatDate(dateStr) {
    const [year, month, day] = dateStr.split('-').map(Number);
    const d = new Date(Date.UTC(year, month - 1, day));
    const dayName = DAYS[d.getUTCDay()];
    return `${dayName}, ${day} ${MONTHS[month - 1]}`;
  }

  function totalForDay(dateStr) {
    return (byDate[dateStr] || []).reduce((sum, r) => sum + r.attempt_count, 0);
  }

  function totalSecondsForDay(dateStr) {
    return (byDate[dateStr] || []).reduce((sum, r) => sum + (r.total_seconds || 0), 0);
  }

  return (
    <div className="daily-activity-list">
      {days.map((dateStr, idx) => {
        const subjects = byDate[dateStr] || [];
        const total = subjects.reduce((sum, r) => sum + r.attempt_count, 0);
        const isToday = idx === 0;
        const daySeconds = totalSecondsForDay(dateStr);
        const dayDuration = formatDuration(daySeconds);
        return (
          <div key={dateStr} className={`daily-day-row${total === 0 ? ' daily-day-row--empty' : ''}`}>
            <div className="daily-day-header">
              <span className="daily-day-label">
                {isToday ? 'Today' : formatDate(dateStr)}
              </span>
              {total > 0
                ? <span className="daily-day-total">
                    {total} question{total !== 1 ? 's' : ''}
                    {dayDuration && ` · ${dayDuration}`}
                  </span>
                : <span className="daily-day-none">No activity</span>
              }
            </div>
            {subjects.length > 0 && (
              <div className="daily-subject-rows">
                {subjects.map((s) => {
                  const subDuration = formatDuration(s.total_seconds);
                  return (
                    <div key={s.subject_id} className="daily-subject-row">
                      <span className="daily-subject-emoji">{s.emoji}</span>
                      <span className="daily-subject-name">{s.subject_name}</span>
                      <span className="daily-subject-count">
                        {s.attempt_count}{subDuration && ` · ${subDuration}`}
                      </span>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}
