import { useDispatch, useSelector } from "../components/FinsembleProvider";
import { MenuActions } from "../actions/menuActions";
import { useCallback, useContext } from "react";
import { MenuContext } from "../components/menu/menuContext";
import { FEAGlobals } from "../../common/Globals";
/**
 * A hook for working with menus. It gets its implicit menu "id" from React context.
 * It dispatches actions to the reducer to modify menu state across MenuShell instances.
 *
 * See menuReducer.ts for "toggle/blur" race condition algorithm
 *
 * Setting window.FEAGlobals.FSBL.debug=true will override menu close on blur, to make it easier to debug windows
 */
export const useMenu = () => {
    const DURATION = 120;
    const dispatch = useDispatch();
    const { openMenuId } = useSelector((state) => state.menu);
    const { thisMenuId } = useContext(MenuContext);
    const toggleMenu = useCallback(() => {
        dispatch(MenuActions.TOGGLE_MENU(thisMenuId));
    }, [dispatch, thisMenuId]);
    const openMenu = useCallback(() => {
        // without this call, the toolbar will stay hidden behind other content, and the menus will not be visible
        FEAGlobals.FSBL.Clients.WindowClient.bringToFront();
        dispatch(MenuActions.OPEN_MENU(thisMenuId));
    }, [dispatch, thisMenuId]);
    const closeMenu = useCallback(() => {
        dispatch(MenuActions.CLOSE_MENU(thisMenuId));
    }, [dispatch, thisMenuId]);
    const blurMenu = useCallback(() => {
        var _a;
        if ((_a = FEAGlobals.FSBL) === null || _a === void 0 ? void 0 : _a.debug)
            return; // If we're debugging then don't blur menus
        // This is a purposeful closure. There is no need to update it with new state.
        const closeIfPending = () => {
            dispatch(MenuActions.CLOSE_MENU_IF_PENDING(thisMenuId));
        };
        dispatch(MenuActions.BLUR_MENU(thisMenuId));
        // See menuReducer.ts for how this timeout is used. Removing the timeout will cause a race condition.
        setTimeout(closeIfPending, DURATION);
    }, [dispatch, thisMenuId]);
    const isMenuActive = () => openMenuId === thisMenuId;
    return {
        openMenuId,
        toggleMenu,
        closeMenu,
        openMenu,
        blurMenu,
        isMenuActive,
    };
};
//# sourceMappingURL=useMenu.js.map