import React__default, { useState } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import { useIsMounted, useRefocusOnActivator, useFocusTrap, useOnKeyDown } from '@jobber/hooks';
import { createPortal } from 'react-dom';
import { tokens } from '@jobber/design';
import { e as TRANSITION_DELAY_IN_SECONDS } from './DataList.const-es.js';

var styles = {"menu":"e1ztw2-YxtM-","overlay":"uMoOb93Pf1Q-","spinning":"_0wS9DWCNuj4-"};

const variants = {
    hidden: { opacity: 0, y: -10 },
    visible: { opacity: 1, y: 0 },
};
function DataListActionsMenu({ visible = false, position, onRequestClose, children, }) {
    const [ref, setRef] = useState();
    const mounted = useIsMounted();
    useRefocusOnActivator(visible);
    const focusTrapRef = useFocusTrap(visible);
    useOnKeyDown(onRequestClose, "Escape");
    const actionsMenu = (React__default.createElement(AnimatePresence, null, visible && (React__default.createElement("div", { ref: focusTrapRef, onClick: handleClick },
        React__default.createElement(motion.div, { role: "menu", "data-elevation": "elevated", ref: setRef, variants: variants, initial: "hidden", animate: "visible", exit: "hidden", transition: { duration: TRANSITION_DELAY_IN_SECONDS }, className: styles.menu, style: getPositionCssVars(), onClick: onRequestClose }, children),
        React__default.createElement("button", { type: "button", className: styles.overlay, onClick: onRequestClose, "aria-label": "Close menu" })))));
    return mounted.current
        ? createPortal(actionsMenu, document.body)
        : actionsMenu;
    function handleClick(event) {
        // Prevent menu from firing the parent's onClick event when it is nested
        // within a clickable list item
        event.stopPropagation();
    }
    function getPositionCssVars() {
        const { posX, posY } = getPosition();
        return {
            "--actions-menu-x": `${posX}px`,
            "--actions-menu-y": `${posY}px`,
        };
    }
    function getPosition() {
        const rect = ref === null || ref === void 0 ? void 0 : ref.getBoundingClientRect();
        const { width = 0, height = 0 } = rect || {};
        const { x, y } = position;
        const xIsOffScreen = x + width > window.innerWidth;
        const yIsOffScreen = y + height > window.innerHeight;
        const xOffSet = x + width - window.innerWidth + tokens["space-base"];
        const yOffSet = y + height - window.innerHeight;
        const newPosX = Math.floor(xIsOffScreen ? x - xOffSet : x);
        const newPosY = Math.floor(yIsOffScreen ? y - yOffSet : y);
        return { posX: newPosX, posY: newPosY };
    }
}

export { DataListActionsMenu as D };
