// Counts slides, collapses redundant slide-break lines, and masks fenced code blocks.

// Counts the number of slides in a markdown body (--- separators + 1).
export function countSlides(body) {
  return body.split('\n').filter((line) => line === '---').length + 1
}

// Collapses consecutive --- slide-break lines into a single ---.
export function collapseBreaks(body) {
  return body.replace(/(^|\n)---(\n(?:[ \t]*\n)*---)+\n/g, '$1---\n')
}

// Blanks out fenced code block contents so that markers inside fences are invisible to other parsers.
export function maskCode(text) {
  const lines = text.split('\n')
  let inFence = false
  let fenceLen = 0
  const result = []
  for (const line of lines) {
    if (!inFence) {
      const m = line.match(/^(`{3,})/)
      if (m) {
        inFence = true
        fenceLen = m[1].length
        result.push(line)
      } else {
        result.push(line)
      }
    } else {
      const m = line.match(/^(`{3,})\s*$/)
      if (m && m[1].length >= fenceLen) {
        inFence = false
        fenceLen = 0
        result.push(line)
      } else {
        result.push('')
      }
    }
  }
  return result.join('\n')
}
