var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React, { forwardRef } from "react";
import { BoxNew } from "../../primitives/box/index.js";
import { DismissableLayer } from "../../utils/components/dismissablelayer/DismissableLayer.js";
import { FocusBoundary } from "../../utils/components/focus-boundary/FocusBoundary.js";
import { FocusGuards } from "../../utils/components/focus-guards/FocusGuards.js";
import { cl } from "../../utils/helpers/index.js";
import { createTransitionStatusAttribute, useMergeRefs, useOpenChangeAnimationComplete, useScrollLock, } from "../../utils/hooks/index.js";
import { useDialogContext } from "../root/DialogRoot.context.js";
const DialogPopupInternal = forwardRef((_a, forwardedRef) => {
    var { className, modal, closeOnOutsideClick = true, initialFocusTo, returnFocusTo, position = "center", width = "medium", height, id, style, "aria-labelledby": ariaLabelledbyProp, withBackdrop, role = "dialog" } = _a, restProps = __rest(_a, ["className", "modal", "closeOnOutsideClick", "initialFocusTo", "returnFocusTo", "position", "width", "height", "id", "style", "aria-labelledby", "withBackdrop", "role"]);
    const { mounted, popupRef, setPopupElement, triggerElement, setOpen, open, transitionStatus, popupElement, nestedOpenDialogCount: nestedOpenDialogCountProp, nested, size, titleId, popupId, onOpenChangeComplete, setMounted, } = useDialogContext();
    const mergedRefs = useMergeRefs(forwardedRef, popupRef, setPopupElement);
    useScrollLock({
        enabled: open && modal === true,
        mounted,
        open,
        referenceElement: popupElement,
    });
    useOpenChangeAnimationComplete({
        open,
        ref: popupRef,
        onComplete() {
            if (open) {
                onOpenChangeComplete === null || onOpenChangeComplete === void 0 ? void 0 : onOpenChangeComplete(true);
            }
            else {
                setMounted(false);
                onOpenChangeComplete === null || onOpenChangeComplete === void 0 ? void 0 : onOpenChangeComplete(false);
            }
        },
    });
    const resolvedInitialFocus = initialFocusTo !== null && initialFocusTo !== void 0 ? initialFocusTo : popupRef;
    const resolvedReturnFocus = () => {
        if (returnFocusTo) {
            return typeof returnFocusTo === "function"
                ? returnFocusTo()
                : returnFocusTo.current;
        }
        if (isFocusable(triggerElement)) {
            return triggerElement;
        }
        return true;
    };
    return (React.createElement(FocusGuards, null,
        React.createElement(FocusBoundary, { loop: true, trapped: open, initialFocus: resolvedInitialFocus, returnFocus: resolvedReturnFocus, modal: true },
            React.createElement(DismissableLayer, { asChild: true, safeZone: {
                    anchor: triggerElement,
                }, onDismiss: (event) => {
                    open && setOpen(false, event);
                }, disableOutsidePointerEvents: modal === true || withBackdrop, onInteractOutside: (event) => {
                    /**
                     * Since trigger might be set up to close the dialog on click,
                     * we need to prevent dismissing when clicking the trigger to avoid double close events (potentially re-triggering open)
                     */
                    const target = event.target;
                    const targetIsTrigger = triggerElement === null || triggerElement === void 0 ? void 0 : triggerElement.contains(target);
                    if (targetIsTrigger) {
                        event.preventDefault();
                    }
                }, 
                /**
                 * Only close dialog on pointerUp pointerEvents
                 */
                onPointerDownOutside: (event) => {
                    event.preventDefault();
                }, onFocusOutside: (event) => {
                    /**
                     * Focus-events are tricky when dealing with portals and nested dialogs.
                     * If multiple dialogs are open, initial auto-focus might cause
                     * onFocusOutside to trigger on the parent dialog when focusing the child dialog.
                     */
                    event.preventDefault();
                }, enablePointerUpOutside: true, onPointerUpOutside: (event) => {
                    !closeOnOutsideClick && event.preventDefault();
                } },
                React.createElement(BoxNew, Object.assign({ "aria-labelledby": ariaLabelledbyProp !== null && ariaLabelledbyProp !== void 0 ? ariaLabelledbyProp : titleId, id: id !== null && id !== void 0 ? id : popupId }, restProps, { ref: mergedRefs, className: cl("aksel-dialog__popup", className), role: role, "aria-modal": "true" }, createTransitionStatusAttribute(transitionStatus), { "data-position": position, "data-size": size, width: translateWidth(width, position), height: translateHeight(height, position), style: Object.assign(Object.assign({}, style), { "--__axc-nested-level": nestedOpenDialogCountProp }), "data-nested-dialog-open": !!nestedOpenDialogCountProp, "data-nested": !!nested }))))));
});
function translateWidth(width, position) {
    if (position === "fullscreen") {
        return undefined;
    }
    switch (width) {
        case "small":
            return "480px";
        case "medium":
            return "640px";
        case "large":
            return "800px";
        default:
            return width;
    }
}
function translateHeight(height, position) {
    if (position === "fullscreen" ||
        position === "left" ||
        position === "right") {
        return undefined;
    }
    return height;
}
function isFocusable(element) {
    if (!(element === null || element === void 0 ? void 0 : element.isConnected)) {
        return false;
    }
    /**
     * Baselined in 2024
     * @see https://caniuse.com/?search=checkvisibility
     */
    if (typeof element.checkVisibility === "function") {
        return element.checkVisibility();
    }
    return getComputedStyle(element).display !== "none";
}
export { DialogPopupInternal };
//# sourceMappingURL=DialogPopupInternal.js.map