import * as i from "react";
import * as g from "react-dom";
import { useComposedRefs as O } from "../../../../../@radix-ui_react-compose-refs@1.1.0_@types_react@18.3.3_react@18.3.0-canary-3d9b20132-20240124/node_modules/@radix-ui/react-compose-refs/dist/index.js";
import { useLayoutEffect as A } from "../../../../../@radix-ui_react-use-layout-effect@1.1.0_@types_react@18.3.3_react@18.3.0-canary-3d9b20132-20240124/node_modules/@radix-ui/react-use-layout-effect/dist/index.js";
function E(n, e) {
  return i.useReducer((t, o) => e[t][o] ?? t, n);
}
var M = (n) => {
  const { present: e, children: t } = n, o = R(e), a = typeof t == "function" ? t({ present: o.isPresent }) : i.Children.only(t), c = O(o.ref, y(a));
  return typeof t == "function" || o.isPresent ? i.cloneElement(a, { ref: c }) : null;
};
M.displayName = "Presence";
function R(n) {
  const [e, t] = i.useState(), o = i.useRef({}), a = i.useRef(n), c = i.useRef("none"), l = n ? "mounted" : "unmounted", [N, s] = E(l, {
    mounted: {
      UNMOUNT: "unmounted",
      ANIMATION_OUT: "unmountSuspended"
    },
    unmountSuspended: {
      MOUNT: "mounted",
      ANIMATION_END: "unmounted"
    },
    unmounted: {
      MOUNT: "mounted"
    }
  });
  return i.useEffect(() => {
    const r = d(o.current);
    c.current = N === "mounted" ? r : "none";
  }, [N]), A(() => {
    const r = o.current, u = a.current;
    if (u !== n) {
      const p = c.current, f = d(r);
      n ? s("MOUNT") : f === "none" || r?.display === "none" ? s("UNMOUNT") : s(u && p !== f ? "ANIMATION_OUT" : "UNMOUNT"), a.current = n;
    }
  }, [n, s]), A(() => {
    if (e) {
      const r = (m) => {
        const f = d(o.current).includes(m.animationName);
        m.target === e && f && g.flushSync(() => s("ANIMATION_END"));
      }, u = (m) => {
        m.target === e && (c.current = d(o.current));
      };
      return e.addEventListener("animationstart", u), e.addEventListener("animationcancel", r), e.addEventListener("animationend", r), () => {
        e.removeEventListener("animationstart", u), e.removeEventListener("animationcancel", r), e.removeEventListener("animationend", r);
      };
    } else
      s("ANIMATION_END");
  }, [e, s]), {
    isPresent: ["mounted", "unmountSuspended"].includes(N),
    ref: i.useCallback((r) => {
      r && (o.current = getComputedStyle(r)), t(r);
    }, [])
  };
}
function d(n) {
  return n?.animationName || "none";
}
function y(n) {
  let e = Object.getOwnPropertyDescriptor(n.props, "ref")?.get, t = e && "isReactWarning" in e && e.isReactWarning;
  return t ? n.ref : (e = Object.getOwnPropertyDescriptor(n, "ref")?.get, t = e && "isReactWarning" in e && e.isReactWarning, t ? n.props.ref : n.props.ref || n.ref);
}
export {
  M as Presence
};
//# sourceMappingURL=index.js.map
