import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2025-2026 GoodData Corporation
import { useCallback, useMemo, useState } from "react";
import { useAutoupdateRef } from "@gooddata/sdk-ui";
import { getFocusableElements } from "../../utils/domUtilities.js";
import { makeKeyboardNavigation } from "../@utils/keyboardNavigation.js";
/**
 * @internal
 */
export function UiTabOutHandler({ onTabOut, children }) {
    const connectors = useUiTabOutHandlerConnectors(onTabOut);
    return (_jsx("div", { style: { display: "contents" }, ...connectors, children: children }));
}
/**
 * @internal
 */
export const useUiTabOutHandlerConnectors = (handler) => {
    const [element, setElement] = useState(null);
    const handlerRef = useAutoupdateRef(handler);
    const handleMoveFocus = useCallback((direction) => (event) => {
        const { firstElement, lastElement } = getFocusableElements(element);
        if ((direction === "forward" && document.activeElement === lastElement) ||
            (direction === "backward" && document.activeElement === firstElement)) {
            handlerRef.current?.(event);
        }
    }, [element, handlerRef]);
    const handleKeyDown = useMemo(() => makeKeyboardNavigation({
        onFocusNext: [{ code: "Tab", modifiers: ["!Shift"] }],
        onFocusPrevious: [{ code: "Tab", modifiers: ["Shift"] }],
    })({
        onFocusNext: handleMoveFocus("forward"),
        onFocusPrevious: handleMoveFocus("backward"),
    }, { shouldPreventDefault: false, shouldStopPropagation: false }), [handleMoveFocus]);
    return useMemo(() => ({ ref: setElement, onKeyDown: handleKeyDown }), [handleKeyDown]);
};
