import 'highlight.js/styles/github-dark.css'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'
import { Marked } from 'marked'
import { markedHighlight } from 'marked-highlight'

const marked = new Marked(
  markedHighlight({
    langPrefix: 'hljs language-',
    highlight(code, lang) {
      if (lang && hljs.getLanguage(lang)) {
        return hljs.highlight(code, { language: lang }).value
      }
      try {
        return hljs.highlightAuto(code).value
      } catch {
        return code
      }
    },
  }),
  { breaks: true, gfm: true },
)

/**
 * Composable for rendering markdown with syntax highlighting
 *
 * @returns Object with render function for markdown content
 */
export function useMarkdown() {
  function render(text: string | undefined): string {
    const rawHtml = marked.parse(text || '') as string
    return DOMPurify.sanitize(rawHtml)
  }

  return { render }
}
