import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2025 GoodData Corporation
import { useCallback, useMemo, useRef, } from "react";
import { useAutoupdateRef, useCombineRefs } from "@gooddata/sdk-ui";
import { useUiAutofocusConnectors } from "./UiAutofocus.js";
import { useUiFocusTrapConnectors } from "./UiFocusTrap.js";
import { useUiReturnFocusOnUnmountConnectors, } from "./UiReturnFocusOnUnmount.js";
import { useUiTabOutHandlerConnectors } from "./UiTabOutHandler.js";
/**
 * @internal
 */
export function UiFocusManager({ children, ...args }) {
    const connectors = useUiFocusManagerConnectors(args);
    return (_jsx("div", { className: "gd-focus-manager", style: { display: "contents" }, ...connectors, children: children }));
}
/**
 * @internal
 */
export const useUiFocusManagerConnectors = ({ enableFocusTrap, enableAutofocus, enableReturnFocusOnUnmount, tabOutHandler, focusCheckFn, }) => {
    const element = useRef(null);
    const autofocusOptions = typeof enableAutofocus === "object" ? enableAutofocus : {};
    const returnFocusOnUnmountOptions = typeof enableReturnFocusOnUnmount === "object" ? enableReturnFocusOnUnmount : {};
    const focusTrapConnectors = useUiFocusTrapConnectors(focusCheckFn ?? (() => true));
    const tabOutConnectors = useUiTabOutHandlerConnectors(tabOutHandler);
    const autofocusConnectors = useUiAutofocusConnectors(autofocusOptions);
    const returnFocusConnectors = useUiReturnFocusOnUnmountConnectors(returnFocusOnUnmountOptions);
    const enabledConnectors = useMemo(() => [
        !!tabOutHandler && tabOutConnectors,
        !!enableReturnFocusOnUnmount && returnFocusConnectors,
        !!enableAutofocus && autofocusConnectors,
        !!enableFocusTrap && focusTrapConnectors,
    ].filter(Boolean), [
        autofocusConnectors,
        enableAutofocus,
        enableFocusTrap,
        enableReturnFocusOnUnmount,
        focusTrapConnectors,
        returnFocusConnectors,
        tabOutConnectors,
        tabOutHandler,
    ]);
    const enabledConnectorsRef = useAutoupdateRef(enabledConnectors);
    const combinedRefs = useCombineRefs(...enabledConnectors.map((connector) => connector.ref));
    const combinedRefCallback = useCallback((el) => {
        element.current = el;
        combinedRefs(el);
    }, [combinedRefs]);
    const combinedKeyDown = useCallback((event) => {
        combinedRefs(element.current);
        enabledConnectorsRef.current.forEach((connector) => {
            connector.onKeyDown?.(event);
        });
    }, [enabledConnectorsRef, combinedRefs]);
    return useMemo(() => ({ ref: combinedRefCallback, onKeyDown: combinedKeyDown }), [combinedKeyDown, combinedRefCallback]);
};
