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

export default function MermaidBlock({ code }: { code: string }) {
  const ref = useRef<HTMLDivElement>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!ref.current) return
    let cancelled = false
    ;(async () => {
      try {
        const mermaid = (await import('mermaid')).default
        mermaid.initialize({ startOnLoad: false, theme: 'neutral' })
        const id = `mermaid-${Math.random().toString(36).slice(2)}`
        const { svg } = await mermaid.render(id, code.trim())
        if (!cancelled && ref.current) ref.current.innerHTML = svg
      } catch (e) {
        if (!cancelled) setError(String(e))
      }
    })()
    return () => { cancelled = true }
  }, [code])

  if (error) {
    return (
      <pre className="text-xs text-red-600 bg-red-50 p-3 rounded overflow-auto">
        Mermaid error: {error}{'\n\n'}{code}
      </pre>
    )
  }

  return (
    <div
      ref={ref}
      className="not-prose my-8 overflow-x-auto rounded-xl border border-gray-100 bg-gray-50 px-6 py-8 shadow-sm [&>svg]:max-w-full [&>svg]:mx-auto [&>svg]:block [&>svg]:h-auto"
    />
  )
}
