import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect } from 'react';
import styled, { css } from 'styled-components';
import Popover from '../Popover';
import { useConsolidatedRef, useDirection, useOuterEvent, useEscape, useUID } from '../../hooks';
import Menu from '../Menu';
import { defaultThemeProp } from '../../theme';
import Flex from '../Flex';
import { getFocusables } from '../../utils';
import Text from '../Text';
const StyledPresetMenuPopover = styled(Popover)(({ theme: { base: { 'content-width': contentWidth } } }) => {
    return css `
    min-width: ${contentWidth.xs};
  `;
});
StyledPresetMenuPopover.defaultProps = defaultThemeProp;
const PresetMenuPopover = ({ heading, buttonRef, menu, isOpen, onClose }) => {
    const popoverRef = useConsolidatedRef();
    const { rtl } = useDirection();
    const headingId = useUID();
    useEscape(e => {
        if (isOpen) {
            onClose();
            e.stopPropagation();
        }
    }, buttonRef);
    useOuterEvent(['mousedown', 'focusin'], [popoverRef], () => {
        if (isOpen) {
            onClose();
        }
    });
    useEffect(() => {
        if (isOpen)
            getFocusables(popoverRef)[0]?.focus();
    }, [isOpen]);
    return (_jsx(StyledPresetMenuPopover, { placement: rtl ? 'bottom-end' : 'bottom-start', hideOnTargetHidden: true, show: !!menu && isOpen, target: buttonRef?.current, ref: popoverRef, "aria-labelledby": headingId, children: menu && (_jsxs(_Fragment, { children: [_jsx(Flex, { container: { pad: [1, 2] }, children: _jsx(Text, { variant: 'h3', id: headingId, children: heading }) }), _jsx(Menu, { ...menu, items: menu.items, onItemClick: (itemId, e) => {
                        if (menu?.mode !== 'multi-select' &&
                            e
                                .detail > 0) {
                            onClose();
                        }
                        menu?.onItemClick?.(itemId, e);
                    }, focusControlEl: buttonRef?.current ?? undefined })] })) }));
};
export default PresetMenuPopover;
//# sourceMappingURL=PresetMenuPopover.js.map