"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/Modal/index.tsx
var Modal_exports = {};
__export(Modal_exports, {
  Modal: () => Modal2,
  useModal: () => useModal
});
module.exports = __toCommonJS(Modal_exports);

// src/components/Modal/Content.tsx
var import_jsx_runtime = require("react/jsx-runtime");
var Content = ({ ref, children, ...otherProps }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { ref, ...otherProps, className: "mobius-modal__content", children });
Content.displayName = "Content";

// src/components/Modal/Header.tsx
var import_react4 = require("react");
var import_icons3 = require("@simplybusiness/icons");

// src/components/Button/Button.tsx
var import_dedupe2 = __toESM(require("classnames/dedupe"));

// src/components/Button/Loading.tsx
var import_icons = require("@simplybusiness/icons");

// src/components/Icon/Icon.tsx
var import_dedupe = __toESM(require("classnames/dedupe"));
var import_Icon = require("@simplybusiness/mobius/src/components/Icon/Icon.css");
var import_jsx_runtime2 = require("react/jsx-runtime");
var ICON_PREFIX = "mobius-icon";
var capitaliseFirstLetter = (str) => str.charAt(0).toUpperCase() + str.slice(1);
function Icon({
  ref,
  icon,
  className,
  size = "xs",
  color,
  fixedWidth,
  spin,
  spinReverse,
  title,
  ...otherProps
}) {
  if (!icon) {
    throw new Error("Must specify icon object");
  }
  const classes = (0, import_dedupe.default)(
    "mobius",
    "mobius-icon",
    `svg-inline--${ICON_PREFIX}`,
    `--size-${size}`,
    className,
    {
      [`${ICON_PREFIX}-fw`]: fixedWidth,
      [`${ICON_PREFIX}-spin`]: spin || spinReverse,
      [`${ICON_PREFIX}-spin-reverse`]: spinReverse
    }
  );
  const { iconName, width, height, svgPathData } = icon;
  const formattedIconName = iconName.split("-").join(" ");
  const defaultTitle = `${capitaliseFirstLetter(formattedIconName)} icon`;
  const titleText = title || defaultTitle;
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
    "svg",
    {
      ref,
      focusable: "false",
      "data-icon": iconName,
      className: classes,
      role: "img",
      xmlns: "http://www.w3.org/2000/svg",
      viewBox: `0 0 ${width} ${height}`,
      style: { color },
      ...otherProps,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("title", { children: titleText }),
        /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { fill: "currentColor", d: svgPathData })
      ]
    }
  );
}

// src/components/VisuallyHidden/VisuallyHidden.tsx
var import_jsx_runtime3 = require("react/jsx-runtime");
function VisuallyHidden(props) {
  const {
    className,
    children,
    elementType: Component = "div",
    ...otherProps
  } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
    Component,
    {
      className,
      style: {
        border: 0,
        clip: "rect(0 0 0 0)",
        clipPath: "inset(50%)",
        height: "1px",
        margin: "-1px",
        overflow: "hidden",
        padding: 0,
        position: "absolute",
        width: "1px",
        whiteSpace: "nowrap"
      },
      ...otherProps,
      children
    }
  );
}

// src/components/Button/Loading.tsx
var import_jsx_runtime4 = require("react/jsx-runtime");
var Loading = (props) => {
  const { children } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "mobius-button__icon-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Icon, { icon: import_icons.loading, spin: true, size: "md" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(VisuallyHidden, { className: "mobius-button__loading-text", children: "Loading" }),
    children
  ] });
};

// src/hooks/useButton/useButton.tsx
var import_react = require("react");
function useButton({
  elementType = "button",
  type = "button",
  isDisabled = false,
  href,
  target,
  rel,
  role,
  name,
  value,
  onClick,
  onPress
}) {
  const realOnClick = (0, import_react.useCallback)(
    (event) => {
      if (isDisabled) {
        return;
      }
      onClick?.(event);
      onPress?.(event);
    },
    [isDisabled, onClick, onPress]
  );
  function getRole() {
    if (role) {
      return role;
    }
    if (elementType === "a") {
      return void 0;
    }
    return "button";
  }
  const extraProps = elementType === "button" ? { type } : {
    role: getRole()
  };
  return {
    buttonProps: {
      href: elementType === "a" ? href : void 0,
      target: elementType === "a" ? target : void 0,
      rel: elementType === "a" ? rel : void 0,
      tabIndex: isDisabled ? -1 : 0,
      disabled: isDisabled || void 0,
      "aria-disabled": isDisabled || void 0,
      name: elementType === "input" || elementType === "button" ? name : void 0,
      value: elementType === "input" || elementType === "button" ? value : void 0,
      ...extraProps,
      onClick: realOnClick
    }
  };
}

