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