@saas-support/react 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class d extends Error{constructor(t,e,s="unknown"){super(e),this.name="SaaSError",this.code=t,this.domain=s}get isNotFound(){return this.code===404}get isUnauthorized(){return this.code===401}get isForbidden(){return this.code===403}get isConflict(){return this.code===409}get isRateLimited(){return this.code===429}}class y{constructor(t,e){this.onUnauthorized=null,this.baseUrl=t,this.authMode=e}setUnauthorizedHandler(t){this.onUnauthorized=t}async request(t,e,s,r){try{return await this.doRequest(t,e,s,r)}catch(i){if(i instanceof d&&i.isUnauthorized&&this.onUnauthorized&&(r!=null&&r.Authorization)){const n=await this.onUnauthorized();if(n)return this.doRequest(t,e,s,{...r,Authorization:`Bearer ${n}`})}throw i}}async get(t,e){return this.request("GET",t,void 0,e)}async post(t,e,s){return this.request("POST",t,e,s)}async patch(t,e,s){return this.request("PATCH",t,e,s)}async del(t,e){return this.request("DELETE",t,void 0,e)}async uploadBinary(t,e,s){try{return await this.doUploadBinary(t,e,s)}catch(r){if(r instanceof d&&r.isUnauthorized&&this.onUnauthorized&&(s!=null&&s.Authorization)){const i=await this.onUnauthorized();if(i)return this.doUploadBinary(t,e,{...s,Authorization:`Bearer ${i}`})}throw r}}async doUploadBinary(t,e,s){const r={"Content-Type":"application/octet-stream",...this.getAuthHeaders(),...s},i=await fetch(`${this.baseUrl}${t}`,{method:"POST",headers:r,body:e}),n=await i.json();if(!i.ok||n.isOk===!1||n.code&&n.code>=400){const a=this.inferDomain(t),c=n.code||i.status;throw new d(c,n.message||"Upload failed",a)}return n.data}async doRequest(t,e,s,r){const i={"Content-Type":"application/json",...this.getAuthHeaders(),...r},n=await fetch(`${this.baseUrl}${e}`,{method:t,headers:i,body:s?JSON.stringify(s):void 0}),a=await n.json();if(!n.ok||a.isOk===!1||a.code&&a.code>=400){const c=this.inferDomain(e),h=a.code||n.status;throw new d(h,a.message||"Request failed",c)}return a.data}getAuthHeaders(){switch(this.authMode.type){case"publishableKey":case"apiKey":return{"X-API-Key":this.authMode.key};case"portalToken":case"embedToken":return{Authorization:`Bearer ${this.authMode.token}`}}}inferDomain(t){return t.startsWith("/auth")?"auth":t.startsWith("/billing")?"billing":t.startsWith("/report")?"report":"unknown"}}class ${constructor(t){this.accessToken=null,this.refreshToken=null,this.refreshTimer=null,this.refreshInFlight=null,this.onRefreshNeeded=null,this.onTokensChanged=null,this.boundHandleStorage=null,this.storageKey=`ss_rt_${t.slice(0,12)}`,this.refreshToken=this.loadRefreshToken(),typeof window<"u"&&(this.boundHandleStorage=this.handleStorageEvent.bind(this),window.addEventListener("storage",this.boundHandleStorage))}setRefreshCallback(t){this.onRefreshNeeded=t}setTokensChangedCallback(t){this.onTokensChanged=t}getAccessToken(){return this.accessToken}getRefreshToken(){return this.refreshToken}hasRefreshToken(){return this.refreshToken!==null}setTokens(t,e){this.accessToken=t,this.refreshToken=e,this.saveRefreshToken(e),this.scheduleRefresh(t)}clearTokens(){this.accessToken=null,this.refreshToken=null,this.removeRefreshToken(),this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}async refreshOnce(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.executeRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}destroy(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),typeof window<"u"&&this.boundHandleStorage&&(window.removeEventListener("storage",this.boundHandleStorage),this.boundHandleStorage=null)}async executeRefresh(){if(!this.onRefreshNeeded)throw new Error("No refresh callback configured");typeof navigator<"u"&&"locks"in navigator?await navigator.locks.request(`ss_refresh_lock_${this.storageKey}`,async()=>{const t=this.loadRefreshToken();t&&t!==this.refreshToken&&(this.refreshToken=t),await this.onRefreshNeeded()}):await this.onRefreshNeeded()}scheduleRefresh(t){this.refreshTimer&&clearTimeout(this.refreshTimer);const e=this.getTokenExpiry(t);if(!e)return;const s=e*1e3-Date.now()-6e4;if(s<=0){this.refreshOnce().catch(()=>{});return}this.refreshTimer=setTimeout(()=>{this.refreshOnce().catch(()=>{})},s)}handleStorageEvent(t){var e;if(t.key===this.storageKey){if(t.newValue===null){this.accessToken=null,this.refreshToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),(e=this.onTokensChanged)==null||e.call(this);return}t.newValue!==this.refreshToken&&(this.refreshToken=t.newValue,this.accessToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null))}}getTokenExpiry(t){try{const e=t.split(".")[1];return JSON.parse(atob(e)).exp??null}catch{return null}}loadRefreshToken(){try{return localStorage.getItem(this.storageKey)}catch{return null}}saveRefreshToken(t){try{localStorage.setItem(this.storageKey,t)}catch{}}removeRefreshToken(){try{localStorage.removeItem(this.storageKey)}catch{}}}class R{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>{var s;(s=this.listeners.get(t))==null||s.delete(e)}}emit(t,e){var s;(s=this.listeners.get(t))==null||s.forEach(r=>r(e))}removeAll(){this.listeners.clear()}}const w=500,T=600,v=5*60*1e3;class b{constructor(t,e,s,r){this.cachedUser=null,this.cachedSettings=null,this.loaded=!1,this.transport=t,this.tokenManager=e,this.emitter=s,this.baseUrl=r}async load(){var t,e;if(!this.loaded){try{this.cachedSettings=await this.transport.get("/auth/settings")}catch(s){console.warn("[SaaS Support] Failed to load project settings:",s)}if((t=this.tokenManager)!=null&&t.hasRefreshToken())try{await this.performRefresh()}catch{(e=this.tokenManager)==null||e.clearTokens()}this.loaded=!0}}async signIn(t,e){const s=await this.transport.post("/auth/login",{email:t,password:e});if("mfaRequired"in s&&s.mfaRequired)return s;const r=s;return this.setSession(r),r}async signUp(t,e){const s=await this.transport.post("/auth/register",{email:t,password:e});return this.setSession(s),s}async signOut(){var e;const t=(e=this.tokenManager)==null?void 0:e.getRefreshToken();if(t)try{await this.transport.post("/auth/logout",{refreshToken:t})}catch{}this.clearSession()}async signInWithOAuth(t){const e=`${this.baseUrl}/auth/oauth/${t}/popup-callback`,{authUrl:s,state:r}=await this.transport.get(`/auth/oauth/${t}?redirect_uri=${encodeURIComponent(e)}`),i=window.screenX+(window.innerWidth-w)/2,n=window.screenY+(window.innerHeight-T)/2,a=window.open(s,"saas-support-oauth",`width=${w},height=${T},left=${i},top=${n},toolbar=no,menubar=no`);return new Promise((c,h)=>{let u=!1;const g=async l=>{var k;if(((k=l.data)==null?void 0:k.type)==="saas-support:oauth-callback"&&!u){if(u=!0,window.removeEventListener("message",g),clearTimeout(m),clearInterval(f),a==null||a.close(),l.data.error){h(new Error(`OAuth error: ${l.data.error}`));return}try{const p=await this.transport.post(`/auth/oauth/${t}/callback`,{code:l.data.code,state:l.data.state||r});this.setSession(p),c(p)}catch(p){h(p)}}};window.addEventListener("message",g);const m=setTimeout(()=>{u||(u=!0,window.removeEventListener("message",g),clearInterval(f),a==null||a.close(),h(new Error("OAuth popup timed out")))},v),f=setInterval(()=>{a!=null&&a.closed&&!u&&(u=!0,clearInterval(f),clearTimeout(m),window.removeEventListener("message",g),h(new Error("OAuth popup was closed")))},500)})}async submitMfaCode(t,e){const s=await this.transport.post("/auth/login/mfa",{mfaToken:t,code:e});return this.setSession(s),s}async sendMagicLink(t,e){await this.transport.post("/auth/magic-link/send",{email:t,redirectUrl:e})}async verifyMagicLink(t){const e=await this.transport.post("/auth/magic-link/verify",{token:t});return this.setSession(e),e}async sendPasswordReset(t,e){await this.transport.post("/auth/password-reset/send",{email:t,redirectUrl:e})}async resetPassword(t,e){await this.transport.post("/auth/password-reset/verify",{token:t,newPassword:e})}async setupMfa(){return this.transport.post("/auth/mfa/setup",void 0,this.authHeaders())}async verifyMfa(t){return this.transport.post("/auth/mfa/verify",{code:t},this.authHeaders())}async disableMfa(t){await this.transport.post("/auth/mfa/disable",{code:t},this.authHeaders())}async getToken(){var e,s,r;const t=((e=this.tokenManager)==null?void 0:e.getAccessToken())??null;if(t)return t;if((s=this.tokenManager)!=null&&s.hasRefreshToken())try{return await this.tokenManager.refreshOnce(),((r=this.tokenManager)==null?void 0:r.getAccessToken())??null}catch{return this.clearSession(),null}return null}async getUser(){if(this.cachedUser)return this.cachedUser;const t=await this.getToken();if(!t)return null;try{return this.cachedUser=await this.transport.get("/auth/me",{Authorization:`Bearer ${t}`}),this.cachedUser}catch{return null}}getUserSync(){return this.cachedUser}isLoaded(){return this.loaded}async getSettings(){if(this.cachedSettings)return this.cachedSettings;try{return this.cachedSettings=await this.transport.get("/auth/settings"),this.cachedSettings}catch{return null}}onAuthStateChange(t){return this.emitter.on("authStateChange",t)}async updateProfile(t){const e=await this.transport.patch("/auth/me",t,this.authHeaders());return this.cachedUser=e,this.emitter.emit("authStateChange",e),e}async uploadAvatar(t){const e=await this.transport.uploadBinary("/auth/avatar",t,this.authHeaders());return this.cachedUser&&(this.cachedUser={...this.cachedUser,avatarUrl:e.avatarUrl},this.emitter.emit("authStateChange",this.cachedUser)),e}async changePassword(t,e){await this.transport.post("/auth/change-password",{currentPassword:t,newPassword:e},this.authHeaders())}async listOrgs(){return this.transport.get("/auth/orgs",this.authHeaders())}async createOrg(t,e){return this.transport.post("/auth/orgs",{name:t,slug:e},this.authHeaders())}async getOrg(t){return this.transport.get(`/auth/orgs/${t}`,this.authHeaders())}async updateOrg(t,e){return this.transport.patch(`/auth/orgs/${t}`,e,this.authHeaders())}async deleteOrg(t){await this.transport.del(`/auth/orgs/${t}`,this.authHeaders())}async listMembers(t){return this.transport.get(`/auth/orgs/${t}/members`,this.authHeaders())}async sendInvite(t,e,s){return this.transport.post(`/auth/orgs/${t}/invites`,{email:e,role:s},this.authHeaders())}async updateMemberRole(t,e,s){await this.transport.patch(`/auth/orgs/${t}/members/${e}`,{role:s},this.authHeaders())}async removeMember(t,e){await this.transport.del(`/auth/orgs/${t}/members/${e}`,this.authHeaders())}async acceptInvite(t){return this.transport.post(`/auth/invites/${t}/accept`,void 0,this.authHeaders())}async listInvites(t){return this.transport.get(`/auth/orgs/${t}/invites`,this.authHeaders())}async revokeInvite(t,e){await this.transport.del(`/auth/orgs/${t}/invites/${e}`,this.authHeaders())}async deleteAccount(){await this.transport.del("/auth/account",this.authHeaders()),this.clearSession()}handleExternalLogout(){this.cachedUser=null,this.emitter.emit("authStateChange",null)}async performRefresh(){var s;const t=(s=this.tokenManager)==null?void 0:s.getRefreshToken();if(!t)throw new Error("No refresh token");const e=await this.transport.post("/auth/refresh",{refreshToken:t});if(this.tokenManager.setTokens(e.accessToken,e.refreshToken),!this.cachedUser)try{this.cachedUser=await this.transport.get("/auth/me",{Authorization:`Bearer ${e.accessToken}`}),this.emitter.emit("authStateChange",this.cachedUser)}catch{}}setSession(t){var e;(e=this.tokenManager)==null||e.setTokens(t.accessToken,t.refreshToken),this.cachedUser=t.user,this.emitter.emit("authStateChange",t.user)}clearSession(){var t;(t=this.tokenManager)==null||t.clearTokens(),this.cachedUser=null,this.emitter.emit("authStateChange",null)}authHeaders(){var e;const t=(e=this.tokenManager)==null?void 0:e.getAccessToken();return t?{Authorization:`Bearer ${t}`}:{}}}class S{constructor(t){this.transport=t}async createCustomer(t){return this.transport.post("/billing/customers",t)}async getCustomer(t){return this.transport.get(`/billing/customers/${t}`)}async updateCustomer(t,e){return this.transport.patch(`/billing/customers/${t}`,e)}async subscribe(t,e){return this.transport.post(`/billing/customers/${t}/subscribe`,{planId:e})}async changePlan(t,e){return this.transport.patch(`/billing/customers/${t}/subscription`,{planId:e})}async cancelSubscription(t){return this.transport.del(`/billing/customers/${t}/subscription`)}async getInvoices(t){return this.transport.get(`/billing/customers/${t}/invoices`)}async ingestUsageEvent(t){return this.transport.post("/billing/events",t)}async getCurrentUsage(t){return this.transport.get(`/billing/customers/${t}/usage`)}async createPortalToken(t,e){return this.transport.post("/billing/portal-tokens",{customerId:t,expiresIn:e})}async applyCoupon(t,e){return this.transport.post(`/billing/customers/${t}/coupon`,{code:e})}}class U{constructor(t){this.transport=t}async executeQuery(t){return this.transport.post("/report/query",t)}async listQueries(t){const e=t?this.toQueryString(t):"";return this.transport.get(`/report/queries${e}`)}async saveQuery(t){return this.transport.post("/report/queries",t)}async updateQuery(t,e){return this.transport.patch(`/report/queries/${t}`,e)}async deleteQuery(t){await this.transport.del(`/report/queries/${t}`)}async listDashboards(t){const e=t?this.toQueryString(t):"";return this.transport.get(`/report/dashboards${e}`)}async createDashboard(t){return this.transport.post("/report/dashboards",t)}async getDashboard(t){return this.transport.get(`/report/dashboards/${t}`)}async updateDashboard(t,e){return this.transport.patch(`/report/dashboards/${t}`,e)}async deleteDashboard(t){await this.transport.del(`/report/dashboards/${t}`)}async createEmbedToken(t){return this.transport.post("/report/embed-tokens",t)}async listEmbedTokens(){return this.transport.get("/report/embed-tokens")}async revokeEmbedToken(t){await this.transport.del(`/report/embed-tokens/${t}`)}toQueryString(t){const e=Object.entries(t).filter(([,s])=>s!=null&&s!=="");return e.length===0?"":"?"+e.map(([s,r])=>`${s}=${encodeURIComponent(String(r))}`).join("&")}}const M="https://api.saas-support.com/v1";class H{constructor(t){if(this.tokenManager=null,this.loaded=!1,!t.publishableKey&&!t.apiKey)throw new Error("SaaSSupport: either publishableKey or apiKey is required");const e=t.baseUrl??M;this.emitter=new R;const s=t.publishableKey?new y(e,{type:"publishableKey",key:t.publishableKey}):null,r=t.apiKey?new y(e,{type:"apiKey",key:t.apiKey}):null;t.publishableKey&&(this.tokenManager=new $(t.publishableKey)),this.auth=new b(s??r,this.tokenManager,this.emitter,e),this.billing=new S(r??s),this.report=new U(r??s),this.tokenManager&&(this.tokenManager.setRefreshCallback(()=>this.auth.performRefresh()),this.tokenManager.setTokensChangedCallback(()=>{this.tokenManager.hasRefreshToken()||this.auth.handleExternalLogout()})),this.tokenManager&&s&&s.setUnauthorizedHandler(async()=>{try{return await this.tokenManager.refreshOnce(),this.tokenManager.getAccessToken()}catch{return null}})}async load(){this.loaded||(await this.auth.load(),this.loaded=!0)}isLoaded(){return this.loaded}onError(t){return this.emitter.on("error",t)}destroy(){var t;(t=this.tokenManager)==null||t.destroy(),this.emitter.removeAll()}}function E(o){return"mfaRequired"in o&&o.mfaRequired===!0}exports.AuthClient=b;exports.BillingClient=S;exports.ReportClient=U;exports.SaaSError=d;exports.SaaSSupport=H;exports.Transport=y;exports.isMfaRequired=E;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class d extends Error{constructor(t,e,s="unknown"){super(e),this.name="SaaSError",this.code=t,this.domain=s}get isNotFound(){return this.code===404}get isUnauthorized(){return this.code===401}get isForbidden(){return this.code===403}get isConflict(){return this.code===409}get isRateLimited(){return this.code===429}}class y{constructor(t,e){this.onUnauthorized=null,this.baseUrl=t,this.authMode=e}setUnauthorizedHandler(t){this.onUnauthorized=t}async request(t,e,s,r){try{return await this.doRequest(t,e,s,r)}catch(i){if(i instanceof d&&i.isUnauthorized&&this.onUnauthorized&&(r!=null&&r.Authorization)){const n=await this.onUnauthorized();if(n)return this.doRequest(t,e,s,{...r,Authorization:`Bearer ${n}`})}throw i}}async get(t,e){return this.request("GET",t,void 0,e)}async post(t,e,s){return this.request("POST",t,e,s)}async patch(t,e,s){return this.request("PATCH",t,e,s)}async del(t,e){return this.request("DELETE",t,void 0,e)}async uploadBinary(t,e,s){try{return await this.doUploadBinary(t,e,s)}catch(r){if(r instanceof d&&r.isUnauthorized&&this.onUnauthorized&&(s!=null&&s.Authorization)){const i=await this.onUnauthorized();if(i)return this.doUploadBinary(t,e,{...s,Authorization:`Bearer ${i}`})}throw r}}async doUploadBinary(t,e,s){const r={"Content-Type":"application/octet-stream",...this.getAuthHeaders(),...s},i=await fetch(`${this.baseUrl}${t}`,{method:"POST",headers:r,body:e}),n=await i.json();if(!i.ok||n.isOk===!1||n.code&&n.code>=400){const a=this.inferDomain(t),u=n.code||i.status;throw new d(u,n.message||"Upload failed",a)}return n.data}async doRequest(t,e,s,r){const i={"Content-Type":"application/json",...this.getAuthHeaders(),...r},n=await fetch(`${this.baseUrl}${e}`,{method:t,headers:i,body:s?JSON.stringify(s):void 0}),a=await n.json();if(!n.ok||a.isOk===!1||a.code&&a.code>=400){const u=this.inferDomain(e),h=a.code||n.status;throw new d(h,a.message||"Request failed",u)}return a.data}getAuthHeaders(){switch(this.authMode.type){case"publishableKey":case"apiKey":return{"X-API-Key":this.authMode.key};case"portalToken":case"embedToken":return{Authorization:`Bearer ${this.authMode.token}`}}}inferDomain(t){return t.startsWith("/auth")?"auth":t.startsWith("/billing")?"billing":t.startsWith("/report")?"report":"unknown"}}class ${constructor(t){this.accessToken=null,this.refreshToken=null,this.refreshTimer=null,this.refreshInFlight=null,this.onRefreshNeeded=null,this.onTokensChanged=null,this.boundHandleStorage=null,this.storageKey=`ss_rt_${t.slice(0,12)}`,this.refreshToken=this.loadRefreshToken(),typeof window<"u"&&(this.boundHandleStorage=this.handleStorageEvent.bind(this),window.addEventListener("storage",this.boundHandleStorage))}setRefreshCallback(t){this.onRefreshNeeded=t}setTokensChangedCallback(t){this.onTokensChanged=t}getAccessToken(){return this.accessToken}getRefreshToken(){return this.refreshToken}hasRefreshToken(){return this.refreshToken!==null}setTokens(t,e){this.accessToken=t,this.refreshToken=e,this.saveRefreshToken(e),this.scheduleRefresh(t)}clearTokens(){this.accessToken=null,this.refreshToken=null,this.removeRefreshToken(),this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}async refreshOnce(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.executeRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}destroy(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),typeof window<"u"&&this.boundHandleStorage&&(window.removeEventListener("storage",this.boundHandleStorage),this.boundHandleStorage=null)}async executeRefresh(){if(!this.onRefreshNeeded)throw new Error("No refresh callback configured");typeof navigator<"u"&&"locks"in navigator?await navigator.locks.request(`ss_refresh_lock_${this.storageKey}`,async()=>{const t=this.loadRefreshToken();t&&t!==this.refreshToken&&(this.refreshToken=t),await this.onRefreshNeeded()}):await this.onRefreshNeeded()}scheduleRefresh(t){this.refreshTimer&&clearTimeout(this.refreshTimer);const e=this.getTokenExpiry(t);if(!e)return;const s=e*1e3-Date.now()-6e4;if(s<=0){this.refreshOnce().catch(()=>{});return}this.refreshTimer=setTimeout(()=>{this.refreshOnce().catch(()=>{})},s)}handleStorageEvent(t){var e;if(t.key===this.storageKey){if(t.newValue===null){this.accessToken=null,this.refreshToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),(e=this.onTokensChanged)==null||e.call(this);return}t.newValue!==this.refreshToken&&(this.refreshToken=t.newValue,this.accessToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null))}}getTokenExpiry(t){try{const e=t.split(".")[1];return JSON.parse(atob(e)).exp??null}catch{return null}}loadRefreshToken(){try{return localStorage.getItem(this.storageKey)}catch{return null}}saveRefreshToken(t){try{localStorage.setItem(this.storageKey,t)}catch{}}removeRefreshToken(){try{localStorage.removeItem(this.storageKey)}catch{}}}class R{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>{var s;(s=this.listeners.get(t))==null||s.delete(e)}}emit(t,e){var s;(s=this.listeners.get(t))==null||s.forEach(r=>r(e))}removeAll(){this.listeners.clear()}}const w=500,T=600,v=5*60*1e3;class b{constructor(t,e,s,r){this.cachedUser=null,this.cachedSettings=null,this.loaded=!1,this.transport=t,this.tokenManager=e,this.emitter=s,this.baseUrl=r}async load(){var t,e;if(!this.loaded){try{this.cachedSettings=await this.transport.get("/auth/settings")}catch(s){console.warn("[SaaS Support] Failed to load project settings:",s)}if((t=this.tokenManager)!=null&&t.hasRefreshToken())try{await this.performRefresh()}catch{(e=this.tokenManager)==null||e.clearTokens()}this.loaded=!0}}async signIn(t,e){const s=await this.transport.post("/auth/login",{email:t,password:e});if("mfaRequired"in s&&s.mfaRequired)return s;const r=s;return this.setSession(r),r}async signUp(t,e){const s=await this.transport.post("/auth/register",{email:t,password:e});return this.setSession(s),s}async signOut(){var e;const t=(e=this.tokenManager)==null?void 0:e.getRefreshToken();if(t)try{await this.transport.post("/auth/logout",{refreshToken:t})}catch{}this.clearSession()}async signInWithOAuth(t){const e=`${this.baseUrl}/auth/oauth/${t}/popup-callback`,{authUrl:s,state:r}=await this.transport.get(`/auth/oauth/${t}?redirect_uri=${encodeURIComponent(e)}`),i=window.screenX+(window.innerWidth-w)/2,n=window.screenY+(window.innerHeight-T)/2,a=window.open(s,"saas-support-oauth",`width=${w},height=${T},left=${i},top=${n},toolbar=no,menubar=no`);return new Promise((u,h)=>{let c=!1;const g=async l=>{var k;if(((k=l.data)==null?void 0:k.type)==="saas-support:oauth-callback"&&!c){if(c=!0,window.removeEventListener("message",g),clearTimeout(m),clearInterval(f),a==null||a.close(),l.data.error){h(new Error(`OAuth error: ${l.data.error}`));return}try{const p=await this.transport.post(`/auth/oauth/${t}/callback`,{code:l.data.code,state:l.data.state||r});this.setSession(p),u(p)}catch(p){h(p)}}};window.addEventListener("message",g);const m=setTimeout(()=>{c||(c=!0,window.removeEventListener("message",g),clearInterval(f),a==null||a.close(),h(new Error("OAuth popup timed out")))},v),f=setInterval(()=>{a!=null&&a.closed&&!c&&(c=!0,clearInterval(f),clearTimeout(m),window.removeEventListener("message",g),h(new Error("OAuth popup was closed")))},500)})}async submitMfaCode(t,e){const s=await this.transport.post("/auth/login/mfa",{mfaToken:t,code:e});return this.setSession(s),s}async sendMagicLink(t,e){await this.transport.post("/auth/magic-link/send",{email:t,redirectUrl:e})}async verifyMagicLink(t){const e=await this.transport.post("/auth/magic-link/verify",{token:t});return this.setSession(e),e}async sendPasswordReset(t,e){await this.transport.post("/auth/password-reset/send",{email:t,redirectUrl:e})}async resetPassword(t,e){await this.transport.post("/auth/password-reset/verify",{token:t,newPassword:e})}async setupMfa(){return this.transport.post("/auth/mfa/setup",void 0,this.authHeaders())}async verifyMfa(t){return this.transport.post("/auth/mfa/verify",{code:t},this.authHeaders())}async disableMfa(t){await this.transport.post("/auth/mfa/disable",{code:t},this.authHeaders())}async getToken(){var e,s,r;const t=((e=this.tokenManager)==null?void 0:e.getAccessToken())??null;if(t)return t;if((s=this.tokenManager)!=null&&s.hasRefreshToken())try{return await this.tokenManager.refreshOnce(),((r=this.tokenManager)==null?void 0:r.getAccessToken())??null}catch{return this.clearSession(),null}return null}async getUser(){if(this.cachedUser)return this.cachedUser;const t=await this.getToken();if(!t)return null;try{return this.cachedUser=await this.transport.get("/auth/me",{Authorization:`Bearer ${t}`}),this.cachedUser}catch{return null}}async refreshUser(){const t=await this.getToken();if(!t)return this.cachedUser;try{return this.cachedUser=await this.transport.get("/auth/me",{Authorization:`Bearer ${t}`}),this.emitter.emit("authStateChange",this.cachedUser),this.cachedUser}catch{return this.cachedUser}}getUserSync(){return this.cachedUser}isLoaded(){return this.loaded}async getSettings(){if(this.cachedSettings)return this.cachedSettings;try{return this.cachedSettings=await this.transport.get("/auth/settings"),this.cachedSettings}catch{return null}}onAuthStateChange(t){return this.emitter.on("authStateChange",t)}async updateProfile(t){const e=await this.transport.patch("/auth/me",t,this.authHeaders());return this.cachedUser=e,this.emitter.emit("authStateChange",e),e}async uploadAvatar(t){const e=await this.transport.uploadBinary("/auth/avatar",t,this.authHeaders());return this.cachedUser&&(this.cachedUser={...this.cachedUser,avatarUrl:e.avatarUrl},this.emitter.emit("authStateChange",this.cachedUser)),e}async changePassword(t,e){await this.transport.post("/auth/change-password",{currentPassword:t,newPassword:e},this.authHeaders())}async listOrgs(){return this.transport.get("/auth/orgs",this.authHeaders())}async createOrg(t,e){return this.transport.post("/auth/orgs",{name:t,slug:e},this.authHeaders())}async getOrg(t){return this.transport.get(`/auth/orgs/${t}`,this.authHeaders())}async updateOrg(t,e){return this.transport.patch(`/auth/orgs/${t}`,e,this.authHeaders())}async deleteOrg(t){await this.transport.del(`/auth/orgs/${t}`,this.authHeaders())}async listMembers(t){return this.transport.get(`/auth/orgs/${t}/members`,this.authHeaders())}async sendInvite(t,e,s){return this.transport.post(`/auth/orgs/${t}/invites`,{email:e,role:s},this.authHeaders())}async updateMemberRole(t,e,s){await this.transport.patch(`/auth/orgs/${t}/members/${e}`,{role:s},this.authHeaders())}async removeMember(t,e){await this.transport.del(`/auth/orgs/${t}/members/${e}`,this.authHeaders())}async acceptInvite(t){return this.transport.post(`/auth/invites/${t}/accept`,void 0,this.authHeaders())}async listInvites(t){return this.transport.get(`/auth/orgs/${t}/invites`,this.authHeaders())}async revokeInvite(t,e){await this.transport.del(`/auth/orgs/${t}/invites/${e}`,this.authHeaders())}async deleteAccount(){await this.transport.del("/auth/account",this.authHeaders()),this.clearSession()}handleExternalLogout(){this.cachedUser=null,this.emitter.emit("authStateChange",null)}async performRefresh(){var s;const t=(s=this.tokenManager)==null?void 0:s.getRefreshToken();if(!t)throw new Error("No refresh token");const e=await this.transport.post("/auth/refresh",{refreshToken:t});if(this.tokenManager.setTokens(e.accessToken,e.refreshToken),!this.cachedUser)try{this.cachedUser=await this.transport.get("/auth/me",{Authorization:`Bearer ${e.accessToken}`}),this.emitter.emit("authStateChange",this.cachedUser)}catch{}}setSession(t){var e;(e=this.tokenManager)==null||e.setTokens(t.accessToken,t.refreshToken),this.cachedUser=t.user,this.emitter.emit("authStateChange",t.user),this.refreshUser()}clearSession(){var t;(t=this.tokenManager)==null||t.clearTokens(),this.cachedUser=null,this.emitter.emit("authStateChange",null)}authHeaders(){var e;const t=(e=this.tokenManager)==null?void 0:e.getAccessToken();return t?{Authorization:`Bearer ${t}`}:{}}}class S{constructor(t){this.transport=t}async createCustomer(t){return this.transport.post("/billing/customers",t)}async getCustomer(t){return this.transport.get(`/billing/customers/${t}`)}async updateCustomer(t,e){return this.transport.patch(`/billing/customers/${t}`,e)}async subscribe(t,e){return this.transport.post(`/billing/customers/${t}/subscribe`,{planId:e})}async changePlan(t,e){return this.transport.patch(`/billing/customers/${t}/subscription`,{planId:e})}async cancelSubscription(t){return this.transport.del(`/billing/customers/${t}/subscription`)}async getInvoices(t){return this.transport.get(`/billing/customers/${t}/invoices`)}async ingestUsageEvent(t){return this.transport.post("/billing/events",t)}async getCurrentUsage(t){return this.transport.get(`/billing/customers/${t}/usage`)}async createPortalToken(t,e){return this.transport.post("/billing/portal-tokens",{customerId:t,expiresIn:e})}async applyCoupon(t,e){return this.transport.post(`/billing/customers/${t}/coupon`,{code:e})}}class U{constructor(t){this.transport=t}async executeQuery(t){return this.transport.post("/report/query",t)}async listQueries(t){const e=t?this.toQueryString(t):"";return this.transport.get(`/report/queries${e}`)}async saveQuery(t){return this.transport.post("/report/queries",t)}async updateQuery(t,e){return this.transport.patch(`/report/queries/${t}`,e)}async deleteQuery(t){await this.transport.del(`/report/queries/${t}`)}async listDashboards(t){const e=t?this.toQueryString(t):"";return this.transport.get(`/report/dashboards${e}`)}async createDashboard(t){return this.transport.post("/report/dashboards",t)}async getDashboard(t){return this.transport.get(`/report/dashboards/${t}`)}async updateDashboard(t,e){return this.transport.patch(`/report/dashboards/${t}`,e)}async deleteDashboard(t){await this.transport.del(`/report/dashboards/${t}`)}async createEmbedToken(t){return this.transport.post("/report/embed-tokens",t)}async listEmbedTokens(){return this.transport.get("/report/embed-tokens")}async revokeEmbedToken(t){await this.transport.del(`/report/embed-tokens/${t}`)}toQueryString(t){const e=Object.entries(t).filter(([,s])=>s!=null&&s!=="");return e.length===0?"":"?"+e.map(([s,r])=>`${s}=${encodeURIComponent(String(r))}`).join("&")}}const M="https://api.saas-support.com/v1";class H{constructor(t){if(this.tokenManager=null,this.loaded=!1,!t.publishableKey&&!t.apiKey)throw new Error("SaaSSupport: either publishableKey or apiKey is required");const e=t.baseUrl??M;this.emitter=new R;const s=t.publishableKey?new y(e,{type:"publishableKey",key:t.publishableKey}):null,r=t.apiKey?new y(e,{type:"apiKey",key:t.apiKey}):null;t.publishableKey&&(this.tokenManager=new $(t.publishableKey)),this.auth=new b(s??r,this.tokenManager,this.emitter,e),this.billing=new S(r??s),this.report=new U(r??s),this.tokenManager&&(this.tokenManager.setRefreshCallback(()=>this.auth.performRefresh()),this.tokenManager.setTokensChangedCallback(()=>{this.tokenManager.hasRefreshToken()||this.auth.handleExternalLogout()})),this.tokenManager&&s&&s.setUnauthorizedHandler(async()=>{try{return await this.tokenManager.refreshOnce(),this.tokenManager.getAccessToken()}catch{return null}})}async load(){this.loaded||(await this.auth.load(),this.loaded=!0)}isLoaded(){return this.loaded}onError(t){return this.emitter.on("error",t)}destroy(){var t;(t=this.tokenManager)==null||t.destroy(),this.emitter.removeAll()}}function C(o){return"mfaRequired"in o&&o.mfaRequired===!0}exports.AuthClient=b;exports.BillingClient=S;exports.ReportClient=U;exports.SaaSError=d;exports.SaaSSupport=H;exports.Transport=y;exports.isMfaRequired=C;
package/dist/index.d.ts CHANGED
@@ -37,6 +37,7 @@ export declare class AuthClient {
37
37
  disableMfa(code: string): Promise<void>;
38
38
  getToken(): Promise<string | null>;
39
39
  getUser(): Promise<User | null>;
40
+ refreshUser(): Promise<User | null>;
40
41
  getUserSync(): User | null;
41
42
  isLoaded(): boolean;
42
43
  getSettings(): Promise<ProjectSettings | null>;
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ class p extends Error {
18
18
  return this.code === 429;
19
19
  }
20
20
  }
