// ===== Site-wide data =====
const NAV_ITEMS = [
  { id: 'home', label: 'Home' },
  { id: 'about', label: 'About' },
  { id: 'locations', label: 'Locations' },
  { id: 'sermons', label: 'Sermons' },
  { id: 'events', label: 'Events' },
  { id: 'ministries', label: 'Ministries' },
  { id: 'contact', label: 'Contact' },
];

const LOCATIONS = [
  {
    id: 'abu-dhabi',
    city: 'Abu Dhabi',
    country: 'United Arab Emirates',
    flag: '🇦🇪',
    time: '10:30 AM',
    day: 'Every Sunday',
    address: 'Al Mushrif Community Hall, Abu Dhabi, UAE',
    badge: 'Founding Campus',
    isMother: true,
    blurb: 'Where it all began in 2017 — the founding campus of Vision Generation, gathering in the heart of the capital.',
  },
  {
    id: 'dubai',
    city: 'Dubai',
    country: 'United Arab Emirates',
    flag: '🇦🇪',
    time: '1:30 PM',
    day: 'Every Sunday',
    address: 'Al Quoz Community Venue, Dubai, UAE',
    badge: 'UAE Campus',
    blurb: 'A growing family in the city of dreams — worshipping together every Sunday afternoon.',
  },
  {
    id: 'imus',
    city: 'Imus',
    country: 'Cavite, Philippines',
    flag: '🇵🇭',
    time: '9:00 AM',
    day: 'Every Sunday',
    address: 'Imus Community Center, Cavite, Philippines',
    badge: 'PH Campus',
    blurb: 'Carrying the vision home to the Philippines — a vibrant family in the heart of Cavite.',
  },
  {
    id: 'trece',
    city: 'Trece Martires',
    country: 'Cavite, Philippines',
    flag: '🇵🇭',
    time: '9:00 AM',
    day: 'Every Sunday',
    address: 'Trece Martires Worship Center, Cavite, Philippines',
    badge: 'PH Campus',
    blurb: 'A young, passionate community pressing in for revival in the city of martyrs.',
  },
];

const MINISTRIES = [
  { id: 'kids', icon: 'kids', name: 'VG Kids', tag: 'Ages 3–11', desc: 'A safe, joyful place where children encounter Jesus through worship, Bible stories, and play every Sunday.' },
  { id: 'youth', icon: 'youth', name: 'VG Youth', tag: 'Ages 12–24', desc: 'Raising a generation that knows who they are in Christ — bold, anchored, and full of fire.' },
  { id: 'worship', icon: 'worship', name: 'Worship & Creative', tag: 'Music · Production', desc: 'Singers, musicians, and creatives leading our church into the presence of God week after week.' },
  { id: 'men', icon: 'men', name: "Men's Ministry", tag: 'Brotherhood', desc: 'Men of conviction sharpening one another — building stronger fathers, husbands, and friends in Christ.' },
  { id: 'women', icon: 'women', name: "Women's Ministry", tag: 'Sisterhood', desc: 'Women growing in grace, courage, and identity — a sisterhood that prays, laughs, and builds together.' },
  { id: 'groups', icon: 'groups', name: 'Life Groups', tag: 'Community', desc: 'Smaller circles where real life happens — meeting in homes across our cities to grow together mid-week.' },
  { id: 'mission', icon: 'mission', name: 'Outreach & Missions', tag: 'Local · Global', desc: 'Bringing the love of Jesus to our neighborhoods and the nations — because we are blessed to bless.' },
  { id: 'discipleship', icon: 'discipleship', name: 'Discipleship', tag: 'Foundations', desc: 'A clear path from first step of faith to becoming a disciple who makes disciples — one journey at a time.' },
  { id: 'volunteer', icon: 'volunteer', name: 'Dream Team', tag: 'Volunteer', desc: 'Hospitality, kids, tech, ushers, and more — the volunteer family that makes Sunday possible.' },
];