// src/components/Button/Success.tsx
var import_icons2 = require("@simplybusiness/icons");
var import_jsx_runtime5 = require("react/jsx-runtime");
var Success = () => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_jsx_runtime5.Fragment, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "mobius-button__icon-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Icon, { icon: import_icons2.tick, size: "md" }) }),
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(VisuallyHidden, { className: "mobius-button__success-text", children: "Success" })
] });

// src/components/Button/Button.tsx
var import_Button = require("@simplybusiness/mobius/src/components/Button/Button.css");
var import_jsx_runtime6 = require("react/jsx-runtime");
var Button = ({ ref, ...props }) => {
  const {
    children,
    elementType: Component = "button",
    isDisabled,
    isLoading,
    isSuccess,
    variant = "primary",
    size = "md",
    onPress,
    onClick,
    ...otherProps
  } = props;
  const { buttonProps } = useButton(props);
  otherProps.className = (0, import_dedupe2.default)(
    "mobius",
    "mobius-button",
    `--variant-${variant}`,
    `--size-${size}`,
    {
      "--is-disabled": isDisabled,
      "--is-loading": isLoading,
      "--is-success": isSuccess && !isLoading
    },
    otherProps.className
  );
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Component, { ref, ...buttonProps, ...otherProps, children: [
    isLoading ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Loading, { children }) : children,
    isSuccess && !isLoading && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Success, {})
  ] });
};
Button.displayName = "Button";

// src/components/Modal/useModal.ts
var import_react3 = require("react");

// src/components/Modal/ModalContext.tsx
var import_react2 = require("react");
var ModalContext = (0, import_react2.createContext)({
  onClose: () => {
  },
  closeLabel: void 0,
  titleId: void 0,
  setTitleId: () => {
  }
});

// src/components/Modal/useModal.ts
var useModal = () => {
  const { onClose, closeLabel, titleId, setTitleId } = (0, import_react3.useContext)(ModalContext);
  return { onClose, closeLabel, titleId, setTitleId };
};

// src/components/Modal/Header.tsx
var import_jsx_runtime7 = require("react/jsx-runtime");
var Header = ({ ref, children, ...otherProps }) => {
  const { onClose, closeLabel, setTitleId } = useModal();
  const titleId = (0, import_react4.useId)();
  (0, import_react4.useEffect)(() => {
    setTitleId(titleId);
  }, [titleId, setTitleId]);
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
    "header",
    {
      ref,
      ...otherProps,
      className: "mobius-modal__header",
      id: titleId,
      children: [
        children,
        /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
          Button,
          {
            "aria-label": "Close",
            variant: "basic",
            onPress: onClose,
            className: "mobius-modal__close",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Icon, { icon: import_icons3.cross }),
              " ",
              closeLabel
            ]
          }
        )
      ]
    }
  );
};
Header.displayName = "Header";

// src/components/Modal/Modal.tsx
var import_dedupe3 = __toESM(require("classnames/dedupe"));
var import_react7 = require("react");

// src/hooks/useDialog/useDialog.ts
var import_react6 = require("react");

// src/utils/mergeRefs.ts
function mergeRefs(refs) {
  return (value) => {
    refs.forEach((ref) => {
      if (typeof ref === "function") {
        ref(value);
      } else if (ref != null) {
        ref.current = value;
      }
    });
  };
}

// src/utils/polyfill-tests.ts
var supportsDialog = () => typeof HTMLDialogElement === "function";

// src/hooks/useDialog/useDialog.ts
var import_mobius_hooks = require("@simplybusiness/mobius-hooks");

// src/hooks/useDialogPolyfill/useDialogPolyfill.ts
var import_react5 = require("react");
var useDialogPolyfill = () => {
  const [hasDialogSupport, setHasDialogSupport] = (0, import_react5.useState)(false);
  const hasAlreadyLoaded = (0, import_react5.useRef)(false);
  (0, import_react5.useEffect)(() => {
    setHasDialogSupport(supportsDialog());
  }, []);
  const polyfillDialog = async (ref) => {
    if (!hasAlreadyLoaded.current && !hasDialogSupport && typeof window !== "undefined" && ref.current !== null) {
      const { default: dialogPolyfill } = await import("dialog-polyfill");
      hasAlreadyLoaded.current = true;
      try {
        if (ref.current) {
          dialogPolyfill.registerDialog(ref.current);
        }
      } catch (error) {
        console.error("Failed to load dialog-polyfill", error);
      }
    }
  };
  return {
    polyfillDialog
  };
};

