import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  deleteOracFormDetail,
  fetchFormWithSectionsAndQuestions,
  fetchLookupCountries,
  fetchLocationsList,
  fetchOracFormDetailsList,
  fetchOracLocationFormsDetailsByFormId,
  forkOracFormVersion,
  fetchOracSectionDetailsList,
  mapLocationToForm,
  mapSectionToForm,
  unmapLocationFromForm,
  unmapSectionFromForm,
  updateOracFormDetail
} from '../../api.js';
import { getSessionUserId } from './adminOracSession.js';
import { formAllowedForNewUse, isTruthyFlag } from '../../utils/oracFormDetails.js';
import { buildSectionQuestionGroups } from '../../utils/oracQuestionGroups.js';
import './admin-shared.css';
import './AdminFormBuilderPage.css';
import './AdminFormsCompositionPage.css';

function AdminFormDetailsPage({ initialFormId, onBack, onNavigateAfterFormDeleted }) {
  const [sections, setSections] = useState([]);
  /** All `orac_form_details` rows from the list API (`version`, `is_archived`, `has_child_version`, …). */
  const [formsAll, setFormsAll] = useState([]);
  const [countries, setCountries] = useState([]);
  const [allLocations, setAllLocations] = useState([]);
  const [formLocationRows, setFormLocationRows] = useState([]);
  const [locationCountryFilter, setLocationCountryFilter] = useState('all');

  const [selectedFormId, setSelectedFormId] = useState('');
  const [formSchema, setFormSchema] = useState(null);

  const [editTitle, setEditTitle] = useState('');
  const [editDescription, setEditDescription] = useState('');
  const [editParentId, setEditParentId] = useState('');

  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [successDialog, setSuccessDialog] = useState({ open: false, title: '', body: '' });

  const uid = getSessionUserId();

  function openSuccessDialog(title, body) {
    setSuccessDialog({ open: true, title, body });
  }

  function closeSuccessDialog() {
    setSuccessDialog((s) => ({ ...s, open: false }));
  }

  useEffect(() => {
    if (!successDialog.open) return undefined;
    function onKey(e) {
      if (e.key === 'Escape') setSuccessDialog((s) => ({ ...s, open: false }));
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [successDialog.open]);

  function formatFormDate(val) {
    if (val == null || val === '') return '—';
    try {
      const d = new Date(val);
      if (Number.isNaN(d.getTime())) return String(val);
      return d.toLocaleString();
    } catch {
      return String(val);
    }
  }

  function formOptionLabel(f) {
    const t = f.title || `Form ${f.form_id}`;
    const vn = f.version != null && f.version !== '' ? ` · v${f.version}` : '';
    return `${t}${vn}`;
  }

  const selectedFormRow = useMemo(() => {
    if (selectedFormId === '') return null;
    return formsAll.find((x) => String(x.form_id) === String(selectedFormId)) ?? null;
  }, [formsAll, selectedFormId]);

  /** Forms allowed for new use — client filter of `formsAll` (same rule as `leaf_only` API). */
  const formsLeaf = useMemo(
    () => (Array.isArray(formsAll) ? formsAll.filter(formAllowedForNewUse) : []),
    [formsAll]
  );

  /** Main dropdown: allowed-for-new-use only, plus current row if it is archived / superseded so selection stays visible. */
  const formsForPrimarySelect = useMemo(() => {
    const leaf = formsLeaf;
    if (!selectedFormRow) return leaf;
    const id = String(selectedFormRow.form_id);
    if (leaf.some((f) => String(f.form_id) === id)) return leaf;
    return [...leaf, selectedFormRow];
  }, [formsLeaf, selectedFormRow]);

  const formsForParentEdit = useMemo(() => {
    return formsAll.filter((f) => String(f.form_id) !== String(selectedFormId));
  }, [formsAll, selectedFormId]);

  useEffect(() => {
    if (initialFormId != null && String(initialFormId) !== '') {
      setSelectedFormId(String(initialFormId));
      setFormSchema(null);
    }
  }, [initialFormId]);

  useEffect(() => {
    if (!selectedFormRow) {
      setEditTitle('');
      setEditDescription('');
      setEditParentId('');
      return;
    }
    setEditTitle(selectedFormRow.title ?? '');
    setEditDescription(selectedFormRow.description ?? '');
    const p = selectedFormRow.form_parent_id;
    setEditParentId(
      p != null && p !== '' && Number(p) > 0 ? String(p) : ''
    );
  }, [selectedFormRow]);

  const loadCatalog = useCallback(async () => {
    const [s, fAll, c, locs] = await Promise.all([
      fetchOracSectionDetailsList().catch(() => []),
      fetchOracFormDetailsList({ with_version: true }).catch(() => []),
      fetchLookupCountries().catch(() => []),
      fetchLocationsList().catch(() => [])
    ]);
    setSections(Array.isArray(s) ? s : []);
    setFormsAll(Array.isArray(fAll) ? fAll : []);
    setCountries(Array.isArray(c) ? c : []);
    setAllLocations(Array.isArray(locs) ? locs : []);
  }, []);

  const refreshFormLocations = useCallback(async (formId) => {
    if (formId == null || formId === '') {
      setFormLocationRows([]);
      return;
    }
    const rows = await fetchOracLocationFormsDetailsByFormId(formId);
    setFormLocationRows(Array.isArray(rows) ? rows : []);
  }, []);

  useEffect(() => {
    setLoading(true);
    setError('');
    loadCatalog()
      .catch((e) => setError(e.message || 'Failed to load data'))
      .finally(() => setLoading(false));
  }, [loadCatalog]);

  const loadFormSchema = useCallback(async (formId) => {
    if (formId == null || formId === '') {
      setFormSchema(null);
      return null;
    }
    const id = Number(formId);
    if (!Number.isInteger(id) || id <= 0) {
      setFormSchema(null);
      return null;
    }
    const data = await fetchFormWithSectionsAndQuestions(id);
    setFormSchema(data);
    return data;
  }, []);

  useEffect(() => {
    if (selectedFormId === '') {
      return;
    }
    let cancelled = false;
    setBusy(true);
    loadFormSchema(selectedFormId)
      .catch((e) => {
        if (!cancelled) setError(e.message || 'Failed to load form');
      })
      .finally(() => {
        if (!cancelled) setBusy(false);
      });
    return () => {
      cancelled = true;
    };
  }, [selectedFormId, loadFormSchema]);

  useEffect(() => {
    if (selectedFormId === '') {
      setFormLocationRows([]);
      return;
    }
    let cancelled = false;
    const fid = selectedFormId;
    (async () => {
      try {
        const rows = await fetchOracLocationFormsDetailsByFormId(fid);
        if (cancelled) return;
        setFormLocationRows(Array.isArray(rows) ? rows : []);
      } catch {
        if (!cancelled) setFormLocationRows([]);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [selectedFormId]);

  const showMsg = (text, isErr = false) => {
    setMessage(text);
    setError(isErr ? text : '');
    if (!isErr) {
      window.setTimeout(() => setMessage(''), 4000);
    }
  };

  /**
   * Only adding or removing a section on this form creates a new `orac_form_details` row and archives the previous
   * form (fork). Title, description, parent link, locations, and section content (questions) are updated in place.
   * Returns `{ fid, schema }` so callers can use the freshly loaded schema (React state is still stale in the same tick).
   */
  const forkIfNeeded = async () => {
    const sid = selectedFormId;
    if (sid === '' || sid == null) return null;
    const base = Number(sid);
    if (!Number.isInteger(base) || base <= 0) return null;
    setBusy(true);
    setError('');
    try {
      const res = await forkOracFormVersion(base, uid != null ? { created_by: uid } : {});
      const newId = res?.insertedId;
      if (newId == null || newId === '') {
        throw new Error('Fork did not return insertedId');
      }
      setSelectedFormId(String(newId));
      setFormSchema(null);
      await loadCatalog();
      const schema = await loadFormSchema(newId);
      return { fid: Number(newId), schema };
    } catch (err) {
      setError(err.message || 'Could not create new form version');
      return null;
    } finally {
      setBusy(false);
    }
  };

  const handleSaveFormMetadata = async (e) => {
    e.preventDefault();
    if (selectedFormId === '') return;
    const fid = Number(selectedFormId);
    if (!Number.isInteger(fid) || fid <= 0) return;
    const parentRaw = editParentId.trim();
    const parentNum = parentRaw === '' ? null : Number(parentRaw);
    if (parentNum != null && Number.isInteger(parentNum) && parentNum === fid) {
      showMsg('A form cannot be its own parent.', true);
      return;
    }
    setBusy(true);
    setError('');
    try {
      await updateOracFormDetail(fid, {
        title: editTitle.trim() || null,
        description: editDescription.trim() || null,
        form_parent_id:
          parentNum != null && Number.isInteger(parentNum) && parentNum > 0 ? parentNum : null
      });
      await loadCatalog();
      await loadFormSchema(fid);
      openSuccessDialog('Saved', 'Form details were updated.');
    } catch (err) {
      setError(err.message || 'Could not save form');
    } finally {
      setBusy(false);
    }
  };

  const handleDeleteForm = async () => {
    if (selectedFormId === '') return;
    const f = formsAll.find((x) => String(x.form_id) === String(selectedFormId));
    if (!window.confirm(`Delete "${f?.title || 'this form'}"?`)) return;
    setBusy(true);
    setError('');
    try {
      await deleteOracFormDetail(selectedFormId);
      setSelectedFormId('');
      setFormSchema(null);
      await loadCatalog();
      if (typeof onNavigateAfterFormDeleted === 'function') {
        onNavigateAfterFormDeleted();
      } else {
        openSuccessDialog('Deleted', 'The form was removed.');
      }
    } catch (err) {
      setError(err.message || 'Could not delete form');
    } finally {
      setBusy(false);
    }
  };

  const sectionIdsInForm = useMemo(() => {
    const list = formSchema?.sections || [];
    return new Set(list.map((s) => s.section_id));
  }, [formSchema]);

  const availableSectionsToAdd = useMemo(() => {
    return sections.filter((s) => !sectionIdsInForm.has(s.section_id));
  }, [sections, sectionIdsInForm]);

  function locationRowLabel(loc) {
    if (!loc) return '—';
    return loc.Location_name || loc.location_name || `Location ${loc.location_id}`;
  }

  function countryLabelForId(countryId) {
    if (countryId == null || countryId === '') return '—';
    const c = countries.find((x) => String(x.country_id) === String(countryId));
    return c?.country_name ?? `Country ${countryId}`;
  }

  const locationIdsOnForm = useMemo(
    () => new Set(formLocationRows.map((r) => r.location_id)),
    [formLocationRows]
  );

  const availableLocationsToAdd = useMemo(() => {
    let list = allLocations.filter((l) => !locationIdsOnForm.has(l.location_id));
    if (locationCountryFilter && locationCountryFilter !== 'all') {
      const cid = Number(locationCountryFilter);
      if (Number.isInteger(cid)) {
        list = list.filter((l) => Number(l.country_id) === cid);
      }
    }
    return [...list].sort((a, b) =>
      locationRowLabel(a).localeCompare(locationRowLabel(b), undefined, { sensitivity: 'base' })
    );
  }, [allLocations, locationIdsOnForm, locationCountryFilter]);

  const handleAddLocationToForm = async (e) => {
    e.preventDefault();
    const lid = Number(e.target.elements.location_pick?.value);
    if (!Number.isInteger(lid) || lid <= 0) return;
    const fid = Number(selectedFormId);
    if (!Number.isInteger(fid) || fid <= 0) return;
    setBusy(true);
    setError('');
    try {
      await mapLocationToForm(fid, lid);
      await refreshFormLocations(fid);
      await loadFormSchema(fid);
      await loadCatalog();
      openSuccessDialog('Saved', 'Location was added to this form.');
    } catch (err) {
      setError(err.message || 'Could not map location');
    } finally {
      setBusy(false);
    }
  };

  const handleRemoveLocationFromForm = async (locationId) => {
    if (!window.confirm('Remove this location?')) return;
    const fid = Number(selectedFormId);
    if (!Number.isInteger(fid) || fid <= 0) return;
    setBusy(true);
    setError('');
    try {
      await unmapLocationFromForm(fid, locationId);
      await refreshFormLocations(fid);
      await loadFormSchema(fid);
      await loadCatalog();
      openSuccessDialog('Removed', 'Location was removed from this form.');
    } catch (err) {
      setError(err.message || 'Could not unmap location');
    } finally {
      setBusy(false);
    }
  };

  const handleAddSectionsToForm = async (e) => {
    e.preventDefault();
    const ids = [...e.currentTarget.querySelectorAll('input[name="section_pick_add"]:checked')]
      .map((el) => Number(el.value))
      .filter((n) => Number.isInteger(n) && n > 0);
    if (ids.length === 0) {
      showMsg('Select sections first.', true);
      return;
    }
    const forked = await forkIfNeeded();
    if (forked == null) return;
    const { fid } = forked;
    setBusy(true);
    setError('');
    try {
      for (const sid of ids) {
        await mapSectionToForm(fid, sid);
      }
      await loadFormSchema(fid);
      await loadCatalog();
      e.currentTarget.querySelectorAll('input[name="section_pick_add"]').forEach((el) => {
        el.checked = false;
      });
      openSuccessDialog(
        'Sections updated',
        ids.length === 1
          ? 'A new version was created and the section was added to this form.'
          : `A new version was created and ${ids.length} sections were added to this form.`
      );
    } catch (err) {
      setError(err.message || 'Could not map one or more sections');
    } finally {
      setBusy(false);
    }
  };

  const handleRemoveSectionFromForm = async (sectionId) => {
    if (!window.confirm('Remove this section?')) return;
    const forked = await forkIfNeeded();
    if (forked == null) return;
    const { fid } = forked;
    setBusy(true);
    setError('');
    try {
      await unmapSectionFromForm(fid, sectionId);
      await loadFormSchema(fid);
      await loadCatalog();
      openSuccessDialog('Section removed', 'A new version was created without this section.');
    } catch (err) {
      setError(err.message || 'Could not unmap section');
    } finally {
      setBusy(false);
    }
  };

  if (loading) {
    return (
      <main className="dashboard-main admin-dashboard admin-dashboard-v2 admin-form-builder admin-orac-page admin-forms-page">
        <p style={{ textAlign: 'center', padding: 40, color: 'var(--theme-gray-500)' }}>Loading…</p>
      </main>
    );
  }

  return (
    <main className="dashboard-main admin-dashboard admin-dashboard-v2 admin-form-builder admin-orac-page admin-forms-page">
      <header className="admin-page-header">
        <div>
          <div className="admin-page-header__toolbar">
            <span className="admin-page-badge">Admin</span>
            {typeof onBack === 'function' && (
              <button type="button" className="admin-outline-button" onClick={onBack}>
                ← Back
              </button>
            )}
          </div>
          <h1>Edit form</h1>
          <p style={{ margin: '8px 0 0', fontSize: 14, color: 'var(--theme-gray-500)', maxWidth: '36rem' }}>
            Title, description, parent, locations, and questions (via sections) update this form in place. Only adding
            or removing a section here creates a new form version.
          </p>
        </div>
      </header>

      {error && (
        <p className="admin-form-builder-msg admin-form-builder-msg--err" role="alert">
          {error}
        </p>
      )}
      {message && !error && <p className="admin-form-builder-msg admin-form-builder-msg--ok">{message}</p>}

      <div className="admin-form-builder-panel">
        <div className="admin-forms-content">
          <section className="admin-forms-panel" aria-labelledby="admin-form-details-title">
            <h2 id="admin-form-details-title" className="admin-forms-panel__title">
              Form
            </h2>

            <div className="admin-forms-toolbar-row">
              <div className="admin-form-builder-field">
                <label htmlFor="form-pick-details">Choose form</label>
                <select
                  id="form-pick-details"
                  value={selectedFormId}
                  onChange={(ev) => {
                    setSelectedFormId(ev.target.value);
                    setFormSchema(null);
                  }}
                  disabled={busy}
                >
                  <option value="">Select…</option>
                  {formsForPrimarySelect.map((f) => (
                    <option key={f.form_id} value={String(f.form_id)}>
                      {formOptionLabel(f)}
                    </option>
                  ))}
                </select>
              </div>
              <div className="admin-forms-toolbar-row__actions">
                {selectedFormId !== '' && (
                  <button type="button" className="admin-form-builder-danger" onClick={handleDeleteForm} disabled={busy}>
                    Delete form
                  </button>
                )}
              </div>
            </div>

            {selectedFormRow && (
              <>
                <div className="admin-forms-meta admin-forms-meta--inline">
                  <span className="admin-forms-meta__inline-item">
                    <span className="admin-forms-meta__label">ID</span> <strong>{selectedFormRow.form_id}</strong>
                  </span>
                  {selectedFormRow.version != null && selectedFormRow.version !== '' && (
                    <span className="admin-forms-meta__inline-item">
                      <span className="admin-forms-meta__label">Version</span> v{selectedFormRow.version}
                    </span>
                  )}
                  {!formAllowedForNewUse(selectedFormRow) && (
                    <span className="admin-forms-meta__inline-item" style={{ color: 'var(--theme-gray-600)' }}>
                      <span className="admin-forms-meta__label">Status</span>{' '}
                      {[
                        isTruthyFlag(selectedFormRow.is_archived) ? 'Archived' : null,
                        isTruthyFlag(selectedFormRow.has_child_version) ? 'Superseded (newer version exists)' : null
                      ]
                        .filter(Boolean)
                        .join(' · ') || '—'}
                    </span>
                  )}
                  <span className="admin-forms-meta__inline-item">
                    <span className="admin-forms-meta__label">Created</span> {formatFormDate(selectedFormRow.created_date)}
                  </span>
                  <span className="admin-forms-meta__inline-item">
                    <span className="admin-forms-meta__label">By</span> {selectedFormRow.created_by ?? '—'}
                  </span>
                </div>

                <form onSubmit={handleSaveFormMetadata} className="admin-forms-edit-metadata">
                  <h3 className="admin-forms-composition-title">Details</h3>
                  <div className="admin-forms-edit-metadata__grid">
                    <div className="admin-form-builder-field">
                      <label htmlFor="edit-form-title">Title</label>
                      <input
                        id="edit-form-title"
                        value={editTitle}
                        onChange={(ev) => setEditTitle(ev.target.value)}
                        placeholder="Form title"
                        disabled={busy}
                        autoComplete="off"
                      />
                    </div>
                    <div className="admin-form-builder-field">
                      <label htmlFor="edit-form-parent">Previous version</label>
                      <select
                        id="edit-form-parent"
                        value={editParentId}
                        onChange={(ev) => setEditParentId(ev.target.value)}
                        disabled={busy}
                      >
                        <option value="">None</option>
                        {formsForParentEdit.map((f) => (
                          <option key={f.form_id} value={String(f.form_id)}>
                            {f.title || 'Untitled'}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div className="admin-form-builder-field admin-form-builder-field--full">
                      <label htmlFor="edit-form-desc">Description</label>
                      <textarea
                        id="edit-form-desc"
                        value={editDescription}
                        onChange={(ev) => setEditDescription(ev.target.value)}
                        placeholder="Optional"
                        disabled={busy}
                        rows={3}
                      />
                    </div>
                  </div>
                  <div className="admin-forms-edit-metadata__actions">
                    <button type="submit" className="admin-action-button" disabled={busy}>
                      Save
                    </button>
                  </div>
                </form>
              </>
            )}

            {selectedFormId !== '' && (
              <div className="admin-forms-locations-block">
                <h3 className="admin-forms-composition-title">Locations</h3>
                <ul className="admin-forms-locations-list">
                  {formLocationRows.length === 0 && (
                    <li className="admin-forms-locations-list__empty">No locations yet.</li>
                  )}
                  {formLocationRows.map((row) => {
                    const loc = allLocations.find((l) => String(l.location_id) === String(row.location_id));
                    return (
                      <li key={`${row.form_id}-${row.location_id}`} className="admin-forms-locations-list__row">
                        <span>
                          <strong>{locationRowLabel(loc)}</strong>
                          <span className="admin-forms-locations-list__meta">
                            {' '}
                            · {countryLabelForId(loc?.country_id)}
                          </span>
                        </span>
                        <button
                          type="button"
                          className="admin-outline-button"
                          onClick={() => handleRemoveLocationFromForm(row.location_id)}
                          disabled={busy}
                        >
                          Remove
                        </button>
                      </li>
                    );
                  })}
                </ul>
                <form onSubmit={handleAddLocationToForm} className="admin-forms-location-add">
                  <div className="admin-form-builder-field">
                    <label htmlFor="location_country_filter">Country</label>
                    <select
                      id="location_country_filter"
                      value={locationCountryFilter}
                      onChange={(ev) => setLocationCountryFilter(ev.target.value)}
                      disabled={busy}
                    >
                      <option value="all">All countries</option>
                      {[...countries]
                        .sort((a, b) =>
                          String(a.country_name || '').localeCompare(String(b.country_name || ''), undefined, {
                            sensitivity: 'base'
                          })
                        )
                        .map((c) => (
                          <option key={c.country_id} value={String(c.country_id)}>
                            {c.country_name || `Country ${c.country_id}`}
                          </option>
                        ))}
                    </select>
                  </div>
                  <div className="admin-forms-add-section admin-forms-add-section--location">
                    <div className="admin-form-builder-field">
                      <label htmlFor="location_pick_details">Add location</label>
                      <select
                        id="location_pick_details"
                        name="location_pick"
                        disabled={busy || !availableLocationsToAdd.length}
                      >
                        <option value="">Select location…</option>
                        {availableLocationsToAdd.map((loc) => (
                          <option key={loc.location_id} value={String(loc.location_id)}>
                            {locationRowLabel(loc)} — {countryLabelForId(loc.country_id)}
                          </option>
                        ))}
                      </select>
                    </div>
                    <button
                      type="submit"
                      className="admin-action-button"
                      disabled={busy || !availableLocationsToAdd.length}
                    >
                      Add to form
                    </button>
                  </div>
                </form>
              </div>
            )}

            {selectedFormId !== '' && (
              <>
                <form onSubmit={handleAddSectionsToForm} className="admin-forms-add-sections-batch">
                  <h3 className="admin-forms-composition-title">Sections</h3>
                  {availableSectionsToAdd.length === 0 ? (
                    <p style={{ fontSize: 14, color: 'var(--theme-gray-500)' }}>All available sections are on this form.</p>
                  ) : (
                    <>
                      <div className="admin-section-detail__checkboxes admin-orac-form-add-questions__box">
                        {[...availableSectionsToAdd]
                          .sort((a, b) => Number(a.section_id) - Number(b.section_id))
                          .map((s) => (
                            <label key={s.section_id} className="admin-section-detail__pick-row">
                              <input
                                type="checkbox"
                                name="section_pick_add"
                                value={String(s.section_id)}
                                disabled={busy}
                              />
                              <span className="admin-section-detail__pick-text">
                                {s.title || `Section ${s.section_id}`}
                              </span>
                            </label>
                          ))}
                      </div>
                      <div style={{ marginTop: 10 }}>
                        <button type="submit" className="admin-action-button" disabled={busy}>
                          Add sections
                        </button>
                      </div>
                    </>
                  )}
                </form>

                {busy && !formSchema && (
                  <p style={{ fontSize: 14, color: 'var(--theme-gray-500)' }}>Loading…</p>
                )}

                {formSchema && (
                  <div style={{ marginTop: 20 }}>
                    <h3 className="admin-forms-composition-title" style={{ marginBottom: 12 }}>
                      Section questions
                    </h3>
                    <p className="admin-form-builder-hint" style={{ marginTop: 0, marginBottom: 14, fontSize: 14 }}>
                      Expand a section below to view its questions. Map questions to sections from the section detail
                      page.
                    </p>
                    {(formSchema.sections || []).length === 0 && (
                      <p style={{ color: 'var(--theme-gray-500)', fontSize: 14 }}>Add sections above first.</p>
                    )}
                    {(formSchema.sections || []).map((sec) => {
                      const qCount = (sec.questions || []).length;
                      return (
                        <div key={sec.section_id} className="admin-form-builder-section-block">
                          <div className="admin-form-builder-section-head">
                            <div>
                              <strong>{sec.title || `Section ${sec.section_id}`}</strong>
                            </div>
                            <button
                              type="button"
                              className="admin-outline-button"
                              onClick={() => handleRemoveSectionFromForm(sec.section_id)}
                              disabled={busy}
                            >
                              Remove section
                            </button>
                          </div>

                          <details className="admin-form-details__section-questions">
                            <summary className="admin-form-details__section-questions-summary">
                              {qCount === 0
                                ? 'View questions (none)'
                                : `View questions (${qCount})`}
                            </summary>
                            <ul className="admin-form-builder-question-list">
                              {qCount === 0 && <li>No questions.</li>}
                              {buildSectionQuestionGroups(sec.questions || []).map((g) => (
                                <li key={g.main.question_id} className="admin-form-builder-q-group">
                                  <div>
                                    <span>
                                      {g.main.question}
                                      {g.children.length > 0 && (
                                        <span style={{ fontSize: 12, color: 'var(--theme-gray-500)' }}>
                                          {' '}
                                          +{g.children.length}
                                        </span>
                                      )}
                                    </span>
                                  </div>
                                  {g.children.length > 0 && (
                                    <ul
                                      style={{
                                        margin: '6px 0 0 18px',
                                        padding: 0,
                                        listStyle: 'disc',
                                        fontSize: 13,
                                        color: 'var(--theme-gray-600)'
                                      }}
                                    >
                                      {g.children.map((c) => (
                                        <li key={c.question_id}>{c.question}</li>
                                      ))}
                                    </ul>
                                  )}
                                </li>
                              ))}
                            </ul>
                          </details>
                        </div>
                      );
                    })}
                  </div>
                )}
              </>
            )}
          </section>
        </div>
      </div>

      {successDialog.open && (
        <div
          className="admin-orac-form-popup-overlay"
          role="dialog"
          aria-modal="true"
          aria-labelledby="admin-form-success-title"
          onClick={(e) => {
            if (e.target === e.currentTarget) closeSuccessDialog();
          }}
        >
          <div className="admin-orac-form-popup-dialog">
            <h3 id="admin-form-success-title">{successDialog.title}</h3>
            <p>{successDialog.body}</p>
            <button type="button" className="admin-action-button admin-orac-form-popup-ok" onClick={closeSuccessDialog}>
              OK
            </button>
          </div>
        </div>
      )}
    </main>
  );
}

export default AdminFormDetailsPage;
