import React, { useState, useCallback, useRef } from 'react';
import { PopoverMenu, IconButton, Loader, Tooltip } from '@wix/design-system';
import { MoreSmall } from '@wix/wix-ui-icons-common';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useCloseOnAncestorScroll } from '../../hooks/useCloseOnAncestorScroll';
export function HeaderActionsPopover({ actions, dataHook, className, }) {
    const { translate: t } = useWixPatternsContainer();
    const [menuOpen, setMenuOpen] = useState(false);
    const [popoverKey, setPopoverKey] = useState(0);
    const wrapperRef = useRef(null);
    const closePopover = useCallback(() => {
        setMenuOpen(false);
        setPopoverKey((k) => k + 1);
    }, []);
    useCloseOnAncestorScroll(wrapperRef, closePopover, menuOpen);
    const menuItems = actions
        .filter((group) => group.length > 0)
        .reduce((result, group, index, array) => {
        const items = group.map((action, i) => (React.createElement(PopoverMenu.MenuItem, { key: `${index}-${i}`, text: action.label, onClick: action.disabled || action.loading ? undefined : action.onClick, prefixIcon: action.loading ? (React.createElement("span", null,
                React.createElement(Loader, { size: "tiny" }))) : (action.icon), disabled: action.disabled || action.loading, disabledDescription: action.loading ? undefined : action.disabledTooltip, skin: action.skin })));
        const divider = index < array.length - 1
            ? [React.createElement(PopoverMenu.Divider, { key: `divider-${index}` })]
            : [];
        return [...result, ...items, ...divider];
    }, []);
    if (menuItems.length === 0) {
        return null;
    }
    return (
    // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
    React.createElement("div", { ref: wrapperRef, className: className, "data-menu-open": menuOpen ? 'true' : 'false', "data-hook": dataHook, onClick: (e) => e.stopPropagation() },
        React.createElement(Tooltip, { content: t('cairo.moreActions'), disabled: menuOpen, appendTo: "window" },
            React.createElement(PopoverMenu, { key: popoverKey, dataHook: dataHook ? `${dataHook}-menu` : undefined, textSize: "small", triggerElement: React.createElement(IconButton, { size: "tiny", skin: "dark", priority: "tertiary", ariaLabel: t('cairo.moreActions'), dataHook: dataHook ? `${dataHook}-more-button` : undefined },
                    React.createElement(MoreSmall, null)), appendTo: "window", placement: "bottom-end", onShow: () => setMenuOpen(true), onHide: () => setMenuOpen(false) }, menuItems))));
}
//# sourceMappingURL=HeaderActionsPopover.js.map