import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2025 GoodData Corporation
import { useCallback, useMemo, useRef } from "react";
import { useAutoupdateRef } from "@gooddata/sdk-ui";
import { resolveRef } from "./utils.js";
import { getFocusableElements, isElementFocusable } from "../../utils/domUtilities.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 originalFocusRef = useRef(document.activeElement);
    const returnFocusToRef = useAutoupdateRef(returnFocusTo);
    const hasMountedRef = useRef(false);
    const ref = useCallback((element) => {
        if (element) {
            hasMountedRef.current = true;
            return;
        }
        const generalElementToFocus = resolveRef(returnFocusToRef.current) ?? originalFocusRef.current;
        const focusableElement = isElementFocusable(generalElementToFocus)
            ? generalElementToFocus
            : getFocusableElements(generalElementToFocus).firstElement;
        if (!hasMountedRef.current || !focusableElement) {
            return;
        }
        focusableElement.focus();
        hasMountedRef.current = false;
    }, [returnFocusToRef]);
    return useMemo(() => ({ ref }), [ref]);
};
//# sourceMappingURL=UiReturnFocusOnUnmount.js.map