'use client'

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

let counter = 0

export function MermaidDiagram({ chart, isDark }: { chart: string; isDark?: boolean }) {
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!ref.current || !chart.trim()) return
    const id = `mermaid-slide-${++counter}`
    mermaid.initialize({
      startOnLoad: false,
      theme: isDark ? 'dark' : 'default',
      themeVariables: isDark
        ? { primaryColor: '#A47148', primaryTextColor: '#F9F8F6', lineColor: '#D4A373', secondaryColor: '#2A2A2A', tertiaryColor: '#1C1C1C' }
        : { primaryColor: '#A47148', primaryTextColor: '#1C1C1C', lineColor: '#D4A373' },
      securityLevel: 'loose',
    })
    mermaid.render(id, chart)
      .then(({ svg }) => {
        if (ref.current) ref.current.innerHTML = svg
      })
      .catch((err) => {
        console.error('[MermaidDiagram] render error:', err)
        if (ref.current) ref.current.innerHTML = `<pre style="color:rgba(255,255,255,0.4);font-size:12px">${chart}</pre>`
      })
  }, [chart, isDark])

  return (
    <div
      ref={ref}
      className="flex justify-center items-center w-full h-full overflow-hidden"
      style={{ minHeight: 200 }}
    />
  )
}
