"use client";import i,{Fragment as R,createContext as E,useContext as f,useEffect as A,useMemo as G,useRef as x,useState as b}from"react";import{createPortal as H}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{useServerHandoffComplete as U}from'../../hooks/use-server-handoff-complete.js';import{optionalRef as N,useSyncRefs as P}from'../../hooks/use-sync-refs.js';import{usePortalRoot as S}from'../../internal/portal-force-root.js';import{env as W}from'../../utils/env.js';import{forwardRefWithAs as T,useRender as d}from'../../utils/render.js';function j(e){let o=S(),l=f(c),[r,p]=b(()=>{var s;if(!o&&l!==null)return(s=l.current)!=null?s:null;if(W.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,I=T(function(o,l){let{ownerDocument:r=null,...p}=o,t=x(null),n=P(N(a=>{t.current=a}),l),s=h(t.current),C=r!=null?r:s,u=j(C),y=f(m),g=O(),v=U(),M=d();return F(()=>{var a;u&&u.childNodes.length<=0&&((a=u.parentElement)==null||a.removeChild(u))}),!u||!v?null:H(i.createElement("div",{"data-headlessui-portal":"",ref:a=>{g.dispose(),y&&a&&g.add(y.register(a))}},M({ourProps:{ref:n},theirProps:p,slot:{},defaultTag:_,name:"Portal"})),u)});function D(e,o){let l=P(o),{enabled:r=!0,ownerDocument:p,...t}=e,n=d();return r?i.createElement(I,{...t,ownerDocument:p,ref:l}):n({ourProps:{ref:l},theirProps:t,slot:{},defaultTag:_,name:"Portal"})}let J=R,c=E(null);function X(e,o){let{target:l,...r}=e,t={ref:P(o)},n=d();return i.createElement(c.Provider,{value:l},n({ourProps:t,theirProps:r,defaultTag:J,name:"Popover.Group"}))}let m=E(null);function oe(){let e=f(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 k=T(D),B=T(X),le=Object.assign(k,{Group:B});export{le as Portal,B as PortalGroup,oe as useNestedPortals};
