import {useRef, useEffect} from '@wordpress/element';

const useSmoothScroll = (dependencyArray = []) => {
    const ref = useRef(null);

    const smoothScrollToBottom = () => {
        if (!ref.current) return;

        const {scrollHeight, clientHeight} = ref.current;
        const scrollDifference = scrollHeight - clientHeight;
        const startScroll = ref.current.scrollTop;
        const startTime = performance.now();
        const duration = 180; // Duration in ms

        const animateScroll = (timestamp) => {
            const elapsed = timestamp - startTime;
            const progress = Math.min(elapsed / duration, 1);
            const easeInOutQuad = progress < 0.5
                ? 2 * progress * progress
                : -1 + (4 - 2 * progress) * progress;

            ref.current.scrollTop = startScroll + (scrollDifference - startScroll) * easeInOutQuad;

            if (elapsed < duration) {
                window.requestAnimationFrame(animateScroll);
            }
        };

        window.requestAnimationFrame(animateScroll);
    };

    useEffect(() => {
        smoothScrollToBottom();
    }, dependencyArray);

    return ref;
};

export default useSmoothScroll;
