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

interface LiteMermaidProps {
  children: string;
}

/**
 * 轻量 Mermaid 渲染：动态 import mermaid，只有出现 mermaid 代码块时才加载
 * mermaid 及其解析器/图布局依赖，避免随 AI 抽屉主包一起加载。
 */
export function LiteMermaid({ children }: LiteMermaidProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    const container = containerRef.current;
    if (!container) return;

    void (async () => {
      try {
        const mermaid = (await import('mermaid')).default;
        mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'strict' });
        const { svg } = await mermaid.render(`mermaid-${crypto.randomUUID()}`, children);
        if (!cancelled) {
          const doc = new DOMParser().parseFromString(svg, 'image/svg+xml');
          container.replaceChildren(doc.documentElement);
          setError(null);
        }
      } catch (e) {
        if (!cancelled) {
          setError(e instanceof Error ? e.message : '图表渲染失败');
        }
      }
    })();

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

  if (error) {
    return (
      <pre style={{ whiteSpace: 'pre-wrap', color: '#cf1322', fontSize: 12 }}>{children}</pre>
    );
  }
  return <div ref={containerRef} className="ai-chat-mermaid" />;
}
