import React__default, { useRef, useEffect, createContext, useContext } from 'react';
import ReactDOM__default from 'react-dom';
import classnames from 'classnames';
import { AnimatePresence, motion } from 'framer-motion';
import { useRefocusOnActivator, useFocusTrap, useOnKeyDown } from '@jobber/hooks';
import { H as Heading } from '../Heading-es.js';
import { B as Button } from '../Button-es.js';
import { B as ButtonDismiss } from '../ButtonDismiss-es.js';
import { n as noop } from '../noop-es.js';
import { b as useFloatingNodeId, u as useFloating, c as useDismiss, h as useRole, d as useInteractions, a as useFloatingParentNodeId, e as FloatingTree, f as FloatingNode, F as FloatingPortal, i as FloatingFocusManager, j as FloatingOverlay } from '../floating-ui.react-es.js';
import { b as identity } from '../identity-es.js';
import { A as AtlantisPortalContent } from '../AtlantisPortalContent-es.js';
import '../Typography-es.js';
import '../tslib.es6-es.js';
import 'react-router-dom';
import '../Icon-es.js';
import '@jobber/design';
import '../_commonjsHelpers-es.js';
import '../floating-ui.utils.dom-es.js';
import '../index.esm-es.js';
import 'react/jsx-runtime';
import '../floating-ui.react-dom-es.js';
import '../isTypedArray-es.js';
import '../isObjectLike-es.js';
import '../AtlantisThemeContext-es.js';
import '../_baseAssignValue-es.js';
import '../_baseFor-es.js';
import '../keysIn-es.js';
import '../_isIterateeCall-es.js';
import '../_setToString-es.js';

var styles$1 = {"container":"y3M-9xoEnk0-","containerFullScreen":"IsN-kBe8icY-","overlay":"zkyJp1mib-U-","modal":"gMPgiggaud8-","header":"_5sBzUnyOqD0-","closeButton":"_4gw63G7IYG0-","actionBar":"cwVJrrJkNDg-","leftAction":"MkD4pNUKeAA-","rightAction":"C-yC8JKpQLg-","spinning":"_7hYqr6OrfHs-"};

var sizes = {"small":"BSZvIAUzFEU-","large":"-ydIALYVvGg-","fullScreen":"_9wD-TaKfDys-","spinning":"_10FfgKITqY0-"};

const MODAL_HEADER_ID = "ATL-Modal-Header";

function ModalLegacy({ open = false, title, size, dismissible = true, children, primaryAction, secondaryAction, tertiaryAction, onRequestClose, ariaLabel, }) {
    const modalClassName = classnames(styles$1.modal, size && sizes[size]);
    const containerClassName = classnames(styles$1.container, size === "fullScreen" && styles$1.containerFullScreen);
    useRefocusOnActivator(open);
    const modalRef = useFocusTrap(open);
    useOnKeyDown(handleRequestClose, "Escape");
    const template = (React__default.createElement(AnimatePresence, null, open && (React__default.createElement("div", { ref: modalRef, role: "dialog", className: containerClassName, tabIndex: 0, "aria-modal": "true", "aria-labelledby": title ? MODAL_HEADER_ID : undefined, "aria-label": ariaLabel },
        React__default.createElement(motion.div, { key: styles$1.overlay, className: styles$1.overlay, onClick: onRequestClose, initial: { opacity: 0 }, animate: { opacity: 0.8 }, exit: { opacity: 0 }, transition: { duration: 0.2 } }),
        React__default.createElement(motion.div, { key: styles$1.modal, className: modalClassName, initial: { scale: 0.9, opacity: 0 }, animate: { scale: 1, opacity: 1 }, exit: { scale: 0.9, opacity: 0 }, transition: {
                duration: 0.2,
                ease: "easeInOut",
            } },
            title != undefined && (React__default.createElement(Header, { title: title, dismissible: dismissible, onRequestClose: onRequestClose })),
            children,
            React__default.createElement(Actions, { primary: primaryAction, secondary: secondaryAction, tertiary: tertiaryAction }))))));
    return (globalThis === null || globalThis === void 0 ? void 0 : globalThis.document)
        ? ReactDOM__default.createPortal(template, document.body)
        : template;
    function handleRequestClose() {
        if (open && onRequestClose) {
            onRequestClose();
        }
    }
}
function Header({ title, dismissible, onRequestClose }) {
    return (React__default.createElement("div", { className: styles$1.header, "data-testid": "modal-header" },
        React__default.createElement(Heading, { level: 2, id: MODAL_HEADER_ID }, title),
        dismissible && (React__default.createElement("div", { className: styles$1.closeButton },
            React__default.createElement(ButtonDismiss, { onClick: onRequestClose, ariaLabel: "Close modal" })))));
}
function Actions({ primary, secondary, tertiary }) {
    const shouldShow = primary != undefined || secondary != undefined || tertiary != undefined;
    if (secondary != undefined) {
        secondary = Object.assign({ type: "primary", variation: "subtle" }, secondary);
    }
    if (tertiary != undefined) {
        tertiary = Object.assign({ type: "secondary", variation: "destructive" }, tertiary);
    }
    return (React__default.createElement(React__default.Fragment, null, shouldShow && (React__default.createElement("div", { className: styles$1.actionBar },
        React__default.createElement("div", { className: styles$1.rightAction },
            primary && React__default.createElement(Button, Object.assign({}, primary)),
            secondary && React__default.createElement(Button, Object.assign({}, secondary))),
        tertiary && (React__default.createElement("div", { className: styles$1.leftAction },
            React__default.createElement(Button, Object.assign({}, tertiary))))))));
}

