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

/**
 * 懒加载Hook - 使用Intersection Observer监听元素是否可见
 * @param threshold 触发可见的阈值 (0-1)，默认0.1表示10%可见时触发
 * @param rootMargin 提前加载的边距，默认50px表示距离视口50px时开始加载
 * @returns { isVisible: boolean, elementRef: RefObject }
 */
export const useLazyLoad = (threshold = 0.1, rootMargin = '50px') => {
  const [isVisible, setIsVisible] = useState(false);
  const elementRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          // 一旦可见就停止观察，避免重复触发
          observer.disconnect();
        }
      },
      { 
        threshold, 
        rootMargin 
      }
    );

    const currentElement = elementRef.current;
    if (currentElement) {
      observer.observe(currentElement);
    }

    return () => {
      observer.disconnect();
    };
  }, [threshold, rootMargin]);

  return { isVisible, elementRef };
};

/**
 * 懒加载Hook的变体 - 支持重复观察
 * 适用于需要监听元素进入/离开视口的场景
 */
export const useLazyLoadWithToggle = (threshold = 0.1, rootMargin = '50px') => {
  const [isVisible, setIsVisible] = useState(false);
  const elementRef = useRef<HTMLDivElement>(null);

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

    const currentElement = elementRef.current;
    if (currentElement) {
      observer.observe(currentElement);
    }

    return () => {
      observer.disconnect();
    };
  }, [threshold, rootMargin]);

  return { isVisible, elementRef };
};
