@skylabs-digital/react-identity-access 2.32.0 → 3.0.0

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.
Files changed (52) hide show
  1. package/dist/components/LoginForm.d.ts +2 -19
  2. package/dist/components/LoginForm.d.ts.map +1 -1
  3. package/dist/components/MagicLinkForm.d.ts +2 -23
  4. package/dist/components/MagicLinkForm.d.ts.map +1 -1
  5. package/dist/components/PasswordRecoveryForm.d.ts +2 -19
  6. package/dist/components/PasswordRecoveryForm.d.ts.map +1 -1
  7. package/dist/components/SignupForm.d.ts +2 -21
  8. package/dist/components/SignupForm.d.ts.map +1 -1
  9. package/dist/components/authFormShared.d.ts +39 -0
  10. package/dist/components/authFormShared.d.ts.map +1 -0
  11. package/dist/hooks/useAuthForm.d.ts +24 -0
  12. package/dist/hooks/useAuthForm.d.ts.map +1 -0
  13. package/dist/index.d.ts +2 -3
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.es.js +1964 -2680
  16. package/dist/index.es.js.map +1 -1
  17. package/dist/index.js +2 -2
  18. package/dist/index.js.map +1 -1
  19. package/dist/providers/AppProvider.d.ts +0 -3
  20. package/dist/providers/AppProvider.d.ts.map +1 -1
  21. package/dist/providers/AuthProvider.d.ts +33 -19
  22. package/dist/providers/AuthProvider.d.ts.map +1 -1
  23. package/dist/providers/RoutingProvider.d.ts.map +1 -1
  24. package/dist/providers/TenantProvider.d.ts +0 -2
  25. package/dist/providers/TenantProvider.d.ts.map +1 -1
  26. package/dist/services/AppApiService.d.ts +1 -3
  27. package/dist/services/AppApiService.d.ts.map +1 -1
  28. package/dist/services/AuthApiService.d.ts +3 -2
  29. package/dist/services/AuthApiService.d.ts.map +1 -1
  30. package/dist/services/FeatureFlagApiService.d.ts +1 -3
  31. package/dist/services/FeatureFlagApiService.d.ts.map +1 -1
  32. package/dist/services/PermissionApiService.d.ts +1 -3
  33. package/dist/services/PermissionApiService.d.ts.map +1 -1
  34. package/dist/services/RoleApiService.d.ts +1 -3
  35. package/dist/services/RoleApiService.d.ts.map +1 -1
  36. package/dist/services/SessionManager.d.ts +1 -12
  37. package/dist/services/SessionManager.d.ts.map +1 -1
  38. package/dist/services/SubscriptionApiService.d.ts +1 -3
  39. package/dist/services/SubscriptionApiService.d.ts.map +1 -1
  40. package/dist/services/SubscriptionPlanApiService.d.ts +1 -3
  41. package/dist/services/SubscriptionPlanApiService.d.ts.map +1 -1
  42. package/dist/services/TenantApiService.d.ts +1 -3
  43. package/dist/services/TenantApiService.d.ts.map +1 -1
  44. package/dist/services/UserApiService.d.ts +1 -3
  45. package/dist/services/UserApiService.d.ts.map +1 -1
  46. package/dist/utils/query.d.ts +6 -0
  47. package/dist/utils/query.d.ts.map +1 -0
  48. package/package.json +1 -1
  49. package/dist/utils/crossDomainAuth.d.ts +0 -37
  50. package/dist/utils/crossDomainAuth.d.ts.map +0 -1
  51. package/dist/utils/mappers.d.ts +0 -29
  52. package/dist/utils/mappers.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),a=require("react"),se=require("react-router-dom");class re{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async executeRequest(e,t,n,i){const o=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,l=(i==null?void 0:i.timeout)||this.timeout;let h={"Content-Type":"application/json",...i==null?void 0:i.headers};if(!(i!=null&&i.skipAuth)&&this.sessionManager){const d=await this.sessionManager.getValidAccessToken();h={...h,Authorization:`Bearer ${d}`}}const f=new AbortController,y=setTimeout(()=>f.abort(),l);try{const d=await fetch(o,{method:e,headers:h,body:n?JSON.stringify(n):void 0,signal:f.signal});if(clearTimeout(y),!d.ok)throw new Error(`HTTP ${d.status}: ${d.statusText}`);const M=d.headers.get("content-type");return!M||!M.includes("application/json")?{}:await d.json()}catch(d){throw clearTimeout(y),d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${l}ms`):d}}async get(e,t){return this.executeRequest("GET",e,void 0,t)}async post(e,t,n){return this.executeRequest("POST",e,t,n)}async put(e,t,n){return this.executeRequest("PUT",e,t,n)}async delete(e,t){return this.executeRequest("DELETE",e,void 0,t)}}class ke{constructor(e,t){this.httpService=e,this.sessionManager=t}async createApp(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/apps/",e,{headers:t})).data}async getApps(e){const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/apps/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{apps:o.data,meta:o.meta}}async getAppById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}`,{headers:t})).data}async updateApp(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:n})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:n})).data}async updateSettingsSchema(e,t,n){const i=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:n},{headers:i})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const je=a.createContext(null);function gt({config:s,children:e}){const t=a.useMemo(()=>{var m,v,k;return{enabled:((m=s.cache)==null?void 0:m.enabled)??!0,ttl:((v=s.cache)==null?void 0:v.ttl)??3e5,storageKey:((k=s.cache)==null?void 0:k.storageKey)??`app_cache_${s.appId}`}},[s.cache,s.appId]),[n,i]=a.useState(()=>{if(!t.enabled)return null;try{const m=localStorage.getItem(t.storageKey);if(!m)return null;const v=JSON.parse(m);return Date.now()-v.timestamp<t.ttl&&v.appId===s.appId?v.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[o,l]=a.useState(!n),[h,f]=a.useState(null),y=a.useMemo(()=>{const m=()=>{d()};return{appId:s.appId,baseUrl:s.baseUrl,appInfo:n,isAppLoading:o,appError:h,retryApp:m}},[s,n,o,h]),d=a.useCallback(async(m=!1)=>{if(!(!m&&t.enabled&&n))try{l(!0),f(null);const v=new re(s.baseUrl),I=await new ke(v,{}).getPublicAppInfo(s.appId);if(i(I),t.enabled)try{const E={data:I,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(E))}catch(E){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Failed to cache app info:",E)}}catch(v){const k=v instanceof Error?v:new Error("Failed to load app information");f(k),i(null)}finally{l(!1)}},[s.baseUrl,s.appId,t,n]),M=a.useCallback(async()=>{if(!(!t.enabled||!n))try{const m=localStorage.getItem(t.storageKey);if(!m)return;const v=JSON.parse(m);if(Date.now()-v.timestamp>t.ttl*.5){const I=new re(s.baseUrl),A=await new ke(I,{}).getPublicAppInfo(s.appId);i(A);const u={data:A,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(u))}}catch(m){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Background app refresh failed:",m)}},[s,t,n]);return a.useEffect(()=>{n?M():d()},[]),r.jsx(je.Provider,{value:y,children:e})}function fe(){const s=a.useContext(je);if(!s)throw new Error("useApp must be used within an AppProvider");return s}function Pe(){return a.useContext(je)}const mt=fe;class Y extends Error{constructor(e,t){const n={token_expired:"Refresh token has expired",token_invalid:"Refresh token is invalid",user_inactive:"User account is inactive"};super(t||n[e]),this.name="SessionExpiredError",this.reason=e}}class _e extends Error{constructor(e){super(`Token refresh timed out after ${e}ms`),this.name="TokenRefreshTimeoutError",this.timeoutMs=e}}class ze extends Error{constructor(e,t){super(`Token refresh failed after ${e} attempts: ${(t==null?void 0:t.message)||"Unknown error"}`),this.name="TokenRefreshError",this.attempts=e,this.lastError=t}}const ee=class ee{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],this.proactiveTimerId=null,this.backgroundRetryTimerId=null,this.isDestroyed=!1,this.sessionGeneration=0,this.consecutiveBackgroundFailures=0,this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.onSessionExpired=e.onSessionExpired,this.baseUrl=e.baseUrl||"",this.enableCookieSession=e.enableCookieSession??!1,this.proactiveRefreshMargin=e.proactiveRefreshMargin??6e4,this.refreshQueueTimeout=e.refreshQueueTimeout??1e4,this.maxRefreshRetries=e.maxRefreshRetries??3,this.retryBackoffBase=e.retryBackoffBase??1e3,this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey),this.scheduleProactiveRefresh()}static getInstance(e={}){const t=ee.resolveStorageKey(e),n=ee.instances.get(t);if(n)return n.updateConfig(e),n;const i=new ee(e);return ee.instances.set(t,i),i}static resetAllInstances(){for(const e of ee.instances.values())e.destroy();ee.instances.clear()}static resolveStorageKey(e){return e.storageKey||"auth_tokens"}updateConfig(e){e.onSessionExpired!==void 0&&(this.onSessionExpired=e.onSessionExpired),e.onRefreshFailed!==void 0&&(this.onRefreshFailed=e.onRefreshFailed),e.baseUrl&&(this.baseUrl=e.baseUrl),e.enableCookieSession!==void 0&&(this.enableCookieSession=e.enableCookieSession)}createTokenStorage(e){return{get:()=>{try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},set:t=>{try{localStorage.setItem(e,JSON.stringify(t))}catch{}},clear:()=>{try{localStorage.removeItem(e)}catch{}}}}static extractJwtExpiry(e){try{const t=e.split(".");if(t.length!==3)return;const n=JSON.parse(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof n.exp=="number"?n.exp*1e3:void 0}catch{return}}static extractJwtClaim(e,t){try{const n=e.split(".");if(n.length!==3)return;const i=JSON.parse(atob(n[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof i[t]=="string"?i[t]:void 0}catch{return}}setTokens(e){const t=e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)||ee.extractJwtExpiry(e.accessToken),n={...e,expiresAt:t},i=this.tokenStorage.get()||{};this.tokenStorage.set({...i,...n}),this.scheduleProactiveRefresh()}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:n,expiresIn:i,tokenType:o}=this.tokenStorage.get()||{};if(!e)return null;const l=n||ee.extractJwtExpiry(e);return{accessToken:e,refreshToken:t,expiresAt:l,expiresIn:i,tokenType:o}}clearTokens(){this.tokenStorage.clear()}isTokenExpired(e){const t=e||this.getTokens();return t!=null&&t.expiresAt?Date.now()>=t.expiresAt:!1}shouldRefreshToken(e){const t=e||this.getTokens();return!(t!=null&&t.expiresAt)||!this.autoRefresh?!1:Date.now()>=t.expiresAt-this.refreshThreshold}getAccessToken(){const e=this.getTokens();return(e==null?void 0:e.accessToken)||null}scheduleProactiveRefresh(){if(this.cancelProactiveTimer(),!this.autoRefresh||this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.expiresAt)||!e.refreshToken)return;const n=e.expiresAt-this.proactiveRefreshMargin-Date.now();if(n<=0){this.backgroundRefresh();return}this.proactiveTimerId=setTimeout(()=>{this.backgroundRefresh()},n)}cancelProactiveTimer(){this.proactiveTimerId!==null&&(clearTimeout(this.proactiveTimerId),this.proactiveTimerId=null),this.backgroundRetryTimerId!==null&&(clearTimeout(this.backgroundRetryTimerId),this.backgroundRetryTimerId=null)}backgroundRefresh(){if(this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.refreshToken)||this.refreshPromise)return;const t=this.sessionGeneration;this.startRefreshAndResolveQueue(e.refreshToken).then(()=>{this.consecutiveBackgroundFailures=0}).catch(n=>{if(!(n instanceof Y)){if(this.sessionGeneration===t){if(this.consecutiveBackgroundFailures++,this.consecutiveBackgroundFailures>=ee.MAX_BACKGROUND_FAILURES){process.env.NODE_ENV==="development"&&console.error(`[SessionManager] Background refresh failed ${this.consecutiveBackgroundFailures} consecutive times — expiring session`),this.consecutiveBackgroundFailures=0,this.handleSessionExpired(new Y("token_invalid","Background refresh failed repeatedly"));return}process.env.NODE_ENV==="development"&&console.warn("[SessionManager] Background refresh failed, retrying in 30s:",n.message),this.backgroundRetryTimerId=setTimeout(()=>{this.backgroundRefresh()},3e4)}}})}async waitForPendingRefresh(){if(!this.refreshPromise)return!1;try{return await this.refreshPromise,!0}catch{return!1}}async attemptCookieSessionRestore(){if(!this.enableCookieSession||!this.baseUrl)return!1;const e=`${this.baseUrl}/auth/refresh`;try{const t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),credentials:"include"});if(!t.ok)return!1;const n=await t.json();return n.accessToken?(this.setTokens({accessToken:n.accessToken,refreshToken:n.refreshToken||"",expiresIn:n.expiresIn}),!0):!1}catch{return!1}}async getValidAccessToken(){const e=this.getTokens();if(!(e!=null&&e.accessToken)){const t=new Y("token_invalid","No tokens available");throw this.handleSessionExpired(t),t}if(!this.shouldRefreshToken(e)&&!this.isTokenExpired(e))return e.accessToken;if(!e.refreshToken){const t=new Y("token_invalid","No refresh token available");throw this.handleSessionExpired(t),t}return this.refreshPromise?this.enqueueForToken():this.startRefreshAndResolveQueue(e.refreshToken)}async getAuthHeaders(){try{return{Authorization:`Bearer ${await this.getValidAccessToken()}`}}catch(e){return e instanceof Y&&this.onRefreshFailed&&this.onRefreshFailed(),{}}}enqueueForToken(){return new Promise((e,t)=>{const n=setTimeout(()=>{const i=this.refreshQueue.findIndex(o=>o.timeoutId===n);i!==-1&&this.refreshQueue.splice(i,1),t(new _e(this.refreshQueueTimeout))},this.refreshQueueTimeout);this.refreshQueue.push({resolve:e,reject:t,timeoutId:n})})}async startRefreshAndResolveQueue(e){this.refreshPromise=this.executeRefreshWithRetry(e);try{await this.refreshPromise;const t=this.getTokens(),n=(t==null?void 0:t.accessToken)||"";return this.resolveQueue(n),n}catch(t){const n=t instanceof Error?t:new Error("Token refresh failed");throw n instanceof Y?(this.rejectQueue(n),this.handleSessionExpired(n)):this.rejectQueue(n),n}finally{this.refreshPromise=null}}resolveQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const n of t)clearTimeout(n.timeoutId),n.resolve(e)}rejectQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const n of t)clearTimeout(n.timeoutId),n.reject(e)}async executeRefreshWithRetry(e){let t;const n=this.sessionGeneration;for(let i=0;i<=this.maxRefreshRetries;i++){if(this.sessionGeneration!==n)throw new Y("token_invalid","Session cleared during refresh");try{await this.performTokenRefresh(e,n);return}catch(o){const l=o instanceof Error?o:new Error(String(o));if(l instanceof Y)throw l;if(t=l,i<this.maxRefreshRetries){const h=this.retryBackoffBase*Math.pow(2,i);await this.sleep(h)}}}throw new ze(this.maxRefreshRetries+1,t)}async performTokenRefresh(e,t){return typeof navigator<"u"&&navigator.locks?navigator.locks.request(`session-refresh:${this.storageKey}`,()=>this.performTokenRefreshInner(e,t)):this.performTokenRefreshInner(e,t)}async performTokenRefreshInner(e,t){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const n=this.getTokens();if(n!=null&&n.accessToken&&!this.isTokenExpired(n)&&!this.shouldRefreshToken(n))return;const i=(n==null?void 0:n.refreshToken)||e,o=`${this.baseUrl}/auth/refresh`,l=ee.extractJwtClaim(i,"deviceId"),h={refreshToken:i};l&&(h.deviceId=l);let f;try{f=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h),...this.enableCookieSession&&{credentials:"include"}})}catch(d){throw d instanceof Error?d:new Error("Network error during token refresh")}if(!f.ok){let d="";try{const M=await f.json();d=(M.message||M.error||"").toLowerCase()}catch{d=f.statusText.toLowerCase()}throw f.status===401?d.includes("expired")?new Y("token_expired"):d.includes("invalid")?new Y("token_invalid"):new Y("token_invalid",`Unauthorized: ${d}`):f.status===400?d.includes("inactive")?new Y("user_inactive"):d.includes("expired")||d.includes("invalid")?new Y("token_invalid",d):d.includes("reuse")||d.includes("revoked")?new Y("token_invalid",d):new Error(`Token refresh failed (400): ${d}`):new Error(`Token refresh failed: ${f.status} ${d}`)}if(this.sessionGeneration!==t)throw new Y("token_invalid","Session cleared during refresh");const y=await f.json();this.setTokens({accessToken:y.accessToken,refreshToken:y.refreshToken||i,expiresIn:y.expiresIn})}handleSessionExpired(e){this.cancelProactiveTimer(),this.clearSession(),this.onSessionExpired?this.onSessionExpired(e):this.onRefreshFailed&&this.onRefreshFailed()}setUser(e){const t=this.tokenStorage.get()||{};this.tokenStorage.set({...t,user:e})}getUser(){const e=this.tokenStorage.get();return(e==null?void 0:e.user)||null}clearUser(){const e=this.tokenStorage.get()||{};delete e.user,this.tokenStorage.set(e)}clearSession(){this.sessionGeneration++,this.cancelProactiveTimer(),this.clearTokens();const e=new Y("token_invalid","Session cleared");this.rejectQueue(e)}destroy(){this.isDestroyed=!0,ee.instances.delete(this.storageKey),this.cancelProactiveTimer();const e=new Y("token_invalid","SessionManager destroyed");this.rejectQueue(e)}getTokenPayload(){try{const e=this.getTokens();if(!(e!=null&&e.accessToken))return null;const t=e.accessToken.split(".");if(t.length!==3)return null;const n=t[1],i=atob(n.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(i)}catch{return null}}getUserId(){const e=this.getTokenPayload();if(e!=null&&e.userId)return e.userId;const t=this.getUser();return(t==null?void 0:t.id)||null}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}sleep(e){return new Promise(t=>setTimeout(t,e))}};ee.instances=new Map,ee.MAX_BACKGROUND_FAILURES=3;let me=ee;const Se=new Map;class Ve{constructor(e){this.httpService=e}async login(e){return await this.httpService.post("/auth/login",e)}async signup(e){return await this.httpService.post("/auth/signup",e)}async signupTenantAdmin(e){return await this.httpService.post("/auth/signup/tenant-admin",e)}async refreshToken(e){return await this.httpService.post("/auth/refresh",e)}async switchTenant(e){return await this.httpService.post("/auth/switch-tenant",e)}async getUserTenants(e){return await this.httpService.get("/auth/tenants",{headers:e})}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e)}async sendMagicLink(e){return await this.httpService.post("/auth/magic-link/send",e)}async verifyMagicLink(e){const t=e.token,n=Se.get(t);if(n)return n;const i=this.httpService.post("/auth/magic-link/verify",e).finally(()=>{Se.delete(t)});return Se.set(t,i),i}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e)}async changePassword(e,t){await this.httpService.post("/auth/change-password",e,{headers:t})}}class Ae{constructor(e,t){this.httpService=e,this.sessionManager=t}async createRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/roles/",e,{headers:t})).data}async getRoleById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/roles/${e}`,{headers:t})).data}async updateRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:n})).data}async deleteRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/roles/${e}`,{headers:t})}async getRolesByApp(e,t){const n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const i=`/roles/app/${e}${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i);return{roles:o.data,meta:o.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:n})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:n})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders(),i=new URLSearchParams;t!=null&&t.page&&i.append("page",t.page.toString()),t!=null&&t.limit&&i.append("limit",t.limit.toString()),t!=null&&t.sortBy&&i.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&i.append("sortOrder",t.sortOrder);const o=`/roles/user/${e}${i.toString()?`?${i.toString()}`:""}`,l=await this.httpService.get(o,{headers:n});return{roles:l.data,meta:l.meta}}}class We{constructor(e,t){this.httpService=e,this.sessionManager=t}async createUser(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/users/",e,{headers:t})).data}async getUsers(e){const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/users/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{users:o.data,meta:o.meta}}async getUserById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/users/${e}`,{headers:t})).data}async updateUser(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:n})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class ue{constructor(e,t,n){this.httpService=e,this.appId=t,this.sessionManager=n}async createTenant(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/tenants/",e,{headers:t})).data}async getTenants(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/tenants/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{tenants:o.data,meta:o.meta}}async getTenantById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/tenants/${e}`,{headers:t})).data}async updateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:n})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:n})).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`)).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`)).data}async updateTenantSettings(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:n})).data}}function yt(s,e){if(s==="localhost"||s.startsWith("127.")||s.startsWith("192.168."))return null;if(e){const i=e.toLowerCase(),o=s.toLowerCase();if(o===i||o===`www.${i}`)return null;if(o.endsWith(`.${i}`)){const l=o.slice(0,-(i.length+1));return l==="www"?null:l}return null}const n=s.split(".");return n.length>=3&&n[0]!=="www"?n[0]:null}function wt(s,e="tenant",t){const i=new URLSearchParams(s).get(e);return i?(t&&t.setItem("tenant",i),i):t?t.getItem("tenant"):null}function xt(s,e,t){const{tenantMode:n,baseDomain:i,selectorParam:o,fixedTenantSlug:l}=s;return n==="fixed"?l||null:n==="subdomain"?yt(e.hostname,i):n==="selector"?wt(e.search,o,t):null}function bt(s,e,t){if(t)return`${s}.${t}`;const n=e.split(".");return n.length===2?`${s}.${e}`:n.length>=3?(n[0]=s,n.join(".")):null}const de="_auth";function Be(s){const e=JSON.stringify(s);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function St(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";const t=atob(e),n=JSON.parse(t);return typeof n.accessToken=="string"&&typeof n.refreshToken=="string"&&typeof n.expiresIn=="number"?n:null}catch{return null}}function vt(){if(typeof window>"u")return null;const e=new URLSearchParams(window.location.search).get(de);return e?St(e):null}function Tt(){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.delete(de),window.history.replaceState({},"",s.toString())}const Re=a.createContext(null);function kt({config:s,children:e}){const{baseUrl:t,appInfo:n,appId:i}=fe(),o=a.useCallback(()=>typeof window>"u"?null:xt({tenantMode:s.tenantMode||"selector",baseDomain:s.baseDomain,selectorParam:s.selectorParam,fixedTenantSlug:s.fixedTenantSlug},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[s.tenantMode,s.baseDomain,s.selectorParam,s.fixedTenantSlug]),[l,h]=a.useState(()=>o()),f=a.useMemo(()=>{var g,N,x;return{enabled:((g=s.cache)==null?void 0:g.enabled)??!0,ttl:((N=s.cache)==null?void 0:N.ttl)??5*60*1e3,storageKey:((x=s.cache)==null?void 0:x.storageKey)??`tenant_cache_${l||"default"}`}},[s.cache,l]),[y,d]=a.useState(()=>{if(s.initialTenant)return s.initialTenant;if(!f.enabled||!l)return null;try{const g=localStorage.getItem(f.storageKey);if(!g)return null;const N=JSON.parse(g);return Date.now()-N.timestamp<f.ttl&&N.tenantSlug===l?N.data:(localStorage.removeItem(f.storageKey),null)}catch{return null}}),[M,m]=a.useState(!y&&!s.initialTenant),[v,k]=a.useState(null),[I,E]=a.useState(null),[A,u]=a.useState(!1),[b,F]=a.useState(null);a.useEffect(()=>{if(s.tenantMode==="fixed")return;const g=o();h(g)},[o,s.tenantMode]);const C=(n==null?void 0:n.settingsSchema)||null,w=a.useCallback(async(g,N=!1)=>{if(!(!N&&f.enabled&&y&&y.domain===g))try{m(!0),k(null);const x=new re(t),S=await new ue(x,i).getPublicTenantInfo(g);if(d(S),f.enabled)try{const P={data:S,timestamp:Date.now(),tenantSlug:g};localStorage.setItem(f.storageKey,JSON.stringify(P))}catch(P){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Failed to cache tenant info:",P)}}catch(x){const p=x instanceof Error?x:new Error("Failed to load tenant information");k(p),d(null)}finally{m(!1)}},[t,i,f,y]),j=a.useCallback(async()=>{if(!(!f.enabled||!y||!l))try{const g=localStorage.getItem(f.storageKey);if(!g)return;const N=JSON.parse(g);if(Date.now()-N.timestamp>f.ttl*.5){const p=new re(t),P=await new ue(p,i).getPublicTenantInfo(l);d(P);const G={data:P,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(f.storageKey,JSON.stringify(G))}}catch(g){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Background tenant refresh failed:",g)}},[t,i,f,y,l]),T=a.useCallback(async()=>{if(y!=null&&y.id)try{u(!0),F(null);const g=new re(t),x=await new ue(g,y.appId).getTenantSettings(y.id);E(x)}catch(g){const N=g instanceof Error?g:new Error("Failed to load tenant settings");F(N),E(null)}finally{u(!1)}},[t,y]),R=a.useCallback(()=>{T()},[T]),c=a.useCallback(g=>{if(!C)return{isValid:!0,errors:[]};const N=[];try{return C.properties&&Object.entries(C.properties).forEach(([x,p])=>{var P;const S=g[x];if((P=C.required)!=null&&P.includes(x)&&S==null){N.push(`Field '${x}' is required`);return}if(S!=null){if(p.type){const G=p.type,W=typeof S;G==="string"&&W!=="string"?N.push(`Field '${x}' must be a string`):(G==="number"||G==="integer")&&W!=="number"?N.push(`Field '${x}' must be a number`):G==="boolean"&&W!=="boolean"?N.push(`Field '${x}' must be a boolean`):G==="array"&&!Array.isArray(S)&&N.push(`Field '${x}' must be an array`)}p.minLength!==void 0&&typeof S=="string"&&S.length<p.minLength&&N.push(`Field '${x}' must be at least ${p.minLength} characters long`),p.maxLength!==void 0&&typeof S=="string"&&S.length>p.maxLength&&N.push(`Field '${x}' must be no more than ${p.maxLength} characters long`),p.minimum!==void 0&&typeof S=="number"&&S<p.minimum&&N.push(`Field '${x}' must be at least ${p.minimum}`),p.maximum!==void 0&&typeof S=="number"&&S>p.maximum&&N.push(`Field '${x}' must be no more than ${p.maximum}`),p.pattern&&typeof S=="string"&&(new RegExp(p.pattern).test(S)||N.push(`Field '${x}' does not match the required pattern`)),p.enum&&!p.enum.includes(S)&&N.push(`Field '${x}' must be one of: ${p.enum.join(", ")}`)}}),{isValid:N.length===0,errors:N}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[C]);a.useEffect(()=>{!s.initialTenant&&l?y?j():w(l):!s.initialTenant&&!l&&(d(null),k(null),m(!1))},[s.initialTenant,l,y,w,j]),a.useEffect(()=>{y!=null&&y.id?T():(E(null),F(null),u(!1))},[y==null?void 0:y.id,T]);const O=a.useCallback((g,N)=>{const{mode:x="reload",tokens:p,redirectPath:S}=N||{},P=s.tenantMode||"selector";if(P==="fixed"){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] switchTenant is a no-op in fixed mode. Tenant is always:",s.fixedTenantSlug),S&&(window.location.href=S);return}if(localStorage.setItem("tenant",g),P==="subdomain"){const G=window.location.hostname,W=bt(g,G,s.baseDomain);if(!W){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",G);return}const K=S||window.location.pathname,_=new URL(`${window.location.protocol}//${W}${K}`);new URLSearchParams(window.location.search).forEach((q,B)=>{B!==de&&_.searchParams.set(B,q)}),p&&_.searchParams.set(de,Be(p)),window.location.href=_.toString()}else if(P==="selector"){const G=S||window.location.pathname,W=new URLSearchParams(window.location.search);if(W.set(s.selectorParam||"tenant",g),W.delete(de),p&&W.set(de,Be(p)),x==="reload"){const K=`${G}?${W.toString()}${window.location.hash}`;window.location.href=K}else{const K=`${G}?${W.toString()}${window.location.hash}`;window.history.pushState({},"",K),h(g),w(g)}}},[s.tenantMode,s.selectorParam,s.baseDomain,w]),L=a.useMemo(()=>({tenant:y,tenantSlug:l,isTenantLoading:M,tenantError:v,retryTenant:()=>{l&&w(l)},settings:I,settingsSchema:C,isSettingsLoading:A,settingsError:b,refreshSettings:R,switchTenant:O,validateSettings:c}),[y,l,M,v,I,C,A,b,R,O,c]);return r.jsx(Re.Provider,{value:L,children:e})}function he(){const s=a.useContext(Re);if(!s)throw new Error("useTenant must be used within a TenantProvider");return s}function ae(){return a.useContext(Re)}const At=he;function jt(){const{settings:s,settingsSchema:e,isSettingsLoading:t,settingsError:n,validateSettings:i}=he();return{settings:s,settingsSchema:e,isLoading:t,error:n,validateSettings:i}}function Ee(){const{tenant:s,tenantSlug:e,isTenantLoading:t,tenantError:n,retryTenant:i}=he();return{tenant:s,tenantSlug:e,isLoading:t,error:n,retry:i}}const Me=a.createContext(null);function Pt({config:s={},children:e}){const t=Pe(),n=ae(),i=(t==null?void 0:t.baseUrl)??s.baseUrl??"",o=(t==null?void 0:t.appId)??s.appId,l=(n==null?void 0:n.tenant)??null,h=(n==null?void 0:n.tenantSlug)??null,f=(n==null?void 0:n.switchTenant)??(()=>{});if(!i)throw new Error("[AuthProvider] baseUrl is required. Provide it via AppProvider or AuthConfig.baseUrl.");const[y,d]=a.useState(s.initialRoles||[]),[M,m]=a.useState(!s.initialRoles),[v,k]=a.useState(null),[I,E]=a.useState(!1),[A,u]=a.useState(null),[b,F]=a.useState(()=>{try{const D=localStorage.getItem("userTenants");return D?JSON.parse(D):[]}catch{return[]}}),[C,w]=a.useState(!1),j=a.useRef({done:!1,urlTokens:null});j.current.done||(j.current.done=!0,j.current.urlTokens=vt());const[T,R]=a.useState(()=>j.current.urlTokens!==null),c=a.useMemo(()=>{const D=me.getInstance({baseUrl:i,enableCookieSession:s.enableCookieSession,refreshQueueTimeout:s.refreshQueueTimeout,proactiveRefreshMargin:s.proactiveRefreshMargin,onSessionExpired:ne=>{k(null),u(null),F([]),w(!1);try{localStorage.removeItem("userTenants")}catch{}s.onSessionExpired?s.onSessionExpired(ne):s.onRefreshFailed&&s.onRefreshFailed()}});return j.current.urlTokens&&D.setTokens({accessToken:j.current.urlTokens.accessToken,refreshToken:j.current.urlTokens.refreshToken,expiresIn:j.current.urlTokens.expiresIn}),D},[i,s.enableCookieSession,s.refreshQueueTimeout,s.proactiveRefreshMargin]),[O,L]=a.useState(()=>{if(j.current.urlTokens)return!1;const D=c.getTokens();return D?c.hasValidSession()||!!D.refreshToken:!!s.enableCookieSession}),g=j.current.done&&!T&&!O,N=a.useMemo(()=>{const D=new re(i);return D.setSessionManager(c),D},[i,c]),x=a.useMemo(()=>new Ve(new re(i)),[i]),p=a.useMemo(()=>new We(N,c),[N,c]),S=a.useMemo(()=>new Ae(new re(i)),[i]),P=a.useMemo(()=>v||c.getUser(),[v,c]),G=a.useMemo(()=>P!=null&&P.roleId&&y.find(D=>D.id===P.roleId)||null,[P,y]),W=a.useMemo(()=>(G==null?void 0:G.permissions)||[],[G]),K=a.useMemo(()=>c.hasValidSession()&&v!==null,[c,v]),_=a.useRef(async()=>{}),H=a.useMemo(()=>{const D=async(U=!1)=>{try{if(!c.hasValidSession()||!U&&v)return;const $=c.getUserId();if(!$){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] No userId available in token or storage");return}E(!0),u(null);const Z=await p.getUserById($);k(Z),c.setUser(Z)}catch($){const Z=$ instanceof Error?$:new Error("Failed to load user data");u(Z),process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data:",Z)}finally{E(!1)}},ne=async()=>{await D()},le=async U=>{var De;const{username:$,password:Z,tenantSlug:z,redirectPath:Q}=U;let X=l==null?void 0:l.id,J=h;z&&(X=(await new ue(N,o).getPublicTenantInfo(z)).id,J=z);const V=await x.login({username:$,password:Z,appId:o,tenantId:X}),pe=z&&z!==h;if(c.setTokens({accessToken:V.accessToken,refreshToken:V.refreshToken,expiresIn:V.expiresIn}),V.user){c.setUser(V.user),k(V.user);try{await D()}catch(ge){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after login:",ge)}}if(V.tenants&&V.tenants.length>0){F(V.tenants);try{localStorage.setItem("userTenants",JSON.stringify(V.tenants))}catch{}}const xe=((De=V.user)==null?void 0:De.tenantId)!==null;w(xe);const be={accessToken:V.accessToken,refreshToken:V.refreshToken,expiresIn:V.expiresIn};if(pe&&J)return f(J,{tokens:be,redirectPath:Q}),V;if(Q&&Q!==window.location.pathname)return f(J||h||"",{tokens:be,redirectPath:Q}),V;if(!xe&&V.tenants&&V.tenants.length>0){const ge=U.autoSwitch!==!1&&s.autoSwitchSingleTenant!==!1;if(V.tenants.length===1&&ge){const Ue=V.tenants[0];return f(Ue.subdomain,{tokens:be,redirectPath:Q}),V}else V.tenants.length>1&&s.onTenantSelectionRequired&&s.onTenantSelectionRequired(V.tenants)}return V},ce=async U=>{const{email:$,phoneNumber:Z,name:z,password:Q,lastName:X,tenantId:J}=U;if(!$&&!Z)throw new Error("Either email or phoneNumber is required");if(!z||!Q)throw new Error("Name and password are required");const V=J??(l==null?void 0:l.id);return await x.signup({email:$,phoneNumber:Z,name:z,password:Q,tenantId:V,lastName:X,appId:o})},rt=async U=>{const{email:$,phoneNumber:Z,name:z,password:Q,tenantName:X,lastName:J}=U;if(!$&&!Z)throw new Error("Either email or phoneNumber is required");if(!z||!Q||!X)throw new Error("Name, password, and tenantName are required");return await x.signupTenantAdmin({email:$,phoneNumber:Z,name:z,password:Q,tenantName:X,appId:o,lastName:J})},nt=async U=>{const{currentPassword:$,newPassword:Z}=U,z=await c.getAuthHeaders();await x.changePassword({currentPassword:$,newPassword:Z},z)},st=async U=>{const{email:$,tenantId:Z}=U,z=Z??(l==null?void 0:l.id);if(!z)throw new Error("tenantId is required for password reset");await x.requestPasswordReset({email:$,tenantId:z})},it=async U=>{const{token:$,newPassword:Z}=U;await x.confirmPasswordReset({token:$,newPassword:Z})},ot=async U=>{const{email:$,frontendUrl:Z,name:z,lastName:Q,tenantId:X}=U,J=X??(l==null?void 0:l.id);if(!J)throw new Error("tenantId is required for magic link authentication");return await x.sendMagicLink({email:$,tenantId:J,frontendUrl:Z,name:z,lastName:Q,appId:o})},at=async U=>{const{token:$,email:Z,tenantSlug:z}=U;let Q=l==null?void 0:l.id,X=h;z&&(Q=(await new ue(N,o).getPublicTenantInfo(z)).id,X=z);const J=await x.verifyMagicLink({token:$,email:Z,appId:o,tenantId:Q}),V=z&&z!==h;if(c.setTokens({accessToken:J.accessToken,refreshToken:J.refreshToken,expiresIn:J.expiresIn}),J.user){c.setUser(J.user),k(J.user);try{await D()}catch(pe){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after magic link:",pe)}}return V&&X&&X!==h&&f(X,{tokens:{accessToken:J.accessToken,refreshToken:J.refreshToken,expiresIn:J.expiresIn}}),J},lt=async()=>{const U=c.getTokens();if(!(U!=null&&U.refreshToken))throw new Error("No refresh token available");const $=await x.refreshToken({refreshToken:U.refreshToken});c.setTokens({accessToken:$.accessToken,refreshToken:$.refreshToken||U.refreshToken,expiresIn:$.expiresIn})},ct=()=>{c.clearSession(),k(null),u(null),F([]),w(!1);try{localStorage.removeItem("userTenants")}catch{}},dt=U=>{c.setTokens(U)},ut=()=>c.hasValidSession(),ht=()=>{c.clearSession(),k(null),u(null)},pt=async()=>{if(o)try{m(!0);const{roles:U}=await S.getRolesByApp(o);d(U)}catch(U){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",U)}finally{m(!1)}},ft=async()=>{await pt()},we=U=>{if(!W||W.length===0)return!1;if(typeof U=="string")return W.includes(U);const $=`${U.resource}.${U.action}`;return W.includes($)};return{isAuthenticated:K,sessionManager:c,authenticatedHttpService:N,login:le,signup:ce,signupTenantAdmin:rt,sendMagicLink:ot,verifyMagicLink:at,changePassword:nt,requestPasswordReset:st,confirmPasswordReset:it,refreshToken:lt,logout:ct,setTokens:dt,hasValidSession:ut,clearSession:ht,currentUser:v,isUserLoading:I,userError:A,loadUserData:D,refreshUser:ne,isAuthInitializing:!g,isAuthReady:g,userRole:G,userPermissions:W,availableRoles:y,rolesLoading:M,hasPermission:we,hasAnyPermission:U=>U.some($=>we($)),hasAllPermissions:U=>U.every($=>we($)),getUserPermissionStrings:()=>W||[],refreshRoles:ft,userTenants:b,hasTenantContext:C,switchToTenant:async(U,$)=>{const{redirectPath:Z}=$||{},z=c.getTokens();if(!(z!=null&&z.refreshToken))throw new Error("No refresh token available for tenant switch");const Q=await x.switchTenant({refreshToken:z.refreshToken,tenantId:U});c.setTokens({accessToken:Q.accessToken,refreshToken:z.refreshToken,expiresIn:Q.expiresIn}),k(Q.user),c.setUser(Q.user),w(!0);const X=b.find(J=>J.id===U);X&&f(X.subdomain,{tokens:{accessToken:Q.accessToken,refreshToken:z.refreshToken,expiresIn:Q.expiresIn},redirectPath:Z})},refreshUserTenants:async()=>{const U=await c.getAuthHeaders(),$=await x.getUserTenants(U);F($);try{localStorage.setItem("userTenants",JSON.stringify($))}catch{}return $}}},[K,c,N,x,p,S,o,l,h,f,y,v,I,A,b,C,g,G,W]);_.current=H.loadUserData,a.useEffect(()=>{!s.initialRoles&&o&&(async()=>{try{m(!0);const ne=new re(i),le=new Ae(ne),{roles:ce}=await le.getRolesByApp(o);d(ce)}catch(ne){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",ne)}finally{m(!1)}})()},[o,i,s.initialRoles]);const[q,B]=a.useState(!1);return a.useEffect(()=>{q||(B(!0),j.current.urlTokens&&(Tt(),R(!0),H.loadUserData().catch(D=>{process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data after URL tokens:",D)}).finally(()=>{R(!1)})))},[H,q]),a.useEffect(()=>{let D=!1;return(async()=>{var ce;if(!c.hasValidSession()&&((ce=c.getTokens())!=null&&ce.refreshToken)&&await c.waitForPendingRefresh(),D||!c.hasValidSession()&&!c.getTokens()&&s.enableCookieSession&&(await c.attemptCookieSessionRestore(),D))return;const le=c.getUser();le&&c.hasValidSession()&&k(le),L(!1)})(),()=>{D=!0}},[c,s.enableCookieSession]),a.useEffect(()=>{q&&(j.current.urlTokens||(!v&&!I&&!A&&c.hasValidSession()?_.current().catch(()=>{}).finally(()=>{L(!1)}):L(!1)))},[v,I,A,c,q]),r.jsx(Me.Provider,{value:H,children:e})}function oe(){const s=a.useContext(Me);if(!s)throw new Error("useAuth must be used within an AuthProvider");return s}function Ie(){return a.useContext(Me)}class Ge{constructor(e,t){this.httpService=e,this.sessionManager=t}async createFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/feature-flags/",e,{headers:t})).data}async getFeatureFlags(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/feature-flags/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{featureFlags:o.data,meta:o.meta}}async getFeatureFlagById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/feature-flags/${e}`,{headers:t})).data}async updateFeatureFlag(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:n})).data}async deleteFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/feature-flags/${e}`,{headers:t})}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const n=new URLSearchParams;n.append("tenantId",e),n.append("appId",t);const i=`/tenant-feature-flags${n.toString()?`?${n.toString()}`:""}`;return(await this.httpService.get(i,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,n){if(!e||!t||!n)throw new Error("Flag Key, Tenant ID and App ID are required");const i=new URLSearchParams;i.append("tenantId",t),i.append("appId",n);const o=`/tenant-feature-flags/${e}${i.toString()?`?${i.toString()}`:""}`;return(await this.httpService.get(o,{headers:{"X-Tenant-ID":t}})).data}}const Fe=a.createContext(null);function Rt({config:s={},children:e}){const t=Pe(),n=ae(),i=(t==null?void 0:t.baseUrl)??"",o=(t==null?void 0:t.appId)??"",l=(n==null?void 0:n.tenant)??null,[h,f]=a.useState([]),[y,d]=a.useState(!1),[M,m]=a.useState(null),[v,k]=a.useState(!1),I=a.useMemo(()=>{const u=new re(i);return new Ge(u)},[i]),E=async()=>{if(!(l!=null&&l.id)){f([]);return}d(!0),m(null);try{const u=await I.getTenantFeatureFlags(l.id,o);f(u)}catch(u){const b=u instanceof Error?u.message:"Failed to fetch feature flags";m(b),s.onError&&s.onError(u instanceof Error?u:new Error(b))}finally{d(!1)}};a.useEffect(()=>{if(!i||!o)return;E().finally(()=>k(!0));const u=s.refreshInterval||5*60*1e3,b=setInterval(E,u);return()=>clearInterval(b)},[l==null?void 0:l.id,i,o,s.refreshInterval]);const A=a.useMemo(()=>{const u=j=>{const T=h.find(R=>R.key===j);return(T==null?void 0:T.value)===!0},b=j=>h.find(T=>T.key===j),F=j=>{const T=h.find(R=>R.key===j);return T?T.value?"enabled":"disabled":"not_found"},C=async()=>{await E()},w=!!(i&&o)&&(v||!(l!=null&&l.id));return{featureFlags:h,loading:y,error:M,isReady:w,isEnabled:u,getFlag:b,getFlagState:F,refresh:C}},[h,y,M,i,o,l==null?void 0:l.id,v]);return r.jsx(Fe.Provider,{value:A,children:e})}function Ze(){const s=a.useContext(Fe);if(!s)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return s}function Je(){return a.useContext(Fe)}class Qe{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscription(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscriptions/",e,{headers:t})).data}async getSubscriptionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscriptions/subscriptions/${e}`,{headers:t})).data}async updateSubscription(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:n})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:n})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`)).data}async processPayment(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:n})).data}}const Le=a.createContext(void 0);function Et({config:s={},children:e}){const t=Pe(),n=ae(),i=(t==null?void 0:t.baseUrl)??"",o=(n==null?void 0:n.tenant)??null,[l,h]=a.useState(null),[f,y]=a.useState(!1),[d,M]=a.useState(null),[m,v]=a.useState(!1),k=a.useMemo(()=>{const A=new re(i);return new Qe(A)},[i]),I=async()=>{if(!(o!=null&&o.id)){h(null);return}y(!0),M(null);try{const A=await k.getTenantSubscriptionFeatures(o.id);h(A)}catch(A){const u=A instanceof Error?A.message:"Failed to fetch subscription";M(u),s.onError&&s.onError(A instanceof Error?A:new Error(u))}finally{y(!1)}};a.useEffect(()=>{if(!i||(I().finally(()=>v(!0)),!s.refreshInterval))return;const A=s.refreshInterval||10*60*1e3,u=setInterval(I,A);return()=>clearInterval(u)},[o==null?void 0:o.id,i,s.refreshInterval]);const E=a.useMemo(()=>{const A=(l==null?void 0:l.features)||[],u=T=>{const R=A.find(c=>c.key===T);return R?R.type==="BOOLEAN"||R.type==="boolean"?R.value===!0:!!R.value:!1},b=T=>A.find(R=>R.key===T),F=(T,R)=>{const c=A.find(O=>O.key===T);return c?c.value:R},C=T=>!l||!l.isActive?!1:T.includes(l.planId),w=async()=>{await I()},j=!!i&&(m||!(o!=null&&o.id));return{subscription:l,features:A,loading:f,error:d,isReady:j,isFeatureEnabled:u,getFeature:b,getFeatureValue:F,hasAllowedPlan:C,refresh:w}},[l,f,d,i,o==null?void 0:o.id,m]);return r.jsx(Le.Provider,{value:E,children:e})}function Ke(){const s=a.useContext(Le);if(s===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return s}function Ye(){return a.useContext(Le)??null}var te=(s=>(s.SUPERUSER="SUPERUSER",s.TENANT_ADMIN="TENANT_ADMIN",s.USER="USER",s))(te||{});const ye={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},Ne={landing:{tenant:"forbidden",auth:"optional"},publicOnly:{tenant:"forbidden",auth:"forbidden"},login:{tenant:"required",auth:"forbidden"},guest:{auth:"forbidden"},authenticated:{auth:"required"},tenant:{tenant:"required"},tenantOpen:{tenant:"required",auth:"optional"},tenantAuth:{tenant:"required",auth:"required"},user:{tenant:"required",auth:"required",userType:te.USER},admin:{tenant:"required",auth:"required",userType:te.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},Ce=a.createContext(null);function Mt({config:s={},children:e}){const t=a.useMemo(()=>{const n={...ye,...s.zoneRoots},i={...Ne,...s.presets};return{zoneRoots:n,presets:i,loadingFallback:s.loadingFallback??null,accessDeniedFallback:s.accessDeniedFallback??null,onAccessDenied:s.onAccessDenied,returnToParam:s.returnToParam??"returnTo",returnToStorage:s.returnToStorage??"url"}},[s]);return r.jsx(Ce.Provider,{value:t,children:e})}function It(){const s=a.useContext(Ce);if(!s)throw new Error("useRouting must be used within a RoutingProvider");return s}function Xe(){const s=a.useContext(Ce);return s||{zoneRoots:ye,presets:Ne,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"}}const $e=()=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),r.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),r.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),r.jsx("button",{style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},onClick:()=>window.location.href="/login",children:"Sign In"})]}),He=({userType:s,minUserType:e,missingPermissions:t})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#fff3cd",border:"1px solid #ffeaa7",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),r.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&s?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",r.jsx("strong",{children:s})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:"You don't have the required permissions to view this content."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]}),Ft=(s,e)=>{const t={[te.USER]:1,[te.TENANT_ADMIN]:2,[te.SUPERUSER]:3};return t[s]>=t[e]};function Lt({children:s,fallback:e,minUserType:t,requiredPermissions:n,requireAllPermissions:i=!1}){const{hasValidSession:o,sessionManager:l,hasPermission:h,hasAnyPermission:f,hasAllPermissions:y}=oe();if(!o())return r.jsx(r.Fragment,{children:e||r.jsx($e,{})});const d=l.getUser();if(!d)return r.jsx(r.Fragment,{children:e||r.jsx($e,{})});if(t&&!Ft(d.userType,t))return r.jsx(He,{userType:d.userType,minUserType:t});if(n&&n.length>0&&!(i?y(n):f(n))){const m=n.filter(v=>!h(v)).map(v=>typeof v=="string"?v:v.name);return r.jsx(He,{missingPermissions:m})}return r.jsx(r.Fragment,{children:s})}const Nt=({redirectPath:s})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})}),Oe=({userType:s,requiredUserType:e,missingPermissions:t})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&s?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",r.jsx("strong",{children:e})," access."]}),r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current user type: ",r.jsx("strong",{children:s})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]})}),Ct=(s,e)=>s===e;function Dt({children:s,redirectTo:e="/login",requiredUserType:t,requiredPermissions:n,requireAllPermissions:i=!1,fallback:o}){const{hasValidSession:l,sessionManager:h,hasPermission:f,hasAnyPermission:y,hasAllPermissions:d}=oe(),M=se.useLocation();if(a.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] ProtectedRoute is deprecated. Use AuthenticatedZone or AdminZone from ZoneRoute instead.")},[]),!l())return o?r.jsx(r.Fragment,{children:o}):r.jsxs(r.Fragment,{children:[r.jsx(Nt,{redirectPath:e}),r.jsx(se.Navigate,{to:e,state:{from:M.pathname},replace:!0})]});const m=h.getUser();if(!m)return r.jsx(se.Navigate,{to:e,state:{from:M.pathname},replace:!0});if(t&&!Ct(m.userType,t))return r.jsx(Oe,{userType:m.userType,requiredUserType:t});if(n&&n.length>0&&!(i?d(n):y(n))){const k=n.filter(I=>!f(I)).map(I=>typeof I=="string"?I:I.name);return r.jsx(Oe,{missingPermissions:k})}return r.jsx(r.Fragment,{children:s})}const Ut=({redirectPath:s})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function Bt({children:s,redirectTo:e="/",fallback:t}){const{tenant:n,isLoading:i,error:o}=Ee(),l=se.useLocation();return a.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] TenantRoute is deprecated. Use TenantZone from ZoneRoute instead.")},[]),i||o?null:n?r.jsx(r.Fragment,{children:s}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Ut,{redirectPath:e}),r.jsx(se.Navigate,{to:e,state:{from:l.pathname},replace:!0})]})}const $t=({redirectPath:s})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function Ht({children:s,redirectTo:e="/dashboard",fallback:t}){const{tenant:n,isLoading:i,error:o}=Ee(),l=se.useLocation();return a.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] LandingRoute is deprecated. Use PublicZone from ZoneRoute instead.")},[]),i||o?null:n?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx($t,{redirectPath:e}),r.jsx(se.Navigate,{to:e,state:{from:l.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:s})}function Ot(s,e){return e?s?Array.isArray(e)?e.includes(s):s===e:!1:!0}function qe(s,e){return!s||s==="optional"?"skip":s==="required"?e?"pass":"fail":s==="forbidden"?e?"fail":"pass":"skip"}function qt(s,e){return qe(s.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":qe(s.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":s.userType&&e.isAuthenticated&&!Ot(e.userType,s.userType)?"wrong_user_type":s.permissions&&s.permissions.length>0&&!(s.requireAllPermissions!==!1?o=>o.every(l=>e.permissions.includes(l)):o=>o.some(l=>e.permissions.includes(l)))(s.permissions)?"missing_permissions":null}function _t(s,e){return s.hasTenant?s.isAuthenticated?s.userType===te.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:s.isAuthenticated?s.userType===te.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function zt(s,e,t,n,i){if(!e||i!=="url")return s;const o=typeof e=="string"?e:t,l=s.includes("?")?"&":"?";return`${s}${l}${n}=${encodeURIComponent(o)}`}function Vt(s,e,t){if(!s||t==="url")return;const n=typeof s=="string"?s:e,i="zone_return_to";t==="session"?sessionStorage.setItem(i,n):t==="local"&&localStorage.setItem(i,n)}const ie=({children:s,preset:e,tenant:t,auth:n,userType:i,requiredPermissions:o,requireAllPermissions:l=!0,returnTo:h,onAccessDenied:f,redirectTo:y,loadingFallback:d,accessDeniedFallback:M})=>{const m=se.useLocation(),{isAuthenticated:v,isAuthInitializing:k,currentUser:I,userPermissions:E}=oe(),{tenant:A,isTenantLoading:u}=he(),b=Xe(),F=a.useMemo(()=>{if(e)return b.presets[e]},[e,b.presets]),C=a.useMemo(()=>({tenant:t??(F==null?void 0:F.tenant),auth:n??(F==null?void 0:F.auth),userType:i??(F==null?void 0:F.userType),permissions:o??(F==null?void 0:F.requiredPermissions),requireAllPermissions:l}),[t,n,i,o,F,l]),w=a.useMemo(()=>({hasTenant:!!A,isAuthenticated:v,userType:I==null?void 0:I.userType,permissions:E,isLoading:k||u}),[A,v,I==null?void 0:I.userType,E,k,u]),j=a.useMemo(()=>w.isLoading?null:qt(C,w),[C,w]),T=a.useMemo(()=>j?y||_t(w,b.zoneRoots):null,[j,y,w,b.zoneRoots]),R=a.useMemo(()=>!j||!T?null:{type:j,required:{tenant:C.tenant,auth:C.auth,userType:C.userType,permissions:C.permissions},current:{hasTenant:w.hasTenant,isAuthenticated:w.isAuthenticated,userType:w.userType,permissions:w.permissions},redirectTo:T},[j,T,C,w]);if(a.useEffect(()=>{R&&(f?f(R):b.onAccessDenied&&b.onAccessDenied(R))},[R,f,b]),a.useEffect(()=>{R&&h&&Vt(h,m.pathname+m.search,b.returnToStorage)},[R,h,m.pathname,m.search,b.returnToStorage]),w.isLoading)return r.jsx(r.Fragment,{children:d??b.loadingFallback??null});if(R&&T){const c=M??b.accessDeniedFallback;if(c)return r.jsx(r.Fragment,{children:c});const O=zt(T,h,m.pathname+m.search,b.returnToParam,b.returnToStorage);return r.jsx(se.Navigate,{to:O,replace:!0})}return r.jsx(r.Fragment,{children:s})},Wt=s=>r.jsx(ie,{tenant:"required",...s}),Gt=s=>r.jsx(ie,{tenant:"forbidden",...s}),Zt=s=>r.jsx(ie,{auth:"required",...s}),Jt=s=>r.jsx(ie,{auth:"forbidden",...s}),Qt=s=>r.jsx(ie,{auth:"required",userType:te.TENANT_ADMIN,...s}),Kt=s=>r.jsx(ie,{auth:"required",userType:te.USER,...s}),Yt=s=>r.jsx(ie,{tenant:"optional",auth:"optional",...s}),Xt=s=>r.jsx(ie,{tenant:"required",auth:"required",...s}),er=s=>r.jsx(ie,{tenant:"required",auth:"optional",...s}),tr=s=>r.jsx(ie,{tenant:"required",auth:"forbidden",...s}),rr=()=>r.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[r.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),r.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function nr({children:s,fallback:e=r.jsx(rr,{}),allowedPlans:t,requiredFeature:n}){const{subscription:i,hasAllowedPlan:o,isFeatureEnabled:l,loading:h}=Ke();return h?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):i?i.isActive?t&&t.length>0&&!o(t)?r.jsx(r.Fragment,{children:e}):n&&!l(n)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:s}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const sr=({flagName:s})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"15px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",fontFamily:"system-ui, sans-serif",color:"#6c757d"},children:[r.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),r.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),r.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',s,'" is disabled']})]});function ir({name:s,children:e,fallback:t}){const{isEnabled:n,loading:i}=Ze();return i?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):n(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(sr,{flagName:s})})}const or=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),ar=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),lr={showPassword:r.jsx(or,{}),hidePassword:r.jsx(ar,{})},cr={title:"Sign In",usernameLabel:"Email or Phone",usernamePlaceholder:"Enter your email or phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",submitButton:"Sign In",forgotPasswordLink:"Forgot your password?",signupLink:"Sign up here",signupText:"Don't have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Invalid credentials",loadingText:"Signing in...",tenantNotFoundError:"Tenant not found",dividerBullet:"•",showPasswordAriaLabel:"Show password",hidePasswordAriaLabel:"Hide password"},dr={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},inputContainer:{position:"relative",display:"flex",alignItems:"center"},passwordToggle:{position:"absolute",right:"0.75rem",background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"#6b7280",display:"flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",borderRadius:"4px",transition:"background-color 0.15s ease-in-out"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},inputWithIcon:{paddingRight:"2.5rem"}};function ur({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onForgotPassword:o,onSignupClick:l,onMagicLinkClick:h,showForgotPassword:f=!0,showSignupLink:y=!0,showMagicLinkOption:d=!0,className:M}){const[m,v]=a.useState(""),[k,I]=a.useState(""),[E,A]=a.useState(!1),[u,b]=a.useState(!1),[F,C]=a.useState(""),[w,j]=a.useState({}),{login:T}=oe(),R={...cr,...s},c={...dr,...e},O={...lr,...t},L=()=>{const p={};return m.trim()||(p.username=!0),k.trim()||(p.password=!0),j(p),Object.keys(p).length===0},g=async p=>{if(p.preventDefault(),!!L()){b(!0),C("");try{const S=await T({username:m,password:k});n==null||n(S)}catch(S){const P=S.message||R.errorMessage;C(P),i==null||i(P)}finally{b(!1)}}},N=p=>({...c.input,...w[p]?c.inputError:{}}),x=()=>({...c.button,...u?c.buttonLoading:{},...!m||!k||u?c.buttonDisabled:{}});return r.jsxs("div",{className:M,style:c.container,children:[r.jsx("h2",{style:c.title,children:R.title}),r.jsxs("form",{onSubmit:g,style:c.form,children:[r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:R.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:m,onChange:p=>{v(p.target.value),w.username&&j(S=>({...S,username:!1}))},placeholder:R.usernamePlaceholder,style:N("username"),disabled:u})]}),r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:R.passwordLabel}),r.jsxs("div",{style:c.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:E?"text":"password",value:k,onChange:p=>{I(p.target.value),w.password&&j(S=>({...S,password:!1}))},placeholder:R.passwordPlaceholder,style:{...N("password"),...c.inputWithIcon},disabled:u}),r.jsx("button",{type:"button",onClick:()=>A(!E),style:c.passwordToggle,disabled:u,"aria-label":E?R.hidePasswordAriaLabel:R.showPasswordAriaLabel,children:E?O.hidePassword:O.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:!m||!k||u,style:x(),children:u?R.loadingText:R.submitButton}),F&&r.jsx("div",{style:c.errorText,children:F})]}),(f||y||d)&&r.jsxs("div",{style:c.linkContainer,children:[d&&r.jsxs("div",{children:[r.jsxs("span",{style:c.divider,children:[R.magicLinkText," "]}),r.jsx("a",{onClick:h,style:c.link,children:R.magicLinkLink})]}),d&&(f||y)&&r.jsx("div",{style:c.divider,children:R.dividerBullet}),f&&r.jsx("a",{onClick:o,style:c.link,children:R.forgotPasswordLink}),f&&y&&r.jsx("div",{style:c.divider,children:R.dividerBullet}),y&&r.jsxs("div",{children:[r.jsxs("span",{style:c.divider,children:[R.signupText," "]}),r.jsx("a",{onClick:l,style:c.link,children:R.signupLink})]})]})]})}const hr={title:"Create Account",nameLabel:"First Name",namePlaceholder:"Enter your first name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",emailLabel:"Email",emailPlaceholder:"Enter your email",phoneNumberLabel:"Phone Number",phoneNumberPlaceholder:"Enter your phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm your password",tenantNameLabel:"Organization Name",tenantNamePlaceholder:"Enter your organization name",submitButton:"Create Account",loginLink:"Sign in here",loginText:"Already have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Failed to create account",loadingText:"Creating account...",passwordMismatchError:"Passwords do not match",isAdminLabel:"Create new organization",isAdminDescription:"Check this if you want to create a new organization",contactMethodHint:"At least one contact method (email or phone) is required",tenantNotFoundError:"Tenant not found",dividerBullet:"•"},pr={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},checkbox:{marginRight:"0.5rem"},checkboxContainer:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem 0"},checkboxLabel:{fontSize:"0.875rem",color:"#374151",lineHeight:"1.4"},button:{padding:"0.75rem 1rem",backgroundColor:"#10b981",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},hintText:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"}};function fr({copy:s={},styles:e={},signupType:t="user",onSuccess:n,onError:i,onLoginClick:o,onMagicLinkClick:l,showLoginLink:h=!0,showMagicLinkOption:f=!0,className:y}){var q;const[d,M]=a.useState(""),[m,v]=a.useState(""),[k,I]=a.useState(""),[E,A]=a.useState(""),[u,b]=a.useState(""),[F,C]=a.useState(""),[w,j]=a.useState(""),[T,R]=a.useState(!1),[c,O]=a.useState(""),[L,g]=a.useState({}),{signup:N,signupTenantAdmin:x}=oe(),p=((q=ae())==null?void 0:q.tenant)??null,S={...hr,...s},P={...pr,...e},G=()=>{const B={};return d.trim()||(B.name=!0),!k.trim()&&!E.trim()&&(B.email=!0,B.phoneNumber=!0),u.trim()||(B.password=!0),F.trim()||(B.confirmPassword=!0),t==="tenant"&&!w.trim()&&(B.tenantName=!0),g(B),Object.keys(B).length===0},W=async B=>{if(B.preventDefault(),!!G()){if(u!==F){O(S.passwordMismatchError),g({confirmPassword:!0});return}if(t==="user"&&!(p!=null&&p.id)){O(S.tenantNotFoundError);return}R(!0),O("");try{let D;t==="tenant"?D=await x({email:k||void 0,phoneNumber:E||void 0,name:d,password:u,tenantName:w,lastName:m||void 0}):D=await N({email:k||void 0,phoneNumber:E||void 0,name:d,password:u,tenantId:p.id,lastName:m||void 0}),n==null||n(D)}catch(D){const ne=D.message||S.errorMessage;O(ne),i==null||i(ne)}finally{R(!1)}}},K=B=>({...P.input,...L[B]?P.inputError:{}}),_=()=>({...P.button,...T?P.buttonLoading:{},...!d||!k&&!E||!u||!F||T||t==="tenant"&&!w?P.buttonDisabled:{}}),H=d&&(k||E)&&u&&F&&(t==="user"||w);return r.jsxs("div",{className:y,style:P.container,children:[r.jsx("h2",{style:P.title,children:S.title}),r.jsxs("form",{onSubmit:W,style:P.form,children:[r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:d,onChange:B=>{M(B.target.value),L.name&&g(D=>({...D,name:!1}))},placeholder:S.namePlaceholder,style:K("name"),disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:m,onChange:B=>v(B.target.value),placeholder:S.lastNamePlaceholder,style:P.input,disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:k,onChange:B=>{I(B.target.value),L.email&&g(D=>({...D,email:!1,phoneNumber:!1}))},placeholder:S.emailPlaceholder,style:K("email"),disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:E,onChange:B=>{A(B.target.value),L.phoneNumber&&g(D=>({...D,email:!1,phoneNumber:!1}))},placeholder:S.phoneNumberPlaceholder,style:K("phoneNumber"),disabled:T})]}),r.jsx("div",{style:P.hintText,children:S.contactMethodHint}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:u,onChange:B=>{b(B.target.value),L.password&&g(D=>({...D,password:!1}))},placeholder:S.passwordPlaceholder,style:K("password"),disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:F,onChange:B=>{C(B.target.value),L.confirmPassword&&g(D=>({...D,confirmPassword:!1})),c===S.passwordMismatchError&&O("")},placeholder:S.confirmPasswordPlaceholder,style:K("confirmPassword"),disabled:T})]}),t==="tenant"&&r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:w,onChange:B=>{j(B.target.value),L.tenantName&&g(D=>({...D,tenantName:!1}))},placeholder:S.tenantNamePlaceholder,style:K("tenantName"),disabled:T})]}),r.jsx("button",{type:"submit",disabled:!H||T,style:_(),children:T?S.loadingText:S.submitButton}),c&&r.jsx("div",{style:P.errorText,children:c})]}),(h||f)&&r.jsxs("div",{style:P.linkContainer,children:[f&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[S.magicLinkText," "]}),r.jsx("a",{onClick:l,style:P.link,children:S.magicLinkLink})]}),f&&h&&r.jsx("div",{style:P.divider,children:S.dividerBullet}),h&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[S.loginText," "]}),r.jsx("a",{onClick:o,style:P.link,children:S.loginLink})]})]})]})}const gr={title:"Sign In with Magic Link",emailLabel:"Email",emailPlaceholder:"Enter your email",nameLabel:"Name",namePlaceholder:"Enter your name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",submitButton:"Send Magic Link",loginLink:"Sign in with password",signupLink:"Sign up with password",loginText:"Already have an account?",signupText:"Prefer traditional signup?",successMessage:"Magic link sent! Check your email and click the link to sign in.",errorMessage:"Failed to send magic link. Please try again.",loadingText:"Sending magic link...",verifyingText:"Verifying magic link...",verifyingDescription:"Please wait while we verify your magic link...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you.",showNameToggle:"New user? Add your name",hideNameToggle:"Existing user? Hide name fields",tenantNotFoundError:"Tenant not found",missingTenantOrEmailError:"Missing tenant or email",dividerBullet:"•"},mr={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1rem",color:"#333333"},description:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",marginBottom:"1.5rem",lineHeight:"1.5"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem",padding:"0.75rem",backgroundColor:"#f0fdf4",borderRadius:"6px",border:"1px solid #bbf7d0"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},verifyingContainer:{textAlign:"center",padding:"2rem"},verifyingText:{fontSize:"1rem",color:"#6b7280"},toggleContainer:{textAlign:"center",marginTop:"0.5rem"},toggleLink:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"}};function yr({copy:s={},styles:e={},onSuccess:t,onError:n,onLoginClick:i,onSignupClick:o,showTraditionalLinks:l=!0,className:h,verifyToken:f,frontendUrl:y}){var _;const[d,M]=a.useState(""),[m,v]=a.useState(""),[k,I]=a.useState(""),[E,A]=a.useState(!1),[u,b]=a.useState(!1),[F,C]=a.useState(""),[w,j]=a.useState(""),[T,R]=a.useState({}),[c,O]=a.useState(!1),{sendMagicLink:L,verifyMagicLink:g}=oe(),N=((_=ae())==null?void 0:_.tenant)??null,x={...gr,...s},p={...mr,...e};a.useEffect(()=>{f&&S(f)},[f]);const S=async H=>{if(!N||!d){C(x.missingTenantOrEmailError);return}b(!0),C("");try{const q=await g({token:H,email:d});t==null||t(q)}catch(q){const B=q.message||"Failed to verify magic link";C(B),n==null||n(B)}finally{b(!1)}},P=()=>{const H={};return d.trim()||(H.email=!0),c&&!m.trim()&&(H.name=!0),R(H),Object.keys(H).length===0},G=async H=>{if(H.preventDefault(),!!P()){if(!(N!=null&&N.id)){C(x.tenantNotFoundError);return}A(!0),C(""),j("");try{const q=y||(typeof window<"u"?window.location.origin:""),B=await L({email:d,tenantId:N.id,frontendUrl:q,name:c?m:void 0,lastName:c?k:void 0});j(x.successMessage),t==null||t(B)}catch(q){const B=q.message||x.errorMessage;C(B),n==null||n(B)}finally{A(!1)}}},W=H=>({...p.input,...T[H]?p.inputError:{}}),K=()=>({...p.button,...E||u?p.buttonLoading:{},...!d||E||u?p.buttonDisabled:{}});return u?r.jsxs("div",{className:h,style:p.container,children:[r.jsx("h2",{style:p.title,children:x.verifyingText}),r.jsx("div",{style:p.verifyingContainer,children:r.jsx("div",{style:p.verifyingText,children:x.verifyingDescription})})]}):r.jsxs("div",{className:h,style:p.container,children:[r.jsx("h2",{style:p.title,children:x.title}),r.jsx("p",{style:p.description,children:x.description}),r.jsxs("form",{onSubmit:G,style:p.form,children:[r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:x.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:d,onChange:H=>{M(H.target.value),T.email&&R(q=>({...q,email:!1}))},placeholder:x.emailPlaceholder,style:W("email"),disabled:E||u})]}),!c&&r.jsx("div",{style:p.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>O(!0),style:p.toggleLink,children:x.showNameToggle})}),c&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:x.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:m,onChange:H=>{v(H.target.value),T.name&&R(q=>({...q,name:!1}))},placeholder:x.namePlaceholder,style:W("name"),disabled:E||u})]}),r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:x.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:k,onChange:H=>I(H.target.value),placeholder:x.lastNamePlaceholder,style:p.input,disabled:E||u})]}),r.jsx("div",{style:p.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>{O(!1),v(""),I("")},style:p.toggleLink,children:x.hideNameToggle})})]}),r.jsx("button",{type:"submit",disabled:!d||E||u,style:K(),children:E?x.loadingText:x.submitButton}),F&&r.jsx("div",{style:p.errorText,children:F}),w&&r.jsx("div",{style:p.successText,children:w})]}),l&&r.jsxs("div",{style:p.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:p.divider,children:[x.loginText," "]}),r.jsx("a",{onClick:i,style:p.link,children:x.loginLink})]}),r.jsx("div",{style:p.divider,children:x.dividerBullet}),r.jsxs("div",{children:[r.jsxs("span",{style:p.divider,children:[x.signupText," "]}),r.jsx("a",{onClick:o,style:p.link,children:x.signupLink})]})]})]})}const wr={title:"Verifying Magic Link",verifyingMessage:"Please wait while we verify your magic link...",successMessage:"Magic link verified successfully! You are now logged in.",errorMessage:"Failed to verify magic link. The link may be expired or invalid.",redirectingMessage:"Redirecting you to the dashboard...",retryButton:"Try Again",backToLoginButton:"Back to Login",missingParamsError:"Missing required parameters: token or email"},et={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},card:{backgroundColor:"transparent",padding:"0",borderRadius:"0",boxShadow:"none",maxWidth:"100%",width:"100%",textAlign:"center"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},message:{fontSize:"1rem",color:"#6b7280",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},successMessage:{fontSize:"1rem",color:"#059669",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},errorMessage:{fontSize:"0.875rem",color:"#ef4444",textAlign:"center",marginBottom:"1rem",lineHeight:"1.5"},spinner:{display:"inline-block",width:"20px",height:"20px",border:"2px solid #e5e7eb",borderTop:"2px solid #3b82f6",borderRadius:"50%",animation:"spin 1s linear infinite",marginRight:"0.5rem"},buttonContainer:{display:"flex",gap:"0.75rem",justifyContent:"center",flexWrap:"wrap",marginTop:"1rem"},retryButton:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out"},backButton:{padding:"0.75rem 1rem",backgroundColor:"#f3f4f6",color:"#374151",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"all 0.15s ease-in-out"},retryButtonHover:{backgroundColor:"#2563eb"},backButtonHover:{backgroundColor:"#e5e7eb"}},xr=()=>r.jsx("div",{style:et.spinner}),br=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#059669",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),r.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),Sr=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),r.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),vr={loading:r.jsx(xr,{}),success:r.jsx(br,{}),error:r.jsx(Sr,{})};function Tr({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onRetry:o,onBackToLogin:l,className:h,token:f,email:y,appId:d,tenantSlug:M,autoRedirectDelay:m=3e3}){const[v,k]=a.useState("verifying"),[I,E]=a.useState(""),{verifyMagicLink:A}=oe(),u={...wr,...s},b={...et,...e},F={...vr,...t},C=()=>{if(typeof window>"u")return{};const c=new URLSearchParams(window.location.search);return{token:f||c.get("token")||"",email:y||c.get("email")||"",appId:d||c.get("appId")||"",tenantSlug:M||c.get("tenantSlug")||void 0}},w=async()=>{k("verifying"),E("");try{const c=C();if(!c.token||!c.email)throw new Error(u.missingParamsError);const O=await A({token:c.token,email:c.email,tenantSlug:c.tenantSlug});k("success"),n==null||n(O),m>0&&setTimeout(()=>{k("redirecting")},m)}catch(c){const O=c.message||u.errorMessage;E(O),k("error"),i==null||i(O)}},j=()=>{o==null||o(),w()},T=()=>{l==null||l()};a.useEffect(()=>{w()},[]);const R=()=>{switch(v){case"verifying":return r.jsxs("div",{style:b.message,children:[F.loading,u.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[F.success,r.jsx("div",{style:b.successMessage,children:u.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[F.loading,r.jsx("div",{style:b.message,children:u.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[F.error,r.jsx("div",{style:b.errorMessage,children:I||u.errorMessage}),r.jsxs("div",{style:b.buttonContainer,children:[r.jsx("button",{onClick:j,style:b.retryButton,onMouseOver:c=>{Object.assign(c.currentTarget.style,b.retryButtonHover)},onMouseOut:c=>{const O=b.retryButton||{};Object.keys(b.retryButtonHover||{}).forEach(L=>{c.currentTarget.style[L]=O[L]??""})},children:u.retryButton}),r.jsx("button",{onClick:T,style:b.backButton,onMouseOver:c=>{Object.assign(c.currentTarget.style,b.backButtonHover)},onMouseOut:c=>{const O=b.backButton||{};Object.keys(b.backButtonHover||{}).forEach(L=>{c.currentTarget.style[L]=O[L]??""})},children:u.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:b.container,className:h,children:[r.jsx("style",{children:`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),o=require("react"),re=require("react-router-dom");class oe{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async executeRequest(e,t,s,i){const l=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,c=(i==null?void 0:i.timeout)||this.timeout;let h={"Content-Type":"application/json",...i==null?void 0:i.headers};if(!(i!=null&&i.skipAuth)&&this.sessionManager){const u=await this.sessionManager.getValidAccessToken();h={...h,Authorization:`Bearer ${u}`}}const v=new AbortController,j=setTimeout(()=>v.abort(),c);try{const u=await fetch(l,{method:e,headers:h,body:s?JSON.stringify(s):void 0,signal:v.signal});if(clearTimeout(j),!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);const S=u.headers.get("content-type");return!S||!S.includes("application/json")?{}:await u.json()}catch(u){throw clearTimeout(j),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${c}ms`):u}}async get(e,t){return this.executeRequest("GET",e,void 0,t)}async post(e,t,s){return this.executeRequest("POST",e,t,s)}async put(e,t,s){return this.executeRequest("PUT",e,t,s)}async delete(e,t){return this.executeRequest("DELETE",e,void 0,t)}}function ne(n){if(!n)return"";const e=new URLSearchParams;for(const[s,i]of Object.entries(n))i!=null&&i!==""&&e.append(s,String(i));const t=e.toString();return t?`?${t}`:""}class Ee{constructor(e){this.httpService=e}async createApp(e){return(await this.httpService.post("/apps/",e)).data}async getApps(e){const t=await this.httpService.get(`/apps/${ne(e)}`);return{apps:t.data,meta:t.meta}}async getAppById(e){return(await this.httpService.get(`/apps/${e}`)).data}async updateApp(e,t){return(await this.httpService.put(`/apps/${e}`,t)).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`,{skipAuth:!0})).data}async setDefaultSubscriptionPlan(e,t){return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t})).data}async updateSettingsSchema(e,t,s){return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:s})).data}async exportConfig(e){return(await this.httpService.get(`/apps/${e}/export-config`)).data}}const je=o.createContext(null),pt=5*60*1e3;function ft({config:n,children:e}){var T,m,g;const{appId:t,baseUrl:s}=n,i=((T=n.cache)==null?void 0:T.enabled)??!0,l=((m=n.cache)==null?void 0:m.ttl)??pt,c=((g=n.cache)==null?void 0:g.storageKey)??`app_cache_${t}`,[h,v]=o.useState(()=>{if(!i)return null;try{const b=localStorage.getItem(c);if(!b)return null;const L=JSON.parse(b);return Date.now()-L.timestamp<l&&L.appId===t?L.data:(localStorage.removeItem(c),null)}catch{return null}}),[j,u]=o.useState(!h),[S,p]=o.useState(null),E=o.useRef(h);E.current=h;const P=o.useCallback(async(b=!1)=>{if(!(!b&&i&&E.current))try{u(!0),p(null);const a=await new Ee(new oe(s)).getPublicAppInfo(t);if(v(a),i)try{const f={data:a,timestamp:Date.now(),appId:t};localStorage.setItem(c,JSON.stringify(f))}catch(f){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Failed to cache app info:",f)}}catch(L){const a=L instanceof Error?L:new Error("Failed to load app information");p(a),v(null)}finally{u(!1)}},[s,t,i,c]),R=o.useCallback(async()=>{if(!(!i||!E.current))try{const b=localStorage.getItem(c);if(!b)return;const L=JSON.parse(b);if(Date.now()-L.timestamp<=l*.5)return;const f=await new Ee(new oe(s)).getPublicAppInfo(t);v(f);const k={data:f,timestamp:Date.now(),appId:t};localStorage.setItem(c,JSON.stringify(k))}catch(b){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Background app refresh failed:",b)}},[s,t,i,l,c]),A=o.useMemo(()=>({appId:t,baseUrl:s,appInfo:h,isAppLoading:j,appError:S,retryApp:()=>{P(!0)}}),[t,s,h,j,S,P]);return o.useEffect(()=>{E.current?R():P()},[]),r.jsx(je.Provider,{value:A,children:e})}function de(){const n=o.useContext(je);if(!n)throw new Error("useApp must be used within an AppProvider");return n}function Ae(){return o.useContext(je)}const mt=de;class H extends Error{constructor(e,t){const s={token_expired:"Refresh token has expired",token_invalid:"Refresh token is invalid",user_inactive:"User account is inactive"};super(t||s[e]),this.name="SessionExpiredError",this.reason=e}}class Ge extends Error{constructor(e){super(`Token refresh timed out after ${e}ms`),this.name="TokenRefreshTimeoutError",this.timeoutMs=e}}class Ze extends Error{constructor(e,t){super(`Token refresh failed after ${e} attempts: ${(t==null?void 0:t.message)||"Unknown error"}`),this.name="TokenRefreshError",this.attempts=e,this.lastError=t}}const Q=class Q{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],this.proactiveTimerId=null,this.backgroundRetryTimerId=null,this.isDestroyed=!1,this.sessionGeneration=0,this.consecutiveBackgroundFailures=0,this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.onSessionExpired=e.onSessionExpired,this.baseUrl=e.baseUrl||"",this.enableCookieSession=e.enableCookieSession??!1,this.proactiveRefreshMargin=e.proactiveRefreshMargin??6e4,this.refreshQueueTimeout=e.refreshQueueTimeout??1e4,this.maxRefreshRetries=e.maxRefreshRetries??3,this.retryBackoffBase=e.retryBackoffBase??1e3,this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey),this.scheduleProactiveRefresh()}static getInstance(e={}){const t=Q.resolveStorageKey(e),s=Q.instances.get(t);if(s)return s.updateConfig(e),s;const i=new Q(e);return Q.instances.set(t,i),i}static resetAllInstances(){for(const e of Q.instances.values())e.destroy();Q.instances.clear()}static resolveStorageKey(e){return e.storageKey||"auth_tokens"}updateConfig(e){e.onSessionExpired!==void 0&&(this.onSessionExpired=e.onSessionExpired),e.onRefreshFailed!==void 0&&(this.onRefreshFailed=e.onRefreshFailed),e.baseUrl&&(this.baseUrl=e.baseUrl),e.enableCookieSession!==void 0&&(this.enableCookieSession=e.enableCookieSession)}createTokenStorage(e){return{get:()=>{try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},set:t=>{try{localStorage.setItem(e,JSON.stringify(t))}catch{}},clear:()=>{try{localStorage.removeItem(e)}catch{}}}}static decodeJwtPayload(e){try{const t=e.split(".");return t.length!==3?null:JSON.parse(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}static extractJwtExpiry(e){const t=Q.decodeJwtPayload(e);return typeof(t==null?void 0:t.exp)=="number"?t.exp*1e3:void 0}static extractJwtClaim(e,t){const s=Q.decodeJwtPayload(e),i=s==null?void 0:s[t];return typeof i=="string"?i:void 0}setTokens(e){const t=e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)||Q.extractJwtExpiry(e.accessToken),s={...e,expiresAt:t},i=this.tokenStorage.get()||{};this.tokenStorage.set({...i,...s}),this.scheduleProactiveRefresh()}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:s,expiresIn:i,tokenType:l}=this.tokenStorage.get()||{};if(!e)return null;const c=s||Q.extractJwtExpiry(e);return{accessToken:e,refreshToken:t,expiresAt:c,expiresIn:i,tokenType:l}}clearTokens(){this.tokenStorage.clear()}isTokenExpired(e){const t=e||this.getTokens();return t!=null&&t.expiresAt?Date.now()>=t.expiresAt:!1}shouldRefreshToken(e){const t=e||this.getTokens();return!(t!=null&&t.expiresAt)||!this.autoRefresh?!1:Date.now()>=t.expiresAt-this.refreshThreshold}getAccessToken(){const e=this.getTokens();return(e==null?void 0:e.accessToken)||null}scheduleProactiveRefresh(){if(this.cancelProactiveTimer(),!this.autoRefresh||this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.expiresAt)||!e.refreshToken)return;const s=e.expiresAt-this.proactiveRefreshMargin-Date.now();if(s<=0){this.backgroundRefresh();return}this.proactiveTimerId=setTimeout(()=>{this.backgroundRefresh()},s)}cancelProactiveTimer(){this.proactiveTimerId!==null&&(clearTimeout(this.proactiveTimerId),this.proactiveTimerId=null),this.backgroundRetryTimerId!==null&&(clearTimeout(this.backgroundRetryTimerId),this.backgroundRetryTimerId=null)}backgroundRefresh(){if(this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.refreshToken)||this.refreshPromise)return;const t=this.sessionGeneration;this.startRefreshAndResolveQueue(e.refreshToken).then(()=>{this.consecutiveBackgroundFailures=0}).catch(s=>{if(!(s instanceof H)){if(this.sessionGeneration===t){if(this.consecutiveBackgroundFailures++,this.consecutiveBackgroundFailures>=Q.MAX_BACKGROUND_FAILURES){process.env.NODE_ENV==="development"&&console.error(`[SessionManager] Background refresh failed ${this.consecutiveBackgroundFailures} consecutive times — expiring session`),this.consecutiveBackgroundFailures=0,this.handleSessionExpired(new H("token_invalid","Background refresh failed repeatedly"));return}process.env.NODE_ENV==="development"&&console.warn("[SessionManager] Background refresh failed, retrying in 30s:",s.message),this.backgroundRetryTimerId=setTimeout(()=>{this.backgroundRefresh()},3e4)}}})}async waitForPendingRefresh(){if(!this.refreshPromise)return!1;try{return await this.refreshPromise,!0}catch{return!1}}async attemptCookieSessionRestore(){if(!this.enableCookieSession||!this.baseUrl)return!1;const e=`${this.baseUrl}/auth/refresh`;try{const t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),credentials:"include"});if(!t.ok)return!1;const s=await t.json();return s.accessToken?(this.setTokens({accessToken:s.accessToken,refreshToken:s.refreshToken||"",expiresIn:s.expiresIn}),!0):!1}catch{return!1}}async getValidAccessToken(){const e=this.getTokens();if(!(e!=null&&e.accessToken)){const t=new H("token_invalid","No tokens available");throw this.handleSessionExpired(t),t}if(!this.shouldRefreshToken(e)&&!this.isTokenExpired(e))return e.accessToken;if(!e.refreshToken){const t=new H("token_invalid","No refresh token available");throw this.handleSessionExpired(t),t}return this.refreshPromise?this.enqueueForToken():this.startRefreshAndResolveQueue(e.refreshToken)}async getAuthHeaders(){try{return{Authorization:`Bearer ${await this.getValidAccessToken()}`}}catch(e){return e instanceof H&&this.onRefreshFailed&&this.onRefreshFailed(),{}}}enqueueForToken(){return new Promise((e,t)=>{const s=setTimeout(()=>{const i=this.refreshQueue.findIndex(l=>l.timeoutId===s);i!==-1&&this.refreshQueue.splice(i,1),t(new Ge(this.refreshQueueTimeout))},this.refreshQueueTimeout);this.refreshQueue.push({resolve:e,reject:t,timeoutId:s})})}async startRefreshAndResolveQueue(e){this.refreshPromise=this.executeRefreshWithRetry(e);try{await this.refreshPromise;const t=this.getTokens(),s=(t==null?void 0:t.accessToken)||"";return this.resolveQueue(s),s}catch(t){const s=t instanceof Error?t:new Error("Token refresh failed");throw s instanceof H?(this.rejectQueue(s),this.handleSessionExpired(s)):this.rejectQueue(s),s}finally{this.refreshPromise=null}}resolveQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const s of t)clearTimeout(s.timeoutId),s.resolve(e)}rejectQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const s of t)clearTimeout(s.timeoutId),s.reject(e)}async executeRefreshWithRetry(e){let t;const s=this.sessionGeneration;for(let i=0;i<=this.maxRefreshRetries;i++){if(this.sessionGeneration!==s)throw new H("token_invalid","Session cleared during refresh");try{await this.performTokenRefresh(e,s);return}catch(l){const c=l instanceof Error?l:new Error(String(l));if(c instanceof H)throw c;if(t=c,i<this.maxRefreshRetries){const h=this.retryBackoffBase*Math.pow(2,i);await this.sleep(h)}}}throw new Ze(this.maxRefreshRetries+1,t)}async performTokenRefresh(e,t){return typeof navigator<"u"&&navigator.locks?navigator.locks.request(`session-refresh:${this.storageKey}`,()=>this.performTokenRefreshInner(e,t)):this.performTokenRefreshInner(e,t)}async performTokenRefreshInner(e,t){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const s=this.getTokens();if(s!=null&&s.accessToken&&!this.isTokenExpired(s)&&!this.shouldRefreshToken(s))return;const i=(s==null?void 0:s.refreshToken)||e,l=`${this.baseUrl}/auth/refresh`,c=Q.extractJwtClaim(i,"deviceId"),h={refreshToken:i};c&&(h.deviceId=c);let v;try{v=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h),...this.enableCookieSession&&{credentials:"include"}})}catch(u){throw u instanceof Error?u:new Error("Network error during token refresh")}if(!v.ok){let u="";try{const S=await v.json();u=(S.message||S.error||"").toLowerCase()}catch{u=v.statusText.toLowerCase()}throw v.status===401?u.includes("expired")?new H("token_expired"):u.includes("invalid")?new H("token_invalid"):new H("token_invalid",`Unauthorized: ${u}`):v.status===400?u.includes("inactive")?new H("user_inactive"):u.includes("expired")||u.includes("invalid")?new H("token_invalid",u):u.includes("reuse")||u.includes("revoked")?new H("token_invalid",u):new Error(`Token refresh failed (400): ${u}`):new Error(`Token refresh failed: ${v.status} ${u}`)}if(this.sessionGeneration!==t)throw new H("token_invalid","Session cleared during refresh");const j=await v.json();this.setTokens({accessToken:j.accessToken,refreshToken:j.refreshToken||i,expiresIn:j.expiresIn})}handleSessionExpired(e){this.cancelProactiveTimer(),this.clearSession(),this.onSessionExpired?this.onSessionExpired(e):this.onRefreshFailed&&this.onRefreshFailed()}setUser(e){const t=this.tokenStorage.get()||{};this.tokenStorage.set({...t,user:e})}getUser(){const e=this.tokenStorage.get();return(e==null?void 0:e.user)||null}clearUser(){const e=this.tokenStorage.get()||{};delete e.user,this.tokenStorage.set(e)}clearSession(){this.sessionGeneration++,this.cancelProactiveTimer(),this.clearTokens();const e=new H("token_invalid","Session cleared");this.rejectQueue(e)}destroy(){this.isDestroyed=!0,Q.instances.delete(this.storageKey),this.cancelProactiveTimer();const e=new H("token_invalid","SessionManager destroyed");this.rejectQueue(e)}getTokenPayload(){var t;const e=(t=this.getTokens())==null?void 0:t.accessToken;return e?Q.decodeJwtPayload(e)??null:null}getUserId(){const e=this.getTokenPayload();if(e!=null&&e.userId)return e.userId;const t=this.getUser();return(t==null?void 0:t.id)||null}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}sleep(e){return new Promise(t=>setTimeout(t,e))}};Q.instances=new Map,Q.MAX_BACKGROUND_FAILURES=3;let me=Q;class He{constructor(e){this.httpService=e,this.pendingVerifications=new Map}async login(e){return await this.httpService.post("/auth/login",e)}async signup(e){return await this.httpService.post("/auth/signup",e)}async signupTenantAdmin(e){return await this.httpService.post("/auth/signup/tenant-admin",e)}async refreshToken(e){return await this.httpService.post("/auth/refresh",e)}async switchTenant(e){return await this.httpService.post("/auth/switch-tenant",e)}async getUserTenants(){return this.httpService.get("/auth/tenants")}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e)}async sendMagicLink(e){return await this.httpService.post("/auth/magic-link/send",e)}async verifyMagicLink(e){const t=e.token,s=this.pendingVerifications.get(t);if(s)return s;const i=this.httpService.post("/auth/magic-link/verify",e).finally(()=>{this.pendingVerifications.delete(t)});return this.pendingVerifications.set(t,i),i}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e)}async changePassword(e){await this.httpService.post("/auth/change-password",e)}}class Qe{constructor(e){this.httpService=e}async createRole(e){return(await this.httpService.post("/roles/",e)).data}async getRoleById(e){return(await this.httpService.get(`/roles/${e}`)).data}async updateRole(e,t){return(await this.httpService.put(`/roles/${e}`,t)).data}async deleteRole(e){await this.httpService.delete(`/roles/${e}`)}async getRolesByApp(e,t){const s=await this.httpService.get(`/roles/app/${e}${ne(t)}`,{skipAuth:!0});return{roles:s.data,meta:s.meta}}async assignRole(e,t){await this.httpService.post(`/roles/${e}/assign`,t)}async revokeRole(e,t){await this.httpService.post(`/roles/${e}/revoke`,t)}async getUserRoles(e,t){const s=await this.httpService.get(`/roles/user/${e}${ne(t)}`);return{roles:s.data,meta:s.meta}}}class Je{constructor(e){this.httpService=e}async createUser(e){return(await this.httpService.post("/users/",e)).data}async getUsers(e){const t=await this.httpService.get(`/users/${ne(e)}`);return{users:t.data,meta:t.meta}}async getUserById(e){return(await this.httpService.get(`/users/${e}`)).data}async updateUser(e,t){return(await this.httpService.put(`/users/${e}`,t)).data}async deleteUser(e){await this.httpService.delete(`/users/${e}`)}}class le{constructor(e,t){this.httpService=e,this.appId=t}async createTenant(e){return(await this.httpService.post("/tenants/",e)).data}async getTenants(e){const t=await this.httpService.get(`/tenants/${ne(e)}`);return{tenants:t.data,meta:t.meta}}async getTenantById(e){return(await this.httpService.get(`/tenants/${e}`)).data}async updateTenant(e,t){return(await this.httpService.put(`/tenants/${e}`,t)).data}async adminUpdateTenant(e,t){return(await this.httpService.put(`/tenants/${e}/admin-update`,t)).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`,{skipAuth:!0})).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`,{skipAuth:!0})).data}async updateTenantSettings(e,t){return(await this.httpService.put(`/tenants/${e}/settings`,t)).data}}function gt(n,e){if(n==="localhost"||n.startsWith("127.")||n.startsWith("192.168."))return null;if(e){const i=e.toLowerCase(),l=n.toLowerCase();if(l===i||l===`www.${i}`)return null;if(l.endsWith(`.${i}`)){const c=l.slice(0,-(i.length+1));return c==="www"?null:c}return null}const s=n.split(".");return s.length>=3&&s[0]!=="www"?s[0]:null}function yt(n,e="tenant",t){const i=new URLSearchParams(n).get(e);return i?(t&&t.setItem("tenant",i),i):t?t.getItem("tenant"):null}function bt(n,e,t){const{tenantMode:s,baseDomain:i,selectorParam:l,fixedTenantSlug:c}=n;return s==="fixed"?c||null:s==="subdomain"?gt(e.hostname,i):s==="selector"?yt(e.search,l,t):null}function xt(n,e,t){if(t)return`${n}.${t}`;const s=e.split(".");return s.length===2?`${n}.${e}`:s.length>=3?(s[0]=n,s.join(".")):null}const Pe=o.createContext(null);function wt({config:n,children:e}){var _,Z,M;const{baseUrl:t,appInfo:s,appId:i}=de(),l=o.useCallback(()=>typeof window>"u"?null:bt({tenantMode:n.tenantMode||"selector",baseDomain:n.baseDomain,selectorParam:n.selectorParam,fixedTenantSlug:n.fixedTenantSlug},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[n.tenantMode,n.baseDomain,n.selectorParam,n.fixedTenantSlug]),[c,h]=o.useState(()=>l()),v=((_=n.cache)==null?void 0:_.enabled)??!0,j=((Z=n.cache)==null?void 0:Z.ttl)??5*60*1e3,u=((M=n.cache)==null?void 0:M.storageKey)??`tenant_cache_${c||"default"}`,S=o.useMemo(()=>({enabled:v,ttl:j,storageKey:u}),[v,j,u]),[p,E]=o.useState(()=>{if(n.initialTenant)return n.initialTenant;if(!S.enabled||!c)return null;try{const D=localStorage.getItem(S.storageKey);if(!D)return null;const F=JSON.parse(D);return Date.now()-F.timestamp<S.ttl&&F.tenantSlug===c?F.data:(localStorage.removeItem(S.storageKey),null)}catch{return null}}),[P,R]=o.useState(!p&&!n.initialTenant),[A,T]=o.useState(null),[m,g]=o.useState(null),[b,L]=o.useState(!1),[a,f]=o.useState(null);o.useEffect(()=>{if(n.tenantMode==="fixed")return;const D=l();h(D)},[l,n.tenantMode]);const k=(s==null?void 0:s.settingsSchema)||null,y=o.useCallback(async(D,F=!1)=>{if(!(!F&&S.enabled&&p&&p.subdomain===D))try{R(!0),T(null);const B=new oe(t),q=await new le(B,i).getPublicTenantInfo(D);if(E(q),S.enabled)try{const J={data:q,timestamp:Date.now(),tenantSlug:D};localStorage.setItem(S.storageKey,JSON.stringify(J))}catch(J){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Failed to cache tenant info:",J)}}catch(B){const U=B instanceof Error?B:new Error("Failed to load tenant information");T(U),E(null)}finally{R(!1)}},[t,i,S,p]),d=o.useCallback(async()=>{if(!(!S.enabled||!p||!c))try{const D=localStorage.getItem(S.storageKey);if(!D)return;const F=JSON.parse(D);if(Date.now()-F.timestamp>S.ttl*.5){const U=new oe(t),J=await new le(U,i).getPublicTenantInfo(c);E(J);const K={data:J,timestamp:Date.now(),tenantSlug:c};localStorage.setItem(S.storageKey,JSON.stringify(K))}}catch(D){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Background tenant refresh failed:",D)}},[t,i,S,p,c]),w=o.useCallback(async()=>{if(p!=null&&p.id)try{L(!0),f(null);const D=new oe(t),B=await new le(D,p.appId).getTenantSettings(p.id);g(B)}catch(D){const F=D instanceof Error?D:new Error("Failed to load tenant settings");f(F),g(null)}finally{L(!1)}},[t,p]),N=o.useCallback(()=>{w()},[w]),X=o.useCallback(D=>{if(!k)return{isValid:!0,errors:[]};const F=[];try{return k.properties&&Object.entries(k.properties).forEach(([B,U])=>{var J;const q=D[B];if((J=k.required)!=null&&J.includes(B)&&q==null){F.push(`Field '${B}' is required`);return}if(q!=null){if(U.type){const K=U.type,te=typeof q;K==="string"&&te!=="string"?F.push(`Field '${B}' must be a string`):(K==="number"||K==="integer")&&te!=="number"?F.push(`Field '${B}' must be a number`):K==="boolean"&&te!=="boolean"?F.push(`Field '${B}' must be a boolean`):K==="array"&&!Array.isArray(q)&&F.push(`Field '${B}' must be an array`)}U.minLength!==void 0&&typeof q=="string"&&q.length<U.minLength&&F.push(`Field '${B}' must be at least ${U.minLength} characters long`),U.maxLength!==void 0&&typeof q=="string"&&q.length>U.maxLength&&F.push(`Field '${B}' must be no more than ${U.maxLength} characters long`),U.minimum!==void 0&&typeof q=="number"&&q<U.minimum&&F.push(`Field '${B}' must be at least ${U.minimum}`),U.maximum!==void 0&&typeof q=="number"&&q>U.maximum&&F.push(`Field '${B}' must be no more than ${U.maximum}`),U.pattern&&typeof q=="string"&&(new RegExp(U.pattern).test(q)||F.push(`Field '${B}' does not match the required pattern`)),U.enum&&!U.enum.includes(q)&&F.push(`Field '${B}' must be one of: ${U.enum.join(", ")}`)}}),{isValid:F.length===0,errors:F}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[k]);o.useEffect(()=>{!n.initialTenant&&c?p?d():y(c):!n.initialTenant&&!c&&(E(null),T(null),R(!1))},[n.initialTenant,c,p,y,d]),o.useEffect(()=>{p!=null&&p.id?w():(g(null),f(null),L(!1))},[p==null?void 0:p.id,w]);const I=o.useCallback((D,F)=>{const{mode:B="reload",redirectPath:U}=F||{},q=n.tenantMode||"selector";if(q==="fixed"){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] switchTenant is a no-op in fixed mode. Tenant is always:",n.fixedTenantSlug),U&&(window.location.href=U);return}if(localStorage.setItem("tenant",D),q==="subdomain"){const J=window.location.hostname,K=xt(D,J,n.baseDomain);if(!K){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",J);return}const te=U||window.location.pathname,he=new URL(`${window.location.protocol}//${K}${te}`);new URLSearchParams(window.location.search).forEach((ve,Se)=>{he.searchParams.set(Se,ve)}),window.location.href=he.toString()}else if(q==="selector"){const J=U||window.location.pathname,K=new URLSearchParams(window.location.search);if(K.set(n.selectorParam||"tenant",D),B==="reload"){const te=`${J}?${K.toString()}${window.location.hash}`;window.location.href=te}else{const te=`${J}?${K.toString()}${window.location.hash}`;window.history.pushState({},"",te),h(D),y(D)}}},[n.tenantMode,n.selectorParam,n.baseDomain,n.fixedTenantSlug,y]),z=o.useMemo(()=>({tenant:p,tenantSlug:c,isTenantLoading:P,tenantError:A,retryTenant:()=>{c&&y(c)},settings:m,settingsSchema:k,isSettingsLoading:b,settingsError:a,refreshSettings:N,switchTenant:I,validateSettings:X}),[p,c,P,A,m,k,b,a,N,I,X]);return r.jsx(Pe.Provider,{value:z,children:e})}function ce(){const n=o.useContext(Pe);if(!n)throw new Error("useTenant must be used within a TenantProvider");return n}function ae(){return o.useContext(Pe)}const vt=ce;function St(){const{settings:n,settingsSchema:e,isSettingsLoading:t,settingsError:s,validateSettings:i}=ce();return{settings:n,settingsSchema:e,isLoading:t,error:s,validateSettings:i}}function Re(){const{tenant:n,tenantSlug:e,isTenantLoading:t,tenantError:s,retryTenant:i}=ce();return{tenant:n,tenantSlug:e,isLoading:t,error:s,retry:i}}const Fe="userTenants";function Tt(){try{const n=localStorage.getItem(Fe);return n?JSON.parse(n):[]}catch{return[]}}function Be(n){try{localStorage.setItem(Fe,JSON.stringify(n))}catch{}}function Oe(){try{localStorage.removeItem(Fe)}catch{}}const ge=o.createContext(null),ye=o.createContext(null);function kt({config:n={},children:e}){const t=Ae(),s=ae(),i=(t==null?void 0:t.baseUrl)??n.baseUrl??"",l=(t==null?void 0:t.appId)??n.appId,c=(s==null?void 0:s.tenant)??null,h=(s==null?void 0:s.tenantSlug)??null,v=(s==null?void 0:s.switchTenant)??(()=>{});if(!i)throw new Error("[AuthProvider] baseUrl is required. Provide it via AppProvider or AuthConfig.baseUrl.");const[j,u]=o.useState(n.initialRoles||[]),[S,p]=o.useState(!n.initialRoles),[E,P]=o.useState(null),[R,A]=o.useState(!1),[T,m]=o.useState(null),[g,b]=o.useState(()=>Tt()),L=o.useRef({done:!1});L.current.done||(L.current.done=!0);const a=o.useMemo(()=>me.getInstance({baseUrl:i,enableCookieSession:n.enableCookieSession,refreshQueueTimeout:n.refreshQueueTimeout,proactiveRefreshMargin:n.proactiveRefreshMargin,onSessionExpired:x=>{P(null),m(null),b([]),Oe(),n.onSessionExpired?n.onSessionExpired(x):n.onRefreshFailed&&n.onRefreshFailed()}}),[i,n.enableCookieSession,n.refreshQueueTimeout,n.proactiveRefreshMargin]),[f,k]=o.useState(()=>{const x=a.getTokens();return x?a.hasValidSession()||!!x.refreshToken:!!n.enableCookieSession}),y=L.current.done&&!f,d=o.useMemo(()=>{const x=new oe(i);return x.setSessionManager(a),x},[i,a]),w=o.useMemo(()=>new He(d),[d]),N=o.useMemo(()=>new Je(d),[d]),X=o.useMemo(()=>new Qe(d),[d]),I=o.useMemo(()=>E!=null&&E.roleId&&j.find(x=>x.id===E.roleId)||null,[E,j]),z=o.useMemo(()=>(I==null?void 0:I.permissions)||[],[I]),_=o.useMemo(()=>a.hasValidSession()&&E!==null,[a,E]),Z=o.useMemo(()=>(E==null?void 0:E.tenantId)!=null,[E]),M=o.useRef(null),D=async(x=!1)=>{try{if(!a.hasValidSession()||!x&&E)return;const C=a.getUserId();if(!C){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] No userId available in token or storage");return}A(!0),m(null);const O=await N.getUserById(C);P(O),a.setUser(O)}catch(C){const O=C instanceof Error?C:new Error("Failed to load user data");m(O),process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data:",O)}finally{A(!1)}},F=async x=>{var Ue;const{username:C,password:O,tenantSlug:$,redirectPath:W}=x;let Y=c==null?void 0:c.id,G=h;$&&(Y=(await new le(d,l).getPublicTenantInfo($)).id,G=$);const V=await w.login({username:C,password:O,appId:l,tenantId:Y}),pe=$&&$!==h;if(a.setTokens({accessToken:V.accessToken,refreshToken:V.refreshToken,expiresIn:V.expiresIn}),V.user){a.setUser(V.user),P(V.user);try{await D()}catch(fe){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after login:",fe)}}V.tenants&&V.tenants.length>0&&(b(V.tenants),Be(V.tenants));const De=((Ue=V.user)==null?void 0:Ue.tenantId)!==null;if(pe&&G)return v(G,{redirectPath:W}),V;if(W&&W!==window.location.pathname)return v(G||h||"",{redirectPath:W}),V;if(!De&&V.tenants&&V.tenants.length>0){const fe=x.autoSwitch!==!1&&n.autoSwitchSingleTenant!==!1;if(V.tenants.length===1&&fe){const $e=V.tenants[0];return v($e.subdomain,{redirectPath:W}),V}else V.tenants.length>1&&n.onTenantSelectionRequired&&n.onTenantSelectionRequired(V.tenants)}return V},B=async x=>{const{email:C,phoneNumber:O,name:$,password:W,lastName:Y,tenantId:G}=x;if(!C&&!O)throw new Error("Either email or phoneNumber is required");if(!$||!W)throw new Error("Name and password are required");return w.signup({email:C,phoneNumber:O,name:$,password:W,tenantId:G??(c==null?void 0:c.id),lastName:Y,appId:l})},U=async x=>{const{email:C,phoneNumber:O,name:$,password:W,tenantName:Y,lastName:G}=x;if(!C&&!O)throw new Error("Either email or phoneNumber is required");if(!$||!W||!Y)throw new Error("Name, password, and tenantName are required");return w.signupTenantAdmin({email:C,phoneNumber:O,name:$,password:W,tenantName:Y,appId:l,lastName:G})},q=async x=>{await w.changePassword(x)},J=async x=>{const{email:C,tenantId:O}=x,$=O??(c==null?void 0:c.id);if(!$)throw new Error("tenantId is required for password reset");await w.requestPasswordReset({email:C,tenantId:$})},K=async x=>{await w.confirmPasswordReset(x)},te=async x=>{const{email:C,frontendUrl:O,name:$,lastName:W,tenantId:Y}=x,G=Y??(c==null?void 0:c.id);if(!G)throw new Error("tenantId is required for magic link authentication");return w.sendMagicLink({email:C,tenantId:G,frontendUrl:O,name:$,lastName:W,appId:l})},he=async x=>{const{token:C,email:O,tenantSlug:$}=x;let W=c==null?void 0:c.id,Y=h;$&&(W=(await new le(d,l).getPublicTenantInfo($)).id,Y=$);const G=await w.verifyMagicLink({token:C,email:O,appId:l,tenantId:W}),V=$&&$!==h;if(a.setTokens({accessToken:G.accessToken,refreshToken:G.refreshToken,expiresIn:G.expiresIn}),G.user){a.setUser(G.user),P(G.user);try{await D()}catch(pe){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after magic link:",pe)}}return V&&Y&&Y!==h&&v(Y),G},Me=async()=>{const x=a.getTokens();if(!(x!=null&&x.refreshToken))throw new Error("No refresh token available");const C=await w.refreshToken({refreshToken:x.refreshToken});a.setTokens({accessToken:C.accessToken,refreshToken:C.refreshToken||x.refreshToken,expiresIn:C.expiresIn})},ve=()=>{a.clearSession(),P(null),m(null),b([]),Oe()},Se=x=>{a.setTokens(x)},ot=()=>a.hasValidSession(),at=()=>{a.clearSession(),P(null),m(null)},lt=async()=>{if(l)try{p(!0);const{roles:x}=await X.getRolesByApp(l);u(x)}catch(x){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",x)}finally{p(!1)}},ct=async(x,C)=>{const{redirectPath:O}=C||{},$=a.getTokens();if(!($!=null&&$.refreshToken))throw new Error("No refresh token available for tenant switch");const W=await w.switchTenant({refreshToken:$.refreshToken,tenantId:x});a.setTokens({accessToken:W.accessToken,refreshToken:$.refreshToken,expiresIn:W.expiresIn}),P(W.user),a.setUser(W.user);const Y=g.find(G=>G.id===x);Y&&v(Y.subdomain,{redirectPath:O})},ut=async()=>{const x=await w.getUserTenants();return b(x),Be(x),x};M.current={login:F,signup:B,signupTenantAdmin:U,sendMagicLink:te,verifyMagicLink:he,changePassword:q,requestPasswordReset:J,confirmPasswordReset:K,refreshToken:Me,logout:ve,setTokens:Se,hasValidSession:ot,clearSession:at,loadUserData:D,refreshUser:()=>D(),refreshRoles:lt,switchToTenant:ct,refreshUserTenants:ut};const dt=o.useMemo(()=>({login:x=>M.current.login(x),signup:x=>M.current.signup(x),signupTenantAdmin:x=>M.current.signupTenantAdmin(x),sendMagicLink:x=>M.current.sendMagicLink(x),verifyMagicLink:x=>M.current.verifyMagicLink(x),changePassword:x=>M.current.changePassword(x),requestPasswordReset:x=>M.current.requestPasswordReset(x),confirmPasswordReset:x=>M.current.confirmPasswordReset(x),refreshToken:()=>M.current.refreshToken(),logout:()=>M.current.logout(),setTokens:x=>M.current.setTokens(x),hasValidSession:()=>M.current.hasValidSession(),clearSession:()=>M.current.clearSession(),loadUserData:x=>M.current.loadUserData(x),refreshUser:()=>M.current.refreshUser(),refreshRoles:()=>M.current.refreshRoles(),switchToTenant:(x,C)=>M.current.switchToTenant(x,C),refreshUserTenants:()=>M.current.refreshUserTenants()}),[]),ht=o.useMemo(()=>{const x=C=>!z||z.length===0?!1:typeof C=="string"?z.includes(C):z.includes(`${C.resource}.${C.action}`);return{isAuthenticated:_,isAuthInitializing:!y,isAuthReady:y,currentUser:E,isUserLoading:R,userError:T,userRole:I,userPermissions:z,availableRoles:j,rolesLoading:S,userTenants:g,hasTenantContext:Z,sessionManager:a,authenticatedHttpService:d,hasPermission:x,hasAnyPermission:C=>C.some(O=>x(O)),hasAllPermissions:C=>C.every(O=>x(O)),getUserPermissionStrings:()=>z||[]}},[_,y,E,R,T,I,z,j,S,g,Z,a,d]);return o.useEffect(()=>{if(n.initialRoles||!l)return;let x=!1;return p(!0),X.getRolesByApp(l).then(({roles:C})=>{x||u(C)}).catch(C=>{process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",C)}).finally(()=>{x||p(!1)}),()=>{x=!0}},[l,n.initialRoles,X]),o.useEffect(()=>{let x=!1;return(async()=>{var $;if(!a.hasValidSession()&&(($=a.getTokens())!=null&&$.refreshToken)&&await a.waitForPendingRefresh(),x||!a.hasValidSession()&&!a.getTokens()&&n.enableCookieSession&&(await a.attemptCookieSessionRestore(),x))return;const O=a.getUser();O&&a.hasValidSession()&&P(O),k(!1)})(),()=>{x=!0}},[a,n.enableCookieSession]),o.useEffect(()=>{!E&&!R&&!T&&a.hasValidSession()?M.current.loadUserData().catch(()=>{}).finally(()=>{k(!1)}):k(!1)},[E,R,T,a]),r.jsx(ye.Provider,{value:dt,children:r.jsx(ge.Provider,{value:ht,children:e})})}function Et(){const n=o.useContext(ge);if(!n)throw new Error("useAuthState must be used within an AuthProvider");return n}function jt(){const n=o.useContext(ye);if(!n)throw new Error("useAuthActions must be used within an AuthProvider");return n}function ie(){const n=o.useContext(ge),e=o.useContext(ye);if(!n||!e)throw new Error("useAuth must be used within an AuthProvider");return o.useMemo(()=>({...n,...e}),[n,e])}function be(){const n=o.useContext(ge),e=o.useContext(ye);return o.useMemo(()=>!n||!e?null:{...n,...e},[n,e])}class Ke{constructor(e){this.httpService=e}async createFeatureFlag(e){return(await this.httpService.post("/feature-flags/",e)).data}async getFeatureFlags(e){const t=await this.httpService.get(`/feature-flags/${ne(e)}`);return{featureFlags:t.data,meta:t.meta}}async getFeatureFlagById(e){return(await this.httpService.get(`/feature-flags/${e}`)).data}async updateFeatureFlag(e,t){return(await this.httpService.put(`/feature-flags/${e}`,t)).data}async deleteFeatureFlag(e){await this.httpService.delete(`/feature-flags/${e}`)}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const s=ne({tenantId:e,appId:t});return(await this.httpService.get(`/tenant-feature-flags${s}`,{headers:{"X-Tenant-ID":e},skipAuth:!0})).data}async getTenantFeatureFlag(e,t,s){if(!e||!t||!s)throw new Error("Flag Key, Tenant ID and App ID are required");const i=ne({tenantId:t,appId:s});return(await this.httpService.get(`/tenant-feature-flags/${e}${i}`,{headers:{"X-Tenant-ID":t},skipAuth:!0})).data}}const Ie=o.createContext(null);function At({config:n={},children:e}){const t=Ae(),s=ae(),i=(t==null?void 0:t.baseUrl)??"",l=(t==null?void 0:t.appId)??"",c=(s==null?void 0:s.tenant)??null,[h,v]=o.useState([]),[j,u]=o.useState(!1),[S,p]=o.useState(null),[E,P]=o.useState(!1),R=o.useMemo(()=>{const m=new oe(i);return new Ke(m)},[i]),A=async()=>{if(!(c!=null&&c.id)){v([]);return}u(!0),p(null);try{const m=await R.getTenantFeatureFlags(c.id,l);v(m)}catch(m){const g=m instanceof Error?m.message:"Failed to fetch feature flags";p(g),n.onError&&n.onError(m instanceof Error?m:new Error(g))}finally{u(!1)}};o.useEffect(()=>{if(!i||!l)return;A().finally(()=>P(!0));const m=n.refreshInterval||5*60*1e3,g=setInterval(A,m);return()=>clearInterval(g)},[c==null?void 0:c.id,i,l,n.refreshInterval]);const T=o.useMemo(()=>{const m=f=>{const k=h.find(y=>y.key===f);return(k==null?void 0:k.value)===!0},g=f=>h.find(k=>k.key===f),b=f=>{const k=h.find(y=>y.key===f);return k?k.value?"enabled":"disabled":"not_found"},L=async()=>{await A()},a=!!(i&&l)&&(E||!(c!=null&&c.id));return{featureFlags:h,loading:j,error:S,isReady:a,isEnabled:m,getFlag:g,getFlagState:b,refresh:L}},[h,j,S,i,l,c==null?void 0:c.id,E]);return r.jsx(Ie.Provider,{value:T,children:e})}function Ye(){const n=o.useContext(Ie);if(!n)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return n}function Xe(){return o.useContext(Ie)}class et{constructor(e){this.httpService=e}async createSubscription(e){return(await this.httpService.post("/subscriptions/",e)).data}async getSubscriptionById(e){return(await this.httpService.get(`/subscriptions/subscriptions/${e}`)).data}async updateSubscription(e,t){return(await this.httpService.put(`/subscriptions/${e}`,t)).data}async changeSubscriptionPlan(e,t){return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`,{skipAuth:!0})).data}async processPayment(e,t){return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t)).data}}const Le=o.createContext(void 0);function Pt({config:n={},children:e}){const t=Ae(),s=ae(),i=(t==null?void 0:t.baseUrl)??"",l=(s==null?void 0:s.tenant)??null,[c,h]=o.useState(null),[v,j]=o.useState(!1),[u,S]=o.useState(null),[p,E]=o.useState(!1),P=o.useMemo(()=>{const T=new oe(i);return new et(T)},[i]),R=async()=>{if(!(l!=null&&l.id)){h(null);return}j(!0),S(null);try{const T=await P.getTenantSubscriptionFeatures(l.id);h(T)}catch(T){const m=T instanceof Error?T.message:"Failed to fetch subscription";S(m),n.onError&&n.onError(T instanceof Error?T:new Error(m))}finally{j(!1)}};o.useEffect(()=>{if(!i||(R().finally(()=>E(!0)),!n.refreshInterval))return;const T=n.refreshInterval||10*60*1e3,m=setInterval(R,T);return()=>clearInterval(m)},[l==null?void 0:l.id,i,n.refreshInterval]);const A=o.useMemo(()=>{const T=(c==null?void 0:c.features)||[],m=k=>{const y=T.find(d=>d.key===k);return y?y.type==="BOOLEAN"||y.type==="boolean"?y.value===!0:!!y.value:!1},g=k=>T.find(y=>y.key===k),b=(k,y)=>{const d=T.find(w=>w.key===k);return d?d.value:y},L=k=>!c||!c.isActive?!1:k.includes(c.planId),a=async()=>{await R()},f=!!i&&(p||!(l!=null&&l.id));return{subscription:c,features:T,loading:v,error:u,isReady:f,isFeatureEnabled:m,getFeature:g,getFeatureValue:b,hasAllowedPlan:L,refresh:a}},[c,v,u,i,l==null?void 0:l.id,p]);return r.jsx(Le.Provider,{value:A,children:e})}function tt(){const n=o.useContext(Le);if(n===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return n}function rt(){return o.useContext(Le)??null}var ee=(n=>(n.SUPERUSER="SUPERUSER",n.TENANT_ADMIN="TENANT_ADMIN",n.USER="USER",n))(ee||{});const xe={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},Ne={landing:{tenant:"forbidden",auth:"optional"},publicOnly:{tenant:"forbidden",auth:"forbidden"},login:{tenant:"required",auth:"forbidden"},guest:{auth:"forbidden"},authenticated:{auth:"required"},tenant:{tenant:"required"},tenantOpen:{tenant:"required",auth:"optional"},tenantAuth:{tenant:"required",auth:"required"},user:{tenant:"required",auth:"required",userType:ee.USER},admin:{tenant:"required",auth:"required",userType:ee.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},Ce=o.createContext(null),Rt={zoneRoots:xe,presets:Ne,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"};function Ft({config:n={},children:e}){const t=o.useMemo(()=>{const s={...xe,...n.zoneRoots},i={...Ne,...n.presets};return{zoneRoots:s,presets:i,loadingFallback:n.loadingFallback??null,accessDeniedFallback:n.accessDeniedFallback??null,onAccessDenied:n.onAccessDenied,returnToParam:n.returnToParam??"returnTo",returnToStorage:n.returnToStorage??"url"}},[n]);return r.jsx(Ce.Provider,{value:t,children:e})}function It(){const n=o.useContext(Ce);if(!n)throw new Error("useRouting must be used within a RoutingProvider");return n}function nt(){return o.useContext(Ce)??Rt}const _e=()=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),r.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),r.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),r.jsx("button",{style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},onClick:()=>window.location.href="/login",children:"Sign In"})]}),qe=({userType:n,minUserType:e,missingPermissions:t})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#fff3cd",border:"1px solid #ffeaa7",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),r.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&n?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",r.jsx("strong",{children:n})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:"You don't have the required permissions to view this content."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]}),Lt=(n,e)=>{const t={[ee.USER]:1,[ee.TENANT_ADMIN]:2,[ee.SUPERUSER]:3};return t[n]>=t[e]};function Nt({children:n,fallback:e,minUserType:t,requiredPermissions:s,requireAllPermissions:i=!1}){const{hasValidSession:l,sessionManager:c,hasPermission:h,hasAnyPermission:v,hasAllPermissions:j}=ie();if(!l())return r.jsx(r.Fragment,{children:e||r.jsx(_e,{})});const u=c.getUser();if(!u)return r.jsx(r.Fragment,{children:e||r.jsx(_e,{})});if(t&&!Lt(u.userType,t))return r.jsx(qe,{userType:u.userType,minUserType:t});if(s&&s.length>0&&!(i?j(s):v(s))){const p=s.filter(E=>!h(E)).map(E=>typeof E=="string"?E:E.name);return r.jsx(qe,{missingPermissions:p})}return r.jsx(r.Fragment,{children:n})}const Ct=({redirectPath:n})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",n,"..."]})]})}),Ve=({userType:n,requiredUserType:e,missingPermissions:t})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&n?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",r.jsx("strong",{children:e})," access."]}),r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current user type: ",r.jsx("strong",{children:n})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]})}),Mt=(n,e)=>n===e;function Dt({children:n,redirectTo:e="/login",requiredUserType:t,requiredPermissions:s,requireAllPermissions:i=!1,fallback:l}){const{hasValidSession:c,sessionManager:h,hasPermission:v,hasAnyPermission:j,hasAllPermissions:u}=ie(),S=re.useLocation();if(o.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] ProtectedRoute is deprecated. Use AuthenticatedZone or AdminZone from ZoneRoute instead.")},[]),!c())return l?r.jsx(r.Fragment,{children:l}):r.jsxs(r.Fragment,{children:[r.jsx(Ct,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:S.pathname},replace:!0})]});const p=h.getUser();if(!p)return r.jsx(re.Navigate,{to:e,state:{from:S.pathname},replace:!0});if(t&&!Mt(p.userType,t))return r.jsx(Ve,{userType:p.userType,requiredUserType:t});if(s&&s.length>0&&!(i?u(s):j(s))){const P=s.filter(R=>!v(R)).map(R=>typeof R=="string"?R:R.name);return r.jsx(Ve,{missingPermissions:P})}return r.jsx(r.Fragment,{children:n})}const Ut=({redirectPath:n})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",n,"..."]})]})});function $t({children:n,redirectTo:e="/",fallback:t}){const{tenant:s,isLoading:i,error:l}=Re(),c=re.useLocation();return o.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] TenantRoute is deprecated. Use TenantZone from ZoneRoute instead.")},[]),i||l?null:s?r.jsx(r.Fragment,{children:n}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Ut,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:c.pathname},replace:!0})]})}const Bt=({redirectPath:n})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",n,"..."]})]})});function Ot({children:n,redirectTo:e="/dashboard",fallback:t}){const{tenant:s,isLoading:i,error:l}=Re(),c=re.useLocation();return o.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] LandingRoute is deprecated. Use PublicZone from ZoneRoute instead.")},[]),i||l?null:s?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Bt,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:c.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:n})}function _t(n,e){return e?n?Array.isArray(e)?e.includes(n):n===e:!1:!0}function ze(n,e){return!n||n==="optional"?"skip":n==="required"?e?"pass":"fail":n==="forbidden"?e?"fail":"pass":"skip"}function qt(n,e){return ze(n.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":ze(n.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":n.userType&&e.isAuthenticated&&!_t(e.userType,n.userType)?"wrong_user_type":n.permissions&&n.permissions.length>0&&!(n.requireAllPermissions!==!1?l=>l.every(c=>e.permissions.includes(c)):l=>l.some(c=>e.permissions.includes(c)))(n.permissions)?"missing_permissions":null}function Vt(n,e){return n.hasTenant?n.isAuthenticated?n.userType===ee.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:n.isAuthenticated?n.userType===ee.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function zt(n,e,t,s,i){if(!e||i!=="url")return n;const l=typeof e=="string"?e:t,c=n.includes("?")?"&":"?";return`${n}${c}${s}=${encodeURIComponent(l)}`}function Wt(n,e,t){if(!n||t==="url")return;const s=typeof n=="string"?n:e,i="zone_return_to";t==="session"?sessionStorage.setItem(i,s):t==="local"&&localStorage.setItem(i,s)}const se=({children:n,preset:e,tenant:t,auth:s,userType:i,requiredPermissions:l,requireAllPermissions:c=!0,returnTo:h,onAccessDenied:v,redirectTo:j,loadingFallback:u,accessDeniedFallback:S})=>{const p=re.useLocation(),{isAuthenticated:E,isAuthInitializing:P,currentUser:R,userPermissions:A}=ie(),{tenant:T,isTenantLoading:m}=ce(),g=nt(),b=o.useMemo(()=>{if(e)return g.presets[e]},[e,g.presets]),L=o.useMemo(()=>({tenant:t??(b==null?void 0:b.tenant),auth:s??(b==null?void 0:b.auth),userType:i??(b==null?void 0:b.userType),permissions:l??(b==null?void 0:b.requiredPermissions),requireAllPermissions:c}),[t,s,i,l,b,c]),a=o.useMemo(()=>({hasTenant:!!T,isAuthenticated:E,userType:R==null?void 0:R.userType,permissions:A,isLoading:P||m}),[T,E,R==null?void 0:R.userType,A,P,m]),f=o.useMemo(()=>a.isLoading?null:qt(L,a),[L,a]),k=o.useMemo(()=>f?j||Vt(a,g.zoneRoots):null,[f,j,a,g.zoneRoots]),y=o.useMemo(()=>!f||!k?null:{type:f,required:{tenant:L.tenant,auth:L.auth,userType:L.userType,permissions:L.permissions},current:{hasTenant:a.hasTenant,isAuthenticated:a.isAuthenticated,userType:a.userType,permissions:a.permissions},redirectTo:k},[f,k,L,a]);if(o.useEffect(()=>{y&&(v?v(y):g.onAccessDenied&&g.onAccessDenied(y))},[y,v,g]),o.useEffect(()=>{y&&h&&Wt(h,p.pathname+p.search,g.returnToStorage)},[y,h,p.pathname,p.search,g.returnToStorage]),a.isLoading)return r.jsx(r.Fragment,{children:u??g.loadingFallback??null});if(y&&k){const d=S??g.accessDeniedFallback;if(d)return r.jsx(r.Fragment,{children:d});const w=zt(k,h,p.pathname+p.search,g.returnToParam,g.returnToStorage);return r.jsx(re.Navigate,{to:w,replace:!0})}return r.jsx(r.Fragment,{children:n})},Gt=n=>r.jsx(se,{tenant:"required",...n}),Zt=n=>r.jsx(se,{tenant:"forbidden",...n}),Ht=n=>r.jsx(se,{auth:"required",...n}),Qt=n=>r.jsx(se,{auth:"forbidden",...n}),Jt=n=>r.jsx(se,{auth:"required",userType:ee.TENANT_ADMIN,...n}),Kt=n=>r.jsx(se,{auth:"required",userType:ee.USER,...n}),Yt=n=>r.jsx(se,{tenant:"optional",auth:"optional",...n}),Xt=n=>r.jsx(se,{tenant:"required",auth:"required",...n}),er=n=>r.jsx(se,{tenant:"required",auth:"optional",...n}),tr=n=>r.jsx(se,{tenant:"required",auth:"forbidden",...n}),rr=()=>r.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[r.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),r.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function nr({children:n,fallback:e=r.jsx(rr,{}),allowedPlans:t,requiredFeature:s}){const{subscription:i,hasAllowedPlan:l,isFeatureEnabled:c,loading:h}=tt();return h?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):i?i.isActive?t&&t.length>0&&!l(t)?r.jsx(r.Fragment,{children:e}):s&&!c(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:n}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const sr=({flagName:n})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"15px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",fontFamily:"system-ui, sans-serif",color:"#6c757d"},children:[r.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),r.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),r.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',n,'" is disabled']})]});function ir({name:n,children:e,fallback:t}){const{isEnabled:s,loading:i}=Ye();return i?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):s(n)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(sr,{flagName:n})})}function ue(n){const{submit:e,defaultErrorMessage:t,validate:s,onSuccess:i,onError:l}=n,[c,h]=o.useState(!1),[v,j]=o.useState(""),[u,S]=o.useState({}),p=o.useCallback((A,T)=>{S(m=>({...m,[A]:T}))},[]),E=o.useCallback(A=>{S(T=>{if(!T[A])return T;const m={...T};return delete m[A],m})},[]),P=o.useCallback(()=>{j(""),S({})},[]),R=o.useCallback(async A=>{if(A&&A.preventDefault(),!(s&&!s())){h(!0),j("");try{const T=await e();return i==null||i(T),T}catch(T){const m=T instanceof Error?T.message:t;j(m),l==null||l(m);return}finally{h(!1)}}},[e,s,t,i,l]);return{loading:c,error:v,setError:j,fieldErrors:u,setFieldError:p,clearFieldError:E,resetErrors:P,handleSubmit:R}}const We={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},inputContainer:{position:"relative",display:"flex",alignItems:"center"},passwordToggle:{position:"absolute",right:"0.75rem",background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"#6b7280",display:"flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",borderRadius:"4px",transition:"background-color 0.15s ease-in-out"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},inputWithIcon:{paddingRight:"2.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem",padding:"0.75rem",backgroundColor:"#f0fdf4",borderRadius:"6px",border:"1px solid #bbf7d0"},hintText:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"},description:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",marginBottom:"1.5rem",lineHeight:"1.5"},verifyingContainer:{textAlign:"center",padding:"2rem"},verifyingText:{fontSize:"1rem",color:"#6b7280"},toggleContainer:{textAlign:"center",marginTop:"0.5rem"},toggleLink:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},modeSwitchDivider:{margin:"0 0.5rem",color:"#6b7280"}};function we(n,e){return{...We,...e,button:{...We.button,backgroundColor:n,...(e==null?void 0:e.button)||{}}}}const or=()=>o.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0}},o.createElement("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),o.createElement("circle",{cx:"12",cy:"12",r:"3"})),ar=()=>o.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0}},o.createElement("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),o.createElement("line",{x1:"1",y1:"1",x2:"23",y2:"23"})),lr={showPassword:r.jsx(or,{}),hidePassword:r.jsx(ar,{})},cr={title:"Sign In",usernameLabel:"Email or Phone",usernamePlaceholder:"Enter your email or phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",submitButton:"Sign In",forgotPasswordLink:"Forgot your password?",signupLink:"Sign up here",signupText:"Don't have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Invalid credentials",loadingText:"Signing in...",tenantNotFoundError:"Tenant not found",dividerBullet:"•",showPasswordAriaLabel:"Show password",hidePasswordAriaLabel:"Hide password"};function ur({copy:n={},styles:e={},icons:t={},onSuccess:s,onError:i,onForgotPassword:l,onSignupClick:c,onMagicLinkClick:h,showForgotPassword:v=!0,showSignupLink:j=!0,showMagicLinkOption:u=!0,className:S}){const[p,E]=o.useState(""),[P,R]=o.useState(""),[A,T]=o.useState(!1),{login:m}=ie(),g={...cr,...n},b=we("#3b82f6",e),L={...lr,...t},a=ue({defaultErrorMessage:g.errorMessage,validate:()=>{const d=[];return p.trim()||d.push("username"),P.trim()||d.push("password"),d.forEach(w=>a.setFieldError(w,!0)),d.length===0},submit:()=>m({username:p,password:P}),onSuccess:s,onError:i}),f=d=>({...b.input,...a.fieldErrors[d]?b.inputError:{}}),k=!p||!P||a.loading,y={...b.button,...a.loading?b.buttonLoading:{},...k?b.buttonDisabled:{}};return r.jsxs("div",{className:S,style:b.container,children:[r.jsx("h2",{style:b.title,children:g.title}),r.jsxs("form",{onSubmit:a.handleSubmit,style:b.form,children:[r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:g.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:p,onChange:d=>{E(d.target.value),a.clearFieldError("username")},placeholder:g.usernamePlaceholder,style:f("username"),disabled:a.loading})]}),r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:g.passwordLabel}),r.jsxs("div",{style:b.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:A?"text":"password",value:P,onChange:d=>{R(d.target.value),a.clearFieldError("password")},placeholder:g.passwordPlaceholder,style:{...f("password"),...b.inputWithIcon},disabled:a.loading}),r.jsx("button",{type:"button",onClick:()=>T(!A),style:b.passwordToggle,disabled:a.loading,"aria-label":A?g.hidePasswordAriaLabel:g.showPasswordAriaLabel,children:A?L.hidePassword:L.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:k,style:y,children:a.loading?g.loadingText:g.submitButton}),a.error&&r.jsx("div",{style:b.errorText,children:a.error})]}),(v||j||u)&&r.jsxs("div",{style:b.linkContainer,children:[u&&r.jsxs("div",{children:[r.jsxs("span",{style:b.divider,children:[g.magicLinkText," "]}),r.jsx("a",{onClick:h,style:b.link,children:g.magicLinkLink})]}),u&&(v||j)&&r.jsx("div",{style:b.divider,children:g.dividerBullet}),v&&r.jsx("a",{onClick:l,style:b.link,children:g.forgotPasswordLink}),v&&j&&r.jsx("div",{style:b.divider,children:g.dividerBullet}),j&&r.jsxs("div",{children:[r.jsxs("span",{style:b.divider,children:[g.signupText," "]}),r.jsx("a",{onClick:c,style:b.link,children:g.signupLink})]})]})]})}const dr={title:"Create Account",nameLabel:"First Name",namePlaceholder:"Enter your first name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",emailLabel:"Email",emailPlaceholder:"Enter your email",phoneNumberLabel:"Phone Number",phoneNumberPlaceholder:"Enter your phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm your password",tenantNameLabel:"Organization Name",tenantNamePlaceholder:"Enter your organization name",submitButton:"Create Account",loginLink:"Sign in here",loginText:"Already have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Failed to create account",loadingText:"Creating account...",passwordMismatchError:"Passwords do not match",isAdminLabel:"Create new organization",isAdminDescription:"Check this if you want to create a new organization",contactMethodHint:"At least one contact method (email or phone) is required",tenantNotFoundError:"Tenant not found",dividerBullet:"•"};function hr({copy:n={},styles:e={},signupType:t="user",onSuccess:s,onError:i,onLoginClick:l,onMagicLinkClick:c,showLoginLink:h=!0,showMagicLinkOption:v=!0,className:j}){var D;const[u,S]=o.useState(""),[p,E]=o.useState(""),[P,R]=o.useState(""),[A,T]=o.useState(""),[m,g]=o.useState(""),[b,L]=o.useState(""),[a,f]=o.useState(""),{signup:k,signupTenantAdmin:y}=ie(),d=((D=ae())==null?void 0:D.tenant)??null,w={...dr,...n},N=we("#10b981",e),X=!!u&&(!!P||!!A)&&!!m&&!!b&&(t==="user"||!!a),I=ue({defaultErrorMessage:w.errorMessage,validate:()=>{const F=[];return u.trim()||F.push("name"),!P.trim()&&!A.trim()&&(F.push("email"),F.push("phoneNumber")),m.trim()||F.push("password"),b.trim()||F.push("confirmPassword"),t==="tenant"&&!a.trim()&&F.push("tenantName"),F.forEach(B=>I.setFieldError(B,!0)),F.length>0?!1:m!==b?(I.setError(w.passwordMismatchError),I.setFieldError("confirmPassword",!0),!1):t==="user"&&!(d!=null&&d.id)?(I.setError(w.tenantNotFoundError),!1):!0},submit:async()=>t==="tenant"?y({email:P||void 0,phoneNumber:A||void 0,name:u,password:m,tenantName:a,lastName:p||void 0}):k({email:P||void 0,phoneNumber:A||void 0,name:u,password:m,tenantId:d.id,lastName:p||void 0}),onSuccess:s,onError:i}),z=F=>({...N.input,...I.fieldErrors[F]?N.inputError:{}}),_=!X||I.loading,Z={...N.button,...I.loading?N.buttonLoading:{},..._?N.buttonDisabled:{}},M=()=>{I.clearFieldError("email"),I.clearFieldError("phoneNumber")};return r.jsxs("div",{className:j,style:N.container,children:[r.jsx("h2",{style:N.title,children:w.title}),r.jsxs("form",{onSubmit:I.handleSubmit,style:N.form,children:[r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:u,onChange:F=>{S(F.target.value),I.clearFieldError("name")},placeholder:w.namePlaceholder,style:z("name"),disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:p,onChange:F=>E(F.target.value),placeholder:w.lastNamePlaceholder,style:N.input,disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:P,onChange:F=>{R(F.target.value),M()},placeholder:w.emailPlaceholder,style:z("email"),disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:A,onChange:F=>{T(F.target.value),M()},placeholder:w.phoneNumberPlaceholder,style:z("phoneNumber"),disabled:I.loading})]}),r.jsx("div",{style:N.hintText,children:w.contactMethodHint}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:m,onChange:F=>{g(F.target.value),I.clearFieldError("password")},placeholder:w.passwordPlaceholder,style:z("password"),disabled:I.loading})]}),r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:b,onChange:F=>{L(F.target.value),I.clearFieldError("confirmPassword"),I.error===w.passwordMismatchError&&I.setError("")},placeholder:w.confirmPasswordPlaceholder,style:z("confirmPassword"),disabled:I.loading})]}),t==="tenant"&&r.jsxs("div",{style:N.fieldGroup,children:[r.jsx("label",{style:N.label,children:w.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:a,onChange:F=>{f(F.target.value),I.clearFieldError("tenantName")},placeholder:w.tenantNamePlaceholder,style:z("tenantName"),disabled:I.loading})]}),r.jsx("button",{type:"submit",disabled:_,style:Z,children:I.loading?w.loadingText:w.submitButton}),I.error&&r.jsx("div",{style:N.errorText,children:I.error})]}),(h||v)&&r.jsxs("div",{style:N.linkContainer,children:[v&&r.jsxs("div",{children:[r.jsxs("span",{style:N.divider,children:[w.magicLinkText," "]}),r.jsx("a",{onClick:c,style:N.link,children:w.magicLinkLink})]}),v&&h&&r.jsx("div",{style:N.divider,children:w.dividerBullet}),h&&r.jsxs("div",{children:[r.jsxs("span",{style:N.divider,children:[w.loginText," "]}),r.jsx("a",{onClick:l,style:N.link,children:w.loginLink})]})]})]})}const pr={title:"Sign In with Magic Link",emailLabel:"Email",emailPlaceholder:"Enter your email",nameLabel:"Name",namePlaceholder:"Enter your name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",submitButton:"Send Magic Link",loginLink:"Sign in with password",signupLink:"Sign up with password",loginText:"Already have an account?",signupText:"Prefer traditional signup?",successMessage:"Magic link sent! Check your email and click the link to sign in.",errorMessage:"Failed to send magic link. Please try again.",loadingText:"Sending magic link...",verifyingText:"Verifying magic link...",verifyingDescription:"Please wait while we verify your magic link...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you.",showNameToggle:"New user? Add your name",hideNameToggle:"Existing user? Hide name fields",tenantNotFoundError:"Tenant not found",missingTenantOrEmailError:"Missing tenant or email",dividerBullet:"•"};function fr({copy:n={},styles:e={},onSuccess:t,onError:s,onLoginClick:i,onSignupClick:l,showTraditionalLinks:c=!0,className:h,verifyToken:v,frontendUrl:j}){var z;const[u,S]=o.useState(""),[p,E]=o.useState(""),[P,R]=o.useState(""),[A,T]=o.useState(!1),[m,g]=o.useState(""),[b,L]=o.useState(!1),{sendMagicLink:a,verifyMagicLink:f}=ie(),k=((z=ae())==null?void 0:z.tenant)??null,y={...pr,...n},d=we("#3b82f6",e),w=ue({defaultErrorMessage:y.errorMessage,validate:()=>{const _=[];return u.trim()||_.push("email"),b&&!p.trim()&&_.push("name"),_.forEach(Z=>w.setFieldError(Z,!0)),_.length>0?!1:k!=null&&k.id?!0:(w.setError(y.tenantNotFoundError),!1)},submit:async()=>{g("");const _=j||(typeof window<"u"?window.location.origin:""),Z=await a({email:u,tenantId:k.id,frontendUrl:_,name:b?p:void 0,lastName:b?P:void 0});return g(y.successMessage),Z},onSuccess:t,onError:s});o.useEffect(()=>{if(!v)return;(async()=>{if(!k||!u){w.setError(y.missingTenantOrEmailError);return}T(!0),w.setError("");try{const Z=await f({token:v,email:u});t==null||t(Z)}catch(Z){const M=Z instanceof Error?Z.message:"Failed to verify magic link";w.setError(M),s==null||s(M)}finally{T(!1)}})()},[v]);const N=_=>({...d.input,...w.fieldErrors[_]?d.inputError:{}}),X=!u||w.loading||A,I={...d.button,...w.loading||A?d.buttonLoading:{},...X?d.buttonDisabled:{}};return A?r.jsxs("div",{className:h,style:d.container,children:[r.jsx("h2",{style:d.title,children:y.verifyingText}),r.jsx("div",{style:d.verifyingContainer,children:r.jsx("div",{style:d.verifyingText,children:y.verifyingDescription})})]}):r.jsxs("div",{className:h,style:d.container,children:[r.jsx("h2",{style:d.title,children:y.title}),r.jsx("p",{style:d.description,children:y.description}),r.jsxs("form",{onSubmit:w.handleSubmit,style:d.form,children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:y.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:u,onChange:_=>{S(_.target.value),w.clearFieldError("email")},placeholder:y.emailPlaceholder,style:N("email"),disabled:w.loading||A})]}),!b&&r.jsx("div",{style:d.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>L(!0),style:d.toggleLink,children:y.showNameToggle})}),b&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:y.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:p,onChange:_=>{E(_.target.value),w.clearFieldError("name")},placeholder:y.namePlaceholder,style:N("name"),disabled:w.loading||A})]}),r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:y.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:P,onChange:_=>R(_.target.value),placeholder:y.lastNamePlaceholder,style:d.input,disabled:w.loading||A})]}),r.jsx("div",{style:d.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>{L(!1),E(""),R("")},style:d.toggleLink,children:y.hideNameToggle})})]}),r.jsx("button",{type:"submit",disabled:X,style:I,children:w.loading?y.loadingText:y.submitButton}),w.error&&r.jsx("div",{style:d.errorText,children:w.error}),m&&r.jsx("div",{style:d.successText,children:m})]}),c&&r.jsxs("div",{style:d.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:d.divider,children:[y.loginText," "]}),r.jsx("a",{onClick:i,style:d.link,children:y.loginLink})]}),r.jsx("div",{style:d.divider,children:y.dividerBullet}),r.jsxs("div",{children:[r.jsxs("span",{style:d.divider,children:[y.signupText," "]}),r.jsx("a",{onClick:l,style:d.link,children:y.signupLink})]})]})]})}const mr={title:"Verifying Magic Link",verifyingMessage:"Please wait while we verify your magic link...",successMessage:"Magic link verified successfully! You are now logged in.",errorMessage:"Failed to verify magic link. The link may be expired or invalid.",redirectingMessage:"Redirecting you to the dashboard...",retryButton:"Try Again",backToLoginButton:"Back to Login",missingParamsError:"Missing required parameters: token or email"},st={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},card:{backgroundColor:"transparent",padding:"0",borderRadius:"0",boxShadow:"none",maxWidth:"100%",width:"100%",textAlign:"center"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},message:{fontSize:"1rem",color:"#6b7280",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},successMessage:{fontSize:"1rem",color:"#059669",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},errorMessage:{fontSize:"0.875rem",color:"#ef4444",textAlign:"center",marginBottom:"1rem",lineHeight:"1.5"},spinner:{display:"inline-block",width:"20px",height:"20px",border:"2px solid #e5e7eb",borderTop:"2px solid #3b82f6",borderRadius:"50%",animation:"spin 1s linear infinite",marginRight:"0.5rem"},buttonContainer:{display:"flex",gap:"0.75rem",justifyContent:"center",flexWrap:"wrap",marginTop:"1rem"},retryButton:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out"},backButton:{padding:"0.75rem 1rem",backgroundColor:"#f3f4f6",color:"#374151",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"all 0.15s ease-in-out"},retryButtonHover:{backgroundColor:"#2563eb"},backButtonHover:{backgroundColor:"#e5e7eb"}},gr=()=>r.jsx("div",{style:st.spinner}),yr=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#059669",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),r.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),br=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),r.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),xr={loading:r.jsx(gr,{}),success:r.jsx(yr,{}),error:r.jsx(br,{})};function wr({copy:n={},styles:e={},icons:t={},onSuccess:s,onError:i,onRetry:l,onBackToLogin:c,className:h,token:v,email:j,appId:u,tenantSlug:S,autoRedirectDelay:p=3e3}){const[E,P]=o.useState("verifying"),[R,A]=o.useState(""),{verifyMagicLink:T}=ie(),m={...mr,...n},g={...st,...e},b={...xr,...t},L=()=>{if(typeof window>"u")return{};const d=new URLSearchParams(window.location.search);return{token:v||d.get("token")||"",email:j||d.get("email")||"",appId:u||d.get("appId")||"",tenantSlug:S||d.get("tenantSlug")||void 0}},a=async()=>{P("verifying"),A("");try{const d=L();if(!d.token||!d.email)throw new Error(m.missingParamsError);const w=await T({token:d.token,email:d.email,tenantSlug:d.tenantSlug});P("success"),s==null||s(w),p>0&&setTimeout(()=>{P("redirecting")},p)}catch(d){const w=d.message||m.errorMessage;A(w),P("error"),i==null||i(w)}},f=()=>{l==null||l(),a()},k=()=>{c==null||c()};o.useEffect(()=>{a()},[]);const y=()=>{switch(E){case"verifying":return r.jsxs("div",{style:g.message,children:[b.loading,m.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[b.success,r.jsx("div",{style:g.successMessage,children:m.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[b.loading,r.jsx("div",{style:g.message,children:m.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[b.error,r.jsx("div",{style:g.errorMessage,children:R||m.errorMessage}),r.jsxs("div",{style:g.buttonContainer,children:[r.jsx("button",{onClick:f,style:g.retryButton,onMouseOver:d=>{Object.assign(d.currentTarget.style,g.retryButtonHover)},onMouseOut:d=>{const w=g.retryButton||{};Object.keys(g.retryButtonHover||{}).forEach(N=>{d.currentTarget.style[N]=w[N]??""})},children:m.retryButton}),r.jsx("button",{onClick:k,style:g.backButton,onMouseOver:d=>{Object.assign(d.currentTarget.style,g.backButtonHover)},onMouseOut:d=>{const w=g.backButton||{};Object.keys(g.backButtonHover||{}).forEach(N=>{d.currentTarget.style[N]=w[N]??""})},children:m.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:g.container,className:h,children:[r.jsx("style",{children:`
