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

interface UseInfiniteScrollOptions {
    hasMore: boolean;
    isLoading: boolean;
    onLoadMore: () => void;
    rootMargin?: string;
    threshold?: number;
}

export const useInfiniteScroll = ({
    hasMore,
    isLoading,
    onLoadMore,
    rootMargin = '100px',
    threshold = 0.1,
}: UseInfiniteScrollOptions) => {
    const sentinelRef = useRef<HTMLDivElement>(null);

    const handleIntersection = useCallback(
        (entries: IntersectionObserverEntry[]) => {
            const [entry] = entries;

            if (entry.isIntersecting && hasMore && !isLoading) {
                onLoadMore();
            }
        },
        [hasMore, isLoading, onLoadMore]
    );

    useEffect(() => {
        const sentinel = sentinelRef.current;
        if (!sentinel) {
            return;
        }

        const observer = new IntersectionObserver(handleIntersection, {
            rootMargin,
            threshold,
        });

        observer.observe(sentinel);

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

    return {
        sentinelRef,
    };
};
