// src/hooks/useInfiniteScroll.ts
import { useEffect, useRef, useState } from 'react';

type UseInfiniteScrollProps = {
  loadMore: () => Promise<void>; // 加载更多的异步方法
  hasMore: boolean; // 是否还有更多数据
};

export const useInfiniteScroll = ({ loadMore, hasMore }: UseInfiniteScrollProps) => {
  const [isLoading, setIsLoading] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleScroll = async () => {
      // 触底判断：滚动条距离底部 < 100px 且 有更多数据 且 不在加载中
      const { scrollTop, scrollHeight, clientHeight } = container;
      if (
        scrollTop + clientHeight >= scrollHeight - 100 &&
        hasMore &&
        !isLoading
      ) {
        setIsLoading(true);
        await loadMore();
        setIsLoading(false);
      }
    };

    container.addEventListener('scroll', handleScroll);
    return () => container.removeEventListener('scroll', handleScroll);
  }, [loadMore, hasMore, isLoading]);

  return { containerRef, isLoading };
};