"use client";
import {
  FocusTrap
} from "../__chunks/BFOIJXK2.js";
import "../__chunks/2F57YTN4.js";
import {
  createElement,
  createHook,
  forwardRef
} from "../__chunks/GWSL6KNJ.js";
import {
  useMergeRefs,
  useWrapElement
} from "../__chunks/KPHZR4MB.js";
import "../__chunks/YXGXYGQX.js";

// src/focus-trap/focus-trap-region.tsx
import { getAllTabbableIn } from "@ariakit/core/utils/focus";
import { removeUndefinedValues } from "@ariakit/core/utils/misc";
import { useRef } from "react";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var TagName = "div";
var useFocusTrapRegion = createHook(
  function useFocusTrapRegion2({ enabled = false, ...props }) {
    const ref = useRef(null);
    props = useWrapElement(
      props,
      (element) => {
        const renderFocusTrap = () => {
          if (!enabled) return null;
          return /* @__PURE__ */ jsx(
            FocusTrap,
            {
              onFocus: (event) => {
                const container = ref.current;
                if (!container) return;
                const tabbables = getAllTabbableIn(container, true);
                const first = tabbables[0];
                const last = tabbables[tabbables.length - 1];
                if (!tabbables.length) {
                  container.focus();
                  return;
                }
                if (event.relatedTarget === first) {
                  last == null ? void 0 : last.focus();
                } else {
                  first == null ? void 0 : first.focus();
                }
              }
            }
          );
        };
        return /* @__PURE__ */ jsxs(Fragment, { children: [
          renderFocusTrap(),
          element,
          renderFocusTrap()
        ] });
      },
      [enabled]
    );
    props = {
      ...props,
      ref: useMergeRefs(ref, props.ref)
    };
    return removeUndefinedValues(props);
  }
);
var FocusTrapRegion = forwardRef(function FocusTrapRegion2(props) {
  const htmlProps = useFocusTrapRegion(props);
  return createElement(TagName, htmlProps);
});
export {
  FocusTrapRegion,
  useFocusTrapRegion
};
