@skylabs-digital/react-identity-access 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/FeatureFlag.d.ts.map +1 -1
- package/dist/index.es.js +480 -479
- package/dist/index.es.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/providers/TenantProvider.d.ts.map +1 -1
- package/dist/services/AuthApiService.d.ts.map +1 -1
- package/dist/services/SessionManager.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),a=require("react"),re=require("react-router-dom");class X{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async request(e,t,s,n){return this.executeRequest(e,t,s,n,!1)}async executeRequest(e,t,s,n,l=!1){const p=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,T=(n==null?void 0:n.timeout)||this.timeout;let j={"Content-Type":"application/json",...n==null?void 0:n.headers};if(!(n!=null&&n.skipAuth)&&this.sessionManager)try{const w=await this.sessionManager.getAuthHeaders();j={...j,...w}}catch(w){console.warn("Failed to inject auth headers:",w)}const S=new AbortController,k=setTimeout(()=>S.abort(),T);try{const w=await fetch(p,{method:e,headers:j,body:s?JSON.stringify(s):void 0,signal:S.signal});if(clearTimeout(k),w.status===401&&!(n!=null&&n.skipRetry)&&!l&&this.sessionManager)try{const h=this.sessionManager.getTokens();if(h!=null&&h.refreshToken)return await this.sessionManager.getAuthHeaders(),this.executeRequest(e,t,s,n,!0)}catch{throw new Error(`HTTP ${w.status}: ${w.statusText}`)}if(!w.ok)throw new Error(`HTTP ${w.status}: ${w.statusText}`);const m=w.headers.get("content-type");return!m||!m.includes("application/json")?{}:await w.json()}catch(w){throw clearTimeout(k),w instanceof Error&&w.name==="AbortError"?new Error(`Request timeout after ${T}ms`):w}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,s){return this.request("POST",e,t,s)}async put(e,t,s){return this.request("PUT",e,t,s)}async delete(e,t){return this.request("DELETE",e,void 0,t)}}class ue{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/apps/${s.toString()?`?${s.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{apps:l.data,meta:l.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:s})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:s})).data}async updateSettingsSchema(e,t,s){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:s},{headers:n})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const me=a.createContext(null),Re=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading application..."})}),Le=({error:i,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Application Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:i.message||"Unable to load application"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function $e({config:i,children:e}){const t=a.useMemo(()=>{var m,h,b;return{enabled:((m=i.cache)==null?void 0:m.enabled)??!0,ttl:((h=i.cache)==null?void 0:h.ttl)??3e5,storageKey:((b=i.cache)==null?void 0:b.storageKey)??`app_cache_${i.appId}`}},[i.cache,i.appId]),[s,n]=a.useState(()=>{if(!t.enabled)return null;try{const m=localStorage.getItem(t.storageKey);if(!m)return null;const h=JSON.parse(m);return Date.now()-h.timestamp<t.ttl&&h.appId===i.appId?h.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[l,p]=a.useState(!s),[T,j]=a.useState(null),S=a.useMemo(()=>{const m=()=>{k()};return{appId:i.appId,baseUrl:i.baseUrl,appInfo:s,isAppLoading:l,appError:T,retryApp:m}},[i,s,l,T]),k=a.useCallback(async(m=!1)=>{if(!(!m&&t.enabled&&s))try{p(!0),j(null);const h=new X(i.baseUrl),E=await new ue(h,{}).getPublicAppInfo(i.appId);if(n(E),t.enabled)try{const F={data:E,timestamp:Date.now(),appId:i.appId};localStorage.setItem(t.storageKey,JSON.stringify(F))}catch(F){console.warn("Failed to cache app info:",F)}}catch(h){const b=h instanceof Error?h:new Error("Failed to load app information");j(b),n(null)}finally{p(!1)}},[i.baseUrl,i.appId,t,s]),w=a.useCallback(async()=>{if(!(!t.enabled||!s))try{const m=localStorage.getItem(t.storageKey);if(!m)return;const h=JSON.parse(m);if(Date.now()-h.timestamp>t.ttl*.5){const E=new X(i.baseUrl),N=await new ue(E,{}).getPublicAppInfo(i.appId);n(N);const v={data:N,timestamp:Date.now(),appId:i.appId};localStorage.setItem(t.storageKey,JSON.stringify(v))}}catch(m){console.warn("Background app refresh failed:",m)}},[i,t,s]);if(a.useEffect(()=>{s?w():k()},[]),l)return r.jsx(r.Fragment,{children:i.loadingFallback||r.jsx(Re,{})});if(T){const m=typeof i.errorFallback=="function"?i.errorFallback(T,()=>k()):i.errorFallback||r.jsx(Le,{error:T,retry:()=>k()});return r.jsx(r.Fragment,{children:m})}return r.jsx(me.Provider,{value:S,children:e})}function ie(){const i=a.useContext(me);if(!i)throw new Error("useApp must be used within an AppProvider");return i}const De=ie;class ce{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(){return this.tokenStorage.get()}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,s)=>{this.refreshQueue.push({resolve:t,reject:s})});this.refreshPromise=this.performTokenRefresh(e.refreshToken);try{await this.refreshPromise;const t=this.getTokens(),s=t!=null&&t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{};return this.refreshQueue.forEach(({resolve:n})=>n(s)),this.refreshQueue=[],s}catch(t){const s=t instanceof Error?t:new Error("Token refresh failed");return this.refreshQueue.forEach(({reject:n})=>n(s)),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`,s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!s.ok)throw new Error(`Token refresh failed: ${s.status} ${s.statusText}`);const n=await s.json();this.setTokens({accessToken:n.accessToken,refreshToken:n.refreshToken||e,expiresIn:n.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 s=t[1],n=atob(s.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(n)}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 ye{constructor(e){this.httpService=e}async login(e){const t=await this.httpService.post("/auth/login",e);return console.log(t),t}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 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 he{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:s})).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 s=new URLSearchParams;t!=null&&t.page&&s.append("page",t.page.toString()),t!=null&&t.limit&&s.append("limit",t.limit.toString()),t!=null&&t.sortBy&&s.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&s.append("sortOrder",t.sortOrder);const n=`/roles/app/${e}${s.toString()?`?${s.toString()}`:""}`,l=await this.httpService.get(n);return{roles:l.data,meta:l.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:s})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:s})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const l=`/roles/user/${e}${n.toString()?`?${n.toString()}`:""}`,p=await this.httpService.get(l,{headers:s});return{roles:p.data,meta:p.meta}}}class xe{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/users/${s.toString()?`?${s.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{users:l.data,meta:l.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:s})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class ne{constructor(e,t,s){this.httpService=e,this.appId=t,this.sessionManager=s}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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/tenants/${s.toString()?`?${s.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{tenants:l.data,meta:l.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:s})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:s})).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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:s})).data}}const we=a.createContext(null),He=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading tenant..."})}),Ne=({error:i,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Tenant Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:i.message||"Unable to load tenant"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function Be({config:i,children:e}){const{baseUrl:t,appInfo:s,appId:n}=ie(),l=a.useCallback(()=>{const o=i.tenantMode||"selector",g="tenant";if(typeof window>"u")return null;if(o==="subdomain"){const d=window.location.hostname.split(".");if(d.length>=3){const c=d[0];return localStorage.setItem(g,c),c}return localStorage.getItem(g)}else if(o==="selector"){const d=new URLSearchParams(window.location.search).get(i.selectorParam||"tenant");return d?(localStorage.setItem(g,d),d):localStorage.getItem(g)}return null},[i.tenantMode,i.selectorParam]),[p,T]=a.useState(()=>l()),j=a.useMemo(()=>{var o,g,f;return{enabled:((o=i.cache)==null?void 0:o.enabled)??!0,ttl:((g=i.cache)==null?void 0:g.ttl)??5*60*1e3,storageKey:((f=i.cache)==null?void 0:f.storageKey)??`tenant_cache_${p||"default"}`}},[i.cache,p]),[S,k]=a.useState(()=>{if(i.initialTenant)return i.initialTenant;if(!j.enabled||!p)return null;try{const o=localStorage.getItem(j.storageKey);if(!o)return null;const g=JSON.parse(o);return Date.now()-g.timestamp<j.ttl&&g.tenantSlug===p?g.data:(localStorage.removeItem(j.storageKey),null)}catch{return null}}),[w,m]=a.useState(!S&&!i.initialTenant),[h,b]=a.useState(null),[E,F]=a.useState(null),[N,v]=a.useState(!1),[u,A]=a.useState(null);a.useEffect(()=>{const o=l();T(o)},[l]);const I=(s==null?void 0:s.settingsSchema)||null,$=a.useCallback(async(o,g=!1)=>{if(!(!g&&j.enabled&&S&&S.domain===o))try{m(!0),b(null);const f=new X(t),c=await new ne(f,n).getPublicTenantInfo(o);if(k(c),j.enabled)try{const y={data:c,timestamp:Date.now(),tenantSlug:o};localStorage.setItem(j.storageKey,JSON.stringify(y))}catch(y){console.warn("Failed to cache tenant info:",y)}}catch(f){const d=f instanceof Error?f:new Error("Failed to load tenant information");b(d),k(null)}finally{m(!1)}},[t,n,j,S]),V=a.useCallback(async()=>{if(!(!j.enabled||!S||!p))try{const o=localStorage.getItem(j.storageKey);if(!o)return;const g=JSON.parse(o);if(Date.now()-g.timestamp>j.ttl*.5){const d=new X(t),y=await new ne(d,n).getPublicTenantInfo(p);k(y);const O={data:y,timestamp:Date.now(),tenantSlug:p};localStorage.setItem(j.storageKey,JSON.stringify(O))}}catch(o){console.warn("Background tenant refresh failed:",o)}},[t,n,j,S,p]),C=a.useCallback(async()=>{if(S!=null&&S.id)try{v(!0),A(null);const o=new X(t),f=await new ne(o,S.appId).getTenantSettings(S.id);F(f)}catch(o){const g=o instanceof Error?o:new Error("Failed to load tenant settings");A(g),F(null)}finally{v(!1)}},[t,S]),z=a.useCallback(()=>{C()},[C]),x=a.useCallback(o=>{if(!I)return{isValid:!0,errors:[]};const g=[];try{return I.properties&&Object.entries(I.properties).forEach(([f,d])=>{var y;const c=o[f];if((y=I.required)!=null&&y.includes(f)&&c==null){g.push(`Field '${f}' is required`);return}if(c!=null){if(d.type){const O=d.type,Q=typeof c;O==="string"&&Q!=="string"?g.push(`Field '${f}' must be a string`):(O==="number"||O==="integer")&&Q!=="number"?g.push(`Field '${f}' must be a number`):O==="boolean"&&Q!=="boolean"?g.push(`Field '${f}' must be a boolean`):O==="array"&&!Array.isArray(c)&&g.push(`Field '${f}' must be an array`)}d.minLength!==void 0&&typeof c=="string"&&c.length<d.minLength&&g.push(`Field '${f}' must be at least ${d.minLength} characters long`),d.maxLength!==void 0&&typeof c=="string"&&c.length>d.maxLength&&g.push(`Field '${f}' must be no more than ${d.maxLength} characters long`),d.minimum!==void 0&&typeof c=="number"&&c<d.minimum&&g.push(`Field '${f}' must be at least ${d.minimum}`),d.maximum!==void 0&&typeof c=="number"&&c>d.maximum&&g.push(`Field '${f}' must be no more than ${d.maximum}`),d.pattern&&typeof c=="string"&&(new RegExp(d.pattern).test(c)||g.push(`Field '${f}' does not match the required pattern`)),d.enum&&!d.enum.includes(c)&&g.push(`Field '${f}' must be one of: ${d.enum.join(", ")}`)}}),{isValid:g.length===0,errors:g}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[I]);a.useEffect(()=>{!i.initialTenant&&p?S?V():$(p):!i.initialTenant&&!p&&(k(null),b(null),m(!1))},[i.initialTenant,p,S,$,V]),a.useEffect(()=>{S!=null&&S.id?C():(F(null),A(null),v(!1))},[S==null?void 0:S.id,C]);const P=a.useCallback((o,g="reload")=>{const f=i.tenantMode||"selector";if(console.log("[TenantProvider] Switching tenant:",{targetTenantSlug:o,currentTenantSlug:p,tenantMode:f,mode:g}),localStorage.setItem("tenant",o),f==="subdomain"){const d=window.location.hostname,c=d.split(".");if(c.length>=2){c[0]=o;const y=c.join("."),O=`${window.location.protocol}//${y}${window.location.pathname}${window.location.search}`;console.log("[TenantProvider] Redirecting to:",O),window.location.href=O}else console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",d)}else if(f==="selector"){const d=new URLSearchParams(window.location.search);if(d.set(i.selectorParam||"tenant",o),g==="reload"){const c=`${window.location.pathname}?${d.toString()}${window.location.hash}`;console.log("[TenantProvider] Reloading with new tenant:",c),window.location.href=c}else{const c=`${window.location.pathname}?${d.toString()}${window.location.hash}`;console.log("[TenantProvider] Navigating without reload:",c),window.history.pushState({},"",c),T(o),$(o)}}},[i.tenantMode,i.selectorParam,$,p]),M=a.useMemo(()=>({tenant:S,tenantSlug:p,isTenantLoading:w,tenantError:h,retryTenant:()=>{p&&$(p)},settings:E,settingsSchema:I,isSettingsLoading:N,settingsError:u,refreshSettings:z,switchTenant:P,validateSettings:x}),[S,p,w,h,E,I,N,u,z,P,x]);if(w)return r.jsx(r.Fragment,{children:i.loadingFallback||r.jsx(He,{})});if(h){const o=typeof i.errorFallback=="function"?i.errorFallback(h,()=>$(p||"")):i.errorFallback||r.jsx(Ne,{error:h,retry:()=>$(p||"")});return r.jsx(r.Fragment,{children:o})}return r.jsx(we.Provider,{value:M,children:e})}function oe(){const i=a.useContext(we);if(!i)throw new Error("useTenant must be used within a TenantProvider");return i}const Ue=oe;function qe(){const{settings:i,settingsSchema:e,isSettingsLoading:t,settingsError:s,validateSettings:n}=oe();return{settings:i,settingsSchema:e,isLoading:t,error:s,validateSettings:n}}function Z(){const{tenant:i,tenantSlug:e,isTenantLoading:t,tenantError:s,retryTenant:n}=oe();return{tenant:i,tenantSlug:e,isLoading:t,error:s,retry:n}}const be=a.createContext(null);function ze({config:i={},children:e}){const{appId:t,baseUrl:s}=ie(),{tenant:n,tenantSlug:l,switchTenant:p}=oe(),[T,j]=a.useState(i.initialRoles||[]),[S,k]=a.useState(!i.initialRoles),[w,m]=a.useState(null),[h,b]=a.useState(!1),[E,F]=a.useState(null),[N,v]=a.useState(0),u=a.useMemo(()=>new ce({tenantSlug:l,onRefreshFailed:i.onRefreshFailed,baseUrl:s}),[l,s,i.onRefreshFailed]),A=a.useMemo(()=>{const g=new X(s);return g.setSessionManager(u),g},[s,u]),I=a.useMemo(()=>new ye(new X(s)),[s]),$=a.useMemo(()=>new xe(A,u),[A,u]),V=a.useMemo(()=>new he(new X(s)),[s]),C=a.useMemo(()=>w||u.getUser(),[w,u]),z=a.useMemo(()=>C!=null&&C.roleId&&T.find(g=>g.id===C.roleId)||null,[C,T]),x=a.useMemo(()=>(z==null?void 0:z.permissions)||[],[z]),P=a.useMemo(()=>u.hasValidSession()&&w!==null,[u,w]),M=5*60*1e3,o=a.useMemo(()=>{const g=async(R=!1)=>{try{if(!u.hasValidSession())return;const H=Date.now();if(!R&&H-N<M&&w)return;const q=u.getUserId();if(!q){console.warn("[AuthProvider] No userId available in token or storage");return}b(!0),F(null);const J=await $.getUserById(q);m(J),u.setUser(J),v(Date.now())}catch(H){const W=H instanceof Error?H:new Error("Failed to load user data");F(W),console.error("[AuthProvider] Failed to load user data:",W)}finally{b(!1)}},f=async()=>{await g()},d=async R=>{const{username:H,password:W,tenantSlug:q}=R;let J=n==null?void 0:n.id,_=l,Y=u;q&&(J=(await new ne(A,t).getPublicTenantInfo(q)).id,_=q);const K=await I.login({username:H,password:W,appId:t,tenantId:J}),se=q&&q!==l;if(se&&(Y=new ce({tenantSlug:_,baseUrl:s})),Y.setTokens({accessToken:K.accessToken,refreshToken:K.refreshToken,expiresIn:K.expiresIn}),K.user){Y.setUser(K.user),m(K.user);try{await g()}catch(ae){console.warn("Failed to load complete user data after login:",ae)}}return se&&_&&_!==l&&p(_),K},c=async R=>{const{email:H,phoneNumber:W,name:q,password:J,lastName:_,tenantId:Y}=R;if(!H&&!W)throw new Error("Either email or phoneNumber is required");if(!q||!J)throw new Error("Name and password are required");const K=Y??(n==null?void 0:n.id);return await I.signup({email:H,phoneNumber:W,name:q,password:J,tenantId:K,lastName:_,appId:t})},y=async R=>{const{email:H,phoneNumber:W,name:q,password:J,tenantName:_,lastName:Y}=R;if(!H&&!W)throw new Error("Either email or phoneNumber is required");if(!q||!J||!_)throw new Error("Name, password, and tenantName are required");return await I.signupTenantAdmin({email:H,phoneNumber:W,name:q,password:J,tenantName:_,appId:t,lastName:Y})},O=async R=>{const{currentPassword:H,newPassword:W}=R,q=await u.getAuthHeaders();await I.changePassword({currentPassword:H,newPassword:W},q)},Q=async R=>{const{email:H,tenantId:W}=R,q=W??(n==null?void 0:n.id);if(!q)throw new Error("tenantId is required for password reset");await I.requestPasswordReset({email:H,tenantId:q})},B=async R=>{const{token:H,newPassword:W}=R;await I.confirmPasswordReset({token:H,newPassword:W})},D=async R=>{const{email:H,frontendUrl:W,name:q,lastName:J,tenantId:_}=R,Y=_??(n==null?void 0:n.id);if(!Y)throw new Error("tenantId is required for magic link authentication");return await I.sendMagicLink({email:H,tenantId:Y,frontendUrl:W,name:q,lastName:J,appId:t})},U=async R=>{const{token:H,email:W,tenantSlug:q}=R;let J=n==null?void 0:n.id,_=l,Y=u;q&&(J=(await new ne(A,t).getPublicTenantInfo(q)).id,_=q);const K=await I.verifyMagicLink({token:H,email:W,appId:t,tenantId:J}),se=q&&q!==l;if(se&&(Y=new ce({tenantSlug:_,baseUrl:s})),Y.setTokens({accessToken:K.accessToken,refreshToken:K.refreshToken,expiresIn:K.expiresIn}),K.user){Y.setUser(K.user),m(K.user);try{await g()}catch(ae){console.warn("Failed to load complete user data after magic link login:",ae)}}return se&&_&&_!==l&&p(_),K},L=async()=>{const R=u.getTokens();if(!(R!=null&&R.refreshToken))throw new Error("No refresh token available");const H=await I.refreshToken({refreshToken:R.refreshToken});u.setTokens({accessToken:H.accessToken,refreshToken:H.refreshToken||R.refreshToken,expiresIn:H.expiresIn})},G=()=>{u.clearSession(),m(null),F(null)},le=R=>{u.setTokens(R)},Me=()=>u.hasValidSession(),Ie=()=>{u.clearSession(),m(null),F(null)},Fe=async()=>{if(t)try{k(!0);const{roles:R}=await V.getRolesByApp(t);j(R)}catch(R){console.error("Failed to fetch roles:",R)}finally{k(!1)}},Ee=async()=>{await Fe()},de=R=>{if(!x||x.length===0)return!1;if(typeof R=="string")return x.includes(R);const H=`${R.resource}.${R.action}`;return x.includes(H)};return{isAuthenticated:P,sessionManager:u,authenticatedHttpService:A,login:d,signup:c,signupTenantAdmin:y,sendMagicLink:D,verifyMagicLink:U,changePassword:O,requestPasswordReset:Q,confirmPasswordReset:B,refreshToken:L,logout:G,setTokens:le,hasValidSession:Me,clearSession:Ie,currentUser:w,isUserLoading:h,userError:E,loadUserData:g,refreshUser:f,userRole:z,userPermissions:x,availableRoles:T,rolesLoading:S,hasPermission:de,hasAnyPermission:R=>R.some(H=>de(H)),hasAllPermissions:R=>R.every(H=>de(H)),getUserPermissionStrings:()=>x||[],refreshRoles:Ee}},[P,u,A,I,$,V,t,n,l,p,T,w,h,E,z,x,N,M]);return a.useEffect(()=>{!i.initialRoles&&t&&(async()=>{try{k(!0);const f=new X(s),d=new he(f),{roles:c}=await d.getRolesByApp(t);j(c)}catch(f){console.error("Failed to fetch roles:",f)}finally{k(!1)}})()},[t,s,i.initialRoles]),a.useEffect(()=>{const g=u.getUser();g&&u.hasValidSession()&&m(g)},[u]),a.useEffect(()=>{!w&&!h&&o.loadUserData().catch(()=>{})},[w,h,o]),a.useEffect(()=>{if(!u.hasValidSession()||!w)return;const g=setInterval(()=>{o.loadUserData().catch(()=>{})},M);return()=>clearInterval(g)},[u,w,o,M]),r.jsx(be.Provider,{value:o,children:e})}function te(){const i=a.useContext(be);if(!i)throw new Error("useAuth must be used within an AuthProvider");return i}class Se{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/feature-flags/${s.toString()?`?${s.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{featureFlags:l.data,meta:l.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:s})).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 s=new URLSearchParams;s.append("tenantId",e),s.append("appId",t);const n=`/tenant-feature-flags${s.toString()?`?${s.toString()}`:""}`;return(await this.httpService.get(n,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,s){if(!e||!t||!s)throw new Error("Flag Key, Tenant ID and App ID are required");const n=new URLSearchParams;n.append("tenantId",t),n.append("appId",s);const l=`/tenant-feature-flags/${e}${n.toString()?`?${n.toString()}`:""}`;return(await this.httpService.get(l,{headers:{"X-Tenant-ID":t}})).data}}const ve=a.createContext(null);function Oe({config:i={},children:e}){const{baseUrl:t,appId:s}=ie(),{tenant:n}=Z(),[l,p]=a.useState([]),[T,j]=a.useState(!1),[S,k]=a.useState(null),w=a.useMemo(()=>{const b=new X(t);return new Se(b)},[t]),m=async()=>{if(!(n!=null&&n.id)){p([]);return}j(!0),k(null);try{const b=await w.getTenantFeatureFlags(n.id,s);p(b)}catch(b){const E=b instanceof Error?b.message:"Failed to fetch feature flags";k(E),i.onError&&i.onError(b instanceof Error?b:new Error(E))}finally{j(!1)}};a.useEffect(()=>{m();const b=i.refreshInterval||5*60*1e3,E=setInterval(m,b);return()=>clearInterval(E)},[n==null?void 0:n.id,i.refreshInterval]);const h=a.useMemo(()=>({featureFlags:l,loading:T,error:S,isEnabled:v=>{const u=l.find(A=>A.key===v);return(u==null?void 0:u.value)===!0},getFlag:v=>l.find(u=>u.key===v),getFlagState:v=>{const u=l.find(A=>A.key===v);return u?u.value?"enabled":"disabled":"not_found"},refresh:async()=>{await m()}}),[l,T,S]);return r.jsx(ve.Provider,{value:h,children:e})}function je(){const i=a.useContext(ve);if(!i)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return i}class ke{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:s})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:s})).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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:s})).data}}const Ae=a.createContext(void 0);function Ve({config:i={},children:e}){const{baseUrl:t}=ie(),{tenant:s}=Z(),[n,l]=a.useState(null),[p,T]=a.useState(!1),[j,S]=a.useState(null),k=a.useMemo(()=>{const h=new X(t);return new ke(h)},[t]),w=async()=>{if(!(s!=null&&s.id)){l(null);return}T(!0),S(null);try{const h=await k.getTenantSubscriptionFeatures(s.id);l(h)}catch(h){const b=h instanceof Error?h.message:"Failed to fetch subscription";S(b),i.onError&&i.onError(h instanceof Error?h:new Error(b))}finally{T(!1)}};a.useEffect(()=>{if(w(),!i.refreshInterval)return;const h=i.refreshInterval||10*60*1e3,b=setInterval(w,h);return()=>clearInterval(b)},[s==null?void 0:s.id,i.refreshInterval]);const m=a.useMemo(()=>{const h=(n==null?void 0:n.features)||[];return{subscription:n,features:h,loading:p,error:j,isFeatureEnabled:u=>{const A=h.find(I=>I.key===u);return A?A.type==="BOOLEAN"||A.type==="boolean"?A.value===!0:!!A.value:!1},getFeature:u=>h.find(A=>A.key===u),getFeatureValue:(u,A)=>{const I=h.find($=>$.key===u);return I?I.value:A},hasAllowedPlan:u=>!n||!n.isActive?!1:u.includes(n.planId),refresh:async()=>{await w()}}},[n,p,j]);return r.jsx(Ae.Provider,{value:m,children:e})}function Pe(){const i=a.useContext(Ae);if(i===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return i}var ee=(i=>(i.SUPERUSER="SUPERUSER",i.TENANT_ADMIN="TENANT_ADMIN",i.USER="USER",i))(ee||{});const ge=()=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),r.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),r.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),r.jsx("button",{style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},onClick:()=>window.location.href="/login",children:"Sign In"})]}),pe=({userType:i,minUserType:e,missingPermissions:t})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#fff3cd",border:"1px solid #ffeaa7",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),r.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&i?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",r.jsx("strong",{children:i})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:"You don't have the required permissions to view this content."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]}),We=(i,e)=>{const t={[ee.USER]:1,[ee.TENANT_ADMIN]:2,[ee.SUPERUSER]:3};return t[i]>=t[e]};function Ge({children:i,fallback:e,minUserType:t,requiredPermissions:s,requireAllPermissions:n=!1}){const{hasValidSession:l,sessionManager:p,hasPermission:T,hasAnyPermission:j,hasAllPermissions:S}=te();if(!l())return r.jsx(r.Fragment,{children:e||r.jsx(ge,{})});const k=p.getUser();if(!k)return r.jsx(r.Fragment,{children:e||r.jsx(ge,{})});if(t&&!We(k.userType,t))return r.jsx(pe,{userType:k.userType,minUserType:t});if(s&&s.length>0&&!(n?S(s):j(s))){const m=s.filter(h=>!T(h)).map(h=>typeof h=="string"?h:h.name);return r.jsx(pe,{missingPermissions:m})}return r.jsx(r.Fragment,{children:i})}const Ke=({redirectPath:i})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})}),fe=({userType:i,minUserType:e,missingPermissions:t})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&i?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current access level: ",r.jsx("strong",{children:i})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]})}),_e=(i,e)=>{const t={[ee.USER]:1,[ee.TENANT_ADMIN]:2,[ee.SUPERUSER]:3};return t[i]>=t[e]};function Je({children:i,redirectTo:e="/login",minUserType:t,requiredPermissions:s,requireAllPermissions:n=!1,fallback:l}){const{hasValidSession:p,sessionManager:T,hasPermission:j,hasAnyPermission:S,hasAllPermissions:k}=te(),w=re.useLocation();if(!p())return l?r.jsx(r.Fragment,{children:l}):r.jsxs(r.Fragment,{children:[r.jsx(Ke,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:w.pathname},replace:!0})]});const m=T.getUser();if(!m)return r.jsx(re.Navigate,{to:e,state:{from:w.pathname},replace:!0});if(t&&!_e(m.userType,t))return r.jsx(fe,{userType:m.userType,minUserType:t});if(s&&s.length>0&&!(n?k(s):S(s))){const b=s.filter(E=>!j(E)).map(E=>typeof E=="string"?E:E.name);return r.jsx(fe,{missingPermissions:b})}return r.jsx(r.Fragment,{children:i})}const Ye=({redirectPath:i})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})});function Qe({children:i,redirectTo:e="/",fallback:t}){const{tenant:s,isLoading:n,error:l}=Z(),p=re.useLocation();return n||l?null:s?r.jsx(r.Fragment,{children:i}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Ye,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:p.pathname},replace:!0})]})}const Xe=({redirectPath:i})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})});function Ze({children:i,redirectTo:e="/dashboard",fallback:t}){const{tenant:s,isLoading:n,error:l}=Z(),p=re.useLocation();return n||l?null:s?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Xe,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:p.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:i})}const et=()=>r.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[r.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),r.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function tt({children:i,fallback:e=r.jsx(et,{}),allowedPlans:t,requiredFeature:s}){const{subscription:n,hasAllowedPlan:l,isFeatureEnabled:p,loading:T}=Pe();return T?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):n?n.isActive?t&&t.length>0&&!l(t)?r.jsx(r.Fragment,{children:e}):s&&!p(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:i}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const rt=({flagName:i})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"15px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",fontFamily:"system-ui, sans-serif",color:"#6c757d"},children:[r.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),r.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),r.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',i,'" is disabled']})]});function st({name:i,children:e,fallback:t}){const{isEnabled:s,loading:n}=je();return n?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):(console.log(i,s(i)),s(i)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(rt,{flagName:i})}))}const nt=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),it=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),at={showPassword:r.jsx(nt,{}),hidePassword:r.jsx(it,{})},ot={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..."},lt={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 ct({copy:i={},styles:e={},icons:t={},onSuccess:s,onError:n,onForgotPassword:l,onSignupClick:p,onMagicLinkClick:T,showForgotPassword:j=!0,showSignupLink:S=!0,showMagicLinkOption:k=!0,className:w}){const[m,h]=a.useState(""),[b,E]=a.useState(""),[F,N]=a.useState(!1),[v,u]=a.useState(!1),[A,I]=a.useState(""),[$,V]=a.useState({}),{login:C}=te(),{tenant:z}=Z(),x={...ot,...i},P={...lt,...e},M={...at,...t},o=()=>{const c={};return m.trim()||(c.username=!0),b.trim()||(c.password=!0),V(c),Object.keys(c).length===0},g=async c=>{if(c.preventDefault(),!!o()){if(!(z!=null&&z.id)){I("Tenant not found");return}u(!0),I("");try{const y=await C({username:m,password:b});s==null||s(y)}catch(y){const O=y.message||x.errorMessage;I(O),n==null||n(O)}finally{u(!1)}}},f=c=>({...P.input,...$[c]?P.inputError:{}}),d=()=>({...P.button,...v?P.buttonLoading:{},...!m||!b||v?P.buttonDisabled:{}});return r.jsxs("div",{className:w,style:P.container,children:[r.jsx("h2",{style:P.title,children:x.title}),r.jsxs("form",{onSubmit:g,style:P.form,children:[r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:x.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:m,onChange:c=>{h(c.target.value),$.username&&V(y=>({...y,username:!1}))},placeholder:x.usernamePlaceholder,style:f("username"),disabled:v})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:x.passwordLabel}),r.jsxs("div",{style:P.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:F?"text":"password",value:b,onChange:c=>{E(c.target.value),$.password&&V(y=>({...y,password:!1}))},placeholder:x.passwordPlaceholder,style:{...f("password"),paddingRight:"2.5rem"},disabled:v}),r.jsx("button",{type:"button",onClick:()=>N(!F),style:P.passwordToggle,disabled:v,"aria-label":F?"Hide password":"Show password",children:F?M.hidePassword:M.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:!m||!b||v,style:d(),children:v?x.loadingText:x.submitButton}),A&&r.jsx("div",{style:P.errorText,children:A})]}),(j||S||k)&&r.jsxs("div",{style:P.linkContainer,children:[k&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[x.magicLinkText," "]}),r.jsx("a",{onClick:T,style:P.link,children:x.magicLinkLink})]}),k&&(j||S)&&r.jsx("div",{style:P.divider,children:"•"}),j&&r.jsx("a",{onClick:l,style:P.link,children:x.forgotPasswordLink}),j&&S&&r.jsx("div",{style:P.divider,children:"•"}),S&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[x.signupText," "]}),r.jsx("a",{onClick:p,style:P.link,children:x.signupLink})]})]})]})}const dt={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"},ut={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},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 ht({copy:i={},styles:e={},signupType:t="user",onSuccess:s,onError:n,onLoginClick:l,onMagicLinkClick:p,showLoginLink:T=!0,showMagicLinkOption:j=!0,className:S}){const[k,w]=a.useState(""),[m,h]=a.useState(""),[b,E]=a.useState(""),[F,N]=a.useState(""),[v,u]=a.useState(""),[A,I]=a.useState(""),[$,V]=a.useState(""),[C,z]=a.useState(!1),[x,P]=a.useState(""),[M,o]=a.useState({}),{signup:g,signupTenantAdmin:f}=te(),{tenant:d}=Z(),c={...dt,...i},y={...ut,...e},O=()=>{const L={};return k.trim()||(L.name=!0),!b.trim()&&!F.trim()&&(L.email=!0,L.phoneNumber=!0),v.trim()||(L.password=!0),A.trim()||(L.confirmPassword=!0),t==="tenant"&&!$.trim()&&(L.tenantName=!0),o(L),Object.keys(L).length===0},Q=async L=>{if(L.preventDefault(),!!O()){if(v!==A){P(c.passwordMismatchError),o({confirmPassword:!0});return}if(t==="user"&&!(d!=null&&d.id)){P("Tenant not found");return}z(!0),P("");try{let G;t==="tenant"?G=await f({email:b||void 0,phoneNumber:F||void 0,name:k,password:v,tenantName:$,lastName:m||void 0}):G=await g({email:b||void 0,phoneNumber:F||void 0,name:k,password:v,tenantId:d.id,lastName:m||void 0}),s==null||s(G)}catch(G){const le=G.message||c.errorMessage;P(le),n==null||n(le)}finally{z(!1)}}},B=L=>({...y.input,...M[L]?y.inputError:{}}),D=()=>({...y.button,...C?y.buttonLoading:{},...!k||!b&&!F||!v||!A||C||t==="tenant"&&!$?y.buttonDisabled:{}}),U=k&&(b||F)&&v&&A&&(t==="user"||$);return r.jsxs("div",{className:S,style:y.container,children:[r.jsx("h2",{style:y.title,children:c.title}),r.jsxs("form",{onSubmit:Q,style:y.form,children:[r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:c.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:k,onChange:L=>{w(L.target.value),M.name&&o(G=>({...G,name:!1}))},placeholder:c.namePlaceholder,style:B("name"),disabled:C})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:c.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:m,onChange:L=>h(L.target.value),placeholder:c.lastNamePlaceholder,style:y.input,disabled:C})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:c.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:b,onChange:L=>{E(L.target.value),M.email&&o(G=>({...G,email:!1,phoneNumber:!1}))},placeholder:c.emailPlaceholder,style:B("email"),disabled:C})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:c.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:F,onChange:L=>{N(L.target.value),M.phoneNumber&&o(G=>({...G,email:!1,phoneNumber:!1}))},placeholder:c.phoneNumberPlaceholder,style:B("phoneNumber"),disabled:C})]}),r.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"}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:c.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:v,onChange:L=>{u(L.target.value),M.password&&o(G=>({...G,password:!1}))},placeholder:c.passwordPlaceholder,style:B("password"),disabled:C})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:c.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:A,onChange:L=>{I(L.target.value),M.confirmPassword&&o(G=>({...G,confirmPassword:!1})),x===c.passwordMismatchError&&P("")},placeholder:c.confirmPasswordPlaceholder,style:B("confirmPassword"),disabled:C})]}),t==="tenant"&&r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:c.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:$,onChange:L=>{V(L.target.value),M.tenantName&&o(G=>({...G,tenantName:!1}))},placeholder:c.tenantNamePlaceholder,style:B("tenantName"),disabled:C})]}),r.jsx("button",{type:"submit",disabled:!U||C,style:D(),children:C?c.loadingText:c.submitButton}),x&&r.jsx("div",{style:y.errorText,children:x})]}),(T||j)&&r.jsxs("div",{style:y.linkContainer,children:[j&&r.jsxs("div",{children:[r.jsxs("span",{style:y.divider,children:[c.magicLinkText," "]}),r.jsx("a",{onClick:p,style:y.link,children:c.magicLinkLink})]}),j&&T&&r.jsx("div",{style:y.divider,children:"•"}),T&&r.jsxs("div",{children:[r.jsxs("span",{style:y.divider,children:[c.loginText," "]}),r.jsx("a",{onClick:l,style:y.link,children:c.loginLink})]})]})]})}const gt={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."},pt={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},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 ft({copy:i={},styles:e={},onSuccess:t,onError:s,onLoginClick:n,onSignupClick:l,showTraditionalLinks:p=!0,className:T,verifyToken:j,frontendUrl:S}){const[k,w]=a.useState(""),[m,h]=a.useState(""),[b,E]=a.useState(""),[F,N]=a.useState(!1),[v,u]=a.useState(!1),[A,I]=a.useState(""),[$,V]=a.useState(""),[C,z]=a.useState({}),[x,P]=a.useState(!1),{sendMagicLink:M,verifyMagicLink:o}=te(),{tenant:g}=Z(),f={...gt,...i},d={...pt,...e};a.useEffect(()=>{j&&c(j)},[j]);const c=async D=>{if(!g||!k){I("Missing tenant or email");return}u(!0),I("");try{const U=await o({token:D,email:k});t==null||t(U)}catch(U){const L=U.message||"Failed to verify magic link";I(L),s==null||s(L)}finally{u(!1)}},y=()=>{const D={};return k.trim()||(D.email=!0),x&&!m.trim()&&(D.name=!0),z(D),Object.keys(D).length===0},O=async D=>{if(D.preventDefault(),!!y()){if(!(g!=null&&g.id)){I("Tenant not found");return}N(!0),I(""),V("");try{const U=S||(typeof window<"u"?window.location.origin:""),L=await M({email:k,tenantId:g.id,frontendUrl:U,name:x?m:void 0,lastName:x?b:void 0});V(f.successMessage),t==null||t(L)}catch(U){const L=U.message||f.errorMessage;I(L),s==null||s(L)}finally{N(!1)}}},Q=D=>({...d.input,...C[D]?d.inputError:{}}),B=()=>({...d.button,...F||v?d.buttonLoading:{},...!k||F||v?d.buttonDisabled:{}});return v?r.jsxs("div",{className:T,style:d.container,children:[r.jsx("h2",{style:d.title,children:f.verifyingText}),r.jsx("div",{style:{textAlign:"center",padding:"2rem"},children:r.jsx("div",{style:{fontSize:"1rem",color:"#6b7280"},children:"Please wait while we verify your magic link..."})})]}):r.jsxs("div",{className:T,style:d.container,children:[r.jsx("h2",{style:d.title,children:f.title}),r.jsx("p",{style:d.description,children:f.description}),r.jsxs("form",{onSubmit:O,style:d.form,children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:f.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:k,onChange:D=>{w(D.target.value),C.email&&z(U=>({...U,email:!1}))},placeholder:f.emailPlaceholder,style:Q("email"),disabled:F||v})]}),!x&&r.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:r.jsx("button",{type:"button",onClick:()=>P(!0),style:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"New user? Add your name"})}),x&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:f.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:m,onChange:D=>{h(D.target.value),C.name&&z(U=>({...U,name:!1}))},placeholder:f.namePlaceholder,style:Q("name"),disabled:F||v})]}),r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:f.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:b,onChange:D=>E(D.target.value),placeholder:f.lastNamePlaceholder,style:d.input,disabled:F||v})]}),r.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:r.jsx("button",{type:"button",onClick:()=>{P(!1),h(""),E("")},style:{background:"none",border:"none",color:"#6b7280",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"Existing user? Hide name fields"})})]}),r.jsx("button",{type:"submit",disabled:!k||F||v,style:B(),children:F?f.loadingText:f.submitButton}),A&&r.jsx("div",{style:d.errorText,children:A}),$&&r.jsx("div",{style:d.successText,children:$})]}),p&&r.jsxs("div",{style:d.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:d.divider,children:[f.loginText," "]}),r.jsx("a",{onClick:n,style:d.link,children:f.loginLink})]}),r.jsx("div",{style:d.divider,children:"•"}),r.jsxs("div",{children:[r.jsxs("span",{style:d.divider,children:[f.signupText," "]}),r.jsx("a",{onClick:l,style:d.link,children:f.signupLink})]})]})]})}const mt={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"},Te={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"}},yt=()=>r.jsx("div",{style:Te.spinner}),xt=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#059669",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),r.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),wt=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),r.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),bt={loading:r.jsx(yt,{}),success:r.jsx(xt,{}),error:r.jsx(wt,{})};function St({copy:i={},styles:e={},icons:t={},onSuccess:s,onError:n,onRetry:l,onBackToLogin:p,className:T,token:j,email:S,appId:k,tenantSlug:w,autoRedirectDelay:m=3e3}){const[h,b]=a.useState("verifying"),[E,F]=a.useState(""),{verifyMagicLink:N}=te(),v={...mt,...i},u={...Te,...e},A={...bt,...t},I=()=>{if(typeof window>"u")return{};const x=new URLSearchParams(window.location.search);return{token:j||x.get("token")||"",email:S||x.get("email")||"",appId:k||x.get("appId")||"",tenantSlug:w||x.get("tenantSlug")||void 0}},$=async()=>{b("verifying"),F("");try{const x=I();if(!x.token||!x.email)throw new Error("Missing required parameters: token or email");const P=await N({token:x.token,email:x.email,tenantSlug:x.tenantSlug});b("success"),s==null||s(P),m>0&&setTimeout(()=>{b("redirecting")},m)}catch(x){const P=x.message||v.errorMessage;F(P),b("error"),n==null||n(P)}},V=()=>{l==null||l(),$()},C=()=>{p==null||p()};a.useEffect(()=>{$()},[]);const z=()=>{switch(h){case"verifying":return r.jsxs("div",{style:u.message,children:[A.loading,v.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[A.success,r.jsx("div",{style:u.successMessage,children:v.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[A.loading,r.jsx("div",{style:u.message,children:v.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[A.error,r.jsx("div",{style:u.errorMessage,children:E||v.errorMessage}),r.jsxs("div",{style:u.buttonContainer,children:[r.jsx("button",{onClick:V,style:u.retryButton,onMouseOver:x=>{x.currentTarget.style.backgroundColor="#2563eb"},onMouseOut:x=>{x.currentTarget.style.backgroundColor="#3b82f6"},children:v.retryButton}),r.jsx("button",{onClick:C,style:u.backButton,onMouseOver:x=>{x.currentTarget.style.backgroundColor="#e5e7eb"},onMouseOut:x=>{x.currentTarget.style.backgroundColor="#f3f4f6"},children:v.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:u.container,className:T,children:[r.jsx("style",{children:`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),a=require("react"),re=require("react-router-dom");class X{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async request(e,t,s,n){return this.executeRequest(e,t,s,n,!1)}async executeRequest(e,t,s,n,o=!1){const p=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,T=(n==null?void 0:n.timeout)||this.timeout;let j={"Content-Type":"application/json",...n==null?void 0:n.headers};if(!(n!=null&&n.skipAuth)&&this.sessionManager)try{const w=await this.sessionManager.getAuthHeaders();j={...j,...w}}catch(w){console.warn("Failed to inject auth headers:",w)}const S=new AbortController,k=setTimeout(()=>S.abort(),T);try{const w=await fetch(p,{method:e,headers:j,body:s?JSON.stringify(s):void 0,signal:S.signal});if(clearTimeout(k),w.status===401&&!(n!=null&&n.skipRetry)&&!o&&this.sessionManager)try{const h=this.sessionManager.getTokens();if(h!=null&&h.refreshToken)return await this.sessionManager.getAuthHeaders(),this.executeRequest(e,t,s,n,!0)}catch{throw new Error(`HTTP ${w.status}: ${w.statusText}`)}if(!w.ok)throw new Error(`HTTP ${w.status}: ${w.statusText}`);const f=w.headers.get("content-type");return!f||!f.includes("application/json")?{}:await w.json()}catch(w){throw clearTimeout(k),w instanceof Error&&w.name==="AbortError"?new Error(`Request timeout after ${T}ms`):w}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,s){return this.request("POST",e,t,s)}async put(e,t,s){return this.request("PUT",e,t,s)}async delete(e,t){return this.request("DELETE",e,void 0,t)}}class ue{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/apps/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:s})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:s})).data}async updateSettingsSchema(e,t,s){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:s},{headers:n})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const me=a.createContext(null),Re=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading application..."})}),Le=({error:i,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Application Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:i.message||"Unable to load application"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function $e({config:i,children:e}){const t=a.useMemo(()=>{var f,h,b;return{enabled:((f=i.cache)==null?void 0:f.enabled)??!0,ttl:((h=i.cache)==null?void 0:h.ttl)??3e5,storageKey:((b=i.cache)==null?void 0:b.storageKey)??`app_cache_${i.appId}`}},[i.cache,i.appId]),[s,n]=a.useState(()=>{if(!t.enabled)return null;try{const f=localStorage.getItem(t.storageKey);if(!f)return null;const h=JSON.parse(f);return Date.now()-h.timestamp<t.ttl&&h.appId===i.appId?h.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[o,p]=a.useState(!s),[T,j]=a.useState(null),S=a.useMemo(()=>{const f=()=>{k()};return{appId:i.appId,baseUrl:i.baseUrl,appInfo:s,isAppLoading:o,appError:T,retryApp:f}},[i,s,o,T]),k=a.useCallback(async(f=!1)=>{if(!(!f&&t.enabled&&s))try{p(!0),j(null);const h=new X(i.baseUrl),E=await new ue(h,{}).getPublicAppInfo(i.appId);if(n(E),t.enabled)try{const F={data:E,timestamp:Date.now(),appId:i.appId};localStorage.setItem(t.storageKey,JSON.stringify(F))}catch(F){console.warn("Failed to cache app info:",F)}}catch(h){const b=h instanceof Error?h:new Error("Failed to load app information");j(b),n(null)}finally{p(!1)}},[i.baseUrl,i.appId,t,s]),w=a.useCallback(async()=>{if(!(!t.enabled||!s))try{const f=localStorage.getItem(t.storageKey);if(!f)return;const h=JSON.parse(f);if(Date.now()-h.timestamp>t.ttl*.5){const E=new X(i.baseUrl),N=await new ue(E,{}).getPublicAppInfo(i.appId);n(N);const v={data:N,timestamp:Date.now(),appId:i.appId};localStorage.setItem(t.storageKey,JSON.stringify(v))}}catch(f){console.warn("Background app refresh failed:",f)}},[i,t,s]);if(a.useEffect(()=>{s?w():k()},[]),o)return r.jsx(r.Fragment,{children:i.loadingFallback||r.jsx(Re,{})});if(T){const f=typeof i.errorFallback=="function"?i.errorFallback(T,()=>k()):i.errorFallback||r.jsx(Le,{error:T,retry:()=>k()});return r.jsx(r.Fragment,{children:f})}return r.jsx(me.Provider,{value:S,children:e})}function ie(){const i=a.useContext(me);if(!i)throw new Error("useApp must be used within an AppProvider");return i}const De=ie;class ce{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:s,expiresIn:n,tokenType:o}=this.tokenStorage.get()||{};return e?{accessToken:e,refreshToken:t,expiresAt:s,expiresIn:n,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,s)=>{this.refreshQueue.push({resolve:t,reject:s})});this.refreshPromise=this.performTokenRefresh(e.refreshToken);try{await this.refreshPromise;const t=this.getTokens(),s=t!=null&&t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{};return this.refreshQueue.forEach(({resolve:n})=>n(s)),this.refreshQueue=[],s}catch(t){const s=t instanceof Error?t:new Error("Token refresh failed");return this.refreshQueue.forEach(({reject:n})=>n(s)),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`,s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!s.ok)throw new Error(`Token refresh failed: ${s.status} ${s.statusText}`);const n=await s.json();this.setTokens({accessToken:n.accessToken,refreshToken:n.refreshToken||e,expiresIn:n.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 s=t[1],n=atob(s.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(n)}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 ye{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 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 he{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:s})).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 s=new URLSearchParams;t!=null&&t.page&&s.append("page",t.page.toString()),t!=null&&t.limit&&s.append("limit",t.limit.toString()),t!=null&&t.sortBy&&s.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&s.append("sortOrder",t.sortOrder);const n=`/roles/app/${e}${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n);return{roles:o.data,meta:o.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:s})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:s})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const o=`/roles/user/${e}${n.toString()?`?${n.toString()}`:""}`,p=await this.httpService.get(o,{headers:s});return{roles:p.data,meta:p.meta}}}class xe{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/users/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:s})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class ne{constructor(e,t,s){this.httpService=e,this.appId=t,this.sessionManager=s}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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/tenants/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:s})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:s})).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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:s})).data}}const we=a.createContext(null),He=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading tenant..."})}),Ne=({error:i,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Tenant Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:i.message||"Unable to load tenant"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function Be({config:i,children:e}){const{baseUrl:t,appInfo:s,appId:n}=ie(),o=a.useCallback(()=>{const l=i.tenantMode||"selector",g="tenant";if(typeof window>"u")return null;if(l==="subdomain"){const c=window.location.hostname.split(".");if(c.length>=3){const d=c[0];return localStorage.setItem(g,d),d}return localStorage.getItem(g)}else if(l==="selector"){const c=new URLSearchParams(window.location.search).get(i.selectorParam||"tenant");return c?(localStorage.setItem(g,c),c):localStorage.getItem(g)}return null},[i.tenantMode,i.selectorParam]),[p,T]=a.useState(()=>o()),j=a.useMemo(()=>{var l,g,m;return{enabled:((l=i.cache)==null?void 0:l.enabled)??!0,ttl:((g=i.cache)==null?void 0:g.ttl)??5*60*1e3,storageKey:((m=i.cache)==null?void 0:m.storageKey)??`tenant_cache_${p||"default"}`}},[i.cache,p]),[S,k]=a.useState(()=>{if(i.initialTenant)return i.initialTenant;if(!j.enabled||!p)return null;try{const l=localStorage.getItem(j.storageKey);if(!l)return null;const g=JSON.parse(l);return Date.now()-g.timestamp<j.ttl&&g.tenantSlug===p?g.data:(localStorage.removeItem(j.storageKey),null)}catch{return null}}),[w,f]=a.useState(!S&&!i.initialTenant),[h,b]=a.useState(null),[E,F]=a.useState(null),[N,v]=a.useState(!1),[u,A]=a.useState(null);a.useEffect(()=>{const l=o();T(l)},[o]);const I=(s==null?void 0:s.settingsSchema)||null,$=a.useCallback(async(l,g=!1)=>{if(!(!g&&j.enabled&&S&&S.domain===l))try{f(!0),b(null);const m=new X(t),d=await new ne(m,n).getPublicTenantInfo(l);if(k(d),j.enabled)try{const y={data:d,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(j.storageKey,JSON.stringify(y))}catch(y){console.warn("Failed to cache tenant info:",y)}}catch(m){const c=m instanceof Error?m:new Error("Failed to load tenant information");b(c),k(null)}finally{f(!1)}},[t,n,j,S]),O=a.useCallback(async()=>{if(!(!j.enabled||!S||!p))try{const l=localStorage.getItem(j.storageKey);if(!l)return;const g=JSON.parse(l);if(Date.now()-g.timestamp>j.ttl*.5){const c=new X(t),y=await new ne(c,n).getPublicTenantInfo(p);k(y);const V={data:y,timestamp:Date.now(),tenantSlug:p};localStorage.setItem(j.storageKey,JSON.stringify(V))}}catch(l){console.warn("Background tenant refresh failed:",l)}},[t,n,j,S,p]),C=a.useCallback(async()=>{if(S!=null&&S.id)try{v(!0),A(null);const l=new X(t),m=await new ne(l,S.appId).getTenantSettings(S.id);F(m)}catch(l){const g=l instanceof Error?l:new Error("Failed to load tenant settings");A(g),F(null)}finally{v(!1)}},[t,S]),z=a.useCallback(()=>{C()},[C]),x=a.useCallback(l=>{if(!I)return{isValid:!0,errors:[]};const g=[];try{return I.properties&&Object.entries(I.properties).forEach(([m,c])=>{var y;const d=l[m];if((y=I.required)!=null&&y.includes(m)&&d==null){g.push(`Field '${m}' is required`);return}if(d!=null){if(c.type){const V=c.type,Q=typeof d;V==="string"&&Q!=="string"?g.push(`Field '${m}' must be a string`):(V==="number"||V==="integer")&&Q!=="number"?g.push(`Field '${m}' must be a number`):V==="boolean"&&Q!=="boolean"?g.push(`Field '${m}' must be a boolean`):V==="array"&&!Array.isArray(d)&&g.push(`Field '${m}' must be an array`)}c.minLength!==void 0&&typeof d=="string"&&d.length<c.minLength&&g.push(`Field '${m}' must be at least ${c.minLength} characters long`),c.maxLength!==void 0&&typeof d=="string"&&d.length>c.maxLength&&g.push(`Field '${m}' must be no more than ${c.maxLength} characters long`),c.minimum!==void 0&&typeof d=="number"&&d<c.minimum&&g.push(`Field '${m}' must be at least ${c.minimum}`),c.maximum!==void 0&&typeof d=="number"&&d>c.maximum&&g.push(`Field '${m}' must be no more than ${c.maximum}`),c.pattern&&typeof d=="string"&&(new RegExp(c.pattern).test(d)||g.push(`Field '${m}' does not match the required pattern`)),c.enum&&!c.enum.includes(d)&&g.push(`Field '${m}' must be one of: ${c.enum.join(", ")}`)}}),{isValid:g.length===0,errors:g}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[I]);a.useEffect(()=>{!i.initialTenant&&p?S?O():$(p):!i.initialTenant&&!p&&(k(null),b(null),f(!1))},[i.initialTenant,p,S,$,O]),a.useEffect(()=>{S!=null&&S.id?C():(F(null),A(null),v(!1))},[S==null?void 0:S.id,C]);const P=a.useCallback((l,g="reload")=>{const m=i.tenantMode||"selector";if(localStorage.setItem("tenant",l),m==="subdomain"){const c=window.location.hostname,d=c.split(".");if(d.length>=2){d[0]=l;const y=d.join("."),V=`${window.location.protocol}//${y}${window.location.pathname}${window.location.search}`;window.location.href=V}else console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",c)}else if(m==="selector"){const c=new URLSearchParams(window.location.search);if(c.set(i.selectorParam||"tenant",l),g==="reload"){const d=`${window.location.pathname}?${c.toString()}${window.location.hash}`;window.location.href=d}else{const d=`${window.location.pathname}?${c.toString()}${window.location.hash}`;window.history.pushState({},"",d),T(l),$(l)}}},[i.tenantMode,i.selectorParam,$,p]),M=a.useMemo(()=>({tenant:S,tenantSlug:p,isTenantLoading:w,tenantError:h,retryTenant:()=>{p&&$(p)},settings:E,settingsSchema:I,isSettingsLoading:N,settingsError:u,refreshSettings:z,switchTenant:P,validateSettings:x}),[S,p,w,h,E,I,N,u,z,P,x]);if(w)return r.jsx(r.Fragment,{children:i.loadingFallback||r.jsx(He,{})});if(h){const l=typeof i.errorFallback=="function"?i.errorFallback(h,()=>$(p||"")):i.errorFallback||r.jsx(Ne,{error:h,retry:()=>$(p||"")});return r.jsx(r.Fragment,{children:l})}return r.jsx(we.Provider,{value:M,children:e})}function oe(){const i=a.useContext(we);if(!i)throw new Error("useTenant must be used within a TenantProvider");return i}const Ue=oe;function qe(){const{settings:i,settingsSchema:e,isSettingsLoading:t,settingsError:s,validateSettings:n}=oe();return{settings:i,settingsSchema:e,isLoading:t,error:s,validateSettings:n}}function Z(){const{tenant:i,tenantSlug:e,isTenantLoading:t,tenantError:s,retryTenant:n}=oe();return{tenant:i,tenantSlug:e,isLoading:t,error:s,retry:n}}const be=a.createContext(null);function ze({config:i={},children:e}){const{appId:t,baseUrl:s}=ie(),{tenant:n,tenantSlug:o,switchTenant:p}=oe(),[T,j]=a.useState(i.initialRoles||[]),[S,k]=a.useState(!i.initialRoles),[w,f]=a.useState(null),[h,b]=a.useState(!1),[E,F]=a.useState(null),[N,v]=a.useState(0),u=a.useMemo(()=>new ce({tenantSlug:o,onRefreshFailed:i.onRefreshFailed,baseUrl:s}),[o,s,i.onRefreshFailed]),A=a.useMemo(()=>{const g=new X(s);return g.setSessionManager(u),g},[s,u]),I=a.useMemo(()=>new ye(new X(s)),[s]),$=a.useMemo(()=>new xe(A,u),[A,u]),O=a.useMemo(()=>new he(new X(s)),[s]),C=a.useMemo(()=>w||u.getUser(),[w,u]),z=a.useMemo(()=>C!=null&&C.roleId&&T.find(g=>g.id===C.roleId)||null,[C,T]),x=a.useMemo(()=>(z==null?void 0:z.permissions)||[],[z]),P=a.useMemo(()=>u.hasValidSession()&&w!==null,[u,w]),M=5*60*1e3,l=a.useMemo(()=>{const g=async(R=!1)=>{try{if(!u.hasValidSession())return;const H=Date.now();if(!R&&H-N<M&&w)return;const q=u.getUserId();if(!q){console.warn("[AuthProvider] No userId available in token or storage");return}b(!0),F(null);const J=await $.getUserById(q);f(J),u.setUser(J),v(Date.now())}catch(H){const W=H instanceof Error?H:new Error("Failed to load user data");F(W),console.error("[AuthProvider] Failed to load user data:",W)}finally{b(!1)}},m=async()=>{await g()},c=async R=>{const{username:H,password:W,tenantSlug:q}=R;let J=n==null?void 0:n.id,_=o,Y=u;q&&(J=(await new ne(A,t).getPublicTenantInfo(q)).id,_=q);const K=await I.login({username:H,password:W,appId:t,tenantId:J}),se=q&&q!==o;if(se&&(Y=new ce({tenantSlug:_,baseUrl:s})),Y.setTokens({accessToken:K.accessToken,refreshToken:K.refreshToken,expiresIn:K.expiresIn}),K.user){Y.setUser(K.user),f(K.user);try{await g()}catch(ae){console.warn("Failed to load complete user data after login:",ae)}}return se&&_&&_!==o&&p(_),K},d=async R=>{const{email:H,phoneNumber:W,name:q,password:J,lastName:_,tenantId:Y}=R;if(!H&&!W)throw new Error("Either email or phoneNumber is required");if(!q||!J)throw new Error("Name and password are required");const K=Y??(n==null?void 0:n.id);return await I.signup({email:H,phoneNumber:W,name:q,password:J,tenantId:K,lastName:_,appId:t})},y=async R=>{const{email:H,phoneNumber:W,name:q,password:J,tenantName:_,lastName:Y}=R;if(!H&&!W)throw new Error("Either email or phoneNumber is required");if(!q||!J||!_)throw new Error("Name, password, and tenantName are required");return await I.signupTenantAdmin({email:H,phoneNumber:W,name:q,password:J,tenantName:_,appId:t,lastName:Y})},V=async R=>{const{currentPassword:H,newPassword:W}=R,q=await u.getAuthHeaders();await I.changePassword({currentPassword:H,newPassword:W},q)},Q=async R=>{const{email:H,tenantId:W}=R,q=W??(n==null?void 0:n.id);if(!q)throw new Error("tenantId is required for password reset");await I.requestPasswordReset({email:H,tenantId:q})},B=async R=>{const{token:H,newPassword:W}=R;await I.confirmPasswordReset({token:H,newPassword:W})},D=async R=>{const{email:H,frontendUrl:W,name:q,lastName:J,tenantId:_}=R,Y=_??(n==null?void 0:n.id);if(!Y)throw new Error("tenantId is required for magic link authentication");return await I.sendMagicLink({email:H,tenantId:Y,frontendUrl:W,name:q,lastName:J,appId:t})},U=async R=>{const{token:H,email:W,tenantSlug:q}=R;let J=n==null?void 0:n.id,_=o,Y=u;q&&(J=(await new ne(A,t).getPublicTenantInfo(q)).id,_=q);const K=await I.verifyMagicLink({token:H,email:W,appId:t,tenantId:J}),se=q&&q!==o;if(se&&(Y=new ce({tenantSlug:_,baseUrl:s})),Y.setTokens({accessToken:K.accessToken,refreshToken:K.refreshToken,expiresIn:K.expiresIn}),K.user){Y.setUser(K.user),f(K.user);try{await g()}catch(ae){console.warn("Failed to load complete user data after magic link login:",ae)}}return se&&_&&_!==o&&p(_),K},L=async()=>{const R=u.getTokens();if(!(R!=null&&R.refreshToken))throw new Error("No refresh token available");const H=await I.refreshToken({refreshToken:R.refreshToken});u.setTokens({accessToken:H.accessToken,refreshToken:H.refreshToken||R.refreshToken,expiresIn:H.expiresIn})},G=()=>{u.clearSession(),f(null),F(null)},le=R=>{u.setTokens(R)},Me=()=>u.hasValidSession(),Ie=()=>{u.clearSession(),f(null),F(null)},Fe=async()=>{if(t)try{k(!0);const{roles:R}=await O.getRolesByApp(t);j(R)}catch(R){console.error("Failed to fetch roles:",R)}finally{k(!1)}},Ee=async()=>{await Fe()},de=R=>{if(!x||x.length===0)return!1;if(typeof R=="string")return x.includes(R);const H=`${R.resource}.${R.action}`;return x.includes(H)};return{isAuthenticated:P,sessionManager:u,authenticatedHttpService:A,login:c,signup:d,signupTenantAdmin:y,sendMagicLink:D,verifyMagicLink:U,changePassword:V,requestPasswordReset:Q,confirmPasswordReset:B,refreshToken:L,logout:G,setTokens:le,hasValidSession:Me,clearSession:Ie,currentUser:w,isUserLoading:h,userError:E,loadUserData:g,refreshUser:m,userRole:z,userPermissions:x,availableRoles:T,rolesLoading:S,hasPermission:de,hasAnyPermission:R=>R.some(H=>de(H)),hasAllPermissions:R=>R.every(H=>de(H)),getUserPermissionStrings:()=>x||[],refreshRoles:Ee}},[P,u,A,I,$,O,t,n,o,p,T,w,h,E,z,x,N,M]);return a.useEffect(()=>{!i.initialRoles&&t&&(async()=>{try{k(!0);const m=new X(s),c=new he(m),{roles:d}=await c.getRolesByApp(t);j(d)}catch(m){console.error("Failed to fetch roles:",m)}finally{k(!1)}})()},[t,s,i.initialRoles]),a.useEffect(()=>{const g=u.getUser();g&&u.hasValidSession()&&f(g)},[u]),a.useEffect(()=>{!w&&!h&&l.loadUserData().catch(()=>{})},[w,h,l]),a.useEffect(()=>{if(!u.hasValidSession()||!w)return;const g=setInterval(()=>{l.loadUserData().catch(()=>{})},M);return()=>clearInterval(g)},[u,w,l,M]),r.jsx(be.Provider,{value:l,children:e})}function te(){const i=a.useContext(be);if(!i)throw new Error("useAuth must be used within an AuthProvider");return i}class Se{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/feature-flags/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:s})).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 s=new URLSearchParams;s.append("tenantId",e),s.append("appId",t);const n=`/tenant-feature-flags${s.toString()?`?${s.toString()}`:""}`;return(await this.httpService.get(n,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,s){if(!e||!t||!s)throw new Error("Flag Key, Tenant ID and App ID are required");const n=new URLSearchParams;n.append("tenantId",t),n.append("appId",s);const o=`/tenant-feature-flags/${e}${n.toString()?`?${n.toString()}`:""}`;return(await this.httpService.get(o,{headers:{"X-Tenant-ID":t}})).data}}const ve=a.createContext(null);function Oe({config:i={},children:e}){const{baseUrl:t,appId:s}=ie(),{tenant:n}=Z(),[o,p]=a.useState([]),[T,j]=a.useState(!1),[S,k]=a.useState(null),w=a.useMemo(()=>{const b=new X(t);return new Se(b)},[t]),f=async()=>{if(!(n!=null&&n.id)){p([]);return}j(!0),k(null);try{const b=await w.getTenantFeatureFlags(n.id,s);p(b)}catch(b){const E=b instanceof Error?b.message:"Failed to fetch feature flags";k(E),i.onError&&i.onError(b instanceof Error?b:new Error(E))}finally{j(!1)}};a.useEffect(()=>{f();const b=i.refreshInterval||5*60*1e3,E=setInterval(f,b);return()=>clearInterval(E)},[n==null?void 0:n.id,i.refreshInterval]);const h=a.useMemo(()=>({featureFlags:o,loading:T,error:S,isEnabled:v=>{const u=o.find(A=>A.key===v);return(u==null?void 0:u.value)===!0},getFlag:v=>o.find(u=>u.key===v),getFlagState:v=>{const u=o.find(A=>A.key===v);return u?u.value?"enabled":"disabled":"not_found"},refresh:async()=>{await f()}}),[o,T,S]);return r.jsx(ve.Provider,{value:h,children:e})}function je(){const i=a.useContext(ve);if(!i)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return i}class ke{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:s})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:s})).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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:s})).data}}const Ae=a.createContext(void 0);function Ve({config:i={},children:e}){const{baseUrl:t}=ie(),{tenant:s}=Z(),[n,o]=a.useState(null),[p,T]=a.useState(!1),[j,S]=a.useState(null),k=a.useMemo(()=>{const h=new X(t);return new ke(h)},[t]),w=async()=>{if(!(s!=null&&s.id)){o(null);return}T(!0),S(null);try{const h=await k.getTenantSubscriptionFeatures(s.id);o(h)}catch(h){const b=h instanceof Error?h.message:"Failed to fetch subscription";S(b),i.onError&&i.onError(h instanceof Error?h:new Error(b))}finally{T(!1)}};a.useEffect(()=>{if(w(),!i.refreshInterval)return;const h=i.refreshInterval||10*60*1e3,b=setInterval(w,h);return()=>clearInterval(b)},[s==null?void 0:s.id,i.refreshInterval]);const f=a.useMemo(()=>{const h=(n==null?void 0:n.features)||[];return{subscription:n,features:h,loading:p,error:j,isFeatureEnabled:u=>{const A=h.find(I=>I.key===u);return A?A.type==="BOOLEAN"||A.type==="boolean"?A.value===!0:!!A.value:!1},getFeature:u=>h.find(A=>A.key===u),getFeatureValue:(u,A)=>{const I=h.find($=>$.key===u);return I?I.value:A},hasAllowedPlan:u=>!n||!n.isActive?!1:u.includes(n.planId),refresh:async()=>{await w()}}},[n,p,j]);return r.jsx(Ae.Provider,{value:f,children:e})}function Pe(){const i=a.useContext(Ae);if(i===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return i}var ee=(i=>(i.SUPERUSER="SUPERUSER",i.TENANT_ADMIN="TENANT_ADMIN",i.USER="USER",i))(ee||{});const ge=()=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),r.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),r.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),r.jsx("button",{style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},onClick:()=>window.location.href="/login",children:"Sign In"})]}),pe=({userType:i,minUserType:e,missingPermissions:t})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#fff3cd",border:"1px solid #ffeaa7",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),r.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&i?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",r.jsx("strong",{children:i})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:"You don't have the required permissions to view this content."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]}),We=(i,e)=>{const t={[ee.USER]:1,[ee.TENANT_ADMIN]:2,[ee.SUPERUSER]:3};return t[i]>=t[e]};function Ge({children:i,fallback:e,minUserType:t,requiredPermissions:s,requireAllPermissions:n=!1}){const{hasValidSession:o,sessionManager:p,hasPermission:T,hasAnyPermission:j,hasAllPermissions:S}=te();if(!o())return r.jsx(r.Fragment,{children:e||r.jsx(ge,{})});const k=p.getUser();if(!k)return r.jsx(r.Fragment,{children:e||r.jsx(ge,{})});if(t&&!We(k.userType,t))return r.jsx(pe,{userType:k.userType,minUserType:t});if(s&&s.length>0&&!(n?S(s):j(s))){const f=s.filter(h=>!T(h)).map(h=>typeof h=="string"?h:h.name);return r.jsx(pe,{missingPermissions:f})}return r.jsx(r.Fragment,{children:i})}const Ke=({redirectPath:i})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})}),fe=({userType:i,minUserType:e,missingPermissions:t})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&i?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current access level: ",r.jsx("strong",{children:i})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]})}),_e=(i,e)=>{const t={[ee.USER]:1,[ee.TENANT_ADMIN]:2,[ee.SUPERUSER]:3};return t[i]>=t[e]};function Je({children:i,redirectTo:e="/login",minUserType:t,requiredPermissions:s,requireAllPermissions:n=!1,fallback:o}){const{hasValidSession:p,sessionManager:T,hasPermission:j,hasAnyPermission:S,hasAllPermissions:k}=te(),w=re.useLocation();if(!p())return o?r.jsx(r.Fragment,{children:o}):r.jsxs(r.Fragment,{children:[r.jsx(Ke,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:w.pathname},replace:!0})]});const f=T.getUser();if(!f)return r.jsx(re.Navigate,{to:e,state:{from:w.pathname},replace:!0});if(t&&!_e(f.userType,t))return r.jsx(fe,{userType:f.userType,minUserType:t});if(s&&s.length>0&&!(n?k(s):S(s))){const b=s.filter(E=>!j(E)).map(E=>typeof E=="string"?E:E.name);return r.jsx(fe,{missingPermissions:b})}return r.jsx(r.Fragment,{children:i})}const Ye=({redirectPath:i})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})});function Qe({children:i,redirectTo:e="/",fallback:t}){const{tenant:s,isLoading:n,error:o}=Z(),p=re.useLocation();return n||o?null:s?r.jsx(r.Fragment,{children:i}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Ye,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:p.pathname},replace:!0})]})}const Xe=({redirectPath:i})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",i,"..."]})]})});function Ze({children:i,redirectTo:e="/dashboard",fallback:t}){const{tenant:s,isLoading:n,error:o}=Z(),p=re.useLocation();return n||o?null:s?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Xe,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:p.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:i})}const et=()=>r.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[r.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),r.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function tt({children:i,fallback:e=r.jsx(et,{}),allowedPlans:t,requiredFeature:s}){const{subscription:n,hasAllowedPlan:o,isFeatureEnabled:p,loading:T}=Pe();return T?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):n?n.isActive?t&&t.length>0&&!o(t)?r.jsx(r.Fragment,{children:e}):s&&!p(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:i}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const rt=({flagName:i})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"15px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",fontFamily:"system-ui, sans-serif",color:"#6c757d"},children:[r.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),r.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),r.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',i,'" is disabled']})]});function st({name:i,children:e,fallback:t}){const{isEnabled:s,loading:n}=je();return n?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):s(i)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(rt,{flagName:i})})}const nt=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),it=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),at={showPassword:r.jsx(nt,{}),hidePassword:r.jsx(it,{})},ot={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..."},lt={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 ct({copy:i={},styles:e={},icons:t={},onSuccess:s,onError:n,onForgotPassword:o,onSignupClick:p,onMagicLinkClick:T,showForgotPassword:j=!0,showSignupLink:S=!0,showMagicLinkOption:k=!0,className:w}){const[f,h]=a.useState(""),[b,E]=a.useState(""),[F,N]=a.useState(!1),[v,u]=a.useState(!1),[A,I]=a.useState(""),[$,O]=a.useState({}),{login:C}=te(),{tenant:z}=Z(),x={...ot,...i},P={...lt,...e},M={...at,...t},l=()=>{const d={};return f.trim()||(d.username=!0),b.trim()||(d.password=!0),O(d),Object.keys(d).length===0},g=async d=>{if(d.preventDefault(),!!l()){if(!(z!=null&&z.id)){I("Tenant not found");return}u(!0),I("");try{const y=await C({username:f,password:b});s==null||s(y)}catch(y){const V=y.message||x.errorMessage;I(V),n==null||n(V)}finally{u(!1)}}},m=d=>({...P.input,...$[d]?P.inputError:{}}),c=()=>({...P.button,...v?P.buttonLoading:{},...!f||!b||v?P.buttonDisabled:{}});return r.jsxs("div",{className:w,style:P.container,children:[r.jsx("h2",{style:P.title,children:x.title}),r.jsxs("form",{onSubmit:g,style:P.form,children:[r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:x.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:f,onChange:d=>{h(d.target.value),$.username&&O(y=>({...y,username:!1}))},placeholder:x.usernamePlaceholder,style:m("username"),disabled:v})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:x.passwordLabel}),r.jsxs("div",{style:P.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:F?"text":"password",value:b,onChange:d=>{E(d.target.value),$.password&&O(y=>({...y,password:!1}))},placeholder:x.passwordPlaceholder,style:{...m("password"),paddingRight:"2.5rem"},disabled:v}),r.jsx("button",{type:"button",onClick:()=>N(!F),style:P.passwordToggle,disabled:v,"aria-label":F?"Hide password":"Show password",children:F?M.hidePassword:M.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:!f||!b||v,style:c(),children:v?x.loadingText:x.submitButton}),A&&r.jsx("div",{style:P.errorText,children:A})]}),(j||S||k)&&r.jsxs("div",{style:P.linkContainer,children:[k&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[x.magicLinkText," "]}),r.jsx("a",{onClick:T,style:P.link,children:x.magicLinkLink})]}),k&&(j||S)&&r.jsx("div",{style:P.divider,children:"•"}),j&&r.jsx("a",{onClick:o,style:P.link,children:x.forgotPasswordLink}),j&&S&&r.jsx("div",{style:P.divider,children:"•"}),S&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[x.signupText," "]}),r.jsx("a",{onClick:p,style:P.link,children:x.signupLink})]})]})]})}const dt={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"},ut={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},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 ht({copy:i={},styles:e={},signupType:t="user",onSuccess:s,onError:n,onLoginClick:o,onMagicLinkClick:p,showLoginLink:T=!0,showMagicLinkOption:j=!0,className:S}){const[k,w]=a.useState(""),[f,h]=a.useState(""),[b,E]=a.useState(""),[F,N]=a.useState(""),[v,u]=a.useState(""),[A,I]=a.useState(""),[$,O]=a.useState(""),[C,z]=a.useState(!1),[x,P]=a.useState(""),[M,l]=a.useState({}),{signup:g,signupTenantAdmin:m}=te(),{tenant:c}=Z(),d={...dt,...i},y={...ut,...e},V=()=>{const L={};return k.trim()||(L.name=!0),!b.trim()&&!F.trim()&&(L.email=!0,L.phoneNumber=!0),v.trim()||(L.password=!0),A.trim()||(L.confirmPassword=!0),t==="tenant"&&!$.trim()&&(L.tenantName=!0),l(L),Object.keys(L).length===0},Q=async L=>{if(L.preventDefault(),!!V()){if(v!==A){P(d.passwordMismatchError),l({confirmPassword:!0});return}if(t==="user"&&!(c!=null&&c.id)){P("Tenant not found");return}z(!0),P("");try{let G;t==="tenant"?G=await m({email:b||void 0,phoneNumber:F||void 0,name:k,password:v,tenantName:$,lastName:f||void 0}):G=await g({email:b||void 0,phoneNumber:F||void 0,name:k,password:v,tenantId:c.id,lastName:f||void 0}),s==null||s(G)}catch(G){const le=G.message||d.errorMessage;P(le),n==null||n(le)}finally{z(!1)}}},B=L=>({...y.input,...M[L]?y.inputError:{}}),D=()=>({...y.button,...C?y.buttonLoading:{},...!k||!b&&!F||!v||!A||C||t==="tenant"&&!$?y.buttonDisabled:{}}),U=k&&(b||F)&&v&&A&&(t==="user"||$);return r.jsxs("div",{className:S,style:y.container,children:[r.jsx("h2",{style:y.title,children:d.title}),r.jsxs("form",{onSubmit:Q,style:y.form,children:[r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:k,onChange:L=>{w(L.target.value),M.name&&l(G=>({...G,name:!1}))},placeholder:d.namePlaceholder,style:B("name"),disabled:C})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:f,onChange:L=>h(L.target.value),placeholder:d.lastNamePlaceholder,style:y.input,disabled:C})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:b,onChange:L=>{E(L.target.value),M.email&&l(G=>({...G,email:!1,phoneNumber:!1}))},placeholder:d.emailPlaceholder,style:B("email"),disabled:C})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:F,onChange:L=>{N(L.target.value),M.phoneNumber&&l(G=>({...G,email:!1,phoneNumber:!1}))},placeholder:d.phoneNumberPlaceholder,style:B("phoneNumber"),disabled:C})]}),r.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"}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:v,onChange:L=>{u(L.target.value),M.password&&l(G=>({...G,password:!1}))},placeholder:d.passwordPlaceholder,style:B("password"),disabled:C})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:A,onChange:L=>{I(L.target.value),M.confirmPassword&&l(G=>({...G,confirmPassword:!1})),x===d.passwordMismatchError&&P("")},placeholder:d.confirmPasswordPlaceholder,style:B("confirmPassword"),disabled:C})]}),t==="tenant"&&r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:$,onChange:L=>{O(L.target.value),M.tenantName&&l(G=>({...G,tenantName:!1}))},placeholder:d.tenantNamePlaceholder,style:B("tenantName"),disabled:C})]}),r.jsx("button",{type:"submit",disabled:!U||C,style:D(),children:C?d.loadingText:d.submitButton}),x&&r.jsx("div",{style:y.errorText,children:x})]}),(T||j)&&r.jsxs("div",{style:y.linkContainer,children:[j&&r.jsxs("div",{children:[r.jsxs("span",{style:y.divider,children:[d.magicLinkText," "]}),r.jsx("a",{onClick:p,style:y.link,children:d.magicLinkLink})]}),j&&T&&r.jsx("div",{style:y.divider,children:"•"}),T&&r.jsxs("div",{children:[r.jsxs("span",{style:y.divider,children:[d.loginText," "]}),r.jsx("a",{onClick:o,style:y.link,children:d.loginLink})]})]})]})}const gt={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."},pt={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},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 ft({copy:i={},styles:e={},onSuccess:t,onError:s,onLoginClick:n,onSignupClick:o,showTraditionalLinks:p=!0,className:T,verifyToken:j,frontendUrl:S}){const[k,w]=a.useState(""),[f,h]=a.useState(""),[b,E]=a.useState(""),[F,N]=a.useState(!1),[v,u]=a.useState(!1),[A,I]=a.useState(""),[$,O]=a.useState(""),[C,z]=a.useState({}),[x,P]=a.useState(!1),{sendMagicLink:M,verifyMagicLink:l}=te(),{tenant:g}=Z(),m={...gt,...i},c={...pt,...e};a.useEffect(()=>{j&&d(j)},[j]);const d=async D=>{if(!g||!k){I("Missing tenant or email");return}u(!0),I("");try{const U=await l({token:D,email:k});t==null||t(U)}catch(U){const L=U.message||"Failed to verify magic link";I(L),s==null||s(L)}finally{u(!1)}},y=()=>{const D={};return k.trim()||(D.email=!0),x&&!f.trim()&&(D.name=!0),z(D),Object.keys(D).length===0},V=async D=>{if(D.preventDefault(),!!y()){if(!(g!=null&&g.id)){I("Tenant not found");return}N(!0),I(""),O("");try{const U=S||(typeof window<"u"?window.location.origin:""),L=await M({email:k,tenantId:g.id,frontendUrl:U,name:x?f:void 0,lastName:x?b:void 0});O(m.successMessage),t==null||t(L)}catch(U){const L=U.message||m.errorMessage;I(L),s==null||s(L)}finally{N(!1)}}},Q=D=>({...c.input,...C[D]?c.inputError:{}}),B=()=>({...c.button,...F||v?c.buttonLoading:{},...!k||F||v?c.buttonDisabled:{}});return v?r.jsxs("div",{className:T,style:c.container,children:[r.jsx("h2",{style:c.title,children:m.verifyingText}),r.jsx("div",{style:{textAlign:"center",padding:"2rem"},children:r.jsx("div",{style:{fontSize:"1rem",color:"#6b7280"},children:"Please wait while we verify your magic link..."})})]}):r.jsxs("div",{className:T,style:c.container,children:[r.jsx("h2",{style:c.title,children:m.title}),r.jsx("p",{style:c.description,children:m.description}),r.jsxs("form",{onSubmit:V,style:c.form,children:[r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:m.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:k,onChange:D=>{w(D.target.value),C.email&&z(U=>({...U,email:!1}))},placeholder:m.emailPlaceholder,style:Q("email"),disabled:F||v})]}),!x&&r.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:r.jsx("button",{type:"button",onClick:()=>P(!0),style:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"New user? Add your name"})}),x&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:m.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:f,onChange:D=>{h(D.target.value),C.name&&z(U=>({...U,name:!1}))},placeholder:m.namePlaceholder,style:Q("name"),disabled:F||v})]}),r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:m.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:b,onChange:D=>E(D.target.value),placeholder:m.lastNamePlaceholder,style:c.input,disabled:F||v})]}),r.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:r.jsx("button",{type:"button",onClick:()=>{P(!1),h(""),E("")},style:{background:"none",border:"none",color:"#6b7280",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"Existing user? Hide name fields"})})]}),r.jsx("button",{type:"submit",disabled:!k||F||v,style:B(),children:F?m.loadingText:m.submitButton}),A&&r.jsx("div",{style:c.errorText,children:A}),$&&r.jsx("div",{style:c.successText,children:$})]}),p&&r.jsxs("div",{style:c.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:c.divider,children:[m.loginText," "]}),r.jsx("a",{onClick:n,style:c.link,children:m.loginLink})]}),r.jsx("div",{style:c.divider,children:"•"}),r.jsxs("div",{children:[r.jsxs("span",{style:c.divider,children:[m.signupText," "]}),r.jsx("a",{onClick:o,style:c.link,children:m.signupLink})]})]})]})}const mt={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"},Te={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"}},yt=()=>r.jsx("div",{style:Te.spinner}),xt=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#059669",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),r.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),wt=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),r.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),bt={loading:r.jsx(yt,{}),success:r.jsx(xt,{}),error:r.jsx(wt,{})};function St({copy:i={},styles:e={},icons:t={},onSuccess:s,onError:n,onRetry:o,onBackToLogin:p,className:T,token:j,email:S,appId:k,tenantSlug:w,autoRedirectDelay:f=3e3}){const[h,b]=a.useState("verifying"),[E,F]=a.useState(""),{verifyMagicLink:N}=te(),v={...mt,...i},u={...Te,...e},A={...bt,...t},I=()=>{if(typeof window>"u")return{};const x=new URLSearchParams(window.location.search);return{token:j||x.get("token")||"",email:S||x.get("email")||"",appId:k||x.get("appId")||"",tenantSlug:w||x.get("tenantSlug")||void 0}},$=async()=>{b("verifying"),F("");try{const x=I();if(!x.token||!x.email)throw new Error("Missing required parameters: token or email");const P=await N({token:x.token,email:x.email,tenantSlug:x.tenantSlug});b("success"),s==null||s(P),f>0&&setTimeout(()=>{b("redirecting")},f)}catch(x){const P=x.message||v.errorMessage;F(P),b("error"),n==null||n(P)}},O=()=>{o==null||o(),$()},C=()=>{p==null||p()};a.useEffect(()=>{$()},[]);const z=()=>{switch(h){case"verifying":return r.jsxs("div",{style:u.message,children:[A.loading,v.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[A.success,r.jsx("div",{style:u.successMessage,children:v.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[A.loading,r.jsx("div",{style:u.message,children:v.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[A.error,r.jsx("div",{style:u.errorMessage,children:E||v.errorMessage}),r.jsxs("div",{style:u.buttonContainer,children:[r.jsx("button",{onClick:O,style:u.retryButton,onMouseOver:x=>{x.currentTarget.style.backgroundColor="#2563eb"},onMouseOut:x=>{x.currentTarget.style.backgroundColor="#3b82f6"},children:v.retryButton}),r.jsx("button",{onClick:C,style:u.backButton,onMouseOver:x=>{x.currentTarget.style.backgroundColor="#e5e7eb"},onMouseOut:x=>{x.currentTarget.style.backgroundColor="#f3f4f6"},children:v.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:u.container,className:T,children:[r.jsx("style",{children:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
0% { transform: rotate(0deg); }
|
|
4
4
|
100% { transform: rotate(360deg); }
|
|
5
5
|
}
|
|
6
|
-
`}),r.jsx("h1",{style:u.title,children:v.title}),z()]})}const vt={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"},jt={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 kt({copy:i={},styles:e={},mode:t="request",token:s="",onSuccess:n,onError:l,onBackToLogin:p,onModeChange:T,className:j}){const[S,k]=a.useState(""),[w,m]=a.useState(s),[h,b]=a.useState(""),[E,F]=a.useState(""),[N,v]=a.useState(!1),[u,A]=a.useState(""),[I,$]=a.useState(""),[V,C]=a.useState({}),{requestPasswordReset:z,confirmPasswordReset:x}=te(),{tenant:P}=Z(),M={...vt,...i},o={...jt,...e},g=()=>{const B={};return S.trim()||(B.email=!0),C(B),Object.keys(B).length===0},f=()=>{const B={};return w.trim()||(B.token=!0),h.trim()||(B.newPassword=!0),E.trim()||(B.confirmPassword=!0),C(B),Object.keys(B).length===0},d=async B=>{if(B.preventDefault(),!!g()){if(!(P!=null&&P.id)){A("Tenant not found");return}v(!0),A(""),$("");try{await z({email:S,tenantId:P.id}),$(M.successMessage),n==null||n()}catch(D){const U=D.message||M.errorMessage;A(U),l==null||l(U)}finally{v(!1)}}},c=async B=>{if(B.preventDefault(),!!f()){if(h!==E){A(M.passwordMismatchError),C({confirmPassword:!0});return}v(!0),A(""),$("");try{await x({token:w,newPassword:h}),$(M.resetSuccessMessage),n==null||n()}catch(D){const U=D.message||M.errorMessage;A(U),l==null||l(U)}finally{v(!1)}}},y=B=>({...o.input,...V[B]?o.inputError:{}}),O=()=>({...o.button,...N?o.buttonLoading:{}});if(t==="reset"){const B=w&&h&&E;return r.jsxs("div",{className:j,style:o.container,children:[r.jsx("h2",{style:o.title,children:M.resetTitle}),r.jsx("p",{style:o.subtitle,children:M.resetSubtitle}),r.jsxs("form",{onSubmit:c,style:o.form,children:[r.jsxs("div",{style:o.fieldGroup,children:[r.jsx("label",{style:o.label,children:M.tokenLabel}),r.jsx("input",{type:"text",value:w,onChange:D=>{m(D.target.value),V.token&&C(U=>({...U,token:!1}))},placeholder:M.tokenPlaceholder,style:y("token"),disabled:N})]}),r.jsxs("div",{style:o.fieldGroup,children:[r.jsx("label",{style:o.label,children:M.newPasswordLabel}),r.jsx("input",{type:"password",value:h,onChange:D=>{b(D.target.value),V.newPassword&&C(U=>({...U,newPassword:!1}))},placeholder:M.newPasswordPlaceholder,style:y("newPassword"),disabled:N})]}),r.jsxs("div",{style:o.fieldGroup,children:[r.jsx("label",{style:o.label,children:M.confirmPasswordLabel}),r.jsx("input",{type:"password",value:E,onChange:D=>{F(D.target.value),V.confirmPassword&&C(U=>({...U,confirmPassword:!1})),u===M.passwordMismatchError&&A("")},placeholder:M.confirmPasswordPlaceholder,style:y("confirmPassword"),disabled:N})]}),r.jsx("button",{type:"submit",disabled:!B||N,style:{...O(),...!B||N?o.buttonDisabled:{}},children:N?M.resetLoadingText:M.resetSubmitButton}),u&&r.jsx("div",{style:o.errorText,children:u}),I&&r.jsx("div",{style:o.successText,children:I})]}),r.jsxs("div",{style:o.linkContainer,children:[r.jsx("a",{onClick:p,style:o.link,children:M.backToLoginLink}),T&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),r.jsx("a",{onClick:()=>T("request"),style:o.link,children:"Request New Link"})]})]})]})}const Q=S;return r.jsxs("div",{className:j,style:o.container,children:[r.jsx("h2",{style:o.title,children:M.title}),r.jsx("p",{style:o.subtitle,children:M.subtitle}),r.jsxs("form",{onSubmit:d,style:o.form,children:[r.jsxs("div",{style:o.fieldGroup,children:[r.jsx("label",{style:o.label,children:M.emailLabel}),r.jsx("input",{type:"email",value:S,onChange:B=>{k(B.target.value),V.email&&C(D=>({...D,email:!1}))},placeholder:M.emailPlaceholder,style:y("email"),disabled:N})]}),r.jsx("button",{type:"submit",disabled:!Q||N,style:{...O(),...!Q||N?o.buttonDisabled:{}},children:N?M.loadingText:M.submitButton}),u&&r.jsx("div",{style:o.errorText,children:u}),I&&r.jsx("div",{style:o.successText,children:I})]}),r.jsxs("div",{style:o.linkContainer,children:[r.jsx("a",{onClick:p,style:o.link,children:M.backToLoginLink}),T&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),r.jsx("a",{onClick:()=>T("reset"),style:o.link,children:"I have a token"})]})]})]})}class At{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/permissions/${s.toString()?`?${s.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{permissions:l.data,meta:l.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:s})).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 s=new URLSearchParams;t!=null&&t.page&&s.append("page",t.page.toString()),t!=null&&t.limit&&s.append("limit",t.limit.toString()),t!=null&&t.sortBy&&s.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&s.append("sortOrder",t.sortOrder);const n=`/permissions/apps/${e}${s.toString()?`?${s.toString()}`:""}`,l=await this.httpService.get(n);return{permissions:l.data,meta:l.meta}}}class Pt{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder),e!=null&&e.appId&&s.append("appId",e.appId);const n=`/subscription-plans/${s.toString()?`?${s.toString()}`:""}`,l=await this.httpService.get(n,{headers:t});return{plans:l.data,meta:l.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:s})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class Tt{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class Mt{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(([s,n])=>{n!=null&&n!==""&&t.append(s,String(n))}),t}}exports.ApiMappers=Mt;exports.AppApiService=ue;exports.AppProvider=$e;exports.AuthApiService=ye;exports.AuthProvider=ze;exports.FeatureFlag=st;exports.FeatureFlagApiService=Se;exports.FeatureFlagProvider=Oe;exports.HealthApiService=Tt;exports.HttpService=X;exports.LandingRoute=Ze;exports.LoginForm=ct;exports.MagicLinkForm=ft;exports.MagicLinkVerify=St;exports.PasswordRecoveryForm=kt;exports.PermissionApiService=At;exports.Protected=Ge;exports.ProtectedRoute=Je;exports.RoleApiService=he;exports.SessionManager=ce;exports.SignupForm=ht;exports.SubscriptionApiService=ke;exports.SubscriptionGuard=tt;exports.SubscriptionPlanApiService=Pt;exports.SubscriptionProvider=Ve;exports.TenantApiService=ne;exports.TenantProvider=Be;exports.TenantRoute=Qe;exports.UserApiService=xe;exports.UserType=ee;exports.useApi=De;exports.useApp=ie;exports.useAuth=te;exports.useFeatureFlags=je;exports.useSettings=qe;exports.useSubscription=Pe;exports.useTenant=oe;exports.useTenantInfo=Z;exports.useTenantSettings=Ue;
|
|
6
|
+
`}),r.jsx("h1",{style:u.title,children:v.title}),z()]})}const vt={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"},jt={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 kt({copy:i={},styles:e={},mode:t="request",token:s="",onSuccess:n,onError:o,onBackToLogin:p,onModeChange:T,className:j}){const[S,k]=a.useState(""),[w,f]=a.useState(s),[h,b]=a.useState(""),[E,F]=a.useState(""),[N,v]=a.useState(!1),[u,A]=a.useState(""),[I,$]=a.useState(""),[O,C]=a.useState({}),{requestPasswordReset:z,confirmPasswordReset:x}=te(),{tenant:P}=Z(),M={...vt,...i},l={...jt,...e},g=()=>{const B={};return S.trim()||(B.email=!0),C(B),Object.keys(B).length===0},m=()=>{const B={};return w.trim()||(B.token=!0),h.trim()||(B.newPassword=!0),E.trim()||(B.confirmPassword=!0),C(B),Object.keys(B).length===0},c=async B=>{if(B.preventDefault(),!!g()){if(!(P!=null&&P.id)){A("Tenant not found");return}v(!0),A(""),$("");try{await z({email:S,tenantId:P.id}),$(M.successMessage),n==null||n()}catch(D){const U=D.message||M.errorMessage;A(U),o==null||o(U)}finally{v(!1)}}},d=async B=>{if(B.preventDefault(),!!m()){if(h!==E){A(M.passwordMismatchError),C({confirmPassword:!0});return}v(!0),A(""),$("");try{await x({token:w,newPassword:h}),$(M.resetSuccessMessage),n==null||n()}catch(D){const U=D.message||M.errorMessage;A(U),o==null||o(U)}finally{v(!1)}}},y=B=>({...l.input,...O[B]?l.inputError:{}}),V=()=>({...l.button,...N?l.buttonLoading:{}});if(t==="reset"){const B=w&&h&&E;return r.jsxs("div",{className:j,style:l.container,children:[r.jsx("h2",{style:l.title,children:M.resetTitle}),r.jsx("p",{style:l.subtitle,children:M.resetSubtitle}),r.jsxs("form",{onSubmit:d,style:l.form,children:[r.jsxs("div",{style:l.fieldGroup,children:[r.jsx("label",{style:l.label,children:M.tokenLabel}),r.jsx("input",{type:"text",value:w,onChange:D=>{f(D.target.value),O.token&&C(U=>({...U,token:!1}))},placeholder:M.tokenPlaceholder,style:y("token"),disabled:N})]}),r.jsxs("div",{style:l.fieldGroup,children:[r.jsx("label",{style:l.label,children:M.newPasswordLabel}),r.jsx("input",{type:"password",value:h,onChange:D=>{b(D.target.value),O.newPassword&&C(U=>({...U,newPassword:!1}))},placeholder:M.newPasswordPlaceholder,style:y("newPassword"),disabled:N})]}),r.jsxs("div",{style:l.fieldGroup,children:[r.jsx("label",{style:l.label,children:M.confirmPasswordLabel}),r.jsx("input",{type:"password",value:E,onChange:D=>{F(D.target.value),O.confirmPassword&&C(U=>({...U,confirmPassword:!1})),u===M.passwordMismatchError&&A("")},placeholder:M.confirmPasswordPlaceholder,style:y("confirmPassword"),disabled:N})]}),r.jsx("button",{type:"submit",disabled:!B||N,style:{...V(),...!B||N?l.buttonDisabled:{}},children:N?M.resetLoadingText:M.resetSubmitButton}),u&&r.jsx("div",{style:l.errorText,children:u}),I&&r.jsx("div",{style:l.successText,children:I})]}),r.jsxs("div",{style:l.linkContainer,children:[r.jsx("a",{onClick:p,style:l.link,children:M.backToLoginLink}),T&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),r.jsx("a",{onClick:()=>T("request"),style:l.link,children:"Request New Link"})]})]})]})}const Q=S;return r.jsxs("div",{className:j,style:l.container,children:[r.jsx("h2",{style:l.title,children:M.title}),r.jsx("p",{style:l.subtitle,children:M.subtitle}),r.jsxs("form",{onSubmit:c,style:l.form,children:[r.jsxs("div",{style:l.fieldGroup,children:[r.jsx("label",{style:l.label,children:M.emailLabel}),r.jsx("input",{type:"email",value:S,onChange:B=>{k(B.target.value),O.email&&C(D=>({...D,email:!1}))},placeholder:M.emailPlaceholder,style:y("email"),disabled:N})]}),r.jsx("button",{type:"submit",disabled:!Q||N,style:{...V(),...!Q||N?l.buttonDisabled:{}},children:N?M.loadingText:M.submitButton}),u&&r.jsx("div",{style:l.errorText,children:u}),I&&r.jsx("div",{style:l.successText,children:I})]}),r.jsxs("div",{style:l.linkContainer,children:[r.jsx("a",{onClick:p,style:l.link,children:M.backToLoginLink}),T&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),r.jsx("a",{onClick:()=>T("reset"),style:l.link,children:"I have a token"})]})]})]})}class At{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/permissions/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:s})).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 s=new URLSearchParams;t!=null&&t.page&&s.append("page",t.page.toString()),t!=null&&t.limit&&s.append("limit",t.limit.toString()),t!=null&&t.sortBy&&s.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&s.append("sortOrder",t.sortOrder);const n=`/permissions/apps/${e}${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n);return{permissions:o.data,meta:o.meta}}}class Pt{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder),e!=null&&e.appId&&s.append("appId",e.appId);const n=`/subscription-plans/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:s})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class Tt{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class Mt{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(([s,n])=>{n!=null&&n!==""&&t.append(s,String(n))}),t}}exports.ApiMappers=Mt;exports.AppApiService=ue;exports.AppProvider=$e;exports.AuthApiService=ye;exports.AuthProvider=ze;exports.FeatureFlag=st;exports.FeatureFlagApiService=Se;exports.FeatureFlagProvider=Oe;exports.HealthApiService=Tt;exports.HttpService=X;exports.LandingRoute=Ze;exports.LoginForm=ct;exports.MagicLinkForm=ft;exports.MagicLinkVerify=St;exports.PasswordRecoveryForm=kt;exports.PermissionApiService=At;exports.Protected=Ge;exports.ProtectedRoute=Je;exports.RoleApiService=he;exports.SessionManager=ce;exports.SignupForm=ht;exports.SubscriptionApiService=ke;exports.SubscriptionGuard=tt;exports.SubscriptionPlanApiService=Pt;exports.SubscriptionProvider=Ve;exports.TenantApiService=ne;exports.TenantProvider=Be;exports.TenantRoute=Qe;exports.UserApiService=xe;exports.UserType=ee;exports.useApi=De;exports.useApp=ie;exports.useAuth=te;exports.useFeatureFlags=je;exports.useSettings=qe;exports.useSubscription=Pe;exports.useTenant=oe;exports.useTenantInfo=Z;exports.useTenantSettings=Ue;
|
|
7
7
|
//# sourceMappingURL=index.js.map
|