'use client';

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

interface MermaidDiagramProps {
  chart: string;
}

let mermaidInitialized = false;

export function MermaidDiagram({ chart }: MermaidDiagramProps) {
  const ref = useRef<HTMLDivElement>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function render() {
      if (!ref.current) return;
      try {
        const mermaid = (await import('mermaid')).default;

        if (!mermaidInitialized) {
          mermaid.initialize({
            startOnLoad: false,
            theme: 'dark',
            themeVariables: {
              background: '#0a0a0f',
              primaryColor: '#a78bfa',
              primaryTextColor: '#e8e6f0',
              primaryBorderColor: '#252540',
              lineColor: '#7b7a95',
              secondaryColor: '#1a1a2e',
              tertiaryColor: '#131320',
            },
          });
          mermaidInitialized = true;
        }

        const id = `mermaid-${Math.random().toString(36).slice(2)}`;
        const { svg } = await mermaid.render(id, chart);

        if (!cancelled && ref.current) {
          ref.current.innerHTML = svg;
        }
      } catch (err) {
        if (!cancelled) {
          setError(err instanceof Error ? err.message : 'Failed to render diagram');
        }
      }
    }

    render();
    return () => {
      cancelled = true;
    };
  }, [chart]);

  if (error) {
    return (
      <pre
        style={{
          background: 'rgba(239,68,68,0.08)',
          border: '1px solid rgba(239,68,68,0.3)',
          borderRadius: '0.5rem',
          padding: '1rem',
          color: '#ef4444',
          fontSize: '0.875rem',
          marginBottom: '1.5rem',
          whiteSpace: 'pre-wrap',
        }}
      >
        Mermaid error: {error}
      </pre>
    );
  }

  return (
    <div
      ref={ref}
      style={{
        background: '#131320',
        border: '1px solid #252540',
        borderRadius: '0.5rem',
        padding: '1rem',
        marginBottom: '1.5rem',
        overflowX: 'auto',
        textAlign: 'center',
      }}
    />
  );
}
