import { useEffect, useRef } from 'preact/hooks'

import { unified } from 'unified'
import remarkParse from 'remark-parse'
import remarkMath from 'remark-math'
import remarkRehype from 'remark-rehype'
import rehypeKatex from 'rehype-katex'
import rehypeStringify from 'rehype-stringify'

export const Markdown = ({ source }) => {
    const elementRef = useRef()

    useEffect(async () => {
        const renderedHtml = await unified()
            .use(remarkParse)
            .use(remarkMath)
            .use(remarkRehype)
            .use(rehypeKatex, { throwOnError: false, errorColor: '#c60' })
            .use(rehypeStringify)
            .process(source)

        if (elementRef.current) {
            elementRef.current.innerHTML = renderedHtml
        }
    }, [source])

    return <div class="markdown" ref={elementRef}></div>
}
