"use client";
'use strict';

var WAGAC6PJ = require('./WAGAC6PJ.cjs');
var _5M6RIVE2 = require('./5M6RIVE2.cjs');
var ZWYATQFU = require('./ZWYATQFU.cjs');
var _6GXEOXGT = require('./6GXEOXGT.cjs');
var HP6HHD56 = require('./HP6HHD56.cjs');
var TOU75OXH = require('./TOU75OXH.cjs');
var BGQ3KQ5M = require('./BGQ3KQ5M.cjs');
var Z5GCVBAY = require('./Z5GCVBAY.cjs');
var _677M2CI3 = require('./677M2CI3.cjs');
var JEWPFJH2 = require('./JEWPFJH2.cjs');
var _3NDVDEB4 = require('./3NDVDEB4.cjs');
var AOUGVQZ3 = require('./AOUGVQZ3.cjs');
var KFH4SEIX = require('./KFH4SEIX.cjs');
var BM6PGYQY = require('./BM6PGYQY.cjs');
var RS7LB2H4 = require('./RS7LB2H4.cjs');
var PFRGBC2K = require('./PFRGBC2K.cjs');
var YV4JVR4I = require('./YV4JVR4I.cjs');
var LMDWO4NN = require('./LMDWO4NN.cjs');
var ABQUS43J = require('./ABQUS43J.cjs');
var _3YLGPPWQ = require('./3YLGPPWQ.cjs');
var DTR5TSDJ = require('../../../../../../@ariakit_core@0.4.15/node_modules/@ariakit/core/esm/__chunks/DTR5TSDJ.cjs');
var events = require('../../../../../../@ariakit_core@0.4.15/node_modules/@ariakit/core/esm/utils/events.cjs');
var focus = require('../../../../../../@ariakit_core@0.4.15/node_modules/@ariakit/core/esm/utils/focus.cjs');
var PBFD2E7P = require('../../../../../../@ariakit_core@0.4.15/node_modules/@ariakit/core/esm/__chunks/PBFD2E7P.cjs');
var QAGXQEUG = require('../../../../../../@ariakit_core@0.4.15/node_modules/@ariakit/core/esm/__chunks/QAGXQEUG.cjs');
var React = require('react');
var jsxRuntime = require('react/jsx-runtime');

