"use client";
import {
  useSafeLayoutEffect
} from "./KPHZR4MB.js";

// src/dialog/utils/use-nested-dialogs.tsx
import { chain } from "@ariakit/core/utils/misc";
import { sync } from "@ariakit/core/utils/store";
import {
  createContext,
  useCallback,
  useContext,
  useMemo,
  useState
} from "react";
import { jsx } from "react/jsx-runtime";
var NestedDialogsContext = createContext({});
function useNestedDialogs(store) {
  const context = useContext(NestedDialogsContext);
  const [dialogs, setDialogs] = useState([]);
  const add = useCallback(
    (dialog) => {
      var _a;
      setDialogs((dialogs2) => [...dialogs2, dialog]);
      return chain((_a = context.add) == null ? void 0 : _a.call(context, dialog), () => {
        setDialogs((dialogs2) => dialogs2.filter((d) => d !== dialog));
      });
    },
    [context]
  );
  useSafeLayoutEffect(() => {
    return sync(store, ["open", "contentElement"], (state) => {
      var _a;
      if (!state.open) return;
      if (!state.contentElement) return;
      return (_a = context.add) == null ? void 0 : _a.call(context, store);
    });
  }, [store, context]);
  const providerValue = useMemo(() => ({ store, add }), [store, add]);
  const wrapElement = useCallback(
    (element) => /* @__PURE__ */ jsx(NestedDialogsContext.Provider, { value: providerValue, children: element }),
    [providerValue]
  );
  return { wrapElement, nestedDialogs: dialogs };
}

export {
  useNestedDialogs
};