21
- class m {
21
+ class k {
22
22
  constructor(t, e) {
23
23
  this.onUnauthorized = null, this.baseUrl = t, this.authMode = e;
24
24
  }
@@ -79,8 +79,8 @@ class m {
79
79
  body: e
80
80
  }), n = await i.json();
81
81
  if (!i.ok || n.isOk === !1 || n.code && n.code >= 400) {
82
- const a = this.inferDomain(t), c = n.code || i.status;
83
- throw new p(c, n.message || "Upload failed", a);
82
+ const a = this.inferDomain(t), u = n.code || i.status;
83
+ throw new p(u, n.message || "Upload failed", a);
84
84
  }
85
85
  return n.data;
86
86
  }
@@ -95,8 +95,8 @@ class m {
95
95
  body: s ? JSON.stringify(s) : void 0
96
96
  }), a = await n.json();
97
97
  if (!n.ok || a.isOk === !1 || a.code && a.code >= 400) {
98
- const c = this.inferDomain(e), h = a.code || n.status;
99
- throw new p(h, a.message || "Request failed", c);
98
+ const u = this.inferDomain(e), h = a.code || n.status;
99
+ throw new p(h, a.message || "Request failed", u);
100
100
  }
101
101
  return a.data;
102
102
  }
@@ -215,7 +215,7 @@ class b {
215
215
  }
216
216
  }
217
217
  }
