import { useEffect, useRef, useState } from 'react'

let idCounter = 0

// Renders a ```mermaid fence. The mermaid library (~1 MB) is imported lazily
// the first time a diagram appears, so documents without diagrams never load
// it. securityLevel 'strict' because documents arrive from shared links.
export default function Mermaid({ code }: { code: string }) {
  const [svg, setSvg] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const idRef = useRef(`mermaid-${idCounter++}`)

  useEffect(() => {
    let cancelled = false
    setSvg(null)
    setError(null)
    ;(async () => {
      try {
        const mermaid = (await import('mermaid')).default
        mermaid.initialize({ startOnLoad: false, securityLevel: 'strict' })
        const { svg } = await mermaid.render(idRef.current, code)
        if (!cancelled) setSvg(svg)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : String(e))
        // mermaid.render leaves an error element in the body on parse failure
        document.getElementById(`d${idRef.current}`)?.remove()
      }
    })()
    return () => {
      cancelled = true
    }
  }, [code])

  if (error) return <pre className="mermaid-error">mermaid: {error}</pre>
  if (svg === null) return <div className="mermaid-loading">rendering diagram…</div>
  return <div className="mermaid-diagram" dangerouslySetInnerHTML={{ __html: svg }} />
}
