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