import R from "./index-extends.js";
import * as r from "react";
import { ModalManager as S, ariaHidden as $ } from "./index-ModalManager.js";
import A from "./index-useForkRef.js";
import w from "./index-useEventCallback2.js";
import L from "./index-ownerDocument2.js";
import H from "./index-createChainedFunction.js";
import N from "./index-extractEventHandlers.js";
function j(o) {
  return typeof o == "function" ? o() : o;
}
function q(o) {
  return o ? o.props.hasOwnProperty("in") : !1;
}
const z = new S();
function ee(o) {
  const {
    container: D,
    disableEscapeKeyDown: M = !1,
    disableScrollLock: b = !1,
    // @ts-ignore internal logic - Base UI supports the manager as a prop too
    manager: s = z,
    closeAfterTransition: p = !1,
    onTransitionEnter: k,
    onTransitionExited: C,
    children: i,
    onClose: d,
    open: l,
    rootRef: K
  } = o, m = r.useRef({}), E = r.useRef(null), a = r.useRef(null), T = A(a, K), [v, x] = r.useState(!l), g = q(i);
  let f = !0;
  (o["aria-hidden"] === "false" || o["aria-hidden"] === !1) && (f = !1);
  const B = () => L(E.current), u = () => (m.current.modalRef = a.current, m.current.mount = E.current, m.current), y = () => {
    s.mount(u(), {
      disableScrollLock: b
    }), a.current && (a.current.scrollTop = 0);
  }, P = w(() => {
    const n = j(D) || B().body;
    s.add(u(), n), a.current && y();
  }), h = r.useCallback(() => s.isTopModal(u()), [s]), _ = w((n) => {
    E.current = n, n && (l && h() ? y() : a.current && $(a.current, f));
  }), c = r.useCallback(() => {
    s.remove(u(), f);
  }, [f, s]);
  r.useEffect(() => () => {
    c();
  }, [c]), r.useEffect(() => {
    l ? P() : (!g || !p) && c();
  }, [l, c, g, p, P]);
  const F = (n) => (e) => {
    var t;
    (t = n.onKeyDown) == null || t.call(n, e), !(e.key !== "Escape" || e.which === 229 || // Wait until IME is settled.
    !h()) && (M || (e.stopPropagation(), d && d(e, "escapeKeyDown")));
  }, O = (n) => (e) => {
    var t;
    (t = n.onClick) == null || t.call(n, e), e.target === e.currentTarget && d && d(e, "backdropClick");
  };
  return {
    getRootProps: (n = {}) => {
      const e = N(o);
      delete e.onTransitionEnter, delete e.onTransitionExited;
      const t = R({}, e, n);
      return R({
        role: "presentation"
      }, t, {
        onKeyDown: F(t),
        ref: T
      });
    },
    getBackdropProps: (n = {}) => {
      const e = n;
      return R({
        "aria-hidden": !0
      }, e, {
        onClick: O(e),
        open: l
      });
    },
    getTransitionProps: () => {
      const n = () => {
        x(!1), k && k();
      }, e = () => {
        x(!0), C && C(), p && c();
      };
      return {
        onEnter: H(n, i == null ? void 0 : i.props.onEnter),
        onExited: H(e, i == null ? void 0 : i.props.onExited)
      };
    },
    rootRef: T,
    portalRef: _,
    isTopModal: h,
    exited: v,
    hasTransition: g
  };
}
export {
  ee as default
};
