import { marked } from 'marked'
import DOMPurify from 'isomorphic-dompurify'

const ALLOWED_TAGS = [
  'a', 'strong', 'em', 'b', 'i', 'u',
  'ul', 'ol', 'li', 'p', 'br',
  'code', 'pre', 'blockquote',
  'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  'hr', 'table', 'thead', 'tbody', 'tr', 'th', 'td',
  'del', 'sup', 'sub'
]

const ALLOWED_ATTR = ['href', 'target', 'rel', 'class']

export const useMarkdown = () => {
  const render = (markdown) => {
    if (!markdown) return ''
    const raw = marked(markdown, {
      breaks: true,
      gfm: true
    })
    return DOMPurify.sanitize(raw, {
      ALLOWED_TAGS,
      ALLOWED_ATTR,
      ALLOW_DATA_ATTR: false
    })
  }

  return {
    render
  }
}