function useModal({ open, activatorRef: refProp, onRequestClose, startedInsideRef, }) {
    const nodeId = useFloatingNodeId();
    const defaultActivatorRef = useRef(null);
    const activatorRef = refProp !== null && refProp !== void 0 ? refProp : defaultActivatorRef;
    const { refs: floatingRefs, context: floatingContext } = useFloating({
        elements: { reference: activatorRef === null || activatorRef === void 0 ? void 0 : activatorRef.current },
        nodeId,
        onOpenChange: (newOpen) => {
            if (!newOpen)
                onRequestClose === null || onRequestClose === void 0 ? void 0 : onRequestClose();
        },
        open: open,
    });
    useEffect(() => {
        if (!startedInsideRef)
            return;
        if (open) {
            // Ensure the first interaction after open is treated as inside
            startedInsideRef.current = true;
        }
        else {
            // Reset on close
            startedInsideRef.current = false;
        }
    }, [open, startedInsideRef]);
    const dismiss = useDismiss(floatingContext, {
        // Use pointerdown so the dialog/overlay capture handlers run first and set intent
        outsidePressEvent: "pointerdown",
        outsidePress: () => {
            var _a;
            const startedInside = (_a = startedInsideRef === null || startedInsideRef === void 0 ? void 0 : startedInsideRef.current) !== null && _a !== void 0 ? _a : true;
            return !startedInside;
        },
        escapeKey: true,
        bubbles: false,
    });
    const role = useRole(floatingContext);
    const { getFloatingProps } = useInteractions([dismiss, role]);
    const parentId = useFloatingParentNodeId();
    return {
        floatingRefs,
        floatingContext,
        nodeId,
        activatorRef,
        parentId,
        getFloatingProps,
    };
}

const ModalContext = createContext({
    open: false,
    onRequestClose: noop,
    activatorRef: { current: null },
    floatingRefs: null,
    floatingContext: {},
    size: undefined,
    floatingNodeId: undefined,
    dismissible: true,
    getFloatingProps: identity,
});
function ModalProvider({ children, open = false, size, onRequestClose = noop, activatorRef: refProp, dismissible = true, modalLabelledBy = MODAL_HEADER_ID, ariaLabel, }) {
    const startedInsideRef = useRef(true);
    const { floatingRefs, floatingContext, nodeId, activatorRef, parentId, getFloatingProps, } = useModal({
        open,
        activatorRef: refProp,
        onRequestClose,
        startedInsideRef,
    });
    const content = (React__default.createElement(ModalContext.Provider, { value: {
            onRequestClose,
            activatorRef,
            floatingRefs,
            floatingContext,
            size,
            open,
            floatingNodeId: nodeId,
            dismissible,
            modalLabelledBy,
            ariaLabel,
            getFloatingProps,
            startedInsideRef,
        } }, children));
    if (parentId) {
        return content;
    }
    return React__default.createElement(FloatingTree, null, content);
}
function useModalContext() {
    return useContext(ModalContext);
}

var styles = {"overlay":"cRhQeXmZobs-","overlayBackground":"PO6ZUDxQoFE-","modal":"OiqCKNmbHZ0-","modalWithStickyRegions":"_6dGKr5VVf9Y-","stickyHeaderRegion":"uo6BCADQuLU-","stickyActionsRegion":"Vq0y9ggAxtI-","modalBody":"zM9SWwAd5Dg-","header":"GDWGHwmjgAc-","closeButton":"KJlGo4z-E6Q-","actionBar":"ZGrhWCAymCw-","leftAction":"hOiEWds2Vq8-","rightAction":"K31NzxPZP9s-","spinning":"SKeimJFlB-g-"};

function useModalStyles(size) {
    return {
        modal: classnames(styles.modal, size && sizes[size]),
        overlay: styles.overlay,
        header: styles.header,
        dismissButton: styles.closeButton,
        actionBar: styles.actionBar,
        leftAction: styles.leftAction,
        rightAction: styles.rightAction,
        overlayBackground: styles.overlayBackground,
    };
}

