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