import { isElement } from "../../../../../@floating-ui/utils/dist/floating-ui.utils.dom.js";
import { useId } from "../../../../utils/esm/useId.js";
import { useRefWithInit } from "../../../../utils/esm/useRefWithInit.js";
import { useIsoLayoutEffect } from "../../../../utils/esm/useIsoLayoutEffect.js";
import { useFloatingParentNodeId } from "../components/FloatingTree.js";
import { FloatingRootStore } from "../components/FloatingRootStore.js";
import { PopupTriggerMap } from "../../utils/popups/popupTriggerMap.js";
function useFloatingRootContext(options) {
  const {
    open = false,
    onOpenChange,
    elements = {}
  } = options;
  const floatingId = useId();
  const nested = useFloatingParentNodeId() != null;
  if (process.env.NODE_ENV !== "production") {
    const optionDomReference = elements.reference;
    if (optionDomReference && !isElement(optionDomReference)) {
      console.error("Cannot pass a virtual element to the `elements.reference` option,", "as it must be a real DOM element. Use `context.setPositionReference()`", "instead.");
    }
  }
  const store = useRefWithInit(() => new FloatingRootStore({
    open,
    onOpenChange,
    referenceElement: elements.reference ?? null,
    floatingElement: elements.floating ?? null,
    triggerElements: elements.triggers ?? new PopupTriggerMap(),
    floatingId,
    nested,
    noEmit: options.noEmit || false
  })).current;
  useIsoLayoutEffect(() => {
    const valuesToSync = {
      open,
      floatingId
    };
    if (elements.reference !== void 0) {
      valuesToSync.referenceElement = elements.reference;
      valuesToSync.domReferenceElement = isElement(elements.reference) ? elements.reference : null;
    }
    if (elements.floating !== void 0) {
      valuesToSync.floatingElement = elements.floating;
    }
    store.update(valuesToSync);
  }, [open, floatingId, elements.reference, elements.floating, store]);
  store.context.onOpenChange = onOpenChange;
  store.context.nested = nested;
  store.context.noEmit = options.noEmit || false;
  return store;
}
export {
  useFloatingRootContext
};
//# sourceMappingURL=useFloatingRootContext.js.map
