// Pacific.AFSWS event data — fetched from the live Apps Script backend.
//
// The backend returns rows with the full v2 schema but most fields may be
// blank. The enrich() helper below merges those sparse rows with defaults
// so every downstream component can read the full shape (activities list,
// eligibility block, FAQ entries, etc.) without null-checks.
//
// ── Backend contract ──
// GET {BACKEND_URL}?action=getEvents
//   -> { events: [ { id, title, date, time, endTime, location, city, type,
//                    tag, capacity, signed, image, opord: { url, filename }|null,
//                    brief, valueProp, details, activities, requirements,
//                    whatToExpect, eligibility, faq, host, qrCode }, ... ] }
//
// POST body is JSON string with Content-Type: text/plain (per Apps Script
// CORS preflight quirk — see submitSignup below).

const BACKEND_URL = 'https://script.google.com/macros/s/AKfycbzaxWhX7Qlar9oUUCHkDwheSHvTJkHvk3i0YBNZx43JQ1z2ysFDn0SHuS2Nag2vXipj8w/exec';

const EVENT_DEFAULTS = {
  valueProp: 'Train with operators. Find out where you stand. Leave better.',
  activities: [
    'Work alongside current AFSPECWAR personnel',
    'Get honest feedback on your fitness and mindset',
    'Meet other candidates on the same path',
  ],
  eligibility: {
    who: 'Open to anyone considering AFSPECWAR or already in the pipeline.',
    age: '16 to 39 years old',
    citizenship: 'U.S. citizenship required for pipeline entry. All welcome at events.',
    fitness: 'General baseline fitness. Specific standards noted per event.',
  },
  whatToExpect: 'Arrive early for check-in. Bring ID. Parking is free but limited. Dress for the weather, not the photo.',
  operatorCreds: 'Hosted by Pacific.AFSWS. Active AFSPECWAR personnel on-site for questions.',
  faq: [
    {
      q: "I'm not in the military yet. Can I still come?",
      a: 'Yes. Most attendees are candidates or considering the pipeline. Events are free and open to anyone serious about the work.',
    },
    {
      q: "I'm not in shape yet. Should I wait?",
      a: 'No. Show up and find your starting point. We meet you where you are. The only wrong move is not starting.',
    },
    {
      q: 'Is there a liability waiver?',
      a: 'Yes. You will receive a waiver by email after you sign up. It must be signed and returned before the event. No waiver, no entry.',
    },
    {
      q: 'What should I eat before?',
      a: 'Light and early. A small meal 2 to 3 hours before, plenty of water the day prior. No heavy food within 90 minutes of physical events.',
    },
    {
      q: 'Is this selection or development?',
      a: 'Development. These are community events to build capacity, test standards, and connect with the community. Selection happens through official channels.',
    },
    {
      q: 'Can I bring a friend?',
      a: 'They need to sign up separately. One spot per person. Space is limited and no-shows forfeit future priority.',
    },
  ],
};

// Merge per-event fields with DEFAULTS so downstream code can always read the full shape.
// Backend rows are sparse by default (only id/title/date/time/location populated);
// this fills in activities/eligibility/faq/etc. so the 6-block event page renders.
function enrich(ev) {
  return {
    ...EVENT_DEFAULTS,
    ...ev,
    eligibility: { ...EVENT_DEFAULTS.eligibility, ...(ev.eligibility || {}) },
    // faq: event-specific FAQs REPLACE defaults if provided, otherwise use defaults
    faq: (ev.faq && ev.faq.length) ? ev.faq : EVENT_DEFAULTS.faq,
    // activities/requirements: same pattern — event-specific wins, else defaults
    activities: (ev.activities && ev.activities.length) ? ev.activities : EVENT_DEFAULTS.activities,
    // type defaults to a sensible label if backend row left it blank
    type: ev.type || 'AFSPECWAR Development',
    tag: ev.tag || 'ALL LEVELS',
  };
}

// Fetch active events from backend. Returns enriched array.
// Rejects on network/HTTP/parse errors so caller can render error UI.
async function fetchEvents() {
  const url = BACKEND_URL + '?action=getEvents';
  const resp = await fetch(url, { method: 'GET' });
  if (!resp.ok) throw new Error('HTTP ' + resp.status);
  const data = await resp.json();
  if (data.error) throw new Error(data.error);
  if (!Array.isArray(data.events)) throw new Error('Malformed response');
  return data.events.map(enrich);
}

// POST a signup to the backend. Returns { ok, status } where status is
// 'confirmed' or 'waitlist'. Rejects on network/HTTP/parse errors.
//
// NOTE: body is sent as text/plain to avoid Apps Script CORS preflight.
// The script's doPost reads e.postData.contents as a JSON string regardless.
async function submitSignup(payload) {
  const resp = await fetch(BACKEND_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'text/plain;charset=utf-8' },
    body: JSON.stringify({ action: 'signup', ...payload }),
  });
  if (!resp.ok) throw new Error('HTTP ' + resp.status);
  const data = await resp.json();
  if (data.error) throw new Error(data.error);
  return data;
}

// Expose to global scope (babel-standalone has no module system).
window.BACKEND_URL = BACKEND_URL;
window.EVENT_DEFAULTS = EVENT_DEFAULTS;
window.fetchEvents = fetchEvents;
window.submitSignup = submitSignup;
window.enrichEvent = enrich;

// EVENTS starts empty. App loads it via fetchEvents() on mount and sets
// React state. Components read events from props passed down from App,
// not from window.EVENTS directly, so updates propagate through React.
window.EVENTS = [];
