import { useEffect, useRef } from 'react';

export function useAutoScroll(dependency: unknown) {
    const viewportRef = useRef<HTMLDivElement>(null);
    const shouldAutoScrollRef = useRef(true);

    const handleScroll = () => {
        const viewport = viewportRef.current;
        if (!viewport) return;
        
        const { scrollTop, scrollHeight, clientHeight } = viewport;
        // If user is near bottom (within 50px), enable auto-scroll
        const isNearBottom = scrollHeight - scrollTop - clientHeight < 50;
        shouldAutoScrollRef.current = isNearBottom;
    };

    useEffect(() => {
        const viewport = viewportRef.current;
        if (viewport) {
            // Initial check
            const { scrollTop, scrollHeight, clientHeight } = viewport;
            shouldAutoScrollRef.current = scrollHeight - scrollTop - clientHeight < 50;
            
            viewport.addEventListener('scroll', handleScroll);
            return () => viewport.removeEventListener('scroll', handleScroll);
        }
    }, []);

    useEffect(() => {
        if (shouldAutoScrollRef.current && viewportRef.current) {
            const viewport = viewportRef.current;
            viewport.scrollTop = viewport.scrollHeight;
        }
    }, [dependency]);

    return viewportRef;
}

