@skylabs-digital/react-identity-access 2.15.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),i=require("react"),te=require("react-router-dom");class ee{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async request(e,t,r,o){return this.executeRequest(e,t,r,o,!1)}async executeRequest(e,t,r,o,a=!1){const l=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,p=(o==null?void 0:o.timeout)||this.timeout;let f={"Content-Type":"application/json",...o==null?void 0:o.headers};if(!(o!=null&&o.skipAuth)&&this.sessionManager)try{const x=await this.sessionManager.getAuthHeaders();f={...f,...x}}catch(x){console.warn("Failed to inject auth headers:",x)}const w=new AbortController,u=setTimeout(()=>w.abort(),p);try{const x=await fetch(l,{method:e,headers:f,body:r?JSON.stringify(r):void 0,signal:w.signal});if(clearTimeout(u),x.status===401&&!(o!=null&&o.skipRetry)&&!a&&this.sessionManager)try{const v=this.sessionManager.getTokens();if(v!=null&&v.refreshToken)return await this.sessionManager.getAuthHeaders(),this.executeRequest(e,t,r,o,!0)}catch{throw new Error(`HTTP ${x.status}: ${x.statusText}`)}if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);const g=x.headers.get("content-type");return!g||!g.includes("application/json")?{}:await x.json()}catch(x){throw clearTimeout(u),x instanceof Error&&x.name==="AbortError"?new Error(`Request timeout after ${p}ms`):x}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,r){return this.request("POST",e,t,r)}async put(e,t,r){return this.request("PUT",e,t,r)}async delete(e,t){return this.request("DELETE",e,void 0,t)}}class Se{constructor(e,t){this.httpService=e,this.sessionManager=t}async createApp(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/apps/",e,{headers:t})).data}async getApps(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const o=`/apps/${r.toString()?`?${r.toString()}`:""}`,a=await this.httpService.get(o,{headers:t});return{apps:a.data,meta:a.meta}}async getAppById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}`,{headers:t})).data}async updateApp(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:r})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:r})).data}async updateSettingsSchema(e,t,r){const o=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:r},{headers:o})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const Te=i.createContext(null);function ct({config:s,children:e}){const t=i.useMemo(()=>{var g,v,P;return{enabled:((g=s.cache)==null?void 0:g.enabled)??!0,ttl:((v=s.cache)==null?void 0:v.ttl)??3e5,storageKey:((P=s.cache)==null?void 0:P.storageKey)??`app_cache_${s.appId}`}},[s.cache,s.appId]),[r,o]=i.useState(()=>{if(!t.enabled)return null;try{const g=localStorage.getItem(t.storageKey);if(!g)return null;const v=JSON.parse(g);return Date.now()-v.timestamp<t.ttl&&v.appId===s.appId?v.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[a,l]=i.useState(!r),[p,f]=i.useState(null),w=i.useMemo(()=>{const g=()=>{u()};return{appId:s.appId,baseUrl:s.baseUrl,appInfo:r,isAppLoading:a,appError:p,retryApp:g}},[s,r,a,p]),u=i.useCallback(async(g=!1)=>{if(!(!g&&t.enabled&&r))try{l(!0),f(null);const v=new ee(s.baseUrl),F=await new Se(v,{}).getPublicAppInfo(s.appId);if(o(F),t.enabled)try{const R={data:F,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(R))}catch(R){console.warn("Failed to cache app info:",R)}}catch(v){const P=v instanceof Error?v:new Error("Failed to load app information");f(P),o(null)}finally{l(!1)}},[s.baseUrl,s.appId,t,r]),x=i.useCallback(async()=>{if(!(!t.enabled||!r))try{const g=localStorage.getItem(t.storageKey);if(!g)return;const v=JSON.parse(g);if(Date.now()-v.timestamp>t.ttl*.5){const F=new ee(s.baseUrl),A=await new Se(F,{}).getPublicAppInfo(s.appId);o(A);const h={data:A,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(h))}}catch(g){console.warn("Background app refresh failed:",g)}},[s,t,r]);return i.useEffect(()=>{r?x():u()},[]),n.jsx(Te.Provider,{value:w,children:e})}function ce(){const s=i.useContext(Te);if(!s)throw new Error("useApp must be used within an AppProvider");return s}function $e(){return i.useContext(Te)}const dt=ce;class ge{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],e.tenantSlug!==void 0?this.storageKey=e.tenantSlug?`auth_tokens_${e.tenantSlug}`:"auth_tokens":this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.baseUrl=e.baseUrl||"",this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey)}createTokenStorage(e){return{get:()=>{try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},set:t=>{try{localStorage.setItem(e,JSON.stringify(t))}catch{}},clear:()=>{try{localStorage.removeItem(e)}catch{}}}}setTokens(e){const t={...e,expiresAt:e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)};this.tokenStorage.set(t)}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:r,expiresIn:o,tokenType:a}=this.tokenStorage.get()||{};return e?{accessToken:e,refreshToken:t,expiresAt:r,expiresIn:o,tokenType:a}:null}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}async getAuthHeaders(){const e=this.getTokens();if(!(e!=null&&e.accessToken))return{};if(!this.shouldRefreshToken(e))return{Authorization:`Bearer ${e.accessToken}`};if(!e.refreshToken)return this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{};if(this.refreshPromise)return new Promise((t,r)=>{this.refreshQueue.push({resolve:t,reject:r})});this.refreshPromise=this.performTokenRefresh(e.refreshToken);try{await this.refreshPromise;const t=this.getTokens(),r=t!=null&&t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{};return this.refreshQueue.forEach(({resolve:o})=>o(r)),this.refreshQueue=[],r}catch(t){const r=t instanceof Error?t:new Error("Token refresh failed");return this.refreshQueue.forEach(({reject:o})=>o(r)),this.refreshQueue=[],this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{}}finally{this.refreshPromise=null}}async performTokenRefresh(e){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const t=`${this.baseUrl}/auth/refresh`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status} ${r.statusText}`);const o=await r.json();this.setTokens({accessToken:o.accessToken,refreshToken:o.refreshToken||e,expiresIn:o.expiresIn})}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.clearTokens(),this.clearUser()}getTokenPayload(){try{const e=this.getTokens();if(!(e!=null&&e.accessToken))return null;const t=e.accessToken.split(".");if(t.length!==3)return null;const r=t[1],o=atob(r.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(o)}catch{return null}}getUserId(){const e=this.getTokenPayload();if(e!=null&&e.userId)return e.userId;const t=this.getUser();return(t==null?void 0:t.id)||null}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}}class He{constructor(e){this.httpService=e}async login(e){return await this.httpService.post("/auth/login",e)}async signup(e){return await this.httpService.post("/auth/signup",e)}async signupTenantAdmin(e){return await this.httpService.post("/auth/signup/tenant-admin",e)}async refreshToken(e){return await this.httpService.post("/auth/refresh",e)}async switchTenant(e){return await this.httpService.post("/auth/switch-tenant",e)}async getUserTenants(e){return await this.httpService.get("/auth/tenants",{headers:e})}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e)}async sendMagicLink(e){return await this.httpService.post("/auth/magic-link/send",e)}async verifyMagicLink(e){return await this.httpService.post("/auth/magic-link/verify",e)}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e)}async changePassword(e,t){await this.httpService.post("/auth/change-password",e,{headers:t})}}class ve{constructor(e,t){this.httpService=e,this.sessionManager=t}async createRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/roles/",e,{headers:t})).data}async getRoleById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/roles/${e}`,{headers:t})).data}async updateRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:r})).data}async deleteRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/roles/${e}`,{headers:t})}async getRolesByApp(e,t){const r=new URLSearchParams;t!=null&&t.page&&r.append("page",t.page.toString()),t!=null&&t.limit&&r.append("limit",t.limit.toString()),t!=null&&t.sortBy&&r.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&r.append("sortOrder",t.sortOrder);const o=`/roles/app/${e}${r.toString()?`?${r.toString()}`:""}`,a=await this.httpService.get(o);return{roles:a.data,meta:a.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:r})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:r})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders(),o=new URLSearchParams;t!=null&&t.page&&o.append("page",t.page.toString()),t!=null&&t.limit&&o.append("limit",t.limit.toString()),t!=null&&t.sortBy&&o.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&o.append("sortOrder",t.sortOrder);const a=`/roles/user/${e}${o.toString()?`?${o.toString()}`:""}`,l=await this.httpService.get(a,{headers:r});return{roles:l.data,meta:l.meta}}}class Be{constructor(e,t){this.httpService=e,this.sessionManager=t}async createUser(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/users/",e,{headers:t})).data}async getUsers(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const o=`/users/${r.toString()?`?${r.toString()}`:""}`,a=await this.httpService.get(o,{headers:t});return{users:a.data,meta:a.meta}}async getUserById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/users/${e}`,{headers:t})).data}async updateUser(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:r})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class le{constructor(e,t,r){this.httpService=e,this.appId=t,this.sessionManager=r}async createTenant(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/tenants/",e,{headers:t})).data}async getTenants(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const o=`/tenants/${r.toString()?`?${r.toString()}`:""}`,a=await this.httpService.get(o,{headers:t});return{tenants:a.data,meta:a.meta}}async getTenantById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/tenants/${e}`,{headers:t})).data}async updateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:r})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:r})).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`)).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`)).data}async updateTenantSettings(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:r})).data}}function ut(s,e){if(s==="localhost"||s.startsWith("127.")||s.startsWith("192.168."))return null;if(e){const o=e.toLowerCase(),a=s.toLowerCase();if(a===o||a===`www.${o}`)return null;if(a.endsWith(`.${o}`)){const l=a.slice(0,-(o.length+1));return l==="www"?null:l}return null}const r=s.split(".");return r.length>=3&&r[0]!=="www"?r[0]:null}function ht(s,e="tenant",t){const o=new URLSearchParams(s).get(e);return o?(t&&t.setItem("tenant",o),o):t?t.getItem("tenant"):null}function gt(s,e,t){const{tenantMode:r,baseDomain:o,selectorParam:a}=s;return r==="subdomain"?ut(e.hostname,o):r==="selector"?ht(e.search,a,t):null}function pt(s,e,t){if(t)return`${s}.${t}`;const r=e.split(".");return r.length===2?`${s}.${e}`:r.length>=3?(r[0]=s,r.join(".")):null}const ie="_auth";function Le(s){const e=JSON.stringify(s);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ft(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";const t=atob(e),r=JSON.parse(t);return typeof r.accessToken=="string"&&typeof r.refreshToken=="string"&&typeof r.expiresIn=="number"?r:null}catch{return null}}function mt(){if(typeof window>"u")return console.log("[CrossDomainAuth] SSR environment, skipping URL token extraction"),null;const e=new URLSearchParams(window.location.search).get(ie);if(console.log("[CrossDomainAuth] extractAuthTokensFromUrl called",{hasAuthParam:!!e,searchParams:window.location.search,encodedLength:e==null?void 0:e.length}),!e)return null;const t=ft(e);return console.log("[CrossDomainAuth] Token decode result:",{success:!!t,hasAccessToken:!!(t!=null&&t.accessToken),hasRefreshToken:!!(t!=null&&t.refreshToken),expiresIn:t==null?void 0:t.expiresIn}),t}function yt(){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.delete(ie),console.log("[CrossDomainAuth] Clearing auth tokens from URL",{oldUrl:window.location.href,newUrl:s.toString()}),window.history.replaceState({},"",s.toString())}const ke=i.createContext(null);function wt({config:s,children:e}){const{baseUrl:t,appInfo:r,appId:o}=ce(),a=i.useCallback(()=>typeof window>"u"?null:gt({tenantMode:s.tenantMode||"selector",baseDomain:s.baseDomain,selectorParam:s.selectorParam},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[s.tenantMode,s.baseDomain,s.selectorParam]),[l,p]=i.useState(()=>a()),f=i.useMemo(()=>{var d,U,I;return{enabled:((d=s.cache)==null?void 0:d.enabled)??!0,ttl:((U=s.cache)==null?void 0:U.ttl)??5*60*1e3,storageKey:((I=s.cache)==null?void 0:I.storageKey)??`tenant_cache_${l||"default"}`}},[s.cache,l]),[w,u]=i.useState(()=>{if(s.initialTenant)return s.initialTenant;if(!f.enabled||!l)return null;try{const d=localStorage.getItem(f.storageKey);if(!d)return null;const U=JSON.parse(d);return Date.now()-U.timestamp<f.ttl&&U.tenantSlug===l?U.data:(localStorage.removeItem(f.storageKey),null)}catch{return null}}),[x,g]=i.useState(!w&&!s.initialTenant),[v,P]=i.useState(null),[F,R]=i.useState(null),[A,h]=i.useState(!1),[k,b]=i.useState(null);i.useEffect(()=>{const d=a();p(d)},[a]);const M=(r==null?void 0:r.settingsSchema)||null,E=i.useCallback(async(d,U=!1)=>{if(!(!U&&f.enabled&&w&&w.domain===d))try{g(!0),P(null);const I=new ee(t),m=await new le(I,o).getPublicTenantInfo(d);if(u(m),f.enabled)try{const S={data:m,timestamp:Date.now(),tenantSlug:d};localStorage.setItem(f.storageKey,JSON.stringify(S))}catch(S){console.warn("Failed to cache tenant info:",S)}}catch(I){const y=I instanceof Error?I:new Error("Failed to load tenant information");P(y),u(null)}finally{g(!1)}},[t,o,f,w]),C=i.useCallback(async()=>{if(!(!f.enabled||!w||!l))try{const d=localStorage.getItem(f.storageKey);if(!d)return;const U=JSON.parse(d);if(Date.now()-U.timestamp>f.ttl*.5){const y=new ee(t),S=await new le(y,o).getPublicTenantInfo(l);u(S);const W={data:S,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(f.storageKey,JSON.stringify(W))}}catch(d){console.warn("Background tenant refresh failed:",d)}},[t,o,f,w,l]),j=i.useCallback(async()=>{if(w!=null&&w.id)try{h(!0),b(null);const d=new ee(t),I=await new le(d,w.appId).getTenantSettings(w.id);R(I)}catch(d){const U=d instanceof Error?d:new Error("Failed to load tenant settings");b(U),R(null)}finally{h(!1)}},[t,w]),D=i.useCallback(()=>{j()},[j]),c=i.useCallback(d=>{if(!M)return{isValid:!0,errors:[]};const U=[];try{return M.properties&&Object.entries(M.properties).forEach(([I,y])=>{var S;const m=d[I];if((S=M.required)!=null&&S.includes(I)&&m==null){U.push(`Field '${I}' is required`);return}if(m!=null){if(y.type){const W=y.type,G=typeof m;W==="string"&&G!=="string"?U.push(`Field '${I}' must be a string`):(W==="number"||W==="integer")&&G!=="number"?U.push(`Field '${I}' must be a number`):W==="boolean"&&G!=="boolean"?U.push(`Field '${I}' must be a boolean`):W==="array"&&!Array.isArray(m)&&U.push(`Field '${I}' must be an array`)}y.minLength!==void 0&&typeof m=="string"&&m.length<y.minLength&&U.push(`Field '${I}' must be at least ${y.minLength} characters long`),y.maxLength!==void 0&&typeof m=="string"&&m.length>y.maxLength&&U.push(`Field '${I}' must be no more than ${y.maxLength} characters long`),y.minimum!==void 0&&typeof m=="number"&&m<y.minimum&&U.push(`Field '${I}' must be at least ${y.minimum}`),y.maximum!==void 0&&typeof m=="number"&&m>y.maximum&&U.push(`Field '${I}' must be no more than ${y.maximum}`),y.pattern&&typeof m=="string"&&(new RegExp(y.pattern).test(m)||U.push(`Field '${I}' does not match the required pattern`)),y.enum&&!y.enum.includes(m)&&U.push(`Field '${I}' must be one of: ${y.enum.join(", ")}`)}}),{isValid:U.length===0,errors:U}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[M]);i.useEffect(()=>{!s.initialTenant&&l?w?C():E(l):!s.initialTenant&&!l&&(u(null),P(null),g(!1))},[s.initialTenant,l,w,E,C]),i.useEffect(()=>{w!=null&&w.id?j():(R(null),b(null),h(!1))},[w==null?void 0:w.id,j]);const L=i.useCallback((d,U)=>{const{mode:I="reload",tokens:y,redirectPath:m}=U||{},S=s.tenantMode||"selector";if(localStorage.setItem("tenant",d),S==="subdomain"){const W=window.location.hostname,G=pt(d,W,s.baseDomain);if(!G){console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",W);return}const H=m||window.location.pathname,B=new URL(`${window.location.protocol}//${G}${H}`);new URLSearchParams(window.location.search).forEach((T,V)=>{V!==ie&&B.searchParams.set(V,T)}),y&&B.searchParams.set(ie,Le(y)),window.location.href=B.toString()}else if(S==="selector"){const W=m||window.location.pathname,G=new URLSearchParams(window.location.search);if(G.set(s.selectorParam||"tenant",d),G.delete(ie),y&&G.set(ie,Le(y)),I==="reload"){const H=`${W}?${G.toString()}${window.location.hash}`;window.location.href=H}else{const H=`${W}?${G.toString()}${window.location.hash}`;window.history.pushState({},"",H),p(d),E(d)}}},[s.tenantMode,s.selectorParam,s.baseDomain,E]),N=i.useMemo(()=>({tenant:w,tenantSlug:l,isTenantLoading:x,tenantError:v,retryTenant:()=>{l&&E(l)},settings:F,settingsSchema:M,isSettingsLoading:A,settingsError:k,refreshSettings:D,switchTenant:L,validateSettings:c}),[w,l,x,v,F,M,A,k,D,L,c]);return n.jsx(ke.Provider,{value:N,children:e})}function se(){const s=i.useContext(ke);if(!s)throw new Error("useTenant must be used within a TenantProvider");return s}function ue(){return i.useContext(ke)}const xt=se;function bt(){const{settings:s,settingsSchema:e,isSettingsLoading:t,settingsError:r,validateSettings:o}=se();return{settings:s,settingsSchema:e,isLoading:t,error:r,validateSettings:o}}function oe(){const{tenant:s,tenantSlug:e,isTenantLoading:t,tenantError:r,retryTenant:o}=se();return{tenant:s,tenantSlug:e,isLoading:t,error:r,retry:o}}const Ae=i.createContext(null);function St({config:s={},children:e}){const{appId:t,baseUrl:r}=ce(),{tenant:o,tenantSlug:a,switchTenant:l}=se(),[p,f]=i.useState(s.initialRoles||[]),[w,u]=i.useState(!s.initialRoles),[x,g]=i.useState(null),[v,P]=i.useState(!1),[F,R]=i.useState(null),[A,h]=i.useState(0),[k,b]=i.useState(()=>{try{const T=localStorage.getItem("userTenants");return T?JSON.parse(T):[]}catch{return[]}}),[M,E]=i.useState(!1),C=i.useRef({done:!1,urlTokens:null});C.current.done||(C.current.done=!0,C.current.urlTokens=mt(),C.current.urlTokens&&console.log("[AuthProvider] SYNC: URL tokens found, will block isAuthReady until user loaded"));const[j,D]=i.useState(()=>{const T=C.current.urlTokens!==null;return console.log("[AuthProvider] SYNC: isLoadingAfterUrlTokens initial:",T),T}),c=i.useMemo(()=>{const T=new ge({tenantSlug:a,onRefreshFailed:s.onRefreshFailed,baseUrl:r});return C.current.urlTokens&&(console.log("[AuthProvider] SYNC: Saving URL tokens to session manager"),T.setTokens({accessToken:C.current.urlTokens.accessToken,refreshToken:C.current.urlTokens.refreshToken,expiresIn:C.current.urlTokens.expiresIn}),console.log("[AuthProvider] SYNC: Session valid:",T.hasValidSession())),T},[a,r,s.onRefreshFailed]),L=C.current.done&&!j,N=i.useMemo(()=>{const T=new ee(r);return T.setSessionManager(c),T},[r,c]),d=i.useMemo(()=>new He(new ee(r)),[r]),U=i.useMemo(()=>new Be(N,c),[N,c]),I=i.useMemo(()=>new ve(new ee(r)),[r]),y=i.useMemo(()=>x||c.getUser(),[x,c]),m=i.useMemo(()=>y!=null&&y.roleId&&p.find(T=>T.id===y.roleId)||null,[y,p]),S=i.useMemo(()=>(m==null?void 0:m.permissions)||[],[m]),W=i.useMemo(()=>c.hasValidSession()&&x!==null,[c,x]),G=5*60*1e3,H=i.useMemo(()=>{const T=async($=!1)=>{try{if(!c.hasValidSession())return;const O=Date.now();if(!$&&O-A<G&&x)return;const q=c.getUserId();if(!q){console.warn("[AuthProvider] No userId available in token or storage");return}P(!0),R(null);const Z=await U.getUserById(q);g(Z),c.setUser(Z),h(Date.now())}catch(O){const K=O instanceof Error?O:new Error("Failed to load user data");R(K),console.error("[AuthProvider] Failed to load user data:",K)}finally{P(!1)}},V=async()=>{await T()},ae=async $=>{var Ie;const{username:O,password:K,tenantSlug:q,redirectPath:Z}=$;let J=o==null?void 0:o.id,Y=a,Q=c;q&&(J=(await new le(N,t).getPublicTenantInfo(q)).id,Y=q);const _=await d.login({username:O,password:K,appId:t,tenantId:J}),de=q&&q!==a;if(de&&(Q=new ge({tenantSlug:Y,baseUrl:r})),Q.setTokens({accessToken:_.accessToken,refreshToken:_.refreshToken,expiresIn:_.expiresIn}),_.user){Q.setUser(_.user),g(_.user);try{await T()}catch(he){console.warn("Failed to load complete user data after login:",he)}}if(_.tenants&&_.tenants.length>0){b(_.tenants);try{localStorage.setItem("userTenants",JSON.stringify(_.tenants))}catch{}}const ye=((Ie=_.user)==null?void 0:Ie.tenantId)!==null;E(ye);const we={accessToken:_.accessToken,refreshToken:_.refreshToken,expiresIn:_.expiresIn};if(de&&Y)return l(Y,{tokens:we,redirectPath:Z}),_;if(Z&&Z!==window.location.pathname)return l(Y||a||"",{tokens:we,redirectPath:Z}),_;if(!ye&&_.tenants&&_.tenants.length>0){const he=$.autoSwitch!==!1&&s.autoSwitchSingleTenant!==!1;if(_.tenants.length===1&&he){const Fe=_.tenants[0];return l(Fe.subdomain,{tokens:we,redirectPath:Z}),_}else _.tenants.length>1&&s.onTenantSelectionRequired&&s.onTenantSelectionRequired(_.tenants)}return _},fe=async $=>{const{email:O,phoneNumber:K,name:q,password:Z,lastName:J,tenantId:Y}=$;if(!O&&!K)throw new Error("Either email or phoneNumber is required");if(!q||!Z)throw new Error("Name and password are required");const Q=Y??(o==null?void 0:o.id);return await d.signup({email:O,phoneNumber:K,name:q,password:Z,tenantId:Q,lastName:J,appId:t})},Je=async $=>{const{email:O,phoneNumber:K,name:q,password:Z,tenantName:J,lastName:Y}=$;if(!O&&!K)throw new Error("Either email or phoneNumber is required");if(!q||!Z||!J)throw new Error("Name, password, and tenantName are required");return await d.signupTenantAdmin({email:O,phoneNumber:K,name:q,password:Z,tenantName:J,appId:t,lastName:Y})},Ye=async $=>{const{currentPassword:O,newPassword:K}=$,q=await c.getAuthHeaders();await d.changePassword({currentPassword:O,newPassword:K},q)},Qe=async $=>{const{email:O,tenantId:K}=$,q=K??(o==null?void 0:o.id);if(!q)throw new Error("tenantId is required for password reset");await d.requestPasswordReset({email:O,tenantId:q})},Xe=async $=>{const{token:O,newPassword:K}=$;await d.confirmPasswordReset({token:O,newPassword:K})},et=async $=>{const{email:O,frontendUrl:K,name:q,lastName:Z,tenantId:J}=$,Y=J??(o==null?void 0:o.id);if(!Y)throw new Error("tenantId is required for magic link authentication");return await d.sendMagicLink({email:O,tenantId:Y,frontendUrl:K,name:q,lastName:Z,appId:t})},tt=async $=>{const{token:O,email:K,tenantSlug:q}=$;let Z=o==null?void 0:o.id,J=a,Y=c;q&&(Z=(await new le(N,t).getPublicTenantInfo(q)).id,J=q);const Q=await d.verifyMagicLink({token:O,email:K,appId:t,tenantId:Z}),_=q&&q!==a;if(_&&(Y=new ge({tenantSlug:J,baseUrl:r})),Y.setTokens({accessToken:Q.accessToken,refreshToken:Q.refreshToken,expiresIn:Q.expiresIn}),Q.user){Y.setUser(Q.user),g(Q.user);try{await T()}catch(de){console.warn("Failed to load complete user data after magic link login:",de)}}return _&&J&&J!==a&&l(J,{tokens:{accessToken:Q.accessToken,refreshToken:Q.refreshToken,expiresIn:Q.expiresIn}}),Q},nt=async()=>{const $=c.getTokens();if(!($!=null&&$.refreshToken))throw new Error("No refresh token available");const O=await d.refreshToken({refreshToken:$.refreshToken});c.setTokens({accessToken:O.accessToken,refreshToken:O.refreshToken||$.refreshToken,expiresIn:O.expiresIn})},rt=()=>{c.clearSession(),g(null),R(null),b([]),E(!1);try{localStorage.removeItem("userTenants")}catch{}},st=$=>{c.setTokens($)},ot=()=>c.hasValidSession(),at=()=>{c.clearSession(),g(null),R(null)},it=async()=>{if(t)try{u(!0);const{roles:$}=await I.getRolesByApp(t);f($)}catch($){console.error("Failed to fetch roles:",$)}finally{u(!1)}},lt=async()=>{await it()},me=$=>{if(!S||S.length===0)return!1;if(typeof $=="string")return S.includes($);const O=`${$.resource}.${$.action}`;return S.includes(O)};return{isAuthenticated:W,sessionManager:c,authenticatedHttpService:N,login:ae,signup:fe,signupTenantAdmin:Je,sendMagicLink:et,verifyMagicLink:tt,changePassword:Ye,requestPasswordReset:Qe,confirmPasswordReset:Xe,refreshToken:nt,logout:rt,setTokens:st,hasValidSession:ot,clearSession:at,currentUser:x,isUserLoading:v,userError:F,loadUserData:T,refreshUser:V,isAuthInitializing:!L,isAuthReady:L,userRole:m,userPermissions:S,availableRoles:p,rolesLoading:w,hasPermission:me,hasAnyPermission:$=>$.some(O=>me(O)),hasAllPermissions:$=>$.every(O=>me(O)),getUserPermissionStrings:()=>S||[],refreshRoles:lt,userTenants:k,hasTenantContext:M,switchToTenant:async($,O)=>{const{redirectPath:K}=O||{},q=c.getTokens();if(!(q!=null&&q.refreshToken))throw new Error("No refresh token available for tenant switch");const Z=await d.switchTenant({refreshToken:q.refreshToken,tenantId:$});c.setTokens({accessToken:Z.accessToken,refreshToken:q.refreshToken,expiresIn:Z.expiresIn}),g(Z.user),c.setUser(Z.user),E(!0);const J=k.find(Y=>Y.id===$);J&&l(J.subdomain,{tokens:{accessToken:Z.accessToken,refreshToken:q.refreshToken,expiresIn:Z.expiresIn},redirectPath:K})},refreshUserTenants:async()=>{const $=await c.getAuthHeaders(),O=await d.getUserTenants($);b(O);try{localStorage.setItem("userTenants",JSON.stringify(O))}catch{}return O}}},[W,c,N,d,U,I,t,o,a,l,p,x,v,F,k,M,L,m,S,A,G]);i.useEffect(()=>{!s.initialRoles&&t&&(async()=>{try{u(!0);const V=new ee(r),ae=new ve(V),{roles:fe}=await ae.getRolesByApp(t);f(fe)}catch(V){console.error("Failed to fetch roles:",V)}finally{u(!1)}})()},[t,r,s.initialRoles]);const[B,z]=i.useState(!1);return i.useEffect(()=>{B||(z(!0),C.current.urlTokens&&(console.log("[AuthProvider] EFFECT: Cleaning up URL after sync token processing"),yt(),D(!0),console.log("[AuthProvider] EFFECT: Loading user data (blocking isAuthReady)..."),H.loadUserData().catch(T=>{console.error("[AuthProvider] Failed to load user data:",T)}).finally(()=>{console.log("[AuthProvider] EFFECT: User data loaded, releasing isAuthReady"),D(!1)})))},[H,B]),i.useEffect(()=>{const T=c.getUser();T&&c.hasValidSession()&&g(T)},[c]),i.useEffect(()=>{B&&(C.current.urlTokens||!x&&!v&&c.hasValidSession()&&(console.log("[AuthProvider] Auto-loading user data..."),H.loadUserData().catch(()=>{})))},[x,v,H,c,B]),i.useEffect(()=>{if(!c.hasValidSession()||!x)return;const T=setInterval(()=>{H.loadUserData().catch(()=>{})},G);return()=>clearInterval(T)},[c,x,H,G]),n.jsx(Ae.Provider,{value:H,children:e})}function re(){const s=i.useContext(Ae);if(!s)throw new Error("useAuth must be used within an AuthProvider");return s}function je(){return i.useContext(Ae)}class Oe{constructor(e,t){this.httpService=e,this.sessionManager=t}async createFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/feature-flags/",e,{headers:t})).data}async getFeatureFlags(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const o=`/feature-flags/${r.toString()?`?${r.toString()}`:""}`,a=await this.httpService.get(o,{headers:t});return{featureFlags:a.data,meta:a.meta}}async getFeatureFlagById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/feature-flags/${e}`,{headers:t})).data}async updateFeatureFlag(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:r})).data}async deleteFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/feature-flags/${e}`,{headers:t})}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const r=new URLSearchParams;r.append("tenantId",e),r.append("appId",t);const o=`/tenant-feature-flags${r.toString()?`?${r.toString()}`:""}`;return(await this.httpService.get(o,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,r){if(!e||!t||!r)throw new Error("Flag Key, Tenant ID and App ID are required");const o=new URLSearchParams;o.append("tenantId",t),o.append("appId",r);const a=`/tenant-feature-flags/${e}${o.toString()?`?${o.toString()}`:""}`;return(await this.httpService.get(a,{headers:{"X-Tenant-ID":t}})).data}}const Pe=i.createContext(null);function vt({config:s={},children:e}){const t=$e(),r=ue(),o=(t==null?void 0:t.baseUrl)??"",a=(t==null?void 0:t.appId)??"",l=(r==null?void 0:r.tenant)??null,[p,f]=i.useState([]),[w,u]=i.useState(!1),[x,g]=i.useState(null),[v,P]=i.useState(!1),F=i.useMemo(()=>{const h=new ee(o);return new Oe(h)},[o]),R=async()=>{if(!(l!=null&&l.id)){f([]);return}u(!0),g(null);try{const h=await F.getTenantFeatureFlags(l.id,a);f(h)}catch(h){const k=h instanceof Error?h.message:"Failed to fetch feature flags";g(k),s.onError&&s.onError(h instanceof Error?h:new Error(k))}finally{u(!1)}};i.useEffect(()=>{if(!o||!a)return;R().finally(()=>P(!0));const h=s.refreshInterval||5*60*1e3,k=setInterval(R,h);return()=>clearInterval(k)},[l==null?void 0:l.id,o,a,s.refreshInterval]);const A=i.useMemo(()=>{const h=C=>{const j=p.find(D=>D.key===C);return(j==null?void 0:j.value)===!0},k=C=>p.find(j=>j.key===C),b=C=>{const j=p.find(D=>D.key===C);return j?j.value?"enabled":"disabled":"not_found"},M=async()=>{await R()},E=!!(o&&a)&&(v||!(l!=null&&l.id));return{featureFlags:p,loading:w,error:x,isReady:E,isEnabled:h,getFlag:k,getFlagState:b,refresh:M}},[p,w,x,o,a,l==null?void 0:l.id,v]);return n.jsx(Pe.Provider,{value:A,children:e})}function qe(){const s=i.useContext(Pe);if(!s)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return s}function ze(){return i.useContext(Pe)}class _e{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscription(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscriptions/",e,{headers:t})).data}async getSubscriptionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscriptions/subscriptions/${e}`,{headers:t})).data}async updateSubscription(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:r})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:r})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`)).data}async processPayment(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:r})).data}}const Re=i.createContext(void 0);function Tt({config:s={},children:e}){const t=$e(),r=ue(),o=(t==null?void 0:t.baseUrl)??"",a=(r==null?void 0:r.tenant)??null,[l,p]=i.useState(null),[f,w]=i.useState(!1),[u,x]=i.useState(null),[g,v]=i.useState(!1),P=i.useMemo(()=>{const A=new ee(o);return new _e(A)},[o]),F=async()=>{if(!(a!=null&&a.id)){p(null);return}w(!0),x(null);try{const A=await P.getTenantSubscriptionFeatures(a.id);p(A)}catch(A){const h=A instanceof Error?A.message:"Failed to fetch subscription";x(h),s.onError&&s.onError(A instanceof Error?A:new Error(h))}finally{w(!1)}};i.useEffect(()=>{if(!o||(F().finally(()=>v(!0)),!s.refreshInterval))return;const A=s.refreshInterval||10*60*1e3,h=setInterval(F,A);return()=>clearInterval(h)},[a==null?void 0:a.id,o,s.refreshInterval]);const R=i.useMemo(()=>{const A=(l==null?void 0:l.features)||[],h=j=>{const D=A.find(c=>c.key===j);return D?D.type==="BOOLEAN"||D.type==="boolean"?D.value===!0:!!D.value:!1},k=j=>A.find(D=>D.key===j),b=(j,D)=>{const c=A.find(L=>L.key===j);return c?c.value:D},M=j=>!l||!l.isActive?!1:j.includes(l.planId),E=async()=>{await F()},C=!!o&&(g||!(a!=null&&a.id));return{subscription:l,features:A,loading:f,error:u,isReady:C,isFeatureEnabled:h,getFeature:k,getFeatureValue:b,hasAllowedPlan:M,refresh:E}},[l,f,u,o,a==null?void 0:a.id,g]);return n.jsx(Re.Provider,{value:R,children:e})}function We(){const s=i.useContext(Re);if(s===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return s}function Ve(){return i.useContext(Re)??null}var X=(s=>(s.SUPERUSER="SUPERUSER",s.TENANT_ADMIN="TENANT_ADMIN",s.USER="USER",s))(X||{});const pe={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},Me={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:X.USER},admin:{tenant:"required",auth:"required",userType:X.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},Ee=i.createContext(null);function kt({config:s={},children:e}){const t=i.useMemo(()=>{const r={...pe,...s.zoneRoots},o={...Me,...s.presets};return{zoneRoots:r,presets:o,loadingFallback:s.loadingFallback??null,accessDeniedFallback:s.accessDeniedFallback??null,onAccessDenied:s.onAccessDenied,returnToParam:s.returnToParam??"returnTo",returnToStorage:s.returnToStorage??"url"}},[s]);return n.jsx(Ee.Provider,{value:t,children:e})}function At(){const s=i.useContext(Ee);if(!s)throw new Error("useRouting must be used within a RoutingProvider");return s}function Ze(){const s=i.useContext(Ee);return s||{zoneRoots:pe,presets:Me,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"}}const Ce=()=>n.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:[n.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),n.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),n.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),n.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"})]}),Ne=({userType:s,minUserType:e,missingPermissions:t})=>n.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:[n.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),n.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&s?n.jsxs(n.Fragment,{children:[n.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",n.jsx("strong",{children:e})," access level or higher."]}),n.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",n.jsx("strong",{children:s})]})]}):n.jsxs(n.Fragment,{children:[n.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&&n.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",n.jsx("strong",{children:t.join(", ")})]})]})]}),jt=(s,e)=>{const t={[X.USER]:1,[X.TENANT_ADMIN]:2,[X.SUPERUSER]:3};return t[s]>=t[e]};function Pt({children:s,fallback:e,minUserType:t,requiredPermissions:r,requireAllPermissions:o=!1}){const{hasValidSession:a,sessionManager:l,hasPermission:p,hasAnyPermission:f,hasAllPermissions:w}=re();if(!a())return n.jsx(n.Fragment,{children:e||n.jsx(Ce,{})});const u=l.getUser();if(!u)return n.jsx(n.Fragment,{children:e||n.jsx(Ce,{})});if(t&&!jt(u.userType,t))return n.jsx(Ne,{userType:u.userType,minUserType:t});if(r&&r.length>0&&!(o?w(r):f(r))){const g=r.filter(v=>!p(v)).map(v=>typeof v=="string"?v:v.name);return n.jsx(Ne,{missingPermissions:g})}return n.jsx(n.Fragment,{children:s})}const Rt=({redirectPath:s})=>n.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:n.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[n.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),n.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),n.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),n.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})}),De=({userType:s,requiredUserType:e,missingPermissions:t})=>n.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:n.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[n.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),n.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&s?n.jsxs(n.Fragment,{children:[n.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",n.jsx("strong",{children:e})," access."]}),n.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current user type: ",n.jsx("strong",{children:s})]})]}):n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&n.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",n.jsx("strong",{children:t.join(", ")})]})]})]})}),Mt=(s,e)=>s===e;function Et({children:s,redirectTo:e="/login",requiredUserType:t,requiredPermissions:r,requireAllPermissions:o=!1,fallback:a}){const{hasValidSession:l,sessionManager:p,hasPermission:f,hasAnyPermission:w,hasAllPermissions:u}=re(),x=te.useLocation();if(i.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] ProtectedRoute is deprecated. Use AuthenticatedZone or AdminZone from ZoneRoute instead.")},[]),!l())return a?n.jsx(n.Fragment,{children:a}):n.jsxs(n.Fragment,{children:[n.jsx(Rt,{redirectPath:e}),n.jsx(te.Navigate,{to:e,state:{from:x.pathname},replace:!0})]});const g=p.getUser();if(!g)return n.jsx(te.Navigate,{to:e,state:{from:x.pathname},replace:!0});if(t&&!Mt(g.userType,t))return n.jsx(De,{userType:g.userType,requiredUserType:t});if(r&&r.length>0&&!(o?u(r):w(r))){const P=r.filter(F=>!f(F)).map(F=>typeof F=="string"?F:F.name);return n.jsx(De,{missingPermissions:P})}return n.jsx(n.Fragment,{children:s})}const It=({redirectPath:s})=>n.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:n.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[n.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),n.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),n.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),n.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function Ft({children:s,redirectTo:e="/",fallback:t}){const{tenant:r,isLoading:o,error:a}=oe(),l=te.useLocation();return i.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] TenantRoute is deprecated. Use TenantZone from ZoneRoute instead.")},[]),o||a?null:r?n.jsx(n.Fragment,{children:s}):t?n.jsx(n.Fragment,{children:t}):n.jsxs(n.Fragment,{children:[n.jsx(It,{redirectPath:e}),n.jsx(te.Navigate,{to:e,state:{from:l.pathname},replace:!0})]})}const Lt=({redirectPath:s})=>n.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:n.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[n.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),n.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),n.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),n.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function Ct({children:s,redirectTo:e="/dashboard",fallback:t}){const{tenant:r,isLoading:o,error:a}=oe(),l=te.useLocation();return i.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] LandingRoute is deprecated. Use PublicZone from ZoneRoute instead.")},[]),o||a?null:r?t?n.jsx(n.Fragment,{children:t}):n.jsxs(n.Fragment,{children:[n.jsx(Lt,{redirectPath:e}),n.jsx(te.Navigate,{to:e,state:{from:l.pathname},replace:!0})]}):n.jsx(n.Fragment,{children:s})}function Nt(s,e){return e?s?Array.isArray(e)?e.includes(s):s===e:!1:!0}function Ue(s,e){return!s||s==="optional"?"skip":s==="required"?e?"pass":"fail":s==="forbidden"?e?"fail":"pass":"skip"}function Dt(s,e){return Ue(s.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":Ue(s.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":s.userType&&e.isAuthenticated&&!Nt(e.userType,s.userType)?"wrong_user_type":s.permissions&&s.permissions.length>0&&!(s.requireAllPermissions!==!1?a=>a.every(l=>e.permissions.includes(l)):a=>a.some(l=>e.permissions.includes(l)))(s.permissions)?"missing_permissions":null}function Ut(s,e){return s.hasTenant?s.isAuthenticated?s.userType===X.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:s.isAuthenticated?s.userType===X.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function $t(s,e,t,r,o){if(!e||o!=="url")return s;const a=typeof e=="string"?e:t,l=s.includes("?")?"&":"?";return`${s}${l}${r}=${encodeURIComponent(a)}`}function Ht(s,e,t){if(!s||t==="url")return;const r=typeof s=="string"?s:e,o="zone_return_to";t==="session"?sessionStorage.setItem(o,r):t==="local"&&localStorage.setItem(o,r)}const ne=({children:s,preset:e,tenant:t,auth:r,userType:o,requiredPermissions:a,requireAllPermissions:l=!0,returnTo:p,onAccessDenied:f,redirectTo:w,loadingFallback:u,accessDeniedFallback:x})=>{const g=te.useLocation(),{isAuthenticated:v,isAuthInitializing:P,currentUser:F,userPermissions:R}=re(),{tenant:A,isTenantLoading:h}=se(),k=Ze(),b=i.useMemo(()=>{if(e)return k.presets[e]},[e,k.presets]),M=i.useMemo(()=>({tenant:t??(b==null?void 0:b.tenant),auth:r??(b==null?void 0:b.auth),userType:o??(b==null?void 0:b.userType),permissions:a??(b==null?void 0:b.requiredPermissions),requireAllPermissions:l}),[t,r,o,a,b,l]),E=i.useMemo(()=>({hasTenant:!!A,isAuthenticated:v,userType:F==null?void 0:F.userType,permissions:R,isLoading:P||h}),[A,v,F==null?void 0:F.userType,R,P,h]),C=i.useMemo(()=>E.isLoading?null:Dt(M,E),[M,E]),j=i.useMemo(()=>C?w||Ut(E,k.zoneRoots):null,[C,w,E,k.zoneRoots]),D=i.useMemo(()=>!C||!j?null:{type:C,required:{tenant:M.tenant,auth:M.auth,userType:M.userType,permissions:M.permissions},current:{hasTenant:E.hasTenant,isAuthenticated:E.isAuthenticated,userType:E.userType,permissions:E.permissions},redirectTo:j},[C,j,M,E]);if(i.useEffect(()=>{D&&(f?f(D):k.onAccessDenied&&k.onAccessDenied(D))},[D,f,k]),i.useEffect(()=>{D&&p&&Ht(p,g.pathname+g.search,k.returnToStorage)},[D,p,g.pathname,g.search,k.returnToStorage]),E.isLoading)return n.jsx(n.Fragment,{children:u??k.loadingFallback??null});if(D&&j){const c=x??k.accessDeniedFallback;if(c)return n.jsx(n.Fragment,{children:c});const L=$t(j,p,g.pathname+g.search,k.returnToParam,k.returnToStorage);return n.jsx(te.Navigate,{to:L,replace:!0})}return n.jsx(n.Fragment,{children:s})},Bt=s=>n.jsx(ne,{tenant:"required",...s}),Ot=s=>n.jsx(ne,{tenant:"forbidden",...s}),qt=s=>n.jsx(ne,{auth:"required",...s}),zt=s=>n.jsx(ne,{auth:"forbidden",...s}),_t=s=>n.jsx(ne,{auth:"required",userType:X.TENANT_ADMIN,...s}),Wt=s=>n.jsx(ne,{auth:"required",userType:X.USER,...s}),Vt=s=>n.jsx(ne,{tenant:"optional",auth:"optional",...s}),Zt=s=>n.jsx(ne,{tenant:"required",auth:"required",...s}),Gt=s=>n.jsx(ne,{tenant:"required",auth:"optional",...s}),Kt=s=>n.jsx(ne,{tenant:"required",auth:"forbidden",...s}),Jt=()=>n.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[n.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),n.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function Yt({children:s,fallback:e=n.jsx(Jt,{}),allowedPlans:t,requiredFeature:r}){const{subscription:o,hasAllowedPlan:a,isFeatureEnabled:l,loading:p}=We();return p?n.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):o?o.isActive?t&&t.length>0&&!a(t)?n.jsx(n.Fragment,{children:e}):r&&!l(r)?n.jsx(n.Fragment,{children:e}):n.jsx(n.Fragment,{children:s}):n.jsx(n.Fragment,{children:e}):n.jsx(n.Fragment,{children:e})}const Qt=({flagName:s})=>n.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:[n.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),n.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),n.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',s,'" is disabled']})]});function Xt({name:s,children:e,fallback:t}){const{isEnabled:r,loading:o}=qe();return o?n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):r(s)?n.jsx(n.Fragment,{children:e}):n.jsx(n.Fragment,{children:t||n.jsx(Qt,{flagName:s})})}const en=()=>n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[n.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),tn=()=>n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[n.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),nn={showPassword:n.jsx(en,{}),hidePassword:n.jsx(tn,{})},rn={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..."},sn={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"}};function on({copy:s={},styles:e={},icons:t={},onSuccess:r,onError:o,onForgotPassword:a,onSignupClick:l,onMagicLinkClick:p,showForgotPassword:f=!0,showSignupLink:w=!0,showMagicLinkOption:u=!0,className:x}){const[g,v]=i.useState(""),[P,F]=i.useState(""),[R,A]=i.useState(!1),[h,k]=i.useState(!1),[b,M]=i.useState(""),[E,C]=i.useState({}),{login:j}=re(),{tenant:D}=oe(),c={...rn,...s},L={...sn,...e},N={...nn,...t},d=()=>{const m={};return g.trim()||(m.username=!0),P.trim()||(m.password=!0),C(m),Object.keys(m).length===0},U=async m=>{if(m.preventDefault(),!!d()){if(!(D!=null&&D.id)){M("Tenant not found");return}k(!0),M("");try{const S=await j({username:g,password:P});r==null||r(S)}catch(S){const W=S.message||c.errorMessage;M(W),o==null||o(W)}finally{k(!1)}}},I=m=>({...L.input,...E[m]?L.inputError:{}}),y=()=>({...L.button,...h?L.buttonLoading:{},...!g||!P||h?L.buttonDisabled:{}});return n.jsxs("div",{className:x,style:L.container,children:[n.jsx("h2",{style:L.title,children:c.title}),n.jsxs("form",{onSubmit:U,style:L.form,children:[n.jsxs("div",{style:L.fieldGroup,children:[n.jsx("label",{style:L.label,children:c.usernameLabel}),n.jsx("input",{id:"username",name:"username",type:"text",value:g,onChange:m=>{v(m.target.value),E.username&&C(S=>({...S,username:!1}))},placeholder:c.usernamePlaceholder,style:I("username"),disabled:h})]}),n.jsxs("div",{style:L.fieldGroup,children:[n.jsx("label",{style:L.label,children:c.passwordLabel}),n.jsxs("div",{style:L.inputContainer,children:[n.jsx("input",{id:"password",name:"password",type:R?"text":"password",value:P,onChange:m=>{F(m.target.value),E.password&&C(S=>({...S,password:!1}))},placeholder:c.passwordPlaceholder,style:{...I("password"),paddingRight:"2.5rem"},disabled:h}),n.jsx("button",{type:"button",onClick:()=>A(!R),style:L.passwordToggle,disabled:h,"aria-label":R?"Hide password":"Show password",children:R?N.hidePassword:N.showPassword})]})]}),n.jsx("button",{type:"submit",disabled:!g||!P||h,style:y(),children:h?c.loadingText:c.submitButton}),b&&n.jsx("div",{style:L.errorText,children:b})]}),(f||w||u)&&n.jsxs("div",{style:L.linkContainer,children:[u&&n.jsxs("div",{children:[n.jsxs("span",{style:L.divider,children:[c.magicLinkText," "]}),n.jsx("a",{onClick:p,style:L.link,children:c.magicLinkLink})]}),u&&(f||w)&&n.jsx("div",{style:L.divider,children:"•"}),f&&n.jsx("a",{onClick:a,style:L.link,children:c.forgotPasswordLink}),f&&w&&n.jsx("div",{style:L.divider,children:"•"}),w&&n.jsxs("div",{children:[n.jsxs("span",{style:L.divider,children:[c.signupText," "]}),n.jsx("a",{onClick:l,style:L.link,children:c.signupLink})]})]})]})}const an={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"},ln={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},checkbox:{marginRight:"0.5rem"},checkboxContainer:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem 0"},checkboxLabel:{fontSize:"0.875rem",color:"#374151",lineHeight:"1.4"},button:{padding:"0.75rem 1rem",backgroundColor:"#10b981",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"}};function cn({copy:s={},styles:e={},signupType:t="user",onSuccess:r,onError:o,onLoginClick:a,onMagicLinkClick:l,showLoginLink:p=!0,showMagicLinkOption:f=!0,className:w}){const[u,x]=i.useState(""),[g,v]=i.useState(""),[P,F]=i.useState(""),[R,A]=i.useState(""),[h,k]=i.useState(""),[b,M]=i.useState(""),[E,C]=i.useState(""),[j,D]=i.useState(!1),[c,L]=i.useState(""),[N,d]=i.useState({}),{signup:U,signupTenantAdmin:I}=re(),{tenant:y}=oe(),m={...an,...s},S={...ln,...e},W=()=>{const T={};return u.trim()||(T.name=!0),!P.trim()&&!R.trim()&&(T.email=!0,T.phoneNumber=!0),h.trim()||(T.password=!0),b.trim()||(T.confirmPassword=!0),t==="tenant"&&!E.trim()&&(T.tenantName=!0),d(T),Object.keys(T).length===0},G=async T=>{if(T.preventDefault(),!!W()){if(h!==b){L(m.passwordMismatchError),d({confirmPassword:!0});return}if(t==="user"&&!(y!=null&&y.id)){L("Tenant not found");return}D(!0),L("");try{let V;t==="tenant"?V=await I({email:P||void 0,phoneNumber:R||void 0,name:u,password:h,tenantName:E,lastName:g||void 0}):V=await U({email:P||void 0,phoneNumber:R||void 0,name:u,password:h,tenantId:y.id,lastName:g||void 0}),r==null||r(V)}catch(V){const ae=V.message||m.errorMessage;L(ae),o==null||o(ae)}finally{D(!1)}}},H=T=>({...S.input,...N[T]?S.inputError:{}}),B=()=>({...S.button,...j?S.buttonLoading:{},...!u||!P&&!R||!h||!b||j||t==="tenant"&&!E?S.buttonDisabled:{}}),z=u&&(P||R)&&h&&b&&(t==="user"||E);return n.jsxs("div",{className:w,style:S.container,children:[n.jsx("h2",{style:S.title,children:m.title}),n.jsxs("form",{onSubmit:G,style:S.form,children:[n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.nameLabel}),n.jsx("input",{id:"name",name:"name",type:"text",value:u,onChange:T=>{x(T.target.value),N.name&&d(V=>({...V,name:!1}))},placeholder:m.namePlaceholder,style:H("name"),disabled:j})]}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.lastNameLabel}),n.jsx("input",{id:"lastName",name:"lastName",type:"text",value:g,onChange:T=>v(T.target.value),placeholder:m.lastNamePlaceholder,style:S.input,disabled:j})]}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.emailLabel}),n.jsx("input",{id:"email",name:"email",type:"email",value:P,onChange:T=>{F(T.target.value),N.email&&d(V=>({...V,email:!1,phoneNumber:!1}))},placeholder:m.emailPlaceholder,style:H("email"),disabled:j})]}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.phoneNumberLabel}),n.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:R,onChange:T=>{A(T.target.value),N.phoneNumber&&d(V=>({...V,email:!1,phoneNumber:!1}))},placeholder:m.phoneNumberPlaceholder,style:H("phoneNumber"),disabled:j})]}),n.jsx("div",{style:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"},children:"At least one contact method (email or phone) is required"}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.passwordLabel}),n.jsx("input",{id:"password",name:"password",type:"password",value:h,onChange:T=>{k(T.target.value),N.password&&d(V=>({...V,password:!1}))},placeholder:m.passwordPlaceholder,style:H("password"),disabled:j})]}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.confirmPasswordLabel}),n.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:b,onChange:T=>{M(T.target.value),N.confirmPassword&&d(V=>({...V,confirmPassword:!1})),c===m.passwordMismatchError&&L("")},placeholder:m.confirmPasswordPlaceholder,style:H("confirmPassword"),disabled:j})]}),t==="tenant"&&n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.tenantNameLabel}),n.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:E,onChange:T=>{C(T.target.value),N.tenantName&&d(V=>({...V,tenantName:!1}))},placeholder:m.tenantNamePlaceholder,style:H("tenantName"),disabled:j})]}),n.jsx("button",{type:"submit",disabled:!z||j,style:B(),children:j?m.loadingText:m.submitButton}),c&&n.jsx("div",{style:S.errorText,children:c})]}),(p||f)&&n.jsxs("div",{style:S.linkContainer,children:[f&&n.jsxs("div",{children:[n.jsxs("span",{style:S.divider,children:[m.magicLinkText," "]}),n.jsx("a",{onClick:l,style:S.link,children:m.magicLinkLink})]}),f&&p&&n.jsx("div",{style:S.divider,children:"•"}),p&&n.jsxs("div",{children:[n.jsxs("span",{style:S.divider,children:[m.loginText," "]}),n.jsx("a",{onClick:a,style:S.link,children:m.loginLink})]})]})]})}const dn={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...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you."},un={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1rem",color:"#333333"},description:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",marginBottom:"1.5rem",lineHeight:"1.5"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem",padding:"0.75rem",backgroundColor:"#f0fdf4",borderRadius:"6px",border:"1px solid #bbf7d0"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"}};function hn({copy:s={},styles:e={},onSuccess:t,onError:r,onLoginClick:o,onSignupClick:a,showTraditionalLinks:l=!0,className:p,verifyToken:f,frontendUrl:w}){const[u,x]=i.useState(""),[g,v]=i.useState(""),[P,F]=i.useState(""),[R,A]=i.useState(!1),[h,k]=i.useState(!1),[b,M]=i.useState(""),[E,C]=i.useState(""),[j,D]=i.useState({}),[c,L]=i.useState(!1),{sendMagicLink:N,verifyMagicLink:d}=re(),{tenant:U}=oe(),I={...dn,...s},y={...un,...e};i.useEffect(()=>{f&&m(f)},[f]);const m=async B=>{if(!U||!u){M("Missing tenant or email");return}k(!0),M("");try{const z=await d({token:B,email:u});t==null||t(z)}catch(z){const T=z.message||"Failed to verify magic link";M(T),r==null||r(T)}finally{k(!1)}},S=()=>{const B={};return u.trim()||(B.email=!0),c&&!g.trim()&&(B.name=!0),D(B),Object.keys(B).length===0},W=async B=>{if(B.preventDefault(),!!S()){if(!(U!=null&&U.id)){M("Tenant not found");return}A(!0),M(""),C("");try{const z=w||(typeof window<"u"?window.location.origin:""),T=await N({email:u,tenantId:U.id,frontendUrl:z,name:c?g:void 0,lastName:c?P:void 0});C(I.successMessage),t==null||t(T)}catch(z){const T=z.message||I.errorMessage;M(T),r==null||r(T)}finally{A(!1)}}},G=B=>({...y.input,...j[B]?y.inputError:{}}),H=()=>({...y.button,...R||h?y.buttonLoading:{},...!u||R||h?y.buttonDisabled:{}});return h?n.jsxs("div",{className:p,style:y.container,children:[n.jsx("h2",{style:y.title,children:I.verifyingText}),n.jsx("div",{style:{textAlign:"center",padding:"2rem"},children:n.jsx("div",{style:{fontSize:"1rem",color:"#6b7280"},children:"Please wait while we verify your magic link..."})})]}):n.jsxs("div",{className:p,style:y.container,children:[n.jsx("h2",{style:y.title,children:I.title}),n.jsx("p",{style:y.description,children:I.description}),n.jsxs("form",{onSubmit:W,style:y.form,children:[n.jsxs("div",{style:y.fieldGroup,children:[n.jsx("label",{style:y.label,children:I.emailLabel}),n.jsx("input",{id:"email",name:"email",type:"email",value:u,onChange:B=>{x(B.target.value),j.email&&D(z=>({...z,email:!1}))},placeholder:I.emailPlaceholder,style:G("email"),disabled:R||h})]}),!c&&n.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:n.jsx("button",{type:"button",onClick:()=>L(!0),style:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"New user? Add your name"})}),c&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:y.fieldGroup,children:[n.jsx("label",{style:y.label,children:I.nameLabel}),n.jsx("input",{id:"name",name:"name",type:"text",value:g,onChange:B=>{v(B.target.value),j.name&&D(z=>({...z,name:!1}))},placeholder:I.namePlaceholder,style:G("name"),disabled:R||h})]}),n.jsxs("div",{style:y.fieldGroup,children:[n.jsx("label",{style:y.label,children:I.lastNameLabel}),n.jsx("input",{id:"lastName",name:"lastName",type:"text",value:P,onChange:B=>F(B.target.value),placeholder:I.lastNamePlaceholder,style:y.input,disabled:R||h})]}),n.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:n.jsx("button",{type:"button",onClick:()=>{L(!1),v(""),F("")},style:{background:"none",border:"none",color:"#6b7280",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"Existing user? Hide name fields"})})]}),n.jsx("button",{type:"submit",disabled:!u||R||h,style:H(),children:R?I.loadingText:I.submitButton}),b&&n.jsx("div",{style:y.errorText,children:b}),E&&n.jsx("div",{style:y.successText,children:E})]}),l&&n.jsxs("div",{style:y.linkContainer,children:[n.jsxs("div",{children:[n.jsxs("span",{style:y.divider,children:[I.loginText," "]}),n.jsx("a",{onClick:o,style:y.link,children:I.loginLink})]}),n.jsx("div",{style:y.divider,children:"•"}),n.jsxs("div",{children:[n.jsxs("span",{style:y.divider,children:[I.signupText," "]}),n.jsx("a",{onClick:a,style:y.link,children:I.signupLink})]})]})]})}const gn={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"},Ge={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"}},pn=()=>n.jsx("div",{style:Ge.spinner}),fn=()=>n.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:[n.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),n.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),mn=()=>n.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:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),n.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),yn={loading:n.jsx(pn,{}),success:n.jsx(fn,{}),error:n.jsx(mn,{})};function wn({copy:s={},styles:e={},icons:t={},onSuccess:r,onError:o,onRetry:a,onBackToLogin:l,className:p,token:f,email:w,appId:u,tenantSlug:x,autoRedirectDelay:g=3e3}){const[v,P]=i.useState("verifying"),[F,R]=i.useState(""),{verifyMagicLink:A}=re(),h={...gn,...s},k={...Ge,...e},b={...yn,...t},M=()=>{if(typeof window>"u")return{};const c=new URLSearchParams(window.location.search);return{token:f||c.get("token")||"",email:w||c.get("email")||"",appId:u||c.get("appId")||"",tenantSlug:x||c.get("tenantSlug")||void 0}},E=async()=>{P("verifying"),R("");try{const c=M();if(!c.token||!c.email)throw new Error("Missing required parameters: token or email");const L=await A({token:c.token,email:c.email,tenantSlug:c.tenantSlug});P("success"),r==null||r(L),g>0&&setTimeout(()=>{P("redirecting")},g)}catch(c){const L=c.message||h.errorMessage;R(L),P("error"),o==null||o(L)}},C=()=>{a==null||a(),E()},j=()=>{l==null||l()};i.useEffect(()=>{E()},[]);const D=()=>{switch(v){case"verifying":return n.jsxs("div",{style:k.message,children:[b.loading,h.verifyingMessage]});case"success":return n.jsxs(n.Fragment,{children:[b.success,n.jsx("div",{style:k.successMessage,children:h.successMessage})]});case"redirecting":return n.jsxs(n.Fragment,{children:[b.loading,n.jsx("div",{style:k.message,children:h.redirectingMessage})]});case"error":return n.jsxs(n.Fragment,{children:[b.error,n.jsx("div",{style:k.errorMessage,children:F||h.errorMessage}),n.jsxs("div",{style:k.buttonContainer,children:[n.jsx("button",{onClick:C,style:k.retryButton,onMouseOver:c=>{c.currentTarget.style.backgroundColor="#2563eb"},onMouseOut:c=>{c.currentTarget.style.backgroundColor="#3b82f6"},children:h.retryButton}),n.jsx("button",{onClick:j,style:k.backButton,onMouseOver:c=>{c.currentTarget.style.backgroundColor="#e5e7eb"},onMouseOut:c=>{c.currentTarget.style.backgroundColor="#f3f4f6"},children:h.backToLoginButton})]})]});default:return null}};return n.jsxs("div",{style:k.container,className:p,children:[n.jsx("style",{children:`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),i=require("react"),te=require("react-router-dom");class ee{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async request(e,t,r,a){return this.executeRequest(e,t,r,a,!1)}async executeRequest(e,t,r,a,o=!1){const l=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,p=(a==null?void 0:a.timeout)||this.timeout;let f={"Content-Type":"application/json",...a==null?void 0:a.headers};if(!(a!=null&&a.skipAuth)&&this.sessionManager)try{const x=await this.sessionManager.getAuthHeaders();f={...f,...x}}catch(x){console.warn("Failed to inject auth headers:",x)}const w=new AbortController,u=setTimeout(()=>w.abort(),p);try{const x=await fetch(l,{method:e,headers:f,body:r?JSON.stringify(r):void 0,signal:w.signal});if(clearTimeout(u),x.status===401&&!(a!=null&&a.skipRetry)&&!o&&this.sessionManager)try{const v=this.sessionManager.getTokens();if(v!=null&&v.refreshToken)return await this.sessionManager.getAuthHeaders(),this.executeRequest(e,t,r,a,!0)}catch{throw new Error(`HTTP ${x.status}: ${x.statusText}`)}if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);const g=x.headers.get("content-type");return!g||!g.includes("application/json")?{}:await x.json()}catch(x){throw clearTimeout(u),x instanceof Error&&x.name==="AbortError"?new Error(`Request timeout after ${p}ms`):x}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,r){return this.request("POST",e,t,r)}async put(e,t,r){return this.request("PUT",e,t,r)}async delete(e,t){return this.request("DELETE",e,void 0,t)}}class Se{constructor(e,t){this.httpService=e,this.sessionManager=t}async createApp(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/apps/",e,{headers:t})).data}async getApps(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const a=`/apps/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(a,{headers:t});return{apps:o.data,meta:o.meta}}async getAppById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}`,{headers:t})).data}async updateApp(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:r})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:r})).data}async updateSettingsSchema(e,t,r){const a=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:r},{headers:a})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const Te=i.createContext(null);function ct({config:s,children:e}){const t=i.useMemo(()=>{var g,v,P;return{enabled:((g=s.cache)==null?void 0:g.enabled)??!0,ttl:((v=s.cache)==null?void 0:v.ttl)??3e5,storageKey:((P=s.cache)==null?void 0:P.storageKey)??`app_cache_${s.appId}`}},[s.cache,s.appId]),[r,a]=i.useState(()=>{if(!t.enabled)return null;try{const g=localStorage.getItem(t.storageKey);if(!g)return null;const v=JSON.parse(g);return Date.now()-v.timestamp<t.ttl&&v.appId===s.appId?v.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[o,l]=i.useState(!r),[p,f]=i.useState(null),w=i.useMemo(()=>{const g=()=>{u()};return{appId:s.appId,baseUrl:s.baseUrl,appInfo:r,isAppLoading:o,appError:p,retryApp:g}},[s,r,o,p]),u=i.useCallback(async(g=!1)=>{if(!(!g&&t.enabled&&r))try{l(!0),f(null);const v=new ee(s.baseUrl),F=await new Se(v,{}).getPublicAppInfo(s.appId);if(a(F),t.enabled)try{const R={data:F,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(R))}catch(R){console.warn("Failed to cache app info:",R)}}catch(v){const P=v instanceof Error?v:new Error("Failed to load app information");f(P),a(null)}finally{l(!1)}},[s.baseUrl,s.appId,t,r]),x=i.useCallback(async()=>{if(!(!t.enabled||!r))try{const g=localStorage.getItem(t.storageKey);if(!g)return;const v=JSON.parse(g);if(Date.now()-v.timestamp>t.ttl*.5){const F=new ee(s.baseUrl),A=await new Se(F,{}).getPublicAppInfo(s.appId);a(A);const h={data:A,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(h))}}catch(g){console.warn("Background app refresh failed:",g)}},[s,t,r]);return i.useEffect(()=>{r?x():u()},[]),n.jsx(Te.Provider,{value:w,children:e})}function ce(){const s=i.useContext(Te);if(!s)throw new Error("useApp must be used within an AppProvider");return s}function $e(){return i.useContext(Te)}const dt=ce;class ge{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],e.tenantSlug!==void 0?this.storageKey=e.tenantSlug?`auth_tokens_${e.tenantSlug}`:"auth_tokens":this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.baseUrl=e.baseUrl||"",this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey)}createTokenStorage(e){return{get:()=>{try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},set:t=>{try{localStorage.setItem(e,JSON.stringify(t))}catch{}},clear:()=>{try{localStorage.removeItem(e)}catch{}}}}setTokens(e){const t={...e,expiresAt:e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)};this.tokenStorage.set(t)}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:r,expiresIn:a,tokenType:o}=this.tokenStorage.get()||{};return e?{accessToken:e,refreshToken:t,expiresAt:r,expiresIn:a,tokenType:o}:null}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}async getAuthHeaders(){const e=this.getTokens();if(!(e!=null&&e.accessToken))return{};if(!this.shouldRefreshToken(e))return{Authorization:`Bearer ${e.accessToken}`};if(!e.refreshToken)return this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{};if(this.refreshPromise)return new Promise((t,r)=>{this.refreshQueue.push({resolve:t,reject:r})});this.refreshPromise=this.performTokenRefresh(e.refreshToken);try{await this.refreshPromise;const t=this.getTokens(),r=t!=null&&t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{};return this.refreshQueue.forEach(({resolve:a})=>a(r)),this.refreshQueue=[],r}catch(t){const r=t instanceof Error?t:new Error("Token refresh failed");return this.refreshQueue.forEach(({reject:a})=>a(r)),this.refreshQueue=[],this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{}}finally{this.refreshPromise=null}}async performTokenRefresh(e){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const t=`${this.baseUrl}/auth/refresh`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status} ${r.statusText}`);const a=await r.json();this.setTokens({accessToken:a.accessToken,refreshToken:a.refreshToken||e,expiresIn:a.expiresIn})}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.clearTokens(),this.clearUser()}getTokenPayload(){try{const e=this.getTokens();if(!(e!=null&&e.accessToken))return null;const t=e.accessToken.split(".");if(t.length!==3)return null;const r=t[1],a=atob(r.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(a)}catch{return null}}getUserId(){const e=this.getTokenPayload();if(e!=null&&e.userId)return e.userId;const t=this.getUser();return(t==null?void 0:t.id)||null}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}}class He{constructor(e){this.httpService=e}async login(e){return await this.httpService.post("/auth/login",e)}async signup(e){return await this.httpService.post("/auth/signup",e)}async signupTenantAdmin(e){return await this.httpService.post("/auth/signup/tenant-admin",e)}async refreshToken(e){return await this.httpService.post("/auth/refresh",e)}async switchTenant(e){return await this.httpService.post("/auth/switch-tenant",e)}async getUserTenants(e){return await this.httpService.get("/auth/tenants",{headers:e})}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e)}async sendMagicLink(e){return await this.httpService.post("/auth/magic-link/send",e)}async verifyMagicLink(e){return await this.httpService.post("/auth/magic-link/verify",e)}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e)}async changePassword(e,t){await this.httpService.post("/auth/change-password",e,{headers:t})}}class ve{constructor(e,t){this.httpService=e,this.sessionManager=t}async createRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/roles/",e,{headers:t})).data}async getRoleById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/roles/${e}`,{headers:t})).data}async updateRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:r})).data}async deleteRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/roles/${e}`,{headers:t})}async getRolesByApp(e,t){const r=new URLSearchParams;t!=null&&t.page&&r.append("page",t.page.toString()),t!=null&&t.limit&&r.append("limit",t.limit.toString()),t!=null&&t.sortBy&&r.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&r.append("sortOrder",t.sortOrder);const a=`/roles/app/${e}${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(a);return{roles:o.data,meta:o.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:r})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:r})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders(),a=new URLSearchParams;t!=null&&t.page&&a.append("page",t.page.toString()),t!=null&&t.limit&&a.append("limit",t.limit.toString()),t!=null&&t.sortBy&&a.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&a.append("sortOrder",t.sortOrder);const o=`/roles/user/${e}${a.toString()?`?${a.toString()}`:""}`,l=await this.httpService.get(o,{headers:r});return{roles:l.data,meta:l.meta}}}class Be{constructor(e,t){this.httpService=e,this.sessionManager=t}async createUser(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/users/",e,{headers:t})).data}async getUsers(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const a=`/users/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(a,{headers:t});return{users:o.data,meta:o.meta}}async getUserById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/users/${e}`,{headers:t})).data}async updateUser(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:r})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class le{constructor(e,t,r){this.httpService=e,this.appId=t,this.sessionManager=r}async createTenant(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/tenants/",e,{headers:t})).data}async getTenants(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const a=`/tenants/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(a,{headers:t});return{tenants:o.data,meta:o.meta}}async getTenantById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/tenants/${e}`,{headers:t})).data}async updateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:r})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:r})).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`)).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`)).data}async updateTenantSettings(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:r})).data}}function ut(s,e){if(s==="localhost"||s.startsWith("127.")||s.startsWith("192.168."))return null;if(e){const a=e.toLowerCase(),o=s.toLowerCase();if(o===a||o===`www.${a}`)return null;if(o.endsWith(`.${a}`)){const l=o.slice(0,-(a.length+1));return l==="www"?null:l}return null}const r=s.split(".");return r.length>=3&&r[0]!=="www"?r[0]:null}function ht(s,e="tenant",t){const a=new URLSearchParams(s).get(e);return a?(t&&t.setItem("tenant",a),a):t?t.getItem("tenant"):null}function gt(s,e,t){const{tenantMode:r,baseDomain:a,selectorParam:o,fixedTenantSlug:l}=s;return r==="fixed"?l||null:r==="subdomain"?ut(e.hostname,a):r==="selector"?ht(e.search,o,t):null}function pt(s,e,t){if(t)return`${s}.${t}`;const r=e.split(".");return r.length===2?`${s}.${e}`:r.length>=3?(r[0]=s,r.join(".")):null}const ie="_auth";function Le(s){const e=JSON.stringify(s);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ft(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";const t=atob(e),r=JSON.parse(t);return typeof r.accessToken=="string"&&typeof r.refreshToken=="string"&&typeof r.expiresIn=="number"?r:null}catch{return null}}function mt(){if(typeof window>"u")return console.log("[CrossDomainAuth] SSR environment, skipping URL token extraction"),null;const e=new URLSearchParams(window.location.search).get(ie);if(console.log("[CrossDomainAuth] extractAuthTokensFromUrl called",{hasAuthParam:!!e,searchParams:window.location.search,encodedLength:e==null?void 0:e.length}),!e)return null;const t=ft(e);return console.log("[CrossDomainAuth] Token decode result:",{success:!!t,hasAccessToken:!!(t!=null&&t.accessToken),hasRefreshToken:!!(t!=null&&t.refreshToken),expiresIn:t==null?void 0:t.expiresIn}),t}function yt(){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.delete(ie),console.log("[CrossDomainAuth] Clearing auth tokens from URL",{oldUrl:window.location.href,newUrl:s.toString()}),window.history.replaceState({},"",s.toString())}const ke=i.createContext(null);function wt({config:s,children:e}){const{baseUrl:t,appInfo:r,appId:a}=ce(),o=i.useCallback(()=>typeof window>"u"?null:gt({tenantMode:s.tenantMode||"selector",baseDomain:s.baseDomain,selectorParam:s.selectorParam,fixedTenantSlug:s.fixedTenantSlug},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[s.tenantMode,s.baseDomain,s.selectorParam,s.fixedTenantSlug]),[l,p]=i.useState(()=>o()),f=i.useMemo(()=>{var d,U,I;return{enabled:((d=s.cache)==null?void 0:d.enabled)??!0,ttl:((U=s.cache)==null?void 0:U.ttl)??5*60*1e3,storageKey:((I=s.cache)==null?void 0:I.storageKey)??`tenant_cache_${l||"default"}`}},[s.cache,l]),[w,u]=i.useState(()=>{if(s.initialTenant)return s.initialTenant;if(!f.enabled||!l)return null;try{const d=localStorage.getItem(f.storageKey);if(!d)return null;const U=JSON.parse(d);return Date.now()-U.timestamp<f.ttl&&U.tenantSlug===l?U.data:(localStorage.removeItem(f.storageKey),null)}catch{return null}}),[x,g]=i.useState(!w&&!s.initialTenant),[v,P]=i.useState(null),[F,R]=i.useState(null),[A,h]=i.useState(!1),[k,b]=i.useState(null);i.useEffect(()=>{if(s.tenantMode==="fixed")return;const d=o();p(d)},[o,s.tenantMode]);const M=(r==null?void 0:r.settingsSchema)||null,E=i.useCallback(async(d,U=!1)=>{if(!(!U&&f.enabled&&w&&w.domain===d))try{g(!0),P(null);const I=new ee(t),m=await new le(I,a).getPublicTenantInfo(d);if(u(m),f.enabled)try{const S={data:m,timestamp:Date.now(),tenantSlug:d};localStorage.setItem(f.storageKey,JSON.stringify(S))}catch(S){console.warn("Failed to cache tenant info:",S)}}catch(I){const y=I instanceof Error?I:new Error("Failed to load tenant information");P(y),u(null)}finally{g(!1)}},[t,a,f,w]),C=i.useCallback(async()=>{if(!(!f.enabled||!w||!l))try{const d=localStorage.getItem(f.storageKey);if(!d)return;const U=JSON.parse(d);if(Date.now()-U.timestamp>f.ttl*.5){const y=new ee(t),S=await new le(y,a).getPublicTenantInfo(l);u(S);const W={data:S,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(f.storageKey,JSON.stringify(W))}}catch(d){console.warn("Background tenant refresh failed:",d)}},[t,a,f,w,l]),j=i.useCallback(async()=>{if(w!=null&&w.id)try{h(!0),b(null);const d=new ee(t),I=await new le(d,w.appId).getTenantSettings(w.id);R(I)}catch(d){const U=d instanceof Error?d:new Error("Failed to load tenant settings");b(U),R(null)}finally{h(!1)}},[t,w]),D=i.useCallback(()=>{j()},[j]),c=i.useCallback(d=>{if(!M)return{isValid:!0,errors:[]};const U=[];try{return M.properties&&Object.entries(M.properties).forEach(([I,y])=>{var S;const m=d[I];if((S=M.required)!=null&&S.includes(I)&&m==null){U.push(`Field '${I}' is required`);return}if(m!=null){if(y.type){const W=y.type,G=typeof m;W==="string"&&G!=="string"?U.push(`Field '${I}' must be a string`):(W==="number"||W==="integer")&&G!=="number"?U.push(`Field '${I}' must be a number`):W==="boolean"&&G!=="boolean"?U.push(`Field '${I}' must be a boolean`):W==="array"&&!Array.isArray(m)&&U.push(`Field '${I}' must be an array`)}y.minLength!==void 0&&typeof m=="string"&&m.length<y.minLength&&U.push(`Field '${I}' must be at least ${y.minLength} characters long`),y.maxLength!==void 0&&typeof m=="string"&&m.length>y.maxLength&&U.push(`Field '${I}' must be no more than ${y.maxLength} characters long`),y.minimum!==void 0&&typeof m=="number"&&m<y.minimum&&U.push(`Field '${I}' must be at least ${y.minimum}`),y.maximum!==void 0&&typeof m=="number"&&m>y.maximum&&U.push(`Field '${I}' must be no more than ${y.maximum}`),y.pattern&&typeof m=="string"&&(new RegExp(y.pattern).test(m)||U.push(`Field '${I}' does not match the required pattern`)),y.enum&&!y.enum.includes(m)&&U.push(`Field '${I}' must be one of: ${y.enum.join(", ")}`)}}),{isValid:U.length===0,errors:U}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[M]);i.useEffect(()=>{!s.initialTenant&&l?w?C():E(l):!s.initialTenant&&!l&&(u(null),P(null),g(!1))},[s.initialTenant,l,w,E,C]),i.useEffect(()=>{w!=null&&w.id?j():(R(null),b(null),h(!1))},[w==null?void 0:w.id,j]);const L=i.useCallback((d,U)=>{const{mode:I="reload",tokens:y,redirectPath:m}=U||{},S=s.tenantMode||"selector";if(S==="fixed"){console.warn("[TenantProvider] switchTenant is a no-op in fixed mode. Tenant is always:",s.fixedTenantSlug),m&&(window.location.href=m);return}if(localStorage.setItem("tenant",d),S==="subdomain"){const W=window.location.hostname,G=pt(d,W,s.baseDomain);if(!G){console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",W);return}const H=m||window.location.pathname,B=new URL(`${window.location.protocol}//${G}${H}`);new URLSearchParams(window.location.search).forEach((T,V)=>{V!==ie&&B.searchParams.set(V,T)}),y&&B.searchParams.set(ie,Le(y)),window.location.href=B.toString()}else if(S==="selector"){const W=m||window.location.pathname,G=new URLSearchParams(window.location.search);if(G.set(s.selectorParam||"tenant",d),G.delete(ie),y&&G.set(ie,Le(y)),I==="reload"){const H=`${W}?${G.toString()}${window.location.hash}`;window.location.href=H}else{const H=`${W}?${G.toString()}${window.location.hash}`;window.history.pushState({},"",H),p(d),E(d)}}},[s.tenantMode,s.selectorParam,s.baseDomain,E]),N=i.useMemo(()=>({tenant:w,tenantSlug:l,isTenantLoading:x,tenantError:v,retryTenant:()=>{l&&E(l)},settings:F,settingsSchema:M,isSettingsLoading:A,settingsError:k,refreshSettings:D,switchTenant:L,validateSettings:c}),[w,l,x,v,F,M,A,k,D,L,c]);return n.jsx(ke.Provider,{value:N,children:e})}function se(){const s=i.useContext(ke);if(!s)throw new Error("useTenant must be used within a TenantProvider");return s}function ue(){return i.useContext(ke)}const xt=se;function bt(){const{settings:s,settingsSchema:e,isSettingsLoading:t,settingsError:r,validateSettings:a}=se();return{settings:s,settingsSchema:e,isLoading:t,error:r,validateSettings:a}}function ae(){const{tenant:s,tenantSlug:e,isTenantLoading:t,tenantError:r,retryTenant:a}=se();return{tenant:s,tenantSlug:e,isLoading:t,error:r,retry:a}}const Ae=i.createContext(null);function St({config:s={},children:e}){const{appId:t,baseUrl:r}=ce(),{tenant:a,tenantSlug:o,switchTenant:l}=se(),[p,f]=i.useState(s.initialRoles||[]),[w,u]=i.useState(!s.initialRoles),[x,g]=i.useState(null),[v,P]=i.useState(!1),[F,R]=i.useState(null),[A,h]=i.useState(0),[k,b]=i.useState(()=>{try{const T=localStorage.getItem("userTenants");return T?JSON.parse(T):[]}catch{return[]}}),[M,E]=i.useState(!1),C=i.useRef({done:!1,urlTokens:null});C.current.done||(C.current.done=!0,C.current.urlTokens=mt(),C.current.urlTokens&&console.log("[AuthProvider] SYNC: URL tokens found, will block isAuthReady until user loaded"));const[j,D]=i.useState(()=>{const T=C.current.urlTokens!==null;return console.log("[AuthProvider] SYNC: isLoadingAfterUrlTokens initial:",T),T}),c=i.useMemo(()=>{const T=new ge({tenantSlug:o,onRefreshFailed:s.onRefreshFailed,baseUrl:r});return C.current.urlTokens&&(console.log("[AuthProvider] SYNC: Saving URL tokens to session manager"),T.setTokens({accessToken:C.current.urlTokens.accessToken,refreshToken:C.current.urlTokens.refreshToken,expiresIn:C.current.urlTokens.expiresIn}),console.log("[AuthProvider] SYNC: Session valid:",T.hasValidSession())),T},[o,r,s.onRefreshFailed]),L=C.current.done&&!j,N=i.useMemo(()=>{const T=new ee(r);return T.setSessionManager(c),T},[r,c]),d=i.useMemo(()=>new He(new ee(r)),[r]),U=i.useMemo(()=>new Be(N,c),[N,c]),I=i.useMemo(()=>new ve(new ee(r)),[r]),y=i.useMemo(()=>x||c.getUser(),[x,c]),m=i.useMemo(()=>y!=null&&y.roleId&&p.find(T=>T.id===y.roleId)||null,[y,p]),S=i.useMemo(()=>(m==null?void 0:m.permissions)||[],[m]),W=i.useMemo(()=>c.hasValidSession()&&x!==null,[c,x]),G=5*60*1e3,H=i.useMemo(()=>{const T=async($=!1)=>{try{if(!c.hasValidSession())return;const O=Date.now();if(!$&&O-A<G&&x)return;const q=c.getUserId();if(!q){console.warn("[AuthProvider] No userId available in token or storage");return}P(!0),R(null);const Z=await U.getUserById(q);g(Z),c.setUser(Z),h(Date.now())}catch(O){const K=O instanceof Error?O:new Error("Failed to load user data");R(K),console.error("[AuthProvider] Failed to load user data:",K)}finally{P(!1)}},V=async()=>{await T()},oe=async $=>{var Ie;const{username:O,password:K,tenantSlug:q,redirectPath:Z}=$;let J=a==null?void 0:a.id,Y=o,Q=c;q&&(J=(await new le(N,t).getPublicTenantInfo(q)).id,Y=q);const _=await d.login({username:O,password:K,appId:t,tenantId:J}),de=q&&q!==o;if(de&&(Q=new ge({tenantSlug:Y,baseUrl:r})),Q.setTokens({accessToken:_.accessToken,refreshToken:_.refreshToken,expiresIn:_.expiresIn}),_.user){Q.setUser(_.user),g(_.user);try{await T()}catch(he){console.warn("Failed to load complete user data after login:",he)}}if(_.tenants&&_.tenants.length>0){b(_.tenants);try{localStorage.setItem("userTenants",JSON.stringify(_.tenants))}catch{}}const ye=((Ie=_.user)==null?void 0:Ie.tenantId)!==null;E(ye);const we={accessToken:_.accessToken,refreshToken:_.refreshToken,expiresIn:_.expiresIn};if(de&&Y)return l(Y,{tokens:we,redirectPath:Z}),_;if(Z&&Z!==window.location.pathname)return l(Y||o||"",{tokens:we,redirectPath:Z}),_;if(!ye&&_.tenants&&_.tenants.length>0){const he=$.autoSwitch!==!1&&s.autoSwitchSingleTenant!==!1;if(_.tenants.length===1&&he){const Fe=_.tenants[0];return l(Fe.subdomain,{tokens:we,redirectPath:Z}),_}else _.tenants.length>1&&s.onTenantSelectionRequired&&s.onTenantSelectionRequired(_.tenants)}return _},fe=async $=>{const{email:O,phoneNumber:K,name:q,password:Z,lastName:J,tenantId:Y}=$;if(!O&&!K)throw new Error("Either email or phoneNumber is required");if(!q||!Z)throw new Error("Name and password are required");const Q=Y??(a==null?void 0:a.id);return await d.signup({email:O,phoneNumber:K,name:q,password:Z,tenantId:Q,lastName:J,appId:t})},Je=async $=>{const{email:O,phoneNumber:K,name:q,password:Z,tenantName:J,lastName:Y}=$;if(!O&&!K)throw new Error("Either email or phoneNumber is required");if(!q||!Z||!J)throw new Error("Name, password, and tenantName are required");return await d.signupTenantAdmin({email:O,phoneNumber:K,name:q,password:Z,tenantName:J,appId:t,lastName:Y})},Ye=async $=>{const{currentPassword:O,newPassword:K}=$,q=await c.getAuthHeaders();await d.changePassword({currentPassword:O,newPassword:K},q)},Qe=async $=>{const{email:O,tenantId:K}=$,q=K??(a==null?void 0:a.id);if(!q)throw new Error("tenantId is required for password reset");await d.requestPasswordReset({email:O,tenantId:q})},Xe=async $=>{const{token:O,newPassword:K}=$;await d.confirmPasswordReset({token:O,newPassword:K})},et=async $=>{const{email:O,frontendUrl:K,name:q,lastName:Z,tenantId:J}=$,Y=J??(a==null?void 0:a.id);if(!Y)throw new Error("tenantId is required for magic link authentication");return await d.sendMagicLink({email:O,tenantId:Y,frontendUrl:K,name:q,lastName:Z,appId:t})},tt=async $=>{const{token:O,email:K,tenantSlug:q}=$;let Z=a==null?void 0:a.id,J=o,Y=c;q&&(Z=(await new le(N,t).getPublicTenantInfo(q)).id,J=q);const Q=await d.verifyMagicLink({token:O,email:K,appId:t,tenantId:Z}),_=q&&q!==o;if(_&&(Y=new ge({tenantSlug:J,baseUrl:r})),Y.setTokens({accessToken:Q.accessToken,refreshToken:Q.refreshToken,expiresIn:Q.expiresIn}),Q.user){Y.setUser(Q.user),g(Q.user);try{await T()}catch(de){console.warn("Failed to load complete user data after magic link login:",de)}}return _&&J&&J!==o&&l(J,{tokens:{accessToken:Q.accessToken,refreshToken:Q.refreshToken,expiresIn:Q.expiresIn}}),Q},nt=async()=>{const $=c.getTokens();if(!($!=null&&$.refreshToken))throw new Error("No refresh token available");const O=await d.refreshToken({refreshToken:$.refreshToken});c.setTokens({accessToken:O.accessToken,refreshToken:O.refreshToken||$.refreshToken,expiresIn:O.expiresIn})},rt=()=>{c.clearSession(),g(null),R(null),b([]),E(!1);try{localStorage.removeItem("userTenants")}catch{}},st=$=>{c.setTokens($)},at=()=>c.hasValidSession(),ot=()=>{c.clearSession(),g(null),R(null)},it=async()=>{if(t)try{u(!0);const{roles:$}=await I.getRolesByApp(t);f($)}catch($){console.error("Failed to fetch roles:",$)}finally{u(!1)}},lt=async()=>{await it()},me=$=>{if(!S||S.length===0)return!1;if(typeof $=="string")return S.includes($);const O=`${$.resource}.${$.action}`;return S.includes(O)};return{isAuthenticated:W,sessionManager:c,authenticatedHttpService:N,login:oe,signup:fe,signupTenantAdmin:Je,sendMagicLink:et,verifyMagicLink:tt,changePassword:Ye,requestPasswordReset:Qe,confirmPasswordReset:Xe,refreshToken:nt,logout:rt,setTokens:st,hasValidSession:at,clearSession:ot,currentUser:x,isUserLoading:v,userError:F,loadUserData:T,refreshUser:V,isAuthInitializing:!L,isAuthReady:L,userRole:m,userPermissions:S,availableRoles:p,rolesLoading:w,hasPermission:me,hasAnyPermission:$=>$.some(O=>me(O)),hasAllPermissions:$=>$.every(O=>me(O)),getUserPermissionStrings:()=>S||[],refreshRoles:lt,userTenants:k,hasTenantContext:M,switchToTenant:async($,O)=>{const{redirectPath:K}=O||{},q=c.getTokens();if(!(q!=null&&q.refreshToken))throw new Error("No refresh token available for tenant switch");const Z=await d.switchTenant({refreshToken:q.refreshToken,tenantId:$});c.setTokens({accessToken:Z.accessToken,refreshToken:q.refreshToken,expiresIn:Z.expiresIn}),g(Z.user),c.setUser(Z.user),E(!0);const J=k.find(Y=>Y.id===$);J&&l(J.subdomain,{tokens:{accessToken:Z.accessToken,refreshToken:q.refreshToken,expiresIn:Z.expiresIn},redirectPath:K})},refreshUserTenants:async()=>{const $=await c.getAuthHeaders(),O=await d.getUserTenants($);b(O);try{localStorage.setItem("userTenants",JSON.stringify(O))}catch{}return O}}},[W,c,N,d,U,I,t,a,o,l,p,x,v,F,k,M,L,m,S,A,G]);i.useEffect(()=>{!s.initialRoles&&t&&(async()=>{try{u(!0);const V=new ee(r),oe=new ve(V),{roles:fe}=await oe.getRolesByApp(t);f(fe)}catch(V){console.error("Failed to fetch roles:",V)}finally{u(!1)}})()},[t,r,s.initialRoles]);const[B,z]=i.useState(!1);return i.useEffect(()=>{B||(z(!0),C.current.urlTokens&&(console.log("[AuthProvider] EFFECT: Cleaning up URL after sync token processing"),yt(),D(!0),console.log("[AuthProvider] EFFECT: Loading user data (blocking isAuthReady)..."),H.loadUserData().catch(T=>{console.error("[AuthProvider] Failed to load user data:",T)}).finally(()=>{console.log("[AuthProvider] EFFECT: User data loaded, releasing isAuthReady"),D(!1)})))},[H,B]),i.useEffect(()=>{const T=c.getUser();T&&c.hasValidSession()&&g(T)},[c]),i.useEffect(()=>{B&&(C.current.urlTokens||!x&&!v&&c.hasValidSession()&&(console.log("[AuthProvider] Auto-loading user data..."),H.loadUserData().catch(()=>{})))},[x,v,H,c,B]),i.useEffect(()=>{if(!c.hasValidSession()||!x)return;const T=setInterval(()=>{H.loadUserData().catch(()=>{})},G);return()=>clearInterval(T)},[c,x,H,G]),n.jsx(Ae.Provider,{value:H,children:e})}function re(){const s=i.useContext(Ae);if(!s)throw new Error("useAuth must be used within an AuthProvider");return s}function je(){return i.useContext(Ae)}class Oe{constructor(e,t){this.httpService=e,this.sessionManager=t}async createFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/feature-flags/",e,{headers:t})).data}async getFeatureFlags(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const a=`/feature-flags/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(a,{headers:t});return{featureFlags:o.data,meta:o.meta}}async getFeatureFlagById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/feature-flags/${e}`,{headers:t})).data}async updateFeatureFlag(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:r})).data}async deleteFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/feature-flags/${e}`,{headers:t})}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const r=new URLSearchParams;r.append("tenantId",e),r.append("appId",t);const a=`/tenant-feature-flags${r.toString()?`?${r.toString()}`:""}`;return(await this.httpService.get(a,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,r){if(!e||!t||!r)throw new Error("Flag Key, Tenant ID and App ID are required");const a=new URLSearchParams;a.append("tenantId",t),a.append("appId",r);const o=`/tenant-feature-flags/${e}${a.toString()?`?${a.toString()}`:""}`;return(await this.httpService.get(o,{headers:{"X-Tenant-ID":t}})).data}}const Pe=i.createContext(null);function vt({config:s={},children:e}){const t=$e(),r=ue(),a=(t==null?void 0:t.baseUrl)??"",o=(t==null?void 0:t.appId)??"",l=(r==null?void 0:r.tenant)??null,[p,f]=i.useState([]),[w,u]=i.useState(!1),[x,g]=i.useState(null),[v,P]=i.useState(!1),F=i.useMemo(()=>{const h=new ee(a);return new Oe(h)},[a]),R=async()=>{if(!(l!=null&&l.id)){f([]);return}u(!0),g(null);try{const h=await F.getTenantFeatureFlags(l.id,o);f(h)}catch(h){const k=h instanceof Error?h.message:"Failed to fetch feature flags";g(k),s.onError&&s.onError(h instanceof Error?h:new Error(k))}finally{u(!1)}};i.useEffect(()=>{if(!a||!o)return;R().finally(()=>P(!0));const h=s.refreshInterval||5*60*1e3,k=setInterval(R,h);return()=>clearInterval(k)},[l==null?void 0:l.id,a,o,s.refreshInterval]);const A=i.useMemo(()=>{const h=C=>{const j=p.find(D=>D.key===C);return(j==null?void 0:j.value)===!0},k=C=>p.find(j=>j.key===C),b=C=>{const j=p.find(D=>D.key===C);return j?j.value?"enabled":"disabled":"not_found"},M=async()=>{await R()},E=!!(a&&o)&&(v||!(l!=null&&l.id));return{featureFlags:p,loading:w,error:x,isReady:E,isEnabled:h,getFlag:k,getFlagState:b,refresh:M}},[p,w,x,a,o,l==null?void 0:l.id,v]);return n.jsx(Pe.Provider,{value:A,children:e})}function qe(){const s=i.useContext(Pe);if(!s)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return s}function ze(){return i.useContext(Pe)}class _e{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscription(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscriptions/",e,{headers:t})).data}async getSubscriptionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscriptions/subscriptions/${e}`,{headers:t})).data}async updateSubscription(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:r})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:r})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`)).data}async processPayment(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:r})).data}}const Re=i.createContext(void 0);function Tt({config:s={},children:e}){const t=$e(),r=ue(),a=(t==null?void 0:t.baseUrl)??"",o=(r==null?void 0:r.tenant)??null,[l,p]=i.useState(null),[f,w]=i.useState(!1),[u,x]=i.useState(null),[g,v]=i.useState(!1),P=i.useMemo(()=>{const A=new ee(a);return new _e(A)},[a]),F=async()=>{if(!(o!=null&&o.id)){p(null);return}w(!0),x(null);try{const A=await P.getTenantSubscriptionFeatures(o.id);p(A)}catch(A){const h=A instanceof Error?A.message:"Failed to fetch subscription";x(h),s.onError&&s.onError(A instanceof Error?A:new Error(h))}finally{w(!1)}};i.useEffect(()=>{if(!a||(F().finally(()=>v(!0)),!s.refreshInterval))return;const A=s.refreshInterval||10*60*1e3,h=setInterval(F,A);return()=>clearInterval(h)},[o==null?void 0:o.id,a,s.refreshInterval]);const R=i.useMemo(()=>{const A=(l==null?void 0:l.features)||[],h=j=>{const D=A.find(c=>c.key===j);return D?D.type==="BOOLEAN"||D.type==="boolean"?D.value===!0:!!D.value:!1},k=j=>A.find(D=>D.key===j),b=(j,D)=>{const c=A.find(L=>L.key===j);return c?c.value:D},M=j=>!l||!l.isActive?!1:j.includes(l.planId),E=async()=>{await F()},C=!!a&&(g||!(o!=null&&o.id));return{subscription:l,features:A,loading:f,error:u,isReady:C,isFeatureEnabled:h,getFeature:k,getFeatureValue:b,hasAllowedPlan:M,refresh:E}},[l,f,u,a,o==null?void 0:o.id,g]);return n.jsx(Re.Provider,{value:R,children:e})}function We(){const s=i.useContext(Re);if(s===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return s}function Ve(){return i.useContext(Re)??null}var X=(s=>(s.SUPERUSER="SUPERUSER",s.TENANT_ADMIN="TENANT_ADMIN",s.USER="USER",s))(X||{});const pe={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},Me={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:X.USER},admin:{tenant:"required",auth:"required",userType:X.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},Ee=i.createContext(null);function kt({config:s={},children:e}){const t=i.useMemo(()=>{const r={...pe,...s.zoneRoots},a={...Me,...s.presets};return{zoneRoots:r,presets:a,loadingFallback:s.loadingFallback??null,accessDeniedFallback:s.accessDeniedFallback??null,onAccessDenied:s.onAccessDenied,returnToParam:s.returnToParam??"returnTo",returnToStorage:s.returnToStorage??"url"}},[s]);return n.jsx(Ee.Provider,{value:t,children:e})}function At(){const s=i.useContext(Ee);if(!s)throw new Error("useRouting must be used within a RoutingProvider");return s}function Ze(){const s=i.useContext(Ee);return s||{zoneRoots:pe,presets:Me,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"}}const Ce=()=>n.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:[n.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),n.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),n.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),n.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"})]}),Ne=({userType:s,minUserType:e,missingPermissions:t})=>n.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:[n.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),n.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&s?n.jsxs(n.Fragment,{children:[n.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",n.jsx("strong",{children:e})," access level or higher."]}),n.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",n.jsx("strong",{children:s})]})]}):n.jsxs(n.Fragment,{children:[n.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&&n.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",n.jsx("strong",{children:t.join(", ")})]})]})]}),jt=(s,e)=>{const t={[X.USER]:1,[X.TENANT_ADMIN]:2,[X.SUPERUSER]:3};return t[s]>=t[e]};function Pt({children:s,fallback:e,minUserType:t,requiredPermissions:r,requireAllPermissions:a=!1}){const{hasValidSession:o,sessionManager:l,hasPermission:p,hasAnyPermission:f,hasAllPermissions:w}=re();if(!o())return n.jsx(n.Fragment,{children:e||n.jsx(Ce,{})});const u=l.getUser();if(!u)return n.jsx(n.Fragment,{children:e||n.jsx(Ce,{})});if(t&&!jt(u.userType,t))return n.jsx(Ne,{userType:u.userType,minUserType:t});if(r&&r.length>0&&!(a?w(r):f(r))){const g=r.filter(v=>!p(v)).map(v=>typeof v=="string"?v:v.name);return n.jsx(Ne,{missingPermissions:g})}return n.jsx(n.Fragment,{children:s})}const Rt=({redirectPath:s})=>n.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:n.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[n.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),n.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),n.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),n.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})}),De=({userType:s,requiredUserType:e,missingPermissions:t})=>n.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:n.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[n.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),n.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&s?n.jsxs(n.Fragment,{children:[n.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",n.jsx("strong",{children:e})," access."]}),n.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current user type: ",n.jsx("strong",{children:s})]})]}):n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&n.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",n.jsx("strong",{children:t.join(", ")})]})]})]})}),Mt=(s,e)=>s===e;function Et({children:s,redirectTo:e="/login",requiredUserType:t,requiredPermissions:r,requireAllPermissions:a=!1,fallback:o}){const{hasValidSession:l,sessionManager:p,hasPermission:f,hasAnyPermission:w,hasAllPermissions:u}=re(),x=te.useLocation();if(i.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] ProtectedRoute is deprecated. Use AuthenticatedZone or AdminZone from ZoneRoute instead.")},[]),!l())return o?n.jsx(n.Fragment,{children:o}):n.jsxs(n.Fragment,{children:[n.jsx(Rt,{redirectPath:e}),n.jsx(te.Navigate,{to:e,state:{from:x.pathname},replace:!0})]});const g=p.getUser();if(!g)return n.jsx(te.Navigate,{to:e,state:{from:x.pathname},replace:!0});if(t&&!Mt(g.userType,t))return n.jsx(De,{userType:g.userType,requiredUserType:t});if(r&&r.length>0&&!(a?u(r):w(r))){const P=r.filter(F=>!f(F)).map(F=>typeof F=="string"?F:F.name);return n.jsx(De,{missingPermissions:P})}return n.jsx(n.Fragment,{children:s})}const It=({redirectPath:s})=>n.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:n.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[n.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),n.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),n.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),n.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function Ft({children:s,redirectTo:e="/",fallback:t}){const{tenant:r,isLoading:a,error:o}=ae(),l=te.useLocation();return i.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] TenantRoute is deprecated. Use TenantZone from ZoneRoute instead.")},[]),a||o?null:r?n.jsx(n.Fragment,{children:s}):t?n.jsx(n.Fragment,{children:t}):n.jsxs(n.Fragment,{children:[n.jsx(It,{redirectPath:e}),n.jsx(te.Navigate,{to:e,state:{from:l.pathname},replace:!0})]})}const Lt=({redirectPath:s})=>n.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:n.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[n.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),n.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),n.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),n.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function Ct({children:s,redirectTo:e="/dashboard",fallback:t}){const{tenant:r,isLoading:a,error:o}=ae(),l=te.useLocation();return i.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] LandingRoute is deprecated. Use PublicZone from ZoneRoute instead.")},[]),a||o?null:r?t?n.jsx(n.Fragment,{children:t}):n.jsxs(n.Fragment,{children:[n.jsx(Lt,{redirectPath:e}),n.jsx(te.Navigate,{to:e,state:{from:l.pathname},replace:!0})]}):n.jsx(n.Fragment,{children:s})}function Nt(s,e){return e?s?Array.isArray(e)?e.includes(s):s===e:!1:!0}function Ue(s,e){return!s||s==="optional"?"skip":s==="required"?e?"pass":"fail":s==="forbidden"?e?"fail":"pass":"skip"}function Dt(s,e){return Ue(s.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":Ue(s.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":s.userType&&e.isAuthenticated&&!Nt(e.userType,s.userType)?"wrong_user_type":s.permissions&&s.permissions.length>0&&!(s.requireAllPermissions!==!1?o=>o.every(l=>e.permissions.includes(l)):o=>o.some(l=>e.permissions.includes(l)))(s.permissions)?"missing_permissions":null}function Ut(s,e){return s.hasTenant?s.isAuthenticated?s.userType===X.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:s.isAuthenticated?s.userType===X.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function $t(s,e,t,r,a){if(!e||a!=="url")return s;const o=typeof e=="string"?e:t,l=s.includes("?")?"&":"?";return`${s}${l}${r}=${encodeURIComponent(o)}`}function Ht(s,e,t){if(!s||t==="url")return;const r=typeof s=="string"?s:e,a="zone_return_to";t==="session"?sessionStorage.setItem(a,r):t==="local"&&localStorage.setItem(a,r)}const ne=({children:s,preset:e,tenant:t,auth:r,userType:a,requiredPermissions:o,requireAllPermissions:l=!0,returnTo:p,onAccessDenied:f,redirectTo:w,loadingFallback:u,accessDeniedFallback:x})=>{const g=te.useLocation(),{isAuthenticated:v,isAuthInitializing:P,currentUser:F,userPermissions:R}=re(),{tenant:A,isTenantLoading:h}=se(),k=Ze(),b=i.useMemo(()=>{if(e)return k.presets[e]},[e,k.presets]),M=i.useMemo(()=>({tenant:t??(b==null?void 0:b.tenant),auth:r??(b==null?void 0:b.auth),userType:a??(b==null?void 0:b.userType),permissions:o??(b==null?void 0:b.requiredPermissions),requireAllPermissions:l}),[t,r,a,o,b,l]),E=i.useMemo(()=>({hasTenant:!!A,isAuthenticated:v,userType:F==null?void 0:F.userType,permissions:R,isLoading:P||h}),[A,v,F==null?void 0:F.userType,R,P,h]),C=i.useMemo(()=>E.isLoading?null:Dt(M,E),[M,E]),j=i.useMemo(()=>C?w||Ut(E,k.zoneRoots):null,[C,w,E,k.zoneRoots]),D=i.useMemo(()=>!C||!j?null:{type:C,required:{tenant:M.tenant,auth:M.auth,userType:M.userType,permissions:M.permissions},current:{hasTenant:E.hasTenant,isAuthenticated:E.isAuthenticated,userType:E.userType,permissions:E.permissions},redirectTo:j},[C,j,M,E]);if(i.useEffect(()=>{D&&(f?f(D):k.onAccessDenied&&k.onAccessDenied(D))},[D,f,k]),i.useEffect(()=>{D&&p&&Ht(p,g.pathname+g.search,k.returnToStorage)},[D,p,g.pathname,g.search,k.returnToStorage]),E.isLoading)return n.jsx(n.Fragment,{children:u??k.loadingFallback??null});if(D&&j){const c=x??k.accessDeniedFallback;if(c)return n.jsx(n.Fragment,{children:c});const L=$t(j,p,g.pathname+g.search,k.returnToParam,k.returnToStorage);return n.jsx(te.Navigate,{to:L,replace:!0})}return n.jsx(n.Fragment,{children:s})},Bt=s=>n.jsx(ne,{tenant:"required",...s}),Ot=s=>n.jsx(ne,{tenant:"forbidden",...s}),qt=s=>n.jsx(ne,{auth:"required",...s}),zt=s=>n.jsx(ne,{auth:"forbidden",...s}),_t=s=>n.jsx(ne,{auth:"required",userType:X.TENANT_ADMIN,...s}),Wt=s=>n.jsx(ne,{auth:"required",userType:X.USER,...s}),Vt=s=>n.jsx(ne,{tenant:"optional",auth:"optional",...s}),Zt=s=>n.jsx(ne,{tenant:"required",auth:"required",...s}),Gt=s=>n.jsx(ne,{tenant:"required",auth:"optional",...s}),Kt=s=>n.jsx(ne,{tenant:"required",auth:"forbidden",...s}),Jt=()=>n.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[n.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),n.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function Yt({children:s,fallback:e=n.jsx(Jt,{}),allowedPlans:t,requiredFeature:r}){const{subscription:a,hasAllowedPlan:o,isFeatureEnabled:l,loading:p}=We();return p?n.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):a?a.isActive?t&&t.length>0&&!o(t)?n.jsx(n.Fragment,{children:e}):r&&!l(r)?n.jsx(n.Fragment,{children:e}):n.jsx(n.Fragment,{children:s}):n.jsx(n.Fragment,{children:e}):n.jsx(n.Fragment,{children:e})}const Qt=({flagName:s})=>n.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:[n.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),n.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),n.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',s,'" is disabled']})]});function Xt({name:s,children:e,fallback:t}){const{isEnabled:r,loading:a}=qe();return a?n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):r(s)?n.jsx(n.Fragment,{children:e}):n.jsx(n.Fragment,{children:t||n.jsx(Qt,{flagName:s})})}const en=()=>n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[n.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),tn=()=>n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[n.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),nn={showPassword:n.jsx(en,{}),hidePassword:n.jsx(tn,{})},rn={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..."},sn={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"}};function an({copy:s={},styles:e={},icons:t={},onSuccess:r,onError:a,onForgotPassword:o,onSignupClick:l,onMagicLinkClick:p,showForgotPassword:f=!0,showSignupLink:w=!0,showMagicLinkOption:u=!0,className:x}){const[g,v]=i.useState(""),[P,F]=i.useState(""),[R,A]=i.useState(!1),[h,k]=i.useState(!1),[b,M]=i.useState(""),[E,C]=i.useState({}),{login:j}=re(),{tenant:D}=ae(),c={...rn,...s},L={...sn,...e},N={...nn,...t},d=()=>{const m={};return g.trim()||(m.username=!0),P.trim()||(m.password=!0),C(m),Object.keys(m).length===0},U=async m=>{if(m.preventDefault(),!!d()){if(!(D!=null&&D.id)){M("Tenant not found");return}k(!0),M("");try{const S=await j({username:g,password:P});r==null||r(S)}catch(S){const W=S.message||c.errorMessage;M(W),a==null||a(W)}finally{k(!1)}}},I=m=>({...L.input,...E[m]?L.inputError:{}}),y=()=>({...L.button,...h?L.buttonLoading:{},...!g||!P||h?L.buttonDisabled:{}});return n.jsxs("div",{className:x,style:L.container,children:[n.jsx("h2",{style:L.title,children:c.title}),n.jsxs("form",{onSubmit:U,style:L.form,children:[n.jsxs("div",{style:L.fieldGroup,children:[n.jsx("label",{style:L.label,children:c.usernameLabel}),n.jsx("input",{id:"username",name:"username",type:"text",value:g,onChange:m=>{v(m.target.value),E.username&&C(S=>({...S,username:!1}))},placeholder:c.usernamePlaceholder,style:I("username"),disabled:h})]}),n.jsxs("div",{style:L.fieldGroup,children:[n.jsx("label",{style:L.label,children:c.passwordLabel}),n.jsxs("div",{style:L.inputContainer,children:[n.jsx("input",{id:"password",name:"password",type:R?"text":"password",value:P,onChange:m=>{F(m.target.value),E.password&&C(S=>({...S,password:!1}))},placeholder:c.passwordPlaceholder,style:{...I("password"),paddingRight:"2.5rem"},disabled:h}),n.jsx("button",{type:"button",onClick:()=>A(!R),style:L.passwordToggle,disabled:h,"aria-label":R?"Hide password":"Show password",children:R?N.hidePassword:N.showPassword})]})]}),n.jsx("button",{type:"submit",disabled:!g||!P||h,style:y(),children:h?c.loadingText:c.submitButton}),b&&n.jsx("div",{style:L.errorText,children:b})]}),(f||w||u)&&n.jsxs("div",{style:L.linkContainer,children:[u&&n.jsxs("div",{children:[n.jsxs("span",{style:L.divider,children:[c.magicLinkText," "]}),n.jsx("a",{onClick:p,style:L.link,children:c.magicLinkLink})]}),u&&(f||w)&&n.jsx("div",{style:L.divider,children:"•"}),f&&n.jsx("a",{onClick:o,style:L.link,children:c.forgotPasswordLink}),f&&w&&n.jsx("div",{style:L.divider,children:"•"}),w&&n.jsxs("div",{children:[n.jsxs("span",{style:L.divider,children:[c.signupText," "]}),n.jsx("a",{onClick:l,style:L.link,children:c.signupLink})]})]})]})}const on={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"},ln={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},checkbox:{marginRight:"0.5rem"},checkboxContainer:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem 0"},checkboxLabel:{fontSize:"0.875rem",color:"#374151",lineHeight:"1.4"},button:{padding:"0.75rem 1rem",backgroundColor:"#10b981",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"}};function cn({copy:s={},styles:e={},signupType:t="user",onSuccess:r,onError:a,onLoginClick:o,onMagicLinkClick:l,showLoginLink:p=!0,showMagicLinkOption:f=!0,className:w}){const[u,x]=i.useState(""),[g,v]=i.useState(""),[P,F]=i.useState(""),[R,A]=i.useState(""),[h,k]=i.useState(""),[b,M]=i.useState(""),[E,C]=i.useState(""),[j,D]=i.useState(!1),[c,L]=i.useState(""),[N,d]=i.useState({}),{signup:U,signupTenantAdmin:I}=re(),{tenant:y}=ae(),m={...on,...s},S={...ln,...e},W=()=>{const T={};return u.trim()||(T.name=!0),!P.trim()&&!R.trim()&&(T.email=!0,T.phoneNumber=!0),h.trim()||(T.password=!0),b.trim()||(T.confirmPassword=!0),t==="tenant"&&!E.trim()&&(T.tenantName=!0),d(T),Object.keys(T).length===0},G=async T=>{if(T.preventDefault(),!!W()){if(h!==b){L(m.passwordMismatchError),d({confirmPassword:!0});return}if(t==="user"&&!(y!=null&&y.id)){L("Tenant not found");return}D(!0),L("");try{let V;t==="tenant"?V=await I({email:P||void 0,phoneNumber:R||void 0,name:u,password:h,tenantName:E,lastName:g||void 0}):V=await U({email:P||void 0,phoneNumber:R||void 0,name:u,password:h,tenantId:y.id,lastName:g||void 0}),r==null||r(V)}catch(V){const oe=V.message||m.errorMessage;L(oe),a==null||a(oe)}finally{D(!1)}}},H=T=>({...S.input,...N[T]?S.inputError:{}}),B=()=>({...S.button,...j?S.buttonLoading:{},...!u||!P&&!R||!h||!b||j||t==="tenant"&&!E?S.buttonDisabled:{}}),z=u&&(P||R)&&h&&b&&(t==="user"||E);return n.jsxs("div",{className:w,style:S.container,children:[n.jsx("h2",{style:S.title,children:m.title}),n.jsxs("form",{onSubmit:G,style:S.form,children:[n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.nameLabel}),n.jsx("input",{id:"name",name:"name",type:"text",value:u,onChange:T=>{x(T.target.value),N.name&&d(V=>({...V,name:!1}))},placeholder:m.namePlaceholder,style:H("name"),disabled:j})]}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.lastNameLabel}),n.jsx("input",{id:"lastName",name:"lastName",type:"text",value:g,onChange:T=>v(T.target.value),placeholder:m.lastNamePlaceholder,style:S.input,disabled:j})]}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.emailLabel}),n.jsx("input",{id:"email",name:"email",type:"email",value:P,onChange:T=>{F(T.target.value),N.email&&d(V=>({...V,email:!1,phoneNumber:!1}))},placeholder:m.emailPlaceholder,style:H("email"),disabled:j})]}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.phoneNumberLabel}),n.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:R,onChange:T=>{A(T.target.value),N.phoneNumber&&d(V=>({...V,email:!1,phoneNumber:!1}))},placeholder:m.phoneNumberPlaceholder,style:H("phoneNumber"),disabled:j})]}),n.jsx("div",{style:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"},children:"At least one contact method (email or phone) is required"}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.passwordLabel}),n.jsx("input",{id:"password",name:"password",type:"password",value:h,onChange:T=>{k(T.target.value),N.password&&d(V=>({...V,password:!1}))},placeholder:m.passwordPlaceholder,style:H("password"),disabled:j})]}),n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.confirmPasswordLabel}),n.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:b,onChange:T=>{M(T.target.value),N.confirmPassword&&d(V=>({...V,confirmPassword:!1})),c===m.passwordMismatchError&&L("")},placeholder:m.confirmPasswordPlaceholder,style:H("confirmPassword"),disabled:j})]}),t==="tenant"&&n.jsxs("div",{style:S.fieldGroup,children:[n.jsx("label",{style:S.label,children:m.tenantNameLabel}),n.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:E,onChange:T=>{C(T.target.value),N.tenantName&&d(V=>({...V,tenantName:!1}))},placeholder:m.tenantNamePlaceholder,style:H("tenantName"),disabled:j})]}),n.jsx("button",{type:"submit",disabled:!z||j,style:B(),children:j?m.loadingText:m.submitButton}),c&&n.jsx("div",{style:S.errorText,children:c})]}),(p||f)&&n.jsxs("div",{style:S.linkContainer,children:[f&&n.jsxs("div",{children:[n.jsxs("span",{style:S.divider,children:[m.magicLinkText," "]}),n.jsx("a",{onClick:l,style:S.link,children:m.magicLinkLink})]}),f&&p&&n.jsx("div",{style:S.divider,children:"•"}),p&&n.jsxs("div",{children:[n.jsxs("span",{style:S.divider,children:[m.loginText," "]}),n.jsx("a",{onClick:o,style:S.link,children:m.loginLink})]})]})]})}const dn={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...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you."},un={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1rem",color:"#333333"},description:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",marginBottom:"1.5rem",lineHeight:"1.5"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem",padding:"0.75rem",backgroundColor:"#f0fdf4",borderRadius:"6px",border:"1px solid #bbf7d0"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"}};function hn({copy:s={},styles:e={},onSuccess:t,onError:r,onLoginClick:a,onSignupClick:o,showTraditionalLinks:l=!0,className:p,verifyToken:f,frontendUrl:w}){const[u,x]=i.useState(""),[g,v]=i.useState(""),[P,F]=i.useState(""),[R,A]=i.useState(!1),[h,k]=i.useState(!1),[b,M]=i.useState(""),[E,C]=i.useState(""),[j,D]=i.useState({}),[c,L]=i.useState(!1),{sendMagicLink:N,verifyMagicLink:d}=re(),{tenant:U}=ae(),I={...dn,...s},y={...un,...e};i.useEffect(()=>{f&&m(f)},[f]);const m=async B=>{if(!U||!u){M("Missing tenant or email");return}k(!0),M("");try{const z=await d({token:B,email:u});t==null||t(z)}catch(z){const T=z.message||"Failed to verify magic link";M(T),r==null||r(T)}finally{k(!1)}},S=()=>{const B={};return u.trim()||(B.email=!0),c&&!g.trim()&&(B.name=!0),D(B),Object.keys(B).length===0},W=async B=>{if(B.preventDefault(),!!S()){if(!(U!=null&&U.id)){M("Tenant not found");return}A(!0),M(""),C("");try{const z=w||(typeof window<"u"?window.location.origin:""),T=await N({email:u,tenantId:U.id,frontendUrl:z,name:c?g:void 0,lastName:c?P:void 0});C(I.successMessage),t==null||t(T)}catch(z){const T=z.message||I.errorMessage;M(T),r==null||r(T)}finally{A(!1)}}},G=B=>({...y.input,...j[B]?y.inputError:{}}),H=()=>({...y.button,...R||h?y.buttonLoading:{},...!u||R||h?y.buttonDisabled:{}});return h?n.jsxs("div",{className:p,style:y.container,children:[n.jsx("h2",{style:y.title,children:I.verifyingText}),n.jsx("div",{style:{textAlign:"center",padding:"2rem"},children:n.jsx("div",{style:{fontSize:"1rem",color:"#6b7280"},children:"Please wait while we verify your magic link..."})})]}):n.jsxs("div",{className:p,style:y.container,children:[n.jsx("h2",{style:y.title,children:I.title}),n.jsx("p",{style:y.description,children:I.description}),n.jsxs("form",{onSubmit:W,style:y.form,children:[n.jsxs("div",{style:y.fieldGroup,children:[n.jsx("label",{style:y.label,children:I.emailLabel}),n.jsx("input",{id:"email",name:"email",type:"email",value:u,onChange:B=>{x(B.target.value),j.email&&D(z=>({...z,email:!1}))},placeholder:I.emailPlaceholder,style:G("email"),disabled:R||h})]}),!c&&n.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:n.jsx("button",{type:"button",onClick:()=>L(!0),style:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"New user? Add your name"})}),c&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:y.fieldGroup,children:[n.jsx("label",{style:y.label,children:I.nameLabel}),n.jsx("input",{id:"name",name:"name",type:"text",value:g,onChange:B=>{v(B.target.value),j.name&&D(z=>({...z,name:!1}))},placeholder:I.namePlaceholder,style:G("name"),disabled:R||h})]}),n.jsxs("div",{style:y.fieldGroup,children:[n.jsx("label",{style:y.label,children:I.lastNameLabel}),n.jsx("input",{id:"lastName",name:"lastName",type:"text",value:P,onChange:B=>F(B.target.value),placeholder:I.lastNamePlaceholder,style:y.input,disabled:R||h})]}),n.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:n.jsx("button",{type:"button",onClick:()=>{L(!1),v(""),F("")},style:{background:"none",border:"none",color:"#6b7280",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"Existing user? Hide name fields"})})]}),n.jsx("button",{type:"submit",disabled:!u||R||h,style:H(),children:R?I.loadingText:I.submitButton}),b&&n.jsx("div",{style:y.errorText,children:b}),E&&n.jsx("div",{style:y.successText,children:E})]}),l&&n.jsxs("div",{style:y.linkContainer,children:[n.jsxs("div",{children:[n.jsxs("span",{style:y.divider,children:[I.loginText," "]}),n.jsx("a",{onClick:a,style:y.link,children:I.loginLink})]}),n.jsx("div",{style:y.divider,children:"•"}),n.jsxs("div",{children:[n.jsxs("span",{style:y.divider,children:[I.signupText," "]}),n.jsx("a",{onClick:o,style:y.link,children:I.signupLink})]})]})]})}const gn={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"},Ge={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"}},pn=()=>n.jsx("div",{style:Ge.spinner}),fn=()=>n.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:[n.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),n.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),mn=()=>n.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:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),n.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),yn={loading:n.jsx(pn,{}),success:n.jsx(fn,{}),error:n.jsx(mn,{})};function wn({copy:s={},styles:e={},icons:t={},onSuccess:r,onError:a,onRetry:o,onBackToLogin:l,className:p,token:f,email:w,appId:u,tenantSlug:x,autoRedirectDelay:g=3e3}){const[v,P]=i.useState("verifying"),[F,R]=i.useState(""),{verifyMagicLink:A}=re(),h={...gn,...s},k={...Ge,...e},b={...yn,...t},M=()=>{if(typeof window>"u")return{};const c=new URLSearchParams(window.location.search);return{token:f||c.get("token")||"",email:w||c.get("email")||"",appId:u||c.get("appId")||"",tenantSlug:x||c.get("tenantSlug")||void 0}},E=async()=>{P("verifying"),R("");try{const c=M();if(!c.token||!c.email)throw new Error("Missing required parameters: token or email");const L=await A({token:c.token,email:c.email,tenantSlug:c.tenantSlug});P("success"),r==null||r(L),g>0&&setTimeout(()=>{P("redirecting")},g)}catch(c){const L=c.message||h.errorMessage;R(L),P("error"),a==null||a(L)}},C=()=>{o==null||o(),E()},j=()=>{l==null||l()};i.useEffect(()=>{E()},[]);const D=()=>{switch(v){case"verifying":return n.jsxs("div",{style:k.message,children:[b.loading,h.verifyingMessage]});case"success":return n.jsxs(n.Fragment,{children:[b.success,n.jsx("div",{style:k.successMessage,children:h.successMessage})]});case"redirecting":return n.jsxs(n.Fragment,{children:[b.loading,n.jsx("div",{style:k.message,children:h.redirectingMessage})]});case"error":return n.jsxs(n.Fragment,{children:[b.error,n.jsx("div",{style:k.errorMessage,children:F||h.errorMessage}),n.jsxs("div",{style:k.buttonContainer,children:[n.jsx("button",{onClick:C,style:k.retryButton,onMouseOver:c=>{c.currentTarget.style.backgroundColor="#2563eb"},onMouseOut:c=>{c.currentTarget.style.backgroundColor="#3b82f6"},children:h.retryButton}),n.jsx("button",{onClick:j,style:k.backButton,onMouseOver:c=>{c.currentTarget.style.backgroundColor="#e5e7eb"},onMouseOut:c=>{c.currentTarget.style.backgroundColor="#f3f4f6"},children:h.backToLoginButton})]})]});default:return null}};return n.jsxs("div",{style:k.container,className:p,children:[n.jsx("style",{children:`
2
2
  @keyframes spin {
3
3
  0% { transform: rotate(0deg); }
4
4
  100% { transform: rotate(360deg); }
5
5
  }
