import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useState, useEffect, useContext, useMemo } from 'react';
import BareButton from '../Button/BareButton';
import Popover from '../Popover';
import Menu from '../Menu';
import { useConsolidatedRef, useI18n } from '../../hooks';
import Tooltip from '../Tooltip';
import AppShellContext from './AppShellContext';
import { StyledAppShellTooltip } from './AppShell.styles';
const Operator = forwardRef(function Operator({ children, actions, popover, as }, ref) {
    const { navOpen } = useContext(AppShellContext);
    const buttonRef = useConsolidatedRef(ref);
    const t = useI18n();
    const operatorMenuItems = useMemo(() => {
        return actions.flat().map(({ id, primary, onClick: click, ...rest }) => ({
            id: id || primary,
            primary,
            onClick: (menuId, e) => click?.(e),
            ...rest
        }));
    }, [actions]);
    const [showMenu, setShowMenu] = useState(false);
    useEffect(() => {
        if (!navOpen)
            setShowMenu(false);
    }, [navOpen]);
    return (_jsxs(_Fragment, { children: [_jsx(BareButton, { as: as, ref: buttonRef, "aria-expanded": showMenu ? 'true' : 'false', "aria-haspopup": 'menu', onClick: () => {
                    setShowMenu(cur => !cur);
                }, onKeyDown: (e) => {
                    if (e.key === 'Escape')
                        setShowMenu(false);
                }, onBlur: () => {
                    setShowMenu(false);
                }, children: children }), _jsx(Tooltip, { target: buttonRef.current, as: StyledAppShellTooltip, showDelay: 'none', hideDelay: 'none', children: t('app_shell_user_account') }), _jsx(Popover, { ...popover, show: showMenu, target: buttonRef.current, children: _jsx(Menu, { focusControlEl: buttonRef.current ?? undefined, mode: 'action', items: operatorMenuItems, 
                    /** @see {@link MenuButton} implementation for explanation of conditions. This is in essence duplicated. */
                    onItemClick: (_, e) => {
                        if (e
                            .detail > 0) {
                            setShowMenu(false);
                        }
                    } }) })] }));
});
export default Operator;
//# sourceMappingURL=Operator.js.map