import { useLocation } from 'react-router-dom';
import { useEffect } from 'react';
import { addLeadingSlash, removeLeadingSlash, useActiveSectionId, IS_BROWSER, } from '@redocly/theme/core/openapi';
import { compose, encodeBackSlashes, tryDecodeURIComponent } from '../../utils/index.js';
let initialPageLoad = true;
export function useAutoScroll(routingBasePath) {
    const location = useLocation();
    const basePath = routingBasePath || '/';
    useEffect(() => {
        if (location.pathname === basePath && location.hash === '') {
            window.scrollTo(0, 0);
            return;
        }
        const pathname = removeLeadingSlash(location.pathname.replace(basePath, ''));
        const legacyHash = getLegacyHash(location.hash);
        const element = legacyHash
            ? getElementById(pathname + legacyHash) ||
                document.querySelector(`[id$="${removeLeadingSlash(legacyHash)}"]`) // handle scroll to operation by legacy hash route
            : getElementById(location.hash.replace('#', '')) || getElementById(pathname);
        if (element) {
            element.scrollIntoView();
        }
    }, [location, basePath]);
    const activeSectionId = useActiveSectionId(location, false, false);
    useEffect(() => {
        if (activeSectionId && initialPageLoad) {
            initialPageLoad = false;
            return;
        }
        if (IS_BROWSER &&
            !window.location.pathname.includes(activeSectionId) &&
            !window.location.hash.includes(activeSectionId)) {
            const url = compose(addLeadingSlash, encodeBackSlashes)(activeSectionId);
            window.history.replaceState({}, '', url);
        }
    }, [activeSectionId]);
}
export function getElementById(id) {
    return document.getElementById(tryDecodeURIComponent(id));
}
export function getLegacyHash(hash) {
    const patterns = ['#tag', '#operation', '#paths'];
    for (const pattern of patterns) {
        if (hash.includes(pattern)) {
            return hash.replace(pattern, '').toLowerCase();
        }
    }
    return '';
}
//# sourceMappingURL=useAutoScroll.js.map