const MINIMIZED_HEADER_HEIGHT = 67;
const EXTRA_SPACE = 48; // Defined by UX
export const scrollAndFocus = ({ scrollableRef, containerRef, focusedItemRef, afterScroll, }) => {
    if (containerRef && focusedItemRef && scrollableRef) {
        focusedItemRef.focus({ preventScroll: true });
        const scrollableRefTop = getTop(scrollableRef);
        const containerRefTop = getTop(containerRef);
        const top = containerRefTop -
            scrollableRefTop -
            MINIMIZED_HEADER_HEIGHT -
            EXTRA_SPACE;
        const isFullHeaderDisplayed = scrollableRef.scrollTop < 40;
        const avoidScrollingToKeepFullHeader = isFullHeaderDisplayed && top < 200;
        if (avoidScrollingToKeepFullHeader) {
            afterScroll?.();
        }
        else {
            setTimeout(async () => {
                scrollableRef.scrollBy({
                    top,
                    behavior: 'smooth',
                });
                // Check if the scroll has finished
                await waitForScrollToFinish(scrollableRef);
                afterScroll?.();
            }, 500);
        }
    }
};
const getTop = (ref) => ref && ref.getBoundingClientRect ? ref.getBoundingClientRect().top : 0;
function waitForScrollToFinish(scrollableRef) {
    return new Promise((resolve) => {
        let lastScrollTop = scrollableRef.scrollTop;
        const checkIfScrollFinished = () => {
            setTimeout(() => {
                const currentScrollTop = scrollableRef.scrollTop;
                // If the scroll position has not changed, the scroll is finished
                if (currentScrollTop === lastScrollTop) {
                    resolve('');
                }
                else {
                    // Otherwise, update the lastScrollTop and keep checking
                    lastScrollTop = currentScrollTop;
                    checkIfScrollFinished();
                }
            }, 100);
        };
        checkIfScrollFinished();
    });
}
//# sourceMappingURL=scrollAndFocus.js.map