// Blog content data — async Directus CMS loader with hardcoded fallbacks

// ---------------------------------------------------------------------------
// PALETTES (hardcoded, synchronous)
// ---------------------------------------------------------------------------
const PALETTES = {
  "gold-maroon": {
    name: "Gold & Maroon",
    gold: "#C09463",
    goldDeep: "#9A6F3F",
    accent: "#5C1A1B",
    accentSoft: "#7A2A2B",
    ink: "#1F1714",
    paper: "#FAF6EE",
    paperWarm: "#F2EADB",
    rule: "rgba(192,148,99,0.35)"
  },
  "gold-green": {
    name: "Gold & Forest",
    gold: "#C09463",
    goldDeep: "#9A6F3F",
    accent: "#1F3A2D",
    accentSoft: "#2E5142",
    ink: "#16201B",
    paper: "#F7F3E8",
    paperWarm: "#EDE6D2",
    rule: "rgba(192,148,99,0.35)"
  },
  "gold-ink": {
    name: "Gold & Ink",
    gold: "#C09463",
    goldDeep: "#9A6F3F",
    accent: "#1A1D24",
    accentSoft: "#33384A",
    ink: "#13161C",
    paper: "#F6F2E8",
    paperWarm: "#EAE2CE",
    rule: "rgba(192,148,99,0.35)"
  },
  "antique-rose": {
    name: "Antique Rose",
    gold: "#B68A55",
    goldDeep: "#8A6638",
    accent: "#7A3B3F",
    accentSoft: "#9A5256",
    ink: "#2A1C1D",
    paper: "#F8EFE7",
    paperWarm: "#F0E2D4",
    rule: "rgba(182,138,85,0.4)"
  },
  "gul-lala": {
    name: "Gul-Lala Tulip",
    gold: "#C9A0A6",       // blush accent
    goldDeep: "#A8555E",   // rose primary
    accent: "#A8555E",     // rose primary — buttons, chips
    accentSoft: "#8C4049", // deep rose — hover
    ink: "#4A4440",        // warm brown body text
    paper: "#FAF7F0",      // cream page background
    paperWarm: "#FFFDF9",  // near-white card background
    rule: "rgba(201,160,166,0.35)"
  }
};

window.PALETTES = PALETTES;

// ---------------------------------------------------------------------------
// CMS configuration
// ---------------------------------------------------------------------------
const DIRECTUS_URL = "https://directcms.happythreads4u.in";

async function apiGet(path) {
  const res = await fetch(`${DIRECTUS_URL}${path}`);
  if (!res.ok) throw new Error(`API ${path} returned ${res.status}`);
  return (await res.json()).data;
}

function formatDate(isoDate) {
  if (!isoDate) return "";
  return new Date(isoDate + "T00:00:00").toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric"
  });
}

window.assetUrl = function(fileId, { w = 1200, h = 800 } = {}) {
  if (!fileId) return null;
  return `${DIRECTUS_URL}/assets/${fileId}?width=${w}&height=${h}&fit=cover`;
};

window.imageFor = function(kind, id, w = 1200, h = 800) {
  return `https://picsum.photos/seed/sdbw-${kind}-${id}/${w}/${h}`;
};

// ---------------------------------------------------------------------------
// FALLBACK data (used when CMS is unavailable)
// ---------------------------------------------------------------------------

const MOCK_IMAGE_BASE = window.MOCK_IMAGE_BASE || "assets/mock-images/";
const natureImage = (file) => `${MOCK_IMAGE_BASE}${file}`;

const FALLBACK_CATEGORIES = [
  { id: "home",       label: "Home",       intro: "" },
  { id: "culture",    label: "Culture",    intro: "" },
  { id: "marriage",   label: "Marriage",   intro: "" },
  { id: "motherhood", label: "Motherhood", intro: "" },
  { id: "household",  label: "Household",  intro: "" },
  { id: "faith",      label: "Faith",      intro: "" },
  { id: "travel",     label: "Travel",     intro: "" },
  { id: "work",       label: "Work",       intro: "" },
  { id: "podcast",    label: "Podcast",    intro: "" }
];