function ModalHeader({ title, children }) {
    const { header, dismissButton } = useModalStyles();
    const { dismissible, onRequestClose, modalLabelledBy } = useModalContext();
    if (children) {
        return React__default.createElement(React__default.Fragment, null, children);
    }
    return (React__default.createElement("div", { className: header, "data-testid": MODAL_HEADER_ID },
        React__default.createElement(Heading, { level: 2, id: modalLabelledBy }, title),
        dismissible && (React__default.createElement("div", { className: dismissButton },
            React__default.createElement(ButtonDismiss, { onClick: onRequestClose, ariaLabel: "Close modal" })))));
}
function ModalActions({ primary, secondary, tertiary, }) {
    const { actionBar, rightAction, leftAction } = useModalStyles();
    const shouldShow = primary != undefined || secondary != undefined || tertiary != undefined;
    return (React__default.createElement(React__default.Fragment, null, shouldShow && (React__default.createElement("div", { className: actionBar, "data-testid": "ATL-Modal-Actions" },
        React__default.createElement("div", { className: rightAction },
            primary && React__default.createElement(Button, Object.assign({}, primary)),
            secondary && (React__default.createElement(Button, Object.assign({ type: "primary", variation: "subtle" }, secondary)))),
        tertiary && (React__default.createElement("div", { className: leftAction },
            React__default.createElement(Button, Object.assign({ type: "secondary", variation: "destructive" }, tertiary))))))));
}
function ModalActivator({ children }) {
    const { activatorRef } = useModalContext();
    return (React__default.createElement("span", { ref: activatorRef, style: { display: "contents" } }, children));
}
/**
 * Background overlay for the modal. Used in the ModalContent.
 */
function ModalOverlay({ children }) {
    const { overlay, overlayBackground } = useModalStyles();
    const { floatingNodeId, startedInsideRef } = useModalContext();
    return (React__default.createElement(FloatingOverlay, { lockScroll: true, className: overlay, "data-modal-node-id": floatingNodeId },
        React__default.createElement(motion.div, { "aria-hidden": "true", className: overlayBackground, initial: { opacity: 0 }, animate: { opacity: 0.8 }, exit: { opacity: 0 }, transition: { duration: 0.2 }, "data-modal-node-id": floatingNodeId, onPointerDownCapture: () => {
                // Interaction began on overlay: mark as outside for the next click
                if (startedInsideRef)
                    startedInsideRef.current = false;
            } }),
        children));
}
function ModalContent({ children }) {
    const { open, floatingContext, activatorRef, floatingRefs, size, floatingNodeId, modalLabelledBy, ariaLabel, getFloatingProps, startedInsideRef, } = useModalContext();
    const { modal } = useModalStyles(size);
    const childrenArray = React__default.Children.toArray(children);
    const { sticky: stickyHeaders, rest: afterHeaders } = extractSticky(childrenArray, ModalHeader, props => props.variant === "sticky");
    const { sticky: stickyActions, rest: bodyChildren } = extractSticky(afterHeaders, ModalActions, props => props.variant === "sticky");
    const hasStickyRegions = stickyHeaders.length > 0 || stickyActions.length > 0;
    return (React__default.createElement(AnimatePresence, null, open && (React__default.createElement(FloatingNode, { id: floatingNodeId },
        React__default.createElement(FloatingPortal, null,
            React__default.createElement(AtlantisPortalContent, null,
                React__default.createElement(ModalOverlay, null,
                    React__default.createElement(FloatingFocusManager, { context: floatingContext, returnFocus: (activatorRef === null || activatorRef === void 0 ? void 0 : activatorRef.current) ? activatorRef : true, order: ["floating", "content"] },
                        React__default.createElement(motion.div, Object.assign({ initial: { scale: 0.9, opacity: 0 }, animate: { scale: 1, opacity: 1 }, exit: { scale: 0.9, opacity: 0 }, transition: {
                                duration: 0.2,
                                ease: "easeInOut",
                            }, ref: floatingRefs === null || floatingRefs === void 0 ? void 0 : floatingRefs.setFloating, "data-modal-node-id": floatingNodeId }, getFloatingProps({
                            role: "dialog",
                            className: hasStickyRegions
                                ? `${modal} ${styles.modalWithStickyRegions}`
                                : modal,
                            "aria-labelledby": modalLabelledBy,
                            "aria-label": ariaLabel,
                            "aria-modal": true,
                        }), { onPointerDownCapture: () => {
                                // Interaction began inside dialog
                                if (startedInsideRef)
                                    startedInsideRef.current = true;
                            } }),
                            stickyHeaders.length > 0 && (React__default.createElement("div", { className: styles.stickyHeaderRegion }, stickyHeaders)),
                            React__default.createElement("div", { className: styles.modalBody, tabIndex: -1 }, bodyChildren),
                            stickyActions.length > 0 && (React__default.createElement("div", { className: styles.stickyActionsRegion }, stickyActions)))))))))));
}
function extractSticky(children, componentType, match) {
    const sticky = [];
    const rest = children.filter(child => {
        if (React__default.isValidElement(child) &&
            child.type === componentType &&
            match(child.props)) {
            sticky.push(child);
            return false;
        }
        return true;
    });
    return { sticky, rest };
}

function Modal(props) {
    return React__default.createElement(ModalLegacy, Object.assign({}, props));
}
Modal.Header = ModalHeader;
Modal.Actions = ModalActions;
Modal.Activator = ModalActivator;
Modal.Provider = ModalProvider;
Modal.Content = ModalContent;

export { Modal, useModalContext, useModalStyles };