6
- `}),n.jsx("h1",{style:k.title,children:h.title}),D()]})}const xn={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"},bn={container:{maxWidth:"400px",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"0.5rem",color:"#333333"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#f59e0b",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"}};function Sn({copy:s={},styles:e={},mode:t="request",token:r="",onSuccess:o,onError:a,onBackToLogin:l,onModeChange:p,className:f}){const[w,u]=i.useState(""),[x,g]=i.useState(r),[v,P]=i.useState(""),[F,R]=i.useState(""),[A,h]=i.useState(!1),[k,b]=i.useState(""),[M,E]=i.useState(""),[C,j]=i.useState({}),{requestPasswordReset:D,confirmPasswordReset:c}=re(),{tenant:L}=oe(),N={...xn,...s},d={...bn,...e},U=()=>{const H={};return w.trim()||(H.email=!0),j(H),Object.keys(H).length===0},I=()=>{const H={};return x.trim()||(H.token=!0),v.trim()||(H.newPassword=!0),F.trim()||(H.confirmPassword=!0),j(H),Object.keys(H).length===0},y=async H=>{if(H.preventDefault(),!!U()){if(!(L!=null&&L.id)){b("Tenant not found");return}h(!0),b(""),E("");try{await D({email:w,tenantId:L.id}),E(N.successMessage),o==null||o()}catch(B){const z=B.message||N.errorMessage;b(z),a==null||a(z)}finally{h(!1)}}},m=async H=>{if(H.preventDefault(),!!I()){if(v!==F){b(N.passwordMismatchError),j({confirmPassword:!0});return}h(!0),b(""),E("");try{await c({token:x,newPassword:v}),E(N.resetSuccessMessage),o==null||o()}catch(B){const z=B.message||N.errorMessage;b(z),a==null||a(z)}finally{h(!1)}}},S=H=>({...d.input,...C[H]?d.inputError:{}}),W=()=>({...d.button,...A?d.buttonLoading:{}});if(t==="reset"){const H=x&&v&&F;return n.jsxs("div",{className:f,style:d.container,children:[n.jsx("h2",{style:d.title,children:N.resetTitle}),n.jsx("p",{style:d.subtitle,children:N.resetSubtitle}),n.jsxs("form",{onSubmit:m,style:d.form,children:[n.jsxs("div",{style:d.fieldGroup,children:[n.jsx("label",{style:d.label,children:N.tokenLabel}),n.jsx("input",{type:"text",value:x,onChange:B=>{g(B.target.value),C.token&&j(z=>({...z,token:!1}))},placeholder:N.tokenPlaceholder,style:S("token"),disabled:A})]}),n.jsxs("div",{style:d.fieldGroup,children:[n.jsx("label",{style:d.label,children:N.newPasswordLabel}),n.jsx("input",{type:"password",value:v,onChange:B=>{P(B.target.value),C.newPassword&&j(z=>({...z,newPassword:!1}))},placeholder:N.newPasswordPlaceholder,style:S("newPassword"),disabled:A})]}),n.jsxs("div",{style:d.fieldGroup,children:[n.jsx("label",{style:d.label,children:N.confirmPasswordLabel}),n.jsx("input",{type:"password",value:F,onChange:B=>{R(B.target.value),C.confirmPassword&&j(z=>({...z,confirmPassword:!1})),k===N.passwordMismatchError&&b("")},placeholder:N.confirmPasswordPlaceholder,style:S("confirmPassword"),disabled:A})]}),n.jsx("button",{type:"submit",disabled:!H||A,style:{...W(),...!H||A?d.buttonDisabled:{}},children:A?N.resetLoadingText:N.resetSubmitButton}),k&&n.jsx("div",{style:d.errorText,children:k}),M&&n.jsx("div",{style:d.successText,children:M})]}),n.jsxs("div",{style:d.linkContainer,children:[n.jsx("a",{onClick:l,style:d.link,children:N.backToLoginLink}),p&&n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),n.jsx("a",{onClick:()=>p("request"),style:d.link,children:"Request New Link"})]})]})]})}const G=w;return n.jsxs("div",{className:f,style:d.container,children:[n.jsx("h2",{style:d.title,children:N.title}),n.jsx("p",{style:d.subtitle,children:N.subtitle}),n.jsxs("form",{onSubmit:y,style:d.form,children:[n.jsxs("div",{style:d.fieldGroup,children:[n.jsx("label",{style:d.label,children:N.emailLabel}),n.jsx("input",{type:"email",value:w,onChange:H=>{u(H.target.value),C.email&&j(B=>({...B,email:!1}))},placeholder:N.emailPlaceholder,style:S("email"),disabled:A})]}),n.jsx("button",{type:"submit",disabled:!G||A,style:{...W(),...!G||A?d.buttonDisabled:{}},children:A?N.loadingText:N.submitButton}),k&&n.jsx("div",{style:d.errorText,children:k}),M&&n.jsx("div",{style:d.successText,children:M})]}),n.jsxs("div",{style:d.linkContainer,children:[n.jsx("a",{onClick:l,style:d.link,children:N.backToLoginLink}),p&&n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),n.jsx("a",{onClick:()=>p("reset"),style:d.link,children:"I have a token"})]})]})]})}const vn=()=>n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:n.jsx("div",{children:"Loading..."})}),Tn=({error:s,retry:e})=>n.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[n.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Error"}),n.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:s.message||"Unable to load application"}),n.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function kn({children:s,loadingFallback:e,errorFallback:t,requireTenant:r=!0}){const{isAppLoading:o,appError:a,retryApp:l}=ce(),p=ue(),f=je(),w=ze(),u=Ve(),x=(p==null?void 0:p.isTenantLoading)??!1,g=(p==null?void 0:p.tenantError)??null,v=(p==null?void 0:p.tenantSlug)??null,P=(p==null?void 0:p.retryTenant)??(()=>{}),F=(f==null?void 0:f.isAuthReady)??!0,R=(w==null?void 0:w.isReady)??!0,A=(u==null?void 0:u.isReady)??!0,h=r&&p&&v,E=o||h&&x||f&&!F||w&&!R||u&&!A,C=a||(h?g:null),j=()=>{a&&l(),g&&p&&P()};if(E)return n.jsx(n.Fragment,{children:e||n.jsx(vn,{})});if(C){const D=typeof t=="function"?t(C,j):t||n.jsx(Tn,{error:C,retry:j});return n.jsx(n.Fragment,{children:D})}return n.jsx(n.Fragment,{children:s})}function An(s=!0){const{isAppLoading:e,appError:t,retryApp:r,appInfo:o}=ce(),a=ue(),l=je(),p=ze(),f=Ve(),w=(a==null?void 0:a.isTenantLoading)??!1,u=(a==null?void 0:a.tenantError)??null,x=(a==null?void 0:a.tenant)??null,g=(a==null?void 0:a.tenantSlug)??null,v=(a==null?void 0:a.retryTenant)??(()=>{}),P=(l==null?void 0:l.isAuthReady)??!0,F=(p==null?void 0:p.isReady)??!0,R=(f==null?void 0:f.isReady)??!0,A=s&&a&&g,M=e||A&&w||l&&!P||p&&!F||f&&!R,E=t||(A?u:null);return{isLoading:M,error:E,isReady:!M&&!E&&o!==null&&(!A||x!==null),retry:()=>{t&&r(),u&&a&&v()},app:{isLoading:e,error:t,data:o},tenant:a?{isLoading:w,error:u,data:x}:null,auth:l?{isReady:P}:null,featureFlags:p?{isReady:F}:null,subscription:f?{isReady:R}:null}}function jn({tenants:s,currentTenantId:e,onSelect:t,className:r="",dropdownClassName:o="",itemClassName:a="",renderItem:l,placeholder:p="Select tenant",disabled:f=!1,showCurrentTenant:w=!0}){var k;const u=je(),[x,g]=i.useState(!1),v=i.useRef(null),P=s??(u==null?void 0:u.userTenants)??[],F=e??((k=u==null?void 0:u.currentUser)==null?void 0:k.tenantId)??null,R=async b=>{g(!1),t?t(b):u!=null&&u.switchToTenant&&await u.switchToTenant(b)};i.useEffect(()=>{const b=M=>{v.current&&!v.current.contains(M.target)&&g(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const A=P.find(b=>b.id===F);if(P.length===0)return null;if(P.length===1&&w)return n.jsx("div",{className:r,children:n.jsx("span",{children:P[0].name})});const h=(b,M)=>n.jsxs("span",{style:{fontWeight:M?"bold":"normal"},children:[b.name,b.role&&n.jsxs("span",{style:{opacity:.7,marginLeft:8},children:["(",b.role,")"]})]});return n.jsxs("div",{ref:v,className:r,style:{position:"relative"},children:[n.jsxs("button",{type:"button",onClick:()=>!f&&g(!x),disabled:f,style:{cursor:f?"not-allowed":"pointer",opacity:f?.6:1},children:[A?A.name:p,n.jsx("span",{style:{marginLeft:8},children:x?"▲":"▼"})]}),x&&n.jsx("div",{className:o,style:{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"},children:P.map(b=>{const M=b.id===F;return n.jsx("div",{className:a,onClick:()=>R(b.id),style:{padding:"8px 12px",cursor:"pointer",backgroundColor:M?"#f0f0f0":"transparent"},onMouseEnter:E=>{M||(E.target.style.backgroundColor="#f5f5f5")},onMouseLeave:E=>{M||(E.target.style.backgroundColor="transparent")},children:l?l(b,M):h(b,M)},b.id)})})]})}class Pn{constructor(e,t){this.httpService=e,this.sessionManager=t}async createPermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/permissions/",e,{headers:t})).data}async getPermissions(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const o=`/permissions/${r.toString()?`?${r.toString()}`:""}`,a=await this.httpService.get(o,{headers:t});return{permissions:a.data,meta:a.meta}}async getPermissionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/permissions/${e}`,{headers:t})).data}async updatePermission(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:r})).data}async deletePermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/permissions/${e}`,{headers:t})}async getAppPermissions(e,t){const r=new URLSearchParams;t!=null&&t.page&&r.append("page",t.page.toString()),t!=null&&t.limit&&r.append("limit",t.limit.toString()),t!=null&&t.sortBy&&r.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&r.append("sortOrder",t.sortOrder);const o=`/permissions/apps/${e}${r.toString()?`?${r.toString()}`:""}`,a=await this.httpService.get(o);return{permissions:a.data,meta:a.meta}}}class Rn{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscription-plans/",e,{headers:t})).data}async getSubscriptionPlans(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder),e!=null&&e.appId&&r.append("appId",e.appId);const o=`/subscription-plans/${r.toString()?`?${r.toString()}`:""}`,a=await this.httpService.get(o,{headers:t});return{plans:a.data,meta:a.meta}}async getSubscriptionPlanById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscription-plans/${e}`,{headers:t})).data}async updateSubscriptionPlan(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:r})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class Mn{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class En{static toDate(e){return new Date(e)}static toISOString(e){return e.toISOString()}static transformPaginationMeta(e){return{total:e.total||0,page:e.page||1,limit:e.limit||100,totalPages:e.totalPages||1,hasNext:e.hasNext||!1,hasPrev:e.hasPrev||!1}}static transformUser(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.lastName?`${e.name} ${e.lastName}`:e.name,isActiveUser:e.isActive}}static transformRole(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),permissionCount:((t=e.permissions)==null?void 0:t.length)||0}}static transformTenant(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.name,hasCustomDomain:!!e.domain}}static transformSubscription(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),startDate:this.toDate(e.startDate),endDate:e.endDate?this.toDate(e.endDate):null,isActive:e.status==="ACTIVE",isExpired:e.endDate?new Date(e.endDate)<new Date:!1}}static transformApp(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isAdminLevel:e.securityLevel==="ADMIN",hasDefaultPlan:!!e.defaultSubscriptionPlanId}}static transformFeatureFlag(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isEnabled:e.isActive}}static transformPermission(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),fullName:`${e.resource}:${e.action}`,isSystemLevel:!e.appId}}static transformSubscriptionPlan(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayPrice:`${e.currency} ${e.price}`,isMonthly:e.billingCycle==="MONTHLY",featureCount:((t=e.features)==null?void 0:t.length)||0}}static transformError(e){var t;return{code:((t=e.error)==null?void 0:t.code)||"UNKNOWN_ERROR",message:e.message||"An unexpected error occurred",type:e.type||"SYSTEM",isAuthError:e.type==="AUTH",isValidationError:e.type==="VALIDATION"}}static transformQueryParams(e){const t=new URLSearchParams;return Object.entries(e).forEach(([r,o])=>{o!=null&&o!==""&&t.append(r,String(o))}),t}}const Ke="returnTo",xe="zone_return_to",be="zone_return_to";function In(s={}){const{zoneRoots:e={},returnToParam:t=Ke,returnToStorage:r="url"}=s,o=te.useNavigate(),[a,l]=te.useSearchParams(),{isAuthenticated:p,currentUser:f}=re(),{tenant:w}=se(),u=i.useMemo(()=>({...pe,...e}),[e]),x=!!w,g=f==null?void 0:f.userType,v=i.useMemo(()=>{switch(r){case"url":return a.get(t);case"session":return sessionStorage.getItem(xe);case"local":return localStorage.getItem(be);default:return null}},[r,a,t]),P=i.useCallback(()=>{switch(r){case"url":{const h=new URLSearchParams(a);h.delete(t),l(h,{replace:!0});break}case"session":sessionStorage.removeItem(xe);break;case"local":localStorage.removeItem(be);break}},[r,a,t,l]),F=i.useCallback(h=>{switch(r){case"url":{const k=new URLSearchParams(a);k.set(t,h),l(k,{replace:!0});break}case"session":sessionStorage.setItem(xe,h);break;case"local":localStorage.setItem(be,h);break}},[r,a,t,l]),R=i.useCallback(h=>{const k=u[h]||u.default;o(k)},[o,u]),A=i.useCallback(()=>x?p?g===X.TENANT_ADMIN?u.tenantAdmin:u.tenantUser:u.tenantGuest:p?g===X.TENANT_ADMIN?u.publicAdmin:u.publicUser:u.publicGuest,[x,p,g,u]);return{returnToUrl:v,clearReturnTo:P,setReturnTo:F,navigateToZone:R,getSmartRedirect:A}}function Fn(s,e,t=Ke,r="url"){if(!e||r!=="url")return s;const o=new URL(s,window.location.origin);return o.searchParams.set(t,e),o.pathname+o.search}exports.AdminZone=_t;exports.ApiMappers=En;exports.AppApiService=Se;exports.AppLoader=kn;exports.AppProvider=ct;exports.AuthApiService=He;exports.AuthProvider=St;exports.AuthenticatedZone=qt;exports.DEFAULT_ZONE_PRESETS=Me;exports.DEFAULT_ZONE_ROOTS=pe;exports.FeatureFlag=Xt;exports.FeatureFlagApiService=Oe;exports.FeatureFlagProvider=vt;exports.GuestZone=zt;exports.HealthApiService=Mn;exports.HttpService=ee;exports.LandingRoute=Ct;exports.LoginForm=on;exports.MagicLinkForm=hn;exports.MagicLinkVerify=wn;exports.OpenZone=Vt;exports.PasswordRecoveryForm=Sn;exports.PermissionApiService=Pn;exports.Protected=Pt;exports.ProtectedRoute=Et;exports.PublicZone=Ot;exports.RoleApiService=ve;exports.RoutingProvider=kt;exports.SessionManager=ge;exports.SignupForm=cn;exports.SubscriptionApiService=_e;exports.SubscriptionGuard=Yt;exports.SubscriptionPlanApiService=Rn;exports.SubscriptionProvider=Tt;exports.TenantApiService=le;exports.TenantAuthenticatedZone=Zt;exports.TenantGuestZone=Kt;exports.TenantOpenZone=Gt;exports.TenantProvider=wt;exports.TenantRoute=Ft;exports.TenantSelector=jn;exports.TenantZone=Bt;exports.UserApiService=Be;exports.UserType=X;exports.UserZone=Wt;exports.ZoneRoute=ne;exports.buildRedirectUrl=Fn;exports.useApi=dt;exports.useApp=ce;exports.useAppLoaderState=An;exports.useAuth=re;exports.useFeatureFlags=qe;exports.useRouting=At;exports.useRoutingOptional=Ze;exports.useSettings=bt;exports.useSubscription=We;exports.useTenant=se;exports.useTenantInfo=oe;exports.useTenantOptional=ue;exports.useTenantSettings=xt;exports.useZoneNavigation=In;
6
+ `}),n.jsx("h1",{style:k.title,children:h.title}),D()]})}const xn={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"},bn={container:{maxWidth:"400px",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"0.5rem",color:"#333333"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#f59e0b",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"}};function Sn({copy:s={},styles:e={},mode:t="request",token:r="",onSuccess:a,onError:o,onBackToLogin:l,onModeChange:p,className:f}){const[w,u]=i.useState(""),[x,g]=i.useState(r),[v,P]=i.useState(""),[F,R]=i.useState(""),[A,h]=i.useState(!1),[k,b]=i.useState(""),[M,E]=i.useState(""),[C,j]=i.useState({}),{requestPasswordReset:D,confirmPasswordReset:c}=re(),{tenant:L}=ae(),N={...xn,...s},d={...bn,...e},U=()=>{const H={};return w.trim()||(H.email=!0),j(H),Object.keys(H).length===0},I=()=>{const H={};return x.trim()||(H.token=!0),v.trim()||(H.newPassword=!0),F.trim()||(H.confirmPassword=!0),j(H),Object.keys(H).length===0},y=async H=>{if(H.preventDefault(),!!U()){if(!(L!=null&&L.id)){b("Tenant not found");return}h(!0),b(""),E("");try{await D({email:w,tenantId:L.id}),E(N.successMessage),a==null||a()}catch(B){const z=B.message||N.errorMessage;b(z),o==null||o(z)}finally{h(!1)}}},m=async H=>{if(H.preventDefault(),!!I()){if(v!==F){b(N.passwordMismatchError),j({confirmPassword:!0});return}h(!0),b(""),E("");try{await c({token:x,newPassword:v}),E(N.resetSuccessMessage),a==null||a()}catch(B){const z=B.message||N.errorMessage;b(z),o==null||o(z)}finally{h(!1)}}},S=H=>({...d.input,...C[H]?d.inputError:{}}),W=()=>({...d.button,...A?d.buttonLoading:{}});if(t==="reset"){const H=x&&v&&F;return n.jsxs("div",{className:f,style:d.container,children:[n.jsx("h2",{style:d.title,children:N.resetTitle}),n.jsx("p",{style:d.subtitle,children:N.resetSubtitle}),n.jsxs("form",{onSubmit:m,style:d.form,children:[n.jsxs("div",{style:d.fieldGroup,children:[n.jsx("label",{style:d.label,children:N.tokenLabel}),n.jsx("input",{type:"text",value:x,onChange:B=>{g(B.target.value),C.token&&j(z=>({...z,token:!1}))},placeholder:N.tokenPlaceholder,style:S("token"),disabled:A})]}),n.jsxs("div",{style:d.fieldGroup,children:[n.jsx("label",{style:d.label,children:N.newPasswordLabel}),n.jsx("input",{type:"password",value:v,onChange:B=>{P(B.target.value),C.newPassword&&j(z=>({...z,newPassword:!1}))},placeholder:N.newPasswordPlaceholder,style:S("newPassword"),disabled:A})]}),n.jsxs("div",{style:d.fieldGroup,children:[n.jsx("label",{style:d.label,children:N.confirmPasswordLabel}),n.jsx("input",{type:"password",value:F,onChange:B=>{R(B.target.value),C.confirmPassword&&j(z=>({...z,confirmPassword:!1})),k===N.passwordMismatchError&&b("")},placeholder:N.confirmPasswordPlaceholder,style:S("confirmPassword"),disabled:A})]}),n.jsx("button",{type:"submit",disabled:!H||A,style:{...W(),...!H||A?d.buttonDisabled:{}},children:A?N.resetLoadingText:N.resetSubmitButton}),k&&n.jsx("div",{style:d.errorText,children:k}),M&&n.jsx("div",{style:d.successText,children:M})]}),n.jsxs("div",{style:d.linkContainer,children:[n.jsx("a",{onClick:l,style:d.link,children:N.backToLoginLink}),p&&n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),n.jsx("a",{onClick:()=>p("request"),style:d.link,children:"Request New Link"})]})]})]})}const G=w;return n.jsxs("div",{className:f,style:d.container,children:[n.jsx("h2",{style:d.title,children:N.title}),n.jsx("p",{style:d.subtitle,children:N.subtitle}),n.jsxs("form",{onSubmit:y,style:d.form,children:[n.jsxs("div",{style:d.fieldGroup,children:[n.jsx("label",{style:d.label,children:N.emailLabel}),n.jsx("input",{type:"email",value:w,onChange:H=>{u(H.target.value),C.email&&j(B=>({...B,email:!1}))},placeholder:N.emailPlaceholder,style:S("email"),disabled:A})]}),n.jsx("button",{type:"submit",disabled:!G||A,style:{...W(),...!G||A?d.buttonDisabled:{}},children:A?N.loadingText:N.submitButton}),k&&n.jsx("div",{style:d.errorText,children:k}),M&&n.jsx("div",{style:d.successText,children:M})]}),n.jsxs("div",{style:d.linkContainer,children:[n.jsx("a",{onClick:l,style:d.link,children:N.backToLoginLink}),p&&n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),n.jsx("a",{onClick:()=>p("reset"),style:d.link,children:"I have a token"})]})]})]})}const vn=()=>n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:n.jsx("div",{children:"Loading..."})}),Tn=({error:s,retry:e})=>n.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[n.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Error"}),n.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:s.message||"Unable to load application"}),n.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function kn({children:s,loadingFallback:e,errorFallback:t,requireTenant:r=!0}){const{isAppLoading:a,appError:o,retryApp:l}=ce(),p=ue(),f=je(),w=ze(),u=Ve(),x=(p==null?void 0:p.isTenantLoading)??!1,g=(p==null?void 0:p.tenantError)??null,v=(p==null?void 0:p.tenantSlug)??null,P=(p==null?void 0:p.retryTenant)??(()=>{}),F=(f==null?void 0:f.isAuthReady)??!0,R=(w==null?void 0:w.isReady)??!0,A=(u==null?void 0:u.isReady)??!0,h=r&&p&&v,E=a||h&&x||f&&!F||w&&!R||u&&!A,C=o||(h?g:null),j=()=>{o&&l(),g&&p&&P()};if(E)return n.jsx(n.Fragment,{children:e||n.jsx(vn,{})});if(C){const D=typeof t=="function"?t(C,j):t||n.jsx(Tn,{error:C,retry:j});return n.jsx(n.Fragment,{children:D})}return n.jsx(n.Fragment,{children:s})}function An(s=!0){const{isAppLoading:e,appError:t,retryApp:r,appInfo:a}=ce(),o=ue(),l=je(),p=ze(),f=Ve(),w=(o==null?void 0:o.isTenantLoading)??!1,u=(o==null?void 0:o.tenantError)??null,x=(o==null?void 0:o.tenant)??null,g=(o==null?void 0:o.tenantSlug)??null,v=(o==null?void 0:o.retryTenant)??(()=>{}),P=(l==null?void 0:l.isAuthReady)??!0,F=(p==null?void 0:p.isReady)??!0,R=(f==null?void 0:f.isReady)??!0,A=s&&o&&g,M=e||A&&w||l&&!P||p&&!F||f&&!R,E=t||(A?u:null);return{isLoading:M,error:E,isReady:!M&&!E&&a!==null&&(!A||x!==null),retry:()=>{t&&r(),u&&o&&v()},app:{isLoading:e,error:t,data:a},tenant:o?{isLoading:w,error:u,data:x}:null,auth:l?{isReady:P}:null,featureFlags:p?{isReady:F}:null,subscription:f?{isReady:R}:null}}function jn({tenants:s,currentTenantId:e,onSelect:t,className:r="",dropdownClassName:a="",itemClassName:o="",renderItem:l,placeholder:p="Select tenant",disabled:f=!1,showCurrentTenant:w=!0}){var k;const u=je(),[x,g]=i.useState(!1),v=i.useRef(null),P=s??(u==null?void 0:u.userTenants)??[],F=e??((k=u==null?void 0:u.currentUser)==null?void 0:k.tenantId)??null,R=async b=>{g(!1),t?t(b):u!=null&&u.switchToTenant&&await u.switchToTenant(b)};i.useEffect(()=>{const b=M=>{v.current&&!v.current.contains(M.target)&&g(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const A=P.find(b=>b.id===F);if(P.length===0)return null;if(P.length===1&&w)return n.jsx("div",{className:r,children:n.jsx("span",{children:P[0].name})});const h=(b,M)=>n.jsxs("span",{style:{fontWeight:M?"bold":"normal"},children:[b.name,b.role&&n.jsxs("span",{style:{opacity:.7,marginLeft:8},children:["(",b.role,")"]})]});return n.jsxs("div",{ref:v,className:r,style:{position:"relative"},children:[n.jsxs("button",{type:"button",onClick:()=>!f&&g(!x),disabled:f,style:{cursor:f?"not-allowed":"pointer",opacity:f?.6:1},children:[A?A.name:p,n.jsx("span",{style:{marginLeft:8},children:x?"▲":"▼"})]}),x&&n.jsx("div",{className:a,style:{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"},children:P.map(b=>{const M=b.id===F;return n.jsx("div",{className:o,onClick:()=>R(b.id),style:{padding:"8px 12px",cursor:"pointer",backgroundColor:M?"#f0f0f0":"transparent"},onMouseEnter:E=>{M||(E.target.style.backgroundColor="#f5f5f5")},onMouseLeave:E=>{M||(E.target.style.backgroundColor="transparent")},children:l?l(b,M):h(b,M)},b.id)})})]})}class Pn{constructor(e,t){this.httpService=e,this.sessionManager=t}async createPermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/permissions/",e,{headers:t})).data}async getPermissions(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder);const a=`/permissions/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(a,{headers:t});return{permissions:o.data,meta:o.meta}}async getPermissionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/permissions/${e}`,{headers:t})).data}async updatePermission(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:r})).data}async deletePermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/permissions/${e}`,{headers:t})}async getAppPermissions(e,t){const r=new URLSearchParams;t!=null&&t.page&&r.append("page",t.page.toString()),t!=null&&t.limit&&r.append("limit",t.limit.toString()),t!=null&&t.sortBy&&r.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&r.append("sortOrder",t.sortOrder);const a=`/permissions/apps/${e}${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(a);return{permissions:o.data,meta:o.meta}}}class Rn{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscription-plans/",e,{headers:t})).data}async getSubscriptionPlans(e){const t=await this.sessionManager.getAuthHeaders(),r=new URLSearchParams;e!=null&&e.page&&r.append("page",e.page.toString()),e!=null&&e.limit&&r.append("limit",e.limit.toString()),e!=null&&e.sortBy&&r.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&r.append("sortOrder",e.sortOrder),e!=null&&e.appId&&r.append("appId",e.appId);const a=`/subscription-plans/${r.toString()?`?${r.toString()}`:""}`,o=await this.httpService.get(a,{headers:t});return{plans:o.data,meta:o.meta}}async getSubscriptionPlanById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscription-plans/${e}`,{headers:t})).data}async updateSubscriptionPlan(e,t){const r=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:r})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class Mn{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class En{static toDate(e){return new Date(e)}static toISOString(e){return e.toISOString()}static transformPaginationMeta(e){return{total:e.total||0,page:e.page||1,limit:e.limit||100,totalPages:e.totalPages||1,hasNext:e.hasNext||!1,hasPrev:e.hasPrev||!1}}static transformUser(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.lastName?`${e.name} ${e.lastName}`:e.name,isActiveUser:e.isActive}}static transformRole(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),permissionCount:((t=e.permissions)==null?void 0:t.length)||0}}static transformTenant(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.name,hasCustomDomain:!!e.domain}}static transformSubscription(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),startDate:this.toDate(e.startDate),endDate:e.endDate?this.toDate(e.endDate):null,isActive:e.status==="ACTIVE",isExpired:e.endDate?new Date(e.endDate)<new Date:!1}}static transformApp(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isAdminLevel:e.securityLevel==="ADMIN",hasDefaultPlan:!!e.defaultSubscriptionPlanId}}static transformFeatureFlag(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isEnabled:e.isActive}}static transformPermission(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),fullName:`${e.resource}:${e.action}`,isSystemLevel:!e.appId}}static transformSubscriptionPlan(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayPrice:`${e.currency} ${e.price}`,isMonthly:e.billingCycle==="MONTHLY",featureCount:((t=e.features)==null?void 0:t.length)||0}}static transformError(e){var t;return{code:((t=e.error)==null?void 0:t.code)||"UNKNOWN_ERROR",message:e.message||"An unexpected error occurred",type:e.type||"SYSTEM",isAuthError:e.type==="AUTH",isValidationError:e.type==="VALIDATION"}}static transformQueryParams(e){const t=new URLSearchParams;return Object.entries(e).forEach(([r,a])=>{a!=null&&a!==""&&t.append(r,String(a))}),t}}const Ke="returnTo",xe="zone_return_to",be="zone_return_to";function In(s={}){const{zoneRoots:e={},returnToParam:t=Ke,returnToStorage:r="url"}=s,a=te.useNavigate(),[o,l]=te.useSearchParams(),{isAuthenticated:p,currentUser:f}=re(),{tenant:w}=se(),u=i.useMemo(()=>({...pe,...e}),[e]),x=!!w,g=f==null?void 0:f.userType,v=i.useMemo(()=>{switch(r){case"url":return o.get(t);case"session":return sessionStorage.getItem(xe);case"local":return localStorage.getItem(be);default:return null}},[r,o,t]),P=i.useCallback(()=>{switch(r){case"url":{const h=new URLSearchParams(o);h.delete(t),l(h,{replace:!0});break}case"session":sessionStorage.removeItem(xe);break;case"local":localStorage.removeItem(be);break}},[r,o,t,l]),F=i.useCallback(h=>{switch(r){case"url":{const k=new URLSearchParams(o);k.set(t,h),l(k,{replace:!0});break}case"session":sessionStorage.setItem(xe,h);break;case"local":localStorage.setItem(be,h);break}},[r,o,t,l]),R=i.useCallback(h=>{const k=u[h]||u.default;a(k)},[a,u]),A=i.useCallback(()=>x?p?g===X.TENANT_ADMIN?u.tenantAdmin:u.tenantUser:u.tenantGuest:p?g===X.TENANT_ADMIN?u.publicAdmin:u.publicUser:u.publicGuest,[x,p,g,u]);return{returnToUrl:v,clearReturnTo:P,setReturnTo:F,navigateToZone:R,getSmartRedirect:A}}function Fn(s,e,t=Ke,r="url"){if(!e||r!=="url")return s;const a=new URL(s,window.location.origin);return a.searchParams.set(t,e),a.pathname+a.search}exports.AdminZone=_t;exports.ApiMappers=En;exports.AppApiService=Se;exports.AppLoader=kn;exports.AppProvider=ct;exports.AuthApiService=He;exports.AuthProvider=St;exports.AuthenticatedZone=qt;exports.DEFAULT_ZONE_PRESETS=Me;exports.DEFAULT_ZONE_ROOTS=pe;exports.FeatureFlag=Xt;exports.FeatureFlagApiService=Oe;exports.FeatureFlagProvider=vt;exports.GuestZone=zt;exports.HealthApiService=Mn;exports.HttpService=ee;exports.LandingRoute=Ct;exports.LoginForm=an;exports.MagicLinkForm=hn;exports.MagicLinkVerify=wn;exports.OpenZone=Vt;exports.PasswordRecoveryForm=Sn;exports.PermissionApiService=Pn;exports.Protected=Pt;exports.ProtectedRoute=Et;exports.PublicZone=Ot;exports.RoleApiService=ve;exports.RoutingProvider=kt;exports.SessionManager=ge;exports.SignupForm=cn;exports.SubscriptionApiService=_e;exports.SubscriptionGuard=Yt;exports.SubscriptionPlanApiService=Rn;exports.SubscriptionProvider=Tt;exports.TenantApiService=le;exports.TenantAuthenticatedZone=Zt;exports.TenantGuestZone=Kt;exports.TenantOpenZone=Gt;exports.TenantProvider=wt;exports.TenantRoute=Ft;exports.TenantSelector=jn;exports.TenantZone=Bt;exports.UserApiService=Be;exports.UserType=X;exports.UserZone=Wt;exports.ZoneRoute=ne;exports.buildRedirectUrl=Fn;exports.useApi=dt;exports.useApp=ce;exports.useAppLoaderState=An;exports.useAuth=re;exports.useFeatureFlags=qe;exports.useRouting=At;exports.useRoutingOptional=Ze;exports.useSettings=bt;exports.useSubscription=We;exports.useTenant=se;exports.useTenantInfo=ae;exports.useTenantOptional=ue;exports.useTenantSettings=xt;exports.useZoneNavigation=In;
7
7
  //# sourceMappingURL=index.js.map