
import React, { useEffect, useRef, useState } from 'react';
import mermaid from 'mermaid';

interface Props {
  chart: string;
  theme?: 'light' | 'dark';
}

const MermaidDiagram: React.FC<Props> = ({ chart, theme = 'light' }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [svg, setSvg] = useState<string>('');

  useEffect(() => {
    mermaid.initialize({
      startOnLoad: false,
      theme: theme === 'dark' ? 'dark' : 'default',
      securityLevel: 'loose',
      fontFamily: 'Inter, sans-serif',
    });
  }, [theme]);

  useEffect(() => {
    const renderChart = async () => {
      if (!containerRef.current) return;
      
      try {
        const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`;
        // Mermaid render returns an object with svg property in newer versions
        const { svg } = await mermaid.render(id, chart);
        setSvg(svg);
      } catch (error) {
        console.error('Mermaid failed to render:', error);
        setSvg(''); // Clear on error
      }
    };

    renderChart();
  }, [chart, theme]);

  if (!svg) return null;

  return (
    <div 
      className="w-full h-full flex items-center justify-center p-4 mermaid-container overflow-hidden"
      ref={containerRef}
      dangerouslySetInnerHTML={{ __html: svg }}
    />
  );
};

export default MermaidDiagram;