// src/hooks/useDialog/useDialog.ts
var TRANSITION_CLASS_NAME = "--transition";
var FALLBACK_TRANSITION_DURATION = 0;
var useDialog = (props) => {
  const { ref, isOpen, transition, onOpen, onClose } = props;
  const [hasDialogSupport, setHasDialogSupport] = (0, import_react6.useState)(false);
  const shouldTransition = hasDialogSupport && transition.isEnabled;
  const { polyfillDialog } = useDialogPolyfill();
  (0, import_react6.useEffect)(() => {
    setHasDialogSupport(supportsDialog());
  }, []);
  const TRANSITION_DURATION_IN_MS = ref.current && Number(
    getComputedStyle(ref.current).getPropertyValue(transition.CSSVariable).replace("ms", "")
  ) || FALLBACK_TRANSITION_DURATION;
  (0, import_mobius_hooks.useBodyScrollLock)({ enabled: isOpen });
  const open = (0, import_react6.useCallback)(() => {
    ref.current?.showModal();
    onOpen?.();
  }, [onOpen, ref]);
  const close = (0, import_react6.useCallback)(() => {
    ref.current?.close();
    onClose?.();
  }, [onClose, ref]);
  const handleClose = (0, import_react6.useCallback)(
    (event) => {
      if (event) {
        event.preventDefault();
        event.stopPropagation();
      }
      if (shouldTransition) {
        ref.current?.classList.remove(TRANSITION_CLASS_NAME);
        setTimeout(() => close(), TRANSITION_DURATION_IN_MS);
      } else {
        close();
      }
    },
    [TRANSITION_DURATION_IN_MS, close, ref, shouldTransition]
  );
  (0, import_react6.useEffect)(() => {
    async function toggleDialog() {
      if (isOpen && !ref.current?.open) {
        await polyfillDialog(ref);
        open();
        setTimeout(() => {
          ref.current?.classList.add(TRANSITION_CLASS_NAME);
        }, 0);
      } else if (!isOpen && ref.current?.open) {
        handleClose();
      }
    }
    void toggleDialog();
  }, [handleClose, isOpen, open, ref, polyfillDialog]);
  return {
    open,
    close: handleClose
  };
};

// src/components/Modal/Modal.tsx
var import_Modal = require("@simplybusiness/mobius/src/components/Modal/Modal.css");
var import_jsx_runtime8 = require("react/jsx-runtime");
var TRANSITION_CSS_VARIABLE = "--modal-transition-duration";
var Modal = ({ ref, ...props }) => {
  const {
    isOpen,
    onClose,
    preventEscapeKey = false,
    onOpen,
    children,
    className,
    closeLabel,
    isFullScreen,
    animation,
    ...rest
  } = props;
  const [shouldTransition, setShouldTransition] = (0, import_react7.useState)(false);
  (0, import_react7.useEffect)(() => {
    setShouldTransition(supportsDialog());
  }, []);
  const dialogRef = (0, import_react7.useRef)(null);
  const { close } = useDialog({
    ref: dialogRef,
    isOpen,
    onOpen,
    onClose,
    transition: {
      isEnabled: !!animation,
      CSSVariable: TRANSITION_CSS_VARIABLE
    }
  });
  const modalClasses = (0, import_dedupe3.default)(
    "mobius",
    "mobius-modal",
    {
      "--no-dialog-support": !shouldTransition,
      // This class is used to correctly position modal in x/y middle on iOS <= 15.2
      "--should-transition": shouldTransition && animation,
      "--slide-up": animation === "slideUp",
      "--fade": animation === "fade",
      "--is-fullscreen": isFullScreen
    },
    className
  );
  const [titleId, setTitleId] = (0, import_react7.useState)(void 0);
  const handleSetTitleId = (0, import_react7.useCallback)((id) => {
    setTitleId(id);
  }, []);
  const contextValue = (0, import_react7.useMemo)(
    () => ({
      onClose: close,
      closeLabel,
      titleId,
      setTitleId: handleSetTitleId
    }),
    [close, closeLabel, titleId, handleSetTitleId]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
    "dialog",
    {
      ref: mergeRefs([dialogRef, ref]),
      onCancel: close,
      onKeyDown: (event) => {
        if (preventEscapeKey && event.key === "Escape") {
          event.preventDefault();
        }
      },
      className: modalClasses,
      "aria-labelledby": titleId,
      ...rest,
      children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(ModalContext.Provider, { value: contextValue, children })
    }
  );
};
Modal.displayName = "Modal";

// src/components/Modal/index.tsx
var Modal2 = Object.assign(Modal, {
  Header,
  Content
});
Modal2.displayName = "Modal";
//# sourceMappingURL=index.js.map
