@skylabs-digital/react-identity-access 3.3.0 → 3.4.1

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