// ── ParentPage ────────────────────────────────────────────────────────────────

function ParentPage() {
  const [parentInfo, setParentInfo] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [hash, setHash] = React.useState(window.location.hash);

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

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

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

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

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

  if (!parentInfo) {
    return <ParentLoginForm onLogin={setParentInfo} />;
  }

  const childDetailMatch = hash.match(/^#\/child\/(\d+)$/);
  if (childDetailMatch) {
    return <ChildDetailPage childId={parseInt(childDetailMatch[1], 10)} navigate={navigate} />;
  }

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

  if (hash.startsWith('#/admin/chapters')) {
    return <CurriculumPage navigate={navigate} />;
  }

  return <ParentDashboard parent={parentInfo} onLogout={handleLogout} navigate={navigate} />;
}

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

function ParentLoginForm({ onLogin }) {
  const [form, setForm] = React.useState({ email: '', password: '' });
  const [error, setError] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setSubmitting(true);
    try {
      const res = await fetch('/api/parents/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.parent); }
    } catch { setError('Could not reach server'); }
    finally { setSubmitting(false); }
  }

  return (
    <div className="parent-shell">
      <div className="parent-card">
        <h1 className="parent-title">StepUp</h1>
        <p className="parent-subtitle">Parent login</p>
        <form className="parent-form" onSubmit={handleSubmit}>
          <label className="parent-label" htmlFor="email">Email</label>
          <input id="email" className="parent-input" type="email" autoComplete="email"
            value={form.email} onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))} required />
          <label className="parent-label" htmlFor="password">Password</label>
          <input id="password" className="parent-input" type="password" autoComplete="current-password"
            value={form.password} onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))} required />
          {error && <p className="parent-error">{error}</p>}
          <button className="parent-btn parent-btn--primary" type="submit" disabled={submitting}>
            {submitting ? 'Signing in…' : 'Sign in'}
          </button>
        </form>
        <p className="app-version">{window.APP_VERSION}</p>
      </div>
    </div>
  );
}

// ── Dashboard ─────────────────────────────────────────────────────────────────