218
- class S {
218
+ class U {
219
219
  constructor() {
220
220
  this.listeners = /* @__PURE__ */ new Map();
221
221
  }
@@ -233,7 +233,7 @@ class S {
233
233
  this.listeners.clear();
234
234
  }
235
235
  }
236
- const w = 500, T = 600, U = 5 * 60 * 1e3;
236
+ const w = 500, T = 600, S = 5 * 60 * 1e3;
237
237
  class $ {
238
238
  constructor(t, e, s, r) {
239
239
  this.cachedUser = null, this.cachedSettings = null, this.loaded = !1, this.transport = t, this.tokenManager = e, this.emitter = s, this.baseUrl = r;
@@ -290,12 +290,12 @@ class $ {
290
290
  "saas-support-oauth",
291
291
  `width=${w},height=${T},left=${i},top=${n},toolbar=no,menubar=no`
292
292
  );
293
- return new Promise((c, h) => {
294
- let u = !1;
293
+ return new Promise((u, h) => {
294
+ let c = !1;
295
295
  const d = async (l) => {
296
- var k;
297
- if (((k = l.data) == null ? void 0 : k.type) === "saas-support:oauth-callback" && !u) {
298
- if (u = !0, window.removeEventListener("message", d), clearTimeout(y), clearInterval(f), a == null || a.close(), l.data.error) {
296
+ var m;
297
+ if (((m = l.data) == null ? void 0 : m.type) === "saas-support:oauth-callback" && !c) {
298
+ if (c = !0, window.removeEventListener("message", d), clearTimeout(y), clearInterval(f), a == null || a.close(), l.data.error) {
299
299
  h(new Error(`OAuth error: ${l.data.error}`));
300
300
  return;
301
301
  }
@@ -304,7 +304,7 @@ class $ {
304
304
  `/auth/oauth/${t}/callback`,
305
305
  { code: l.data.code, state: l.data.state || r }
306
306
  );
307
- this.setSession(g), c(g);
307
+ this.setSession(g), u(g);
308
308
  } catch (g) {
309
309
  h(g);
310
310
  }
@@ -312,9 +312,9 @@ class $ {
312
312
  };
313
313
  window.addEventListener("message", d);
314
314
  const y = setTimeout(() => {
315
- u || (u = !0, window.removeEventListener("message", d), clearInterval(f), a == null || a.close(), h(new Error("OAuth popup timed out")));
316
- }, U), f = setInterval(() => {
317
- a != null && a.closed && !u && (u = !0, clearInterval(f), clearTimeout(y), window.removeEventListener("message", d), h(new Error("OAuth popup was closed")));
315
+ c || (c = !0, window.removeEventListener("message", d), clearInterval(f), a == null || a.close(), h(new Error("OAuth popup timed out")));
316
+ }, S), f = setInterval(() => {
317
+ a != null && a.closed && !c && (c = !0, clearInterval(f), clearTimeout(y), window.removeEventListener("message", d), h(new Error("OAuth popup was closed")));
318
318
  }, 500);
319
319
  });
320
320
  }
@@ -375,6 +375,15 @@ class $ {
375
375
  return null;
376
376
  }
377
377
  }
378
+ async refreshUser() {
379
+ const t = await this.getToken();
380
+ if (!t) return this.cachedUser;
381
+ try {
382
+ return this.cachedUser = await this.transport.get("/auth/me", { Authorization: `Bearer ${t}` }), this.emitter.emit("authStateChange", this.cachedUser), this.cachedUser;
383
+ } catch {
384
+ return this.cachedUser;
385
+ }
386
+ }
378
387
  getUserSync() {
379
388
  return this.cachedUser;
380
389
  }
@@ -475,7 +484,7 @@ class $ {
475
484
  }
476
485
  setSession(t) {
477
486
  var e;
478
- (e = this.tokenManager) == null || e.setTokens(t.accessToken, t.refreshToken), this.cachedUser = t.user, this.emitter.emit("authStateChange", t.user);
487
+ (e = this.tokenManager) == null || e.setTokens(t.accessToken, t.refreshToken), this.cachedUser = t.user, this.emitter.emit("authStateChange", t.user), this.refreshUser();
479
488
  }
480
489
  clearSession() {
481
490
  var t;
@@ -591,8 +600,8 @@ class H {
591
600
  if (this.tokenManager = null, this.loaded = !1, !t.publishableKey && !t.apiKey)
592
601
  throw new Error("SaaSSupport: either publishableKey or apiKey is required");
593
602
  const e = t.baseUrl ?? M;
594
- this.emitter = new S();
595
- const s = t.publishableKey ? new m(e, { type: "publishableKey", key: t.publishableKey }) : null, r = t.apiKey ? new m(e, { type: "apiKey", key: t.apiKey }) : null;
603
+ this.emitter = new U();
604
+ const s = t.publishableKey ? new k(e, { type: "publishableKey", key: t.publishableKey }) : null, r = t.apiKey ? new k(e, { type: "apiKey", key: t.apiKey }) : null;
596
605
  t.publishableKey && (this.tokenManager = new b(t.publishableKey)), this.auth = new $(
597
606
  s ?? r,
598
607
  this.tokenManager,
@@ -631,6 +640,6 @@ export {
631
640
  v as ReportClient,
632
641
  p as SaaSError,
633
642
  H as SaaSSupport,
634
- m as Transport,
643
+ k as Transport,
635
644
  E as isMfaRequired
636
645
  };
package/dist/react.cjs CHANGED
@@ -2040,4 +2040,4 @@
2040
2040
  .ss-auth-signout-row { flex-direction: column; text-align: center; }
2041
2041
  .ss-auth-signout-info { flex-direction: column; }
2042
2042
  }
2043
- `}function M({children:a,appearance:r}){const e=t.useRef(null),[o,n]=t.useState(null);t.useEffect(()=>{var x;if(!e.current||e.current.shadowRoot){n(((x=e.current)==null?void 0:x.shadowRoot)??null);return}const l=e.current.attachShadow({mode:"open"});if((r==null?void 0:r.fontUrl)!==null){const p=(r==null?void 0:r.fontUrl)??"https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Inter:wght@400;500;600&family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap";if(!document.querySelector(`link[href="${p}"]`)){const f=document.createElement("link");f.rel="stylesheet",f.href=p,document.head.appendChild(f)}const g=document.createElement("link");g.rel="stylesheet",g.href=p,l.appendChild(g)}const c=Y(r),d=document.createElement("style");d.textContent=Q(c),l.appendChild(d);const i=document.createElement("div");l.appendChild(i),n(l)},[]),t.useEffect(()=>{if(!o)return;const l=o.querySelector("style");if(l){const c=Y(r);l.textContent=Q(c)}},[r,o]);const u=(o==null?void 0:o.querySelector("div"))??null;return s.jsx("div",{ref:e,style:{display:"contents"},children:u&&vs.createPortal(a,u)})}function H(){const{client:a,user:r,isLoaded:e}=E();return{isLoaded:e,isSignedIn:!!r,user:r,signOut:t.useCallback(()=>a.auth.signOut(),[a]),getToken:t.useCallback(()=>a.auth.getToken(),[a])}}function $s(){const{user:a,isLoaded:r}=E();return{user:a,isLoaded:r}}function Z(){const{client:a}=E(),[r,e]=t.useState(!1),[o,n]=t.useState(null),u=t.useCallback(async(d,i)=>{e(!0),n(null);try{return await a.auth.signIn(d,i)}catch(x){return n(x instanceof Error?x.message:"Sign in failed"),null}finally{e(!1)}},[a]),l=t.useCallback(async d=>{e(!0),n(null);try{return await a.auth.signInWithOAuth(d)}catch(i){return n(i instanceof Error?i.message:"OAuth sign in failed"),null}finally{e(!1)}},[a]),c=t.useCallback(async(d,i)=>{e(!0),n(null);try{return await a.auth.submitMfaCode(d,i)}catch(x){return n(x instanceof Error?x.message:"MFA verification failed"),null}finally{e(!1)}},[a]);return{signIn:u,signInWithOAuth:l,submitMfaCode:c,isLoading:r,error:o,setError:n}}function as(){const{client:a}=E(),[r,e]=t.useState(!1),[o,n]=t.useState(null);return{signUp:t.useCallback(async(l,c)=>{e(!0),n(null);try{return await a.auth.signUp(l,c)}catch(d){return n(d instanceof Error?d.message:"Sign up failed"),null}finally{e(!1)}},[a]),isLoading:r,error:o,setError:n}}function K(){const{client:a}=E(),[r,e]=t.useState([]),[o,n]=t.useState(null),[u,l]=t.useState([]),[c,d]=t.useState([]),[i,x]=t.useState(!1),[p,g]=t.useState(null),f=t.useCallback(async()=>{x(!0),g(null);try{const w=await a.auth.listOrgs();e(w);const m=typeof window<"u"?localStorage.getItem("ss_selected_org"):null;if(m&&w.some(y=>y.id===m)&&!o){const y=w.find(C=>C.id===m);n(y);try{const C=await a.auth.listMembers(y.id);l(C)}catch{}}}catch(w){g(w instanceof Error?w.message:"Failed to load organizations")}finally{x(!1)}},[a,o]);t.useEffect(()=>{f()},[f]);const v=t.useCallback(async w=>{try{const m=await a.auth.getOrg(w);n(m),typeof window<"u"&&localStorage.setItem("ss_selected_org",w);const y=await a.auth.listMembers(w);l(y)}catch(m){g(m instanceof Error?m.message:"Failed to load organization")}},[a]),b=t.useCallback(async(w,m)=>{try{const y=await a.auth.createOrg(w,m);return e(C=>[...C,y]),y}catch(y){return g(y instanceof Error?y.message:"Failed to create organization"),null}},[a]),N=t.useCallback(async(w,m)=>{try{const y=await a.auth.updateOrg(w,m);return e(C=>C.map(B=>B.id===w?y:B)),(o==null?void 0:o.id)===w&&n(y),y}catch(y){return g(y instanceof Error?y.message:"Failed to update organization"),null}},[a,o]),h=t.useCallback(async w=>{try{return await a.auth.deleteOrg(w),e(m=>m.filter(y=>y.id!==w)),(o==null?void 0:o.id)===w&&(n(null),l([]),d([]),typeof window<"u"&&localStorage.removeItem("ss_selected_org")),!0}catch(m){return g(m instanceof Error?m.message:"Failed to delete organization"),!1}},[a,o]),j=t.useCallback(async(w,m,y)=>{try{return await a.auth.sendInvite(w,m,y)}catch(C){return g(C instanceof Error?C.message:"Failed to send invite"),null}},[a]),S=t.useCallback(async w=>{try{const m=await a.auth.listInvites(w);d(m)}catch(m){g(m instanceof Error?m.message:"Failed to load invites")}},[a]),k=t.useCallback(async(w,m)=>{try{return await a.auth.revokeInvite(w,m),d(y=>y.filter(C=>C.id!==m)),!0}catch(y){return g(y instanceof Error?y.message:"Failed to revoke invite"),!1}},[a]),P=t.useCallback(async(w,m,y)=>{try{return await a.auth.updateMemberRole(w,m,y),l(C=>C.map(B=>B.userId===m?{...B,role:y}:B)),!0}catch(C){return g(C instanceof Error?C.message:"Failed to update member role"),!1}},[a]),z=t.useCallback(async(w,m)=>{try{return await a.auth.removeMember(w,m),l(y=>y.filter(C=>C.userId!==m)),!0}catch(y){return g(y instanceof Error?y.message:"Failed to remove member"),!1}},[a]),F=t.useCallback(async w=>{try{const m=await a.auth.listMembers(w);l(m)}catch(m){g(m instanceof Error?m.message:"Failed to load members")}},[a]);return{orgs:r,selectedOrg:o,members:u,invites:c,isLoading:i,error:p,setError:g,refresh:f,selectOrg:v,createOrg:b,updateOrg:N,deleteOrg:h,sendInvite:j,refreshInvites:S,revokeInvite:k,updateMemberRole:P,removeMember:z,refreshMembers:F}}function es(){const{client:a}=E(),[r,e]=t.useState(!1),[o,n]=t.useState(null);return{deleteAccount:t.useCallback(async()=>{e(!0),n(null);try{return await a.auth.deleteAccount(),!0}catch(l){return n(l instanceof Error?l.message:"Failed to delete account"),!1}finally{e(!1)}},[a]),isLoading:r,error:o,setError:n}}function X(){const{client:a,user:r}=E(),[e,o]=t.useState(!1),[n,u]=t.useState(null),[l,c]=t.useState(null),d=t.useCallback(async p=>{o(!0),u(null),c(null);try{const g=await a.auth.updateProfile(p);return c("Profile updated"),g}catch(g){return u(g instanceof Error?g.message:"Failed to update profile"),null}finally{o(!1)}},[a]),i=t.useCallback(async(p,g)=>{o(!0),u(null),c(null);try{return await a.auth.changePassword(p,g),c("Password changed successfully"),!0}catch(f){return u(f instanceof Error?f.message:"Failed to change password"),!1}finally{o(!1)}},[a]),x=t.useCallback(async p=>{o(!0),u(null),c(null);try{const g=await a.auth.uploadAvatar(p);return c("Avatar updated"),g}catch(g){return u(g instanceof Error?g.message:"Failed to upload avatar"),null}finally{o(!1)}},[a]);return{user:r,updateProfile:d,uploadAvatar:x,changePassword:i,isLoading:e,error:n,success:l,setError:u,setSuccess:c}}const ts='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>',rs='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" fill="currentColor"/></svg>',$={close:"close",person:"person",logout:"logout",checkCircle:"check_circle",unfoldMore:"unfold_more",cloudUpload:"cloud_upload",zoomIn:"zoom_in",zoomOut:"zoom_out",lock:"lock",visibility:"visibility",visibilityOff:"visibility_off",add:"add",addCircle:"add_circle",camera:"photo_camera",security:"security",errorOutline:"error_outline",info:"info",arrowForward:"arrow_forward",verified:"verified",token:"token",autoAwesome:"auto_awesome",corporateFare:"corporate_fare",cloudDone:"cloud_done",check:"check",image:"image"};function Cs({appearance:a,signUpUrl:r,onSignUp:e}){const{appearance:o,settings:n}=E(),{signIn:u,signInWithOAuth:l,submitMfaCode:c,isLoading:d,error:i,setError:x}=Z(),p=a??o,[g,f]=t.useState(""),[v,b]=t.useState(""),[N,h]=t.useState(!1),[j,S]=t.useState(!1),[k,P]=t.useState(""),[z,F]=t.useState(["","","","","",""]),w=t.useRef([]),m=t.useCallback(async L=>{if(L.preventDefault(),j){await c(k,z.join(""));return}const T=await u(g,v);T&&U.isMfaRequired(T)&&(P(T.mfaToken),S(!0),x(null))},[g,v,j,k,z,u,c,x]),y=t.useCallback(async L=>{await l(L)},[l]),C=t.useCallback((L,T)=>{var R;if(!/^\d*$/.test(T))return;const O=T.slice(-1);F(_=>{const q=[..._];return q[L]=O,q}),O&&L<5&&((R=w.current[L+1])==null||R.focus())},[]),B=t.useCallback((L,T)=>{var O;T.key==="Backspace"&&!z[L]&&L>0&&((O=w.current[L-1])==null||O.focus())},[z]),D=(n==null?void 0:n.googleEnabled)||(n==null?void 0:n.githubEnabled);return s.jsx(M,{appearance:p,children:s.jsx("div",{className:"ss-auth-card",children:s.jsxs("div",{className:"ss-auth-card-body",children:[s.jsxs("div",{className:"ss-auth-header",children:[s.jsx("div",{className:"ss-auth-brand-icon",children:s.jsx("span",{className:"material-symbols-outlined",children:$.token})}),s.jsx("h1",{className:"ss-auth-title",children:"Sign in to your account"}),s.jsx("p",{className:"ss-auth-subtitle",children:"Welcome back to your workspace"})]}),!j&&D&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"ss-auth-oauth-grid",children:[(n==null?void 0:n.googleEnabled)&&s.jsxs("button",{type:"button",className:"ss-auth-btn-social",onClick:()=>y("google"),disabled:d,children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:ts}}),"Google"]}),(n==null?void 0:n.githubEnabled)&&s.jsxs("button",{type:"button",className:"ss-auth-btn-social",onClick:()=>y("github"),disabled:d,children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:rs}}),"GitHub"]})]}),s.jsx("div",{className:"ss-auth-divider",children:"or continue with"})]}),i&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:i})]}),s.jsxs("form",{onSubmit:m,children:[j?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"ss-auth-mfa-divider",children:s.jsx("span",{children:"Verification Required"})}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"6-Digit Code"}),s.jsx("div",{className:"ss-auth-mfa-group",children:z.map((L,T)=>s.jsx("input",{ref:O=>{w.current[T]=O},className:"ss-auth-mfa-digit",type:"text",inputMode:"numeric",maxLength:1,value:L,onChange:O=>C(T,O.target.value),onKeyDown:O=>B(T,O),autoFocus:T===0},T))}),s.jsx("p",{className:"ss-auth-mfa-hint",children:"We sent a 6-digit code to your registered email."})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-email",children:"Email Address"}),s.jsx("input",{id:"ss-email",className:"ss-auth-input",type:"email",autoComplete:"email",placeholder:"name@company.com",value:g,onChange:L=>f(L.target.value),required:!0})]}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsxs("div",{className:"ss-auth-field-row",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-password",style:{marginBottom:0},children:"Password"}),s.jsx("span",{className:"ss-auth-link",style:{fontSize:"12px"},children:"Forgot?"})]}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{id:"ss-password",className:"ss-auth-input",type:N?"text":"password",autoComplete:"current-password",placeholder:"••••••••",value:v,onChange:L=>b(L.target.value),required:!0}),s.jsx("button",{type:"button",className:"ss-auth-visibility-toggle",onClick:()=>h(!N),children:s.jsx("span",{className:"material-symbols-outlined",children:N?$.visibilityOff:$.visibility})})]})]})]}),s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary",disabled:d,children:[d&&s.jsx("span",{className:"ss-auth-spinner"}),j?"Verify":"Sign in",!d&&s.jsx("span",{className:"material-symbols-outlined",children:$.arrowForward})]})]}),j?s.jsx("div",{className:"ss-auth-footer",children:s.jsx("span",{className:"ss-auth-link",onClick:()=>{S(!1),F(["","","","","",""]),x(null)},children:"Back to sign in"})}):s.jsxs("div",{className:"ss-auth-footer",children:["Don't have an account?"," ",e?s.jsx("span",{className:"ss-auth-link",onClick:e,children:"Sign up"}):r?s.jsx("a",{className:"ss-auth-link",href:r,children:"Sign up"}):s.jsx("span",{className:"ss-auth-link",children:"Sign up"})]})]})})})}function Ps({appearance:a,signInUrl:r,onSignIn:e}){const{appearance:o,settings:n}=E(),{signUp:u,isLoading:l,error:c,setError:d}=as(),{signInWithOAuth:i}=Z(),x=a??o,[p,g]=t.useState(""),[f,v]=t.useState(""),[b,N]=t.useState(""),[h,j]=t.useState(!1),[S,k]=t.useState(null),P=t.useCallback(async m=>{if(m.preventDefault(),k(null),f!==b){k("Passwords do not match");return}const y=(n==null?void 0:n.passwordMinLength)??8;if(f.length<y){k(`Password must be at least ${y} characters`);return}await u(p,f)},[p,f,b,n,u]),z=t.useCallback(async m=>{await i(m)},[i]),F=(n==null?void 0:n.googleEnabled)||(n==null?void 0:n.githubEnabled),w=S||c;return s.jsx(M,{appearance:x,children:s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",width:"100%",maxWidth:"520px"},children:[s.jsxs("div",{className:"ss-auth-header",children:[s.jsx("div",{className:"ss-auth-brand-icon-gradient",children:s.jsx("span",{className:"material-symbols-outlined",children:$.autoAwesome})}),s.jsx("h1",{className:"ss-auth-title ss-auth-title-lg",children:"Create your account"}),s.jsx("p",{className:"ss-auth-subtitle",children:"Join the ecosystem"})]}),s.jsx("div",{className:"ss-auth-card",children:s.jsxs("div",{className:"ss-auth-card-body",children:[F&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"ss-auth-oauth-grid",children:[(n==null?void 0:n.googleEnabled)&&s.jsxs("button",{type:"button",className:"ss-auth-btn-social",onClick:()=>z("google"),disabled:l,children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:ts}}),"Google"]}),(n==null?void 0:n.githubEnabled)&&s.jsxs("button",{type:"button",className:"ss-auth-btn-social",onClick:()=>z("github"),disabled:l,children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:rs}}),"GitHub"]})]}),s.jsx("div",{className:"ss-auth-divider",children:"or sign up with email"})]}),w&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:w})]}),s.jsxs("form",{onSubmit:P,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-signup-email",children:"Email"}),s.jsx("input",{id:"ss-signup-email",className:"ss-auth-input",type:"email",autoComplete:"email",placeholder:"name@company.com",value:p,onChange:m=>g(m.target.value),required:!0})]}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-signup-password",children:"Password"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{id:"ss-signup-password",className:"ss-auth-input",type:h?"text":"password",autoComplete:"new-password",placeholder:"••••••••",value:f,onChange:m=>{v(m.target.value),k(null)},required:!0}),s.jsx("button",{type:"button",className:"ss-auth-visibility-toggle",onClick:()=>j(!h),children:s.jsx("span",{className:"material-symbols-outlined",children:h?$.visibilityOff:$.visibility})})]})]}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-signup-confirm",children:"Confirm Password"}),s.jsx("input",{id:"ss-signup-confirm",className:"ss-auth-input",type:"password",autoComplete:"new-password",placeholder:"••••••••",value:b,onChange:m=>{N(m.target.value),k(null)},required:!0})]}),s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary",disabled:l,children:[l&&s.jsx("span",{className:"ss-auth-spinner"}),"Sign up",!l&&s.jsx("span",{className:"material-symbols-outlined",children:$.arrowForward})]})]}),s.jsxs("div",{className:"ss-auth-footer",children:["Already have an account?"," ",e?s.jsx("span",{className:"ss-auth-link",onClick:e,children:"Sign in"}):r?s.jsx("a",{className:"ss-auth-link",href:r,children:"Sign in"}):s.jsx("span",{className:"ss-auth-link",children:"Sign in"})]})]})})]})})}const I=320,V=128;function zs({file:a,onCrop:r,onCancel:e}){const o=t.useRef(null),n=t.useRef(null),[u,l]=t.useState(1),[c,d]=t.useState({x:0,y:0}),[i,x]=t.useState(!1),p=t.useRef({x:0,y:0,ox:0,oy:0}),[g,f]=t.useState(!1);t.useEffect(()=>{const h=new Image,j=URL.createObjectURL(a);return h.onload=()=>{n.current=h,f(!0),d({x:0,y:0}),l(1)},h.src=j,()=>URL.revokeObjectURL(j)},[a]),t.useEffect(()=>{if(!g||!n.current||!o.current)return;const h=o.current.getContext("2d");if(!h)return;const j=n.current;h.clearRect(0,0,I,I),h.fillStyle="#111",h.fillRect(0,0,I,I);const S=Math.max(I/j.width,I/j.height)*u,k=j.width*S,P=j.height*S,z=(I-k)/2+c.x,F=(I-P)/2+c.y;h.save(),h.beginPath(),h.arc(I/2,I/2,V,0,Math.PI*2),h.clip(),h.drawImage(j,z,F,k,P),h.restore(),h.save(),h.fillStyle="rgba(0, 0, 0, 0.6)",h.fillRect(0,0,I,I),h.globalCompositeOperation="destination-out",h.beginPath(),h.arc(I/2,I/2,V,0,Math.PI*2),h.fill(),h.restore(),h.save(),h.beginPath(),h.arc(I/2,I/2,V,0,Math.PI*2),h.clip(),h.drawImage(j,z,F,k,P),h.restore(),h.strokeStyle="rgba(255, 255, 255, 0.4)",h.lineWidth=2,h.beginPath(),h.arc(I/2,I/2,V,0,Math.PI*2),h.stroke()},[u,c,g]);const v=t.useCallback(h=>{x(!0),p.current={x:h.clientX,y:h.clientY,ox:c.x,oy:c.y},h.target.setPointerCapture(h.pointerId)},[c]),b=t.useCallback(h=>{i&&d({x:p.current.ox+(h.clientX-p.current.x),y:p.current.oy+(h.clientY-p.current.y)})},[i]),N=t.useCallback(()=>x(!1),[]);return t.useCallback(()=>{if(!n.current)return;const h=document.createElement("canvas"),j=V*2;h.width=j,h.height=j;const S=h.getContext("2d");if(!S)return;const k=n.current,P=Math.max(I/k.width,I/k.height)*u,z=k.width*P,F=k.height*P,w=(I-z)/2+c.x-(I/2-V),m=(I-F)/2+c.y-(I/2-V);S.beginPath(),S.arc(V,V,V,0,Math.PI*2),S.clip(),S.drawImage(k,w,m,z,F),h.toBlob(y=>{y&&r(y)},"image/png")},[u,c,r]),s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"24px"},children:[s.jsxs("div",{className:"ss-auth-crop-area",children:[s.jsx("canvas",{ref:o,width:I,height:I,style:{cursor:i?"grabbing":"grab",width:"100%",height:"100%"},onPointerDown:v,onPointerMove:b,onPointerUp:N}),s.jsx("div",{className:"ss-auth-crop-size-badge",children:"256 x 256 px"})]}),s.jsxs("div",{className:"ss-auth-zoom-control",style:{width:"100%",maxWidth:"280px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.zoomOut}),s.jsx("input",{type:"range",min:"1",max:"3",step:"0.01",value:u,onChange:h=>l(parseFloat(h.target.value)),className:"ss-auth-zoom-slider"}),s.jsx("span",{className:"material-symbols-outlined",children:$.zoomIn})]})]})}function ns({onUpload:a,onClose:r,isLoading:e}){const[o,n]=t.useState(null),[u,l]=t.useState(!1),[c,d]=t.useState(null),i=t.useRef(null),x=t.useCallback(f=>{if(!f.type.startsWith("image/")){d("Please select an image file");return}if(f.size>5*1024*1024){d("Image must be smaller than 5 MB");return}d(null),n(f)},[]),p=t.useCallback(f=>{f.preventDefault(),l(!1);const v=f.dataTransfer.files[0];v&&x(v)},[x]),g=t.useCallback(async f=>{await a(f)},[a]);return s.jsx("div",{className:"ss-auth-modal-overlay",onClick:f=>{f.target===f.currentTarget&&r()},children:s.jsxs("div",{className:"ss-auth-modal ss-auth-card-wide",children:[s.jsxs("div",{className:"ss-auth-modal-header",children:[s.jsx("h2",{children:"Upload avatar"}),s.jsx("button",{type:"button",className:"ss-auth-modal-close",onClick:r,children:s.jsx("span",{className:"material-symbols-outlined",children:$.close})})]}),s.jsxs("div",{className:"ss-auth-modal-body",children:[c&&s.jsxs("div",{className:"ss-auth-error",style:{marginBottom:"24px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:c})]}),s.jsxs("div",{className:"ss-auth-upload-grid",children:[s.jsx("div",{children:o?s.jsx(zs,{file:o,onCrop:g,onCancel:()=>n(null)}):s.jsxs("div",{className:"ss-auth-crop-area",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"8px",width:"100%",aspectRatio:"1"},children:[s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"48px",opacity:.3},children:$.image}),s.jsx("span",{style:{fontSize:"12px",opacity:.4},children:"No image selected"})]})}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:[s.jsxs("div",{className:`ss-auth-dropzone${u?" ss-auth-dropzone-active":""}`,onDragOver:f=>{f.preventDefault(),l(!0)},onDragLeave:()=>l(!1),onDrop:p,onClick:()=>{var f;return(f=i.current)==null?void 0:f.click()},style:{minHeight:"180px"},children:[s.jsx("div",{className:"ss-auth-dropzone-icon",children:s.jsx("span",{className:"material-symbols-outlined",children:$.cloudUpload})}),s.jsx("span",{className:"ss-auth-dropzone-title",children:"Drag and drop"}),s.jsxs("span",{className:"ss-auth-dropzone-desc",children:["JPG, PNG or WEBP",s.jsx("br",{}),"Max file size 5 MB"]}),s.jsx("button",{type:"button",className:"ss-auth-dropzone-btn",children:"Choose File"}),s.jsx("input",{ref:i,type:"file",accept:"image/*",style:{display:"none"},onChange:f=>{var v;(v=f.target.files)!=null&&v[0]&&x(f.target.files[0])}})]}),s.jsxs("div",{className:"ss-auth-info-box",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.info}),s.jsx("span",{children:"Your profile photo will be visible to all members of your organization."})]})]})]})]}),s.jsxs("div",{className:"ss-auth-modal-footer",children:[s.jsx("button",{type:"button",className:"ss-auth-btn-ghost",onClick:r,children:"Cancel"}),s.jsxs("button",{type:"button",className:"ss-auth-btn-primary ss-auth-btn-sm",onClick:()=>{},disabled:!o||e,style:{width:"auto"},children:[e&&s.jsx("span",{className:"ss-auth-spinner"}),"Save Profile",!e&&s.jsx("span",{className:"material-symbols-outlined",children:$.check})]})]})]})})}function Es({appearance:a,afterSignOutUrl:r,afterDeleteAccountUrl:e,showOrgSwitcher:o=!0,onOrgChange:n,onOrgSettingsClick:u}){const{appearance:l}=E(),{user:c,signOut:d}=H(),i=a??l,[x,p]=t.useState(!1),[g,f]=t.useState(!1),[v,b]=t.useState(""),[N,h]=t.useState(null),[j,S]=t.useState(!1),k=t.useRef(null),{orgs:P,selectedOrg:z,selectOrg:F,createOrg:w}=K(),m=t.useCallback(C=>{k.current&&!C.composedPath().includes(k.current)&&p(!1)},[]);t.useEffect(()=>{if(x){const C=setTimeout(()=>{document.addEventListener("click",m)},0);return()=>{clearTimeout(C),document.removeEventListener("click",m)}}},[x,m]);const y=t.useCallback(async C=>{C.preventDefault(),h(null),S(!0);const B=v.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");try{const D=await w(v,B);D&&(await F(D.id),n==null||n(D),b(""),p(!1))}catch(D){h(D instanceof Error?D.message:"Failed to create organization")}finally{S(!1)}},[v,w,F,n]);return c?s.jsx(M,{appearance:i,children:s.jsxs("div",{style:{position:"relative",display:"inline-block"},ref:k,children:[s.jsx("button",{type:"button",className:"ss-auth-avatar-trigger",onClick:()=>p(!x),"aria-label":"User menu",children:c.avatarUrl?s.jsx("img",{src:c.avatarUrl,alt:""}):s.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",fontWeight:700},children:(c.name||c.email).charAt(0).toUpperCase()})}),x&&s.jsxs("div",{className:"ss-auth-dropdown ss-auth-glass-panel",style:{minWidth:"320px"},children:[s.jsxs("div",{className:"ss-auth-dropdown-header",children:[s.jsx("div",{className:"ss-auth-dropdown-avatar",children:c.avatarUrl?s.jsx("img",{src:c.avatarUrl,alt:""}):s.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"20px",fontWeight:800},children:(c.name||c.email).charAt(0).toUpperCase()})}),s.jsxs("div",{children:[c.name&&s.jsx("div",{className:"ss-auth-dropdown-name",children:c.name}),s.jsx("div",{className:"ss-auth-dropdown-email",children:c.email})]})]}),s.jsx("div",{style:{padding:"4px 8px"},children:s.jsxs("button",{type:"button",className:"ss-auth-dropdown-action",onClick:()=>{p(!1),f(!0)},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.person}),"Profile"]})}),o&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"ss-auth-section-label",children:"Organizations"}),s.jsx("div",{style:{padding:"0 8px 4px"},children:P.map(C=>{const B=(z==null?void 0:z.id)===C.id,D=C.name.split(" ").map(L=>L[0]).join("").slice(0,2).toUpperCase();return s.jsxs("button",{type:"button",className:`ss-auth-org-item${B?" ss-auth-org-item-active":""}`,onClick:async()=>{p(!1),await F(C.id),n==null||n(C)},children:[s.jsxs("div",{className:"ss-auth-org-item-inner",children:[s.jsx("div",{className:`ss-auth-org-avatar${B?"":" ss-auth-org-avatar-inactive"}`,children:D}),s.jsx("span",{style:{fontFamily:"'Manrope', sans-serif",letterSpacing:"-0.01em"},children:C.name})]}),B&&s.jsx("span",{className:"material-symbols-outlined ss-auth-org-check",style:{fontSize:"18px"},children:$.checkCircle})]},C.id)})}),s.jsxs("div",{className:"ss-auth-inline-create",children:[N&&s.jsx("div",{className:"ss-auth-error",style:{marginBottom:"8px",fontSize:"12px"},children:s.jsx("span",{children:N})}),s.jsx("form",{onSubmit:y,children:s.jsxs("div",{className:"ss-auth-inline-create-input",children:[s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"New organization name",value:v,onChange:C=>b(C.target.value),required:!0,style:{fontSize:"13px",padding:"10px 40px 10px 12px"}}),s.jsx("button",{type:"submit",className:"ss-auth-inline-create-btn",disabled:j||!v.trim(),children:s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"20px"},children:$.add})})]})})]}),z&&u&&s.jsx("div",{style:{padding:"0 8px 4px"},children:s.jsxs("button",{type:"button",className:"ss-auth-dropdown-action",onClick:()=>{p(!1),u(z)},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.corporateFare}),"Org settings"]})})]}),s.jsx("div",{className:"ss-auth-signout-section",style:{padding:"8px"},children:s.jsxs("button",{type:"button",className:"ss-auth-dropdown-action",onClick:async()=>{p(!1),await d(),r&&(window.location.href=r)},style:{color:"inherit"},children:[s.jsx("span",{className:"material-symbols-outlined",style:{color:"inherit"},children:$.logout}),"Sign out"]})})]}),g&&s.jsx(Os,{onClose:()=>f(!1),afterDeleteAccountUrl:e})]})}):null}function Os({onClose:a,afterDeleteAccountUrl:r}){const{user:e,updateProfile:o,uploadAvatar:n,changePassword:u,isLoading:l,error:c,success:d,setError:i,setSuccess:x}=X(),{signOut:p}=H(),{deleteAccount:g,isLoading:f,error:v,setError:b}=es(),[N,h]=t.useState((e==null?void 0:e.name)??""),[j,S]=t.useState((e==null?void 0:e.avatarUrl)??""),[k,P]=t.useState(!1),[z,F]=t.useState(""),[w,m]=t.useState(""),[y,C]=t.useState(""),[B,D]=t.useState(null),[L,T]=t.useState(!1),[O,R]=t.useState(""),_=t.useCallback(async A=>{A.preventDefault(),i(null),x(null),await o({name:N,avatarUrl:j||void 0})},[N,j,o,i,x]),q=t.useCallback(async A=>{const G=await n(A);G&&(S(G.avatarUrl),P(!1))},[n]),gs=t.useCallback(async A=>{if(A.preventDefault(),D(null),i(null),x(null),w!==y){D("Passwords do not match");return}if(w.length<8){D("Password must be at least 8 characters");return}await u(z,w)&&(F(""),m(""),C(""))},[z,w,y,u,i,x]),fs=t.useCallback(async()=>{await g()&&(await p(),r&&(window.location.href=r))},[g,p,r]),ms=(e==null?void 0:e.provider)==="email",bs=O===(e==null?void 0:e.email),ys=((e==null?void 0:e.name)||(e==null?void 0:e.email)||"?").charAt(0).toUpperCase();return s.jsx("div",{className:"ss-auth-modal-overlay",onClick:A=>{A.target===A.currentTarget&&a()},children:s.jsxs("div",{className:"ss-auth-modal",style:{maxWidth:"640px"},children:[s.jsxs("div",{className:"ss-auth-modal-header",children:[s.jsx("h2",{children:"Profile"}),s.jsx("button",{type:"button",className:"ss-auth-modal-close",onClick:a,children:s.jsx("span",{className:"material-symbols-outlined",children:$.close})})]}),s.jsxs("div",{className:"ss-auth-profile-header",children:[s.jsxs("div",{className:"ss-auth-avatar-lg",onClick:()=>P(!0),children:[j?s.jsx("img",{src:j,alt:""}):s.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"48px",fontWeight:800,opacity:.4},children:ys}),s.jsxs("div",{className:"ss-auth-avatar-overlay",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.camera}),s.jsx("span",{children:"Edit"})]})]}),s.jsxs("div",{className:"ss-auth-profile-info",children:[s.jsxs("h2",{className:"ss-auth-profile-name",children:[(e==null?void 0:e.name)||"Unnamed User",(e==null?void 0:e.emailVerified)&&s.jsxs("span",{className:"ss-auth-badge ss-auth-badge-success",children:[s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"12px",fontVariationSettings:"'FILL' 1"},children:$.verified}),"Verified"]})]}),s.jsx("p",{className:"ss-auth-profile-desc",children:e==null?void 0:e.email})]})]}),s.jsxs("div",{className:"ss-auth-modal-body",children:[c&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:c})]}),d&&s.jsxs("div",{className:"ss-auth-info-box",style:{marginBottom:"16px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.check}),s.jsx("span",{children:d})]}),s.jsxs("form",{onSubmit:_,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Full Name"}),s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"Your name",value:N,onChange:A=>h(A.target.value)})]}),s.jsxs("div",{className:"ss-auth-profile-grid",style:{marginBottom:"16px"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Email Address"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{className:"ss-auth-input ss-auth-input-readonly",type:"email",value:(e==null?void 0:e.email)??"",readOnly:!0}),s.jsx("span",{className:"ss-auth-visibility-toggle",style:{cursor:"default"},children:s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"18px"},children:$.lock})})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Auth Provider"}),s.jsx("input",{className:"ss-auth-input ss-auth-input-readonly",type:"text",value:(e==null?void 0:e.provider)??"",readOnly:!0})]})]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary ss-auth-btn-sm",disabled:l,style:{width:"auto"},children:[l&&s.jsx("span",{className:"ss-auth-spinner"}),"Save changes"]})})]}),ms&&s.jsxs("div",{className:"ss-auth-section",children:[s.jsxs("div",{className:"ss-auth-section-title",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.security}),"Security Credentials"]}),B&&s.jsxs("div",{className:"ss-auth-error",style:{marginTop:"16px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:B})]}),s.jsxs("form",{onSubmit:gs,style:{marginTop:"16px"},children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Current Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"••••••••••••",value:z,onChange:A=>F(A.target.value),required:!0})]}),s.jsxs("div",{className:"ss-auth-profile-grid",style:{marginBottom:"16px"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"New Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"Min. 8 characters",value:w,onChange:A=>m(A.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Confirm New Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"Repeat new password",value:y,onChange:A=>C(A.target.value),required:!0})]})]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsx("button",{type:"submit",className:"ss-auth-btn-ghost",disabled:l,children:"Update Security"})})]})]}),s.jsxs("div",{className:"ss-auth-section",children:[s.jsx("div",{className:"ss-auth-section-title",style:{color:"inherit"},children:"Danger Zone"}),s.jsx("p",{className:"ss-auth-section-desc",style:{marginBottom:"16px"},children:"Deleting your account is permanent. All organizations you own will also be deleted."}),v&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:v})]}),L?s.jsxs("div",{children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Type your email to confirm"}),s.jsx("input",{className:"ss-auth-input",type:"email",placeholder:e==null?void 0:e.email,value:O,onChange:A=>R(A.target.value),autoFocus:!0})]}),s.jsxs("div",{style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[s.jsx("button",{type:"button",className:"ss-auth-btn-ghost",onClick:()=>{T(!1),R(""),b(null)},children:"Cancel"}),s.jsxs("button",{type:"button",className:"ss-auth-btn-primary ss-auth-btn-sm",style:{width:"auto",background:"linear-gradient(135deg, #ef4444, #dc2626)"},disabled:!bs||f,onClick:fs,children:[f&&s.jsx("span",{className:"ss-auth-spinner"}),"Delete account"]})]})]}):s.jsx("button",{type:"button",className:"ss-auth-btn-outline",style:{borderColor:"currentColor",width:"auto"},onClick:()=>T(!0),children:"Delete my account"})]})]}),k&&s.jsx(ns,{onUpload:q,onClose:()=>P(!1),isLoading:l})]})})}function Is({appearance:a}){const{appearance:r}=E(),{user:e,signOut:o}=H(),{updateProfile:n,uploadAvatar:u,changePassword:l,isLoading:c,error:d,success:i,setError:x,setSuccess:p}=X(),g=a??r,[f,v]=t.useState((e==null?void 0:e.name)??""),[b,N]=t.useState((e==null?void 0:e.avatarUrl)??""),[h,j]=t.useState(!1),[S,k]=t.useState(""),[P,z]=t.useState(""),[F,w]=t.useState(""),[m,y]=t.useState(null),C=t.useCallback(async O=>{O.preventDefault(),x(null),p(null),await n({name:f,avatarUrl:b||void 0})},[f,b,n,x,p]),B=t.useCallback(async O=>{const R=await u(O);R&&(N(R.avatarUrl),j(!1))},[u]),D=t.useCallback(async O=>{if(O.preventDefault(),y(null),x(null),p(null),P!==F){y("Passwords do not match");return}if(P.length<8){y("Password must be at least 8 characters");return}await l(S,P)&&(k(""),z(""),w(""))},[S,P,F,l,x,p]);if(!e)return null;const L=e.provider==="email",T=(e.name||e.email).charAt(0).toUpperCase();return s.jsx(M,{appearance:g,children:s.jsxs("div",{className:"ss-auth-card",style:{maxWidth:"640px"},children:[s.jsxs("div",{className:"ss-auth-profile-header",children:[s.jsxs("div",{className:"ss-auth-avatar-lg",onClick:()=>j(!0),children:[b?s.jsx("img",{src:b,alt:""}):s.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"48px",fontWeight:800,opacity:.4},children:T}),s.jsxs("div",{className:"ss-auth-avatar-overlay",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.camera}),s.jsx("span",{children:"Edit"})]})]}),s.jsxs("div",{className:"ss-auth-profile-info",children:[s.jsxs("h2",{className:"ss-auth-profile-name",children:[e.name||"Unnamed User",e.emailVerified&&s.jsxs("span",{className:"ss-auth-badge ss-auth-badge-success",children:[s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"12px",fontVariationSettings:"'FILL' 1"},children:$.verified}),"Verified"]})]}),s.jsx("p",{className:"ss-auth-profile-desc",children:e.email})]})]}),s.jsxs("div",{className:"ss-auth-card-body",children:[d&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:d})]}),i&&s.jsxs("div",{className:"ss-auth-info-box",style:{marginBottom:"16px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.check}),s.jsx("span",{children:i})]}),s.jsxs("form",{onSubmit:C,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Full Name"}),s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"Your name",value:f,onChange:O=>v(O.target.value)})]}),s.jsxs("div",{className:"ss-auth-profile-grid",style:{marginBottom:"16px"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Email Address"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{className:"ss-auth-input ss-auth-input-readonly",type:"email",value:e.email,readOnly:!0}),s.jsx("span",{className:"ss-auth-visibility-toggle",style:{cursor:"default"},children:s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"18px"},children:$.lock})})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Auth Provider"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{className:"ss-auth-input ss-auth-input-readonly",type:"text",value:e.provider,readOnly:!0}),s.jsx("span",{className:"ss-auth-visibility-toggle",style:{cursor:"default"},children:s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"18px"},children:$.cloudDone})})]})]})]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary ss-auth-btn-sm",disabled:c,style:{width:"auto"},children:[c&&s.jsx("span",{className:"ss-auth-spinner"}),"Save changes"]})})]}),L&&s.jsxs("div",{className:"ss-auth-section",children:[s.jsxs("div",{className:"ss-auth-section-title",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.security}),"Security Credentials"]}),s.jsx("p",{className:"ss-auth-section-desc",style:{marginBottom:"24px"},children:"Update your password to keep your account secure."}),m&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:m})]}),s.jsxs("form",{onSubmit:D,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Current Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"••••••••••••",value:S,onChange:O=>k(O.target.value),required:!0})]}),s.jsxs("div",{className:"ss-auth-profile-grid",style:{marginBottom:"16px"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"New Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"Min. 8 characters",value:P,onChange:O=>z(O.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Confirm New Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"Repeat new password",value:F,onChange:O=>w(O.target.value),required:!0})]})]}),s.jsxs("div",{className:"ss-auth-info-box",style:{marginBottom:"16px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.info}),s.jsx("span",{children:"Password must be at least 8 characters long."})]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsx("button",{type:"submit",className:"ss-auth-btn-ghost",disabled:c,children:"Update Security"})})]})]}),s.jsx("div",{className:"ss-auth-section",style:{borderTop:"none",paddingTop:0,marginTop:"24px"},children:s.jsx("div",{className:"ss-auth-signout-section",style:{borderRadius:"12px",padding:"16px 20px"},children:s.jsxs("div",{className:"ss-auth-signout-row",children:[s.jsxs("div",{className:"ss-auth-signout-info",children:[s.jsx("div",{className:"ss-auth-signout-icon",children:s.jsx("span",{className:"material-symbols-outlined",children:$.logout})}),s.jsxs("div",{children:[s.jsx("div",{className:"ss-auth-signout-title",children:"End Session"}),s.jsx("div",{className:"ss-auth-signout-desc",children:"Terminate your active session"})]})]}),s.jsx("button",{type:"button",className:"ss-auth-btn-outline",onClick:()=>o(),style:{width:"auto",flexShrink:0},children:"Sign out"})]})})})]}),h&&s.jsx(ns,{onUpload:B,onClose:()=>j(!1),isLoading:c})]})})}function Fs({appearance:a,onOrgChange:r}){const{appearance:e}=E(),{orgs:o,selectedOrg:n,selectOrg:u,createOrg:l,isLoading:c}=K(),d=a??e,[i,x]=t.useState(!1),[p,g]=t.useState(""),[f,v]=t.useState(""),[b,N]=t.useState(null),[h,j]=t.useState(!1),S=t.useRef(null),k=t.useCallback(m=>{S.current&&!m.composedPath().includes(S.current)&&x(!1)},[]);t.useEffect(()=>{if(i){const m=setTimeout(()=>{document.addEventListener("click",k)},0);return()=>{clearTimeout(m),document.removeEventListener("click",k)}}},[i,k]);const P=t.useCallback(m=>{g(m),v(m.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},[]),z=t.useCallback(async m=>{m.preventDefault(),N(null),j(!0);try{const y=await l(p,f);y&&(await u(y.id),r==null||r(y),g(""),v(""),x(!1))}catch(y){N(y instanceof Error?y.message:"Failed to create organization")}finally{j(!1)}},[p,f,l,u,r]);if(c)return null;const F=(n==null?void 0:n.name)??(o.length===0?"No organization":"Select organization"),w=n?n.name.split(" ").map(m=>m[0]).join("").slice(0,2).toUpperCase():"--";return s.jsx(M,{appearance:d,children:s.jsxs("div",{style:{position:"relative",display:"inline-block",width:"100%",maxWidth:"360px"},ref:S,children:[s.jsxs("button",{type:"button",className:"ss-auth-org-trigger",onClick:()=>x(!i),children:[s.jsxs("div",{className:"ss-auth-org-trigger-inner",children:[s.jsx("div",{className:"ss-auth-org-avatar",children:w}),s.jsxs("div",{style:{textAlign:"left"},children:[s.jsx("div",{className:"ss-auth-org-trigger-label",children:"Current Organization"}),s.jsx("div",{className:"ss-auth-org-trigger-name",children:F})]})]}),s.jsx("span",{className:"material-symbols-outlined",children:$.unfoldMore})]}),i&&s.jsxs("div",{className:"ss-auth-dropdown ss-auth-dropdown-left ss-auth-glass-panel",style:{width:"100%"},children:[s.jsx("div",{className:"ss-auth-section-label",children:"Your Organizations"}),s.jsx("div",{style:{padding:"0 8px 4px"},children:o.map(m=>{const y=(n==null?void 0:n.id)===m.id,C=m.name.split(" ").map(B=>B[0]).join("").slice(0,2).toUpperCase();return s.jsxs("button",{type:"button",className:`ss-auth-org-item${y?" ss-auth-org-item-active":""}`,onClick:async()=>{x(!1),await u(m.id),r==null||r(m)},children:[s.jsxs("div",{className:"ss-auth-org-item-inner",children:[s.jsx("div",{className:`ss-auth-org-avatar${y?"":" ss-auth-org-avatar-inactive"}`,children:C}),s.jsx("span",{style:{fontFamily:"'Manrope', sans-serif",letterSpacing:"-0.01em"},children:m.name})]}),y&&s.jsx("span",{className:"material-symbols-outlined ss-auth-org-check",style:{fontSize:"18px"},children:$.checkCircle})]},m.id)})}),s.jsxs("div",{className:"ss-auth-org-create",children:[s.jsxs("div",{className:"ss-auth-org-create-header",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.addCircle}),s.jsx("span",{children:"Create organization"})]}),b&&s.jsx("div",{className:"ss-auth-error",style:{marginBottom:"12px",fontSize:"12px"},children:s.jsx("span",{children:b})}),s.jsxs("form",{onSubmit:z,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",style:{fontSize:"10px"},children:"Org Name"}),s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"e.g. Nexus Dynamics",value:p,onChange:m=>P(m.target.value),required:!0,style:{fontSize:"13px",padding:"10px 12px"}})]}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",style:{fontSize:"10px"},children:"Workspace Slug"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("span",{className:"ss-auth-org-slug-prefix",children:"/"}),s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"nexus-dynamics",value:f,onChange:m=>v(m.target.value),required:!0,style:{fontSize:"13px",padding:"10px 12px 10px 22px"}})]})]}),s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary",disabled:h||!p.trim(),style:{marginTop:"8px"},children:[h&&s.jsx("span",{className:"ss-auth-spinner"}),"Initialize Organization"]})]})]})]})]})})}function Ls(a,r="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:r,minimumFractionDigits:a%100===0?0:2}).format(a/100)}function Bs({plans:a,currentPlanId:r,onSelectPlan:e,interval:o,appearance:n}){const{appearance:u}=E(),l=n??u,c=o?a.filter(d=>d.interval===o||d.isFree):a;return s.jsx(M,{appearance:l,children:s.jsx("div",{className:"ss-pricing-grid",children:c.map(d=>{const i=d.id===r;return s.jsxs("div",{className:`ss-pricing-card ${i?"ss-pricing-card-current":""}`,children:[s.jsxs("div",{className:"ss-pricing-header",children:[s.jsx("h3",{className:"ss-pricing-name",children:d.name}),d.trialDays>0&&s.jsxs("span",{className:"ss-badge ss-badge-trialing",children:[d.trialDays,"-day trial"]}),d.isFree&&s.jsx("span",{className:"ss-badge ss-badge-active",children:"Free"})]}),s.jsx("div",{className:"ss-pricing-price",children:d.isFree?s.jsx("span",{className:"ss-pricing-amount",children:"Free"}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"ss-pricing-amount",children:Ls(d.amountCents,d.currency)}),s.jsxs("span",{className:"ss-pricing-interval",children:["/",d.interval]})]})}),d.description&&s.jsx("p",{className:"ss-pricing-desc",children:d.description}),d.features.length>0&&s.jsx("ul",{className:"ss-pricing-features",children:d.features.map((x,p)=>s.jsxs("li",{className:"ss-pricing-feature",children:[s.jsx("span",{className:"ss-check",children:"✓"})," ",x]},p))}),s.jsx("button",{type:"button",className:`ss-btn ${i?"ss-btn-current":"ss-btn-primary"}`,disabled:i,onClick:()=>e(d.id),children:i?"Current plan":"Select plan"})]},d.id)})})})}function Ts(){const{client:a}=E();return{billing:a.billing}}function W(a){const{client:r}=E();return t.useMemo(()=>{if(a){const e=new U.Transport("https://api.saas-support.com/v1",{type:"portalToken",token:a});return new U.BillingClient(e)}return r.billing},[r,a])}function os(a,r){const e=W(r),[o,n]=t.useState(null),[u,l]=t.useState(!0),[c,d]=t.useState(null),i=t.useCallback(async()=>{l(!0),d(null);try{const x=await e.getCustomer(a);n(x)}catch(x){d(x instanceof Error?x.message:"Failed to load subscription")}finally{l(!1)}},[e,a]);return t.useEffect(()=>{i()},[i]),{customer:o,isLoading:u,error:c,refresh:i}}function is(a,r){const e=W(r),[o,n]=t.useState([]),[u,l]=t.useState(!0),[c,d]=t.useState(null),i=t.useCallback(async()=>{l(!0),d(null);try{const x=await e.getInvoices(a);n(x)}catch(x){d(x instanceof Error?x.message:"Failed to load invoices")}finally{l(!1)}},[e,a]);return t.useEffect(()=>{i()},[i]),{invoices:o,isLoading:u,error:c,refresh:i}}function ls(a,r){const e=W(r),[o,n]=t.useState([]),[u,l]=t.useState(!0),[c,d]=t.useState(null),i=t.useCallback(async()=>{l(!0),d(null);try{const x=await e.getCurrentUsage(a);n(x)}catch(x){d(x instanceof Error?x.message:"Failed to load usage")}finally{l(!1)}},[e,a]);return t.useEffect(()=>{i()},[i]),{usage:o,isLoading:u,error:c,refresh:i}}const As={active:"ss-badge-active"};function cs({customerId:a,portalToken:r,onChangePlan:e,onCancel:o,appearance:n}){const{appearance:u}=E(),{customer:l,isLoading:c,error:d}=os(a,r),i=n??u;return s.jsx(M,{appearance:i,children:s.jsxs("div",{className:"ss-card",children:[s.jsx("h2",{className:"ss-title",children:"Subscription"}),c&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading..."]}),d&&s.jsx("div",{className:"ss-global-error",children:d}),l&&!c&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"ss-field",children:[s.jsx("label",{className:"ss-label",children:"Customer"}),s.jsx("input",{className:"ss-input",value:l.name||l.email,disabled:!0,readOnly:!0})]}),s.jsxs("div",{className:"ss-field",children:[s.jsx("label",{className:"ss-label",children:"Status"}),s.jsx("div",{children:s.jsx("span",{className:`ss-badge ${As.active}`,children:"Active"})})]}),s.jsxs("div",{className:"ss-btn-group",children:[e&&s.jsx("button",{type:"button",className:"ss-btn ss-btn-primary",onClick:e,children:"Change plan"}),o&&s.jsx("button",{type:"button",className:"ss-btn ss-btn-danger",onClick:o,children:"Cancel subscription"})]})]})]})})}const Ds={paid:"ss-badge-active",open:"ss-badge-trialing",draft:"ss-badge-paused",void:"ss-badge-canceled",uncollectible:"ss-badge-past-due"};function Ms(a){return new Date(a).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}function Us(a){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2}).format(a/100)}function ds({customerId:a,portalToken:r,appearance:e}){const{appearance:o}=E(),{invoices:n,isLoading:u,error:l}=is(a,r),c=e??o,d=[...n].sort((i,x)=>new Date(x.createdAt).getTime()-new Date(i.createdAt).getTime());return s.jsx(M,{appearance:c,children:s.jsxs("div",{className:"ss-card ss-card-wide",children:[s.jsx("h2",{className:"ss-title",children:"Invoices"}),u&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading..."]}),l&&s.jsx("div",{className:"ss-global-error",children:l}),!u&&d.length===0&&s.jsx("p",{className:"ss-empty",children:"No invoices yet."}),!u&&d.length>0&&s.jsxs("table",{className:"ss-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{className:"ss-th",children:"Date"}),s.jsx("th",{className:"ss-th",children:"Amount"}),s.jsx("th",{className:"ss-th",children:"Status"}),s.jsx("th",{className:"ss-th",children:"PDF"})]})}),s.jsx("tbody",{children:d.map(i=>s.jsxs("tr",{className:"ss-tr",children:[s.jsx("td",{className:"ss-td",children:Ms(i.createdAt)}),s.jsx("td",{className:"ss-td",children:Us(i.amountCents)}),s.jsx("td",{className:"ss-td",children:s.jsx("span",{className:`ss-badge ${Ds[i.status]||""}`,children:i.status})}),s.jsx("td",{className:"ss-td",children:i.pdfUrl?s.jsx("a",{className:"ss-link",href:i.pdfUrl,target:"_blank",rel:"noopener noreferrer",children:"Download"}):"—"})]},i.id))})]})]})})}function us({customerId:a,limits:r,portalToken:e,appearance:o}){const{appearance:n}=E(),{usage:u,isLoading:l,error:c}=ls(a,e),d=o??n;return s.jsx(M,{appearance:d,children:s.jsxs("div",{className:"ss-card",children:[s.jsx("h2",{className:"ss-title",children:"Usage"}),l&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading..."]}),c&&s.jsx("div",{className:"ss-global-error",children:c}),!l&&u.length===0&&s.jsx("p",{className:"ss-empty",children:"No usage data."}),!l&&u.map(i=>{const x=r==null?void 0:r[i.metric],p=x?Math.min(100,i.total/x*100):null;return s.jsxs("div",{className:"ss-usage-item",children:[s.jsxs("div",{className:"ss-usage-header",children:[s.jsx("span",{className:"ss-usage-metric",children:i.metric}),s.jsxs("span",{className:"ss-usage-value",children:[i.total.toLocaleString(),x?` / ${x.toLocaleString()}`:""]})]}),p!==null&&s.jsx("div",{className:"ss-progress-bar",children:s.jsx("div",{className:`ss-progress-fill ${p>90?"ss-progress-danger":""}`,style:{width:`${p}%`}})})]},i.metric)})]})})}function Vs({customerId:a,portalToken:r,limits:e,onChangePlan:o,onCancel:n,appearance:u}){const{appearance:l}=E(),c=u??l,[d,i]=t.useState("subscription"),x=[{id:"subscription",label:"Subscription"},{id:"invoices",label:"Invoices"},{id:"usage",label:"Usage"}];return s.jsx(M,{appearance:c,children:s.jsxs("div",{className:"ss-card ss-card-wide",children:[s.jsx("h2",{className:"ss-title",children:"Billing"}),s.jsx("div",{className:"ss-tab-group",children:x.map(p=>s.jsx("button",{type:"button",className:`ss-tab ${d===p.id?"ss-tab-active":""}`,onClick:()=>i(p.id),children:p.label},p.id))}),s.jsxs("div",{className:"ss-tab-content",children:[d==="subscription"&&s.jsx(cs,{customerId:a,portalToken:r,onChangePlan:o,onCancel:n}),d==="invoices"&&s.jsx(ds,{customerId:a,portalToken:r}),d==="usage"&&s.jsx(us,{customerId:a,portalToken:r,limits:e})]})]})})}function Rs({customerId:a,portalToken:r,onApplied:e,appearance:o}){const{appearance:n}=E(),u=W(r),l=o??n,[c,d]=t.useState(""),[i,x]=t.useState(!1),[p,g]=t.useState(null),[f,v]=t.useState(null),b=t.useCallback(async N=>{if(N.preventDefault(),!!c.trim()){x(!0),g(null),v(null);try{const h=await u.applyCoupon(a,c.trim());v(`Coupon applied! ${h.discountType==="percent"?`${h.amount}% off`:`$${(h.amount/100).toFixed(2)} off`}`),d(""),e==null||e(h)}catch(h){g(h instanceof Error?h.message:"Invalid coupon code")}finally{x(!1)}}},[u,a,c,e]);return s.jsx(M,{appearance:l,children:s.jsxs("div",{className:"ss-card",children:[s.jsx("h2",{className:"ss-title",children:"Apply coupon"}),p&&s.jsx("div",{className:"ss-global-error",children:p}),f&&s.jsx("div",{className:"ss-success-msg",children:f}),s.jsxs("form",{onSubmit:b,children:[s.jsxs("div",{className:"ss-field",children:[s.jsx("label",{className:"ss-label",htmlFor:"ss-coupon-code",children:"Coupon code"}),s.jsx("input",{id:"ss-coupon-code",className:"ss-input",type:"text",placeholder:"Enter coupon code",value:c,onChange:N=>d(N.target.value),required:!0})]}),s.jsxs("button",{type:"submit",className:"ss-btn ss-btn-primary",disabled:i||!c.trim(),children:[i&&s.jsx("span",{className:"ss-spinner"}),"Apply"]})]})]})})}function qs(){const{client:a}=E();return{report:a.report}}function ss(){const{client:a}=E(),[r,e]=t.useState(null),[o,n]=t.useState(!1),[u,l]=t.useState(null),c=t.useCallback(async d=>{n(!0),l(null);try{const i=await a.report.executeQuery(d);return e(i),i}catch(i){return l(i instanceof Error?i.message:"Query failed"),null}finally{n(!1)}},[a]);return{result:r,execute:c,isLoading:o,error:u}}function ps(a){const{client:r}=E(),[e,o]=t.useState(null),[n,u]=t.useState(!0),[l,c]=t.useState(null),d=t.useCallback(async()=>{u(!0),c(null);try{const i=await r.report.listQueries(a);o(i)}catch(i){c(i instanceof Error?i.message:"Failed to load queries")}finally{u(!1)}},[r,a]);return t.useEffect(()=>{d()},[d]),{queries:(e==null?void 0:e.data)??[],meta:e==null?void 0:e.meta,isLoading:n,error:l,refresh:d}}function Hs(a){const{client:r}=E(),[e,o]=t.useState(null),[n,u]=t.useState(!0),[l,c]=t.useState(null),d=t.useCallback(async()=>{u(!0),c(null);try{const i=await r.report.getDashboard(a);o(i)}catch(i){c(i instanceof Error?i.message:"Failed to load dashboard")}finally{u(!1)}},[r,a]);return t.useEffect(()=>{d()},[d]),{dashboard:e,isLoading:n,error:l,refresh:d}}function Ws(a,r,e="https://api.saas-support.com/v1"){const o=t.useMemo(()=>{const p=new U.Transport(e,{type:"embedToken",token:a});return new U.ReportClient(p)},[a,e]),[n,u]=t.useState(null),[l,c]=t.useState(!0),[d,i]=t.useState(null),x=t.useCallback(async()=>{c(!0),i(null);try{const p=await o.getDashboard(r);u(p)}catch(p){i(p instanceof Error?p.message:"Failed to load dashboard")}finally{c(!1)}},[o,r]);return t.useEffect(()=>{x()},[x]),{dashboard:n,reportClient:o,isLoading:l,error:d,refresh:x}}function _s({onResult:a,mode:r="both",placeholder:e,appearance:o}){const{appearance:n}=E(),{execute:u,isLoading:l,error:c}=ss(),d=o??n,[i,x]=t.useState(""),[p,g]=t.useState(r==="sql"?"sql":"nl"),f=t.useCallback(async v=>{if(v.preventDefault(),!i.trim())return;const N=await u(p==="sql"?{sql:i}:{naturalLanguage:i});N&&(a==null||a(N))},[i,p,u,a]);return s.jsx(M,{appearance:d,children:s.jsxs("div",{className:"ss-card ss-card-wide",children:[r==="both"&&s.jsxs("div",{className:"ss-tab-group ss-tab-group-sm",children:[s.jsx("button",{type:"button",className:`ss-tab ${p==="nl"?"ss-tab-active":""}`,onClick:()=>g("nl"),children:"Natural Language"}),s.jsx("button",{type:"button",className:`ss-tab ${p==="sql"?"ss-tab-active":""}`,onClick:()=>g("sql"),children:"SQL"})]}),c&&s.jsx("div",{className:"ss-global-error",children:c}),s.jsxs("form",{onSubmit:f,children:[s.jsx("div",{className:"ss-field",children:s.jsx("textarea",{className:"ss-input ss-query-textarea",placeholder:e??(p==="sql"?"SELECT ...":"Ask a question about your data..."),value:i,onChange:v=>x(v.target.value),rows:3})}),s.jsxs("button",{type:"submit",className:"ss-btn ss-btn-primary",disabled:l||!i.trim(),children:[l&&s.jsx("span",{className:"ss-spinner"}),"Run query"]})]})]})})}function hs({columns:a,rows:r,sortable:e=!0,maxRows:o,appearance:n}){const{appearance:u}=E(),l=n??u,[c,d]=t.useState(null),[i,x]=t.useState("asc"),p=t.useMemo(()=>c?[...r].sort((b,N)=>{const h=b[c],j=N[c];if(h==null&&j==null)return 0;if(h==null)return 1;if(j==null)return-1;if(typeof h=="number"&&typeof j=="number")return i==="asc"?h-j:j-h;const S=String(h),k=String(j);return i==="asc"?S.localeCompare(k):k.localeCompare(S)}):r,[r,c,i]),g=o?p.slice(0,o):p,f=b=>{e&&(c===b?x(N=>N==="asc"?"desc":"asc"):(d(b),x("asc")))};function v(b){return b==null?"":typeof b=="object"?JSON.stringify(b):String(b)}return s.jsx(M,{appearance:l,children:s.jsxs("div",{className:"ss-table-container",children:[s.jsxs("table",{className:"ss-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:a.map(b=>s.jsxs("th",{className:`ss-th ${e?"ss-th-sortable":""} ${c===b?i==="asc"?"ss-sorted-asc":"ss-sorted-desc":""}`,onClick:()=>f(b),children:[b,c===b&&s.jsx("span",{className:"ss-sort-indicator",children:i==="asc"?" ▲":" ▼"})]},b))})}),s.jsx("tbody",{children:g.map((b,N)=>s.jsx("tr",{className:"ss-tr",children:a.map(h=>s.jsx("td",{className:"ss-td",children:v(b[h])},h))},N))})]}),o&&r.length>o&&s.jsxs("div",{className:"ss-table-footer",children:["Showing ",o," of ",r.length," rows"]})]})})}function Gs(a,r="#6366f1"){const e=parseInt(r.replace("#","").slice(0,2),16),o=[];for(let n=0;n<a;n++){const u=(e+n*Math.floor(360/Math.max(a,1)))%360;o.push(`hsl(${u}, 65%, 55%)`)}return o}function Ys({labels:a,values:r,w:e,h:o,colors:n}){const u=Math.max(...r,1),l=40,c=e-l*2,d=o-l*2,i=Math.max(1,c/a.length-4);return s.jsxs("g",{children:[s.jsx("line",{x1:l,y1:o-l,x2:e-l,y2:o-l,stroke:"#ccc",strokeWidth:1}),r.map((x,p)=>{const g=x/u*d,f=l+c/a.length*p+2,v=o-l-g;return s.jsxs("g",{children:[s.jsx("rect",{x:f,y:v,width:i,height:g,fill:n[p%n.length],rx:2}),s.jsx("text",{x:f+i/2,y:o-l+14,textAnchor:"middle",fontSize:10,fill:"#666",children:a[p].length>8?a[p].slice(0,8)+"...":a[p]})]},p)})]})}function Qs({labels:a,values:r,w:e,h:o,colors:n}){const u=Math.max(...r,1),l=40,c=e-l*2,d=o-l*2,i=a.length>1?c/(a.length-1):0,x=r.map((p,g)=>{const f=l+i*g,v=o-l-p/u*d;return`${f},${v}`});return s.jsxs("g",{children:[[.25,.5,.75,1].map(p=>{const g=o-l-p*d;return s.jsx("line",{x1:l,y1:g,x2:e-l,y2:g,stroke:"#eee",strokeWidth:1},p)}),s.jsx("polyline",{points:x.join(" "),fill:"none",stroke:n[0],strokeWidth:2}),r.map((p,g)=>{const f=l+i*g,v=o-l-p/u*d;return s.jsx("circle",{cx:f,cy:v,r:4,fill:n[0]},g)})]})}function Js({labels:a,values:r,w:e,h:o,colors:n}){const u=r.reduce((g,f)=>g+f,0)||1,l=e/2,c=o/2-20,d=Math.min(e,o)/2-40,i=2*Math.PI*d;let x=0;const p=r.map((g,f)=>{const v=g/u,b=v*i,N={dash:b,offset:x,color:n[f%n.length],label:a[f],pct:v};return x+=b,N});return s.jsxs("g",{children:[p.map((g,f)=>s.jsx("circle",{cx:l,cy:c,r:d,fill:"none",stroke:g.color,strokeWidth:d*.6,strokeDasharray:`${g.dash} ${i-g.dash}`,strokeDashoffset:-g.offset,transform:`rotate(-90 ${l} ${c})`},f)),s.jsx("g",{transform:`translate(${l-a.length*30}, ${o-20})`,children:p.slice(0,6).map((g,f)=>s.jsxs("g",{transform:`translate(${f*60}, 0)`,children:[s.jsx("rect",{width:10,height:10,fill:g.color,rx:2}),s.jsx("text",{x:14,y:9,fontSize:9,fill:"#666",children:g.label.length>6?g.label.slice(0,6)+"..":g.label})]},f))})]})}function xs({type:a,data:r,title:e,width:o=400,height:n=300,appearance:u}){const{appearance:l}=E(),c=u??l,d=t.useMemo(()=>Gs(r.labels.length),[r.labels.length]);return s.jsx(M,{appearance:c,children:s.jsxs("div",{className:"ss-chart-container",children:[e&&s.jsx("h3",{className:"ss-chart-title",children:e}),s.jsxs("svg",{viewBox:`0 0 ${o} ${n}`,width:"100%",style:{maxWidth:o},children:[a==="bar"&&s.jsx(Ys,{labels:r.labels,values:r.values,w:o,h:n,colors:d}),a==="line"&&s.jsx(Qs,{labels:r.labels,values:r.values,w:o,h:n,colors:d}),a==="pie"&&s.jsx(Js,{labels:r.labels,values:r.values,w:o,h:n,colors:d})]})]})})}function Zs({dashboardId:a,embedToken:r,baseUrl:e,refreshInterval:o,appearance:n}){const u=E(),l=n??(u==null?void 0:u.appearance),c=t.useMemo(()=>{if(r){const h=e??"https://api.saas-support.com/v1",j=new U.Transport(h,{type:"embedToken",token:r});return new U.ReportClient(j)}return u.client.report},[r,e,u]),[d,i]=t.useState([]),[x,p]=t.useState({}),[g,f]=t.useState(!0),[v,b]=t.useState(null),N=t.useCallback(async()=>{f(!0),b(null);try{const h=await c.getDashboard(a),j=JSON.parse(h.layoutJson||"[]");i(j);const S={};for(const k of j)try{const P=await c.listQueries({search:k.queryId,perPage:1});if(P.data.length>0&&P.data[0].generatedSql){const z=await c.executeQuery({sql:P.data[0].generatedSql});S[k.queryId]=z}}catch{}p(S)}catch(h){b(h instanceof Error?h.message:"Failed to load dashboard")}finally{f(!1)}},[c,a]);return t.useEffect(()=>{N()},[N]),t.useEffect(()=>{if(!o||o<=0)return;const h=setInterval(N,o*1e3);return()=>clearInterval(h)},[o,N]),s.jsx(M,{appearance:l,children:s.jsxs("div",{className:"ss-dashboard-grid",children:[g&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading dashboard..."]}),v&&s.jsx("div",{className:"ss-global-error",children:v}),!g&&d.map((h,j)=>{const S=x[h.queryId];if(!S)return null;const k=S.columns.length>=2?{labels:S.rows.map(P=>String(P[S.columns[0]]??"")),values:S.rows.map(P=>Number(P[S.columns[1]]??0))}:{labels:[],values:[]};return s.jsxs("div",{className:"ss-widget",children:[h.title&&s.jsx("h4",{className:"ss-widget-header",children:h.title}),h.chartType==="table"?s.jsx(hs,{columns:S.columns,rows:S.rows,maxRows:50}):s.jsx(xs,{type:h.chartType||"bar",data:k,width:h.w,height:h.h})]},j)})]})})}function Ks(a){return new Date(a).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}function Xs({onSelectQuery:a,onRunQuery:r,appearance:e}){const{appearance:o}=E(),{queries:n,isLoading:u,error:l}=ps(),{execute:c,isLoading:d}=ss(),i=e??o,x=t.useCallback(async p=>{if(!p.generatedSql)return;const g=await c({sql:p.generatedSql});g&&(r==null||r(g))},[c,r]);return s.jsx(M,{appearance:i,children:s.jsxs("div",{className:"ss-card ss-card-wide",children:[s.jsx("h2",{className:"ss-title",children:"Saved Queries"}),u&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading..."]}),l&&s.jsx("div",{className:"ss-global-error",children:l}),!u&&n.length===0&&s.jsx("p",{className:"ss-empty",children:"No saved queries."}),!u&&n.map(p=>s.jsxs("div",{className:"ss-saved-query-card",onClick:()=>a==null?void 0:a(p),children:[s.jsxs("div",{className:"ss-saved-query-header",children:[s.jsx("span",{className:"ss-saved-query-name",children:p.name}),p.chartType&&s.jsx("span",{className:"ss-badge",children:p.chartType})]}),p.naturalLanguage&&s.jsx("p",{className:"ss-saved-query-desc",children:p.naturalLanguage}),s.jsxs("div",{className:"ss-saved-query-footer",children:[s.jsx("span",{className:"ss-saved-query-date",children:Ks(p.createdAt)}),s.jsx("button",{type:"button",className:"ss-btn ss-btn-sm ss-btn-primary",disabled:d||!p.generatedSql,onClick:g=>{g.stopPropagation(),x(p)},children:d?s.jsx("span",{className:"ss-spinner"}):"Run"})]})]},p.id))]})})}function sa({embedToken:a,dashboardId:r,baseUrl:e="https://api.saas-support.com/v1",refreshInterval:o,appearance:n}){const u=t.useMemo(()=>{const b=new U.Transport(e,{type:"embedToken",token:a});return new U.ReportClient(b)},[a,e]),[l,c]=t.useState([]),[d,i]=t.useState(!0),[x,p]=t.useState(null),g=t.useMemo(()=>Y(n),[n]),f=t.useMemo(()=>Q(g),[g]),v=t.useCallback(async()=>{i(!0),p(null);try{const b=await u.getDashboard(r),N=JSON.parse(b.layoutJson||"[]"),h=await Promise.all(N.map(async j=>{try{const S=await u.listQueries({search:j.queryId,perPage:1});if(S.data.length>0&&S.data[0].generatedSql){const k=await u.executeQuery({sql:S.data[0].generatedSql});return{...j,result:k}}}catch{}return j}));c(h)}catch(b){p(b instanceof Error?b.message:"Failed to load dashboard")}finally{i(!1)}},[u,r]);return t.useEffect(()=>{v()},[v]),t.useEffect(()=>{if(!o||o<=0)return;const b=setInterval(v,o*1e3);return()=>clearInterval(b)},[o,v]),s.jsx("div",{ref:b=>{if(!b||b.shadowRoot)return;const N=b.attachShadow({mode:"open"}),h=document.createElement("style");h.textContent=f,N.appendChild(h);const j=document.createElement("div");N.appendChild(j)},style:{display:"contents"},children:s.jsxs("div",{className:"ss-dashboard-grid",children:[d&&s.jsx("div",{className:"ss-loading",children:"Loading dashboard..."}),x&&s.jsx("div",{className:"ss-global-error",children:x}),!d&&l.map((b,N)=>{if(!b.result)return null;const{columns:h,rows:j}=b.result;return s.jsxs("div",{className:"ss-widget",children:[b.title&&s.jsx("h4",{className:"ss-widget-header",children:b.title}),s.jsxs("table",{className:"ss-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:h.map(S=>s.jsx("th",{className:"ss-th",children:S},S))})}),s.jsx("tbody",{children:j.slice(0,50).map((S,k)=>s.jsx("tr",{className:"ss-tr",children:h.map(P=>s.jsx("td",{className:"ss-td",children:String(S[P]??"")},P))},k))})]})]},N)})]})})}exports.SaaSError=U.SaaSError;exports.SaaSSupport=U.SaaSSupport;exports.isMfaRequired=U.isMfaRequired;exports.Chart=xs;exports.CouponInput=Rs;exports.DashboardView=Zs;exports.DataTable=hs;exports.InvoiceHistory=ds;exports.OrgSwitcher=Fs;exports.PaymentPortal=Vs;exports.PricingTable=Bs;exports.QueryInput=_s;exports.ReportEmbed=sa;exports.SaaSContext=J;exports.SaaSProvider=js;exports.SavedQueryList=Xs;exports.SignIn=Cs;exports.SignUp=Ps;exports.SubscriptionStatus=cs;exports.UsageDisplay=us;exports.UserButton=Es;exports.UserProfile=Is;exports.useAuth=H;exports.useBilling=Ts;exports.useDashboard=Hs;exports.useDeleteAccount=es;exports.useEmbedDashboard=Ws;exports.useInvoices=is;exports.useOrg=K;exports.useProfile=X;exports.useQuery=ss;exports.useReport=qs;exports.useSaaSContext=E;exports.useSavedQueries=ps;exports.useSignIn=Z;exports.useSignUp=as;exports.useSubscription=os;exports.useUsage=ls;exports.useUser=$s;
2043
+ `}function M({children:a,appearance:r}){const e=t.useRef(null),[o,n]=t.useState(null);t.useEffect(()=>{var x;if(!e.current||e.current.shadowRoot){n(((x=e.current)==null?void 0:x.shadowRoot)??null);return}const l=e.current.attachShadow({mode:"open"});if((r==null?void 0:r.fontUrl)!==null){const p=(r==null?void 0:r.fontUrl)??"https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Inter:wght@400;500;600&family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap";if(!document.querySelector(`link[href="${p}"]`)){const f=document.createElement("link");f.rel="stylesheet",f.href=p,document.head.appendChild(f)}const g=document.createElement("link");g.rel="stylesheet",g.href=p,l.appendChild(g)}const c=Y(r),d=document.createElement("style");d.textContent=Q(c),l.appendChild(d);const i=document.createElement("div");l.appendChild(i),n(l)},[]),t.useEffect(()=>{if(!o)return;const l=o.querySelector("style");if(l){const c=Y(r);l.textContent=Q(c)}},[r,o]);const u=(o==null?void 0:o.querySelector("div"))??null;return s.jsx("div",{ref:e,style:{display:"contents"},children:u&&vs.createPortal(a,u)})}function H(){const{client:a,user:r,isLoaded:e}=E();return{isLoaded:e,isSignedIn:!!r,user:r,signOut:t.useCallback(()=>a.auth.signOut(),[a]),getToken:t.useCallback(()=>a.auth.getToken(),[a]),refreshUser:t.useCallback(()=>a.auth.refreshUser(),[a])}}function $s(){const{user:a,isLoaded:r}=E();return{user:a,isLoaded:r}}function Z(){const{client:a}=E(),[r,e]=t.useState(!1),[o,n]=t.useState(null),u=t.useCallback(async(d,i)=>{e(!0),n(null);try{return await a.auth.signIn(d,i)}catch(x){return n(x instanceof Error?x.message:"Sign in failed"),null}finally{e(!1)}},[a]),l=t.useCallback(async d=>{e(!0),n(null);try{return await a.auth.signInWithOAuth(d)}catch(i){return n(i instanceof Error?i.message:"OAuth sign in failed"),null}finally{e(!1)}},[a]),c=t.useCallback(async(d,i)=>{e(!0),n(null);try{return await a.auth.submitMfaCode(d,i)}catch(x){return n(x instanceof Error?x.message:"MFA verification failed"),null}finally{e(!1)}},[a]);return{signIn:u,signInWithOAuth:l,submitMfaCode:c,isLoading:r,error:o,setError:n}}function as(){const{client:a}=E(),[r,e]=t.useState(!1),[o,n]=t.useState(null);return{signUp:t.useCallback(async(l,c)=>{e(!0),n(null);try{return await a.auth.signUp(l,c)}catch(d){return n(d instanceof Error?d.message:"Sign up failed"),null}finally{e(!1)}},[a]),isLoading:r,error:o,setError:n}}function K(){const{client:a}=E(),[r,e]=t.useState([]),[o,n]=t.useState(null),[u,l]=t.useState([]),[c,d]=t.useState([]),[i,x]=t.useState(!1),[p,g]=t.useState(null),f=t.useCallback(async()=>{x(!0),g(null);try{const w=await a.auth.listOrgs();e(w);const m=typeof window<"u"?localStorage.getItem("ss_selected_org"):null;if(m&&w.some(y=>y.id===m)&&!o){const y=w.find(C=>C.id===m);n(y);try{const C=await a.auth.listMembers(y.id);l(C)}catch{}}}catch(w){g(w instanceof Error?w.message:"Failed to load organizations")}finally{x(!1)}},[a,o]);t.useEffect(()=>{f()},[f]);const v=t.useCallback(async w=>{try{const m=await a.auth.getOrg(w);n(m),typeof window<"u"&&localStorage.setItem("ss_selected_org",w);const y=await a.auth.listMembers(w);l(y)}catch(m){g(m instanceof Error?m.message:"Failed to load organization")}},[a]),b=t.useCallback(async(w,m)=>{try{const y=await a.auth.createOrg(w,m);return e(C=>[...C,y]),y}catch(y){return g(y instanceof Error?y.message:"Failed to create organization"),null}},[a]),N=t.useCallback(async(w,m)=>{try{const y=await a.auth.updateOrg(w,m);return e(C=>C.map(B=>B.id===w?y:B)),(o==null?void 0:o.id)===w&&n(y),y}catch(y){return g(y instanceof Error?y.message:"Failed to update organization"),null}},[a,o]),h=t.useCallback(async w=>{try{return await a.auth.deleteOrg(w),e(m=>m.filter(y=>y.id!==w)),(o==null?void 0:o.id)===w&&(n(null),l([]),d([]),typeof window<"u"&&localStorage.removeItem("ss_selected_org")),!0}catch(m){return g(m instanceof Error?m.message:"Failed to delete organization"),!1}},[a,o]),j=t.useCallback(async(w,m,y)=>{try{return await a.auth.sendInvite(w,m,y)}catch(C){return g(C instanceof Error?C.message:"Failed to send invite"),null}},[a]),S=t.useCallback(async w=>{try{const m=await a.auth.listInvites(w);d(m)}catch(m){g(m instanceof Error?m.message:"Failed to load invites")}},[a]),k=t.useCallback(async(w,m)=>{try{return await a.auth.revokeInvite(w,m),d(y=>y.filter(C=>C.id!==m)),!0}catch(y){return g(y instanceof Error?y.message:"Failed to revoke invite"),!1}},[a]),P=t.useCallback(async(w,m,y)=>{try{return await a.auth.updateMemberRole(w,m,y),l(C=>C.map(B=>B.userId===m?{...B,role:y}:B)),!0}catch(C){return g(C instanceof Error?C.message:"Failed to update member role"),!1}},[a]),z=t.useCallback(async(w,m)=>{try{return await a.auth.removeMember(w,m),l(y=>y.filter(C=>C.userId!==m)),!0}catch(y){return g(y instanceof Error?y.message:"Failed to remove member"),!1}},[a]),F=t.useCallback(async w=>{try{const m=await a.auth.listMembers(w);l(m)}catch(m){g(m instanceof Error?m.message:"Failed to load members")}},[a]);return{orgs:r,selectedOrg:o,members:u,invites:c,isLoading:i,error:p,setError:g,refresh:f,selectOrg:v,createOrg:b,updateOrg:N,deleteOrg:h,sendInvite:j,refreshInvites:S,revokeInvite:k,updateMemberRole:P,removeMember:z,refreshMembers:F}}function es(){const{client:a}=E(),[r,e]=t.useState(!1),[o,n]=t.useState(null);return{deleteAccount:t.useCallback(async()=>{e(!0),n(null);try{return await a.auth.deleteAccount(),!0}catch(l){return n(l instanceof Error?l.message:"Failed to delete account"),!1}finally{e(!1)}},[a]),isLoading:r,error:o,setError:n}}function X(){const{client:a,user:r}=E(),[e,o]=t.useState(!1),[n,u]=t.useState(null),[l,c]=t.useState(null),d=t.useCallback(async p=>{o(!0),u(null),c(null);try{const g=await a.auth.updateProfile(p);return c("Profile updated"),g}catch(g){return u(g instanceof Error?g.message:"Failed to update profile"),null}finally{o(!1)}},[a]),i=t.useCallback(async(p,g)=>{o(!0),u(null),c(null);try{return await a.auth.changePassword(p,g),c("Password changed successfully"),!0}catch(f){return u(f instanceof Error?f.message:"Failed to change password"),!1}finally{o(!1)}},[a]),x=t.useCallback(async p=>{o(!0),u(null),c(null);try{const g=await a.auth.uploadAvatar(p);return c("Avatar updated"),g}catch(g){return u(g instanceof Error?g.message:"Failed to upload avatar"),null}finally{o(!1)}},[a]);return{user:r,updateProfile:d,uploadAvatar:x,changePassword:i,isLoading:e,error:n,success:l,setError:u,setSuccess:c}}const ts='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>',rs='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" fill="currentColor"/></svg>',$={close:"close",person:"person",logout:"logout",checkCircle:"check_circle",unfoldMore:"unfold_more",cloudUpload:"cloud_upload",zoomIn:"zoom_in",zoomOut:"zoom_out",lock:"lock",visibility:"visibility",visibilityOff:"visibility_off",add:"add",addCircle:"add_circle",camera:"photo_camera",security:"security",errorOutline:"error_outline",info:"info",arrowForward:"arrow_forward",verified:"verified",token:"token",autoAwesome:"auto_awesome",corporateFare:"corporate_fare",cloudDone:"cloud_done",check:"check",image:"image"};function Cs({appearance:a,signUpUrl:r,onSignUp:e}){const{appearance:o,settings:n}=E(),{signIn:u,signInWithOAuth:l,submitMfaCode:c,isLoading:d,error:i,setError:x}=Z(),p=a??o,[g,f]=t.useState(""),[v,b]=t.useState(""),[N,h]=t.useState(!1),[j,S]=t.useState(!1),[k,P]=t.useState(""),[z,F]=t.useState(["","","","","",""]),w=t.useRef([]),m=t.useCallback(async L=>{if(L.preventDefault(),j){await c(k,z.join(""));return}const T=await u(g,v);T&&U.isMfaRequired(T)&&(P(T.mfaToken),S(!0),x(null))},[g,v,j,k,z,u,c,x]),y=t.useCallback(async L=>{await l(L)},[l]),C=t.useCallback((L,T)=>{var R;if(!/^\d*$/.test(T))return;const O=T.slice(-1);F(_=>{const q=[..._];return q[L]=O,q}),O&&L<5&&((R=w.current[L+1])==null||R.focus())},[]),B=t.useCallback((L,T)=>{var O;T.key==="Backspace"&&!z[L]&&L>0&&((O=w.current[L-1])==null||O.focus())},[z]),D=(n==null?void 0:n.googleEnabled)||(n==null?void 0:n.githubEnabled);return s.jsx(M,{appearance:p,children:s.jsx("div",{className:"ss-auth-card",children:s.jsxs("div",{className:"ss-auth-card-body",children:[s.jsxs("div",{className:"ss-auth-header",children:[s.jsx("div",{className:"ss-auth-brand-icon",children:s.jsx("span",{className:"material-symbols-outlined",children:$.token})}),s.jsx("h1",{className:"ss-auth-title",children:"Sign in to your account"}),s.jsx("p",{className:"ss-auth-subtitle",children:"Welcome back to your workspace"})]}),!j&&D&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"ss-auth-oauth-grid",children:[(n==null?void 0:n.googleEnabled)&&s.jsxs("button",{type:"button",className:"ss-auth-btn-social",onClick:()=>y("google"),disabled:d,children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:ts}}),"Google"]}),(n==null?void 0:n.githubEnabled)&&s.jsxs("button",{type:"button",className:"ss-auth-btn-social",onClick:()=>y("github"),disabled:d,children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:rs}}),"GitHub"]})]}),s.jsx("div",{className:"ss-auth-divider",children:"or continue with"})]}),i&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:i})]}),s.jsxs("form",{onSubmit:m,children:[j?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"ss-auth-mfa-divider",children:s.jsx("span",{children:"Verification Required"})}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"6-Digit Code"}),s.jsx("div",{className:"ss-auth-mfa-group",children:z.map((L,T)=>s.jsx("input",{ref:O=>{w.current[T]=O},className:"ss-auth-mfa-digit",type:"text",inputMode:"numeric",maxLength:1,value:L,onChange:O=>C(T,O.target.value),onKeyDown:O=>B(T,O),autoFocus:T===0},T))}),s.jsx("p",{className:"ss-auth-mfa-hint",children:"We sent a 6-digit code to your registered email."})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-email",children:"Email Address"}),s.jsx("input",{id:"ss-email",className:"ss-auth-input",type:"email",autoComplete:"email",placeholder:"name@company.com",value:g,onChange:L=>f(L.target.value),required:!0})]}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsxs("div",{className:"ss-auth-field-row",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-password",style:{marginBottom:0},children:"Password"}),s.jsx("span",{className:"ss-auth-link",style:{fontSize:"12px"},children:"Forgot?"})]}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{id:"ss-password",className:"ss-auth-input",type:N?"text":"password",autoComplete:"current-password",placeholder:"••••••••",value:v,onChange:L=>b(L.target.value),required:!0}),s.jsx("button",{type:"button",className:"ss-auth-visibility-toggle",onClick:()=>h(!N),children:s.jsx("span",{className:"material-symbols-outlined",children:N?$.visibilityOff:$.visibility})})]})]})]}),s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary",disabled:d,children:[d&&s.jsx("span",{className:"ss-auth-spinner"}),j?"Verify":"Sign in",!d&&s.jsx("span",{className:"material-symbols-outlined",children:$.arrowForward})]})]}),j?s.jsx("div",{className:"ss-auth-footer",children:s.jsx("span",{className:"ss-auth-link",onClick:()=>{S(!1),F(["","","","","",""]),x(null)},children:"Back to sign in"})}):s.jsxs("div",{className:"ss-auth-footer",children:["Don't have an account?"," ",e?s.jsx("span",{className:"ss-auth-link",onClick:e,children:"Sign up"}):r?s.jsx("a",{className:"ss-auth-link",href:r,children:"Sign up"}):s.jsx("span",{className:"ss-auth-link",children:"Sign up"})]})]})})})}function Ps({appearance:a,signInUrl:r,onSignIn:e}){const{appearance:o,settings:n}=E(),{signUp:u,isLoading:l,error:c,setError:d}=as(),{signInWithOAuth:i}=Z(),x=a??o,[p,g]=t.useState(""),[f,v]=t.useState(""),[b,N]=t.useState(""),[h,j]=t.useState(!1),[S,k]=t.useState(null),P=t.useCallback(async m=>{if(m.preventDefault(),k(null),f!==b){k("Passwords do not match");return}const y=(n==null?void 0:n.passwordMinLength)??8;if(f.length<y){k(`Password must be at least ${y} characters`);return}await u(p,f)},[p,f,b,n,u]),z=t.useCallback(async m=>{await i(m)},[i]),F=(n==null?void 0:n.googleEnabled)||(n==null?void 0:n.githubEnabled),w=S||c;return s.jsx(M,{appearance:x,children:s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",width:"100%",maxWidth:"520px"},children:[s.jsxs("div",{className:"ss-auth-header",children:[s.jsx("div",{className:"ss-auth-brand-icon-gradient",children:s.jsx("span",{className:"material-symbols-outlined",children:$.autoAwesome})}),s.jsx("h1",{className:"ss-auth-title ss-auth-title-lg",children:"Create your account"}),s.jsx("p",{className:"ss-auth-subtitle",children:"Join the ecosystem"})]}),s.jsx("div",{className:"ss-auth-card",children:s.jsxs("div",{className:"ss-auth-card-body",children:[F&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"ss-auth-oauth-grid",children:[(n==null?void 0:n.googleEnabled)&&s.jsxs("button",{type:"button",className:"ss-auth-btn-social",onClick:()=>z("google"),disabled:l,children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:ts}}),"Google"]}),(n==null?void 0:n.githubEnabled)&&s.jsxs("button",{type:"button",className:"ss-auth-btn-social",onClick:()=>z("github"),disabled:l,children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:rs}}),"GitHub"]})]}),s.jsx("div",{className:"ss-auth-divider",children:"or sign up with email"})]}),w&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:w})]}),s.jsxs("form",{onSubmit:P,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-signup-email",children:"Email"}),s.jsx("input",{id:"ss-signup-email",className:"ss-auth-input",type:"email",autoComplete:"email",placeholder:"name@company.com",value:p,onChange:m=>g(m.target.value),required:!0})]}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-signup-password",children:"Password"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{id:"ss-signup-password",className:"ss-auth-input",type:h?"text":"password",autoComplete:"new-password",placeholder:"••••••••",value:f,onChange:m=>{v(m.target.value),k(null)},required:!0}),s.jsx("button",{type:"button",className:"ss-auth-visibility-toggle",onClick:()=>j(!h),children:s.jsx("span",{className:"material-symbols-outlined",children:h?$.visibilityOff:$.visibility})})]})]}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",htmlFor:"ss-signup-confirm",children:"Confirm Password"}),s.jsx("input",{id:"ss-signup-confirm",className:"ss-auth-input",type:"password",autoComplete:"new-password",placeholder:"••••••••",value:b,onChange:m=>{N(m.target.value),k(null)},required:!0})]}),s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary",disabled:l,children:[l&&s.jsx("span",{className:"ss-auth-spinner"}),"Sign up",!l&&s.jsx("span",{className:"material-symbols-outlined",children:$.arrowForward})]})]}),s.jsxs("div",{className:"ss-auth-footer",children:["Already have an account?"," ",e?s.jsx("span",{className:"ss-auth-link",onClick:e,children:"Sign in"}):r?s.jsx("a",{className:"ss-auth-link",href:r,children:"Sign in"}):s.jsx("span",{className:"ss-auth-link",children:"Sign in"})]})]})})]})})}const I=320,V=128;function zs({file:a,onCrop:r,onCancel:e}){const o=t.useRef(null),n=t.useRef(null),[u,l]=t.useState(1),[c,d]=t.useState({x:0,y:0}),[i,x]=t.useState(!1),p=t.useRef({x:0,y:0,ox:0,oy:0}),[g,f]=t.useState(!1);t.useEffect(()=>{const h=new Image,j=URL.createObjectURL(a);return h.onload=()=>{n.current=h,f(!0),d({x:0,y:0}),l(1)},h.src=j,()=>URL.revokeObjectURL(j)},[a]),t.useEffect(()=>{if(!g||!n.current||!o.current)return;const h=o.current.getContext("2d");if(!h)return;const j=n.current;h.clearRect(0,0,I,I),h.fillStyle="#111",h.fillRect(0,0,I,I);const S=Math.max(I/j.width,I/j.height)*u,k=j.width*S,P=j.height*S,z=(I-k)/2+c.x,F=(I-P)/2+c.y;h.save(),h.beginPath(),h.arc(I/2,I/2,V,0,Math.PI*2),h.clip(),h.drawImage(j,z,F,k,P),h.restore(),h.save(),h.fillStyle="rgba(0, 0, 0, 0.6)",h.fillRect(0,0,I,I),h.globalCompositeOperation="destination-out",h.beginPath(),h.arc(I/2,I/2,V,0,Math.PI*2),h.fill(),h.restore(),h.save(),h.beginPath(),h.arc(I/2,I/2,V,0,Math.PI*2),h.clip(),h.drawImage(j,z,F,k,P),h.restore(),h.strokeStyle="rgba(255, 255, 255, 0.4)",h.lineWidth=2,h.beginPath(),h.arc(I/2,I/2,V,0,Math.PI*2),h.stroke()},[u,c,g]);const v=t.useCallback(h=>{x(!0),p.current={x:h.clientX,y:h.clientY,ox:c.x,oy:c.y},h.target.setPointerCapture(h.pointerId)},[c]),b=t.useCallback(h=>{i&&d({x:p.current.ox+(h.clientX-p.current.x),y:p.current.oy+(h.clientY-p.current.y)})},[i]),N=t.useCallback(()=>x(!1),[]);return t.useCallback(()=>{if(!n.current)return;const h=document.createElement("canvas"),j=V*2;h.width=j,h.height=j;const S=h.getContext("2d");if(!S)return;const k=n.current,P=Math.max(I/k.width,I/k.height)*u,z=k.width*P,F=k.height*P,w=(I-z)/2+c.x-(I/2-V),m=(I-F)/2+c.y-(I/2-V);S.beginPath(),S.arc(V,V,V,0,Math.PI*2),S.clip(),S.drawImage(k,w,m,z,F),h.toBlob(y=>{y&&r(y)},"image/png")},[u,c,r]),s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"24px"},children:[s.jsxs("div",{className:"ss-auth-crop-area",children:[s.jsx("canvas",{ref:o,width:I,height:I,style:{cursor:i?"grabbing":"grab",width:"100%",height:"100%"},onPointerDown:v,onPointerMove:b,onPointerUp:N}),s.jsx("div",{className:"ss-auth-crop-size-badge",children:"256 x 256 px"})]}),s.jsxs("div",{className:"ss-auth-zoom-control",style:{width:"100%",maxWidth:"280px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.zoomOut}),s.jsx("input",{type:"range",min:"1",max:"3",step:"0.01",value:u,onChange:h=>l(parseFloat(h.target.value)),className:"ss-auth-zoom-slider"}),s.jsx("span",{className:"material-symbols-outlined",children:$.zoomIn})]})]})}function ns({onUpload:a,onClose:r,isLoading:e}){const[o,n]=t.useState(null),[u,l]=t.useState(!1),[c,d]=t.useState(null),i=t.useRef(null),x=t.useCallback(f=>{if(!f.type.startsWith("image/")){d("Please select an image file");return}if(f.size>5*1024*1024){d("Image must be smaller than 5 MB");return}d(null),n(f)},[]),p=t.useCallback(f=>{f.preventDefault(),l(!1);const v=f.dataTransfer.files[0];v&&x(v)},[x]),g=t.useCallback(async f=>{await a(f)},[a]);return s.jsx("div",{className:"ss-auth-modal-overlay",onClick:f=>{f.target===f.currentTarget&&r()},children:s.jsxs("div",{className:"ss-auth-modal ss-auth-card-wide",children:[s.jsxs("div",{className:"ss-auth-modal-header",children:[s.jsx("h2",{children:"Upload avatar"}),s.jsx("button",{type:"button",className:"ss-auth-modal-close",onClick:r,children:s.jsx("span",{className:"material-symbols-outlined",children:$.close})})]}),s.jsxs("div",{className:"ss-auth-modal-body",children:[c&&s.jsxs("div",{className:"ss-auth-error",style:{marginBottom:"24px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:c})]}),s.jsxs("div",{className:"ss-auth-upload-grid",children:[s.jsx("div",{children:o?s.jsx(zs,{file:o,onCrop:g,onCancel:()=>n(null)}):s.jsxs("div",{className:"ss-auth-crop-area",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"8px",width:"100%",aspectRatio:"1"},children:[s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"48px",opacity:.3},children:$.image}),s.jsx("span",{style:{fontSize:"12px",opacity:.4},children:"No image selected"})]})}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:[s.jsxs("div",{className:`ss-auth-dropzone${u?" ss-auth-dropzone-active":""}`,onDragOver:f=>{f.preventDefault(),l(!0)},onDragLeave:()=>l(!1),onDrop:p,onClick:()=>{var f;return(f=i.current)==null?void 0:f.click()},style:{minHeight:"180px"},children:[s.jsx("div",{className:"ss-auth-dropzone-icon",children:s.jsx("span",{className:"material-symbols-outlined",children:$.cloudUpload})}),s.jsx("span",{className:"ss-auth-dropzone-title",children:"Drag and drop"}),s.jsxs("span",{className:"ss-auth-dropzone-desc",children:["JPG, PNG or WEBP",s.jsx("br",{}),"Max file size 5 MB"]}),s.jsx("button",{type:"button",className:"ss-auth-dropzone-btn",children:"Choose File"}),s.jsx("input",{ref:i,type:"file",accept:"image/*",style:{display:"none"},onChange:f=>{var v;(v=f.target.files)!=null&&v[0]&&x(f.target.files[0])}})]}),s.jsxs("div",{className:"ss-auth-info-box",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.info}),s.jsx("span",{children:"Your profile photo will be visible to all members of your organization."})]})]})]})]}),s.jsxs("div",{className:"ss-auth-modal-footer",children:[s.jsx("button",{type:"button",className:"ss-auth-btn-ghost",onClick:r,children:"Cancel"}),s.jsxs("button",{type:"button",className:"ss-auth-btn-primary ss-auth-btn-sm",onClick:()=>{},disabled:!o||e,style:{width:"auto"},children:[e&&s.jsx("span",{className:"ss-auth-spinner"}),"Save Profile",!e&&s.jsx("span",{className:"material-symbols-outlined",children:$.check})]})]})]})})}function Es({appearance:a,afterSignOutUrl:r,afterDeleteAccountUrl:e,showOrgSwitcher:o=!0,onOrgChange:n,onOrgSettingsClick:u}){const{appearance:l}=E(),{user:c,signOut:d}=H(),i=a??l,[x,p]=t.useState(!1),[g,f]=t.useState(!1),[v,b]=t.useState(""),[N,h]=t.useState(null),[j,S]=t.useState(!1),k=t.useRef(null),{orgs:P,selectedOrg:z,selectOrg:F,createOrg:w}=K(),m=t.useCallback(C=>{k.current&&!C.composedPath().includes(k.current)&&p(!1)},[]);t.useEffect(()=>{if(x){const C=setTimeout(()=>{document.addEventListener("click",m)},0);return()=>{clearTimeout(C),document.removeEventListener("click",m)}}},[x,m]);const y=t.useCallback(async C=>{C.preventDefault(),h(null),S(!0);const B=v.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");try{const D=await w(v,B);D&&(await F(D.id),n==null||n(D),b(""),p(!1))}catch(D){h(D instanceof Error?D.message:"Failed to create organization")}finally{S(!1)}},[v,w,F,n]);return c?s.jsx(M,{appearance:i,children:s.jsxs("div",{style:{position:"relative",display:"inline-block"},ref:k,children:[s.jsx("button",{type:"button",className:"ss-auth-avatar-trigger",onClick:()=>p(!x),"aria-label":"User menu",children:c.avatarUrl?s.jsx("img",{src:c.avatarUrl,alt:""}):s.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",fontWeight:700},children:(c.name||c.email).charAt(0).toUpperCase()})}),x&&s.jsxs("div",{className:"ss-auth-dropdown ss-auth-glass-panel",style:{minWidth:"320px"},children:[s.jsxs("div",{className:"ss-auth-dropdown-header",children:[s.jsx("div",{className:"ss-auth-dropdown-avatar",children:c.avatarUrl?s.jsx("img",{src:c.avatarUrl,alt:""}):s.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"20px",fontWeight:800},children:(c.name||c.email).charAt(0).toUpperCase()})}),s.jsxs("div",{children:[c.name&&s.jsx("div",{className:"ss-auth-dropdown-name",children:c.name}),s.jsx("div",{className:"ss-auth-dropdown-email",children:c.email})]})]}),s.jsx("div",{style:{padding:"4px 8px"},children:s.jsxs("button",{type:"button",className:"ss-auth-dropdown-action",onClick:()=>{p(!1),f(!0)},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.person}),"Profile"]})}),o&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"ss-auth-section-label",children:"Organizations"}),s.jsx("div",{style:{padding:"0 8px 4px"},children:P.map(C=>{const B=(z==null?void 0:z.id)===C.id,D=C.name.split(" ").map(L=>L[0]).join("").slice(0,2).toUpperCase();return s.jsxs("button",{type:"button",className:`ss-auth-org-item${B?" ss-auth-org-item-active":""}`,onClick:async()=>{p(!1),await F(C.id),n==null||n(C)},children:[s.jsxs("div",{className:"ss-auth-org-item-inner",children:[s.jsx("div",{className:`ss-auth-org-avatar${B?"":" ss-auth-org-avatar-inactive"}`,children:D}),s.jsx("span",{style:{fontFamily:"'Manrope', sans-serif",letterSpacing:"-0.01em"},children:C.name})]}),B&&s.jsx("span",{className:"material-symbols-outlined ss-auth-org-check",style:{fontSize:"18px"},children:$.checkCircle})]},C.id)})}),s.jsxs("div",{className:"ss-auth-inline-create",children:[N&&s.jsx("div",{className:"ss-auth-error",style:{marginBottom:"8px",fontSize:"12px"},children:s.jsx("span",{children:N})}),s.jsx("form",{onSubmit:y,children:s.jsxs("div",{className:"ss-auth-inline-create-input",children:[s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"New organization name",value:v,onChange:C=>b(C.target.value),required:!0,style:{fontSize:"13px",padding:"10px 40px 10px 12px"}}),s.jsx("button",{type:"submit",className:"ss-auth-inline-create-btn",disabled:j||!v.trim(),children:s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"20px"},children:$.add})})]})})]}),z&&u&&s.jsx("div",{style:{padding:"0 8px 4px"},children:s.jsxs("button",{type:"button",className:"ss-auth-dropdown-action",onClick:()=>{p(!1),u(z)},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.corporateFare}),"Org settings"]})})]}),s.jsx("div",{className:"ss-auth-signout-section",style:{padding:"8px"},children:s.jsxs("button",{type:"button",className:"ss-auth-dropdown-action",onClick:async()=>{p(!1),await d(),r&&(window.location.href=r)},style:{color:"inherit"},children:[s.jsx("span",{className:"material-symbols-outlined",style:{color:"inherit"},children:$.logout}),"Sign out"]})})]}),g&&s.jsx(Os,{onClose:()=>f(!1),afterDeleteAccountUrl:e})]})}):null}function Os({onClose:a,afterDeleteAccountUrl:r}){const{user:e,updateProfile:o,uploadAvatar:n,changePassword:u,isLoading:l,error:c,success:d,setError:i,setSuccess:x}=X(),{signOut:p}=H(),{deleteAccount:g,isLoading:f,error:v,setError:b}=es(),[N,h]=t.useState((e==null?void 0:e.name)??""),[j,S]=t.useState((e==null?void 0:e.avatarUrl)??""),[k,P]=t.useState(!1),[z,F]=t.useState(""),[w,m]=t.useState(""),[y,C]=t.useState(""),[B,D]=t.useState(null),[L,T]=t.useState(!1),[O,R]=t.useState(""),_=t.useCallback(async A=>{A.preventDefault(),i(null),x(null),await o({name:N,avatarUrl:j||void 0})},[N,j,o,i,x]),q=t.useCallback(async A=>{const G=await n(A);G&&(S(G.avatarUrl),P(!1))},[n]),gs=t.useCallback(async A=>{if(A.preventDefault(),D(null),i(null),x(null),w!==y){D("Passwords do not match");return}if(w.length<8){D("Password must be at least 8 characters");return}await u(z,w)&&(F(""),m(""),C(""))},[z,w,y,u,i,x]),fs=t.useCallback(async()=>{await g()&&(await p(),r&&(window.location.href=r))},[g,p,r]),ms=(e==null?void 0:e.provider)==="email",bs=O===(e==null?void 0:e.email),ys=((e==null?void 0:e.name)||(e==null?void 0:e.email)||"?").charAt(0).toUpperCase();return s.jsx("div",{className:"ss-auth-modal-overlay",onClick:A=>{A.target===A.currentTarget&&a()},children:s.jsxs("div",{className:"ss-auth-modal",style:{maxWidth:"640px"},children:[s.jsxs("div",{className:"ss-auth-modal-header",children:[s.jsx("h2",{children:"Profile"}),s.jsx("button",{type:"button",className:"ss-auth-modal-close",onClick:a,children:s.jsx("span",{className:"material-symbols-outlined",children:$.close})})]}),s.jsxs("div",{className:"ss-auth-profile-header",children:[s.jsxs("div",{className:"ss-auth-avatar-lg",onClick:()=>P(!0),children:[j?s.jsx("img",{src:j,alt:""}):s.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"48px",fontWeight:800,opacity:.4},children:ys}),s.jsxs("div",{className:"ss-auth-avatar-overlay",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.camera}),s.jsx("span",{children:"Edit"})]})]}),s.jsxs("div",{className:"ss-auth-profile-info",children:[s.jsxs("h2",{className:"ss-auth-profile-name",children:[(e==null?void 0:e.name)||"Unnamed User",(e==null?void 0:e.emailVerified)&&s.jsxs("span",{className:"ss-auth-badge ss-auth-badge-success",children:[s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"12px",fontVariationSettings:"'FILL' 1"},children:$.verified}),"Verified"]})]}),s.jsx("p",{className:"ss-auth-profile-desc",children:e==null?void 0:e.email})]})]}),s.jsxs("div",{className:"ss-auth-modal-body",children:[c&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:c})]}),d&&s.jsxs("div",{className:"ss-auth-info-box",style:{marginBottom:"16px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.check}),s.jsx("span",{children:d})]}),s.jsxs("form",{onSubmit:_,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Full Name"}),s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"Your name",value:N,onChange:A=>h(A.target.value)})]}),s.jsxs("div",{className:"ss-auth-profile-grid",style:{marginBottom:"16px"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Email Address"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{className:"ss-auth-input ss-auth-input-readonly",type:"email",value:(e==null?void 0:e.email)??"",readOnly:!0}),s.jsx("span",{className:"ss-auth-visibility-toggle",style:{cursor:"default"},children:s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"18px"},children:$.lock})})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Auth Provider"}),s.jsx("input",{className:"ss-auth-input ss-auth-input-readonly",type:"text",value:(e==null?void 0:e.provider)??"",readOnly:!0})]})]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary ss-auth-btn-sm",disabled:l,style:{width:"auto"},children:[l&&s.jsx("span",{className:"ss-auth-spinner"}),"Save changes"]})})]}),ms&&s.jsxs("div",{className:"ss-auth-section",children:[s.jsxs("div",{className:"ss-auth-section-title",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.security}),"Security Credentials"]}),B&&s.jsxs("div",{className:"ss-auth-error",style:{marginTop:"16px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:B})]}),s.jsxs("form",{onSubmit:gs,style:{marginTop:"16px"},children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Current Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"••••••••••••",value:z,onChange:A=>F(A.target.value),required:!0})]}),s.jsxs("div",{className:"ss-auth-profile-grid",style:{marginBottom:"16px"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"New Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"Min. 8 characters",value:w,onChange:A=>m(A.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Confirm New Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"Repeat new password",value:y,onChange:A=>C(A.target.value),required:!0})]})]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsx("button",{type:"submit",className:"ss-auth-btn-ghost",disabled:l,children:"Update Security"})})]})]}),s.jsxs("div",{className:"ss-auth-section",children:[s.jsx("div",{className:"ss-auth-section-title",style:{color:"inherit"},children:"Danger Zone"}),s.jsx("p",{className:"ss-auth-section-desc",style:{marginBottom:"16px"},children:"Deleting your account is permanent. All organizations you own will also be deleted."}),v&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:v})]}),L?s.jsxs("div",{children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Type your email to confirm"}),s.jsx("input",{className:"ss-auth-input",type:"email",placeholder:e==null?void 0:e.email,value:O,onChange:A=>R(A.target.value),autoFocus:!0})]}),s.jsxs("div",{style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[s.jsx("button",{type:"button",className:"ss-auth-btn-ghost",onClick:()=>{T(!1),R(""),b(null)},children:"Cancel"}),s.jsxs("button",{type:"button",className:"ss-auth-btn-primary ss-auth-btn-sm",style:{width:"auto",background:"linear-gradient(135deg, #ef4444, #dc2626)"},disabled:!bs||f,onClick:fs,children:[f&&s.jsx("span",{className:"ss-auth-spinner"}),"Delete account"]})]})]}):s.jsx("button",{type:"button",className:"ss-auth-btn-outline",style:{borderColor:"currentColor",width:"auto"},onClick:()=>T(!0),children:"Delete my account"})]})]}),k&&s.jsx(ns,{onUpload:q,onClose:()=>P(!1),isLoading:l})]})})}function Is({appearance:a}){const{appearance:r}=E(),{user:e,signOut:o}=H(),{updateProfile:n,uploadAvatar:u,changePassword:l,isLoading:c,error:d,success:i,setError:x,setSuccess:p}=X(),g=a??r,[f,v]=t.useState((e==null?void 0:e.name)??""),[b,N]=t.useState((e==null?void 0:e.avatarUrl)??""),[h,j]=t.useState(!1),[S,k]=t.useState(""),[P,z]=t.useState(""),[F,w]=t.useState(""),[m,y]=t.useState(null),C=t.useCallback(async O=>{O.preventDefault(),x(null),p(null),await n({name:f,avatarUrl:b||void 0})},[f,b,n,x,p]),B=t.useCallback(async O=>{const R=await u(O);R&&(N(R.avatarUrl),j(!1))},[u]),D=t.useCallback(async O=>{if(O.preventDefault(),y(null),x(null),p(null),P!==F){y("Passwords do not match");return}if(P.length<8){y("Password must be at least 8 characters");return}await l(S,P)&&(k(""),z(""),w(""))},[S,P,F,l,x,p]);if(!e)return null;const L=e.provider==="email",T=(e.name||e.email).charAt(0).toUpperCase();return s.jsx(M,{appearance:g,children:s.jsxs("div",{className:"ss-auth-card",style:{maxWidth:"640px"},children:[s.jsxs("div",{className:"ss-auth-profile-header",children:[s.jsxs("div",{className:"ss-auth-avatar-lg",onClick:()=>j(!0),children:[b?s.jsx("img",{src:b,alt:""}):s.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"48px",fontWeight:800,opacity:.4},children:T}),s.jsxs("div",{className:"ss-auth-avatar-overlay",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.camera}),s.jsx("span",{children:"Edit"})]})]}),s.jsxs("div",{className:"ss-auth-profile-info",children:[s.jsxs("h2",{className:"ss-auth-profile-name",children:[e.name||"Unnamed User",e.emailVerified&&s.jsxs("span",{className:"ss-auth-badge ss-auth-badge-success",children:[s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"12px",fontVariationSettings:"'FILL' 1"},children:$.verified}),"Verified"]})]}),s.jsx("p",{className:"ss-auth-profile-desc",children:e.email})]})]}),s.jsxs("div",{className:"ss-auth-card-body",children:[d&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:d})]}),i&&s.jsxs("div",{className:"ss-auth-info-box",style:{marginBottom:"16px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.check}),s.jsx("span",{children:i})]}),s.jsxs("form",{onSubmit:C,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Full Name"}),s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"Your name",value:f,onChange:O=>v(O.target.value)})]}),s.jsxs("div",{className:"ss-auth-profile-grid",style:{marginBottom:"16px"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Email Address"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{className:"ss-auth-input ss-auth-input-readonly",type:"email",value:e.email,readOnly:!0}),s.jsx("span",{className:"ss-auth-visibility-toggle",style:{cursor:"default"},children:s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"18px"},children:$.lock})})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Auth Provider"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{className:"ss-auth-input ss-auth-input-readonly",type:"text",value:e.provider,readOnly:!0}),s.jsx("span",{className:"ss-auth-visibility-toggle",style:{cursor:"default"},children:s.jsx("span",{className:"material-symbols-outlined",style:{fontSize:"18px"},children:$.cloudDone})})]})]})]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary ss-auth-btn-sm",disabled:c,style:{width:"auto"},children:[c&&s.jsx("span",{className:"ss-auth-spinner"}),"Save changes"]})})]}),L&&s.jsxs("div",{className:"ss-auth-section",children:[s.jsxs("div",{className:"ss-auth-section-title",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.security}),"Security Credentials"]}),s.jsx("p",{className:"ss-auth-section-desc",style:{marginBottom:"24px"},children:"Update your password to keep your account secure."}),m&&s.jsxs("div",{className:"ss-auth-error",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.errorOutline}),s.jsx("span",{children:m})]}),s.jsxs("form",{onSubmit:D,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",children:"Current Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"••••••••••••",value:S,onChange:O=>k(O.target.value),required:!0})]}),s.jsxs("div",{className:"ss-auth-profile-grid",style:{marginBottom:"16px"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"New Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"Min. 8 characters",value:P,onChange:O=>z(O.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"ss-auth-label",children:"Confirm New Password"}),s.jsx("input",{className:"ss-auth-input",type:"password",placeholder:"Repeat new password",value:F,onChange:O=>w(O.target.value),required:!0})]})]}),s.jsxs("div",{className:"ss-auth-info-box",style:{marginBottom:"16px"},children:[s.jsx("span",{className:"material-symbols-outlined",children:$.info}),s.jsx("span",{children:"Password must be at least 8 characters long."})]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsx("button",{type:"submit",className:"ss-auth-btn-ghost",disabled:c,children:"Update Security"})})]})]}),s.jsx("div",{className:"ss-auth-section",style:{borderTop:"none",paddingTop:0,marginTop:"24px"},children:s.jsx("div",{className:"ss-auth-signout-section",style:{borderRadius:"12px",padding:"16px 20px"},children:s.jsxs("div",{className:"ss-auth-signout-row",children:[s.jsxs("div",{className:"ss-auth-signout-info",children:[s.jsx("div",{className:"ss-auth-signout-icon",children:s.jsx("span",{className:"material-symbols-outlined",children:$.logout})}),s.jsxs("div",{children:[s.jsx("div",{className:"ss-auth-signout-title",children:"End Session"}),s.jsx("div",{className:"ss-auth-signout-desc",children:"Terminate your active session"})]})]}),s.jsx("button",{type:"button",className:"ss-auth-btn-outline",onClick:()=>o(),style:{width:"auto",flexShrink:0},children:"Sign out"})]})})})]}),h&&s.jsx(ns,{onUpload:B,onClose:()=>j(!1),isLoading:c})]})})}function Fs({appearance:a,onOrgChange:r}){const{appearance:e}=E(),{orgs:o,selectedOrg:n,selectOrg:u,createOrg:l,isLoading:c}=K(),d=a??e,[i,x]=t.useState(!1),[p,g]=t.useState(""),[f,v]=t.useState(""),[b,N]=t.useState(null),[h,j]=t.useState(!1),S=t.useRef(null),k=t.useCallback(m=>{S.current&&!m.composedPath().includes(S.current)&&x(!1)},[]);t.useEffect(()=>{if(i){const m=setTimeout(()=>{document.addEventListener("click",k)},0);return()=>{clearTimeout(m),document.removeEventListener("click",k)}}},[i,k]);const P=t.useCallback(m=>{g(m),v(m.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},[]),z=t.useCallback(async m=>{m.preventDefault(),N(null),j(!0);try{const y=await l(p,f);y&&(await u(y.id),r==null||r(y),g(""),v(""),x(!1))}catch(y){N(y instanceof Error?y.message:"Failed to create organization")}finally{j(!1)}},[p,f,l,u,r]);if(c)return null;const F=(n==null?void 0:n.name)??(o.length===0?"No organization":"Select organization"),w=n?n.name.split(" ").map(m=>m[0]).join("").slice(0,2).toUpperCase():"--";return s.jsx(M,{appearance:d,children:s.jsxs("div",{style:{position:"relative",display:"inline-block",width:"100%",maxWidth:"360px"},ref:S,children:[s.jsxs("button",{type:"button",className:"ss-auth-org-trigger",onClick:()=>x(!i),children:[s.jsxs("div",{className:"ss-auth-org-trigger-inner",children:[s.jsx("div",{className:"ss-auth-org-avatar",children:w}),s.jsxs("div",{style:{textAlign:"left"},children:[s.jsx("div",{className:"ss-auth-org-trigger-label",children:"Current Organization"}),s.jsx("div",{className:"ss-auth-org-trigger-name",children:F})]})]}),s.jsx("span",{className:"material-symbols-outlined",children:$.unfoldMore})]}),i&&s.jsxs("div",{className:"ss-auth-dropdown ss-auth-dropdown-left ss-auth-glass-panel",style:{width:"100%"},children:[s.jsx("div",{className:"ss-auth-section-label",children:"Your Organizations"}),s.jsx("div",{style:{padding:"0 8px 4px"},children:o.map(m=>{const y=(n==null?void 0:n.id)===m.id,C=m.name.split(" ").map(B=>B[0]).join("").slice(0,2).toUpperCase();return s.jsxs("button",{type:"button",className:`ss-auth-org-item${y?" ss-auth-org-item-active":""}`,onClick:async()=>{x(!1),await u(m.id),r==null||r(m)},children:[s.jsxs("div",{className:"ss-auth-org-item-inner",children:[s.jsx("div",{className:`ss-auth-org-avatar${y?"":" ss-auth-org-avatar-inactive"}`,children:C}),s.jsx("span",{style:{fontFamily:"'Manrope', sans-serif",letterSpacing:"-0.01em"},children:m.name})]}),y&&s.jsx("span",{className:"material-symbols-outlined ss-auth-org-check",style:{fontSize:"18px"},children:$.checkCircle})]},m.id)})}),s.jsxs("div",{className:"ss-auth-org-create",children:[s.jsxs("div",{className:"ss-auth-org-create-header",children:[s.jsx("span",{className:"material-symbols-outlined",children:$.addCircle}),s.jsx("span",{children:"Create organization"})]}),b&&s.jsx("div",{className:"ss-auth-error",style:{marginBottom:"12px",fontSize:"12px"},children:s.jsx("span",{children:b})}),s.jsxs("form",{onSubmit:z,children:[s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",style:{fontSize:"10px"},children:"Org Name"}),s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"e.g. Nexus Dynamics",value:p,onChange:m=>P(m.target.value),required:!0,style:{fontSize:"13px",padding:"10px 12px"}})]}),s.jsxs("div",{className:"ss-auth-field",children:[s.jsx("label",{className:"ss-auth-label",style:{fontSize:"10px"},children:"Workspace Slug"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("span",{className:"ss-auth-org-slug-prefix",children:"/"}),s.jsx("input",{className:"ss-auth-input",type:"text",placeholder:"nexus-dynamics",value:f,onChange:m=>v(m.target.value),required:!0,style:{fontSize:"13px",padding:"10px 12px 10px 22px"}})]})]}),s.jsxs("button",{type:"submit",className:"ss-auth-btn-primary",disabled:h||!p.trim(),style:{marginTop:"8px"},children:[h&&s.jsx("span",{className:"ss-auth-spinner"}),"Initialize Organization"]})]})]})]})]})})}function Ls(a,r="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:r,minimumFractionDigits:a%100===0?0:2}).format(a/100)}function Bs({plans:a,currentPlanId:r,onSelectPlan:e,interval:o,appearance:n}){const{appearance:u}=E(),l=n??u,c=o?a.filter(d=>d.interval===o||d.isFree):a;return s.jsx(M,{appearance:l,children:s.jsx("div",{className:"ss-pricing-grid",children:c.map(d=>{const i=d.id===r;return s.jsxs("div",{className:`ss-pricing-card ${i?"ss-pricing-card-current":""}`,children:[s.jsxs("div",{className:"ss-pricing-header",children:[s.jsx("h3",{className:"ss-pricing-name",children:d.name}),d.trialDays>0&&s.jsxs("span",{className:"ss-badge ss-badge-trialing",children:[d.trialDays,"-day trial"]}),d.isFree&&s.jsx("span",{className:"ss-badge ss-badge-active",children:"Free"})]}),s.jsx("div",{className:"ss-pricing-price",children:d.isFree?s.jsx("span",{className:"ss-pricing-amount",children:"Free"}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"ss-pricing-amount",children:Ls(d.amountCents,d.currency)}),s.jsxs("span",{className:"ss-pricing-interval",children:["/",d.interval]})]})}),d.description&&s.jsx("p",{className:"ss-pricing-desc",children:d.description}),d.features.length>0&&s.jsx("ul",{className:"ss-pricing-features",children:d.features.map((x,p)=>s.jsxs("li",{className:"ss-pricing-feature",children:[s.jsx("span",{className:"ss-check",children:"✓"})," ",x]},p))}),s.jsx("button",{type:"button",className:`ss-btn ${i?"ss-btn-current":"ss-btn-primary"}`,disabled:i,onClick:()=>e(d.id),children:i?"Current plan":"Select plan"})]},d.id)})})})}function Ts(){const{client:a}=E();return{billing:a.billing}}function W(a){const{client:r}=E();return t.useMemo(()=>{if(a){const e=new U.Transport("https://api.saas-support.com/v1",{type:"portalToken",token:a});return new U.BillingClient(e)}return r.billing},[r,a])}function os(a,r){const e=W(r),[o,n]=t.useState(null),[u,l]=t.useState(!0),[c,d]=t.useState(null),i=t.useCallback(async()=>{l(!0),d(null);try{const x=await e.getCustomer(a);n(x)}catch(x){d(x instanceof Error?x.message:"Failed to load subscription")}finally{l(!1)}},[e,a]);return t.useEffect(()=>{i()},[i]),{customer:o,isLoading:u,error:c,refresh:i}}function is(a,r){const e=W(r),[o,n]=t.useState([]),[u,l]=t.useState(!0),[c,d]=t.useState(null),i=t.useCallback(async()=>{l(!0),d(null);try{const x=await e.getInvoices(a);n(x)}catch(x){d(x instanceof Error?x.message:"Failed to load invoices")}finally{l(!1)}},[e,a]);return t.useEffect(()=>{i()},[i]),{invoices:o,isLoading:u,error:c,refresh:i}}function ls(a,r){const e=W(r),[o,n]=t.useState([]),[u,l]=t.useState(!0),[c,d]=t.useState(null),i=t.useCallback(async()=>{l(!0),d(null);try{const x=await e.getCurrentUsage(a);n(x)}catch(x){d(x instanceof Error?x.message:"Failed to load usage")}finally{l(!1)}},[e,a]);return t.useEffect(()=>{i()},[i]),{usage:o,isLoading:u,error:c,refresh:i}}const As={active:"ss-badge-active"};function cs({customerId:a,portalToken:r,onChangePlan:e,onCancel:o,appearance:n}){const{appearance:u}=E(),{customer:l,isLoading:c,error:d}=os(a,r),i=n??u;return s.jsx(M,{appearance:i,children:s.jsxs("div",{className:"ss-card",children:[s.jsx("h2",{className:"ss-title",children:"Subscription"}),c&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading..."]}),d&&s.jsx("div",{className:"ss-global-error",children:d}),l&&!c&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"ss-field",children:[s.jsx("label",{className:"ss-label",children:"Customer"}),s.jsx("input",{className:"ss-input",value:l.name||l.email,disabled:!0,readOnly:!0})]}),s.jsxs("div",{className:"ss-field",children:[s.jsx("label",{className:"ss-label",children:"Status"}),s.jsx("div",{children:s.jsx("span",{className:`ss-badge ${As.active}`,children:"Active"})})]}),s.jsxs("div",{className:"ss-btn-group",children:[e&&s.jsx("button",{type:"button",className:"ss-btn ss-btn-primary",onClick:e,children:"Change plan"}),o&&s.jsx("button",{type:"button",className:"ss-btn ss-btn-danger",onClick:o,children:"Cancel subscription"})]})]})]})})}const Ds={paid:"ss-badge-active",open:"ss-badge-trialing",draft:"ss-badge-paused",void:"ss-badge-canceled",uncollectible:"ss-badge-past-due"};function Ms(a){return new Date(a).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}function Us(a){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2}).format(a/100)}function ds({customerId:a,portalToken:r,appearance:e}){const{appearance:o}=E(),{invoices:n,isLoading:u,error:l}=is(a,r),c=e??o,d=[...n].sort((i,x)=>new Date(x.createdAt).getTime()-new Date(i.createdAt).getTime());return s.jsx(M,{appearance:c,children:s.jsxs("div",{className:"ss-card ss-card-wide",children:[s.jsx("h2",{className:"ss-title",children:"Invoices"}),u&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading..."]}),l&&s.jsx("div",{className:"ss-global-error",children:l}),!u&&d.length===0&&s.jsx("p",{className:"ss-empty",children:"No invoices yet."}),!u&&d.length>0&&s.jsxs("table",{className:"ss-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{className:"ss-th",children:"Date"}),s.jsx("th",{className:"ss-th",children:"Amount"}),s.jsx("th",{className:"ss-th",children:"Status"}),s.jsx("th",{className:"ss-th",children:"PDF"})]})}),s.jsx("tbody",{children:d.map(i=>s.jsxs("tr",{className:"ss-tr",children:[s.jsx("td",{className:"ss-td",children:Ms(i.createdAt)}),s.jsx("td",{className:"ss-td",children:Us(i.amountCents)}),s.jsx("td",{className:"ss-td",children:s.jsx("span",{className:`ss-badge ${Ds[i.status]||""}`,children:i.status})}),s.jsx("td",{className:"ss-td",children:i.pdfUrl?s.jsx("a",{className:"ss-link",href:i.pdfUrl,target:"_blank",rel:"noopener noreferrer",children:"Download"}):"—"})]},i.id))})]})]})})}function us({customerId:a,limits:r,portalToken:e,appearance:o}){const{appearance:n}=E(),{usage:u,isLoading:l,error:c}=ls(a,e),d=o??n;return s.jsx(M,{appearance:d,children:s.jsxs("div",{className:"ss-card",children:[s.jsx("h2",{className:"ss-title",children:"Usage"}),l&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading..."]}),c&&s.jsx("div",{className:"ss-global-error",children:c}),!l&&u.length===0&&s.jsx("p",{className:"ss-empty",children:"No usage data."}),!l&&u.map(i=>{const x=r==null?void 0:r[i.metric],p=x?Math.min(100,i.total/x*100):null;return s.jsxs("div",{className:"ss-usage-item",children:[s.jsxs("div",{className:"ss-usage-header",children:[s.jsx("span",{className:"ss-usage-metric",children:i.metric}),s.jsxs("span",{className:"ss-usage-value",children:[i.total.toLocaleString(),x?` / ${x.toLocaleString()}`:""]})]}),p!==null&&s.jsx("div",{className:"ss-progress-bar",children:s.jsx("div",{className:`ss-progress-fill ${p>90?"ss-progress-danger":""}`,style:{width:`${p}%`}})})]},i.metric)})]})})}function Vs({customerId:a,portalToken:r,limits:e,onChangePlan:o,onCancel:n,appearance:u}){const{appearance:l}=E(),c=u??l,[d,i]=t.useState("subscription"),x=[{id:"subscription",label:"Subscription"},{id:"invoices",label:"Invoices"},{id:"usage",label:"Usage"}];return s.jsx(M,{appearance:c,children:s.jsxs("div",{className:"ss-card ss-card-wide",children:[s.jsx("h2",{className:"ss-title",children:"Billing"}),s.jsx("div",{className:"ss-tab-group",children:x.map(p=>s.jsx("button",{type:"button",className:`ss-tab ${d===p.id?"ss-tab-active":""}`,onClick:()=>i(p.id),children:p.label},p.id))}),s.jsxs("div",{className:"ss-tab-content",children:[d==="subscription"&&s.jsx(cs,{customerId:a,portalToken:r,onChangePlan:o,onCancel:n}),d==="invoices"&&s.jsx(ds,{customerId:a,portalToken:r}),d==="usage"&&s.jsx(us,{customerId:a,portalToken:r,limits:e})]})]})})}function Rs({customerId:a,portalToken:r,onApplied:e,appearance:o}){const{appearance:n}=E(),u=W(r),l=o??n,[c,d]=t.useState(""),[i,x]=t.useState(!1),[p,g]=t.useState(null),[f,v]=t.useState(null),b=t.useCallback(async N=>{if(N.preventDefault(),!!c.trim()){x(!0),g(null),v(null);try{const h=await u.applyCoupon(a,c.trim());v(`Coupon applied! ${h.discountType==="percent"?`${h.amount}% off`:`$${(h.amount/100).toFixed(2)} off`}`),d(""),e==null||e(h)}catch(h){g(h instanceof Error?h.message:"Invalid coupon code")}finally{x(!1)}}},[u,a,c,e]);return s.jsx(M,{appearance:l,children:s.jsxs("div",{className:"ss-card",children:[s.jsx("h2",{className:"ss-title",children:"Apply coupon"}),p&&s.jsx("div",{className:"ss-global-error",children:p}),f&&s.jsx("div",{className:"ss-success-msg",children:f}),s.jsxs("form",{onSubmit:b,children:[s.jsxs("div",{className:"ss-field",children:[s.jsx("label",{className:"ss-label",htmlFor:"ss-coupon-code",children:"Coupon code"}),s.jsx("input",{id:"ss-coupon-code",className:"ss-input",type:"text",placeholder:"Enter coupon code",value:c,onChange:N=>d(N.target.value),required:!0})]}),s.jsxs("button",{type:"submit",className:"ss-btn ss-btn-primary",disabled:i||!c.trim(),children:[i&&s.jsx("span",{className:"ss-spinner"}),"Apply"]})]})]})})}function qs(){const{client:a}=E();return{report:a.report}}function ss(){const{client:a}=E(),[r,e]=t.useState(null),[o,n]=t.useState(!1),[u,l]=t.useState(null),c=t.useCallback(async d=>{n(!0),l(null);try{const i=await a.report.executeQuery(d);return e(i),i}catch(i){return l(i instanceof Error?i.message:"Query failed"),null}finally{n(!1)}},[a]);return{result:r,execute:c,isLoading:o,error:u}}function ps(a){const{client:r}=E(),[e,o]=t.useState(null),[n,u]=t.useState(!0),[l,c]=t.useState(null),d=t.useCallback(async()=>{u(!0),c(null);try{const i=await r.report.listQueries(a);o(i)}catch(i){c(i instanceof Error?i.message:"Failed to load queries")}finally{u(!1)}},[r,a]);return t.useEffect(()=>{d()},[d]),{queries:(e==null?void 0:e.data)??[],meta:e==null?void 0:e.meta,isLoading:n,error:l,refresh:d}}function Hs(a){const{client:r}=E(),[e,o]=t.useState(null),[n,u]=t.useState(!0),[l,c]=t.useState(null),d=t.useCallback(async()=>{u(!0),c(null);try{const i=await r.report.getDashboard(a);o(i)}catch(i){c(i instanceof Error?i.message:"Failed to load dashboard")}finally{u(!1)}},[r,a]);return t.useEffect(()=>{d()},[d]),{dashboard:e,isLoading:n,error:l,refresh:d}}function Ws(a,r,e="https://api.saas-support.com/v1"){const o=t.useMemo(()=>{const p=new U.Transport(e,{type:"embedToken",token:a});return new U.ReportClient(p)},[a,e]),[n,u]=t.useState(null),[l,c]=t.useState(!0),[d,i]=t.useState(null),x=t.useCallback(async()=>{c(!0),i(null);try{const p=await o.getDashboard(r);u(p)}catch(p){i(p instanceof Error?p.message:"Failed to load dashboard")}finally{c(!1)}},[o,r]);return t.useEffect(()=>{x()},[x]),{dashboard:n,reportClient:o,isLoading:l,error:d,refresh:x}}function _s({onResult:a,mode:r="both",placeholder:e,appearance:o}){const{appearance:n}=E(),{execute:u,isLoading:l,error:c}=ss(),d=o??n,[i,x]=t.useState(""),[p,g]=t.useState(r==="sql"?"sql":"nl"),f=t.useCallback(async v=>{if(v.preventDefault(),!i.trim())return;const N=await u(p==="sql"?{sql:i}:{naturalLanguage:i});N&&(a==null||a(N))},[i,p,u,a]);return s.jsx(M,{appearance:d,children:s.jsxs("div",{className:"ss-card ss-card-wide",children:[r==="both"&&s.jsxs("div",{className:"ss-tab-group ss-tab-group-sm",children:[s.jsx("button",{type:"button",className:`ss-tab ${p==="nl"?"ss-tab-active":""}`,onClick:()=>g("nl"),children:"Natural Language"}),s.jsx("button",{type:"button",className:`ss-tab ${p==="sql"?"ss-tab-active":""}`,onClick:()=>g("sql"),children:"SQL"})]}),c&&s.jsx("div",{className:"ss-global-error",children:c}),s.jsxs("form",{onSubmit:f,children:[s.jsx("div",{className:"ss-field",children:s.jsx("textarea",{className:"ss-input ss-query-textarea",placeholder:e??(p==="sql"?"SELECT ...":"Ask a question about your data..."),value:i,onChange:v=>x(v.target.value),rows:3})}),s.jsxs("button",{type:"submit",className:"ss-btn ss-btn-primary",disabled:l||!i.trim(),children:[l&&s.jsx("span",{className:"ss-spinner"}),"Run query"]})]})]})})}function hs({columns:a,rows:r,sortable:e=!0,maxRows:o,appearance:n}){const{appearance:u}=E(),l=n??u,[c,d]=t.useState(null),[i,x]=t.useState("asc"),p=t.useMemo(()=>c?[...r].sort((b,N)=>{const h=b[c],j=N[c];if(h==null&&j==null)return 0;if(h==null)return 1;if(j==null)return-1;if(typeof h=="number"&&typeof j=="number")return i==="asc"?h-j:j-h;const S=String(h),k=String(j);return i==="asc"?S.localeCompare(k):k.localeCompare(S)}):r,[r,c,i]),g=o?p.slice(0,o):p,f=b=>{e&&(c===b?x(N=>N==="asc"?"desc":"asc"):(d(b),x("asc")))};function v(b){return b==null?"":typeof b=="object"?JSON.stringify(b):String(b)}return s.jsx(M,{appearance:l,children:s.jsxs("div",{className:"ss-table-container",children:[s.jsxs("table",{className:"ss-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:a.map(b=>s.jsxs("th",{className:`ss-th ${e?"ss-th-sortable":""} ${c===b?i==="asc"?"ss-sorted-asc":"ss-sorted-desc":""}`,onClick:()=>f(b),children:[b,c===b&&s.jsx("span",{className:"ss-sort-indicator",children:i==="asc"?" ▲":" ▼"})]},b))})}),s.jsx("tbody",{children:g.map((b,N)=>s.jsx("tr",{className:"ss-tr",children:a.map(h=>s.jsx("td",{className:"ss-td",children:v(b[h])},h))},N))})]}),o&&r.length>o&&s.jsxs("div",{className:"ss-table-footer",children:["Showing ",o," of ",r.length," rows"]})]})})}function Gs(a,r="#6366f1"){const e=parseInt(r.replace("#","").slice(0,2),16),o=[];for(let n=0;n<a;n++){const u=(e+n*Math.floor(360/Math.max(a,1)))%360;o.push(`hsl(${u}, 65%, 55%)`)}return o}function Ys({labels:a,values:r,w:e,h:o,colors:n}){const u=Math.max(...r,1),l=40,c=e-l*2,d=o-l*2,i=Math.max(1,c/a.length-4);return s.jsxs("g",{children:[s.jsx("line",{x1:l,y1:o-l,x2:e-l,y2:o-l,stroke:"#ccc",strokeWidth:1}),r.map((x,p)=>{const g=x/u*d,f=l+c/a.length*p+2,v=o-l-g;return s.jsxs("g",{children:[s.jsx("rect",{x:f,y:v,width:i,height:g,fill:n[p%n.length],rx:2}),s.jsx("text",{x:f+i/2,y:o-l+14,textAnchor:"middle",fontSize:10,fill:"#666",children:a[p].length>8?a[p].slice(0,8)+"...":a[p]})]},p)})]})}function Qs({labels:a,values:r,w:e,h:o,colors:n}){const u=Math.max(...r,1),l=40,c=e-l*2,d=o-l*2,i=a.length>1?c/(a.length-1):0,x=r.map((p,g)=>{const f=l+i*g,v=o-l-p/u*d;return`${f},${v}`});return s.jsxs("g",{children:[[.25,.5,.75,1].map(p=>{const g=o-l-p*d;return s.jsx("line",{x1:l,y1:g,x2:e-l,y2:g,stroke:"#eee",strokeWidth:1},p)}),s.jsx("polyline",{points:x.join(" "),fill:"none",stroke:n[0],strokeWidth:2}),r.map((p,g)=>{const f=l+i*g,v=o-l-p/u*d;return s.jsx("circle",{cx:f,cy:v,r:4,fill:n[0]},g)})]})}function Js({labels:a,values:r,w:e,h:o,colors:n}){const u=r.reduce((g,f)=>g+f,0)||1,l=e/2,c=o/2-20,d=Math.min(e,o)/2-40,i=2*Math.PI*d;let x=0;const p=r.map((g,f)=>{const v=g/u,b=v*i,N={dash:b,offset:x,color:n[f%n.length],label:a[f],pct:v};return x+=b,N});return s.jsxs("g",{children:[p.map((g,f)=>s.jsx("circle",{cx:l,cy:c,r:d,fill:"none",stroke:g.color,strokeWidth:d*.6,strokeDasharray:`${g.dash} ${i-g.dash}`,strokeDashoffset:-g.offset,transform:`rotate(-90 ${l} ${c})`},f)),s.jsx("g",{transform:`translate(${l-a.length*30}, ${o-20})`,children:p.slice(0,6).map((g,f)=>s.jsxs("g",{transform:`translate(${f*60}, 0)`,children:[s.jsx("rect",{width:10,height:10,fill:g.color,rx:2}),s.jsx("text",{x:14,y:9,fontSize:9,fill:"#666",children:g.label.length>6?g.label.slice(0,6)+"..":g.label})]},f))})]})}function xs({type:a,data:r,title:e,width:o=400,height:n=300,appearance:u}){const{appearance:l}=E(),c=u??l,d=t.useMemo(()=>Gs(r.labels.length),[r.labels.length]);return s.jsx(M,{appearance:c,children:s.jsxs("div",{className:"ss-chart-container",children:[e&&s.jsx("h3",{className:"ss-chart-title",children:e}),s.jsxs("svg",{viewBox:`0 0 ${o} ${n}`,width:"100%",style:{maxWidth:o},children:[a==="bar"&&s.jsx(Ys,{labels:r.labels,values:r.values,w:o,h:n,colors:d}),a==="line"&&s.jsx(Qs,{labels:r.labels,values:r.values,w:o,h:n,colors:d}),a==="pie"&&s.jsx(Js,{labels:r.labels,values:r.values,w:o,h:n,colors:d})]})]})})}function Zs({dashboardId:a,embedToken:r,baseUrl:e,refreshInterval:o,appearance:n}){const u=E(),l=n??(u==null?void 0:u.appearance),c=t.useMemo(()=>{if(r){const h=e??"https://api.saas-support.com/v1",j=new U.Transport(h,{type:"embedToken",token:r});return new U.ReportClient(j)}return u.client.report},[r,e,u]),[d,i]=t.useState([]),[x,p]=t.useState({}),[g,f]=t.useState(!0),[v,b]=t.useState(null),N=t.useCallback(async()=>{f(!0),b(null);try{const h=await c.getDashboard(a),j=JSON.parse(h.layoutJson||"[]");i(j);const S={};for(const k of j)try{const P=await c.listQueries({search:k.queryId,perPage:1});if(P.data.length>0&&P.data[0].generatedSql){const z=await c.executeQuery({sql:P.data[0].generatedSql});S[k.queryId]=z}}catch{}p(S)}catch(h){b(h instanceof Error?h.message:"Failed to load dashboard")}finally{f(!1)}},[c,a]);return t.useEffect(()=>{N()},[N]),t.useEffect(()=>{if(!o||o<=0)return;const h=setInterval(N,o*1e3);return()=>clearInterval(h)},[o,N]),s.jsx(M,{appearance:l,children:s.jsxs("div",{className:"ss-dashboard-grid",children:[g&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading dashboard..."]}),v&&s.jsx("div",{className:"ss-global-error",children:v}),!g&&d.map((h,j)=>{const S=x[h.queryId];if(!S)return null;const k=S.columns.length>=2?{labels:S.rows.map(P=>String(P[S.columns[0]]??"")),values:S.rows.map(P=>Number(P[S.columns[1]]??0))}:{labels:[],values:[]};return s.jsxs("div",{className:"ss-widget",children:[h.title&&s.jsx("h4",{className:"ss-widget-header",children:h.title}),h.chartType==="table"?s.jsx(hs,{columns:S.columns,rows:S.rows,maxRows:50}):s.jsx(xs,{type:h.chartType||"bar",data:k,width:h.w,height:h.h})]},j)})]})})}function Ks(a){return new Date(a).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}function Xs({onSelectQuery:a,onRunQuery:r,appearance:e}){const{appearance:o}=E(),{queries:n,isLoading:u,error:l}=ps(),{execute:c,isLoading:d}=ss(),i=e??o,x=t.useCallback(async p=>{if(!p.generatedSql)return;const g=await c({sql:p.generatedSql});g&&(r==null||r(g))},[c,r]);return s.jsx(M,{appearance:i,children:s.jsxs("div",{className:"ss-card ss-card-wide",children:[s.jsx("h2",{className:"ss-title",children:"Saved Queries"}),u&&s.jsxs("div",{className:"ss-loading",children:[s.jsx("span",{className:"ss-spinner"})," Loading..."]}),l&&s.jsx("div",{className:"ss-global-error",children:l}),!u&&n.length===0&&s.jsx("p",{className:"ss-empty",children:"No saved queries."}),!u&&n.map(p=>s.jsxs("div",{className:"ss-saved-query-card",onClick:()=>a==null?void 0:a(p),children:[s.jsxs("div",{className:"ss-saved-query-header",children:[s.jsx("span",{className:"ss-saved-query-name",children:p.name}),p.chartType&&s.jsx("span",{className:"ss-badge",children:p.chartType})]}),p.naturalLanguage&&s.jsx("p",{className:"ss-saved-query-desc",children:p.naturalLanguage}),s.jsxs("div",{className:"ss-saved-query-footer",children:[s.jsx("span",{className:"ss-saved-query-date",children:Ks(p.createdAt)}),s.jsx("button",{type:"button",className:"ss-btn ss-btn-sm ss-btn-primary",disabled:d||!p.generatedSql,onClick:g=>{g.stopPropagation(),x(p)},children:d?s.jsx("span",{className:"ss-spinner"}):"Run"})]})]},p.id))]})})}function sa({embedToken:a,dashboardId:r,baseUrl:e="https://api.saas-support.com/v1",refreshInterval:o,appearance:n}){const u=t.useMemo(()=>{const b=new U.Transport(e,{type:"embedToken",token:a});return new U.ReportClient(b)},[a,e]),[l,c]=t.useState([]),[d,i]=t.useState(!0),[x,p]=t.useState(null),g=t.useMemo(()=>Y(n),[n]),f=t.useMemo(()=>Q(g),[g]),v=t.useCallback(async()=>{i(!0),p(null);try{const b=await u.getDashboard(r),N=JSON.parse(b.layoutJson||"[]"),h=await Promise.all(N.map(async j=>{try{const S=await u.listQueries({search:j.queryId,perPage:1});if(S.data.length>0&&S.data[0].generatedSql){const k=await u.executeQuery({sql:S.data[0].generatedSql});return{...j,result:k}}}catch{}return j}));c(h)}catch(b){p(b instanceof Error?b.message:"Failed to load dashboard")}finally{i(!1)}},[u,r]);return t.useEffect(()=>{v()},[v]),t.useEffect(()=>{if(!o||o<=0)return;const b=setInterval(v,o*1e3);return()=>clearInterval(b)},[o,v]),s.jsx("div",{ref:b=>{if(!b||b.shadowRoot)return;const N=b.attachShadow({mode:"open"}),h=document.createElement("style");h.textContent=f,N.appendChild(h);const j=document.createElement("div");N.appendChild(j)},style:{display:"contents"},children:s.jsxs("div",{className:"ss-dashboard-grid",children:[d&&s.jsx("div",{className:"ss-loading",children:"Loading dashboard..."}),x&&s.jsx("div",{className:"ss-global-error",children:x}),!d&&l.map((b,N)=>{if(!b.result)return null;const{columns:h,rows:j}=b.result;return s.jsxs("div",{className:"ss-widget",children:[b.title&&s.jsx("h4",{className:"ss-widget-header",children:b.title}),s.jsxs("table",{className:"ss-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:h.map(S=>s.jsx("th",{className:"ss-th",children:S},S))})}),s.jsx("tbody",{children:j.slice(0,50).map((S,k)=>s.jsx("tr",{className:"ss-tr",children:h.map(P=>s.jsx("td",{className:"ss-td",children:String(S[P]??"")},P))},k))})]})]},N)})]})})}exports.SaaSError=U.SaaSError;exports.SaaSSupport=U.SaaSSupport;exports.isMfaRequired=U.isMfaRequired;exports.Chart=xs;exports.CouponInput=Rs;exports.DashboardView=Zs;exports.DataTable=hs;exports.InvoiceHistory=ds;exports.OrgSwitcher=Fs;exports.PaymentPortal=Vs;exports.PricingTable=Bs;exports.QueryInput=_s;exports.ReportEmbed=sa;exports.SaaSContext=J;exports.SaaSProvider=js;exports.SavedQueryList=Xs;exports.SignIn=Cs;exports.SignUp=Ps;exports.SubscriptionStatus=cs;exports.UsageDisplay=us;exports.UserButton=Es;exports.UserProfile=Is;exports.useAuth=H;exports.useBilling=Ts;exports.useDashboard=Hs;exports.useDeleteAccount=es;exports.useEmbedDashboard=Ws;exports.useInvoices=is;exports.useOrg=K;exports.useProfile=X;exports.useQuery=ss;exports.useReport=qs;exports.useSaaSContext=E;exports.useSavedQueries=ps;exports.useSignIn=Z;exports.useSignUp=as;exports.useSubscription=os;exports.useUsage=ls;exports.useUser=$s;
package/dist/react.d.ts CHANGED
@@ -43,6 +43,7 @@ declare class AuthClient {
43
43
  disableMfa(code: string): Promise<void>;
44
44
  getToken(): Promise<string | null>;
45
45
  getUser(): Promise<User | null>;
46
+ refreshUser(): Promise<User | null>;
46
47
  getUserSync(): User | null;
47
48
  isLoaded(): boolean;
48
49
  getSettings(): Promise<ProjectSettings | null>;
@@ -712,6 +713,7 @@ export declare function useAuth(): {
712
713
  user: User | null;
713
714
  signOut: () => Promise<void>;
714
715
  getToken: () => Promise<string | null>;
716
+ refreshUser: () => Promise<User | null>;
715
717
  };
716
718
 
717
719
  export declare function useBilling(): {
package/dist/react.js CHANGED
@@ -2227,7 +2227,8 @@ function ta() {
2227
2227
  isSignedIn: !!s,
2228
2228
  user: s,
2229
2229
  signOut: $(() => a.auth.signOut(), [a]),
2230
- getToken: $(() => a.auth.getToken(), [a])
2230
+ getToken: $(() => a.auth.getToken(), [a]),
2231
+ refreshUser: $(() => a.auth.refreshUser(), [a])
2231
2232
  };
2232
2233
  }
2233
2234
  function ae() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saas-support/react",
3
- "version": "0.6.2",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "Unified embeddable SDK for SaaS Support — auth, billing, and reporting",
6
6
  "exports": {