@wacht/jsx 0.0.1-alpha.28 → 0.0.1-alpha.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * This source code is licensed under the MIT license found in the
17
17
  * LICENSE file in the root directory of this source tree.
18
- */var Ma;function od(){return Ma||(Ma=1,process.env.NODE_ENV!=="production"&&function(){function t(m,v){return m===v&&(m!==0||1/m===1/v)||m!==m&&v!==v}function r(m,v){d||s.startTransition===void 0||(d=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var y=v();if(!u){var S=v();a(y,S)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),u=!0)}S=h({inst:{value:y,getSnapshot:v}});var E=S[0].inst,b=S[1];return c(function(){E.value=y,E.getSnapshot=v,o(E)&&b({inst:E})},[m,y,v]),f(function(){return o(E)&&b({inst:E}),m(function(){o(E)&&b({inst:E})})},[m]),p(y),y}function o(m){var v=m.getSnapshot;m=m.value;try{var y=v();return!a(m,y)}catch{return!0}}function n(m,v){return v()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var s=i,a=typeof Object.is=="function"?Object.is:t,h=s.useState,f=s.useEffect,c=s.useLayoutEffect,p=s.useDebugValue,d=!1,u=!1,g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n:r;cn.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:g,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),cn}var La;function nd(){return La||(La=1,process.env.NODE_ENV==="production"?Yr.exports=rd():Yr.exports=od()),Yr.exports}var ad=nd();const Gi=0,Hi=1,qi=2,Aa=3;var Da=Object.prototype.hasOwnProperty;function Yn(t,r){var o,n;if(t===r)return!0;if(t&&r&&(o=t.constructor)===r.constructor){if(o===Date)return t.getTime()===r.getTime();if(o===RegExp)return t.toString()===r.toString();if(o===Array){if((n=t.length)===r.length)for(;n--&&Yn(t[n],r[n]););return n===-1}if(!o||typeof t=="object"){n=0;for(o in t)if(Da.call(t,o)&&++n&&!Da.call(r,o)||!(o in r)||!Yn(t[o],r[o]))return!1;return Object.keys(r).length===n}}return t!==t&&r!==r}const xt=new WeakMap,St=()=>{},Ge=St(),Zn=Object,Ce=t=>t===Ge,ct=t=>typeof t=="function",Et=(t,r)=>({...t,...r}),Yi=t=>ct(t.then),ln={},Zr={},xa="undefined",Br=typeof window!=xa,Qn=typeof document!=xa,sd=Br&&"Deno"in window,id=()=>Br&&typeof window.requestAnimationFrame!=xa,Zi=(t,r)=>{const o=xt.get(t);return[()=>!Ce(r)&&t.get(r)||ln,n=>{if(!Ce(r)){const s=t.get(r);r in Zr||(Zr[r]=s),o[5](r,Et(s,n),s||ln)}},o[6],()=>!Ce(r)&&r in Zr?Zr[r]:!Ce(r)&&t.get(r)||ln]};let Kn=!0;const cd=()=>Kn,[Xn,Jn]=Br&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[St,St],ld=()=>{const t=Qn&&document.visibilityState;return Ce(t)||t!=="hidden"},dd=t=>(Qn&&document.addEventListener("visibilitychange",t),Xn("focus",t),()=>{Qn&&document.removeEventListener("visibilitychange",t),Jn("focus",t)}),ud=t=>{const r=()=>{Kn=!0,t()},o=()=>{Kn=!1};return Xn("online",r),Xn("offline",o),()=>{Jn("online",r),Jn("offline",o)}},pd={isOnline:cd,isVisible:ld},hd={initFocus:dd,initReconnect:ud},Fa=!i.useId,Ar=!Br||sd,fd=t=>id()?window.requestAnimationFrame(t):setTimeout(t,1),dn=Ar?i.useEffect:i.useLayoutEffect,un=typeof navigator<"u"&&navigator.connection,Na=!Ar&&un&&(["slow-2g","2g"].includes(un.effectiveType)||un.saveData),Qr=new WeakMap,gd=t=>Zn.prototype.toString.call(t),pn=(t,r)=>t===`[object ${r}]`;let md=0;const ea=t=>{const r=typeof t,o=gd(t),n=pn(o,"Date"),s=pn(o,"RegExp"),a=pn(o,"Object");let h,f;if(Zn(t)===t&&!n&&!s){if(h=Qr.get(t),h)return h;if(h=++md+"~",Qr.set(t,h),Array.isArray(t)){for(h="@",f=0;f<t.length;f++)h+=ea(t[f])+",";Qr.set(t,h)}if(a){h="#";const c=Zn.keys(t).sort();for(;!Ce(f=c.pop());)Ce(t[f])||(h+=f+":"+ea(t[f])+",");Qr.set(t,h)}}else h=n?t.toJSON():r=="symbol"?t.toString():r=="string"?JSON.stringify(t):""+t;return h},va=t=>{if(ct(t))try{t=t()}catch{t=""}const r=t;return t=typeof t=="string"?t:(Array.isArray(t)?t.length:t)?ea(t):"",[t,r]};let xd=0;const ta=()=>++xd;async function Qi(...t){const[r,o,n,s]=t,a=Et({populateCache:!0,throwOnError:!0},typeof s=="boolean"?{revalidate:s}:s||{});let h=a.populateCache;const f=a.rollbackOnError;let c=a.optimisticData;const p=g=>typeof f=="function"?f(g):f!==!1,d=a.throwOnError;if(ct(o)){const g=o,m=[],v=r.keys();for(const y of v)!/^\$(inf|sub)\$/.test(y)&&g(r.get(y)._k)&&m.push(y);return Promise.all(m.map(u))}return u(o);async function u(g){const[m]=va(g);if(!m)return;const[v,y]=Zi(r,m),[S,E,b,$]=xt.get(r),C=()=>{const z=S[m];return(ct(a.revalidate)?a.revalidate(v().data,g):a.revalidate!==!1)&&(delete b[m],delete $[m],z&&z[0])?z[0](qi).then(()=>v().data):v().data};if(t.length<3)return C();let w=n,j,x=!1;const I=ta();E[m]=[I,0];const k=!Ce(c),R=v(),_=R.data,O=R._c,P=Ce(O)?_:O;if(k&&(c=ct(c)?c(P,_):c,y({data:c,_c:P})),ct(w))try{w=w(P)}catch(z){j=z,x=!0}if(w&&Yi(w))if(w=await w.catch(z=>{j=z,x=!0}),I!==E[m][0]){if(x)throw j;return w}else x&&k&&p(j)&&(h=!0,y({data:P,_c:Ge}));if(h&&!x)if(ct(h)){const z=h(w,P);y({data:z,error:Ge,_c:Ge})}else y({data:w,error:Ge,_c:Ge});if(E[m][1]=ta(),Promise.resolve(C()).then(()=>{y({_c:Ge})}),x){if(d)throw j;return}return w}}const Ba=(t,r)=>{for(const o in t)t[o][0]&&t[o][0](r)},vd=(t,r)=>{if(!xt.has(t)){const o=Et(hd,r),n=Object.create(null),s=Qi.bind(Ge,t);let a=St;const h=Object.create(null),f=(d,u)=>{const g=h[d]||[];return h[d]=g,g.push(u),()=>g.splice(g.indexOf(u),1)},c=(d,u,g)=>{t.set(d,u);const m=h[d];if(m)for(const v of m)v(u,g)},p=()=>{if(!xt.has(t)&&(xt.set(t,[n,Object.create(null),Object.create(null),Object.create(null),s,c,f]),!Ar)){const d=o.initFocus(setTimeout.bind(Ge,Ba.bind(Ge,n,Gi))),u=o.initReconnect(setTimeout.bind(Ge,Ba.bind(Ge,n,Hi)));a=()=>{d&&d(),u&&u(),xt.delete(t)}}};return p(),[t,s,p,a]}return[t,xt.get(t)[4]]},bd=(t,r,o,n,s)=>{const a=o.errorRetryCount,h=s.retryCount,f=~~((Math.random()+.5)*(1<<(h<8?h:8)))*o.errorRetryInterval;!Ce(a)&&h>a||setTimeout(n,f,s)},yd=Yn,[Ki,wd]=vd(new Map),jd=Et({onLoadingSlow:St,onSuccess:St,onError:St,onErrorRetry:bd,onDiscarded:St,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:Na?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:Na?5e3:3e3,compare:yd,isPaused:()=>!1,cache:Ki,mutate:wd,fallback:{}},pd),kd=(t,r)=>{const o=Et(t,r);if(r){const{use:n,fallback:s}=t,{use:a,fallback:h}=r;n&&a&&(o.use=n.concat(a)),s&&h&&(o.fallback=Et(s,h))}return o},_d=i.createContext({}),Cd="$inf$",Xi=Br&&window.__SWR_DEVTOOLS_USE__,Sd=Xi?window.__SWR_DEVTOOLS_USE__:[],$d=()=>{Xi&&(window.__SWR_DEVTOOLS_REACT__=i)},zd=t=>ct(t[1])?[t[0],t[1],t[2]||{}]:[t[0],null,(t[1]===null?t[2]:t[1])||{}],Ji=()=>Et(jd,i.useContext(_d)),Ed=t=>(r,o,n)=>t(r,o&&((...a)=>{const[h]=va(r),[,,,f]=xt.get(Ki);if(h.startsWith(Cd))return o(...a);const c=f[h];return Ce(c)?o(...a):(delete f[h],c)}),n),Pd=Sd.concat(Ed),Rd=t=>function(...o){const n=Ji(),[s,a,h]=zd(o),f=kd(n,h);let c=t;const{use:p}=f,d=(p||[]).concat(Pd);for(let u=d.length;u--;)c=d[u](c);return c(s,a||f.fetcher||null,f)},Id=(t,r,o)=>{const n=r[t]||(r[t]=[]);return n.push(o),()=>{const s=n.indexOf(o);s>=0&&(n[s]=n[n.length-1],n.pop())}};$d();const hn=i.use||(t=>{switch(t.status){case"pending":throw t;case"fulfilled":return t.value;case"rejected":throw t.reason;default:throw t.status="pending",t.then(r=>{t.status="fulfilled",t.value=r},r=>{t.status="rejected",t.reason=r}),t}}),fn={dedupe:!0},Td=(t,r,o)=>{const{cache:n,compare:s,suspense:a,fallbackData:h,revalidateOnMount:f,revalidateIfStale:c,refreshInterval:p,refreshWhenHidden:d,refreshWhenOffline:u,keepPreviousData:g}=o,[m,v,y,S]=xt.get(n),[E,b]=va(t),$=i.useRef(!1),C=i.useRef(!1),w=i.useRef(E),j=i.useRef(r),x=i.useRef(o),I=()=>x.current,k=()=>I().isVisible()&&I().isOnline(),[R,_,O,P]=Zi(n,E),z=i.useRef({}).current,T=Ce(h)?Ce(o.fallback)?Ge:o.fallback[E]:h,M=(V,D)=>{for(const le in z){const H=le;if(H==="data"){if(!s(V[H],D[H])&&(!Ce(V[H])||!s(ee,D[H])))return!1}else if(D[H]!==V[H])return!1}return!0},F=i.useMemo(()=>{const V=!E||!r?!1:Ce(f)?I().isPaused()||a?!1:c!==!1:f,D=Y=>{const Z=Et(Y);return delete Z._k,V?{isValidating:!0,isLoading:!0,...Z}:Z},le=R(),H=P(),ae=D(le),ke=le===H?ae:D(H);let ne=ae;return[()=>{const Y=D(R());return M(Y,ne)?(ne.data=Y.data,ne.isLoading=Y.isLoading,ne.isValidating=Y.isValidating,ne.error=Y.error,ne):(ne=Y,Y)},()=>ke]},[n,E]),G=ad.useSyncExternalStore(i.useCallback(V=>O(E,(D,le)=>{M(le,D)||V()}),[n,E]),F[0],F[1]),L=!$.current,A=m[E]&&m[E].length>0,se=G.data,te=Ce(se)?T&&Yi(T)?hn(T):T:se,U=G.error,K=i.useRef(te),ee=g?Ce(se)?Ce(K.current)?te:K.current:se:te,J=A&&!Ce(U)?!1:L&&!Ce(f)?f:I().isPaused()?!1:a?Ce(te)?!1:c:Ce(te)||c,ie=!!(E&&r&&L&&J),oe=Ce(G.isValidating)?ie:G.isValidating,de=Ce(G.isLoading)?ie:G.isLoading,Q=i.useCallback(async V=>{const D=j.current;if(!E||!D||C.current||I().isPaused())return!1;let le,H,ae=!0;const ke=V||{},ne=!y[E]||!ke.dedupe,Y=()=>Fa?!C.current&&E===w.current&&$.current:E===w.current,Z={isValidating:!1,isLoading:!1},N=()=>{_(Z)},W=()=>{const ye=y[E];ye&&ye[1]===H&&delete y[E]},fe={isValidating:!0};Ce(R().data)&&(fe.isLoading=!0);try{if(ne&&(_(fe),o.loadingTimeout&&Ce(R().data)&&setTimeout(()=>{ae&&Y()&&I().onLoadingSlow(E,o)},o.loadingTimeout),y[E]=[D(b),ta()]),[le,H]=y[E],le=await le,ne&&setTimeout(W,o.dedupingInterval),!y[E]||y[E][1]!==H)return ne&&Y()&&I().onDiscarded(E),!1;Z.error=Ge;const ye=v[E];if(!Ce(ye)&&(H<=ye[0]||H<=ye[1]||ye[1]===0))return N(),ne&&Y()&&I().onDiscarded(E),!1;const re=R().data;Z.data=s(re,le)?re:le,ne&&Y()&&I().onSuccess(le,E,o)}catch(ye){W();const re=I(),{shouldRetryOnError:je}=re;re.isPaused()||(Z.error=ye,ne&&Y()&&(re.onError(ye,E,re),(je===!0||ct(je)&&je(ye))&&(!I().revalidateOnFocus||!I().revalidateOnReconnect||k())&&re.onErrorRetry(ye,E,re,me=>{const Se=m[E];Se&&Se[0]&&Se[0](Aa,me)},{retryCount:(ke.retryCount||0)+1,dedupe:!0})))}return ae=!1,N(),!0},[E,n]),ce=i.useCallback((...V)=>Qi(n,w.current,...V),[]);if(dn(()=>{j.current=r,x.current=o,Ce(se)||(K.current=se)}),dn(()=>{if(!E)return;const V=Q.bind(Ge,fn);let D=0;I().revalidateOnFocus&&(D=Date.now()+I().focusThrottleInterval);const H=Id(E,m,(ae,ke={})=>{if(ae==Gi){const ne=Date.now();I().revalidateOnFocus&&ne>D&&k()&&(D=ne+I().focusThrottleInterval,V())}else if(ae==Hi)I().revalidateOnReconnect&&k()&&V();else{if(ae==qi)return Q();if(ae==Aa)return Q(ke)}});return C.current=!1,w.current=E,$.current=!0,_({_k:b}),J&&(y[E]||(Ce(te)||Ar?V():fd(V))),()=>{C.current=!0,H()}},[E]),dn(()=>{let V;function D(){const H=ct(p)?p(R().data):p;H&&V!==-1&&(V=setTimeout(le,H))}function le(){!R().error&&(d||I().isVisible())&&(u||I().isOnline())?Q(fn).then(D):D()}return D(),()=>{V&&(clearTimeout(V),V=-1)}},[p,d,u,E]),i.useDebugValue(ee),a&&Ce(te)&&E){if(!Fa&&Ar)throw new Error("Fallback data is required when using Suspense in SSR.");j.current=r,x.current=o,C.current=!1;const V=S[E];if(!Ce(V)){const D=ce(V);hn(D)}if(Ce(U)){const D=Q(fn);Ce(ee)||(D.status="fulfilled",D.value=!0),hn(D)}else throw U}return{mutate:ce,get data(){return z.data=!0,ee},get error(){return z.error=!0,U},get isValidating(){return z.isValidating=!0,oe},get isLoading(){return z.isLoading=!0,de}}},Ne=Rd(Td);async function q(t){if(!t.ok){let o=`HTTP ${t.status}: ${t.statusText}`;try{const n=await t.json();n.message?o=n.message:n.errors&&n.errors.length>0&&(o=n.errors[0].message||o)}catch{}throw new Error(o)}return{data:(await t.json()).data}}function ec(t){const{client:r}=Fe(),o=i.useCallback(async()=>{const c=await r(`/api/agent/contexts?token=${encodeURIComponent(t)}`,{method:"GET"});return(await q(c)).data},[r,t]),{data:n,error:s,mutate:a}=Ne(t?`wacht-agent-sessions:${t}`:null,o,{revalidateOnFocus:!1}),h=i.useCallback(async c=>{const p=new FormData;p.append("title",c.title),c.system_instructions&&p.append("system_instructions",c.system_instructions);const d=await r(`/api/agent/contexts?token=${encodeURIComponent(t)}`,{method:"POST",body:p}),u=await q(d);return await a(g=>g&&{...g,data:[u.data,...g.data]}),u.data},[r,t,a]),f=i.useCallback(async c=>{await r(`/api/agent/contexts/${c}/delete?token=${encodeURIComponent(t)}`,{method:"POST"}),await a(p=>p&&{...p,data:p.data.filter(d=>d.id!==c)})},[r,t,a]);return{sessions:(n==null?void 0:n.data)||[],loading:!n&&!s,error:s,createSession:h,deleteSession:f,refetch:async()=>{await a()}}}const tc=i.createContext(void 0);function Ho(){const t=i.useContext(tc);if(!t)throw new Error("useAgentConversationContext must be used within AgentConversationProvider");return t}function Od({children:t,agentName:r,token:o,platformAdapter:n,defaultSessionId:s,onSessionCreated:a,onSessionDeleted:h,onError:f}){const[c,p]=i.useState(s?{id:s,title:"Conversation",status:"idle",last_activity_at:new Date().toISOString(),created_at:new Date().toISOString()}:null),[d,u]=i.useState(!1),{sessions:g,loading:m,error:v,createSession:y,deleteSession:S,refetch:E}=ec(o);i.useEffect(()=>{if(s&&g.length>0){const j=g.find(x=>x.id===s);j&&p(j)}},[s,g]);const b=i.useCallback(j=>{p(j),u(!1)},[]),$=i.useCallback(async j=>{try{const x=j||`Chat ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,I=await y({title:x});return p(I),a==null||a(I),I}catch(x){const I=x instanceof Error?x.message:"Failed to create session";throw f==null||f(I),x}},[y,a,f]),C=i.useCallback(async j=>{try{await S(j),(c==null?void 0:c.id)===j&&p(null),h==null||h(j)}catch(x){const I=x instanceof Error?x.message:"Failed to delete session";throw f==null||f(I),x}},[S,c,h,f]),w={agentName:r,token:o,platformAdapter:n,sessions:g,selectedSession:c,loadingSessions:m,sessionError:v,selectSession:b,createSession:$,deleteSession:C,refreshSessions:E,showHistory:d,setShowHistory:u,onSessionCreated:a,onSessionDeleted:h,onError:f};return e.jsx(tc.Provider,{value:w,children:t})}var rc=(t=>(t.XOauth="x_oauth",t.GithubOauth="github_oauth",t.GitlabOauth="gitlab_oauth",t.GoogleOauth="google_oauth",t.FacebookOauth="facebook_oauth",t.MicrosoftOauth="microsoft_oauth",t.LinkedinOauth="linkedin_oauth",t.DiscordOauth="discord_oauth",t.AppleOauth="apple_oauth",t))(rc||{});function Md(t,r){const o={username:Ld(t,r),email:Ad(t,r),phone:Dd(t,r),email_otp:Fd(t,r),magic_link:Nd(t,r),oauth:Bd(t),generic:Ud(t,r)};return function(s){return o[s]}}function Ld(t,r){return async({username:o,password:n})=>{var f,c;const s=new FormData;s.append("strategy","plain_username"),s.append("username",o),s.append("password",n);const a=await t("/auth/signin",{method:"POST",body:s}),h=await q(a);return"data"in h&&((c=(f=h.data)==null?void 0:f.signin_attempts)!=null&&c.length)&&r(h.data.signin_attempts.at(-1)||null),h}}function Ad(t,r){return async({email:o,password:n})=>{var f,c;const s=new FormData;s.append("strategy","plain_email"),s.append("email",o),s.append("password",n);const a=await t("/auth/signin",{method:"POST",body:s}),h=await q(a);return"data"in h&&((c=(f=h.data)==null?void 0:f.signin_attempts)!=null&&c.length)&&r(h.data.signin_attempts.at(-1)||null),h}}function Dd(t,r){return async({phone:o})=>{var h,f;const n=new FormData;n.append("strategy","phone_otp"),n.append("phone",o);const s=await t("/auth/signin",{method:"POST",body:n}),a=await q(s);return"data"in a&&((f=(h=a.data)==null?void 0:h.signin_attempts)!=null&&f.length)&&r(a.data.signin_attempts.at(-1)||null),a}}function Fd(t,r){return async({email:o})=>{var h,f;const n=new FormData;n.append("strategy","email_otp"),n.append("email",o);const s=await t("/auth/signin",{method:"POST",body:n}),a=await q(s);return"data"in a&&((f=(h=a.data)==null?void 0:h.signin_attempts)!=null&&f.length)&&r(a.data.signin_attempts.at(-1)||null),a}}function Nd(t,r){return async({email:o})=>{var h,f;const n=new FormData;n.append("strategy","magic_link"),n.append("email",o);const s=await t("/auth/signin",{method:"POST",body:n}),a=await q(s);return"data"in a&&((f=(h=a.data)==null?void 0:h.signin_attempts)!=null&&f.length)&&r(a.data.signin_attempts.at(-1)||null),a}}function Bd(t){return async({provider:r,redirectUri:o})=>{const n=new URLSearchParams({provider:r});o&&n.append("redirect_uri",o);const s=await t(`/auth/oauth2/init?${n.toString()}`,{method:"POST"}),a=await q(s);return"data"in a&&a.data.oauth_url&&(window.location.href=a.data.oauth_url),a}}function Ud(t,r){return async({email:o,username:n,password:s,phone:a,strategy:h,token:f})=>{var u,g;const c=new FormData;h&&c.append("strategy",h),o&&c.append("email",o),n&&c.append("username",n),s&&c.append("password",s),a&&c.append("phone",a),f&&c.append("token",f);const p=await t("/auth/signin",{method:"POST",body:c}),d=await q(p);return"data"in d&&((g=(u=d.data)==null?void 0:u.signin_attempts)!=null&&g.length)&&r(d.data.signin_attempts.at(-1)||null),d}}function oc(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(null);return r?{loading:!0,signIn:null,signinAttempt:null,discardSignInAttempt:()=>{n(null)},setSignInAttempt:n}:{loading:!1,signinAttempt:o,signIn:{createStrategy:Md(t,n),completeVerification:async s=>{var c,p;const a=new FormData;a.append("verification_code",s);const h=await t(`/auth/attempt-verification?attempt_identifier=${o==null?void 0:o.id}&identifier_type=signin`,{method:"POST",body:a}),f=await q(h);if("data"in f&&((p=(c=f.data)==null?void 0:c.signin_attempts)!=null&&p.length)){const d=f.data.signin_attempts.at(-1);return n(d||null),f.data}else throw new Error("Verification failed")},prepareVerification:async s=>{var f;const a=new URL("/auth/prepare-verification",window.location.origin);a.searchParams.set("attempt_identifier",((f=o==null?void 0:o.id)==null?void 0:f.toString())||""),a.searchParams.set("strategy",s.strategy),a.searchParams.set("identifier_type","signin"),s.strategy==="phone_otp"&&s.lastDigits?a.searchParams.set("last_digits",s.lastDigits):(s.strategy==="email_otp"&&s.redirectUri||s.strategy==="magic_link"&&s.redirectUri)&&a.searchParams.set("redirect_uri",s.redirectUri);const h=await t(a.pathname+a.search,{method:"POST"});return q(h)},completeProfile:async s=>{var c;if(!o)throw new Error("No signin attempt found");const a=new FormData;for(const[p,d]of Object.entries(s))d&&a.append(p,d);const h=await t(`/auth/complete-profile?attempt_id=${o.id}`,{method:"POST",body:a}),f=await q(h);if("data"in f&&f.data){const p=(c=f.data.signin_attempts)==null?void 0:c.find(d=>d.id===o.id);return p&&n(p),f.data}else throw new Error("Profile completion failed")},identify:async s=>{const a=await t("/auth/identify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:s})});if(!a.ok){const h=await a.json().catch(()=>({}));throw new Error(h.message||"Failed to identify user")}return a.json()},initEnterpriseSso:async(s,a)=>{const h=new URLSearchParams({connection_id:s});a&&h.append("redirect_uri",a);const f=await t(`/auth/sso/login?${h.toString()}`,{method:"POST"});if(!f.ok){const c=await f.json().catch(()=>({}));throw new Error(c.message||"Failed to initiate SSO")}return f.json()}},discardSignInAttempt:()=>{n(null)},setSignInAttempt:n}}function Dr(t){const{loading:r,signIn:o,signinAttempt:n,discardSignInAttempt:s,setSignInAttempt:a}=oc();if(r)return{loading:!0,signIn:null,signinAttempt:null,discardSignInAttempt:s,setSignInAttempt:a};const h=(()=>{switch(t){case"username":return o.createStrategy("username");case"email":return o.createStrategy("email");case"phone":return o.createStrategy("phone");case"email_otp":return o.createStrategy("email_otp");case"magic_link":return o.createStrategy("magic_link");case"oauth":return o.createStrategy("oauth");case"generic":return o.createStrategy("generic");default:throw new Error("Invalid sign-in strategy")}})();return{loading:!1,signinAttempt:n,signIn:{create:h,completeVerification:o.completeVerification,prepareVerification:o.prepareVerification,completeProfile:o.completeProfile,identify:o.identify,initEnterpriseSso:o.initEnterpriseSso},discardSignInAttempt:s,setSignInAttempt:a}}function Wd(t,r,o){return{create:async n=>{var f,c,p;const s=new FormData;for(const[d,u]of Object.entries(n))s.append(d,u);const a=await t("/auth/signup",{method:"POST",body:s}),h=await q(a);return"data"in h&&((c=(f=h.data)==null?void 0:f.signup_attempts)!=null&&c.length)&&o(((p=h.data.signup_attempts)==null?void 0:p.at(-1))||null),h},prepareVerification:async n=>{var h;const s=new URL("/auth/prepare-verification",window.location.origin);s.searchParams.set("attempt_identifier",((h=r==null?void 0:r.id)==null?void 0:h.toString())||""),s.searchParams.set("strategy",n.strategy),s.searchParams.set("identifier_type","signup"),n.strategy==="phone_otp"&&n.lastDigits?s.searchParams.set("last_digits",n.lastDigits):n.strategy==="email_otp"&&n.redirectUri&&s.searchParams.set("redirect_uri",n.redirectUri);const a=await t(s.pathname+s.search,{method:"POST"});return q(a)},completeVerification:async n=>{var f,c;const s=new FormData;s.append("verification_code",n);const a=await t(`/auth/attempt-verification?attempt_identifier=${r==null?void 0:r.id}&identifier_type=signup`,{method:"POST",body:s}),h=await q(a);return"data"in h&&((c=(f=h.data)==null?void 0:f.signup_attempts)!=null&&c.length)&&o(h.data.signup_attempts.at(-1)||null),h},validateDeploymentInvitation:async n=>{try{const s=await t(`/deployment/invitations/validate?token=${encodeURIComponent(n)}`,{method:"GET"}),a=await q(s);return"data"in a&&a.data?a.data:{valid:!1,message:"Failed to validate invitation",error_code:"VALIDATION_ERROR"}}catch(s){return{valid:!1,message:s.message||"Failed to validate invitation",error_code:"NETWORK_ERROR"}}}}}function nc(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(null);return r?{loading:!0,signUp:null,signupAttempt:null,discardSignupAttempt:()=>{n(null)}}:{loading:!1,signupAttempt:o,discardSignupAttempt:()=>{n(null)},signUp:Wd(t,o,n)}}const Ve=()=>{const{adapter:t,deployment:r}=ve(),o=t.useNavigate(),n=(f,c)=>{o?o(f,c):window.location.href=f};return{navigate:n,navigateToSignIn:f=>{if(!r)return;const c=f||window.location.href,p=new URLSearchParams;p.set("redirect_uri",c),(r==null?void 0:r.mode)==="staging"&&p.set("dev_session",localStorage.getItem("__dev_session__")??""),n(`${r.ui_settings.sign_in_page_url}?${p.toString()}`,{replace:!0})},navigateToAccountSelection:f=>{if(!r)return;const c=f||window.location.href,p=new URLSearchParams;p.set("redirect_uri",c),(r==null?void 0:r.mode)==="staging"&&p.set("dev_session",localStorage.getItem("__dev_session__")??""),n(`https://${r.frontend_host}?${p.toString()}`,{replace:!0})},navigateToSignUp:f=>{if(!r)return;const c=f||window.location.href,p=new URLSearchParams;p.set("redirect_uri",c),(r==null?void 0:r.mode)==="staging"&&p.set("dev_session",localStorage.getItem("__dev_session__")??""),n(`${r.ui_settings.sign_up_page_url}?${p.toString()}`,{replace:!0})}}};async function Vd(t){const r=await t("/session",{method:"GET"});return(await q(r)).data}async function Gd(t,r){const o=await t(`/session/switch-sign-in?sign_in_id=${r}`,{method:"POST"});return q(o)}async function Hd(t,r){const o=r?`/session/sign-out?sign_in_id=${r}`:"/session/sign-out",n=await t(o,{method:"POST"});return q(n)}async function qd(t,r){const o=await t(`/session/switch-organization${r?`?organization_id=${r}`:""}`,{method:"POST"});return q(o)}async function Yd(t,r){const o=await t(`/session/switch-workspace?workspace_id=${r}`,{method:"POST"});return q(o)}const ra=new Map,Tr=new Map;function $t(){ra.clear(),Tr.clear()}async function Zd(t,r){const o=await t(`/session/token${r?`?template=${r}`:""}`);return q(o)}function Be(){const{client:t,loading:r}=Fe(),{deployment:o}=ve(),{navigate:n}=Ve(),{cache:s}=Ji(),{data:a,error:h,mutate:f,isLoading:c}=Ne(r?null:"/session",()=>Vd(t),{refreshInterval:3e4,revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,dedupingInterval:5e3}),p=i.useCallback(async()=>{await f(void 0,{revalidate:!0})},[f]),d=i.useCallback(async(u="default")=>{if(!a)throw new Error("no session");const g=ra.get(u);if(g&&g.expires>Date.now())return(g==null?void 0:g.token)||"";Tr.get(u)||Tr.set(u,Zd(t,u));const m=await Tr.get(u);return Tr.delete(u),ra.set(u,m.data),m.data.token},[t,a==null?void 0:a.active_signin]);return r||!a||c?{loading:!0,error:h,session:null,switchSignIn:null,switchOrganization:null,switchWorkspace:null,signOut:null,getToken:null,refetch:p}:{loading:c,error:h,session:a,switchSignIn:async u=>{await Gd(t,u),await f(void 0,{revalidate:!0})},signOut:async u=>{await Hd(t,u);const g=["/session","/user","/me/signins","/me/organization-memberships","/me/workspace-memberships","wacht-notifications:channel-counts"],m=["wacht-notifications:","wacht-agent-sessions:","wacht-agent-contexts:","wacht-org-domains:","wacht-api-workspaces:","wacht-api-organizations:"];if(s instanceof Map){const v=Array.from(s.keys());for(const y of v){let S=!1;(g.includes(y)||typeof y=="string"&&m.some(E=>y.startsWith(E)))&&(S=!0),S&&s.delete(y)}}$t(),await f(void 0,{revalidate:!0}),o!=null&&o.ui_settings&&(u&&o.ui_settings.after_sign_out_one_page_url?n(o.ui_settings.after_sign_out_one_page_url):!u&&o.ui_settings.after_sign_out_all_page_url&&n(o.ui_settings.after_sign_out_all_page_url))},switchOrganization:async u=>{await qd(t,u),$t(),await f(void 0,{revalidate:!0})},switchWorkspace:async u=>{await Yd(t,u),$t(),await f(void 0,{revalidate:!0})},getToken:d,refetch:p}}const qo=()=>{const{organizationMemberships:t,refetch:r,loading:o}=vt(),{client:n}=Fe(),{refetch:s}=Be(),a=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/roles`,{method:"GET"}))).data,[n]),h=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/members`,{method:"GET"}))).data,[n]),f=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/invitations`,{method:"GET"}))).data,[n]),c=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/domains`,{method:"GET"}))).data,[n]),p=i.useCallback(async(P,z)=>{await n(`/organizations/${P.id}/members/${z.id}/remove`,{method:"POST"}),await r()},[r,n]),d=i.useCallback(async P=>{const z=new FormData;z.append("name",P.name),P.image&&z.append("image",P.image),P.description&&z.append("description",P.description);const T=await q(await n("/organizations",{method:"POST",body:z}));return $t(),await r(),await s(),T},[s,r,n]),u=i.useCallback(async(P,z)=>{const T=Object.entries(z).reduce((F,[G,L])=>(L&&F.append(G,L),F),new FormData),M=await q(await n(`/organizations/${P.id}/update`,{method:"POST",body:T}));return await r(),M},[r,n]),g=i.useCallback(async(P,z)=>{await n(`/organizations/${P.id}/roles/${z.id}/remove`,{method:"POST"})},[n]),m=i.useCallback(async(P,z)=>{const T=new FormData;return T.append("domain",z.fqdn),await q(await n(`/organizations/${P.id}/domains`,{method:"POST",body:T}))},[n]),v=i.useCallback(async(P,z)=>await q(await n(`/organizations/${P.id}/domains/${z.id}/verify`,{method:"POST"})),[n]),y=i.useCallback(async(P,z)=>await q(await n(`/organizations/${P.id}/domains/${z.id}/delete`,{method:"POST"})),[n]),S=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/enterprise-connections`,{method:"GET"}))).data,[n]),E=i.useCallback(async(P,z)=>{const T=new FormData;return T.append("protocol",z.protocol),T.append("idp_entity_id",z.idp_entity_id),T.append("idp_sso_url",z.idp_sso_url),T.append("idp_certificate",z.idp_certificate),z.domain_id&&T.append("domain_id",z.domain_id),(await q(await n(`/organizations/${P.id}/enterprise-connections`,{method:"POST",body:T}))).data},[n]),b=i.useCallback(async(P,z,T)=>{const M=new FormData;return T.idp_entity_id&&M.append("idp_entity_id",T.idp_entity_id),T.idp_sso_url&&M.append("idp_sso_url",T.idp_sso_url),T.idp_certificate&&M.append("idp_certificate",T.idp_certificate),T.domain_id&&M.append("domain_id",T.domain_id),(await q(await n(`/organizations/${P.id}/enterprise-connections/${z}/update`,{method:"POST",body:M}))).data},[n]),$=i.useCallback(async(P,z)=>{await n(`/organizations/${P.id}/enterprise-connections/${z}/delete`,{method:"POST"})},[n]),C=i.useCallback(async(P,z)=>{const T=new FormData;return T.append("name",z.name),z.permissions&&z.permissions.forEach((F,G)=>{T.append(`permissions[${G}]`,F)}),await q(await n(`/organizations/${P.id}/roles`,{method:"POST",body:T}))},[n]),w=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/leave`,{method:"POST"}))).data,[n]),j=i.useCallback(async P=>{const z=await q(await n(`/organizations/${P.id}/delete`,{method:"POST"}));return $t(),await r(),await s(),z.data},[n,r,s]),x=i.useCallback(async(P,z,T)=>(await q(await n(`/organizations/${P.id}/members/${z.id}/roles/${T.id}/add`,{method:"POST"}))).data,[n]),I=i.useCallback(async(P,z,T)=>(await q(await n(`/organizations/${P.id}/members/${z.id}/roles/${T.id}/remove`,{method:"POST"}))).data,[n]),k=i.useCallback(async(P,z)=>{var F,G;const T=new FormData;return T.append("email",z.email),T.append("role_id",z.organizationRole.id),(F=z.workspace)!=null&&F.id&&T.append("workspace_id",z.workspace.id),(G=z.workspaceRole)!=null&&G.id&&T.append("workspace_role_id",z.workspaceRole.id),(await q(await n(`/organizations/${P.id}/invitations`,{method:"POST",body:T}))).data},[n]),R=i.useCallback(async(P,z)=>(await q(await n(`/organizations/${P.id}/invitations/${z.id}/remove`,{method:"POST"}))).data,[n]),_=i.useCallback(async(P,z)=>(await q(await n(`/organizations/${P.id}/invitations/${z.id}/resend`,{method:"POST"}))).data,[n]);return{organizations:i.useMemo(()=>t==null?void 0:t.map(P=>P.organization),[t]),loading:o,error:null,refetch:r,leaveOrganization:w,getOrganizationRoles:a,getOrganizationMembers:h,removeOrganizationMember:p,createOrganization:d,getOrganizationInvitations:f,getOrganizationDomains:c,addOrganizationDomain:m,verifyOrganizationDomain:v,removeOrganizationDomain:y,addRoleToOrganizationMember:x,removeRoleFromOrganizationMember:I,inviteOrganizationMember:k,discardOrganizationInvitation:R,resendOrganizationInvitation:_,updateOrganization:u,addRole:C,removeOrganizationRoles:g,deleteOrganization:j,getEnterpriseConnections:S,createEnterpriseConnection:E,updateEnterpriseConnection:b,deleteEnterpriseConnection:$}},qe=()=>{const{loading:t,error:r,refetch:o,getOrganizationMembers:n,getOrganizationRoles:s,leaveOrganization:a,removeOrganizationMember:h,getOrganizationInvitations:f,getOrganizationDomains:c,removeOrganizationDomain:p,addOrganizationDomain:d,verifyOrganizationDomain:u,addRoleToOrganizationMember:g,removeRoleFromOrganizationMember:m,inviteOrganizationMember:v,discardOrganizationInvitation:y,resendOrganizationInvitation:S,updateOrganization:E,removeOrganizationRoles:b,getEnterpriseConnections:$,createEnterpriseConnection:C,updateEnterpriseConnection:w,deleteEnterpriseConnection:j}=qo(),{session:x,error:I,loading:k}=Be(),{organizationMemberships:R}=vt(),_=i.useMemo(()=>{var B;return((B=R==null?void 0:R.find(V=>{var D;return V.id===((D=x==null?void 0:x.active_signin)==null?void 0:D.active_organization_membership_id)}))==null?void 0:B.organization)||null},[R,x]),O=i.useCallback(async B=>_?await E(_,B):[],[_,E]),P=i.useCallback(async()=>_?await n(_):[],[_,n]),z=i.useCallback(async()=>_?await s(_):[],[_,s]),T=i.useCallback(async B=>_?await h(_,B):[],[_,h]),M=i.useCallback(async B=>_?await b(_,B):void 0,[_,b]),F=i.useCallback(async()=>_?await c(_):[],[_,c]),G=i.useCallback(async B=>_?await d(_,B):void 0,[_,d]),L=i.useCallback(async B=>_?await u(_,B):void 0,[_,u]),A=i.useCallback(async B=>_?await p(_,B):void 0,[_,p]),se=i.useCallback(async(B,V)=>_?await g(_,B,V):void 0,[_,g]),te=i.useCallback(async(B,V)=>_?await m(_,B,V):void 0,[_,m]),U=i.useCallback(async B=>_?await v(_,B):void 0,[_,v]),K=i.useCallback(async B=>_?await y(_,B):void 0,[_,y]),ee=i.useCallback(async B=>_?await S(_,B):void 0,[_,S]),J=i.useCallback(async()=>{_&&await a(_)},[_,a]),ie=i.useCallback(async()=>_?await f(_):[],[_,f]),oe=i.useCallback(async()=>_?await $(_):[],[_,$]),de=i.useCallback(async B=>{if(_)return await C(_,B)},[_,C]),Q=i.useCallback(async(B,V)=>{if(_)return await w(_,B,V)},[_,w]),ce=i.useCallback(async B=>{_&&await j(_,B)},[_,j]);return k||t?{activeOrganization:null,loading:!0,error:I||r,updateOrganization:null,getRoles:null,getMembers:null,getDomains:null,addDomain:null,verifyDomain:null,removeDomain:null,removeRole:null,getInvitations:null,removeMember:null,addMemberRole:null,removeMemberRole:null,inviteMember:null,discardInvitation:null,resendInvitation:null,leave:null,getEnterpriseConnections:null,createEnterpriseConnection:null,updateEnterpriseConnection:null,deleteEnterpriseConnection:null}:{activeOrganization:_,loading:!1,refetch:o,getRoles:z,updateOrganization:O,getMembers:P,getDomains:F,addDomain:G,verifyDomain:L,removeDomain:A,getInvitations:ie,removeMember:T,leave:J,removeRole:M,addMemberRole:se,removeMemberRole:te,inviteMember:U,discardInvitation:K,resendInvitation:ee,getEnterpriseConnections:oe,createEnterpriseConnection:de,updateEnterpriseConnection:Q,deleteEnterpriseConnection:ce,error:null}};async function Qd(t){return(await q(await t("/me/organization-memberships"))).data}const vt=()=>{const{client:t,loading:r}=Fe(),{data:o,isLoading:n,error:s,mutate:a}=Ne(r?null:"/me/organization-memberships",()=>Qd(t),{refreshInterval:3e4,revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,dedupingInterval:5e3}),h=i.useCallback(async()=>{await a(void 0,{revalidate:!0})},[a]);return{organizationMemberships:o,loading:r||n,error:s,refetch:h}};async function Kd(t){return(await q(await t("/me/workspace-memberships"))).data}async function Xd(t,r,o){return(await q(await t(`/workspaces/${r}/members/${o}/remove`,{method:"POST"}))).data}const Yo=()=>{const{client:t,loading:r}=Fe(),{deployment:o}=ve(),{data:n,isLoading:s,error:a,mutate:h}=Ne(!r&&(o!=null&&o.b2b_settings.workspaces_enabled)?"/me/workspace-memberships":null,()=>Kd(t),{refreshInterval:3e4,revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,dedupingInterval:5e3}),f=i.useCallback(async()=>{await h(void 0,{revalidate:!0})},[h]);return{workspaceMemberships:n,loading:r||s,error:a,refetch:f}},bt=()=>{const{workspaceMemberships:t,refetch:r,loading:o,error:n}=Yo(),{client:s}=Fe(),a=i.useMemo(()=>t==null?void 0:t.map(b=>({...b.workspace,organization:b.organization,eligibility_restriction:b.eligibility_restriction})),[t]),h=i.useCallback(async(b,$,C,w)=>{const j=new FormData;j.append("name",$),C&&j.append("image",C),w&&j.append("description",w),j.append("organization_id",b);const x=await q(await s("/workspaces",{method:"POST",body:j}));return $t(),await r(),x.data},[s,r]),f=i.useCallback(async(b,$)=>{const C=await Xd(s,b,$);return await r(),C},[s,r]),c=i.useCallback(async(b,$)=>{const C=new FormData;$.name&&C.append("name",$.name),$.description&&C.append("description",$.description),$.image&&C.append("image",$.image),$.enforce_2fa!==void 0&&C.append("enforce_2fa",String($.enforce_2fa)),$.enable_ip_restriction!==void 0&&C.append("enable_ip_restriction",String($.enable_ip_restriction)),$.whitelisted_ips&&$.whitelisted_ips.forEach(j=>C.append("whitelisted_ips",j));const w=await q(await s(`/workspaces/${b.id}/update`,{method:"POST",body:C}));return await r(),w.data},[s,r]),p=i.useCallback(async b=>{const $=await q(await s(`/workspaces/${b.id}/delete`,{method:"POST"}));return $t(),await r(),$.data},[s,r]),d=i.useCallback(async b=>(await q(await s(`/workspaces/${b.id}/members`,{method:"GET"}))).data,[s]),u=i.useCallback(async b=>(await q(await s(`/workspaces/${b.id}/roles`,{method:"GET"}))).data,[s]),g=i.useCallback(async(b,$,C)=>(await q(await s(`/workspaces/${b.id}/roles`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:$,permissions:C})}))).data,[s]),m=i.useCallback(async(b,$)=>(await q(await s(`/workspaces/${b.id}/roles/${$.id}/delete`,{method:"POST"}))).data,[s]),v=i.useCallback(async(b,$,C)=>(await q(await s(`/workspaces/${b.id}/members`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:$,role_id:C})}))).data,[s]),y=i.useCallback(async(b,$)=>{const C=await q(await s(`/workspaces/${b.id}/members/${$}/remove`,{method:"POST"}));return await r(),C.data},[s,r]),S=i.useCallback(async(b,$,C)=>(await q(await s(`/workspaces/${b.id}/members/${$}/roles/${C}/add`,{method:"POST"}))).data,[s]),E=i.useCallback(async(b,$,C)=>(await q(await s(`/workspaces/${b.id}/members/${$}/roles/${C}/remove`,{method:"POST"}))).data,[s]);return{workspaces:a||[],loading:o,error:n,refetch:r,leaveWorkspace:f,createWorkspace:h,updateWorkspace:c,deleteWorkspace:p,getWorkspaceMembers:d,getWorkspaceRoles:u,createWorkspaceRole:g,deleteWorkspaceRole:m,inviteWorkspaceMember:v,removeWorkspaceMember:y,addWorkspaceMemberRole:S,removeWorkspaceMemberRole:E}},Rt=()=>{const{refetch:t,loading:r,error:o,leaveWorkspace:n,updateWorkspace:s,deleteWorkspace:a,getWorkspaceMembers:h,getWorkspaceRoles:f,createWorkspaceRole:c,deleteWorkspaceRole:p,inviteWorkspaceMember:d,removeWorkspaceMember:u,addWorkspaceMemberRole:g,removeWorkspaceMemberRole:m}=bt(),{workspaceMemberships:v}=Yo(),{session:y,loading:S,error:E}=Be(),b=i.useMemo(()=>{var M;return((M=v==null?void 0:v.find(F=>{var G;return F.id===((G=y==null?void 0:y.active_signin)==null?void 0:G.active_workspace_membership_id)}))==null?void 0:M.workspace)||null},[v,y]),$=i.useCallback(async()=>{var M;if(!(!b||!((M=y==null?void 0:y.active_signin)!=null&&M.user_id)))return await n(b.id,y.active_signin.user_id)},[b,n,y]),C=i.useCallback(async M=>{if(b)return await s(b,M)},[b,s]),w=i.useCallback(async()=>{if(b)return await a(b)},[b,a]),j=i.useCallback(async()=>b?await h(b):[],[b,h]),x=i.useCallback(async()=>b?await f(b):[],[b,f]),I=i.useCallback(async(M,F)=>{if(b)return await c(b,M,F)},[b,c]),k=i.useCallback(async M=>{if(b)return await p(b,M)},[b,p]),R=i.useCallback(async(M,F)=>{if(b)return await d(b,M,F)},[b,d]),_=i.useCallback(async M=>{if(b)return await u(b,M)},[b,u]),O=i.useCallback(async(M,F)=>{if(b)return await g(b,M,F)},[b,g]),P=i.useCallback(async(M,F)=>{if(b)return await m(b,M,F)},[b,m]),z=r||S,T=o||E;return z?{activeWorkspace:null,loading:!0,error:T,refetch:t,leave:null,updateWorkspace:null,deleteWorkspace:null,getMembers:null,getRoles:null,createRole:null,deleteRole:null,inviteMember:null,removeMember:null,addMemberRole:null,removeMemberRole:null}:{activeWorkspace:b,loading:!1,error:T,refetch:t,leave:$,updateWorkspace:C,deleteWorkspace:w,getMembers:j,getRoles:x,createRole:I,deleteRole:k,inviteMember:R,removeMember:_,addMemberRole:O,removeMemberRole:P}},Jd=async t=>(await q(await t("/me"))).data,eu=async t=>(await q(await t("/me/signins"))).data;function rr(){const{client:t,loading:r}=Fe(),{data:o,error:n,isLoading:s,mutate:a}=Ne(r?null:"/user",()=>Jd(t)),h=async z=>{const T=new FormData;for(const[F,G]of Object.entries(z))G!=null&&G!==""&&T.append(F,String(G));const M=await q(await t("/me",{method:"POST",body:T}));return a(),M},f=async()=>await q(await t("/me/email-addresses",{method:"GET"})),c=async z=>await q(await t(`/me/email-addresses/${z}`,{method:"GET"})),p=async z=>{const T=new FormData;return T.append("email",z),await q(await t("/me/email-addresses",{method:"POST",body:T}))},d=async z=>await q(await t(`/me/email-addresses/${z}/delete`,{method:"POST"})),u=async z=>await q(await t(`/me/email-addresses/${z}/prepare-verification`,{method:"POST"})),g=async(z,T)=>await q(await t(`/me/email-addresses/${z}/attempt-verification?code=${T}`,{method:"POST"})),m=async(z,T)=>{const M=new FormData;return M.append("phone_number",z),M.append("country_code",T),await q(await t("/me/phone-numbers",{method:"POST",body:M}))},v=async z=>await q(await t(`/me/phone-numbers/${z}/delete`,{method:"POST"})),y=async z=>await q(await t(`/me/phone-numbers/${z}/prepare-verification`,{method:"POST"})),S=async(z,T)=>{const M=new FormData;return M.append("code",T),await q(await t(`/me/phone-numbers/${z}/attempt-verification`,{method:"POST",body:M}))},E=async z=>{const T=await q(await t(`/me/phone-numbers/${z}/make-primary`,{method:"POST"}));return a(),T},b=async z=>await q(await t(`/me/email-addresses/${z}/make-primary`,{method:"POST"})),$=async()=>(await q(await t("/me/authenticator",{method:"POST"}))).data,C=async(z,T)=>{const M=new FormData;return M.append("authenticator_id",z),T.forEach(G=>{M.append("codes",G)}),await q(await t("/me/authenticator/attempt-verification",{method:"POST",body:M}))},w=async z=>await q(await t(`/me/authenticator/${z}/delete`,{method:"POST"})),j=async()=>(await q(await t("/me/backup-codes",{method:"POST"}))).data,x=async z=>{const T=new FormData;return T.append("file",z),await q(await t("/me/profile-picture",{method:"POST",body:T}))},I=async()=>(await q(await t("/me/backup-codes/regenerate",{method:"POST"}))).data,k=async(z,T)=>{const M=new FormData;return M.append("current_password",z),M.append("new_password",T),await q(await t("/me/update-password",{method:"POST",body:M}))},R=async z=>{const T=new FormData;T.append("current_password",z);const M=await q(await t("/me/remove-password",{method:"POST",body:T}));return a(),M},_=async z=>{const T=new FormData;return T.append("password",z),await q(await t("/me/account/delete",{method:"POST",body:T}))},O=async z=>await q(await t(`/me/social-connections/${z}/disconnect`,{method:"POST"})),P=async({provider:z,redirectUri:T})=>{var G;const M=new URLSearchParams({provider:z});T&&M.append("redirect_uri",T);const F=await q(await t(`/me/init-sso-connection?${M.toString()}`,{method:"POST"}));return"data"in F&&((G=F.data)!=null&&G.oauth_url)&&window.open(F.data.oauth_url,"_blank"),F};return{user:{...o,refetch:a},loading:r||s,error:n||null,updateProfile:h,getEmailAddresses:f,getEmailAddress:c,createEmailAddress:p,deleteEmailAddress:d,prepareEmailVerification:u,attemptEmailVerification:g,makeEmailPrimary:b,createPhoneNumber:m,deletePhoneNumber:v,preparePhoneVerification:y,attemptPhoneVerification:S,makePhonePrimary:E,setupAuthenticator:$,verifyAuthenticator:C,deleteAuthenticator:w,generateBackupCodes:j,regenerateBackupCodes:I,updateProfilePicture:x,disconnectSocialConnection:O,connectSocialAccount:P,updatePassword:k,removePassword:R,deleteAccount:_}}function ac(){const{client:t,loading:r}=Fe(),{data:o,error:n,isLoading:s,mutate:a}=Ne(r?null:"/me/signins",()=>eu(t));return{signins:o,error:n||null,removeSignin:async f=>await q(await t(`/me/signins/${f}/signout`,{method:"POST"})),refetch:a,loading:s||r}}function tu(){const{session:t,loading:r}=Be(),{loading:o,organizationMemberships:n}=vt(),{loading:s,workspaceMemberships:a}=Yo();if(r||o||s)return{loading:!0,orgMembership:null,workspaceMembership:null};const h=i.useMemo(()=>!t||!t.signins||t.signins.length===0?null:n==null?void 0:n.find(c=>{var p;return c.id===((p=t.active_signin)==null?void 0:p.active_organization_membership_id)}),[t]),f=i.useMemo(()=>!t||!t.signins||t.signins.length===0?null:a==null?void 0:a.find(c=>{var p;return c.id===((p=t.active_signin)==null?void 0:p.active_workspace_membership_id)}),[t]);return{loading:!1,orgMembership:h,workspaceMembership:f}}function sc(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(!1),s=async a=>{n(!0);try{const h=new FormData;for(const[p,d]of Object.entries(a))d&&h.append(p,d);const f=await t("/waitlist/join",{method:"POST",body:h});return await q(f)}finally{n(!1)}};return r?{loading:!0,joinWaitlist:null}:{loading:o,joinWaitlist:s}}function ic(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(!1),[s,a]=i.useState(null),[h,f]=i.useState(null),[c,p]=i.useState(null),[d,u]=i.useState(!1),[g,m]=i.useState(null);i.useEffect(()=>{if(d||r)return;const y=new URLSearchParams(window.location.search),S=y.get("code"),E=y.get("state"),b=y.get("error"),$=y.get("error_description");if(!S&&!b){u(!0);const C=new Error("No OAuth callback data found.");a(C);return}if(u(!0),n(!0),b){const C=$||b,w=new Error(`OAuth Error: ${C}`);a(w),n(!1);return}if(S&&E)v(S,E);else{const C=new Error("Missing required OAuth parameters");a(C),n(!1)}},[d,r]);const v=async(y,S)=>{try{let E,b;try{const w=S.split(".");if(w.length!==2)throw new Error("Invalid OAuth state format - missing signature");const j=w[0].replace(/-/g,"+").replace(/_/g,"/"),x=j.length%4?"=".repeat(4-j.length%4):"",k=atob(j+x).split("|")[0];if(k==="sign_in")E="/auth/oauth2/callback",b="GET";else if(k==="connect_social")E="/me/sso-connection-callback",b="POST";else throw new Error(`Unknown OAuth action: ${k}`)}catch(w){const j=w instanceof Error?w:new Error("Failed to parse OAuth state");a(new Error(`Invalid OAuth callback: ${j.message}. The authorization link may be expired or malformed. Please try signing in again.`)),n(!1);return}const $=await t(`${E}?code=${encodeURIComponent(y)}&state=${encodeURIComponent(S)}`,{method:b}),C=await q($);if("data"in C){const w=C.data.session,j=C.data.redirect_uri||null;if(f(w),p(j),w.signin_attempts&&w.signin_attempts.length>0){const x=w.signin_attempts.at(-1);x&&m(x)}}else{const w=new Error("SSO callback failed");a(w)}}catch(E){const b=E instanceof Error?E:new Error("Unknown error occurred");a(b)}finally{n(!1)}};return{loading:o,error:s,session:h,redirectUri:c,processed:d,signinAttempt:g}}function cc(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(!1),[s,a]=i.useState(null);return{loading:r||o,verifyMagicLink:async f=>{if(!f.token||!f.attempt)throw new Error("Invalid magic link parameters");n(!0),a(null);try{const c=new URL("/auth/verify-magic-link",window.location.origin);c.searchParams.set("token",f.token),c.searchParams.set("attempt",f.attempt),f.redirectUri&&c.searchParams.set("redirect_uri",f.redirectUri);const p=await t(c.pathname+c.search,{method:"GET"}),d=await q(p);return n(!1),a(!0),d}catch(c){throw n(!1),a(!1),c}},success:s}}function lc(){const[t,r]=i.useState({});return i.useEffect(()=>{const o=new URLSearchParams(window.location.search);r({token:o.get("token")||void 0,attempt:o.get("attempt")||void 0,redirectUri:o.get("redirect_uri")||void 0})},[]),t}function dc(){const{client:t,loading:r}=Fe();return{loading:r,forgotPassword:async a=>{const h=new FormData;h.append("email",a);const f=await t("/auth/forgot-password",{method:"POST",body:h});return await q(f)},verifyOtp:async(a,h)=>{const f=new FormData;f.append("email",a),f.append("otp",h);const c=await t("/auth/forgot-password",{method:"POST",body:f});return await q(c)},resetPassword:async(a,h)=>{const f=new FormData;f.append("token",a),f.append("password",h);const c=await t("/auth/reset-password",{method:"POST",body:f});return await q(c)}}}function uc({enabled:t=!0,channels:r,organizationIds:o,workspaceIds:n,onNotification:s,onError:a,reconnectDelay:h=1e3,maxReconnectAttempts:f=5}={}){const{session:c,loading:p}=Be(),{deployment:d,loading:u}=ve(),[g,m]=i.useState(!1),[v,y]=i.useState(null),S=i.useRef(null),E=i.useRef(null),b=i.useRef(0),$=i.useRef(null),C=i.useRef(s),w=i.useRef(a),j=i.useRef(r),x=i.useRef(o),I=i.useRef(n),k=i.useRef(h),R=i.useRef(f);C.current=s,w.current=a,j.current=r,x.current=o,I.current=n,k.current=h,R.current=f;const _=i.useCallback(()=>{E.current&&(clearTimeout(E.current),E.current=null),$.current&&(clearInterval($.current),$.current=null),S.current&&(S.current.close(),S.current=null)},[]),O=i.useCallback(async()=>{var G;if(!t||p||u||!c||!d)return;_();const T=new URL(d.backend_host),M=T.protocol==="https:"?"wss:":"ws:",F=new URL("/realtime/notifications",`${M}//${T.host}`);if(d.mode==="staging"){const L=localStorage.getItem("__dev_session__");L&&F.searchParams.set("__dev_session__",L)}j.current&&j.current.length>0&&j.current.forEach(L=>F.searchParams.append("channels",L)),x.current&&x.current.length>0&&x.current.forEach(L=>F.searchParams.append("organization_ids",L.toString())),I.current&&I.current.length>0&&I.current.forEach(L=>F.searchParams.append("workspace_ids",L.toString()));try{const L=new WebSocket(F.toString());S.current=L,L.onopen=()=>{m(!0),y(null),b.current=0,$.current=setInterval(()=>{L.readyState===WebSocket.OPEN&&L.send("ping")},3e4)},L.onmessage=A=>{var se,te;try{const U=JSON.parse(A.data);if(U.type==="notification"&&U.data)(se=C.current)==null||se.call(C,U.data);else if(U.type==="error"){const K=U.error||"Unknown error occurred";y(K),(te=w.current)==null||te.call(w,K)}else U.type}catch{}},L.onerror=()=>{var A;y("Connection error occurred"),(A=w.current)==null||A.call(w,"Connection error occurred")},L.onclose=A=>{var se;if(m(!1),$.current&&(clearInterval($.current),$.current=null),t&&A.code!==1e3&&b.current<R.current){b.current++;const te=k.current*Math.pow(2,b.current-1);E.current=setTimeout(()=>{O()},te)}else b.current>=R.current&&(y("Max reconnection attempts reached"),(se=w.current)==null||se.call(w,"Max reconnection attempts reached"))}}catch{y("Failed to connect"),(G=w.current)==null||G.call(w,"Failed to connect")}},[t,p,u,c,d,_]);i.useEffect(()=>(O(),()=>{_()}),[O,_]),i.useEffect(()=>{S.current&&S.current.readyState===WebSocket.OPEN&&O()},[r,o,n,O]);const P=i.useCallback(()=>{_(),m(!1)},[_]),z=i.useCallback(()=>{b.current=0,O()},[O]);return{isConnected:g,connectionError:v,disconnect:P,reconnect:z}}async function ru(t,r){const o=new URLSearchParams;r&&(r.limit&&o.append("limit",r.limit.toString()),r.offset&&o.append("offset",r.offset.toString()),r.channels&&r.channels.forEach(h=>o.append("channels",h)),r.organization_ids&&r.organization_ids.forEach(h=>o.append("organization_ids",h.toString())),r.workspace_ids&&r.workspace_ids.forEach(h=>o.append("workspace_ids",h.toString())),r.is_read!==void 0&&o.append("is_read",r.is_read.toString()),r.is_archived!==void 0&&o.append("is_archived",r.is_archived.toString()),r.severity&&o.append("severity",r.severity));const n=`/notifications${o.toString()?"?"+o.toString():""}`,s=await t(n,{method:"GET"});return(await q(s)).data}async function ou(t){const r=await t("/notifications/channel-counts",{method:"GET"});return(await q(r)).data}async function nu(t,r){const o=await t(`/notifications/${r}/read`,{method:"POST"});return q(o)}async function au(t){const r=await t("/notifications/mark-all-read",{method:"POST"});return q(r)}async function su(t,r){const o=await t(`/notifications/${r}/delete`,{method:"POST"});return q(o)}function pc(t){const{client:r,loading:o}=Fe(),{data:n,error:s,mutate:a,isLoading:h}=Ne(o?null:`wacht-notifications:${JSON.stringify(t)}`,()=>ru(r,t),{refreshInterval:6e4,revalidateOnFocus:!0});uc({enabled:!o&&!!n,onNotification:i.useCallback(u=>{a(async g=>!g||g.notifications.some(v=>v.id===u.id.toString())?g:{...g,notifications:[{id:u.id.toString(),user_id:u.user_id.toString(),deployment_id:u.deployment_id.toString(),title:u.title,body:u.body,severity:u.severity,action_url:u.action_url,action_label:u.action_label,is_read:!1,is_archived:!1,created_at:u.created_at,updated_at:u.created_at},...g.notifications],unread_count:g.unread_count+1,total:g.total+1},!1)},[a]),onError:i.useCallback(()=>{},[])});const f=i.useCallback(async u=>{o||(await a(async g=>g&&{...g,notifications:g.notifications.map(m=>m.id===u?{...m,is_read:!0}:m),unread_count:Math.max(0,g.unread_count-1)},!1),await nu(r,u),await a())},[r,o,a]),c=i.useCallback(async()=>{o||(await a(async u=>u&&{...u,notifications:u.notifications.map(g=>({...g,is_read:!0})),unread_count:0},!1),await au(r),await a())},[r,a]),p=i.useCallback(async u=>{o||(await a(async g=>{if(!g)return g;const m=g.notifications.find(v=>v.id===u);return{...g,notifications:g.notifications.filter(v=>v.id!==u),unread_count:m&&!m.is_read?Math.max(0,g.unread_count-1):g.unread_count,total:Math.max(0,g.total-1)}},!1),await su(r,u),await a())},[r,o,a]),d=i.useCallback(async()=>{await a()},[a]);return!n||o||h?{loading:!0,notifications:void 0,unreadCount:void 0,unreadCounts:void 0,channels:void 0,hasMore:void 0,markAsRead:void 0,markAllAsRead:void 0,deleteNotification:void 0,error:s,refetch:d}:{loading:!1,error:s,notifications:n.notifications,unreadCount:n.unread_count,unreadCounts:n.unread_counts,channels:n.channels,hasMore:n.has_more,markAsRead:f,markAllAsRead:c,deleteNotification:p,refetch:d}}async function iu(t){const r=await t("/notifications/channel-counts",{method:"GET"});return(await q(r)).data}function cu(){const{client:t,loading:r}=Fe(),{data:o,error:n,mutate:s}=Ne(r?null:"wacht-notifications:channel-counts",()=>iu(t),{refreshInterval:3e4,revalidateOnFocus:!0}),a=async()=>{await s()};return!o||r?{loading:!0,counts:void 0,error:n,refetch:a}:{loading:!1,counts:o,error:n,refetch:a}}const Ht=class Ht{constructor(){tt(this,"ws",null);tt(this,"messageHandlers",new Set);tt(this,"connectionStateHandlers",new Set);tt(this,"reconnectTimer",null);tt(this,"reconnectAttempts",0);tt(this,"url",null);tt(this,"isIntentionalDisconnect",!1);tt(this,"sessionMessages",{});tt(this,"currentSessionKey",null)}static getInstance(){return Ht.instance||(Ht.instance=new Ht),Ht.instance}connect(r){var o,n;if(this.url=r,this.isIntentionalDisconnect=!1,((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN&&this.url===r){this.notifyConnectionState({isConnected:!0});return}((n=this.ws)==null?void 0:n.readyState)!==WebSocket.CONNECTING&&this.createConnection()}createConnection(){if(this.url)try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,this.notifyConnectionState({isConnected:!0})},this.ws.onmessage=r=>{try{const o=JSON.parse(r.data);this.notifyMessageHandlers(o)}catch{}},this.ws.onerror=()=>{this.notifyConnectionState({isConnected:!1,error:"Connection error"})},this.ws.onclose=()=>{this.ws=null,this.notifyConnectionState({isConnected:!1}),this.isIntentionalDisconnect||this.scheduleReconnect()}}catch(r){this.notifyConnectionState({isConnected:!1,error:r instanceof Error?r.message:"Failed to connect"})}}scheduleReconnect(){this.reconnectAttempts++;const r=Math.min(1e3*Math.pow(2,this.reconnectAttempts-1),3e4),o=Math.random()*.3*r,n=Math.floor(r+o);this.reconnectTimer=setTimeout(()=>{this.createConnection()},n)}disconnect(){this.isIntentionalDisconnect=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null)}send(r){var o;if(((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN){const n=JSON.stringify(r);this.ws.send(n)}}onMessage(r){return this.messageHandlers.add(r),()=>{this.messageHandlers.delete(r)}}onConnectionStateChange(r){var o;return this.connectionStateHandlers.add(r),r({isConnected:((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN}),()=>{this.connectionStateHandlers.delete(r)}}notifyMessageHandlers(r){this.messageHandlers.forEach(o=>{try{o(r)}catch{}})}notifyConnectionState(r){this.connectionStateHandlers.forEach(o=>{try{o(r)}catch{}})}isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}setCurrentSession(r){this.currentSessionKey=r,this.sessionMessages[r]||(this.sessionMessages[r]=[])}addMessage(r){this.currentSessionKey&&(this.sessionMessages[this.currentSessionKey]||(this.sessionMessages[this.currentSessionKey]=[]),this.sessionMessages[this.currentSessionKey].push(r))}getSessionMessages(r){return this.sessionMessages[r]||[]}clearSessionMessages(r){this.sessionMessages[r]&&(this.sessionMessages[r]=[])}};tt(Ht,"instance");let oa=Ht;const Qe=oa.getInstance(),mt={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",ERROR:"error"},Ae={IDLE:"idle",STARTING:"starting",RUNNING:"running",WAITING_FOR_INPUT:"waiting_for_input",COMPLETED:"completed",FAILED:"failed"},Ot={IDLE:"Idle",STARTING:"Starting",RUNNING:"Running",WAITING_FOR_INPUT:"WaitingForInput",COMPLETED:"Completed",FAILED:"Failed",CANCELLED:"Cancelled"};function Ua(t){switch(t){case Ot.IDLE:return Ae.IDLE;case Ot.STARTING:return Ae.STARTING;case Ot.RUNNING:return Ae.RUNNING;case Ot.WAITING_FOR_INPUT:return Ae.WAITING_FOR_INPUT;case Ot.COMPLETED:return Ae.COMPLETED;case Ot.FAILED:case Ot.CANCELLED:return Ae.FAILED;default:return Ae.IDLE}}function Wa(t){return t===Ae.STARTING||t===Ae.RUNNING||t===Ae.WAITING_FOR_INPUT}function hc({contextId:t,agentName:r,token:o,platformAdapter:n,autoConnect:s=!0}){const{deployment:a}=ve(),{client:h}=Fe(),[f,c]=i.useState([]),[p,d]=i.useState(null),[u,g]=i.useState(null),[m,v]=i.useState(!1),[y,S]=i.useState(!1),[E,b]=i.useState(Ae.IDLE),[$,C]=i.useState({status:mt.DISCONNECTED}),[w,j]=i.useState(!0),[x,I]=i.useState(!1),k=i.useRef(null),R=i.useRef(null),_=i.useCallback(U=>{var K,ee;switch(U.message_type){case"session_connected":if(v(!0),C({status:mt.CONNECTED}),(K=U.data)!=null&&K.execution_status){const ie=U.data.execution_status,oe=Ua(ie);b(oe),S(Wa(oe))}break;case"conversation_message":O(U.data);break;case"user_input_request":P(U.data);break;case"platform_event":z(U.data);break;case"platform_function":T(U.data);break;case"execution_complete":S(!1),b(Ae.IDLE),R.current=null;break;case"execution_error":S(!1),b(Ae.FAILED),R.current=null;break;case"execution_cancelled":S(!1),b(Ae.IDLE),R.current=null;break;case"execution_status":const J=(ee=U.data)==null?void 0:ee.status;if(J){const ie=Ua(J);b(ie),S(Wa(ie))}break}},[p]),O=i.useCallback(U=>{var oe,de,Q,ce,B,V,D,le;const{id:K,message_type:ee,content:J}=U,ie=H=>f.some(ae=>ae.id===H);if(ee==="system_decision"||ee==="action_execution_result"||ee==="assistant_task_breakdown"||ee==="assistant_validation"||ee==="assistant_action_planning"||ee==="context_results"){d(null),g(null);let H="";if(ee==="system_decision"){const ae=J==null?void 0:J.step,ke=J==null?void 0:J.reasoning;if(ae==="gathercontext")ke&&ke.length>0?H=ke.length>60?`${ke.substring(0,60)}...`:ke:H="Gathering context...";else if(ae==="executeaction")H="Executing action";else if(ae==="deliverresponse")H="Preparing response";else if(ae==="taskplanning")H="Planning approach";else if(ae==="validateprogress")H="Validating progress";else if(ae==="acknowledge")H="Processing request";else if(ae==="finishplanning")H="Finalizing plan";else if(ae==="executetasks")H="Executing tasks";else if(ae==="requestuserinput")H="Waiting for input";else if(ae==="complete")H="Completed";else if(ae==="examinetool")H="Examining tool";else if(ae==="examineworkflow")H="Examining workflow";else{const ne=(J==null?void 0:J.confidence)||.5;ne>.8?H="Analyzing":ne>.6?H="Thinking":H="Reasoning"}}else if(ee==="action_execution_result")((oe=J.task_execution)==null?void 0:oe.status)==="completed"?H="Task execution completed":(de=J.task_execution)!=null&&de.approach?H=J.task_execution.approach:H="Executing task";else if(ee==="assistant_task_breakdown")(Q=J.task_breakdown)!=null&&Q.total_tasks?H=`Identified ${J.task_breakdown.total_tasks} tasks`:H="Planning tasks";else if(ee==="assistant_validation")H="Validated results";else if(ee==="assistant_action_planning")(ce=J.task_execution)!=null&&ce.total_tasks?H=`Planned ${J.task_execution.total_tasks} tasks`:(V=(B=J.task_execution)==null?void 0:B.tasks)!=null&&V.length?H=`Planned ${J.task_execution.tasks.length} tasks`:H="Planning actions";else if(ee==="context_results"){const ae=J.query,ke=J.result_count||0;ae&&ae!=="General context gathering"?H=`${ae}: Found ${ke} results`:H=`Found ${ke} results`}H&&!ie(K)&&c(ae=>[...ae,{id:K,role:"system",content:H,timestamp:new Date,metadata:{type:"log",messageType:ee}}]);return}if(ee==="user_message")ie(K)||(d(null),g(null),c(H=>[...H,{id:K,role:"user",content:J.message,images:J.images,timestamp:new Date}]));else if(ee==="agent_response")ie(K)||(d(null),g(null),S(!1),b(Ae.IDLE),R.current=null,c(H=>[...H,{id:K,role:"assistant",content:J.response,timestamp:new Date,isStreaming:!1}]));else if(ee==="assistant_acknowledgment")ie(K)||(d(null),g(null),c(H=>[...H,{id:K,role:"assistant",content:J.acknowledgment_message,timestamp:new Date}]));else if(ee==="assistant_ideation"||ee==="assistant_action_planning"||ee==="action_execution_result"||ee==="assistant_validation"||ee==="assistant_context_gathering"||ee==="assistant_task_breakdown"){let H="";if(J.reasoning_summary)H=J.reasoning_summary;else if((D=J.task_execution)!=null&&D.approach)H=J.task_execution.approach;else if(J.strategic_synthesis)H=J.strategic_synthesis;else if((le=J.task_breakdown)!=null&&le.total_tasks)H=`Breaking down into ${J.task_breakdown.total_tasks} tasks...`;else if(J.acknowledgment_message)H=J.acknowledgment_message;else return;c(ae=>[...ae,{id:K,role:"assistant",content:H,timestamp:new Date}])}else if(ee==="user_input_request"){const H={question:J.question,context:J.context,input_type:J.input_type,options:J.options||J.suggestions,default_value:J.default_value,placeholder:J.placeholder};b("waiting_for_input"),c(ae=>[...ae,{id:K,role:"system",content:H.question,timestamp:new Date,metadata:{type:"user_input_request",userInputRequest:H}}])}},[]),P=i.useCallback(async U=>{b("waiting_for_input");const K=`input-request-${Date.now()}`;c(ee=>[...ee,{id:K,role:"system",content:U.question,timestamp:new Date,metadata:{type:"user_input_request",userInputRequest:U}}])},[]),z=i.useCallback(U=>{const{event_label:K,event_data:ee}=U;n!=null&&n.onPlatformEvent&&n.onPlatformEvent(K,ee)},[n]),T=i.useCallback(async U=>{const{function_name:K,function_data:ee}=U,{parameters:J,execution_id:ie}=ee;if(!(n!=null&&n.onPlatformFunction)){Qe.send({message_type:{platform_function_result:[ie,{error:"No platform function handler registered"}]},data:{}});return}try{const oe=await n.onPlatformFunction(K,J,ie),de={message_type:{platform_function_result:[ie,oe]},data:{}};Qe.send(de)}catch(oe){Qe.send({message_type:{platform_function_result:[ie,{error:oe instanceof Error?oe.message:"Function execution failed",stack:oe instanceof Error?oe.stack:void 0}]},data:{}})}},[n]);i.useEffect(()=>{if(!a)return;const K=`wss://${a==null?void 0:a.backend_host.replace(/https?:\/\//,"")}/realtime/agent?token=${encodeURIComponent(o)}`;C({status:mt.CONNECTING}),Qe.connect(K)},[a,o]),i.useEffect(()=>Qe.onConnectionStateChange(K=>{C({status:K.isConnected?mt.CONNECTED:K.error?mt.ERROR:mt.DISCONNECTED}),v(K.isConnected)}),[]),i.useEffect(()=>Qe.onMessage(_),[_]),i.useEffect(()=>{m&&t&&r&&s&&Qe.send({message_type:{session_connect:[t,r]},data:{}})},[m,t,r,s]);const M=i.useCallback(async()=>(m&&t&&r&&Qe.send({message_type:{session_connect:[t,r]},data:{}}),()=>{}),[m,t,r]),F=i.useCallback((U,K)=>{m&&(d(U),g(K||null),S(!0),b(Ae.STARTING),Qe.send({message_type:{message_input:U},data:K?{images:K}:{}}))},[m]),G=i.useCallback(()=>{c([]),R.current=null},[]),L=i.useCallback(U=>{!m||E!==Ae.WAITING_FOR_INPUT||(Qe.send({message_type:{user_input_response:U},data:{}}),b(Ae.RUNNING))},[m,E]),A=i.useCallback(async U=>{var K;if(!(!o||!t))try{const ee=new URLSearchParams({token:o,limit:"50"});U&&(ee.append("before_id",U),I(!0));const ie=await(await h(`/api/agent/contexts/${t}/messages?${ee}`,{method:"GET"})).json();if(ie.status===200&&ie.data){const oe=ie.data;if(Array.isArray(oe.data)){const de=oe.data.filter(Q=>{var V;let ce=Q.content;if(typeof Q.content=="string")try{ce=JSON.parse(Q.content)}catch{ce={message:Q.content}}const B=((V=Q.metadata)==null?void 0:V.message_type)||(ce==null?void 0:ce.message_type);return B==="user_message"||B==="agent_response"||B==="assistant_acknowledgment"||B==="user_input_request"||B==="system_decision"||B==="action_execution_result"||B==="assistant_task_breakdown"||B==="assistant_validation"||B==="assistant_action_planning"||B==="context_results"}).map(Q=>{var H,ae,ke,ne,Y,Z,N;let ce="",B,V,D=Q.content;if(typeof Q.content=="string")try{D=JSON.parse(Q.content)}catch{D=Q.content}const le=((H=Q.metadata)==null?void 0:H.message_type)||(D==null?void 0:D.message_type);if(le==="user_message"?(ce=(D==null?void 0:D.message)||"",B=(D==null?void 0:D.images)||void 0):le==="agent_response"?ce=(D==null?void 0:D.response)||"":le==="assistant_acknowledgment"?ce=(D==null?void 0:D.acknowledgment_message)||"":le==="user_input_request"&&(ce=(D==null?void 0:D.question)||"",V={type:"user_input_request",userInputRequest:{question:(D==null?void 0:D.question)||"",context:(D==null?void 0:D.context)||"",input_type:(D==null?void 0:D.input_type)||"text",options:(D==null?void 0:D.options)||(D==null?void 0:D.suggestions)||[],default_value:(D==null?void 0:D.default_value)||"",placeholder:(D==null?void 0:D.placeholder)||""}}),le==="system_decision"||le==="action_execution_result"||le==="assistant_task_breakdown"||le==="assistant_validation"||le==="assistant_action_planning"||le==="context_results"){let W="";if(le==="system_decision"){const fe=D==null?void 0:D.step,ye=D==null?void 0:D.reasoning;if(fe==="gathercontext")ye&&ye.length>0?W=ye.length>60?`${ye.substring(0,60)}...`:ye:W="Gathering context...";else if(fe==="executeaction")W="Executing action";else if(fe==="deliverresponse")W="Preparing response";else if(fe==="taskplanning")W="Planning approach";else if(fe==="validateprogress")W="Validating progress";else if(fe==="acknowledge")W="Processing request";else if(fe==="finishplanning")W="Finalizing plan";else if(fe==="executetasks")W="Executing tasks";else if(fe==="requestuserinput")W="Waiting for input";else if(fe==="complete")W="Completed";else if(fe==="examinetool")W="Examining tool";else if(fe==="examineworkflow")W="Examining workflow";else{const re=(D==null?void 0:D.confidence)||.5;re>.8?W="Analyzing":re>.6?W="Thinking":W="Reasoning"}}else if(le==="action_execution_result")((ae=D==null?void 0:D.task_execution)==null?void 0:ae.status)==="completed"?W="Task execution completed":(ke=D==null?void 0:D.task_execution)!=null&&ke.approach?W=D.task_execution.approach:W="Executing task";else if(le==="assistant_task_breakdown")(ne=D==null?void 0:D.task_breakdown)!=null&&ne.total_tasks?W=`Identified ${D.task_breakdown.total_tasks} tasks`:W="Planning tasks";else if(le==="assistant_validation")W="Validated results";else if(le==="assistant_action_planning")(Y=D==null?void 0:D.task_execution)!=null&&Y.total_tasks?W=`Planned ${D.task_execution.total_tasks} tasks`:(N=(Z=D==null?void 0:D.task_execution)==null?void 0:Z.tasks)!=null&&N.length?W=`Planned ${D.task_execution.tasks.length} tasks`:W="Planning actions";else if(le==="context_results"){const fe=D==null?void 0:D.query,ye=(D==null?void 0:D.result_count)||0;fe&&fe!=="General context gathering"?W=`${fe}: Found ${ye} results`:W=`Found ${ye} results`}ce=W,V={type:"log",messageType:le}}return{id:Q.id,role:le==="user_message"?"user":le==="user_input_request"?"system":"assistant",content:ce,images:B,timestamp:new Date(Q.timestamp||Q.created_at||Date.now()),metadata:V}}).filter(Q=>Q.content||Q.metadata||Q.images).sort((Q,ce)=>{const B=BigInt(Q.id),V=BigInt(ce.id);return B<V?-1:B>V?1:0});de.length>0&&(k.current=de[0].id),U?(c(Q=>[...de,...Q]),j(de.length>=50)):(c(de),de.length>0&&((K=de[de.length-1].metadata)==null?void 0:K.type)==="user_input_request"&&b(Ae.WAITING_FOR_INPUT)),I(!1)}}}catch(ee){console.error("Failed to fetch messages:",ee),I(!1)}},[o,t,h]);i.useEffect(()=>{t&&o&&A()},[t,o]);const se=i.useCallback(async()=>{if(!(x||!w||!k.current)){I(!0);try{await A(k.current)}finally{I(!1)}}},[x,w,A]),te=i.useCallback(()=>{!m||!y||(Qe.send({message_type:{cancel_execution:null},data:{}}),S(!1),b("idle"))},[m,y]);return{messages:f,pendingMessage:p,pendingImages:u,connectionState:$,isConnected:m,isExecuting:y,executionStatus:E,isWaitingForInput:E==="waiting_for_input",hasMoreMessages:w,isLoadingMore:x,sendMessage:F,submitUserInput:L,clearMessages:G,loadMoreMessages:se,cancelExecution:te,connect:M,disconnect:()=>Qe.disconnect()}}const fc=()=>{const{client:t}=Fe(),[r,o]=i.useState(!1),[n,s]=i.useState(null),[a,h]=i.useState(null),f=i.useCallback(async p=>{o(!0),s(null),h(null);try{const d=await t("/organizations/invitations/accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:p})}),g=(await q(d)).data;return h(g),g.error_code&&s(g.message||"Failed to accept invitation"),g}catch(d){const u=d.message||"Failed to accept invitation";s(u);const g={error_code:"NETWORK_ERROR",message:u};return h(g),g}finally{o(!1)}},[t]),c=i.useCallback(()=>{s(null),h(null)},[]);return{acceptInvitation:f,invitationData:a,loading:r,error:n,reset:c}},lu=({children:t})=>{const{loading:r}=ve();return r?null:e.jsx(e.Fragment,{children:t})},du=({children:t})=>{const{loading:r}=ve();return r?e.jsx(e.Fragment,{children:t}):null};var He=function(){return He=Object.assign||function(r){for(var o,n=1,s=arguments.length;n<s;n++){o=arguments[n];for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(r[a]=o[a])}return r},He.apply(this,arguments)};function Xt(t,r,o){if(o||arguments.length===2)for(var n=0,s=r.length,a;n<s;n++)(a||!(n in r))&&(a||(a=Array.prototype.slice.call(r,0,n)),a[n]=r[n]);return t.concat(a||Array.prototype.slice.call(r))}function uu(t){var r=Object.create(null);return function(o){return r[o]===void 0&&(r[o]=t(o)),r[o]}}var pu=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/,hu=uu(function(t){return pu.test(t)||t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&t.charCodeAt(2)<91}),Pe="-ms-",Lr="-moz-",$e="-webkit-",gc="comm",Zo="rule",ba="decl",fu="@import",mc="@keyframes",gu="@layer",xc=Math.abs,ya=String.fromCharCode,na=Object.assign;function mu(t,r){return Ue(t,0)^45?(((r<<2^Ue(t,0))<<2^Ue(t,1))<<2^Ue(t,2))<<2^Ue(t,3):0}function vc(t){return t.trim()}function gt(t,r){return(t=r.exec(t))?t[0]:t}function xe(t,r,o){return t.replace(r,o)}function zo(t,r,o){return t.indexOf(r,o)}function Ue(t,r){return t.charCodeAt(r)|0}function mr(t,r,o){return t.slice(r,o)}function it(t){return t.length}function bc(t){return t.length}function Or(t,r){return r.push(t),t}function xu(t,r){return t.map(r).join("")}function Va(t,r){return t.filter(function(o){return!gt(o,r)})}var Qo=1,xr=1,yc=0,Xe=0,De=0,kr="";function Ko(t,r,o,n,s,a,h,f){return{value:t,root:r,parent:o,type:n,props:s,children:a,line:Qo,column:xr,length:h,return:"",siblings:f}}function Ct(t,r){return na(Ko("",null,null,"",null,null,0,t.siblings),t,{length:-t.length},r)}function sr(t){for(;t.root;)t=Ct(t.root,{children:[t]});Or(t,t.siblings)}function vu(){return De}function bu(){return De=Xe>0?Ue(kr,--Xe):0,xr--,De===10&&(xr=1,Qo--),De}function rt(){return De=Xe<yc?Ue(kr,Xe++):0,xr++,De===10&&(xr=1,Qo++),De}function Yt(){return Ue(kr,Xe)}function Eo(){return Xe}function Xo(t,r){return mr(kr,t,r)}function aa(t){switch(t){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function yu(t){return Qo=xr=1,yc=it(kr=t),Xe=0,[]}function wu(t){return kr="",t}function gn(t){return vc(Xo(Xe-1,sa(t===91?t+2:t===40?t+1:t)))}function ju(t){for(;(De=Yt())&&De<33;)rt();return aa(t)>2||aa(De)>3?"":" "}function ku(t,r){for(;--r&&rt()&&!(De<48||De>102||De>57&&De<65||De>70&&De<97););return Xo(t,Eo()+(r<6&&Yt()==32&&rt()==32))}function sa(t){for(;rt();)switch(De){case t:return Xe;case 34:case 39:t!==34&&t!==39&&sa(De);break;case 40:t===41&&sa(t);break;case 92:rt();break}return Xe}function _u(t,r){for(;rt()&&t+De!==57;)if(t+De===84&&Yt()===47)break;return"/*"+Xo(r,Xe-1)+"*"+ya(t===47?t:rt())}function Cu(t){for(;!aa(Yt());)rt();return Xo(t,Xe)}function Su(t){return wu(Po("",null,null,null,[""],t=yu(t),0,[0],t))}function Po(t,r,o,n,s,a,h,f,c){for(var p=0,d=0,u=h,g=0,m=0,v=0,y=1,S=1,E=1,b=0,$="",C=s,w=a,j=n,x=$;S;)switch(v=b,b=rt()){case 40:if(v!=108&&Ue(x,u-1)==58){zo(x+=xe(gn(b),"&","&\f"),"&\f",xc(p?f[p-1]:0))!=-1&&(E=-1);break}case 34:case 39:case 91:x+=gn(b);break;case 9:case 10:case 13:case 32:x+=ju(v);break;case 92:x+=ku(Eo()-1,7);continue;case 47:switch(Yt()){case 42:case 47:Or($u(_u(rt(),Eo()),r,o,c),c);break;default:x+="/"}break;case 123*y:f[p++]=it(x)*E;case 125*y:case 59:case 0:switch(b){case 0:case 125:S=0;case 59+d:E==-1&&(x=xe(x,/\f/g,"")),m>0&&it(x)-u&&Or(m>32?Ha(x+";",n,o,u-1,c):Ha(xe(x," ","")+";",n,o,u-2,c),c);break;case 59:x+=";";default:if(Or(j=Ga(x,r,o,p,d,s,f,$,C=[],w=[],u,a),a),b===123)if(d===0)Po(x,r,j,j,C,a,u,f,w);else switch(g===99&&Ue(x,3)===110?100:g){case 100:case 108:case 109:case 115:Po(t,j,j,n&&Or(Ga(t,j,j,0,0,s,f,$,s,C=[],u,w),w),s,w,u,f,n?C:w);break;default:Po(x,j,j,j,[""],w,0,f,w)}}p=d=m=0,y=E=1,$=x="",u=h;break;case 58:u=1+it(x),m=v;default:if(y<1){if(b==123)--y;else if(b==125&&y++==0&&bu()==125)continue}switch(x+=ya(b),b*y){case 38:E=d>0?1:(x+="\f",-1);break;case 44:f[p++]=(it(x)-1)*E,E=1;break;case 64:Yt()===45&&(x+=gn(rt())),g=Yt(),d=u=it($=x+=Cu(Eo())),b++;break;case 45:v===45&&it(x)==2&&(y=0)}}return a}function Ga(t,r,o,n,s,a,h,f,c,p,d,u){for(var g=s-1,m=s===0?a:[""],v=bc(m),y=0,S=0,E=0;y<n;++y)for(var b=0,$=mr(t,g+1,g=xc(S=h[y])),C=t;b<v;++b)(C=vc(S>0?m[b]+" "+$:xe($,/&\f/g,m[b])))&&(c[E++]=C);return Ko(t,r,o,s===0?Zo:f,c,p,d,u)}function $u(t,r,o,n){return Ko(t,r,o,gc,ya(vu()),mr(t,2,-2),0,n)}function Ha(t,r,o,n,s){return Ko(t,r,o,ba,mr(t,0,n),mr(t,n+1,-1),n,s)}function wc(t,r,o){switch(mu(t,r)){case 5103:return $e+"print-"+t+t;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return $e+t+t;case 4789:return Lr+t+t;case 5349:case 4246:case 4810:case 6968:case 2756:return $e+t+Lr+t+Pe+t+t;case 5936:switch(Ue(t,r+11)){case 114:return $e+t+Pe+xe(t,/[svh]\w+-[tblr]{2}/,"tb")+t;case 108:return $e+t+Pe+xe(t,/[svh]\w+-[tblr]{2}/,"tb-rl")+t;case 45:return $e+t+Pe+xe(t,/[svh]\w+-[tblr]{2}/,"lr")+t}case 6828:case 4268:case 2903:return $e+t+Pe+t+t;case 6165:return $e+t+Pe+"flex-"+t+t;case 5187:return $e+t+xe(t,/(\w+).+(:[^]+)/,$e+"box-$1$2"+Pe+"flex-$1$2")+t;case 5443:return $e+t+Pe+"flex-item-"+xe(t,/flex-|-self/g,"")+(gt(t,/flex-|baseline/)?"":Pe+"grid-row-"+xe(t,/flex-|-self/g,""))+t;case 4675:return $e+t+Pe+"flex-line-pack"+xe(t,/align-content|flex-|-self/g,"")+t;case 5548:return $e+t+Pe+xe(t,"shrink","negative")+t;case 5292:return $e+t+Pe+xe(t,"basis","preferred-size")+t;case 6060:return $e+"box-"+xe(t,"-grow","")+$e+t+Pe+xe(t,"grow","positive")+t;case 4554:return $e+xe(t,/([^-])(transform)/g,"$1"+$e+"$2")+t;case 6187:return xe(xe(xe(t,/(zoom-|grab)/,$e+"$1"),/(image-set)/,$e+"$1"),t,"")+t;case 5495:case 3959:return xe(t,/(image-set\([^]*)/,$e+"$1$`$1");case 4968:return xe(xe(t,/(.+:)(flex-)?(.*)/,$e+"box-pack:$3"+Pe+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+$e+t+t;case 4200:if(!gt(t,/flex-|baseline/))return Pe+"grid-column-align"+mr(t,r)+t;break;case 2592:case 3360:return Pe+xe(t,"template-","")+t;case 4384:case 3616:return o&&o.some(function(n,s){return r=s,gt(n.props,/grid-\w+-end/)})?~zo(t+(o=o[r].value),"span",0)?t:Pe+xe(t,"-start","")+t+Pe+"grid-row-span:"+(~zo(o,"span",0)?gt(o,/\d+/):+gt(o,/\d+/)-+gt(t,/\d+/))+";":Pe+xe(t,"-start","")+t;case 4896:case 4128:return o&&o.some(function(n){return gt(n.props,/grid-\w+-start/)})?t:Pe+xe(xe(t,"-end","-span"),"span ","")+t;case 4095:case 3583:case 4068:case 2532:return xe(t,/(.+)-inline(.+)/,$e+"$1$2")+t;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(it(t)-1-r>6)switch(Ue(t,r+1)){case 109:if(Ue(t,r+4)!==45)break;case 102:return xe(t,/(.+:)(.+)-([^]+)/,"$1"+$e+"$2-$3$1"+Lr+(Ue(t,r+3)==108?"$3":"$2-$3"))+t;case 115:return~zo(t,"stretch",0)?wc(xe(t,"stretch","fill-available"),r,o)+t:t}break;case 5152:case 5920:return xe(t,/(.+?):(\d+)(\s*\/\s*(span)?\s*(\d+))?(.*)/,function(n,s,a,h,f,c,p){return Pe+s+":"+a+p+(h?Pe+s+"-span:"+(f?c:+c-+a)+p:"")+t});case 4949:if(Ue(t,r+6)===121)return xe(t,":",":"+$e)+t;break;case 6444:switch(Ue(t,Ue(t,14)===45?18:11)){case 120:return xe(t,/(.+:)([^;\s!]+)(;|(\s+)?!.+)?/,"$1"+$e+(Ue(t,14)===45?"inline-":"")+"box$3$1"+$e+"$2$3$1"+Pe+"$2box$3")+t;case 100:return xe(t,":",":"+Pe)+t}break;case 5719:case 2647:case 2135:case 3927:case 2391:return xe(t,"scroll-","scroll-snap-")+t}return t}function Lo(t,r){for(var o="",n=0;n<t.length;n++)o+=r(t[n],n,t,r)||"";return o}function zu(t,r,o,n){switch(t.type){case gu:if(t.children.length)break;case fu:case ba:return t.return=t.return||t.value;case gc:return"";case mc:return t.return=t.value+"{"+Lo(t.children,n)+"}";case Zo:if(!it(t.value=t.props.join(",")))return""}return it(o=Lo(t.children,n))?t.return=t.value+"{"+o+"}":""}function Eu(t){var r=bc(t);return function(o,n,s,a){for(var h="",f=0;f<r;f++)h+=t[f](o,n,s,a)||"";return h}}function Pu(t){return function(r){r.root||(r=r.return)&&t(r)}}function Ru(t,r,o,n){if(t.length>-1&&!t.return)switch(t.type){case ba:t.return=wc(t.value,t.length,o);return;case mc:return Lo([Ct(t,{value:xe(t.value,"@","@"+$e)})],n);case Zo:if(t.length)return xu(o=t.props,function(s){switch(gt(s,n=/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":sr(Ct(t,{props:[xe(s,/:(read-\w+)/,":"+Lr+"$1")]})),sr(Ct(t,{props:[s]})),na(t,{props:Va(o,n)});break;case"::placeholder":sr(Ct(t,{props:[xe(s,/:(plac\w+)/,":"+$e+"input-$1")]})),sr(Ct(t,{props:[xe(s,/:(plac\w+)/,":"+Lr+"$1")]})),sr(Ct(t,{props:[xe(s,/:(plac\w+)/,Pe+"input-$1")]})),sr(Ct(t,{props:[s]})),na(t,{props:Va(o,n)});break}return""})}}var Iu={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},Jt=typeof process<"u"&&process.env!==void 0&&(process.env.REACT_APP_SC_ATTR||process.env.SC_ATTR)||"data-styled",jc="active",kc="data-styled-version",Jo="6.1.19",wa=`/*!sc*/
18
+ */var Ma;function od(){return Ma||(Ma=1,process.env.NODE_ENV!=="production"&&function(){function t(m,v){return m===v&&(m!==0||1/m===1/v)||m!==m&&v!==v}function r(m,v){d||s.startTransition===void 0||(d=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var y=v();if(!u){var S=v();a(y,S)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),u=!0)}S=h({inst:{value:y,getSnapshot:v}});var E=S[0].inst,b=S[1];return c(function(){E.value=y,E.getSnapshot=v,o(E)&&b({inst:E})},[m,y,v]),f(function(){return o(E)&&b({inst:E}),m(function(){o(E)&&b({inst:E})})},[m]),p(y),y}function o(m){var v=m.getSnapshot;m=m.value;try{var y=v();return!a(m,y)}catch{return!0}}function n(m,v){return v()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var s=i,a=typeof Object.is=="function"?Object.is:t,h=s.useState,f=s.useEffect,c=s.useLayoutEffect,p=s.useDebugValue,d=!1,u=!1,g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n:r;cn.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:g,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),cn}var La;function nd(){return La||(La=1,process.env.NODE_ENV==="production"?Yr.exports=rd():Yr.exports=od()),Yr.exports}var ad=nd();const Gi=0,Hi=1,qi=2,Aa=3;var Da=Object.prototype.hasOwnProperty;function Yn(t,r){var o,n;if(t===r)return!0;if(t&&r&&(o=t.constructor)===r.constructor){if(o===Date)return t.getTime()===r.getTime();if(o===RegExp)return t.toString()===r.toString();if(o===Array){if((n=t.length)===r.length)for(;n--&&Yn(t[n],r[n]););return n===-1}if(!o||typeof t=="object"){n=0;for(o in t)if(Da.call(t,o)&&++n&&!Da.call(r,o)||!(o in r)||!Yn(t[o],r[o]))return!1;return Object.keys(r).length===n}}return t!==t&&r!==r}const xt=new WeakMap,$t=()=>{},Ge=$t(),Zn=Object,Ce=t=>t===Ge,ct=t=>typeof t=="function",Pt=(t,r)=>({...t,...r}),Yi=t=>ct(t.then),ln={},Zr={},xa="undefined",Br=typeof window!=xa,Qn=typeof document!=xa,sd=Br&&"Deno"in window,id=()=>Br&&typeof window.requestAnimationFrame!=xa,Zi=(t,r)=>{const o=xt.get(t);return[()=>!Ce(r)&&t.get(r)||ln,n=>{if(!Ce(r)){const s=t.get(r);r in Zr||(Zr[r]=s),o[5](r,Pt(s,n),s||ln)}},o[6],()=>!Ce(r)&&r in Zr?Zr[r]:!Ce(r)&&t.get(r)||ln]};let Kn=!0;const cd=()=>Kn,[Xn,Jn]=Br&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[$t,$t],ld=()=>{const t=Qn&&document.visibilityState;return Ce(t)||t!=="hidden"},dd=t=>(Qn&&document.addEventListener("visibilitychange",t),Xn("focus",t),()=>{Qn&&document.removeEventListener("visibilitychange",t),Jn("focus",t)}),ud=t=>{const r=()=>{Kn=!0,t()},o=()=>{Kn=!1};return Xn("online",r),Xn("offline",o),()=>{Jn("online",r),Jn("offline",o)}},pd={isOnline:cd,isVisible:ld},hd={initFocus:dd,initReconnect:ud},Fa=!i.useId,Ar=!Br||sd,fd=t=>id()?window.requestAnimationFrame(t):setTimeout(t,1),dn=Ar?i.useEffect:i.useLayoutEffect,un=typeof navigator<"u"&&navigator.connection,Na=!Ar&&un&&(["slow-2g","2g"].includes(un.effectiveType)||un.saveData),Qr=new WeakMap,gd=t=>Zn.prototype.toString.call(t),pn=(t,r)=>t===`[object ${r}]`;let md=0;const ea=t=>{const r=typeof t,o=gd(t),n=pn(o,"Date"),s=pn(o,"RegExp"),a=pn(o,"Object");let h,f;if(Zn(t)===t&&!n&&!s){if(h=Qr.get(t),h)return h;if(h=++md+"~",Qr.set(t,h),Array.isArray(t)){for(h="@",f=0;f<t.length;f++)h+=ea(t[f])+",";Qr.set(t,h)}if(a){h="#";const c=Zn.keys(t).sort();for(;!Ce(f=c.pop());)Ce(t[f])||(h+=f+":"+ea(t[f])+",");Qr.set(t,h)}}else h=n?t.toJSON():r=="symbol"?t.toString():r=="string"?JSON.stringify(t):""+t;return h},va=t=>{if(ct(t))try{t=t()}catch{t=""}const r=t;return t=typeof t=="string"?t:(Array.isArray(t)?t.length:t)?ea(t):"",[t,r]};let xd=0;const ta=()=>++xd;async function Qi(...t){const[r,o,n,s]=t,a=Pt({populateCache:!0,throwOnError:!0},typeof s=="boolean"?{revalidate:s}:s||{});let h=a.populateCache;const f=a.rollbackOnError;let c=a.optimisticData;const p=g=>typeof f=="function"?f(g):f!==!1,d=a.throwOnError;if(ct(o)){const g=o,m=[],v=r.keys();for(const y of v)!/^\$(inf|sub)\$/.test(y)&&g(r.get(y)._k)&&m.push(y);return Promise.all(m.map(u))}return u(o);async function u(g){const[m]=va(g);if(!m)return;const[v,y]=Zi(r,m),[S,E,b,$]=xt.get(r),C=()=>{const z=S[m];return(ct(a.revalidate)?a.revalidate(v().data,g):a.revalidate!==!1)&&(delete b[m],delete $[m],z&&z[0])?z[0](qi).then(()=>v().data):v().data};if(t.length<3)return C();let w=n,j,x=!1;const I=ta();E[m]=[I,0];const k=!Ce(c),R=v(),_=R.data,O=R._c,P=Ce(O)?_:O;if(k&&(c=ct(c)?c(P,_):c,y({data:c,_c:P})),ct(w))try{w=w(P)}catch(z){j=z,x=!0}if(w&&Yi(w))if(w=await w.catch(z=>{j=z,x=!0}),I!==E[m][0]){if(x)throw j;return w}else x&&k&&p(j)&&(h=!0,y({data:P,_c:Ge}));if(h&&!x)if(ct(h)){const z=h(w,P);y({data:z,error:Ge,_c:Ge})}else y({data:w,error:Ge,_c:Ge});if(E[m][1]=ta(),Promise.resolve(C()).then(()=>{y({_c:Ge})}),x){if(d)throw j;return}return w}}const Ba=(t,r)=>{for(const o in t)t[o][0]&&t[o][0](r)},vd=(t,r)=>{if(!xt.has(t)){const o=Pt(hd,r),n=Object.create(null),s=Qi.bind(Ge,t);let a=$t;const h=Object.create(null),f=(d,u)=>{const g=h[d]||[];return h[d]=g,g.push(u),()=>g.splice(g.indexOf(u),1)},c=(d,u,g)=>{t.set(d,u);const m=h[d];if(m)for(const v of m)v(u,g)},p=()=>{if(!xt.has(t)&&(xt.set(t,[n,Object.create(null),Object.create(null),Object.create(null),s,c,f]),!Ar)){const d=o.initFocus(setTimeout.bind(Ge,Ba.bind(Ge,n,Gi))),u=o.initReconnect(setTimeout.bind(Ge,Ba.bind(Ge,n,Hi)));a=()=>{d&&d(),u&&u(),xt.delete(t)}}};return p(),[t,s,p,a]}return[t,xt.get(t)[4]]},bd=(t,r,o,n,s)=>{const a=o.errorRetryCount,h=s.retryCount,f=~~((Math.random()+.5)*(1<<(h<8?h:8)))*o.errorRetryInterval;!Ce(a)&&h>a||setTimeout(n,f,s)},yd=Yn,[Ki,wd]=vd(new Map),jd=Pt({onLoadingSlow:$t,onSuccess:$t,onError:$t,onErrorRetry:bd,onDiscarded:$t,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:Na?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:Na?5e3:3e3,compare:yd,isPaused:()=>!1,cache:Ki,mutate:wd,fallback:{}},pd),kd=(t,r)=>{const o=Pt(t,r);if(r){const{use:n,fallback:s}=t,{use:a,fallback:h}=r;n&&a&&(o.use=n.concat(a)),s&&h&&(o.fallback=Pt(s,h))}return o},_d=i.createContext({}),Cd="$inf$",Xi=Br&&window.__SWR_DEVTOOLS_USE__,Sd=Xi?window.__SWR_DEVTOOLS_USE__:[],$d=()=>{Xi&&(window.__SWR_DEVTOOLS_REACT__=i)},zd=t=>ct(t[1])?[t[0],t[1],t[2]||{}]:[t[0],null,(t[1]===null?t[2]:t[1])||{}],Ji=()=>Pt(jd,i.useContext(_d)),Ed=t=>(r,o,n)=>t(r,o&&((...a)=>{const[h]=va(r),[,,,f]=xt.get(Ki);if(h.startsWith(Cd))return o(...a);const c=f[h];return Ce(c)?o(...a):(delete f[h],c)}),n),Pd=Sd.concat(Ed),Rd=t=>function(...o){const n=Ji(),[s,a,h]=zd(o),f=kd(n,h);let c=t;const{use:p}=f,d=(p||[]).concat(Pd);for(let u=d.length;u--;)c=d[u](c);return c(s,a||f.fetcher||null,f)},Id=(t,r,o)=>{const n=r[t]||(r[t]=[]);return n.push(o),()=>{const s=n.indexOf(o);s>=0&&(n[s]=n[n.length-1],n.pop())}};$d();const hn=i.use||(t=>{switch(t.status){case"pending":throw t;case"fulfilled":return t.value;case"rejected":throw t.reason;default:throw t.status="pending",t.then(r=>{t.status="fulfilled",t.value=r},r=>{t.status="rejected",t.reason=r}),t}}),fn={dedupe:!0},Td=(t,r,o)=>{const{cache:n,compare:s,suspense:a,fallbackData:h,revalidateOnMount:f,revalidateIfStale:c,refreshInterval:p,refreshWhenHidden:d,refreshWhenOffline:u,keepPreviousData:g}=o,[m,v,y,S]=xt.get(n),[E,b]=va(t),$=i.useRef(!1),C=i.useRef(!1),w=i.useRef(E),j=i.useRef(r),x=i.useRef(o),I=()=>x.current,k=()=>I().isVisible()&&I().isOnline(),[R,_,O,P]=Zi(n,E),z=i.useRef({}).current,T=Ce(h)?Ce(o.fallback)?Ge:o.fallback[E]:h,M=(V,D)=>{for(const le in z){const H=le;if(H==="data"){if(!s(V[H],D[H])&&(!Ce(V[H])||!s(ee,D[H])))return!1}else if(D[H]!==V[H])return!1}return!0},F=i.useMemo(()=>{const V=!E||!r?!1:Ce(f)?I().isPaused()||a?!1:c!==!1:f,D=Y=>{const Z=Pt(Y);return delete Z._k,V?{isValidating:!0,isLoading:!0,...Z}:Z},le=R(),H=P(),ae=D(le),ke=le===H?ae:D(H);let ne=ae;return[()=>{const Y=D(R());return M(Y,ne)?(ne.data=Y.data,ne.isLoading=Y.isLoading,ne.isValidating=Y.isValidating,ne.error=Y.error,ne):(ne=Y,Y)},()=>ke]},[n,E]),G=ad.useSyncExternalStore(i.useCallback(V=>O(E,(D,le)=>{M(le,D)||V()}),[n,E]),F[0],F[1]),L=!$.current,A=m[E]&&m[E].length>0,se=G.data,te=Ce(se)?T&&Yi(T)?hn(T):T:se,U=G.error,K=i.useRef(te),ee=g?Ce(se)?Ce(K.current)?te:K.current:se:te,J=A&&!Ce(U)?!1:L&&!Ce(f)?f:I().isPaused()?!1:a?Ce(te)?!1:c:Ce(te)||c,ie=!!(E&&r&&L&&J),oe=Ce(G.isValidating)?ie:G.isValidating,de=Ce(G.isLoading)?ie:G.isLoading,Q=i.useCallback(async V=>{const D=j.current;if(!E||!D||C.current||I().isPaused())return!1;let le,H,ae=!0;const ke=V||{},ne=!y[E]||!ke.dedupe,Y=()=>Fa?!C.current&&E===w.current&&$.current:E===w.current,Z={isValidating:!1,isLoading:!1},N=()=>{_(Z)},W=()=>{const ye=y[E];ye&&ye[1]===H&&delete y[E]},fe={isValidating:!0};Ce(R().data)&&(fe.isLoading=!0);try{if(ne&&(_(fe),o.loadingTimeout&&Ce(R().data)&&setTimeout(()=>{ae&&Y()&&I().onLoadingSlow(E,o)},o.loadingTimeout),y[E]=[D(b),ta()]),[le,H]=y[E],le=await le,ne&&setTimeout(W,o.dedupingInterval),!y[E]||y[E][1]!==H)return ne&&Y()&&I().onDiscarded(E),!1;Z.error=Ge;const ye=v[E];if(!Ce(ye)&&(H<=ye[0]||H<=ye[1]||ye[1]===0))return N(),ne&&Y()&&I().onDiscarded(E),!1;const re=R().data;Z.data=s(re,le)?re:le,ne&&Y()&&I().onSuccess(le,E,o)}catch(ye){W();const re=I(),{shouldRetryOnError:je}=re;re.isPaused()||(Z.error=ye,ne&&Y()&&(re.onError(ye,E,re),(je===!0||ct(je)&&je(ye))&&(!I().revalidateOnFocus||!I().revalidateOnReconnect||k())&&re.onErrorRetry(ye,E,re,me=>{const Se=m[E];Se&&Se[0]&&Se[0](Aa,me)},{retryCount:(ke.retryCount||0)+1,dedupe:!0})))}return ae=!1,N(),!0},[E,n]),ce=i.useCallback((...V)=>Qi(n,w.current,...V),[]);if(dn(()=>{j.current=r,x.current=o,Ce(se)||(K.current=se)}),dn(()=>{if(!E)return;const V=Q.bind(Ge,fn);let D=0;I().revalidateOnFocus&&(D=Date.now()+I().focusThrottleInterval);const H=Id(E,m,(ae,ke={})=>{if(ae==Gi){const ne=Date.now();I().revalidateOnFocus&&ne>D&&k()&&(D=ne+I().focusThrottleInterval,V())}else if(ae==Hi)I().revalidateOnReconnect&&k()&&V();else{if(ae==qi)return Q();if(ae==Aa)return Q(ke)}});return C.current=!1,w.current=E,$.current=!0,_({_k:b}),J&&(y[E]||(Ce(te)||Ar?V():fd(V))),()=>{C.current=!0,H()}},[E]),dn(()=>{let V;function D(){const H=ct(p)?p(R().data):p;H&&V!==-1&&(V=setTimeout(le,H))}function le(){!R().error&&(d||I().isVisible())&&(u||I().isOnline())?Q(fn).then(D):D()}return D(),()=>{V&&(clearTimeout(V),V=-1)}},[p,d,u,E]),i.useDebugValue(ee),a&&Ce(te)&&E){if(!Fa&&Ar)throw new Error("Fallback data is required when using Suspense in SSR.");j.current=r,x.current=o,C.current=!1;const V=S[E];if(!Ce(V)){const D=ce(V);hn(D)}if(Ce(U)){const D=Q(fn);Ce(ee)||(D.status="fulfilled",D.value=!0),hn(D)}else throw U}return{mutate:ce,get data(){return z.data=!0,ee},get error(){return z.error=!0,U},get isValidating(){return z.isValidating=!0,oe},get isLoading(){return z.isLoading=!0,de}}},Ne=Rd(Td);async function q(t){if(!t.ok){let o=`HTTP ${t.status}: ${t.statusText}`;try{const n=await t.json();n.message?o=n.message:n.errors&&n.errors.length>0&&(o=n.errors[0].message||o)}catch{}throw new Error(o)}return{data:(await t.json()).data}}function ec(t){const{client:r}=Fe(),o=i.useCallback(async()=>{const c=await r(`/api/agent/contexts?token=${encodeURIComponent(t)}`,{method:"GET"});return(await q(c)).data},[r,t]),{data:n,error:s,mutate:a}=Ne(t?`wacht-agent-sessions:${t}`:null,o,{revalidateOnFocus:!1}),h=i.useCallback(async c=>{const p=new FormData;p.append("title",c.title),c.system_instructions&&p.append("system_instructions",c.system_instructions);const d=await r(`/api/agent/contexts?token=${encodeURIComponent(t)}`,{method:"POST",body:p}),u=await q(d);return await a(g=>g&&{...g,data:[u.data,...g.data]}),u.data},[r,t,a]),f=i.useCallback(async c=>{await r(`/api/agent/contexts/${c}/delete?token=${encodeURIComponent(t)}`,{method:"POST"}),await a(p=>p&&{...p,data:p.data.filter(d=>d.id!==c)})},[r,t,a]);return{sessions:(n==null?void 0:n.data)||[],loading:!n&&!s,error:s,createSession:h,deleteSession:f,refetch:async()=>{await a()}}}const tc=i.createContext(void 0);function Ho(){const t=i.useContext(tc);if(!t)throw new Error("useAgentConversationContext must be used within AgentConversationProvider");return t}function Od({children:t,agentName:r,token:o,platformAdapter:n,defaultSessionId:s,onSessionCreated:a,onSessionDeleted:h,onError:f}){const[c,p]=i.useState(s?{id:s,title:"Conversation",status:"idle",last_activity_at:new Date().toISOString(),created_at:new Date().toISOString()}:null),[d,u]=i.useState(!1),{sessions:g,loading:m,error:v,createSession:y,deleteSession:S,refetch:E}=ec(o);i.useEffect(()=>{if(s&&g.length>0){const j=g.find(x=>x.id===s);j&&p(j)}},[s,g]);const b=i.useCallback(j=>{p(j),u(!1)},[]),$=i.useCallback(async j=>{try{const x=j||`Chat ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,I=await y({title:x});return p(I),a==null||a(I),I}catch(x){const I=x instanceof Error?x.message:"Failed to create session";throw f==null||f(I),x}},[y,a,f]),C=i.useCallback(async j=>{try{await S(j),(c==null?void 0:c.id)===j&&p(null),h==null||h(j)}catch(x){const I=x instanceof Error?x.message:"Failed to delete session";throw f==null||f(I),x}},[S,c,h,f]),w={agentName:r,token:o,platformAdapter:n,sessions:g,selectedSession:c,loadingSessions:m,sessionError:v,selectSession:b,createSession:$,deleteSession:C,refreshSessions:E,showHistory:d,setShowHistory:u,onSessionCreated:a,onSessionDeleted:h,onError:f};return e.jsx(tc.Provider,{value:w,children:t})}var rc=(t=>(t.XOauth="x_oauth",t.GithubOauth="github_oauth",t.GitlabOauth="gitlab_oauth",t.GoogleOauth="google_oauth",t.FacebookOauth="facebook_oauth",t.MicrosoftOauth="microsoft_oauth",t.LinkedinOauth="linkedin_oauth",t.DiscordOauth="discord_oauth",t.AppleOauth="apple_oauth",t))(rc||{});function Md(t,r){const o={username:Ld(t,r),email:Ad(t,r),phone:Dd(t,r),email_otp:Fd(t,r),magic_link:Nd(t,r),oauth:Bd(t),generic:Ud(t,r)};return function(s){return o[s]}}function Ld(t,r){return async({username:o,password:n})=>{var f,c;const s=new FormData;s.append("strategy","plain_username"),s.append("username",o),s.append("password",n);const a=await t("/auth/signin",{method:"POST",body:s}),h=await q(a);return"data"in h&&((c=(f=h.data)==null?void 0:f.signin_attempts)!=null&&c.length)&&r(h.data.signin_attempts.at(-1)||null),h}}function Ad(t,r){return async({email:o,password:n})=>{var f,c;const s=new FormData;s.append("strategy","plain_email"),s.append("email",o),s.append("password",n);const a=await t("/auth/signin",{method:"POST",body:s}),h=await q(a);return"data"in h&&((c=(f=h.data)==null?void 0:f.signin_attempts)!=null&&c.length)&&r(h.data.signin_attempts.at(-1)||null),h}}function Dd(t,r){return async({phone:o})=>{var h,f;const n=new FormData;n.append("strategy","phone_otp"),n.append("phone",o);const s=await t("/auth/signin",{method:"POST",body:n}),a=await q(s);return"data"in a&&((f=(h=a.data)==null?void 0:h.signin_attempts)!=null&&f.length)&&r(a.data.signin_attempts.at(-1)||null),a}}function Fd(t,r){return async({email:o})=>{var h,f;const n=new FormData;n.append("strategy","email_otp"),n.append("email",o);const s=await t("/auth/signin",{method:"POST",body:n}),a=await q(s);return"data"in a&&((f=(h=a.data)==null?void 0:h.signin_attempts)!=null&&f.length)&&r(a.data.signin_attempts.at(-1)||null),a}}function Nd(t,r){return async({email:o})=>{var h,f;const n=new FormData;n.append("strategy","magic_link"),n.append("email",o);const s=await t("/auth/signin",{method:"POST",body:n}),a=await q(s);return"data"in a&&((f=(h=a.data)==null?void 0:h.signin_attempts)!=null&&f.length)&&r(a.data.signin_attempts.at(-1)||null),a}}function Bd(t){return async({provider:r,redirectUri:o})=>{const n=new URLSearchParams({provider:r});o&&n.append("redirect_uri",o);const s=await t(`/auth/oauth2/init?${n.toString()}`,{method:"POST"}),a=await q(s);return"data"in a&&a.data.oauth_url&&(window.location.href=a.data.oauth_url),a}}function Ud(t,r){return async({email:o,username:n,password:s,phone:a,strategy:h,token:f})=>{var u,g;const c=new FormData;h&&c.append("strategy",h),o&&c.append("email",o),n&&c.append("username",n),s&&c.append("password",s),a&&c.append("phone",a),f&&c.append("token",f);const p=await t("/auth/signin",{method:"POST",body:c}),d=await q(p);return"data"in d&&((g=(u=d.data)==null?void 0:u.signin_attempts)!=null&&g.length)&&r(d.data.signin_attempts.at(-1)||null),d}}function oc(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(null);return r?{loading:!0,signIn:null,signinAttempt:null,discardSignInAttempt:()=>{n(null)},setSignInAttempt:n}:{loading:!1,signinAttempt:o,signIn:{createStrategy:Md(t,n),completeVerification:async s=>{var c,p;const a=new FormData;a.append("verification_code",s);const h=await t(`/auth/attempt-verification?attempt_identifier=${o==null?void 0:o.id}&identifier_type=signin`,{method:"POST",body:a}),f=await q(h);if("data"in f&&((p=(c=f.data)==null?void 0:c.signin_attempts)!=null&&p.length)){const d=f.data.signin_attempts.at(-1);return n(d||null),f.data}else throw new Error("Verification failed")},prepareVerification:async s=>{var f;const a=new URL("/auth/prepare-verification",window.location.origin);a.searchParams.set("attempt_identifier",((f=o==null?void 0:o.id)==null?void 0:f.toString())||""),a.searchParams.set("strategy",s.strategy),a.searchParams.set("identifier_type","signin"),s.strategy==="phone_otp"&&s.lastDigits?a.searchParams.set("last_digits",s.lastDigits):(s.strategy==="email_otp"&&s.redirectUri||s.strategy==="magic_link"&&s.redirectUri)&&a.searchParams.set("redirect_uri",s.redirectUri);const h=await t(a.pathname+a.search,{method:"POST"});return q(h)},completeProfile:async s=>{var c;if(!o)throw new Error("No signin attempt found");const a=new FormData;for(const[p,d]of Object.entries(s))d&&a.append(p,d);const h=await t(`/auth/complete-profile?attempt_id=${o.id}`,{method:"POST",body:a}),f=await q(h);if("data"in f&&f.data){const p=(c=f.data.signin_attempts)==null?void 0:c.find(d=>d.id===o.id);return p&&n(p),f.data}else throw new Error("Profile completion failed")},identify:async s=>{const a=await t("/auth/identify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:s})});if(!a.ok){const h=await a.json().catch(()=>({}));throw new Error(h.message||"Failed to identify user")}return a.json()},initEnterpriseSso:async(s,a)=>{const h=new URLSearchParams({connection_id:s});a&&h.append("redirect_uri",a);const f=await t(`/auth/sso/login?${h.toString()}`,{method:"POST"});if(!f.ok){const c=await f.json().catch(()=>({}));throw new Error(c.message||"Failed to initiate SSO")}return f.json()}},discardSignInAttempt:()=>{n(null)},setSignInAttempt:n}}function Dr(t){const{loading:r,signIn:o,signinAttempt:n,discardSignInAttempt:s,setSignInAttempt:a}=oc();if(r)return{loading:!0,signIn:null,signinAttempt:null,discardSignInAttempt:s,setSignInAttempt:a};const h=(()=>{switch(t){case"username":return o.createStrategy("username");case"email":return o.createStrategy("email");case"phone":return o.createStrategy("phone");case"email_otp":return o.createStrategy("email_otp");case"magic_link":return o.createStrategy("magic_link");case"oauth":return o.createStrategy("oauth");case"generic":return o.createStrategy("generic");default:throw new Error("Invalid sign-in strategy")}})();return{loading:!1,signinAttempt:n,signIn:{create:h,completeVerification:o.completeVerification,prepareVerification:o.prepareVerification,completeProfile:o.completeProfile,identify:o.identify,initEnterpriseSso:o.initEnterpriseSso},discardSignInAttempt:s,setSignInAttempt:a}}function Wd(t,r,o){return{create:async n=>{var f,c,p;const s=new FormData;for(const[d,u]of Object.entries(n))s.append(d,u);const a=await t("/auth/signup",{method:"POST",body:s}),h=await q(a);return"data"in h&&((c=(f=h.data)==null?void 0:f.signup_attempts)!=null&&c.length)&&o(((p=h.data.signup_attempts)==null?void 0:p.at(-1))||null),h},prepareVerification:async n=>{var h;const s=new URL("/auth/prepare-verification",window.location.origin);s.searchParams.set("attempt_identifier",((h=r==null?void 0:r.id)==null?void 0:h.toString())||""),s.searchParams.set("strategy",n.strategy),s.searchParams.set("identifier_type","signup"),n.strategy==="phone_otp"&&n.lastDigits?s.searchParams.set("last_digits",n.lastDigits):n.strategy==="email_otp"&&n.redirectUri&&s.searchParams.set("redirect_uri",n.redirectUri);const a=await t(s.pathname+s.search,{method:"POST"});return q(a)},completeVerification:async n=>{var f,c;const s=new FormData;s.append("verification_code",n);const a=await t(`/auth/attempt-verification?attempt_identifier=${r==null?void 0:r.id}&identifier_type=signup`,{method:"POST",body:s}),h=await q(a);return"data"in h&&((c=(f=h.data)==null?void 0:f.signup_attempts)!=null&&c.length)&&o(h.data.signup_attempts.at(-1)||null),h},validateDeploymentInvitation:async n=>{try{const s=await t(`/deployment/invitations/validate?token=${encodeURIComponent(n)}`,{method:"GET"}),a=await q(s);return"data"in a&&a.data?a.data:{valid:!1,message:"Failed to validate invitation",error_code:"VALIDATION_ERROR"}}catch(s){return{valid:!1,message:s.message||"Failed to validate invitation",error_code:"NETWORK_ERROR"}}}}}function nc(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(null);return r?{loading:!0,signUp:null,signupAttempt:null,discardSignupAttempt:()=>{n(null)}}:{loading:!1,signupAttempt:o,discardSignupAttempt:()=>{n(null)},signUp:Wd(t,o,n)}}const Ve=()=>{const{adapter:t,deployment:r}=ve(),o=t.useNavigate(),n=(f,c)=>{o?o(f,c):window.location.href=f};return{navigate:n,navigateToSignIn:f=>{if(!r)return;const c=f||window.location.href,p=new URLSearchParams;p.set("redirect_uri",c),(r==null?void 0:r.mode)==="staging"&&p.set("dev_session",localStorage.getItem("__dev_session__")??""),n(`${r.ui_settings.sign_in_page_url}?${p.toString()}`,{replace:!0})},navigateToAccountSelection:f=>{if(!r)return;const c=f||window.location.href,p=new URLSearchParams;p.set("redirect_uri",c),(r==null?void 0:r.mode)==="staging"&&p.set("dev_session",localStorage.getItem("__dev_session__")??""),n(`https://${r.frontend_host}?${p.toString()}`,{replace:!0})},navigateToSignUp:f=>{if(!r)return;const c=f||window.location.href,p=new URLSearchParams;p.set("redirect_uri",c),(r==null?void 0:r.mode)==="staging"&&p.set("dev_session",localStorage.getItem("__dev_session__")??""),n(`${r.ui_settings.sign_up_page_url}?${p.toString()}`,{replace:!0})}}};async function Vd(t){const r=await t("/session",{method:"GET"});return(await q(r)).data}async function Gd(t,r){const o=await t(`/session/switch-sign-in?sign_in_id=${r}`,{method:"POST"});return q(o)}async function Hd(t,r){const o=r?`/session/sign-out?sign_in_id=${r}`:"/session/sign-out",n=await t(o,{method:"POST"});return q(n)}async function qd(t,r){const o=await t(`/session/switch-organization${r?`?organization_id=${r}`:""}`,{method:"POST"});return q(o)}async function Yd(t,r){const o=await t(`/session/switch-workspace?workspace_id=${r}`,{method:"POST"});return q(o)}const ra=new Map,Tr=new Map;function zt(){ra.clear(),Tr.clear()}async function Zd(t,r){const o=await t(`/session/token${r?`?template=${r}`:""}`);return q(o)}function Be(){const{client:t,loading:r}=Fe(),{deployment:o}=ve(),{navigate:n}=Ve(),{cache:s}=Ji(),{data:a,error:h,mutate:f,isLoading:c}=Ne(r?null:"/session",()=>Vd(t),{refreshInterval:3e4,revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,dedupingInterval:5e3}),p=i.useCallback(async()=>{await f(void 0,{revalidate:!0})},[f]),d=i.useCallback(async(u="default")=>{if(!a)throw new Error("no session");const g=ra.get(u);if(g&&g.expires>Date.now())return(g==null?void 0:g.token)||"";Tr.get(u)||Tr.set(u,Zd(t,u));const m=await Tr.get(u);return Tr.delete(u),ra.set(u,m.data),m.data.token},[t,a==null?void 0:a.active_signin]);return r||!a||c?{loading:!0,error:h,session:null,switchSignIn:null,switchOrganization:null,switchWorkspace:null,signOut:null,getToken:null,refetch:p}:{loading:c,error:h,session:a,switchSignIn:async u=>{await Gd(t,u),await f(void 0,{revalidate:!0})},signOut:async u=>{await Hd(t,u);const g=["/session","/user","/me/signins","/me/organization-memberships","/me/workspace-memberships","wacht-notifications:channel-counts"],m=["wacht-notifications:","wacht-agent-sessions:","wacht-agent-contexts:","wacht-org-domains:","wacht-api-workspaces:","wacht-api-organizations:"];if(s instanceof Map){const v=Array.from(s.keys());for(const y of v){let S=!1;(g.includes(y)||typeof y=="string"&&m.some(E=>y.startsWith(E)))&&(S=!0),S&&s.delete(y)}}zt(),await f(void 0,{revalidate:!0}),o!=null&&o.ui_settings&&(u&&o.ui_settings.after_sign_out_one_page_url?n(o.ui_settings.after_sign_out_one_page_url):!u&&o.ui_settings.after_sign_out_all_page_url&&n(o.ui_settings.after_sign_out_all_page_url))},switchOrganization:async u=>{await qd(t,u),zt(),await f(void 0,{revalidate:!0})},switchWorkspace:async u=>{await Yd(t,u),zt(),await f(void 0,{revalidate:!0})},getToken:d,refetch:p}}const qo=()=>{const{organizationMemberships:t,refetch:r,loading:o}=bt(),{client:n}=Fe(),{refetch:s}=Be(),a=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/roles`,{method:"GET"}))).data,[n]),h=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/members`,{method:"GET"}))).data,[n]),f=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/invitations`,{method:"GET"}))).data,[n]),c=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/domains`,{method:"GET"}))).data,[n]),p=i.useCallback(async(P,z)=>{await n(`/organizations/${P.id}/members/${z.id}/remove`,{method:"POST"}),await r()},[r,n]),d=i.useCallback(async P=>{const z=new FormData;z.append("name",P.name),P.image&&z.append("image",P.image),P.description&&z.append("description",P.description);const T=await q(await n("/organizations",{method:"POST",body:z}));return zt(),await r(),await s(),T},[s,r,n]),u=i.useCallback(async(P,z)=>{const T=Object.entries(z).reduce((F,[G,L])=>(L&&F.append(G,L),F),new FormData),M=await q(await n(`/organizations/${P.id}/update`,{method:"POST",body:T}));return await r(),M},[r,n]),g=i.useCallback(async(P,z)=>{await n(`/organizations/${P.id}/roles/${z.id}/remove`,{method:"POST"})},[n]),m=i.useCallback(async(P,z)=>{const T=new FormData;return T.append("domain",z.fqdn),await q(await n(`/organizations/${P.id}/domains`,{method:"POST",body:T}))},[n]),v=i.useCallback(async(P,z)=>await q(await n(`/organizations/${P.id}/domains/${z.id}/verify`,{method:"POST"})),[n]),y=i.useCallback(async(P,z)=>await q(await n(`/organizations/${P.id}/domains/${z.id}/delete`,{method:"POST"})),[n]),S=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/enterprise-connections`,{method:"GET"}))).data,[n]),E=i.useCallback(async(P,z)=>{const T=new FormData;return T.append("protocol",z.protocol),T.append("idp_entity_id",z.idp_entity_id),T.append("idp_sso_url",z.idp_sso_url),T.append("idp_certificate",z.idp_certificate),z.domain_id&&T.append("domain_id",z.domain_id),(await q(await n(`/organizations/${P.id}/enterprise-connections`,{method:"POST",body:T}))).data},[n]),b=i.useCallback(async(P,z,T)=>{const M=new FormData;return T.idp_entity_id&&M.append("idp_entity_id",T.idp_entity_id),T.idp_sso_url&&M.append("idp_sso_url",T.idp_sso_url),T.idp_certificate&&M.append("idp_certificate",T.idp_certificate),T.domain_id&&M.append("domain_id",T.domain_id),(await q(await n(`/organizations/${P.id}/enterprise-connections/${z}/update`,{method:"POST",body:M}))).data},[n]),$=i.useCallback(async(P,z)=>{await n(`/organizations/${P.id}/enterprise-connections/${z}/delete`,{method:"POST"})},[n]),C=i.useCallback(async(P,z)=>{const T=new FormData;return T.append("name",z.name),z.permissions&&z.permissions.forEach((F,G)=>{T.append(`permissions[${G}]`,F)}),await q(await n(`/organizations/${P.id}/roles`,{method:"POST",body:T}))},[n]),w=i.useCallback(async P=>(await q(await n(`/organizations/${P.id}/leave`,{method:"POST"}))).data,[n]),j=i.useCallback(async P=>{const z=await q(await n(`/organizations/${P.id}/delete`,{method:"POST"}));return zt(),await r(),await s(),z.data},[n,r,s]),x=i.useCallback(async(P,z,T)=>(await q(await n(`/organizations/${P.id}/members/${z.id}/roles/${T.id}/add`,{method:"POST"}))).data,[n]),I=i.useCallback(async(P,z,T)=>(await q(await n(`/organizations/${P.id}/members/${z.id}/roles/${T.id}/remove`,{method:"POST"}))).data,[n]),k=i.useCallback(async(P,z)=>{var F,G;const T=new FormData;return T.append("email",z.email),T.append("role_id",z.organizationRole.id),(F=z.workspace)!=null&&F.id&&T.append("workspace_id",z.workspace.id),(G=z.workspaceRole)!=null&&G.id&&T.append("workspace_role_id",z.workspaceRole.id),(await q(await n(`/organizations/${P.id}/invitations`,{method:"POST",body:T}))).data},[n]),R=i.useCallback(async(P,z)=>(await q(await n(`/organizations/${P.id}/invitations/${z.id}/remove`,{method:"POST"}))).data,[n]),_=i.useCallback(async(P,z)=>(await q(await n(`/organizations/${P.id}/invitations/${z.id}/resend`,{method:"POST"}))).data,[n]);return{organizations:i.useMemo(()=>t==null?void 0:t.map(P=>P.organization),[t]),loading:o,error:null,refetch:r,leaveOrganization:w,getOrganizationRoles:a,getOrganizationMembers:h,removeOrganizationMember:p,createOrganization:d,getOrganizationInvitations:f,getOrganizationDomains:c,addOrganizationDomain:m,verifyOrganizationDomain:v,removeOrganizationDomain:y,addRoleToOrganizationMember:x,removeRoleFromOrganizationMember:I,inviteOrganizationMember:k,discardOrganizationInvitation:R,resendOrganizationInvitation:_,updateOrganization:u,addRole:C,removeOrganizationRoles:g,deleteOrganization:j,getEnterpriseConnections:S,createEnterpriseConnection:E,updateEnterpriseConnection:b,deleteEnterpriseConnection:$}},qe=()=>{const{loading:t,error:r,refetch:o,getOrganizationMembers:n,getOrganizationRoles:s,leaveOrganization:a,removeOrganizationMember:h,getOrganizationInvitations:f,getOrganizationDomains:c,removeOrganizationDomain:p,addOrganizationDomain:d,verifyOrganizationDomain:u,addRoleToOrganizationMember:g,removeRoleFromOrganizationMember:m,inviteOrganizationMember:v,discardOrganizationInvitation:y,resendOrganizationInvitation:S,updateOrganization:E,removeOrganizationRoles:b,getEnterpriseConnections:$,createEnterpriseConnection:C,updateEnterpriseConnection:w,deleteEnterpriseConnection:j}=qo(),{session:x,error:I,loading:k}=Be(),{organizationMemberships:R}=bt(),_=i.useMemo(()=>{var B;return((B=R==null?void 0:R.find(V=>{var D;return V.id===((D=x==null?void 0:x.active_signin)==null?void 0:D.active_organization_membership_id)}))==null?void 0:B.organization)||null},[R,x]),O=i.useCallback(async B=>_?await E(_,B):[],[_,E]),P=i.useCallback(async()=>_?await n(_):[],[_,n]),z=i.useCallback(async()=>_?await s(_):[],[_,s]),T=i.useCallback(async B=>_?await h(_,B):[],[_,h]),M=i.useCallback(async B=>_?await b(_,B):void 0,[_,b]),F=i.useCallback(async()=>_?await c(_):[],[_,c]),G=i.useCallback(async B=>_?await d(_,B):void 0,[_,d]),L=i.useCallback(async B=>_?await u(_,B):void 0,[_,u]),A=i.useCallback(async B=>_?await p(_,B):void 0,[_,p]),se=i.useCallback(async(B,V)=>_?await g(_,B,V):void 0,[_,g]),te=i.useCallback(async(B,V)=>_?await m(_,B,V):void 0,[_,m]),U=i.useCallback(async B=>_?await v(_,B):void 0,[_,v]),K=i.useCallback(async B=>_?await y(_,B):void 0,[_,y]),ee=i.useCallback(async B=>_?await S(_,B):void 0,[_,S]),J=i.useCallback(async()=>{_&&await a(_)},[_,a]),ie=i.useCallback(async()=>_?await f(_):[],[_,f]),oe=i.useCallback(async()=>_?await $(_):[],[_,$]),de=i.useCallback(async B=>{if(_)return await C(_,B)},[_,C]),Q=i.useCallback(async(B,V)=>{if(_)return await w(_,B,V)},[_,w]),ce=i.useCallback(async B=>{_&&await j(_,B)},[_,j]);return k||t?{activeOrganization:null,loading:!0,error:I||r,updateOrganization:null,getRoles:null,getMembers:null,getDomains:null,addDomain:null,verifyDomain:null,removeDomain:null,removeRole:null,getInvitations:null,removeMember:null,addMemberRole:null,removeMemberRole:null,inviteMember:null,discardInvitation:null,resendInvitation:null,leave:null,getEnterpriseConnections:null,createEnterpriseConnection:null,updateEnterpriseConnection:null,deleteEnterpriseConnection:null}:{activeOrganization:_,loading:!1,refetch:o,getRoles:z,updateOrganization:O,getMembers:P,getDomains:F,addDomain:G,verifyDomain:L,removeDomain:A,getInvitations:ie,removeMember:T,leave:J,removeRole:M,addMemberRole:se,removeMemberRole:te,inviteMember:U,discardInvitation:K,resendInvitation:ee,getEnterpriseConnections:oe,createEnterpriseConnection:de,updateEnterpriseConnection:Q,deleteEnterpriseConnection:ce,error:null}};async function Qd(t){return(await q(await t("/me/organization-memberships"))).data}const bt=()=>{const{client:t,loading:r}=Fe(),{data:o,isLoading:n,error:s,mutate:a}=Ne(r?null:"/me/organization-memberships",()=>Qd(t),{refreshInterval:3e4,revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,dedupingInterval:5e3}),h=i.useCallback(async()=>{await a(void 0,{revalidate:!0})},[a]);return{organizationMemberships:o,loading:r||n,error:s,refetch:h}};async function Kd(t){return(await q(await t("/me/workspace-memberships"))).data}async function Xd(t,r,o){return(await q(await t(`/workspaces/${r}/members/${o}/remove`,{method:"POST"}))).data}const Yo=()=>{const{client:t,loading:r}=Fe(),{deployment:o}=ve(),{data:n,isLoading:s,error:a,mutate:h}=Ne(!r&&(o!=null&&o.b2b_settings.workspaces_enabled)?"/me/workspace-memberships":null,()=>Kd(t),{refreshInterval:3e4,revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,dedupingInterval:5e3}),f=i.useCallback(async()=>{await h(void 0,{revalidate:!0})},[h]);return{workspaceMemberships:n,loading:r||s,error:a,refetch:f}},yt=()=>{const{workspaceMemberships:t,refetch:r,loading:o,error:n}=Yo(),{client:s}=Fe(),a=i.useMemo(()=>t==null?void 0:t.map(b=>({...b.workspace,organization:b.organization,eligibility_restriction:b.eligibility_restriction})),[t]),h=i.useCallback(async(b,$,C,w)=>{const j=new FormData;j.append("name",$),C&&j.append("image",C),w&&j.append("description",w),j.append("organization_id",b);const x=await q(await s("/workspaces",{method:"POST",body:j}));return zt(),await r(),x.data},[s,r]),f=i.useCallback(async(b,$)=>{const C=await Xd(s,b,$);return await r(),C},[s,r]),c=i.useCallback(async(b,$)=>{const C=new FormData;$.name&&C.append("name",$.name),$.description&&C.append("description",$.description),$.image&&C.append("image",$.image),$.enforce_2fa!==void 0&&C.append("enforce_2fa",String($.enforce_2fa)),$.enable_ip_restriction!==void 0&&C.append("enable_ip_restriction",String($.enable_ip_restriction)),$.whitelisted_ips&&$.whitelisted_ips.forEach(j=>C.append("whitelisted_ips",j));const w=await q(await s(`/workspaces/${b.id}/update`,{method:"POST",body:C}));return await r(),w.data},[s,r]),p=i.useCallback(async b=>{const $=await q(await s(`/workspaces/${b.id}/delete`,{method:"POST"}));return zt(),await r(),$.data},[s,r]),d=i.useCallback(async b=>(await q(await s(`/workspaces/${b.id}/members`,{method:"GET"}))).data,[s]),u=i.useCallback(async b=>(await q(await s(`/workspaces/${b.id}/roles`,{method:"GET"}))).data,[s]),g=i.useCallback(async(b,$,C)=>(await q(await s(`/workspaces/${b.id}/roles`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:$,permissions:C})}))).data,[s]),m=i.useCallback(async(b,$)=>(await q(await s(`/workspaces/${b.id}/roles/${$.id}/delete`,{method:"POST"}))).data,[s]),v=i.useCallback(async(b,$,C)=>(await q(await s(`/workspaces/${b.id}/members`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:$,role_id:C})}))).data,[s]),y=i.useCallback(async(b,$)=>{const C=await q(await s(`/workspaces/${b.id}/members/${$}/remove`,{method:"POST"}));return await r(),C.data},[s,r]),S=i.useCallback(async(b,$,C)=>(await q(await s(`/workspaces/${b.id}/members/${$}/roles/${C}/add`,{method:"POST"}))).data,[s]),E=i.useCallback(async(b,$,C)=>(await q(await s(`/workspaces/${b.id}/members/${$}/roles/${C}/remove`,{method:"POST"}))).data,[s]);return{workspaces:a||[],loading:o,error:n,refetch:r,leaveWorkspace:f,createWorkspace:h,updateWorkspace:c,deleteWorkspace:p,getWorkspaceMembers:d,getWorkspaceRoles:u,createWorkspaceRole:g,deleteWorkspaceRole:m,inviteWorkspaceMember:v,removeWorkspaceMember:y,addWorkspaceMemberRole:S,removeWorkspaceMemberRole:E}},Rt=()=>{const{refetch:t,loading:r,error:o,leaveWorkspace:n,updateWorkspace:s,deleteWorkspace:a,getWorkspaceMembers:h,getWorkspaceRoles:f,createWorkspaceRole:c,deleteWorkspaceRole:p,inviteWorkspaceMember:d,removeWorkspaceMember:u,addWorkspaceMemberRole:g,removeWorkspaceMemberRole:m}=yt(),{workspaceMemberships:v}=Yo(),{session:y,loading:S,error:E}=Be(),b=i.useMemo(()=>{var M;return((M=v==null?void 0:v.find(F=>{var G;return F.id===((G=y==null?void 0:y.active_signin)==null?void 0:G.active_workspace_membership_id)}))==null?void 0:M.workspace)||null},[v,y]),$=i.useCallback(async()=>{var M;if(!(!b||!((M=y==null?void 0:y.active_signin)!=null&&M.user_id)))return await n(b.id,y.active_signin.user_id)},[b,n,y]),C=i.useCallback(async M=>{if(b)return await s(b,M)},[b,s]),w=i.useCallback(async()=>{if(b)return await a(b)},[b,a]),j=i.useCallback(async()=>b?await h(b):[],[b,h]),x=i.useCallback(async()=>b?await f(b):[],[b,f]),I=i.useCallback(async(M,F)=>{if(b)return await c(b,M,F)},[b,c]),k=i.useCallback(async M=>{if(b)return await p(b,M)},[b,p]),R=i.useCallback(async(M,F)=>{if(b)return await d(b,M,F)},[b,d]),_=i.useCallback(async M=>{if(b)return await u(b,M)},[b,u]),O=i.useCallback(async(M,F)=>{if(b)return await g(b,M,F)},[b,g]),P=i.useCallback(async(M,F)=>{if(b)return await m(b,M,F)},[b,m]),z=r||S,T=o||E;return z?{activeWorkspace:null,loading:!0,error:T,refetch:t,leave:null,updateWorkspace:null,deleteWorkspace:null,getMembers:null,getRoles:null,createRole:null,deleteRole:null,inviteMember:null,removeMember:null,addMemberRole:null,removeMemberRole:null}:{activeWorkspace:b,loading:!1,error:T,refetch:t,leave:$,updateWorkspace:C,deleteWorkspace:w,getMembers:j,getRoles:x,createRole:I,deleteRole:k,inviteMember:R,removeMember:_,addMemberRole:O,removeMemberRole:P}},Jd=async t=>(await q(await t("/me"))).data,eu=async t=>(await q(await t("/me/signins"))).data;function rr(){const{client:t,loading:r}=Fe(),{data:o,error:n,isLoading:s,mutate:a}=Ne(r?null:"/user",()=>Jd(t)),h=async z=>{const T=new FormData;for(const[F,G]of Object.entries(z))G!=null&&G!==""&&T.append(F,String(G));const M=await q(await t("/me",{method:"POST",body:T}));return a(),M},f=async()=>await q(await t("/me/email-addresses",{method:"GET"})),c=async z=>await q(await t(`/me/email-addresses/${z}`,{method:"GET"})),p=async z=>{const T=new FormData;return T.append("email",z),await q(await t("/me/email-addresses",{method:"POST",body:T}))},d=async z=>await q(await t(`/me/email-addresses/${z}/delete`,{method:"POST"})),u=async z=>await q(await t(`/me/email-addresses/${z}/prepare-verification`,{method:"POST"})),g=async(z,T)=>await q(await t(`/me/email-addresses/${z}/attempt-verification?code=${T}`,{method:"POST"})),m=async(z,T)=>{const M=new FormData;return M.append("phone_number",z),M.append("country_code",T),await q(await t("/me/phone-numbers",{method:"POST",body:M}))},v=async z=>await q(await t(`/me/phone-numbers/${z}/delete`,{method:"POST"})),y=async z=>await q(await t(`/me/phone-numbers/${z}/prepare-verification`,{method:"POST"})),S=async(z,T)=>{const M=new FormData;return M.append("code",T),await q(await t(`/me/phone-numbers/${z}/attempt-verification`,{method:"POST",body:M}))},E=async z=>{const T=await q(await t(`/me/phone-numbers/${z}/make-primary`,{method:"POST"}));return a(),T},b=async z=>await q(await t(`/me/email-addresses/${z}/make-primary`,{method:"POST"})),$=async()=>(await q(await t("/me/authenticator",{method:"POST"}))).data,C=async(z,T)=>{const M=new FormData;return M.append("authenticator_id",z),T.forEach(G=>{M.append("codes",G)}),await q(await t("/me/authenticator/attempt-verification",{method:"POST",body:M}))},w=async z=>await q(await t(`/me/authenticator/${z}/delete`,{method:"POST"})),j=async()=>(await q(await t("/me/backup-codes",{method:"POST"}))).data,x=async z=>{const T=new FormData;return T.append("file",z),await q(await t("/me/profile-picture",{method:"POST",body:T}))},I=async()=>(await q(await t("/me/backup-codes/regenerate",{method:"POST"}))).data,k=async(z,T)=>{const M=new FormData;return M.append("current_password",z),M.append("new_password",T),await q(await t("/me/update-password",{method:"POST",body:M}))},R=async z=>{const T=new FormData;T.append("current_password",z);const M=await q(await t("/me/remove-password",{method:"POST",body:T}));return a(),M},_=async z=>{const T=new FormData;return T.append("password",z),await q(await t("/me/account/delete",{method:"POST",body:T}))},O=async z=>await q(await t(`/me/social-connections/${z}/disconnect`,{method:"POST"})),P=async({provider:z,redirectUri:T})=>{var G;const M=new URLSearchParams({provider:z});T&&M.append("redirect_uri",T);const F=await q(await t(`/me/init-sso-connection?${M.toString()}`,{method:"POST"}));return"data"in F&&((G=F.data)!=null&&G.oauth_url)&&window.open(F.data.oauth_url,"_blank"),F};return{user:{...o,refetch:a},loading:r||s,error:n||null,updateProfile:h,getEmailAddresses:f,getEmailAddress:c,createEmailAddress:p,deleteEmailAddress:d,prepareEmailVerification:u,attemptEmailVerification:g,makeEmailPrimary:b,createPhoneNumber:m,deletePhoneNumber:v,preparePhoneVerification:y,attemptPhoneVerification:S,makePhonePrimary:E,setupAuthenticator:$,verifyAuthenticator:C,deleteAuthenticator:w,generateBackupCodes:j,regenerateBackupCodes:I,updateProfilePicture:x,disconnectSocialConnection:O,connectSocialAccount:P,updatePassword:k,removePassword:R,deleteAccount:_}}function ac(){const{client:t,loading:r}=Fe(),{data:o,error:n,isLoading:s,mutate:a}=Ne(r?null:"/me/signins",()=>eu(t));return{signins:o,error:n||null,removeSignin:async f=>await q(await t(`/me/signins/${f}/signout`,{method:"POST"})),refetch:a,loading:s||r}}function tu(){const{session:t,loading:r}=Be(),{loading:o,organizationMemberships:n}=bt(),{loading:s,workspaceMemberships:a}=Yo();if(r||o||s)return{loading:!0,orgMembership:null,workspaceMembership:null};const h=i.useMemo(()=>!t||!t.signins||t.signins.length===0?null:n==null?void 0:n.find(c=>{var p;return c.id===((p=t.active_signin)==null?void 0:p.active_organization_membership_id)}),[t]),f=i.useMemo(()=>!t||!t.signins||t.signins.length===0?null:a==null?void 0:a.find(c=>{var p;return c.id===((p=t.active_signin)==null?void 0:p.active_workspace_membership_id)}),[t]);return{loading:!1,orgMembership:h,workspaceMembership:f}}function sc(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(!1),s=async a=>{n(!0);try{const h=new FormData;for(const[p,d]of Object.entries(a))d&&h.append(p,d);const f=await t("/waitlist/join",{method:"POST",body:h});return await q(f)}finally{n(!1)}};return r?{loading:!0,joinWaitlist:null}:{loading:o,joinWaitlist:s}}function ic(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(!1),[s,a]=i.useState(null),[h,f]=i.useState(null),[c,p]=i.useState(null),[d,u]=i.useState(!1),[g,m]=i.useState(null);i.useEffect(()=>{if(d||r)return;const y=new URLSearchParams(window.location.search),S=y.get("code"),E=y.get("state"),b=y.get("error"),$=y.get("error_description");if(!S&&!b){u(!0);const C=new Error("No OAuth callback data found.");a(C);return}if(u(!0),n(!0),b){const C=$||b,w=new Error(`OAuth Error: ${C}`);a(w),n(!1);return}if(S&&E)v(S,E);else{const C=new Error("Missing required OAuth parameters");a(C),n(!1)}},[d,r]);const v=async(y,S)=>{try{let E,b;try{const w=S.split(".");if(w.length!==2)throw new Error("Invalid OAuth state format - missing signature");const j=w[0].replace(/-/g,"+").replace(/_/g,"/"),x=j.length%4?"=".repeat(4-j.length%4):"",k=atob(j+x).split("|")[0];if(k==="sign_in")E="/auth/oauth2/callback",b="GET";else if(k==="connect_social")E="/me/sso-connection-callback",b="POST";else throw new Error(`Unknown OAuth action: ${k}`)}catch(w){const j=w instanceof Error?w:new Error("Failed to parse OAuth state");a(new Error(`Invalid OAuth callback: ${j.message}. The authorization link may be expired or malformed. Please try signing in again.`)),n(!1);return}const $=await t(`${E}?code=${encodeURIComponent(y)}&state=${encodeURIComponent(S)}`,{method:b}),C=await q($);if("data"in C){const w=C.data.session,j=C.data.redirect_uri||null;if(f(w),p(j),w.signin_attempts&&w.signin_attempts.length>0){const x=w.signin_attempts.at(-1);x&&m(x)}}else{const w=new Error("SSO callback failed");a(w)}}catch(E){const b=E instanceof Error?E:new Error("Unknown error occurred");a(b)}finally{n(!1)}};return{loading:o,error:s,session:h,redirectUri:c,processed:d,signinAttempt:g}}function cc(){const{client:t,loading:r}=Fe(),[o,n]=i.useState(!1),[s,a]=i.useState(null);return{loading:r||o,verifyMagicLink:async f=>{if(!f.token||!f.attempt)throw new Error("Invalid magic link parameters");n(!0),a(null);try{const c=new URL("/auth/verify-magic-link",window.location.origin);c.searchParams.set("token",f.token),c.searchParams.set("attempt",f.attempt),f.redirectUri&&c.searchParams.set("redirect_uri",f.redirectUri);const p=await t(c.pathname+c.search,{method:"GET"}),d=await q(p);return n(!1),a(!0),d}catch(c){throw n(!1),a(!1),c}},success:s}}function lc(){const[t,r]=i.useState({});return i.useEffect(()=>{const o=new URLSearchParams(window.location.search);r({token:o.get("token")||void 0,attempt:o.get("attempt")||void 0,redirectUri:o.get("redirect_uri")||void 0})},[]),t}function dc(){const{client:t,loading:r}=Fe();return{loading:r,forgotPassword:async a=>{const h=new FormData;h.append("email",a);const f=await t("/auth/forgot-password",{method:"POST",body:h});return await q(f)},verifyOtp:async(a,h)=>{const f=new FormData;f.append("email",a),f.append("otp",h);const c=await t("/auth/forgot-password",{method:"POST",body:f});return await q(c)},resetPassword:async(a,h)=>{const f=new FormData;f.append("token",a),f.append("password",h);const c=await t("/auth/reset-password",{method:"POST",body:f});return await q(c)}}}function uc({enabled:t=!0,channels:r,organizationIds:o,workspaceIds:n,onNotification:s,onError:a,reconnectDelay:h=1e3,maxReconnectAttempts:f=5}={}){const{session:c,loading:p}=Be(),{deployment:d,loading:u}=ve(),[g,m]=i.useState(!1),[v,y]=i.useState(null),S=i.useRef(null),E=i.useRef(null),b=i.useRef(0),$=i.useRef(null),C=i.useRef(s),w=i.useRef(a),j=i.useRef(r),x=i.useRef(o),I=i.useRef(n),k=i.useRef(h),R=i.useRef(f);C.current=s,w.current=a,j.current=r,x.current=o,I.current=n,k.current=h,R.current=f;const _=i.useCallback(()=>{E.current&&(clearTimeout(E.current),E.current=null),$.current&&(clearInterval($.current),$.current=null),S.current&&(S.current.close(),S.current=null)},[]),O=i.useCallback(async()=>{var G;if(!t||p||u||!c||!d)return;_();const T=new URL(d.backend_host),M=T.protocol==="https:"?"wss:":"ws:",F=new URL("/realtime/notifications",`${M}//${T.host}`);if(d.mode==="staging"){const L=localStorage.getItem("__dev_session__");L&&F.searchParams.set("__dev_session__",L)}j.current&&j.current.length>0&&j.current.forEach(L=>F.searchParams.append("channels",L)),x.current&&x.current.length>0&&x.current.forEach(L=>F.searchParams.append("organization_ids",L.toString())),I.current&&I.current.length>0&&I.current.forEach(L=>F.searchParams.append("workspace_ids",L.toString()));try{const L=new WebSocket(F.toString());S.current=L,L.onopen=()=>{m(!0),y(null),b.current=0,$.current=setInterval(()=>{L.readyState===WebSocket.OPEN&&L.send("ping")},3e4)},L.onmessage=A=>{var se,te;try{const U=JSON.parse(A.data);if(U.type==="notification"&&U.data)(se=C.current)==null||se.call(C,U.data);else if(U.type==="error"){const K=U.error||"Unknown error occurred";y(K),(te=w.current)==null||te.call(w,K)}else U.type}catch{}},L.onerror=()=>{var A;y("Connection error occurred"),(A=w.current)==null||A.call(w,"Connection error occurred")},L.onclose=A=>{var se;if(m(!1),$.current&&(clearInterval($.current),$.current=null),t&&A.code!==1e3&&b.current<R.current){b.current++;const te=k.current*Math.pow(2,b.current-1);E.current=setTimeout(()=>{O()},te)}else b.current>=R.current&&(y("Max reconnection attempts reached"),(se=w.current)==null||se.call(w,"Max reconnection attempts reached"))}}catch{y("Failed to connect"),(G=w.current)==null||G.call(w,"Failed to connect")}},[t,p,u,c,d,_]);i.useEffect(()=>(O(),()=>{_()}),[O,_]),i.useEffect(()=>{S.current&&S.current.readyState===WebSocket.OPEN&&O()},[r,o,n,O]);const P=i.useCallback(()=>{_(),m(!1)},[_]),z=i.useCallback(()=>{b.current=0,O()},[O]);return{isConnected:g,connectionError:v,disconnect:P,reconnect:z}}async function ru(t,r){const o=new URLSearchParams;r&&(r.limit&&o.append("limit",r.limit.toString()),r.offset&&o.append("offset",r.offset.toString()),r.channels&&r.channels.forEach(h=>o.append("channels",h)),r.organization_ids&&r.organization_ids.forEach(h=>o.append("organization_ids",h.toString())),r.workspace_ids&&r.workspace_ids.forEach(h=>o.append("workspace_ids",h.toString())),r.is_read!==void 0&&o.append("is_read",r.is_read.toString()),r.is_archived!==void 0&&o.append("is_archived",r.is_archived.toString()),r.severity&&o.append("severity",r.severity));const n=`/notifications${o.toString()?"?"+o.toString():""}`,s=await t(n,{method:"GET"});return(await q(s)).data}async function ou(t){const r=await t("/notifications/channel-counts",{method:"GET"});return(await q(r)).data}async function nu(t,r){const o=await t(`/notifications/${r}/read`,{method:"POST"});return q(o)}async function au(t){const r=await t("/notifications/mark-all-read",{method:"POST"});return q(r)}async function su(t,r){const o=await t(`/notifications/${r}/delete`,{method:"POST"});return q(o)}function pc(t){const{client:r,loading:o}=Fe(),{data:n,error:s,mutate:a,isLoading:h}=Ne(o?null:`wacht-notifications:${JSON.stringify(t)}`,()=>ru(r,t),{refreshInterval:6e4,revalidateOnFocus:!0});uc({enabled:!o&&!!n,onNotification:i.useCallback(u=>{a(async g=>!g||g.notifications.some(v=>v.id===u.id.toString())?g:{...g,notifications:[{id:u.id.toString(),user_id:u.user_id.toString(),deployment_id:u.deployment_id.toString(),title:u.title,body:u.body,severity:u.severity,action_url:u.action_url,action_label:u.action_label,is_read:!1,is_archived:!1,created_at:u.created_at,updated_at:u.created_at},...g.notifications],unread_count:g.unread_count+1,total:g.total+1},!1)},[a]),onError:i.useCallback(()=>{},[])});const f=i.useCallback(async u=>{o||(await a(async g=>g&&{...g,notifications:g.notifications.map(m=>m.id===u?{...m,is_read:!0}:m),unread_count:Math.max(0,g.unread_count-1)},!1),await nu(r,u),await a())},[r,o,a]),c=i.useCallback(async()=>{o||(await a(async u=>u&&{...u,notifications:u.notifications.map(g=>({...g,is_read:!0})),unread_count:0},!1),await au(r),await a())},[r,a]),p=i.useCallback(async u=>{o||(await a(async g=>{if(!g)return g;const m=g.notifications.find(v=>v.id===u);return{...g,notifications:g.notifications.filter(v=>v.id!==u),unread_count:m&&!m.is_read?Math.max(0,g.unread_count-1):g.unread_count,total:Math.max(0,g.total-1)}},!1),await su(r,u),await a())},[r,o,a]),d=i.useCallback(async()=>{await a()},[a]);return!n||o||h?{loading:!0,notifications:void 0,unreadCount:void 0,unreadCounts:void 0,channels:void 0,hasMore:void 0,markAsRead:void 0,markAllAsRead:void 0,deleteNotification:void 0,error:s,refetch:d}:{loading:!1,error:s,notifications:n.notifications,unreadCount:n.unread_count,unreadCounts:n.unread_counts,channels:n.channels,hasMore:n.has_more,markAsRead:f,markAllAsRead:c,deleteNotification:p,refetch:d}}async function iu(t){const r=await t("/notifications/channel-counts",{method:"GET"});return(await q(r)).data}function cu(){const{client:t,loading:r}=Fe(),{data:o,error:n,mutate:s}=Ne(r?null:"wacht-notifications:channel-counts",()=>iu(t),{refreshInterval:3e4,revalidateOnFocus:!0}),a=async()=>{await s()};return!o||r?{loading:!0,counts:void 0,error:n,refetch:a}:{loading:!1,counts:o,error:n,refetch:a}}const Ht=class Ht{constructor(){tt(this,"ws",null);tt(this,"messageHandlers",new Set);tt(this,"connectionStateHandlers",new Set);tt(this,"reconnectTimer",null);tt(this,"reconnectAttempts",0);tt(this,"url",null);tt(this,"isIntentionalDisconnect",!1);tt(this,"sessionMessages",{});tt(this,"currentSessionKey",null)}static getInstance(){return Ht.instance||(Ht.instance=new Ht),Ht.instance}connect(r){var o,n;if(this.url=r,this.isIntentionalDisconnect=!1,((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN&&this.url===r){this.notifyConnectionState({isConnected:!0});return}((n=this.ws)==null?void 0:n.readyState)!==WebSocket.CONNECTING&&this.createConnection()}createConnection(){if(this.url)try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,this.notifyConnectionState({isConnected:!0})},this.ws.onmessage=r=>{try{const o=JSON.parse(r.data);this.notifyMessageHandlers(o)}catch{}},this.ws.onerror=()=>{this.notifyConnectionState({isConnected:!1,error:"Connection error"})},this.ws.onclose=()=>{this.ws=null,this.notifyConnectionState({isConnected:!1}),this.isIntentionalDisconnect||this.scheduleReconnect()}}catch(r){this.notifyConnectionState({isConnected:!1,error:r instanceof Error?r.message:"Failed to connect"})}}scheduleReconnect(){this.reconnectAttempts++;const r=Math.min(1e3*Math.pow(2,this.reconnectAttempts-1),3e4),o=Math.random()*.3*r,n=Math.floor(r+o);this.reconnectTimer=setTimeout(()=>{this.createConnection()},n)}disconnect(){this.isIntentionalDisconnect=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null)}send(r){var o;if(((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN){const n=JSON.stringify(r);this.ws.send(n)}}onMessage(r){return this.messageHandlers.add(r),()=>{this.messageHandlers.delete(r)}}onConnectionStateChange(r){var o;return this.connectionStateHandlers.add(r),r({isConnected:((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN}),()=>{this.connectionStateHandlers.delete(r)}}notifyMessageHandlers(r){this.messageHandlers.forEach(o=>{try{o(r)}catch{}})}notifyConnectionState(r){this.connectionStateHandlers.forEach(o=>{try{o(r)}catch{}})}isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}setCurrentSession(r){this.currentSessionKey=r,this.sessionMessages[r]||(this.sessionMessages[r]=[])}addMessage(r){this.currentSessionKey&&(this.sessionMessages[this.currentSessionKey]||(this.sessionMessages[this.currentSessionKey]=[]),this.sessionMessages[this.currentSessionKey].push(r))}getSessionMessages(r){return this.sessionMessages[r]||[]}clearSessionMessages(r){this.sessionMessages[r]&&(this.sessionMessages[r]=[])}};tt(Ht,"instance");let oa=Ht;const Qe=oa.getInstance(),mt={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",ERROR:"error"},Ae={IDLE:"idle",STARTING:"starting",RUNNING:"running",WAITING_FOR_INPUT:"waiting_for_input",COMPLETED:"completed",FAILED:"failed"},Ot={IDLE:"Idle",STARTING:"Starting",RUNNING:"Running",WAITING_FOR_INPUT:"WaitingForInput",COMPLETED:"Completed",FAILED:"Failed",CANCELLED:"Cancelled"};function Ua(t){switch(t){case Ot.IDLE:return Ae.IDLE;case Ot.STARTING:return Ae.STARTING;case Ot.RUNNING:return Ae.RUNNING;case Ot.WAITING_FOR_INPUT:return Ae.WAITING_FOR_INPUT;case Ot.COMPLETED:return Ae.COMPLETED;case Ot.FAILED:case Ot.CANCELLED:return Ae.FAILED;default:return Ae.IDLE}}function Wa(t){return t===Ae.STARTING||t===Ae.RUNNING||t===Ae.WAITING_FOR_INPUT}function hc({contextId:t,agentName:r,token:o,platformAdapter:n,autoConnect:s=!0}){const{deployment:a}=ve(),{client:h}=Fe(),[f,c]=i.useState([]),[p,d]=i.useState(null),[u,g]=i.useState(null),[m,v]=i.useState(!1),[y,S]=i.useState(!1),[E,b]=i.useState(Ae.IDLE),[$,C]=i.useState({status:mt.DISCONNECTED}),[w,j]=i.useState(!0),[x,I]=i.useState(!1),k=i.useRef(null),R=i.useRef(null),_=i.useCallback(U=>{var K,ee;switch(U.message_type){case"session_connected":if(v(!0),C({status:mt.CONNECTED}),(K=U.data)!=null&&K.execution_status){const ie=U.data.execution_status,oe=Ua(ie);b(oe),S(Wa(oe))}break;case"conversation_message":O(U.data);break;case"user_input_request":P(U.data);break;case"platform_event":z(U.data);break;case"platform_function":T(U.data);break;case"execution_complete":S(!1),b(Ae.IDLE),R.current=null;break;case"execution_error":S(!1),b(Ae.FAILED),R.current=null;break;case"execution_cancelled":S(!1),b(Ae.IDLE),R.current=null;break;case"execution_status":const J=(ee=U.data)==null?void 0:ee.status;if(J){const ie=Ua(J);b(ie),S(Wa(ie))}break}},[p]),O=i.useCallback(U=>{var oe,de,Q,ce,B,V,D,le;const{id:K,message_type:ee,content:J}=U,ie=H=>f.some(ae=>ae.id===H);if(ee==="system_decision"||ee==="action_execution_result"||ee==="assistant_task_breakdown"||ee==="assistant_validation"||ee==="assistant_action_planning"||ee==="context_results"){d(null),g(null);let H="";if(ee==="system_decision"){const ae=J==null?void 0:J.step,ke=J==null?void 0:J.reasoning;if(ae==="gathercontext")ke&&ke.length>0?H=ke.length>60?`${ke.substring(0,60)}...`:ke:H="Gathering context...";else if(ae==="executeaction")H="Executing action";else if(ae==="deliverresponse")H="Preparing response";else if(ae==="taskplanning")H="Planning approach";else if(ae==="validateprogress")H="Validating progress";else if(ae==="acknowledge")H="Processing request";else if(ae==="finishplanning")H="Finalizing plan";else if(ae==="executetasks")H="Executing tasks";else if(ae==="requestuserinput")H="Waiting for input";else if(ae==="complete")H="Completed";else if(ae==="examinetool")H="Examining tool";else if(ae==="examineworkflow")H="Examining workflow";else{const ne=(J==null?void 0:J.confidence)||.5;ne>.8?H="Analyzing":ne>.6?H="Thinking":H="Reasoning"}}else if(ee==="action_execution_result")((oe=J.task_execution)==null?void 0:oe.status)==="completed"?H="Task execution completed":(de=J.task_execution)!=null&&de.approach?H=J.task_execution.approach:H="Executing task";else if(ee==="assistant_task_breakdown")(Q=J.task_breakdown)!=null&&Q.total_tasks?H=`Identified ${J.task_breakdown.total_tasks} tasks`:H="Planning tasks";else if(ee==="assistant_validation")H="Validated results";else if(ee==="assistant_action_planning")(ce=J.task_execution)!=null&&ce.total_tasks?H=`Planned ${J.task_execution.total_tasks} tasks`:(V=(B=J.task_execution)==null?void 0:B.tasks)!=null&&V.length?H=`Planned ${J.task_execution.tasks.length} tasks`:H="Planning actions";else if(ee==="context_results"){const ae=J.query,ke=J.result_count||0;ae&&ae!=="General context gathering"?H=`${ae}: Found ${ke} results`:H=`Found ${ke} results`}H&&!ie(K)&&c(ae=>[...ae,{id:K,role:"system",content:H,timestamp:new Date,metadata:{type:"log",messageType:ee}}]);return}if(ee==="user_message")ie(K)||(d(null),g(null),c(H=>[...H,{id:K,role:"user",content:J.message,images:J.images,timestamp:new Date}]));else if(ee==="agent_response")ie(K)||(d(null),g(null),S(!1),b(Ae.IDLE),R.current=null,c(H=>[...H,{id:K,role:"assistant",content:J.response,timestamp:new Date,isStreaming:!1}]));else if(ee==="assistant_acknowledgment")ie(K)||(d(null),g(null),c(H=>[...H,{id:K,role:"assistant",content:J.acknowledgment_message,timestamp:new Date}]));else if(ee==="assistant_ideation"||ee==="assistant_action_planning"||ee==="action_execution_result"||ee==="assistant_validation"||ee==="assistant_context_gathering"||ee==="assistant_task_breakdown"){let H="";if(J.reasoning_summary)H=J.reasoning_summary;else if((D=J.task_execution)!=null&&D.approach)H=J.task_execution.approach;else if(J.strategic_synthesis)H=J.strategic_synthesis;else if((le=J.task_breakdown)!=null&&le.total_tasks)H=`Breaking down into ${J.task_breakdown.total_tasks} tasks...`;else if(J.acknowledgment_message)H=J.acknowledgment_message;else return;c(ae=>[...ae,{id:K,role:"assistant",content:H,timestamp:new Date}])}else if(ee==="user_input_request"){const H={question:J.question,context:J.context,input_type:J.input_type,options:J.options||J.suggestions,default_value:J.default_value,placeholder:J.placeholder};b("waiting_for_input"),c(ae=>[...ae,{id:K,role:"system",content:H.question,timestamp:new Date,metadata:{type:"user_input_request",userInputRequest:H}}])}},[]),P=i.useCallback(async U=>{b("waiting_for_input");const K=`input-request-${Date.now()}`;c(ee=>[...ee,{id:K,role:"system",content:U.question,timestamp:new Date,metadata:{type:"user_input_request",userInputRequest:U}}])},[]),z=i.useCallback(U=>{const{event_label:K,event_data:ee}=U;n!=null&&n.onPlatformEvent&&n.onPlatformEvent(K,ee)},[n]),T=i.useCallback(async U=>{const{function_name:K,function_data:ee}=U,{parameters:J,execution_id:ie}=ee;if(!(n!=null&&n.onPlatformFunction)){Qe.send({message_type:{platform_function_result:[ie,{error:"No platform function handler registered"}]},data:{}});return}try{const oe=await n.onPlatformFunction(K,J,ie),de={message_type:{platform_function_result:[ie,oe]},data:{}};Qe.send(de)}catch(oe){Qe.send({message_type:{platform_function_result:[ie,{error:oe instanceof Error?oe.message:"Function execution failed",stack:oe instanceof Error?oe.stack:void 0}]},data:{}})}},[n]);i.useEffect(()=>{if(!a)return;const K=`wss://${a==null?void 0:a.backend_host.replace(/https?:\/\//,"")}/realtime/agent?token=${encodeURIComponent(o)}`;C({status:mt.CONNECTING}),Qe.connect(K)},[a,o]),i.useEffect(()=>Qe.onConnectionStateChange(K=>{C({status:K.isConnected?mt.CONNECTED:K.error?mt.ERROR:mt.DISCONNECTED}),v(K.isConnected)}),[]),i.useEffect(()=>Qe.onMessage(_),[_]),i.useEffect(()=>{m&&t&&r&&s&&Qe.send({message_type:{session_connect:[t,r]},data:{}})},[m,t,r,s]);const M=i.useCallback(async()=>(m&&t&&r&&Qe.send({message_type:{session_connect:[t,r]},data:{}}),()=>{}),[m,t,r]),F=i.useCallback((U,K)=>{m&&(d(U),g(K||null),S(!0),b(Ae.STARTING),Qe.send({message_type:{message_input:U},data:K?{images:K}:{}}))},[m]),G=i.useCallback(()=>{c([]),R.current=null},[]),L=i.useCallback(U=>{!m||E!==Ae.WAITING_FOR_INPUT||(Qe.send({message_type:{user_input_response:U},data:{}}),b(Ae.RUNNING))},[m,E]),A=i.useCallback(async U=>{var K;if(!(!o||!t))try{const ee=new URLSearchParams({token:o,limit:"50"});U&&(ee.append("before_id",U),I(!0));const ie=await(await h(`/api/agent/contexts/${t}/messages?${ee}`,{method:"GET"})).json();if(ie.status===200&&ie.data){const oe=ie.data;if(Array.isArray(oe.data)){const de=oe.data.filter(Q=>{var V;let ce=Q.content;if(typeof Q.content=="string")try{ce=JSON.parse(Q.content)}catch{ce={message:Q.content}}const B=((V=Q.metadata)==null?void 0:V.message_type)||(ce==null?void 0:ce.message_type);return B==="user_message"||B==="agent_response"||B==="assistant_acknowledgment"||B==="user_input_request"||B==="system_decision"||B==="action_execution_result"||B==="assistant_task_breakdown"||B==="assistant_validation"||B==="assistant_action_planning"||B==="context_results"}).map(Q=>{var H,ae,ke,ne,Y,Z,N;let ce="",B,V,D=Q.content;if(typeof Q.content=="string")try{D=JSON.parse(Q.content)}catch{D=Q.content}const le=((H=Q.metadata)==null?void 0:H.message_type)||(D==null?void 0:D.message_type);if(le==="user_message"?(ce=(D==null?void 0:D.message)||"",B=(D==null?void 0:D.images)||void 0):le==="agent_response"?ce=(D==null?void 0:D.response)||"":le==="assistant_acknowledgment"?ce=(D==null?void 0:D.acknowledgment_message)||"":le==="user_input_request"&&(ce=(D==null?void 0:D.question)||"",V={type:"user_input_request",userInputRequest:{question:(D==null?void 0:D.question)||"",context:(D==null?void 0:D.context)||"",input_type:(D==null?void 0:D.input_type)||"text",options:(D==null?void 0:D.options)||(D==null?void 0:D.suggestions)||[],default_value:(D==null?void 0:D.default_value)||"",placeholder:(D==null?void 0:D.placeholder)||""}}),le==="system_decision"||le==="action_execution_result"||le==="assistant_task_breakdown"||le==="assistant_validation"||le==="assistant_action_planning"||le==="context_results"){let W="";if(le==="system_decision"){const fe=D==null?void 0:D.step,ye=D==null?void 0:D.reasoning;if(fe==="gathercontext")ye&&ye.length>0?W=ye.length>60?`${ye.substring(0,60)}...`:ye:W="Gathering context...";else if(fe==="executeaction")W="Executing action";else if(fe==="deliverresponse")W="Preparing response";else if(fe==="taskplanning")W="Planning approach";else if(fe==="validateprogress")W="Validating progress";else if(fe==="acknowledge")W="Processing request";else if(fe==="finishplanning")W="Finalizing plan";else if(fe==="executetasks")W="Executing tasks";else if(fe==="requestuserinput")W="Waiting for input";else if(fe==="complete")W="Completed";else if(fe==="examinetool")W="Examining tool";else if(fe==="examineworkflow")W="Examining workflow";else{const re=(D==null?void 0:D.confidence)||.5;re>.8?W="Analyzing":re>.6?W="Thinking":W="Reasoning"}}else if(le==="action_execution_result")((ae=D==null?void 0:D.task_execution)==null?void 0:ae.status)==="completed"?W="Task execution completed":(ke=D==null?void 0:D.task_execution)!=null&&ke.approach?W=D.task_execution.approach:W="Executing task";else if(le==="assistant_task_breakdown")(ne=D==null?void 0:D.task_breakdown)!=null&&ne.total_tasks?W=`Identified ${D.task_breakdown.total_tasks} tasks`:W="Planning tasks";else if(le==="assistant_validation")W="Validated results";else if(le==="assistant_action_planning")(Y=D==null?void 0:D.task_execution)!=null&&Y.total_tasks?W=`Planned ${D.task_execution.total_tasks} tasks`:(N=(Z=D==null?void 0:D.task_execution)==null?void 0:Z.tasks)!=null&&N.length?W=`Planned ${D.task_execution.tasks.length} tasks`:W="Planning actions";else if(le==="context_results"){const fe=D==null?void 0:D.query,ye=(D==null?void 0:D.result_count)||0;fe&&fe!=="General context gathering"?W=`${fe}: Found ${ye} results`:W=`Found ${ye} results`}ce=W,V={type:"log",messageType:le}}return{id:Q.id,role:le==="user_message"?"user":le==="user_input_request"?"system":"assistant",content:ce,images:B,timestamp:new Date(Q.timestamp||Q.created_at||Date.now()),metadata:V}}).filter(Q=>Q.content||Q.metadata||Q.images).sort((Q,ce)=>{const B=BigInt(Q.id),V=BigInt(ce.id);return B<V?-1:B>V?1:0});de.length>0&&(k.current=de[0].id),U?(c(Q=>[...de,...Q]),j(de.length>=50)):(c(de),de.length>0&&((K=de[de.length-1].metadata)==null?void 0:K.type)==="user_input_request"&&b(Ae.WAITING_FOR_INPUT)),I(!1)}}}catch(ee){console.error("Failed to fetch messages:",ee),I(!1)}},[o,t,h]);i.useEffect(()=>{t&&o&&A()},[t,o]);const se=i.useCallback(async()=>{if(!(x||!w||!k.current)){I(!0);try{await A(k.current)}finally{I(!1)}}},[x,w,A]),te=i.useCallback(()=>{!m||!y||(Qe.send({message_type:{cancel_execution:null},data:{}}),S(!1),b("idle"))},[m,y]);return{messages:f,pendingMessage:p,pendingImages:u,connectionState:$,isConnected:m,isExecuting:y,executionStatus:E,isWaitingForInput:E==="waiting_for_input",hasMoreMessages:w,isLoadingMore:x,sendMessage:F,submitUserInput:L,clearMessages:G,loadMoreMessages:se,cancelExecution:te,connect:M,disconnect:()=>Qe.disconnect()}}const fc=()=>{const{client:t}=Fe(),[r,o]=i.useState(!1),[n,s]=i.useState(null),[a,h]=i.useState(null),f=i.useCallback(async p=>{o(!0),s(null),h(null);try{const d=await t("/organizations/invitations/accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:p})}),g=(await q(d)).data;return h(g),g.error_code&&s(g.message||"Failed to accept invitation"),g}catch(d){const u=d.message||"Failed to accept invitation";s(u);const g={error_code:"NETWORK_ERROR",message:u};return h(g),g}finally{o(!1)}},[t]),c=i.useCallback(()=>{s(null),h(null)},[]);return{acceptInvitation:f,invitationData:a,loading:r,error:n,reset:c}},lu=({children:t})=>{const{loading:r}=ve();return r?null:e.jsx(e.Fragment,{children:t})},du=({children:t})=>{const{loading:r}=ve();return r?e.jsx(e.Fragment,{children:t}):null};var He=function(){return He=Object.assign||function(r){for(var o,n=1,s=arguments.length;n<s;n++){o=arguments[n];for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(r[a]=o[a])}return r},He.apply(this,arguments)};function Xt(t,r,o){if(o||arguments.length===2)for(var n=0,s=r.length,a;n<s;n++)(a||!(n in r))&&(a||(a=Array.prototype.slice.call(r,0,n)),a[n]=r[n]);return t.concat(a||Array.prototype.slice.call(r))}function uu(t){var r=Object.create(null);return function(o){return r[o]===void 0&&(r[o]=t(o)),r[o]}}var pu=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/,hu=uu(function(t){return pu.test(t)||t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&t.charCodeAt(2)<91}),Pe="-ms-",Lr="-moz-",$e="-webkit-",gc="comm",Zo="rule",ba="decl",fu="@import",mc="@keyframes",gu="@layer",xc=Math.abs,ya=String.fromCharCode,na=Object.assign;function mu(t,r){return Ue(t,0)^45?(((r<<2^Ue(t,0))<<2^Ue(t,1))<<2^Ue(t,2))<<2^Ue(t,3):0}function vc(t){return t.trim()}function gt(t,r){return(t=r.exec(t))?t[0]:t}function xe(t,r,o){return t.replace(r,o)}function zo(t,r,o){return t.indexOf(r,o)}function Ue(t,r){return t.charCodeAt(r)|0}function mr(t,r,o){return t.slice(r,o)}function it(t){return t.length}function bc(t){return t.length}function Or(t,r){return r.push(t),t}function xu(t,r){return t.map(r).join("")}function Va(t,r){return t.filter(function(o){return!gt(o,r)})}var Qo=1,xr=1,yc=0,Xe=0,De=0,kr="";function Ko(t,r,o,n,s,a,h,f){return{value:t,root:r,parent:o,type:n,props:s,children:a,line:Qo,column:xr,length:h,return:"",siblings:f}}function St(t,r){return na(Ko("",null,null,"",null,null,0,t.siblings),t,{length:-t.length},r)}function sr(t){for(;t.root;)t=St(t.root,{children:[t]});Or(t,t.siblings)}function vu(){return De}function bu(){return De=Xe>0?Ue(kr,--Xe):0,xr--,De===10&&(xr=1,Qo--),De}function rt(){return De=Xe<yc?Ue(kr,Xe++):0,xr++,De===10&&(xr=1,Qo++),De}function Yt(){return Ue(kr,Xe)}function Eo(){return Xe}function Xo(t,r){return mr(kr,t,r)}function aa(t){switch(t){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function yu(t){return Qo=xr=1,yc=it(kr=t),Xe=0,[]}function wu(t){return kr="",t}function gn(t){return vc(Xo(Xe-1,sa(t===91?t+2:t===40?t+1:t)))}function ju(t){for(;(De=Yt())&&De<33;)rt();return aa(t)>2||aa(De)>3?"":" "}function ku(t,r){for(;--r&&rt()&&!(De<48||De>102||De>57&&De<65||De>70&&De<97););return Xo(t,Eo()+(r<6&&Yt()==32&&rt()==32))}function sa(t){for(;rt();)switch(De){case t:return Xe;case 34:case 39:t!==34&&t!==39&&sa(De);break;case 40:t===41&&sa(t);break;case 92:rt();break}return Xe}function _u(t,r){for(;rt()&&t+De!==57;)if(t+De===84&&Yt()===47)break;return"/*"+Xo(r,Xe-1)+"*"+ya(t===47?t:rt())}function Cu(t){for(;!aa(Yt());)rt();return Xo(t,Xe)}function Su(t){return wu(Po("",null,null,null,[""],t=yu(t),0,[0],t))}function Po(t,r,o,n,s,a,h,f,c){for(var p=0,d=0,u=h,g=0,m=0,v=0,y=1,S=1,E=1,b=0,$="",C=s,w=a,j=n,x=$;S;)switch(v=b,b=rt()){case 40:if(v!=108&&Ue(x,u-1)==58){zo(x+=xe(gn(b),"&","&\f"),"&\f",xc(p?f[p-1]:0))!=-1&&(E=-1);break}case 34:case 39:case 91:x+=gn(b);break;case 9:case 10:case 13:case 32:x+=ju(v);break;case 92:x+=ku(Eo()-1,7);continue;case 47:switch(Yt()){case 42:case 47:Or($u(_u(rt(),Eo()),r,o,c),c);break;default:x+="/"}break;case 123*y:f[p++]=it(x)*E;case 125*y:case 59:case 0:switch(b){case 0:case 125:S=0;case 59+d:E==-1&&(x=xe(x,/\f/g,"")),m>0&&it(x)-u&&Or(m>32?Ha(x+";",n,o,u-1,c):Ha(xe(x," ","")+";",n,o,u-2,c),c);break;case 59:x+=";";default:if(Or(j=Ga(x,r,o,p,d,s,f,$,C=[],w=[],u,a),a),b===123)if(d===0)Po(x,r,j,j,C,a,u,f,w);else switch(g===99&&Ue(x,3)===110?100:g){case 100:case 108:case 109:case 115:Po(t,j,j,n&&Or(Ga(t,j,j,0,0,s,f,$,s,C=[],u,w),w),s,w,u,f,n?C:w);break;default:Po(x,j,j,j,[""],w,0,f,w)}}p=d=m=0,y=E=1,$=x="",u=h;break;case 58:u=1+it(x),m=v;default:if(y<1){if(b==123)--y;else if(b==125&&y++==0&&bu()==125)continue}switch(x+=ya(b),b*y){case 38:E=d>0?1:(x+="\f",-1);break;case 44:f[p++]=(it(x)-1)*E,E=1;break;case 64:Yt()===45&&(x+=gn(rt())),g=Yt(),d=u=it($=x+=Cu(Eo())),b++;break;case 45:v===45&&it(x)==2&&(y=0)}}return a}function Ga(t,r,o,n,s,a,h,f,c,p,d,u){for(var g=s-1,m=s===0?a:[""],v=bc(m),y=0,S=0,E=0;y<n;++y)for(var b=0,$=mr(t,g+1,g=xc(S=h[y])),C=t;b<v;++b)(C=vc(S>0?m[b]+" "+$:xe($,/&\f/g,m[b])))&&(c[E++]=C);return Ko(t,r,o,s===0?Zo:f,c,p,d,u)}function $u(t,r,o,n){return Ko(t,r,o,gc,ya(vu()),mr(t,2,-2),0,n)}function Ha(t,r,o,n,s){return Ko(t,r,o,ba,mr(t,0,n),mr(t,n+1,-1),n,s)}function wc(t,r,o){switch(mu(t,r)){case 5103:return $e+"print-"+t+t;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return $e+t+t;case 4789:return Lr+t+t;case 5349:case 4246:case 4810:case 6968:case 2756:return $e+t+Lr+t+Pe+t+t;case 5936:switch(Ue(t,r+11)){case 114:return $e+t+Pe+xe(t,/[svh]\w+-[tblr]{2}/,"tb")+t;case 108:return $e+t+Pe+xe(t,/[svh]\w+-[tblr]{2}/,"tb-rl")+t;case 45:return $e+t+Pe+xe(t,/[svh]\w+-[tblr]{2}/,"lr")+t}case 6828:case 4268:case 2903:return $e+t+Pe+t+t;case 6165:return $e+t+Pe+"flex-"+t+t;case 5187:return $e+t+xe(t,/(\w+).+(:[^]+)/,$e+"box-$1$2"+Pe+"flex-$1$2")+t;case 5443:return $e+t+Pe+"flex-item-"+xe(t,/flex-|-self/g,"")+(gt(t,/flex-|baseline/)?"":Pe+"grid-row-"+xe(t,/flex-|-self/g,""))+t;case 4675:return $e+t+Pe+"flex-line-pack"+xe(t,/align-content|flex-|-self/g,"")+t;case 5548:return $e+t+Pe+xe(t,"shrink","negative")+t;case 5292:return $e+t+Pe+xe(t,"basis","preferred-size")+t;case 6060:return $e+"box-"+xe(t,"-grow","")+$e+t+Pe+xe(t,"grow","positive")+t;case 4554:return $e+xe(t,/([^-])(transform)/g,"$1"+$e+"$2")+t;case 6187:return xe(xe(xe(t,/(zoom-|grab)/,$e+"$1"),/(image-set)/,$e+"$1"),t,"")+t;case 5495:case 3959:return xe(t,/(image-set\([^]*)/,$e+"$1$`$1");case 4968:return xe(xe(t,/(.+:)(flex-)?(.*)/,$e+"box-pack:$3"+Pe+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+$e+t+t;case 4200:if(!gt(t,/flex-|baseline/))return Pe+"grid-column-align"+mr(t,r)+t;break;case 2592:case 3360:return Pe+xe(t,"template-","")+t;case 4384:case 3616:return o&&o.some(function(n,s){return r=s,gt(n.props,/grid-\w+-end/)})?~zo(t+(o=o[r].value),"span",0)?t:Pe+xe(t,"-start","")+t+Pe+"grid-row-span:"+(~zo(o,"span",0)?gt(o,/\d+/):+gt(o,/\d+/)-+gt(t,/\d+/))+";":Pe+xe(t,"-start","")+t;case 4896:case 4128:return o&&o.some(function(n){return gt(n.props,/grid-\w+-start/)})?t:Pe+xe(xe(t,"-end","-span"),"span ","")+t;case 4095:case 3583:case 4068:case 2532:return xe(t,/(.+)-inline(.+)/,$e+"$1$2")+t;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(it(t)-1-r>6)switch(Ue(t,r+1)){case 109:if(Ue(t,r+4)!==45)break;case 102:return xe(t,/(.+:)(.+)-([^]+)/,"$1"+$e+"$2-$3$1"+Lr+(Ue(t,r+3)==108?"$3":"$2-$3"))+t;case 115:return~zo(t,"stretch",0)?wc(xe(t,"stretch","fill-available"),r,o)+t:t}break;case 5152:case 5920:return xe(t,/(.+?):(\d+)(\s*\/\s*(span)?\s*(\d+))?(.*)/,function(n,s,a,h,f,c,p){return Pe+s+":"+a+p+(h?Pe+s+"-span:"+(f?c:+c-+a)+p:"")+t});case 4949:if(Ue(t,r+6)===121)return xe(t,":",":"+$e)+t;break;case 6444:switch(Ue(t,Ue(t,14)===45?18:11)){case 120:return xe(t,/(.+:)([^;\s!]+)(;|(\s+)?!.+)?/,"$1"+$e+(Ue(t,14)===45?"inline-":"")+"box$3$1"+$e+"$2$3$1"+Pe+"$2box$3")+t;case 100:return xe(t,":",":"+Pe)+t}break;case 5719:case 2647:case 2135:case 3927:case 2391:return xe(t,"scroll-","scroll-snap-")+t}return t}function Lo(t,r){for(var o="",n=0;n<t.length;n++)o+=r(t[n],n,t,r)||"";return o}function zu(t,r,o,n){switch(t.type){case gu:if(t.children.length)break;case fu:case ba:return t.return=t.return||t.value;case gc:return"";case mc:return t.return=t.value+"{"+Lo(t.children,n)+"}";case Zo:if(!it(t.value=t.props.join(",")))return""}return it(o=Lo(t.children,n))?t.return=t.value+"{"+o+"}":""}function Eu(t){var r=bc(t);return function(o,n,s,a){for(var h="",f=0;f<r;f++)h+=t[f](o,n,s,a)||"";return h}}function Pu(t){return function(r){r.root||(r=r.return)&&t(r)}}function Ru(t,r,o,n){if(t.length>-1&&!t.return)switch(t.type){case ba:t.return=wc(t.value,t.length,o);return;case mc:return Lo([St(t,{value:xe(t.value,"@","@"+$e)})],n);case Zo:if(t.length)return xu(o=t.props,function(s){switch(gt(s,n=/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":sr(St(t,{props:[xe(s,/:(read-\w+)/,":"+Lr+"$1")]})),sr(St(t,{props:[s]})),na(t,{props:Va(o,n)});break;case"::placeholder":sr(St(t,{props:[xe(s,/:(plac\w+)/,":"+$e+"input-$1")]})),sr(St(t,{props:[xe(s,/:(plac\w+)/,":"+Lr+"$1")]})),sr(St(t,{props:[xe(s,/:(plac\w+)/,Pe+"input-$1")]})),sr(St(t,{props:[s]})),na(t,{props:Va(o,n)});break}return""})}}var Iu={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},Jt=typeof process<"u"&&process.env!==void 0&&(process.env.REACT_APP_SC_ATTR||process.env.SC_ATTR)||"data-styled",jc="active",kc="data-styled-version",Jo="6.1.19",wa=`/*!sc*/
19
19
  `,Ao=typeof window<"u"&&typeof document<"u",Tu=!!(typeof SC_DISABLE_SPEEDY=="boolean"?SC_DISABLE_SPEEDY:typeof process<"u"&&process.env!==void 0&&process.env.REACT_APP_SC_DISABLE_SPEEDY!==void 0&&process.env.REACT_APP_SC_DISABLE_SPEEDY!==""?process.env.REACT_APP_SC_DISABLE_SPEEDY!=="false"&&process.env.REACT_APP_SC_DISABLE_SPEEDY:typeof process<"u"&&process.env!==void 0&&process.env.SC_DISABLE_SPEEDY!==void 0&&process.env.SC_DISABLE_SPEEDY!==""?process.env.SC_DISABLE_SPEEDY!=="false"&&process.env.SC_DISABLE_SPEEDY:process.env.NODE_ENV!=="production"),qa=/invalid hook call/i,Kr=new Set,Ou=function(t,r){if(process.env.NODE_ENV!=="production"){var o=r?' with the id of "'.concat(r,'"'):"",n="The component ".concat(t).concat(o,` has been created dynamically.
20
20
  `)+`You may see this warning because you've called styled inside another component.
21
21
  To resolve this only create new StyledComponents outside of any render method and function component.
@@ -199,12 +199,12 @@ See https://s-c.sh/2BAXzed for more info.`),window[eo]+=1);/**
199
199
  *
200
200
  * This source code is licensed under the ISC license.
201
201
  * See the LICENSE file in the root directory of this source tree.
202
- */const qp=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Pt=be("LoaderCircle",qp);/**
202
+ */const qp=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],vt=be("LoaderCircle",qp);/**
203
203
  * @license lucide-react v0.474.0 - ISC
204
204
  *
205
205
  * This source code is licensed under the ISC license.
206
206
  * See the LICENSE file in the root directory of this source tree.
207
- */const Yp=[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]],zt=be("LogOut",Yp);/**
207
+ */const Yp=[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]],Et=be("LogOut",Yp);/**
208
208
  * @license lucide-react v0.474.0 - ISC
209
209
  *
210
210
  * This source code is licensed under the ISC license.
@@ -921,7 +921,7 @@ See https://s-c.sh/2BAXzed for more info.`),window[eo]+=1);/**
921
921
  `,lr=l.span`
922
922
  color: var(--color-danger);
923
923
  margin-left: 2px;
924
- `;function Xh(){var U,K,ee,J,ie,oe,de,Q,ce,B,V,D,le,H,ae,ke,ne;const{loading:t,signUp:r,signupAttempt:o,discardSignupAttempt:n}=nc(),{signIn:s}=Dr("oauth"),{deployment:a}=ve(),{navigate:h}=Ve(),{session:f,refetch:c,loading:p}=Be(),[d,u]=i.useState({first_name:"",last_name:"",email:"",password:"",username:"",phone_number:""}),[g,m]=i.useState({}),[v,y]=i.useState(!1),[S,E]=i.useState(void 0),[b,$]=i.useState(null),[C,w]=i.useState(null),[j,x]=i.useState(!1),I=((U=a==null?void 0:a.restrictions)==null?void 0:U.sign_up_mode)==="restricted",k=((K=a==null?void 0:a.restrictions)==null?void 0:K.sign_up_mode)==="waitlist",R=((J=(ee=a==null?void 0:a.auth_settings)==null?void 0:ee.multi_session_support)==null?void 0:J.enabled)??!1;i.useEffect(()=>{var Y;if(!p&&(f!=null&&f.active_signin)&&!R&&!j){x(!0);let Z=new URLSearchParams(window.location.search).get("redirect_uri");Z||(Z=((Y=a==null?void 0:a.ui_settings)==null?void 0:Y.after_signin_redirect_url)||null),!Z&&(a!=null&&a.frontend_host)&&(Z=`https://${a.frontend_host}`),!Z&&(a!=null&&a.frontend_host)&&(Z=`https://${a.frontend_host}`),Z&&h(Z)}},[f,p,R,a,h,j]),i.useEffect(()=>{var N;if(!a)return;const Z=new URLSearchParams(window.location.search).get("invite_token");if(k&&!Z){x(!0);const W=((N=a.ui_settings)==null?void 0:N.waitlist_page_url)||`https://${a.frontend_host}/waitlist`;h(W);return}Z&&!b&&r&&(w(Z),r.validateDeploymentInvitation(Z).then(W=>{$(W),W.valid&&u(fe=>({...fe,first_name:W.first_name||fe.first_name,last_name:W.last_name||fe.last_name,email:W.email||fe.email}))}).catch(W=>{console.error("Failed to validate invitation:",W)}))},[a,k,h,b,r]);const[_,O]=i.useState(!1),[P,z]=i.useState(""),T=Y=>{let{name:Z,value:N}=Y.target;Z==="phone_number"?N=N.replace(/[^0-9-]/g,""):Z==="email"&&(N=N.toLowerCase()),u(W=>({...W,[Z]:N})),m(W=>({...W,[Z]:""}))},M=()=>{u({first_name:"",last_name:"",email:"",password:"",username:"",phone_number:""}),m({}),O(!1),z(""),n()},F=async Y=>{if(Y.preventDefault(),console.log("Signup form - handleSubmit called"),console.log("Auth settings:",A),console.log("Form data:",d),t||v)return;const Z={},N=/^[a-zA-Z]{3,30}$/,W=/^[a-zA-Z][a-zA-Z0-9_.]{2,29}$/,fe=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,ye=/^\d{7,15}$/,re=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,125}$/;if(A!=null&&A.first_name.enabled&&(A!=null&&A.first_name.required&&!d.first_name?Z.first_name="First name is required":d.first_name&&!N.test(d.first_name)&&(Z.first_name="Invalid name")),A!=null&&A.last_name.enabled&&(A!=null&&A.last_name.required&&!d.last_name?Z.last_name="Last name is required":d.last_name&&!N.test(d.last_name)&&(Z.last_name="Invalid last name")),A!=null&&A.username.enabled&&(A!=null&&A.username.required&&!d.username?Z.username="Username is required":d.username&&!W.test(d.username)&&(Z.username="Username must be 3-20 characters")),A!=null&&A.email_address.enabled&&(A!=null&&A.email_address.required&&!d.email?Z.email="Email address is required":d.email&&!fe.test(d.email)&&(Z.email="Invalid email address")),A!=null&&A.phone_number.enabled&&(A!=null&&A.phone_number.required&&!d.phone_number?Z.phone_number="Phone number is required":d.phone_number&&!ye.test(d.phone_number)&&(Z.phone_number="Phone number must contain 7-15 digits")),A!=null&&A.password.enabled&&(d.password?re.test(d.password)||(Z.password="Password must be 8-125 characters and include uppercase, lowercase, number, and special character"):Z.password="Password is required"),m(Z),Object.keys(Z).length>0){console.log("Signup validation failed. Errors:",Z);return}console.log("Signup validation passed"),y(!0);try{const je={...d};d.phone_number&&S&&(je.phone_country_code=S),C&&(je.invite_token=C),console.log("Submitting signup data:",je),console.log("Phone number:",je.phone_number),console.log("Phone country code:",je.phone_country_code),await r.create(je)}catch(je){m({submit:je.message})}finally{y(!1)}},G=async Y=>{if(!(t||v)){y(!0);try{const N=new URLSearchParams(window.location.search).get("redirect_uri")||void 0,{data:W}=await s.create({provider:Y.provider,redirectUri:N});W&&typeof W=="object"&&"oauth_url"in W&&(window.location.href=W.oauth_url)}catch(Z){m({submit:Z.message})}finally{y(!1)}}},L=(a==null?void 0:a.social_connections.filter(Y=>Y.enabled))||[],A=a==null?void 0:a.auth_settings,se=!!((ie=A==null?void 0:A.first_name)!=null&&ie.enabled&&((oe=A==null?void 0:A.last_name)!=null&&oe.enabled)),te=async Y=>{var N;if(Y.preventDefault(),t||v)return;y(!0);const Z={};if(!P){Z.otp="OTP code is required",m(Z),y(!1);return}m(Z);try{const W=await r.completeVerification(P);"data"in W&&((N=W.data)!=null&&N.active_signin)&&await c()}catch(W){console.error("Verification failed:",W)}finally{y(!1)}};return i.useEffect(()=>{var Y;if(o){if(o.completed){let Z=new URLSearchParams(window.location.search).get("redirect_uri");if(Z||(Z=((Y=a==null?void 0:a.ui_settings)==null?void 0:Y.after_signup_redirect_url)||null),!Z&&(a!=null&&a.frontend_host)&&(Z=`https://${a.frontend_host}`),Z){const N=new URL(Z);(a==null?void 0:a.mode)==="staging"&&N.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),h(N.toString())}return}if(!_){switch(o.current_step){case"verify_email":r.prepareVerification({strategy:"email_otp"});break;case"verify_phone":r.prepareVerification({strategy:"phone_otp"});break}O(!0)}}},[o,r,_,a,f,h]),p?e.jsx(ue,{children:e.jsxs(to,{children:[e.jsx(Re,{}),e.jsx(is,{children:e.jsx(Pt,{size:32})})]})}):j?e.jsx(ue,{children:e.jsxs(to,{children:[e.jsx(Re,{}),e.jsx(is,{children:e.jsx(Pt,{size:32})})]})}):I?e.jsx(ue,{children:e.jsxs(to,{children:[e.jsx(Re,{}),e.jsx(kn,{children:e.jsx(_n,{children:"Sign up Restricted!"})}),e.jsx(qh,{children:e.jsx(Yh,{children:"New account registration is currently restricted. Please check back later."})}),e.jsx(Zh,{children:e.jsxs(Qh,{children:["Need assistance?"," ",e.jsx(Kh,{href:(de=a==null?void 0:a.ui_settings)!=null&&de.sign_in_page_url?`${a.ui_settings.sign_in_page_url}?help=true`:"/contact",children:"Get help"})]})})]})}):e.jsx(ue,{children:e.jsx(to,{children:_?e.jsxs(e.Fragment,{children:[e.jsxs(kn,{children:[e.jsxs(_n,{children:["Check your"," ",(o==null?void 0:o.current_step)==="verify_email"?"email":"phone"]}),e.jsx(cs,{children:(o==null?void 0:o.current_step)==="verify_email"?`${d.email} to continue to ${(Q=a==null?void 0:a.ui_settings)==null?void 0:Q.app_name}`:`${d.phone_number} to continue to ${(ce=a==null?void 0:a.ui_settings)==null?void 0:ce.app_name}`})]}),e.jsxs(ls,{style:{gap:"15px"},onSubmit:te,noValidate:!0,children:[e.jsx(It,{onComplete:async Y=>{z(Y)},onResend:async()=>{const Y=(o==null?void 0:o.current_step)==="verify_email"?"email_otp":"phone_otp";await r.prepareVerification({strategy:Y})},error:g.otp,isSubmitting:v}),e.jsx(ds,{type:"submit",disabled:v||t||!P,children:v?"Verifying...":`Continue to ${(B=a==null?void 0:a.ui_settings)==null?void 0:B.app_name}`})]}),e.jsxs(us,{children:["Having trouble?"," ",e.jsx(Cn,{children:e.jsx(ot,{to:a.ui_settings.support_page_url,children:"Contact support"})}),e.jsx("div",{style:{marginTop:"var(--space-sm)"},children:e.jsx(Cn,{onClick:()=>{M()},style:{cursor:"pointer"},children:"Use other method"})})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{}),e.jsxs(kn,{children:[e.jsx(_n,{children:"Create your account"}),e.jsx(cs,{children:b!=null&&b.valid?"You've been invited! Complete your registration below.":"Welcome! Please fill in the details to get started."})]}),L.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(_a,{connections:L,callback:G}),e.jsx(Wh,{children:e.jsx(Vh,{children:"or"})})]}),e.jsxs(ls,{onSubmit:F,noValidate:!0,children:[(((V=A==null?void 0:A.first_name)==null?void 0:V.enabled)||((D=A==null?void 0:A.last_name)==null?void 0:D.enabled))&&e.jsxs(Gh,{$isBothEnabled:se,children:[((le=A==null?void 0:A.first_name)==null?void 0:le.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"first_name",children:["First name",((H=A==null?void 0:A.first_name)==null?void 0:H.required)&&e.jsx(lr,{children:"*"})]}),e.jsx(pe,{type:"text",id:"first_name",name:"first_name",required:!0,minLength:3,maxLength:30,value:d.first_name,onChange:T,placeholder:"First name","aria-invalid":!!g.first_name,pattern:"^[a-zA-Z]{3,30}$"}),g.first_name&&e.jsx(Mt,{children:g.first_name})]}),((ae=A==null?void 0:A.last_name)==null?void 0:ae.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"last_name",children:["Last name",((ke=A==null?void 0:A.last_name)==null?void 0:ke.required)&&e.jsx(lr,{children:"*"})]}),e.jsx(pe,{type:"text",id:"last_name",name:"last_name",required:!0,minLength:3,maxLength:30,value:d.last_name,onChange:T,placeholder:"Last name","aria-invalid":!!g.last_name,pattern:"^[a-zA-Z]{3,30}$"}),g.last_name&&e.jsx(Mt,{children:g.last_name})]})]}),(A==null?void 0:A.username.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"username",children:["Username",A.username.required&&e.jsx(lr,{children:"*"})]}),e.jsx(pe,{type:"text",id:"username",name:"username",minLength:3,maxLength:20,value:d.username,onChange:T,placeholder:"Choose a username","aria-invalid":!!g.username,required:!0,pattern:"^[a-zA-Z][a-zA-Z0-9_.]{2,29}$"}),g.username&&e.jsx(Mt,{children:g.username})]}),(A==null?void 0:A.email_address.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"email",children:["Email address",A.email_address.required&&e.jsx(lr,{children:"*"})]}),e.jsx(pe,{type:"email",id:"email",name:"email",maxLength:320,value:d.email,onChange:T,placeholder:"Enter your email address","aria-invalid":!!g.email,required:!0,readOnly:(b==null?void 0:b.valid)&&!!(b!=null&&b.email),pattern:"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"}),g.email&&e.jsx(Mt,{children:g.email})]}),(A==null?void 0:A.phone_number.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"phone_number",children:["Phone number",A.phone_number.required&&e.jsx(lr,{children:"*"})]}),e.jsx(Gr,{value:d.phone_number,onChange:T,error:g.phone_number,countryCode:S,setCountryCode:E}),g.phone_number&&e.jsx(Mt,{children:g.phone_number})]}),(A==null?void 0:A.password.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"password",children:["Password",A.password.required&&e.jsx(lr,{children:"*"})]}),e.jsx(Hh,{children:e.jsx(pe,{type:"password",id:"password",name:"password",value:d.password,onChange:T,placeholder:"Enter your password","aria-invalid":!!g.password,required:!0,minLength:8,maxLength:128,pattern:"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,125}$"})}),g.password&&e.jsx(Mt,{children:g.password})]}),g.submit&&e.jsx(Mt,{children:g.submit}),e.jsx(ds,{type:"submit",disabled:v||t,children:v?"Creating account...":"Continue"})]}),e.jsxs(us,{children:["Already have an account?"," ",e.jsx(Cn,{children:e.jsx(ot,{to:`${(ne=a.ui_settings)==null?void 0:ne.sign_in_page_url}${window.location.search}`,children:"Sign in"})})]})]})})})}const Kc=i.createContext(void 0),Xc=()=>{const t=i.useContext(Kc);if(!t)throw new Error("Dialog components must be used within a Dialog");return t},Jh=l.div`
924
+ `;function Xh(){var U,K,ee,J,ie,oe,de,Q,ce,B,V,D,le,H,ae,ke,ne;const{loading:t,signUp:r,signupAttempt:o,discardSignupAttempt:n}=nc(),{signIn:s}=Dr("oauth"),{deployment:a}=ve(),{navigate:h}=Ve(),{session:f,refetch:c,loading:p}=Be(),[d,u]=i.useState({first_name:"",last_name:"",email:"",password:"",username:"",phone_number:""}),[g,m]=i.useState({}),[v,y]=i.useState(!1),[S,E]=i.useState(void 0),[b,$]=i.useState(null),[C,w]=i.useState(null),[j,x]=i.useState(!1),I=((U=a==null?void 0:a.restrictions)==null?void 0:U.sign_up_mode)==="restricted",k=((K=a==null?void 0:a.restrictions)==null?void 0:K.sign_up_mode)==="waitlist",R=((J=(ee=a==null?void 0:a.auth_settings)==null?void 0:ee.multi_session_support)==null?void 0:J.enabled)??!1;i.useEffect(()=>{var Y;if(!p&&(f!=null&&f.active_signin)&&!R&&!j){x(!0);let Z=new URLSearchParams(window.location.search).get("redirect_uri");Z||(Z=((Y=a==null?void 0:a.ui_settings)==null?void 0:Y.after_signin_redirect_url)||null),!Z&&(a!=null&&a.frontend_host)&&(Z=`https://${a.frontend_host}`),!Z&&(a!=null&&a.frontend_host)&&(Z=`https://${a.frontend_host}`),Z&&h(Z)}},[f,p,R,a,h,j]),i.useEffect(()=>{var N;if(!a)return;const Z=new URLSearchParams(window.location.search).get("invite_token");if(k&&!Z){x(!0);const W=((N=a.ui_settings)==null?void 0:N.waitlist_page_url)||`https://${a.frontend_host}/waitlist`;h(W);return}Z&&!b&&r&&(w(Z),r.validateDeploymentInvitation(Z).then(W=>{$(W),W.valid&&u(fe=>({...fe,first_name:W.first_name||fe.first_name,last_name:W.last_name||fe.last_name,email:W.email||fe.email}))}).catch(W=>{console.error("Failed to validate invitation:",W)}))},[a,k,h,b,r]);const[_,O]=i.useState(!1),[P,z]=i.useState(""),T=Y=>{let{name:Z,value:N}=Y.target;Z==="phone_number"?N=N.replace(/[^0-9-]/g,""):Z==="email"&&(N=N.toLowerCase()),u(W=>({...W,[Z]:N})),m(W=>({...W,[Z]:""}))},M=()=>{u({first_name:"",last_name:"",email:"",password:"",username:"",phone_number:""}),m({}),O(!1),z(""),n()},F=async Y=>{if(Y.preventDefault(),console.log("Signup form - handleSubmit called"),console.log("Auth settings:",A),console.log("Form data:",d),t||v)return;const Z={},N=/^[a-zA-Z]{3,30}$/,W=/^[a-zA-Z][a-zA-Z0-9_.]{2,29}$/,fe=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,ye=/^\d{7,15}$/,re=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,125}$/;if(A!=null&&A.first_name.enabled&&(A!=null&&A.first_name.required&&!d.first_name?Z.first_name="First name is required":d.first_name&&!N.test(d.first_name)&&(Z.first_name="Invalid name")),A!=null&&A.last_name.enabled&&(A!=null&&A.last_name.required&&!d.last_name?Z.last_name="Last name is required":d.last_name&&!N.test(d.last_name)&&(Z.last_name="Invalid last name")),A!=null&&A.username.enabled&&(A!=null&&A.username.required&&!d.username?Z.username="Username is required":d.username&&!W.test(d.username)&&(Z.username="Username must be 3-20 characters")),A!=null&&A.email_address.enabled&&(A!=null&&A.email_address.required&&!d.email?Z.email="Email address is required":d.email&&!fe.test(d.email)&&(Z.email="Invalid email address")),A!=null&&A.phone_number.enabled&&(A!=null&&A.phone_number.required&&!d.phone_number?Z.phone_number="Phone number is required":d.phone_number&&!ye.test(d.phone_number)&&(Z.phone_number="Phone number must contain 7-15 digits")),A!=null&&A.password.enabled&&(d.password?re.test(d.password)||(Z.password="Password must be 8-125 characters and include uppercase, lowercase, number, and special character"):Z.password="Password is required"),m(Z),Object.keys(Z).length>0){console.log("Signup validation failed. Errors:",Z);return}console.log("Signup validation passed"),y(!0);try{const je={...d};d.phone_number&&S&&(je.phone_country_code=S),C&&(je.invite_token=C),console.log("Submitting signup data:",je),console.log("Phone number:",je.phone_number),console.log("Phone country code:",je.phone_country_code),await r.create(je)}catch(je){m({submit:je.message})}finally{y(!1)}},G=async Y=>{if(!(t||v)){y(!0);try{const N=new URLSearchParams(window.location.search).get("redirect_uri")||void 0,{data:W}=await s.create({provider:Y.provider,redirectUri:N});W&&typeof W=="object"&&"oauth_url"in W&&(window.location.href=W.oauth_url)}catch(Z){m({submit:Z.message})}finally{y(!1)}}},L=(a==null?void 0:a.social_connections.filter(Y=>Y.enabled))||[],A=a==null?void 0:a.auth_settings,se=!!((ie=A==null?void 0:A.first_name)!=null&&ie.enabled&&((oe=A==null?void 0:A.last_name)!=null&&oe.enabled)),te=async Y=>{var N;if(Y.preventDefault(),t||v)return;y(!0);const Z={};if(!P){Z.otp="OTP code is required",m(Z),y(!1);return}m(Z);try{const W=await r.completeVerification(P);"data"in W&&((N=W.data)!=null&&N.active_signin)&&await c()}catch(W){console.error("Verification failed:",W)}finally{y(!1)}};return i.useEffect(()=>{var Y;if(o){if(o.completed){let Z=new URLSearchParams(window.location.search).get("redirect_uri");if(Z||(Z=((Y=a==null?void 0:a.ui_settings)==null?void 0:Y.after_signup_redirect_url)||null),!Z&&(a!=null&&a.frontend_host)&&(Z=`https://${a.frontend_host}`),Z){const N=new URL(Z);(a==null?void 0:a.mode)==="staging"&&N.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),h(N.toString())}return}if(!_){switch(o.current_step){case"verify_email":r.prepareVerification({strategy:"email_otp"});break;case"verify_phone":r.prepareVerification({strategy:"phone_otp"});break}O(!0)}}},[o,r,_,a,f,h]),p?e.jsx(ue,{children:e.jsxs(to,{children:[e.jsx(Re,{}),e.jsx(is,{children:e.jsx(vt,{size:32})})]})}):j?e.jsx(ue,{children:e.jsxs(to,{children:[e.jsx(Re,{}),e.jsx(is,{children:e.jsx(vt,{size:32})})]})}):I?e.jsx(ue,{children:e.jsxs(to,{children:[e.jsx(Re,{}),e.jsx(kn,{children:e.jsx(_n,{children:"Sign up Restricted!"})}),e.jsx(qh,{children:e.jsx(Yh,{children:"New account registration is currently restricted. Please check back later."})}),e.jsx(Zh,{children:e.jsxs(Qh,{children:["Need assistance?"," ",e.jsx(Kh,{href:(de=a==null?void 0:a.ui_settings)!=null&&de.sign_in_page_url?`${a.ui_settings.sign_in_page_url}?help=true`:"/contact",children:"Get help"})]})})]})}):e.jsx(ue,{children:e.jsx(to,{children:_?e.jsxs(e.Fragment,{children:[e.jsxs(kn,{children:[e.jsxs(_n,{children:["Check your"," ",(o==null?void 0:o.current_step)==="verify_email"?"email":"phone"]}),e.jsx(cs,{children:(o==null?void 0:o.current_step)==="verify_email"?`${d.email} to continue to ${(Q=a==null?void 0:a.ui_settings)==null?void 0:Q.app_name}`:`${d.phone_number} to continue to ${(ce=a==null?void 0:a.ui_settings)==null?void 0:ce.app_name}`})]}),e.jsxs(ls,{style:{gap:"15px"},onSubmit:te,noValidate:!0,children:[e.jsx(It,{onComplete:async Y=>{z(Y)},onResend:async()=>{const Y=(o==null?void 0:o.current_step)==="verify_email"?"email_otp":"phone_otp";await r.prepareVerification({strategy:Y})},error:g.otp,isSubmitting:v}),e.jsx(ds,{type:"submit",disabled:v||t||!P,children:v?"Verifying...":`Continue to ${(B=a==null?void 0:a.ui_settings)==null?void 0:B.app_name}`})]}),e.jsxs(us,{children:["Having trouble?"," ",e.jsx(Cn,{children:e.jsx(ot,{to:a.ui_settings.support_page_url,children:"Contact support"})}),e.jsx("div",{style:{marginTop:"var(--space-sm)"},children:e.jsx(Cn,{onClick:()=>{M()},style:{cursor:"pointer"},children:"Use other method"})})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{}),e.jsxs(kn,{children:[e.jsx(_n,{children:"Create your account"}),e.jsx(cs,{children:b!=null&&b.valid?"You've been invited! Complete your registration below.":"Welcome! Please fill in the details to get started."})]}),L.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(_a,{connections:L,callback:G}),e.jsx(Wh,{children:e.jsx(Vh,{children:"or"})})]}),e.jsxs(ls,{onSubmit:F,noValidate:!0,children:[(((V=A==null?void 0:A.first_name)==null?void 0:V.enabled)||((D=A==null?void 0:A.last_name)==null?void 0:D.enabled))&&e.jsxs(Gh,{$isBothEnabled:se,children:[((le=A==null?void 0:A.first_name)==null?void 0:le.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"first_name",children:["First name",((H=A==null?void 0:A.first_name)==null?void 0:H.required)&&e.jsx(lr,{children:"*"})]}),e.jsx(pe,{type:"text",id:"first_name",name:"first_name",required:!0,minLength:3,maxLength:30,value:d.first_name,onChange:T,placeholder:"First name","aria-invalid":!!g.first_name,pattern:"^[a-zA-Z]{3,30}$"}),g.first_name&&e.jsx(Mt,{children:g.first_name})]}),((ae=A==null?void 0:A.last_name)==null?void 0:ae.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"last_name",children:["Last name",((ke=A==null?void 0:A.last_name)==null?void 0:ke.required)&&e.jsx(lr,{children:"*"})]}),e.jsx(pe,{type:"text",id:"last_name",name:"last_name",required:!0,minLength:3,maxLength:30,value:d.last_name,onChange:T,placeholder:"Last name","aria-invalid":!!g.last_name,pattern:"^[a-zA-Z]{3,30}$"}),g.last_name&&e.jsx(Mt,{children:g.last_name})]})]}),(A==null?void 0:A.username.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"username",children:["Username",A.username.required&&e.jsx(lr,{children:"*"})]}),e.jsx(pe,{type:"text",id:"username",name:"username",minLength:3,maxLength:20,value:d.username,onChange:T,placeholder:"Choose a username","aria-invalid":!!g.username,required:!0,pattern:"^[a-zA-Z][a-zA-Z0-9_.]{2,29}$"}),g.username&&e.jsx(Mt,{children:g.username})]}),(A==null?void 0:A.email_address.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"email",children:["Email address",A.email_address.required&&e.jsx(lr,{children:"*"})]}),e.jsx(pe,{type:"email",id:"email",name:"email",maxLength:320,value:d.email,onChange:T,placeholder:"Enter your email address","aria-invalid":!!g.email,required:!0,readOnly:(b==null?void 0:b.valid)&&!!(b!=null&&b.email),pattern:"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"}),g.email&&e.jsx(Mt,{children:g.email})]}),(A==null?void 0:A.phone_number.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"phone_number",children:["Phone number",A.phone_number.required&&e.jsx(lr,{children:"*"})]}),e.jsx(Gr,{value:d.phone_number,onChange:T,error:g.phone_number,countryCode:S,setCountryCode:E}),g.phone_number&&e.jsx(Mt,{children:g.phone_number})]}),(A==null?void 0:A.password.enabled)&&e.jsxs(ir,{children:[e.jsxs(cr,{htmlFor:"password",children:["Password",A.password.required&&e.jsx(lr,{children:"*"})]}),e.jsx(Hh,{children:e.jsx(pe,{type:"password",id:"password",name:"password",value:d.password,onChange:T,placeholder:"Enter your password","aria-invalid":!!g.password,required:!0,minLength:8,maxLength:128,pattern:"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,125}$"})}),g.password&&e.jsx(Mt,{children:g.password})]}),g.submit&&e.jsx(Mt,{children:g.submit}),e.jsx(ds,{type:"submit",disabled:v||t,children:v?"Creating account...":"Continue"})]}),e.jsxs(us,{children:["Already have an account?"," ",e.jsx(Cn,{children:e.jsx(ot,{to:`${(ne=a.ui_settings)==null?void 0:ne.sign_in_page_url}${window.location.search}`,children:"Sign in"})})]})]})})})}const Kc=i.createContext(void 0),Xc=()=>{const t=i.useContext(Kc);if(!t)throw new Error("Dialog components must be used within a Dialog");return t},Jh=l.div`
925
925
  position: fixed;
926
926
  inset: 0;
927
927
  background-color: var(--color-dialog-backdrop, rgba(0, 0, 0, 0.5));
@@ -1065,7 +1065,7 @@ See https://s-c.sh/2BAXzed for more info.`),window[eo]+=1);/**
1065
1065
  left: ${t=>t.checked?"20px":"2px"};
1066
1066
  transition: left 0.2s ease;
1067
1067
  }
1068
- `,jr=({checked:t,onChange:r})=>{const o=n=>{r(n.target.checked)};return e.jsxs(yf,{children:[e.jsx(wf,{type:"checkbox",checked:t,onChange:o}),e.jsx(jf,{checked:t})]})},Mr=(t=!1)=>{const[r,o]=i.useState(t),n=i.useCallback(()=>{o(!0)},[]),s=i.useCallback(()=>{o(!1)},[]),a=i.useCallback(()=>{o(h=>!h)},[]);return{isOpen:r,open:n,close:s,toggle:a}},yt=({onChange:t,placeholder:r,value:o})=>e.jsxs("div",{style:{display:"flex",flexGrow:1,alignItems:"center",border:"1px solid var(--color-border)",borderRadius:"8px",padding:"8px 12px",backgroundColor:"var(--color-input-background)",minWidth:"250px"},children:[e.jsx(ah,{size:16,color:"var(--color-secondary-text)",style:{marginRight:"8px"}}),e.jsx("input",{type:"text",placeholder:r,value:o,onChange:n=>t(n.target.value),style:{border:"none",outline:"none",width:"100%",fontSize:"14px",color:"var(--color-text)",backgroundColor:"transparent"}})]}),X=l.button`
1068
+ `,jr=({checked:t,onChange:r})=>{const o=n=>{r(n.target.checked)};return e.jsxs(yf,{children:[e.jsx(wf,{type:"checkbox",checked:t,onChange:o}),e.jsx(jf,{checked:t})]})},Mr=(t=!1)=>{const[r,o]=i.useState(t),n=i.useCallback(()=>{o(!0)},[]),s=i.useCallback(()=>{o(!1)},[]),a=i.useCallback(()=>{o(h=>!h)},[]);return{isOpen:r,open:n,close:s,toggle:a}},wt=({onChange:t,placeholder:r,value:o})=>e.jsxs("div",{style:{display:"flex",flexGrow:1,alignItems:"center",border:"1px solid var(--color-border)",borderRadius:"8px",padding:"8px 12px",backgroundColor:"var(--color-input-background)",minWidth:"250px"},children:[e.jsx(ah,{size:16,color:"var(--color-secondary-text)",style:{marginRight:"8px"}}),e.jsx("input",{type:"text",placeholder:r,value:o,onChange:n=>t(n.target.value),style:{border:"none",outline:"none",width:"100%",fontSize:"14px",color:"var(--color-text)",backgroundColor:"transparent"}})]}),X=l.button`
1069
1069
  width: 100%;
1070
1070
  padding: var(--space-sm) var(--space-md);
1071
1071
  border: 1px solid transparent;
@@ -1517,7 +1517,7 @@ See https://s-c.sh/2BAXzed for more info.`),window[eo]+=1);/**
1517
1517
  }
1518
1518
  `,ig=l(pe)`
1519
1519
  padding: var(--space-sm) var(--space-md);
1520
- `;function hl({onBack:t,attempt:r,completeVerification:o,prepareVerification:n}){const{deployment:s}=ve(),[a,h]=i.useState(""),[f,c]=i.useState({}),[p,d]=i.useState(!1),[u,g]=i.useState(null),[m,v]=i.useState(!0),[y,S]=i.useState(!1),[E,b]=i.useState(""),[$,C]=i.useState(!1),{navigate:w}=Ve(),j=(r==null?void 0:r.available_2fa_methods)||[],x=[{id:"authenticator",name:"Authenticator app",description:"Use your authenticator app",icon:e.jsx(tg,{}),available:j.includes("authenticator")},{id:"phone_otp",name:"Text message",description:"Get a code via SMS",icon:e.jsx(rg,{}),available:j.includes("phone_otp"),phoneNumber:E},{id:"backup_code",name:"Backup code",description:"Use one of your backup codes",icon:e.jsx(og,{}),available:j.includes("backup_code")}].filter(O=>O.available),I=async O=>{g(O),v(!1),O==="phone_otp"&&S(!0)},k=async O=>{var P,z;if(r){d(!0);try{const T=await n({strategy:"phone_otp",lastDigits:O});T&&"data"in T&&((P=T.data)!=null&&P.otp_sent)?((z=T.data)!=null&&z.masked_phone&&b(T.data.masked_phone),S(!1)):c({phone:"Phone number verification failed"})}catch(T){c({phone:T.message})}finally{d(!1)}}},R=async O=>{if(O.preventDefault(),p)return;const P={};if(a?u==="authenticator"&&a.length!==6?P.code="Authentication code must be 6 digits":u==="phone_otp"&&a.length!==6&&(P.code="SMS code must be 6 digits"):P.code="Verification code is required",c(P),!(Object.keys(P).length>0)){d(!0);try{await o(a)}catch(z){c({submit:z.message})}finally{d(!1)}}},_=O=>{const P=O.target.value.replace(/\D/g,"").slice(0,6);h(P),c(z=>({...z,code:""}))};return i.useEffect(()=>{var O;if(r.completed){C(!0);let P=new URLSearchParams(window.location.search).get("redirect_uri");if(P||(P=((O=s==null?void 0:s.ui_settings)==null?void 0:O.after_signin_redirect_url)||null),!P&&(s!=null&&s.frontend_host)&&(P=`https://${s.frontend_host}`),P){const z=new URL(P);(s==null?void 0:s.mode)==="staging"&&z.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),w(z.toString())}return}},[r,s]),$?e.jsx(ue,{children:e.jsxs(zn,{children:[e.jsx(Re,{}),e.jsx(ag,{children:e.jsx(Pt,{size:32})})]})}):m?x.length===0?e.jsx(ue,{children:e.jsxs(zn,{children:[e.jsx(Re,{}),e.jsxs(fs,{children:[e.jsx(gs,{children:"Set Up Two-Factor Authentication"}),e.jsx(ms,{children:"Your account requires two-factor authentication, but you haven't set up any methods yet. Please contact your administrator to set up 2FA."})]}),e.jsxs(vs,{children:[t&&e.jsx("div",{children:e.jsx(Rr,{onClick:t,style:{cursor:"pointer"},children:"Back to login"})}),e.jsxs("div",{style:{marginTop:"var(--space-sm)"},children:["Having trouble?"," ",e.jsx(Rr,{children:e.jsx(ot,{to:(s==null?void 0:s.ui_settings.support_page_url)||"#",children:"Get help"})})]})]})]})}):e.jsx(ul,{methods:x,onSelectMethod:I,onBack:t}):y&&u==="phone_otp"?e.jsx(pl,{onVerify:k,onBack:()=>{S(!1),v(!0),g(null)},loading:p}):e.jsx(ue,{children:e.jsxs(zn,{children:[e.jsx(Re,{}),e.jsxs(fs,{children:[e.jsx(gs,{children:"Two-factor authentication"}),e.jsxs(ms,{children:[u==="authenticator"&&"Enter the 6-digit code from your authenticator app",u==="phone_otp"&&`Enter the 6-digit code sent to your phone ${E}`,u==="backup_code"&&"Enter one of your backup codes"]})]}),e.jsxs(lt,{onSubmit:R,noValidate:!0,children:[u==="backup_code"?e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"code",children:"Backup code"}),e.jsx(ig,{type:"text",id:"code",name:"code",value:a,onChange:_,placeholder:"Enter backup code",maxLength:20,autoComplete:"one-time-code","aria-invalid":!!f.code,autoFocus:!0}),f.code&&e.jsx(xs,{children:f.code})]}):e.jsx(It,{onComplete:async O=>{if(h(O),u!=="backup_code"){const P=new Event("submit",{bubbles:!0,cancelable:!0});await R(P)}},onResend:u==="phone_otp"?async()=>{try{await n({strategy:"phone_otp",lastDigits:E.slice(-4)})}catch(O){c({submit:O.message})}}:void 0,error:f.code,isSubmitting:p}),e.jsxs("div",{children:[f.submit&&e.jsx(xs,{children:f.submit}),e.jsx(sg,{type:"submit",disabled:p||!a,children:p?"Verifying...":"Verify"})]})]}),e.jsxs(vs,{children:[e.jsx(Rr,{onClick:()=>{v(!0),g(null),h(""),c({})},style:{cursor:"pointer"},children:"Try another method"}),e.jsxs("div",{style:{marginTop:"var(--space-sm)"},children:["Having trouble?"," ",e.jsx(Rr,{children:e.jsx(ot,{to:(s==null?void 0:s.ui_settings.support_page_url)||"#",children:"Get help"})})]}),t&&e.jsx("div",{style:{marginTop:"var(--space-sm)"},children:e.jsx(Rr,{onClick:t,style:{cursor:"pointer"},children:"Back to login"})})]})]})})}const En=l.div`
1520
+ `;function hl({onBack:t,attempt:r,completeVerification:o,prepareVerification:n}){const{deployment:s}=ve(),[a,h]=i.useState(""),[f,c]=i.useState({}),[p,d]=i.useState(!1),[u,g]=i.useState(null),[m,v]=i.useState(!0),[y,S]=i.useState(!1),[E,b]=i.useState(""),[$,C]=i.useState(!1),{navigate:w}=Ve(),j=(r==null?void 0:r.available_2fa_methods)||[],x=[{id:"authenticator",name:"Authenticator app",description:"Use your authenticator app",icon:e.jsx(tg,{}),available:j.includes("authenticator")},{id:"phone_otp",name:"Text message",description:"Get a code via SMS",icon:e.jsx(rg,{}),available:j.includes("phone_otp"),phoneNumber:E},{id:"backup_code",name:"Backup code",description:"Use one of your backup codes",icon:e.jsx(og,{}),available:j.includes("backup_code")}].filter(O=>O.available),I=async O=>{g(O),v(!1),O==="phone_otp"&&S(!0)},k=async O=>{var P,z;if(r){d(!0);try{const T=await n({strategy:"phone_otp",lastDigits:O});T&&"data"in T&&((P=T.data)!=null&&P.otp_sent)?((z=T.data)!=null&&z.masked_phone&&b(T.data.masked_phone),S(!1)):c({phone:"Phone number verification failed"})}catch(T){c({phone:T.message})}finally{d(!1)}}},R=async O=>{if(O.preventDefault(),p)return;const P={};if(a?u==="authenticator"&&a.length!==6?P.code="Authentication code must be 6 digits":u==="phone_otp"&&a.length!==6&&(P.code="SMS code must be 6 digits"):P.code="Verification code is required",c(P),!(Object.keys(P).length>0)){d(!0);try{await o(a)}catch(z){c({submit:z.message})}finally{d(!1)}}},_=O=>{const P=O.target.value.replace(/\D/g,"").slice(0,6);h(P),c(z=>({...z,code:""}))};return i.useEffect(()=>{var O;if(r.completed){C(!0);let P=new URLSearchParams(window.location.search).get("redirect_uri");if(P||(P=((O=s==null?void 0:s.ui_settings)==null?void 0:O.after_signin_redirect_url)||null),!P&&(s!=null&&s.frontend_host)&&(P=`https://${s.frontend_host}`),P){const z=new URL(P);(s==null?void 0:s.mode)==="staging"&&z.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),w(z.toString())}return}},[r,s]),$?e.jsx(ue,{children:e.jsxs(zn,{children:[e.jsx(Re,{}),e.jsx(ag,{children:e.jsx(vt,{size:32})})]})}):m?x.length===0?e.jsx(ue,{children:e.jsxs(zn,{children:[e.jsx(Re,{}),e.jsxs(fs,{children:[e.jsx(gs,{children:"Set Up Two-Factor Authentication"}),e.jsx(ms,{children:"Your account requires two-factor authentication, but you haven't set up any methods yet. Please contact your administrator to set up 2FA."})]}),e.jsxs(vs,{children:[t&&e.jsx("div",{children:e.jsx(Rr,{onClick:t,style:{cursor:"pointer"},children:"Back to login"})}),e.jsxs("div",{style:{marginTop:"var(--space-sm)"},children:["Having trouble?"," ",e.jsx(Rr,{children:e.jsx(ot,{to:(s==null?void 0:s.ui_settings.support_page_url)||"#",children:"Get help"})})]})]})]})}):e.jsx(ul,{methods:x,onSelectMethod:I,onBack:t}):y&&u==="phone_otp"?e.jsx(pl,{onVerify:k,onBack:()=>{S(!1),v(!0),g(null)},loading:p}):e.jsx(ue,{children:e.jsxs(zn,{children:[e.jsx(Re,{}),e.jsxs(fs,{children:[e.jsx(gs,{children:"Two-factor authentication"}),e.jsxs(ms,{children:[u==="authenticator"&&"Enter the 6-digit code from your authenticator app",u==="phone_otp"&&`Enter the 6-digit code sent to your phone ${E}`,u==="backup_code"&&"Enter one of your backup codes"]})]}),e.jsxs(lt,{onSubmit:R,noValidate:!0,children:[u==="backup_code"?e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"code",children:"Backup code"}),e.jsx(ig,{type:"text",id:"code",name:"code",value:a,onChange:_,placeholder:"Enter backup code",maxLength:20,autoComplete:"one-time-code","aria-invalid":!!f.code,autoFocus:!0}),f.code&&e.jsx(xs,{children:f.code})]}):e.jsx(It,{onComplete:async O=>{if(h(O),u!=="backup_code"){const P=new Event("submit",{bubbles:!0,cancelable:!0});await R(P)}},onResend:u==="phone_otp"?async()=>{try{await n({strategy:"phone_otp",lastDigits:E.slice(-4)})}catch(O){c({submit:O.message})}}:void 0,error:f.code,isSubmitting:p}),e.jsxs("div",{children:[f.submit&&e.jsx(xs,{children:f.submit}),e.jsx(sg,{type:"submit",disabled:p||!a,children:p?"Verifying...":"Verify"})]})]}),e.jsxs(vs,{children:[e.jsx(Rr,{onClick:()=>{v(!0),g(null),h(""),c({})},style:{cursor:"pointer"},children:"Try another method"}),e.jsxs("div",{style:{marginTop:"var(--space-sm)"},children:["Having trouble?"," ",e.jsx(Rr,{children:e.jsx(ot,{to:(s==null?void 0:s.ui_settings.support_page_url)||"#",children:"Get help"})})]}),t&&e.jsx("div",{style:{marginTop:"var(--space-sm)"},children:e.jsx(Rr,{onClick:t,style:{cursor:"pointer"},children:"Back to login"})})]})]})})}const En=l.div`
1521
1521
  max-width: 380px;
1522
1522
  width: 380px;
1523
1523
  padding: var(--space-3xl);
@@ -1582,7 +1582,7 @@ See https://s-c.sh/2BAXzed for more info.`),window[eo]+=1);/**
1582
1582
  transform: rotate(360deg);
1583
1583
  }
1584
1584
  }
1585
- `;function fl({attempt:t,onBack:r,completeProfile:o,completeVerification:n,prepareVerification:s}){var G,L,A,se,te,U,K,ee,J;const{deployment:a}=ve(),{navigate:h}=Ve(),[f,c]=i.useState({}),[p,d]=i.useState({}),[u,g]=i.useState("US"),[m,v]=i.useState(!1),[y,S]=i.useState(!1),[E,b]=i.useState(null),[$,C]=i.useState(!1),w=E,j=y,x=async ie=>{var oe;S(!0),b(null);try{if(await o(ie)){C(!0);let Q=new URLSearchParams(window.location.search).get("redirect_uri");if(Q||(Q=((oe=a==null?void 0:a.ui_settings)==null?void 0:oe.after_signin_redirect_url)||null),!Q&&(a!=null&&a.frontend_host)&&(Q=`https://${a.frontend_host}`),Q){const ce=new URL(Q);(a==null?void 0:a.mode)==="staging"&&ce.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),h(ce.toString())}}}catch(de){const Q=de;throw b(Q),Q}finally{S(!1)}},I=async ie=>{var oe;S(!0),b(null);try{if(await n(ie)){C(!0);let Q=new URLSearchParams(window.location.search).get("redirect_uri");if(Q||(Q=((oe=a==null?void 0:a.ui_settings)==null?void 0:oe.after_signin_redirect_url)||null),!Q&&(a!=null&&a.frontend_host)&&(Q=`https://${a.frontend_host}`),Q){const ce=new URL(Q);(a==null?void 0:a.mode)==="staging"&&ce.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),h(ce.toString())}}return!0}catch(de){return b(de),!1}finally{S(!1)}};if($||!t)return e.jsx(ue,{children:e.jsxs(En,{children:[e.jsx(Re,{}),e.jsx(dg,{children:e.jsx(Pt,{size:32})})]})});const k=t.missing_fields||[],R="Complete Your Profile",_="Please provide the following information to continue",O=a==null?void 0:a.auth_settings,P=(t==null?void 0:t.current_step)==="verify_phone_otp"||(t==null?void 0:t.current_step)==="verify_email_otp"||m,z=ie=>{const{name:oe,value:de}=ie.target;c(Q=>({...Q,[oe]:de})),p[oe]&&d(Q=>({...Q,[oe]:""}))},T=()=>{const ie={};return k.forEach(oe=>{var ce,B,V,D,le;const de=f[oe];let Q=!1;switch(oe){case"first_name":Q=((ce=O==null?void 0:O.first_name)==null?void 0:ce.enabled)||!1;break;case"last_name":Q=((B=O==null?void 0:O.last_name)==null?void 0:B.enabled)||!1;break;case"username":Q=((V=O==null?void 0:O.username)==null?void 0:V.enabled)||!1;break;case"phone_number":Q=((D=O==null?void 0:O.phone_number)==null?void 0:D.enabled)||!1;break;case"email_address":Q=((le=O==null?void 0:O.email_address)==null?void 0:le.enabled)||!1;break;default:Q=!0}if(Q&&(!de||de.trim()==="")){const H=oe.replace("_"," ").replace(/\b\w/g,ae=>ae.toUpperCase());ie[oe]=`${H} is required`}}),f.username&&k.includes("username")&&(/^[a-zA-Z0-9_-]{3,30}$/.test(f.username)||(ie.username="Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens")),f.phone_number&&k.includes("phone_number")&&(/^\d{7,15}$/.test(f.phone_number)||(ie.phone_number="Phone number must contain 7-15 digits")),f.email&&k.includes("email_address")&&(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(f.email)||(ie.email_address="Please enter a valid email address")),d(ie),Object.keys(ie).length===0},M=async ie=>{if(ie.preventDefault(),!T())return;const oe={...f};f.phone_number&&u&&(oe.phone_country_code=u),await x(oe)},F=ie=>{const oe=ie.target.value;c(de=>({...de,phone_number:oe})),p.phone_number&&d(de=>({...de,phone_number:""}))};if(P){const ie=t.current_step==="verify_phone_otp"?"Verify Your Phone Number":"Verify Your Email",oe=t.current_step==="verify_phone_otp"?"Enter the 6-digit code sent to your phone":"Enter the 6-digit code sent to your email",de=t.current_step==="verify_phone_otp"?"phone_otp":"email_otp";return e.jsx(ue,{children:e.jsxs(En,{children:[e.jsx(Re,{}),e.jsxs(bs,{children:[e.jsx(ys,{children:ie}),e.jsx(ws,{children:oe})]}),e.jsxs(lt,{onSubmit:Q=>Q.preventDefault(),noValidate:!0,children:[e.jsx(It,{onComplete:I,onResend:async()=>{await s({strategy:de})},error:w==null?void 0:w.message,isSubmitting:j}),w&&e.jsx(Lt,{style:{marginBottom:"var(--space-md)"},children:w.message})]}),e.jsxs(js,{children:[e.jsx("div",{children:e.jsx(ao,{onClick:()=>v(!1),style:{cursor:"pointer"},children:"Back to profile completion"})}),e.jsxs("div",{style:{marginTop:"var(--space-sm)"},children:["Having trouble?"," ",e.jsx(ao,{children:e.jsx(ot,{to:(a==null?void 0:a.ui_settings.support_page_url)||"#",children:"Get help"})})]})]})]})})}return e.jsx(ue,{children:e.jsxs(En,{children:[e.jsx(Re,{}),e.jsxs(bs,{children:[e.jsx(ys,{children:R}),e.jsx(ws,{children:_})]}),e.jsxs(lt,{onSubmit:M,noValidate:!0,children:[(k.includes("first_name")||k.includes("last_name"))&&(((G=O==null?void 0:O.first_name)==null?void 0:G.enabled)||((L=O==null?void 0:O.last_name)==null?void 0:L.enabled))&&e.jsxs(cg,{$isBothEnabled:!!((A=O==null?void 0:O.first_name)!=null&&A.enabled&&((se=O==null?void 0:O.last_name)!=null&&se.enabled)&&k.includes("first_name")&&k.includes("last_name")),children:[k.includes("first_name")&&((te=O==null?void 0:O.first_name)==null?void 0:te.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"first_name",children:["First name ",O.first_name.required&&"*"]}),e.jsx(pe,{type:"text",id:"first_name",name:"first_name",value:f.first_name||"",onChange:z,placeholder:"Enter your first name","aria-invalid":!!p.first_name,disabled:j,autoComplete:"given-name"}),p.first_name&&e.jsx(Lt,{children:p.first_name})]}),k.includes("last_name")&&((U=O==null?void 0:O.last_name)==null?void 0:U.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"last_name",children:["Last name ",O.last_name.required&&"*"]}),e.jsx(pe,{type:"text",id:"last_name",name:"last_name",value:f.last_name||"",onChange:z,placeholder:"Enter your last name","aria-invalid":!!p.last_name,disabled:j,autoComplete:"family-name"}),p.last_name&&e.jsx(Lt,{children:p.last_name})]})]}),k.includes("username")&&((K=O==null?void 0:O.username)==null?void 0:K.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"username",children:["Username ",O.username.required&&"*"]}),e.jsx(pe,{type:"text",id:"username",name:"username",value:f.username||"",onChange:z,placeholder:"Choose a username","aria-invalid":!!p.username,disabled:j,autoComplete:"username"}),p.username&&e.jsx(Lt,{children:p.username})]}),k.includes("phone_number")&&((ee=O==null?void 0:O.phone_number)==null?void 0:ee.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"phone_number",children:["Phone number ",O.phone_number.required&&"*"]}),e.jsx(Gr,{value:f.phone_number||"",onChange:F,error:p.phone_number,countryCode:u,setCountryCode:g}),p.phone_number&&e.jsx(Lt,{children:p.phone_number})]}),k.includes("email_address")&&((J=O==null?void 0:O.email_address)==null?void 0:J.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"email",children:["Email address ",O.email_address.required&&"*"]}),e.jsx(pe,{type:"email",id:"email",name:"email",value:f.email||"",onChange:z,placeholder:"Enter your email address","aria-invalid":!!p.email_address,disabled:j,autoComplete:"email"}),p.email_address&&e.jsx(Lt,{children:p.email_address})]}),w&&e.jsx(Lt,{style:{marginBottom:"var(--space-md)"},children:w.message}),e.jsx(lg,{type:"submit",disabled:j,children:j?"Completing...":"Continue"})]}),e.jsxs(js,{children:[r&&e.jsx("div",{children:e.jsx(ao,{onClick:r,style:{cursor:"pointer"},children:"Back to login"})}),e.jsxs("div",{style:{marginTop:"var(--space-sm)"},children:["Having trouble?"," ",e.jsx(ao,{children:e.jsx(ot,{to:(a==null?void 0:a.ui_settings.support_page_url)||"#",children:"Get help"})})]})]})]})})}const ug=or`
1585
+ `;function fl({attempt:t,onBack:r,completeProfile:o,completeVerification:n,prepareVerification:s}){var G,L,A,se,te,U,K,ee,J;const{deployment:a}=ve(),{navigate:h}=Ve(),[f,c]=i.useState({}),[p,d]=i.useState({}),[u,g]=i.useState("US"),[m,v]=i.useState(!1),[y,S]=i.useState(!1),[E,b]=i.useState(null),[$,C]=i.useState(!1),w=E,j=y,x=async ie=>{var oe;S(!0),b(null);try{if(await o(ie)){C(!0);let Q=new URLSearchParams(window.location.search).get("redirect_uri");if(Q||(Q=((oe=a==null?void 0:a.ui_settings)==null?void 0:oe.after_signin_redirect_url)||null),!Q&&(a!=null&&a.frontend_host)&&(Q=`https://${a.frontend_host}`),Q){const ce=new URL(Q);(a==null?void 0:a.mode)==="staging"&&ce.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),h(ce.toString())}}}catch(de){const Q=de;throw b(Q),Q}finally{S(!1)}},I=async ie=>{var oe;S(!0),b(null);try{if(await n(ie)){C(!0);let Q=new URLSearchParams(window.location.search).get("redirect_uri");if(Q||(Q=((oe=a==null?void 0:a.ui_settings)==null?void 0:oe.after_signin_redirect_url)||null),!Q&&(a!=null&&a.frontend_host)&&(Q=`https://${a.frontend_host}`),Q){const ce=new URL(Q);(a==null?void 0:a.mode)==="staging"&&ce.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),h(ce.toString())}}return!0}catch(de){return b(de),!1}finally{S(!1)}};if($||!t)return e.jsx(ue,{children:e.jsxs(En,{children:[e.jsx(Re,{}),e.jsx(dg,{children:e.jsx(vt,{size:32})})]})});const k=t.missing_fields||[],R="Complete Your Profile",_="Please provide the following information to continue",O=a==null?void 0:a.auth_settings,P=(t==null?void 0:t.current_step)==="verify_phone_otp"||(t==null?void 0:t.current_step)==="verify_email_otp"||m,z=ie=>{const{name:oe,value:de}=ie.target;c(Q=>({...Q,[oe]:de})),p[oe]&&d(Q=>({...Q,[oe]:""}))},T=()=>{const ie={};return k.forEach(oe=>{var ce,B,V,D,le;const de=f[oe];let Q=!1;switch(oe){case"first_name":Q=((ce=O==null?void 0:O.first_name)==null?void 0:ce.enabled)||!1;break;case"last_name":Q=((B=O==null?void 0:O.last_name)==null?void 0:B.enabled)||!1;break;case"username":Q=((V=O==null?void 0:O.username)==null?void 0:V.enabled)||!1;break;case"phone_number":Q=((D=O==null?void 0:O.phone_number)==null?void 0:D.enabled)||!1;break;case"email_address":Q=((le=O==null?void 0:O.email_address)==null?void 0:le.enabled)||!1;break;default:Q=!0}if(Q&&(!de||de.trim()==="")){const H=oe.replace("_"," ").replace(/\b\w/g,ae=>ae.toUpperCase());ie[oe]=`${H} is required`}}),f.username&&k.includes("username")&&(/^[a-zA-Z0-9_-]{3,30}$/.test(f.username)||(ie.username="Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens")),f.phone_number&&k.includes("phone_number")&&(/^\d{7,15}$/.test(f.phone_number)||(ie.phone_number="Phone number must contain 7-15 digits")),f.email&&k.includes("email_address")&&(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(f.email)||(ie.email_address="Please enter a valid email address")),d(ie),Object.keys(ie).length===0},M=async ie=>{if(ie.preventDefault(),!T())return;const oe={...f};f.phone_number&&u&&(oe.phone_country_code=u),await x(oe)},F=ie=>{const oe=ie.target.value;c(de=>({...de,phone_number:oe})),p.phone_number&&d(de=>({...de,phone_number:""}))};if(P){const ie=t.current_step==="verify_phone_otp"?"Verify Your Phone Number":"Verify Your Email",oe=t.current_step==="verify_phone_otp"?"Enter the 6-digit code sent to your phone":"Enter the 6-digit code sent to your email",de=t.current_step==="verify_phone_otp"?"phone_otp":"email_otp";return e.jsx(ue,{children:e.jsxs(En,{children:[e.jsx(Re,{}),e.jsxs(bs,{children:[e.jsx(ys,{children:ie}),e.jsx(ws,{children:oe})]}),e.jsxs(lt,{onSubmit:Q=>Q.preventDefault(),noValidate:!0,children:[e.jsx(It,{onComplete:I,onResend:async()=>{await s({strategy:de})},error:w==null?void 0:w.message,isSubmitting:j}),w&&e.jsx(Lt,{style:{marginBottom:"var(--space-md)"},children:w.message})]}),e.jsxs(js,{children:[e.jsx("div",{children:e.jsx(ao,{onClick:()=>v(!1),style:{cursor:"pointer"},children:"Back to profile completion"})}),e.jsxs("div",{style:{marginTop:"var(--space-sm)"},children:["Having trouble?"," ",e.jsx(ao,{children:e.jsx(ot,{to:(a==null?void 0:a.ui_settings.support_page_url)||"#",children:"Get help"})})]})]})]})})}return e.jsx(ue,{children:e.jsxs(En,{children:[e.jsx(Re,{}),e.jsxs(bs,{children:[e.jsx(ys,{children:R}),e.jsx(ws,{children:_})]}),e.jsxs(lt,{onSubmit:M,noValidate:!0,children:[(k.includes("first_name")||k.includes("last_name"))&&(((G=O==null?void 0:O.first_name)==null?void 0:G.enabled)||((L=O==null?void 0:O.last_name)==null?void 0:L.enabled))&&e.jsxs(cg,{$isBothEnabled:!!((A=O==null?void 0:O.first_name)!=null&&A.enabled&&((se=O==null?void 0:O.last_name)!=null&&se.enabled)&&k.includes("first_name")&&k.includes("last_name")),children:[k.includes("first_name")&&((te=O==null?void 0:O.first_name)==null?void 0:te.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"first_name",children:["First name ",O.first_name.required&&"*"]}),e.jsx(pe,{type:"text",id:"first_name",name:"first_name",value:f.first_name||"",onChange:z,placeholder:"Enter your first name","aria-invalid":!!p.first_name,disabled:j,autoComplete:"given-name"}),p.first_name&&e.jsx(Lt,{children:p.first_name})]}),k.includes("last_name")&&((U=O==null?void 0:O.last_name)==null?void 0:U.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"last_name",children:["Last name ",O.last_name.required&&"*"]}),e.jsx(pe,{type:"text",id:"last_name",name:"last_name",value:f.last_name||"",onChange:z,placeholder:"Enter your last name","aria-invalid":!!p.last_name,disabled:j,autoComplete:"family-name"}),p.last_name&&e.jsx(Lt,{children:p.last_name})]})]}),k.includes("username")&&((K=O==null?void 0:O.username)==null?void 0:K.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"username",children:["Username ",O.username.required&&"*"]}),e.jsx(pe,{type:"text",id:"username",name:"username",value:f.username||"",onChange:z,placeholder:"Choose a username","aria-invalid":!!p.username,disabled:j,autoComplete:"username"}),p.username&&e.jsx(Lt,{children:p.username})]}),k.includes("phone_number")&&((ee=O==null?void 0:O.phone_number)==null?void 0:ee.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"phone_number",children:["Phone number ",O.phone_number.required&&"*"]}),e.jsx(Gr,{value:f.phone_number||"",onChange:F,error:p.phone_number,countryCode:u,setCountryCode:g}),p.phone_number&&e.jsx(Lt,{children:p.phone_number})]}),k.includes("email_address")&&((J=O==null?void 0:O.email_address)==null?void 0:J.enabled)&&e.jsxs(ge,{children:[e.jsxs(he,{htmlFor:"email",children:["Email address ",O.email_address.required&&"*"]}),e.jsx(pe,{type:"email",id:"email",name:"email",value:f.email||"",onChange:z,placeholder:"Enter your email address","aria-invalid":!!p.email_address,disabled:j,autoComplete:"email"}),p.email_address&&e.jsx(Lt,{children:p.email_address})]}),w&&e.jsx(Lt,{style:{marginBottom:"var(--space-md)"},children:w.message}),e.jsx(lg,{type:"submit",disabled:j,children:j?"Completing...":"Continue"})]}),e.jsxs(js,{children:[r&&e.jsx("div",{children:e.jsx(ao,{onClick:r,style:{cursor:"pointer"},children:"Back to login"})}),e.jsxs("div",{style:{marginTop:"var(--space-sm)"},children:["Having trouble?"," ",e.jsx(ao,{children:e.jsx(ot,{to:(a==null?void 0:a.ui_settings.support_page_url)||"#",children:"Get help"})})]})]})]})})}const ug=or`
1586
1586
  from {
1587
1587
  transform: rotate(0deg);
1588
1588
  }
@@ -1666,7 +1666,7 @@ cursor: pointer;
1666
1666
  &:hover {
1667
1667
  color: var(--color-primary-hover);
1668
1668
  }
1669
- `;function gg(){return e.jsx(kf,{children:e.jsx(mg,{})})}function mg(){var ie,oe,de,Q,ce,B,V,D,le,H,ae,ke;const{deployment:t}=ve(),{navigate:r}=Ve(),{session:o,loading:n}=Be(),s=((oe=(ie=t==null?void 0:t.auth_settings)==null?void 0:ie.multi_session_support)==null?void 0:oe.enabled)??!1,{setEmail:a,otpSent:h,setOtpSent:f,showForgotPassword:c,setShowForgotPassword:p,showOtherOptions:d,setShowOtherOptions:u,enabledSocialsProviders:g,firstFactor:m,signInStep:v,setSignInStep:y}=ll(),{loading:S,signIn:E,signinAttempt:b,discardSignInAttempt:$,setSignInAttempt:C}=Dr("generic"),{signIn:w}=Dr("oauth"),[j,x]=i.useState({email:"",username:"",password:"",phone:""}),[I,k]=i.useState({}),[R,_]=i.useState(!1),[O,P]=i.useState(""),[z,T]=i.useState("US"),[M,F]=i.useState(!1);i.useEffect(()=>{var ne;if(!n&&(o!=null&&o.active_signin)&&!s&&!M){F(!0);let Y=new URLSearchParams(window.location.search).get("redirect_uri");Y||(Y=((ne=t==null?void 0:t.ui_settings)==null?void 0:ne.after_signin_redirect_url)||null),!Y&&(t!=null&&t.frontend_host)&&(Y=`https://${t.frontend_host}`),Y&&r(Y)}},[o,n,s,t,r,M]);const G=ne=>{let{name:Y,value:Z}=ne.target;Y==="phone"?Z=Z.replace(/[^0-9]/g,""):Y==="email"&&(a(Z),Z=Z.toLowerCase()),x(N=>({...N,[Y]:Z})),k(N=>({...N,[Y]:""}))},L=()=>{x({email:"",username:"",password:"",phone:""}),k({}),T("US"),y("identifier")},A=async ne=>{if(!ne){k({email:"Email address is required"});return}try{const Y=await E.identify(ne);if(Y.strategy==="sso"&&Y.connection_id){const N=new URLSearchParams(window.location.search).get("redirect_uri")||void 0,W=await E.initEnterpriseSso(Y.connection_id,N);W&&W.sso_url&&(window.location.href=W.sso_url)}else if(Y.strategy==="social"&&Y.provider){const Z=g.find(N=>N.provider===Y.provider);if(Z){const W=new URLSearchParams(window.location.search).get("redirect_uri")||void 0,{data:fe}=await w.create({provider:Z.provider,redirectUri:W});fe&&typeof fe=="object"&&"oauth_url"in fe&&(window.location.href=fe.oauth_url)}else y("password")}else y("password")}catch(Y){k({submit:Y.message})}},se=async ne=>{if(ne.preventDefault(),S||R)return;$();const Y={};if(v==="identifier"&&m==="email_password"){if(!j.email){k({email:"Email address is required"});return}await A(j.email);return}if(m==="email_password"?(j.email||(Y.email="Email address is required"),j.password||(Y.password="Password is required")):m==="username_password"?(j.username||(Y.username="Username is required"),j.password||(Y.password="Password is required")):m==="email_otp"||m==="email_magic_link"?j.email||(Y.email="Email address is required"):m==="phone_otp"&&(j.phone?/^\d{7,15}$/.test(j.phone)||(Y.phone="Phone number must contain 7-15 digits"):Y.phone="Phone number is required"),k(Y),Object.keys(Y).length>0)return;let Z="";switch(m){case"email_password":Z="plain_email";break;case"username_password":Z="plain_username";break;case"email_otp":Z="email_otp";break;case"email_magic_link":Z="magic_link";break;case"phone_otp":Z="phone_otp";break}_(!0);try{const N={...j,strategy:Z};m==="phone_otp"&&z&&(N.phone_country_code=z),await E.create(N)}catch(N){k({submit:N.message}),_(!1)}},te=async ne=>{if(ne.preventDefault(),S||R)return;const Y={};if(!O){Y.otp="OTP code is required",k(Y);return}_(!0),k({});try{await E.completeVerification(O),f(!1),P("")}catch(Z){k({otp:Z.message||"Verification failed"})}finally{_(!1)}},U=async ne=>{if(!(S||R)){_(!0);try{const Z=new URLSearchParams(window.location.search).get("redirect_uri")||void 0,{data:N}=await w.create({provider:ne.provider,redirectUri:Z});N&&typeof N=="object"&&"oauth_url"in N&&(window.location.href=N.oauth_url)}catch(Y){k({submit:Y.message})}finally{_(!1)}}},K=i.useRef(!1);if(i.useEffect(()=>{if(n)return;const ne=new URLSearchParams(window.location.search),Y=ne.get("impersonation_token");if(Y&&!b&&!S&&!K.current){K.current=!0,ne.delete("impersonation_token");const N=ne.toString()?`${window.location.pathname}?${ne.toString()} `:window.location.pathname;window.history.replaceState({},"",N),(async()=>{try{_(!0),await E.create({strategy:"impersonation",token:Y})}catch(fe){k({submit:fe.message}),_(!1),K.current=!1}})();return}const Z=ne.get("signin_attempt_id");if(Z&&(o!=null&&o.signin_attempts)&&!b){const N=o.signin_attempts.find(W=>W.id===Z);if(N){C(N),ne.delete("signin_attempt_id");const W=ne.toString()?`${window.location.pathname}?${ne.toString()} `:window.location.pathname;window.history.replaceState({},"",W)}}},[o,n,b,C,S]),i.useEffect(()=>{var N;if(!b)return;if(b.completed){F(!0);let W=new URLSearchParams(window.location.search).get("redirect_uri");if(W||(W=((N=t==null?void 0:t.ui_settings)==null?void 0:N.after_signin_redirect_url)||null),!W&&(t!=null&&t.frontend_host)&&(W=`https://${t.frontend_host}`),W){const fe=new URL(W);(t==null?void 0:t.mode)==="staging"&&fe.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),r(fe.toString())}return}if(!E||h)return;const Y={verify_email:"email_otp",verify_email_otp:"email_otp",verify_email_link:"magic_link",verify_phone:"phone_otp",verify_phone_otp:"phone_otp"}[b.current_step];if(!Y)return;(async()=>{try{await E.prepareVerification({strategy:Y}),f(!0)}catch(W){console.error("Failed to prepare verification:",W),k({submit:"Failed to send verification. Please try again."})}finally{_(!1)}})()},[b,E,h,f,r,t]),i.useEffect(()=>{},[]),d)return e.jsx(Of,{onBack:()=>u(!1)});if(c)return e.jsx(zf,{onBack:()=>p(!1)});if((b==null?void 0:b.current_step)==="verify_second_factor")return e.jsx(hl,{attempt:b,completeVerification:E.completeVerification,prepareVerification:E.prepareVerification,onBack:()=>{$(),L(),f(!1)}});if((b==null?void 0:b.current_step)==="complete_profile")return e.jsx(fl,{attempt:b,completeProfile:E.completeProfile,completeVerification:E.completeVerification,prepareVerification:E.prepareVerification,onBack:()=>{$(),L(),f(!1)}});if(n)return e.jsx(ue,{children:e.jsxs(Pn,{children:[e.jsx(Re,{}),e.jsx(ks,{children:e.jsx(Pt,{size:32})})]})});if(M)return e.jsx(ue,{children:e.jsxs(Pn,{children:[e.jsx(Re,{}),e.jsx(ks,{children:e.jsx(Pt,{size:32})})]})});const J=(b==null?void 0:b.current_step)&&["verify_email","verify_email_otp","verify_email_link","verify_phone","verify_phone_otp"].includes(b.current_step)&&h;return e.jsx(ue,{children:e.jsxs(Pn,{children:[e.jsx(Re,{}),J?e.jsx(e.Fragment,{children:e.jsxs(_s,{children:[e.jsx(Cs,{children:m==="phone_otp"?"Check your phone":"Check your email"}),e.jsx(Ss,{children:m==="email_magic_link"?`If ${j.email} exists in our records, you will receive a magic link. Click the link to sign in.`:m==="phone_otp"?`If ${j.phone} exists in our records, you will receive a verification code via SMS. Enter it below to continue.`:`If ${j.email} exists in our records, you will receive a verification code. Enter it below to continue.`})]})}):e.jsxs(_s,{children:[e.jsx(Cs,{children:"Sign in to your account"}),e.jsxs(Ss,{children:["Please enter your details to continue to"," ",(t==null?void 0:t.ui_settings.app_name)||"App","!"]})]}),J?m==="email_magic_link"?e.jsxs(Rn,{children:["Having trouble?"," ",e.jsx(At,{children:e.jsx(ot,{to:t.ui_settings.support_page_url,children:"Get help"})}),e.jsx("div",{style:{marginTop:"var(--space-sm)"},children:e.jsx(At,{onClick:()=>{f(!1),$(),L()},style:{cursor:"pointer"},children:"Back to login"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(lt,{style:{gap:"15px"},onSubmit:te,noValidate:!0,children:[e.jsx(It,{onComplete:async ne=>{if(P(ne),ne&&ne.length===6){_(!0),k({});try{await E.completeVerification(ne),f(!1)}catch(Y){k({otp:Y.message||"Verification failed"})}finally{_(!1)}}},onResend:async()=>{const ne=m==="email_otp"?"email_otp":"phone_otp";await E.prepareVerification({strategy:ne})},error:I.otp,isSubmitting:R}),e.jsx($s,{type:"submit",disabled:R||S||!O,style:{margin:0},children:R?"Verifying...":`Continue to ${(ke=t==null?void 0:t.ui_settings)==null?void 0:ke.app_name}`})]}),e.jsxs(Rn,{children:["Having trouble?"," ",e.jsx(At,{children:e.jsx(ot,{to:t.ui_settings.support_page_url,children:"Get help"})}),e.jsx("div",{style:{marginTop:"var(--space-sm)"},children:e.jsx(At,{onClick:()=>{f(!1),$(),L()},style:{cursor:"pointer"},children:"Back to login"})})]})]}):e.jsxs(e.Fragment,{children:[g.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(_a,{connections:g,callback:U}),e.jsx(pg,{children:e.jsx(hg,{children:"or"})})]}),e.jsxs(lt,{onSubmit:se,noValidate:!0,children:[(m==="email_password"||m==="email_otp"||m==="email_magic_link")&&((Q=(de=t==null?void 0:t.auth_settings)==null?void 0:de.email_address)==null?void 0:Q.enabled)&&e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"email",children:"Email address"}),e.jsx(pe,{type:"email",id:"email",name:"email",value:j.email,onChange:G,placeholder:"Enter your email address","aria-invalid":!!I.email}),I.email&&e.jsx(Ir,{children:I.email})]}),m==="username_password"&&((B=(ce=t==null?void 0:t.auth_settings)==null?void 0:ce.username)==null?void 0:B.enabled)&&e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"username",children:"Username"}),e.jsx(pe,{type:"text",id:"username",name:"username",value:j.username,onChange:G,placeholder:"Enter your username","aria-invalid":!!I.username}),I.username&&e.jsx(Ir,{children:I.username})]}),m==="phone_otp"&&((D=(V=t==null?void 0:t.auth_settings)==null?void 0:V.phone_number)==null?void 0:D.enabled)&&e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"phone",children:"Phone number"}),e.jsx(Gr,{value:j.phone,onChange:G,error:I.phone,countryCode:z,setCountryCode:T}),I.phone&&e.jsx(Ir,{children:I.phone})]}),v==="password"&&(m==="email_password"||m==="username_password")&&((H=(le=t==null?void 0:t.auth_settings)==null?void 0:le.password)==null?void 0:H.enabled)&&e.jsxs(ge,{children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[e.jsx(he,{htmlFor:"password",children:"Password"}),e.jsx(At,{style:{fontSize:"12px"},onClick:()=>p(!0),children:"Forgot password?"})]}),e.jsx(fg,{children:e.jsx(pe,{type:"password",id:"password",name:"password",value:j.password,onChange:G,placeholder:"Enter your password","aria-invalid":!!I.password})}),I.password&&e.jsx(Ir,{children:I.password})]}),e.jsxs("div",{children:[I.submit&&e.jsx(Ir,{children:I.submit}),e.jsx($s,{type:"submit",disabled:R||S,children:R?v==="identifier"?"Checking...":"Signing in...":v==="identifier"?"Continue":"Sign in"})]}),e.jsx(At,{style:{fontSize:"12px",textAlign:"center"},onClick:()=>u(!0),children:"Use other methods"})]}),e.jsxs(Rn,{children:["Don't have an account?"," ",e.jsx(At,{children:e.jsx(ot,{to:`${(ae=t.ui_settings)==null?void 0:ae.sign_up_page_url}${window.location.search}`,children:"Sign up"})})]})]})]})})}const zs=l.div`
1669
+ `;function gg(){return e.jsx(kf,{children:e.jsx(mg,{})})}function mg(){var ie,oe,de,Q,ce,B,V,D,le,H,ae,ke;const{deployment:t}=ve(),{navigate:r}=Ve(),{session:o,loading:n}=Be(),s=((oe=(ie=t==null?void 0:t.auth_settings)==null?void 0:ie.multi_session_support)==null?void 0:oe.enabled)??!1,{setEmail:a,otpSent:h,setOtpSent:f,showForgotPassword:c,setShowForgotPassword:p,showOtherOptions:d,setShowOtherOptions:u,enabledSocialsProviders:g,firstFactor:m,signInStep:v,setSignInStep:y}=ll(),{loading:S,signIn:E,signinAttempt:b,discardSignInAttempt:$,setSignInAttempt:C}=Dr("generic"),{signIn:w}=Dr("oauth"),[j,x]=i.useState({email:"",username:"",password:"",phone:""}),[I,k]=i.useState({}),[R,_]=i.useState(!1),[O,P]=i.useState(""),[z,T]=i.useState("US"),[M,F]=i.useState(!1);i.useEffect(()=>{var ne;if(!n&&(o!=null&&o.active_signin)&&!s&&!M){F(!0);let Y=new URLSearchParams(window.location.search).get("redirect_uri");Y||(Y=((ne=t==null?void 0:t.ui_settings)==null?void 0:ne.after_signin_redirect_url)||null),!Y&&(t!=null&&t.frontend_host)&&(Y=`https://${t.frontend_host}`),Y&&r(Y)}},[o,n,s,t,r,M]);const G=ne=>{let{name:Y,value:Z}=ne.target;Y==="phone"?Z=Z.replace(/[^0-9]/g,""):Y==="email"&&(a(Z),Z=Z.toLowerCase()),x(N=>({...N,[Y]:Z})),k(N=>({...N,[Y]:""}))},L=()=>{x({email:"",username:"",password:"",phone:""}),k({}),T("US"),y("identifier")},A=async ne=>{if(!ne){k({email:"Email address is required"});return}_(!0),k({});try{const Y=await E.identify(ne);if(Y.strategy==="sso"&&Y.connection_id){const N=new URLSearchParams(window.location.search).get("redirect_uri")||void 0,W=await E.initEnterpriseSso(Y.connection_id,N);if(W&&W.sso_url){F(!0),window.location.href=W.sso_url;return}}else if(Y.strategy==="social"&&Y.provider){const Z=g.find(N=>N.provider===Y.provider);if(Z){const W=new URLSearchParams(window.location.search).get("redirect_uri")||void 0,{data:fe}=await w.create({provider:Z.provider,redirectUri:W});if(fe&&typeof fe=="object"&&"oauth_url"in fe){F(!0),window.location.href=fe.oauth_url;return}}else y("password")}else y("password")}catch(Y){k({submit:Y.message})}finally{M||_(!1)}},se=async ne=>{if(ne.preventDefault(),S||R)return;$();const Y={};if(v==="identifier"&&m==="email_password"){if(!j.email){k({email:"Email address is required"});return}await A(j.email);return}if(m==="email_password"?(j.email||(Y.email="Email address is required"),j.password||(Y.password="Password is required")):m==="username_password"?(j.username||(Y.username="Username is required"),j.password||(Y.password="Password is required")):m==="email_otp"||m==="email_magic_link"?j.email||(Y.email="Email address is required"):m==="phone_otp"&&(j.phone?/^\d{7,15}$/.test(j.phone)||(Y.phone="Phone number must contain 7-15 digits"):Y.phone="Phone number is required"),k(Y),Object.keys(Y).length>0)return;let Z="";switch(m){case"email_password":Z="plain_email";break;case"username_password":Z="plain_username";break;case"email_otp":Z="email_otp";break;case"email_magic_link":Z="magic_link";break;case"phone_otp":Z="phone_otp";break}_(!0);try{const N={...j,strategy:Z};m==="phone_otp"&&z&&(N.phone_country_code=z),await E.create(N)}catch(N){k({submit:N.message}),_(!1)}},te=async ne=>{if(ne.preventDefault(),S||R)return;const Y={};if(!O){Y.otp="OTP code is required",k(Y);return}_(!0),k({});try{await E.completeVerification(O),f(!1),P("")}catch(Z){k({otp:Z.message||"Verification failed"})}finally{_(!1)}},U=async ne=>{if(!(S||R)){_(!0);try{const Z=new URLSearchParams(window.location.search).get("redirect_uri")||void 0,{data:N}=await w.create({provider:ne.provider,redirectUri:Z});N&&typeof N=="object"&&"oauth_url"in N&&(window.location.href=N.oauth_url)}catch(Y){k({submit:Y.message})}finally{_(!1)}}},K=i.useRef(!1);if(i.useEffect(()=>{if(n)return;const ne=new URLSearchParams(window.location.search),Y=ne.get("impersonation_token");if(Y&&!b&&!S&&!K.current){K.current=!0,ne.delete("impersonation_token");const N=ne.toString()?`${window.location.pathname}?${ne.toString()} `:window.location.pathname;window.history.replaceState({},"",N),(async()=>{try{_(!0),await E.create({strategy:"impersonation",token:Y})}catch(fe){k({submit:fe.message}),_(!1),K.current=!1}})();return}const Z=ne.get("signin_attempt_id");if(Z&&(o!=null&&o.signin_attempts)&&!b){const N=o.signin_attempts.find(W=>W.id===Z);if(N){C(N),ne.delete("signin_attempt_id");const W=ne.toString()?`${window.location.pathname}?${ne.toString()} `:window.location.pathname;window.history.replaceState({},"",W)}}},[o,n,b,C,S]),i.useEffect(()=>{var N;if(!b)return;if(b.completed){F(!0);let W=new URLSearchParams(window.location.search).get("redirect_uri");if(W||(W=((N=t==null?void 0:t.ui_settings)==null?void 0:N.after_signin_redirect_url)||null),!W&&(t!=null&&t.frontend_host)&&(W=`https://${t.frontend_host}`),W){const fe=new URL(W);(t==null?void 0:t.mode)==="staging"&&fe.searchParams.set("__dev_session__",localStorage.getItem("__dev_session__")||""),r(fe.toString())}return}if(!E||h)return;const Y={verify_email:"email_otp",verify_email_otp:"email_otp",verify_email_link:"magic_link",verify_phone:"phone_otp",verify_phone_otp:"phone_otp"}[b.current_step];if(!Y)return;(async()=>{try{await E.prepareVerification({strategy:Y}),f(!0)}catch(W){console.error("Failed to prepare verification:",W),k({submit:"Failed to send verification. Please try again."})}finally{_(!1)}})()},[b,E,h,f,r,t]),i.useEffect(()=>{},[]),d)return e.jsx(Of,{onBack:()=>u(!1)});if(c)return e.jsx(zf,{onBack:()=>p(!1)});if((b==null?void 0:b.current_step)==="verify_second_factor")return e.jsx(hl,{attempt:b,completeVerification:E.completeVerification,prepareVerification:E.prepareVerification,onBack:()=>{$(),L(),f(!1)}});if((b==null?void 0:b.current_step)==="complete_profile")return e.jsx(fl,{attempt:b,completeProfile:E.completeProfile,completeVerification:E.completeVerification,prepareVerification:E.prepareVerification,onBack:()=>{$(),L(),f(!1)}});if(n)return e.jsx(ue,{children:e.jsxs(Pn,{children:[e.jsx(Re,{}),e.jsx(ks,{children:e.jsx(vt,{size:32})})]})});if(M)return e.jsx(ue,{children:e.jsxs(Pn,{children:[e.jsx(Re,{}),e.jsx(ks,{children:e.jsx(vt,{size:32})})]})});const J=(b==null?void 0:b.current_step)&&["verify_email","verify_email_otp","verify_email_link","verify_phone","verify_phone_otp"].includes(b.current_step)&&h;return e.jsx(ue,{children:e.jsxs(Pn,{children:[e.jsx(Re,{}),J?e.jsx(e.Fragment,{children:e.jsxs(_s,{children:[e.jsx(Cs,{children:m==="phone_otp"?"Check your phone":"Check your email"}),e.jsx(Ss,{children:m==="email_magic_link"?`If ${j.email} exists in our records, you will receive a magic link. Click the link to sign in.`:m==="phone_otp"?`If ${j.phone} exists in our records, you will receive a verification code via SMS. Enter it below to continue.`:`If ${j.email} exists in our records, you will receive a verification code. Enter it below to continue.`})]})}):e.jsxs(_s,{children:[e.jsx(Cs,{children:"Sign in to your account"}),e.jsxs(Ss,{children:["Please enter your details to continue to"," ",(t==null?void 0:t.ui_settings.app_name)||"App","!"]})]}),J?m==="email_magic_link"?e.jsxs(Rn,{children:["Having trouble?"," ",e.jsx(At,{children:e.jsx(ot,{to:t.ui_settings.support_page_url,children:"Get help"})}),e.jsx("div",{style:{marginTop:"var(--space-sm)"},children:e.jsx(At,{onClick:()=>{f(!1),$(),L()},style:{cursor:"pointer"},children:"Back to login"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(lt,{style:{gap:"15px"},onSubmit:te,noValidate:!0,children:[e.jsx(It,{onComplete:async ne=>{if(P(ne),ne&&ne.length===6){_(!0),k({});try{await E.completeVerification(ne),f(!1)}catch(Y){k({otp:Y.message||"Verification failed"})}finally{_(!1)}}},onResend:async()=>{const ne=m==="email_otp"?"email_otp":"phone_otp";await E.prepareVerification({strategy:ne})},error:I.otp,isSubmitting:R}),e.jsx($s,{type:"submit",disabled:R||S||!O,style:{margin:0},children:R?"Verifying...":`Continue to ${(ke=t==null?void 0:t.ui_settings)==null?void 0:ke.app_name}`})]}),e.jsxs(Rn,{children:["Having trouble?"," ",e.jsx(At,{children:e.jsx(ot,{to:t.ui_settings.support_page_url,children:"Get help"})}),e.jsx("div",{style:{marginTop:"var(--space-sm)"},children:e.jsx(At,{onClick:()=>{f(!1),$(),L()},style:{cursor:"pointer"},children:"Back to login"})})]})]}):e.jsxs(e.Fragment,{children:[g.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(_a,{connections:g,callback:U}),e.jsx(pg,{children:e.jsx(hg,{children:"or"})})]}),e.jsxs(lt,{onSubmit:se,noValidate:!0,children:[(m==="email_password"||m==="email_otp"||m==="email_magic_link")&&((Q=(de=t==null?void 0:t.auth_settings)==null?void 0:de.email_address)==null?void 0:Q.enabled)&&e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"email",children:"Email address"}),e.jsx(pe,{type:"email",id:"email",name:"email",value:j.email,onChange:G,placeholder:"Enter your email address","aria-invalid":!!I.email}),I.email&&e.jsx(Ir,{children:I.email})]}),m==="username_password"&&((B=(ce=t==null?void 0:t.auth_settings)==null?void 0:ce.username)==null?void 0:B.enabled)&&e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"username",children:"Username"}),e.jsx(pe,{type:"text",id:"username",name:"username",value:j.username,onChange:G,placeholder:"Enter your username","aria-invalid":!!I.username}),I.username&&e.jsx(Ir,{children:I.username})]}),m==="phone_otp"&&((D=(V=t==null?void 0:t.auth_settings)==null?void 0:V.phone_number)==null?void 0:D.enabled)&&e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"phone",children:"Phone number"}),e.jsx(Gr,{value:j.phone,onChange:G,error:I.phone,countryCode:z,setCountryCode:T}),I.phone&&e.jsx(Ir,{children:I.phone})]}),v==="password"&&(m==="email_password"||m==="username_password")&&((H=(le=t==null?void 0:t.auth_settings)==null?void 0:le.password)==null?void 0:H.enabled)&&e.jsxs(ge,{children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[e.jsx(he,{htmlFor:"password",children:"Password"}),e.jsx(At,{style:{fontSize:"12px"},onClick:()=>p(!0),children:"Forgot password?"})]}),e.jsx(fg,{children:e.jsx(pe,{type:"password",id:"password",name:"password",value:j.password,onChange:G,placeholder:"Enter your password","aria-invalid":!!I.password})}),I.password&&e.jsx(Ir,{children:I.password})]}),e.jsxs("div",{children:[I.submit&&e.jsx(Ir,{children:I.submit}),e.jsx($s,{type:"submit",disabled:R||S,children:R?e.jsxs(e.Fragment,{children:[e.jsx(vt,{size:16,style:{animation:"spin 1s linear infinite",marginRight:"8px"}}),v==="identifier"?"Checking...":"Signing in..."]}):v==="identifier"?"Continue":"Sign in"})]}),e.jsx(At,{style:{fontSize:"12px",textAlign:"center"},onClick:()=>u(!0),children:"Use other methods"})]}),e.jsxs(Rn,{children:["Don't have an account?"," ",e.jsx(At,{children:e.jsx(ot,{to:`${(ae=t.ui_settings)==null?void 0:ae.sign_up_page_url}${window.location.search}`,children:"Sign up"})})]})]})]})})}const zs=l.div`
1670
1670
  max-width: 380px;
1671
1671
  width: 380px;
1672
1672
  padding: var(--space-3xl);
@@ -2357,7 +2357,7 @@ cursor: pointer;
2357
2357
  color: var(--color-foreground);
2358
2358
  background: var(--color-input-background);
2359
2359
  }
2360
- `,Ns=({onClose:t,onSuccess:r,role:o,triggerRef:n})=>{var j;const s=i.useRef(null),[a,h]=i.useState((o==null?void 0:o.name)||""),[f,c]=i.useState((o==null?void 0:o.permissions)||[]);qe();const[p,d]=i.useState(!1),[u,g]=i.useState(!1),[m,v]=i.useState({top:0,left:0}),{deployment:y}=ve(),{toast:S}=Je(),E=!!o,b=Array.isArray((j=y==null?void 0:y.b2b_settings)==null?void 0:j.organization_permissions)?y.b2b_settings.organization_permissions.map(x=>({value:x,label:x})):[];i.useEffect(()=>{g(!0);const x=setTimeout(()=>{if(!s.current)return;let _=null;if(n!=null&&n.current)_=n.current;else if(E){const O=document.querySelectorAll("[data-role-dropdown-trigger]");for(let P=0;P<O.length;P++){const z=O[P];if(z.offsetParent!==null){_=z;break}}}else{const O=document.querySelectorAll("button");for(let P=0;P<O.length;P++){const z=O[P];if(z.textContent==="Add role"&&z.offsetParent!==null){_=z;break}}}if(_){const O=_.getBoundingClientRect(),P=400;let z=O.bottom+8,T=O.right-P;T<10&&(T=O.left),z+300>window.innerHeight&&(z=O.top-300-8),v({top:z,left:T})}},10),I=_=>{s.current&&!s.current.contains(_.target)&&(t==null||t())},k=_=>{_.key==="Escape"&&(t==null||t())},R=setTimeout(()=>{document.addEventListener("mousedown",I),document.addEventListener("keydown",k)},100);return()=>{clearTimeout(x),clearTimeout(R),document.removeEventListener("mousedown",I),document.removeEventListener("keydown",k)}},[t,E,n]);const $=x=>x.trim().replace(/[<>\"'&]/g,""),C=x=>x.length>=2&&x.length<=50&&/^[a-zA-Z0-9\s_-]+$/.test(x),w=async()=>{const x=$(a);if(!x){S("Please enter a role name","error");return}if(!C(x)){S("Role name must be 2-50 characters and contain only letters, numbers, spaces, underscores, and hyphens","error");return}if(f.length===0){S("Please select at least one permission","error");return}d(!0);try{const I={id:o==null?void 0:o.id,name:x,permissions:f||[]};r==null||r(I)}catch(I){const k=I.message||`Failed to ${E?"update":"create"} role. Please try again.`;S(k,"error")}finally{d(!1)}};return u?e.jsxs(Cm,{ref:s,$isInTable:E,style:{top:`${m.top}px`,left:`${m.left}px`,visibility:m.top>0?"visible":"hidden"},onClick:x=>x.stopPropagation(),role:"dialog","aria-labelledby":"role-dialog-title","aria-modal":"true",children:[e.jsxs(Sm,{children:[e.jsx($m,{id:"role-dialog-title",children:E?"Edit Role":"Create New Role"}),e.jsx(Pm,{onClick:t,"aria-label":`Close ${E?"edit":"create"} role dialog`,children:e.jsx(Ze,{size:16})})]}),e.jsx(zm,{children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:[e.jsxs(ge,{children:[e.jsx(he,{children:"Role Name"}),e.jsx(pe,{type:"text",placeholder:"e.g. Admin, Editor, Viewer",value:a,onChange:x=>h(x.target.value),autoFocus:!0,"aria-label":"Role name","aria-describedby":"role-name-help"})]}),e.jsxs(ge,{children:[e.jsx(he,{children:"Permissions"}),e.jsx(il,{options:b,value:f,onChange:c,placeholder:"Select permissions","aria-label":"Select permissions for role"})]})]})}),e.jsxs(Em,{children:[e.jsx(X,{$outline:!0,onClick:t,style:{width:"auto"},children:"Cancel"}),e.jsx(X,{onClick:w,disabled:!a||p,style:{width:"auto"},children:p?e.jsxs(e.Fragment,{children:[e.jsx(Ee,{size:14})," ",E?"Updating...":"Creating..."]}):E?"Update Role":"Create Role"})]})]}):null},wt=l.table`
2360
+ `,Ns=({onClose:t,onSuccess:r,role:o,triggerRef:n})=>{var j;const s=i.useRef(null),[a,h]=i.useState((o==null?void 0:o.name)||""),[f,c]=i.useState((o==null?void 0:o.permissions)||[]);qe();const[p,d]=i.useState(!1),[u,g]=i.useState(!1),[m,v]=i.useState({top:0,left:0}),{deployment:y}=ve(),{toast:S}=Je(),E=!!o,b=Array.isArray((j=y==null?void 0:y.b2b_settings)==null?void 0:j.organization_permissions)?y.b2b_settings.organization_permissions.map(x=>({value:x,label:x})):[];i.useEffect(()=>{g(!0);const x=setTimeout(()=>{if(!s.current)return;let _=null;if(n!=null&&n.current)_=n.current;else if(E){const O=document.querySelectorAll("[data-role-dropdown-trigger]");for(let P=0;P<O.length;P++){const z=O[P];if(z.offsetParent!==null){_=z;break}}}else{const O=document.querySelectorAll("button");for(let P=0;P<O.length;P++){const z=O[P];if(z.textContent==="Add role"&&z.offsetParent!==null){_=z;break}}}if(_){const O=_.getBoundingClientRect(),P=400;let z=O.bottom+8,T=O.right-P;T<10&&(T=O.left),z+300>window.innerHeight&&(z=O.top-300-8),v({top:z,left:T})}},10),I=_=>{s.current&&!s.current.contains(_.target)&&(t==null||t())},k=_=>{_.key==="Escape"&&(t==null||t())},R=setTimeout(()=>{document.addEventListener("mousedown",I),document.addEventListener("keydown",k)},100);return()=>{clearTimeout(x),clearTimeout(R),document.removeEventListener("mousedown",I),document.removeEventListener("keydown",k)}},[t,E,n]);const $=x=>x.trim().replace(/[<>\"'&]/g,""),C=x=>x.length>=2&&x.length<=50&&/^[a-zA-Z0-9\s_-]+$/.test(x),w=async()=>{const x=$(a);if(!x){S("Please enter a role name","error");return}if(!C(x)){S("Role name must be 2-50 characters and contain only letters, numbers, spaces, underscores, and hyphens","error");return}if(f.length===0){S("Please select at least one permission","error");return}d(!0);try{const I={id:o==null?void 0:o.id,name:x,permissions:f||[]};r==null||r(I)}catch(I){const k=I.message||`Failed to ${E?"update":"create"} role. Please try again.`;S(k,"error")}finally{d(!1)}};return u?e.jsxs(Cm,{ref:s,$isInTable:E,style:{top:`${m.top}px`,left:`${m.left}px`,visibility:m.top>0?"visible":"hidden"},onClick:x=>x.stopPropagation(),role:"dialog","aria-labelledby":"role-dialog-title","aria-modal":"true",children:[e.jsxs(Sm,{children:[e.jsx($m,{id:"role-dialog-title",children:E?"Edit Role":"Create New Role"}),e.jsx(Pm,{onClick:t,"aria-label":`Close ${E?"edit":"create"} role dialog`,children:e.jsx(Ze,{size:16})})]}),e.jsx(zm,{children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:[e.jsxs(ge,{children:[e.jsx(he,{children:"Role Name"}),e.jsx(pe,{type:"text",placeholder:"e.g. Admin, Editor, Viewer",value:a,onChange:x=>h(x.target.value),autoFocus:!0,"aria-label":"Role name","aria-describedby":"role-name-help"})]}),e.jsxs(ge,{children:[e.jsx(he,{children:"Permissions"}),e.jsx(il,{options:b,value:f,onChange:c,placeholder:"Select permissions","aria-label":"Select permissions for role"})]})]})}),e.jsxs(Em,{children:[e.jsx(X,{$outline:!0,onClick:t,style:{width:"auto"},children:"Cancel"}),e.jsx(X,{onClick:w,disabled:!a||p,style:{width:"auto"},children:p?e.jsxs(e.Fragment,{children:[e.jsx(Ee,{size:14})," ",E?"Updating...":"Creating..."]}):E?"Update Role":"Create Role"})]})]}):null},jt=l.table`
2361
2361
  width: 100%;
2362
2362
  border-collapse: separate;
2363
2363
  border-spacing: 0;
@@ -2366,9 +2366,9 @@ cursor: pointer;
2366
2366
  border-radius: 8px;
2367
2367
  overflow: hidden;
2368
2368
  background: var(--color-background);
2369
- `,jt=l.thead`
2369
+ `,kt=l.thead`
2370
2370
  background-color: var(--color-background-alt);
2371
- `,kt=l.tbody`
2371
+ `,_t=l.tbody`
2372
2372
  background-color: var(--color-background);
2373
2373
 
2374
2374
  tr:last-child td:last-child {
@@ -2409,7 +2409,7 @@ cursor: pointer;
2409
2409
  align-items: center;
2410
2410
  gap: 12px;
2411
2411
  }
2412
- `,_t=l(Le)`
2412
+ `,Ct=l(Le)`
2413
2413
  text-align: right;
2414
2414
  width: auto;
2415
2415
  white-space: nowrap;
@@ -2710,7 +2710,7 @@ cursor: pointer;
2710
2710
  flex-wrap: wrap;
2711
2711
  gap: 12px;
2712
2712
  margin-bottom: 24px;
2713
- `,rx=()=>{var T,M,F,G;const{activeOrganization:t,loading:r}=qe(),{switchOrganization:o,refetch:n}=Be(),{workspaces:s}=bt(),{deployment:a}=ve(),{deleteOrganization:h,updateOrganization:f}=qo(),{toast:c}=Je(),[p,d]=i.useState((t==null?void 0:t.name)||""),[u,g]=i.useState((t==null?void 0:t.description)||""),[m,v]=i.useState((t==null?void 0:t.image_url)||null),y=i.useRef(null),[S,E]=i.useState(!1),[b,$]=i.useState({mfa_required:!1,ip_restrictions:!1,allowed_ips:"",default_workspace_id:""}),[C,w]=i.useState(""),[j,x]=i.useState(!1),[I,k]=i.useState(!1),R=i.useCallback(async()=>{if(!(!t||S))try{E(!0),await f(t,{name:p,description:u}),c("Changes saved","info")}catch(L){const A=L.message||"Failed to save changes. Please try again.";c(A,"error")}finally{E(!1)}},[t,p,u,m,b,f,c]);i.useEffect(()=>{var L;t&&(d(t.name||""),g(t.description||""),v(t.image_url||null),$({allowed_ips:((L=t.whitelisted_ips)==null?void 0:L.join(`
2713
+ `,rx=()=>{var T,M,F,G;const{activeOrganization:t,loading:r}=qe(),{switchOrganization:o,refetch:n}=Be(),{workspaces:s}=yt(),{deployment:a}=ve(),{deleteOrganization:h,updateOrganization:f}=qo(),{toast:c}=Je(),[p,d]=i.useState((t==null?void 0:t.name)||""),[u,g]=i.useState((t==null?void 0:t.description)||""),[m,v]=i.useState((t==null?void 0:t.image_url)||null),y=i.useRef(null),[S,E]=i.useState(!1),[b,$]=i.useState({mfa_required:!1,ip_restrictions:!1,allowed_ips:"",default_workspace_id:""}),[C,w]=i.useState(""),[j,x]=i.useState(!1),[I,k]=i.useState(!1),R=i.useCallback(async()=>{if(!(!t||S))try{E(!0),await f(t,{name:p,description:u}),c("Changes saved","info")}catch(L){const A=L.message||"Failed to save changes. Please try again.";c(A,"error")}finally{E(!1)}},[t,p,u,m,b,f,c]);i.useEffect(()=>{var L;t&&(d(t.name||""),g(t.description||""),v(t.image_url||null),$({allowed_ips:((L=t.whitelisted_ips)==null?void 0:L.join(`
2714
2714
  `))||"",ip_restrictions:t.enable_ip_restriction||!1,mfa_required:t.enforce_mfa||!1,default_workspace_id:t.auto_assigned_workspace_id||""}))},[t]);const _=i.useMemo(()=>s.filter(A=>A.organization.id===(t==null?void 0:t.id)),[s,t==null?void 0:t.id]),O=async()=>{if(!(!t||C!==t.name))try{x(!0),await o(""),await h(t),await n(),c("Organization deleted successfully","info")}catch{c("Failed to delete organization","error")}finally{x(!1),w("")}};if(i.useEffect(()=>()=>{m&&URL.revokeObjectURL(m)},[m]),r)return e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})});const P=L=>{var A;if((A=L.target.files)!=null&&A[0]){const se=L.target.files[0];if(se.size>2*1024*1024){c("File size cannot exceed 2MB","error");return}if(!se.type.startsWith("image/")){c("Please select a valid image file","error");return}m&&URL.revokeObjectURL(m),v(URL.createObjectURL(se)),setTimeout(()=>R(),100)}},z=()=>{y.current&&y.current.click()};return e.jsx(e.Fragment,{children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-2xl)"},children:[e.jsxs("div",{style:{display:"flex",gap:"var(--space-2xl)",alignItems:"center"},children:[e.jsx("div",{style:{flexShrink:0},children:e.jsxs("div",{style:{width:"120px",height:"120px",borderRadius:"50%",border:"2px dashed var(--color-border)",background:m?"transparent":"var(--color-input-background)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",transition:"all 0.2s ease"},onClick:z,onMouseEnter:L=>{L.currentTarget.style.borderColor="var(--color-primary)",L.currentTarget.style.transform="scale(1.02)"},onMouseLeave:L=>{L.currentTarget.style.borderColor="var(--color-border)",L.currentTarget.style.transform="scale(1)"},children:[m?e.jsx("img",{src:m,alt:"Organization Logo",style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:"50%"}}):e.jsx(Fr,{size:32,color:"var(--color-muted)"}),e.jsx("input",{type:"file",ref:y,style:{display:"none"},accept:"image/*",onChange:P,"aria-label":"Upload organization logo"})]})}),e.jsxs("div",{style:{flex:1},children:[e.jsxs("div",{style:{marginBottom:"var(--space-lg)"},children:[e.jsx("h3",{style:{fontSize:"var(--font-sm)",color:"var(--color-foreground)",margin:"0 0 var(--space-2xs) 0"},children:"Organization Logo"}),e.jsx("p",{style:{fontSize:"var(--font-xs)",color:"var(--color-secondary-text)",margin:0},children:"Upload an image to represent your organization"})]}),e.jsxs("div",{style:{display:"flex",gap:"var(--space-sm)",marginBottom:"var(--space-sm)"},children:[e.jsxs(X,{onClick:()=>{var L;return(L=y.current)==null?void 0:L.click()},style:{padding:"var(--space-xs) var(--space-md)",fontSize:"var(--font-xs)",height:"32px",width:"100px",display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx(Fr,{size:14}),m?"Change":"Upload"]}),e.jsxs(X,{onClick:()=>{v(null),y.current&&(y.current.value="")},style:{background:"transparent",color:"var(--color-muted)",border:"1px solid var(--color-border)",padding:"var(--space-xs) var(--space-md)",fontSize:"var(--font-xs)",height:"32px",width:"100px",display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx(Vr,{size:14}),"Remove"]})]})]})]}),e.jsx("div",{style:{position:"relative",height:"1px",background:"var(--color-divider)",margin:"0"}}),e.jsxs("div",{children:[e.jsxs("div",{style:{marginBottom:"var(--space-md)"},children:[e.jsx("h3",{style:{fontSize:"var(--font-sm)",color:"var(--color-foreground)",margin:"0 0 var(--space-2xs) 0"},children:"Organization Details"}),e.jsx("p",{style:{fontSize:"var(--font-xs)",color:"var(--color-secondary-text)",margin:0},children:"Basic information about your organization"})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-lg)"},children:[e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"name",children:"Organization Name"}),e.jsx(pe,{id:"name",type:"text",value:p,onChange:L=>d(L.target.value),onBlur:R,placeholder:"Enter organization name",required:!0})]}),e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(pe,{id:"description",as:"textarea",value:u,onChange:L=>g(L.target.value),onBlur:R,placeholder:"Enter organization description",style:{minHeight:"80px",resize:"vertical",fontFamily:"inherit"}}),e.jsx("p",{style:{fontSize:"var(--font-2xs)",color:"var(--color-muted)",margin:"var(--space-2xs) 0 0 0"},children:"Brief description of your organization"})]}),((T=a==null?void 0:a.b2b_settings)==null?void 0:T.enforce_mfa_per_org_enabled)&&e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{children:[e.jsx(he,{style:{fontSize:"var(--font-xs)",color:"var(--color-foreground)",display:"block",marginBottom:"var(--space-2xs)"},children:"Multi-Factor Authentication"}),e.jsx("div",{style:{fontSize:"var(--font-2xs)",color:"var(--color-muted)"},id:"mfa-description",children:"Require all members to set up MFA for added security"})]}),e.jsx(jr,{checked:b.mfa_required,onChange:()=>{$(L=>({...L,mfa_required:!L.mfa_required})),setTimeout(()=>R(),100)}})]}),((M=a==null?void 0:a.b2b_settings)==null?void 0:M.ip_allowlist_per_org_enabled)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{children:[e.jsx(he,{style:{fontSize:"var(--font-xs)",color:"var(--color-foreground)",display:"block",marginBottom:"var(--space-2xs)"},children:"IP Restrictions"}),e.jsx("div",{style:{fontSize:"var(--font-2xs)",color:"var(--color-muted)"},id:"ip-restrictions-description",children:"Only allow access from specific IP addresses"})]}),e.jsx(jr,{checked:b.ip_restrictions,onChange:()=>{$(L=>({...L,ip_restrictions:!L.ip_restrictions})),setTimeout(()=>R(),100)},"aria-label":"Enable IP address restrictions","aria-describedby":"ip-restrictions-description"})]}),b.ip_restrictions&&e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"allowed_ips",children:"Allowed IP Addresses"}),e.jsx(pe,{id:"allowed_ips",as:"textarea",value:b.allowed_ips,onChange:L=>$(A=>({...A,allowed_ips:L.target.value})),onBlur:R,placeholder:`192.168.1.1
2715
2715
  10.0.0.0/24`,style:{minHeight:"80px",resize:"vertical",fontFamily:"monospace"}}),e.jsx("p",{style:{fontSize:"var(--font-2xs)",color:"var(--color-muted)",margin:"var(--space-2xs) 0 0 0"},children:"Enter one IP address or CIDR block per line"})]})]}),((F=a==null?void 0:a.b2b_settings)==null?void 0:F.workspaces_enabled)&&_.length>0&&e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"default_workspace",children:"Default Workspace"}),e.jsx(Ca,{options:_.map(L=>({value:L.id,label:L.name})),value:b.default_workspace_id,onChange:L=>{$(A=>({...A,default_workspace_id:L})),setTimeout(()=>R(),100)},placeholder:"Select default workspace"}),e.jsx("p",{style:{fontSize:"var(--font-2xs)",color:"var(--color-muted)",margin:"var(--space-2xs) 0 0 0"},children:"Workspace that new members will be added to automatically"})]})]})]}),((G=a==null?void 0:a.b2b_settings)==null?void 0:G.allow_org_deletion)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{position:"relative",height:"1px",background:"var(--color-divider)",margin:"0"}}),e.jsxs("div",{children:[e.jsxs("div",{style:{marginBottom:"16px"},children:[e.jsx("h3",{style:{fontSize:"16px",color:"var(--color-foreground)",margin:"0 0 4px 0"},children:"Danger Zone"}),e.jsx("p",{style:{fontSize:"14px",color:"var(--color-muted)",margin:0},children:"Irreversible and destructive actions"})]}),e.jsxs("div",{style:{padding:"20px",border:"1px solid var(--color-error)",borderRadius:"8px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:I?"20px":"0"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"14px",color:"var(--color-foreground)",marginBottom:"4px",fontWeight:"500"},children:"Delete Organization"}),e.jsx("div",{style:{fontSize:"13px",color:"var(--color-muted)"},children:"Once you delete this organization, there is no going back. Please be certain."})]}),e.jsx(X,{onClick:()=>{I?(k(!1),w("")):k(!0)},style:{background:"var(--color-error)",color:"white",border:"none",padding:"6px 12px",fontSize:"13px",height:"32px",width:"auto"},children:I?"Cancel":"Delete"})]}),I&&e.jsxs("div",{children:[e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"confirm_name",children:"Confirm by typing the organization name"}),e.jsx(pe,{id:"confirm_name",type:"text",value:C,onChange:L=>w(L.target.value),placeholder:`Type "${t==null?void 0:t.name}" to confirm`})]}),e.jsx(X,{onClick:O,disabled:C!==(t==null?void 0:t.name)||j,style:{background:C===(t==null?void 0:t.name)?"var(--color-error)":"transparent",color:C===(t==null?void 0:t.name)?"white":"var(--color-muted)",border:"1px solid var(--color-border)",padding:"8px 16px",fontSize:"14px",height:"36px",cursor:C===(t==null?void 0:t.name)?"pointer":"not-allowed",opacity:C===(t==null?void 0:t.name)?1:.6,marginTop:"12px"},children:j?e.jsx(Ee,{size:12}):"Delete Forever"})]})]})]})]})]})})},Us=l.span`
2716
2716
  background: var(--color-primary-background);
@@ -2749,7 +2749,7 @@ cursor: pointer;
2749
2749
  opacity: 0.5;
2750
2750
  cursor: not-allowed;
2751
2751
  }
2752
- `,ox=()=>{const{activeOrganization:t,loading:r,getDomains:o,removeDomain:n}=qe(),s=i.useRef(null),[a,h]=i.useState(null),{data:f=[],isLoading:c,mutate:p}=Ne(t!=null&&t.id?`wacht-org-domains:${t.id}`:null,async()=>(await(o==null?void 0:o())||[]).map((k,R)=>({...k,verified:k.verified!==void 0?k.verified:R%2===0})),{refreshInterval:3e4,revalidateOnFocus:!1,revalidateOnReconnect:!1,dedupingInterval:5e3}),d=f,[u,g]=i.useState(!1),[m,v]=i.useState(null),[y,S]=i.useState(""),[E,b]=i.useState(null),$=i.useRef(null),C=i.useRef({}),w=i.useMemo(()=>{let I=d;if(y.trim()!==""){const k=y.toLowerCase();I=I.filter(R=>R.fqdn.toLowerCase().includes(k))}return I},[d,y]),j=async I=>{await n(I),p()},x=async I=>{v(I)};return r||c?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs(bl,{children:[e.jsx(yt,{value:y,onChange:S,placeholder:"Search Domain"}),e.jsxs("div",{children:[e.jsx(X,{ref:$,onClick:()=>g(!u),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"New Domain"}),u&&e.jsx(Fs,{onClose:()=>{g(!1),p()},triggerRef:$})]})]}),e.jsxs("div",{style:{padding:"12px 16px",background:"var(--color-background-alt)",borderRadius:"8px",marginBottom:"24px",border:"1px solid var(--color-border)",fontSize:"13px",color:"var(--color-secondary-text)"},children:["Users with verified domain emails automatically join this organization",(t==null?void 0:t.auto_assigned_workspace_id)&&" and its default workspace","."]}),w!=null&&w.length?e.jsxs(wt,{ref:s,children:[e.jsx(jt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Domain"}),e.jsx(ze,{children:"Status"}),e.jsx(ze,{children:"Date Added"}),e.jsx(ze,{})]})}),e.jsx(kt,{children:w.map(I=>e.jsxs(We,{children:[e.jsx(Le,{children:I.fqdn}),e.jsx(Le,{children:I.verified?e.jsx(Us,{style:{background:"var(--color-primary-background)",color:"var(--color-primary)"},children:"✓ Verified"}):e.jsxs(Us,{style:{background:"var(--color-warning-background)",color:"var(--color-warning)",border:"1px solid var(--color-warning-border)"},children:[e.jsx(dt,{size:9})," Pending Verification"]})}),e.jsx(Le,{children:new Date(I.created_at).toLocaleDateString()}),e.jsx(_t,{children:e.jsxs("div",{style:{position:"relative"},children:[e.jsxs(nt,{style:{marginLeft:"auto"},open:E===I.id,openChange:k=>b(k?I.id:null),children:[e.jsx(st,{children:e.jsx(Sa,{ref:k=>{C.current[I.id]=k},children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>{x(I.id),b(null)},children:e.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:I.verified?"📋 View DNS Record":"✓ Verify Domain"})}),e.jsx(Te,{onClick:()=>{b(null),navigator.clipboard.writeText(I.fqdn)},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Fo,{size:16,color:"var(--color-muted)"})," Copy Domain"]})}),e.jsx(Te,{onClick:()=>{window.open(`https://${I.fqdn}`,"_blank"),b(null)},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Uc,{size:16,color:"var(--color-muted)"})," ","Visit Domain"]})}),e.jsx(on,{}),e.jsx(Te,{$destructive:!0,onClick:()=>{b(null),h(I.id)},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Vr,{size:16,color:"var(--color-error)"})," ","Remove Domain"]})})]})]}),a===I.id&&e.jsx(Hr,{title:"Are you sure you want to delete this domain?",onConfirm:()=>j(I),onCancel:()=>h(null)}),m===I.id&&e.jsx(Fs,{domain:I,onClose:()=>v(null),triggerRef:{current:C.current[I.id]}})]})})]},I.id))})]}):e.jsx(et,{title:y!=="all"?"No domains match your criteria":"No domains added",description:"Add a domain to get started"})]})},nx=l.div`
2752
+ `,ox=()=>{const{activeOrganization:t,loading:r,getDomains:o,removeDomain:n}=qe(),s=i.useRef(null),[a,h]=i.useState(null),{data:f=[],isLoading:c,mutate:p}=Ne(t!=null&&t.id?`wacht-org-domains:${t.id}`:null,async()=>(await(o==null?void 0:o())||[]).map((k,R)=>({...k,verified:k.verified!==void 0?k.verified:R%2===0})),{refreshInterval:3e4,revalidateOnFocus:!1,revalidateOnReconnect:!1,dedupingInterval:5e3}),d=f,[u,g]=i.useState(!1),[m,v]=i.useState(null),[y,S]=i.useState(""),[E,b]=i.useState(null),$=i.useRef(null),C=i.useRef({}),w=i.useMemo(()=>{let I=d;if(y.trim()!==""){const k=y.toLowerCase();I=I.filter(R=>R.fqdn.toLowerCase().includes(k))}return I},[d,y]),j=async I=>{await n(I),p()},x=async I=>{v(I)};return r||c?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs(bl,{children:[e.jsx(wt,{value:y,onChange:S,placeholder:"Search Domain"}),e.jsxs("div",{children:[e.jsx(X,{ref:$,onClick:()=>g(!u),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"New Domain"}),u&&e.jsx(Fs,{onClose:()=>{g(!1),p()},triggerRef:$})]})]}),e.jsxs("div",{style:{padding:"12px 16px",background:"var(--color-background-alt)",borderRadius:"8px",marginBottom:"24px",border:"1px solid var(--color-border)",fontSize:"13px",color:"var(--color-secondary-text)"},children:["Users with verified domain emails automatically join this organization",(t==null?void 0:t.auto_assigned_workspace_id)&&" and its default workspace","."]}),w!=null&&w.length?e.jsxs(jt,{ref:s,children:[e.jsx(kt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Domain"}),e.jsx(ze,{children:"Status"}),e.jsx(ze,{children:"Date Added"}),e.jsx(ze,{})]})}),e.jsx(_t,{children:w.map(I=>e.jsxs(We,{children:[e.jsx(Le,{children:I.fqdn}),e.jsx(Le,{children:I.verified?e.jsx(Us,{style:{background:"var(--color-primary-background)",color:"var(--color-primary)"},children:"✓ Verified"}):e.jsxs(Us,{style:{background:"var(--color-warning-background)",color:"var(--color-warning)",border:"1px solid var(--color-warning-border)"},children:[e.jsx(dt,{size:9})," Pending Verification"]})}),e.jsx(Le,{children:new Date(I.created_at).toLocaleDateString()}),e.jsx(Ct,{children:e.jsxs("div",{style:{position:"relative"},children:[e.jsxs(nt,{style:{marginLeft:"auto"},open:E===I.id,openChange:k=>b(k?I.id:null),children:[e.jsx(st,{children:e.jsx(Sa,{ref:k=>{C.current[I.id]=k},children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>{x(I.id),b(null)},children:e.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:I.verified?"📋 View DNS Record":"✓ Verify Domain"})}),e.jsx(Te,{onClick:()=>{b(null),navigator.clipboard.writeText(I.fqdn)},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Fo,{size:16,color:"var(--color-muted)"})," Copy Domain"]})}),e.jsx(Te,{onClick:()=>{window.open(`https://${I.fqdn}`,"_blank"),b(null)},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Uc,{size:16,color:"var(--color-muted)"})," ","Visit Domain"]})}),e.jsx(on,{}),e.jsx(Te,{$destructive:!0,onClick:()=>{b(null),h(I.id)},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Vr,{size:16,color:"var(--color-error)"})," ","Remove Domain"]})})]})]}),a===I.id&&e.jsx(Hr,{title:"Are you sure you want to delete this domain?",onConfirm:()=>j(I),onCancel:()=>h(null)}),m===I.id&&e.jsx(Fs,{domain:I,onClose:()=>v(null),triggerRef:{current:C.current[I.id]}})]})})]},I.id))})]}):e.jsx(et,{title:y!=="all"?"No domains match your criteria":"No domains added",description:"Add a domain to get started"})]})},nx=l.div`
2753
2753
  width: 40px;
2754
2754
  height: 40px;
2755
2755
  border-radius: 50%;
@@ -2761,7 +2761,7 @@ cursor: pointer;
2761
2761
  font-weight: 400;
2762
2762
  font-size: 14px;
2763
2763
  overflow: hidden;
2764
- `,ax=()=>{const{activeOrganization:t,loading:r,getMembers:o,getRoles:n,addMemberRole:s,removeMemberRole:a,removeMember:h}=qe(),{session:f}=Be(),{toast:c}=Je(),[p,d]=i.useState(""),[u,g]=i.useState(!1),m=i.useRef(null),{data:v=[],isLoading:y,mutate:S}=Ne(t?`wacht-api-organizations:${t.id}:members`:null,()=>(o==null?void 0:o())||[]),{data:E=[],isLoading:b}=Ne(t?`wacht-api-organizations:${t.id}:roles`:null,()=>(n==null?void 0:n())||[]),$=E,C=i.useMemo(()=>p?v.filter(k=>{var T;const R=k.user;if(!R)return!1;const _=R.first_name||"",O=R.last_name||"",P=((T=R.primary_email_address)==null?void 0:T.email)||"";return`${_} ${O}`.trim().toLowerCase().includes(p.toLowerCase())||P.toLowerCase().includes(p.toLowerCase())}):v,[v,p]),w=async(k,R,_)=>{try{_?(await a(k,R),c("Role removed successfully","info")):(await s(k,R),c("Role added successfully","info")),S()}catch(O){const P=O.message||"Failed to update role. Please try again.";c(P,"error")}},j=(k="",R="")=>`${k[0]||""}${R[0]||""}`.toUpperCase(),x=(k,R)=>{var _;return((_=k.roles)==null?void 0:_.some(O=>O.id===R))||!1},I=()=>{g(!1),S(),c("Invitation sent successfully","info")};return r||y||b?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:"24px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:"16px"},children:[e.jsx("div",{style:{flex:1},children:e.jsx(yt,{value:p,onChange:d,placeholder:"Search members..."})}),e.jsx(X,{ref:m,onClick:()=>g(!u),style:{background:"var(--color-primary)",color:"white",border:"none",padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,whiteSpace:"nowrap",height:"36px",width:"auto"},children:"Invite Members"})]}),u&&e.jsx(xl,{onClose:()=>g(!1),onSuccess:I,roles:$,triggerRef:m}),C.length===0?e.jsx(et,{title:p?"No members match your search":"No members yet",description:"Invite members to your organization to get started."}):e.jsxs(wt,{children:[e.jsx(jt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Member"}),e.jsx(ze,{children:"Joined"}),e.jsx(ze,{children:"Roles"})]})}),e.jsx(kt,{children:C.map(k=>{var P,z;const R=k.roles||[],_=k.user,O=(_==null?void 0:_.id)===((P=f==null?void 0:f.active_signin)==null?void 0:P.user_id);return e.jsxs(We,{children:[e.jsx(vl,{children:e.jsxs("div",{children:[e.jsx(nx,{children:_!=null&&_.profile_picture_url?e.jsx("img",{src:_.profile_picture_url,alt:`${_.first_name||""} ${_.last_name||""}`,style:{width:"100%",height:"100%",objectFit:"cover"}}):j(_==null?void 0:_.first_name,_==null?void 0:_.last_name)||"?"}),e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("span",{style:{fontSize:"14px",fontWeight:500,color:"var(--color-foreground)"},children:(()=>{var M;if(!_)return"Unknown User";const T=`${_.first_name||""} ${_.last_name||""}`.trim();return T||((M=_.primary_email_address)==null?void 0:M.email)||"Unknown User"})()}),O&&e.jsx("span",{style:{fontSize:"12px",padding:"2px 8px",background:"var(--color-background-alt)",borderRadius:"4px",color:"var(--color-secondary-text)"},children:"You"})]}),e.jsx("div",{style:{fontSize:"13px",color:"var(--color-secondary-text)"},children:(z=_==null?void 0:_.primary_email_address)==null?void 0:z.email})]})]})}),e.jsx(Le,{children:new Date(k.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}),e.jsx(_t,{children:e.jsx("div",{style:{position:"relative"},children:e.jsxs(nt,{children:[e.jsx(st,{children:e.jsxs(X,{style:{background:"var(--color-background)",border:"1px solid var(--color-border)",borderRadius:"6px",padding:"6px 12px",fontSize:"14px",color:"var(--color-foreground)",display:"flex",alignItems:"center",gap:"4px",minWidth:"120px",justifyContent:"space-between"},children:[e.jsx("span",{children:R.length>0?R[0].name:"No role"}),e.jsx(er,{size:14})]})}),e.jsxs(at,{children:[$.map(T=>{const M=x(k,T.id);return e.jsx(Te,{onClick:()=>w(k,T,M),children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[e.jsx("span",{children:T.name}),M&&e.jsx(Ye,{size:16,color:"var(--color-success)"})]})},T.id)}),e.jsx(on,{}),e.jsx(Te,{$destructive:!0,onClick:()=>h(k),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Vr,{size:16,color:"var(--color-error)"}),e.jsx("span",{children:"Remove Member"})]})})]})]})})})]},k.id)})})]})]})},sx=()=>{const{activeOrganization:t,loading:r,getInvitations:o,getRoles:n,discardInvitation:s,resendInvitation:a}=qe(),{toast:h}=Je(),[f,c]=i.useState(!1),[p,d]=i.useState(""),u=i.useRef(null),{data:g=[],isLoading:m,mutate:v}=Ne(t?`wacht-api-organizations:${t.id}:invitations`:null,()=>(o==null?void 0:o())||[]),{data:y=[],isLoading:S}=Ne(t?`wacht-api-organizations:${t.id}:roles`:null,()=>(n==null?void 0:n())||[]),E=y,b=i.useMemo(()=>p?g.filter(j=>j.email.toLowerCase().includes(p.toLowerCase())):g,[g,p]),$=()=>{h("Invitation sent successfully","info"),v(),c(!1)},C=async j=>{try{await s(j),v(),h("Invitation cancelled successfully","info")}catch(x){const I=x.message||"Failed to cancel invitation. Please try again.";h(I,"error")}},w=async j=>{try{await a(j),h("Invitation resent successfully","info")}catch(x){const I=x.message||"Failed to resend invitation. Please try again.";h(I,"error")}};return r||m||S?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:"24px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:"16px"},children:[e.jsx("div",{style:{flex:1},children:e.jsx(yt,{value:p,onChange:d,placeholder:"Search invitations..."})}),e.jsx(X,{ref:u,onClick:()=>c(!f),style:{background:"var(--color-primary)",color:"white",border:"none",padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,whiteSpace:"nowrap",height:"36px",width:"auto"},children:"Invite Members"})]}),f&&e.jsx(xl,{onClose:()=>c(!1),onSuccess:$,roles:E,triggerRef:u}),b.length===0?e.jsx(et,{title:p?"No invitations match your search":"No pending invitations",description:"Invite new members to your organization."}):e.jsxs(wt,{children:[e.jsx(jt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Email"}),e.jsx(ze,{children:"Role"}),e.jsx(ze,{children:"Invited"}),e.jsx(ze,{})]})}),e.jsx(kt,{children:b.map(j=>{var x;return e.jsxs(We,{children:[e.jsx(Le,{children:j.email}),e.jsx(Le,{children:((x=j.initial_organization_role)==null?void 0:x.name)||"No role"}),e.jsx(Le,{children:new Date(j.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}),e.jsx(_t,{children:e.jsx("div",{style:{position:"relative"},children:e.jsxs(nt,{children:[e.jsx(st,{children:e.jsx(Sa,{children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>w(j),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Wr,{size:16,color:"var(--color-muted)"}),e.jsx("span",{children:"Resend Invitation"})]})}),e.jsx(Te,{$destructive:!0,onClick:()=>C(j),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Vr,{size:16,color:"var(--color-error)"}),e.jsx("span",{children:"Cancel Invitation"})]})})]})]})})})]},j.id)})})]})]})},ix=()=>{var j;const{activeOrganization:t,loading:r,getRoles:o,removeRole:n}=qe(),{deployment:s}=ve(),[a,h]=i.useState({isOpen:!1}),[f,c]=i.useState(null),[p,d]=i.useState(null),[u,g]=i.useState(""),[m,v]=i.useState(null),y=i.useRef(null),{data:S=[],isLoading:E,mutate:b}=Ne(t?`wacht-api-organizations:${t.id}:roles`:null,()=>(o==null?void 0:o())||[]),$=i.useMemo(()=>u?S.filter(x=>x.name.toLowerCase().includes(u.toLowerCase())):S,[S,u]),C=async x=>{try{x.id?(await new Promise(I=>setTimeout(I,1e3)),c({text:"Role updated successfully",type:"success"})):(await new Promise(I=>setTimeout(I,1e3)),c({text:"Role created successfully",type:"success"})),h({isOpen:!1}),b()}catch(I){const k=(I==null?void 0:I.message)||(x.id?"Failed to update role. Please try again.":"Failed to create role. Please try again.");x.id?c({text:k,type:"error"}):c({text:k,type:"error"})}finally{setTimeout(()=>c(null),3e3)}},w=async x=>{try{await n(x),b()}catch{}finally{setTimeout(()=>c(null),3e3)}};return r||E?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[f&&e.jsxs("div",{style:{marginBottom:"20px",padding:"8px",background:f.type==="success"?"var(--color-success-background)":"var(--color-error-background)",color:f.type==="success"?"var(--color-success)":"var(--color-error)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"},children:[f.type==="success"?"✓":e.jsx(dt,{size:16}),f.text]}),e.jsxs(bl,{children:[e.jsx(yt,{placeholder:"Search roles",onChange:g,value:u}),((j=s==null?void 0:s.b2b_settings)==null?void 0:j.custom_org_role_enabled)&&e.jsxs("div",{children:[e.jsx(X,{ref:y,onClick:()=>h({isOpen:!a.isOpen}),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Add role"}),a.isOpen&&!a.role&&e.jsx(Ns,{role:a.role,onClose:()=>h({isOpen:!1}),onSuccess:C,triggerRef:y})]})]}),$.length===0?e.jsx(et,{title:u?"No roles match your search":"No roles defined yet. Create your first role to get started.",description:"Create a role to get started"}):e.jsxs(wt,{children:[e.jsx(jt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Role"}),e.jsx(ze,{children:"Permissions"}),e.jsx(ze,{})]})}),e.jsx(kt,{children:$.map(x=>{var I;return e.jsxs(We,{children:[e.jsx(Le,{children:e.jsx("div",{style:{fontSize:"14px",fontWeight:500},children:x.name})}),e.jsx(Le,{style:{color:"var(--color-secondary-text)"},children:x.permissions.join(", ")}),e.jsx(_t,{children:e.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center",justifyContent:"flex-end",position:"relative"},children:[e.jsxs(nt,{open:p===x.id,openChange:k=>d(k?x.id:null),children:[e.jsx(st,{children:e.jsx(Sa,{disabled:!x.organization_id,"data-role-dropdown-trigger":x.id,children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>{d(null),h({isOpen:!0,role:x})},children:"Edit Role"}),e.jsx(Te,{$destructive:!0,onClick:()=>{d(null),v(x.id)},children:"Remove Role"})]})]}),m===x.id&&e.jsx(Hr,{title:"Are you sure you want to delete this role?",onConfirm:()=>w(x),onCancel:()=>v(null)}),a.isOpen&&((I=a.role)==null?void 0:I.id)===x.id&&e.jsx(Ns,{role:a.role,onClose:()=>{h({isOpen:!1}),d(null)},onSuccess:C})]})})]},x.id)})})]})]})},yl=()=>{const{loading:t,activeOrganization:r}=qe(),[o,n]=i.useState("general"),[s,a]=i.useState(null),[h,f]=i.useState("info"),c=i.useCallback((p,d="info")=>{a(p),f(d),setTimeout(()=>a(null),3e3)},[a]);return t?e.jsx(Fn,{style:{display:"flex",justifyContent:"center",alignItems:"center"},children:e.jsx(Ee,{})}):r?e.jsx(Bs,{children:e.jsx(gl.Provider,{value:{screen:null,setScreen:()=>{},toast:c},children:e.jsxs(Fn,{children:[e.jsx(Jm,{children:e.jsxs(ex,{children:[e.jsx(dr,{$isActive:o==="general",onClick:()=>n("general"),children:e.jsxs(ur,{children:[e.jsx(Kt,{size:16}),"General"]})}),e.jsx(dr,{$isActive:o==="domains",onClick:()=>n("domains"),children:e.jsxs(ur,{children:[e.jsx(Vp,{size:16}),"Domains"]})}),e.jsx(dr,{$isActive:o==="members",onClick:()=>n("members"),children:e.jsxs(ur,{children:[e.jsx(Bo,{size:16}),"Members"]})}),e.jsx(dr,{$isActive:o==="invitations",onClick:()=>n("invitations"),children:e.jsxs(ur,{children:[e.jsx(Wr,{size:16}),"Invitations"]})}),e.jsx(dr,{$isActive:o==="roles",onClick:()=>n("roles"),children:e.jsxs(ur,{children:[e.jsx(wr,{size:16}),"Roles"]})}),e.jsx(dr,{$isActive:o==="sso",onClick:()=>n("sso"),children:e.jsxs(ur,{children:[e.jsx(wr,{size:16}),"SSO"]})})]})}),e.jsxs(tx,{children:[o==="general"&&e.jsx(rx,{}),o==="domains"&&e.jsx(ox,{}),o==="members"&&e.jsx(ax,{}),o==="invitations"&&e.jsx(sx,{}),o==="roles"&&e.jsx(ix,{}),o==="sso"&&e.jsx(Qm,{})]}),s&&e.jsx("div",{style:{position:"absolute",bottom:"20px",right:"20px",maxWidth:"360px",background:"var(--color-input-background)",border:"1px solid var(--color-border)",borderRadius:"8px",padding:"12px 16px",boxShadow:"0 4px 12px var(--color-shadow)",animation:"slideUp 0.3s ease-out",wordBreak:"break-word"},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[h==="error"?e.jsx(dt,{size:16,color:"var(--color-error)"}):e.jsx(Ye,{size:16,color:"var(--color-success)"}),e.jsx("span",{style:{fontSize:"14px",color:"var(--color-foreground)"},children:s})]})})]})})}):e.jsx(Bs,{children:e.jsx(Fn,{children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",padding:"40px 24px",textAlign:"center"},children:[e.jsx("div",{style:{width:"80px",height:"80px",borderRadius:"50%",background:"var(--color-input-background)",display:"flex",alignItems:"center",justifyContent:"center",marginBottom:"24px",border:"2px dashed var(--color-border)"},children:e.jsx(Fr,{size:32,color:"var(--color-muted)"})}),e.jsx("h3",{style:{fontSize:"18px",fontWeight:600,color:"var(--color-foreground)",margin:"0 0 8px 0"},children:"No Organization Selected"}),e.jsx(zl,{})]})})})},cx=({isOpen:t,onClose:r,title:o,showHeader:n,headerContent:s,footerContent:a,customContent:h,children:f,showCloseButton:c})=>e.jsx(_e,{isOpen:t,onClose:r,children:e.jsx(_e.Overlay,{children:e.jsxs(_e.Content,{style:{width:"900px",maxWidth:"100%"},children:[n&&e.jsx(_e.Header,{showCloseButton:c,children:s||o}),h||f||e.jsx(yl,{}),a&&e.jsx(_e.Footer,{children:a})]})})}),lx=l.div`
2764
+ `,ax=()=>{const{activeOrganization:t,loading:r,getMembers:o,getRoles:n,addMemberRole:s,removeMemberRole:a,removeMember:h}=qe(),{session:f}=Be(),{toast:c}=Je(),[p,d]=i.useState(""),[u,g]=i.useState(!1),m=i.useRef(null),{data:v=[],isLoading:y,mutate:S}=Ne(t?`wacht-api-organizations:${t.id}:members`:null,()=>(o==null?void 0:o())||[]),{data:E=[],isLoading:b}=Ne(t?`wacht-api-organizations:${t.id}:roles`:null,()=>(n==null?void 0:n())||[]),$=E,C=i.useMemo(()=>p?v.filter(k=>{var T;const R=k.user;if(!R)return!1;const _=R.first_name||"",O=R.last_name||"",P=((T=R.primary_email_address)==null?void 0:T.email)||"";return`${_} ${O}`.trim().toLowerCase().includes(p.toLowerCase())||P.toLowerCase().includes(p.toLowerCase())}):v,[v,p]),w=async(k,R,_)=>{try{_?(await a(k,R),c("Role removed successfully","info")):(await s(k,R),c("Role added successfully","info")),S()}catch(O){const P=O.message||"Failed to update role. Please try again.";c(P,"error")}},j=(k="",R="")=>`${k[0]||""}${R[0]||""}`.toUpperCase(),x=(k,R)=>{var _;return((_=k.roles)==null?void 0:_.some(O=>O.id===R))||!1},I=()=>{g(!1),S(),c("Invitation sent successfully","info")};return r||y||b?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:"24px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:"16px"},children:[e.jsx("div",{style:{flex:1},children:e.jsx(wt,{value:p,onChange:d,placeholder:"Search members..."})}),e.jsx(X,{ref:m,onClick:()=>g(!u),style:{background:"var(--color-primary)",color:"white",border:"none",padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,whiteSpace:"nowrap",height:"36px",width:"auto"},children:"Invite Members"})]}),u&&e.jsx(xl,{onClose:()=>g(!1),onSuccess:I,roles:$,triggerRef:m}),C.length===0?e.jsx(et,{title:p?"No members match your search":"No members yet",description:"Invite members to your organization to get started."}):e.jsxs(jt,{children:[e.jsx(kt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Member"}),e.jsx(ze,{children:"Joined"}),e.jsx(ze,{children:"Roles"})]})}),e.jsx(_t,{children:C.map(k=>{var P,z;const R=k.roles||[],_=k.user,O=(_==null?void 0:_.id)===((P=f==null?void 0:f.active_signin)==null?void 0:P.user_id);return e.jsxs(We,{children:[e.jsx(vl,{children:e.jsxs("div",{children:[e.jsx(nx,{children:_!=null&&_.profile_picture_url?e.jsx("img",{src:_.profile_picture_url,alt:`${_.first_name||""} ${_.last_name||""}`,style:{width:"100%",height:"100%",objectFit:"cover"}}):j(_==null?void 0:_.first_name,_==null?void 0:_.last_name)||"?"}),e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("span",{style:{fontSize:"14px",fontWeight:500,color:"var(--color-foreground)"},children:(()=>{var M;if(!_)return"Unknown User";const T=`${_.first_name||""} ${_.last_name||""}`.trim();return T||((M=_.primary_email_address)==null?void 0:M.email)||"Unknown User"})()}),O&&e.jsx("span",{style:{fontSize:"12px",padding:"2px 8px",background:"var(--color-background-alt)",borderRadius:"4px",color:"var(--color-secondary-text)"},children:"You"})]}),e.jsx("div",{style:{fontSize:"13px",color:"var(--color-secondary-text)"},children:(z=_==null?void 0:_.primary_email_address)==null?void 0:z.email})]})]})}),e.jsx(Le,{children:new Date(k.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}),e.jsx(Ct,{children:e.jsx("div",{style:{position:"relative"},children:e.jsxs(nt,{children:[e.jsx(st,{children:e.jsxs(X,{style:{background:"var(--color-background)",border:"1px solid var(--color-border)",borderRadius:"6px",padding:"6px 12px",fontSize:"14px",color:"var(--color-foreground)",display:"flex",alignItems:"center",gap:"4px",minWidth:"120px",justifyContent:"space-between"},children:[e.jsx("span",{children:R.length>0?R[0].name:"No role"}),e.jsx(er,{size:14})]})}),e.jsxs(at,{children:[$.map(T=>{const M=x(k,T.id);return e.jsx(Te,{onClick:()=>w(k,T,M),children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[e.jsx("span",{children:T.name}),M&&e.jsx(Ye,{size:16,color:"var(--color-success)"})]})},T.id)}),e.jsx(on,{}),e.jsx(Te,{$destructive:!0,onClick:()=>h(k),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Vr,{size:16,color:"var(--color-error)"}),e.jsx("span",{children:"Remove Member"})]})})]})]})})})]},k.id)})})]})]})},sx=()=>{const{activeOrganization:t,loading:r,getInvitations:o,getRoles:n,discardInvitation:s,resendInvitation:a}=qe(),{toast:h}=Je(),[f,c]=i.useState(!1),[p,d]=i.useState(""),u=i.useRef(null),{data:g=[],isLoading:m,mutate:v}=Ne(t?`wacht-api-organizations:${t.id}:invitations`:null,()=>(o==null?void 0:o())||[]),{data:y=[],isLoading:S}=Ne(t?`wacht-api-organizations:${t.id}:roles`:null,()=>(n==null?void 0:n())||[]),E=y,b=i.useMemo(()=>p?g.filter(j=>j.email.toLowerCase().includes(p.toLowerCase())):g,[g,p]),$=()=>{h("Invitation sent successfully","info"),v(),c(!1)},C=async j=>{try{await s(j),v(),h("Invitation cancelled successfully","info")}catch(x){const I=x.message||"Failed to cancel invitation. Please try again.";h(I,"error")}},w=async j=>{try{await a(j),h("Invitation resent successfully","info")}catch(x){const I=x.message||"Failed to resend invitation. Please try again.";h(I,"error")}};return r||m||S?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:"24px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:"16px"},children:[e.jsx("div",{style:{flex:1},children:e.jsx(wt,{value:p,onChange:d,placeholder:"Search invitations..."})}),e.jsx(X,{ref:u,onClick:()=>c(!f),style:{background:"var(--color-primary)",color:"white",border:"none",padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,whiteSpace:"nowrap",height:"36px",width:"auto"},children:"Invite Members"})]}),f&&e.jsx(xl,{onClose:()=>c(!1),onSuccess:$,roles:E,triggerRef:u}),b.length===0?e.jsx(et,{title:p?"No invitations match your search":"No pending invitations",description:"Invite new members to your organization."}):e.jsxs(jt,{children:[e.jsx(kt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Email"}),e.jsx(ze,{children:"Role"}),e.jsx(ze,{children:"Invited"}),e.jsx(ze,{})]})}),e.jsx(_t,{children:b.map(j=>{var x;return e.jsxs(We,{children:[e.jsx(Le,{children:j.email}),e.jsx(Le,{children:((x=j.initial_organization_role)==null?void 0:x.name)||"No role"}),e.jsx(Le,{children:new Date(j.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}),e.jsx(Ct,{children:e.jsx("div",{style:{position:"relative"},children:e.jsxs(nt,{children:[e.jsx(st,{children:e.jsx(Sa,{children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>w(j),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Wr,{size:16,color:"var(--color-muted)"}),e.jsx("span",{children:"Resend Invitation"})]})}),e.jsx(Te,{$destructive:!0,onClick:()=>C(j),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Vr,{size:16,color:"var(--color-error)"}),e.jsx("span",{children:"Cancel Invitation"})]})})]})]})})})]},j.id)})})]})]})},ix=()=>{var j;const{activeOrganization:t,loading:r,getRoles:o,removeRole:n}=qe(),{deployment:s}=ve(),[a,h]=i.useState({isOpen:!1}),[f,c]=i.useState(null),[p,d]=i.useState(null),[u,g]=i.useState(""),[m,v]=i.useState(null),y=i.useRef(null),{data:S=[],isLoading:E,mutate:b}=Ne(t?`wacht-api-organizations:${t.id}:roles`:null,()=>(o==null?void 0:o())||[]),$=i.useMemo(()=>u?S.filter(x=>x.name.toLowerCase().includes(u.toLowerCase())):S,[S,u]),C=async x=>{try{x.id?(await new Promise(I=>setTimeout(I,1e3)),c({text:"Role updated successfully",type:"success"})):(await new Promise(I=>setTimeout(I,1e3)),c({text:"Role created successfully",type:"success"})),h({isOpen:!1}),b()}catch(I){const k=(I==null?void 0:I.message)||(x.id?"Failed to update role. Please try again.":"Failed to create role. Please try again.");x.id?c({text:k,type:"error"}):c({text:k,type:"error"})}finally{setTimeout(()=>c(null),3e3)}},w=async x=>{try{await n(x),b()}catch{}finally{setTimeout(()=>c(null),3e3)}};return r||E?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[f&&e.jsxs("div",{style:{marginBottom:"20px",padding:"8px",background:f.type==="success"?"var(--color-success-background)":"var(--color-error-background)",color:f.type==="success"?"var(--color-success)":"var(--color-error)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"},children:[f.type==="success"?"✓":e.jsx(dt,{size:16}),f.text]}),e.jsxs(bl,{children:[e.jsx(wt,{placeholder:"Search roles",onChange:g,value:u}),((j=s==null?void 0:s.b2b_settings)==null?void 0:j.custom_org_role_enabled)&&e.jsxs("div",{children:[e.jsx(X,{ref:y,onClick:()=>h({isOpen:!a.isOpen}),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Add role"}),a.isOpen&&!a.role&&e.jsx(Ns,{role:a.role,onClose:()=>h({isOpen:!1}),onSuccess:C,triggerRef:y})]})]}),$.length===0?e.jsx(et,{title:u?"No roles match your search":"No roles defined yet. Create your first role to get started.",description:"Create a role to get started"}):e.jsxs(jt,{children:[e.jsx(kt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Role"}),e.jsx(ze,{children:"Permissions"}),e.jsx(ze,{})]})}),e.jsx(_t,{children:$.map(x=>{var I;return e.jsxs(We,{children:[e.jsx(Le,{children:e.jsx("div",{style:{fontSize:"14px",fontWeight:500},children:x.name})}),e.jsx(Le,{style:{color:"var(--color-secondary-text)"},children:x.permissions.join(", ")}),e.jsx(Ct,{children:e.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center",justifyContent:"flex-end",position:"relative"},children:[e.jsxs(nt,{open:p===x.id,openChange:k=>d(k?x.id:null),children:[e.jsx(st,{children:e.jsx(Sa,{disabled:!x.organization_id,"data-role-dropdown-trigger":x.id,children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>{d(null),h({isOpen:!0,role:x})},children:"Edit Role"}),e.jsx(Te,{$destructive:!0,onClick:()=>{d(null),v(x.id)},children:"Remove Role"})]})]}),m===x.id&&e.jsx(Hr,{title:"Are you sure you want to delete this role?",onConfirm:()=>w(x),onCancel:()=>v(null)}),a.isOpen&&((I=a.role)==null?void 0:I.id)===x.id&&e.jsx(Ns,{role:a.role,onClose:()=>{h({isOpen:!1}),d(null)},onSuccess:C})]})})]},x.id)})})]})]})},yl=()=>{const{loading:t,activeOrganization:r}=qe(),[o,n]=i.useState("general"),[s,a]=i.useState(null),[h,f]=i.useState("info"),c=i.useCallback((p,d="info")=>{a(p),f(d),setTimeout(()=>a(null),3e3)},[a]);return t?e.jsx(Fn,{style:{display:"flex",justifyContent:"center",alignItems:"center"},children:e.jsx(Ee,{})}):r?e.jsx(Bs,{children:e.jsx(gl.Provider,{value:{screen:null,setScreen:()=>{},toast:c},children:e.jsxs(Fn,{children:[e.jsx(Jm,{children:e.jsxs(ex,{children:[e.jsx(dr,{$isActive:o==="general",onClick:()=>n("general"),children:e.jsxs(ur,{children:[e.jsx(Kt,{size:16}),"General"]})}),e.jsx(dr,{$isActive:o==="domains",onClick:()=>n("domains"),children:e.jsxs(ur,{children:[e.jsx(Vp,{size:16}),"Domains"]})}),e.jsx(dr,{$isActive:o==="members",onClick:()=>n("members"),children:e.jsxs(ur,{children:[e.jsx(Bo,{size:16}),"Members"]})}),e.jsx(dr,{$isActive:o==="invitations",onClick:()=>n("invitations"),children:e.jsxs(ur,{children:[e.jsx(Wr,{size:16}),"Invitations"]})}),e.jsx(dr,{$isActive:o==="roles",onClick:()=>n("roles"),children:e.jsxs(ur,{children:[e.jsx(wr,{size:16}),"Roles"]})}),e.jsx(dr,{$isActive:o==="sso",onClick:()=>n("sso"),children:e.jsxs(ur,{children:[e.jsx(wr,{size:16}),"SSO"]})})]})}),e.jsxs(tx,{children:[o==="general"&&e.jsx(rx,{}),o==="domains"&&e.jsx(ox,{}),o==="members"&&e.jsx(ax,{}),o==="invitations"&&e.jsx(sx,{}),o==="roles"&&e.jsx(ix,{}),o==="sso"&&e.jsx(Qm,{})]}),s&&e.jsx("div",{style:{position:"absolute",bottom:"20px",right:"20px",maxWidth:"360px",background:"var(--color-input-background)",border:"1px solid var(--color-border)",borderRadius:"8px",padding:"12px 16px",boxShadow:"0 4px 12px var(--color-shadow)",animation:"slideUp 0.3s ease-out",wordBreak:"break-word"},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[h==="error"?e.jsx(dt,{size:16,color:"var(--color-error)"}):e.jsx(Ye,{size:16,color:"var(--color-success)"}),e.jsx("span",{style:{fontSize:"14px",color:"var(--color-foreground)"},children:s})]})})]})})}):e.jsx(Bs,{children:e.jsx(Fn,{children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",padding:"40px 24px",textAlign:"center"},children:[e.jsx("div",{style:{width:"80px",height:"80px",borderRadius:"50%",background:"var(--color-input-background)",display:"flex",alignItems:"center",justifyContent:"center",marginBottom:"24px",border:"2px dashed var(--color-border)"},children:e.jsx(Fr,{size:32,color:"var(--color-muted)"})}),e.jsx("h3",{style:{fontSize:"18px",fontWeight:600,color:"var(--color-foreground)",margin:"0 0 8px 0"},children:"No Organization Selected"}),e.jsx(zl,{})]})})})},cx=({isOpen:t,onClose:r,title:o,showHeader:n,headerContent:s,footerContent:a,customContent:h,children:f,showCloseButton:c})=>e.jsx(_e,{isOpen:t,onClose:r,children:e.jsx(_e.Overlay,{children:e.jsxs(_e.Content,{style:{width:"900px",maxWidth:"100%"},children:[n&&e.jsx(_e.Header,{showCloseButton:c,children:s||o}),h||f||e.jsx(yl,{}),a&&e.jsx(_e.Footer,{children:a})]})})}),lx=l.div`
2765
2765
  display: flex;
2766
2766
  height: 100%;
2767
2767
  min-height: 400px;
@@ -3052,7 +3052,7 @@ cursor: pointer;
3052
3052
  align-items: center;
3053
3053
  justify-content: center;
3054
3054
  color: var(--color-primary);
3055
- `,$a=({organizationId:t,onSuccess:r,onCancel:o,onCreateOrganization:n})=>{var z;const[s,a]=i.useState(""),[h,f]=i.useState(""),[c,p]=i.useState(),[d,u]=i.useState(null),[g,m]=i.useState(!1),[v,y]=i.useState(!1),[S,E]=i.useState(t),b=i.useRef(null),$=i.useRef(null),{toast:C}=Je(),{createWorkspace:w}=bt(),{organizationMemberships:j}=vt(),x=(z=j==null?void 0:j.find(T=>T.organization.id===S))==null?void 0:z.organization,I=T=>{if(T.target.files&&T.target.files[0]){const M=T.target.files[0];if(M.size>2*1024*1024){C("File size cannot exceed 2MB","error");return}if(!M.type.startsWith("image/")){C("Please select a valid image file","error");return}d&&URL.revokeObjectURL(d),p(M),u(URL.createObjectURL(M))}},k=()=>{var T;(T=b.current)==null||T.click()},R=T=>T.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2)||"W",_=T=>T.trim().replace(/[<>\"'&]/g,""),O=T=>T.length>=2&&T.length<=100&&/^[a-zA-Z0-9\s_.-]+$/.test(T),P=async()=>{const T=_(s),M=_(h);if(!T||!S){C("Please enter a workspace name","error");return}if(!O(T)){C("Workspace name must be 2-100 characters and contain only letters, numbers, spaces, dots, underscores, and hyphens","error");return}if(M.length>500){C("Description must be less than 500 characters","error");return}m(!0);try{const F=await w(S,T,c,M);r==null||r(F)}catch(F){const G=F.message||"Failed to create workspace. Please try again.";C(G,"error")}finally{m(!1)}};return i.useEffect(()=>()=>{d&&URL.revokeObjectURL(d)},[d]),i.useEffect(()=>{const T=M=>{$.current&&!$.current.contains(M.target)&&y(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[]),e.jsx(ue,{children:e.jsxs(lx,{children:[e.jsxs(dx,{children:[e.jsxs(wl,{hasImage:!!d,onClick:k,children:[d?e.jsx(px,{src:d,alt:"Workspace logo"}):e.jsx(hx,{children:R(s||"W")}),e.jsx(Sx,{children:e.jsx($x,{children:"Upload Logo"})})]}),e.jsx(Cx,{type:"file",ref:b,onChange:I,accept:"image/png, image/jpeg, image/gif",disabled:g}),e.jsx(fx,{children:"Create new workspace"}),e.jsx(gx,{children:"Workspaces are used to organize your projects and team members into logical groups."})]}),e.jsxs(ux,{children:[e.jsxs(mx,{children:[e.jsx(xx,{children:"Choose your workspace name"}),e.jsx(vx,{children:"Enter a name for your new workspace. This will be visible to all members."})]}),e.jsxs(bx,{children:[e.jsxs(Nn,{children:[e.jsx(Bn,{children:"Organization"}),e.jsxs(zx,{ref:$,children:[e.jsxs(Ex,{type:"button",onClick:()=>y(!v),disabled:g,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Ws,{children:x!=null&&x.image_url?e.jsx(Vs,{src:x.image_url,alt:x.name}):R((x==null?void 0:x.name)||"O").charAt(0)}),e.jsx("span",{children:(x==null?void 0:x.name)||"Select organization"})]}),e.jsx(er,{size:16,style:{color:"var(--color-secondary-text)"}})]}),v&&e.jsxs(Px,{children:[j==null?void 0:j.map(T=>e.jsxs(jl,{onClick:()=>{E(T.organization.id),y(!1)},children:[e.jsx(Ws,{children:T.organization.image_url?e.jsx(Vs,{src:T.organization.image_url,alt:T.organization.name}):R(T.organization.name).charAt(0)}),e.jsx("span",{children:T.organization.name})]},T.organization.id)),e.jsxs(Rx,{onClick:()=>{y(!1),n==null||n()},children:[e.jsx(Ix,{children:e.jsx(Ke,{size:12})}),e.jsx("span",{children:"Create new organization"})]})]})]})]}),e.jsxs(Nn,{children:[e.jsx(Bn,{children:"Workspace name"}),e.jsx(yx,{type:"text",value:s,onChange:T=>a(T.target.value),placeholder:"Workspace Name",disabled:g})]}),e.jsxs(Nn,{children:[e.jsx(Bn,{children:"Description (optional)"}),e.jsx(wx,{value:h,onChange:T=>f(T.target.value),placeholder:"What is this workspace for?",disabled:g})]})]}),e.jsxs(jx,{children:[o?e.jsxs(kx,{onClick:o,disabled:g,children:[e.jsx(Ur,{size:16}),"Back"]}):e.jsx("div",{}),e.jsx(_x,{onClick:P,disabled:g||!s.trim(),children:g?"Creating...":"Create"})]})]})]})})},kl=({isOpen:t,onClose:r,onCreated:o,organizationId:n})=>{const[s,a]=i.useState(!1),[h,f]=i.useState(n),{refetch:c,organizationMemberships:p}=vt(),d=()=>{o==null||o(),r==null||r()},u=()=>{a(!0)},g=async()=>{await c(),setTimeout(()=>{if(p&&p.length>0){const m=p[p.length-1];f(m.organization.id)}a(!1)},500)};return e.jsx(ue,{children:e.jsx(_e,{isOpen:t,onClose:r,children:e.jsx(_e.Overlay,{children:e.jsx(_e.Content,{style:{width:"900px",maxWidth:"90vw"},children:e.jsx(_e.Body,{style:{padding:0},children:s?e.jsx(nn,{onSuccess:g,onCancel:()=>a(!1)}):e.jsx($a,{organizationId:h||n,onSuccess:d,onCancel:r,onCreateOrganization:u})})})})})})},Tx=l.div`
3055
+ `,$a=({organizationId:t,onSuccess:r,onCancel:o,onCreateOrganization:n})=>{var z;const[s,a]=i.useState(""),[h,f]=i.useState(""),[c,p]=i.useState(),[d,u]=i.useState(null),[g,m]=i.useState(!1),[v,y]=i.useState(!1),[S,E]=i.useState(t),b=i.useRef(null),$=i.useRef(null),{toast:C}=Je(),{createWorkspace:w}=yt(),{organizationMemberships:j}=bt(),x=(z=j==null?void 0:j.find(T=>T.organization.id===S))==null?void 0:z.organization,I=T=>{if(T.target.files&&T.target.files[0]){const M=T.target.files[0];if(M.size>2*1024*1024){C("File size cannot exceed 2MB","error");return}if(!M.type.startsWith("image/")){C("Please select a valid image file","error");return}d&&URL.revokeObjectURL(d),p(M),u(URL.createObjectURL(M))}},k=()=>{var T;(T=b.current)==null||T.click()},R=T=>T.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2)||"W",_=T=>T.trim().replace(/[<>\"'&]/g,""),O=T=>T.length>=2&&T.length<=100&&/^[a-zA-Z0-9\s_.-]+$/.test(T),P=async()=>{const T=_(s),M=_(h);if(!T||!S){C("Please enter a workspace name","error");return}if(!O(T)){C("Workspace name must be 2-100 characters and contain only letters, numbers, spaces, dots, underscores, and hyphens","error");return}if(M.length>500){C("Description must be less than 500 characters","error");return}m(!0);try{const F=await w(S,T,c,M);r==null||r(F)}catch(F){const G=F.message||"Failed to create workspace. Please try again.";C(G,"error")}finally{m(!1)}};return i.useEffect(()=>()=>{d&&URL.revokeObjectURL(d)},[d]),i.useEffect(()=>{const T=M=>{$.current&&!$.current.contains(M.target)&&y(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[]),e.jsx(ue,{children:e.jsxs(lx,{children:[e.jsxs(dx,{children:[e.jsxs(wl,{hasImage:!!d,onClick:k,children:[d?e.jsx(px,{src:d,alt:"Workspace logo"}):e.jsx(hx,{children:R(s||"W")}),e.jsx(Sx,{children:e.jsx($x,{children:"Upload Logo"})})]}),e.jsx(Cx,{type:"file",ref:b,onChange:I,accept:"image/png, image/jpeg, image/gif",disabled:g}),e.jsx(fx,{children:"Create new workspace"}),e.jsx(gx,{children:"Workspaces are used to organize your projects and team members into logical groups."})]}),e.jsxs(ux,{children:[e.jsxs(mx,{children:[e.jsx(xx,{children:"Choose your workspace name"}),e.jsx(vx,{children:"Enter a name for your new workspace. This will be visible to all members."})]}),e.jsxs(bx,{children:[e.jsxs(Nn,{children:[e.jsx(Bn,{children:"Organization"}),e.jsxs(zx,{ref:$,children:[e.jsxs(Ex,{type:"button",onClick:()=>y(!v),disabled:g,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Ws,{children:x!=null&&x.image_url?e.jsx(Vs,{src:x.image_url,alt:x.name}):R((x==null?void 0:x.name)||"O").charAt(0)}),e.jsx("span",{children:(x==null?void 0:x.name)||"Select organization"})]}),e.jsx(er,{size:16,style:{color:"var(--color-secondary-text)"}})]}),v&&e.jsxs(Px,{children:[j==null?void 0:j.map(T=>e.jsxs(jl,{onClick:()=>{E(T.organization.id),y(!1)},children:[e.jsx(Ws,{children:T.organization.image_url?e.jsx(Vs,{src:T.organization.image_url,alt:T.organization.name}):R(T.organization.name).charAt(0)}),e.jsx("span",{children:T.organization.name})]},T.organization.id)),e.jsxs(Rx,{onClick:()=>{y(!1),n==null||n()},children:[e.jsx(Ix,{children:e.jsx(Ke,{size:12})}),e.jsx("span",{children:"Create new organization"})]})]})]})]}),e.jsxs(Nn,{children:[e.jsx(Bn,{children:"Workspace name"}),e.jsx(yx,{type:"text",value:s,onChange:T=>a(T.target.value),placeholder:"Workspace Name",disabled:g})]}),e.jsxs(Nn,{children:[e.jsx(Bn,{children:"Description (optional)"}),e.jsx(wx,{value:h,onChange:T=>f(T.target.value),placeholder:"What is this workspace for?",disabled:g})]})]}),e.jsxs(jx,{children:[o?e.jsxs(kx,{onClick:o,disabled:g,children:[e.jsx(Ur,{size:16}),"Back"]}):e.jsx("div",{}),e.jsx(_x,{onClick:P,disabled:g||!s.trim(),children:g?"Creating...":"Create"})]})]})]})})},kl=({isOpen:t,onClose:r,onCreated:o,organizationId:n})=>{const[s,a]=i.useState(!1),[h,f]=i.useState(n),{refetch:c,organizationMemberships:p}=bt(),d=()=>{o==null||o(),r==null||r()},u=()=>{a(!0)},g=async()=>{await c(),setTimeout(()=>{if(p&&p.length>0){const m=p[p.length-1];f(m.organization.id)}a(!1)},500)};return e.jsx(ue,{children:e.jsx(_e,{isOpen:t,onClose:r,children:e.jsx(_e.Overlay,{children:e.jsx(_e.Content,{style:{width:"900px",maxWidth:"90vw"},children:e.jsx(_e.Body,{style:{padding:0},children:s?e.jsx(nn,{onSuccess:g,onCancel:()=>a(!1)}):e.jsx($a,{organizationId:h||n,onSuccess:d,onCancel:r,onCreateOrganization:u})})})})})})},Tx=l.div`
3056
3056
  position: fixed;
3057
3057
  width: 360px;
3058
3058
  max-width: calc(100vw - 48px);
@@ -3316,7 +3316,7 @@ cursor: pointer;
3316
3316
  opacity: 0.5;
3317
3317
  cursor: not-allowed;
3318
3318
  }
3319
- `,o0=()=>{const{activeWorkspace:t,loading:r,getRoles:o}=Rt(),{workspaces:n}=bt(),{client:s}=Fe(),a=n==null?void 0:n.find(O=>O.id===(t==null?void 0:t.id)),[h,f]=i.useState(!0),[c,p]=i.useState(!0),[d,u]=i.useState(""),[g,m]=i.useState(""),[v,y]=i.useState([]),[S,E]=i.useState([]),[b,$]=i.useState(!1),C=i.useRef(null),w=i.useCallback(async()=>{if(!t||!a)return[];try{return(await q(await s(`/organizations/${a.organization.id}/invitations`,{method:"GET"}))).data.filter(z=>z.workspace_id===t.id)}catch{return[]}},[s,t,a]),j=i.useCallback(async(O,P)=>{if(!t||!a)return;const T=(await q(await s(`/organizations/${a.organization.id}/roles`,{method:"GET"}))).data,M=T.find(G=>!G.organization_id)||T[0];return(await q(await s(`/organizations/${a.organization.id}/invitations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:O,role_id:M==null?void 0:M.id,workspace_id:t.id,workspace_role_id:P})}))).data},[s,t,a]),x=i.useCallback(async O=>!t||!a?void 0:(await q(await s(`/organizations/${a.organization.id}/invitations/${O}/remove`,{method:"POST"}))).data,[s,t,a]);i.useEffect(()=>{if(!t)return;(async()=>{f(!0),p(!0);try{const[P,z]=await Promise.all([o(),w()]);E(P),y(z)}catch{}finally{f(!1),p(!1)}})()},[t==null?void 0:t.id]);const I=async O=>{try{await x(O.id);const P=await w();y(P)}catch{}},k=async O=>{var P;try{await x(O.id),await j(O.email,O.workspace_role_id||((P=O.initial_workspace_role)==null?void 0:P.id)||O.role_id);const z=await w();y(z),m("Invitation resent successfully"),setTimeout(()=>m(""),3e3)}catch{}},R=async()=>{$(!1);const O=await w();y(O),m("Invitation sent successfully"),setTimeout(()=>m(""),3e3)},_=i.useMemo(()=>d?v.filter(O=>(O.email||"").toLowerCase().includes(d.toLowerCase())):v,[v,d]);return r||h||c?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[g&&e.jsxs("div",{style:{marginBottom:"16px",padding:"12px 16px",background:"var(--color-success-background)",color:"var(--color-success)",borderRadius:"6px",fontSize:"14px"},children:["✓ ",g]}),e.jsxs(za,{children:[e.jsx(yt,{value:d,onChange:u,placeholder:"Search Invitation"}),e.jsxs("div",{children:[e.jsx(X,{ref:C,onClick:()=>$(!b),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Invite Members"}),b&&e.jsx(Fx,{onClose:()=>$(!1),onSuccess:R,roles:S,createInvitation:j,triggerRef:C})]})]}),e.jsx("div",{children:_.length===0?e.jsx(et,{title:d?"No invitations match your search":"No pending invitations",description:"Invite new members to your workspace."}):e.jsx("div",{style:{borderTop:"1px solid var(--color-border)"},children:_.map(O=>{var P,z,T;return e.jsxs(Qx,{children:[e.jsx(Kx,{children:e.jsxs(Jx,{children:[e.jsx(e0,{children:O.email}),e.jsx(t0,{children:((P=O.initial_workspace_role)==null?void 0:P.name)||((z=O.initial_organization_role)==null?void 0:z.name)||((T=O.role)==null?void 0:T.name)})]})}),e.jsx(r0,{children:e.jsxs(nt,{children:[e.jsx(st,{children:e.jsx(_l,{children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>k(O),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Wr,{size:16,color:"var(--color-muted)"}),e.jsx("span",{children:"Resend Invitation"})]})}),e.jsx(Te,{$destructive:!0,onClick:()=>I(O),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(rn,{size:16,color:"var(--color-error)"}),e.jsx("span",{children:"Cancel Invitation"})]})})]})]})})]},O.id)})})})]})},n0=()=>{const{activeWorkspace:t,loading:r,getMembers:o,getRoles:n,removeMember:s,addMemberRole:a,removeMemberRole:h}=Rt(),{session:f}=Be(),{toast:c}=i.useContext(Sr)||{},[p,d]=i.useState(""),{data:u=[],isLoading:g,mutate:m}=Ne(t?`wacht-api-workspaces:${t.id}:members`:null,()=>o()||[]),{data:v=[],isLoading:y}=Ne(t?`wacht-api-workspaces:${t.id}:roles`:null,()=>n()||[]),S=v,E=i.useMemo(()=>p?u.filter(j=>{var O;const x=j.public_user_data;if(!x)return!1;const I=x.first_name||"",k=x.last_name||"",R=((O=x.primary_email_address)==null?void 0:O.email)||"";return`${I} ${k}`.trim().toLowerCase().includes(p.toLowerCase())||R.toLowerCase().includes(p.toLowerCase())}):u,[u,p]),b=async j=>{try{await s(j),c==null||c("Member removed successfully","info"),m()}catch{c==null||c("Failed to remove member","error")}},$=async(j,x,I)=>{try{I?(await h(j,x),c==null||c("Role removed successfully","info")):(await a(j,x),c==null||c("Role added successfully","info")),m()}catch{c==null||c("Failed to toggle role","error"),c==null||c("Failed to update role","error")}},C=(j="",x="")=>`${j[0]||""}${x[0]||""}`.toUpperCase(),w=(j,x)=>{var I;return((I=j.roles)==null?void 0:I.some(k=>k.id===x))||!1};return r||g||y?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsx(za,{children:e.jsx(yt,{value:p,onChange:d,placeholder:"Search members..."})}),E.length===0?e.jsx(et,{title:p?"No members match your search":"No members yet",description:"Invite members to your workspace to get started."}):e.jsxs(wt,{children:[e.jsx(jt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Member"}),e.jsx(ze,{children:"Joined"}),e.jsx(ze,{children:"Role"})]})}),e.jsx(kt,{children:E.map(j=>{var R,_;const x=j.public_user_data,I=j.roles||[],k=(x==null?void 0:x.id)===((R=f==null?void 0:f.active_signin)==null?void 0:R.user_id);return e.jsxs(We,{children:[e.jsx(vl,{children:e.jsxs("div",{children:[e.jsx(Xx,{children:x&&x.profile_picture_url?e.jsx("img",{src:x.profile_picture_url,alt:`${x.first_name||""} ${x.last_name||""}`,style:{width:"100%",height:"100%",objectFit:"cover"}}):C(x==null?void 0:x.first_name,x==null?void 0:x.last_name)||"?"}),e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("span",{style:{fontSize:"14px",fontWeight:500,color:"var(--color-foreground)"},children:(()=>{var P;if(!x)return"Unknown User";const O=`${x.first_name||""} ${x.last_name||""}`.trim();return O||((P=x.primary_email_address)==null?void 0:P.email)||"Unknown User"})()}),k&&e.jsx("span",{style:{fontSize:"12px",padding:"2px 8px",background:"var(--color-background-alt)",borderRadius:"4px",color:"var(--color-secondary-text)"},children:"You"})]}),e.jsx("div",{style:{fontSize:"13px",color:"var(--color-secondary-text)"},children:(_=x==null?void 0:x.primary_email_address)==null?void 0:_.email})]})]})}),e.jsx(Le,{children:new Date(j.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}),e.jsx(_t,{children:e.jsxs(nt,{children:[e.jsx(st,{children:e.jsxs(X,{style:{background:"var(--color-background)",border:"1px solid var(--color-border)",borderRadius:"6px",padding:"8px 12px",fontSize:"14px",color:"var(--color-foreground)",display:"flex",alignItems:"center",gap:"4px",minWidth:"120px",justifyContent:"space-between"},children:[e.jsx("span",{children:I.length>0?I[0].name:"No role"}),e.jsx(er,{size:14})]})}),e.jsxs(at,{children:[S.map(O=>{const P=w(j,O.id);return e.jsx(Te,{onClick:()=>$(j.id,O.id,P),children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[e.jsx("span",{children:O.name}),P&&e.jsx(Ye,{size:16,color:"var(--color-success)"})]})},O.id)}),e.jsx(on,{}),e.jsx(Te,{$destructive:!0,onClick:()=>b(j.id),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(rn,{size:16,color:"var(--color-error)"}),e.jsx("span",{children:"Remove Member"})]})})]})]})})]},j.id)})})]})]})},a0=()=>{var se,te;const{activeWorkspace:t,loading:r,updateWorkspace:o}=Rt(),{deleteWorkspace:n}=bt(),{deployment:s}=ve(),{toast:a}=i.useContext(Sr)||{},[h,f]=i.useState((t==null?void 0:t.name)||""),[c,p]=i.useState((t==null?void 0:t.description)||""),[d,u]=i.useState({mfa_required:!1,ip_restrictions:!1,allowed_ips:""}),[g,m]=i.useState(null),[v,y]=i.useState((t==null?void 0:t.image_url)||null),[S,E]=i.useState(!1),[b,$]=i.useState(!1),[C,w]=i.useState(""),[j,x]=i.useState(!1),[I,k]=i.useState(!1),R=i.useRef(null),_=i.useRef(null);if(i.useEffect(()=>{var U;t&&(f(t.name||""),p(t.description||""),y(t.image_url||null),u({mfa_required:t.enforce_2fa||!1,ip_restrictions:t.enable_ip_restriction||!1,allowed_ips:((U=t.whitelisted_ips)==null?void 0:U.join(`
3319
+ `,o0=()=>{const{activeWorkspace:t,loading:r,getRoles:o}=Rt(),{workspaces:n}=yt(),{client:s}=Fe(),a=n==null?void 0:n.find(O=>O.id===(t==null?void 0:t.id)),[h,f]=i.useState(!0),[c,p]=i.useState(!0),[d,u]=i.useState(""),[g,m]=i.useState(""),[v,y]=i.useState([]),[S,E]=i.useState([]),[b,$]=i.useState(!1),C=i.useRef(null),w=i.useCallback(async()=>{if(!t||!a)return[];try{return(await q(await s(`/organizations/${a.organization.id}/invitations`,{method:"GET"}))).data.filter(z=>z.workspace_id===t.id)}catch{return[]}},[s,t,a]),j=i.useCallback(async(O,P)=>{if(!t||!a)return;const T=(await q(await s(`/organizations/${a.organization.id}/roles`,{method:"GET"}))).data,M=T.find(G=>!G.organization_id)||T[0];return(await q(await s(`/organizations/${a.organization.id}/invitations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:O,role_id:M==null?void 0:M.id,workspace_id:t.id,workspace_role_id:P})}))).data},[s,t,a]),x=i.useCallback(async O=>!t||!a?void 0:(await q(await s(`/organizations/${a.organization.id}/invitations/${O}/remove`,{method:"POST"}))).data,[s,t,a]);i.useEffect(()=>{if(!t)return;(async()=>{f(!0),p(!0);try{const[P,z]=await Promise.all([o(),w()]);E(P),y(z)}catch{}finally{f(!1),p(!1)}})()},[t==null?void 0:t.id]);const I=async O=>{try{await x(O.id);const P=await w();y(P)}catch{}},k=async O=>{var P;try{await x(O.id),await j(O.email,O.workspace_role_id||((P=O.initial_workspace_role)==null?void 0:P.id)||O.role_id);const z=await w();y(z),m("Invitation resent successfully"),setTimeout(()=>m(""),3e3)}catch{}},R=async()=>{$(!1);const O=await w();y(O),m("Invitation sent successfully"),setTimeout(()=>m(""),3e3)},_=i.useMemo(()=>d?v.filter(O=>(O.email||"").toLowerCase().includes(d.toLowerCase())):v,[v,d]);return r||h||c?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[g&&e.jsxs("div",{style:{marginBottom:"16px",padding:"12px 16px",background:"var(--color-success-background)",color:"var(--color-success)",borderRadius:"6px",fontSize:"14px"},children:["✓ ",g]}),e.jsxs(za,{children:[e.jsx(wt,{value:d,onChange:u,placeholder:"Search Invitation"}),e.jsxs("div",{children:[e.jsx(X,{ref:C,onClick:()=>$(!b),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Invite Members"}),b&&e.jsx(Fx,{onClose:()=>$(!1),onSuccess:R,roles:S,createInvitation:j,triggerRef:C})]})]}),e.jsx("div",{children:_.length===0?e.jsx(et,{title:d?"No invitations match your search":"No pending invitations",description:"Invite new members to your workspace."}):e.jsx("div",{style:{borderTop:"1px solid var(--color-border)"},children:_.map(O=>{var P,z,T;return e.jsxs(Qx,{children:[e.jsx(Kx,{children:e.jsxs(Jx,{children:[e.jsx(e0,{children:O.email}),e.jsx(t0,{children:((P=O.initial_workspace_role)==null?void 0:P.name)||((z=O.initial_organization_role)==null?void 0:z.name)||((T=O.role)==null?void 0:T.name)})]})}),e.jsx(r0,{children:e.jsxs(nt,{children:[e.jsx(st,{children:e.jsx(_l,{children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>k(O),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Wr,{size:16,color:"var(--color-muted)"}),e.jsx("span",{children:"Resend Invitation"})]})}),e.jsx(Te,{$destructive:!0,onClick:()=>I(O),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(rn,{size:16,color:"var(--color-error)"}),e.jsx("span",{children:"Cancel Invitation"})]})})]})]})})]},O.id)})})})]})},n0=()=>{const{activeWorkspace:t,loading:r,getMembers:o,getRoles:n,removeMember:s,addMemberRole:a,removeMemberRole:h}=Rt(),{session:f}=Be(),{toast:c}=i.useContext(Sr)||{},[p,d]=i.useState(""),{data:u=[],isLoading:g,mutate:m}=Ne(t?`wacht-api-workspaces:${t.id}:members`:null,()=>o()||[]),{data:v=[],isLoading:y}=Ne(t?`wacht-api-workspaces:${t.id}:roles`:null,()=>n()||[]),S=v,E=i.useMemo(()=>p?u.filter(j=>{var O;const x=j.public_user_data;if(!x)return!1;const I=x.first_name||"",k=x.last_name||"",R=((O=x.primary_email_address)==null?void 0:O.email)||"";return`${I} ${k}`.trim().toLowerCase().includes(p.toLowerCase())||R.toLowerCase().includes(p.toLowerCase())}):u,[u,p]),b=async j=>{try{await s(j),c==null||c("Member removed successfully","info"),m()}catch{c==null||c("Failed to remove member","error")}},$=async(j,x,I)=>{try{I?(await h(j,x),c==null||c("Role removed successfully","info")):(await a(j,x),c==null||c("Role added successfully","info")),m()}catch{c==null||c("Failed to toggle role","error"),c==null||c("Failed to update role","error")}},C=(j="",x="")=>`${j[0]||""}${x[0]||""}`.toUpperCase(),w=(j,x)=>{var I;return((I=j.roles)==null?void 0:I.some(k=>k.id===x))||!1};return r||g||y?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsx(za,{children:e.jsx(wt,{value:p,onChange:d,placeholder:"Search members..."})}),E.length===0?e.jsx(et,{title:p?"No members match your search":"No members yet",description:"Invite members to your workspace to get started."}):e.jsxs(jt,{children:[e.jsx(kt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Member"}),e.jsx(ze,{children:"Joined"}),e.jsx(ze,{children:"Role"})]})}),e.jsx(_t,{children:E.map(j=>{var R,_;const x=j.public_user_data,I=j.roles||[],k=(x==null?void 0:x.id)===((R=f==null?void 0:f.active_signin)==null?void 0:R.user_id);return e.jsxs(We,{children:[e.jsx(vl,{children:e.jsxs("div",{children:[e.jsx(Xx,{children:x&&x.profile_picture_url?e.jsx("img",{src:x.profile_picture_url,alt:`${x.first_name||""} ${x.last_name||""}`,style:{width:"100%",height:"100%",objectFit:"cover"}}):C(x==null?void 0:x.first_name,x==null?void 0:x.last_name)||"?"}),e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("span",{style:{fontSize:"14px",fontWeight:500,color:"var(--color-foreground)"},children:(()=>{var P;if(!x)return"Unknown User";const O=`${x.first_name||""} ${x.last_name||""}`.trim();return O||((P=x.primary_email_address)==null?void 0:P.email)||"Unknown User"})()}),k&&e.jsx("span",{style:{fontSize:"12px",padding:"2px 8px",background:"var(--color-background-alt)",borderRadius:"4px",color:"var(--color-secondary-text)"},children:"You"})]}),e.jsx("div",{style:{fontSize:"13px",color:"var(--color-secondary-text)"},children:(_=x==null?void 0:x.primary_email_address)==null?void 0:_.email})]})]})}),e.jsx(Le,{children:new Date(j.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}),e.jsx(Ct,{children:e.jsxs(nt,{children:[e.jsx(st,{children:e.jsxs(X,{style:{background:"var(--color-background)",border:"1px solid var(--color-border)",borderRadius:"6px",padding:"8px 12px",fontSize:"14px",color:"var(--color-foreground)",display:"flex",alignItems:"center",gap:"4px",minWidth:"120px",justifyContent:"space-between"},children:[e.jsx("span",{children:I.length>0?I[0].name:"No role"}),e.jsx(er,{size:14})]})}),e.jsxs(at,{children:[S.map(O=>{const P=w(j,O.id);return e.jsx(Te,{onClick:()=>$(j.id,O.id,P),children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[e.jsx("span",{children:O.name}),P&&e.jsx(Ye,{size:16,color:"var(--color-success)"})]})},O.id)}),e.jsx(on,{}),e.jsx(Te,{$destructive:!0,onClick:()=>b(j.id),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(rn,{size:16,color:"var(--color-error)"}),e.jsx("span",{children:"Remove Member"})]})})]})]})})]},j.id)})})]})]})},a0=()=>{var se,te;const{activeWorkspace:t,loading:r,updateWorkspace:o}=Rt(),{deleteWorkspace:n}=yt(),{deployment:s}=ve(),{toast:a}=i.useContext(Sr)||{},[h,f]=i.useState((t==null?void 0:t.name)||""),[c,p]=i.useState((t==null?void 0:t.description)||""),[d,u]=i.useState({mfa_required:!1,ip_restrictions:!1,allowed_ips:""}),[g,m]=i.useState(null),[v,y]=i.useState((t==null?void 0:t.image_url)||null),[S,E]=i.useState(!1),[b,$]=i.useState(!1),[C,w]=i.useState(""),[j,x]=i.useState(!1),[I,k]=i.useState(!1),R=i.useRef(null),_=i.useRef(null);if(i.useEffect(()=>{var U;t&&(f(t.name||""),p(t.description||""),y(t.image_url||null),u({mfa_required:t.enforce_2fa||!1,ip_restrictions:t.enable_ip_restriction||!1,allowed_ips:((U=t.whitelisted_ips)==null?void 0:U.join(`
3320
3320
  `))||""}))},[t]),r||!t)return e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})});const O=U=>{var K;if((K=U.target.files)!=null&&K[0]){const ee=U.target.files[0];m(ee),y(URL.createObjectURL(ee)),setTimeout(()=>z(),100)}},P=()=>{R.current&&R.current.click()},z=i.useCallback(async()=>{if(!(!t||b))try{$(!0);const U={};g&&(U.image=g,m(null)),h!==t.name&&(U.name=h),c!==t.description&&(U.description=c),d.mfa_required!==t.enforce_2fa&&(U.enforce_2fa=d.mfa_required),d.ip_restrictions!==t.enable_ip_restriction&&(U.enable_ip_restriction=d.ip_restrictions);const K=(t.whitelisted_ips||[]).join(`
3321
3321
  `);d.allowed_ips!==K&&(U.whitelisted_ips=d.allowed_ips.split(`
3322
3322
  `).map(ee=>ee.trim()).filter(ee=>ee!=="")),Object.keys(U).length>0&&(await o(U),E(!0),setTimeout(()=>E(!1),3e3))}catch{a==null||a("Failed to auto-save workspace","error")}finally{$(!1)}},[t,o,h,c,g,d,b]),T=i.useCallback(()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{z()},1e3)},[z]),M=U=>{f(U.target.value),T()},F=U=>{p(U.target.value),T()},G=()=>{_.current&&clearTimeout(_.current),z()},L=()=>{_.current&&clearTimeout(_.current),z()},A=async()=>{if(!(!t||C!==t.name))try{x(!0),await n(t),a==null||a("Workspace deleted successfully","info")}catch(U){a==null||a(U.message||"Failed to delete workspace","error")}finally{x(!1),w(""),k(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-2xl)"},children:[e.jsxs("div",{style:{display:"flex",gap:"var(--space-2xl)",alignItems:"center"},children:[e.jsx("div",{style:{flexShrink:0},children:e.jsxs("div",{style:{width:"120px",height:"120px",borderRadius:"50%",border:"2px dashed var(--color-border)",background:v?"transparent":"var(--color-input-background)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",transition:"all 0.2s ease"},onClick:P,onMouseEnter:U=>{U.currentTarget.style.borderColor="var(--color-primary)",U.currentTarget.style.transform="scale(1.02)"},onMouseLeave:U=>{U.currentTarget.style.borderColor="var(--color-border)",U.currentTarget.style.transform="scale(1)"},children:[v?e.jsx("img",{src:v,alt:"Workspace Logo",style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:"50%"}}):e.jsx(Fr,{size:32,color:"var(--color-muted)"}),e.jsx("input",{type:"file",ref:R,style:{display:"none"},accept:"image/*",onChange:O})]})}),e.jsxs("div",{style:{flex:1},children:[e.jsxs("div",{style:{marginBottom:"var(--space-lg)"},children:[e.jsx("h3",{style:{fontSize:"var(--font-sm)",color:"var(--color-foreground)",margin:"0 0 var(--space-2xs) 0"},children:"Workspace Logo"}),e.jsx("p",{style:{fontSize:"var(--font-xs)",color:"var(--color-secondary-text)",margin:0},children:"Upload an image to represent your workspace"})]}),e.jsxs("div",{style:{display:"flex",gap:"var(--space-sm)",marginBottom:"var(--space-sm)"},children:[e.jsxs(X,{onClick:()=>{var U;return(U=R.current)==null?void 0:U.click()},style:{padding:"var(--space-xs) var(--space-md)",fontSize:"var(--font-xs)",height:"32px",width:"100px",display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx(Fr,{size:14}),v?"Change":"Upload"]}),e.jsxs(X,{onClick:()=>{y(null),m(null),R.current&&(R.current.value=""),setTimeout(()=>z(),100)},style:{background:"transparent",color:"var(--color-muted)",border:"1px solid var(--color-border)",padding:"var(--space-xs) var(--space-md)",fontSize:"var(--font-xs)",height:"32px",width:"100px",display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx(rn,{size:14}),"Remove"]})]})]})]}),e.jsx("div",{style:{position:"relative",height:"1px",background:"var(--color-divider)",margin:"0"}}),e.jsxs("div",{children:[e.jsxs("div",{style:{marginBottom:"var(--space-md)"},children:[e.jsx("h3",{style:{fontSize:"var(--font-sm)",color:"var(--color-foreground)",margin:"0 0 var(--space-2xs) 0"},children:"Workspace Details"}),e.jsx("p",{style:{fontSize:"var(--font-xs)",color:"var(--color-secondary-text)",margin:0},children:"Basic information about your workspace"})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-lg)"},children:[e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"name",children:"Workspace Name"}),e.jsx(pe,{id:"name",type:"text",value:h,onChange:M,onBlur:G,placeholder:"Enter workspace name",required:!0})]}),e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(pe,{id:"description",as:"textarea",value:c,onChange:F,onBlur:L,placeholder:"Tell us about your workspace",style:{minHeight:"80px",resize:"vertical",fontFamily:"inherit"}}),e.jsx("p",{style:{fontSize:"var(--font-2xs)",color:"var(--color-muted)",margin:"var(--space-2xs) 0 0 0"},children:"Brief description of your workspace and its purpose"})]}),((se=s==null?void 0:s.b2b_settings)==null?void 0:se.enforce_mfa_per_workspace_enabled)&&e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{children:[e.jsx(he,{style:{fontSize:"var(--font-xs)",color:"var(--color-foreground)",display:"block",marginBottom:"var(--space-2xs)"},children:"Multi-Factor Authentication"}),e.jsx("div",{style:{fontSize:"var(--font-2xs)",color:"var(--color-muted)"},id:"mfa-description",children:"Require all members to set up MFA for added security"})]}),e.jsx(jr,{checked:d.mfa_required,onChange:()=>{u(U=>({...U,mfa_required:!U.mfa_required})),setTimeout(()=>z(),100)}})]}),((te=s==null?void 0:s.b2b_settings)==null?void 0:te.ip_allowlist_per_workspace_enabled)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{children:[e.jsx(he,{style:{fontSize:"var(--font-xs)",color:"var(--color-foreground)",display:"block",marginBottom:"var(--space-2xs)"},children:"IP Restrictions"}),e.jsx("div",{style:{fontSize:"var(--font-2xs)",color:"var(--color-muted)"},id:"ip-restrictions-description",children:"Only allow access from specific IP addresses"})]}),e.jsx(jr,{checked:d.ip_restrictions,onChange:()=>{u(U=>({...U,ip_restrictions:!U.ip_restrictions})),setTimeout(()=>z(),100)},"aria-label":"Enable IP address restrictions","aria-describedby":"ip-restrictions-description"})]}),d.ip_restrictions&&e.jsxs(ge,{children:[e.jsx(he,{htmlFor:"allowed_ips",children:"Allowed IP Addresses"}),e.jsx(pe,{id:"allowed_ips",as:"textarea",value:d.allowed_ips,onChange:U=>u(K=>({...K,allowed_ips:U.target.value})),onBlur:z,placeholder:`192.168.1.1
@@ -3331,7 +3331,7 @@ cursor: pointer;
3331
3331
  transform: translateX(-50%) translateY(0);
3332
3332
  }
3333
3333
  }
3334
- `})]})},s0=()=>{var x;const{activeWorkspace:t,loading:r,getRoles:o,createRole:n,deleteRole:s}=Rt(),{toast:a}=i.useContext(Sr)||{},{deployment:h}=ve(),[f,c]=i.useState(""),[p,d]=i.useState({isOpen:!1}),[u,g]=i.useState(null),[m,v]=i.useState(null),y=i.useRef(null),S=i.useRef(new Map),{data:E=[],isLoading:b,mutate:$}=Ne(t?`wacht-api-workspaces:${t.id}:roles`:null,()=>o()||[]),C=i.useMemo(()=>f?E.filter(I=>I.name.toLowerCase().includes(f.toLowerCase())):E,[E,f]),w=async I=>{try{await n(I.name,I.permissions||[]),a==null||a("Role created successfully","info"),d({isOpen:!1}),$()}catch{a==null||a("Failed to save role","error"),a==null||a("Failed to create role","error")}},j=async I=>{try{await s(I),a==null||a("Role deleted successfully","info"),v(null),$()}catch{a==null||a("Failed to delete role","error"),a==null||a("Failed to delete role","error")}};return r||b?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs(za,{children:[e.jsx(yt,{placeholder:"Search roles",onChange:c,value:f}),e.jsxs("div",{style:{position:"relative"},children:[((x=h==null?void 0:h.b2b_settings)==null?void 0:x.custom_workspace_role_enabled)&&e.jsx(X,{ref:y,onClick:()=>d({isOpen:!0,triggerElement:y.current}),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Add role"}),p.isOpen&&!p.role&&e.jsx(Gs,{role:p.role,triggerRef:{current:p.triggerElement||null},onClose:()=>d({isOpen:!1}),onSuccess:w})]})]}),C.length===0?e.jsx(et,{title:f?"No roles match your search":"No roles available",description:f?"Try adjusting your search query":"Contact your administrator to set up workspace roles."}):e.jsx("div",{style:{position:"relative",overflowX:"auto",overflowY:"visible"},children:e.jsxs(wt,{children:[e.jsx(jt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Role"}),e.jsx(ze,{children:"Permissions"}),e.jsx(ze,{})]})}),e.jsx(kt,{children:C.map(I=>{var k;return e.jsxs(We,{children:[e.jsx(Le,{children:e.jsx("div",{style:{fontSize:"14px",fontWeight:500},children:I.name})}),e.jsx(Le,{style:{color:"var(--color-secondary-text)"},children:I.permissions&&I.permissions.length>0?I.permissions.join(", "):""}),e.jsx(_t,{children:e.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center",justifyContent:"flex-end",position:"relative"},children:[e.jsxs(nt,{open:u===I.id,openChange:R=>g(R?I.id:null),children:[e.jsx(st,{children:e.jsx(_l,{ref:R=>{R&&S.current.set(I.id,R)},disabled:!I.workspace_id,"data-role-dropdown-trigger":I.id,children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>{g(null);const R=S.current.get(I.id);d({isOpen:!0,role:I,triggerElement:R||null})},children:"Edit Role"}),e.jsx(Te,{$destructive:!0,onClick:()=>{g(null),v(I.id)},children:"Remove Role"})]})]}),m===I.id&&e.jsx(Hr,{title:"Are you sure you want to delete this role?",onConfirm:()=>j(I),onCancel:()=>v(null)}),p.isOpen&&((k=p.role)==null?void 0:k.id)===I.id&&e.jsx(Gs,{role:p.role,triggerRef:{current:p.triggerElement||null},onClose:()=>{d({isOpen:!1}),g(null)},onSuccess:w})]})})]},I.id)})})]})})]})},Cl=()=>{const{activeWorkspace:t,loading:r}=Rt(),[o,n]=i.useState("general"),[s,a]=i.useState(null),[h,f]=i.useState("info"),c=i.useCallback((p,d="info")=>{a(p),f(d),setTimeout(()=>a(null),3e3)},[]);return r?e.jsx(Hs,{style:{display:"flex",justifyContent:"center",alignItems:"center"},children:e.jsx(Ee,{})}):t?e.jsx(Sr.Provider,{value:{screen:null,setScreen:()=>{},toast:c},children:e.jsx(Hx,{children:e.jsxs(Hs,{children:[e.jsx(qx,{children:e.jsxs(Yx,{children:[e.jsx(go,{$isActive:o==="general",onClick:()=>n("general"),children:e.jsxs(mo,{children:[e.jsx(Kt,{size:16}),"General"]})}),e.jsx(go,{$isActive:o==="members",onClick:()=>n("members"),children:e.jsxs(mo,{children:[e.jsx(Bo,{size:16}),"Members"]})}),e.jsx(go,{$isActive:o==="invitations",onClick:()=>n("invitations"),children:e.jsxs(mo,{children:[e.jsx(Wc,{size:16}),"Invitations"]})}),e.jsx(go,{$isActive:o==="roles",onClick:()=>n("roles"),children:e.jsxs(mo,{children:[e.jsx(wr,{size:16}),"Roles"]})})]})}),e.jsxs(Zx,{children:[o==="general"&&e.jsx(a0,{}),o==="members"&&e.jsx(n0,{}),o==="invitations"&&e.jsx(o0,{}),o==="roles"&&e.jsx(s0,{})]}),s&&e.jsx("div",{style:{position:"absolute",bottom:"20px",right:"20px",background:"var(--color-input-background)",border:"1px solid var(--color-border)",padding:"12px 16px",borderRadius:"8px",boxShadow:"0 4px 12px var(--color-shadow)",zIndex:50,animation:"slideUp 0.3s ease-out"},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[h==="error"?e.jsx(dt,{size:16,color:"var(--color-error)"}):e.jsx(Ye,{size:16,color:"var(--color-success)"}),e.jsx("span",{style:{fontSize:"14px",color:"var(--color-foreground)"},children:s})]})})]})})}):null},Sl=({isOpen:t,onClose:r,title:o,showHeader:n,headerContent:s,footerContent:a,customContent:h,children:f,showCloseButton:c})=>e.jsx(_e,{isOpen:t,onClose:r,children:e.jsx(_e.Overlay,{children:e.jsxs(_e.Content,{style:{width:"900px",maxWidth:"100%"},children:[n&&e.jsx(_e.Header,{showCloseButton:c,children:s||o}),h||f||e.jsx(Cl,{}),a&&e.jsx(_e.Footer,{children:a})]})})}),$l=({triggerRef:t,isOpen:r,minWidth:o=300,defaultMaxHeight:n=400,offset:s=8})=>{const[a,h]=i.useState();return i.useEffect(()=>{if(!r||!t.current){h(void 0);return}const f=()=>{if(!t.current)return;const c=t.current.getBoundingClientRect(),p=window.innerWidth,d=window.innerHeight,u=p-c.left,g=c.right,m=d-c.bottom,v=c.top;let y={};u>=o?y.left=c.left:g>=o?y.left=c.right-o:y.left=Math.max(s,Math.min(p-o-s,c.left)),m>=150?(y.top=c.bottom+s,y.maxHeight=Math.min(n,m-s*2)):v>=150?(y.bottom=d-c.top+s,y.maxHeight=Math.min(n,v-s*2)):(y.top=c.bottom+s,y.maxHeight=Math.max(100,m-s*2)),h(y)};return f(),window.addEventListener("resize",f),window.addEventListener("scroll",f,!0),()=>{window.removeEventListener("resize",f),window.removeEventListener("scroll",f,!0)}},[r,o,n,s]),a},qs=l.div`
3334
+ `})]})},s0=()=>{var x;const{activeWorkspace:t,loading:r,getRoles:o,createRole:n,deleteRole:s}=Rt(),{toast:a}=i.useContext(Sr)||{},{deployment:h}=ve(),[f,c]=i.useState(""),[p,d]=i.useState({isOpen:!1}),[u,g]=i.useState(null),[m,v]=i.useState(null),y=i.useRef(null),S=i.useRef(new Map),{data:E=[],isLoading:b,mutate:$}=Ne(t?`wacht-api-workspaces:${t.id}:roles`:null,()=>o()||[]),C=i.useMemo(()=>f?E.filter(I=>I.name.toLowerCase().includes(f.toLowerCase())):E,[E,f]),w=async I=>{try{await n(I.name,I.permissions||[]),a==null||a("Role created successfully","info"),d({isOpen:!1}),$()}catch{a==null||a("Failed to save role","error"),a==null||a("Failed to create role","error")}},j=async I=>{try{await s(I),a==null||a("Role deleted successfully","info"),v(null),$()}catch{a==null||a("Failed to delete role","error"),a==null||a("Failed to delete role","error")}};return r||b?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"40px 0"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs(za,{children:[e.jsx(wt,{placeholder:"Search roles",onChange:c,value:f}),e.jsxs("div",{style:{position:"relative"},children:[((x=h==null?void 0:h.b2b_settings)==null?void 0:x.custom_workspace_role_enabled)&&e.jsx(X,{ref:y,onClick:()=>d({isOpen:!0,triggerElement:y.current}),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Add role"}),p.isOpen&&!p.role&&e.jsx(Gs,{role:p.role,triggerRef:{current:p.triggerElement||null},onClose:()=>d({isOpen:!1}),onSuccess:w})]})]}),C.length===0?e.jsx(et,{title:f?"No roles match your search":"No roles available",description:f?"Try adjusting your search query":"Contact your administrator to set up workspace roles."}):e.jsx("div",{style:{position:"relative",overflowX:"auto",overflowY:"visible"},children:e.jsxs(jt,{children:[e.jsx(kt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Role"}),e.jsx(ze,{children:"Permissions"}),e.jsx(ze,{})]})}),e.jsx(_t,{children:C.map(I=>{var k;return e.jsxs(We,{children:[e.jsx(Le,{children:e.jsx("div",{style:{fontSize:"14px",fontWeight:500},children:I.name})}),e.jsx(Le,{style:{color:"var(--color-secondary-text)"},children:I.permissions&&I.permissions.length>0?I.permissions.join(", "):""}),e.jsx(Ct,{children:e.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center",justifyContent:"flex-end",position:"relative"},children:[e.jsxs(nt,{open:u===I.id,openChange:R=>g(R?I.id:null),children:[e.jsx(st,{children:e.jsx(_l,{ref:R=>{R&&S.current.set(I.id,R)},disabled:!I.workspace_id,"data-role-dropdown-trigger":I.id,children:"•••"})}),e.jsxs(at,{children:[e.jsx(Te,{onClick:()=>{g(null);const R=S.current.get(I.id);d({isOpen:!0,role:I,triggerElement:R||null})},children:"Edit Role"}),e.jsx(Te,{$destructive:!0,onClick:()=>{g(null),v(I.id)},children:"Remove Role"})]})]}),m===I.id&&e.jsx(Hr,{title:"Are you sure you want to delete this role?",onConfirm:()=>j(I),onCancel:()=>v(null)}),p.isOpen&&((k=p.role)==null?void 0:k.id)===I.id&&e.jsx(Gs,{role:p.role,triggerRef:{current:p.triggerElement||null},onClose:()=>{d({isOpen:!1}),g(null)},onSuccess:w})]})})]},I.id)})})]})})]})},Cl=()=>{const{activeWorkspace:t,loading:r}=Rt(),[o,n]=i.useState("general"),[s,a]=i.useState(null),[h,f]=i.useState("info"),c=i.useCallback((p,d="info")=>{a(p),f(d),setTimeout(()=>a(null),3e3)},[]);return r?e.jsx(Hs,{style:{display:"flex",justifyContent:"center",alignItems:"center"},children:e.jsx(Ee,{})}):t?e.jsx(Sr.Provider,{value:{screen:null,setScreen:()=>{},toast:c},children:e.jsx(Hx,{children:e.jsxs(Hs,{children:[e.jsx(qx,{children:e.jsxs(Yx,{children:[e.jsx(go,{$isActive:o==="general",onClick:()=>n("general"),children:e.jsxs(mo,{children:[e.jsx(Kt,{size:16}),"General"]})}),e.jsx(go,{$isActive:o==="members",onClick:()=>n("members"),children:e.jsxs(mo,{children:[e.jsx(Bo,{size:16}),"Members"]})}),e.jsx(go,{$isActive:o==="invitations",onClick:()=>n("invitations"),children:e.jsxs(mo,{children:[e.jsx(Wc,{size:16}),"Invitations"]})}),e.jsx(go,{$isActive:o==="roles",onClick:()=>n("roles"),children:e.jsxs(mo,{children:[e.jsx(wr,{size:16}),"Roles"]})})]})}),e.jsxs(Zx,{children:[o==="general"&&e.jsx(a0,{}),o==="members"&&e.jsx(n0,{}),o==="invitations"&&e.jsx(o0,{}),o==="roles"&&e.jsx(s0,{})]}),s&&e.jsx("div",{style:{position:"absolute",bottom:"20px",right:"20px",background:"var(--color-input-background)",border:"1px solid var(--color-border)",padding:"12px 16px",borderRadius:"8px",boxShadow:"0 4px 12px var(--color-shadow)",zIndex:50,animation:"slideUp 0.3s ease-out"},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[h==="error"?e.jsx(dt,{size:16,color:"var(--color-error)"}):e.jsx(Ye,{size:16,color:"var(--color-success)"}),e.jsx("span",{style:{fontSize:"14px",color:"var(--color-foreground)"},children:s})]})})]})})}):null},Sl=({isOpen:t,onClose:r,title:o,showHeader:n,headerContent:s,footerContent:a,customContent:h,children:f,showCloseButton:c})=>e.jsx(_e,{isOpen:t,onClose:r,children:e.jsx(_e.Overlay,{children:e.jsxs(_e.Content,{style:{width:"900px",maxWidth:"100%"},children:[n&&e.jsx(_e.Header,{showCloseButton:c,children:s||o}),h||f||e.jsx(Cl,{}),a&&e.jsx(_e.Footer,{children:a})]})})}),$l=({triggerRef:t,isOpen:r,minWidth:o=300,defaultMaxHeight:n=400,offset:s=8})=>{const[a,h]=i.useState();return i.useEffect(()=>{if(!r||!t.current){h(void 0);return}const f=()=>{if(!t.current)return;const c=t.current.getBoundingClientRect(),p=window.innerWidth,d=window.innerHeight,u=p-c.left,g=c.right,m=d-c.bottom,v=c.top;let y={};u>=o?y.left=c.left:g>=o?y.left=c.right-o:y.left=Math.max(s,Math.min(p-o-s,c.left)),m>=150?(y.top=c.bottom+s,y.maxHeight=Math.min(n,m-s*2)):v>=150?(y.bottom=d-c.top+s,y.maxHeight=Math.min(n,v-s*2)):(y.top=c.bottom+s,y.maxHeight=Math.max(100,m-s*2)),h(y)};return f(),window.addEventListener("resize",f),window.addEventListener("scroll",f,!0),()=>{window.removeEventListener("resize",f),window.removeEventListener("scroll",f,!0)}},[r,o,n,s]),a},qs=l.div`
3335
3335
  position: relative;
3336
3336
  display: inline-block;
3337
3337
  width: 100%;
@@ -3682,7 +3682,7 @@ cursor: pointer;
3682
3682
  height: 16px;
3683
3683
  background: var(--color-border);
3684
3684
  border-radius: 2px;
3685
- `,zl=({showPersonal:t=!0})=>{var de,Q,ce;const[r,o]=i.useState(!1),[n,s]=i.useState(!1),[a,h]=i.useState(new Set),f=i.useRef(null),c=i.useRef(null),p=$l({triggerRef:f,isOpen:r,minWidth:300}),d=Mr(!1),u=Mr(!1),g=Mr(!1),m=Mr(!1),[v,y]=i.useState(null),[S,E]=i.useState(!1),[b,$]=i.useState(null),{organizationMemberships:C,loading:w,refetch:j}=vt(),{activeOrganization:x,leave:I}=qe(),{activeWorkspace:k,leave:R}=Rt(),{workspaces:_,loading:O}=bt(),{session:P,loading:z,switchOrganization:T,switchWorkspace:M}=Be(),{deployment:F}=ve(),{toast:G}=Je(),L=F==null?void 0:F.b2b_settings.organizations_enabled,A=F==null?void 0:F.b2b_settings.workspaces_enabled,se=F==null?void 0:F.b2b_settings.allow_users_to_create_orgs,te=!((de=P==null?void 0:P.active_signin)!=null&&de.active_organization_membership_id),U=i.useMemo(()=>{var V,D;if(te)return{name:"Personal account",image_url:(D=(V=P==null?void 0:P.active_signin)==null?void 0:V.user)==null?void 0:D.profile_picture_url,isPersonal:!0};let B=(x==null?void 0:x.name)||"";return A&&k&&(B=`${x==null?void 0:x.name} / ${k.name}`),{name:B,image_url:x==null?void 0:x.image_url,isPersonal:!1}},[te,x,k,P,A]);i.useEffect(()=>{if(!r)return;let B=null;const V=setTimeout(()=>{const D=le=>{var ae,ke;const H=le.target;(ae=f.current)!=null&&ae.contains(H)||(ke=c.current)!=null&&ke.contains(H)||(o(!1),$(null))};document.addEventListener("mousedown",D),B=()=>{document.removeEventListener("mousedown",D)}},50);return()=>{clearTimeout(V),B==null||B()}},[r]),i.useEffect(()=>{if(b){const B=setTimeout(()=>{$(null)},5e3);return()=>clearTimeout(B)}},[b]);const K=()=>{j()};if(!L)return null;const ee=B=>{s(!0),T(B).finally(()=>{s(!1)})},J=B=>{s(!0),M(B).finally(()=>{s(!1)})},ie=B=>{const V=new Set(a);V.has(B)?V.delete(B):V.add(B),h(V)},oe=B=>B.split(" ").map(V=>V[0]).join("").toUpperCase().slice(0,2);return w||z?e.jsx(ue,{children:e.jsx(qs,{children:e.jsxs(m0,{children:[e.jsxs(Ys,{children:[e.jsx(x0,{}),e.jsx(v0,{})]}),e.jsx(b0,{})]})})}):e.jsx(ue,{children:e.jsxs(qs,{children:[e.jsxs(i0,{ref:f,onClick:()=>{o(!r),r||$(null)},disabled:n,children:[e.jsxs(Ys,{children:[e.jsx(c0,{children:U.image_url?e.jsx(l0,{src:U.image_url,alt:U.name}):U.isPersonal?e.jsx(No,{size:12}):oe(U.name)}),e.jsx(d0,{children:U.name})]}),e.jsx(Mp,{size:16})]}),typeof window<"u"&&Nr.createPortal(e.jsx(ue,{children:e.jsx(u0,{ref:c,$isOpen:r,$position:p,children:w||O?e.jsxs(g0,{children:[e.jsxs(wo,{children:[e.jsx(jo,{}),e.jsxs(ko,{children:[e.jsx(_o,{width:"120px"}),e.jsx(ei,{width:"80px"})]})]}),e.jsx(pr,{}),e.jsxs(wo,{children:[e.jsx(jo,{}),e.jsx(ko,{children:e.jsx(_o,{width:"100px"})})]}),e.jsx(pr,{}),e.jsxs(wo,{children:[e.jsx(jo,{}),e.jsxs(ko,{children:[e.jsx(_o,{width:"140px"}),e.jsx(ei,{width:"60px"})]})]}),e.jsx(pr,{}),e.jsxs(wo,{children:[e.jsx(jo,{}),e.jsx(ko,{children:e.jsx(_o,{width:"110px"})})]})]}):e.jsxs("div",{children:[t&&e.jsxs(e.Fragment,{children:[e.jsxs(Oo,{as:"button",$isActive:te,onClick:B=>{B.stopPropagation(),te||ee()},disabled:n||te,children:[te&&e.jsx(bo,{}),e.jsxs(pt,{children:[e.jsx(p0,{children:(ce=(Q=P==null?void 0:P.active_signin)==null?void 0:Q.user)!=null&&ce.profile_picture_url?e.jsx(h0,{src:P.active_signin.user.profile_picture_url,alt:"Personal account"}):e.jsx(No,{size:12})}),e.jsx(ht,{children:e.jsx(ft,{children:"Personal account"})})]}),!te&&e.jsx(xo,{className:"hover-arrow",size:14})]}),!te&&x&&e.jsx(pr,{})]}),!te&&x&&e.jsxs(Oo,{$isActive:!0,onClick:()=>{A&&ie(x.id)},style:n?{pointerEvents:"none",opacity:.7}:void 0,children:[e.jsx(bo,{}),e.jsxs(pt,{children:[A&&e.jsx(er,{size:12,style:{marginRight:"4px",transform:a.has(x.id)?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.2s ease",color:"var(--color-secondary-text)"}}),e.jsx(Zs,{children:x.image_url?e.jsx(Qs,{src:x.image_url,alt:x.name}):oe(x.name)}),e.jsx(ht,{children:e.jsx(ft,{children:x.name})})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Mo,{onClick:B=>{B.stopPropagation(),u.open()},title:"Manage organization",children:e.jsx(Kt,{size:12})}),e.jsx(Un,{onClick:async B=>{B.stopPropagation(),E(!0),$(null);try{await I(),await j(),setTimeout(()=>{E(!1)},500)}catch(V){$(V instanceof Error?V.message:"Failed to leave organization"),E(!1)}},disabled:S,title:"Leave organization",children:e.jsx(zt,{size:12})})]})]}),x&&A&&a.has(x.id)&&e.jsxs(e.Fragment,{children:[_==null?void 0:_.filter(B=>B.organization.id===x.id).map(B=>{const V=(k==null?void 0:k.id)===B.id;return e.jsxs(yo,{as:V?void 0:"button",$isActive:V,onClick:V?void 0:()=>J(B.id),...V?{style:n?{pointerEvents:"none",opacity:.7}:void 0}:{disabled:n},children:[V&&e.jsx(bo,{}),e.jsxs(pt,{children:[e.jsx(Xs,{children:B.image_url?e.jsx("img",{src:B.image_url,alt:B.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):oe(B.name).charAt(0)}),e.jsx(ht,{children:e.jsx(ft,{children:B.name})})]}),V?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Mo,{onClick:D=>{D.stopPropagation(),m.open()},title:"Manage workspace",children:e.jsx(Kt,{size:12})}),e.jsx(Un,{onClick:async D=>{D.stopPropagation();try{R&&await R()}catch(le){const H=le.message||"Failed to leave workspace. Please try again.";G(H,"error")}},title:"Leave workspace",children:e.jsx(zt,{size:12})})]}):e.jsx(xo,{className:"hover-arrow",size:14})]},B.id)}),e.jsx(yo,{as:"button",onClick:()=>{y(x.id),g.open()},disabled:n,children:e.jsxs(pt,{children:[e.jsx(vo,{style:{width:"14px",height:"14px"},children:e.jsx(Ke,{size:12})}),e.jsx(ht,{children:e.jsx(ft,{children:"Create workspace"})})]})})]}),(S||b)&&e.jsxs(e.Fragment,{children:[S&&e.jsxs(Js,{children:[e.jsx(f0,{}),"Leaving organization..."]}),b&&e.jsxs(Js,{$isError:!0,children:[e.jsx("span",{children:"⚠️"}),b]})]}),e.jsx(pr,{}),C&&C.length>0&&e.jsx(e.Fragment,{children:C.filter(B=>B.organization.id!==(x==null?void 0:x.id)).map(B=>{const V=B.organization,D=(_==null?void 0:_.filter(H=>H.organization.id===V.id))||[],le=a.has(V.id);return e.jsxs(i.Fragment,{children:[e.jsxs(Oo,{as:"button",$isActive:!1,onClick:()=>{A?ie(V.id):ee(V.id)},disabled:n,children:[e.jsxs(pt,{children:[A&&e.jsx(er,{size:12,style:{marginRight:"4px",transform:le?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.2s ease",color:"var(--color-secondary-text)"}}),e.jsx(Zs,{children:V.image_url?e.jsx(Qs,{src:V.image_url,alt:V.name}):oe(V.name)}),e.jsx(ht,{children:e.jsx(ft,{children:V.name})})]}),e.jsx(xo,{className:"hover-arrow",size:14})]}),A&&le&&e.jsxs(e.Fragment,{children:[D.map(H=>{const ae=(k==null?void 0:k.id)===H.id;return e.jsxs(yo,{as:ae?void 0:"button",$isActive:ae,onClick:ae?void 0:()=>J(H.id),...ae?{style:n?{pointerEvents:"none",opacity:.7}:void 0}:{disabled:n},children:[ae&&e.jsx(bo,{}),e.jsxs(pt,{children:[e.jsx(Xs,{children:H.image_url?e.jsx("img",{src:H.image_url,alt:H.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):oe(H.name).charAt(0)}),e.jsx(ht,{children:e.jsx(ft,{children:H.name})})]}),ae?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Mo,{onClick:ke=>{ke.stopPropagation(),m.open()},title:"Manage workspace",children:e.jsx(Kt,{size:12})}),e.jsx(Un,{onClick:async ke=>{ke.stopPropagation();try{R&&await R()}catch(ne){const Y=ne.message||"Failed to leave workspace. Please try again.";G(Y,"error")}},title:"Leave workspace",children:e.jsx(zt,{size:12})})]}):e.jsx(xo,{className:"hover-arrow",size:16})]},H.id)}),e.jsx(yo,{as:"button",onClick:()=>{y(V.id),g.open()},disabled:n,children:e.jsxs(pt,{children:[e.jsx(vo,{style:{width:"14px",height:"14px"},children:e.jsx(Ke,{size:10})}),e.jsx(ht,{children:e.jsx(ft,{children:"Create workspace"})})]})})]}),e.jsx(pr,{})]},V.id)})}),A?x&&e.jsx(Ks,{onClick:()=>{y(x.id),g.open()},disabled:n,children:e.jsxs(pt,{children:[e.jsx(vo,{children:e.jsx(Ke,{size:12})}),e.jsx(ht,{children:e.jsx(ft,{children:"Create workspace"})})]})}):se&&e.jsx(Ks,{onClick:()=>{d.open()},disabled:n,children:e.jsxs(pt,{children:[e.jsx(vo,{children:e.jsx(Ke,{size:12})}),e.jsx(ht,{children:e.jsx(ft,{children:"Create organization"})})]})})]})})}),document.body),L&&se&&e.jsx(xm,{isOpen:d.isOpen,onClose:d.close,onCreated:K}),e.jsx(cx,{isOpen:u.isOpen,onClose:u.close}),e.jsx(Sl,{isOpen:m.isOpen,onClose:m.close}),v&&e.jsx(kl,{isOpen:g.isOpen,onClose:()=>{g.close(),y(null)},organizationId:v})]})})};var y0=Object.defineProperty,Vo=Object.getOwnPropertySymbols,El=Object.prototype.hasOwnProperty,Pl=Object.prototype.propertyIsEnumerable,ti=(t,r,o)=>r in t?y0(t,r,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[r]=o,ga=(t,r)=>{for(var o in r||(r={}))El.call(r,o)&&ti(t,o,r[o]);if(Vo)for(var o of Vo(r))Pl.call(r,o)&&ti(t,o,r[o]);return t},ma=(t,r)=>{var o={};for(var n in t)El.call(t,n)&&r.indexOf(n)<0&&(o[n]=t[n]);if(t!=null&&Vo)for(var n of Vo(t))r.indexOf(n)<0&&Pl.call(t,n)&&(o[n]=t[n]);return o};/**
3685
+ `,zl=({showPersonal:t=!0})=>{var de,Q,ce;const[r,o]=i.useState(!1),[n,s]=i.useState(!1),[a,h]=i.useState(new Set),f=i.useRef(null),c=i.useRef(null),p=$l({triggerRef:f,isOpen:r,minWidth:300}),d=Mr(!1),u=Mr(!1),g=Mr(!1),m=Mr(!1),[v,y]=i.useState(null),[S,E]=i.useState(!1),[b,$]=i.useState(null),{organizationMemberships:C,loading:w,refetch:j}=bt(),{activeOrganization:x,leave:I}=qe(),{activeWorkspace:k,leave:R}=Rt(),{workspaces:_,loading:O}=yt(),{session:P,loading:z,switchOrganization:T,switchWorkspace:M}=Be(),{deployment:F}=ve(),{toast:G}=Je(),L=F==null?void 0:F.b2b_settings.organizations_enabled,A=F==null?void 0:F.b2b_settings.workspaces_enabled,se=F==null?void 0:F.b2b_settings.allow_users_to_create_orgs,te=!((de=P==null?void 0:P.active_signin)!=null&&de.active_organization_membership_id),U=i.useMemo(()=>{var V,D;if(te)return{name:"Personal account",image_url:(D=(V=P==null?void 0:P.active_signin)==null?void 0:V.user)==null?void 0:D.profile_picture_url,isPersonal:!0};let B=(x==null?void 0:x.name)||"";return A&&k&&(B=`${x==null?void 0:x.name} / ${k.name}`),{name:B,image_url:x==null?void 0:x.image_url,isPersonal:!1}},[te,x,k,P,A]);i.useEffect(()=>{if(!r)return;let B=null;const V=setTimeout(()=>{const D=le=>{var ae,ke;const H=le.target;(ae=f.current)!=null&&ae.contains(H)||(ke=c.current)!=null&&ke.contains(H)||(o(!1),$(null))};document.addEventListener("mousedown",D),B=()=>{document.removeEventListener("mousedown",D)}},50);return()=>{clearTimeout(V),B==null||B()}},[r]),i.useEffect(()=>{if(b){const B=setTimeout(()=>{$(null)},5e3);return()=>clearTimeout(B)}},[b]);const K=()=>{j()};if(!L)return null;const ee=B=>{s(!0),T(B).finally(()=>{s(!1)})},J=B=>{s(!0),M(B).finally(()=>{s(!1)})},ie=B=>{const V=new Set(a);V.has(B)?V.delete(B):V.add(B),h(V)},oe=B=>B.split(" ").map(V=>V[0]).join("").toUpperCase().slice(0,2);return w||z?e.jsx(ue,{children:e.jsx(qs,{children:e.jsxs(m0,{children:[e.jsxs(Ys,{children:[e.jsx(x0,{}),e.jsx(v0,{})]}),e.jsx(b0,{})]})})}):e.jsx(ue,{children:e.jsxs(qs,{children:[e.jsxs(i0,{ref:f,onClick:()=>{o(!r),r||$(null)},disabled:n,children:[e.jsxs(Ys,{children:[e.jsx(c0,{children:U.image_url?e.jsx(l0,{src:U.image_url,alt:U.name}):U.isPersonal?e.jsx(No,{size:12}):oe(U.name)}),e.jsx(d0,{children:U.name})]}),e.jsx(Mp,{size:16})]}),typeof window<"u"&&Nr.createPortal(e.jsx(ue,{children:e.jsx(u0,{ref:c,$isOpen:r,$position:p,children:w||O?e.jsxs(g0,{children:[e.jsxs(wo,{children:[e.jsx(jo,{}),e.jsxs(ko,{children:[e.jsx(_o,{width:"120px"}),e.jsx(ei,{width:"80px"})]})]}),e.jsx(pr,{}),e.jsxs(wo,{children:[e.jsx(jo,{}),e.jsx(ko,{children:e.jsx(_o,{width:"100px"})})]}),e.jsx(pr,{}),e.jsxs(wo,{children:[e.jsx(jo,{}),e.jsxs(ko,{children:[e.jsx(_o,{width:"140px"}),e.jsx(ei,{width:"60px"})]})]}),e.jsx(pr,{}),e.jsxs(wo,{children:[e.jsx(jo,{}),e.jsx(ko,{children:e.jsx(_o,{width:"110px"})})]})]}):e.jsxs("div",{children:[t&&e.jsxs(e.Fragment,{children:[e.jsxs(Oo,{as:"button",$isActive:te,onClick:B=>{B.stopPropagation(),te||ee()},disabled:n||te,children:[te&&e.jsx(bo,{}),e.jsxs(pt,{children:[e.jsx(p0,{children:(ce=(Q=P==null?void 0:P.active_signin)==null?void 0:Q.user)!=null&&ce.profile_picture_url?e.jsx(h0,{src:P.active_signin.user.profile_picture_url,alt:"Personal account"}):e.jsx(No,{size:12})}),e.jsx(ht,{children:e.jsx(ft,{children:"Personal account"})})]}),!te&&e.jsx(xo,{className:"hover-arrow",size:14})]}),!te&&x&&e.jsx(pr,{})]}),!te&&x&&e.jsxs(Oo,{$isActive:!0,onClick:()=>{A&&ie(x.id)},style:n?{pointerEvents:"none",opacity:.7}:void 0,children:[e.jsx(bo,{}),e.jsxs(pt,{children:[A&&e.jsx(er,{size:12,style:{marginRight:"4px",transform:a.has(x.id)?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.2s ease",color:"var(--color-secondary-text)"}}),e.jsx(Zs,{children:x.image_url?e.jsx(Qs,{src:x.image_url,alt:x.name}):oe(x.name)}),e.jsx(ht,{children:e.jsx(ft,{children:x.name})})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Mo,{onClick:B=>{B.stopPropagation(),u.open()},title:"Manage organization",children:e.jsx(Kt,{size:12})}),e.jsx(Un,{onClick:async B=>{B.stopPropagation(),E(!0),$(null);try{await I(),await j(),setTimeout(()=>{E(!1)},500)}catch(V){$(V instanceof Error?V.message:"Failed to leave organization"),E(!1)}},disabled:S,title:"Leave organization",children:e.jsx(Et,{size:12})})]})]}),x&&A&&a.has(x.id)&&e.jsxs(e.Fragment,{children:[_==null?void 0:_.filter(B=>B.organization.id===x.id).map(B=>{const V=(k==null?void 0:k.id)===B.id;return e.jsxs(yo,{as:V?void 0:"button",$isActive:V,onClick:V?void 0:()=>J(B.id),...V?{style:n?{pointerEvents:"none",opacity:.7}:void 0}:{disabled:n},children:[V&&e.jsx(bo,{}),e.jsxs(pt,{children:[e.jsx(Xs,{children:B.image_url?e.jsx("img",{src:B.image_url,alt:B.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):oe(B.name).charAt(0)}),e.jsx(ht,{children:e.jsx(ft,{children:B.name})})]}),V?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Mo,{onClick:D=>{D.stopPropagation(),m.open()},title:"Manage workspace",children:e.jsx(Kt,{size:12})}),e.jsx(Un,{onClick:async D=>{D.stopPropagation();try{R&&await R()}catch(le){const H=le.message||"Failed to leave workspace. Please try again.";G(H,"error")}},title:"Leave workspace",children:e.jsx(Et,{size:12})})]}):e.jsx(xo,{className:"hover-arrow",size:14})]},B.id)}),e.jsx(yo,{as:"button",onClick:()=>{y(x.id),g.open()},disabled:n,children:e.jsxs(pt,{children:[e.jsx(vo,{style:{width:"14px",height:"14px"},children:e.jsx(Ke,{size:12})}),e.jsx(ht,{children:e.jsx(ft,{children:"Create workspace"})})]})})]}),(S||b)&&e.jsxs(e.Fragment,{children:[S&&e.jsxs(Js,{children:[e.jsx(f0,{}),"Leaving organization..."]}),b&&e.jsxs(Js,{$isError:!0,children:[e.jsx("span",{children:"⚠️"}),b]})]}),e.jsx(pr,{}),C&&C.length>0&&e.jsx(e.Fragment,{children:C.filter(B=>B.organization.id!==(x==null?void 0:x.id)).map(B=>{const V=B.organization,D=(_==null?void 0:_.filter(H=>H.organization.id===V.id))||[],le=a.has(V.id);return e.jsxs(i.Fragment,{children:[e.jsxs(Oo,{as:"button",$isActive:!1,onClick:()=>{A?ie(V.id):ee(V.id)},disabled:n,children:[e.jsxs(pt,{children:[A&&e.jsx(er,{size:12,style:{marginRight:"4px",transform:le?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.2s ease",color:"var(--color-secondary-text)"}}),e.jsx(Zs,{children:V.image_url?e.jsx(Qs,{src:V.image_url,alt:V.name}):oe(V.name)}),e.jsx(ht,{children:e.jsx(ft,{children:V.name})})]}),e.jsx(xo,{className:"hover-arrow",size:14})]}),A&&le&&e.jsxs(e.Fragment,{children:[D.map(H=>{const ae=(k==null?void 0:k.id)===H.id;return e.jsxs(yo,{as:ae?void 0:"button",$isActive:ae,onClick:ae?void 0:()=>J(H.id),...ae?{style:n?{pointerEvents:"none",opacity:.7}:void 0}:{disabled:n},children:[ae&&e.jsx(bo,{}),e.jsxs(pt,{children:[e.jsx(Xs,{children:H.image_url?e.jsx("img",{src:H.image_url,alt:H.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):oe(H.name).charAt(0)}),e.jsx(ht,{children:e.jsx(ft,{children:H.name})})]}),ae?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Mo,{onClick:ke=>{ke.stopPropagation(),m.open()},title:"Manage workspace",children:e.jsx(Kt,{size:12})}),e.jsx(Un,{onClick:async ke=>{ke.stopPropagation();try{R&&await R()}catch(ne){const Y=ne.message||"Failed to leave workspace. Please try again.";G(Y,"error")}},title:"Leave workspace",children:e.jsx(Et,{size:12})})]}):e.jsx(xo,{className:"hover-arrow",size:16})]},H.id)}),e.jsx(yo,{as:"button",onClick:()=>{y(V.id),g.open()},disabled:n,children:e.jsxs(pt,{children:[e.jsx(vo,{style:{width:"14px",height:"14px"},children:e.jsx(Ke,{size:10})}),e.jsx(ht,{children:e.jsx(ft,{children:"Create workspace"})})]})})]}),e.jsx(pr,{})]},V.id)})}),A?x&&e.jsx(Ks,{onClick:()=>{y(x.id),g.open()},disabled:n,children:e.jsxs(pt,{children:[e.jsx(vo,{children:e.jsx(Ke,{size:12})}),e.jsx(ht,{children:e.jsx(ft,{children:"Create workspace"})})]})}):se&&e.jsx(Ks,{onClick:()=>{d.open()},disabled:n,children:e.jsxs(pt,{children:[e.jsx(vo,{children:e.jsx(Ke,{size:12})}),e.jsx(ht,{children:e.jsx(ft,{children:"Create organization"})})]})})]})})}),document.body),L&&se&&e.jsx(xm,{isOpen:d.isOpen,onClose:d.close,onCreated:K}),e.jsx(cx,{isOpen:u.isOpen,onClose:u.close}),e.jsx(Sl,{isOpen:m.isOpen,onClose:m.close}),v&&e.jsx(kl,{isOpen:g.isOpen,onClose:()=>{g.close(),y(null)},organizationId:v})]})})};var y0=Object.defineProperty,Vo=Object.getOwnPropertySymbols,El=Object.prototype.hasOwnProperty,Pl=Object.prototype.propertyIsEnumerable,ti=(t,r,o)=>r in t?y0(t,r,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[r]=o,ga=(t,r)=>{for(var o in r||(r={}))El.call(r,o)&&ti(t,o,r[o]);if(Vo)for(var o of Vo(r))Pl.call(r,o)&&ti(t,o,r[o]);return t},ma=(t,r)=>{var o={};for(var n in t)El.call(t,n)&&r.indexOf(n)<0&&(o[n]=t[n]);if(t!=null&&Vo)for(var n of Vo(t))r.indexOf(n)<0&&Pl.call(t,n)&&(o[n]=t[n]);return o};/**
3686
3686
  * @license QR Code generator library (TypeScript)
3687
3687
  * Copyright (c) Project Nayuki.
3688
3688
  * SPDX-License-Identifier: MIT
@@ -4105,7 +4105,7 @@ cursor: pointer;
4105
4105
  flex-wrap: wrap;
4106
4106
  gap: 12px;
4107
4107
  margin-bottom: 0;
4108
- `,cv=()=>e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",style:{color:"var(--color-secondary-text)"},children:[e.jsx("circle",{cx:"12",cy:"12",r:"11",fill:"currentColor",stroke:"currentColor",strokeWidth:"0.5",opacity:"0.6"}),e.jsx("circle",{cx:"12",cy:"12",r:"8",fill:"none",stroke:"currentColor",strokeWidth:"0.5",opacity:"0.3"}),e.jsx("path",{d:"M12 8c-2.2 0-4 1.8-4 4s1.8 4 4 4 4-1.8 4-4-1.8-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z",fill:"currentColor",opacity:"0.5"}),e.jsx("circle",{cx:"12",cy:"12",r:"1",fill:"currentColor"}),e.jsx("text",{x:"12",y:"16.5",textAnchor:"middle",fill:"currentColor",fontSize:"6",opacity:"0.7",children:"?"})]}),lv=({browser:t})=>{const r=(t==null?void 0:t.toLowerCase())||"",o={width:20,height:20};return r.includes("chrome")?e.jsx(K0,{...o}):r.includes("firefox")?e.jsx(X0,{...o}):r.includes("safari")?e.jsx(J0,{...o}):r.includes("edge")?e.jsx(ev,{...o}):r.includes("opera")?e.jsx(tv,{...o}):r.includes("brave")?e.jsx(rv,{...o}):e.jsx(cv,{})},dv=()=>{const[t,r]=i.useState(null),{signins:o,removeSignin:n,refetch:s,loading:a}=ac(),{refetch:h}=Be(),{toast:f}=Tt(),c=o,p=async u=>{try{await n(u),await Promise.all([s(),h()]),r(null),f("Session ended successfully","info")}catch(g){f(g.message||"Failed to end session. Please try again.","error")}},d=u=>{if(!u||u.trim()==="")return"Unknown";const g=new Date(u);if(isNaN(g.getTime()))return"Unknown";const v=Math.floor((new Date().getTime()-g.getTime())/(1e3*60));return v<1?"Just now":v<60?`${v}m ago`:v<1440?`${Math.floor(v/60)}h ago`:g.toLocaleDateString()};return a?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"20px"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:"16px"},children:[e.jsx("h3",{style:{fontSize:"16px",color:"var(--color-foreground)",margin:0},children:"Active Sessions"}),e.jsx("p",{style:{fontSize:"14px",color:"var(--color-muted)",margin:0},children:"Manage your active browser sessions and sign-ins"})]}),e.jsx("div",{children:c&&c.length>0?e.jsxs(wt,{children:[e.jsx(jt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Browser & Device"}),e.jsx(ze,{children:"Location"}),e.jsx(ze,{children:"Last Active"}),e.jsx(ze,{})]})}),e.jsx(kt,{children:c.map(u=>e.jsxs(We,{children:[e.jsx(Le,{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Nl,{children:e.jsx(lv,{browser:u.browser||"Unknown"})}),e.jsxs("div",{children:[e.jsx("div",{children:u.browser||"Unknown Browser"}),u.device&&e.jsx("div",{style:{fontSize:"12px",color:"var(--color-muted)"},children:u.device})]})]})}),e.jsx(Le,{children:e.jsxs("div",{children:[e.jsx("div",{children:u.city&&u.country?`${u.city}, ${u.country}`:"Unknown location"}),u.ip_address&&e.jsx("div",{style:{fontSize:"12px",color:"var(--color-muted)"},children:u.ip_address})]})}),e.jsx(Le,{children:d(u.last_active_at)}),e.jsx(_t,{children:e.jsxs(nt,{open:t===u.id,openChange:g=>r(g?u.id:null),children:[e.jsx(st,{children:e.jsx(an,{children:"•••"})}),e.jsx(at,{children:e.jsx(Te,{onClick:()=>p(u.id),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(zt,{size:14}),"End Session"]})})})]})})]},u.id))})]}):e.jsx(et,{title:"No active sessions",description:"You don't have any active sessions at the moment."})})]})},uv=()=>{var j,x,I,k;const{deployment:t}=ve(),{toast:r}=Tt(),[o,n]=i.useState(null),[s,a]=i.useState(""),[h,f]=i.useState(!1),[c,p]=i.useState(null),[d,u]=i.useState(""),g=i.useRef(null),m=i.useRef({}),{user:v,createEmailAddress:y,deleteEmailAddress:S,prepareEmailVerification:E,attemptEmailVerification:b,makeEmailPrimary:$}=rr();if(!((x=(j=t==null?void 0:t.auth_settings)==null?void 0:j.email_address)!=null&&x.enabled))return null;const C=async R=>{try{if(R===(v==null?void 0:v.primary_email_address_id)){r("Cannot delete primary email address. Please set another email as primary first.","error");return}await S(R),v.refetch(),r("Email address deleted successfully","info")}catch(_){r(_.message||"Failed to delete email address. Please try again.","error")}},w=i.useMemo(()=>v!=null&&v.user_email_addresses?d.trim()?v.user_email_addresses.filter(R=>R.email.toLowerCase().includes(d.toLowerCase())):v.user_email_addresses:[],[v==null?void 0:v.user_email_addresses,d]);return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{style:{marginBottom:"20px"},children:[e.jsx(yt,{value:d,onChange:u,placeholder:"Search Email"}),e.jsxs("div",{style:{position:"relative"},children:[e.jsx(X,{ref:g,onClick:()=>f(!0),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Add Email"}),h&&e.jsx(ni,{triggerRef:g,onClose:()=>f(!1),onAddEmail:async R=>{const _=await y(R);a(_.data.id),await E(_.data.id),v.refetch()},onPrepareVerification:async()=>{await E(s),v.refetch()},onAttemptVerification:async R=>{await b(s,R),v.refetch(),f(!1),a(""),r("Email added and verified successfully!","info")}})]})]}),w!=null&&w.length?e.jsxs(wt,{children:[e.jsx(jt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Email Address"}),e.jsx(ze,{children:"Status"}),e.jsx(ze,{})]})}),e.jsx(kt,{children:w.map(R=>e.jsxs(We,{children:[e.jsx(Le,{children:R.email}),e.jsx(Le,{children:R.id===(v==null?void 0:v.primary_email_address_id)?"Primary":R.verified?"Verified":"Not Verified"}),e.jsx(_t,{children:R.id!==(v==null?void 0:v.primary_email_address_id)||!R.verified?e.jsxs(nt,{open:o===R.id,openChange:_=>n(_?R.id:null),children:[e.jsx(st,{children:e.jsx(an,{ref:_=>{_&&(m.current[R.id]=_)},children:"•••"})}),e.jsxs(at,{children:[R.id!==(v==null?void 0:v.primary_email_address_id)&&R.verified&&e.jsx(Te,{onClick:async()=>{try{await $(R.id),v.refetch(),n(null),r("Primary email updated successfully","info")}catch(_){r(_.message||"Failed to update primary email","error")}},children:"Make primary"}),!R.verified&&e.jsx(Te,{onClick:async()=>{n(null),await E(R.id),p(R.id)},children:"Verify email"}),R.id!==(v==null?void 0:v.primary_email_address_id)&&e.jsx(Te,{$destructive:!0,onClick:()=>{C(R.id),n(null)},children:"Remove"})]})]}):null})]},R.id))})]}):e.jsx(et,{title:d?"No emails match your search":"No email addresses",description:"Add an email address to get started."}),c&&e.jsx(ni,{existingEmail:(k=(I=v==null?void 0:v.user_email_addresses)==null?void 0:I.find(R=>R.id===c))==null?void 0:k.email,triggerRef:{current:m.current[c]},onClose:()=>p(null),onAddEmail:async()=>{},onPrepareVerification:async()=>{await E(c),v.refetch()},onAttemptVerification:async R=>{await b(c,R),v.refetch(),p(null),r("Email verified successfully!","info")}})]})},pv=()=>{var w,j,x,I;const{deployment:t}=ve(),[r,o]=i.useState(null),[n,s]=i.useState(""),[a,h]=i.useState(!1),[f,c]=i.useState(null),[p,d]=i.useState(""),u=i.useRef(null),g=i.useRef({}),{user:m,createPhoneNumber:v,deletePhoneNumber:y,preparePhoneVerification:S,attemptPhoneVerification:E,makePhonePrimary:b}=rr();if(!((j=(w=t==null?void 0:t.auth_settings)==null?void 0:w.phone_number)!=null&&j.enabled))return null;const $=k=>{const R=To.find(_=>_.dialCode===k);return(R==null?void 0:R.flag)||"🌍"},C=i.useMemo(()=>m!=null&&m.user_phone_numbers?p.trim()?m.user_phone_numbers.filter(k=>k.phone_number.toLowerCase().includes(p.toLowerCase())):m.user_phone_numbers:[],[m==null?void 0:m.user_phone_numbers,p]);return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{style:{marginBottom:"20px"},children:[e.jsx(yt,{value:p,onChange:d,placeholder:"Search Phone"}),e.jsxs("div",{style:{position:"relative"},children:[e.jsx(X,{ref:u,onClick:()=>h(!0),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Add Phone"}),a&&e.jsx(ii,{triggerRef:u,onClose:()=>h(!1),onAddPhone:async(k,R)=>{const _=await v(k,R);s(_.data.id),await S(_.data.id)},onPrepareVerification:async()=>{await S(n),m.refetch()},onAttemptVerification:async k=>{await E(n,k),m.refetch(),h(!1)}}),f&&e.jsx(ii,{existingPhone:(I=(x=m==null?void 0:m.user_phone_numbers)==null?void 0:x.find(k=>k.id===f))==null?void 0:I.phone_number,triggerRef:{current:g.current[f]},onClose:()=>c(null),onAddPhone:async()=>{},onPrepareVerification:async()=>{await S(f),m.refetch()},onAttemptVerification:async k=>{await E(f,k),m.refetch(),c(null)}})]})]}),C!=null&&C.length?e.jsxs(wt,{children:[e.jsx(jt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Phone Number"}),e.jsx(ze,{children:"Status"}),e.jsx(ze,{})]})}),e.jsx(kt,{children:C.map(k=>e.jsxs(We,{children:[e.jsx(Le,{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("span",{style:{fontSize:"18px"},children:$(k.country_code)}),e.jsx("span",{children:k.country_code}),e.jsx("span",{children:k.phone_number})]})}),e.jsx(Le,{children:k.id===(m==null?void 0:m.primary_phone_number_id)?"Primary":k.verified?"Verified":"Not Verified"}),e.jsx(_t,{children:e.jsxs(nt,{open:r===k.id,openChange:R=>o(R?k.id:null),children:[e.jsx(st,{children:e.jsx(an,{ref:R=>{R&&(g.current[k.id]=R)},children:"•••"})}),e.jsxs(at,{children:[k.id!==(m==null?void 0:m.primary_phone_number_id)&&k.verified&&e.jsx(Te,{onClick:async()=>{await b(k.id),o(null),m.refetch()},children:"Make primary"}),!k.verified&&e.jsx(Te,{onClick:async()=>{await S(k.id),c(k.id),o(null)},children:"Verify phone"}),e.jsx(Te,{$destructive:!0,onClick:async()=>{await y(k.id),o(null),m.refetch()},children:"Remove"})]})]})})]},k.id))})]}):e.jsx(et,{title:p?"No phones match your search":"No phone numbers",description:"Add a phone number to get started."})]})},Nl=l.div`
4108
+ `,cv=()=>e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",style:{color:"var(--color-secondary-text)"},children:[e.jsx("circle",{cx:"12",cy:"12",r:"11",fill:"currentColor",stroke:"currentColor",strokeWidth:"0.5",opacity:"0.6"}),e.jsx("circle",{cx:"12",cy:"12",r:"8",fill:"none",stroke:"currentColor",strokeWidth:"0.5",opacity:"0.3"}),e.jsx("path",{d:"M12 8c-2.2 0-4 1.8-4 4s1.8 4 4 4 4-1.8 4-4-1.8-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z",fill:"currentColor",opacity:"0.5"}),e.jsx("circle",{cx:"12",cy:"12",r:"1",fill:"currentColor"}),e.jsx("text",{x:"12",y:"16.5",textAnchor:"middle",fill:"currentColor",fontSize:"6",opacity:"0.7",children:"?"})]}),lv=({browser:t})=>{const r=(t==null?void 0:t.toLowerCase())||"",o={width:20,height:20};return r.includes("chrome")?e.jsx(K0,{...o}):r.includes("firefox")?e.jsx(X0,{...o}):r.includes("safari")?e.jsx(J0,{...o}):r.includes("edge")?e.jsx(ev,{...o}):r.includes("opera")?e.jsx(tv,{...o}):r.includes("brave")?e.jsx(rv,{...o}):e.jsx(cv,{})},dv=()=>{const[t,r]=i.useState(null),{signins:o,removeSignin:n,refetch:s,loading:a}=ac(),{refetch:h}=Be(),{toast:f}=Tt(),c=o,p=async u=>{try{await n(u),await Promise.all([s(),h()]),r(null),f("Session ended successfully","info")}catch(g){f(g.message||"Failed to end session. Please try again.","error")}},d=u=>{if(!u||u.trim()==="")return"Unknown";const g=new Date(u);if(isNaN(g.getTime()))return"Unknown";const v=Math.floor((new Date().getTime()-g.getTime())/(1e3*60));return v<1?"Just now":v<60?`${v}m ago`:v<1440?`${Math.floor(v/60)}h ago`:g.toLocaleDateString()};return a?e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"20px"},children:e.jsx(Ee,{})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:"16px"},children:[e.jsx("h3",{style:{fontSize:"16px",color:"var(--color-foreground)",margin:0},children:"Active Sessions"}),e.jsx("p",{style:{fontSize:"14px",color:"var(--color-muted)",margin:0},children:"Manage your active browser sessions and sign-ins"})]}),e.jsx("div",{children:c&&c.length>0?e.jsxs(jt,{children:[e.jsx(kt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Browser & Device"}),e.jsx(ze,{children:"Location"}),e.jsx(ze,{children:"Last Active"}),e.jsx(ze,{})]})}),e.jsx(_t,{children:c.map(u=>e.jsxs(We,{children:[e.jsx(Le,{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Nl,{children:e.jsx(lv,{browser:u.browser||"Unknown"})}),e.jsxs("div",{children:[e.jsx("div",{children:u.browser||"Unknown Browser"}),u.device&&e.jsx("div",{style:{fontSize:"12px",color:"var(--color-muted)"},children:u.device})]})]})}),e.jsx(Le,{children:e.jsxs("div",{children:[e.jsx("div",{children:u.city&&u.country?`${u.city}, ${u.country}`:"Unknown location"}),u.ip_address&&e.jsx("div",{style:{fontSize:"12px",color:"var(--color-muted)"},children:u.ip_address})]})}),e.jsx(Le,{children:d(u.last_active_at)}),e.jsx(Ct,{children:e.jsxs(nt,{open:t===u.id,openChange:g=>r(g?u.id:null),children:[e.jsx(st,{children:e.jsx(an,{children:"•••"})}),e.jsx(at,{children:e.jsx(Te,{onClick:()=>p(u.id),children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(Et,{size:14}),"End Session"]})})})]})})]},u.id))})]}):e.jsx(et,{title:"No active sessions",description:"You don't have any active sessions at the moment."})})]})},uv=()=>{var j,x,I,k;const{deployment:t}=ve(),{toast:r}=Tt(),[o,n]=i.useState(null),[s,a]=i.useState(""),[h,f]=i.useState(!1),[c,p]=i.useState(null),[d,u]=i.useState(""),g=i.useRef(null),m=i.useRef({}),{user:v,createEmailAddress:y,deleteEmailAddress:S,prepareEmailVerification:E,attemptEmailVerification:b,makeEmailPrimary:$}=rr();if(!((x=(j=t==null?void 0:t.auth_settings)==null?void 0:j.email_address)!=null&&x.enabled))return null;const C=async R=>{try{if(R===(v==null?void 0:v.primary_email_address_id)){r("Cannot delete primary email address. Please set another email as primary first.","error");return}await S(R),v.refetch(),r("Email address deleted successfully","info")}catch(_){r(_.message||"Failed to delete email address. Please try again.","error")}},w=i.useMemo(()=>v!=null&&v.user_email_addresses?d.trim()?v.user_email_addresses.filter(R=>R.email.toLowerCase().includes(d.toLowerCase())):v.user_email_addresses:[],[v==null?void 0:v.user_email_addresses,d]);return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{style:{marginBottom:"20px"},children:[e.jsx(wt,{value:d,onChange:u,placeholder:"Search Email"}),e.jsxs("div",{style:{position:"relative"},children:[e.jsx(X,{ref:g,onClick:()=>f(!0),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Add Email"}),h&&e.jsx(ni,{triggerRef:g,onClose:()=>f(!1),onAddEmail:async R=>{const _=await y(R);a(_.data.id),await E(_.data.id),v.refetch()},onPrepareVerification:async()=>{await E(s),v.refetch()},onAttemptVerification:async R=>{await b(s,R),v.refetch(),f(!1),a(""),r("Email added and verified successfully!","info")}})]})]}),w!=null&&w.length?e.jsxs(jt,{children:[e.jsx(kt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Email Address"}),e.jsx(ze,{children:"Status"}),e.jsx(ze,{})]})}),e.jsx(_t,{children:w.map(R=>e.jsxs(We,{children:[e.jsx(Le,{children:R.email}),e.jsx(Le,{children:R.id===(v==null?void 0:v.primary_email_address_id)?"Primary":R.verified?"Verified":"Not Verified"}),e.jsx(Ct,{children:R.id!==(v==null?void 0:v.primary_email_address_id)||!R.verified?e.jsxs(nt,{open:o===R.id,openChange:_=>n(_?R.id:null),children:[e.jsx(st,{children:e.jsx(an,{ref:_=>{_&&(m.current[R.id]=_)},children:"•••"})}),e.jsxs(at,{children:[R.id!==(v==null?void 0:v.primary_email_address_id)&&R.verified&&e.jsx(Te,{onClick:async()=>{try{await $(R.id),v.refetch(),n(null),r("Primary email updated successfully","info")}catch(_){r(_.message||"Failed to update primary email","error")}},children:"Make primary"}),!R.verified&&e.jsx(Te,{onClick:async()=>{n(null),await E(R.id),p(R.id)},children:"Verify email"}),R.id!==(v==null?void 0:v.primary_email_address_id)&&e.jsx(Te,{$destructive:!0,onClick:()=>{C(R.id),n(null)},children:"Remove"})]})]}):null})]},R.id))})]}):e.jsx(et,{title:d?"No emails match your search":"No email addresses",description:"Add an email address to get started."}),c&&e.jsx(ni,{existingEmail:(k=(I=v==null?void 0:v.user_email_addresses)==null?void 0:I.find(R=>R.id===c))==null?void 0:k.email,triggerRef:{current:m.current[c]},onClose:()=>p(null),onAddEmail:async()=>{},onPrepareVerification:async()=>{await E(c),v.refetch()},onAttemptVerification:async R=>{await b(c,R),v.refetch(),p(null),r("Email verified successfully!","info")}})]})},pv=()=>{var w,j,x,I;const{deployment:t}=ve(),[r,o]=i.useState(null),[n,s]=i.useState(""),[a,h]=i.useState(!1),[f,c]=i.useState(null),[p,d]=i.useState(""),u=i.useRef(null),g=i.useRef({}),{user:m,createPhoneNumber:v,deletePhoneNumber:y,preparePhoneVerification:S,attemptPhoneVerification:E,makePhonePrimary:b}=rr();if(!((j=(w=t==null?void 0:t.auth_settings)==null?void 0:w.phone_number)!=null&&j.enabled))return null;const $=k=>{const R=To.find(_=>_.dialCode===k);return(R==null?void 0:R.flag)||"🌍"},C=i.useMemo(()=>m!=null&&m.user_phone_numbers?p.trim()?m.user_phone_numbers.filter(k=>k.phone_number.toLowerCase().includes(p.toLowerCase())):m.user_phone_numbers:[],[m==null?void 0:m.user_phone_numbers,p]);return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{style:{marginBottom:"20px"},children:[e.jsx(wt,{value:p,onChange:d,placeholder:"Search Phone"}),e.jsxs("div",{style:{position:"relative"},children:[e.jsx(X,{ref:u,onClick:()=>h(!0),style:{padding:"8px 16px",borderRadius:"6px",fontSize:"14px",fontWeight:500,height:"36px"},children:"Add Phone"}),a&&e.jsx(ii,{triggerRef:u,onClose:()=>h(!1),onAddPhone:async(k,R)=>{const _=await v(k,R);s(_.data.id),await S(_.data.id)},onPrepareVerification:async()=>{await S(n),m.refetch()},onAttemptVerification:async k=>{await E(n,k),m.refetch(),h(!1)}}),f&&e.jsx(ii,{existingPhone:(I=(x=m==null?void 0:m.user_phone_numbers)==null?void 0:x.find(k=>k.id===f))==null?void 0:I.phone_number,triggerRef:{current:g.current[f]},onClose:()=>c(null),onAddPhone:async()=>{},onPrepareVerification:async()=>{await S(f),m.refetch()},onAttemptVerification:async k=>{await E(f,k),m.refetch(),c(null)}})]})]}),C!=null&&C.length?e.jsxs(jt,{children:[e.jsx(kt,{children:e.jsxs(We,{children:[e.jsx(ze,{children:"Phone Number"}),e.jsx(ze,{children:"Status"}),e.jsx(ze,{})]})}),e.jsx(_t,{children:C.map(k=>e.jsxs(We,{children:[e.jsx(Le,{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("span",{style:{fontSize:"18px"},children:$(k.country_code)}),e.jsx("span",{children:k.country_code}),e.jsx("span",{children:k.phone_number})]})}),e.jsx(Le,{children:k.id===(m==null?void 0:m.primary_phone_number_id)?"Primary":k.verified?"Verified":"Not Verified"}),e.jsx(Ct,{children:e.jsxs(nt,{open:r===k.id,openChange:R=>o(R?k.id:null),children:[e.jsx(st,{children:e.jsx(an,{ref:R=>{R&&(g.current[k.id]=R)},children:"•••"})}),e.jsxs(at,{children:[k.id!==(m==null?void 0:m.primary_phone_number_id)&&k.verified&&e.jsx(Te,{onClick:async()=>{await b(k.id),o(null),m.refetch()},children:"Make primary"}),!k.verified&&e.jsx(Te,{onClick:async()=>{await S(k.id),c(k.id),o(null)},children:"Verify phone"}),e.jsx(Te,{$destructive:!0,onClick:async()=>{await y(k.id),o(null),m.refetch()},children:"Remove"})]})]})})]},k.id))})]}):e.jsx(et,{title:p?"No phones match your search":"No phone numbers",description:"Add a phone number to get started."})]})},Nl=l.div`
4109
4109
  width: 20px;
4110
4110
  height: 20px;
4111
4111
  flex-shrink: 0;
@@ -4261,7 +4261,7 @@ cursor: pointer;
4261
4261
  width: 14px;
4262
4262
  height: 14px;
4263
4263
  }
4264
- `,Pa=({showName:t=!0})=>{var j,x,I,k;const[r,o]=i.useState(!1),n=i.useRef(null),s=i.useRef(null),a=$l({triggerRef:n,isOpen:r,minWidth:380}),h=Mr(!1),{session:f,signOut:c,switchSignIn:p,refetch:d}=Be(),{navigateToSignIn:u}=Ve(),{deployment:g}=ve(),m=(j=f==null?void 0:f.active_signin)==null?void 0:j.user,v=((I=(x=g==null?void 0:g.auth_settings)==null?void 0:x.multi_session_support)==null?void 0:I.enabled)??!1,y=(((k=f==null?void 0:f.signins)==null?void 0:k.length)??0)>1;i.useEffect(()=>{if(!r)return;const R=setTimeout(()=>{const _=O=>{var z,T;const P=O.target;(z=n.current)!=null&&z.contains(P)||(T=s.current)!=null&&T.contains(P)||o(!1)};return document.addEventListener("mousedown",_),()=>{document.removeEventListener("mousedown",_)}},50);return()=>{clearTimeout(R)}},[r]);const S=()=>{o(!r)},E=R=>R.split(" ").map(_=>_[0]).join("").toUpperCase(),b=async R=>{try{await c(R),await d(),o(!1)}catch{}},$=async()=>{try{await c(),await d(),o(!1)}catch{}},C=async R=>{try{await p(R),await d(),o(!1)}catch{}},w=()=>{h.open(),o(!1)};return e.jsx(ue,{children:e.jsxs(mv,{children:[e.jsxs(xv,{ref:n,onClick:S,children:[e.jsx(Hn,{children:e.jsx(Wl,{children:m!=null&&m.has_profile_picture?e.jsx("img",{src:m.profile_picture_url,alt:m.first_name}):E(`${(m==null?void 0:m.first_name)||""} ${(m==null?void 0:m.last_name)||""}`)})}),t&&e.jsx(vv,{children:`${(m==null?void 0:m.first_name)||""} ${(m==null?void 0:m.last_name)||""}`})]}),typeof window<"u"&&r&&Nr.createPortal(e.jsx(ue,{children:e.jsx(bv,{ref:s,$position:a,$isOpen:r,$maxHeight:a==null?void 0:a.maxHeight,children:e.jsxs("div",{children:[v?(()=>{const R=[...(f==null?void 0:f.signins)||[]].sort((_,O)=>{const P=_.user.id===(m==null?void 0:m.id),z=O.user.id===(m==null?void 0:m.id);return P&&!z?-1:!P&&z?1:0});return R.map(({user:_,id:O},P)=>{const z=_.id===(m==null?void 0:m.id),T=!z;return e.jsxs(i.Fragment,{children:[e.jsxs(mi,{$isClickable:T,onClick:T?()=>C(O):void 0,children:[e.jsxs(xi,{children:[e.jsx(Hn,{children:e.jsx(yi,{children:_.has_profile_picture?e.jsx("img",{src:_.profile_picture_url,alt:_.first_name}):E(`${(_==null?void 0:_.first_name)||""} ${(_==null?void 0:_.last_name)||""}`)})}),e.jsxs(vi,{children:[e.jsx(bi,{children:e.jsx(fi,{children:`${(_==null?void 0:_.first_name)||""} ${(_==null?void 0:_.last_name)||""}`})}),e.jsx(gi,{children:_.primary_email_address.email})]})]}),z&&e.jsxs(wi,{children:[e.jsxs(So,{onClick:w,children:[e.jsx(Kt,{}),"Manage account"]}),e.jsxs(So,{$destructive:!0,onClick:()=>b(O),children:[e.jsx(zt,{}),"Sign out"]})]})]}),P===0&&R.length>1&&e.jsx("div",{style:{borderBottom:"1px solid var(--color-border)",margin:"0"}})]},_.id)})})():m&&e.jsxs(mi,{$isClickable:!1,children:[e.jsxs(xi,{children:[e.jsx(Hn,{children:e.jsx(yi,{children:m.has_profile_picture?e.jsx("img",{src:m.profile_picture_url,alt:m.first_name}):E(`${(m==null?void 0:m.first_name)||""} ${(m==null?void 0:m.last_name)||""}`)})}),e.jsxs(vi,{children:[e.jsx(bi,{children:e.jsx(fi,{children:`${(m==null?void 0:m.first_name)||""} ${(m==null?void 0:m.last_name)||""}`})}),e.jsx(gi,{children:m.primary_email_address.email})]})]}),e.jsxs(wi,{children:[e.jsxs(So,{onClick:w,children:[e.jsx(Kt,{}),"Manage account"]}),e.jsxs(So,{$destructive:!0,onClick:()=>{var R;return b(((R=f==null?void 0:f.active_signin)==null?void 0:R.id)||"")},children:[e.jsx(zt,{}),"Sign out"]})]})]}),v&&e.jsxs(e.Fragment,{children:[e.jsx(ji,{style:{borderBottom:"1px solid var(--color-border)"},children:e.jsxs(ki,{onClick:()=>u(),children:[e.jsx(Ke,{}),"Add new account"]})}),y&&e.jsx(ji,{children:e.jsxs(ki,{onClick:$,children:[e.jsx(zt,{}),"Sign out of all accounts"]})})]})]})})}),document.body),e.jsx(Ul,{isOpen:h.isOpen,onClose:h.close})]})})},yv=l.div`
4264
+ `,Pa=({showName:t=!0})=>{var j,x,I,k;const[r,o]=i.useState(!1),n=i.useRef(null),s=i.useRef(null),a=$l({triggerRef:n,isOpen:r,minWidth:380}),h=Mr(!1),{session:f,signOut:c,switchSignIn:p,refetch:d}=Be(),{navigateToSignIn:u}=Ve(),{deployment:g}=ve(),m=(j=f==null?void 0:f.active_signin)==null?void 0:j.user,v=((I=(x=g==null?void 0:g.auth_settings)==null?void 0:x.multi_session_support)==null?void 0:I.enabled)??!1,y=(((k=f==null?void 0:f.signins)==null?void 0:k.length)??0)>1;i.useEffect(()=>{if(!r)return;const R=setTimeout(()=>{const _=O=>{var z,T;const P=O.target;(z=n.current)!=null&&z.contains(P)||(T=s.current)!=null&&T.contains(P)||o(!1)};return document.addEventListener("mousedown",_),()=>{document.removeEventListener("mousedown",_)}},50);return()=>{clearTimeout(R)}},[r]);const S=()=>{o(!r)},E=R=>R.split(" ").map(_=>_[0]).join("").toUpperCase(),b=async R=>{try{await c(R),await d(),o(!1)}catch{}},$=async()=>{try{await c(),await d(),o(!1)}catch{}},C=async R=>{try{await p(R),await d(),o(!1)}catch{}},w=()=>{h.open(),o(!1)};return e.jsx(ue,{children:e.jsxs(mv,{children:[e.jsxs(xv,{ref:n,onClick:S,children:[e.jsx(Hn,{children:e.jsx(Wl,{children:m!=null&&m.has_profile_picture?e.jsx("img",{src:m.profile_picture_url,alt:m.first_name}):E(`${(m==null?void 0:m.first_name)||""} ${(m==null?void 0:m.last_name)||""}`)})}),t&&e.jsx(vv,{children:`${(m==null?void 0:m.first_name)||""} ${(m==null?void 0:m.last_name)||""}`})]}),typeof window<"u"&&r&&Nr.createPortal(e.jsx(ue,{children:e.jsx(bv,{ref:s,$position:a,$isOpen:r,$maxHeight:a==null?void 0:a.maxHeight,children:e.jsxs("div",{children:[v?(()=>{const R=[...(f==null?void 0:f.signins)||[]].sort((_,O)=>{const P=_.user.id===(m==null?void 0:m.id),z=O.user.id===(m==null?void 0:m.id);return P&&!z?-1:!P&&z?1:0});return R.map(({user:_,id:O},P)=>{const z=_.id===(m==null?void 0:m.id),T=!z;return e.jsxs(i.Fragment,{children:[e.jsxs(mi,{$isClickable:T,onClick:T?()=>C(O):void 0,children:[e.jsxs(xi,{children:[e.jsx(Hn,{children:e.jsx(yi,{children:_.has_profile_picture?e.jsx("img",{src:_.profile_picture_url,alt:_.first_name}):E(`${(_==null?void 0:_.first_name)||""} ${(_==null?void 0:_.last_name)||""}`)})}),e.jsxs(vi,{children:[e.jsx(bi,{children:e.jsx(fi,{children:`${(_==null?void 0:_.first_name)||""} ${(_==null?void 0:_.last_name)||""}`})}),e.jsx(gi,{children:_.primary_email_address.email})]})]}),z&&e.jsxs(wi,{children:[e.jsxs(So,{onClick:w,children:[e.jsx(Kt,{}),"Manage account"]}),e.jsxs(So,{$destructive:!0,onClick:()=>b(O),children:[e.jsx(Et,{}),"Sign out"]})]})]}),P===0&&R.length>1&&e.jsx("div",{style:{borderBottom:"1px solid var(--color-border)",margin:"0"}})]},_.id)})})():m&&e.jsxs(mi,{$isClickable:!1,children:[e.jsxs(xi,{children:[e.jsx(Hn,{children:e.jsx(yi,{children:m.has_profile_picture?e.jsx("img",{src:m.profile_picture_url,alt:m.first_name}):E(`${(m==null?void 0:m.first_name)||""} ${(m==null?void 0:m.last_name)||""}`)})}),e.jsxs(vi,{children:[e.jsx(bi,{children:e.jsx(fi,{children:`${(m==null?void 0:m.first_name)||""} ${(m==null?void 0:m.last_name)||""}`})}),e.jsx(gi,{children:m.primary_email_address.email})]})]}),e.jsxs(wi,{children:[e.jsxs(So,{onClick:w,children:[e.jsx(Kt,{}),"Manage account"]}),e.jsxs(So,{$destructive:!0,onClick:()=>{var R;return b(((R=f==null?void 0:f.active_signin)==null?void 0:R.id)||"")},children:[e.jsx(Et,{}),"Sign out"]})]})]}),v&&e.jsxs(e.Fragment,{children:[e.jsx(ji,{style:{borderBottom:"1px solid var(--color-border)"},children:e.jsxs(ki,{onClick:()=>u(),children:[e.jsx(Ke,{}),"Add new account"]})}),y&&e.jsx(ji,{children:e.jsxs(ki,{onClick:$,children:[e.jsx(Et,{}),"Sign out of all accounts"]})})]})]})})}),document.body),e.jsx(Ul,{isOpen:h.isOpen,onClose:h.close})]})})},yv=l.div`
4265
4265
  padding: var(--space-md) var(--space-lg);
4266
4266
  background: ${t=>t.$unread?"var(--color-background-hover)":"transparent"};
4267
4267
  transition: all 0.2s ease;
@@ -4777,7 +4777,7 @@ cursor: pointer;
4777
4777
  &:hover {
4778
4778
  color: var(--color-primary-hover);
4779
4779
  }
4780
- `,d1=({onAccountSelect:t,showAddAccount:r=!0})=>{var C,w,j,x,I;const{session:o,loading:n,switchSignIn:s,signOut:a}=Be(),{deployment:h}=ve(),{navigateToSignIn:f,navigate:c}=Ve(),[p,d]=i.useState(null),[u,g]=i.useState(null),m=o==null?void 0:o.active_signin,v=(o==null?void 0:o.signins)||[],y=((w=(C=h==null?void 0:h.auth_settings)==null?void 0:C.multi_session_support)==null?void 0:w.enabled)??!1;i.useEffect(()=>{n||v.length||f()},[n,v,f]);const S=k=>k.split(" ").map(R=>R[0]).join("").toUpperCase().slice(0,2),E=async k=>{var R;if(!(k===(m==null?void 0:m.id)||u)){g(k);try{if(await s(k),t)t(k),g(null);else{let _=new URLSearchParams(window.location.search).get("redirect_uri");if(_||(_=(R=h.ui_settings)==null?void 0:R.after_signin_redirect_url),_){const O=new URL(_);(h==null?void 0:h.mode)==="staging"&&O.searchParams.set("dev_session",localStorage.getItem("__dev_session__")??""),c(O.toString())}else g(null)}}catch(_){console.error("Failed to switch account:",_),g(null)}}},b=async(k,R)=>{k.stopPropagation(),d(R);try{await a(R)}catch(_){console.error("Failed to sign out:",_)}finally{d(null)}},$=()=>{var R;let k=new URLSearchParams(window.location.search).get("redirect_uri");k||(k=(R=h.ui_settings)==null?void 0:R.after_signin_redirect_url),f(k)};return n?e.jsx(ue,{children:e.jsxs(_i,{children:[e.jsx(Re,{}),e.jsxs(Si,{children:[e.jsx($i,{children:"Choose an account"}),e.jsxs(zi,{children:["to continue to ",((j=h==null?void 0:h.ui_settings)==null?void 0:j.app_name)||"App"]})]}),e.jsx(Ci,{children:[1,2].map(k=>e.jsxs(a1,{children:[e.jsx(s1,{}),e.jsxs(i1,{children:[e.jsx(Ei,{}),e.jsx(Ei,{$width:"small"})]})]},k))})]})}):v.length?e.jsx(ue,{children:e.jsxs(_i,{children:[e.jsx(Re,{}),e.jsxs(Si,{children:[e.jsx($i,{children:"Choose an account"}),e.jsxs(zi,{children:["to continue to ",(x=h==null?void 0:h.ui_settings)==null?void 0:x.app_name]})]}),e.jsxs(Ci,{children:[v.map(({user:k,id:R})=>{var z,T,M,F,G;if(!k)return null;const _=R===(m==null?void 0:m.id),O=u===R,P=`${k.first_name||""} ${k.last_name||""}`.trim();return e.jsxs(Xv,{$isActive:_,$isSwitching:O,onClick:()=>E(R),children:[e.jsx(Jv,{children:k.has_profile_picture?e.jsx("img",{src:k.profile_picture_url,alt:P}):S(P||((z=k.primary_email_address)==null?void 0:z.email)||((T=k.primary_phone_number)==null?void 0:T.phone_number)||k.username||"U")}),e.jsxs(e1,{children:[e.jsx(t1,{children:P||((M=k.primary_email_address)==null?void 0:M.email)||((F=k.primary_phone_number)==null?void 0:F.phone_number)||k.username||"User"}),e.jsx(r1,{children:((G=k.primary_email_address)==null?void 0:G.email)||k.username})]}),!O&&e.jsxs(o1,{onClick:L=>b(L,R),$isLoading:p===R,disabled:p===R,children:[p===R?e.jsx(Pt,{size:12}):e.jsx(zt,{size:12}),p===R?"Signing out...":"Sign out"]})]},R)}),r&&y&&e.jsxs(n1,{onClick:$,children:[e.jsx(Ke,{}),"Add another account"]})]}),e.jsxs(c1,{children:["Don't have an account?"," ",e.jsx(l1,{children:e.jsx(ot,{to:`${(I=h.ui_settings)==null?void 0:I.sign_up_page_url}${window.location.search}`,children:"Sign up"})})]})]})}):null},u1=()=>{const{navigateToSignIn:t}=Ve();return i.useEffect(()=>{t()},[t]),null},p1=()=>{const{navigateToSignUp:t}=Ve();return i.useEffect(()=>{t()},[t]),null},h1=l.div`
4780
+ `,d1=({onAccountSelect:t,showAddAccount:r=!0})=>{var C,w,j,x,I;const{session:o,loading:n,switchSignIn:s,signOut:a}=Be(),{deployment:h}=ve(),{navigateToSignIn:f,navigate:c}=Ve(),[p,d]=i.useState(null),[u,g]=i.useState(null),m=o==null?void 0:o.active_signin,v=(o==null?void 0:o.signins)||[],y=((w=(C=h==null?void 0:h.auth_settings)==null?void 0:C.multi_session_support)==null?void 0:w.enabled)??!1;i.useEffect(()=>{n||v.length||f()},[n,v,f]);const S=k=>k.split(" ").map(R=>R[0]).join("").toUpperCase().slice(0,2),E=async k=>{var R;if(!(k===(m==null?void 0:m.id)||u)){g(k);try{if(await s(k),t)t(k),g(null);else{let _=new URLSearchParams(window.location.search).get("redirect_uri");if(_||(_=(R=h.ui_settings)==null?void 0:R.after_signin_redirect_url),_){const O=new URL(_);(h==null?void 0:h.mode)==="staging"&&O.searchParams.set("dev_session",localStorage.getItem("__dev_session__")??""),c(O.toString())}else g(null)}}catch(_){console.error("Failed to switch account:",_),g(null)}}},b=async(k,R)=>{k.stopPropagation(),d(R);try{await a(R)}catch(_){console.error("Failed to sign out:",_)}finally{d(null)}},$=()=>{var R;let k=new URLSearchParams(window.location.search).get("redirect_uri");k||(k=(R=h.ui_settings)==null?void 0:R.after_signin_redirect_url),f(k)};return n?e.jsx(ue,{children:e.jsxs(_i,{children:[e.jsx(Re,{}),e.jsxs(Si,{children:[e.jsx($i,{children:"Choose an account"}),e.jsxs(zi,{children:["to continue to ",((j=h==null?void 0:h.ui_settings)==null?void 0:j.app_name)||"App"]})]}),e.jsx(Ci,{children:[1,2].map(k=>e.jsxs(a1,{children:[e.jsx(s1,{}),e.jsxs(i1,{children:[e.jsx(Ei,{}),e.jsx(Ei,{$width:"small"})]})]},k))})]})}):v.length?e.jsx(ue,{children:e.jsxs(_i,{children:[e.jsx(Re,{}),e.jsxs(Si,{children:[e.jsx($i,{children:"Choose an account"}),e.jsxs(zi,{children:["to continue to ",(x=h==null?void 0:h.ui_settings)==null?void 0:x.app_name]})]}),e.jsxs(Ci,{children:[v.map(({user:k,id:R})=>{var z,T,M,F,G;if(!k)return null;const _=R===(m==null?void 0:m.id),O=u===R,P=`${k.first_name||""} ${k.last_name||""}`.trim();return e.jsxs(Xv,{$isActive:_,$isSwitching:O,onClick:()=>E(R),children:[e.jsx(Jv,{children:k.has_profile_picture?e.jsx("img",{src:k.profile_picture_url,alt:P}):S(P||((z=k.primary_email_address)==null?void 0:z.email)||((T=k.primary_phone_number)==null?void 0:T.phone_number)||k.username||"U")}),e.jsxs(e1,{children:[e.jsx(t1,{children:P||((M=k.primary_email_address)==null?void 0:M.email)||((F=k.primary_phone_number)==null?void 0:F.phone_number)||k.username||"User"}),e.jsx(r1,{children:((G=k.primary_email_address)==null?void 0:G.email)||k.username})]}),!O&&e.jsxs(o1,{onClick:L=>b(L,R),$isLoading:p===R,disabled:p===R,children:[p===R?e.jsx(vt,{size:12}):e.jsx(Et,{size:12}),p===R?"Signing out...":"Sign out"]})]},R)}),r&&y&&e.jsxs(n1,{onClick:$,children:[e.jsx(Ke,{}),"Add another account"]})]}),e.jsxs(c1,{children:["Don't have an account?"," ",e.jsx(l1,{children:e.jsx(ot,{to:`${(I=h.ui_settings)==null?void 0:I.sign_up_page_url}${window.location.search}`,children:"Sign up"})})]})]})}):null},u1=()=>{const{navigateToSignIn:t}=Ve();return i.useEffect(()=>{t()},[t]),null},p1=()=>{const{navigateToSignUp:t}=Ve();return i.useEffect(()=>{t()},[t]),null},h1=l.div`
4781
4781
  width: 100%;
4782
4782
  height: 500px;
4783
4783
  background: var(--color-background);
@@ -4985,10 +4985,10 @@ cursor: pointer;
4985
4985
  margin: 0 auto;
4986
4986
  padding: 6px 16px;
4987
4987
  font-size: 13px;
4988
- `,_1=()=>{var _,O;const{organizationMemberships:t,refetch:r,loading:o}=vt(),{workspaces:n}=bt(),{switchOrganization:s,switchWorkspace:a}=Be(),{deployment:h}=ve(),[f,c]=i.useState(null),[p,d]=i.useState("orgList"),[u,g]=i.useState(null),m=(h==null?void 0:h.b2b_settings.workspaces_enabled)??!1,v=(h==null?void 0:h.b2b_settings.allow_users_to_create_orgs)??!1,y=i.useRef(!1);i.useEffect(()=>{if(!(y.current||!t)){if(y.current=!0,t.length===0){d("createOrg");return}if(!m){d("orgList");return}if(!n||n.length===0){t[0]&&g(t[0].organization.id),d("createWorkspace");return}d("orgList")}},[t,n,m]),console.log("view mode",p,m);const S=P=>P.split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2),E=async P=>{if(m){g(P.id),d("workspaceList");return}c(P.id);try{await s(P.id)}finally{c(null)}},b=async P=>{c(P.id);try{await a(P.id)}finally{c(null)}},$=async P=>{await r(),m&&P&&(g(P.id),d("createWorkspace"))},C=()=>{},w=async()=>{g(null),d("orgList")},j=(_=t==null?void 0:t.find(P=>P.organization.id===u))==null?void 0:_.organization,x=u?n==null?void 0:n.filter(P=>P.organization.id===u):[];if(o)return null;if(p==="createOrg")return e.jsx(_e.Body,{style:{padding:0},children:e.jsx(nn,{onSuccess:$,onCancel:()=>d("orgList")})});if(p==="createWorkspace"&&u)return e.jsx(_e.Body,{style:{padding:0},children:e.jsx($a,{organizationId:u,onSuccess:C,onCancel:()=>d("workspaceList"),onCreateOrganization:()=>d("createOrg")})});const I=p==="workspaceList",k=I?"Select a workspace":"Select an organization",R=I?`Choose a workspace in ${(j==null?void 0:j.name)||""}`:`to continue to ${((O=h==null?void 0:h.ui_settings)==null?void 0:O.app_name)||"App"}`;return e.jsxs(h1,{children:[e.jsxs(f1,{children:[e.jsxs("div",{children:[e.jsx(Re,{}),e.jsxs(y1,{children:[e.jsx(w1,{children:k}),e.jsx(j1,{children:R})]})]}),e.jsx(Pa,{showName:!0})]}),e.jsxs(g1,{children:[e.jsxs(m1,{children:[e.jsxs(x1,{children:[e.jsx(v1,{children:I?"Workspaces":"Your organizations"}),I&&e.jsxs(b1,{onClick:w,children:[e.jsx(Ur,{}),"Go back"]})]}),e.jsx(k1,{children:I?e.jsx(e.Fragment,{children:x&&x.length>0?x.map(P=>{var T,M,F;const z=((T=P.eligibility_restriction)==null?void 0:T.type)!=="none"&&((M=P.eligibility_restriction)==null?void 0:M.type)!==void 0;return e.jsxs(Pi,{onClick:()=>!z&&b(P),disabled:f===P.id||z,style:{opacity:z?.7:1},children:[e.jsx(Ri,{children:P.image_url?e.jsx(Ii,{src:P.image_url,alt:P.name}):S(P.name).charAt(0)}),e.jsxs(Ti,{children:[e.jsx(Oi,{children:P.name}),e.jsxs(Mi,{children:[e.jsx(Bo,{}),"Workspace"]})]}),e.jsx(Li,{children:e.jsx(fa,{})}),z&&e.jsxs(Ai,{children:[e.jsx(dt,{size:14}),(F=P.eligibility_restriction)==null?void 0:F.message]})]},P.id)}):e.jsxs(Di,{children:[e.jsx(Fi,{children:"No workspaces yet"}),e.jsxs(Ni,{children:["Create your first workspace for"," ",(j==null?void 0:j.name)||"this organization"]}),e.jsxs(Bi,{onClick:()=>d("createWorkspace"),children:[e.jsx(Ke,{}),"Create workspace"]})]})}):t&&t.length>0?t.map(P=>{var te,U,K;const z=P.organization,T=n==null?void 0:n.filter(ee=>ee.organization.id===z.id),M=(T==null?void 0:T.length)||0,F=z.member_count,G=P.roles[0].name,L=P.roles.length-1,A=L>0?`${G.charAt(0).toUpperCase()+G.slice(1)} +${L}`:G.charAt(0).toUpperCase()+G.slice(1),se=((te=P.eligibility_restriction)==null?void 0:te.type)!=="none"&&((U=P.eligibility_restriction)==null?void 0:U.type)!==void 0;return e.jsxs(Pi,{onClick:()=>!se&&E(z),disabled:f===z.id||se,style:{opacity:se?.7:1},children:[e.jsx(Ri,{children:z.image_url?e.jsx(Ii,{src:z.image_url,alt:z.name}):S(z.name)}),e.jsxs(Ti,{children:[e.jsx(Oi,{children:z.name}),e.jsx(Mi,{children:m?e.jsxs(e.Fragment,{children:[e.jsx(Bo,{}),M," workspace",M!==1?"s":""]}):e.jsxs(e.Fragment,{children:[e.jsx($p,{}),A," • ",F," member",F!==1?"s":""]})})]}),e.jsx(Li,{children:e.jsx(fa,{})}),se&&e.jsxs(Ai,{children:[e.jsx(dt,{size:14}),(K=P.eligibility_restriction)==null?void 0:K.message]})]},z.id)}):e.jsxs(Di,{children:[e.jsx(Fi,{children:"No organizations yet"}),e.jsx(Ni,{children:v?"Create your first organization to get started":"You don't have access to any organizations yet"}),v&&e.jsxs(Bi,{onClick:()=>d("createOrg"),children:[e.jsx(Ke,{}),"Create organization"]})]})})]}),I&&x&&x.length>0&&e.jsxs(X,{style:{marginTop:"var(--space-md)"},onClick:()=>d("createWorkspace"),disabled:f!==null,children:[e.jsx(Ke,{size:12}),"Create new workspace"]}),!I&&t&&t.length>0&&v&&e.jsxs(X,{style:{marginTop:"var(--space-md)"},onClick:()=>d("createOrg"),disabled:f!==null,children:[e.jsx(Ke,{size:12}),"Create new organization"]})]})]})},C1=l(_e.Content)`
4988
+ `,_1=()=>{var _,O;const{organizationMemberships:t,refetch:r,loading:o}=bt(),{workspaces:n}=yt(),{switchOrganization:s,switchWorkspace:a}=Be(),{deployment:h}=ve(),[f,c]=i.useState(null),[p,d]=i.useState("orgList"),[u,g]=i.useState(null),m=(h==null?void 0:h.b2b_settings.workspaces_enabled)??!1,v=(h==null?void 0:h.b2b_settings.allow_users_to_create_orgs)??!1,y=i.useRef(!1);i.useEffect(()=>{if(!(y.current||!t)){if(y.current=!0,t.length===0){d("createOrg");return}if(!m){d("orgList");return}if(!n||n.length===0){t[0]&&g(t[0].organization.id),d("createWorkspace");return}d("orgList")}},[t,n,m]),console.log("view mode",p,m);const S=P=>P.split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2),E=async P=>{if(m){g(P.id),d("workspaceList");return}c(P.id);try{await s(P.id)}finally{c(null)}},b=async P=>{c(P.id);try{await a(P.id)}finally{c(null)}},$=async P=>{await r(),m&&P&&(g(P.id),d("createWorkspace"))},C=()=>{},w=async()=>{g(null),d("orgList")},j=(_=t==null?void 0:t.find(P=>P.organization.id===u))==null?void 0:_.organization,x=u?n==null?void 0:n.filter(P=>P.organization.id===u):[];if(o)return null;if(p==="createOrg")return e.jsx(_e.Body,{style:{padding:0},children:e.jsx(nn,{onSuccess:$,onCancel:()=>d("orgList")})});if(p==="createWorkspace"&&u)return e.jsx(_e.Body,{style:{padding:0},children:e.jsx($a,{organizationId:u,onSuccess:C,onCancel:()=>d("workspaceList"),onCreateOrganization:()=>d("createOrg")})});const I=p==="workspaceList",k=I?"Select a workspace":"Select an organization",R=I?`Choose a workspace in ${(j==null?void 0:j.name)||""}`:`to continue to ${((O=h==null?void 0:h.ui_settings)==null?void 0:O.app_name)||"App"}`;return e.jsxs(h1,{children:[e.jsxs(f1,{children:[e.jsxs("div",{children:[e.jsx(Re,{}),e.jsxs(y1,{children:[e.jsx(w1,{children:k}),e.jsx(j1,{children:R})]})]}),e.jsx(Pa,{showName:!0})]}),e.jsxs(g1,{children:[e.jsxs(m1,{children:[e.jsxs(x1,{children:[e.jsx(v1,{children:I?"Workspaces":"Your organizations"}),I&&e.jsxs(b1,{onClick:w,children:[e.jsx(Ur,{}),"Go back"]})]}),e.jsx(k1,{children:I?e.jsx(e.Fragment,{children:x&&x.length>0?x.map(P=>{var T,M,F;const z=((T=P.eligibility_restriction)==null?void 0:T.type)!=="none"&&((M=P.eligibility_restriction)==null?void 0:M.type)!==void 0;return e.jsxs(Pi,{onClick:()=>!z&&b(P),disabled:f===P.id||z,style:{opacity:z?.7:1},children:[e.jsx(Ri,{children:P.image_url?e.jsx(Ii,{src:P.image_url,alt:P.name}):S(P.name).charAt(0)}),e.jsxs(Ti,{children:[e.jsx(Oi,{children:P.name}),e.jsxs(Mi,{children:[e.jsx(Bo,{}),"Workspace"]})]}),e.jsx(Li,{children:e.jsx(fa,{})}),z&&e.jsxs(Ai,{children:[e.jsx(dt,{size:14}),(F=P.eligibility_restriction)==null?void 0:F.message]})]},P.id)}):e.jsxs(Di,{children:[e.jsx(Fi,{children:"No workspaces yet"}),e.jsxs(Ni,{children:["Create your first workspace for"," ",(j==null?void 0:j.name)||"this organization"]}),e.jsxs(Bi,{onClick:()=>d("createWorkspace"),children:[e.jsx(Ke,{}),"Create workspace"]})]})}):t&&t.length>0?t.map(P=>{var te,U,K;const z=P.organization,T=n==null?void 0:n.filter(ee=>ee.organization.id===z.id),M=(T==null?void 0:T.length)||0,F=z.member_count,G=P.roles[0].name,L=P.roles.length-1,A=L>0?`${G.charAt(0).toUpperCase()+G.slice(1)} +${L}`:G.charAt(0).toUpperCase()+G.slice(1),se=((te=P.eligibility_restriction)==null?void 0:te.type)!=="none"&&((U=P.eligibility_restriction)==null?void 0:U.type)!==void 0;return e.jsxs(Pi,{onClick:()=>!se&&E(z),disabled:f===z.id||se,style:{opacity:se?.7:1},children:[e.jsx(Ri,{children:z.image_url?e.jsx(Ii,{src:z.image_url,alt:z.name}):S(z.name)}),e.jsxs(Ti,{children:[e.jsx(Oi,{children:z.name}),e.jsx(Mi,{children:m?e.jsxs(e.Fragment,{children:[e.jsx(Bo,{}),M," workspace",M!==1?"s":""]}):e.jsxs(e.Fragment,{children:[e.jsx($p,{}),A," • ",F," member",F!==1?"s":""]})})]}),e.jsx(Li,{children:e.jsx(fa,{})}),se&&e.jsxs(Ai,{children:[e.jsx(dt,{size:14}),(K=P.eligibility_restriction)==null?void 0:K.message]})]},z.id)}):e.jsxs(Di,{children:[e.jsx(Fi,{children:"No organizations yet"}),e.jsx(Ni,{children:v?"Create your first organization to get started":"You don't have access to any organizations yet"}),v&&e.jsxs(Bi,{onClick:()=>d("createOrg"),children:[e.jsx(Ke,{}),"Create organization"]})]})})]}),I&&x&&x.length>0&&e.jsxs(X,{style:{marginTop:"var(--space-md)"},onClick:()=>d("createWorkspace"),disabled:f!==null,children:[e.jsx(Ke,{size:12}),"Create new workspace"]}),!I&&t&&t.length>0&&v&&e.jsxs(X,{style:{marginTop:"var(--space-md)"},onClick:()=>d("createOrg"),disabled:f!==null,children:[e.jsx(Ke,{size:12}),"Create new organization"]})]})]})},C1=l(_e.Content)`
4989
4989
  padding: 0;
4990
4990
  max-width: 90vw;
4991
- `,S1=({children:t})=>{var y,S,E,b;const{loading:r,session:o}=Be(),{activeOrganization:n}=qe(),{activeWorkspace:s,loading:a}=Rt(),{workspaces:h}=bt(),{deployment:f}=ve(),{organizationMemberships:c}=vt(),p=(f==null?void 0:f.b2b_settings.workspaces_enabled)??!1,d=c==null?void 0:c.find($=>$.organization.id===(n==null?void 0:n.id)),u=h==null?void 0:h.find($=>{var C;return $.id===((C=o==null?void 0:o.active_signin)==null?void 0:C.active_workspace_membership_id)}),g=((y=d==null?void 0:d.eligibility_restriction)==null?void 0:y.type)!=="none"&&((S=d==null?void 0:d.eligibility_restriction)==null?void 0:S.type)!==void 0,m=((E=u==null?void 0:u.eligibility_restriction)==null?void 0:E.type)!=="none"&&((b=u==null?void 0:u.eligibility_restriction)==null?void 0:b.type)!==void 0;return r||p&&a?null:(g||m||!n?!1:p?s?h==null?void 0:h.some(C=>C.id===s.id&&C.organization.id===n.id):!1:!0)?(console.log("valid"),e.jsx(e.Fragment,{children:t})):e.jsx(ue,{children:e.jsx(_e,{isOpen:!0,children:e.jsx(_e.Overlay,{children:e.jsx(C1,{style:{width:"850px"},children:e.jsx(_1,{})})})})})},$1=l.div`
4991
+ `,S1=({children:t})=>{var y,S,E,b;const{loading:r,session:o}=Be(),{activeOrganization:n}=qe(),{activeWorkspace:s,loading:a}=Rt(),{workspaces:h}=yt(),{deployment:f}=ve(),{organizationMemberships:c}=bt(),p=(f==null?void 0:f.b2b_settings.workspaces_enabled)??!1,d=c==null?void 0:c.find($=>$.organization.id===(n==null?void 0:n.id)),u=h==null?void 0:h.find($=>{var C;return $.id===((C=o==null?void 0:o.active_signin)==null?void 0:C.active_workspace_membership_id)}),g=((y=d==null?void 0:d.eligibility_restriction)==null?void 0:y.type)!=="none"&&((S=d==null?void 0:d.eligibility_restriction)==null?void 0:S.type)!==void 0,m=((E=u==null?void 0:u.eligibility_restriction)==null?void 0:E.type)!=="none"&&((b=u==null?void 0:u.eligibility_restriction)==null?void 0:b.type)!==void 0;return r||p&&a?null:(g||m||!n?!1:p?s?h==null?void 0:h.some(C=>C.id===s.id&&C.organization.id===n.id):!1:!0)?(console.log("valid"),e.jsx(e.Fragment,{children:t})):e.jsx(ue,{children:e.jsx(_e,{isOpen:!0,children:e.jsx(_e.Overlay,{children:e.jsx(C1,{style:{width:"850px"},children:e.jsx(_1,{})})})})})},$1=l.div`
4992
4992
  display: flex;
4993
4993
  gap: 8px;
4994
4994
  flex-wrap: wrap;
@@ -5670,7 +5670,7 @@ cursor: pointer;
5670
5670
  &:hover .expand-icon {
5671
5671
  opacity: 1;
5672
5672
  }
5673
- `,u2=({isOpen:t,imageUrl:r,zoomLevel:o,dragPosition:n,isDragging:s,onClose:a,onDownload:h,onZoom:f,onReset:c,onWheel:p,onMouseDown:d,onMouseMove:u,onMouseUp:g})=>{const[m,v]=i.useState(!1),y=i.useRef(null);return i.useEffect(()=>(v(!0),()=>v(!1)),[]),i.useEffect(()=>{if(t){const S=document.body.style.overflow;document.body.style.overflow="hidden";const E=C=>{(C.ctrlKey||C.metaKey)&&C.preventDefault()},b=C=>{C.preventDefault()},$=C=>{C.preventDefault()};return document.addEventListener("wheel",E,{passive:!1}),document.addEventListener("gesturestart",b,{passive:!1}),document.addEventListener("gesturechange",$,{passive:!1}),()=>{document.body.style.overflow=S,document.removeEventListener("wheel",E),document.removeEventListener("gesturestart",b),document.removeEventListener("gesturechange",$)}}},[t]),!m||!t||!r?null:Nr.createPortal(e.jsx(ue,{children:e.jsx(n2,{ref:y,$isOpen:!0,onClick:S=>{S.target===S.currentTarget&&a()},children:e.jsxs(a2,{onClick:S=>S.stopPropagation(),onWheel:S=>{S.preventDefault(),S.stopPropagation(),p(S)},onMouseMove:u,onMouseUp:g,onMouseLeave:g,children:[e.jsx(s2,{src:r,alt:"Preview",$zoom:o,$x:n.x,$y:n.y,$isDragging:s,onMouseDown:d,draggable:!1}),e.jsx($o,{$variant:"ghost",onClick:a,title:"Close",style:{position:"absolute",top:"16px",right:"16px",background:"var(--color-background)",border:"1px solid var(--color-border)"},children:e.jsx(Ze,{size:14})}),e.jsxs(i2,{children:[e.jsxs(c2,{children:[e.jsx($o,{$variant:"ghost",onClick:()=>f(-.25),title:"Zoom out",disabled:o<=.5,children:e.jsx(vh,{size:14})}),e.jsxs(l2,{children:[Math.round(o*100),"%"]}),e.jsx($o,{$variant:"ghost",onClick:()=>f(.25),title:"Zoom in",disabled:o>=3,children:e.jsx(mh,{size:14})}),e.jsx($o,{$variant:"ghost",onClick:c,title:"Reset zoom",children:e.jsx(Kp,{size:14})})]}),e.jsxs(Zl,{$variant:"primary",onClick:h,title:"Download image",children:[e.jsx(tn,{size:14}),"Download"]})]})]})})}),document.body)};function Ql({showBackButton:t=!1,onBack:r}){const{agentName:o,token:n,platformAdapter:s,selectedSession:a,selectSession:h}=Ho(),f=a==null?void 0:a.id;if(!f)return e.jsx(ue,{style:{height:"100%",width:"100%"},children:e.jsx(Ui,{children:e.jsxs(Wi,{children:[e.jsx(bn,{size:48,strokeWidth:1.5}),e.jsx("p",{children:"No conversation selected"})]})})});const c=!0,p=!0,d="Start a conversation by typing a message below",[u,g]=i.useState(""),[m,v]=i.useState(!1),[y,S]=i.useState(null),[E,b]=i.useState([]),[$,C]=i.useState([]),[w,j]=i.useState(null),[x,I]=i.useState(1),[k,R]=i.useState(!1),[_,O]=i.useState({x:0,y:0}),[P,z]=i.useState({x:0,y:0}),T=i.useRef(null),M=i.useRef(null),{messages:F,pendingMessage:G,pendingImages:L,connectionState:A,isConnected:se,isExecuting:te,executionStatus:U,isWaitingForInput:K,sendMessage:ee,submitUserInput:J,cancelExecution:ie}=hc({contextId:f,agentName:o,token:n,platformAdapter:s,autoConnect:c});i.useEffect(()=>{var N;(N=T.current)==null||N.scrollIntoView({behavior:"smooth"})},[F]),i.useEffect(()=>{var N;if(K){const W=F.slice().reverse().find(fe=>{var ye;return((ye=fe.metadata)==null?void 0:ye.type)==="user_input_request"});(N=W==null?void 0:W.metadata)!=null&&N.userInputRequest&&S(W.metadata.userInputRequest)}else S(null),b([])},[K,F]);const oe=N=>{if(N.preventDefault(),!!se)if(K&&y){let W=u.trim();y.input_type==="multiselect"&&(W=E.join(",")),W&&(J(W),g(""),b([]))}else!te&&u.trim()&&(ee(u,$.length>0?$:void 0),g(""),C([]))},de=N=>{const W=N.target.files;W&&(Array.from(W).forEach(fe=>{if(fe.type.startsWith("image/")){const ye=new FileReader;ye.onload=re=>{var je;if((je=re.target)!=null&&je.result){const Se=re.target.result.split(",")[1];C(Me=>[...Me,{mime_type:fe.type,data:Se}])}},ye.readAsDataURL(fe)}}),M.current&&(M.current.value=""))},Q=N=>{C(W=>W.filter((fe,ye)=>ye!==N))},ce=N=>{j(N),I(1),O({x:0,y:0})},B=()=>{j(null),I(1),O({x:0,y:0}),R(!1)},V=N=>{const W=document.createElement("a");W.href=N,W.download=`image-${Date.now()}.png`,document.body.appendChild(W),W.click(),document.body.removeChild(W)},D=N=>{I(W=>{const fe=W+N;return Math.min(Math.max(fe,.5),3)})},le=N=>{N.preventDefault(),N.stopPropagation();const W=N.deltaY>0?-.1:.1;D(W)},H=N=>{x>1&&(R(!0),z({x:N.clientX-_.x,y:N.clientY-_.y}))},ae=N=>{k&&x>1&&O({x:N.clientX-P.x,y:N.clientY-P.y})},ke=()=>{R(!1)},ne=()=>A.status===mt.CONNECTING?"Connecting...":A.status===mt.ERROR?"Connection error":A.status===mt.DISCONNECTED||!se?"Disconnected":K?"Waiting for your input...":te?"Working...":"Ready",Y=()=>{if(!K||!y)return"Ask anything";switch(y.input_type){case"select":case"boolean":case"date":return"Use controls above to make selection";case"multiselect":return"Select options above";default:return"Enter your response..."}},Z=()=>!K||!y?!1:["select","multiselect","boolean","date"].includes(y.input_type||"");return e.jsxs(ue,{style:{height:"100%",width:"100%"},children:[e.jsxs(Ui,{children:[e.jsxs(I1,{children:[e.jsxs(T1,{children:[t&&e.jsx(O1,{onClick:()=>{r?r():h(null)},children:e.jsx(Ur,{size:20})}),e.jsxs(M1,{children:[e.jsx(L1,{children:e.jsx(bn,{size:20})}),e.jsxs(A1,{children:[e.jsx(F1,{children:o}),e.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[e.jsx(D1,{$status:ne()}),e.jsx(N1,{$status:ne(),children:ne()})]})]})]})]}),U!==Ae.IDLE&&e.jsx(B1,{$status:U,children:U.replace("_"," ")})]}),e.jsx(U1,{children:F.length===0&&p?e.jsxs(Wi,{children:[e.jsx(bn,{size:48,strokeWidth:1.5}),e.jsx("p",{children:d})]}):e.jsxs(e.Fragment,{children:[F.map((N,W)=>{var fe,ye,re,je;if(((fe=N.metadata)==null?void 0:fe.type)==="user_input_request"&&N.metadata.userInputRequest){const me=N.metadata.userInputRequest,Se=!me.input_type||me.input_type==="text"||me.input_type==="number",Me=K&&(y==null?void 0:y.input_type)===me.input_type;return e.jsx(qn,{$isUser:!1,children:e.jsxs(H1,{children:[e.jsx("div",{className:"question",children:me.question}),me.context&&me.context.trim()&&e.jsx("div",{className:"context",children:me.context}),!Se&&e.jsxs("div",{className:"controls",children:[me.input_type==="select"&&me.options&&e.jsxs("select",{value:Me?u:"",onChange:Ie=>g(Ie.target.value),disabled:!Me,children:[e.jsx("option",{value:"",children:"Choose an option..."}),me.options.map(Ie=>e.jsx("option",{value:Ie,children:Ie},Ie))]}),me.input_type==="multiselect"&&me.options&&e.jsx("div",{className:"checkbox-group",children:me.options.map(Ie=>e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:Me&&E.includes(Ie),onChange:nr=>{nr.target.checked?b([...E,Ie]):b(E.filter(ar=>ar!==Ie))},disabled:!Me}),e.jsx("span",{children:Ie})]},Ie))}),me.input_type==="boolean"&&e.jsxs("div",{className:"radio-group",children:[e.jsxs("label",{className:"radio-label",children:[e.jsx("input",{type:"radio",name:"boolean",value:"true",checked:Me&&u==="true",onChange:Ie=>g(Ie.target.value),disabled:!Me}),e.jsx("span",{children:"Yes"})]}),e.jsxs("label",{className:"radio-label",children:[e.jsx("input",{type:"radio",name:"boolean",value:"false",checked:Me&&u==="false",onChange:Ie=>g(Ie.target.value),disabled:!Me}),e.jsx("span",{children:"No"})]})]}),me.input_type==="date"&&e.jsx("input",{type:"date",value:Me?u:"",onChange:Ie=>g(Ie.target.value),disabled:!Me})]}),e.jsx("div",{className:"instruction",children:Me?Se?"Type your response below":me.input_type==="multiselect"?"Select options above and click send":"Make your selection above and click send":""})]})},N.id)}if(((ye=N.metadata)==null?void 0:ye.type)==="log"){const me=F[W-1],Se=F[W+1],Me=((re=me==null?void 0:me.metadata)==null?void 0:re.type)==="log",Ie=((je=Se==null?void 0:Se.metadata)==null?void 0:je.type)==="log",nr=Me||Ie,ar=!Me&&Ie,qr=Me&&!Ie;return e.jsx(G1,{$isGrouped:nr,$isFirstInGroup:ar,$isLastInGroup:qr,children:e.jsx("div",{className:"log-content",children:N.content})},N.id)}return!N.content&&(!N.images||N.images.length===0)?null:e.jsx(qn,{$isUser:N.role==="user",children:e.jsxs(Yl,{$isUser:N.role==="user",children:[e.jsx("div",{children:N.content}),N.images&&N.images.length>0&&e.jsx("div",{style:{display:"flex",gap:"8px",marginTop:"8px",flexWrap:"wrap"},children:N.images.map((me,Se)=>{const Me=me.url||`data:${me.mime_type};base64,${me.data}`;return e.jsxs(d2,{onClick:()=>ce(Me),title:"Click to preview",children:[e.jsx("img",{src:Me,alt:`Image ${Se+1}`,loading:"lazy"}),e.jsx("div",{className:"expand-icon",children:e.jsx(Fp,{size:14})})]},Se)})}),N.isStreaming&&e.jsx(W1,{})]})},N.id)}),G&&e.jsx(qn,{$isUser:!0,children:e.jsxs(V1,{$isUser:!0,children:[e.jsx("div",{children:G}),L&&L.length>0&&e.jsx("div",{style:{display:"flex",gap:"8px",marginTop:"8px",flexWrap:"wrap"},children:L.map((N,W)=>e.jsx("div",{style:{width:"200px",height:"200px",borderRadius:"8px",border:"1px solid var(--color-border)",overflow:"hidden",backgroundColor:"var(--color-background-subtle)",position:"relative",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx("img",{src:N.data?`data:${N.mime_type};base64,${N.data}`:"#",alt:`Image ${W+1}`,style:{maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",objectFit:"contain"},loading:"lazy"})},W))})]})}),e.jsx("div",{ref:T})]})}),$.length>0&&e.jsx(X1,{children:$.map((N,W)=>e.jsxs(J1,{children:[e.jsx("img",{src:N.data?`data:${N.mime_type};base64,${N.data}`:"#",alt:`Upload ${W+1}`}),e.jsx(e2,{type:"button",onClick:()=>Q(W),children:e.jsx(Ze,{size:12})})]},W))}),e.jsx(q1,{onSubmit:oe,children:e.jsxs(Y1,{children:[e.jsxs(Z1,{children:[e.jsx(Q1,{value:u,onChange:N=>g(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),oe(N))},placeholder:Y(),disabled:!se||te&&!K||Z(),rows:1}),e.jsx(K1,{children:e.jsxs(r2,{type:"button",disabled:!se||te,onClick:()=>{var N;return(N=M.current)==null?void 0:N.click()},children:[e.jsx(eh,{size:16}),"Attach"]})}),e.jsx(t2,{ref:M,type:"file",accept:"image/*",multiple:!0,onChange:de})]}),e.jsx(o2,{type:te?"button":"submit",disabled:!se||!K&&!te&&!u.trim(),onClick:te?ie:void 0,onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),style:{background:te&&m?"var(--color-error)":void 0},children:te?m?e.jsx(Ze,{size:14}):e.jsx(Pt,{size:14,className:"animate-spin"}):e.jsx(Wc,{size:14})})]})})]}),e.jsx(u2,{isOpen:!!w,imageUrl:w,zoomLevel:x,dragPosition:_,isDragging:k,onClose:B,onDownload:()=>w&&V(w),onZoom:D,onReset:()=>{I(1),O({x:0,y:0})},onWheel:le,onMouseDown:H,onMouseMove:ae,onMouseUp:ke})]})}const p2=l.div`
5673
+ `,u2=({isOpen:t,imageUrl:r,zoomLevel:o,dragPosition:n,isDragging:s,onClose:a,onDownload:h,onZoom:f,onReset:c,onWheel:p,onMouseDown:d,onMouseMove:u,onMouseUp:g})=>{const[m,v]=i.useState(!1),y=i.useRef(null);return i.useEffect(()=>(v(!0),()=>v(!1)),[]),i.useEffect(()=>{if(t){const S=document.body.style.overflow;document.body.style.overflow="hidden";const E=C=>{(C.ctrlKey||C.metaKey)&&C.preventDefault()},b=C=>{C.preventDefault()},$=C=>{C.preventDefault()};return document.addEventListener("wheel",E,{passive:!1}),document.addEventListener("gesturestart",b,{passive:!1}),document.addEventListener("gesturechange",$,{passive:!1}),()=>{document.body.style.overflow=S,document.removeEventListener("wheel",E),document.removeEventListener("gesturestart",b),document.removeEventListener("gesturechange",$)}}},[t]),!m||!t||!r?null:Nr.createPortal(e.jsx(ue,{children:e.jsx(n2,{ref:y,$isOpen:!0,onClick:S=>{S.target===S.currentTarget&&a()},children:e.jsxs(a2,{onClick:S=>S.stopPropagation(),onWheel:S=>{S.preventDefault(),S.stopPropagation(),p(S)},onMouseMove:u,onMouseUp:g,onMouseLeave:g,children:[e.jsx(s2,{src:r,alt:"Preview",$zoom:o,$x:n.x,$y:n.y,$isDragging:s,onMouseDown:d,draggable:!1}),e.jsx($o,{$variant:"ghost",onClick:a,title:"Close",style:{position:"absolute",top:"16px",right:"16px",background:"var(--color-background)",border:"1px solid var(--color-border)"},children:e.jsx(Ze,{size:14})}),e.jsxs(i2,{children:[e.jsxs(c2,{children:[e.jsx($o,{$variant:"ghost",onClick:()=>f(-.25),title:"Zoom out",disabled:o<=.5,children:e.jsx(vh,{size:14})}),e.jsxs(l2,{children:[Math.round(o*100),"%"]}),e.jsx($o,{$variant:"ghost",onClick:()=>f(.25),title:"Zoom in",disabled:o>=3,children:e.jsx(mh,{size:14})}),e.jsx($o,{$variant:"ghost",onClick:c,title:"Reset zoom",children:e.jsx(Kp,{size:14})})]}),e.jsxs(Zl,{$variant:"primary",onClick:h,title:"Download image",children:[e.jsx(tn,{size:14}),"Download"]})]})]})})}),document.body)};function Ql({showBackButton:t=!1,onBack:r}){const{agentName:o,token:n,platformAdapter:s,selectedSession:a,selectSession:h}=Ho(),f=a==null?void 0:a.id;if(!f)return e.jsx(ue,{style:{height:"100%",width:"100%"},children:e.jsx(Ui,{children:e.jsxs(Wi,{children:[e.jsx(bn,{size:48,strokeWidth:1.5}),e.jsx("p",{children:"No conversation selected"})]})})});const c=!0,p=!0,d="Start a conversation by typing a message below",[u,g]=i.useState(""),[m,v]=i.useState(!1),[y,S]=i.useState(null),[E,b]=i.useState([]),[$,C]=i.useState([]),[w,j]=i.useState(null),[x,I]=i.useState(1),[k,R]=i.useState(!1),[_,O]=i.useState({x:0,y:0}),[P,z]=i.useState({x:0,y:0}),T=i.useRef(null),M=i.useRef(null),{messages:F,pendingMessage:G,pendingImages:L,connectionState:A,isConnected:se,isExecuting:te,executionStatus:U,isWaitingForInput:K,sendMessage:ee,submitUserInput:J,cancelExecution:ie}=hc({contextId:f,agentName:o,token:n,platformAdapter:s,autoConnect:c});i.useEffect(()=>{var N;(N=T.current)==null||N.scrollIntoView({behavior:"smooth"})},[F]),i.useEffect(()=>{var N;if(K){const W=F.slice().reverse().find(fe=>{var ye;return((ye=fe.metadata)==null?void 0:ye.type)==="user_input_request"});(N=W==null?void 0:W.metadata)!=null&&N.userInputRequest&&S(W.metadata.userInputRequest)}else S(null),b([])},[K,F]);const oe=N=>{if(N.preventDefault(),!!se)if(K&&y){let W=u.trim();y.input_type==="multiselect"&&(W=E.join(",")),W&&(J(W),g(""),b([]))}else!te&&u.trim()&&(ee(u,$.length>0?$:void 0),g(""),C([]))},de=N=>{const W=N.target.files;W&&(Array.from(W).forEach(fe=>{if(fe.type.startsWith("image/")){const ye=new FileReader;ye.onload=re=>{var je;if((je=re.target)!=null&&je.result){const Se=re.target.result.split(",")[1];C(Me=>[...Me,{mime_type:fe.type,data:Se}])}},ye.readAsDataURL(fe)}}),M.current&&(M.current.value=""))},Q=N=>{C(W=>W.filter((fe,ye)=>ye!==N))},ce=N=>{j(N),I(1),O({x:0,y:0})},B=()=>{j(null),I(1),O({x:0,y:0}),R(!1)},V=N=>{const W=document.createElement("a");W.href=N,W.download=`image-${Date.now()}.png`,document.body.appendChild(W),W.click(),document.body.removeChild(W)},D=N=>{I(W=>{const fe=W+N;return Math.min(Math.max(fe,.5),3)})},le=N=>{N.preventDefault(),N.stopPropagation();const W=N.deltaY>0?-.1:.1;D(W)},H=N=>{x>1&&(R(!0),z({x:N.clientX-_.x,y:N.clientY-_.y}))},ae=N=>{k&&x>1&&O({x:N.clientX-P.x,y:N.clientY-P.y})},ke=()=>{R(!1)},ne=()=>A.status===mt.CONNECTING?"Connecting...":A.status===mt.ERROR?"Connection error":A.status===mt.DISCONNECTED||!se?"Disconnected":K?"Waiting for your input...":te?"Working...":"Ready",Y=()=>{if(!K||!y)return"Ask anything";switch(y.input_type){case"select":case"boolean":case"date":return"Use controls above to make selection";case"multiselect":return"Select options above";default:return"Enter your response..."}},Z=()=>!K||!y?!1:["select","multiselect","boolean","date"].includes(y.input_type||"");return e.jsxs(ue,{style:{height:"100%",width:"100%"},children:[e.jsxs(Ui,{children:[e.jsxs(I1,{children:[e.jsxs(T1,{children:[t&&e.jsx(O1,{onClick:()=>{r?r():h(null)},children:e.jsx(Ur,{size:20})}),e.jsxs(M1,{children:[e.jsx(L1,{children:e.jsx(bn,{size:20})}),e.jsxs(A1,{children:[e.jsx(F1,{children:o}),e.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[e.jsx(D1,{$status:ne()}),e.jsx(N1,{$status:ne(),children:ne()})]})]})]})]}),U!==Ae.IDLE&&e.jsx(B1,{$status:U,children:U.replace("_"," ")})]}),e.jsx(U1,{children:F.length===0&&p?e.jsxs(Wi,{children:[e.jsx(bn,{size:48,strokeWidth:1.5}),e.jsx("p",{children:d})]}):e.jsxs(e.Fragment,{children:[F.map((N,W)=>{var fe,ye,re,je;if(((fe=N.metadata)==null?void 0:fe.type)==="user_input_request"&&N.metadata.userInputRequest){const me=N.metadata.userInputRequest,Se=!me.input_type||me.input_type==="text"||me.input_type==="number",Me=K&&(y==null?void 0:y.input_type)===me.input_type;return e.jsx(qn,{$isUser:!1,children:e.jsxs(H1,{children:[e.jsx("div",{className:"question",children:me.question}),me.context&&me.context.trim()&&e.jsx("div",{className:"context",children:me.context}),!Se&&e.jsxs("div",{className:"controls",children:[me.input_type==="select"&&me.options&&e.jsxs("select",{value:Me?u:"",onChange:Ie=>g(Ie.target.value),disabled:!Me,children:[e.jsx("option",{value:"",children:"Choose an option..."}),me.options.map(Ie=>e.jsx("option",{value:Ie,children:Ie},Ie))]}),me.input_type==="multiselect"&&me.options&&e.jsx("div",{className:"checkbox-group",children:me.options.map(Ie=>e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:Me&&E.includes(Ie),onChange:nr=>{nr.target.checked?b([...E,Ie]):b(E.filter(ar=>ar!==Ie))},disabled:!Me}),e.jsx("span",{children:Ie})]},Ie))}),me.input_type==="boolean"&&e.jsxs("div",{className:"radio-group",children:[e.jsxs("label",{className:"radio-label",children:[e.jsx("input",{type:"radio",name:"boolean",value:"true",checked:Me&&u==="true",onChange:Ie=>g(Ie.target.value),disabled:!Me}),e.jsx("span",{children:"Yes"})]}),e.jsxs("label",{className:"radio-label",children:[e.jsx("input",{type:"radio",name:"boolean",value:"false",checked:Me&&u==="false",onChange:Ie=>g(Ie.target.value),disabled:!Me}),e.jsx("span",{children:"No"})]})]}),me.input_type==="date"&&e.jsx("input",{type:"date",value:Me?u:"",onChange:Ie=>g(Ie.target.value),disabled:!Me})]}),e.jsx("div",{className:"instruction",children:Me?Se?"Type your response below":me.input_type==="multiselect"?"Select options above and click send":"Make your selection above and click send":""})]})},N.id)}if(((ye=N.metadata)==null?void 0:ye.type)==="log"){const me=F[W-1],Se=F[W+1],Me=((re=me==null?void 0:me.metadata)==null?void 0:re.type)==="log",Ie=((je=Se==null?void 0:Se.metadata)==null?void 0:je.type)==="log",nr=Me||Ie,ar=!Me&&Ie,qr=Me&&!Ie;return e.jsx(G1,{$isGrouped:nr,$isFirstInGroup:ar,$isLastInGroup:qr,children:e.jsx("div",{className:"log-content",children:N.content})},N.id)}return!N.content&&(!N.images||N.images.length===0)?null:e.jsx(qn,{$isUser:N.role==="user",children:e.jsxs(Yl,{$isUser:N.role==="user",children:[e.jsx("div",{children:N.content}),N.images&&N.images.length>0&&e.jsx("div",{style:{display:"flex",gap:"8px",marginTop:"8px",flexWrap:"wrap"},children:N.images.map((me,Se)=>{const Me=me.url||`data:${me.mime_type};base64,${me.data}`;return e.jsxs(d2,{onClick:()=>ce(Me),title:"Click to preview",children:[e.jsx("img",{src:Me,alt:`Image ${Se+1}`,loading:"lazy"}),e.jsx("div",{className:"expand-icon",children:e.jsx(Fp,{size:14})})]},Se)})}),N.isStreaming&&e.jsx(W1,{})]})},N.id)}),G&&e.jsx(qn,{$isUser:!0,children:e.jsxs(V1,{$isUser:!0,children:[e.jsx("div",{children:G}),L&&L.length>0&&e.jsx("div",{style:{display:"flex",gap:"8px",marginTop:"8px",flexWrap:"wrap"},children:L.map((N,W)=>e.jsx("div",{style:{width:"200px",height:"200px",borderRadius:"8px",border:"1px solid var(--color-border)",overflow:"hidden",backgroundColor:"var(--color-background-subtle)",position:"relative",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx("img",{src:N.data?`data:${N.mime_type};base64,${N.data}`:"#",alt:`Image ${W+1}`,style:{maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",objectFit:"contain"},loading:"lazy"})},W))})]})}),e.jsx("div",{ref:T})]})}),$.length>0&&e.jsx(X1,{children:$.map((N,W)=>e.jsxs(J1,{children:[e.jsx("img",{src:N.data?`data:${N.mime_type};base64,${N.data}`:"#",alt:`Upload ${W+1}`}),e.jsx(e2,{type:"button",onClick:()=>Q(W),children:e.jsx(Ze,{size:12})})]},W))}),e.jsx(q1,{onSubmit:oe,children:e.jsxs(Y1,{children:[e.jsxs(Z1,{children:[e.jsx(Q1,{value:u,onChange:N=>g(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),oe(N))},placeholder:Y(),disabled:!se||te&&!K||Z(),rows:1}),e.jsx(K1,{children:e.jsxs(r2,{type:"button",disabled:!se||te,onClick:()=>{var N;return(N=M.current)==null?void 0:N.click()},children:[e.jsx(eh,{size:16}),"Attach"]})}),e.jsx(t2,{ref:M,type:"file",accept:"image/*",multiple:!0,onChange:de})]}),e.jsx(o2,{type:te?"button":"submit",disabled:!se||!K&&!te&&!u.trim(),onClick:te?ie:void 0,onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),style:{background:te&&m?"var(--color-error)":void 0},children:te?m?e.jsx(Ze,{size:14}):e.jsx(vt,{size:14,className:"animate-spin"}):e.jsx(Wc,{size:14})})]})})]}),e.jsx(u2,{isOpen:!!w,imageUrl:w,zoomLevel:x,dragPosition:_,isDragging:k,onClose:B,onDownload:()=>w&&V(w),onZoom:D,onReset:()=>{I(1),O({x:0,y:0})},onWheel:le,onMouseDown:H,onMouseMove:ae,onMouseUp:ke})]})}const p2=l.div`
5674
5674
  height: 100%;
5675
5675
  display: flex;
5676
5676
  flex-direction: column;
@@ -6023,5 +6023,5 @@ cursor: pointer;
6023
6023
  display: flex;
6024
6024
  flex-direction: column;
6025
6025
  gap: var(--space-xs);
6026
- `;function K2(){const[t,r]=i.useState(!1),{sessions:o,selectedSession:n,showHistory:s,selectSession:a,createSession:h,setShowHistory:f}=Ho(),c=async()=>{try{r(!0),await h()}finally{r(!1)}},p=d=>{try{const u=new Date(d),m=new Date().getTime()-u.getTime(),v=Math.floor(m/6e4),y=Math.floor(v/60),S=Math.floor(y/24);return S>0?`${S}d ago`:y>0?`${y}h ago`:v>0?`${v}m ago`:"Just now"}catch{return""}};return s?e.jsx(Kl,{showBackButton:!0}):n?e.jsx(Ql,{showBackButton:!0}):e.jsx(ue,{style:{height:"100%",width:"100%"},children:e.jsx(M2,{children:e.jsxs(L2,{children:[e.jsx(A2,{children:e.jsx("svg",{fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})})}),e.jsx(D2,{children:"Hi there! 👋"}),e.jsx(F2,{children:"How can I help you today?"}),e.jsx(N2,{onClick:c,disabled:t,children:t?e.jsxs(e.Fragment,{children:["Starting",e.jsx(B2,{})]}):"Start a conversation"}),o.length>0&&e.jsxs(H2,{children:[e.jsxs(q2,{children:[e.jsx(Y2,{children:"Recent Chats"}),e.jsx(Z2,{onClick:()=>f(!0),children:"View All →"})]}),e.jsx(Q2,{children:o.slice(0,2).map(d=>e.jsx(U2,{onClick:()=>a(d),children:e.jsxs(G2,{children:[e.jsx(W2,{children:d.title}),e.jsxs(V2,{children:[e.jsx("span",{children:p(d.last_activity_at)}),d.status==="running"&&e.jsx("span",{children:"• Active"})]})]})},d.id))})]})]})})})}const X2=t=>{const r=t.toLowerCase().trim();return["javascript:","data:","vbscript:"].some(s=>r.startsWith(s))?!0:["http://","https://","//","ftp://","ftps://","mailto:","tel:","sms:","file:","blob:"].some(s=>r.startsWith(s))},J2=t=>{const r=t.toLowerCase().trim();return!["javascript:","data:","vbscript:"].some(n=>r.startsWith(n))};exports.AcceptInvite=Kg;exports.AgentConversation=Ql;exports.AgentConversationHistory=Kl;exports.AgentConversationHub=K2;exports.AgentConversationProvider=Od;exports.AuthFormImage=Re;exports.ChannelSelector=R1;exports.CreateOrganizationForm=nn;exports.CreateWorkspaceDialog=kl;exports.CreateWorkspaceForm=$a;exports.DeploymentInitialized=lu;exports.DeploymentInitializing=du;exports.DeploymentProvider=ed;exports.Dialog=_e;exports.DialogTrigger=ff;exports.Dropdown=nt;exports.DropdownDivider=on;exports.DropdownItem=Te;exports.DropdownItems=at;exports.DropdownTrigger=st;exports.Form=lt;exports.FormGroup=ge;exports.Input=pe;exports.Label=he;exports.MagicLinkVerification=Vg;exports.ManageAccount=Bl;exports.ManageAccountDialog=Ul;exports.ManageOrganization=yl;exports.ManageWorkspace=Cl;exports.ManageWorkspaceDialog=Sl;exports.NavigateToSignIn=u1;exports.NavigateToSignUp=p1;exports.NavigationLink=ot;exports.NotificationBell=Hl;exports.NotificationItem=Vl;exports.NotificationPopover=Gl;exports.OAuthProvider=rc;exports.OTPInput=It;exports.OrganizationSwitcher=zl;exports.PhoneNumberInput=Gr;exports.PhoneVerification=pl;exports.ProfileCompletion=fl;exports.RequireActiveTenancy=S1;exports.SSOCallback=Mg;exports.SignInForm=gg;exports.SignUpForm=Xh;exports.SignedIn=Zv;exports.SignedInAccounts=d1;exports.SignedOut=Qv;exports.SimpleDialog=hf;exports.Spinner=Ee;exports.Switch=jr;exports.TwoFactorMethodSelector=ul;exports.TwoFactorVerification=hl;exports.UserButton=Pa;exports.UserControls=Yv;exports.WaitlistForm=Pg;exports.clearTokenCache=$t;exports.fetchChannelCounts=ou;exports.hasIncompleteProfile=Gg;exports.isExternalUrl=X2;exports.isSafeUrl=J2;exports.redirectToProfileCompletion=Hg;exports.useActiveOrganization=qe;exports.useActiveTenancy=tu;exports.useActiveWorkspace=Rt;exports.useAgentConversation=hc;exports.useAgentConversationContext=Ho;exports.useChannelCounts=cu;exports.useClient=Fe;exports.useConversationSessions=ec;exports.useDeployment=ve;exports.useForgotPassword=dc;exports.useInvitation=fc;exports.useMagicLinkParams=lc;exports.useMagicLinkVerification=cc;exports.useNavigation=Ve;exports.useNotificationStream=uc;exports.useNotifications=pc;exports.useOrganizationList=qo;exports.useOrganizationMemberships=vt;exports.useSSOCallback=ic;exports.useSession=Be;exports.useSignIn=oc;exports.useSignInWithStrategy=Dr;exports.useSignUp=nc;exports.useUser=rr;exports.useUserSignins=ac;exports.useWaitlist=sc;exports.useWorkspaceList=bt;exports.useWorkspaceMemberships=Yo;Object.keys(Ta).forEach(t=>{t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>Ta[t]})});
6026
+ `;function K2(){const[t,r]=i.useState(!1),{sessions:o,selectedSession:n,showHistory:s,selectSession:a,createSession:h,setShowHistory:f}=Ho(),c=async()=>{try{r(!0),await h()}finally{r(!1)}},p=d=>{try{const u=new Date(d),m=new Date().getTime()-u.getTime(),v=Math.floor(m/6e4),y=Math.floor(v/60),S=Math.floor(y/24);return S>0?`${S}d ago`:y>0?`${y}h ago`:v>0?`${v}m ago`:"Just now"}catch{return""}};return s?e.jsx(Kl,{showBackButton:!0}):n?e.jsx(Ql,{showBackButton:!0}):e.jsx(ue,{style:{height:"100%",width:"100%"},children:e.jsx(M2,{children:e.jsxs(L2,{children:[e.jsx(A2,{children:e.jsx("svg",{fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})})}),e.jsx(D2,{children:"Hi there! 👋"}),e.jsx(F2,{children:"How can I help you today?"}),e.jsx(N2,{onClick:c,disabled:t,children:t?e.jsxs(e.Fragment,{children:["Starting",e.jsx(B2,{})]}):"Start a conversation"}),o.length>0&&e.jsxs(H2,{children:[e.jsxs(q2,{children:[e.jsx(Y2,{children:"Recent Chats"}),e.jsx(Z2,{onClick:()=>f(!0),children:"View All →"})]}),e.jsx(Q2,{children:o.slice(0,2).map(d=>e.jsx(U2,{onClick:()=>a(d),children:e.jsxs(G2,{children:[e.jsx(W2,{children:d.title}),e.jsxs(V2,{children:[e.jsx("span",{children:p(d.last_activity_at)}),d.status==="running"&&e.jsx("span",{children:"• Active"})]})]})},d.id))})]})]})})})}const X2=t=>{const r=t.toLowerCase().trim();return["javascript:","data:","vbscript:"].some(s=>r.startsWith(s))?!0:["http://","https://","//","ftp://","ftps://","mailto:","tel:","sms:","file:","blob:"].some(s=>r.startsWith(s))},J2=t=>{const r=t.toLowerCase().trim();return!["javascript:","data:","vbscript:"].some(n=>r.startsWith(n))};exports.AcceptInvite=Kg;exports.AgentConversation=Ql;exports.AgentConversationHistory=Kl;exports.AgentConversationHub=K2;exports.AgentConversationProvider=Od;exports.AuthFormImage=Re;exports.ChannelSelector=R1;exports.CreateOrganizationForm=nn;exports.CreateWorkspaceDialog=kl;exports.CreateWorkspaceForm=$a;exports.DeploymentInitialized=lu;exports.DeploymentInitializing=du;exports.DeploymentProvider=ed;exports.Dialog=_e;exports.DialogTrigger=ff;exports.Dropdown=nt;exports.DropdownDivider=on;exports.DropdownItem=Te;exports.DropdownItems=at;exports.DropdownTrigger=st;exports.Form=lt;exports.FormGroup=ge;exports.Input=pe;exports.Label=he;exports.MagicLinkVerification=Vg;exports.ManageAccount=Bl;exports.ManageAccountDialog=Ul;exports.ManageOrganization=yl;exports.ManageWorkspace=Cl;exports.ManageWorkspaceDialog=Sl;exports.NavigateToSignIn=u1;exports.NavigateToSignUp=p1;exports.NavigationLink=ot;exports.NotificationBell=Hl;exports.NotificationItem=Vl;exports.NotificationPopover=Gl;exports.OAuthProvider=rc;exports.OTPInput=It;exports.OrganizationSwitcher=zl;exports.PhoneNumberInput=Gr;exports.PhoneVerification=pl;exports.ProfileCompletion=fl;exports.RequireActiveTenancy=S1;exports.SSOCallback=Mg;exports.SignInForm=gg;exports.SignUpForm=Xh;exports.SignedIn=Zv;exports.SignedInAccounts=d1;exports.SignedOut=Qv;exports.SimpleDialog=hf;exports.Spinner=Ee;exports.Switch=jr;exports.TwoFactorMethodSelector=ul;exports.TwoFactorVerification=hl;exports.UserButton=Pa;exports.UserControls=Yv;exports.WaitlistForm=Pg;exports.clearTokenCache=zt;exports.fetchChannelCounts=ou;exports.hasIncompleteProfile=Gg;exports.isExternalUrl=X2;exports.isSafeUrl=J2;exports.redirectToProfileCompletion=Hg;exports.useActiveOrganization=qe;exports.useActiveTenancy=tu;exports.useActiveWorkspace=Rt;exports.useAgentConversation=hc;exports.useAgentConversationContext=Ho;exports.useChannelCounts=cu;exports.useClient=Fe;exports.useConversationSessions=ec;exports.useDeployment=ve;exports.useForgotPassword=dc;exports.useInvitation=fc;exports.useMagicLinkParams=lc;exports.useMagicLinkVerification=cc;exports.useNavigation=Ve;exports.useNotificationStream=uc;exports.useNotifications=pc;exports.useOrganizationList=qo;exports.useOrganizationMemberships=bt;exports.useSSOCallback=ic;exports.useSession=Be;exports.useSignIn=oc;exports.useSignInWithStrategy=Dr;exports.useSignUp=nc;exports.useUser=rr;exports.useUserSignins=ac;exports.useWaitlist=sc;exports.useWorkspaceList=yt;exports.useWorkspaceMemberships=Yo;Object.keys(Ta).forEach(t=>{t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>Ta[t]})});
6027
6027
  //# sourceMappingURL=index.cjs.js.map