// Data layer: maps the real NLC APIs into the shapes screens render, plus
// demo placeholder content used when no worker is behind the server (design
// preview) and as instant-boot cache fallback.
(function () {
  // ---- mapping real API data → screen shapes --------------------------------
  const THEMES = ['navy', 'leaf', 'wheat', 'clay'];
  function themeFor(name) {
    let h = 0;
    const s = String(name || '');
    for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
    return THEMES[h % THEMES.length];
  }

  const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  function prettyDate(iso) { // "2026-06-07" → "June 7, 2026" (no timezone drift)
    const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso || '');
    if (!m) return iso || '';
    return `${MONTHS[+m[2] - 1]} ${+m[3]}, ${m[1]}`;
  }

  function mapSermon(raw) {
    const seriesName = raw.series || '';
    return {
      id: raw.uid || raw.id,
      title: raw.title || 'Untitled message',
      speaker: raw.speaker || '',
      seriesName,
      part: raw.part || '',
      theme: themeFor(seriesName || raw.title),
      date: prettyDate(raw.date),
      rawDate: raw.date || '',
      length: raw.length || '',
      scripture: raw.scripture || '',
      book: raw.book || '',
      topic: raw.topic || '',
      blurb: raw.description || raw.notes || '',
      thumbnail: raw.thumbnail || null,
      videoUrl: raw.r2Key ? `/api/video/${raw.r2Key}` : (raw.videoUrl || null),
      hls: raw.hlsUrl || (raw.playback && raw.playback.hls) || null,
      archivedLocally: !!raw.archivedLocally,
      progress: 0, // filled from synced state at render time
    };
  }

  function mapEvent(raw) {
    const d = raw.startsAt ? new Date(raw.startsAt) : null;
    return {
      id: raw.id,
      title: raw.name || 'Church event',
      day: d ? String(d.getDate()).padStart(2, '0') : '··',
      mo: d ? d.toLocaleDateString('en-US', { month: 'short' }).toUpperCase() : '',
      when: d ? d.toLocaleDateString('en-US', { weekday: 'short' }) + ' · ' +
        (raw.allDay ? 'All day' : d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })) : '',
      startsAt: raw.startsAt,
      loc: raw.location || 'New Life Church',
      tag: '',
      theme: themeFor(raw.name),
      summary: raw.summary || '',
      description: String(raw.description || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(),
      imageUrl: raw.imageUrl || null,
      churchCenterUrl: raw.churchCenterUrl || null,
    };
  }

  function mapGallery(raw) {
    return {
      id: raw.id,
      title: raw.title || 'Gallery',
      date: prettyDate(raw.date) || raw.date || '',
      count: raw.photoCount || raw.count || 0,
      theme: themeFor(raw.title),
      coverUrl: raw.coverPhotoId ? `/api/photo/${raw.id}/${raw.coverPhotoId}` : null,
    };
  }

  // ---- Bible: all 66 books with chapter counts ------------------------------
  const BOOKS = [
    ['Genesis',50],['Exodus',40],['Leviticus',27],['Numbers',36],['Deuteronomy',34],
    ['Joshua',24],['Judges',21],['Ruth',4],['1 Samuel',31],['2 Samuel',24],
    ['1 Kings',22],['2 Kings',25],['1 Chronicles',29],['2 Chronicles',36],['Ezra',10],
    ['Nehemiah',13],['Esther',10],['Job',42],['Psalms',150],['Proverbs',31],
    ['Ecclesiastes',12],['Song of Solomon',8],['Isaiah',66],['Jeremiah',52],['Lamentations',5],
    ['Ezekiel',48],['Daniel',12],['Hosea',14],['Joel',3],['Amos',9],
    ['Obadiah',1],['Jonah',4],['Micah',7],['Nahum',3],['Habakkuk',3],
    ['Zephaniah',3],['Haggai',2],['Zechariah',14],['Malachi',4],
    ['Matthew',28],['Mark',16],['Luke',24],['John',21],['Acts',28],
    ['Romans',16],['1 Corinthians',16],['2 Corinthians',13],['Galatians',6],['Ephesians',6],
    ['Philippians',4],['Colossians',4],['1 Thessalonians',5],['2 Thessalonians',3],['1 Timothy',6],
    ['2 Timothy',4],['Titus',3],['Philemon',1],['Hebrews',13],['James',5],
    ['1 Peter',5],['2 Peter',3],['1 John',5],['2 John',1],['3 John',1],
    ['Jude',1],['Revelation',22],
  ];
  // Parse "1 Corinthians 12:7-11" → { book, chapter, key: "1 Corinthians 12" }
  function parseRef(ref) {
    const m = /^([1-3]?\s?[A-Za-z ]+?)\s+(\d+)/.exec(String(ref || '').trim());
    if (!m) return null;
    const book = m[1].trim();
    const found = BOOKS.find(([b]) => b.toLowerCase() === book.toLowerCase());
    if (!found) return null;
    return { book: found[0], chapter: +m[2], key: `${found[0]} ${+m[2]}` };
  }

  // ---- Bundled chapters (instant offline; the rest load via /api/bible) -----
  const bibleText = {
    'John 1': [
      [1, 'In the beginning was the Word, and the Word was with God, and the Word was God.'],
      [2, 'The same was in the beginning with God.'],
      [3, 'All things were made through him. Without him, nothing was made that has been made.'],
      [4, 'In him was life, and the life was the light of men.'],
      [5, 'The light shines in the darkness, and the darkness hasn’t overcome it.'],
      [6, 'There came a man sent from God, whose name was John.'],
      [7, 'The same came as a witness, that he might testify about the light, that all might believe through him.'],
      [8, 'He was not the light, but was sent that he might testify about the light.'],
      [9, 'The true light that enlightens everyone was coming into the world.'],
      [10, 'He was in the world, and the world was made through him, and the world didn’t recognize him.'],
      [11, 'He came to his own, and those who were his own didn’t receive him.'],
      [12, 'But as many as received him, to them he gave the right to become God’s children, to those who believe in his name.'],
      [13, 'who were born, not of blood, nor of the will of the flesh, nor of the will of man, but of God.'],
      [14, 'The Word became flesh, and lived among us. We saw his glory, such glory as of the one and only Son of the Father, full of grace and truth.'],
    ],
    'Psalms 23': [
      [1, 'Yahweh is my shepherd; I shall lack nothing.'],
      [2, 'He makes me lie down in green pastures. He leads me beside still waters.'],
      [3, 'He restores my soul. He guides me in the paths of righteousness for his name’s sake.'],
      [4, 'Even though I walk through the valley of the shadow of death, I will fear no evil, for you are with me. Your rod and your staff, they comfort me.'],
      [5, 'You prepare a table before me in the presence of my enemies. You anoint my head with oil. My cup runs over.'],
      [6, 'Surely goodness and loving kindness shall follow me all the days of my life, and I will dwell in Yahweh’s house forever.'],
    ],
  };

  // ---- Demo placeholder content (design preview without a worker) -----------
  const user = { first: 'Hannah', name: 'Hannah Brooks', email: 'hannah.brooks@gmail.com', membership: 'Member', role: 'member' };

  const demoSermons = [
    { uid: 'demo1', title: 'The Wall Between Us', speaker: 'Pastor Mike Carter', series: 'Loving Down Walls',
      date: '2026-06-08', length: '38 min', scripture: 'Ephesians 2:14-18', topic: 'Reconciliation',
      description: 'Christ himself is our peace, who has broken down the dividing wall of hostility.' },
    { uid: 'demo2', title: 'Strangers and Neighbors', speaker: 'Pastor Mike Carter', series: 'Loving Down Walls',
      date: '2026-06-01', length: '41 min', scripture: 'Luke 10:25-37', topic: 'Compassion',
      description: 'The parable of the Good Samaritan asks an uncomfortable question — and answers it with action.' },
    { uid: 'demo3', title: 'When Grace Walks In', speaker: 'Pastor Dana Reyes', series: 'Loving Down Walls',
      date: '2026-05-25', length: '35 min', scripture: 'John 4:1-26', topic: 'Grace',
      description: 'At a well in the heat of the day, Jesus crosses every wall his culture built.' },
  ];
  const demoGalleries = [
    { id: 'g1', title: 'Baptism Sunday', date: '2026-06-01', photoCount: 48 },
    { id: 'g2', title: 'Kids Camp 2026', date: '2026-05-24', photoCount: 126 },
    { id: 'g3', title: 'Easter Gathering', date: '2026-04-20', photoCount: 91 },
    { id: 'g4', title: 'Serve Day', date: '2026-03-22', photoCount: 57 },
  ];
  const demoEvents = [
    { id: 'e1', name: 'Sunday Worship', startsAt: '2026-06-14T10:00:00-04:00', location: 'Main Auditorium' },
    { id: 'e2', name: 'Wednesday Bible Study', startsAt: '2026-06-17T19:00:00-04:00', location: 'Gathering Room' },
    { id: 'e3', name: 'Youth Summer Kickoff', startsAt: '2026-06-19T18:30:00-04:00', location: 'The Barn' },
  ];
  const demoAnnouncements = [
    { id: 'a1', title: 'Baptisms — sign up by June 18', body: 'Ready to take your next step? We’ll baptize during the June 22 service.', tag: 'Next Steps', theme: 'leaf' },
    { id: 'a2', title: 'VBS volunteers needed', body: 'Vacation Bible School is July 14–18. We need 20 more helpers.', tag: 'Serve', theme: 'navy' },
  ];
  const demoServing = [
    { id: 'sv1', team: 'Worship Team', position: 'Vocals', date: 'Sun, Jun 15', mo: 'JUN', day: '15',
      time: 'Rehearsal 8:30 AM · Service 10:00 AM', plan: 'Sunday Worship', status: 'confirmed', theme: 'navy' },
    { id: 'sv2', team: 'Kids Ministry', position: 'Elementary Leader', date: 'Sun, Jun 22', mo: 'JUN', day: '22',
      time: '9:30 AM – 11:30 AM', plan: 'New Life Kids', status: 'unconfirmed', theme: 'leaf', needBy: 'Respond by Jun 18' },
  ];

  window.NLData = {
    // live content — populated from /api/bootstrap by app.jsx (demo until then)
    mode: 'demo',
    user,
    sermons: demoSermons.map(mapSermon),
    galleries: demoGalleries.map(mapGallery),
    events: demoEvents.map(mapEvent),
    announcements: demoAnnouncements,
    serving: demoServing,
    live: { isLive: false },
    config: { givingUrl: 'https://newlifepetersburg.com/give', churchCenterUrl: '' },
    // bible
    BOOKS, bibleText, parseRef,
    // helpers
    mapSermon, mapEvent, mapGallery, themeFor, prettyDate,
  };
})();