function ParentDashboard({ parent, onLogout, navigate }) {
  const [children, setChildren] = React.useState([]);
  const [loadingChildren, setLoadingChildren] = React.useState(true);
  const [showAddForm, setShowAddForm] = React.useState(false);
  const [editingId, setEditingId] = React.useState(null);
  const [globalError, setGlobalError] = React.useState('');

  function fetchChildren() {
    return fetch('/api/children', { credentials: 'include' })
      .then((r) => r.json())
      .then(setChildren)
      .catch(() => setGlobalError('Failed to load children'));
  }

  React.useEffect(() => {
    fetchChildren().finally(() => setLoadingChildren(false));
  }, []);

  async function handleDelete(child) {
    if (!window.confirm(`Delete ${child.display_name}? This cannot be undone.`)) return;
    try {
      const res = await fetch(`/api/children/${child.id}`, { method: 'DELETE', credentials: 'include' });
      if (!res.ok) throw new Error();
      await fetchChildren();
    } catch { setGlobalError('Failed to delete child'); }
  }

  return (
    <div className="parent-shell">
      <div className="parent-card">
        <div className="dash-header">
          <div>
            <h1 className="parent-title">StepUp</h1>
            <span className="app-version">{window.APP_VERSION}</span>
          </div>
          <button className="parent-btn parent-btn--secondary dash-logout" onClick={onLogout}>Logout</button>
        </div>
        <p className="parent-greeting">Hello, {parent.display_name}</p>
        <button className="curriculum-link" onClick={() => navigate('/admin/chapters')}>
          Curriculum
        </button>

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

        <div className="dash-section-title">Children</div>

        {loadingChildren ? (
          <p className="parent-loading">Loading…</p>
        ) : (
          <div className="children-list">
            {children.length === 0 && !showAddForm && (
              <p className="dash-empty">No children yet — add one below.</p>
            )}
            {children.map((child) =>
              editingId === child.id ? (
                <EditChildForm key={child.id} child={child}
                  onSave={async () => { await fetchChildren(); setEditingId(null); }}
                  onCancel={() => setEditingId(null)} />
              ) : (
                <ChildCard key={child.id} child={child}
                  onView={() => navigate(`/child/${child.id}`)}
                  onEdit={() => setEditingId(child.id)}
                  onDelete={() => handleDelete(child)} />
              )
            )}
            {showAddForm ? (
              <AddChildForm
                onSave={async () => { await fetchChildren(); setShowAddForm(false); }}
                onCancel={() => setShowAddForm(false)} />
            ) : (
              <button className="parent-btn parent-btn--primary" style={{ marginTop: '1rem' }}
                onClick={() => setShowAddForm(true)}>
                + Add Child
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Child card ────────────────────────────────────────────────────────────────

function ChildCard({ child, onView, onEdit, onDelete }) {
  return (
    <div className="child-card child-card--tappable" onClick={onView}>
      <div className="child-avatar">{child.avatar_emoji || '👤'}</div>
      <div className="child-info">
        <div className="child-name">{child.display_name}</div>
        <div className="child-meta">Class {child.class_number} · {child.board}</div>
      </div>
      <div className="child-actions" onClick={(e) => e.stopPropagation()}>
        <button className="child-btn child-btn--edit" onClick={onEdit}>Edit</button>
        <button className="child-btn child-btn--delete" onClick={onDelete}>Delete</button>
      </div>
    </div>
  );
}

// ── Add child form ────────────────────────────────────────────────────────────

function AddChildForm({ onSave, onCancel }) {
  const [form, setForm] = React.useState({
    display_name: '', pin: '', class_number: '9', board: 'ICSE', avatar_emoji: '',
  });
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);

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

  return (
    <div className="child-form-box">
      <div className="child-form-title">New child</div>
      <form className="child-form" onSubmit={handleSubmit}>
        <ChildFormFields form={form} setForm={setForm} showPin={true} />
        {error && <p className="parent-error">{error}</p>}
        <div className="child-form-actions">
          <button className="parent-btn parent-btn--primary" type="submit" disabled={saving}>
            {saving ? 'Saving…' : 'Save'}
          </button>
          <button className="parent-btn parent-btn--secondary" type="button" onClick={onCancel}>
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
}

// ── Edit child form ───────────────────────────────────────────────────────────

function EditChildForm({ child, onSave, onCancel }) {
  const [form, setForm] = React.useState({
    display_name: child.display_name,
    class_number: String(child.class_number),
    board: child.board,
    avatar_emoji: child.avatar_emoji || '',
  });
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      const res = await fetch(`/api/children/${child.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ ...form, class_number: parseInt(form.class_number, 10) }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error || 'Failed to update child'); }
      else { await onSave(); }
    } catch { setError('Could not reach server'); }
    finally { setSaving(false); }
  }

  return (
    <div className="child-form-box">
      <div className="child-form-title">Edit {child.display_name}</div>
      <form className="child-form" onSubmit={handleSubmit}>
        <ChildFormFields form={form} setForm={setForm} showPin={false} />
        {error && <p className="parent-error">{error}</p>}
        <div className="child-form-actions">
          <button className="parent-btn parent-btn--primary" type="submit" disabled={saving}>
            {saving ? 'Saving…' : 'Save'}
          </button>
          <button className="parent-btn parent-btn--secondary" type="button" onClick={onCancel}>
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
}

// ── Shared form fields ────────────────────────────────────────────────────────

function ChildFormFields({ form, setForm, showPin }) {
  const f = (key) => (e) => setForm((prev) => ({ ...prev, [key]: e.target.value }));
  const classes = Array.from({ length: 12 }, (_, i) => i + 1);

  return (
    <React.Fragment>
      <label className="parent-label">Name</label>
      <input className="parent-input" type="text" maxLength={50}
        value={form.display_name} onChange={f('display_name')} required />

      {showPin && (
        <React.Fragment>
          <label className="parent-label">PIN (4 digits)</label>
          <input className="parent-input" type="password" inputMode="numeric"
            maxLength={4} pattern="\d{4}" value={form.pin} onChange={f('pin')} required />
        </React.Fragment>
      )}

      <label className="parent-label">Class</label>
      <select className="parent-input" value={form.class_number} onChange={f('class_number')}>
        {classes.map((n) => <option key={n} value={n}>{n}</option>)}
      </select>

      <label className="parent-label">Board</label>
      <select className="parent-input" value={form.board} onChange={f('board')}>
        <option value="ICSE">ICSE</option>
        <option value="CBSE">CBSE</option>
        <option value="TN_STATE">TN State</option>
      </select>

      <label className="parent-label">Avatar emoji (optional)</label>
      <input className="parent-input" type="text" maxLength={4} placeholder="e.g. 🦁"
        value={form.avatar_emoji} onChange={f('avatar_emoji')} />
    </React.Fragment>
  );
}

// ── CurriculumPage ────────────────────────────────────────────────────────────

function CurriculumPage({ navigate }) {
  const [curriculum, setCurriculum] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');
  // view: 'list' | 'chapters' | 'correct'
  const [view, setView] = React.useState('list');
  const [selected, setSelected] = React.useState(null); // { child, subject }

  React.useEffect(() => {
    fetch('/api/parents/chapters/curriculum', { credentials: 'include' })
      .then((r) => r.json().then((b) => ({ ok: r.ok, b })))
      .then(({ ok, b }) => {
        if (!ok) throw new Error(b.error || 'Failed to load');
        setCurriculum(b);
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  if (view === 'correct' && selected) {
    return (
      <ChapterCorrectionFlow
        child={selected.child}
        subject={selected.subject}
        onBack={() => setView('chapters')}
        onDone={() => { setView('list'); setSelected(null); }}
      />
    );
  }

  if (view === 'chapters' && selected) {
    return (
      <ChapterListView
        child={selected.child}
        subject={selected.subject}
        onBack={() => setView('list')}
        onCorrect={() => setView('correct')}
      />
    );
  }

  return (
    <div className="parent-shell">
      <div className="parent-card">
        <div className="dash-header">
          <button className="child-detail-back" onClick={() => navigate('')}>← Back</button>
          <h2 className="parent-title" style={{ fontSize: '1.3rem' }}>Curriculum</h2>
        </div>
        <p style={{ fontSize: '0.85rem', color: '#6b7280', marginBottom: '1.25rem' }}>
          Review chapter lists and correct them from your textbook photo.
        </p>

        {loading && <p className="parent-loading">Loading…</p>}
        {error && <p className="parent-error">{error}</p>}

        {!loading && !error && curriculum && curriculum.map((child) => (
          <div key={child.child_id} className="curriculum-child-section">
            <div className="curriculum-child-name">
              {child.child_name} <span className="curriculum-child-meta">Class {child.class_number} · {child.board}</span>
            </div>
            {child.subjects.map((sub) => (
              <button
                key={sub.subject_id}
                className="curriculum-subject-row"
                onClick={() => { setSelected({ child, subject: sub }); setView('chapters'); }}
              >
                <span className="curriculum-subject-emoji">{sub.emoji}</span>
                <span className="curriculum-subject-name">{sub.subject_name}</span>
                <span className="curriculum-subject-count">{sub.chapter_count} chapters →</span>
              </button>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

// ── ChapterListView ────────────────────────────────────────────────────────────

function ChapterListView({ child, subject, onBack, onCorrect }) {
  const [chapters, setChapters] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    fetch(`/api/parents/chapters/${child.class_number}/${child.board}/${subject.subject_id}`, { credentials: 'include' })
      .then((r) => r.json().then((b) => ({ ok: r.ok, b })))
      .then(({ ok, b }) => {
        if (!ok) throw new Error(b.error || 'Failed to load');
        setChapters(b);
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="parent-shell">
      <div className="parent-card">
        <button className="child-detail-back" onClick={onBack}>← Back</button>
        <div className="child-detail-header">
          <div className="child-detail-name">{subject.emoji} {subject.subject_name}</div>
          <div className="child-detail-meta">{child.child_name} · Class {child.class_number} · {child.board}</div>
        </div>

        {loading && <p className="parent-loading">Loading…</p>}
        {error && <p className="parent-error">{error}</p>}

        {chapters && (
          <div className="curriculum-chapter-list">
            {chapters.length === 0 ? (
              <p className="dash-empty">No chapters yet — they'll be seeded when a child first opens this subject.</p>
            ) : (
              chapters.map((ch) => (
                <div key={ch.id} className="curriculum-chapter-row">
                  <span className="curriculum-chapter-num">{ch.sequence_number}.</span>
                  <div className="curriculum-chapter-info">
                    <span className="curriculum-chapter-name">{ch.name}</span>
                    {ch.unit && <span className="curriculum-chapter-unit">{ch.unit}</span>}
                  </div>
                </div>
              ))
            )}
          </div>
        )}

        {chapters && chapters.length > 0 && (
          <div style={{ marginTop: '1.5rem' }}>
            <p style={{ fontSize: '0.8rem', color: '#6b7280', marginBottom: '0.75rem' }}>
              List looks wrong for your textbook?
            </p>
            <button className="parent-btn parent-btn--secondary" style={{ width: '100%' }} onClick={onCorrect}>
              Correct it with a photo
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// ── ChapterCorrectionFlow ─────────────────────────────────────────────────────

function ChapterCorrectionFlow({ child, subject, onBack, onDone }) {
  const [step, setStep] = React.useState(1); // 1=upload, 2=extracting, 3=review, 4=success
  const [file, setFile] = React.useState(null);
  const [correctionId, setCorrectionId] = React.useState(null);
  const [extractedChapters, setExtractedChapters] = React.useState([]);
  const [existingChapters, setExistingChapters] = React.useState([]);
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState('');
  const [confirming, setConfirming] = React.useState(false);
  const fileInputRef = React.useRef(null);

  async function handleUpload() {
    if (!file) return;
    setError('');
    setStep(2);

    const formData = new FormData();
    formData.append('class_number', child.class_number);
    formData.append('board', child.board);
    formData.append('subject_id', subject.subject_id);
    formData.append('photo', file);

    try {
      const r = await fetch('/api/parents/chapters/correct/upload', {
        method: 'POST', credentials: 'include', body: formData,
      });
      const data = await r.json();
      if (!r.ok) throw new Error(data.error || 'Upload failed');
      setCorrectionId(data.correction_id);
      setExistingChapters(data.existing_chapters);
      setExtractedChapters(data.extracted_chapters.map((ch, i) => ({ ...ch, _key: i })));
      setStep(3);
    } catch (e) {
      setError(e.message || 'Upload failed');
      setStep(1);
    }
  }

  async function handleConfirm() {
    setError('');
    setConfirming(true);
    try {
      const r = await fetch(`/api/parents/chapters/correct/${correctionId}/confirm`, {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ chapters: extractedChapters.map(({ _key, ...ch }) => ch) }),
      });
      const data = await r.json();
      if (!r.ok) throw new Error(data.error || 'Confirm failed');
      setResult(data);
      setStep(4);
    } catch (e) {
      setError(e.message);
    } finally {
      setConfirming(false);
    }
  }

  function updateChapter(key, field, value) {
    setExtractedChapters((prev) =>
      prev.map((ch) => ch._key === key ? { ...ch, [field]: value } : ch)
    );
  }

  function deleteChapter(key) {
    setExtractedChapters((prev) => prev.filter((ch) => ch._key !== key));
  }

  function addChapter() {
    const maxSeq = extractedChapters.reduce((m, ch) => Math.max(m, ch.sequence_number || 0), 0);
    setExtractedChapters((prev) => [...prev, { sequence_number: maxSeq + 1, name: '', unit: null, _key: Date.now() }]);
  }

  // ── Step 1: Upload ──
  if (step === 1) {
    return (
      <div className="parent-shell">
        <div className="parent-card">
          <button className="child-detail-back" onClick={onBack}>← Back</button>
          <div className="child-detail-header">
            <div className="child-detail-name">Correct chapter list</div>
            <div className="child-detail-meta">{subject.emoji} {subject.subject_name} · {child.child_name}</div>
          </div>
          <p className="correction-instructions">
            Take a clear photo of your textbook's contents page — all chapters and units should be visible.
            We'll extract the chapter list and ask you to confirm before updating.
          </p>

          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            capture="environment"
            style={{ display: 'none' }}
            onChange={(e) => setFile(e.target.files[0] || null)}
          />

          {!file ? (
            <button className="parent-btn parent-btn--primary" style={{ width: '100%', marginTop: '1rem' }}
              onClick={() => fileInputRef.current.click()}>
              Choose photo
            </button>
          ) : (
            <div className="correction-file-chosen">
              <span className="correction-file-name">{file.name}</span>
              <button className="correction-file-change" onClick={() => fileInputRef.current.click()}>Change</button>
            </div>
          )}

          {error && <p className="parent-error" style={{ marginTop: '0.75rem' }}>{error}</p>}

          {file && (
            <button className="parent-btn parent-btn--primary" style={{ width: '100%', marginTop: '1rem' }}
              onClick={handleUpload}>
              Extract chapters
            </button>
          )}
        </div>
      </div>
    );
  }

  // ── Step 2: Extracting ──
  if (step === 2) {
    return (
      <div className="parent-shell">
        <div className="parent-card" style={{ textAlign: 'center', padding: '3rem 1.5rem' }}>
          <div className="correction-spinner" />
          <p style={{ marginTop: '1.5rem', color: '#4b5563' }}>Extracting chapters from your photo…</p>
          <p style={{ fontSize: '0.8rem', color: '#9ca3af', marginTop: '0.5rem' }}>This takes 5–10 seconds</p>
        </div>
      </div>
    );
  }

  // ── Step 3: Review ──
  if (step === 3) {
    return (
      <div className="parent-shell">
        <div className="parent-card correction-review-card">
          <button className="child-detail-back" onClick={() => setStep(1)}>← Back</button>
          <div className="child-detail-header">
            <div className="child-detail-name">Review extracted chapters</div>
            <div className="child-detail-meta">{subject.emoji} {subject.subject_name}</div>
          </div>

          <div className="correction-review-grid">
            <div className="correction-col">
              <div className="correction-col-label">Current in StepUp</div>
              {existingChapters.map((ch) => (
                <div key={ch.id} className="correction-existing-row">
                  <span className="correction-seq">{ch.sequence_number}.</span>
                  <div>
                    <div className="correction-name">{ch.name}</div>
                    {ch.unit && <div className="correction-unit">{ch.unit}</div>}
                  </div>
                </div>
              ))}
            </div>

            <div className="correction-col">
              <div className="correction-col-label">From your photo — edit if needed</div>
              {extractedChapters.map((ch) => (
                <div key={ch._key} className="correction-extracted-row">
                  <input
                    className="correction-seq-input"
                    type="number"
                    min="1"
                    value={ch.sequence_number}
                    onChange={(e) => updateChapter(ch._key, 'sequence_number', parseInt(e.target.value, 10) || 1)}
                  />
                  <div className="correction-extracted-fields">
                    <input
                      className="correction-name-input"
                      type="text"
                      value={ch.name}
                      placeholder="Chapter name"
                      onChange={(e) => updateChapter(ch._key, 'name', e.target.value)}
                    />
                    <input
                      className="correction-unit-input"
                      type="text"
                      value={ch.unit || ''}
                      placeholder="Unit (optional)"
                      onChange={(e) => updateChapter(ch._key, 'unit', e.target.value || null)}
                    />
                  </div>
                  <button className="correction-delete-btn" title="Remove row"
                    onClick={() => deleteChapter(ch._key)}>✕</button>
                </div>
              ))}
              <button className="correction-add-row-btn" onClick={addChapter}>+ Add row</button>
            </div>
          </div>

          <div className="correction-confirm-box">
            <p className="correction-confirm-explainer">
              When you confirm: current chapters become invisible, these become the official list.
              Children's existing progress is preserved. This affects all children on Class {child.class_number} {child.board} {subject.subject_name}.
            </p>
            {error && <p className="parent-error" style={{ marginBottom: '0.75rem' }}>{error}</p>}
            <button
              className="parent-btn parent-btn--primary"
              style={{ width: '100%' }}
              disabled={confirming || extractedChapters.length === 0 || extractedChapters.some((ch) => !ch.name.trim())}
              onClick={handleConfirm}
            >
              {confirming ? 'Applying…' : `Confirm and apply (${extractedChapters.length} chapters)`}
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ── Step 4: Success ──
  return (
    <div className="parent-shell">
      <div className="parent-card" style={{ textAlign: 'center' }}>
        <div style={{ fontSize: '2.5rem', marginBottom: '0.75rem' }}>✓</div>
        <h2 style={{ fontSize: '1.1rem', fontWeight: 700, color: '#166534', marginBottom: '0.5rem' }}>
          Chapter list updated
        </h2>
        <p style={{ color: '#4b5563', marginBottom: '0.25rem' }}>
          Class {child.class_number} {child.board} {subject.subject_name}
        </p>
        <p style={{ fontSize: '0.85rem', color: '#6b7280', marginTop: '1rem' }}>
          Old chapters deactivated: {result.deactivated_count}<br />
          New chapters added: {result.inserted_count}
        </p>
        <button className="parent-btn parent-btn--secondary" style={{ marginTop: '1.5rem', width: '100%' }}
          onClick={onDone}>
          Back to Curriculum
        </button>
      </div>
    </div>
  );
}
