import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2025 GoodData Corporation
import { useCallback, useEffect, useMemo, useRef } from "react";
import { resolveRef } from "./utils.js";
/**
 * @internal
 */
export function UiReturnFocusOnUnmount({ children, ...options }) {
    const connectors = useUiReturnFocusOnUnmountConnectors(options);
    return (_jsx("div", { style: { display: "contents" }, ...connectors, children: children }));
}
/**
 * @internal
 */
export const useUiReturnFocusOnUnmountConnectors = ({ returnFocusTo, } = {}) => {
    const returnFocusRef = useRef(null);
    useEffect(() => {
        returnFocusRef.current = resolveRef(returnFocusTo) ?? document.activeElement;
    }, [returnFocusTo]);
    const hasMountedRef = useRef(false);
    const ref = useCallback((element) => {
        if (element) {
            hasMountedRef.current = true;
            return;
        }
        const elementToFocus = resolveRef(returnFocusRef);
        if (!hasMountedRef.current || !elementToFocus) {
            return;
        }
        elementToFocus.focus();
        hasMountedRef.current = false;
    }, []);
    return useMemo(() => ({ ref }), [ref]);
};
//# sourceMappingURL=UiReturnFocusOnUnmount.js.map