// Family Bible Stories — short 9:16 narrative films (modern parables that
// open into Scripture). Single compressed.mp4 per story; no separate preview,
// so the feed uses the same file for the card and the full play.
//
// DYNAMIC: fetches the R2 index on load and parses every compressed.mp4 it
// references, exactly like the music catalog. Drop a new story folder into
// the bucket + add it to family-bible-studies.html and it shows up here
// automatically. The bundled list below is the offline/CORS fallback.
const FAMILY_BASE = `${CDN}/family-bible-studies`;
const FAMILY_INDEX_URL = "https://pub-28a96ef5d275416ea27ae14f6e84c132.r2.dev/family-bible-studies.html";

const FAMILY_BUNDLED = [
  ["the-gloves-on-the-windowsill",              "The Gloves on the Windowsill"],
  ["the-list-on-the-refrigerator-door",         "The List on the Refrigerator Door"],
  ["what-i-couldn-t-pack",                       "What I Couldn\u2019t Pack"],
  ["when-a-man-takes-a-city",                    "When a Man Takes a City"],
  ["when-jealousy-grew-quietly",                 "When Jealousy Grew Quietly"],
  ["when-the-bag-got-heavy",                     "When the Bag Got Heavy"],
  ["when-the-lights-came-on-across-the-street",  "When the Lights Came On Across the Street"],
  ["when-the-maul-came-down",                    "When the Maul Came Down"],
];

function prettifyFamilyTitle(s) {
  if (!s) return s;
  let t = s.trim();
  // Restore contractions the index strips ("Couldn T" → "Couldn't", "I M" → "I'm").
  t = t.replace(/\b([A-Za-z]+n)\sT\b/g, "$1't");      // Couldn T, Don T, Isn T
  t = t.replace(/\bI\sM\b/g, "I'm");
  t = t.replace(/\b([A-Za-z]+)\sRe\b/g, "$1're");
  t = t.replace(/\b([A-Za-z]+)\sVe\b/g, "$1've");
  t = t.replace(/\b([A-Za-z]+)\sLl\b/g, "$1'll");
  // Lowercase minor words unless they start the title.
  const minor = new Set(["a", "an", "the", "of", "and", "or", "to", "in", "on", "at", "by", "for", "across"]);
  t = t.split(/\s+/).map((w, i) => (i > 0 && minor.has(w.toLowerCase()) ? w.toLowerCase() : w)).join(" ");
  return t;
}

function familyStoryFrom(slug, title) {
  const url = `${FAMILY_BASE}/${slug}/compressed.mp4`;
  const raw = title || slug.split("/").pop().replace(/-/g, " ").replace(/\b\w/g, c => c.toUpperCase());
  return {
    id: "family-" + slug,
    slug,
    title: prettifyFamilyTitle(raw),
    shorts: url,   // feed card source
    full: url,     // "Full Video" link target (same file)
    scripture: null,
    collectionTitle: "Family Bible Stories",
    kind: "family",
  };
}

// Seed window immediately with the bundled list so the first paint has cards.
const FAMILY_STORIES = FAMILY_BUNDLED.map(([slug, title]) => familyStoryFrom(slug, title));
Object.assign(window, { FAMILY_STORIES });

// ─── Live index parse ────────────────────────────────────────────────────────
async function fetchFamilyIndex() {
  try {
    const res = await fetch(FAMILY_INDEX_URL);
    if (!res.ok) throw new Error("HTTP " + res.status);
    const html = await res.text();
    const doc = new DOMParser().parseFromString(html, "text/html");
    const found = [];
    const seen = new Set();
    const refs = doc.querySelectorAll('[src*="family-bible-studies"], [href*="family-bible-studies"]');
    refs.forEach((el) => {
      const url = el.getAttribute("src") || el.getAttribute("href") || "";
      const m = url.match(/family-bible-studies\/(.+?)\/compressed\.mp4/);
      if (!m) return;
      const slug = m[1];
      if (seen.has(slug)) return;
      seen.add(slug);
      let title = null;
      let card = el.closest("article, section, li, div.card, [class*='card']");
      if (!card) card = el.parentElement?.parentElement || null;
      if (card) {
        const h = card.querySelector("h1, h2, h3, h4");
        if (h) title = h.textContent.trim();
      }
      found.push(familyStoryFrom(slug, title));
    });
    return found.length ? found : null;
  } catch {
    return null;
  }
}

// Reactive hook: returns the bundled list instantly, then swaps to the live
// list once the index resolves. Consumers re-render automatically.
function useFamilyStories() {
  const [list, setList] = React.useState(window.FAMILY_STORIES);
  React.useEffect(() => {
    let cancelled = false;
    fetchFamilyIndex().then((live) => {
      if (cancelled || !live) return;
      window.FAMILY_STORIES = live;
      setList(live);
    });
    return () => { cancelled = true; };
  }, []);
  return list;
}

Object.assign(window, { useFamilyStories });
