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

function useStickyOnScroll(threshold: number = 5, delay: number = 100): boolean {
    const [isSticky, setIsSticky] = useState<boolean>(true);
    const lastScrollTop = useRef<number>(0);
    const userInitiatedScroll = useRef<boolean>(false);
    const scrollTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);

    useEffect(() => {
        const enableUserScroll = () => {
            userInitiatedScroll.current = true;

            if (scrollTimeout.current) {
                clearTimeout(scrollTimeout.current);
            }

            scrollTimeout.current = setTimeout(() => {
                userInitiatedScroll.current = false;
            }, delay);
        };

        const handleScroll = () => {
            const scrollTop = window.scrollY || document.documentElement.scrollTop;
            const delta = scrollTop - lastScrollTop.current;

            if (!userInitiatedScroll.current) return;

            if (delta > threshold) {
                setIsSticky(false);
            } else if (delta < -threshold) {
                setIsSticky(true);
            }

            lastScrollTop.current = scrollTop;
        };

        lastScrollTop.current = window.scrollY || document.documentElement.scrollTop;

        window.addEventListener('wheel', enableUserScroll, { passive: true });
        window.addEventListener('touchmove', enableUserScroll, { passive: true });
        window.addEventListener('scroll', handleScroll, { passive: true });

        return () => {
            window.removeEventListener('wheel', enableUserScroll);
            window.removeEventListener('touchmove', enableUserScroll);
            window.removeEventListener('scroll', handleScroll);
            if (scrollTimeout.current) {
                clearTimeout(scrollTimeout.current);
            }
        };
    }, [threshold, delay]);

    return isSticky;
}

export default useStickyOnScroll;