2
2
  @keyframes spin {
3
3
  0% { transform: rotate(0deg); }
4
4
  100% { transform: rotate(360deg); }
5
5
  }
6
- `}),r.jsx("h1",{style:b.title,children:u.title}),R()]})}const kr={title:"Reset Password",subtitle:"Enter your email address and we'll send you a link to reset your password.",emailLabel:"Email",emailPlaceholder:"Enter your email",submitButton:"Send Reset Link",backToLoginLink:"Back to Sign In",successMessage:"Password reset link sent! Check your email.",errorMessage:"Failed to send reset link",loadingText:"Sending...",resetTitle:"Set New Password",resetSubtitle:"Enter your reset token and new password.",tokenLabel:"Reset Token",tokenPlaceholder:"Enter reset token from email",newPasswordLabel:"New Password",newPasswordPlaceholder:"Enter new password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm new password",resetSubmitButton:"Reset Password",resetLoadingText:"Resetting...",resetSuccessMessage:"Password reset successfully!",passwordMismatchError:"Passwords do not match",requestNewLinkLink:"Request New Link",haveTokenLink:"I have a token",tenantNotFoundError:"Tenant not found",dividerBullet:"•"},Ar={container:{maxWidth:"400px",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"0.5rem",color:"#333333"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#f59e0b",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},modeSwitchDivider:{margin:"0 0.5rem",color:"#6b7280"}};function jr({copy:s={},styles:e={},mode:t="request",token:n="",onSuccess:i,onError:o,onBackToLogin:l,onModeChange:h,className:f}){var K;const[y,d]=a.useState(""),[M,m]=a.useState(n),[v,k]=a.useState(""),[I,E]=a.useState(""),[A,u]=a.useState(!1),[b,F]=a.useState(""),[C,w]=a.useState(""),[j,T]=a.useState({}),{requestPasswordReset:R,confirmPasswordReset:c}=oe(),O=((K=ae())==null?void 0:K.tenant)??null,L={...kr,...s},g={...Ar,...e},N=()=>{const _={};return y.trim()||(_.email=!0),T(_),Object.keys(_).length===0},x=()=>{const _={};return M.trim()||(_.token=!0),v.trim()||(_.newPassword=!0),I.trim()||(_.confirmPassword=!0),T(_),Object.keys(_).length===0},p=async _=>{if(_.preventDefault(),!!N()){if(!(O!=null&&O.id)){F(L.tenantNotFoundError);return}u(!0),F(""),w("");try{await R({email:y,tenantId:O.id}),w(L.successMessage),i==null||i()}catch(H){const q=H.message||L.errorMessage;F(q),o==null||o(q)}finally{u(!1)}}},S=async _=>{if(_.preventDefault(),!!x()){if(v!==I){F(L.passwordMismatchError),T({confirmPassword:!0});return}u(!0),F(""),w("");try{await c({token:M,newPassword:v}),w(L.resetSuccessMessage),i==null||i()}catch(H){const q=H.message||L.errorMessage;F(q),o==null||o(q)}finally{u(!1)}}},P=_=>({...g.input,...j[_]?g.inputError:{}}),G=()=>({...g.button,...A?g.buttonLoading:{}});if(t==="reset"){const _=M&&v&&I;return r.jsxs("div",{className:f,style:g.container,children:[r.jsx("h2",{style:g.title,children:L.resetTitle}),r.jsx("p",{style:g.subtitle,children:L.resetSubtitle}),r.jsxs("form",{onSubmit:S,style:g.form,children:[r.jsxs("div",{style:g.fieldGroup,children:[r.jsx("label",{style:g.label,children:L.tokenLabel}),r.jsx("input",{type:"text",value:M,onChange:H=>{m(H.target.value),j.token&&T(q=>({...q,token:!1}))},placeholder:L.tokenPlaceholder,style:P("token"),disabled:A})]}),r.jsxs("div",{style:g.fieldGroup,children:[r.jsx("label",{style:g.label,children:L.newPasswordLabel}),r.jsx("input",{type:"password",value:v,onChange:H=>{k(H.target.value),j.newPassword&&T(q=>({...q,newPassword:!1}))},placeholder:L.newPasswordPlaceholder,style:P("newPassword"),disabled:A})]}),r.jsxs("div",{style:g.fieldGroup,children:[r.jsx("label",{style:g.label,children:L.confirmPasswordLabel}),r.jsx("input",{type:"password",value:I,onChange:H=>{E(H.target.value),j.confirmPassword&&T(q=>({...q,confirmPassword:!1})),b===L.passwordMismatchError&&F("")},placeholder:L.confirmPasswordPlaceholder,style:P("confirmPassword"),disabled:A})]}),r.jsx("button",{type:"submit",disabled:!_||A,style:{...G(),...!_||A?g.buttonDisabled:{}},children:A?L.resetLoadingText:L.resetSubmitButton}),b&&r.jsx("div",{style:g.errorText,children:b}),C&&r.jsx("div",{style:g.successText,children:C})]}),r.jsxs("div",{style:g.linkContainer,children:[r.jsx("a",{onClick:l,style:g.link,children:L.backToLoginLink}),h&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:g.modeSwitchDivider,children:L.dividerBullet}),r.jsx("a",{onClick:()=>h("request"),style:g.link,children:L.requestNewLinkLink})]})]})]})}const W=y;return r.jsxs("div",{className:f,style:g.container,children:[r.jsx("h2",{style:g.title,children:L.title}),r.jsx("p",{style:g.subtitle,children:L.subtitle}),r.jsxs("form",{onSubmit:p,style:g.form,children:[r.jsxs("div",{style:g.fieldGroup,children:[r.jsx("label",{style:g.label,children:L.emailLabel}),r.jsx("input",{type:"email",value:y,onChange:_=>{d(_.target.value),j.email&&T(H=>({...H,email:!1}))},placeholder:L.emailPlaceholder,style:P("email"),disabled:A})]}),r.jsx("button",{type:"submit",disabled:!W||A,style:{...G(),...!W||A?g.buttonDisabled:{}},children:A?L.loadingText:L.submitButton}),b&&r.jsx("div",{style:g.errorText,children:b}),C&&r.jsx("div",{style:g.successText,children:C})]}),r.jsxs("div",{style:g.linkContainer,children:[r.jsx("a",{onClick:l,style:g.link,children:L.backToLoginLink}),h&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:g.modeSwitchDivider,children:L.dividerBullet}),r.jsx("a",{onClick:()=>h("reset"),style:g.link,children:L.haveTokenLink})]})]})]})}const Pr=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),Rr=({error:s,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:s.message||"Unable to load application"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function Er({children:s,loadingFallback:e,errorFallback:t,requireTenant:n=!0}){const{isAppLoading:i,appError:o,retryApp:l}=fe(),h=ae(),f=Ie(),y=Je(),d=Ye(),M=(h==null?void 0:h.isTenantLoading)??!1,m=(h==null?void 0:h.tenantError)??null,v=(h==null?void 0:h.tenantSlug)??null,k=(h==null?void 0:h.retryTenant)??(()=>{}),I=(f==null?void 0:f.isAuthReady)??!0,E=(y==null?void 0:y.isReady)??!0,A=(d==null?void 0:d.isReady)??!0,u=n&&h&&v,w=i||u&&M||f&&!I||y&&!E||d&&!A,j=o||(u?m:null),T=()=>{o&&l(),m&&h&&k()};if(w)return r.jsx(r.Fragment,{children:e||r.jsx(Pr,{})});if(j){const R=typeof t=="function"?t(j,T):t||r.jsx(Rr,{error:j,retry:T});return r.jsx(r.Fragment,{children:R})}return r.jsx(r.Fragment,{children:s})}function Mr(s=!0){const{isAppLoading:e,appError:t,retryApp:n,appInfo:i}=fe(),o=ae(),l=Ie(),h=Je(),f=Ye(),y=(o==null?void 0:o.isTenantLoading)??!1,d=(o==null?void 0:o.tenantError)??null,M=(o==null?void 0:o.tenant)??null,m=(o==null?void 0:o.tenantSlug)??null,v=(o==null?void 0:o.retryTenant)??(()=>{}),k=(l==null?void 0:l.isAuthReady)??!0,I=(h==null?void 0:h.isReady)??!0,E=(f==null?void 0:f.isReady)??!0,A=s&&o&&m,C=e||A&&y||l&&!k||h&&!I||f&&!E,w=t||(A?d:null);return{isLoading:C,error:w,isReady:!C&&!w&&i!==null&&(!A||M!==null),retry:()=>{t&&n(),d&&o&&v()},app:{isLoading:e,error:t,data:i},tenant:o?{isLoading:y,error:d,data:M}:null,auth:l?{isReady:k}:null,featureFlags:h?{isReady:I}:null,subscription:f?{isReady:E}:null}}const Ir={wrapper:{position:"relative"},button:{cursor:"pointer",opacity:1},buttonDisabled:{cursor:"not-allowed",opacity:.6},dropdown:{position:"absolute",top:"100%",left:0,right:0,zIndex:1e3,backgroundColor:"white",border:"1px solid #ccc",borderRadius:4,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",maxHeight:300,overflowY:"auto"},item:{padding:"8px 12px",cursor:"pointer",backgroundColor:"transparent"},itemSelected:{backgroundColor:"#f0f0f0"},itemHover:{backgroundColor:"#f5f5f5"},itemRole:{opacity:.7,marginLeft:8},arrow:{marginLeft:8}};function Fr({tenants:s,currentTenantId:e,onSelect:t,styles:n={},className:i="",dropdownClassName:o="",itemClassName:l="",renderItem:h,placeholder:f="Select tenant",disabled:y=!1,showCurrentTenant:d=!0}){var C;const M={...Ir,...n},m=Ie(),[v,k]=a.useState(!1),I=a.useRef(null),E=s??(m==null?void 0:m.userTenants)??[],A=e??((C=m==null?void 0:m.currentUser)==null?void 0:C.tenantId)??null,u=async w=>{k(!1),t?t(w):m!=null&&m.switchToTenant&&await m.switchToTenant(w)};a.useEffect(()=>{const w=j=>{I.current&&!I.current.contains(j.target)&&k(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]);const b=E.find(w=>w.id===A);if(E.length===0)return null;if(E.length===1&&d)return r.jsx("div",{className:i,children:r.jsx("span",{children:E[0].name})});const F=(w,j)=>r.jsxs("span",{style:{fontWeight:j?"bold":"normal"},children:[w.name,w.role&&r.jsxs("span",{style:M.itemRole,children:["(",w.role,")"]})]});return r.jsxs("div",{ref:I,className:i,style:M.wrapper,children:[r.jsxs("button",{type:"button",onClick:()=>!y&&k(!v),disabled:y,style:{...M.button,...y?M.buttonDisabled:{}},children:[b?b.name:f,r.jsx("span",{style:M.arrow,children:v?"▲":"▼"})]}),v&&r.jsx("div",{className:o,style:M.dropdown,children:E.map(w=>{const j=w.id===A;return r.jsx("div",{className:l,onClick:()=>u(w.id),style:{...M.item,...j?M.itemSelected:{}},onMouseEnter:T=>{j||Object.assign(T.currentTarget.style,M.itemHover)},onMouseLeave:T=>{if(!j){const R=M.item||{};Object.keys(M.itemHover||{}).forEach(c=>{T.currentTarget.style[c]=R[c]??""})}},children:h?h(w,j):F(w,j)},w.id)})})]})}class Lr{constructor(e,t){this.httpService=e,this.sessionManager=t}async createPermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/permissions/",e,{headers:t})).data}async getPermissions(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/permissions/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{permissions:o.data,meta:o.meta}}async getPermissionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/permissions/${e}`,{headers:t})).data}async updatePermission(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:n})).data}async deletePermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/permissions/${e}`,{headers:t})}async getAppPermissions(e,t){const n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const i=`/permissions/apps/${e}${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i);return{permissions:o.data,meta:o.meta}}}class Nr{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscription-plans/",e,{headers:t})).data}async getSubscriptionPlans(e){const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder),e!=null&&e.appId&&n.append("appId",e.appId);const i=`/subscription-plans/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{plans:o.data,meta:o.meta}}async getSubscriptionPlanById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscription-plans/${e}`,{headers:t})).data}async updateSubscriptionPlan(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:n})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class Cr{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class Dr{static toDate(e){return new Date(e)}static toISOString(e){return e.toISOString()}static transformPaginationMeta(e){return{total:e.total||0,page:e.page||1,limit:e.limit||100,totalPages:e.totalPages||1,hasNext:e.hasNext||!1,hasPrev:e.hasPrev||!1}}static transformUser(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.lastName?`${e.name} ${e.lastName}`:e.name,isActiveUser:e.isActive}}static transformRole(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),permissionCount:((t=e.permissions)==null?void 0:t.length)||0}}static transformTenant(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.name,hasCustomDomain:!!e.domain}}static transformSubscription(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),startDate:this.toDate(e.startDate),endDate:e.endDate?this.toDate(e.endDate):null,isActive:e.status==="ACTIVE",isExpired:e.endDate?new Date(e.endDate)<new Date:!1}}static transformApp(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isAdminLevel:e.securityLevel==="ADMIN",hasDefaultPlan:!!e.defaultSubscriptionPlanId}}static transformFeatureFlag(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isEnabled:e.isActive}}static transformPermission(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),fullName:`${e.resource}:${e.action}`,isSystemLevel:!e.appId}}static transformSubscriptionPlan(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayPrice:`${e.currency} ${e.price}`,isMonthly:e.billingCycle==="MONTHLY",featureCount:((t=e.features)==null?void 0:t.length)||0}}static transformError(e){var t;return{code:((t=e.error)==null?void 0:t.code)||"UNKNOWN_ERROR",message:e.message||"An unexpected error occurred",type:e.type||"SYSTEM",isAuthError:e.type==="AUTH",isValidationError:e.type==="VALIDATION"}}static transformQueryParams(e){const t=new URLSearchParams;return Object.entries(e).forEach(([n,i])=>{i!=null&&i!==""&&t.append(n,String(i))}),t}}const tt="returnTo",ve="zone_return_to",Te="zone_return_to";function Ur(s={}){const{zoneRoots:e={},returnToParam:t=tt,returnToStorage:n="url"}=s,i=se.useNavigate(),[o,l]=se.useSearchParams(),{isAuthenticated:h,currentUser:f}=oe(),{tenant:y}=he(),d=a.useMemo(()=>({...ye,...e}),[e]),M=!!y,m=f==null?void 0:f.userType,v=a.useMemo(()=>{switch(n){case"url":return o.get(t);case"session":return sessionStorage.getItem(ve);case"local":return localStorage.getItem(Te);default:return null}},[n,o,t]),k=a.useCallback(()=>{switch(n){case"url":{const u=new URLSearchParams(o);u.delete(t),l(u,{replace:!0});break}case"session":sessionStorage.removeItem(ve);break;case"local":localStorage.removeItem(Te);break}},[n,o,t,l]),I=a.useCallback(u=>{switch(n){case"url":{const b=new URLSearchParams(o);b.set(t,u),l(b,{replace:!0});break}case"session":sessionStorage.setItem(ve,u);break;case"local":localStorage.setItem(Te,u);break}},[n,o,t,l]),E=a.useCallback(u=>{const b=d[u]||d.default;i(b)},[i,d]),A=a.useCallback(()=>M?h?m===te.TENANT_ADMIN?d.tenantAdmin:d.tenantUser:d.tenantGuest:h?m===te.TENANT_ADMIN?d.publicAdmin:d.publicUser:d.publicGuest,[M,h,m,d]);return{returnToUrl:v,clearReturnTo:k,setReturnTo:I,navigateToZone:E,getSmartRedirect:A}}function Br(s,e,t=tt,n="url"){if(!e||n!=="url")return s;const i=new URL(s,window.location.origin);return i.searchParams.set(t,e),i.pathname+i.search}exports.AdminZone=Qt;exports.ApiMappers=Dr;exports.AppApiService=ke;exports.AppLoader=Er;exports.AppProvider=gt;exports.AuthApiService=Ve;exports.AuthProvider=Pt;exports.AuthenticatedZone=Zt;exports.DEFAULT_ZONE_PRESETS=Ne;exports.DEFAULT_ZONE_ROOTS=ye;exports.FeatureFlag=ir;exports.FeatureFlagApiService=Ge;exports.FeatureFlagProvider=Rt;exports.GuestZone=Jt;exports.HealthApiService=Cr;exports.HttpService=re;exports.LandingRoute=Ht;exports.LoginForm=ur;exports.MagicLinkForm=yr;exports.MagicLinkVerify=Tr;exports.OpenZone=Yt;exports.PasswordRecoveryForm=jr;exports.PermissionApiService=Lr;exports.Protected=Lt;exports.ProtectedRoute=Dt;exports.PublicZone=Gt;exports.RoleApiService=Ae;exports.RoutingProvider=Mt;exports.SessionExpiredError=Y;exports.SessionManager=me;exports.SignupForm=fr;exports.SubscriptionApiService=Qe;exports.SubscriptionGuard=nr;exports.SubscriptionPlanApiService=Nr;exports.SubscriptionProvider=Et;exports.TenantApiService=ue;exports.TenantAuthenticatedZone=Xt;exports.TenantGuestZone=tr;exports.TenantOpenZone=er;exports.TenantProvider=kt;exports.TenantRoute=Bt;exports.TenantSelector=Fr;exports.TenantZone=Wt;exports.TokenRefreshError=ze;exports.TokenRefreshTimeoutError=_e;exports.UserApiService=We;exports.UserType=te;exports.UserZone=Kt;exports.ZoneRoute=ie;exports.buildRedirectUrl=Br;exports.useApi=mt;exports.useApp=fe;exports.useAppLoaderState=Mr;exports.useAuth=oe;exports.useFeatureFlags=Ze;exports.useRouting=It;exports.useRoutingOptional=Xe;exports.useSettings=jt;exports.useSubscription=Ke;exports.useTenant=he;exports.useTenantInfo=Ee;exports.useTenantOptional=ae;exports.useTenantSettings=At;exports.useZoneNavigation=Ur;
6
+ `}),r.jsx("h1",{style:g.title,children:m.title}),y()]})}const vr={title:"Reset Password",subtitle:"Enter your email address and we'll send you a link to reset your password.",emailLabel:"Email",emailPlaceholder:"Enter your email",submitButton:"Send Reset Link",backToLoginLink:"Back to Sign In",successMessage:"Password reset link sent! Check your email.",errorMessage:"Failed to send reset link",loadingText:"Sending...",resetTitle:"Set New Password",resetSubtitle:"Enter your reset token and new password.",tokenLabel:"Reset Token",tokenPlaceholder:"Enter reset token from email",newPasswordLabel:"New Password",newPasswordPlaceholder:"Enter new password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm new password",resetSubmitButton:"Reset Password",resetLoadingText:"Resetting...",resetSuccessMessage:"Password reset successfully!",passwordMismatchError:"Passwords do not match",requestNewLinkLink:"Request New Link",haveTokenLink:"I have a token",tenantNotFoundError:"Tenant not found",dividerBullet:"•"};function Sr({copy:n={},styles:e={},mode:t="request",token:s="",onSuccess:i,onError:l,onBackToLogin:c,onModeChange:h,className:v}){var X;const[j,u]=o.useState(""),[S,p]=o.useState(s),[E,P]=o.useState(""),[R,A]=o.useState(""),[T,m]=o.useState(""),{requestPasswordReset:g,confirmPasswordReset:b}=ie(),L=((X=ae())==null?void 0:X.tenant)??null,a={...vr,...n},f=we("#f59e0b",e),k=ue({defaultErrorMessage:a.errorMessage,validate:()=>j.trim()?L!=null&&L.id?!0:(k.setError(a.tenantNotFoundError),!1):(k.setFieldError("email",!0),!1),submit:async()=>{m(""),await g({email:j,tenantId:L.id}),m(a.successMessage)},onSuccess:()=>i==null?void 0:i(),onError:l}),y=ue({defaultErrorMessage:a.errorMessage,validate:()=>{const I=[];return S.trim()||I.push("token"),E.trim()||I.push("newPassword"),R.trim()||I.push("confirmPassword"),I.forEach(z=>y.setFieldError(z,!0)),I.length>0?!1:E!==R?(y.setError(a.passwordMismatchError),y.setFieldError("confirmPassword",!0),!1):!0},submit:async()=>{m(""),await b({token:S,newPassword:E}),m(a.resetSuccessMessage)},onSuccess:()=>i==null?void 0:i(),onError:l});if(t==="reset"){const I=M=>({...f.input,...y.fieldErrors[M]?f.inputError:{}}),_=!(!!S&&!!E&&!!R)||y.loading,Z={...f.button,...y.loading?f.buttonLoading:{},..._?f.buttonDisabled:{}};return r.jsxs("div",{className:v,style:f.container,children:[r.jsx("h2",{style:f.title,children:a.resetTitle}),r.jsx("p",{style:f.subtitle,children:a.resetSubtitle}),r.jsxs("form",{onSubmit:y.handleSubmit,style:f.form,children:[r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.tokenLabel}),r.jsx("input",{type:"text",value:S,onChange:M=>{p(M.target.value),y.clearFieldError("token")},placeholder:a.tokenPlaceholder,style:I("token"),disabled:y.loading})]}),r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.newPasswordLabel}),r.jsx("input",{type:"password",value:E,onChange:M=>{P(M.target.value),y.clearFieldError("newPassword")},placeholder:a.newPasswordPlaceholder,style:I("newPassword"),disabled:y.loading})]}),r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.confirmPasswordLabel}),r.jsx("input",{type:"password",value:R,onChange:M=>{A(M.target.value),y.clearFieldError("confirmPassword"),y.error===a.passwordMismatchError&&y.setError("")},placeholder:a.confirmPasswordPlaceholder,style:I("confirmPassword"),disabled:y.loading})]}),r.jsx("button",{type:"submit",disabled:_,style:Z,children:y.loading?a.resetLoadingText:a.resetSubmitButton}),y.error&&r.jsx("div",{style:f.errorText,children:y.error}),T&&r.jsx("div",{style:f.successText,children:T})]}),r.jsxs("div",{style:f.linkContainer,children:[r.jsx("a",{onClick:c,style:f.link,children:a.backToLoginLink}),h&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:f.modeSwitchDivider,children:a.dividerBullet}),r.jsx("a",{onClick:()=>h("request"),style:f.link,children:a.requestNewLinkLink})]})]})]})}const d=I=>({...f.input,...k.fieldErrors[I]?f.inputError:{}}),w=!j||k.loading,N={...f.button,...k.loading?f.buttonLoading:{},...w?f.buttonDisabled:{}};return r.jsxs("div",{className:v,style:f.container,children:[r.jsx("h2",{style:f.title,children:a.title}),r.jsx("p",{style:f.subtitle,children:a.subtitle}),r.jsxs("form",{onSubmit:k.handleSubmit,style:f.form,children:[r.jsxs("div",{style:f.fieldGroup,children:[r.jsx("label",{style:f.label,children:a.emailLabel}),r.jsx("input",{type:"email",value:j,onChange:I=>{u(I.target.value),k.clearFieldError("email")},placeholder:a.emailPlaceholder,style:d("email"),disabled:k.loading})]}),r.jsx("button",{type:"submit",disabled:w,style:N,children:k.loading?a.loadingText:a.submitButton}),k.error&&r.jsx("div",{style:f.errorText,children:k.error}),T&&r.jsx("div",{style:f.successText,children:T})]}),r.jsxs("div",{style:f.linkContainer,children:[r.jsx("a",{onClick:c,style:f.link,children:a.backToLoginLink}),h&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:f.modeSwitchDivider,children:a.dividerBullet}),r.jsx("a",{onClick:()=>h("reset"),style:f.link,children:a.haveTokenLink})]})]})]})}const Tr=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),kr=({error:n,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:n.message||"Unable to load application"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function Er({children:n,loadingFallback:e,errorFallback:t,requireTenant:s=!0}){const{isAppLoading:i,appError:l,retryApp:c}=de(),h=ae(),v=be(),j=Xe(),u=rt(),S=(h==null?void 0:h.isTenantLoading)??!1,p=(h==null?void 0:h.tenantError)??null,E=(h==null?void 0:h.tenantSlug)??null,P=(h==null?void 0:h.retryTenant)??(()=>{}),R=(v==null?void 0:v.isAuthReady)??!0,A=(j==null?void 0:j.isReady)??!0,T=(u==null?void 0:u.isReady)??!0,m=s&&h&&E,a=i||m&&S||v&&!R||j&&!A||u&&!T,f=l||(m?p:null),k=()=>{l&&c(),p&&h&&P()};if(a)return r.jsx(r.Fragment,{children:e||r.jsx(Tr,{})});if(f){const y=typeof t=="function"?t(f,k):t||r.jsx(kr,{error:f,retry:k});return r.jsx(r.Fragment,{children:y})}return r.jsx(r.Fragment,{children:n})}function jr(n=!0){const{isAppLoading:e,appError:t,retryApp:s,appInfo:i}=de(),l=ae(),c=be(),h=Xe(),v=rt(),j=(l==null?void 0:l.isTenantLoading)??!1,u=(l==null?void 0:l.tenantError)??null,S=(l==null?void 0:l.tenant)??null,p=(l==null?void 0:l.tenantSlug)??null,E=(l==null?void 0:l.retryTenant)??(()=>{}),P=(c==null?void 0:c.isAuthReady)??!0,R=(h==null?void 0:h.isReady)??!0,A=(v==null?void 0:v.isReady)??!0,T=n&&l&&p,L=e||T&&j||c&&!P||h&&!R||v&&!A,a=t||(T?u:null);return{isLoading:L,error:a,isReady:!L&&!a&&i!==null&&(!T||S!==null),retry:()=>{t&&s(),u&&l&&E()},app:{isLoading:e,error:t,data:i},tenant:l?{isLoading:j,error:u,data:S}:null,auth:c?{isReady:P}:null,featureFlags:h?{isReady:R}:null,subscription:v?{isReady:A}:null}}const Ar={wrapper:{position:"relative"},button:{cursor:"pointer",opacity:1},buttonDisabled:{cursor:"not-allowed",opacity:.6},dropdown:{position:"absolute",top:"100%",left:0,right:0,zIndex:1e3,backgroundColor:"white",border:"1px solid #ccc",borderRadius:4,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",maxHeight:300,overflowY:"auto"},item:{padding:"8px 12px",cursor:"pointer",backgroundColor:"transparent"},itemSelected:{backgroundColor:"#f0f0f0"},itemHover:{backgroundColor:"#f5f5f5"},itemRole:{opacity:.7,marginLeft:8},arrow:{marginLeft:8}};function Pr({tenants:n,currentTenantId:e,onSelect:t,styles:s={},className:i="",dropdownClassName:l="",itemClassName:c="",renderItem:h,placeholder:v="Select tenant",disabled:j=!1,showCurrentTenant:u=!0}){var L;const S={...Ar,...s},p=be(),[E,P]=o.useState(!1),R=o.useRef(null),A=n??(p==null?void 0:p.userTenants)??[],T=e??((L=p==null?void 0:p.currentUser)==null?void 0:L.tenantId)??null,m=async a=>{P(!1),t?t(a):p!=null&&p.switchToTenant&&await p.switchToTenant(a)};o.useEffect(()=>{const a=f=>{R.current&&!R.current.contains(f.target)&&P(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const g=A.find(a=>a.id===T);if(A.length===0)return null;if(A.length===1&&u)return r.jsx("div",{className:i,children:r.jsx("span",{children:A[0].name})});const b=(a,f)=>r.jsxs("span",{style:{fontWeight:f?"bold":"normal"},children:[a.name,a.role&&r.jsxs("span",{style:S.itemRole,children:["(",a.role,")"]})]});return r.jsxs("div",{ref:R,className:i,style:S.wrapper,children:[r.jsxs("button",{type:"button",onClick:()=>!j&&P(!E),disabled:j,style:{...S.button,...j?S.buttonDisabled:{}},children:[g?g.name:v,r.jsx("span",{style:S.arrow,children:E?"▲":"▼"})]}),E&&r.jsx("div",{className:l,style:S.dropdown,children:A.map(a=>{const f=a.id===T;return r.jsx("div",{className:c,onClick:()=>m(a.id),style:{...S.item,...f?S.itemSelected:{}},onMouseEnter:k=>{f||Object.assign(k.currentTarget.style,S.itemHover)},onMouseLeave:k=>{if(!f){const y=S.item||{};Object.keys(S.itemHover||{}).forEach(d=>{k.currentTarget.style[d]=y[d]??""})}},children:h?h(a,f):b(a,f)},a.id)})})]})}class Rr{constructor(e){this.httpService=e}async createPermission(e){return(await this.httpService.post("/permissions/",e)).data}async getPermissions(e){const t=await this.httpService.get(`/permissions/${ne(e)}`);return{permissions:t.data,meta:t.meta}}async getPermissionById(e){return(await this.httpService.get(`/permissions/${e}`)).data}async updatePermission(e,t){return(await this.httpService.put(`/permissions/${e}`,t)).data}async deletePermission(e){await this.httpService.delete(`/permissions/${e}`)}async getAppPermissions(e,t){const s=await this.httpService.get(`/permissions/apps/${e}${ne(t)}`,{skipAuth:!0});return{permissions:s.data,meta:s.meta}}}class Fr{constructor(e){this.httpService=e}async createSubscriptionPlan(e){return(await this.httpService.post("/subscription-plans/",e)).data}async getSubscriptionPlans(e){const t=await this.httpService.get(`/subscription-plans/${ne(e)}`);return{plans:t.data,meta:t.meta}}async getSubscriptionPlanById(e){return(await this.httpService.get(`/subscription-plans/${e}`)).data}async updateSubscriptionPlan(e,t){return(await this.httpService.put(`/subscription-plans/${e}`,t)).data}async deleteSubscriptionPlan(e){await this.httpService.delete(`/subscription-plans/${e}`)}}class Ir{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}const it="returnTo",Te="zone_return_to",ke="zone_return_to";function Lr(n={}){const{zoneRoots:e={},returnToParam:t=it,returnToStorage:s="url"}=n,i=re.useNavigate(),[l,c]=re.useSearchParams(),{isAuthenticated:h,currentUser:v}=ie(),{tenant:j}=ce(),u=o.useMemo(()=>({...xe,...e}),[e]),S=!!j,p=v==null?void 0:v.userType,E=o.useMemo(()=>{switch(s){case"url":return l.get(t);case"session":return sessionStorage.getItem(Te);case"local":return localStorage.getItem(ke);default:return null}},[s,l,t]),P=o.useCallback(()=>{switch(s){case"url":{const m=new URLSearchParams(l);m.delete(t),c(m,{replace:!0});break}case"session":sessionStorage.removeItem(Te);break;case"local":localStorage.removeItem(ke);break}},[s,l,t,c]),R=o.useCallback(m=>{switch(s){case"url":{const g=new URLSearchParams(l);g.set(t,m),c(g,{replace:!0});break}case"session":sessionStorage.setItem(Te,m);break;case"local":localStorage.setItem(ke,m);break}},[s,l,t,c]),A=o.useCallback(m=>{const g=u[m]||u.default;i(g)},[i,u]),T=o.useCallback(()=>S?h?p===ee.TENANT_ADMIN?u.tenantAdmin:u.tenantUser:u.tenantGuest:h?p===ee.TENANT_ADMIN?u.publicAdmin:u.publicUser:u.publicGuest,[S,h,p,u]);return{returnToUrl:E,clearReturnTo:P,setReturnTo:R,navigateToZone:A,getSmartRedirect:T}}function Nr(n,e,t=it,s="url"){if(!e||s!=="url")return n;const i=new URL(n,window.location.origin);return i.searchParams.set(t,e),i.pathname+i.search}exports.AdminZone=Jt;exports.AppApiService=Ee;exports.AppLoader=Er;exports.AppProvider=ft;exports.AuthApiService=He;exports.AuthProvider=kt;exports.AuthenticatedZone=Ht;exports.DEFAULT_ZONE_PRESETS=Ne;exports.DEFAULT_ZONE_ROOTS=xe;exports.FeatureFlag=ir;exports.FeatureFlagApiService=Ke;exports.FeatureFlagProvider=At;exports.GuestZone=Qt;exports.HealthApiService=Ir;exports.HttpService=oe;exports.LandingRoute=Ot;exports.LoginForm=ur;exports.MagicLinkForm=fr;exports.MagicLinkVerify=wr;exports.OpenZone=Yt;exports.PasswordRecoveryForm=Sr;exports.PermissionApiService=Rr;exports.Protected=Nt;exports.ProtectedRoute=Dt;exports.PublicZone=Zt;exports.RoleApiService=Qe;exports.RoutingProvider=Ft;exports.SessionExpiredError=H;exports.SessionManager=me;exports.SignupForm=hr;exports.SubscriptionApiService=et;exports.SubscriptionGuard=nr;exports.SubscriptionPlanApiService=Fr;exports.SubscriptionProvider=Pt;exports.TenantApiService=le;exports.TenantAuthenticatedZone=Xt;exports.TenantGuestZone=tr;exports.TenantOpenZone=er;exports.TenantProvider=wt;exports.TenantRoute=$t;exports.TenantSelector=Pr;exports.TenantZone=Gt;exports.TokenRefreshError=Ze;exports.TokenRefreshTimeoutError=Ge;exports.UserApiService=Je;exports.UserType=ee;exports.UserZone=Kt;exports.ZoneRoute=se;exports.buildRedirectUrl=Nr;exports.useApi=mt;exports.useApp=de;exports.useAppLoaderState=jr;exports.useAuth=ie;exports.useAuthActions=jt;exports.useAuthOptional=be;exports.useAuthState=Et;exports.useFeatureFlags=Ye;exports.useRouting=It;exports.useRoutingOptional=nt;exports.useSettings=St;exports.useSubscription=tt;exports.useTenant=ce;exports.useTenantInfo=Re;exports.useTenantOptional=ae;exports.useTenantSettings=vt;exports.useZoneNavigation=Lr;
7
7
  //# sourceMappingURL=index.js.map