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

/**
 * 加载 SVG 文件并将指定颜色替换为主题色后内联渲染
 * @param {string} url - SVG 文件地址
 * @param {string} color - 替换的目标主题色 (hex)
 * @param {string} className - 外层容器样式
 */
export default function ThemedSvg({ url, color, className }) {
  const [content, setContent] = useState('');
  const ref = useRef(null);

  useEffect(() => {
    let cancelled = false;
    fetch(url)
      .then(res => res.text())
      .then(text => {
        if (cancelled) return;
        // 将 undraw 默认紫色 #6c63ff 替换为页面主题色
        const themed = text.replace(/#6c63ff/gi, color);
        setContent(themed);
      })
      .catch(() => {
        if (!cancelled) setContent('');
      });
    return () => { cancelled = true; };
  }, [url, color]);

  if (!content) {
    return <div className={className} />;
  }

  return (
    <div
      ref={ref}
      className={className}
      dangerouslySetInnerHTML={{ __html: content }}
    />
  );
}