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 { useFloatingPortalNode } from "@floating-ui/react";
import React, { forwardRef, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { useDateInputContext } from "../date/Date.Input.js";
import { useProvider } from "../provider/Provider.js";
import { Detail, Heading } from "../typography/index.js";
import { useId } from "../utils-external/index.js";
import { cl, composeEventHandlers } from "../utils/helpers/index.js";
import { useMergeRefs, useScrollLock } from "../utils/hooks/index.js";
import { ModalContextProvider, useModalContext } from "./Modal.context.js";
import ModalBody from "./ModalBody.js";
import ModalFooter from "./ModalFooter.js";
import ModalHeader from "./ModalHeader.js";
import { coordsAreInside, getCloseHandler, useIsModalOpen, } from "./ModalUtils.js";
import dialogPolyfill, { needPolyfill } from "./dialog-polyfill.js";
const polyfillClassName = "aksel-modal--polyfilled";
/**
 * A component that displays a modal dialog.
 *
 * @see [📝 Documentation](https://aksel.nav.no/komponenter/core/modal)
 * @see 🏷️ {@link ModalProps}
 *
 * @example
 * State change with `useRef`
 * ```jsx
 * const ref = useRef<HTMLDialogElement>(null);
 * <Button onClick={() => ref.current?.showModal()}>Open modal</Button>
 * <Modal
 *   ref={ref}
 *   header={{
 *     label: "Optional label",
 *     icon: <FileIcon aria-hidden />,
 *     heading: "My heading",
 *   }}
 * >
 *   <Modal.Body>
 *     <BodyLong>Hello world</BodyLong>
 *   </Modal.Body>
 *   <Modal.Footer>
 *     <Button>Save</Button>
 *     <Button type="button" variant="tertiary" onClick={() => ref.current?.close()}>Close</Button>
 *   </Modal.Footer>
 * </Modal>
 * ```
 * @example
 * State change with `useState`
 * ```jsx
 * const [open, setOpen] = useState(false);
 * <Modal
 *   open={open}
 *   onClose={() => setOpen(false)}
 *   aria-labelledby="modal-heading"
 * >
 *   <Modal.Header>
 *     <Heading level="1" size="large" id="modal-heading">My heading</Heading>
 *   </Modal.Header>
 *   <Modal.Body>
 *     <BodyLong>Hello world</BodyLong>
 *   </Modal.Body>
 * </Modal>
 * ```
 */
export const Modal = forwardRef((_a, ref) => {
    var _b, _c;
    var { header, children, open, onBeforeClose, onCancel, closeOnBackdropClick, width, placement, portal, className, "aria-labelledby": ariaLabelledby, style, onClick, onMouseDown, size = "medium" } = _a, rest = __rest(_a, ["header", "children", "open", "onBeforeClose", "onCancel", "closeOnBackdropClick", "width", "placement", "portal", "className", "aria-labelledby", "style", "onClick", "onMouseDown", "size"]);
    const modalRef = useRef(null);
    const mergedRef = useMergeRefs(modalRef, ref);
    const ariaLabelId = useId();
    const rootElement = (_b = useProvider()) === null || _b === void 0 ? void 0 : _b.rootElement;
    const portalNode = useFloatingPortalNode({ root: rootElement });
    const dateContext = useDateInputContext(false);
    const isNested = useModalContext(false) !== undefined;
    const isModalOpen = useIsModalOpen(modalRef.current);
    if (isNested && !dateContext) {
        console.error("Modals should not be nested");
    }
    useEffect(() => {
        // If using portal, modalRef.current will not be set before portalNode is set.
        // If not using portal, modalRef.current is available first.
        // We check both to avoid activating polyfill twice when not using portal.
        if (needPolyfill && modalRef.current && portalNode) {
            dialogPolyfill.registerDialog(modalRef.current);
            // Force-add the "polyfilled" class in case of SSR (needPolyfill will always be false on the server)
            modalRef.current.classList.add(polyfillClassName);
        }
        // We set autofocus on the dialog element to prevent the default behavior where first focusable element gets focus when modal is opened.
        // This is mainly to fix an edge case where having a Tooltip as the first focusable element would make it activate when you open the modal.
        // We have to use JS because it doesn't work to set it with a prop (React bug?)
        // Currently doesn't seem to work in Chrome. See also Tooltip.tsx
        if (modalRef.current && portalNode)
            modalRef.current.autofocus = true;
    }, [portalNode]);
    useEffect(() => {
        // We need to have this in a useEffect so that the content renders before the modal is displayed,
        // and in case `open` is true initially.
        // We need to check both modalRef.current and portalNode to make sure the polyfill has been activated.
        if (modalRef.current && portalNode && open !== undefined) {
            if (open && !modalRef.current.open) {
                modalRef.current.showModal();
            }
            else if (!open && modalRef.current.open) {
                modalRef.current.close();
            }
        }
    }, [portalNode, open]);
    useScrollLock({
        enabled: isModalOpen,
        mounted: isModalOpen,
        open: isModalOpen,
        referenceElement: modalRef.current,
    });
    const isWidthPreset = typeof width === "string" && ["small", "medium"].includes(width);
    const mergedClassName = cl("aksel-modal", className, `aksel-modal--${size}`, {
        [polyfillClassName]: needPolyfill,
        "aksel-modal--autowidth": !width,
        [`aksel-modal--width-${width}`]: isWidthPreset,
        "aksel-modal--top": placement === "top" && !needPolyfill,
    });
    const mergedStyle = Object.assign(Object.assign({}, style), (!isWidthPreset ? { width } : {}));
    const mouseClickStart = useRef({
        clientX: 0,
        clientY: 0,
    });
    const handleModalMouseDown = (event) => {
        mouseClickStart.current = event;
    };
    const shouldHandleModalClick = closeOnBackdropClick && !needPolyfill;
    /**
     * `closeOnBackdropClick` has issues on polyfill when nesting modals (DatePicker)
     */
    const handleModalClick = (endEvent) => {
        if (endEvent.target !== modalRef.current) {
            return;
        }
        const modalRect = modalRef.current.getBoundingClientRect();
        if (coordsAreInside(mouseClickStart.current, modalRect) ||
            coordsAreInside(endEvent, modalRect)) {
            return;
        }
        if (onBeforeClose !== undefined && onBeforeClose() === false) {
            return;
        }
        modalRef.current.close();
    };
    /**
     * onCancel fires when you press `Esc`
     */
    const handleModalCancel = (event) => {
        onBeforeClose && onBeforeClose() === false && event.preventDefault();
    };
    const mergedAriaLabelledBy = !ariaLabelledby && !rest["aria-label"] && header
        ? ariaLabelId
        : ariaLabelledby;
    const component = (React.createElement("dialog", Object.assign({}, rest, { ref: mergedRef, className: mergedClassName, style: mergedStyle, onCancel: composeEventHandlers(onCancel, handleModalCancel), onClick: shouldHandleModalClick
            ? composeEventHandlers(onClick, handleModalClick)
            : onClick, onMouseDown: shouldHandleModalClick
            ? composeEventHandlers(onMouseDown, handleModalMouseDown)
            : onMouseDown, "aria-labelledby": mergedAriaLabelledBy, onKeyDown: (e) => {
            /**
             * Stops propagation of Escape key to prevent closing parent modals/dialogs
             */
            if (e.key === "Escape") {
                e.stopPropagation();
            }
        } }),
        React.createElement(ModalContextProvider, { closeHandler: getCloseHandler(modalRef, header, onBeforeClose), modalRef: modalRef },
            header && (React.createElement(ModalHeader, null,
                header.label && (React.createElement(Detail, { className: "aksel-modal__label" }, header.label)),
                React.createElement(Heading, { size: (_c = header.size) !== null && _c !== void 0 ? _c : "medium", level: "1", id: ariaLabelId },
                    header.icon && (React.createElement("span", { className: "aksel-modal__header-icon" }, header.icon)),
                    header.heading))),
            children)));
    if (portal) {
        if (portalNode)
            return createPortal(component, portalNode);
        return null;
    }
    return component;
});
Modal.Header = ModalHeader;
Modal.Body = ModalBody;
Modal.Footer = ModalFooter;
export default Modal;
//# sourceMappingURL=Modal.js.map