export function slugify(text) {
  return text.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
}

export function expandMorphSpans(markdown) {
  const lines = markdown.split('\n')
  let inFence = false
  let fenceLen = 0

  return lines.map(line => {
    if (!inFence) {
      const fenceMatch = line.match(/^(`{3,})/)
      if (fenceMatch) { inFence = true; fenceLen = fenceMatch[1].length; return line }
      if (/^ {4}/.test(line)) return line  // indented code block
      return line.replace(/\[([^\]]+)\]\{morph(?:=([^\s}]+))?\}/g, (_, text, key) => {
        const id = key?.trim() ?? slugify(text)
        return `<span data-morph-id="${id}">${text}</span>`
      })
    }
    const closeMatch = line.match(/^(`{3,})\s*$/)
    if (closeMatch && closeMatch[1].length >= fenceLen) { inFence = false; fenceLen = 0 }
    return line
  }).join('\n')
}
