import { jsx as _jsx } from "react/jsx-runtime";
import { useCallback, useEffect } from 'react';
import { useBeforeUnload, useLocation, useNavigation } from 'react-router-dom';
export function ElementScrollRestoration({ elementQuery, ...props }) {
    const STORAGE_KEY = `position:${elementQuery}`;
    const navigation = useNavigation();
    const location = useLocation();
    const updatePositions = useCallback(() => {
        const element = document.querySelector(elementQuery);
        if (!element)
            return;
        let positions = {};
        try {
            const rawPositions = JSON.parse(sessionStorage.getItem(STORAGE_KEY) || '{}');
            if (typeof rawPositions === 'object' && rawPositions !== null) {
                positions = rawPositions;
            }
        }
        catch (error) {
            console.warn(`Error parsing scroll positions from sessionStorage:`, error);
        }
        const newPositions = {
            ...positions,
            [location.key]: element.scrollTop,
        };
        sessionStorage.setItem(STORAGE_KEY, JSON.stringify(newPositions));
    }, [STORAGE_KEY, elementQuery, location.key]);
    useEffect(() => {
        if (navigation.state === 'idle') {
            const element = document.querySelector(elementQuery);
            if (!element)
                return;
            try {
                const positions = JSON.parse(sessionStorage.getItem(STORAGE_KEY) || '{}');
                const storedY = positions[window.history.state.key];
                if (typeof storedY === 'number') {
                    element.scrollTop = storedY;
                }
            }
            catch (error) {
                console.error(error);
                sessionStorage.removeItem(STORAGE_KEY);
            }
        }
        else {
            updatePositions();
        }
    }, [STORAGE_KEY, elementQuery, navigation.state, updatePositions]);
    useBeforeUnload(() => {
        updatePositions();
    });
    function restoreScroll(storageKey, elementQuery) {
        const element = document.querySelector(elementQuery);
        if (!element) {
            console.warn(`Element not found: ${elementQuery}. Cannot restore scroll.`);
            return;
        }
        if (!window.history.state || !window.history.state.key) {
            const key = Math.random().toString(32).slice(2);
            window.history.replaceState({ key }, '');
        }
        try {
            const positions = JSON.parse(sessionStorage.getItem(storageKey) || '{}');
            const storedY = positions[window.history.state.key];
            if (typeof storedY === 'number') {
                element.scrollTop = storedY;
            }
        }
        catch (error) {
            console.error(error);
            sessionStorage.removeItem(storageKey);
        }
    }
    return (_jsx("script", { ...props, suppressHydrationWarning: true, dangerouslySetInnerHTML: {
            __html: `(${restoreScroll})(${JSON.stringify(STORAGE_KEY)}, ${JSON.stringify(elementQuery)})`,
        } }));
}