const SERMONS = [
  { id: 's1', featured: true, title: "Blessed to Bless: Living a Life That Overflows", series: 'Blessed to Bless', speaker: 'Ps. Stephen Bala', date: 'May 4, 2025', length: '42 min', tag: 'Latest', desc: 'The heartbeat of our church in one phrase. Pastor Stephen unpacks what it really means to be blessed by God so that you become a blessing to your family, your city, and the nations.' },
  { id: 's2', title: 'A Faith That Moves Mountains', series: 'Mountain Movers', speaker: 'Ps. Stephen Bala', date: 'Apr 27, 2025', length: '38 min' },
  { id: 's3', title: 'The Power of a Praying Family', series: 'Built to Last', speaker: 'Ps. Stephen Bala', date: 'Apr 20, 2025', length: '45 min' },
  { id: 's4', title: 'When God Says Go', series: 'The Great Commission', speaker: 'Ps. Pamela Rose', date: 'Apr 13, 2025', length: '36 min' },
  { id: 's5', title: 'Anchored: Identity in Christ', series: 'Anchored', speaker: 'Ps. Mark Reyes', date: 'Apr 6, 2025', length: '40 min' },
  { id: 's6', title: 'Holy Spirit, Have Your Way', series: 'Spirit & Truth', speaker: 'Ps. Stephen Bala', date: 'Mar 30, 2025', length: '47 min' },
  { id: 's7', title: 'The Gift of Generations', series: 'Built to Last', speaker: 'Ps. Pamela Rose', date: 'Mar 23, 2025', length: '34 min' },
];

const SERIES = ['All Series', 'Blessed to Bless', 'Mountain Movers', 'Built to Last', 'Anchored', 'Spirit & Truth', 'The Great Commission'];

const EVENTS = [
  { id: 'e1', title: 'Vision Sunday 2025', date: 'Jun 1', time: '10:30 AM', location: 'All Campuses', category: 'Special', tag: 'Don\'t Miss', desc: 'Once a year we gather as one family to receive the vision God is putting on our pastors\' hearts for the year ahead.' },
  { id: 'e2', title: 'VG Youth Encounter Night', date: 'Jun 7', time: '6:30 PM', location: 'Abu Dhabi', category: 'Youth', desc: 'A night of worship, the Word, and encounter for ages 12–24.' },
  { id: 'e3', title: 'Family Picnic & Baptism', date: 'Jun 14', time: '8:00 AM', location: 'Dubai', category: 'Family', desc: 'Join us at the beach as we celebrate new life in Christ and break bread together as a family.' },
  { id: 'e4', title: "Women's Brunch: Anchored", date: 'Jun 21', time: '10:00 AM', location: 'Imus', category: 'Women', desc: 'A morning of worship, the Word, and warm community for the women of our church.' },
  { id: 'e5', title: "Men's Breakfast: Iron Sharpens Iron", date: 'Jun 28', time: '7:00 AM', location: 'Trece Martires', category: 'Men', desc: 'A monthly gathering of brothers — strong coffee, real talk, deep faith.' },
  { id: 'e6', title: 'VG Kids Camp', date: 'Jul 5–7', time: 'All Day', location: 'Abu Dhabi', category: 'Kids', desc: 'Three full days of fun, worship, and Bible adventure for ages 6–11.' },
  { id: 'e7', title: 'Night of Prayer', date: 'Jul 11', time: '8:00 PM', location: 'All Campuses', category: 'Prayer', desc: 'Every second Friday — our whole church family lifts their voice as one.' },
  { id: 'e8', title: 'Outreach Saturday', date: 'Jul 19', time: '9:00 AM', location: 'Cavite', category: 'Outreach', desc: 'Serving our neighborhoods with food, prayer, and the love of Jesus.' },
];

const EVENT_CATEGORIES = ['All Events', 'Special', 'Youth', 'Family', 'Women', 'Men', 'Kids', 'Prayer', 'Outreach'];

