'use client';

import { useEffect, useState, useRef } from 'react';
import { useTheme } from 'next-themes';

export function ThemeTransition() {
  const { theme, resolvedTheme } = useTheme();
  const [prevTheme, setPrevTheme] = useState<string | undefined>();
  const [capturedImage, setCapturedImage] = useState<string | null>(null);
  const overlayRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Listen for theme transition start event with captured image
    const handleTransitionStart = (event: CustomEvent<{ imageDataUrl: string; newTheme: string }>) => {
      setCapturedImage(event.detail.imageDataUrl);
    };

    window.addEventListener('theme-transition-start', handleTransitionStart as EventListener);

    return () => {
      window.removeEventListener('theme-transition-start', handleTransitionStart as EventListener);
    };
  }, []);

  useEffect(() => {
    const currentTheme = resolvedTheme || theme;
    if (prevTheme && prevTheme !== currentTheme && currentTheme && overlayRef.current && capturedImage) {
      // Set the captured image as background
      overlayRef.current.style.backgroundImage = `url(${capturedImage})`;
      overlayRef.current.style.backgroundSize = 'cover';
      overlayRef.current.style.backgroundPosition = 'center';
      overlayRef.current.style.opacity = '1';
      overlayRef.current.classList.add('theme-wipe-active');
      
      const timer = setTimeout(() => {
        if (overlayRef.current) {
          overlayRef.current.classList.remove('theme-wipe-active');
          overlayRef.current.style.opacity = '0';
          overlayRef.current.style.backgroundImage = '';
          setCapturedImage(null);
        }
      }, 600);
      
      return () => {
        clearTimeout(timer);
      };
    }
    setPrevTheme(currentTheme);
  }, [theme, resolvedTheme, prevTheme, capturedImage]);

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-[9999] pointer-events-none theme-wipe-overlay"
      style={{
        opacity: 0,
      }}
    />
  );
}

