import DOMPurify from 'dompurify';
import React, { useCallback, useEffect, useMemo,useRef, useState } from 'react';

import type { Artifact } from '@/types/artifact';

interface SvgRendererProps {
  artifact: Artifact;
}

const SvgRenderer: React.FC<SvgRendererProps> = ({ artifact }) => {
  const [scale, setScale] = useState(1);
  const containerRef = useRef<HTMLDivElement>(null);

  const sanitizedSvg = useMemo(() => {
    if (!artifact.content) return '';
    return DOMPurify.sanitize(artifact.content, {
      USE_PROFILES: { svg: true, svgFilters: true },
      ADD_TAGS: ['use'],
    });
  }, [artifact.content]);

  const handleWheel = useCallback((e: WheelEvent) => {
    if (e.ctrlKey || e.metaKey) {
      e.preventDefault();
      setScale(prev => Math.max(0.1, Math.min(5, prev - e.deltaY * 0.001)));
    }
  }, []);

  const resetZoom = useCallback(() => setScale(1), []);

  useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    el.addEventListener('wheel', handleWheel, { passive: false });
    return () => el.removeEventListener('wheel', handleWheel);
  }, [handleWheel]);

  return (
    <div className="relative w-full h-full overflow-auto" ref={containerRef}>
      <div
        className="flex items-center justify-center min-h-full p-4"
        style={{ transform: `scale(${scale})`, transformOrigin: 'center center' }}
        dangerouslySetInnerHTML={{ __html: sanitizedSvg }}
      />
      {scale !== 1 && (
        <button
          onClick={resetZoom}
          className="absolute bottom-3 right-3 px-2 py-1 text-xs rounded bg-surface text-secondary hover:bg-surface-hover"
        >
          {Math.round(scale * 100)}%
        </button>
      )}
    </div>
  );
};

export default SvgRenderer;
