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

interface UseLazyImageProps {
  src: string;
  placeholder?: string;
  threshold?: number;
}

// Hook personalizado para lazy loading de imágenes
export function useLazyImage({ src, placeholder = '', threshold = 0.25 }: UseLazyImageProps) {
  const [imageSrc, setImageSrc] = useState(placeholder);
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);
  const imgRef = useRef<HTMLImageElement>(null);

  useEffect(() => {
    let observer: IntersectionObserver;
    let didCancel = false;

    const currentImg = imgRef.current;
    if (currentImg && imageSrc === placeholder) {
      // Crear observer que detecta cuando la imagen entra en viewport
      observer = new IntersectionObserver(
        entries => {
          entries.forEach(entry => {
            if (!didCancel && entry.isIntersecting) {
              setIsLoading(true);
              setImageSrc(src);
            }
          });
        },
        {
          threshold,
          rootMargin: '50px' // Empezar a cargar 50px antes de que sea visible
        }
      );

      observer.observe(currentImg);
    }

    return () => {
      didCancel = true;
      if (observer && currentImg) {
        observer.unobserve(currentImg);
      }
    };
  }, [src, imageSrc, placeholder, threshold]);

  const handleLoad = () => {
    setIsLoading(false);
  };

  const handleError = () => {
    setIsLoading(false);
    setIsError(true);
  };

  return {
    imgRef,
    imageSrc,
    isLoading,
    isError,
    handleLoad,
    handleError
  };
}
