import s, { useState as m, createContext as p, useContext as v } from "react";
import { Hidden as h, HiddenFeatures as E } from "../internal/hidden.js";
import { getOwnerDocument as H } from "../utils/owner.js";
import { useEvent as c } from "./use-event.js";
import { useOwnerDocument as T } from "./use-owner.js";
function x({ defaultContainers: u = [], portals: n, mainTreeNode: r } = {}) {
  let i = T(r), a = c(() => {
    var o, l;
    let t = [];
    for (let e of u) e !== null && (e instanceof HTMLElement ? t.push(e) : "current" in e && e.current instanceof HTMLElement && t.push(e.current));
    if (n != null && n.current) for (let e of n.current) t.push(e);
    for (let e of (o = i == null ? void 0 : i.querySelectorAll("html > *, body > *")) != null ? o : []) e !== document.body && e !== document.head && e instanceof HTMLElement && e.id !== "headlessui-portal-root" && (r && (e.contains(r) || e.contains((l = r == null ? void 0 : r.getRootNode()) == null ? void 0 : l.host)) || t.some((f) => e.contains(f)) || t.push(e));
    return t;
  });
  return { resolveContainers: a, contains: c((o) => a().some((l) => l.contains(o))) };
}
let d = p(null);
function N({ children: u, node: n }) {
  let [r, i] = m(null), a = b(n ?? r);
  return s.createElement(d.Provider, { value: a }, u, a === null && s.createElement(h, { features: E.Hidden, ref: (o) => {
    var l, t;
    if (o) {
      for (let e of (t = (l = H(o)) == null ? void 0 : l.querySelectorAll("html > *, body > *")) != null ? t : []) if (e !== document.body && e !== document.head && e instanceof HTMLElement && e != null && e.contains(o)) {
        i(e);
        break;
      }
    }
  } }));
}
function b(u = null) {
  var n;
  return (n = v(d)) != null ? n : u;
}
export {
  N as MainTreeProvider,
  b as useMainTreeNode,
  x as useRootContainers
};