var TagName = "div";
var isSafariBrowser = QAGXQEUG.isSafari();
function isAlreadyFocusingAnotherElement(dialog) {
  const activeElement = DTR5TSDJ.getActiveElement();
  if (!activeElement) return false;
  if (dialog && DTR5TSDJ.contains(dialog, activeElement)) return false;
  if (focus.isFocusable(activeElement)) return true;
  return false;
}
function getElementFromProp(prop, focusable = false) {
  if (!prop) return null;
  const element = "current" in prop ? prop.current : prop;
  if (!element) return null;
  if (focusable) return focus.isFocusable(element) ? element : null;
  return element;
}
var useDialog = LMDWO4NN.createHook(function useDialog2(_a) {
  var _b = _a, {
    store: storeProp,
    open: openProp,
    onClose,
    focusable = true,
    modal = true,
    portal = !!modal,
    backdrop = !!modal,
    hideOnEscape = true,
    hideOnInteractOutside = true,
    getPersistentElements,
    preventBodyScroll = !!modal,
    autoFocusOnShow = true,
    autoFocusOnHide = true,
    initialFocus,
    finalFocus,
    unmountOnHide,
    unstable_treeSnapshotKey
  } = _b, props = _3YLGPPWQ.__objRest(_b, [
    "store",
    "open",
    "onClose",
    "focusable",
    "modal",
    "portal",
    "backdrop",
    "hideOnEscape",
    "hideOnInteractOutside",
    "getPersistentElements",
    "preventBodyScroll",
    "autoFocusOnShow",
    "autoFocusOnHide",
    "initialFocus",
    "finalFocus",
    "unmountOnHide",
    "unstable_treeSnapshotKey"
  ]);
  const context = RS7LB2H4.useDialogProviderContext();
  const ref = React.useRef(null);
  const store = BM6PGYQY.useDialogStore({
    store: storeProp || context,
    open: openProp,
    setOpen(open2) {
      if (open2) return;
      const dialog = ref.current;
      if (!dialog) return;
      const event = new Event("close", { bubbles: false, cancelable: true });
      if (onClose) {
        dialog.addEventListener("close", onClose, { once: true });
      }
      dialog.dispatchEvent(event);
      if (!event.defaultPrevented) return;
      store.setOpen(true);
    }
  });
  const { portalRef, domReady } = ABQUS43J.usePortalRef(portal, props.portalRef);
  const preserveTabOrderProp = props.preserveTabOrder;
  const preserveTabOrder = YV4JVR4I.useStoreState(
    store,
    (state) => preserveTabOrderProp && !modal && state.mounted
  );
  const id = ABQUS43J.useId(props.id);
  const open = YV4JVR4I.useStoreState(store, "open");
  const mounted = YV4JVR4I.useStoreState(store, "mounted");
  const contentElement = YV4JVR4I.useStoreState(store, "contentElement");
  const hidden = KFH4SEIX.isHidden(mounted, props.hidden, props.alwaysVisible);
  BGQ3KQ5M.usePreventBodyScroll(contentElement, id, preventBodyScroll && !hidden);
  HP6HHD56.useHideOnInteractOutside(store, hideOnInteractOutside, domReady);
  const { wrapElement, nestedDialogs } = TOU75OXH.useNestedDialogs(store);
  props = ABQUS43J.useWrapElement(props, wrapElement, [wrapElement]);
  ABQUS43J.useSafeLayoutEffect(() => {
    if (!open) return;
    const dialog = ref.current;
    const activeElement = DTR5TSDJ.getActiveElement(dialog, true);
    if (!activeElement) return;
    if (activeElement.tagName === "BODY") return;
    if (dialog && DTR5TSDJ.contains(dialog, activeElement)) return;
    store.setDisclosureElement(activeElement);
  }, [store, open]);
  if (isSafariBrowser) {
    React.useEffect(() => {
      if (!mounted) return;
      const { disclosureElement } = store.getState();
      if (!disclosureElement) return;
      if (!DTR5TSDJ.isButton(disclosureElement)) return;
      const onMouseDown = () => {
        let receivedFocus = false;
        const onFocus = () => {
          receivedFocus = true;
        };
        const options = { capture: true, once: true };
        disclosureElement.addEventListener("focusin", onFocus, options);
        events.queueBeforeEvent(disclosureElement, "mouseup", () => {
          disclosureElement.removeEventListener("focusin", onFocus, true);
          if (receivedFocus) return;
          focus.focusIfNeeded(disclosureElement);
        });
      };
      disclosureElement.addEventListener("mousedown", onMouseDown);
      return () => {
        disclosureElement.removeEventListener("mousedown", onMouseDown);
      };
    }, [store, mounted]);
  }
  React.useEffect(() => {
    if (!mounted) return;
    if (!domReady) return;
    const dialog = ref.current;
    if (!dialog) return;
    const win = DTR5TSDJ.getWindow(dialog);
    const viewport = win.visualViewport || win;
    const setViewportHeight = () => {
      var _a2, _b2;
      const height = (_b2 = (_a2 = win.visualViewport) == null ? void 0 : _a2.height) != null ? _b2 : win.innerHeight;
      dialog.style.setProperty("--dialog-viewport-height", `${height}px`);
    };
    setViewportHeight();
    viewport.addEventListener("resize", setViewportHeight);
    return () => {
      viewport.removeEventListener("resize", setViewportHeight);
    };
  }, [mounted, domReady]);
  React.useEffect(() => {
    if (!modal) return;
    if (!mounted) return;
    if (!domReady) return;
    const dialog = ref.current;
    if (!dialog) return;
    const existingDismiss = dialog.querySelector("[data-dialog-dismiss]");
    if (existingDismiss) return;
    return _6GXEOXGT.prependHiddenDismiss(dialog, store.hide);
  }, [store, modal, mounted, domReady]);
  ABQUS43J.useSafeLayoutEffect(() => {
    if (!_677M2CI3.supportsInert()) return;
    if (open) return;
    if (!mounted) return;
    if (!domReady) return;
    const dialog = ref.current;
    if (!dialog) return;
    return Z5GCVBAY.disableTree(dialog);
  }, [open, mounted, domReady]);
  const canTakeTreeSnapshot = open && domReady;
  ABQUS43J.useSafeLayoutEffect(() => {
    if (!id) return;
    if (!canTakeTreeSnapshot) return;
    const dialog = ref.current;
    return AOUGVQZ3.createWalkTreeSnapshot(id, [dialog]);
  }, [id, canTakeTreeSnapshot, unstable_treeSnapshotKey]);
  const getPersistentElementsProp = ABQUS43J.useEvent(getPersistentElements);
  ABQUS43J.useSafeLayoutEffect(() => {
    if (!id) return;
    if (!canTakeTreeSnapshot) return;
    const { disclosureElement } = store.getState();
    const dialog = ref.current;
    const persistentElements = getPersistentElementsProp() || [];
    const allElements = [
      dialog,
      ...persistentElements,
      ...nestedDialogs.map((dialog2) => dialog2.getState().contentElement)
    ];
    if (modal) {
      return PBFD2E7P.chain(
        _3NDVDEB4.markTreeOutside(id, allElements),
        Z5GCVBAY.disableTreeOutside(id, allElements)
      );
    }
    return _3NDVDEB4.markTreeOutside(id, [disclosureElement, ...allElements]);
  }, [
    id,
    store,
    canTakeTreeSnapshot,
    getPersistentElementsProp,
    nestedDialogs,
    modal,
    unstable_treeSnapshotKey
  ]);
  const mayAutoFocusOnShow = !!autoFocusOnShow;
  const autoFocusOnShowProp = ABQUS43J.useBooleanEvent(autoFocusOnShow);
  const [autoFocusEnabled, setAutoFocusEnabled] = React.useState(false);
  React.useEffect(() => {
    if (!open) return;
    if (!mayAutoFocusOnShow) return;
    if (!domReady) return;
    if (!(contentElement == null ? void 0 : contentElement.isConnected)) return;
    const element = getElementFromProp(initialFocus, true) || // If no initial focus is specified, we try to focus the first element
    // with the autofocus attribute. If it's an Ariakit component, the
    // Focusable component will consume the autoFocus prop and add the
    // data-autofocus attribute to the element instead.
    contentElement.querySelector(
      "[data-autofocus=true],[autofocus]"
    ) || // We have to fallback to the first focusable element otherwise portaled
    // dialogs with preserveTabOrder set to true will not receive focus
    // properly because the elements aren't tabbable until the dialog receives
    // focus.
    focus.getFirstTabbableIn(contentElement, true, portal && preserveTabOrder) || // Finally, we fallback to the dialog element itself.
    contentElement;
    const isElementFocusable = focus.isFocusable(element);
    if (!autoFocusOnShowProp(isElementFocusable ? element : null)) return;
    setAutoFocusEnabled(true);
    queueMicrotask(() => {
      element.focus();
      if (!isSafariBrowser) return;
      if (!isElementFocusable) return;
      element.scrollIntoView({ block: "nearest", inline: "nearest" });
    });
  }, [
    open,
    mayAutoFocusOnShow,
    domReady,
    contentElement,
    initialFocus,
    portal,
    preserveTabOrder,
    autoFocusOnShowProp
  ]);
  const mayAutoFocusOnHide = !!autoFocusOnHide;
  const autoFocusOnHideProp = ABQUS43J.useBooleanEvent(autoFocusOnHide);
  const [hasOpened, setHasOpened] = React.useState(false);
  React.useEffect(() => {
    if (!open) return;
    setHasOpened(true);
    return () => setHasOpened(false);
  }, [open]);
  const focusOnHide = React.useCallback(
    (dialog, retry = true) => {
      const { disclosureElement } = store.getState();
      if (isAlreadyFocusingAnotherElement(dialog)) return;
      let element = getElementFromProp(finalFocus) || disclosureElement;
      if (element == null ? void 0 : element.id) {
        const doc = DTR5TSDJ.getDocument(element);
        const selector = `[aria-activedescendant="${element.id}"]`;
        const composite = doc.querySelector(selector);
        if (composite) {
          element = composite;
        }
      }
      if (element && !focus.isFocusable(element)) {
        const maybeParentDialog = element.closest("[data-dialog]");
        if (maybeParentDialog == null ? void 0 : maybeParentDialog.id) {
          const doc = DTR5TSDJ.getDocument(maybeParentDialog);
          const selector = `[aria-controls~="${maybeParentDialog.id}"]`;
          const control = doc.querySelector(selector);
          if (control) {
            element = control;
          }
        }
      }
      const isElementFocusable = element && focus.isFocusable(element);
      if (!isElementFocusable && retry) {
        requestAnimationFrame(() => focusOnHide(dialog, false));
        return;
      }
      if (!autoFocusOnHideProp(isElementFocusable ? element : null)) return;
      if (!isElementFocusable) return;
      element == null ? void 0 : element.focus({ preventScroll: true });
    },
    [store, finalFocus, autoFocusOnHideProp]
  );
  const focusedOnHideRef = React.useRef(false);
  ABQUS43J.useSafeLayoutEffect(() => {
    if (open) return;
    if (!hasOpened) return;
    if (!mayAutoFocusOnHide) return;
    const dialog = ref.current;
    focusedOnHideRef.current = true;
    focusOnHide(dialog);
  }, [open, hasOpened, domReady, mayAutoFocusOnHide, focusOnHide]);
  React.useEffect(() => {
    if (!hasOpened) return;
    if (!mayAutoFocusOnHide) return;
    const dialog = ref.current;
    return () => {
      if (focusedOnHideRef.current) {
        focusedOnHideRef.current = false;
        return;
      }
      focusOnHide(dialog);
    };
  }, [hasOpened, mayAutoFocusOnHide, focusOnHide]);
  const hideOnEscapeProp = ABQUS43J.useBooleanEvent(hideOnEscape);
  React.useEffect(() => {
    if (!domReady) return;
    if (!mounted) return;
    const onKeyDown = (event) => {
      if (event.key !== "Escape") return;
      if (event.defaultPrevented) return;
      const dialog = ref.current;
      if (!dialog) return;
      if (_3NDVDEB4.isElementMarked(dialog)) return;
      const target = event.target;
      if (!target) return;
      const { disclosureElement } = store.getState();
      const isValidTarget = () => {
        if (target.tagName === "BODY") return true;
        if (DTR5TSDJ.contains(dialog, target)) return true;
        if (!disclosureElement) return true;
        if (DTR5TSDJ.contains(disclosureElement, target)) return true;
        return false;
      };
      if (!isValidTarget()) return;
      if (!hideOnEscapeProp(event)) return;
      store.hide();
    };
    return events.addGlobalEventListener("keydown", onKeyDown, true);
  }, [store, domReady, mounted, hideOnEscapeProp]);
  props = ABQUS43J.useWrapElement(
    props,
    (element) => /* @__PURE__ */ jsxRuntime.jsx(_5M6RIVE2.HeadingLevel, { level: modal ? 1 : void 0, children: element }),
    [modal]
  );
  const hiddenProp = props.hidden;
  const alwaysVisible = props.alwaysVisible;
  props = ABQUS43J.useWrapElement(
    props,
    (element) => {
      if (!backdrop) return element;
      return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
        /* @__PURE__ */ jsxRuntime.jsx(
          JEWPFJH2.DialogBackdrop,
          {
            store,
            backdrop,
            hidden: hiddenProp,
            alwaysVisible
          }
        ),
        element
      ] });
    },
    [store, backdrop, hiddenProp, alwaysVisible]
  );
  const [headingId, setHeadingId] = React.useState();
  const [descriptionId, setDescriptionId] = React.useState();
  props = ABQUS43J.useWrapElement(
    props,
    (element) => /* @__PURE__ */ jsxRuntime.jsx(RS7LB2H4.DialogScopedContextProvider, { value: store, children: /* @__PURE__ */ jsxRuntime.jsx(RS7LB2H4.DialogHeadingContext.Provider, { value: setHeadingId, children: /* @__PURE__ */ jsxRuntime.jsx(RS7LB2H4.DialogDescriptionContext.Provider, { value: setDescriptionId, children: element }) }) }),
    [store]
  );
  props = _3YLGPPWQ.__spreadProps(_3YLGPPWQ.__spreadValues({
    id,
    "data-dialog": "",
    role: "dialog",
    tabIndex: focusable ? -1 : void 0,
    "aria-labelledby": headingId,
    "aria-describedby": descriptionId
  }, props), {
    ref: ABQUS43J.useMergeRefs(ref, props.ref)
  });
  props = ZWYATQFU.useFocusableContainer(_3YLGPPWQ.__spreadProps(_3YLGPPWQ.__spreadValues({}, props), {
    autoFocusOnShow: autoFocusEnabled
  }));
  props = KFH4SEIX.useDisclosureContent(_3YLGPPWQ.__spreadValues({ store }, props));
  props = PFRGBC2K.useFocusable(_3YLGPPWQ.__spreadProps(_3YLGPPWQ.__spreadValues({}, props), { focusable }));
  props = WAGAC6PJ.usePortal(_3YLGPPWQ.__spreadProps(_3YLGPPWQ.__spreadValues({ portal }, props), { portalRef, preserveTabOrder }));
  return props;
});
function createDialogComponent(Component, useProviderContext = RS7LB2H4.useDialogProviderContext) {
  return LMDWO4NN.forwardRef(function DialogComponent(props) {
    const context = useProviderContext();
    const store = props.store || context;
    const mounted = YV4JVR4I.useStoreState(
      store,
      (state) => !props.unmountOnHide || (state == null ? void 0 : state.mounted) || !!props.open
    );
    if (!mounted) return null;
    return /* @__PURE__ */ jsxRuntime.jsx(Component, _3YLGPPWQ.__spreadValues({}, props));
  });
}
createDialogComponent(
  LMDWO4NN.forwardRef(function Dialog2(props) {
    const htmlProps = useDialog(props);
    return LMDWO4NN.createElement(TagName, htmlProps);
  }),
  RS7LB2H4.useDialogProviderContext
);

exports.createDialogComponent = createDialogComponent;
exports.useDialog = useDialog;
//# sourceMappingURL=DVTPF4J4.cjs.map
