// Injects speaker notes (Markdown HTML comments) into Marp-rendered HTML via cheerio.
import * as cheerio from 'cheerio'
import { marked } from 'marked'

export function renderNotes(html, sourceMarkdown) {
  const notes = extractNotesBySlide(sourceMarkdown)
  const $ = cheerio.load(html)
  $('.bespoke-marp-note').each((_, el) => {
    const idx = parseInt($(el).attr('data-index'))
    const raw = notes[idx]?.trim() ?? ''
    if (raw) $(el).html(marked.parse(raw))
  })
  return $.html()
}

export function extractNotesBySlide(markdown) {
  const chunks = markdown.split('\n---\n')
  // First chunk starts with --- if there's a frontmatter block — skip it
  const slides = chunks[0].startsWith('---') ? chunks.slice(1) : chunks
  return slides.map(chunk => {
    const match = chunk.match(/<!--([\s\S]*?)-->/)
    return match ? match[1] : ''
  })
}
