// ── ChildPage ─────────────────────────────────────────────────────────────────

function ChildPage() {
  const [childInfo, setChildInfo] = React.useState(null); // null=loading, false=not logged in
  const [loading, setLoading] = React.useState(true);
  const [hash, setHash] = React.useState(window.location.hash);

  React.useEffect(() => {
    const onHash = () => setHash(window.location.hash);
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  React.useEffect(() => {
    fetch('/api/children/me', { credentials: 'include' })
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => { setChildInfo(data || false); setLoading(false); })
      .catch(() => { setChildInfo(false); setLoading(false); });
  }, []);

  async function handleLogout() {
    await fetch('/api/children/logout', { method: 'POST', credentials: 'include' });
    window.location.hash = '';
    setChildInfo(false);
  }

  function navigate(path) {
    window.location.hash = path;
  }

  if (loading) {
    return (
      <div className="child-shell">
        <div className="child-card">
          <p className="child-loading">Loading…</p>
        </div>
      </div>
    );
  }

  if (!childInfo) return <ChildLoginForm onLogin={setChildInfo} />;

  const subjectMatch = hash.match(/^#\/subject\/(\d+)$/);
  if (subjectMatch) {
    return (
      <ChapterListPage
        subjectId={parseInt(subjectMatch[1], 10)}
        onBack={() => navigate('')}
        onNavigate={navigate}
      />
    );
  }

  const chapterMatch = hash.match(/^#\/chapter\/(\d+)$/);
  if (chapterMatch) {
    return <ChapterPage chapterId={parseInt(chapterMatch[1], 10)} navigate={navigate} />;
  }

  const questionMatch = hash.match(/^#\/question\/(\d+)$/);
  if (questionMatch) {
    return <QuestionPage chapterId={parseInt(questionMatch[1], 10)} navigate={navigate} />;
  }

  if (hash === '#/random-quiz') {
    return <RandomQuizPage navigate={navigate} />;
  }

  return <SubjectTilesHome child={childInfo} onLogout={handleLogout} onNavigate={navigate} />;
}

// ── Login form ────────────────────────────────────────────────────────────────

function ChildLoginForm({ onLogin }) {
  const [form, setForm] = React.useState({ display_name: '', pin: '' });
  const [error, setError] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const nameRef = React.useRef(null);

  React.useEffect(() => {
    if (nameRef.current) nameRef.current.focus();
  }, []);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setSubmitting(true);
    try {
      const res = await fetch('/api/children/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error || 'Login failed'); }
      else { onLogin(data.child); }
    } catch { setError('Could not reach server'); }
    finally { setSubmitting(false); }
  }

  return (
    <div className="child-shell">
      <div className="child-card">
        <div className="child-logo">StepUp</div>
        <p className="child-tagline">What's your name?</p>

        <form className="child-form-login" onSubmit={handleSubmit}>
          <input
            ref={nameRef}
            className="child-input"
            type="text"
            placeholder="Your name"
            autoComplete="off"
            value={form.display_name}
            onChange={(e) => setForm((f) => ({ ...f, display_name: e.target.value }))}
            required
          />
          <input
            className="child-input"
            type="tel"
            inputMode="numeric"
            pattern="[0-9]{4}"
            maxLength={4}
            placeholder="PIN"
            autoComplete="off"
            value={form.pin}
            onChange={(e) => setForm((f) => ({ ...f, pin: e.target.value }))}
            required
          />

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

          <button className="child-login-btn" type="submit" disabled={submitting}>
            {submitting ? 'Logging in…' : 'Log in'}
          </button>
        </form>

        <a className="child-parent-link" href="/parent">Parent login</a>
        <p className="app-version">{window.APP_VERSION}</p>
      </div>
    </div>
  );
}

// ── Subject tiles home ────────────────────────────────────────────────────────

function SubjectTilesHome({ child, onLogout, onNavigate }) {
  const [subjects, setSubjects] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');
  const [corrections, setCorrections] = React.useState([]);

  function loadSubjects() {
    setLoading(true);
    setError('');
    fetch('/api/children/subjects', { credentials: 'include' })
      .then((r) => r.json().then((body) => ({ ok: r.ok, body })))
      .then(({ ok, body }) => {
        if (!ok) throw new Error(body.error || 'Failed to load');
        setSubjects(body);
      })
      .catch((err) => setError(err.message || "Couldn't load your subjects, please try again"))
      .finally(() => setLoading(false));
  }

  function loadNotifications() {
    fetch('/api/children/notifications', { credentials: 'include' })
      .then((r) => r.json())
      .then((data) => setCorrections(data.corrections || []))
      .catch(() => {});
  }

  async function dismissCorrection(flagId) {
    setCorrections((prev) => prev.filter((c) => c.flag_id !== flagId));
    await fetch(`/api/children/notifications/${flagId}/ack`, { method: 'POST', credentials: 'include' })
      .catch(() => {});
  }

  React.useEffect(() => { loadSubjects(); loadNotifications(); }, []);

  return (
    <div className="child-home-shell">
      <div className="child-home-topbar">
        <div className="child-home-identity">
          <span className="child-home-avatar-sm">{child.avatar_emoji || '👤'}</span>
          <div>
            <div className="child-home-greeting">Hello, {child.display_name}!</div>
            <div className="child-home-meta">Class {child.class_number} · {child.board}</div>
          </div>
        </div>
        <button className="child-logout-btn" onClick={onLogout}>Logout</button>
      </div>

      {/* Correction notifications */}
      {corrections.map((c) => (
        <div key={c.flag_id} className="correction-banner">
          <span className="correction-banner-star">⭐</span>
          <div className="correction-banner-body">
            <div className="correction-banner-title">Great work!</div>
            <div className="correction-banner-text">
              Your challenge on &ldquo;{c.question_preview}&rdquo; was confirmed by the senior teacher.
              The question has been corrected for everyone.
            </div>
          </div>
          <button className="correction-banner-dismiss" onClick={() => dismissCorrection(c.flag_id)}>✕</button>
        </div>
      ))}

      {loading && <p className="child-loading" style={{ padding: '2rem', textAlign: 'center' }}>Loading…</p>}

      {error && (
        <div style={{ padding: '2rem', textAlign: 'center' }}>
          <p className="child-error">{error}</p>
          <button className="child-login-btn" style={{ marginTop: '1rem' }} onClick={loadSubjects}>Retry</button>
        </div>
      )}

      {!loading && !error && (
        <>
          <div className="random-quiz-banner">
            <button className="random-quiz-btn" onClick={() => onNavigate('/random-quiz')}>
              <span className="random-quiz-btn-dice">🎲</span>
              <span className="random-quiz-btn-label">Random Quiz</span>
              <span className="random-quiz-btn-sub">Any subject · Any chapter</span>
            </button>
          </div>
          <div className="subject-grid">
            {subjects.map((s) => (
              <button key={s.subject_id} className="subject-tile" onClick={() => onNavigate(`/subject/${s.subject_id}`)}>
                <span className="subject-tile-emoji">{s.emoji}</span>
                <span className="subject-tile-name">{s.name}</span>
                <span className="subject-tile-progress">
                  {s.chapter_count !== null
                    ? `${s.started_count} of ${s.chapter_count} chapters started`
                    : 'Tap to explore'}
                </span>
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}
