import{j as c}from"./jsx-runtime-C5WNSv3b.js";import{r as l}from"./index-Az39ZADK.js";import{u as Re,e as ke,f as A,g as $,P as S,h as D,i as G,j as Ie,D as Le,n as Me}from"./tooltip-C2AQeNhD.js";import{P as je,h as We,R as Ae,u as Ue,F as Fe}from"./index-Cod-PQ6D.js";import{c as O,I as He}from"./misc-BapXpylh.js";import{o as m,s as f,as as I,a1 as F,aJ as oe,l as w,a as L,a2 as Q}from"./types-Cl2NuNg4.js";import{e as $e}from"./chunk-UIGDSWPH-BWkP6tD5.js";import{u as Ge}from"./online-Dw7HU4wM.js";import{u as C,a as qe}from"./root-loader-C5P2c7MU.js";var j="Dialog",[re]=ke(j),[Ve,g]=re(j),ne=e=>{const{__scopeDialog:t,children:s,open:o,defaultOpen:r,onOpenChange:n,modal:u=!0}=e,i=l.useRef(null),a=l.useRef(null),[h,p]=Re({prop:o,defaultProp:r??!1,onChange:n,caller:j});return c.jsx(Ve,{scope:t,triggerRef:i,contentRef:a,contentId:A(),titleId:A(),descriptionId:A(),open:h,onOpenChange:p,onOpenToggle:l.useCallback(()=>p(d=>!d),[p]),modal:u,children:s})};ne.displayName=j;var ie="DialogTrigger",ae=l.forwardRef((e,t)=>{const{__scopeDialog:s,...o}=e,r=g(ie,s),n=$(t,r.triggerRef);return c.jsx(S.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":B(r.open),...o,ref:n,onClick:D(e.onClick,r.onOpenToggle)})});ae.displayName=ie;var q="DialogPortal",[Be,ce]=re(q,{forceMount:void 0}),le=e=>{const{__scopeDialog:t,forceMount:s,children:o,container:r}=e,n=g(q,t);return c.jsx(Be,{scope:t,forceMount:s,children:l.Children.map(o,u=>c.jsx(G,{present:s||n.open,children:c.jsx(je,{asChild:!0,container:r,children:u})}))})};le.displayName=q;var M="DialogOverlay",ue=l.forwardRef((e,t)=>{const s=ce(M,e.__scopeDialog),{forceMount:o=s.forceMount,...r}=e,n=g(M,e.__scopeDialog);return n.modal?c.jsx(G,{present:o||n.open,children:c.jsx(Qe,{...r,ref:t})}):null});ue.displayName=M;var ze=Ie("DialogOverlay.RemoveScroll"),Qe=l.forwardRef((e,t)=>{const{__scopeDialog:s,...o}=e,r=g(M,s);return c.jsx(Ae,{as:ze,allowPinchZoom:!0,shards:[r.contentRef],children:c.jsx(S.div,{"data-state":B(r.open),...o,ref:t,style:{pointerEvents:"auto",...o.style}})})}),E="DialogContent",de=l.forwardRef((e,t)=>{const s=ce(E,e.__scopeDialog),{forceMount:o=s.forceMount,...r}=e,n=g(E,e.__scopeDialog);return c.jsx(G,{present:o||n.open,children:n.modal?c.jsx(Je,{...r,ref:t}):c.jsx(Ye,{...r,ref:t})})});de.displayName=E;var Je=l.forwardRef((e,t)=>{const s=g(E,e.__scopeDialog),o=l.useRef(null),r=$(t,s.contentRef,o);return l.useEffect(()=>{const n=o.current;if(n)return We(n)},[]),c.jsx(he,{...e,ref:r,trapFocus:s.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:D(e.onCloseAutoFocus,n=>{n.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:D(e.onPointerDownOutside,n=>{const u=n.detail.originalEvent,i=u.button===0&&u.ctrlKey===!0;(u.button===2||i)&&n.preventDefault()}),onFocusOutside:D(e.onFocusOutside,n=>n.preventDefault())})}),Ye=l.forwardRef((e,t)=>{const s=g(E,e.__scopeDialog),o=l.useRef(!1),r=l.useRef(!1);return c.jsx(he,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:n=>{e.onCloseAutoFocus?.(n),n.defaultPrevented||(o.current||s.triggerRef.current?.focus(),n.preventDefault()),o.current=!1,r.current=!1},onInteractOutside:n=>{e.onInteractOutside?.(n),n.defaultPrevented||(o.current=!0,n.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const u=n.target;s.triggerRef.current?.contains(u)&&n.preventDefault(),n.detail.originalEvent.type==="focusin"&&r.current&&n.preventDefault()}})}),he=l.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:o,onOpenAutoFocus:r,onCloseAutoFocus:n,...u}=e,i=g(E,s),a=l.useRef(null),h=$(t,a);return Ue(),c.jsxs(c.Fragment,{children:[c.jsx(Fe,{asChild:!0,loop:!0,trapped:o,onMountAutoFocus:r,onUnmountAutoFocus:n,children:c.jsx(Le,{role:"dialog",id:i.contentId,"aria-describedby":i.descriptionId,"aria-labelledby":i.titleId,"data-state":B(i.open),...u,ref:h,onDismiss:()=>i.onOpenChange(!1)})}),c.jsxs(c.Fragment,{children:[c.jsx(Ke,{titleId:i.titleId}),c.jsx(Xe,{contentRef:a,descriptionId:i.descriptionId})]})]})}),V="DialogTitle",pe=l.forwardRef((e,t)=>{const{__scopeDialog:s,...o}=e,r=g(V,s);return c.jsx(S.h2,{id:r.titleId,...o,ref:t})});pe.displayName=V;var fe="DialogDescription",me=l.forwardRef((e,t)=>{const{__scopeDialog:s,...o}=e,r=g(fe,s);return c.jsx(S.p,{id:r.descriptionId,...o,ref:t})});me.displayName=fe;var ge="DialogClose",_e=l.forwardRef((e,t)=>{const{__scopeDialog:s,...o}=e,r=g(ge,s);return c.jsx(S.button,{type:"button",...o,ref:t,onClick:D(e.onClick,()=>r.onOpenChange(!1))})});_e.displayName=ge;function B(e){return e?"open":"closed"}var ye="DialogTitleWarning",[Gt,be]=Me(ye,{contentName:E,titleName:V,docsSlug:"dialog"}),Ke=({titleId:e})=>{const t=be(ye),s=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.

If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.

For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return l.useEffect(()=>{e&&(document.getElementById(e)||console.error(s))},[s,e]),null},Ze="DialogDescriptionWarning",Xe=({contentRef:e,descriptionId:t})=>{const o=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${be(Ze).contentName}}.`;return l.useEffect(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(o))},[o,e,t]),null},et=ne,tt=ae,st=le,ve=ue,xe=de,we=pe,Ee=me,ot=_e;const qt=et,Vt=tt,rt=st;function Ce({className:e,ref:t,...s}){return c.jsx(ve,{ref:t,className:O("bg-background/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 backdrop-blur-sm",e),...s})}Ce.displayName=ve.displayName;function nt({className:e,children:t,ref:s,...o}){return c.jsxs(rt,{children:[c.jsx(Ce,{}),c.jsxs(xe,{ref:s,className:O("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border p-6 shadow-lg duration-200 sm:rounded-lg md:w-full",e),...o,children:[t,c.jsxs(ot,{className:"ring-offset-background data-[state=open]:bg-accent data-[state=open]:text-muted-foreground focus:ring-ring absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none",children:[c.jsx(He,{name:"Close"}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}nt.displayName=xe.displayName;function it({className:e,...t}){return c.jsx("div",{className:O("flex flex-col space-y-1.5 text-center sm:text-left",e),...t})}it.displayName="DialogHeader";function at({className:e,ref:t,...s}){return c.jsx(we,{ref:t,className:O("text-lg leading-none font-semibold tracking-tight",e),...s})}at.displayName=we.displayName;function ct({className:e,ref:t,...s}){return c.jsx(Ee,{ref:t,className:O("text-muted-foreground text-sm",e),...s})}ct.displayName=Ee.displayName;const Ne="epic-web-presence",lt=`https://epic-web-presence.kentcdodds.partykit.dev/parties/main/${Ne}`,ut=m({updatesAvailable:F().nullable().optional(),commitsAhead:I().nullable().optional(),commitsBehind:I().nullable().optional(),localCommit:f().nullable().optional(),remoteCommit:f().nullable().optional()}),J=m({workshopTitle:f().nullable().optional(),origin:f().nullable().optional(),productHost:f().nullable().optional(),exercise:m({type:oe([w("problem"),w("solution")]).nullable().optional(),exerciseNumber:I().nullable().optional(),stepNumber:I().nullable().optional()}).nullable().optional(),epicshopVersion:f().nullable().optional(),repoStatus:ut.nullable().optional(),lastUpdatedAt:f().nullable().optional()}),H=m({id:f(),hasAccess:F().nullable().optional(),avatarUrl:f().nullable().optional(),imageUrlSmall:f().nullable().optional(),imageUrlLarge:f().nullable().optional(),name:f().nullable().optional(),optOut:F().nullable().optional(),loggedInProductHosts:L(f()).nullable().optional(),location:J.nullable().optional(),locations:L(J).nullable().optional()}),dt=m({type:w("remove-user"),payload:m({id:f()})}).or(m({type:w("add-user"),payload:H})).or(m({type:w("presence"),payload:m({users:L(H)})}));m({users:L(H)});const ht={"www.epicreact.dev":"🚀","www.epicai.pro":"⚡","www.epicweb.dev":"🌌"};function Bt(e){return e?ht[e]??null:null}(!globalThis.EventTarget||!globalThis.Event)&&console.error(`
  PartySocket requires a global 'EventTarget' class to be available!
  You can polyfill this global by adding this to your code before any partysocket imports: 
  
  \`\`\`
  import 'partysocket/event-target-polyfill';
  \`\`\`
  Please file an issue at https://github.com/partykit/partykit if you're still having trouble.
`);var Pe=class extends Event{message;error;constructor(e,t){super("error",t),this.message=e.message,this.error=e}},Te=class extends Event{code;reason;wasClean=!0;constructor(e=1e3,t="",s){super("close",s),this.code=e,this.reason=t}},U={Event,ErrorEvent:Pe,CloseEvent:Te};function pt(e,t){if(!e)throw new Error(t)}function ft(e){return new e.constructor(e.type,e)}function mt(e){return"data"in e?new MessageEvent(e.type,e):"code"in e||"reason"in e?new Te(e.code||1999,e.reason||"unknown reason",e):"error"in e?new Pe(e.error,e):new Event(e.type,e)}var Y,gt=typeof process<"u"&&typeof((Y=process.versions)==null?void 0:Y.node)<"u"&&typeof document>"u",k=gt?mt:ft,v={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:Number.POSITIVE_INFINITY,maxEnqueuedMessages:Number.POSITIVE_INFINITY},K=!1,_t=class x extends EventTarget{_ws;_retryCount=-1;_uptimeTimeout;_connectTimeout;_shouldReconnect=!0;_connectLock=!1;_binaryType="blob";_closeCalled=!1;_messageQueue=[];_debugLogger=console.log.bind(console);_url;_protocols;_options;constructor(t,s,o={}){super(),this._url=t,this._protocols=s,this._options=o,this._options.startClosed&&(this._shouldReconnect=!1),this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return x.CONNECTING}get OPEN(){return x.OPEN}get CLOSING(){return x.CLOSING}get CLOSED(){return x.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((s,o)=>(typeof o=="string"?s+=o.length:o instanceof Blob?s+=o.size:s+=o.byteLength,s),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?x.CLOSED:x.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}onclose=null;onerror=null;onmessage=null;onopen=null;close(t=1e3,s){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,s)}reconnect(t,s){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,s),this._connect())}send(t){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:s=v.maxEnqueuedMessages}=this._options;this._messageQueue.length<s&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=v.reconnectionDelayGrowFactor,minReconnectionDelay:s=v.minReconnectionDelay,maxReconnectionDelay:o=v.maxReconnectionDelay}=this._options;let r=0;return this._retryCount>0&&(r=s*t**(this._retryCount-1),r>o&&(r=o)),this._debug("next delay",r),r}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_getNextProtocols(t){if(!t)return Promise.resolve(null);if(typeof t=="string"||Array.isArray(t))return Promise.resolve(t);if(typeof t=="function"){const s=t();if(!s)return Promise.resolve(null);if(typeof s=="string"||Array.isArray(s))return Promise.resolve(s);if(s.then)return s}throw Error("Invalid protocols")}_getNextUrl(t){if(typeof t=="string")return Promise.resolve(t);if(typeof t=="function"){const s=t();if(typeof s=="string")return Promise.resolve(s);if(s.then)return s}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=v.maxRetries,connectionTimeout:s=v.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>Promise.all([this._getNextUrl(this._url),this._getNextProtocols(this._protocols||null)])).then(([o,r])=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!K&&(console.error(`‼️ No WebSocket implementation available. You should define options.WebSocket. 

For example, if you're using node.js, run \`npm install ws\`, and then in your code:

import PartySocket from 'partysocket';
import WS from 'ws';

const partysocket = new PartySocket({
  host: "127.0.0.1:1999",
  room: "test-room",
  WebSocket: WS
});

`),K=!0);const n=this._options.WebSocket||WebSocket;this._debug("connect",{url:o,protocols:r}),this._ws=r?new n(o,r):new n(o),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),s)}).catch(o=>{this._connectLock=!1,this._handleError(new U.ErrorEvent(Error(o.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new U.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,s){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{(this._ws.readyState===this.OPEN||this._ws.readyState===this.CONNECTING)&&this._ws.close(t,s),this._handleClose(new U.CloseEvent(t,s,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_handleOpen=t=>{this._debug("open event");const{minUptime:s=v.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),pt(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(o=>{var r;(r=this._ws)==null||r.send(o)}),this._messageQueue=[],this.onopen&&this.onopen(t),this.dispatchEvent(k(t))};_handleMessage=t=>{this._debug("message event"),this.onmessage&&this.onmessage(t),this.dispatchEvent(k(t))};_handleError=t=>{this._debug("error event",t.message),this._disconnect(void 0,t.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(t),this._debug("exec error listeners"),this.dispatchEvent(k(t)),this._connect()};_handleClose=t=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(t),this.dispatchEvent(k(t))};_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}};var yt=e=>e[1]!==null&&e[1]!==void 0;function bt(){if(crypto!=null&&crypto.randomUUID)return crypto.randomUUID();let e=Date.now(),t=performance?.now&&performance.now()*1e3||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let o=Math.random()*16;return e>0?(o=(e+o)%16|0,e=Math.floor(e/16)):(o=(t+o)%16|0,t=Math.floor(t/16)),(s==="x"?o:o&3|8).toString(16)})}function De(e,t,s={}){const{host:o,path:r,protocol:n,room:u,party:i,basePath:a,prefix:h,query:p}=e;let d=o.replace(/^(http|https|ws|wss):\/\//,"");if(d.endsWith("/")&&(d=d.slice(0,-1)),r?.startsWith("/"))throw new Error("path must not start with a slash");const N=i??"main",b=r?`/${r}`:"",_=n||(d.startsWith("localhost:")||d.startsWith("127.0.0.1:")||d.startsWith("192.168.")||d.startsWith("10.")||d.startsWith("172.")&&d.split(".")[1]>="16"&&d.split(".")[1]<="31"||d.startsWith("[::ffff:7f00:1]:")?t:`${t}s`),y=`${_}://${d}/${a||`${h||"parties"}/${N}/${u}`}${b}`,W=(T={})=>`${y}?${new URLSearchParams([...Object.entries(s),...Object.entries(T).filter(yt)])}`,P=typeof p=="function"?async()=>W(await p()):W(p);return{host:d,path:b,room:u,name:N,protocol:_,partyUrl:y,urlProvider:P}}var vt=class extends _t{constructor(e){var t,s;const o=Z(e);super(o.urlProvider,o.protocols,o.socketOptions),this.partySocketOptions=e,this.setWSProperties(o),e.disableNameValidation||((t=e.party)!=null&&t.includes("/")&&console.warn(`PartySocket: party name "${e.party}" contains forward slash which may cause routing issues. Consider using a name without forward slashes or set disableNameValidation: true to bypass this warning.`),(s=e.room)!=null&&s.includes("/")&&console.warn(`PartySocket: room name "${e.room}" contains forward slash which may cause routing issues. Consider using a name without forward slashes or set disableNameValidation: true to bypass this warning.`))}_pk;_pkurl;name;room;host;path;updateProperties(e){const t=Z({...this.partySocketOptions,...e,host:e.host??this.host,room:e.room??this.room,path:e.path??this.path});this._url=t.urlProvider,this._protocols=t.protocols,this._options=t.socketOptions,this.setWSProperties(t)}setWSProperties(e){const{_pk:t,_pkurl:s,name:o,room:r,host:n,path:u}=e;this._pk=t,this._pkurl=s,this.name=o,this.room=r,this.host=n,this.path=u}reconnect(e,t){if(!this.room||!this.host)throw new Error("The room and host must be set before connecting, use `updateProperties` method to set them or pass them to the constructor.");super.reconnect(e,t)}get id(){return this._pk}get roomUrl(){return this._pkurl}static async fetch(e,t){const s=De(e,"http"),o=typeof s.urlProvider=="string"?s.urlProvider:await s.urlProvider();return(e.fetch??fetch)(o,t)}};function Z(e){const{id:t,host:s,path:o,party:r,room:n,protocol:u,query:i,protocols:a,...h}=e,p=t||bt(),d=De(e,"ws",{_pk:p});return{_pk:p,_pkurl:d.partyUrl,name:d.name,room:d.room,host:d.host,path:d.path,protocols:a,socketOptions:h,urlProvider:d.urlProvider}}var xt=(e,t)=>{const s=l.useRef(t);s.current=t,l.useEffect(()=>{const o=i=>{var a,h;return(h=(a=s.current)==null?void 0:a.onOpen)==null?void 0:h.call(a,i)},r=i=>{var a,h;return(h=(a=s.current)==null?void 0:a.onMessage)==null?void 0:h.call(a,i)},n=i=>{var a,h;return(h=(a=s.current)==null?void 0:a.onClose)==null?void 0:h.call(a,i)},u=i=>{var a,h;return(h=(a=s.current)==null?void 0:a.onError)==null?void 0:h.call(a,i)};return e.addEventListener("open",o),e.addEventListener("close",n),e.addEventListener("error",u),e.addEventListener("message",r),()=>{e.removeEventListener("open",o),e.removeEventListener("close",n),e.removeEventListener("error",u),e.removeEventListener("message",r)}},[e])},wt=e=>[e.startClosed,e.minUptime,e.maxRetries,e.connectionTimeout,e.maxEnqueuedMessages,e.maxReconnectionDelay,e.minReconnectionDelay,e.reconnectionDelayGrowFactor,e.debug];function Et({options:e,createSocket:t,createSocketMemoKey:s}){const o=s(e),r=l.useMemo(()=>e,[o]),[n,u]=l.useState(()=>t({...r,startClosed:!0})),i=l.useRef(null),a=l.useRef(t);return a.current=t,l.useEffect(()=>{if(i.current===n){const h=a.current({...r,startClosed:!1});u(h)}else return!i.current&&r.startClosed!==!0&&n.reconnect(),i.current=n,()=>{n.close()}},[n,r]),n}function Ct(e){const{host:t,...s}=e,o=Et({options:{host:t||(typeof window<"u"?window.location.host:"dummy-domain.com"),...s},createSocket:r=>new vt(r),createSocketMemoKey:r=>JSON.stringify([r.query,r.id,r.host,r.room,r.party,r.path,r.protocol,r.protocols,r.basePath,r.prefix,...wt(r)])});return xt(o,e),o}const z=l.createContext(null);function Nt(){return C()?.preferences?.presence??null}function Pt(){return C()?.workshopTitle??null}const Tt=m({type:oe([w("problem"),w("solution")]).optional(),exerciseNumber:Q.number().finite(),stepNumber:Q.number().finite().optional()});function Dt(e,t){const[s]=l.useState(()=>new Promise(i=>setTimeout(i,t))),o=l.useRef(!0),r=l.useRef(null),n=l.useRef(e);return l.useEffect(()=>{n.current=e},[e]),l.useCallback((...i)=>{const a=Symbol();r.current=a,s.then(()=>{o.current&&r.current===a&&n.current(...i)})},[s])}function St(){return C()?.workshopConfig?.product?.host??null}function Ot(){return C()?.loggedInProductHosts??[]}function Se(){const e=Pt(),t=qe(),s=St(),o=$e(),r=Tt.safeParse(o),n=r.success?r.data:null,{ENV:u,repoUpdates:i}=C()??{},a=u?.EPICSHOP_APP_VERSION??null,h=i&&"updatesAvailable"in i?{...i}:null;return{workshopTitle:e,origin:t.origin,productHost:s,epicshopVersion:a,repoStatus:h,...n?{exercise:{type:n.type,exerciseNumber:n.exerciseNumber,stepNumber:n.stepNumber}}:null}}function Rt(e){const t=Nt(),{userId:s,presence:o,userHasAccess:r}=C()??{},[n,u]=l.useState(o?.users??[]),i=Se(),a=Ot(),h=Dt(P=>{const T=dt.safeParse(JSON.parse(String(P.data)));T.success&&T.data.type==="presence"&&u(T.data.payload.users)},2e3),p=Ct({host:new URL(lt).host,room:Ne,onMessage:h}),d=e?.id??s?.id,b=(d?o?.users?.find(P=>P.id===d):null)??e??{};let _=null;d&&(t?.optOut?_={type:"add-user",payload:{...b,id:d,hasAccess:r,optOut:!0,loggedInProductHosts:a,location:i}}:_={type:"add-user",payload:{...b,id:d,hasAccess:r,location:i,loggedInProductHosts:a}});const y=_?JSON.stringify(_):null;return l.useEffect(()=>{y&&p.send(y)},[y,p]),{users:Oe({id:s?.id,location:i},n)}}function R(e){return e.locations&&e.locations.length>0?e.locations.filter(Boolean):e.location?[e.location]:[]}function Oe(e,t){const{location:s}=e;return t.map(r=>{let n=0;if(r.optOut)return{user:r,score:0};const u=R(r);for(const i of u)s?.workshopTitle&&s.workshopTitle===i.workshopTitle?(n=Math.max(n,.4),s.exercise?.exerciseNumber!=null&&s.exercise.exerciseNumber===i.exercise?.exerciseNumber&&(n=Math.max(n,.6),s.exercise.stepNumber!=null&&s.exercise.stepNumber===i.exercise?.stepNumber&&(n=Math.max(n,.8),s.exercise.type&&s.exercise.type===i.exercise?.type&&(n=1)))):s?.productHost&&s.productHost===i.productHost&&(n=Math.max(n,.2));return{user:r,score:n}}).sort((r,n)=>{if(r.user.id===e.id)return-1;if(n.user.id===e.id||r.user.optOut&&!n.user.optOut)return 1;if(!r.user.optOut&&n.user.optOut)return-1;const u=X(s,r.user),i=X(s,n.user);if(u&&!i)return-1;if(!u&&i)return 1;const a=ee(s,r.user),h=ee(s,n.user);if(a&&!h)return-1;if(!a&&h)return 1;const p=te(s,r.user),d=te(s,n.user);if(p&&!d)return-1;if(!p&&d)return 1;const N=se(s,r.user),b=se(s,n.user);if(N&&!b)return-1;if(!N&&b)return 1;const _=r.user.loggedInProductHosts?.length??0,y=n.user.loggedInProductHosts?.length??0;return _!==y?y-_:0})}function X(e,t){return e?.exercise?R(t).some(o=>o.workshopTitle===e.workshopTitle&&o.exercise?.exerciseNumber===e.exercise?.exerciseNumber&&o.exercise?.stepNumber===e.exercise?.stepNumber&&o.exercise?.type===e.exercise?.type):!1}function ee(e,t){return e?.exercise?.exerciseNumber?R(t).some(o=>o.workshopTitle===e.workshopTitle&&o.exercise?.exerciseNumber===e.exercise?.exerciseNumber):!1}function te(e,t){return e?.workshopTitle?R(t).some(o=>o.workshopTitle===e.workshopTitle):!1}function se(e,t){return e?.productHost?R(t).some(o=>o.productHost===e.productHost):!1}function kt({user:e,children:t}){return c.jsx(z.Provider,{value:Rt(e),children:t})}function It({user:e,children:t}){const s=Se(),{presence:o}=C()??{};return c.jsx(z.Provider,{value:{users:Oe({id:e?.id,location:s},o?.users??[])},children:t})}function zt({user:e,children:t}){return Ge()?c.jsx(kt,{user:e,children:t}):c.jsx(It,{user:e,children:t})}function Qt(){const e=l.useContext(z);if(!e)throw new Error("usePresence must be used within a PresenceProvider");return e}export{qt as D,zt as P,Vt as a,nt as b,it as c,ct as d,at as e,Bt as g,ht as p,Qt as u};
//# sourceMappingURL=presence-9HHV7YsZ.js.map
