"use client";

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

interface MermaidProps {
    chart: string;
}

const Mermaid: React.FC<MermaidProps> = ({ chart }) => {
    const ref = useRef<HTMLDivElement>(null);
    const [rendered, setRendered] = useState("");

    useEffect(() => {
        // Only verify we're on client side
        if (typeof window === "undefined") return;

        // Initialize mermaid
        mermaid.initialize({
            startOnLoad: false,
            theme: 'base',
            securityLevel: 'loose',
            fontFamily: 'inherit',
        });

        let isMounted = true;

        const renderChart = async () => {
            try {
                if (!ref.current) return;

                // Use a unique ID for each render to avoid conflicts
                const id = `mermaid-${Math.random().toString(36).substring(2, 9)}`;

                // Render the chart
                const { svg } = await mermaid.render(id, chart);

                if (isMounted) {
                    setRendered(svg);
                }
            } catch (error) {
                console.error("Mermaid rendering failed:", error);
                // Show error in UI
                if (isMounted) {
                    setRendered(`<div class="text-red-500 text-sm bg-red-50 p-2 rounded">Failed to render diagram</div>`);
                }
            }
        };

        renderChart();

        return () => {
            isMounted = false;
        };
    }, [chart]);

    return (
        <div
            className="mermaid my-4 flex justify-center bg-white dark:bg-zinc-900/50 p-4 rounded-lg overflow-x-auto"
            ref={ref}
            dangerouslySetInnerHTML={{ __html: rendered }}
        />
    );
};

export default Mermaid;
