@skylabs-digital/react-identity-access 2.30.0 → 2.32.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.
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"),ie=require("react-router-dom");class ne{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 u={"Content-Type":"application/json",...i==null?void 0:i.headers};if(!(i!=null&&i.skipAuth)&&this.sessionManager){const d=await this.sessionManager.getValidAccessToken();u={...u,Authorization:`Bearer ${d}`}}const f=new AbortController,y=setTimeout(()=>f.abort(),l);try{const d=await fetch(o,{method:e,headers:u,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 Ae{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 Pe=a.createContext(null);function mt({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),[u,f]=a.useState(null),y=a.useMemo(()=>{const m=()=>{d()};return{appId:s.appId,baseUrl:s.baseUrl,appInfo:n,isAppLoading:o,appError:u,retryApp:m}},[s,n,o,u]),d=a.useCallback(async(m=!1)=>{if(!(!m&&t.enabled&&n))try{l(!0),f(null);const v=new ne(s.baseUrl),I=await new Ae(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 ne(s.baseUrl),A=await new Ae(I,{}).getPublicAppInfo(s.appId);i(A);const h={data:A,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(h))}}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(Pe.Provider,{value:y,children:e})}function me(){const s=a.useContext(Pe);if(!s)throw new Error("useApp must be used within an AppProvider");return s}function Re(){return a.useContext(Pe)}const yt=me;class ee 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 ze extends Error{constructor(e){super(`Token refresh timed out after ${e}ms`),this.name="TokenRefreshTimeoutError",this.timeoutMs=e}}class Ve 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 te=class te{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],this.proactiveTimerId=null,this.backgroundRetryTimerId=null,this.isDestroyed=!1,this.sessionGeneration=0,this.consecutiveBackgroundFailures=0,e.tenantSlug!==void 0?this.storageKey=e.tenantSlug?`auth_tokens_${e.tenantSlug}`:"auth_tokens":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.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=te.resolveStorageKey(e),n=te.instances.get(t);if(n)return n.updateConfig(e),n;const i=new te(e);return te.instances.set(t,i),i}static resetAllInstances(){for(const e of te.instances.values())e.destroy();te.instances.clear()}static resolveStorageKey(e){return e.storageKey?e.storageKey:e.tenantSlug!==void 0&&e.tenantSlug?`auth_tokens_${e.tenantSlug}`:"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)}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)||te.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||te.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 ee)){if(this.sessionGeneration===t){if(this.consecutiveBackgroundFailures++,this.consecutiveBackgroundFailures>=te.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 ee("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 getValidAccessToken(){const e=this.getTokens();if(!(e!=null&&e.accessToken)){const t=new ee("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 ee("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 ee&&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 ze(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 ee?(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 ee("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 ee)throw l;if(t=l,i<this.maxRefreshRetries){const u=this.retryBackoffBase*Math.pow(2,i);await this.sleep(u)}}}throw new Ve(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=te.extractJwtClaim(i,"deviceId"),u={refreshToken:i};l&&(u.deviceId=l);let f;try{f=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)})}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 ee("token_expired"):d.includes("invalid")?new ee("token_invalid"):new ee("token_invalid",`Unauthorized: ${d}`):f.status===400?d.includes("inactive")?new ee("user_inactive"):d.includes("expired")||d.includes("invalid")?new ee("token_invalid",d):d.includes("reuse")||d.includes("revoked")?new ee("token_invalid",d):new Error(`Token refresh failed (400): ${d}`):new Error(`Token refresh failed: ${f.status} ${d}`)}if(this.sessionGeneration!==t)throw new ee("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 ee("token_invalid","Session cleared");this.rejectQueue(e)}destroy(){this.isDestroyed=!0,te.instances.delete(this.storageKey),this.cancelProactiveTimer();const e=new ee("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))}};te.instances=new Map,te.MAX_BACKGROUND_FAILURES=3;let he=te;const ve=new Map;class We{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=ve.get(t);if(n)return n;const i=this.httpService.post("/auth/magic-link/verify",e).finally(()=>{ve.delete(t)});return ve.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 je{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 Ge{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 pe{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 wt(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 xt(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 bt(s,e,t){const{tenantMode:n,baseDomain:i,selectorParam:o,fixedTenantSlug:l}=s;return n==="fixed"?l||null:n==="subdomain"?wt(e.hostname,i):n==="selector"?xt(e.search,o,t):null}function St(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 ue="_auth";function $e(s){const e=JSON.stringify(s);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function vt(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 Tt(){if(typeof window>"u")return null;const e=new URLSearchParams(window.location.search).get(ue);return e?vt(e):null}function kt(){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.delete(ue),window.history.replaceState({},"",s.toString())}const Ee=a.createContext(null);function At({config:s,children:e}){const{baseUrl:t,appInfo:n,appId:i}=me(),o=a.useCallback(()=>typeof window>"u"?null:bt({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,u]=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,h]=a.useState(!1),[b,F]=a.useState(null);a.useEffect(()=>{if(s.tenantMode==="fixed")return;const g=o();u(g)},[o,s.tenantMode]);const D=(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 ne(t),S=await new pe(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 ne(t),P=await new pe(p,i).getPublicTenantInfo(l);d(P);const W={data:P,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(f.storageKey,JSON.stringify(W))}}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{h(!0),F(null);const g=new ne(t),x=await new pe(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{h(!1)}},[t,y]),R=a.useCallback(()=>{T()},[T]),c=a.useCallback(g=>{if(!D)return{isValid:!0,errors:[]};const N=[];try{return D.properties&&Object.entries(D.properties).forEach(([x,p])=>{var P;const S=g[x];if((P=D.required)!=null&&P.includes(x)&&S==null){N.push(`Field '${x}' is required`);return}if(S!=null){if(p.type){const W=p.type,V=typeof S;W==="string"&&V!=="string"?N.push(`Field '${x}' must be a string`):(W==="number"||W==="integer")&&V!=="number"?N.push(`Field '${x}' must be a number`):W==="boolean"&&V!=="boolean"?N.push(`Field '${x}' must be a boolean`):W==="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"]}}},[D]);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),h(!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 W=window.location.hostname,V=St(g,W,s.baseDomain);if(!V){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",W);return}const Q=S||window.location.pathname,_=new URL(`${window.location.protocol}//${V}${Q}`);new URLSearchParams(window.location.search).forEach((q,B)=>{B!==ue&&_.searchParams.set(B,q)}),p&&_.searchParams.set(ue,$e(p)),window.location.href=_.toString()}else if(P==="selector"){const W=S||window.location.pathname,V=new URLSearchParams(window.location.search);if(V.set(s.selectorParam||"tenant",g),V.delete(ue),p&&V.set(ue,$e(p)),x==="reload"){const Q=`${W}?${V.toString()}${window.location.hash}`;window.location.href=Q}else{const Q=`${W}?${V.toString()}${window.location.hash}`;window.history.pushState({},"",Q),u(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:D,isSettingsLoading:A,settingsError:b,refreshSettings:R,switchTenant:O,validateSettings:c}),[y,l,M,v,I,D,A,b,R,O,c]);return r.jsx(Ee.Provider,{value:L,children:e})}function fe(){const s=a.useContext(Ee);if(!s)throw new Error("useTenant must be used within a TenantProvider");return s}function le(){return a.useContext(Ee)}const jt=fe;function Pt(){const{settings:s,settingsSchema:e,isSettingsLoading:t,settingsError:n,validateSettings:i}=fe();return{settings:s,settingsSchema:e,isLoading:t,error:n,validateSettings:i}}function Me(){const{tenant:s,tenantSlug:e,isTenantLoading:t,tenantError:n,retryTenant:i}=fe();return{tenant:s,tenantSlug:e,isLoading:t,error:n,retry:i}}const Ie=a.createContext(null);function Rt({config:s={},children:e}){const t=Re(),n=le(),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,u=(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,h]=a.useState(null),[b,F]=a.useState(()=>{try{const C=localStorage.getItem("userTenants");return C?JSON.parse(C):[]}catch{return[]}}),[D,w]=a.useState(!1),j=a.useRef({done:!1,urlTokens:null});j.current.done||(j.current.done=!0,j.current.urlTokens=Tt());const[T,R]=a.useState(()=>j.current.urlTokens!==null),c=a.useMemo(()=>{const C=he.getInstance({tenantSlug:u,baseUrl:i,refreshQueueTimeout:s.refreshQueueTimeout,proactiveRefreshMargin:s.proactiveRefreshMargin,onSessionExpired:se=>{k(null),h(null),F([]),w(!1);try{localStorage.removeItem("userTenants")}catch{}s.onSessionExpired?s.onSessionExpired(se):s.onRefreshFailed&&s.onRefreshFailed()}});return j.current.urlTokens&&C.setTokens({accessToken:j.current.urlTokens.accessToken,refreshToken:j.current.urlTokens.refreshToken,expiresIn:j.current.urlTokens.expiresIn}),C},[u,i,s.refreshQueueTimeout,s.proactiveRefreshMargin]),[O,L]=a.useState(()=>{if(j.current.urlTokens)return!1;const C=c.getTokens();return C?c.hasValidSession()||!!C.refreshToken:!1}),g=j.current.done&&!T&&!O,N=a.useMemo(()=>{const C=new ne(i);return C.setSessionManager(c),C},[i,c]),x=a.useMemo(()=>new We(new ne(i)),[i]),p=a.useMemo(()=>new Ge(N,c),[N,c]),S=a.useMemo(()=>new je(new ne(i)),[i]),P=a.useMemo(()=>v||c.getUser(),[v,c]),W=a.useMemo(()=>P!=null&&P.roleId&&y.find(C=>C.id===P.roleId)||null,[P,y]),V=a.useMemo(()=>(W==null?void 0:W.permissions)||[],[W]),Q=a.useMemo(()=>c.hasValidSession()&&v!==null,[c,v]),_=a.useRef(async()=>{}),H=a.useMemo(()=>{const C=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),h(null);const Z=await p.getUserById($);k(Z),c.setUser(Z)}catch($){const Z=$ instanceof Error?$:new Error("Failed to load user data");h(Z),process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data:",Z)}finally{E(!1)}},se=async()=>{await C()},ce=async U=>{var Ue;const{username:$,password:Z,tenantSlug:z,redirectPath:K}=U;let J=l==null?void 0:l.id,Y=u,X=c;z&&(J=(await new pe(N,o).getPublicTenantInfo(z)).id,Y=z);const G=await x.login({username:$,password:Z,appId:o,tenantId:J}),ge=z&&z!==u;if(ge&&(X=new he({tenantSlug:Y,baseUrl:i})),X.setTokens({accessToken:G.accessToken,refreshToken:G.refreshToken,expiresIn:G.expiresIn}),G.user){X.setUser(G.user),k(G.user);try{await C()}catch(ye){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after login:",ye)}}if(G.tenants&&G.tenants.length>0){F(G.tenants);try{localStorage.setItem("userTenants",JSON.stringify(G.tenants))}catch{}}const be=((Ue=G.user)==null?void 0:Ue.tenantId)!==null;w(be);const Se={accessToken:G.accessToken,refreshToken:G.refreshToken,expiresIn:G.expiresIn};if(ge&&Y)return f(Y,{tokens:Se,redirectPath:K}),G;if(K&&K!==window.location.pathname)return f(Y||u||"",{tokens:Se,redirectPath:K}),G;if(!be&&G.tenants&&G.tenants.length>0){const ye=U.autoSwitch!==!1&&s.autoSwitchSingleTenant!==!1;if(G.tenants.length===1&&ye){const Be=G.tenants[0];return f(Be.subdomain,{tokens:Se,redirectPath:K}),G}else G.tenants.length>1&&s.onTenantSelectionRequired&&s.onTenantSelectionRequired(G.tenants)}return G},de=async U=>{const{email:$,phoneNumber:Z,name:z,password:K,lastName:J,tenantId:Y}=U;if(!$&&!Z)throw new Error("Either email or phoneNumber is required");if(!z||!K)throw new Error("Name and password are required");const X=Y??(l==null?void 0:l.id);return await x.signup({email:$,phoneNumber:Z,name:z,password:K,tenantId:X,lastName:J,appId:o})},nt=async U=>{const{email:$,phoneNumber:Z,name:z,password:K,tenantName:J,lastName:Y}=U;if(!$&&!Z)throw new Error("Either email or phoneNumber is required");if(!z||!K||!J)throw new Error("Name, password, and tenantName are required");return await x.signupTenantAdmin({email:$,phoneNumber:Z,name:z,password:K,tenantName:J,appId:o,lastName:Y})},st=async U=>{const{currentPassword:$,newPassword:Z}=U,z=await c.getAuthHeaders();await x.changePassword({currentPassword:$,newPassword:Z},z)},it=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})},ot=async U=>{const{token:$,newPassword:Z}=U;await x.confirmPasswordReset({token:$,newPassword:Z})},at=async U=>{const{email:$,frontendUrl:Z,name:z,lastName:K,tenantId:J}=U,Y=J??(l==null?void 0:l.id);if(!Y)throw new Error("tenantId is required for magic link authentication");return await x.sendMagicLink({email:$,tenantId:Y,frontendUrl:Z,name:z,lastName:K,appId:o})},lt=async U=>{const{token:$,email:Z,tenantSlug:z}=U;let K=l==null?void 0:l.id,J=u,Y=c;z&&(K=(await new pe(N,o).getPublicTenantInfo(z)).id,J=z);const X=await x.verifyMagicLink({token:$,email:Z,appId:o,tenantId:K}),G=z&&z!==u;if(G&&(Y=new he({tenantSlug:J,baseUrl:i})),Y.setTokens({accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn}),X.user){Y.setUser(X.user),k(X.user);try{await C()}catch(ge){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after magic link:",ge)}}return G&&J&&J!==u&&f(J,{tokens:{accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn}}),X},ct=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})},dt=()=>{c.clearSession(),k(null),h(null),F([]),w(!1);try{localStorage.removeItem("userTenants")}catch{}},ut=U=>{c.setTokens(U)},ht=()=>c.hasValidSession(),pt=()=>{c.clearSession(),k(null),h(null)},ft=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)}},gt=async()=>{await ft()},xe=U=>{if(!V||V.length===0)return!1;if(typeof U=="string")return V.includes(U);const $=`${U.resource}.${U.action}`;return V.includes($)};return{isAuthenticated:Q,sessionManager:c,authenticatedHttpService:N,login:ce,signup:de,signupTenantAdmin:nt,sendMagicLink:at,verifyMagicLink:lt,changePassword:st,requestPasswordReset:it,confirmPasswordReset:ot,refreshToken:ct,logout:dt,setTokens:ut,hasValidSession:ht,clearSession:pt,currentUser:v,isUserLoading:I,userError:A,loadUserData:C,refreshUser:se,isAuthInitializing:!g,isAuthReady:g,userRole:W,userPermissions:V,availableRoles:y,rolesLoading:M,hasPermission:xe,hasAnyPermission:U=>U.some($=>xe($)),hasAllPermissions:U=>U.every($=>xe($)),getUserPermissionStrings:()=>V||[],refreshRoles:gt,userTenants:b,hasTenantContext:D,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 K=await x.switchTenant({refreshToken:z.refreshToken,tenantId:U});c.setTokens({accessToken:K.accessToken,refreshToken:z.refreshToken,expiresIn:K.expiresIn}),k(K.user),c.setUser(K.user),w(!0);const J=b.find(Y=>Y.id===U);J&&f(J.subdomain,{tokens:{accessToken:K.accessToken,refreshToken:z.refreshToken,expiresIn:K.expiresIn},redirectPath:Z})},refreshUserTenants:async()=>{const U=await c.getAuthHeaders(),$=await x.getUserTenants(U);F($);try{localStorage.setItem("userTenants",JSON.stringify($))}catch{}return $}}},[Q,c,N,x,p,S,o,l,u,f,y,v,I,A,b,D,g,W,V]);_.current=H.loadUserData,a.useEffect(()=>{!s.initialRoles&&o&&(async()=>{try{m(!0);const se=new ne(i),ce=new je(se),{roles:de}=await ce.getRolesByApp(o);d(de)}catch(se){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",se)}finally{m(!1)}})()},[o,i,s.initialRoles]);const[q,B]=a.useState(!1);return a.useEffect(()=>{q||(B(!0),j.current.urlTokens&&(kt(),R(!0),H.loadUserData().catch(C=>{process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data after URL tokens:",C)}).finally(()=>{R(!1)})))},[H,q]),a.useEffect(()=>{let C=!1;return(async()=>{var de;if(!c.hasValidSession()&&((de=c.getTokens())!=null&&de.refreshToken)&&await c.waitForPendingRefresh(),C)return;const ce=c.getUser();ce&&c.hasValidSession()&&k(ce),L(!1)})(),()=>{C=!0}},[c]),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(Ie.Provider,{value:H,children:e})}function ae(){const s=a.useContext(Ie);if(!s)throw new Error("useAuth must be used within an AuthProvider");return s}function Fe(){return a.useContext(Ie)}class Ze{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 Le=a.createContext(null);function Et({config:s={},children:e}){const t=Re(),n=le(),i=(t==null?void 0:t.baseUrl)??"",o=(t==null?void 0:t.appId)??"",l=(n==null?void 0:n.tenant)??null,[u,f]=a.useState([]),[y,d]=a.useState(!1),[M,m]=a.useState(null),[v,k]=a.useState(!1),I=a.useMemo(()=>{const h=new ne(i);return new Ze(h)},[i]),E=async()=>{if(!(l!=null&&l.id)){f([]);return}d(!0),m(null);try{const h=await I.getTenantFeatureFlags(l.id,o);f(h)}catch(h){const b=h instanceof Error?h.message:"Failed to fetch feature flags";m(b),s.onError&&s.onError(h instanceof Error?h:new Error(b))}finally{d(!1)}};a.useEffect(()=>{if(!i||!o)return;E().finally(()=>k(!0));const h=s.refreshInterval||5*60*1e3,b=setInterval(E,h);return()=>clearInterval(b)},[l==null?void 0:l.id,i,o,s.refreshInterval]);const A=a.useMemo(()=>{const h=j=>{const T=u.find(R=>R.key===j);return(T==null?void 0:T.value)===!0},b=j=>u.find(T=>T.key===j),F=j=>{const T=u.find(R=>R.key===j);return T?T.value?"enabled":"disabled":"not_found"},D=async()=>{await E()},w=!!(i&&o)&&(v||!(l!=null&&l.id));return{featureFlags:u,loading:y,error:M,isReady:w,isEnabled:h,getFlag:b,getFlagState:F,refresh:D}},[u,y,M,i,o,l==null?void 0:l.id,v]);return r.jsx(Le.Provider,{value:A,children:e})}function Ke(){const s=a.useContext(Le);if(!s)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return s}function Qe(){return a.useContext(Le)}class Je{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 Ne=a.createContext(void 0);function Mt({config:s={},children:e}){const t=Re(),n=le(),i=(t==null?void 0:t.baseUrl)??"",o=(n==null?void 0:n.tenant)??null,[l,u]=a.useState(null),[f,y]=a.useState(!1),[d,M]=a.useState(null),[m,v]=a.useState(!1),k=a.useMemo(()=>{const A=new ne(i);return new Je(A)},[i]),I=async()=>{if(!(o!=null&&o.id)){u(null);return}y(!0),M(null);try{const A=await k.getTenantSubscriptionFeatures(o.id);u(A)}catch(A){const h=A instanceof Error?A.message:"Failed to fetch subscription";M(h),s.onError&&s.onError(A instanceof Error?A:new Error(h))}finally{y(!1)}};a.useEffect(()=>{if(!i||(I().finally(()=>v(!0)),!s.refreshInterval))return;const A=s.refreshInterval||10*60*1e3,h=setInterval(I,A);return()=>clearInterval(h)},[o==null?void 0:o.id,i,s.refreshInterval]);const E=a.useMemo(()=>{const A=(l==null?void 0:l.features)||[],h=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},D=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:h,getFeature:b,getFeatureValue:F,hasAllowedPlan:D,refresh:w}},[l,f,d,i,o==null?void 0:o.id,m]);return r.jsx(Ne.Provider,{value:E,children:e})}function Ye(){const s=a.useContext(Ne);if(s===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return s}function Xe(){return a.useContext(Ne)??null}var re=(s=>(s.SUPERUSER="SUPERUSER",s.TENANT_ADMIN="TENANT_ADMIN",s.USER="USER",s))(re||{});const we={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},De={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:re.USER},admin:{tenant:"required",auth:"required",userType:re.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},Ce=a.createContext(null);function It({config:s={},children:e}){const t=a.useMemo(()=>{const n={...we,...s.zoneRoots},i={...De,...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 Ft(){const s=a.useContext(Ce);if(!s)throw new Error("useRouting must be used within a RoutingProvider");return s}function et(){const s=a.useContext(Ce);return s||{zoneRoots:we,presets:De,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"}}const He=()=>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"})]}),Oe=({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(", ")})]})]})]}),Lt=(s,e)=>{const t={[re.USER]:1,[re.TENANT_ADMIN]:2,[re.SUPERUSER]:3};return t[s]>=t[e]};function Nt({children:s,fallback:e,minUserType:t,requiredPermissions:n,requireAllPermissions:i=!1}){const{hasValidSession:o,sessionManager:l,hasPermission:u,hasAnyPermission:f,hasAllPermissions:y}=ae();if(!o())return r.jsx(r.Fragment,{children:e||r.jsx(He,{})});const d=l.getUser();if(!d)return r.jsx(r.Fragment,{children:e||r.jsx(He,{})});if(t&&!Lt(d.userType,t))return r.jsx(Oe,{userType:d.userType,minUserType:t});if(n&&n.length>0&&!(i?y(n):f(n))){const m=n.filter(v=>!u(v)).map(v=>typeof v=="string"?v:v.name);return r.jsx(Oe,{missingPermissions:m})}return r.jsx(r.Fragment,{children:s})}const Dt=({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,"..."]})]})}),qe=({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 Ut({children:s,redirectTo:e="/login",requiredUserType:t,requiredPermissions:n,requireAllPermissions:i=!1,fallback:o}){const{hasValidSession:l,sessionManager:u,hasPermission:f,hasAnyPermission:y,hasAllPermissions:d}=ae(),M=ie.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(Dt,{redirectPath:e}),r.jsx(ie.Navigate,{to:e,state:{from:M.pathname},replace:!0})]});const m=u.getUser();if(!m)return r.jsx(ie.Navigate,{to:e,state:{from:M.pathname},replace:!0});if(t&&!Ct(m.userType,t))return r.jsx(qe,{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(qe,{missingPermissions:k})}return r.jsx(r.Fragment,{children:s})}const Bt=({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 $t({children:s,redirectTo:e="/",fallback:t}){const{tenant:n,isLoading:i,error:o}=Me(),l=ie.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(Bt,{redirectPath:e}),r.jsx(ie.Navigate,{to:e,state:{from:l.pathname},replace:!0})]})}const Ht=({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 Ot({children:s,redirectTo:e="/dashboard",fallback:t}){const{tenant:n,isLoading:i,error:o}=Me(),l=ie.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(Ht,{redirectPath:e}),r.jsx(ie.Navigate,{to:e,state:{from:l.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:s})}function qt(s,e){return e?s?Array.isArray(e)?e.includes(s):s===e:!1:!0}function _e(s,e){return!s||s==="optional"?"skip":s==="required"?e?"pass":"fail":s==="forbidden"?e?"fail":"pass":"skip"}function _t(s,e){return _e(s.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":_e(s.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":s.userType&&e.isAuthenticated&&!qt(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 zt(s,e){return s.hasTenant?s.isAuthenticated?s.userType===re.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:s.isAuthenticated?s.userType===re.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function Vt(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 Wt(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 oe=({children:s,preset:e,tenant:t,auth:n,userType:i,requiredPermissions:o,requireAllPermissions:l=!0,returnTo:u,onAccessDenied:f,redirectTo:y,loadingFallback:d,accessDeniedFallback:M})=>{const m=ie.useLocation(),{isAuthenticated:v,isAuthInitializing:k,currentUser:I,userPermissions:E}=ae(),{tenant:A,isTenantLoading:h}=fe(),b=et(),F=a.useMemo(()=>{if(e)return b.presets[e]},[e,b.presets]),D=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||h}),[A,v,I==null?void 0:I.userType,E,k,h]),j=a.useMemo(()=>w.isLoading?null:_t(D,w),[D,w]),T=a.useMemo(()=>j?y||zt(w,b.zoneRoots):null,[j,y,w,b.zoneRoots]),R=a.useMemo(()=>!j||!T?null:{type:j,required:{tenant:D.tenant,auth:D.auth,userType:D.userType,permissions:D.permissions},current:{hasTenant:w.hasTenant,isAuthenticated:w.isAuthenticated,userType:w.userType,permissions:w.permissions},redirectTo:T},[j,T,D,w]);if(a.useEffect(()=>{R&&(f?f(R):b.onAccessDenied&&b.onAccessDenied(R))},[R,f,b]),a.useEffect(()=>{R&&u&&Wt(u,m.pathname+m.search,b.returnToStorage)},[R,u,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=Vt(T,u,m.pathname+m.search,b.returnToParam,b.returnToStorage);return r.jsx(ie.Navigate,{to:O,replace:!0})}return r.jsx(r.Fragment,{children:s})},Gt=s=>r.jsx(oe,{tenant:"required",...s}),Zt=s=>r.jsx(oe,{tenant:"forbidden",...s}),Kt=s=>r.jsx(oe,{auth:"required",...s}),Qt=s=>r.jsx(oe,{auth:"forbidden",...s}),Jt=s=>r.jsx(oe,{auth:"required",userType:re.TENANT_ADMIN,...s}),Yt=s=>r.jsx(oe,{auth:"required",userType:re.USER,...s}),Xt=s=>r.jsx(oe,{tenant:"optional",auth:"optional",...s}),er=s=>r.jsx(oe,{tenant:"required",auth:"required",...s}),tr=s=>r.jsx(oe,{tenant:"required",auth:"optional",...s}),rr=s=>r.jsx(oe,{tenant:"required",auth:"forbidden",...s}),nr=()=>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 sr({children:s,fallback:e=r.jsx(nr,{}),allowedPlans:t,requiredFeature:n}){const{subscription:i,hasAllowedPlan:o,isFeatureEnabled:l,loading:u}=Ye();return u?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 ir=({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 or({name:s,children:e,fallback:t}){const{isEnabled:n,loading:i}=Ke();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(ir,{flagName:s})})}const 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:"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"})]}),lr=()=>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"})]}),cr={showPassword:r.jsx(ar,{}),hidePassword:r.jsx(lr,{})},dr={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"},ur={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 hr({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onForgotPassword:o,onSignupClick:l,onMagicLinkClick:u,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),[h,b]=a.useState(!1),[F,D]=a.useState(""),[w,j]=a.useState({}),{login:T}=ae(),R={...dr,...s},c={...ur,...e},O={...cr,...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),D("");try{const S=await T({username:m,password:k});n==null||n(S)}catch(S){const P=S.message||R.errorMessage;D(P),i==null||i(P)}finally{b(!1)}}},N=p=>({...c.input,...w[p]?c.inputError:{}}),x=()=>({...c.button,...h?c.buttonLoading:{},...!m||!k||h?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:h})]}),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:h}),r.jsx("button",{type:"button",onClick:()=>A(!E),style:c.passwordToggle,disabled:h,"aria-label":E?R.hidePasswordAriaLabel:R.showPasswordAriaLabel,children:E?O.hidePassword:O.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:!m||!k||h,style:x(),children:h?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:u,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 pr={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:"•"},fr={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 gr({copy:s={},styles:e={},signupType:t="user",onSuccess:n,onError:i,onLoginClick:o,onMagicLinkClick:l,showLoginLink:u=!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(""),[h,b]=a.useState(""),[F,D]=a.useState(""),[w,j]=a.useState(""),[T,R]=a.useState(!1),[c,O]=a.useState(""),[L,g]=a.useState({}),{signup:N,signupTenantAdmin:x}=ae(),p=((q=le())==null?void 0:q.tenant)??null,S={...pr,...s},P={...fr,...e},W=()=>{const B={};return d.trim()||(B.name=!0),!k.trim()&&!E.trim()&&(B.email=!0,B.phoneNumber=!0),h.trim()||(B.password=!0),F.trim()||(B.confirmPassword=!0),t==="tenant"&&!w.trim()&&(B.tenantName=!0),g(B),Object.keys(B).length===0},V=async B=>{if(B.preventDefault(),!!W()){if(h!==F){O(S.passwordMismatchError),g({confirmPassword:!0});return}if(t==="user"&&!(p!=null&&p.id)){O(S.tenantNotFoundError);return}R(!0),O("");try{let C;t==="tenant"?C=await x({email:k||void 0,phoneNumber:E||void 0,name:d,password:h,tenantName:w,lastName:m||void 0}):C=await N({email:k||void 0,phoneNumber:E||void 0,name:d,password:h,tenantId:p.id,lastName:m||void 0}),n==null||n(C)}catch(C){const se=C.message||S.errorMessage;O(se),i==null||i(se)}finally{R(!1)}}},Q=B=>({...P.input,...L[B]?P.inputError:{}}),_=()=>({...P.button,...T?P.buttonLoading:{},...!d||!k&&!E||!h||!F||T||t==="tenant"&&!w?P.buttonDisabled:{}}),H=d&&(k||E)&&h&&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:V,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(C=>({...C,name:!1}))},placeholder:S.namePlaceholder,style:Q("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(C=>({...C,email:!1,phoneNumber:!1}))},placeholder:S.emailPlaceholder,style:Q("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(C=>({...C,email:!1,phoneNumber:!1}))},placeholder:S.phoneNumberPlaceholder,style:Q("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:h,onChange:B=>{b(B.target.value),L.password&&g(C=>({...C,password:!1}))},placeholder:S.passwordPlaceholder,style:Q("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=>{D(B.target.value),L.confirmPassword&&g(C=>({...C,confirmPassword:!1})),c===S.passwordMismatchError&&O("")},placeholder:S.confirmPasswordPlaceholder,style:Q("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(C=>({...C,tenantName:!1}))},placeholder:S.tenantNamePlaceholder,style:Q("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})]}),(u||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&&u&&r.jsx("div",{style:P.divider,children:S.dividerBullet}),u&&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 mr={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:"•"},yr={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 wr({copy:s={},styles:e={},onSuccess:t,onError:n,onLoginClick:i,onSignupClick:o,showTraditionalLinks:l=!0,className:u,verifyToken:f,frontendUrl:y}){var _;const[d,M]=a.useState(""),[m,v]=a.useState(""),[k,I]=a.useState(""),[E,A]=a.useState(!1),[h,b]=a.useState(!1),[F,D]=a.useState(""),[w,j]=a.useState(""),[T,R]=a.useState({}),[c,O]=a.useState(!1),{sendMagicLink:L,verifyMagicLink:g}=ae(),N=((_=le())==null?void 0:_.tenant)??null,x={...mr,...s},p={...yr,...e};a.useEffect(()=>{f&&S(f)},[f]);const S=async H=>{if(!N||!d){D(x.missingTenantOrEmailError);return}b(!0),D("");try{const q=await g({token:H,email:d});t==null||t(q)}catch(q){const B=q.message||"Failed to verify magic link";D(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},W=async H=>{if(H.preventDefault(),!!P()){if(!(N!=null&&N.id)){D(x.tenantNotFoundError);return}A(!0),D(""),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;D(B),n==null||n(B)}finally{A(!1)}}},V=H=>({...p.input,...T[H]?p.inputError:{}}),Q=()=>({...p.button,...E||h?p.buttonLoading:{},...!d||E||h?p.buttonDisabled:{}});return h?r.jsxs("div",{className:u,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:u,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:W,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:V("email"),disabled:E||h})]}),!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:V("name"),disabled:E||h})]}),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||h})]}),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||h,style:Q(),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 xr={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"},tt={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"}},br=()=>r.jsx("div",{style:tt.spinner}),Sr=()=>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"})]}),vr=()=>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"})]}),Tr={loading:r.jsx(br,{}),success:r.jsx(Sr,{}),error:r.jsx(vr,{})};function kr({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onRetry:o,onBackToLogin:l,className:u,token:f,email:y,appId:d,tenantSlug:M,autoRedirectDelay:m=3e3}){const[v,k]=a.useState("verifying"),[I,E]=a.useState(""),{verifyMagicLink:A}=ae(),h={...xr,...s},b={...tt,...e},F={...Tr,...t},D=()=>{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=D();if(!c.token||!c.email)throw new Error(h.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||h.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,h.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[F.success,r.jsx("div",{style:b.successMessage,children:h.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[F.loading,r.jsx("div",{style:b.message,children:h.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[F.error,r.jsx("div",{style:b.errorMessage,children:I||h.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:h.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:h.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:b.container,className:u,children:[r.jsx("style",{children:`
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:`
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:h.title}),R()]})}const Ar={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:"•"},jr={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 Pr({copy:s={},styles:e={},mode:t="request",token:n="",onSuccess:i,onError:o,onBackToLogin:l,onModeChange:u,className:f}){var Q;const[y,d]=a.useState(""),[M,m]=a.useState(n),[v,k]=a.useState(""),[I,E]=a.useState(""),[A,h]=a.useState(!1),[b,F]=a.useState(""),[D,w]=a.useState(""),[j,T]=a.useState({}),{requestPasswordReset:R,confirmPasswordReset:c}=ae(),O=((Q=le())==null?void 0:Q.tenant)??null,L={...Ar,...s},g={...jr,...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}h(!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{h(!1)}}},S=async _=>{if(_.preventDefault(),!!x()){if(v!==I){F(L.passwordMismatchError),T({confirmPassword:!0});return}h(!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{h(!1)}}},P=_=>({...g.input,...j[_]?g.inputError:{}}),W=()=>({...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:{...W(),...!_||A?g.buttonDisabled:{}},children:A?L.resetLoadingText:L.resetSubmitButton}),b&&r.jsx("div",{style:g.errorText,children:b}),D&&r.jsx("div",{style:g.successText,children:D})]}),r.jsxs("div",{style:g.linkContainer,children:[r.jsx("a",{onClick:l,style:g.link,children:L.backToLoginLink}),u&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:g.modeSwitchDivider,children:L.dividerBullet}),r.jsx("a",{onClick:()=>u("request"),style:g.link,children:L.requestNewLinkLink})]})]})]})}const V=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:!V||A,style:{...W(),...!V||A?g.buttonDisabled:{}},children:A?L.loadingText:L.submitButton}),b&&r.jsx("div",{style:g.errorText,children:b}),D&&r.jsx("div",{style:g.successText,children:D})]}),r.jsxs("div",{style:g.linkContainer,children:[r.jsx("a",{onClick:l,style:g.link,children:L.backToLoginLink}),u&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:g.modeSwitchDivider,children:L.dividerBullet}),r.jsx("a",{onClick:()=>u("reset"),style:g.link,children:L.haveTokenLink})]})]})]})}const Rr=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),Er=({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 Mr({children:s,loadingFallback:e,errorFallback:t,requireTenant:n=!0}){const{isAppLoading:i,appError:o,retryApp:l}=me(),u=le(),f=Fe(),y=Qe(),d=Xe(),M=(u==null?void 0:u.isTenantLoading)??!1,m=(u==null?void 0:u.tenantError)??null,v=(u==null?void 0:u.tenantSlug)??null,k=(u==null?void 0:u.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,h=n&&u&&v,w=i||h&&M||f&&!I||y&&!E||d&&!A,j=o||(h?m:null),T=()=>{o&&l(),m&&u&&k()};if(w)return r.jsx(r.Fragment,{children:e||r.jsx(Rr,{})});if(j){const R=typeof t=="function"?t(j,T):t||r.jsx(Er,{error:j,retry:T});return r.jsx(r.Fragment,{children:R})}return r.jsx(r.Fragment,{children:s})}function Ir(s=!0){const{isAppLoading:e,appError:t,retryApp:n,appInfo:i}=me(),o=le(),l=Fe(),u=Qe(),f=Xe(),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=(u==null?void 0:u.isReady)??!0,E=(f==null?void 0:f.isReady)??!0,A=s&&o&&m,D=e||A&&y||l&&!k||u&&!I||f&&!E,w=t||(A?d:null);return{isLoading:D,error:w,isReady:!D&&!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:u?{isReady:I}:null,subscription:f?{isReady:E}:null}}const Fr={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 Lr({tenants:s,currentTenantId:e,onSelect:t,styles:n={},className:i="",dropdownClassName:o="",itemClassName:l="",renderItem:u,placeholder:f="Select tenant",disabled:y=!1,showCurrentTenant:d=!0}){var D;const M={...Fr,...n},m=Fe(),[v,k]=a.useState(!1),I=a.useRef(null),E=s??(m==null?void 0:m.userTenants)??[],A=e??((D=m==null?void 0:m.currentUser)==null?void 0:D.tenantId)??null,h=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:()=>h(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:u?u(w,j):F(w,j)},w.id)})})]})}class Nr{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 Dr{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 Ur{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 rt="returnTo",Te="zone_return_to",ke="zone_return_to";function Br(s={}){const{zoneRoots:e={},returnToParam:t=rt,returnToStorage:n="url"}=s,i=ie.useNavigate(),[o,l]=ie.useSearchParams(),{isAuthenticated:u,currentUser:f}=ae(),{tenant:y}=fe(),d=a.useMemo(()=>({...we,...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(Te);case"local":return localStorage.getItem(ke);default:return null}},[n,o,t]),k=a.useCallback(()=>{switch(n){case"url":{const h=new URLSearchParams(o);h.delete(t),l(h,{replace:!0});break}case"session":sessionStorage.removeItem(Te);break;case"local":localStorage.removeItem(ke);break}},[n,o,t,l]),I=a.useCallback(h=>{switch(n){case"url":{const b=new URLSearchParams(o);b.set(t,h),l(b,{replace:!0});break}case"session":sessionStorage.setItem(Te,h);break;case"local":localStorage.setItem(ke,h);break}},[n,o,t,l]),E=a.useCallback(h=>{const b=d[h]||d.default;i(b)},[i,d]),A=a.useCallback(()=>M?u?m===re.TENANT_ADMIN?d.tenantAdmin:d.tenantUser:d.tenantGuest:u?m===re.TENANT_ADMIN?d.publicAdmin:d.publicUser:d.publicGuest,[M,u,m,d]);return{returnToUrl:v,clearReturnTo:k,setReturnTo:I,navigateToZone:E,getSmartRedirect:A}}function $r(s,e,t=rt,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=Jt;exports.ApiMappers=Ur;exports.AppApiService=Ae;exports.AppLoader=Mr;exports.AppProvider=mt;exports.AuthApiService=We;exports.AuthProvider=Rt;exports.AuthenticatedZone=Kt;exports.DEFAULT_ZONE_PRESETS=De;exports.DEFAULT_ZONE_ROOTS=we;exports.FeatureFlag=or;exports.FeatureFlagApiService=Ze;exports.FeatureFlagProvider=Et;exports.GuestZone=Qt;exports.HealthApiService=Cr;exports.HttpService=ne;exports.LandingRoute=Ot;exports.LoginForm=hr;exports.MagicLinkForm=wr;exports.MagicLinkVerify=kr;exports.OpenZone=Xt;exports.PasswordRecoveryForm=Pr;exports.PermissionApiService=Nr;exports.Protected=Nt;exports.ProtectedRoute=Ut;exports.PublicZone=Zt;exports.RoleApiService=je;exports.RoutingProvider=It;exports.SessionExpiredError=ee;exports.SessionManager=he;exports.SignupForm=gr;exports.SubscriptionApiService=Je;exports.SubscriptionGuard=sr;exports.SubscriptionPlanApiService=Dr;exports.SubscriptionProvider=Mt;exports.TenantApiService=pe;exports.TenantAuthenticatedZone=er;exports.TenantGuestZone=rr;exports.TenantOpenZone=tr;exports.TenantProvider=At;exports.TenantRoute=$t;exports.TenantSelector=Lr;exports.TenantZone=Gt;exports.TokenRefreshError=Ve;exports.TokenRefreshTimeoutError=ze;exports.UserApiService=Ge;exports.UserType=re;exports.UserZone=Yt;exports.ZoneRoute=oe;exports.buildRedirectUrl=$r;exports.useApi=yt;exports.useApp=me;exports.useAppLoaderState=Ir;exports.useAuth=ae;exports.useFeatureFlags=Ke;exports.useRouting=Ft;exports.useRoutingOptional=et;exports.useSettings=Pt;exports.useSubscription=Ye;exports.useTenant=fe;exports.useTenantInfo=Me;exports.useTenantOptional=le;exports.useTenantSettings=jt;exports.useZoneNavigation=Br;
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;
7
7
  //# sourceMappingURL=index.js.map