// Fetches and parses a case study from content/cases/<slug>.md.
// YAML frontmatter holds structured fields (pullQuote, quoteAttrib, pillars, results);
// the markdown body is split into challenge/approach/outcome sections by H2 headings.

async function loadCase(slug) {
  const res = await fetch(`content/cases/${slug}.md`);
  if (!res.ok) throw new Error(`Failed to load case ${slug}: ${res.status}`);
  const text = await res.text();

  const m = text.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
  if (!m) throw new Error(`Frontmatter not found in ${slug}.md`);

  const fm = jsyaml.load(m[1]);
  const body = m[2];

  const sections = {};
  const parts = body.split(/^## /m).filter(p => p.trim());
  for (const part of parts) {
    const firstNewline = part.indexOf('\n');
    const sectionName = part.slice(0, firstNewline).trim().toLowerCase();
    const sectionBody = part.slice(firstNewline + 1).trim();
    const titleMatch = sectionBody.match(/^### (.+?)\n([\s\S]*)$/);
    sections[sectionName] = titleMatch
      ? { title: titleMatch[1].trim(), html: marked.parse(titleMatch[2].trim()) }
      : { title: '', html: marked.parse(sectionBody) };
  }

  return {
    challenge:   sections.challenge,
    approach:    { ...sections.approach, pillars: fm.pillars || [] },
    outcome:     sections.outcome,
    pullQuote:   fm.pullQuote,
    quoteAttrib: fm.quoteAttrib,
    results:     fm.results || [],
  };
}

Object.assign(window, { loadCase });
