import { useEffect, useCallback, useRef } from 'react';
import { InfiniteScrollOptions } from '../types';

export function useInfiniteScroll({
  threshold = 100,
  loading = false,
  hasMore = true,
  onLoadMore
}: InfiniteScrollOptions) {
  const scrollRef = useRef<HTMLElement | null>(null);
  
  const handleScroll = useCallback(() => {
    if (!scrollRef.current || loading || !hasMore) return;
    
    const element = scrollRef.current;
    const { scrollTop, scrollHeight, clientHeight } = element;
    
    if (scrollHeight - scrollTop - clientHeight < threshold) {
      onLoadMore();
    }
  }, [threshold, loading, hasMore, onLoadMore]);
  
  useEffect(() => {
    const element = scrollRef.current;
    if (!element) return;
    
    element.addEventListener('scroll', handleScroll);
    return () => element.removeEventListener('scroll', handleScroll);
  }, [handleScroll]);
  
  return {
    scrollRef,
    isLoading: loading,
    hasMore
  };
}