const FALLBACK_ARTICLES = [
  {
    id: "threads-of-heritage",
    slug: "threads-of-heritage",
    title: "Threads of Heritage",
    subtitle: "The rida and its storied embroidery, traced through six generations",
    category: "culture",
    author: "Sakina N.",
    date: "Apr 21, 2026",
    readTime: "11 min read",
    featured: true,
    image: "assets/threads-of-heritage.jpg",
    imageAlt: "A grandmother's hands resting on a rida embroidered with trailing florals, with a manuscript and magnifying glass nearby",
    imageCaption: "The rida as a woman's hand-embroidered map of her line.",
    likes: 126,
    comments: [
      { author: "Zahra", text: "This brought back the exact way my nani folded her rida." },
      { author: "Mariam", text: "The image and essay feel beautifully paired." }
    ],
    excerpt:
      "A grandmother folds her rida the way her mother taught her, the way her mother before that — corner to corner, hem at the heart. The embroidery has changed. The folding has not.",
    tags: [],
    body: [
      "On a slow Surat afternoon, the air thick with the perfume of cardamom from the kitchen, my grandmother spread her rida across the dining table like a cartographer unrolling a map. \"This one,\" she said, pressing her thumb to a sun-bleached corner, \"your great-grandmother stitched in the year the river flooded.\"",
      "The rida is a two-piece dress worn by Dawoodi Bohra women — a pardi that drapes the head and shoulders, and a ghaghro that falls to the feet. It is the most public garment a woman owns, and so it is also the most private. The embroidery is hers. The choice of cotton, the placement of lace, the colour she chooses on the morning of a wedding — these are decisions made in quiet rooms with mothers and aunts, generations of taste folded into a single hem.",
      "What is often missed by those outside the community is how the rida is read. A woman entering a hall can, with a glance, tell you whose mother stitched whose border; whose family came from Yemen by way of Gujarat; whose taste leans modern, whose runs deep with the old patterns from Burhanpur. It is a language without grammar, and the speakers are all women."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "The embroidery has changed. The folding has not."
  },
  {
    id: "voices-burhanpur",
    slug: "voices-burhanpur",
    title: "Voices from Burhanpur",
    subtitle: "Three generations of women scholars, in their own words",
    category: "work",
    author: "Maryam T.",
    date: "Apr 12, 2026",
    readTime: "14 min read",
    featured: false,
    image: natureImage("forest-path.svg"),
    imageAlt: "A winding path through tall forest trees",
    imageCaption: "Mock nature image — forest path in soft light",
    likes: 92,
    comments: [
      { author: "Sakina", text: "I would love more oral histories from Burhanpur." }
    ],
    excerpt:
      "An oral history project recorded in the alleys of a small Madhya Pradesh town that has produced more women teachers than any other Bohra mohalla in India.",
    tags: [],
    body: [
      "Burhanpur is not a large town. You can walk its principal lanes in a morning, and most of the older residents will know who you are looking for before you finish the sentence. But for a century and a half, this small place has held an outsized weight in the intellectual life of Bohra women.",
      "We sat with three women — Bibi Husaina (88), her daughter Sakina (62), and her granddaughter Insiyah (29) — over three afternoons of tea and the kind of questions that do not have short answers."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "I was taught to read aloud before I was taught to whisper."
  },
  {
    id: "kitchen-as-memory",
    slug: "kitchen-as-memory",
    title: "The Kitchen as Memory",
    subtitle: "Heirloom recipes passed from mother to daughter, written down for the first time",
    category: "culture",
    author: "Fatema R.",
    date: "Apr 4, 2026",
    readTime: "8 min read",
    featured: false,
    image: natureImage("river-garden.svg"),
    imageAlt: "A quiet garden river bordered by reeds and trees",
    imageCaption: "Mock nature image — quiet river garden",
    likes: 78,
    comments: [
      { author: "Fatema", text: "So many recipes really do live in the hands first." }
    ],
    excerpt:
      "The thaal is the round platter we share our food from, eight hands reaching toward the centre. But the recipes were never written. They moved through fingers and tongue.",
    tags: [],
    body: [
      "There is a particular way my mother folds the malida — a sweet of crumbled roti, ghee, and jaggery — that I have never been able to replicate. She does it with the heel of her hand, in three motions, eyes elsewhere. When I asked her to teach me, she said: \"You watch. The hand learns before the head.\"",
      "For most of Bohra culinary history, this has been the curriculum. The recipes were never written because they were not meant to be — they lived in the bodies of women, in the muscle memory of festival mornings and Ramadan evenings."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "The hand learns before the head."
  },
  {
    id: "pilgrim-daughters",
    slug: "pilgrim-daughters",
    title: "Pilgrim Daughters",
    subtitle: "A journey to Najaf and Karbala, told through a daughter's letters home",
    category: "travel",
    author: "Zainab H.",
    date: "Mar 28, 2026",
    readTime: "12 min read",
    featured: false,
    image: natureImage("coast-cliffs.svg"),
    imageAlt: "Sea waves below layered coastal cliffs",
    imageCaption: "Mock nature image — coastline and open water",
    likes: 64,
    comments: [],
    excerpt:
      "A young woman's first ziyarat, narrated in seven letters to her grandmother, who could not make the journey herself.",
    tags: [],
    body: [
      "My dearest Mami — I have not yet seen the dome. The bus from Baghdad was delayed by a sandstorm, and we slept in the depot under blankets that smelled of cumin and other people's grandmothers. I thought of you the whole night."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "I have not yet seen the dome. I thought of you the whole night."
  },
  {
    id: "madrasa-and-marketplace",
    slug: "madrasa-and-marketplace",
    title: "The Madrasa and the Marketplace",
    subtitle: "Women's education in the community across four centuries",
    category: "work",
    author: "Dr. Ruqaiya M.",
    date: "Mar 21, 2026",
    readTime: "16 min read",
    featured: false,
    image: natureImage("mountain-mist.svg"),
    imageAlt: "Mist moving through a mountain valley",
    imageCaption: "Mock nature image — mist through mountain valleys",
    likes: 103,
    comments: [
      { author: "Ruqaiya", text: "This is the kind of archival framing we need more of." }
    ],
    excerpt:
      "Long before the modern Bohra woman entered the boardroom, she entered the library. A historical survey of teaching, learning, and the women who taught women.",
    tags: [],
    body: [
      "The standard narrative of Muslim women's education in South Asia tends to treat the late nineteenth century as a beginning. For the Dawoodi Bohra community, this is incorrect by some three hundred years."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "She entered the library long before she entered the boardroom."
  },
  {
    id: "light-at-asr",
    slug: "light-at-asr",
    title: "Light at Asr",
    subtitle: "Photographs from a Bohra mohalla in Surat",
    category: "faith",
    author: "Husaina K.",
    date: "Mar 14, 2026",
    readTime: "5 min read",
    featured: false,
    image: natureImage("lotus-pond.svg"),
    imageAlt: "Lotus flowers floating on a calm pond",
    imageCaption: "Mock nature image — lotus pond at dusk",
    likes: 51,
    comments: [],
    excerpt:
      "A photo essay on the slant of afternoon sun through carved jharokhas, the unhurried geometry of a community at prayer.",
    tags: [],
    body: [
      "The mohalla is at its most photographable in the hour before Asr. The light, by then, has done most of its arguing with the city and has settled into something quieter."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "The light, by then, has settled into something quieter."
  },
  {
    id: "henna-hands-histories",
    slug: "henna-hands-histories",
    title: "Henna, Hands, and Histories",
    subtitle: "The visual grammar of a bridal mehndi night",
    category: "marriage",
    author: "Insiyah B.",
    date: "Mar 8, 2026",
    readTime: "7 min read",
    featured: false,
    image: natureImage("wildflower-field.svg"),
    imageAlt: "Wildflowers scattered across a green field",
    imageCaption: "Mock nature image — wildflowers in a green field",
    likes: 73,
    comments: [
      { author: "Insiyah", text: "The visual grammar idea is so rich." }
    ],
    excerpt:
      "Why the bride's palms are read like manuscripts, and what the symbols once meant before they meant beauty.",
    tags: [],
    body: [
      "Before the design became ornamental, it was a vocabulary. A peacock in a particular position. A vine that wound a certain way around a finger. These were not flourishes."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "Before the design became ornamental, it was a vocabulary."
  },
  {
    id: "quiet-architecture",
    slug: "quiet-architecture",
    title: "The Quiet Architecture of Bohra Homes",
    subtitle: "Threshold, courtyard, kitchen: a feminine reading of the haveli",
    category: "culture",
    author: "Tasneem A.",
    date: "Feb 28, 2026",
    readTime: "10 min read",
    featured: false,
    image: natureImage("banyan-courtyard.svg"),
    imageAlt: "A leafy banyan tree shading an empty courtyard",
    imageCaption: "Mock nature image — banyan shade in an empty courtyard",
    likes: 89,
    comments: [],
    excerpt:
      "The Bohra home was, for centuries, designed by men and made livable by women. The doorways, the angles, the placement of the water-pot — all of it tells a story.",
    tags: [],
    body: [
      "Walk into any old Bohra haveli in Sidhpur or Kapadwanj and you will notice, before anything else, the threshold. It is raised — never level with the street."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "Designed by men and made livable by women."
  },
  {
    id: "mothers-calendar",
    slug: "mothers-calendar",
    title: "The Mothers Who Kept the Calendar",
    subtitle: "How family seasons were remembered in kitchens, courtyards, and careful notebooks",
    category: "motherhood",
    author: "Amina S.",
    date: "Feb 18, 2026",
    readTime: "9 min read",
    featured: false,
    image: natureImage("monsoon-leaves.svg"),
    imageAlt: "Large green leaves after rain in soft monsoon light",
    imageCaption: "Mock nature image — monsoon leaves after rain",
    likes: 68,
    comments: [
      { author: "Husaina", text: "My mother still keeps a calendar exactly like this." }
    ],
    excerpt:
      "Before shared calendars and reminder bells, mothers carried the year's map in memory: births, ziyafats, school terms, doctor's visits, and the first mangoes of summer.",
    tags: [],
    body: [
      "My mother kept three calendars: the printed one near the telephone, the lunar one tucked into her prayer book, and the invisible one that lived in her mind.",
      "The invisible calendar was the most precise. It knew which cousin needed exam prayers, which aunt expected a call, and which child quietly dreaded the first day of school."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "The invisible calendar was the most precise."
  },
  {
    id: "first-forty-days",
    slug: "first-forty-days",
    title: "Songs for the First Forty Days",
    subtitle: "A young mother listens for advice between lullabies and old household rhythms",
    category: "motherhood",
    author: "Noor J.",
    date: "Feb 10, 2026",
    readTime: "7 min read",
    featured: false,
    image: natureImage("lotus-pond.svg"),
    imageAlt: "Lotus flowers floating on a calm pond",
    imageCaption: "Mock nature image — lotus pond in still water",
    likes: 57,
    comments: [],
    excerpt:
      "In the first weeks after birth, advice comes from every doorway. Some of it is instruction, some of it is memory, and some of it arrives as song.",
    tags: [],
    body: [
      "The first song was not meant for the baby. It was meant for me, sung softly by my aunt while she folded tiny cotton vests into impossible neatness.",
      "Only later did I understand that the songs were also a kind of shelter."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "The songs were also a kind of shelter."
  },
  {
    id: "cupboards-of-memory",
    slug: "cupboards-of-memory",
    title: "Cupboards of Memory",
    subtitle: "Household shelves as small archives of migration, repair, and everyday care",
    category: "household",
    author: "Tasneem V.",
    date: "Jan 29, 2026",
    readTime: "8 min read",
    featured: false,
    image: natureImage("banyan-courtyard.svg"),
    imageAlt: "A leafy banyan tree shading an empty courtyard",
    imageCaption: "Mock nature image — banyan shade in an empty courtyard",
    likes: 62,
    comments: [
      { author: "Zainab", text: "The cupboard as archive is such a perfect phrase." }
    ],
    excerpt:
      "A steel cupboard can hold more than saris and school certificates. It can hold the routes a family took, the things it repaired, and the things it refused to throw away.",
    tags: [],
    body: [
      "Every shelf in my grandmother's cupboard had a climate of its own: camphor, sandalwood soap, old paper, starched cotton.",
      "Nothing inside was random. Even the broken spectacles had a reason for staying."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "Every shelf had a climate of its own."
  },
  {
    id: "thaal-at-noon",
    slug: "thaal-at-noon",
    title: "The Thaal at Noon",
    subtitle: "A household ritual of sharing, order, and affectionate negotiation",
    category: "household",
    author: "Mufaddala R.",
    date: "Jan 20, 2026",
    readTime: "6 min read",
    featured: false,
    image: natureImage("river-garden.svg"),
    imageAlt: "A quiet garden river bordered by reeds and trees",
    imageCaption: "Mock nature image — garden river in afternoon light",
    likes: 74,
    comments: [],
    excerpt:
      "Around the thaal, hierarchy softened into habit: elders first, children nudged closer, the quiet passing of lime, salt, and second helpings.",
    tags: [],
    body: [
      "At noon, the house changed its rhythm. The television lowered, the youngest child was called twice, and the thaal arrived like a small moon.",
      "What looked like lunch was also choreography."
    ].map(p => `<p>${p}</p>`).join(""),
    pull: "What looked like lunch was also choreography."
  }
];

const FALLBACK_PODCAST_META = {
  name: "The Threshold",
  tagline: "A monthly conversation with the women keeping our stories.",
  hostedBy: "Maryam T. & Sakina N.",
  intro:
    "Recorded around kitchen tables, mosque courtyards, and the occasional long-distance phone line. New episode on the first Sunday of every month.",
  spotifyUrl: "",
  applePodcastsUrl: ""
};

const FALLBACK_PODCAST_EPISODES = [
  {
    id: "ep-12",
    number: 12,
    title: "The Embroiderer's Daughter",
    subtitle: "Bibi Husaina, 88, on six decades of rida embroidery",
    guest: "Bibi Husaina",
    location: "Burhanpur, Madhya Pradesh",
    date: "May 04, 2026",
    durationMin: 47,
    durationStr: "47 min",
    coverImage: natureImage("grove-square.svg"),
    description:
      "We sit with one of the last full-time embroiderers in Burhanpur. She talks about thread that came by ship from Yemen, the year the river flooded, and why her granddaughter is the first in the family to refuse to learn the craft."
  },
  {
    id: "ep-11",
    number: 11,
    title: "Kitchen Memory",
    subtitle: "An unwritten recipe, transcribed for the first time",
    guest: "Fatema R. & her mother",
    location: "Mumbai",
    date: "Apr 06, 2026",
    durationMin: 38,
    durationStr: "38 min",
    coverImage: natureImage("river-garden.svg"),
    description:
      "A daughter and her mother attempt to write down a recipe — kheer puri — that has lived for four generations entirely in hands and tongue. They argue gently. We let the tape roll."
  },
  {
    id: "ep-10",
    number: 10,
    title: "Pilgrim Daughters",
    subtitle: "Three women, three first journeys to Karbala",
    guest: "Zainab H., Insiyah B., Tasneem A.",
    location: "London · Karachi · Surat",
    date: "Mar 02, 2026",
    durationMin: 54,
    durationStr: "54 min",
    coverImage: natureImage("mountain-mist.svg"),
    description:
      "A round-table conversation, recorded over three continents, on what it feels like to make the journey for the first time — and what their grandmothers told them to look for when they got there."
  },
  {
    id: "ep-09",
    number: 9,
    title: "The Marketplace and the Madrasa",
    subtitle: "Dr. Ruqaiya M. on four centuries of Bohra women in education",
    guest: "Dr. Ruqaiya M.",
    location: "Karachi",
    date: "Feb 02, 2026",
    durationMin: 62,
    durationStr: "1 hr 02 min",
    coverImage: natureImage("forest-path.svg"),
    description:
      "A historian walks us through the archive — letters, account books, school registers — to show that the modern Bohra woman did not begin in the 20th century. She began much earlier, and she was reading."
  },
  {
    id: "ep-08",
    number: 8,
    title: "Henna Night",
    subtitle: "A pre-wedding mehndi, recorded with the bride's permission",
    guest: "Anonymous bride and her aunts",
    location: "Ahmedabad",
    date: "Jan 05, 2026",
    durationMin: 41,
    durationStr: "41 min",
    coverImage: natureImage("wildflower-field.svg"),
    description:
      "Field recording from a bridal mehndi night — songs, teasing, the slow scrape of cone-tip on palm. The bride speaks at the end, briefly, about what she would tell her younger self."
  }
];

const FALLBACK_MEDIA_GALLERY = [
  { id: 1, caption: "Mock nature image — monsoon leaves", tone: "warm", image: natureImage("monsoon-leaves.svg"), imageAlt: "Large green leaves after rain in soft monsoon light" },
  { id: 2, caption: "Mock nature image — desert blooms",  tone: "deep", image: natureImage("desert-bloom.svg"),   imageAlt: "Soft desert dunes with flowering cactus plants" },
  { id: 3, caption: "Mock nature image — river garden",   tone: "soft", image: natureImage("river-garden.svg"),   imageAlt: "A quiet garden river bordered by reeds and trees" },
  { id: 4, caption: "Mock nature image — forest path",    tone: "warm", image: natureImage("forest-path.svg"),    imageAlt: "A winding path through tall forest trees" },
  { id: 5, caption: "Mock nature image — mountain mist",  tone: "deep", image: natureImage("mountain-mist.svg"),  imageAlt: "Mist moving through a mountain valley" },
  { id: 6, caption: "Mock nature image — coastal cliffs", tone: "soft", image: natureImage("coast-cliffs.svg"),   imageAlt: "Sea waves below layered coastal cliffs" }
];

const FALLBACK_SITE_SETTINGS = {
  siteTitle:             "Our Legacy, Our Herstory",
  tagline:               "",
  submitStoryUrl:        "",
  newsletterDescription: "",
  footerText:            ""
};

// ---------------------------------------------------------------------------
// Async CMS loader — called from blog-app.jsx before React mounts
// ---------------------------------------------------------------------------
window.loadCMSData = async function() {
  try {
    const [
      rawCats,
      rawArticles,
      rawEps,
      rawMeta,
      rawGallery,
      rawSettings
    ] = await Promise.all([
      apiGet("/items/categories?sort=sort"),
      apiGet("/items/articles?filter[status][_eq]=published&sort[]=-featured&sort[]=published_date&limit=100"),
      apiGet("/items/podcast_episodes?filter[status][_eq]=published&sort=-episode_number"),
      apiGet("/items/podcast_meta"),
      apiGet("/items/gallery_items?sort=sort"),
      apiGet("/items/site_settings")
    ]);

    // Normalize: Directus singletons return an object; regular collections return an array
    const metaObj     = Array.isArray(rawMeta)     ? (rawMeta[0]     || {}) : (rawMeta     || {});
    const settingsObj = Array.isArray(rawSettings) ? (rawSettings[0] || {}) : (rawSettings || {});

    window.CATEGORIES = [
      { id: "home",    label: "Home",    intro: "" },
      ...rawCats.map(c => ({ id: c.id, label: c.label, intro: c.intro_text || "" })),
      { id: "podcast", label: "Podcast", intro: "" },
    ];

    window.ARTICLES = rawArticles.map(a => ({
      id:           a.slug,
      slug:         a.slug,
      title:        a.title,
      subtitle:     a.subtitle     || "",
      excerpt:      a.excerpt      || "",
      author:       a.author || "",
      date:         formatDate(a.published_date),
      readTime:     a.read_time    || "",
      category:     a.category,
      imageCaption: a.image_caption || "",
      featured:     a.featured     || false,
      pull:         a.pull_quote   || "",
      tags:         Array.isArray(a.tags) ? a.tags : [],
      body:         a.body         || "",
      image:        a.featured_image
                      ? window.assetUrl(a.featured_image)
                      : window.imageFor("article", a.slug),
      imageAlt:     a.title,
      likes:        0,
      comments:     [],
    }));

    window.PODCAST_META = {
      name:             metaObj.name            || "The Threshold",
      tagline:          metaObj.tagline         || "",
      intro:            metaObj.intro_text      || "",
      hostedBy:         metaObj.hosts           || "",
      spotifyUrl:       metaObj.spotify_url     || "",
      applePodcastsUrl: metaObj.apple_podcasts_url || "",
    };

    window.PODCAST_EPISODES = rawEps.map(ep => ({
      number:      ep.episode_number,
      id:          `ep-${ep.episode_number}`,
      title:       ep.title,
      subtitle:    "",
      description: ep.description   || "",
      guest:       [ep.guest, ep.guest_location].filter(Boolean).join(", "),
      location:    ep.guest_location || "",
      date:        formatDate(ep.published_date),
      durationStr: ep.duration      || "",
      coverImage: ep.cover_image
        ? window.assetUrl(ep.cover_image, { w: 480, h: 480 })
        : window.imageFor("podcast", ep.episode_number, 480, 480),
    }));

    window.MEDIA_GALLERY = rawGallery.length > 0
      ? rawGallery.map((g, i) => ({
          id:       g.id,
          caption:  g.caption  || "",
          tone:     ["warm","deep","soft","warm","deep","soft"][i % 6],
          image:    g.image ? window.assetUrl(g.image, { w: 800, h: 600 }) : null,
          imageAlt: g.caption  || "",
        }))
      : FALLBACK_MEDIA_GALLERY;

    window.SITE_SETTINGS = {
      siteTitle:             settingsObj.site_title             || "Our Legacy, Our Herstory",
      tagline:               settingsObj.tagline                || "",
      submitStoryUrl:        settingsObj.submit_story_url       || "",
      newsletterDescription: settingsObj.newsletter_description || "",
      footerText:            settingsObj.footer_text            || "",
    };

  } catch (err) {
    console.warn("CMS unavailable, using fallback data:", err.message);
    window.CATEGORIES       = FALLBACK_CATEGORIES;
    window.ARTICLES         = FALLBACK_ARTICLES;
    window.PODCAST_META     = FALLBACK_PODCAST_META;
    window.PODCAST_EPISODES = FALLBACK_PODCAST_EPISODES;
    window.MEDIA_GALLERY    = FALLBACK_MEDIA_GALLERY;
    window.SITE_SETTINGS    = FALLBACK_SITE_SETTINGS;
  }
};
