// src/components/LazyImage.tsx

import { useLazyImage } from '../hooks/useLazyImage';
import clsx from 'clsx';

interface LazyImageProps {
  src: string;
  alt: string;
  className?: string;
  placeholder?: string;
  fallbackSrc?: string;
}

export default function LazyImage({
  src,
  alt,
  className = '',
  placeholder = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"%3E%3Crect fill="%23f0f0f0" width="400" height="300"/%3E%3C/svg%3E',
  fallbackSrc
}: LazyImageProps) {
  const {
    imgRef,
    imageSrc,
    isLoading,
    isError,
    handleLoad,
    handleError
  } = useLazyImage({ src, placeholder });

  const isRealImage = imageSrc && !imageSrc.startsWith('data:');

  return (
    <div className={clsx("relative w-full h-full overflow-hidden", className)}>
      {isLoading && (
        <div className="absolute inset-0 bg-slate-200 animate-pulse z-10" />
      )}

      {isError ? (
        <div className="absolute inset-0 flex items-center justify-center bg-slate-100 text-slate-400 text-[10px] p-2 text-center">
          {fallbackSrc ? (
            <img src={fallbackSrc} alt={alt} className="w-full h-full object-cover" />
          ) : (
            <span>Imagen no disponible</span>
          )}
        </div>
      ) : (
        <picture className="w-full h-full">
          {/* Solo renderizamos el source si es una imagen real del servidor */}
          {isRealImage && <source srcSet={imageSrc} type="image/webp" />}
          <img
            ref={imgRef}
            src={imageSrc}
            alt={alt}
            className={clsx(
              "w-full h-full object-cover transition-opacity duration-500 block",
              isLoading ? 'opacity-0' : 'opacity-100'
            )}
            onLoad={handleLoad}
            onError={handleError}
            loading="lazy"
          />
        </picture>
      )}
    </div>
  );
}