function applyInline(text: string): string {
  text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
  text = text.replace(/\*(.+?)\*/g, '<em>$1</em>')
  return text
}

export function renderSimpleMarkdown(raw: string): string {
  // escape HTML first
  const text = raw
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')

  // split into blocks by double newlines
  const blocks = text.split(/\n\n+/)
  const rendered = blocks.map(block => {
    const lines = block.split('\n')
    // check if block is a list
    const isList = lines.every(l => l.match(/^\s*- /))
    if (isList) {
      const items = lines.map(l => {
        let item = l.replace(/^\s*- /, '')
        item = applyInline(item)
        return `<li>${item}</li>`
      })
      return `<ul>${items.join('')}</ul>`
    }
    // process each line
    const processed = lines.map(line => {
      // headings
      if (line.match(/^## /)) return `<h4>${applyInline(line.slice(3))}</h4>`
      if (line.match(/^# /)) return `<h3>${applyInline(line.slice(2))}</h3>`
      // single list item within a paragraph block
      if (line.match(/^\s*- /)) return `<li>${applyInline(line.replace(/^\s*- /, ''))}</li>`
      return applyInline(line)
    })
    // wrap non-heading lines in <p>
    const out: string[] = []
    let buf: string[] = []
    for (const p of processed) {
      if (p.startsWith('<h3>') || p.startsWith('<h4>') || p.startsWith('<li>') || p.startsWith('<ul>')) {
        if (buf.length) { out.push(`<p>${buf.join('<br>')}</p>`); buf = [] }
        out.push(p)
      } else {
        buf.push(p)
      }
    }
    if (buf.length) out.push(`<p>${buf.join('<br>')}</p>`)
    return out.join('')
  })
  return rendered.join('')
}