// About-section content store — fetches the singleton About row from the API.
//
// Public consumers (landing/mobile) call useAboutContent() and read the
// returned object. Admin uses the same hook plus the `update` mutator to
// write through to PUT /api/admin/about. A safe fallback shape is rendered
// while the initial fetch is in flight so the public site never flashes
// blank.

// Defaults render immediately on mount and are overwritten when the API
// fetch resolves. Mirroring the seed copy means the public site degrades
// gracefully if the API is unreachable.
const ABOUT_DEFAULTS = {
  headline: 'WHAT IS TRAINING DAY?',
  intro: [
    "Training Day is a free, full-day event built for anyone interested in Air Force Special Warfare careers. Whether you're just starting to explore the pipeline or you've been training on your own for months, this is your chance to experience what AFSW demands firsthand.",
    "You'll train alongside active-duty AFSW operators and recruiters through a full day of structured events designed to challenge you physically and mentally while giving you a real look at what lies ahead.",
  ],
  expect: [
    { num: '01', title: 'Info Brief',        body: 'Get the real answers. Learn about the eight AFSW career fields, what each pipeline looks like, how to prepare, and what it takes to earn your place. Ask questions directly to the people who have been through it.' },
    { num: '02', title: 'Physical Training', body: 'A coached workout led by AFSW cadre. This is not a smoke session. It is a structured training evolution designed to push you, assess your baseline, and show you where you stand.' },
    { num: '03', title: 'Water Confidence',  body: 'Get in the pool. Water confidence events are a cornerstone of the AFSW pipeline, and Training Day gives you a controlled introduction to what that looks like. No experience required.' },
    { num: '04', title: 'Mentorship',        body: 'One-on-one and small group time with active-duty Special Warfare operators and recruiters. Get honest guidance on your training plan, your timeline, and your next steps.' },
  ],
  who: [
    { label: 'CAREERS',    text: 'Anyone curious about Pararescue (PJ), Combat Control (CCT), Tactical Air Control Party (TACP), Special Reconnaissance (SR), Special Tactics Officer (STO), Combat Rescue Officer (CRO), Explosive Ordnance Disposal (EOD), or Survival, Evasion, Resistance, Escape (SERE).' },
    { label: 'FITNESS',    text: 'All fitness levels welcome. You do not need to be pipeline-ready to attend.' },
    { label: 'AGE',        text: '17 and up. Candidates under 18 require guardian permission.' },
    { label: 'BACKGROUND', text: 'No military experience required. Civilians, ROTC cadets, DEP members, and active duty are all welcome.' },
  ],
  bottomLine: 'Training Day is free. No cost, no commitment, no recruiter pressure. Just show up ready to work and find out if this is the path for you.',
};

const _aboutCache = { content: null, loading: false };

function _publish(content) {
  _aboutCache.content = content;
  window.dispatchEvent(new CustomEvent('aboutcontentchange', { detail: content }));
}

// Debounced PUT so typing into a textarea doesn't fire a request per char.
let _saveTimer = null;
function _scheduleSave(content) {
  if (_saveTimer) clearTimeout(_saveTimer);
  _saveTimer = setTimeout(async () => {
    _saveTimer = null;
    try {
      const r = await window.api.apiPut('/api/admin/about', content);
      if (r?.about) _publish(r.about);
    } catch (err) {
      console.warn('About save failed:', err.message);
      window.dispatchEvent(new CustomEvent('aboutcontenterror', { detail: err }));
    }
  }, 700);
}

function useAboutContent() {
  const [content, setContent] = React.useState(() => _aboutCache.content || ABOUT_DEFAULTS);
  const [loading, setLoading] = React.useState(_aboutCache.content === null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    const onChange = (e) => setContent(e.detail);
    window.addEventListener('aboutcontentchange', onChange);

    if (_aboutCache.content === null && !_aboutCache.loading) {
      _aboutCache.loading = true;
      window.api.apiGet('/api/about')
        .then(r => { if (r?.about) _publish(r.about); })
        .catch(err => setError(err))
        .finally(() => { _aboutCache.loading = false; setLoading(false); });
    } else {
      setLoading(false);
    }

    return () => window.removeEventListener('aboutcontentchange', onChange);
  }, []);

  // Admin-only patch — accepts a partial object or an updater function. The
  // local cache updates immediately so typing feels instant; the PUT is
  // debounced so we don't fire one request per keystroke.
  const update = React.useCallback((patch) => {
    const prev = _aboutCache.content || ABOUT_DEFAULTS;
    const next = typeof patch === 'function' ? patch(prev) : { ...prev, ...patch };
    _publish(next);
    _scheduleSave(next);
  }, []);

  // Reset is a no-op; defaults are server-side. Keep the function so existing
  // UI doesn't error.
  const reset = React.useCallback(async () => {
    if (!window.confirm('About content is now server-managed. Re-seed via `npm run db:seed:local` on the backend.')) return;
  }, []);

  return [content, update, reset];
}

Object.assign(window, { useAboutContent, ABOUT_DEFAULTS });
