"use client";
import * as React from "react";
import { getWindow, isHTMLElement } from "../../../../../@floating-ui/utils/dist/floating-ui.utils.dom.js";
import { useTimeout } from "../../../../utils/esm/useTimeout.js";
import { createChangeEventDetails } from "../createBaseUIEventDetails.js";
import { activeElement, contains, getDocument } from "../../floating-ui-react/utils/element.js";
import { triggerFocus } from "../reason-parts.js";
function useFocusWithDelay(store, props = {}) {
  const domReference = store.useState("domReferenceElement");
  const dataRef = store.context.dataRef;
  const {
    delay
  } = props;
  const timeout = useTimeout();
  const blockFocusRef = React.useRef(false);
  React.useEffect(() => {
    const win = getWindow(domReference);
    function handleBlur() {
      const currentDomReference = store.select("domReferenceElement");
      if (!store.select("open") && isHTMLElement(currentDomReference) && currentDomReference === activeElement(getDocument(currentDomReference))) {
        blockFocusRef.current = true;
      }
    }
    win.addEventListener("blur", handleBlur);
    return () => {
      win.removeEventListener("blur", handleBlur);
    };
  }, [store, domReference]);
  const reference = React.useMemo(() => ({
    onFocus(event) {
      const {
        nativeEvent
      } = event;
      const delayValue = typeof delay === "function" ? delay() : delay;
      timeout.start(delayValue ?? 0, () => {
        store.setOpen(true, createChangeEventDetails(triggerFocus, nativeEvent));
      });
    },
    onBlur(event) {
      blockFocusRef.current = false;
      const {
        relatedTarget,
        nativeEvent
      } = event;
      timeout.start(0, () => {
        const currentDomReference = store.select("domReferenceElement");
        const activeEl = activeElement(currentDomReference ? currentDomReference.ownerDocument : document);
        if (!relatedTarget && activeEl === currentDomReference) {
          return;
        }
        if (contains(dataRef.current.floatingContext?.refs.floating.current, activeEl) || contains(currentDomReference, activeEl)) {
          return;
        }
        store.setOpen(false, createChangeEventDetails(triggerFocus, nativeEvent));
      });
    }
  }), [delay, store, dataRef, timeout]);
  return React.useMemo(() => ({
    reference
  }), [reference]);
}
export {
  useFocusWithDelay
};
//# sourceMappingURL=useFocusWithDelay.js.map
