import { useEffect, useState } from 'react';
import { pageLayoutClassnames } from '../PageLayoutContainer';
import { useViewportType } from '../useViewportType';
/**
 * Отслеживание скролла для динамического отображения футера
 */
export const useScrollManagement = ({ scrollRef, isEndReached, onLoadMore, virtuosoId, }) => {
    const [scrollParent, setScrollParent] = useState(null);
    const [hasVerticalScroll, setHasVerticalScroll] = useState(false);
    const { isMobile } = useViewportType();
    useEffect(() => {
        if (isMobile) {
            // На мобильных устройствах scroll находится на контейнере pageLayout
            const rootScrollElement = document.querySelector(`.${pageLayoutClassnames.root}`);
            if (rootScrollElement instanceof HTMLElement) {
                setScrollParent(rootScrollElement);
                return;
            }
        }
        if (scrollRef?.current) {
            setScrollParent(scrollRef.current);
        }
        if (scrollRef?.current?.parentElement) {
            scrollRef.current.parentElement.style.position = 'relative';
        }
    }, [scrollRef]);
    const recalculateVerticalScroll = () => {
        const list = document.getElementById(virtuosoId);
        if (scrollRef?.current && list) {
            setHasVerticalScroll(list?.clientHeight > scrollRef.current?.clientHeight);
        }
    };
    const handleEndReach = () => {
        if (!isEndReached && onLoadMore) {
            onLoadMore();
        }
    };
    return {
        scrollParent,
        hasVerticalScroll,
        recalculateVerticalScroll,
        handleEndReach,
        isEndReachedWithScroll: isEndReached && hasVerticalScroll,
    };
};
