import * as a from "react";
import { useRefWithInit as T } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useRefWithInit.js";
import { useStableCallback as l } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useStableCallback.js";
import { useIsoLayoutEffect as f } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useIsoLayoutEffect.js";
import { CompositeListContext as D } from "./CompositeListContext.js";
import { jsx as L } from "react/jsx-runtime";
function k(h) {
  const {
    children: N,
    elementsRef: t,
    labelsRef: o,
    onMapChange: _
  } = h, C = l(_), O = a.useRef(0), d = T(R).current, i = T(P).current, [p, M] = a.useState(0), c = a.useRef(p), E = l((e, u) => {
    i.set(e, u ?? null), c.current += 1, M(c.current);
  }), I = l((e) => {
    i.delete(e), c.current += 1, M(c.current);
  }), r = a.useMemo(() => {
    const e = /* @__PURE__ */ new Map();
    return Array.from(i.keys()).filter((n) => n.isConnected).sort(S).forEach((n, m) => {
      const s = i.get(n) ?? {};
      e.set(n, {
        ...s,
        index: m
      });
    }), e;
  }, [i, p]);
  f(() => {
    if (typeof MutationObserver != "function" || r.size === 0)
      return;
    const e = new MutationObserver((u) => {
      const n = /* @__PURE__ */ new Set(), m = (s) => n.has(s) ? n.delete(s) : n.add(s);
      u.forEach((s) => {
        s.removedNodes.forEach(m), s.addedNodes.forEach(m);
      }), n.size === 0 && (c.current += 1, M(c.current));
    });
    return r.forEach((u, n) => {
      n.parentElement && e.observe(n.parentElement, {
        childList: !0
      });
    }), () => {
      e.disconnect();
    };
  }, [r]), f(() => {
    c.current === p && (t.current.length !== r.size && (t.current.length = r.size), o && o.current.length !== r.size && (o.current.length = r.size), O.current = r.size), C(r);
  }, [C, r, t, o, p]), f(() => () => {
    t.current = [];
  }, [t]), f(() => () => {
    o && (o.current = []);
  }, [o]);
  const g = l((e) => (d.add(e), () => {
    d.delete(e);
  }));
  f(() => {
    d.forEach((e) => e(r));
  }, [d, r]);
  const b = a.useMemo(() => ({
    register: E,
    unregister: I,
    subscribeMapChange: g,
    elementsRef: t,
    labelsRef: o,
    nextIndexRef: O
  }), [E, I, g, t, o, O]);
  return /* @__PURE__ */ L(D.Provider, {
    value: b,
    children: N
  });
}
function P() {
  return /* @__PURE__ */ new Map();
}
function R() {
  return /* @__PURE__ */ new Set();
}
function S(h, N) {
  const t = h.compareDocumentPosition(N);
  return t & Node.DOCUMENT_POSITION_FOLLOWING || t & Node.DOCUMENT_POSITION_CONTAINED_BY ? -1 : t & Node.DOCUMENT_POSITION_PRECEDING || t & Node.DOCUMENT_POSITION_CONTAINS ? 1 : 0;
}
export {
  k as CompositeList
};
