// Minimal frontmatter parser. Splits a leading `---`-delimited YAML-ish
// block from the rest of a markdown file. Body markdown itself is rendered
// by the existing MarkdownBody/renderInline in writing.jsx — this module
// only handles the frontmatter split + key:value parsing.

function parseFrontmatter(raw) {
  const text = String(raw).replace(/\r\n/g, '\n');
  const lines = text.split('\n');
  if (lines[0].trim() !== '---') {
    return { meta: {}, body: text };
  }
  let end = -1;
  for (let i = 1; i < lines.length; i++) {
    if (lines[i].trim() === '---') { end = i; break; }
  }
  if (end === -1) {
    return { meta: {}, body: text };
  }
  const meta = {};
  for (let i = 1; i < end; i++) {
    const line = lines[i];
    if (!line.trim()) continue;
    const m = line.match(/^([A-Za-z0-9_]+):\s*(.*)$/);
    if (!m) continue;
    const key = m[1];
    let val = m[2].trim();
    if (/^\[.*\]$/.test(val)) {
      val = val.slice(1, -1).split(',').map((s) => s.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
    } else if (/^".*"$/.test(val) || /^'.*'$/.test(val)) {
      val = val.slice(1, -1);
    } else if (val === 'true') {
      val = true;
    } else if (val === 'false') {
      val = false;
    }
    meta[key] = val;
  }
  const body = lines.slice(end + 1).join('\n').replace(/^\n+/, '');
  return { meta, body };
}

if (typeof module !== 'undefined' && module.exports) {
  module.exports = { parseFrontmatter };
}
if (typeof window !== 'undefined') {
  window.Markdown = { parseFrontmatter };
}
