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