"use client";import T,{Fragment as E,createContext as A,useContext as d,useEffect as G,useMemo as x,useRef as L,useState as c}from"react";import{createPortal as h}from"react-dom";import{useEvent as _}from'../../hooks/use-event.js';import{useIsoMorphicEffect as C}from'../../hooks/use-iso-morphic-effect.js';import{useOnUnmount as F}from'../../hooks/use-on-unmount.js';import{useOwnerDocument as U}from'../../hooks/use-owner.js';import{useServerHandoffComplete as N}from'../../hooks/use-server-handoff-complete.js';import{optionalRef as S,useSyncRefs as m}from'../../hooks/use-sync-refs.js';import{usePortalRoot as W}from'../../internal/portal-force-root.js';import*as j from'../../utils/dom.js';import{env as v}from'../../utils/env.js';import{forwardRefWithAs as y,useRender as R}from'../../utils/render.js';function I(e){let l=W(),o=d(H),[r,u]=c(()=>{var i;if(!l&&o!==null)return(i=o.current)!=null?i:null;if(v.isServer)return null;let t=e==null?void 0:e.getElementById("headlessui-portal-root");if(t)return t;if(e===null)return null;let a=e.createElement("div");return a.setAttribute("id","headlessui-portal-root"),e.body.appendChild(a)});return G(()=>{r!==null&&(e!=null&&e.body.contains(r)||e==null||e.body.appendChild(r))},[r,e]),G(()=>{l||o!==null&&u(o.current)},[o,u,l]),r}let M=E,D=y(function(l,o){let{ownerDocument:r=null,...u}=l,t=L(null),a=m(S(s=>{t.current=s}),o),i=U(t),f=r!=null?r:i,p=I(f),[n]=c(()=>{var s;return v.isServer?null:(s=f==null?void 0:f.createElement("div"))!=null?s:null}),P=d(g),O=N();C(()=>{!p||!n||p.contains(n)||(n.setAttribute("data-headlessui-portal",""),p.appendChild(n))},[p,n]),C(()=>{if(n&&P)return P.register(n)},[P,n]),F(()=>{var s;!p||!n||(j.isNode(n)&&p.contains(n)&&p.removeChild(n),p.childNodes.length<=0&&((s=p.parentElement)==null||s.removeChild(p)))});let b=R();return O?!p||!n?null:h(b({ourProps:{ref:a},theirProps:u,slot:{},defaultTag:M,name:"Portal"}),n):null});function J(e,l){let o=m(l),{enabled:r=!0,ownerDocument:u,...t}=e,a=R();return r?T.createElement(D,{...t,ownerDocument:u,ref:o}):a({ourProps:{ref:o},theirProps:t,slot:{},defaultTag:M,name:"Portal"})}let X=E,H=A(null);function k(e,l){let{target:o,...r}=e,t={ref:m(l)},a=R();return T.createElement(H.Provider,{value:o},a({ourProps:t,theirProps:r,defaultTag:X,name:"Popover.Group"}))}let g=A(null);function oe(){let e=d(g),l=L([]),o=_(t=>(l.current.push(t),e&&e.register(t),()=>r(t))),r=_(t=>{let a=l.current.indexOf(t);a!==-1&&l.current.splice(a,1),e&&e.unregister(t)}),u=x(()=>({register:o,unregister:r,portals:l}),[o,r,l]);return[l,x(()=>function({children:a}){return T.createElement(g.Provider,{value:u},a)},[u])]}let B=y(J),q=y(k),ne=Object.assign(B,{Group:q});export{ne as Portal,q as PortalGroup,oe as useNestedPortals};
