import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2025-2026 GoodData Corporation
import { cloneElement, useCallback, useMemo, useState } from "react";
import { getFocusableElements } from "../../utils/domUtilities.js";
import { makeKeyboardNavigation } from "../@utils/keyboardNavigation.js";
import { focusAndEnsureReachableElement, getNextFocusableElement } from "./utils.js";
/**
 * @internal
 */
export const useUiFocusTrapConnectors = (focusCheckFn) => {
    const [element, setElement] = useState(null);
    const handleMoveFocus = useCallback((direction) => () => {
        const { focusableElements } = getFocusableElements(element);
        focusAndEnsureReachableElement(getNextFocusableElement(document.activeElement, focusableElements, direction), focusableElements, direction, focusCheckFn);
    }, [element, focusCheckFn]);
    const handleKeyDown = useMemo(() => makeKeyboardNavigation({
        onFocusNext: [{ code: "Tab", modifiers: ["!Shift"] }],
        onFocusPrevious: [{ code: "Tab", modifiers: ["Shift"] }],
    })({
        onFocusNext: handleMoveFocus("forward"),
        onFocusPrevious: handleMoveFocus("backward"),
    }, { shouldPreventDefault: true, shouldStopPropagation: true }), [handleMoveFocus]);
    return useMemo(() => ({ ref: setElement, onKeyDown: handleKeyDown }), [handleKeyDown]);
};
/**
 * @internal
 */
export function UiFocusTrap({ root, children, focusCheckFn, }) {
    const rootElement = root || _jsx("div", { className: "gd-focus-trap", style: { display: "contents" } });
    const connectors = useUiFocusTrapConnectors(focusCheckFn ?? (() => true));
    return cloneElement(rootElement, { ...rootElement.props, ...connectors }, children);
}
