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

interface LazyLoadProps {
  children: React.ReactNode;
  placeholder?: React.ReactNode;
  threshold?: number;
  rootMargin?: string;
}

export const LazyLoad: React.FC<LazyLoadProps> = ({
  children,
  placeholder = <div className="w-full h-full bg-gray-100 flex items-center justify-center">加载中...</div>,
  threshold = 0.1,
  rootMargin = '0px',
}) => {
  const [isVisible, setIsVisible] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.disconnect();
        }
      },
      {
        threshold,
        rootMargin,
      }
    );

    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      if (ref.current) {
        observer.unobserve(ref.current);
      }
    };
  }, [threshold, rootMargin]);

  return (
    <div ref={ref} className="w-full">
      {isVisible ? children : placeholder}
    </div>
  );
};

interface LazyImageProps {
  src: string;
  alt: string;
  className?: string;
  placeholder?: React.ReactNode;
  threshold?: number;
  rootMargin?: string;
}

export const LazyImage: React.FC<LazyImageProps> = ({
  src,
  alt,
  className = '',
  placeholder = <div className="w-full h-full bg-gray-100 flex items-center justify-center">加载中...</div>,
  threshold = 0.1,
  rootMargin = '0px',
}) => {
  return (
    <LazyLoad placeholder={placeholder} threshold={threshold} rootMargin={rootMargin}>
      <img src={src} alt={alt} className={className} />
    </LazyLoad>
  );
};

export default LazyLoad;