import { jsx as k, Fragment as Y } from "react/jsx-runtime";
import { useMemo as F, useRef as p, useState as v, useContext as G } from "react";
import { LayoutGroupContext as O } from "../../context/LayoutGroupContext.es.js";
import { useConstant as R } from "../../utils/use-constant.es.js";
import { useIsomorphicLayoutEffect as V } from "../../utils/use-isomorphic-effect.es.js";
import { PresenceChild as X } from "./PresenceChild.es.js";
import { usePresence as _ } from "./use-presence.es.js";
import { onlyElements as A, getChildKey as c } from "./utils.es.js";
const W = ({ children: C, custom: L, initial: b = !0, onExitComplete: y, presenceAffectsLayout: j = !0, mode: u = "sync", propagate: l = !1, anchorX: D = "left", anchorY: I = "top", root: K }) => {
  const [x, f] = _(l), n = F(() => A(C), [C]), o = l && !x ? [] : n.map(c), g = p(!0), P = p(n), i = R(() => /* @__PURE__ */ new Map()), d = p(/* @__PURE__ */ new Set()), [M, N] = v(n), [r, w] = v(n);
  V(() => {
    g.current = !1, P.current = n;
    for (let t = 0; t < r.length; t++) {
      const e = c(r[t]);
      o.includes(e) ? (i.delete(e), d.current.delete(e)) : i.get(e) !== !0 && i.set(e, !1);
    }
  }, [r, o.length, o.join("-")]);
  const m = [];
  if (n !== M) {
    let t = [...n];
    for (let e = 0; e < r.length; e++) {
      const s = r[e], h = c(s);
      o.includes(h) || (t.splice(e, 0, s), m.push(s));
    }
    return u === "wait" && m.length && (t = m), w(A(t)), N(n), null;
  }
  process.env.NODE_ENV !== "production" && u === "wait" && r.length > 1 && console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);
  const { forceRender: a } = G(O);
  return k(Y, { children: r.map((t) => {
    const e = c(t), s = l && !x ? !1 : n === r || o.includes(e), h = () => {
      if (d.current.has(e))
        return;
      if (i.has(e))
        d.current.add(e), i.set(e, !0);
      else
        return;
      let E = !0;
      i.forEach((S) => {
        S || (E = !1);
      }), E && (a == null || a(), w(P.current), l && (f == null || f()), y && y());
    };
    return k(X, { isPresent: s, initial: !g.current || b ? void 0 : !1, custom: L, presenceAffectsLayout: j, mode: u, root: K, onExitComplete: s ? void 0 : h, anchorX: D, anchorY: I, children: t }, e);
  }) });
};
export {
  W as AnimatePresence
};
//# sourceMappingURL=index.es.js.map
