import {
  toReactNodes
} from "./chunk-VE7J2N47.js";
import {
  useLiveRef
} from "./chunk-NBCCPGA4.js";
import {
  ProgressBar
} from "./chunk-E3AOYBY5.js";
import {
  Button
} from "./chunk-ZANLDY2W.js";
import {
  select
} from "./chunk-YMNSXZ5D.js";
import {
  UnstyledButton
} from "./chunk-3GS5EFXV.js";
import {
  z
} from "./chunk-55OQPFLF.js";
import {
  overflowAutoWithoutScrollbars,
  pxToRems
} from "./chunk-FCZJILMW.js";
import {
  Icon
} from "./chunk-RWIZ7Q74.js";
import {
  overlaySurface,
  standardBorderRadius,
  standardContentInset,
  standardFocusOutline
} from "./chunk-JK4BP73A.js";
import {
  bp,
  useBreakpoints
} from "./chunk-JSGRNWSB.js";

// src/components/Modal.tsx
import styled from "@emotion/styled";
import React, { Fragment, useEffect, useLayoutEffect, useRef } from "react";
import ReactDOM from "react-dom";
import { jsx, jsxs } from "@emotion/react/jsx-runtime";
function Modal({
  visible,
  title,
  description,
  children,
  onClose,
  onCancel,
  cancelDisabled,
  cancelHidden,
  ghost,
  onSubmit,
  submitDisabled,
  submitLoading,
  submitText,
  cancelText = "Cancel",
  firstFocusRef,
  nonDismissable = false,
  autoFocus = true,
  width = 460,
  progressBar
}) {
  const visibleChangedRef = useRef(false);
  const nodeRef = useRef(null);
  const [defaultFirstFocusRef, defaultFirstFocusRefCb] = useLiveRef();
  const ref = firstFocusRef || defaultFirstFocusRef;
  const [nodeReady, setNodeReady] = React.useState(false);
  const overlayRef = useRef(null);
  const prevFocusedElement = useRef();
  const modalContainerRef = useRef(null);
  const bp2 = useBreakpoints();
  const isSm = bp2.current("sm" /* sm */);
  const formattedDescription = description ? toReactNodes(description) : null;
  useEffect(() => {
    if (visible !== visibleChangedRef.current) {
      visibleChangedRef.current = visible;
    }
  }, [visible]);
  const visibleChanged = visible !== visibleChangedRef.current;
  useEffect(() => {
    prevFocusedElement.current = document.activeElement;
    if (!nodeRef.current) {
      nodeRef.current = document.createElement("div");
      document.body.appendChild(nodeRef.current);
    }
    setNodeReady(true);
    return () => {
      if (nodeRef.current) {
        document.body.removeChild(nodeRef.current);
        nodeRef.current = null;
      }
    };
  }, []);
  useEffect(() => {
    const handleOutsideClick = (event) => {
      if (visible && overlayRef.current && event.target && overlayRef.current.contains(event.target) && !nonDismissable) {
        onClose();
      }
    };
    const handleKeyDown = (event) => {
      if (visible && event.key === "Escape" && !nonDismissable) {
        onClose();
      }
    };
    if (visible) {
      if (modalContainerRef.current) {
        modalContainerRef.current.addEventListener("keydown", handleKeyDown);
      }
      if (overlayRef.current) {
        overlayRef.current.addEventListener("click", handleOutsideClick);
      }
    } else {
      if (modalContainerRef.current) {
        modalContainerRef.current.removeEventListener("keydown", handleKeyDown);
      }
      if (overlayRef.current) {
        overlayRef.current.removeEventListener("click", handleOutsideClick);
      }
    }
    const containerRef = modalContainerRef.current;
    const overlayRefVar = overlayRef.current;
    return () => {
      if (containerRef) {
        containerRef.removeEventListener("keydown", handleKeyDown);
      }
      if (overlayRefVar) {
        overlayRefVar.removeEventListener("click", handleOutsideClick);
      }
    };
  }, [onClose, visible, nonDismissable]);
  useLayoutEffect(() => {
    if (visible) {
      if (visibleChanged) {
        prevFocusedElement.current = document.activeElement;
      }
      if (typeof ref === "object" && (ref == null ? void 0 : ref.current) && autoFocus) {
        ref.current.focus();
      }
    } else if (visibleChanged && prevFocusedElement.current) {
      prevFocusedElement.current.focus();
    }
  }, [visible, visibleChanged, ref, autoFocus]);
  function onClickCloseButton(event) {
    event.stopPropagation();
    onClose();
  }
  function onSubmitForm(e) {
    e.preventDefault();
    if (!submitDisabled && onSubmit) {
      onSubmit();
    }
  }
  function onClickCancel() {
    if (onCancel) {
      onCancel();
    } else {
      onClose();
    }
  }
  const modalContent = /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ModalOverlay, { ref: overlayRef }),
    /* @__PURE__ */ jsx(
      ModalContainer,
      {
        "aria-modal": true,
        "aria-hidden": true,
        tabIndex: -1,
        role: "dialog",
        ref: modalContainerRef,
        children: /* @__PURE__ */ jsxs(ModalContent, { width, ghost, children: [
          !firstFocusRef && /* @__PURE__ */ jsx(DefaultFocusTarget, { ref: defaultFirstFocusRefCb }),
          !(nonDismissable || ghost) && /* @__PURE__ */ jsx(CloseButton, { onClick: onClickCloseButton, type: "button", children: /* @__PURE__ */ jsx(Icon, { name: "Close", width: 9 }) }),
          /* @__PURE__ */ jsxs(ModalContentInner, { ghost, children: [
            progressBar ? /* @__PURE__ */ jsx("div", { css: { marginBottom: "20px" }, children: /* @__PURE__ */ jsx(
              ProgressBar,
              {
                progressPercentage: progressBar.progressPercentage,
                isSm: progressBar.isSm
              }
            ) }) : null,
            title ? /* @__PURE__ */ jsx("h4", { children: title }) : null,
            formattedDescription ? /* @__PURE__ */ jsx(Description, { children: formattedDescription }) : null,
            /* @__PURE__ */ jsx("div", { children }),
            onSubmit || onCancel ? /* @__PURE__ */ jsxs(ModalButtonRow, { children: [
              !isSm && !cancelHidden && /* @__PURE__ */ jsx(
                Button,
                {
                  disabled: cancelDisabled,
                  onClick: onClickCancel,
                  text: cancelText
                }
              ),
              onSubmit && /* @__PURE__ */ jsx(
                Button,
                {
                  disabled: submitDisabled,
                  primary: true,
                  text: submitText != null ? submitText : "Continue",
                  loading: submitLoading,
                  type: "submit"
                }
              ),
              isSm && !cancelHidden && /* @__PURE__ */ jsx(Button, { onClick: onClose, text: cancelText })
            ] }) : null
          ] })
        ] })
      }
    )
  ] });
  return visible && nodeReady && nodeRef.current ? ReactDOM.createPortal(
    onSubmit ? /* @__PURE__ */ jsx("form", { onSubmit: onSubmitForm, children: modalContent }) : modalContent,
    nodeRef.current
  ) : null;
}
var DefaultFocusTarget = styled(UnstyledButton)`
  position: absolute;
  top: -30px;
  width: 0;
  height: 0;
`;
var ModalOverlay = styled.div`
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: ${z.modalOverlay};
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(2px);
`;
var ModalContainer = styled.div`
  pointer-events: none;
  position: fixed;
  top: 0;
  left: 0;
  z-index: ${z.modalContainer};
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  outline: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: ${({ theme }) => theme.text};
  padding-top: ${standardContentInset.smPx}px;
`;
var contentTopMarginPx = 24;
var Description = styled.div`
  color: ${({ theme }) => theme.mcNeutral};
  margin-top: 4px;
  & + * {
    margin-top: ${contentTopMarginPx}px;
  }
`;
var ModalButtonRow = styled.div`
  margin-top: 32px;
  ${bp.minSm(`display: flex;`)}
  gap: 10px;

  button {
    width: 50%;
    ${bp.sm(`
      width: 100%;
    `)}
  }

  button:last-of-type {
    ${bp.sm(`
      margin-top: 16px;
    `)}
  }
`;
var ModalContent = styled.div`
  ${overflowAutoWithoutScrollbars}
  ${standardContentInset.smCSS}
  ${standardBorderRadius(16)}
  ${(props) => props.ghost ? "" : overlaySurface}
  pointer-events: auto;
  transition: width 0.25s ease-in;
  width: ${(props) => props.width}px;
  max-width: 100%;
  max-height: 100%;
  position: absolute;
  ${(props) => props.ghost ? "" : "padding: 16px 16px 40px;"}

  h4 {
    margin: 0;
    font-weight: 800;
    font-size: ${pxToRems(21)};
    & + *:not(${select(Description)}) {
      margin-top: ${contentTopMarginPx}px;
    }
  }
`;
var CloseButton = styled(UnstyledButton)`
  ${standardFocusOutline}
  width: 24px;
  height: 24px;
`;
var ModalContentInner = styled.div`
  ${(props) => props.ghost ? "" : "padding: 32px 24px 0;"}
  ${(props) => props.ghost ? "" : `${bp.sm(`
    padding-left: 10px;
    padding-right: 10px;
  `)}`}
`;

export {
  Modal
};