const BELIEFS = [
  { title: 'The Bible', body: 'The Bible is the inspired, infallible Word of God — our final authority for faith, life, and everything in between.' },
  { title: 'Jesus Christ', body: 'Jesus is fully God and fully man — born of a virgin, crucified for our sins, risen, ascended, and coming again as Lord and Savior.' },
  { title: 'Salvation', body: 'Salvation is by grace alone, through faith alone, in Jesus Christ alone — a free gift available to anyone who calls on His name.' },
  { title: 'The Holy Spirit', body: 'The Holy Spirit empowers every believer to live a Spirit-filled life — comforter, helper, teacher, and giver of gifts for the building of the Church.' },
  { title: 'Prayer', body: 'Prayer is the privilege of every believer — a real conversation with a living God who hears, answers, and moves on behalf of His people.' },
  { title: 'Worship', body: 'We were made to worship. Our gatherings are filled with passionate, Spirit-led worship that lifts up the name of Jesus above every other name.' },
  { title: 'Discipleship', body: 'Following Jesus is a lifelong journey. We are committed to growing as disciples and helping others walk that same road.' },
  { title: 'Evangelism', body: 'The Good News is too good to keep. We are sent to share the love of Jesus with our families, our cities, and the nations.' },
  { title: 'Healing', body: 'We believe Jesus still heals today — body, soul, and spirit. We pray boldly and trust God for the miraculous.' },
  { title: 'The Great Commission', body: '"Go and make disciples of all nations." This is our mandate, our heartbeat, and the reason our church exists across two countries and counting.' },
];

// ─────────────────────────────────────────────────────────────────────
// Site-content provider — wires the static SPA to the live CMS.
//
// SERMONS / EVENTS above are seed defaults (used while the API call
// is in flight, and as a safety net if the network fails). On mount,
// the provider fetches /api/site/content and replaces the in-memory
// arrays with whatever the senior pastor has set in /admin/site-cms.
//
// Components consume the data via `useSiteContent()` instead of
// importing the seed arrays directly, so a save on the CMS surfaces
// on the next page load without code changes.
// ─────────────────────────────────────────────────────────────────────

// Helper: compute the series pill list from a sermon array. Used both
// on initial render (against the seeded SERMONS) and after the API
// response lands. Always prepends "All Series" so the filter has a
// clear-all affordance regardless of what's in the data.
function deriveSeriesList(sermons) {
  const seen = new Set();
  const list = ['All Series'];
  for (const s of sermons || []) {
    const name = ((s && s.series) || '').trim();
    if (!name || seen.has(name)) continue;
    seen.add(name);
    list.push(name);
  }
  return list;
}

const SiteContentContext = React.createContext({
  sermons: SERMONS,
  events: EVENTS,
  series: deriveSeriesList(SERMONS),
  loading: false,
});

function SiteContentProvider({ children }) {
  const [state, setState] = React.useState({
    sermons: SERMONS,
    events: EVENTS,
    series: deriveSeriesList(SERMONS),
    loading: true,
  });

  React.useEffect(() => {
    let cancelled = false;
    fetch('/api/site/content', { cache: 'no-store' })
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => {
        if (cancelled || !json) return;
        // The API guarantees the field-name shape matches the seed
        // arrays, so we can swap them in 1-for-1. Empty result =
        // the senior pastor hasn't seeded the CMS yet; fall back to
        // the bundled seeds rather than rendering nothing.
        const liveSermons =
          Array.isArray(json.sermons) && json.sermons.length > 0
            ? json.sermons
            : SERMONS;
        const liveEvents =
          Array.isArray(json.events) && json.events.length > 0
            ? json.events
            : EVENTS;
        // Series ordering: prefer the API list (alphabetical with
        // count), fall back to deriving from the live sermons. Always
        // prepend the "All Series" affordance.
        const apiSeries =
          Array.isArray(json.series) && json.series.length > 0
            ? ['All Series', ...json.series.map((s) => s && s.name).filter(Boolean)]
            : deriveSeriesList(liveSermons);
        setState({
          sermons: liveSermons,
          events: liveEvents,
          series: apiSeries,
          loading: false,
        });
      })
      .catch(() => {
        if (cancelled) return;
        setState((s) => ({ ...s, loading: false }));
      });
    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <SiteContentContext.Provider value={state}>
      {children}
    </SiteContentContext.Provider>
  );
}

function useSiteContent() {
  return React.useContext(SiteContentContext);
}

Object.assign(window, {
  NAV_ITEMS,
  LOCATIONS,
  MINISTRIES,
  SERMONS,
  SERIES,
  EVENTS,
  EVENT_CATEGORIES,
  BELIEFS,
  SiteContentProvider,
  useSiteContent,
});
