@buildbase/sdk 0.0.50 → 0.0.53

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.
Files changed (52) hide show
  1. package/AGENTS.md +41 -13
  2. package/CHANGELOG.md +109 -0
  3. package/README.md +343 -44
  4. package/dist/css/styles.css +1 -1
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.ts +874 -53
  7. package/dist/index.mjs +1 -1
  8. package/dist/mcp/index.cjs +1 -0
  9. package/dist/mcp/index.d.ts +1402 -0
  10. package/dist/mcp/index.mjs +1 -0
  11. package/dist/react/chunks/SettingsDialog-BxDYsie6.mjs +2 -0
  12. package/dist/react/chunks/SettingsDialog-Dy8W3NA6.cjs +2 -0
  13. package/dist/react/chunks/SubscriptionDialog-6c5dHoQd.mjs +2 -0
  14. package/dist/react/chunks/SubscriptionDialog-CpVnnXJg.cjs +2 -0
  15. package/dist/react/chunks/ar-1Z1MOGAP.mjs +2 -0
  16. package/dist/react/chunks/ar-VGzBv3AZ.cjs +2 -0
  17. package/dist/react/chunks/de-BjdDg60Y.cjs +2 -0
  18. package/dist/react/chunks/de-CXUItplO.mjs +2 -0
  19. package/dist/react/chunks/es-BBPsSZUp.cjs +2 -0
  20. package/dist/react/chunks/es-BTbzVutz.mjs +2 -0
  21. package/dist/react/chunks/fr-Cax48X_S.cjs +2 -0
  22. package/dist/react/chunks/fr-DPMeOQu3.mjs +2 -0
  23. package/dist/react/chunks/hi-BJqvpG6d.cjs +2 -0
  24. package/dist/react/chunks/hi-JfJx-LV7.mjs +2 -0
  25. package/dist/react/chunks/ja-CDGtLzTk.mjs +2 -0
  26. package/dist/react/chunks/ja-DvVyj5xX.cjs +2 -0
  27. package/dist/react/chunks/react-4SlWxHdh.cjs +2 -0
  28. package/dist/react/chunks/react-OL1uSkpr.mjs +2 -0
  29. package/dist/react/chunks/zh-BAcqxkxk.cjs +2 -0
  30. package/dist/react/chunks/zh-BNZ2Ooe8.mjs +2 -0
  31. package/dist/react/index.cjs +1 -1
  32. package/dist/react/index.d.ts +484 -93
  33. package/dist/react/index.mjs +1 -1
  34. package/package.json +22 -5
  35. package/dist/react/chunks/SubscriptionDialog-A6oETKbb.cjs +0 -2
  36. package/dist/react/chunks/SubscriptionDialog-nuMunBn4.mjs +0 -2
  37. package/dist/react/chunks/ar-BRvKHRYS.cjs +0 -2
  38. package/dist/react/chunks/ar-IhPhJAZA.mjs +0 -2
  39. package/dist/react/chunks/de-D3q0vQBG.cjs +0 -2
  40. package/dist/react/chunks/de-bvh5IFSx.mjs +0 -2
  41. package/dist/react/chunks/es-B9kiwJmF.cjs +0 -2
  42. package/dist/react/chunks/es-TyUz4_E1.mjs +0 -2
  43. package/dist/react/chunks/fr-C500Ytao.cjs +0 -2
  44. package/dist/react/chunks/fr-CKm-bSvG.mjs +0 -2
  45. package/dist/react/chunks/hi-CfFhH2uQ.cjs +0 -2
  46. package/dist/react/chunks/hi-Ck9cPpd-.mjs +0 -2
  47. package/dist/react/chunks/ja-AM4H1tXw.mjs +0 -2
  48. package/dist/react/chunks/ja-DfROrx_j.cjs +0 -2
  49. package/dist/react/chunks/react-CTX0_nOV.cjs +0 -2
  50. package/dist/react/chunks/react-DzQupoqH.mjs +0 -2
  51. package/dist/react/chunks/zh-CLmBh-it.cjs +0 -2
  52. package/dist/react/chunks/zh-DCVPxie-.mjs +0 -2
@@ -1,2 +0,0 @@
1
- "use client";
2
- "use strict";var e=require("react/jsx-runtime"),s=require("react"),t=require("clsx"),a=require("tailwind-merge"),r=require("intl-messageformat"),n=require("lucide-react"),i=require("@radix-ui/react-slot"),o=require("class-variance-authority"),c=require("@radix-ui/react-dialog"),l=require("@radix-ui/react-icons"),d=require("@radix-ui/react-alert-dialog"),u=require("@radix-ui/react-switch"),m=require("react-hook-form"),p=require("zod/v4/core"),h=require("zod"),g=require("@radix-ui/react-label"),f=require("@radix-ui/react-radio-group"),x=require("@radix-ui/react-scroll-area"),b=require("cmdk"),y=require("@radix-ui/react-popover"),v=require("@radix-ui/react-select"),w=require("@radix-ui/react-avatar"),S=require("@radix-ui/react-separator");function N(e){var s=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var a=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,a.get?a:{enumerable:!0,get:function(){return e[t]}})}}),s.default=e,Object.freeze(s)}var j=N(s),k=N(c),C=N(d),A=N(u),T=N(p),E=N(g),P=N(f),I=N(x),U=N(y),R=N(v),M=N(w),D=N(S);function W(...e){return a.twMerge(t.clsx(e))}let F=!0;function _(e,...s){F&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...s)}function O(e,...s){console.error(e,...s)}function L(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function B(e){const s=await e.text();if(!s)throw new Error("Empty response body");try{return JSON.parse(s)}catch(e){throw new Error(`Invalid JSON response: ${s.substring(0,100)}${s.length>100?"...":""}`)}}async function G(e,s="Request failed"){if(!e.ok){let t=s;try{const s=await B(e);t=s.message||s.error||t}catch{t=function(e,s){const t={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||s;return new Error(`${s} (${e.status}: ${t})`)}(e,s).message}throw new Error(t)}try{return await B(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class K extends Error{constructor(e,s,t,a){super(e),this.code=s,this.context=t,this.originalError=a,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,K)}}const V=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(F=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,s={}){if(L(e))return;const t=e instanceof Error?e:new K("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",s),a=t instanceof K?t:new K(t.message,"SDK_ERROR",s,t);if(this.config.enableConsoleLogging&&_(`[SDK Error] ${s.component||"Unknown"}:`,{message:a.message,code:a.code,context:a.context,originalError:a.originalError,stack:a.stack}),this.config.onError)try{this.config.onError(a,s)}catch(e){O("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(a,s)}notifyUser(e,s){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:s}}))}wrapAsync(e,s){return(...t)=>e(...t).catch(e=>{throw this.handleError(e,s),e})}wrapSync(e,s){return(...t)=>{try{return e(...t)}catch(e){throw this.handleError(e,s),e}}}};function z(e,s={}){V.handleError(e,s)}function $(e,s={}){return!L(e)&&(V.handleError(e,s),!0)}function q(e,s,t){return e instanceof Error?e.message:t(s)}class H extends s.Component{constructor(e){super(e),this.resetError=()=>{this.setState({hasError:!1,error:null})},this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,s){if(z(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:s.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,s)}catch(e){O("[SDK ErrorBoundary] Error in onError callback:",e)}}componentDidUpdate(e){this.state.hasError&&!1!==this.props.resetOnPropsChange&&e.children!==this.props.children&&this.resetError()}render(){return this.state.hasError&&this.state.error?this.props.fallback?"function"==typeof this.props.fallback?this.props.fallback(this.state.error,this.resetError):this.props.fallback:e.jsxs("div",{style:{padding:"1rem",border:"1px solid #ef4444",borderRadius:"0.5rem",backgroundColor:"#fef2f2",color:"#991b1b"},children:[e.jsx("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:"Something went wrong"}),e.jsx("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),e.jsx("button",{onClick:this.resetError,style:{padding:"0.5rem 1rem",backgroundColor:"#ef4444",color:"white",border:"none",borderRadius:"0.25rem",cursor:"pointer",fontSize:"0.875rem"},children:"Try again"})]}):this.props.children}}const J=()=>({type:"AUTHENTICATION_STARTED"}),Y=()=>({type:"AUTHENTICATION_PROCESSING"}),Z=()=>({type:"AUTHENTICATION_FAILED"}),Q=e=>({type:"SET_SESSION",payload:e}),X=()=>({type:"REMOVE_SESSION"});function ee(e,t,a){const r=s.useRef(t),n=s.useRef(a),i=s.useRef(void 0),o=s.useRef(!1),c=r.current!==t,l=n.current!==a,d=c||l;r.current=t,n.current=a;const u=s.useRef(0);d&&(u.current+=1);const m=u.current;return s.useMemo(()=>{const s=t(e);if(o.current){if(a?a(i.current,s):Object.is(i.current,s))return i.current}return i.current=s,o.current=!0,s},[e,m])}function se({name:t,initialState:a,reducer:r,initializer:n}){const i=s.createContext(null),o=s.createContext(null),c=s.createContext(null),l=s.memo(({children:t})=>{const[l,d]=s.useReducer(r,a,n||(e=>e)),u=s.useMemo(()=>({state:l,dispatch:d}),[l,d]);return e.jsx(c.Provider,{value:u,children:e.jsx(i.Provider,{value:l,children:e.jsx(o.Provider,{value:d,children:t})})})});l.displayName=`${t}Provider`;const d=e=>new Error(`use${t}${e} must be used within a ${t}Provider. Make sure SaaSOSProvider is wrapping your application.`),u=()=>{const e=s.useContext(i);if(null===e)throw d("State");return e};return{Provider:l,useContext:()=>{const e=s.useContext(c);if(!e)throw d("Context");return e},useState:u,useDispatch:()=>{const e=s.useContext(o);if(null===e)throw d("Dispatch");return e},useSelector:(e,s)=>{const t=e||(e=>e);return ee(u(),t,s)}}}var te;function ae(e){return{isAuthenticated:e===te.authenticated,isLoading:e===te.loading||e===te.redirecting||e===te.authenticating,isRedirecting:e===te.redirecting}}function re(e,s,t){return{...e,[s]:t}}function ne(e,s){return{...e,...s}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(te||(te={}));const ie=()=>({session:null,status:te.loading}),{Provider:oe,useState:ce,useDispatch:le}=se({name:"Auth",initialState:ie(),reducer:(e,s)=>{switch(s.type){case"AUTHENTICATION_STARTED":return re(e,"status",te.redirecting);case"AUTHENTICATION_PROCESSING":return re(e,"status",te.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return ne(e,{session:null,status:te.unauthenticated});case"SET_SESSION":return ne(e,{session:s.payload,status:te.authenticated});default:return e}},initializer:ie}),de=oe,ue=ce,me=le,pe=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),he=e=>({type:"SET_SETTINGS",payload:e});var ge;function fe(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}!function(e){e.V1="v1"}(ge||(ge={}));const xe=()=>({serverUrl:"",version:ge.V1,orgId:"",settings:null}),{Provider:be,useState:ye,useDispatch:ve}=se({name:"OS",initialState:xe(),reducer:(e,s)=>{switch(s.type){case"SET_SAAS_OS_CONFIG":return ne(e,s.payload);case"REMOVE_SAAS_OS_CONFIG":return xe();case"SET_SETTINGS":return re(e,"settings",s.payload);default:return e}}}),we=be,Se=ye,Ne=ve,je=e=>({type:"SET_WORKSPACES",payload:e}),ke=e=>({type:"ADD_WORKSPACE",payload:e}),Ce=e=>({type:"UPDATE_WORKSPACE",payload:e}),Ae=e=>({type:"REMOVE_WORKSPACE",payload:e}),Te=e=>({type:"SET_ALL_FEATURES",payload:e}),Ee=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),Pe=()=>({type:"RESET_CURRENT_WORKSPACE"}),Ie=e=>({type:"SET_IS_INITIALIZED",payload:e}),Ue=e=>({type:"SET_LOADING",payload:e}),Re=e=>({type:"SET_ERROR",payload:e}),Me=e=>({type:"SET_REFRESHING",payload:e}),De=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:We,useState:Fe,useDispatch:_e}=se({name:"Workspace",initialState:{workspaces:[],loading:!1,error:null,currentWorkspace:null,refreshing:!1,switchingToId:null,isInitialized:!1,allFeatures:[]},reducer:(e,s)=>{switch(s.type){case"SET_WORKSPACES":return re(e,"workspaces",s.payload);case"ADD_WORKSPACE":return re(e,"workspaces",[...e.workspaces,s.payload]);case"UPDATE_WORKSPACE":return re(e,"workspaces",e.workspaces.map(e=>e._id===s.payload._id?s.payload:e));case"REMOVE_WORKSPACE":return re(e,"workspaces",e.workspaces.filter(e=>e._id!==s.payload));case"SET_ALL_FEATURES":return re(e,"allFeatures",s.payload);case"SET_CURRENT_WORKSPACE":return re(e,"currentWorkspace",s.payload);case"RESET_CURRENT_WORKSPACE":return re(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return re(e,"isInitialized",s.payload);case"SET_LOADING":return re(e,"loading",s.payload);case"SET_ERROR":return re(e,"error",s.payload);case"SET_REFRESHING":return re(e,"refreshing",s.payload);case"SET_SWITCHING_TO_ID":return re(e,"switchingToId",s.payload);default:return e}}}),Oe=We,Le=Fe,Be=_e,Ge=s.memo(({children:s})=>e.jsx(we,{children:e.jsx(de,{children:e.jsx(Oe,{children:s})})}));Ge.displayName="SDKContextProvider";const Ke=s.createContext({});Ke.displayName="CheckoutConfigContext";const Ve=s.memo(({getCheckoutStripeParams:t,children:a})=>{const r=s.useMemo(()=>({getCheckoutStripeParams:t}),[t]);return e.jsx(Ke.Provider,{value:r,children:a})});function ze(){const e=new Set;return{subscribe:s=>(e.add(s),()=>{e.delete(s)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}Ve.displayName="CheckoutConfigProvider";const $e=ze(),qe=$e.subscribe,He=$e.invalidate,Je=ze(),Ye=Je.subscribe,Ze=Je.invalidate,Qe={settings:{titles:{profile:"Account",security:"Security",general:"Workspace Settings",users:"Workspace Members",subscription:"Plan & Billing",usage:"Usage",credits:"Credits",features:"Workspace Features",notifications:"Notifications",permissions:"Permissions",danger:"Danger Zone"},sidebar:{account:"Account",workspace:"Workspace",profile:"Account",security:"Security",general:"Settings",users:"Members",subscription:"Plan & Billing",usage:"Usage",credits:"Credits",features:"Features",notifications:"Notifications",permissions:"Permissions",danger:"Danger Zone"},common:{refresh:"Refresh",refreshing:"Refreshing...",retry:"Retry",retrying:"Retrying...",save:"Save",saving:"Saving...",cancel:"Cancel",delete:"Delete",dismiss:"Dismiss",loading:"Loading...",success:"Success!",error:"Error",refreshAction:"{loading, select, true {Refreshing...} other {Refresh}}",retryAction:"{loading, select, true {Retrying...} other {Retry}}",noPermissionTitle:"Access Restricted",noPermissionDescription:"You don't have permission to access this section. Contact a workspace admin if you need access.",billingManageOnly:"Only users with billing management permissions can perform this action."}},subscription:{managePlan:"Manage your plan and billing",changePlan:"Change Plan",viewPricingPlans:"View Pricing Plans",viewPlans:"View Plans",upgradePlan:"Upgrade Now",subscribe:"Subscribe",currentPlan:"Current Plan",noSubscription:"You don't have an active subscription",choosePlan:"Choose Your Plan",choosePlanDescription:"Compare plans and select the one that fits your needs",forWorkspace:"for {name}",planUpdateAvailable:"Plan update available",updateSuccess:"Subscription updated successfully!",updateFailed:"Update failed",cancelTitle:"Cancel Subscription",cancelConfirm:"Are you sure you want to cancel your subscription?",cancelKeep:"Keep Subscription",cancelButton:"Yes, Cancel Subscription",canceling:"Canceling...",cancelSuccess:"Subscription will be canceled at the end of the billing period.",cancelNotCharged:"You won't be charged again after cancellation",cancelResumeAnytime:"You can resume your subscription anytime before it ends",cancelTrialTitle:"Cancel Trial",cancelTrialConfirm:"Are you sure you want to cancel your trial?",cancelTrialAccess:"Your trial will continue until",cancelTrialNoCharge:"You won't be charged — your trial will simply expire",cancelTrialResume:"You can resume your trial anytime before it ends",cancelTrialKeep:"Keep Trial",cancelTrialButton:"Yes, Cancel Trial",resumeTitle:"Resume Subscription",resumeTrial:"Resume Trial",resumeConfirm:"Are you sure you want to resume your subscription?",resumeKeep:"Keep Canceled",resumeButton:"Yes, Resume Subscription",resuming:"Resuming...",resumeSuccess:"Subscription has been resumed.",managePayment:"Manage Payment",openingPortal:"Opening...",viewAllPlans:"View All Plans",scheduledCancellation:"Subscription scheduled for cancellation",scheduledTrialCancellation:"Trial scheduled for cancellation",paymentPastDue:"Payment past due",paymentPastDueDescription:"Please update your payment method to avoid service interruption.",subscriptionPaused:"Subscription paused",subscriptionPausedDescription:"Your subscription is currently paused. Resume to restore full access.",errorLoading:"Error loading subscription data",errorLoadingDescription:"Please check your connection and try again.",errorProcessing:"Failed to process subscription",errorCanceling:"Failed to cancel subscription",errorResuming:"Failed to resume subscription",invalidWorkspace:"Invalid workspace ID",billingInterval:{monthly:"Monthly",quarterly:"Quarterly",yearly:"Yearly",perMonth:"/month",perQuarter:"/quarter",perYear:"/year"},seats:{title:"Seats",members:"Members",included:"Included",billable:"Billable",perExtraSeat:"Per extra seat",limit:"Limit",includedSeats:"Included seats",maxSeats:"Max seats",freeWithBase:"Free with base price",allIncluded:"All included",extra:"extra",unlimited:"Unlimited"},items:{features:"Features",limits:"Limits",quotas:"Usage Quotas",credits:"AI Credits",creditsPerMonth:"Credits per month",creditsOneTime:"Credits (given once)",creditRenewal:"Credit renewal",creditModeReset:"Fresh every month",creditModeTopup:"Adds up every month",creditModeLifetime:"Given once",creditsPerPeriod:"Credits per month",creditRollover:"Credit renewal"},checkout:{upgrade:"Upgrade",downgrade:"Downgrade",switchTo:"Switch to",select:"Select"},status:{active:"Active",canceling:"Canceling",trial:"Trial",canceled:"Canceled",pastDue:"Past Due",paused:"Paused",deprecated:"Deprecated",unknown:"Unknown"},plan:"Plan",invoicesTab:"Invoices",changePlanButton:"Change Plan",noPlanAssigned:"No plan assigned",free:"Free",perSeatDisplay:"+ {price}/seat{interval}",estTotalDisplay:"Est. total: {total}{interval} ({count, plural, one {# extra seat} other {# extra seats}})",nextBillingDisplay:"Next billing: {date}",membersInWorkspace:"{count, plural, one {# member} other {# members}} in workspace",billingInCurrency:"Billing in {currency}",savingsPercent:"Save {percent, number}%",switchToInterval:"Switch to {interval}",seatPriceDisplay:"+ {price}/seat{interval} ({included} {includedLabel})",trialEnded:"Your trial has ended.",trialEndsIn:"Your trial ends in {days, plural, one {# day} other {# days}}.",onTrial:"You are on a trial.",upgradeToKeepAccess:"Upgrade to keep access.",viewInvoices:"View Invoices",cancelTrial:"Cancel Trial",dunningFinal:"Final warning: Subscription will be suspended",dunningSuspended:"Subscription suspended",dunningRecovery:"Payment recovery in progress",dunningSuspendedDescription:"Your subscription has been suspended due to repeated payment failures. Update your payment method to restore access.",dunningRecoveryDescription:"We were unable to process your payment. Please update your payment method to avoid losing access.",cancelEndDescription:"Your subscription will end on",trialEndDescription:"Your trial will end on",cancelEndFallback:"Your subscription will be canceled at the end of the current billing period. You won't be charged again.",resumeChargeDate:"You will be charged again on",resumeChargeFallback:"the next billing date",resumeContinue:"Your subscription will continue automatically and you'll be billed according to your plan",resumeCancelAnytime:"You can cancel anytime before the next billing date if you change your mind",retainAccess:"You'll retain full access to this plan until",retainAccessFallback:"the end of your current billing period",noPlansAvailable:"No plan groups are available for this workspace. Please contact support if you believe this is an error.",noPlansAvailableHint:"No plan groups are available for this workspace.",startTrialDescription:"Try the full plan with no commitment. You can upgrade or cancel anytime.",noSubscriptionDescription:"Choose a plan to get started with your workspace",startFreeTrial:"Start Free Trial",startTrialDays:"Start {days}-day Free Trial",trialBadge:"{days}-day trial"},users:{title:"Workspace Members",adminOnly:"Only workspace admin can manage users and roles.",inviteByEmail:"Invite member by email",inviteButton:"Invite",inviting:"Inviting...",inviteSuccess:"User invited successfully",emailRequired:"Email is required",invalidEmail:"Invalid email address format",inviteFailed:"Failed to invite member",seatLimitReached:"Seat limit reached",memberLimitReached:"Member limit reached",role:"Role",you:"You",owner:"Owner",noMembers:"No members found in this workspace.",extraSeatCost:"Each additional member adds {price}/{interval, select, yearly {yr} quarterly {qtr} other {mo}} to your subscription",unknownUser:"Unknown User",seats:"Seats",members:"Members",included:"included",perExtraSeat:"/extra seat",maxMembers:"max members",available:"available",noMemberLimit:"No member limit",seatHeading:"{hasSeatPricing, select, true {Seats} other {Members}}",limitReached:"{reason, select, seat_limit_reached {Seat limit reached} other {Member limit reached}}",memberCount:"{count, plural, one {# member} other {# members}}",subscriptionRequired:"A subscription is required to invite members.",seatLimitMessage:"Your plan allows up to {maxUsers, number} members. Upgrade for more seats.",settingsLimitMessage:"This workspace allows up to {maxUsers, number} members.",memberLimitMessage:"Member limit of {maxUsers, number} reached.",selectRole:"Select a role",inviteAs:"Invite as {role}"},invoices:{title:"Billing History",description:"View and download your invoices",pay:"Pay",view:"View",viewDetails:"View Details",download:"PDF",errorLoading:"Error loading invoices",noInvoices:"No invoices yet. Subscribe to a plan to receive invoices.",noInvoicesWithSub:"No invoices with download option found",paidAmount:"Paid: {amount}",na:"N/A",status:{draft:"Draft",open:"Open",paid:"Paid",uncollectible:"Uncollectible",void:"Void"}},usage:{title:"Usage",description:"Monitor your resource consumption and quotas",totalResources:"Total Resources",overallUsage:"Overall Usage",inOverage:"In Overage",estOverageCost:"Est. Overage Cost",overageDetected:"Overage Detected",overageDescription:"Additional usage will be billed as overage on your next invoice.",overageUnits:"Overage units",rate:"Rate",billableBlocks:"Billable blocks",estimatedCharge:"Estimated charge",noData:"No quota usage data available for this workspace.",noDataHint:"Quotas will appear here once your plan includes metered resources.",used:"used",remaining:"remaining",overLimit:"over limit",percentUsed:"{percent, number}% used",availableRemaining:"{count} remaining",overLimitCount:"{count} over limit",overageWarning:"{count, plural, one {# resource has exceeded the included quota.} other {# resources have exceeded the included quota.}} Additional usage will be billed as overage on your next invoice.",fullyUsed:"Fully used",renewingSoon:"renewing soon",almostFull:"Almost full",overage:"Overage",errorLoading:"Failed to load usage data",perUnit:"/ unit",perUnits:"/ units",rateDisplay:"{rate} {unitSize, plural, =1 {/ unit} other {/ {unitSize, number} units}}",resourcesExceeded:"{count, plural, one {# resource has exceeded the included quota.} other {# resources have exceeded the included quota.}}",estOverageCharges:"Estimated overage charges this period: {amount}",overageRateDisplay:"Overage rate: {rate}",resetDateDisplay:"Usage resets on {date}",daysRemainingDisplay:"{count, plural, one {# day remaining} other {# days remaining}}"},profile:{email:"Email",name:"Name",language:"Language",country:"Country",currency:"Currency",timezone:"Timezone",profileImage:"Profile Image",success:"Profile saved successfully",nameMinLength:"Name must be at least 2 characters.",save:"Save",reset:"Reset"},general:{ownerOnly:"Only the workspace owner can change the workspace settings.",name:"Name",namePlaceholder:"My Awesome Workspace",nameMinLength:"Workspace name must be at least 2 characters.",billingCurrency:"Billing currency",icon:"Icon",iconDescription:"Choose an emoji or upload a custom image for your workspace.",imageUrl:"Image URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"Enter a valid URL for your workspace image. Supports PNG, JPG, and SVG formats.",previewLabel:"Preview:",success:"Workspace settings saved successfully",chooseEmoji:"Choose Emoji",customImageUrl:"Custom Image URL",updateWorkspace:"Update Workspace"},features:{title:"Workspace Features",ownerOnly:"Only the workspace owner can change the features.",noFeatures:"Workspace has no features to manage.",enabled:"enabled",disabled:"disabled",enabling:"Enabling",disabling:"Disabling",featureSuccess:"successfully",updateSuccess:"{feature} {enabled, select, true {enabled} other {disabled}} successfully",actionStatus:"{action, select, enabling {Enabling} disabling {Disabling} other {}}"},danger:{title:"Delete Workspace",adminOnly:"Only workspace admins can delete workspaces.",deleteWorkspace:"Delete Workspace",deleteConfirm:"Are you absolutely sure?",deleteWarning:"This action cannot be undone. This will permanently delete the workspace and all associated data.",deleting:"Deleting...",deleteDescription:"Once you delete a workspace, there is no going back. This will permanently delete the workspace and all of its data, including members, settings, and features.",deleteConfirmDescription:"This action cannot be undone. This will permanently delete the workspace and all of its data.",failedToDelete:"Failed to delete workspace"},notifications:{title:"Notification Preferences",permissionDenied:"Notification permission denied",notSupported:"Push notifications are not supported in this browser.",manageDescription:"Manage how you receive notifications from this workspace.",blocked:"Notifications Blocked",blockedDescription:"You previously blocked notifications for this site. To enable them, update your browser settings:",pushTitle:"Push Notifications",pushEnabledDescription:"You will receive browser notifications for important updates.",pushDisabledDescription:"Get notified about payment issues, trial expiry, and other important updates.",enabling:"Enabling...",disabling:"Disabling...",enable:"Enable",disable:"Disable",toggleAction:"{loading, select, true {{subscribed, select, true {Disabling...} other {Enabling...}}} other {{subscribed, select, true {Disable} other {Enable}}}}",pushDescription:"{subscribed, select, true {You will receive browser notifications for important updates.} other {Get notified about payment issues, trial expiry, and other important updates.}}",deviceNote:"Notifications are sent to this device. Enable on other devices separately.",prefsSaved:"Notification preferences saved.",loadingPrefs:"Loading preferences...",categories:{workspace:"Workspace",billing:"Billing & Payments"},events:{workspace_invite:"Member Invited",workspace_invite_desc:"When a new member is added to the workspace",workspace_removed:"Member Removed",workspace_removed_desc:"When a member is removed from the workspace",workspace_role_changed:"Role Changed",workspace_role_changed_desc:"When a member's role is updated",subscription_created:"Subscription Created",subscription_created_desc:"When a new subscription is activated",subscription_upgraded:"Plan Upgraded",subscription_upgraded_desc:"When the subscription plan is upgraded",subscription_canceled:"Subscription Canceled",subscription_canceled_desc:"When the subscription is canceled",subscription_suspended:"Access Suspended",subscription_suspended_desc:"When access is suspended due to payment failures",trial_ending:"Trial Ending",trial_ending_desc:"A few days before the trial expires",trial_expired:"Trial Expired",trial_expired_desc:"When the trial period has ended",payment_failed:"Payment Failed",payment_failed_desc:"When a payment could not be processed",payment_action_required:"Payment Action Required",payment_action_required_desc:"When a payment requires additional verification",payment_succeeded:"Payment Received",payment_succeeded_desc:"When a payment is successfully processed"},unblock:{firefox:{step1:"Click the lock icon (or shield icon) in the address bar",step2:'Find "Notifications" in the permissions list',step3:'Change from "Blocked" to "Allow"',step4:"Reload this page"},safari:{step1:"Open Safari → Settings → Websites → Notifications",step2:"Find this website in the list",step3:'Change from "Deny" to "Allow"',step4:"Reload this page"},edge:{step1:"Click the lock icon in the address bar",step2:'Click "Permissions for this site"',step3:'Set "Notifications" to "Allow"',step4:"Reload this page"},chrome:{step1:"Click the lock icon (or tune icon) in the address bar",step2:'Click "Site settings"',step3:'Set "Notifications" to "Allow"',step4:"Reload this page"}}},quota:{includedOnly:"{count, number}/mo",includedWithOverage:"{count, number}/mo, then {price} / {unit}",includedHardLimit:"{count, number}/mo (hard limit)",unitFallback:"unit"},pricing:{title:"Choose Your Plan",description:"Compare plans and select the one that fits your needs",currency:"Currency",billingIn:"Billing in",noPlansCurrency:"No plans available for your billing currency.",noPlansCurrencyHint:"Something went wrong. Please contact support.",noPlans:"No plans available",free:"Free",included:"included",save:"Save",current:"Current",processing:"Processing...",unavailable:"Unavailable",selectCurrency:"Select billing currency",billingInterval:"Billing interval"},beta:{nameLabel:"Name",emailLabel:"Email",submitText:"Submit",submittingText:"Submitting...",errorMessage:"An error occurred",tryAgain:"Try Again",privacyConsent:"By submitting this form, you consent to our",privacyPolicy:"Privacy Policy",and:"and",termsOfService:"Terms of Service"},workspace:{switchTitle:"Switch Workspace",switchDescription:"Select a workspace to switch to or create a new one.",notLoggedIn:"Looks like you are not logged in. Please login to continue.",availableWorkspaces:"Available Workspaces ({count, number})",loadingWorkspaces:"Loading workspaces...",searchPlaceholder:"Search workspaces...",noWorkspacesFound:"No workspaces found",noWorkspacesAvailable:"No workspaces available",switchTo:"Switch to",membersCount:"{count, plural, one {# member} other {# members}}",createNew:"Create New Workspace",createTitle:"Create New Workspace",createDescription:"Create a new workspace to get started.",workspaceName:"Workspace Name",workspaceNamePlaceholder:"My Awesome Workspace",workspaceNameMinLength:"Workspace name must be at least 2 characters.",workspaceIcon:"Workspace Icon",iconDescription:"Choose an emoji or upload a custom image for your workspace.",chooseEmoji:"Choose Emoji",customImageUrl:"Custom Image URL",imageUrl:"Image URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"Enter a valid URL for your workspace image. Supports PNG, JPG, and SVG formats.",invalidUrl:"Please enter a valid URL",creating:"Creating...",createWorkspace:"Create Workspace"},dropdowns:{search:"Search...",chooseOption:"Choose option",chooseCountry:"Choose country",searchCountry:"Choose country...",chooseLanguage:"Choose language",searchLanguage:"Choose language...",chooseCurrency:"Choose currency",searchCurrency:"Choose currency...",chooseTimezone:"Choose timezone",searchTimezone:"Choose timezone..."},push:{failedToSubscribe:"Failed to subscribe to push notifications",failedToUnsubscribe:"Failed to unsubscribe from push notifications"},permissions:{title:"Permissions",description:"Permissions assigned to each role in this workspace.",ownerOnly:"Only the workspace owner can manage permissions.",save:"Save Permissions",saving:"Saving...",saveSuccess:"Permissions saved successfully"},credits:{title:"Credits",description:"Credits can be used for premium actions like AI generation.",balance:"Credit Balance",available:"Available",totalGranted:"Total Granted",totalConsumed:"Total Consumed",totalExpired:"Total Expired",noCredits:"No credits yet",noCreditsHint:"Credits will appear here when granted by your plan or purchased.",buyCredits:"Buy Credits",buyAmount:"Buy {count} Credits",purchasing:"Redirecting...",packages:"Credit Packages",noPackages:"No credit packages available.",creditsAmount:"{count} credits",validityDays:"Valid for {count} days",validityUnlimited:"No expiry",transactions:"Recent Transactions",noTransactions:"No transactions yet.",loadMore:"Load More",viewAll:"View All",expiringSoon:"Expiring Soon",expiringInDays:"{count} credits expiring within {days} days",noExpiring:"No credits expiring soon.",type:{plan_grant:"Plan Grant",pack_purchased:"Purchased",consumed:"Consumed",expired:"Expired",admin_grant:"Granted",admin_revoke:"Revoked",refund:"Refund"},dialogTitle:"Buy Credit Packages",dialogDescription:"Choose a credit package to purchase.",dialogDescriptionWorkspace:"Purchase credits for {workspace}.",perCredit:"{price} per credit",purchaseSuccess:"Credits purchased successfully! Your balance has been updated.",purchaseCanceled:"Credit purchase was canceled. No charges were made.",purchaseFailed:"Credit purchase failed. Please try again or contact support.",errorLoading:"Failed to load credit data",insufficientCredits:"Not enough credits"},loading:{restoringSession:"Restoring your session...",redirecting:"Redirecting...",signingIn:"Signing you in...",verifyingAccount:"Verifying your account...",almostThere:"Almost there..."},errors:{networkError:"Network error: Please check your internet connection",unauthorized:"Unauthorized - Please check your session",notFound:"Resource not found",generic:"An error occurred",fetchPlans:"Failed to fetch plans",fetchPlanGroup:"Failed to fetch plan group",fetchPlanGroupVersion:"Failed to fetch plan group version",fetchPlanGroupVersions:"Failed to fetch plan group versions",fetchSubscription:"Failed to fetch subscription",createCheckout:"Failed to create checkout session",updateSubscription:"Failed to update subscription",fetchInvoices:"Failed to fetch invoices",fetchInvoice:"Failed to fetch invoice",openBillingPortal:"Failed to open billing portal",cancelSubscription:"Failed to cancel subscription",resumeSubscription:"Failed to resume subscription",recordUsage:"Failed to record usage",fetchQuotaUsage:"Failed to fetch quota usage status",fetchAllQuotaUsage:"Failed to fetch all quota usage",fetchUsageLogs:"Failed to fetch usage logs",fetchCreditBalance:"Failed to fetch credit balance",consumeCredits:"Failed to consume credits",purchaseCredits:"Failed to purchase credits",fetchCreditPackages:"Failed to fetch credit packages",fetchCreditTransactions:"Failed to fetch credit transactions",fetchExpiringCredits:"Failed to fetch expiring credits"},security:{inactive:"Inactive",inactiveHint:"Registered on a previous sign-in domain and can no longer be used. You can remove it.",passkeysTitle:"Passkeys",passkeysDescription:"Passkeys let you sign in with your fingerprint, face, or device PIN.",noPasskeys:"No passkeys registered",addHint:'To add a passkey, choose "Add a passkey" the next time you sign in on the device you want to use.',rename:"Rename",remove:"Remove",removeTitle:"Remove passkey",removeDescription:"You will no longer be able to sign in with this passkey.",renamePlaceholder:"Passkey name",lastUsed:"Last used",added:"Added"}},Xe={en:async()=>Qe,es:async()=>(await Promise.resolve().then(function(){return require("./es-B9kiwJmF.cjs")})).es,fr:async()=>(await Promise.resolve().then(function(){return require("./fr-C500Ytao.cjs")})).fr,de:async()=>(await Promise.resolve().then(function(){return require("./de-D3q0vQBG.cjs")})).de,ja:async()=>(await Promise.resolve().then(function(){return require("./ja-DfROrx_j.cjs")})).ja,zh:async()=>(await Promise.resolve().then(function(){return require("./zh-CLmBh-it.cjs")})).zh,hi:async()=>(await Promise.resolve().then(function(){return require("./hi-CfFhH2uQ.cjs")})).hi,ar:async()=>(await Promise.resolve().then(function(){return require("./ar-BRvKHRYS.cjs")})).ar},es=["en","es","fr","de","ja","zh","hi","ar"];const ss={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};const ts=s.createContext({messages:Qe,locale:"en",formattingLocale:"en"});function as({locale:e="en",children:t}){const a=function(e){const s=e.toLowerCase().replace("_","-");if(es.includes(s))return s;const t=s.split("-")[0];return es.includes(t)?t:"en"}(e),[r,n]=s.useState(Qe);s.useEffect(()=>{if("en"===a)return void n(Qe);let e=!1;const s=Xe[a];return s&&s().then(s=>{e||n(s)}),()=>{e=!0}},[a]);const i=function(e){return ss[e]??e}(a),o=s.useMemo(()=>({messages:r,locale:a,formattingLocale:i}),[r,a,i]);return s.createElement(ts.Provider,{value:o},t)}const rs=new Map,ns=new Map,is=new Map;function os(e,s){return s?`${e}:${JSON.stringify(s)}`:e}const cs={getNumberFormat(e,s){const t=os(e,s);let a=rs.get(t);return a||(a=new Intl.NumberFormat(e,s),rs.set(t,a)),a},getDateTimeFormat(e,s){const t=os(e,s);let a=ns.get(t);return a||(a=new Intl.DateTimeFormat(e,s),ns.set(t,a)),a},getPluralRules(e,s){const t=os(e,s);let a=is.get(t);return a||(a=new Intl.PluralRules(e,s),is.set(t,a)),a}},ls=new Map;function ds(){const{messages:e,locale:t,formattingLocale:a}=s.useContext(ts),n=s.useMemo(()=>(s,t)=>{const n=s.split(".");let i=e;for(const e of n){if(!i||"object"!=typeof i||!(e in i))return s;i=i[e]}const o="string"==typeof i?i:s;if(!t)return o;try{const e=function(e,s){const t=`${s}:${e}`;let a=ls.get(t);return a||(a=new r(e,s,void 0,{formatters:cs}),ls.set(t,a)),a}(o,a),s=e.format(t);return"string"==typeof s?s:String(s)}catch{return o.replace(/\{(\w+)\}/g,(e,s)=>String(t[s]??`{${s}}`))}},[e,a]),i="ar"===t?"rtl":"ltr",o=s.useMemo(()=>e=>e.toLocaleString(a),[a]),c=s.useMemo(()=>(e,s)=>{const t=(s??"").trim().toUpperCase();if(!t)return(e/100).toLocaleString(a,{minimumFractionDigits:2});try{return new Intl.NumberFormat(a,{style:"currency",currency:t,minimumFractionDigits:2}).format(e/100)}catch{return(e/100).toLocaleString(a,{minimumFractionDigits:2})}},[a]);return{t:n,locale:t,formattingLocale:a,dir:i,fmtNum:o,fmtCents:c,messages:e}}function us(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(s){return z(s,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function ms(e,s){if("undefined"!=typeof window)try{localStorage.setItem(e,s)}catch(s){z(s,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function ps(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(s){z(s,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}const hs="saas-session-id",gs="code",fs="state";function xs(e){ms(hs,e)}function bs(){return function(){if("undefined"==typeof window)return null;try{return us(hs)}catch(e){return z(e,{component:"auth-utils",action:"getSessionId",metadata:{key:hs}}),null}}()}function ys(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(gs)}catch(e){return z(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:gs}}),null}}function vs(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(gs),e.searchParams.delete(fs),window.history.replaceState({},"",e.toString())}catch(e){z(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:gs}})}}const ws=new WeakSet,Ss="SDK is not ready (missing serverUrl, version, or orgId)";class Ns{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(Ss);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(Ss)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=bs(),s={};return e&&(s["x-session-id"]=e),s}()}url(e){const s=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${s}`}buildHeaders(e){const s={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(s,e.headers),null==e.body||s["Content-Type"]||(s["Content-Type"]="application/json"),s}reportError(e,s){ws.has(e)||(ws.add(e),this._onError?.(e,s))}async executeFetch(e,s){return this.executeFetchUrl(this.url(e),s,e)}async executeFetchUrl(e,s,t){const a=(s.method??"GET").toUpperCase(),r=t??e,n=this.buildHeaders(s),i={...s,headers:n};let o;if(this._timeout>0){const e=new AbortController;o=setTimeout(()=>e.abort(),this._timeout),i.signal=s.signal?function(e,s){const t=AbortSignal.any;if("function"==typeof t)return t([e,s]);const a=new AbortController,r=e=>{a.signal.aborted||a.abort(e.reason)};for(const t of[e,s]){if(t.aborted){r(t);break}t.addEventListener("abort",()=>r(t),{once:!0})}return a.signal}(s.signal,e.signal):e.signal}const c=async s=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const t=this._fetch.bind(globalThis),r=await t(e,i);if(this._debug&&console.log(`[BuildBase] ${a} ${e} → ${r.status}`),401===r.status&&this._onUnauthorized&&this._onUnauthorized(),r.status>=500&&s<this._maxRetries){const e=Math.min(1e3*Math.pow(2,s),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${s+1}/${this._maxRetries})`),await new Promise(s=>setTimeout(s,e)),c(s+1)}return r}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(void 0!==o){const e=new Error(`Request timeout after ${this._timeout}ms: ${a} ${r}`);throw this.reportError(e,{method:a,path:r}),e}throw e}if(s<this._maxRetries){const e=Math.min(1e3*Math.pow(2,s),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${s+1}/${this._maxRetries})`),await new Promise(s=>setTimeout(s,e)),c(s+1)}throw e instanceof Error&&this.reportError(e,{method:a,path:r}),e}};try{return await c(0)}finally{void 0!==o&&clearTimeout(o)}}async fetchJson(e,s={},t="Request failed"){this.ensureReady();try{const a=await this.executeFetch(e,s);return await G(a,t)}catch(t){throw t instanceof Error&&this.reportError(t,{method:(s.method??"GET").toUpperCase(),path:e}),t}}async fetchResponse(e,s={}){return this.ensureReady(),this.executeFetch(e,s)}async fetchAbsoluteUrl(e,s={}){return this.ensureReady(),this.executeFetchUrl(e,s)}async throwResponseError(e,s){let t=s;try{t=(await e.json()).message||t}catch{t=`${s} (${e.status}: ${e.statusText})`}throw new Error(t)}async unwrapResponse(e,s){const t=await e.json();if(void 0!==t.success){if(!t.success)throw new Error(t.message||s);return t.data||t}return t}}class js extends Ns{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,s){return this.fetchJson(`workspaces/${e}`,{method:"PUT",body:JSON.stringify(s)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,s){return this.fetchJson(`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(s)},"Failed to invite member")}async removeUser(e,s){return this.fetchJson(`workspaces/${e}/users/${s}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,s,t){return this.fetchJson(`workspaces/${e}/users/${s}`,{method:"PATCH",body:JSON.stringify(t)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,s){return this.fetchJson(`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:s})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,s,t){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[s]:t}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getPasskeys(){const e=await this.fetchJson("passkeys",{},"Failed to fetch passkeys");return e?.passkeys??[]}async renamePasskey(e,s){await this.fetchJson(`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:s})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const s=await this.fetchResponse(`workspaces/${e}/subscription`);return s.ok||await this.throwResponseError(s,"Failed to fetch subscription"),this.unwrapResponse(s,"Failed to fetch subscription")}async getPlanGroup(e){const s=await this.fetchResponse(`workspaces/${e}/subscription/plan-group`);return s.ok||await this.throwResponseError(s,"Failed to fetch plan group"),this.unwrapResponse(s,"Failed to fetch plan group")}async getPlanGroupByVersion(e,s){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${encodeURIComponent(s)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group version"),this.unwrapResponse(t,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const s=await this.fetchResponse(`workspaces/${e}/subscription/plan-group/versions`);return s.ok||await this.throwResponseError(s,"Failed to fetch plan group versions"),this.unwrapResponse(s,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const s=await this.fetchResponse(`${this.orgId}/plans/${encodeURIComponent(e)}`);return s.ok||await this.throwResponseError(s,"Failed to fetch plans"),this.unwrapResponse(s,"Failed to fetch plans")}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(`${this.orgId}/credit-packages`);return e.ok||await this.throwResponseError(e,"Failed to fetch credit packages"),this.unwrapResponse(e,"Failed to fetch credit packages")}async getPlanGroupVersion(e){const s=await this.fetchResponse(`plan-group-versions/${e}`);return s.ok||await this.throwResponseError(s,"Failed to fetch plan group version"),this.unwrapResponse(s,"Failed to fetch plan group version")}async createCheckoutSession(e,s){const t=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(s)});return t.ok||await this.throwResponseError(t,"Failed to create checkout session"),this.unwrapResponse(t,"Failed to create checkout session")}async selectFreePlan(e,s){const t=await this.fetchResponse(`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:s})});return t.ok||await this.throwResponseError(t,"Failed to select free plan"),t.json()}async updateSubscription(e,s){const t=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(s)});return t.ok||await this.throwResponseError(t,"Failed to update subscription"),this.unwrapResponse(t,"Failed to update subscription")}async createBillingPortalSession(e,s){return this.fetchJson(`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(s?{returnUrl:s}:{})})}async listInvoices(e,s=10,t){const a=new URLSearchParams;a.append("limit",s.toString()),t&&a.append("starting_after",t);const r=await this.fetchResponse(`workspaces/${e}/subscription/invoices?${a.toString()}`);return r.ok||await this.throwResponseError(r,"Failed to fetch invoices"),this.unwrapResponse(r,"Failed to fetch invoices")}async getInvoice(e,s){const t=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${s}`);return t.ok||await this.throwResponseError(t,"Failed to fetch invoice"),this.unwrapResponse(t,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const s=await this.fetchResponse(`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return s.ok||await this.throwResponseError(s,"Failed to cancel subscription"),this.unwrapResponse(s,"Failed to cancel subscription")}async resumeSubscription(e){const s=await this.fetchResponse(`workspaces/${e}/subscription/resume`,{method:"POST"});return s.ok||await this.throwResponseError(s,"Failed to resume subscription"),this.unwrapResponse(s,"Failed to resume subscription")}async recordUsage(e,s){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(s)});return t.ok||await this.throwResponseError(t,"Failed to record usage"),this.unwrapResponse(t,"Failed to record usage")}async recordUsageBatch(e,s){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(s)});return t.ok||await this.throwResponseError(t,"Failed to record batch usage"),this.unwrapResponse(t,"Failed to record batch usage")}async getQuotaUsageStatus(e,s){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(s)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch quota usage status"),this.unwrapResponse(t,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage/all`);return s.ok||await this.throwResponseError(s,"Failed to fetch all quota usage"),this.unwrapResponse(s,"Failed to fetch all quota usage")}async getUsageLogs(e,s){const t=new URLSearchParams;s?.quotaSlug&&t.append("quotaSlug",s.quotaSlug),s?.from&&t.append("from",s.from),s?.to&&t.append("to",s.to),s?.source&&t.append("source",s.source),s?.page&&t.append("page",s.page.toString()),s?.limit&&t.append("limit",s.limit.toString());const a=t.toString(),r=`workspaces/${e}/subscription/usage/logs${a?`?${a}`:""}`,n=await this.fetchResponse(r);return n.ok||await this.throwResponseError(n,"Failed to fetch usage logs"),this.unwrapResponse(n,"Failed to fetch usage logs")}async sendNotification(e,s,t,a){const r={event:s};return t&&(r.userId=t),a&&(r.data=a),this.fetchJson(`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(r)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,s){return(await this.fetchJson(`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:s})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const s=await this.fetchResponse(`workspaces/${e}/credits`);return s.ok||await this.throwResponseError(s,"Failed to fetch credit balance"),this.unwrapResponse(s,"Failed to fetch credit balance")}async consumeCredits(e,s){const t=await this.fetchResponse(`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(s)});if(!t.ok){if(402===t.status){const e=await t.json().catch(()=>({})),s=new Error(e.message||"Insufficient credits");throw s.available=e.available,s.requested=e.requested,s.code="INSUFFICIENT_CREDITS",s}await this.throwResponseError(t,"Failed to consume credits")}return this.unwrapResponse(t,"Failed to consume credits")}async purchaseCredits(e,s){const t=await this.fetchResponse(`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(s)});return t.ok||await this.throwResponseError(t,"Failed to create credit purchase checkout"),this.unwrapResponse(t,"Failed to create credit purchase checkout")}async getCreditPackages(e){const s=await this.fetchResponse(`workspaces/${e}/credits/packages`);s.ok||await this.throwResponseError(s,"Failed to fetch credit packages");const t=await this.unwrapResponse(s,"Failed to fetch credit packages");return t.docs??t}async getCreditTransactions(e,s){const t=new URLSearchParams;s?.type&&t.append("type",s.type),s?.page&&t.append("page",s.page.toString()),s?.limit&&t.append("limit",s.limit.toString());const a=t.toString(),r=`workspaces/${e}/credits/transactions${a?`?${a}`:""}`,n=await this.fetchResponse(r);return n.ok||await this.throwResponseError(n,"Failed to fetch credit transactions"),this.unwrapResponse(n,"Failed to fetch credit transactions")}async getCreditBuckets(e,s){const t=new URLSearchParams;s?.status&&t.append("status",s.status),s?.source&&t.append("source",s.source),s?.page&&t.append("page",s.page.toString()),s?.limit&&t.append("limit",s.limit.toString());const a=t.toString(),r=`workspaces/${e}/credits/buckets${a?`?${a}`:""}`,n=await this.fetchResponse(r);return n.ok||await this.throwResponseError(n,"Failed to fetch credit buckets"),this.unwrapResponse(n,"Failed to fetch credit buckets")}async getExpiringCredits(e,s){const t=s?`?days=${s}`:"",a=await this.fetchResponse(`workspaces/${e}/credits/expiring${t}`);return a.ok||await this.throwResponseError(a,"Failed to fetch expiring credits"),this.unwrapResponse(a,"Failed to fetch expiring credits")}}function ks(){const e=me(),t=Ne(),a=Be();return s.useMemo(()=>({auth:e,os:t,workspaces:a}),[e,t,a])}function Cs(e,t){const a=Se(),r=ue(),n=Le(),i=e||(e=>e);return ee(s.useMemo(()=>({os:a,auth:r,workspaces:n}),[a,r,n]),i,t)}function As(e,t,a){s.useEffect(()=>{const s=new AbortController;return e(s.signal).catch(e=>{L(e)||(a?.onError?a.onError(e):z(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>s.abort()},t)}class Ts extends Ns{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}function Es(){return Cs(e=>e.os)}let Ps=null;function Is(){const e=ks(),t=Es(),{serverUrl:a,version:r,orgId:n,settings:i}=t,o=s.useMemo(()=>fe(t)?new Ts({serverUrl:a,version:r,orgId:n}):null,[a,r,n]),c=s.useCallback(async s=>o?Ps||(Ps=(async()=>{try{const t=await o.getSettings(s);return e.os(he(t)),t}catch(e){return $(e,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:a,version:r,orgId:n}}),null}finally{Ps=null}})(),Ps):null,[o,e,a,r,n]);return As(async e=>{i||fe(t)&&await c(e)},[a,r,n],{onError:e=>$(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:a,version:r,orgId:n}})}),s.useMemo(()=>({settings:i,getSettings:c}),[i,c])}function Us(){const e=Es(),t=s.useCallback(()=>{e.auth?.callbacks?.onSessionExpired?.("expired")},[e.auth?.callbacks?.onSessionExpired]),a=function(e,t){return s.useMemo(()=>new js({...e,onUnauthorized:t}),[e.serverUrl,e.version,e.orgId,t])}(e,t);return s.useMemo(()=>({os:e,api:a}),[e,a])}const Rs=e=>{const{t:t}=ds(),{os:a,api:r}=Us(),n=fe(a),[i,o]=s.useState(null),[c,l]=s.useState(!1),[d,u]=s.useState(null),m=s.useCallback(async()=>{if(e&&n){l(!0),u(null);try{const s=await r.getPublicPlans(e);o(s)}catch(s){const a=q(s,"errors.fetchPlans",t);u(a),z(s,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{l(!1)}}else o(null)},[r,e,n]);s.useEffect(()=>{m()},[m]);const p=e&&!n||c;return{items:i?.items??[],plans:i?.plans??[],notes:i?.notes,loading:p,error:d,refetch:m}},Ms=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(null),[i,o]=s.useState(!1),[c,l]=s.useState(null),d=s.useCallback(async()=>{if(e){o(!0),l(null);try{const s=await a.getCurrentSubscription(e);n(s)}catch(s){const a=q(s,"errors.fetchSubscription",t);l(a),z(s,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[a,e]);return s.useEffect(()=>{d()},[d]),{subscription:r,loading:i,error:c,refetch:d}},Ds=(e,t)=>{const{t:a}=ds(),{api:r}=Us(),[n,i]=s.useState(null),[o,c]=s.useState(!1),[l,d]=s.useState(null),u=s.useCallback(async()=>{if(e){c(!0),d(null);try{const s=t?await r.getPlanGroupByVersion(e,t):await r.getPlanGroup(e);i(s)}catch(s){const r=q(s,"errors.fetchPlanGroup",a);d(r),z(s,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:t}})}finally{c(!1)}}else i(null)},[r,e,t]);return s.useEffect(()=>{u()},[u]),{planGroup:n,loading:o,error:l,refetch:u}},Ws=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(null),[i,o]=s.useState(!1),[c,l]=s.useState(null),d=s.useCallback(async()=>{if(e){o(!0),l(null);try{const s=await a.getPlanGroupVersions(e);n(s)}catch(s){const a=q(s,"errors.fetchPlanGroupVersions",t);l(a),z(s,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[a,e]);return s.useEffect(()=>{d()},[d]),{versions:r,loading:i,error:c,refetch:d}},Fs=e=>{const{t:t}=ds(),{api:a}=Us(),{getCheckoutStripeParams:r}=s.useContext(Ke),[n,i]=s.useState(!1),[o,c]=s.useState(null);return{createCheckoutSession:s.useCallback(async s=>{if(!e)throw new Error("Workspace ID is required");i(!0),c(null);try{let t=s;if(r){const e=await r(s);e&&(t={...s,stripeOptions:{...s.stripeOptions,...e,metadata:{...s.stripeOptions?.metadata,...e.metadata},subscriptionMetadata:{...s.stripeOptions?.subscriptionMetadata,...e.subscriptionMetadata}}})}const n=await a.createCheckoutSession(e,t);return"trial_started"===n.type&&(Ze(),He()),n}catch(a){const r=q(a,"errors.createCheckout",t);throw c(r),z(a,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:s}}),a}finally{i(!1)}},[a,e,r]),loading:n,error:o}},_s=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(!1),[i,o]=s.useState(null);return{updateSubscription:s.useCallback(async(s,r)=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const t={planVersionId:s,...r?.billingInterval&&{billingInterval:r.billingInterval},...r?.successUrl&&{successUrl:r.successUrl},...r?.cancelUrl&&{cancelUrl:r.cancelUrl}},n=await a.updateSubscription(e,t);return Ze(),n}catch(a){const n=q(a,"errors.updateSubscription",t);throw o(n),z(a,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:s,options:r}}),a}finally{n(!1)}},[a,e]),loading:r,error:i}},Os=(e,t)=>{const a=Ms(e),r=Ds(e,t),n=_s(e),i=s.useCallback(async()=>{await Promise.all([a.refetch(),r.refetch()])},[a.refetch,r.refetch]);return{subscription:a.subscription,planGroup:r.planGroup,loading:a.loading||r.loading||n.loading,error:a.error||r.error||n.error,updateSubscription:n.updateSubscription,refetch:i}},Ls=(e,t=10,a)=>{const{t:r}=ds(),{api:n}=Us(),[i,o]=s.useState([]),[c,l]=s.useState(!1),[d,u]=s.useState(!1),[m,p]=s.useState(null),h=s.useCallback(async()=>{if(!e)return o([]),void l(!1);u(!0),p(null);try{const s=await n.listInvoices(e,t,a);o(s.invoices||[]),l(s.has_more||!1)}catch(s){const n=q(s,"errors.fetchInvoices",r);p(n),z(s,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:t,startingAfter:a}})}finally{u(!1)}},[n,e,t,a]);return s.useEffect(()=>{h()},[h]),{invoices:i,hasMore:c,loading:d,error:m,refetch:h}},Bs=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(!1),[i,o]=s.useState(null);return{openBillingPortal:s.useCallback(async s=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const t=s||window.location.href,r=await a.createBillingPortalSession(e,t);return r.url&&window.open(r.url,"_blank","noopener,noreferrer"),r}catch(s){const a=q(s,"errors.openBillingPortal",t);throw o(a),z(s,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),s}finally{n(!1)}},[e,a]),loading:r,error:i}},Gs=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(!1),[i,o]=s.useState(null);return{cancelSubscription:s.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const s=await a.cancelSubscriptionAtPeriodEnd(e);return Ze(),s}catch(s){const a=q(s,"errors.cancelSubscription",t);throw o(a),z(s,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),s}finally{n(!1)}},[a,e]),loading:r,error:i}},Ks=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(!1),[i,o]=s.useState(null);return{resumeSubscription:s.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const s=await a.resumeSubscription(e);return Ze(),s}catch(s){const a=q(s,"errors.resumeSubscription",t);throw o(a),z(s,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),s}finally{n(!1)}},[a,e]),loading:r,error:i}},Vs=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(null),[i,o]=s.useState(!1),[c,l]=s.useState(null),d=s.useCallback(async()=>{if(e){o(!0),l(null);try{const s=await a.getAllQuotaUsage(e);n(s.quotas)}catch(s){const a=q(s,"errors.fetchAllQuotaUsage",t);l(a),z(s,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[a,e]);return s.useEffect(()=>{d()},[d]),{quotas:r,loading:i,error:c,refetch:d}},zs=s.createContext(null);zs.displayName="SubscriptionContext";const $s=s.memo(function({children:t}){const a=Cs(e=>e.workspaces.currentWorkspace),{subscription:r,loading:n,error:i,refetch:o}=Ms(a?._id);s.useEffect(()=>Ye(o),[o]);const c=s.useMemo(()=>({response:r,loading:n,error:i,refetch:o}),[r,n,i,o]);return e.jsx(zs.Provider,{value:c,children:t})});function qs(){const e=s.useContext(zs);if(null===e)throw new Error("useSubscriptionContext must be used within SubscriptionContextProvider. Make sure SubscriptionContextProvider is wrapping your application (or the tree that uses subscription gates).");return e}$s.displayName="SubscriptionContextProvider";const Hs=ze(),Js=Hs.subscribe,Ys=Hs.invalidate,Zs=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(null),[i,o]=s.useState(!1),[c,l]=s.useState(null),d=s.useCallback(async()=>{if(e){o(!0),l(null);try{const s=await a.getCreditBalance(e);n(s)}catch(s){const a=q(s,"errors.fetchCreditBalance",t);l(a),z(s,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[a,e]);return s.useEffect(()=>{d()},[d]),{balance:r,loading:i,error:c,refetch:d}},Qs=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(!1),[i,o]=s.useState(null);return{consumeCredits:s.useCallback(async s=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const t=await a.consumeCredits(e,s);return Ys(),t}catch(a){const r="INSUFFICIENT_CREDITS"===a.code?`Insufficient credits. Available: ${a.available}, requested: ${a.requested}`:q(a,"errors.consumeCredits",t);throw o(r),z(a,{component:"useConsumeCredits",action:"consumeCredits",metadata:{workspaceId:e,request:s}}),a}finally{n(!1)}},[a,e]),loading:r,error:i}},Xs=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(!1),[i,o]=s.useState(null);return{purchaseCredits:s.useCallback(async s=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{return await a.purchaseCredits(e,s)}catch(a){const r=q(a,"errors.purchaseCredits",t);throw o(r),z(a,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:s}}),a}finally{n(!1)}},[a,e]),loading:r,error:i}},et=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState([]),[i,o]=s.useState(!1),[c,l]=s.useState(null),d=s.useCallback(async()=>{if(e){o(!0),l(null);try{const s=await a.getCreditPackages(e);n(s)}catch(s){const a=q(s,"errors.fetchCreditPackages",t);l(a),z(s,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{o(!1)}}else n([])},[a,e]);return s.useEffect(()=>{d()},[d]),{packages:r,loading:i,error:c,refetch:d}},st=(e,t)=>{const{t:a}=ds(),{api:r}=Us(),[n,i]=s.useState([]),[o,c]=s.useState(0),[l,d]=s.useState(0),[u,m]=s.useState(1),[p,h]=s.useState(!1),[g,f]=s.useState(!1),[x,b]=s.useState(!1),[y,v]=s.useState(null),w=t?.type,S=t?.page,N=t?.limit,j=s.useCallback(async()=>{if(!e)return i([]),c(0),d(0),m(1),h(!1),void f(!1);b(!0),v(null);try{const s=await r.getCreditTransactions(e,{type:w,page:S,limit:N});i(s.docs||[]),c(s.totalDocs||0),d(s.totalPages||0),m(s.page||1),h(s.hasNextPage||!1),f(s.hasPrevPage||!1)}catch(s){const t=q(s,"errors.fetchCreditTransactions",a);v(t),z(s,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{b(!1)}},[r,e,w,S,N]);return s.useEffect(()=>{j()},[j]),{transactions:n,totalDocs:o,totalPages:l,page:u,hasNextPage:p,hasPrevPage:g,loading:x,error:y,refetch:j}},tt=(e,t)=>{const{t:a}=ds(),{api:r}=Us(),[n,i]=s.useState(null),[o,c]=s.useState(!1),[l,d]=s.useState(null),u=s.useCallback(async()=>{if(e){c(!0),d(null);try{const s=await r.getExpiringCredits(e,t);i(s)}catch(s){const r=q(s,"errors.fetchExpiringCredits",a);d(r),z(s,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:t}})}finally{c(!1)}}else i(null)},[r,e,t]);return s.useEffect(()=>{u()},[u]),{expiringCredits:n?.expiringCredits??0,buckets:n?.buckets??[],days:n?.days??t??7,loading:o,error:l,refetch:u}},at=()=>{const{t:e}=ds(),{os:t,api:a}=Us(),r=fe(t),[n,i]=s.useState([]),[o,c]=s.useState(),[l,d]=s.useState(!1),[u,m]=s.useState(null),p=s.useCallback(async()=>{if(r){d(!0),m(null);try{const e=await a.getPublicCreditPackages();i(e.packages||[]),c(e.notes)}catch(s){const t=q(s,"errors.fetchCreditPackages",e);m(t),z(s,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{d(!1)}}else i([])},[a,r]);s.useEffect(()=>{p()},[p]);return{packages:n,notes:o,loading:!r||l,error:u,refetch:p}},rt=s.createContext(null);rt.displayName="CreditBalanceContext";const nt=s.memo(function({children:t}){const a=Cs(e=>e.workspaces.currentWorkspace),{balance:r,loading:n,error:i,refetch:o}=Zs(a?._id);s.useEffect(()=>Js(o),[o]);const c=s.useMemo(()=>({balance:r,loading:n,error:i,refetch:o}),[r,n,i,o]);return e.jsx(rt.Provider,{value:c,children:t})});function it(){const e=s.useContext(rt);if(null===e)throw new Error("useCreditBalanceContext must be used within CreditBalanceContextProvider. Make sure CreditBalanceContextProvider is wrapping your application (included in SaaSOSProvider by default).");return e}nt.displayName="CreditBalanceContextProvider";const ot=({message:s})=>e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"bb-fs-loader-spinner",style:{width:40,height:40,border:"3px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"bb-fs-loader-spin 0.6s linear infinite"}}),e.jsx("p",{"aria-hidden":"true",style:{marginTop:16,color:"#6b7280",fontSize:14},children:s}),e.jsx("style",{children:"\n @keyframes bb-fs-loader-spin { to { transform: rotate(360deg) } }\n @media (prefers-reduced-motion: reduce) {\n .bb-fs-loader-spinner { animation: none !important; }\n }\n @media (prefers-color-scheme: dark) {\n .bb-fs-loader-spinner {\n border-color: #374151 !important;\n border-top-color: #9ca3af !important;\n }\n }\n "})]}),ct=({children:s,message:t="Loading...",backgroundColor:a})=>e.jsxs("div",{role:"status","aria-live":"polite","aria-busy":"true",className:"bb-fs-loader",style:{position:"fixed",inset:0,zIndex:2147483647,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",backgroundColor:a??void 0},children:[e.jsx("span",{style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:t}),s??e.jsx(ot,{message:t}),e.jsx("style",{children:"\n .bb-fs-loader {\n background-color: #fff;\n }\n @media (prefers-color-scheme: dark) {\n .bb-fs-loader {\n background-color: #0a0a0a;\n }\n .bb-fs-loader p {\n color: #9ca3af !important;\n }\n }\n "})]});ct.displayName="FullScreenLoader";const lt=s.createContext(null),dt=({children:t,loadingComponent:a})=>{const[r,n]=s.useState({visible:!1,message:""}),i=s.useRef(null),o=s.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null)},[]),c=s.useCallback(()=>{o(),n({visible:!1,message:""})},[o]),l=s.useCallback(e=>{o(),n({visible:!0,message:e}),i.current=setTimeout(()=>{z(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),n({visible:!1,message:""})},6e4)},[o]);s.useEffect(()=>()=>o(),[o]);const d=s.useMemo(()=>({show:l,hide:c,visible:r.visible,message:r.message}),[l,c,r.visible,r.message]),u="function"==typeof a?a({message:r.message}):a;return e.jsxs(lt.Provider,{value:d,children:[t,r.visible&&e.jsx(ct,{message:r.message,children:u})]})};function ut(){const e=s.useContext(lt);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}dt.displayName="FullScreenLoaderProvider";const mt=s.createContext({appPermissions:void 0});function pt({appPermissions:t,children:a}){const r=s.useMemo(()=>({appPermissions:t}),[t]);return e.jsx(mt.Provider,{value:r,children:a})}function ht(){return s.useContext(mt)}const gt=s.createContext(null);gt.displayName="QuotaUsageContext";const ft=s.memo(function({children:t}){const a=Cs(e=>e.workspaces.currentWorkspace),{quotas:r,loading:n,error:i,refetch:o}=Vs(a?._id);s.useEffect(()=>qe(o),[o]);const c=s.useMemo(()=>({quotas:r,loading:n,error:i,refetch:o}),[r,n,i,o]);return e.jsx(gt.Provider,{value:c,children:t})});function xt(){const e=s.useContext(gt);if(null===e)throw new Error("useQuotaUsageContext must be used within QuotaUsageContextProvider. Make sure QuotaUsageContextProvider is wrapping your application (or the tree that uses quota gates).");return e}function bt(e){if(!e||"string"!=typeof e)return null;try{const s=new URL(e);return"https:"===s.protocol?e:"http:"!==s.protocol||"localhost"!==s.hostname&&"127.0.0.1"!==s.hostname&&"::1"!==s.hostname?null:e}catch{return null}}function yt(e,s="/"){if("undefined"==typeof window||!window.location)return!1;const t=bt(e);return window.location.href=t??s,!0}ft.displayName="QuotaUsageContextProvider";const vt="saas-auth-intent";function wt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function St(e){bt(e)&&function(e,s){try{ms(e,JSON.stringify(s))}catch(s){z(s,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}(vt,{returnUrl:e,createdAt:Date.now()})}function Nt(){const e=function(e,s){const t=us(e);if(!t)return null;try{const a=JSON.parse(t);return s&&!s(a)?(z(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),ps(e),null):a}catch(s){return z(s,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),ps(e),null}}(vt,wt);return ps(vt),e?Date.now()-e.createdAt>6e5?null:bt(e.returnUrl):null}const jt="saas-oauth-state";function kt(){ps(jt)}class Ct extends Ns{constructor(e){super(e)}async requestAuth(e){const s=`${this.serverUrl}/api/${this.version}/auth/request`,t=await this.fetchAbsoluteUrl(s,{method:"POST",body:JSON.stringify(e)});return t.ok||await this.throwResponseError(t,"Failed to initiate authentication"),t.json()}async getProfile(e,s){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:s},"Failed to fetch user profile")}}const At="bb",Tt="checkout",Et="billing",Pt="selectPlan",It="creditPurchase",Ut="openCreditStore",Rt="success",Mt="cancel",Dt="error",Wt="subscription",Ft="credits";function _t(e,s){let t;try{const e=s||("undefined"!=typeof window?window.location.href:"https://localhost");t=new URL(e),t.search=""}catch{t=new URL("https://localhost")}return t.searchParams.set(At,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,s])=>`${encodeURIComponent(e)}:${encodeURIComponent(s)}`).join(",")}(e)),t.toString()}function Ot(e,s){const t="undefined"!=typeof window?window.location.href:void 0;return{successUrl:_t({action:It,status:Rt,ws:e,screen:Ft},t),cancelUrl:_t({action:It,status:Mt,ws:e,screen:Ft},t)}}function Lt(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(At);if(!e)return null;const s=function(e){const s={};if(!e)return s;const t=e.split(",");for(const e of t){const t=e.indexOf(":");if(-1===t)continue;const a=decodeURIComponent(e.slice(0,t)),r=decodeURIComponent(e.slice(t+1));a&&(s[a]=r)}return s}(e);return Object.keys(s).length>0?s:null}catch{return null}}function Bt(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(At)&&(e.searchParams.delete(At),window.history.replaceState({},"",e.toString()))}catch{}}const Gt={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},Kt="active",Vt="trialing",zt="canceled",$t="past_due",qt="paused",Ht="draft",Jt="open",Yt="paid",Zt="uncollectible",Qt="void",Xt={Feature:"feature",Limit:"limit",Quota:"quota"},ea="none",sa="final",ta="suspended",aa="plan_grant",ra="pack_purchased",na="consumed",ia="expired",oa="admin_grant",ca="admin_revoke",la="refund";function da(e,s){const t=e.pricingVariants;if(!t?.length)return null;const a=s.toLowerCase();return t.find(e=>e.currency?.toLowerCase()===a)??null}function ua(e,s,t){const a=da(e,s);if(!a?.basePricing)return null;const r=a.basePricing[t];return null!=r?r:null}function ma(e,s,t,a){const r=da(e,s),n=r?.quotaOverages?.[t];if(n)return n[a]}function pa(e,s,t,a){const r=e.quotas?.[t];if(null==r)return null;const n=r[a];if(!n)return null;const i=ma(e,s,t,a);return{included:n.included,...void 0!==n.unitSize&&{unitSize:n.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==r.allowOverage}}function ha(e,s){if(!e)return null;for(const t of s){const s=t.pricingVariants;if(s?.length)for(const t of s){const s=t.stripePrices;if(s){if(s.monthlyPriceId===e||s.monthly===e)return{interval:"monthly",currency:t.currency};if(s.yearlyPriceId===e||s.yearly===e)return{interval:"yearly",currency:t.currency};if(s.quarterlyPriceId===e)return{interval:"quarterly",currency:t.currency}}}}return null}function ga(e,s){const t=da(e,s);return t?.seatPricing?.enabled?t.seatPricing:null}function fa(e,s,t){const a=ga(e,s);return a?.perSeat?a.perSeat[t]??null:null}function xa(e){const{planVersion:s,currency:t="usd",settingsMaxUsers:a}=e;if(s){const e=ga(s,t);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=a&&a>0?{maxUsers:a,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function ba(e){const{memberCount:s,maxUsersConfig:t,hasSubscription:a=!0,requireSubscription:r=!1}=e;if(r&&!a)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:n,source:i}=t;if(n<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(s>=n){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:n}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const ya="user:created",va="user:updated",wa="workspace:changed",Sa="workspace:updated",Na="workspace:user-added",ja="workspace:user-removed",ka="workspace:user-role-changed",Ca="workspace:created",Aa="workspace:deleted";const Ta=new class{constructor(){this.callbacks=null}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,s){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,s)}catch(s){z(s,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(ya,{user:e})}async emitUserUpdated(e,s){await this.emit(va,{user:e,previousUser:s})}async emitWorkspaceChanged(e,s){await this.emit(wa,{workspace:e,previousWorkspace:s})}async emitWorkspaceUpdated(e){await this.emit(Sa,{workspace:e})}async emitWorkspaceUserAdded(e,s,t){await this.emit(Na,{userId:e,workspace:s,role:t})}async emitWorkspaceUserRemoved(e,s,t){await this.emit(ja,{userId:e,workspace:s,role:t})}async emitWorkspaceUserRoleChanged(e,s,t,a){await this.emit(ka,{userId:e,workspace:s,previousRole:t,newRole:a})}async emitWorkspaceCreated(e){await this.emit(Ca,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(Aa,{workspace:e})}},Ea=o.cva("inline-flex items-center justify-center rounded-full font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"underline-offset-4 hover:underline text-primary"},withIcon:{true:"flex"},fullWidth:{true:"w-full"},size:{default:"h-9 py-2 px-4 text-sm",sm:"h-8 px-3 text-xs",lg:"h-10 px-6 text-base",icon:"h-9 w-9"}},compoundVariants:[{size:"lg",withIcon:!0,className:"gap-x-1.5"},{size:"default",withIcon:!0,className:"gap-x-1"},{size:"sm",withIcon:!0,className:"gap-x-0.5"}],defaultVariants:{variant:"default",size:"default"}}),Pa=j.forwardRef(({className:s,variant:t,progress:a,size:r,startIcon:o,endIcon:c,asChild:l=!1,...d},u)=>{const m=l?i.Slot:"button",p=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(r);return e.jsxs(m,{disabled:a||d.disabled,className:W(Ea({variant:t,size:r,withIcon:null!=a||null!=o||null!=c,className:s})),ref:u,...d,children:[a&&e.jsx(n.Loader2,{size:p,className:"animate-spin"}),o&&j.cloneElement(o,{size:p}),d.children,c&&j.cloneElement(c,{size:p})]})});Pa.displayName="Button";const Ia=s.createContext({container:null,setContainer:()=>{}}),Ua=s.memo(({children:t})=>{const[a,r]=s.useState(null),n=s.useMemo(()=>({container:a,setContainer:r}),[a]);return e.jsxs(Ia.Provider,{value:n,children:[t,e.jsx("div",{ref:r,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});Ua.displayName="PortalProvider";const Ra=k.Root,Ma=k.Trigger,Da=k.Portal,Wa=j.forwardRef(({className:s,...t},a)=>e.jsx(k.Overlay,{ref:a,className:W("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...t}));Wa.displayName=k.Overlay.displayName;const Fa=j.forwardRef(({className:s,children:t,...a},r)=>{const{container:n}=j.useContext(Ia);return e.jsxs(Da,{container:n,children:[e.jsx(Wa,{}),e.jsxs(k.Content,{ref:r,className:W("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",s),...a,children:[t,e.jsxs(k.Close,{className:"absolute right-4 rtl:right-auto rtl:left-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(l.Cross2Icon,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});Fa.displayName=k.Content.displayName;const _a=({className:s,...t})=>e.jsx("div",{className:W("flex flex-col space-y-1.5 text-center sm:text-start",s),...t});_a.displayName="DialogHeader";const Oa=j.forwardRef(({className:s,...t},a)=>e.jsx(k.Title,{ref:a,className:W("text-lg font-semibold leading-none tracking-tight",s),...t}));Oa.displayName=k.Title.displayName;const La=j.forwardRef(({className:s,...t},a)=>e.jsx(k.Description,{ref:a,className:W("text-sm text-muted-foreground",s),...t}));La.displayName=k.Description.displayName;const Ba="saas-workspace-current",Ga=e=>{e?ms(Ba,e._id):ps(Ba)},Ka=()=>us(Ba),Va=()=>{ps(Ba)},za=(e,s)=>!!e&&s.some(s=>s._id===e);function $a(e,s){if(!s)return!1;const t=(a=e.createdBy)?"string"==typeof a?a:"object"==typeof a&&"_id"in a&&"string"==typeof a._id?a._id:null:null;var a;return null!==t&&t===s}function qa(e,s){if(!s||!e.users||!Array.isArray(e.users))return null;const t=e.users.find(e=>"string"==typeof e?e===s:"object"==typeof e&&null!==e&&"_id"in e&&e._id===s);return t&&"object"==typeof t&&"role"in t&&"string"==typeof t.role?t.role:null}const Ha={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view"},Ja=Object.values(Ha),Ya={admin:Ja.filter(e=>e!==Ha.WORKSPACE_DELETE),member:[Ha.WORKSPACE_SETTINGS_VIEW,Ha.WORKSPACE_MEMBERS_VIEW,Ha.WORKSPACE_FEATURES_VIEW,Ha.WORKSPACE_BILLING_VIEW,Ha.WORKSPACE_USAGE_VIEW],viewer:[Ha.WORKSPACE_SETTINGS_VIEW,Ha.WORKSPACE_MEMBERS_VIEW]};function Za(e){const s=new Set;for(const t of Object.values(e))for(const e of t)s.add(e);return Array.from(s)}function Qa(e){const{userId:s,workspace:t,settings:a,appPermissions:r}=e;if(!t||!s)return new Set;if($a(t,s)){const e=new Set(Ja);if(r)for(const s of Za(r))e.add(s);if(t.permissions)for(const s of Za(t.permissions))e.add(s);if(a?.workspace?.permissions)for(const s of Za(a.workspace.permissions))e.add(s);return e}const n=e.workspaceRole??qa(t,s);if(!n)return new Set;const i=t.permissions,o=a?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),d=i?.[n]?c(i[n]):[],u=o?.[n]?c(o[n]):[],m=Ya[n]??[];let p;if(d.length>0)p=d;else if(u.length>0)p=u;else if(m.length>0)p=m;else{p=Ya[a?.workspace?.defaultRole??"member"]??Ya.member??[]}const h=new Set(p),g=i?.[n]?l(i[n]):[],f=r?.[n]?l(r[n]):[],x=g.length>0?g:f;for(const e of x)h.add(e);return function(e,s,t){if(!t?.workspace)return;const{canInviteMembers:a}=t.workspace;(!1===a||"admin-only"===a&&"admin"!==s)&&e.delete(Ha.WORKSPACE_MEMBERS_INVITE)}(h,n,a),h}function Xa(e){const{user:t}=xi(),{currentWorkspace:a}=pi(),{settings:r}=Is(),{appPermissions:n}=ht(),i=e??a??null,o=t?.id??null,c=s.useMemo(()=>i?qa(i,o):null,[i,o]),l=s.useMemo(()=>!!i&&$a(i,o),[i,o]),d=s.useMemo(()=>Qa({userId:o,workspaceRole:c,workspace:i,settings:r,appPermissions:n}),[o,c,i,r,n]);return{can:s.useCallback(e=>Array.isArray(e)?e.every(e=>d.has(e)):d.has(e),[d]),permissions:d,isOwner:l,role:c}}const er={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},sr={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function tr(e){return e&&e.trim()?sr[e.trim().toLowerCase()]??"":""}function ar(e){if(!e||!e.trim())return"";const s=e.trim().toLowerCase();return er[s]??s.toUpperCase()}["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"].map(e=>({value:e,label:`${e.toUpperCase()} (${ar(e)})`}));const rr=({open:t,onOpenChange:a,packages:r,billingCurrency:i,workspaceName:o,onSelectPackage:c,purchasingPackageId:l,loading:d=!1})=>{const{t:u,dir:m,fmtNum:p,fmtCents:h}=ds(),g=s.useMemo(()=>{const e=new Set;return r.forEach(s=>{s.pricingVariants?.forEach(s=>{s.currency&&e.add(s.currency.toLowerCase())})}),Array.from(e)},[r]),f=s.useMemo(()=>{const e=i?.trim().toLowerCase();return e?g.includes(e)?[e]:[]:g},[i,g]),[x,b]=s.useState(()=>f.length>0?f[0]:""),y=i?.trim().toLowerCase()||x,v=d||!!l;return e.jsx(Ra,{open:t,onOpenChange:a,children:e.jsxs(Fa,{dir:m,className:"inset-0 w-screen h-screen max-w-none rounded-none translate-x-0 translate-y-0 p-0 flex flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 px-4 py-4 sm:px-6 sm:py-6 border-b space-y-3 sm:space-y-4",children:[e.jsxs("div",{children:[e.jsx(Oa,{className:"text-xl sm:text-2xl font-bold",children:u("credits.dialogTitle")}),e.jsxs(La,{className:"mt-1 text-sm",children:[u("credits.dialogDescription"),o&&e.jsx("span",{className:"ms-1 font-medium text-foreground",children:u("credits.dialogDescriptionWorkspace",{workspace:o})})]})]}),!i?.trim()&&f.length>1&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-slate-600",children:u("pricing.currency")}),e.jsx("div",{className:"flex gap-1 rounded-lg border border-gray-200 bg-gray-50/50 p-1",children:f.map(s=>e.jsxs("button",{type:"button",onClick:()=>b(s),className:W("rounded-md px-3 py-1.5 text-sm font-medium transition-colors",y===s?"bg-white text-gray-900 shadow-sm":"text-gray-500 hover:text-gray-700"),children:[ar(s)," ",s.toUpperCase()]},s))})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:0===r.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-gray-400",children:[e.jsx(n.Coins,{className:"h-12 w-12 mb-3"}),e.jsx("p",{className:"text-sm",children:u("credits.noPackages")})]}):e.jsx("div",{className:"max-w-2xl mx-auto px-4 py-6 sm:px-6 space-y-4",children:r.map(s=>{const t=s.pricingVariants?.find(e=>e.currency?.toLowerCase()===y)??s.pricingVariants?.[0],a=t?.amount,r=t?.currency??y,i=l===s._id,o=null!=a&&a>0&&s.creditAmount>0?Math.round(a/s.creditAmount):null;return e.jsxs("div",{className:W("rounded-xl border p-5 sm:p-6 flex flex-col sm:flex-row sm:items-center gap-4 transition-all",i?"border-primary bg-primary/5 shadow-md":"border-gray-200 hover:border-gray-300 hover:shadow-sm"),children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:s.name}),e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-blue-50 px-2.5 py-0.5 text-xs font-medium text-blue-700",children:[e.jsx(n.Coins,{className:"h-3 w-3"}),u("credits.creditsAmount",{count:p(s.creditAmount)})]})]}),s.description&&e.jsx("p",{className:"text-sm text-gray-500 mb-2",children:s.description}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-400",children:[e.jsx("span",{children:s.validityDays?u("credits.validityDays",{count:s.validityDays}):u("credits.validityUnlimited")}),null!=o&&e.jsx("span",{children:u("credits.perCredit",{price:h(o,r)})})]})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:flex-col sm:items-end sm:gap-2 shrink-0",children:[null!=a&&e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-gray-900 whitespace-nowrap",children:h(a,r)}),e.jsx(Pa,{size:"sm",onClick:()=>c(s),disabled:v,progress:i,className:"whitespace-nowrap",children:i?u("credits.purchasing"):u("credits.buyAmount",{count:p(s.creditAmount)})})]})]},s._id)})})})]})})},nr=({titleKey:s,descriptionKey:t})=>{const{t:a}=ds();return e.jsx("div",{className:"border border-amber-200 bg-amber-50 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(n.ShieldAlert,{className:"h-5 w-5 text-amber-600 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-amber-800",children:a(s??"settings.common.noPermissionTitle")}),e.jsx("p",{className:"text-xs text-amber-700 mt-1",children:a(t??"settings.common.noPermissionDescription")})]})]})})};function ir({className:s,...t}){return e.jsx("div",{className:W("animate-pulse rounded-md bg-primary/10",s),...t})}function or(){return e.jsxs("div",{className:"space-y-3.5",children:[e.jsx(ir,{className:"h-10 w-full"}),e.jsx(ir,{className:"h-10 w-full"}),e.jsx(ir,{className:"h-10 w-full"})]})}function cr(e,s="en-US",t){try{const a=new Date(e);return isNaN(a.getTime())?"":new Intl.DateTimeFormat(s,t??{month:"short",day:"numeric",year:"numeric"}).format(a)}catch{return""}}function lr(e,s="en-US"){return cr(e,s,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function dr(e,s="en-US"){return e?new Date(1e3*e).toLocaleDateString(s,{year:"numeric",month:"short",day:"numeric"}):""}const ur={[aa]:"credits.type.plan_grant",[ra]:"credits.type.pack_purchased",[na]:"credits.type.consumed",[ia]:"credits.type.expired",[oa]:"credits.type.admin_grant",[ca]:"credits.type.admin_revoke",[la]:"credits.type.refund"};const mr=({workspace:t})=>{const a=t._id?.toString(),{t:r,fmtNum:i}=ds(),{can:o}=Xa(),c=o(Ha.WORKSPACE_BILLING_VIEW),l=o(Ha.WORKSPACE_BILLING_MANAGE),{balance:d,loading:u,error:m,refetch:p}=it(),{packages:h,loading:g}=et(a),{expiringCredits:f,loading:x}=tt(a,7),[b,y]=s.useState(1),{transactions:v,hasNextPage:w,loading:S}=st(a,{limit:10,page:b}),[N,j]=s.useState([]);s.useEffect(()=>{S||0===v.length||j(1===b?v:e=>{const s=new Set(e.map(e=>e._id)),t=v.filter(e=>!s.has(e._id));return t.length>0?[...e,...t]:e})},[v,b,S]);const k=s.useCallback(()=>{w&&!S&&y(e=>e+1)},[w,S]),C=N,{purchaseCredits:A,loading:T}=Xs(a),[E,P]=s.useState(!1),[I,U]=s.useState(null),[R,M]=s.useState(!1),[D,F]=s.useState(!1),[_,O]=s.useState(null),[L,B]=s.useState(!1),G=s.useRef(!1),K=u&&!d;s.useEffect(()=>{if(G.current)return;const e=mi.getState();if(!e.params?.action)return;if(e.params.action===Ut)return G.current=!0,mi.clearParams(),void B(!0);if(e.params.action!==It)return;G.current=!0;const s=e.params.status;if(mi.clearParams(),s===Rt){M(!0),Ys();const e=setTimeout(()=>M(!1),8e3);return()=>clearTimeout(e)}if(s===Mt){F(!0);const e=setTimeout(()=>F(!1),5e3);return()=>clearTimeout(e)}s===Dt&&U(r("credits.purchaseFailed"))},[]);if(K)return e.jsx(or,{});if(!c)return e.jsx(nr,{});if(!a)return e.jsx("div",{className:"border rounded-lg p-4 text-center text-gray-500",children:e.jsx("p",{children:r("subscription.invalidWorkspace")})});const V=!g&&h.length>0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-gray-600",children:r("credits.description")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[V&&l&&e.jsxs(Pa,{size:"sm",onClick:()=>B(!0),children:[e.jsx(n.ShoppingCart,{className:"h-3.5 w-3.5 me-1.5"}),r("credits.buyCredits")]}),e.jsxs(Pa,{variant:"ghost",size:"sm",onClick:async()=>{P(!0);try{await p()}finally{P(!1)}},disabled:E,children:[e.jsx(n.RefreshCw,{className:W("h-3.5 w-3.5 me-1.5",E&&"animate-spin")}),r("settings.common.refreshAction",{loading:String(E)})]})]})]}),m&&e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg",children:[e.jsx("p",{className:"font-medium",children:r("credits.errorLoading")}),e.jsx("p",{className:"text-sm mt-1",children:m})]}),R&&e.jsxs("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CheckCircle2,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium",children:r("credits.purchaseSuccess")})]}),e.jsx(Pa,{variant:"outline",size:"sm",onClick:()=>M(!1),className:"flex-shrink-0 border-green-200 text-green-700 hover:bg-green-100",children:r("settings.common.dismiss")})]}),D&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 text-amber-700 px-4 py-3 rounded-lg flex items-start justify-between gap-4",children:[e.jsx("p",{className:"text-sm font-medium",children:r("credits.purchaseCanceled")}),e.jsx(Pa,{variant:"outline",size:"sm",onClick:()=>F(!1),className:"flex-shrink-0 border-amber-200 text-amber-700 hover:bg-amber-100",children:r("settings.common.dismiss")})]}),I&&e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg flex items-start justify-between gap-4",children:[e.jsx("p",{className:"text-sm",children:I}),e.jsx(Pa,{variant:"outline",size:"sm",onClick:()=>U(null),className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:r("settings.common.dismiss")})]}),e.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"bg-gray-50/50 p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wider",children:r("credits.balance")}),e.jsx(n.Coins,{className:"h-5 w-5 text-gray-400"})]}),d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900 mb-4",children:i(d.available)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:r("credits.totalGranted")}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:i(d.totalGranted)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:r("credits.totalConsumed")}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:i(d.totalConsumed)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:r("credits.totalExpired")}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:i(d.totalExpired)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:r("credits.available")}),e.jsx("p",{className:"text-sm font-semibold text-green-600",children:i(d.available)})]})]})]}):e.jsxs("div",{className:"text-center py-4",children:[e.jsx(n.Coins,{className:"h-10 w-10 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:r("credits.noCredits")}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:r("credits.noCreditsHint")}),V&&l&&e.jsxs(Pa,{size:"sm",className:"mt-3",onClick:()=>B(!0),children:[e.jsx(n.ShoppingCart,{className:"h-3.5 w-3.5 me-1.5"}),r("credits.buyCredits")]})]})]}),!x&&f>0&&e.jsx("div",{className:"px-4 py-3 bg-amber-50 border-t border-amber-200 text-sm text-amber-800",children:r("credits.expiringInDays",{count:f,days:7})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 mb-3",children:r("credits.transactions")}),S&&0===C.length?e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-600",children:[e.jsx(n.Loader2,{className:"h-4 w-4 animate-spin flex-shrink-0"}),e.jsx("span",{children:r("settings.common.loading")})]}):0===C.length?e.jsx("div",{className:"border rounded-lg p-6 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:r("credits.noTransactions")})}):e.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[e.jsx("div",{className:"divide-y divide-gray-100",children:C.map(s=>e.jsx(pr,{tx:s},s._id))}),w&&e.jsx("div",{className:"border-t border-gray-200 px-4 py-3 text-center",children:e.jsx(Pa,{variant:"ghost",size:"sm",onClick:k,disabled:S,progress:S&&b>1,children:r("credits.loadMore")})})]})]}),V&&l&&e.jsx(rr,{open:L,onOpenChange:B,packages:h,billingCurrency:t.billingCurrency,workspaceName:t.name,onSelectPackage:async e=>{if(a){U(null),O(e._id);try{const{successUrl:s,cancelUrl:t}=Ot(a),r=await A({creditPackageId:e._id,successUrl:s,cancelUrl:t});r.url&&yt(r.url)}catch(e){U(e instanceof Error?e.message:r("errors.purchaseCredits")),O(null)}}},purchasingPackageId:_,loading:T})]})};function pr({tx:s}){const{t:t,formattingLocale:a,fmtNum:r}=ds(),n=ur[s.type]??"credits.type.consumed",i=function(e){switch(e){case"plan_grant":case"admin_grant":case"refund":return"bg-green-100 text-green-800";case"pack_purchased":return"bg-blue-100 text-blue-800";case"consumed":default:return"bg-gray-100 text-gray-800";case"expired":case"admin_revoke":return"bg-red-100 text-red-800"}}(s.type),o=s.amount>0;return e.jsx("div",{className:"px-3 py-3 sm:px-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-0.5",children:[e.jsx("span",{className:W("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium shrink-0",i),children:t(n)}),s.description&&e.jsx("p",{className:"text-sm text-gray-700 truncate",children:s.description})]}),e.jsx("p",{className:"text-xs text-gray-400",children:lr(s.createdAt,a)})]}),e.jsxs("div",{className:"text-end shrink-0",children:[e.jsxs("span",{className:W("text-sm font-semibold",o?"text-green-600":"text-gray-900"),children:[o?"+":"",r(s.amount)]}),e.jsx("p",{className:"text-xs text-gray-400",children:r(s.balanceAfter)})]})]})})}const hr=C.Root,gr=C.Trigger,fr=C.Portal,xr=j.forwardRef(({className:s,...t},a)=>e.jsx(C.Overlay,{className:W("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...t,ref:a}));xr.displayName=C.Overlay.displayName;const br=j.forwardRef(({className:s,...t},a)=>{const{container:r}=j.useContext(Ia);return e.jsxs(fr,{container:r,children:[e.jsx(xr,{}),e.jsx(C.Content,{ref:a,className:W("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",s),...t})]})});br.displayName=C.Content.displayName;const yr=({className:s,...t})=>e.jsx("div",{className:W("flex flex-col space-y-2 text-center sm:text-start",s),...t});yr.displayName="AlertDialogHeader";const vr=({className:s,...t})=>e.jsx("div",{className:W("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});vr.displayName="AlertDialogFooter";const wr=j.forwardRef(({className:s,...t},a)=>e.jsx(C.Title,{ref:a,className:W("text-lg font-semibold",s),...t}));wr.displayName=C.Title.displayName;const Sr=j.forwardRef(({className:s,...t},a)=>e.jsx(C.Description,{ref:a,className:W("text-sm text-muted-foreground",s),...t}));Sr.displayName=C.Description.displayName;const Nr=j.forwardRef(({className:s,...t},a)=>e.jsx(C.Action,{ref:a,className:W(Ea(),s),...t}));Nr.displayName=C.Action.displayName;const jr=j.forwardRef(({className:s,...t},a)=>e.jsx(C.Cancel,{ref:a,className:W(Ea({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));jr.displayName=C.Cancel.displayName;const kr=({workspace:t})=>{const[a,r]=s.useState(!1),{deleteWorkspace:i}=pi(),{can:o}=Xa(),{settings:c}=Is(),{t:l}=ds();if(1===(c?.workspace?.maxWorkspacesPerUser??0))return null;if(!t)return e.jsx(or,{});return o(Ha.WORKSPACE_DELETE)?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-destructive",children:l("danger.title")}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:l("danger.deleteDescription")})]}),e.jsxs(hr,{children:[e.jsx(gr,{asChild:!0,children:e.jsxs(Pa,{variant:"destructive",disabled:a,progress:a,children:[e.jsx(n.Trash2,{className:"h-4 w-4 me-2"}),l("danger.deleteWorkspace")]})}),e.jsxs(br,{children:[e.jsxs(yr,{children:[e.jsx(wr,{children:l("danger.deleteConfirm")}),e.jsx(Sr,{children:l("danger.deleteConfirmDescription")})]}),e.jsxs(vr,{children:[e.jsx(jr,{disabled:a,children:l("settings.common.cancel")}),e.jsx(Nr,{onClick:async()=>{r(!0);try{await i(t._id)}catch(e){z(e,{component:"WorkspaceSettingsDanger",action:"handleDeleteWorkspace",metadata:{workspaceId:t._id}}),alert(e instanceof Error?e.message:l("danger.failedToDelete"))}finally{r(!1)}},disabled:a,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:a?e.jsxs(e.Fragment,{children:[e.jsx(n.Loader2,{className:"me-2 h-4 w-4 animate-spin"}),l("danger.deleting")]}):l("danger.deleteWorkspace")})]})]})]})]}):e.jsx(nr,{descriptionKey:"danger.adminOnly"})},Cr=j.forwardRef(({className:s,...t},a)=>e.jsx(A.Root,{className:W("peer inline-flex h-[20px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",s),...t,ref:a,children:e.jsx(A.Thumb,{className:W("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));function Ar(e=5e3){const[t,a]=s.useState(null),r=s.useRef(null);s.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);return{message:t,show:s.useCallback(s=>{a(s),r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{a(null)},e)},[e]),clear:s.useCallback(()=>{a(null),r.current&&clearTimeout(r.current)},[])}}Cr.displayName=A.Root.displayName;const Tr=({workspaceId:t})=>{const{t:a}=ds(),{allFeatures:r,updateFeature:i,getWorkspace:o}=pi(),{can:c}=Xa(),[l,d]=s.useState({}),u=Ar(),[m,p]=s.useState(null);if(s.useEffect(()=>{o(t).then(p)},[t]),!m)return e.jsx(or,{});const h=c(Ha.WORKSPACE_FEATURES_EDIT);return e.jsxs("div",{children:[u.message&&e.jsxs("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-4",children:[e.jsx("p",{className:"font-medium",children:a("settings.common.success")}),e.jsx("p",{className:"text-sm",children:u.message})]}),e.jsxs("div",{className:"flex flex-col gap-y-3.5 pe-4",children:[!h&&e.jsx(nr,{descriptionKey:"features.ownerOnly"}),!r.length&&e.jsx("div",{className:"text-muted-foreground",children:a("features.noFeatures")}),r.length>0&&e.jsx("div",{className:"flex flex-col gap-y-3.5",children:r.map(s=>{const t=m?.features?.[s.slug],o=null!==l[s.slug]&&void 0!==l[s.slug],c=l[s.slug],g=a("features.actionStatus",{action:!0===c?"enabling":!1===c?"disabling":"none"});return e.jsxs("div",{className:"flex items-center gap-x-2 justify-between w-full",children:[e.jsxs("div",{className:"flex gap-x-2 flex-col",children:[e.jsx("h3",{className:"font-medium text-ellipsis",children:s.name}),e.jsx("p",{className:"text-muted-foreground",children:s.description})]}),o?e.jsxs("div",{className:"flex items-center gap-x-1",children:[e.jsx(n.Loader2,{className:"h-4 w-4 animate-spin text-gray-500"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[g,"..."]})]}):e.jsx(Cr,{disabled:!h,checked:t??s.defaultValue,onCheckedChange:e=>async function(e,s){if(m){d(t=>({...t,[e]:s})),u.clear();try{const t=await i(m._id,e,s);p(t);const n=r.find(s=>s.slug===e),o=n?.name||"Feature";u.show(a("features.updateSuccess",{feature:o,enabled:String(s)}))}catch(s){z(s,{component:"WorkspaceSettingsFeatures",action:"updateFeature",metadata:{workspaceId:m._id,featureKey:e}})}finally{d(s=>({...s,[e]:null}))}}}(s.slug,e)})]},s._id)})})]})]})},Er=(e,s,t)=>{if(e&&"reportValidity"in e){const a=m.get(t,s);e.setCustomValidity(a&&a.message||""),e.reportValidity()}},Pr=(e,s)=>{for(const t in s.fields){const a=s.fields[t];a&&a.ref&&"reportValidity"in a.ref?Er(a.ref,t,e):a&&a.refs&&a.refs.forEach(s=>Er(s,t,e))}},Ir=(e,s)=>{s.shouldUseNativeValidation&&Pr(e,s);const t={};for(const a in e){const r=m.get(s.fields,a),n=Object.assign(e[a]||{},{ref:r&&r.ref});if(Ur(s.names||Object.keys(e),a)){const e=Object.assign({},m.get(t,a));m.set(e,"root",n),m.set(t,a,e)}else m.set(t,a,n)}return t},Ur=(e,s)=>{const t=Rr(s);return e.some(e=>Rr(e).match(`^${t}\\.\\d+`))};function Rr(e){return e.replace(/\]|\[/g,"")}function Mr(e,s){try{var t=e()}catch(e){return s(e)}return t&&t.then?t.then(void 0,s):t}function Dr(e,s){for(var t={};e.length;){var a=e[0],r=a.code,n=a.message,i=a.path.join(".");if(!t[i])if("unionErrors"in a){var o=a.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:n,type:r};if("unionErrors"in a&&a.unionErrors.forEach(function(s){return s.errors.forEach(function(s){return e.push(s)})}),s){var c=t[i].types,l=c&&c[a.code];t[i]=m.appendErrors(i,s,t,r,l?[].concat(l,a.message):a.message)}e.shift()}return t}function Wr(e,s){for(var t={};e.length;){var a=e[0],r=a.code,n=a.message,i=a.path.join(".");if(!t[i])if("invalid_union"===a.code&&a.errors.length>0){var o=a.errors[0][0];t[i]={message:o.message,type:o.code}}else t[i]={message:n,type:r};if("invalid_union"===a.code&&a.errors.forEach(function(s){return s.forEach(function(s){return e.push(s)})}),s){var c=t[i].types,l=c&&c[a.code];t[i]=m.appendErrors(i,s,t,r,l?[].concat(l,a.message):a.message)}e.shift()}return t}function Fr(e,s,t){if(void 0===t&&(t={}),function(e){return"_def"in e&&"object"==typeof e._def&&"typeName"in e._def}(e))return function(a,r,n){try{return Promise.resolve(Mr(function(){return Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](a,s)).then(function(e){return n.shouldUseNativeValidation&&Pr({},n),{errors:{},values:t.raw?Object.assign({},a):e}})},function(e){if(function(e){return Array.isArray(null==e?void 0:e.issues)}(e))return{values:{},errors:Ir(Dr(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(e){return Promise.reject(e)}};if(function(e){return"_zod"in e&&"object"==typeof e._zod}(e))return function(a,r,n){try{return Promise.resolve(Mr(function(){return Promise.resolve(("sync"===t.mode?T.parse:T.parseAsync)(e,a,s)).then(function(e){return n.shouldUseNativeValidation&&Pr({},n),{errors:{},values:t.raw?Object.assign({},a):e}})},function(e){if(function(e){return e instanceof T.$ZodError}(e))return{values:{},errors:Ir(Wr(e.issues,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(e){return Promise.reject(e)}};throw new Error("Invalid input: not a Zod schema")}const _r=o.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Or=j.forwardRef(({className:s,...t},a)=>e.jsx(E.Root,{ref:a,className:W(_r(),s),...t}));Or.displayName=E.Root.displayName;const Lr=m.FormProvider,Br=j.createContext({}),Gr=({...s})=>e.jsx(Br.Provider,{value:{name:s.name},children:e.jsx(m.Controller,{...s})}),Kr=()=>{const e=j.useContext(Br),s=j.useContext(Vr),{getFieldState:t,formState:a}=m.useFormContext(),r=t(e.name,a);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=s;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},Vr=j.createContext({}),zr=j.forwardRef(({className:s,...t},a)=>{const r=j.useId();return e.jsx(Vr.Provider,{value:{id:r},children:e.jsx("div",{ref:a,className:W("space-y-2",s),...t})})});zr.displayName="FormItem";const $r=j.forwardRef(({className:s,...t},a)=>{const{error:r,formItemId:n}=Kr();return e.jsx(Or,{ref:a,className:W(r&&"text-destructive",s),htmlFor:n,...t})});$r.displayName="FormLabel";const qr=j.forwardRef(({...s},t)=>{const{error:a,formItemId:r,formDescriptionId:n,formMessageId:o}=Kr();return e.jsx(i.Slot,{ref:t,id:r,"aria-describedby":a?`${n} ${o}`:`${n}`,"aria-invalid":!!a,...s})});qr.displayName="FormControl";const Hr=j.forwardRef(({className:s,...t},a)=>{const{formDescriptionId:r}=Kr();return e.jsx("p",{ref:a,id:r,className:W("text-sm text-muted-foreground",s),...t})});Hr.displayName="FormDescription";const Jr=j.forwardRef(({className:s,children:t,...a},r)=>{const{error:n,formMessageId:i}=Kr(),o=n?String(n?.message):t;return o?e.jsx("p",{ref:r,id:i,className:W("text-sm font-medium text-destructive",s),...a,children:o}):null});Jr.displayName="FormMessage";const Yr=j.forwardRef(({className:s,type:t,...a},r)=>e.jsx("input",{type:t,className:W("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",s),ref:r,...a}));Yr.displayName="Input";const Zr=j.forwardRef(({className:s,...t},a)=>e.jsx(P.Root,{className:W("grid gap-2",s),...t,ref:a}));Zr.displayName=P.Root.displayName;const Qr=j.forwardRef(({className:s,...t},a)=>e.jsx(P.Item,{ref:a,className:W("aspect-square h-4 w-4 rounded-full border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",s),...t,children:e.jsx(P.Indicator,{className:"flex items-center justify-center",children:e.jsx(l.CheckIcon,{className:"h-3.5 w-3.5 fill-primary"})})}));Qr.displayName=P.Item.displayName;const Xr=j.forwardRef(({className:s,children:t,...a},r)=>e.jsxs(I.Root,{ref:r,className:W("relative overflow-hidden",s),...a,children:[e.jsx(I.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(en,{}),e.jsx(I.Corner,{})]}));Xr.displayName=I.Root.displayName;const en=j.forwardRef(({className:s,orientation:t="vertical",...a},r)=>e.jsx(I.ScrollAreaScrollbar,{ref:r,orientation:t,className:W("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 border-t border-t-transparent p-[1px]",s),...a,children:e.jsx(I.ScrollAreaThumb,{className:W("relative rounded-full bg-border","vertical"===t&&"flex-1")})}));function sn(e){return`data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text x="50%" y="50%" dominant-baseline="middle" alignment-baseline="middle" text-anchor="middle" font-size="50" font-family="sans-serif">${e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}</text></svg>`}en.displayName=I.ScrollAreaScrollbar.displayName;const tn=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑‍💻","👨‍💻","👩‍💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨‍💼","👩‍💼","👨‍🏫","👩‍🏫","👨‍🔬","👩‍🔬","👨‍🎨","👩‍🎨","👨‍🔧","👩‍🔧","👨‍🚀","👩‍🚀","👨‍⚖️","👩‍⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️‍🌈","🎟️","🎫"],an=({workspace:t})=>{const{t:a}=ds(),{updateWorkspace:r}=pi(),{can:i}=Xa(),[o,c]=s.useState(!1),[l,d]=s.useState("emoji"),[u,p]=s.useState(),g=Ar(),f=h.z.object({name:h.z.string().min(2,{message:a("general.nameMinLength")}),image:h.z.string().optional()}),x=m.useForm({resolver:Fr(f),defaultValues:{name:t.name||"",image:t.image||""}});if(!t)return e.jsx(or,{});const b=i(Ha.WORKSPACE_SETTINGS_EDIT);return e.jsxs("div",{children:[g.message&&e.jsxs("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-4",children:[e.jsx("p",{className:"font-medium",children:a("settings.common.success")}),e.jsx("p",{className:"text-sm",children:g.message})]}),!b&&e.jsx(nr,{descriptionKey:"general.ownerOnly"}),e.jsx(Lr,{...x,children:e.jsxs("form",{onSubmit:x.handleSubmit(async function(e){c(!0),g.clear();try{await r(t,e),g.show(a("general.success"))}catch(e){z(e,{component:"WorkspaceSettingsGeneral",action:"updateWorkspace",metadata:{workspaceId:t._id}})}finally{c(!1)}}),className:"space-y-6",children:[e.jsx(Gr,{control:x.control,name:"name",render:({field:s})=>e.jsxs(zr,{children:[e.jsx($r,{children:a("general.name")}),e.jsx(qr,{children:e.jsx(Yr,{placeholder:a("general.namePlaceholder"),...s,disabled:!b})}),e.jsx(Jr,{})]})}),t.billingCurrency?.trim()&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Or,{className:"text-sm font-medium text-muted-foreground",children:a("general.billingCurrency")}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[tr(t.billingCurrency)&&e.jsx("span",{className:"text-base",children:tr(t.billingCurrency)}),e.jsx("span",{children:t.billingCurrency.trim().toUpperCase()})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Or,{className:"text-sm font-medium",children:a("general.icon")}),e.jsx(Hr,{children:a("general.iconDescription")})]}),e.jsxs(Zr,{value:l,disabled:!b,onValueChange:e=>d(e),className:"flex flex-col space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qr,{value:"emoji",id:"emoji"}),e.jsxs(Or,{htmlFor:"emoji",className:"flex items-center gap-2",children:[e.jsx(n.Smile,{className:"h-4 w-4"}),a("general.chooseEmoji")]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qr,{value:"url",id:"url"}),e.jsxs(Or,{htmlFor:"url",className:"flex items-center gap-2",children:[e.jsx(n.ImageIcon,{className:"h-4 w-4"}),a("general.customImageUrl")]})]})]}),"emoji"===l&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:a("general.previewLabel")}),e.jsxs("div",{className:"w-12 h-12 rounded-lg border-2 border-border flex items-center justify-center text-2xl bg-muted",children:[u&&e.jsx("span",{className:"text-2xl",children:u}),!u&&x.watch("image")?.trim()&&e.jsx("img",{src:x.watch("image")||void 0,alt:"Workspace preview"})]})]}),b&&e.jsx(Xr,{className:"h-32 w-full rounded-md border",children:e.jsx("div",{className:"p-4 grid grid-cols-8 gap-2",children:tn.map((s,t)=>e.jsx("button",{type:"button",onClick:()=>(e=>{p(e),x.setValue("image",sn(e))})(s),disabled:!b,className:"w-8 h-8 rounded flex items-center justify-center text-lg hover:bg-muted transition-colors "+(u===s?"bg-primary text-primary-foreground":""),children:s},t))})})]}),"url"===l&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Gr,{control:x.control,name:"image",render:({field:s})=>e.jsxs(zr,{children:[e.jsx($r,{children:a("general.imageUrl")}),e.jsx(qr,{children:e.jsx(Yr,{placeholder:a("general.imageUrlPlaceholder"),...s,disabled:!b})}),e.jsx(Hr,{children:a("general.imageUrlDescription")}),e.jsx(Jr,{})]})}),x.watch("image")&&x.watch("image")?.trim()&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:a("general.previewLabel")}),e.jsx("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:e.jsx("img",{src:x.watch("image")||void 0,className:"w-full h-full object-cover",alt:"Workspace preview"})})]})]})]}),e.jsx("div",{className:"flex justify-end gap-3 pt-4",children:b&&e.jsx(Pa,{type:"submit",disabled:o,progress:o,children:a("general.updateWorkspace")})})]})})]})};class rn extends Ns{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,s){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:s})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}const nn=s.createContext(null);function on(e){const s=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),t=atob(s),a=new Uint8Array(t.length);for(let e=0;e<t.length;e++)a[e]=t.charCodeAt(e);return a}const cn=s.memo(function({children:t,serviceWorkerPath:a="/push-sw.js",autoSubscribe:r=!1}){const{t:n}=ds(),i=Es(),{isAuthenticated:o}=xi(),c=s.useMemo(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=s.useMemo(()=>new rn({serverUrl:i.serverUrl,version:i.version,orgId:i.orgId}),[i.serverUrl,i.version,i.orgId]),[d,u]=s.useState({permission:c?Notification.permission:"default",isSubscribed:!1,isSupported:c,loading:!1,error:null});s.useEffect(()=>{if(!o||!c)return;let e=!1;return(async()=>{try{const s=await navigator.serviceWorker.getRegistration(a);if(e)return;if(!s)return void u(e=>({...e,isSubscribed:!1}));const t=await s.pushManager.getSubscription();if(e)return;u(e=>({...e,isSubscribed:!!t,permission:Notification.permission}))}catch{e||u(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[o,c,a]);const m=s.useCallback(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return u(s=>({...s,permission:e})),"granted"===e},[c]),p=s.useCallback(async()=>{if(c&&o){u(e=>({...e,loading:!0,error:null}));try{if(!await m())return void u(e=>({...e,loading:!1,error:n("notifications.permissionDenied")}));const{publicKey:e}=await l.getVapidPublicKey(),s=await navigator.serviceWorker.register(a);await navigator.serviceWorker.ready;const t=(await s.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:on(e)})).toJSON();await l.subscribe({endpoint:t.endpoint,keys:{p256dh:t.keys.p256dh,auth:t.keys.auth}},navigator.userAgent),u(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const s=e instanceof Error?e.message:n("push.failedToSubscribe");u(e=>({...e,loading:!1,error:s})),z(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,o,l,a,m]),h=s.useCallback(async()=>{if(c){u(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(a);if(e){const s=await e.pushManager.getSubscription();if(s){const e=s.endpoint;await s.unsubscribe(),await l.unsubscribe(e)}}u(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const s=e instanceof Error?e.message:n("push.failedToUnsubscribe");u(e=>({...e,loading:!1,error:s})),z(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,a]),g=s.useMemo(()=>({...d,requestPermission:m,subscribe:p,unsubscribe:h}),[d,m,p,h]);return e.jsx(nn.Provider,{value:g,children:t})});function ln(){const e=s.useContext(nn);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e}const dn={firefox:4,safari:4,edge:4,chrome:4},un=({workspace:t})=>{const{isSupported:a,permission:r,isSubscribed:i,loading:o,error:c,subscribe:l,unsubscribe:d}=ln(),{t:u}=ds(),{api:m}=Us(),{can:p}=Xa(),h=p(Ha.WORKSPACE_SETTINGS_EDIT),g=s.useMemo(()=>function(){const e="undefined"!=typeof navigator?navigator.userAgent:"";return e.includes("Firefox")?"firefox":e.includes("Safari")&&!e.includes("Chrome")?"safari":e.includes("Edg")?"edge":"chrome"}(),[]),f=dn[g],[x,b]=s.useState([]),[y,v]=s.useState(!0),[w,S]=s.useState({}),[N,j]=s.useState(!0),[k,C]=s.useState(null),[A,T]=s.useState(null),E=s.useRef(null);s.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]),s.useEffect(()=>{if(!t?._id)return;const e=t._id.toString();v(!0),j(!0),Promise.all([m.getNotificationEvents(e).catch(()=>[]),m.getNotificationPreferences(e).catch(()=>({}))]).then(([e,s])=>{b(e),S(s)}).finally(()=>{v(!1),j(!1)})},[t?._id]);const P=s.useCallback(async(e,s,a)=>{if(!t?._id||!h)return;const r=!a;C(`${e}.${s}`),T(null),S(t=>({...t,[e]:{...t[e],[s]:r}}));try{const a=await m.updateNotificationPreferences(t._id.toString(),{[e]:{[s]:r}});S(a),T(u("notifications.prefsSaved")),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>T(null),3e3)}catch(t){S(t=>({...t,[e]:{...t[e],[s]:a}})),z(t,{component:"SettingsNotifications",action:"toggleChannel"})}finally{C(null)}},[t?._id,h,m,u]),I=(e,s)=>!1!==w[e]?.[s],U=s.useMemo(()=>{const e=new Map;for(const s of x){const t=s.category||"general";e.has(t)||e.set(t,[]),e.get(t).push(s)}return Array.from(e.entries())},[x]),R=y||N,M=x.length>0;return e.jsxs("div",{className:"space-y-6",children:[e.jsx("p",{className:"text-sm text-gray-600",children:u("notifications.manageDescription")}),a&&e.jsxs(e.Fragment,{children:[c&&"denied"!==r&&e.jsx("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm",children:c}),"denied"===r&&e.jsx("div",{className:"border border-amber-200 bg-amber-50 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(n.ShieldAlert,{className:"h-5 w-5 text-amber-600 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-amber-800",children:u("notifications.blocked")}),e.jsx("p",{className:"text-xs text-amber-700 mt-1",children:u("notifications.blockedDescription")}),e.jsx("ol",{className:"text-xs text-amber-700 mt-2 space-y-1 list-decimal list-inside",children:Array.from({length:f},(s,t)=>e.jsx("li",{children:u(`notifications.unblock.${g}.step${t+1}`)},t))})]})]})}),"denied"!==r&&e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-2 rounded-lg "+(i?"bg-green-100":"bg-gray-100"),children:i?e.jsx(n.Bell,{className:"h-4 w-4 text-green-600"}):e.jsx(n.BellOff,{className:"h-4 w-4 text-gray-400"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-gray-900",children:u("notifications.pushTitle")}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:u("notifications.pushDescription",{subscribed:String(i)})})]})]}),e.jsx(Pa,{variant:i?"outline":"default",size:"sm",className:"shrink-0",onClick:i?d:l,disabled:o,progress:o,children:u("notifications.toggleAction",{loading:String(o),subscribed:String(i)})})]}),i&&e.jsx("div",{className:"mt-3 pt-3 border-t border-gray-100 text-xs text-gray-500",children:u("notifications.deviceNote")})]})]}),R&&e.jsx("div",{className:"text-center text-sm text-gray-400 py-4",children:u("notifications.loadingPrefs")}),!R&&M&&h&&e.jsxs(e.Fragment,{children:[A&&e.jsx("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg text-sm",children:A}),U.map(([s,t])=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"bg-gray-50 px-4 py-2.5 border-b",children:e.jsx("h4",{className:"text-sm font-medium text-gray-700 capitalize",children:s})}),e.jsxs("div",{className:"divide-y",children:[e.jsxs("div",{className:"flex items-center px-4 py-2 bg-gray-50/50",children:[e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx(n.Mail,{className:"h-3.5 w-3.5 text-gray-400"})}),e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx(n.Smartphone,{className:"h-3.5 w-3.5 text-gray-400"})})]})]}),t.map(s=>{const t=I(s.slug,"email"),a=I(s.slug,"push"),r=k===`${s.slug}.email`,n=k===`${s.slug}.push`;return e.jsxs("div",{className:"flex items-center px-4 py-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-gray-900",children:s.name}),s.description&&e.jsx("div",{className:"text-xs text-gray-500 mt-0.5",children:s.description})]}),e.jsxs("div",{className:"flex items-center gap-6 shrink-0",children:[e.jsx("div",{className:"w-12 flex justify-center",children:s.channels.email?e.jsx(Cr,{checked:t,onCheckedChange:()=>P(s.slug,"email",t),disabled:r}):e.jsx("span",{className:"text-xs text-gray-300",children:"—"})}),e.jsx("div",{className:"w-12 flex justify-center",children:s.channels.push?e.jsx(Cr,{checked:a,onCheckedChange:()=>P(s.slug,"push",a),disabled:n}):e.jsx("span",{className:"text-xs text-gray-300",children:"—"})})]})]},s.slug)})]})]},s))]})]})},mn=({workspace:t})=>{const{t:a}=ds(),{isOwner:r}=Xa(),{settings:n}=Is(),{appPermissions:i}=ht(),{updateWorkspacePermissions:o}=pi(),[c,l]=s.useState(!1),d=Ar(),u=s.useMemo(()=>n?.workspace?.roles??t.roles??[],[n?.workspace?.roles,t.roles]),m=s.useMemo(()=>{if(!i)return[];const e=new Set;for(const s of Object.values(i))for(const t of s)t.startsWith("workspace:")||e.add(t);return Array.from(e).sort()},[i]),[p,h]=s.useState({});if(s.useEffect(()=>{if(!i)return;const e=t.permissions,s={};for(const t of u)s[t]=e&&t in e?e[t].filter(e=>!e.startsWith("workspace:")):t in i?i[t].filter(e=>!e.startsWith("workspace:")):[];h(s)},[t.permissions,i,u]),!t)return e.jsx(or,{});if(!i||0===m.length)return null;return e.jsxs("div",{children:[d.message&&e.jsxs("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-4",children:[e.jsx("p",{className:"font-medium",children:a("settings.common.success")}),e.jsx("p",{className:"text-sm",children:d.message})]}),!r&&e.jsx(nr,{descriptionKey:"permissions.ownerOnly"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:a("permissions.description")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-start py-2 pe-4 font-medium text-gray-500 min-w-[160px]"}),u.map(s=>e.jsx("th",{className:"text-center py-2 px-3 font-medium text-gray-700 capitalize min-w-[80px]",children:s},s))]})}),e.jsx("tbody",{children:m.map(s=>e.jsxs("tr",{className:"border-b border-gray-50 hover:bg-gray-50/50",children:[e.jsx("td",{className:"py-2 pe-4 text-gray-700 font-mono text-xs",children:s}),u.map(t=>{const a="admin"===t,n=a||(p[t]??[]).includes(s);return e.jsx("td",{className:"text-center py-2 px-3",children:e.jsx(Cr,{checked:n,disabled:!r||a,onCheckedChange:()=>((e,s)=>{h(t=>{const a=t[e]??[],r=a.includes(s);return{...t,[e]:r?a.filter(e=>e!==s):[...a,s]}})})(t,s),className:"mx-auto"})},t)})]},s))})]})}),r&&e.jsx("div",{className:"mt-6",children:e.jsx(Pa,{onClick:async()=>{l(!0),d.clear();try{const e=t.permissions??{},s={},r=new Set([...Object.keys(e),...Object.keys(p)]);for(const t of r){const a=(e[t]??[]).filter(e=>e.startsWith("workspace:")),r=p[t]??[];s[t]=[...a,...r]}await o(t._id,s),d.show(a("permissions.saveSuccess"))}catch(e){z(e,{component:"WorkspaceSettingsPermissions",action:"savePermissions",metadata:{workspaceId:t._id}})}finally{l(!1)}},disabled:c,progress:c,children:a(c?"permissions.saving":"permissions.save")})})]})},pn=j.forwardRef(({className:s,...t},a)=>e.jsx(b.Command,{ref:a,className:W("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));pn.displayName=b.Command.displayName;const hn=j.forwardRef(({className:s,...t},a)=>e.jsxs("div",{className:"flex items-center border-b px-3","data-cmdk-input-wrapper":"",children:[e.jsx(l.MagnifyingGlassIcon,{className:"me-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(b.Command.Input,{ref:a,className:W("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",s),...t})]}));hn.displayName=b.Command.Input.displayName;const gn=j.forwardRef(({className:s,...t},a)=>e.jsx(b.Command.List,{ref:a,className:W("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));gn.displayName=b.Command.List.displayName;j.forwardRef((s,t)=>e.jsx(b.Command.Empty,{ref:t,className:"py-6 text-center text-sm",...s})).displayName=b.Command.Empty.displayName;const fn=j.forwardRef(({className:s,...t},a)=>e.jsx(b.Command.Group,{ref:a,className:W("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",s),...t}));fn.displayName=b.Command.Group.displayName;j.forwardRef(({className:s,...t},a)=>e.jsx(b.Command.Separator,{ref:a,className:W("-mx-1 h-px bg-border",s),...t})).displayName=b.Command.Separator.displayName;const xn=j.forwardRef(({className:s,...t},a)=>e.jsx(b.Command.Item,{ref:a,className:W("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...t}));xn.displayName=b.Command.Item.displayName;const bn=U.Root,yn=U.Trigger,vn=j.forwardRef(({className:s,align:t="center",sideOffset:a=4,...r},n)=>{const{container:i}=j.useContext(Ia);return e.jsx(U.Portal,{container:i,children:e.jsx(U.Content,{ref:n,align:t,sideOffset:a,className:W("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r})})});function wn({options:t,value:a,onChange:r,placeholder:i="Search...",emptyLabel:o="Choose option"}){const[c,l]=s.useState(a??""),[d,u]=s.useState(!1);s.useEffect(()=>{void 0!==a&&l(a)},[a]);const m=t.find(e=>e.value===c);return e.jsxs(bn,{open:d,onOpenChange:u,children:[e.jsx(yn,{asChild:!0,children:e.jsxs(Pa,{variant:"outline",role:"combobox","aria-expanded":d,className:"justify-between overflow-hidden text-ellipsis",children:[m?e.jsxs("div",{children:[String(m.label).trim(),m.icon&&e.jsx("span",{className:"ms-2 text-xs text-muted-foreground",children:m.icon})]}):e.jsx("span",{className:"text-muted-foreground",children:o}),e.jsx(n.ChevronsUpDown,{className:"ms-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(vn,{className:"p-0 overflow-hidden text-ellipsis",children:e.jsxs(pn,{children:[e.jsx(hn,{placeholder:i}),e.jsx(gn,{children:e.jsx(fn,{children:t.map(s=>e.jsxs(xn,{className:W("whitespace-nowrap text-start",{"text-green-500":c===s.value}),value:s.value,defaultValue:s.value,onSelect:()=>{return e=s.value,l(e),r?.(e),void u(!1);var e},children:[c===s.value&&e.jsx(n.CheckCheck,{className:W("me-2 h-4 w-4 text-green-400",c===s.value?"opacity-100":"opacity-0")}),String(s.label).trim(),s.icon&&e.jsx("span",{className:"ms-2 text-xs text-muted-foreground",children:s.icon})]},s.value))})})]})})]})}vn.displayName=U.Content.displayName;const Sn={USD:"$",EUR:"€",JPY:"¥",GBP:"£",AUD:"A$",CAD:"C$",CHF:"CHF",CNY:"¥",SEK:"kr",NZD:"NZ$",INR:"₹",RUB:"₽",KRW:"₩",BRL:"R$",ZAR:"R",HKD:"HK$",SGD:"S$",MXN:"Mex$",NOK:"kr",TRY:"₺",IDR:"Rp",PLN:"zł",THB:"฿",ILS:"₪",PHP:"₱",MYR:"RM",CZK:"Kč",HUF:"Ft",DKK:"kr",PKR:"₨",EGP:"£",NGN:"₦",BDT:"৳",UAH:"₴",KZT:"₸",VND:"₫",ARS:"$",BGN:"лв",COP:"COL$",HRK:"kn",ISK:"kr",KES:"KSh",LKR:"Rs",MAD:"د.م.",MNT:"₮",NPR:"रू",RSD:"дин.",SAR:"ر.س",TWD:"NT$",UYU:"$U",YER:"﷼",FJD:"FJ$",JMD:"J$",HTG:"G",BHD:"ب.د",KWD:"د.ك",OMR:"ر.ع.",BND:"B$",KPW:"₩",GHS:"₵",SYP:"ل.س",SLL:"Le",SSP:"£",AFN:"؋",MGA:"Ar",MDL:"lei",FOK:"kr",GMD:"D",LTL:"Lt",LVL:"Ls",HNL:"L",GEL:"₾",BMD:"$",AWG:"Afl",BTN:"Nu",GTQ:"Q",TZS:"TSh",BBD:"Bds$",NAD:"N$",BZD:"$",JEP:"£",WST:"T",PGK:"K",KGS:"лв",AZN:"₼",QAR:"ر.ق",XOF:"CFA",XPF:"CFP"},Nn={AF:"AFN",AX:"EUR",AL:"ALL",DZ:"DZD",AS:"USD",AD:"EUR",AO:"AOA",AI:"XCD",AQ:"USD",AG:"XCD",AR:"ARS",AM:"AMD",AW:"AWG",AU:"AUD",AT:"EUR",AZ:"AZN",BS:"BSD",BH:"BHD",BD:"BDT",BB:"BBD",BY:"BYN",BE:"EUR",BZ:"BZD",BJ:"XOF",BM:"BMD",BT:"BTN",BO:"BOB",BA:"BAM",BW:"BWP",BV:"NOK",BR:"BRL",IO:"USD",BN:"BND",BG:"BGN",BF:"XOF",BI:"BIF",KH:"KHR",CM:"XAF",CA:"CAD",CV:"CVE",KY:"KYD",CF:"XAF",TD:"XAF",CL:"CLP",CN:"CNY",CX:"AUD",CC:"AUD",CO:"COP",KM:"KMF",CG:"XAF",CD:"CDF",CK:"NZD",CR:"CRC",CI:"XOF",HR:"HRK",CU:"CUP",CY:"EUR",CZ:"CZK",DK:"DKK",DJ:"DJF",DM:"XCD",DO:"DOP",EC:"USD",EG:"EGP",SV:"USD",GQ:"XAF",ER:"ERN",EE:"EUR",ET:"ETB",FK:"FKP",FO:"DKK",FJ:"FJD",FI:"EUR",FR:"EUR",GF:"EUR",PF:"XPF",TF:"EUR",GA:"XAF",GM:"GMD",GE:"GEL",DE:"EUR",GH:"GHS",GI:"GIP",GR:"EUR",GL:"DKK",GD:"XCD",GP:"EUR",GU:"USD",GT:"GTQ",GG:"GBP",GN:"GNF",GW:"XOF",GY:"GYD",HT:"HTG",HM:"AUD",VA:"EUR",HN:"HNL",HK:"HKD",HU:"HUF",IS:"ISK",IN:"INR",ID:"IDR",IR:"IRR",IQ:"IQD",IE:"EUR",IM:"GBP",IL:"ILS",IT:"EUR",JM:"JMD",JP:"JPY",JE:"GBP",JO:"JOD",KZ:"KZT",KE:"KES",KI:"AUD",KP:"KPW",KR:"KRW",KW:"KWD",KG:"KGS",LA:"LAK",LV:"EUR",LB:"LBP",LS:"LSL",LR:"LRD",LY:"LYD",LI:"CHF",LT:"EUR",LU:"EUR",MO:"MOP",MK:"MKD",MG:"MGA",MW:"MWK",MY:"MYR",MV:"MVR",ML:"XOF",MT:"EUR",MH:"USD",MQ:"EUR",MR:"MRU",MU:"MUR",YT:"EUR",MX:"MXN",FM:"USD",MD:"MDL",MC:"EUR",MN:"MNT",ME:"EUR",MS:"XCD",MA:"MAD",MZ:"MZN",MM:"MMK",NA:"NAD",NR:"AUD",NP:"NPR",NL:"EUR",AN:"ANG",NC:"XPF",NZ:"NZD",NI:"NIO",NE:"XOF",NG:"NGN",NU:"NZD",NF:"AUD",MP:"USD",NO:"NOK",OM:"OMR",PK:"PKR",PW:"USD",PS:"ILS",PA:"PAB",PG:"PGK",PY:"PYG",PE:"PEN",PH:"PHP",PN:"NZD",PL:"PLN",PT:"EUR",PR:"USD",QA:"QAR",RE:"EUR",RO:"RON",RU:"RUB",RW:"RWF",SH:"SHP",KN:"XCD",LC:"XCD",PM:"EUR",VC:"XCD",WS:"WST",SM:"EUR",ST:"STN",SA:"SAR",SN:"XOF",RS:"RSD",SC:"SCR",SL:"SLL",SG:"SGD",SK:"EUR",SI:"EUR",SB:"SBD",SO:"SOS",ZA:"ZAR",GS:"GBP",ES:"EUR",LK:"LKR",SD:"SDG",SR:"SRD",SJ:"NOK",SZ:"SZL",SE:"SEK",CH:"CHF",SY:"SYP",TW:"TWD",TJ:"TJS",TZ:"TZS",TH:"THB"},jn=[{name:"Afghanistan",code:"AF"},{name:"land Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"},{name:"American Samoa",code:"AS"},{name:"AndorrA",code:"AD"},{name:"Angola",code:"AO"},{name:"Anguilla",code:"AI"},{name:"Antarctica",code:"AQ"},{name:"Antigua and Barbuda",code:"AG"},{name:"Argentina",code:"AR"},{name:"Armenia",code:"AM"},{name:"Aruba",code:"AW"},{name:"Australia",code:"AU"},{name:"Austria",code:"AT"},{name:"Azerbaijan",code:"AZ"},{name:"Bahamas",code:"BS"},{name:"Bahrain",code:"BH"},{name:"Bangladesh",code:"BD"},{name:"Barbados",code:"BB"},{name:"Belarus",code:"BY"},{name:"Belgium",code:"BE"},{name:"Belize",code:"BZ"},{name:"Benin",code:"BJ"},{name:"Bermuda",code:"BM"},{name:"Bhutan",code:"BT"},{name:"Bolivia",code:"BO"},{name:"Bosnia and Herzegovina",code:"BA"},{name:"Botswana",code:"BW"},{name:"Bouvet Island",code:"BV"},{name:"Brazil",code:"BR"},{name:"British Indian Ocean Territory",code:"IO"},{name:"Brunei Darussalam",code:"BN"},{name:"Bulgaria",code:"BG"},{name:"Burkina Faso",code:"BF"},{name:"Burundi",code:"BI"},{name:"Cambodia",code:"KH"},{name:"Cameroon",code:"CM"},{name:"Canada",code:"CA"},{name:"Cape Verde",code:"CV"},{name:"Cayman Islands",code:"KY"},{name:"Central African Republic",code:"CF"},{name:"Chad",code:"TD"},{name:"Chile",code:"CL"},{name:"China",code:"CN"},{name:"Christmas Island",code:"CX"},{name:"Cocos (Keeling) Islands",code:"CC"},{name:"Colombia",code:"CO"},{name:"Comoros",code:"KM"},{name:"Congo",code:"CG"},{name:"Congo, The Democratic Republic of the",code:"CD"},{name:"Cook Islands",code:"CK"},{name:"Costa Rica",code:"CR"},{name:"Cote D Ivoire",code:"CI"},{name:"Croatia",code:"HR"},{name:"Cuba",code:"CU"},{name:"Cyprus",code:"CY"},{name:"Czech Republic",code:"CZ"},{name:"Denmark",code:"DK"},{name:"Djibouti",code:"DJ"},{name:"Dominica",code:"DM"},{name:"Dominican Republic",code:"DO"},{name:"Ecuador",code:"EC"},{name:"Egypt",code:"EG"},{name:"El Salvador",code:"SV"},{name:"Equatorial Guinea",code:"GQ"},{name:"Eritrea",code:"ER"},{name:"Estonia",code:"EE"},{name:"Ethiopia",code:"ET"},{name:"Falkland Islands (Malvinas)",code:"FK"},{name:"Faroe Islands",code:"FO"},{name:"Fiji",code:"FJ"},{name:"Finland",code:"FI"},{name:"France",code:"FR"},{name:"French Guiana",code:"GF"},{name:"French Polynesia",code:"PF"},{name:"French Southern Territories",code:"TF"},{name:"Gabon",code:"GA"},{name:"Gambia",code:"GM"},{name:"Georgia",code:"GE"},{name:"Germany",code:"DE"},{name:"Ghana",code:"GH"},{name:"Gibraltar",code:"GI"},{name:"Greece",code:"GR"},{name:"Greenland",code:"GL"},{name:"Grenada",code:"GD"},{name:"Guadeloupe",code:"GP"},{name:"Guam",code:"GU"},{name:"Guatemala",code:"GT"},{name:"Guernsey",code:"GG"},{name:"Guinea",code:"GN"},{name:"Guinea-Bissau",code:"GW"},{name:"Guyana",code:"GY"},{name:"Haiti",code:"HT"},{name:"Heard Island and Mcdonald Islands",code:"HM"},{name:"Holy See (Vatican City State)",code:"VA"},{name:"Honduras",code:"HN"},{name:"Hong Kong",code:"HK"},{name:"Hungary",code:"HU"},{name:"Iceland",code:"IS"},{name:"India",code:"IN"},{name:"Indonesia",code:"ID"},{name:"Iran, Islamic Republic Of",code:"IR"},{name:"Iraq",code:"IQ"},{name:"Ireland",code:"IE"},{name:"Isle of Man",code:"IM"},{name:"Israel",code:"IL"},{name:"Italy",code:"IT"},{name:"Jamaica",code:"JM"},{name:"Japan",code:"JP"},{name:"Jersey",code:"JE"},{name:"Jordan",code:"JO"},{name:"Kazakhstan",code:"KZ"},{name:"Kenya",code:"KE"},{name:"Kiribati",code:"KI"},{name:'Korea, Democratic People"S Republic of',code:"KP"},{name:"Korea, Republic of",code:"KR"},{name:"Kuwait",code:"KW"},{name:"Kyrgyzstan",code:"KG"},{name:'Lao People"S Democratic Republic',code:"LA"},{name:"Latvia",code:"LV"},{name:"Lebanon",code:"LB"},{name:"Lesotho",code:"LS"},{name:"Liberia",code:"LR"},{name:"Libyan Arab Jamahiriya",code:"LY"},{name:"Liechtenstein",code:"LI"},{name:"Lithuania",code:"LT"},{name:"Luxembourg",code:"LU"},{name:"Macao",code:"MO"},{name:"Macedonia, The Former Yugoslav Republic of",code:"MK"},{name:"Madagascar",code:"MG"},{name:"Malawi",code:"MW"},{name:"Malaysia",code:"MY"},{name:"Maldives",code:"MV"},{name:"Mali",code:"ML"},{name:"Malta",code:"MT"},{name:"Marshall Islands",code:"MH"},{name:"Martinique",code:"MQ"},{name:"Mauritania",code:"MR"},{name:"Mauritius",code:"MU"},{name:"Mayotte",code:"YT"},{name:"Mexico",code:"MX"},{name:"Micronesia, Federated States of",code:"FM"},{name:"Moldova, Republic of",code:"MD"},{name:"Monaco",code:"MC"},{name:"Mongolia",code:"MN"},{name:"Montenegro",code:"ME"},{name:"Montserrat",code:"MS"},{name:"Morocco",code:"MA"},{name:"Mozambique",code:"MZ"},{name:"Myanmar",code:"MM"},{name:"Namibia",code:"NA"},{name:"Nauru",code:"NR"},{name:"Nepal",code:"NP"},{name:"Netherlands",code:"NL"},{name:"Netherlands Antilles",code:"AN"},{name:"New Caledonia",code:"NC"},{name:"New Zealand",code:"NZ"},{name:"Nicaragua",code:"NI"},{name:"Niger",code:"NE"},{name:"Nigeria",code:"NG"},{name:"Niue",code:"NU"},{name:"Norfolk Island",code:"NF"},{name:"Northern Mariana Islands",code:"MP"},{name:"Norway",code:"NO"},{name:"Oman",code:"OM"},{name:"Pakistan",code:"PK"},{name:"Palau",code:"PW"},{name:"Palestinian Territory, Occupied",code:"PS"},{name:"Panama",code:"PA"},{name:"Papua New Guinea",code:"PG"},{name:"Paraguay",code:"PY"},{name:"Peru",code:"PE"},{name:"Philippines",code:"PH"},{name:"Pitcairn",code:"PN"},{name:"Poland",code:"PL"},{name:"Portugal",code:"PT"},{name:"Puerto Rico",code:"PR"},{name:"Qatar",code:"QA"},{name:"Reunion",code:"RE"},{name:"Romania",code:"RO"},{name:"Russian Federation",code:"RU"},{name:"RWANDA",code:"RW"},{name:"Saint Helena",code:"SH"},{name:"Saint Kitts and Nevis",code:"KN"},{name:"Saint Lucia",code:"LC"},{name:"Saint Pierre and Miquelon",code:"PM"},{name:"Saint Vincent and the Grenadines",code:"VC"},{name:"Samoa",code:"WS"},{name:"San Marino",code:"SM"},{name:"Sao Tome and Principe",code:"ST"},{name:"Saudi Arabia",code:"SA"},{name:"Senegal",code:"SN"},{name:"Serbia",code:"RS"},{name:"Seychelles",code:"SC"},{name:"Sierra Leone",code:"SL"},{name:"Singapore",code:"SG"},{name:"Slovakia",code:"SK"},{name:"Slovenia",code:"SI"},{name:"Solomon Islands",code:"SB"},{name:"Somalia",code:"SO"},{name:"South Africa",code:"ZA"},{name:"South Georgia and the South Sandwich Islands",code:"GS"},{name:"Spain",code:"ES"},{name:"Sri Lanka",code:"LK"},{name:"Sudan",code:"SD"},{name:"Suriname",code:"SR"},{name:"Svalbard and Jan Mayen",code:"SJ"},{name:"Swaziland",code:"SZ"},{name:"Sweden",code:"SE"},{name:"Switzerland",code:"CH"},{name:"Syrian Arab Republic",code:"SY"},{name:"Taiwan, Province of China",code:"TW"},{name:"Tajikistan",code:"TJ"},{name:"Tanzania, United Republic of",code:"TZ"},{name:"Thailand",code:"TH"},{name:"Timor-Leste",code:"TL"},{name:"Togo",code:"TG"},{name:"Tokelau",code:"TK"},{name:"Tonga",code:"TO"},{name:"Trinidad and Tobago",code:"TT"},{name:"Tunisia",code:"TN"},{name:"Turkey",code:"TR"},{name:"Turkmenistan",code:"TM"},{name:"Turks and Caicos Islands",code:"TC"},{name:"Tuvalu",code:"TV"},{name:"Uganda",code:"UG"},{name:"Ukraine",code:"UA"},{name:"United Arab Emirates",code:"AE"},{name:"United Kingdom",code:"GB"},{name:"United States",code:"US"},{name:"United States Minor Outlying Islands",code:"UM"},{name:"Uruguay",code:"UY"},{name:"Uzbekistan",code:"UZ"},{name:"Vanuatu",code:"VU"},{name:"Venezuela",code:"VE"},{name:"Viet Nam",code:"VN"},{name:"Virgin Islands, British",code:"VG"},{name:"Virgin Islands, U.S.",code:"VI"},{name:"Wallis and Futuna",code:"WF"},{name:"Western Sahara",code:"EH"},{name:"Yemen",code:"YE"},{name:"Zambia",code:"ZM"},{name:"Zimbabwe",code:"ZW"}].map(e=>{const s=Nn[e.code]||"USD",t=Sn[s]||"";return{value:e.code,flag:(a=e.code,a.toUpperCase().replace(/./g,e=>String.fromCodePoint(127397+e.charCodeAt(0)))),text:e.name,currencyCode:s,currencyIcon:t};var a});function kn({value:s,onChange:t}){const{t:a}=ds(),r=jn.map(e=>({value:e.value,label:e.text,icon:e.flag}));return e.jsx(wn,{options:r,value:s,onChange:t,placeholder:a("dropdowns.searchCountry"),emptyLabel:a("dropdowns.chooseCountry")})}const Cn=jn.map(e=>({value:e.currencyCode,text:e.currencyCode,icon:e.currencyIcon??null})),An=Array.from(new Set(Cn.map(e=>e.value))).map(e=>Cn.find(s=>s.value===e)).filter(e=>void 0!==e);function Tn({value:s,onChange:t}){const{t:a}=ds(),r=An.map(e=>({value:e.value,label:e.text,icon:e.icon??void 0}));return e.jsx(wn,{options:r,value:s,onChange:t,placeholder:a("dropdowns.searchCurrency"),emptyLabel:a("dropdowns.chooseCurrency")})}let En=[{code:"en",label:"English",flag:"🇬🇧"},{code:"en-GB",label:"English (United Kingdom)",flag:"🇬🇧"},{code:"en-US",label:"English (United States)",flag:"🇺🇸"},{code:"en-AU",label:"English (Australia)",flag:"🇦🇺"},{code:"en-CA",label:"English (Canada)",flag:"🇨🇦"},{code:"en-NZ",label:"English (New Zealand)",flag:"🇳🇿"},{code:"es",label:"Spanish",flag:"🇪🇸"},{code:"es-ES",label:"Spanish (Spain)",flag:"🇪🇸"},{code:"es-MX",label:"Spanish (Mexico)",flag:"🇲🇽"},{code:"fr",label:"French",flag:"🇫🇷"},{code:"fr-FR",label:"French (France)",flag:"🇫🇷"},{code:"de",label:"German",flag:"🇩🇪"},{code:"de-DE",label:"German (Germany)",flag:"🇩🇪"},{code:"it",label:"Italian",flag:"🇮🇹"},{code:"it-IT",label:"Italian (Italy)",flag:"🇮🇹"},{code:"pt",label:"Portuguese",flag:"🇵🇹"},{code:"pt-PT",label:"Portuguese (Portugal)",flag:"🇵🇹"},{code:"pt-BR",label:"Portuguese (Brazil)",flag:"🇧🇷"},{code:"ru",label:"Russian",flag:"🇷🇺"},{code:"ru-RU",label:"Russian (Russia)",flag:"🇷🇺"},{code:"zh",label:"Chinese",flag:"🇨🇳"},{code:"zh-CN",label:"Chinese (Simplified)",flag:"🇨🇳"},{code:"zh-TW",label:"Chinese (Traditional)",flag:"🇹🇼"},{code:"ja",label:"Japanese",flag:"🇯🇵"},{code:"ja-JP",label:"Japanese (Japan)",flag:"🇯🇵"},{code:"ko",label:"Korean",flag:"🇰🇷"},{code:"ko-KR",label:"Korean (South Korea)",flag:"🇰🇷"},{code:"ar",label:"Arabic",flag:"🇸🇦"},{code:"ar-SA",label:"Arabic (Saudi Arabia)",flag:"🇸🇦"},{code:"hi",label:"Hindi",flag:"🇮🇳"},{code:"hi-IN",label:"Hindi (India)",flag:"🇮🇳"},{code:"bn",label:"Bengali",flag:"🇮🇳"},{code:"bn-IN",label:"Bengali (India)",flag:"🇮🇳"},{code:"gu",label:"Gujarati",flag:"🇮🇳"},{code:"gu-IN",label:"Gujarati (India)",flag:"🇮🇳"},{code:"ta",label:"Tamil",flag:"🇮🇳"},{code:"ta-IN",label:"Tamil (India)",flag:"🇮🇳"},{code:"te",label:"Telugu",flag:"🇮🇳"},{code:"te-IN",label:"Telugu (India)",flag:"🇮🇳"},{code:"ml",label:"Malayalam",flag:"🇮🇳"},{code:"ml-IN",label:"Malayalam (India)",flag:"🇮🇳"},{code:"kn",label:"Kannada",flag:"🇮🇳"},{code:"kn-IN",label:"Kannada (India)",flag:"🇮🇳"},{code:"mr",label:"Marathi",flag:"🇮🇳"},{code:"mr-IN",label:"Marathi (India)",flag:"🇮🇳"},{code:"pa",label:"Punjabi",flag:"🇮🇳"},{code:"pa-IN",label:"Punjabi (India)",flag:"🇮🇳"},{code:"ur",label:"Urdu",flag:"🇮🇳"},{code:"ur-IN",label:"Urdu (India)",flag:"🇮🇳"},{code:"or",label:"Odia",flag:"🇮🇳"},{code:"or-IN",label:"Odia (India)",flag:"🇮🇳"},{code:"as",label:"Assamese",flag:"🇮🇳"},{code:"as-IN",label:"Assamese (India)",flag:"🇮🇳"},{code:"zh-HK",label:"Chinese (Hong Kong)",flag:"🇭🇰"},{code:"nl",label:"Dutch",flag:"🇳🇱"},{code:"nl-NL",label:"Dutch (Netherlands)",flag:"🇳🇱"},{code:"pl",label:"Polish",flag:"🇵🇱"},{code:"pl-PL",label:"Polish (Poland)",flag:"🇵🇱"},{code:"sv",label:"Swedish",flag:"🇸🇪"},{code:"sv-SE",label:"Swedish (Sweden)",flag:"🇸🇪"},{code:"da",label:"Danish",flag:"🇩🇰"},{code:"da-DK",label:"Danish (Denmark)",flag:"🇩🇰"},{code:"no",label:"Norwegian",flag:"🇳🇴"},{code:"no-NO",label:"Norwegian (Norway)",flag:"🇳🇴"},{code:"fi",label:"Finnish",flag:"🇫🇮"},{code:"fi-FI",label:"Finnish (Finland)",flag:"🇫🇮"},{code:"tr",label:"Turkish",flag:"🇹🇷"},{code:"tr-TR",label:"Turkish (Turkey)",flag:"🇹🇷"},{code:"cs",label:"Czech",flag:"🇨🇿"},{code:"cs-CZ",label:"Czech (Czech Republic)",flag:"🇨🇿"},{code:"sk",label:"Slovak",flag:"🇸🇰"},{code:"sk-SK",label:"Slovak (Slovakia)",flag:"🇸🇰"},{code:"hu",label:"Hungarian",flag:"🇭🇺"},{code:"hu-HU",label:"Hungarian (Hungary)",flag:"🇭🇺"},{code:"ro",label:"Romanian",flag:"🇷🇴"},{code:"ro-RO",label:"Romanian (Romania)",flag:"🇷🇴"},{code:"el",label:"Greek",flag:"🇬🇷"},{code:"el-GR",label:"Greek (Greece)",flag:"🇬🇷"},{code:"th",label:"Thai",flag:"🇹🇭"},{code:"th-TH",label:"Thai (Thailand)",flag:"🇹🇭"},{code:"id",label:"Indonesian",flag:"🇮🇩"},{code:"id-ID",label:"Indonesian (Indonesia)",flag:"🇮🇩"},{code:"ms",label:"Malay",flag:"🇲🇾"},{code:"ms-MY",label:"Malay (Malaysia)",flag:"🇲🇾"},{code:"vi",label:"Vietnamese",flag:"🇻🇳"},{code:"vi-VN",label:"Vietnamese (Vietnam)",flag:"🇻🇳"},{code:"he",label:"Hebrew",flag:"🇮🇱"},{code:"he-IL",label:"Hebrew (Israel)",flag:"🇮🇱"}];En=En.filter((e,s,t)=>s===t.findIndex(s=>s.code===e.code&&s.label===e.label)),En.sort((e,s)=>e.label<s.label?-1:e.label>s.label?1:0);const Pn=En.filter(e=>function(e){try{const s=new Intl.DateTimeFormat(e);return s.resolvedOptions().locale===e||s.resolvedOptions().locale.startsWith(e)}catch{return!1}}(e.code)).filter((e,s,t)=>s===t.findIndex(s=>s.code===e.code&&s.label===e.label)).map(e=>({value:e.code,label:e.label,flag:e.flag}));function In({value:s,onChange:t}){const{t:a}=ds(),r=Pn.map(e=>({value:e.value,label:e.label,icon:e.flag}));return e.jsx(wn,{options:r,value:s,onChange:t,placeholder:a("dropdowns.searchLanguage"),emptyLabel:a("dropdowns.chooseLanguage")})}const Un=[{value:"Dateline Standard Time",abbr:"DST",offset:-12,isdst:!1,text:"(UTC-12:00) International Date Line West",utc:["Etc/GMT+12"]},{value:"UTC-11",abbr:"U",offset:-11,isdst:!1,text:"(UTC-11:00) Coordinated Universal Time-11",utc:["Etc/GMT+11","Pacific/Midway","Pacific/Niue","Pacific/Pago_Pago"]},{value:"Hawaiian Standard Time",abbr:"HST",offset:-10,isdst:!1,text:"(UTC-10:00) Hawaii",utc:["Etc/GMT+10","Pacific/Honolulu","Pacific/Johnston","Pacific/Rarotonga","Pacific/Tahiti"]},{value:"Alaskan Standard Time",abbr:"AKDT",offset:-8,isdst:!0,text:"(UTC-09:00) Alaska",utc:["America/Anchorage","America/Juneau","America/Nome","America/Sitka","America/Yakutat"]},{value:"Pacific Standard Time (Mexico)",abbr:"PDT",offset:-7,isdst:!0,text:"(UTC-08:00) Baja California",utc:["America/Santa_Isabel"]},{value:"Pacific Daylight Time",abbr:"PDT",offset:-7,isdst:!0,text:"(UTC-07:00) Pacific Daylight Time (US & Canada)",utc:["America/Los_Angeles","America/Tijuana","America/Vancouver"]},{value:"Pacific Standard Time",abbr:"PST",offset:-8,isdst:!1,text:"(UTC-08:00) Pacific Standard Time (US & Canada)",utc:["America/Los_Angeles","America/Tijuana","America/Vancouver","PST8PDT"]},{value:"US Mountain Standard Time",abbr:"UMST",offset:-7,isdst:!1,text:"(UTC-07:00) Arizona",utc:["America/Creston","America/Dawson","America/Dawson_Creek","America/Hermosillo","America/Phoenix","America/Whitehorse","Etc/GMT+7"]},{value:"Mountain Standard Time (Mexico)",abbr:"MDT",offset:-6,isdst:!0,text:"(UTC-07:00) Chihuahua, La Paz, Mazatlan",utc:["America/Chihuahua","America/Mazatlan"]},{value:"Mountain Standard Time",abbr:"MDT",offset:-6,isdst:!0,text:"(UTC-07:00) Mountain Time (US & Canada)",utc:["America/Boise","America/Cambridge_Bay","America/Denver","America/Edmonton","America/Inuvik","America/Ojinaga","America/Yellowknife","MST7MDT"]},{value:"Central America Standard Time",abbr:"CAST",offset:-6,isdst:!1,text:"(UTC-06:00) Central America",utc:["America/Belize","America/Costa_Rica","America/El_Salvador","America/Guatemala","America/Managua","America/Tegucigalpa","Etc/GMT+6","Pacific/Galapagos"]},{value:"Central Standard Time",abbr:"CDT",offset:-5,isdst:!0,text:"(UTC-06:00) Central Time (US & Canada)",utc:["America/Chicago","America/Indiana/Knox","America/Indiana/Tell_City","America/Matamoros","America/Menominee","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Rainy_River","America/Rankin_Inlet","America/Resolute","America/Winnipeg","CST6CDT"]},{value:"Central Standard Time (Mexico)",abbr:"CDT",offset:-5,isdst:!0,text:"(UTC-06:00) Guadalajara, Mexico City, Monterrey",utc:["America/Bahia_Banderas","America/Cancun","America/Merida","America/Mexico_City","America/Monterrey"]},{value:"Canada Central Standard Time",abbr:"CCST",offset:-6,isdst:!1,text:"(UTC-06:00) Saskatchewan",utc:["America/Regina","America/Swift_Current"]},{value:"SA Pacific Standard Time",abbr:"SPST",offset:-5,isdst:!1,text:"(UTC-05:00) Bogota, Lima, Quito",utc:["America/Bogota","America/Cayman","America/Coral_Harbour","America/Eirunepe","America/Guayaquil","America/Jamaica","America/Lima","America/Panama","America/Rio_Branco","Etc/GMT+5"]},{value:"Eastern Standard Time",abbr:"EST",offset:-5,isdst:!1,text:"(UTC-05:00) Eastern Time (US & Canada)",utc:["America/Detroit","America/Havana","America/Indiana/Petersburg","America/Indiana/Vincennes","America/Indiana/Winamac","America/Iqaluit","America/Kentucky/Monticello","America/Louisville","America/Montreal","America/Nassau","America/New_York","America/Nipigon","America/Pangnirtung","America/Port-au-Prince","America/Thunder_Bay","America/Toronto"]},{value:"Eastern Daylight Time",abbr:"EDT",offset:-4,isdst:!0,text:"(UTC-04:00) Eastern Daylight Time (US & Canada)",utc:["America/Detroit","America/Havana","America/Indiana/Petersburg","America/Indiana/Vincennes","America/Indiana/Winamac","America/Iqaluit","America/Kentucky/Monticello","America/Louisville","America/Montreal","America/Nassau","America/New_York","America/Nipigon","America/Pangnirtung","America/Port-au-Prince","America/Thunder_Bay","America/Toronto"]},{value:"US Eastern Standard Time",abbr:"UEDT",offset:-5,isdst:!1,text:"(UTC-05:00) Indiana (East)",utc:["America/Indiana/Marengo","America/Indiana/Vevay","America/Indianapolis"]},{value:"Venezuela Standard Time",abbr:"VST",offset:-4.5,isdst:!1,text:"(UTC-04:30) Caracas",utc:["America/Caracas"]},{value:"Paraguay Standard Time",abbr:"PYT",offset:-4,isdst:!1,text:"(UTC-04:00) Asuncion",utc:["America/Asuncion"]},{value:"Atlantic Standard Time",abbr:"ADT",offset:-3,isdst:!0,text:"(UTC-04:00) Atlantic Time (Canada)",utc:["America/Glace_Bay","America/Goose_Bay","America/Halifax","America/Moncton","America/Thule","Atlantic/Bermuda"]},{value:"Central Brazilian Standard Time",abbr:"CBST",offset:-4,isdst:!1,text:"(UTC-04:00) Cuiaba",utc:["America/Campo_Grande","America/Cuiaba"]},{value:"SA Western Standard Time",abbr:"SWST",offset:-4,isdst:!1,text:"(UTC-04:00) Georgetown, La Paz, Manaus, San Juan",utc:["America/Anguilla","America/Antigua","America/Aruba","America/Barbados","America/Blanc-Sablon","America/Boa_Vista","America/Curacao","America/Dominica","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guyana","America/Kralendijk","America/La_Paz","America/Lower_Princes","America/Manaus","America/Marigot","America/Martinique","America/Montserrat","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Santo_Domingo","America/St_Barthelemy","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Tortola","Etc/GMT+4"]},{value:"Pacific SA Standard Time",abbr:"PSST",offset:-4,isdst:!1,text:"(UTC-04:00) Santiago",utc:["America/Santiago","Antarctica/Palmer"]},{value:"Newfoundland Standard Time",abbr:"NDT",offset:-2.5,isdst:!0,text:"(UTC-03:30) Newfoundland",utc:["America/St_Johns"]},{value:"E. South America Standard Time",abbr:"ESAST",offset:-3,isdst:!1,text:"(UTC-03:00) Brasilia",utc:["America/Sao_Paulo"]},{value:"Argentina Standard Time",abbr:"AST",offset:-3,isdst:!1,text:"(UTC-03:00) Buenos Aires",utc:["America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Buenos_Aires","America/Catamarca","America/Cordoba","America/Jujuy","America/Mendoza"]},{value:"SA Eastern Standard Time",abbr:"SEST",offset:-3,isdst:!1,text:"(UTC-03:00) Cayenne, Fortaleza",utc:["America/Araguaina","America/Belem","America/Cayenne","America/Fortaleza","America/Maceio","America/Paramaribo","America/Recife","America/Santarem","Antarctica/Rothera","Atlantic/Stanley","Etc/GMT+3"]},{value:"Greenland Standard Time",abbr:"GDT",offset:-3,isdst:!0,text:"(UTC-03:00) Greenland",utc:["America/Godthab"]},{value:"Montevideo Standard Time",abbr:"MST",offset:-3,isdst:!1,text:"(UTC-03:00) Montevideo",utc:["America/Montevideo"]},{value:"Bahia Standard Time",abbr:"BST",offset:-3,isdst:!1,text:"(UTC-03:00) Salvador",utc:["America/Bahia"]},{value:"UTC-02",abbr:"U",offset:-2,isdst:!1,text:"(UTC-02:00) Coordinated Universal Time-02",utc:["America/Noronha","Atlantic/South_Georgia","Etc/GMT+2"]},{value:"Mid-Atlantic Standard Time",abbr:"MDT",offset:-1,isdst:!0,text:"(UTC-02:00) Mid-Atlantic - Old",utc:[]},{value:"Azores Standard Time",abbr:"ADT",offset:0,isdst:!0,text:"(UTC-01:00) Azores",utc:["America/Scoresbysund","Atlantic/Azores"]},{value:"Cape Verde Standard Time",abbr:"CVST",offset:-1,isdst:!1,text:"(UTC-01:00) Cape Verde Is.",utc:["Atlantic/Cape_Verde","Etc/GMT+1"]},{value:"Morocco Standard Time",abbr:"MDT",offset:1,isdst:!0,text:"(UTC) Casablanca",utc:["Africa/Casablanca","Africa/El_Aaiun"]},{value:"UTC",abbr:"UTC",offset:0,isdst:!1,text:"(UTC) Coordinated Universal Time",utc:["America/Danmarkshavn","Etc/GMT"]},{value:"GMT Standard Time",abbr:"GMT",offset:0,isdst:!1,text:"(UTC) Edinburgh, London",utc:["Europe/Isle_of_Man","Europe/Guernsey","Europe/Jersey","Europe/London"]},{value:"British Summer Time",abbr:"BST",offset:1,isdst:!0,text:"(UTC+01:00) Edinburgh, London",utc:["Europe/Isle_of_Man","Europe/Guernsey","Europe/Jersey","Europe/London"]},{value:"GMT Standard Time",abbr:"GDT",offset:1,isdst:!0,text:"(UTC) Dublin, Lisbon",utc:["Atlantic/Canary","Atlantic/Faeroe","Atlantic/Madeira","Europe/Dublin","Europe/Lisbon"]},{value:"Greenwich Standard Time",abbr:"GST",offset:0,isdst:!1,text:"(UTC) Monrovia, Reykjavik",utc:["Africa/Abidjan","Africa/Accra","Africa/Bamako","Africa/Banjul","Africa/Bissau","Africa/Conakry","Africa/Dakar","Africa/Freetown","Africa/Lome","Africa/Monrovia","Africa/Nouakchott","Africa/Ouagadougou","Africa/Sao_Tome","Atlantic/Reykjavik","Atlantic/St_Helena"]},{value:"W. Europe Standard Time",abbr:"WEDT",offset:2,isdst:!0,text:"(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna",utc:["Arctic/Longyearbyen","Europe/Amsterdam","Europe/Andorra","Europe/Berlin","Europe/Busingen","Europe/Gibraltar","Europe/Luxembourg","Europe/Malta","Europe/Monaco","Europe/Oslo","Europe/Rome","Europe/San_Marino","Europe/Stockholm","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Zurich"]},{value:"Central Europe Standard Time",abbr:"CEDT",offset:2,isdst:!0,text:"(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague",utc:["Europe/Belgrade","Europe/Bratislava","Europe/Budapest","Europe/Ljubljana","Europe/Podgorica","Europe/Prague","Europe/Tirane"]},{value:"Romance Standard Time",abbr:"RDT",offset:2,isdst:!0,text:"(UTC+01:00) Brussels, Copenhagen, Madrid, Paris",utc:["Africa/Ceuta","Europe/Brussels","Europe/Copenhagen","Europe/Madrid","Europe/Paris"]},{value:"Central European Standard Time",abbr:"CEDT",offset:2,isdst:!0,text:"(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb",utc:["Europe/Sarajevo","Europe/Skopje","Europe/Warsaw","Europe/Zagreb"]},{value:"W. Central Africa Standard Time",abbr:"WCAST",offset:1,isdst:!1,text:"(UTC+01:00) West Central Africa",utc:["Africa/Algiers","Africa/Bangui","Africa/Brazzaville","Africa/Douala","Africa/Kinshasa","Africa/Lagos","Africa/Libreville","Africa/Luanda","Africa/Malabo","Africa/Ndjamena","Africa/Niamey","Africa/Porto-Novo","Africa/Tunis","Etc/GMT-1"]},{value:"Namibia Standard Time",abbr:"NST",offset:1,isdst:!1,text:"(UTC+01:00) Windhoek",utc:["Africa/Windhoek"]},{value:"GTB Standard Time",abbr:"GDT",offset:3,isdst:!0,text:"(UTC+02:00) Athens, Bucharest",utc:["Asia/Nicosia","Europe/Athens","Europe/Bucharest","Europe/Chisinau"]},{value:"Middle East Standard Time",abbr:"MEDT",offset:3,isdst:!0,text:"(UTC+02:00) Beirut",utc:["Asia/Beirut"]},{value:"Egypt Standard Time",abbr:"EST",offset:2,isdst:!1,text:"(UTC+02:00) Cairo",utc:["Africa/Cairo"]},{value:"Syria Standard Time",abbr:"SDT",offset:3,isdst:!0,text:"(UTC+02:00) Damascus",utc:["Asia/Damascus"]},{value:"E. Europe Standard Time",abbr:"EEDT",offset:3,isdst:!0,text:"(UTC+02:00) E. Europe",utc:["Asia/Nicosia","Europe/Athens","Europe/Bucharest","Europe/Chisinau","Europe/Helsinki","Europe/Kyiv","Europe/Mariehamn","Europe/Nicosia","Europe/Riga","Europe/Sofia","Europe/Tallinn","Europe/Uzhhorod","Europe/Vilnius","Europe/Zaporizhzhia"]},{value:"South Africa Standard Time",abbr:"SAST",offset:2,isdst:!1,text:"(UTC+02:00) Harare, Pretoria",utc:["Africa/Blantyre","Africa/Bujumbura","Africa/Gaborone","Africa/Harare","Africa/Johannesburg","Africa/Kigali","Africa/Lubumbashi","Africa/Lusaka","Africa/Maputo","Africa/Maseru","Africa/Mbabane","Etc/GMT-2"]},{value:"FLE Standard Time",abbr:"FDT",offset:3,isdst:!0,text:"(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius",utc:["Europe/Helsinki","Europe/Kyiv","Europe/Mariehamn","Europe/Riga","Europe/Sofia","Europe/Tallinn","Europe/Uzhhorod","Europe/Vilnius","Europe/Zaporizhzhia"]},{value:"Turkey Standard Time",abbr:"TDT",offset:3,isdst:!1,text:"(UTC+03:00) Istanbul",utc:["Europe/Istanbul"]},{value:"Israel Standard Time",abbr:"JDT",offset:3,isdst:!0,text:"(UTC+02:00) Jerusalem",utc:["Asia/Jerusalem"]},{value:"Libya Standard Time",abbr:"LST",offset:2,isdst:!1,text:"(UTC+02:00) Tripoli",utc:["Africa/Tripoli"]},{value:"Jordan Standard Time",abbr:"JST",offset:3,isdst:!1,text:"(UTC+03:00) Amman",utc:["Asia/Amman"]},{value:"Arabic Standard Time",abbr:"AST",offset:3,isdst:!1,text:"(UTC+03:00) Baghdad",utc:["Asia/Baghdad"]},{value:"Kaliningrad Standard Time",abbr:"KST",offset:3,isdst:!1,text:"(UTC+02:00) Kaliningrad",utc:["Europe/Kaliningrad"]},{value:"Arab Standard Time",abbr:"AST",offset:3,isdst:!1,text:"(UTC+03:00) Kuwait, Riyadh",utc:["Asia/Aden","Asia/Bahrain","Asia/Kuwait","Asia/Qatar","Asia/Riyadh"]},{value:"E. Africa Standard Time",abbr:"EAST",offset:3,isdst:!1,text:"(UTC+03:00) Nairobi",utc:["Africa/Addis_Ababa","Africa/Asmera","Africa/Dar_es_Salaam","Africa/Djibouti","Africa/Juba","Africa/Kampala","Africa/Khartoum","Africa/Mogadishu","Africa/Nairobi","Antarctica/Syowa","Etc/GMT-3","Indian/Antananarivo","Indian/Comoro","Indian/Mayotte"]},{value:"Moscow Standard Time",abbr:"MSK",offset:3,isdst:!1,text:"(UTC+03:00) Moscow, St. Petersburg, Volgograd, Minsk",utc:["Europe/Kirov","Europe/Moscow","Europe/Simferopol","Europe/Volgograd","Europe/Minsk"]},{value:"Samara Time",abbr:"SAMT",offset:4,isdst:!1,text:"(UTC+04:00) Samara, Ulyanovsk, Saratov",utc:["Europe/Astrakhan","Europe/Samara","Europe/Ulyanovsk"]},{value:"Iran Standard Time",abbr:"IDT",offset:4.5,isdst:!0,text:"(UTC+03:30) Tehran",utc:["Asia/Tehran"]},{value:"Arabian Standard Time",abbr:"AST",offset:4,isdst:!1,text:"(UTC+04:00) Abu Dhabi, Muscat",utc:["Asia/Dubai","Asia/Muscat","Etc/GMT-4"]},{value:"Azerbaijan Standard Time",abbr:"ADT",offset:5,isdst:!0,text:"(UTC+04:00) Baku",utc:["Asia/Baku"]},{value:"Mauritius Standard Time",abbr:"MST",offset:4,isdst:!1,text:"(UTC+04:00) Port Louis",utc:["Indian/Mahe","Indian/Mauritius","Indian/Reunion"]},{value:"Georgian Standard Time",abbr:"GET",offset:4,isdst:!1,text:"(UTC+04:00) Tbilisi",utc:["Asia/Tbilisi"]},{value:"Caucasus Standard Time",abbr:"CST",offset:4,isdst:!1,text:"(UTC+04:00) Yerevan",utc:["Asia/Yerevan"]},{value:"Afghanistan Standard Time",abbr:"AST",offset:4.5,isdst:!1,text:"(UTC+04:30) Kabul",utc:["Asia/Kabul"]},{value:"West Asia Standard Time",abbr:"WAST",offset:5,isdst:!1,text:"(UTC+05:00) Ashgabat, Tashkent",utc:["Antarctica/Mawson","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Dushanbe","Asia/Oral","Asia/Samarkand","Asia/Tashkent","Etc/GMT-5","Indian/Kerguelen","Indian/Maldives"]},{value:"Yekaterinburg Time",abbr:"YEKT",offset:5,isdst:!1,text:"(UTC+05:00) Yekaterinburg",utc:["Asia/Yekaterinburg"]},{value:"Pakistan Standard Time",abbr:"PKT",offset:5,isdst:!1,text:"(UTC+05:00) Islamabad, Karachi",utc:["Asia/Karachi"]},{value:"India Standard Time",abbr:"IST",offset:5.5,isdst:!1,text:"(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi",utc:["Asia/Kolkata","Asia/Calcutta"]},{value:"Sri Lanka Standard Time",abbr:"SLST",offset:5.5,isdst:!1,text:"(UTC+05:30) Sri Jayawardenepura",utc:["Asia/Colombo"]},{value:"Nepal Standard Time",abbr:"NST",offset:5.75,isdst:!1,text:"(UTC+05:45) Kathmandu",utc:["Asia/Kathmandu"]},{value:"Central Asia Standard Time",abbr:"CAST",offset:6,isdst:!1,text:"(UTC+06:00) Nur-Sultan (Astana)",utc:["Antarctica/Vostok","Asia/Almaty","Asia/Bishkek","Asia/Qyzylorda","Asia/Urumqi","Etc/GMT-6","Indian/Chagos"]},{value:"Bangladesh Standard Time",abbr:"BST",offset:6,isdst:!1,text:"(UTC+06:00) Dhaka",utc:["Asia/Dhaka","Asia/Thimphu"]},{value:"Myanmar Standard Time",abbr:"MST",offset:6.5,isdst:!1,text:"(UTC+06:30) Yangon (Rangoon)",utc:["Asia/Rangoon","Indian/Cocos"]},{value:"SE Asia Standard Time",abbr:"SAST",offset:7,isdst:!1,text:"(UTC+07:00) Bangkok, Hanoi, Jakarta",utc:["Antarctica/Davis","Asia/Bangkok","Asia/Hovd","Asia/Jakarta","Asia/Phnom_Penh","Asia/Pontianak","Asia/Saigon","Asia/Vientiane","Etc/GMT-7","Indian/Christmas"]},{value:"N. Central Asia Standard Time",abbr:"NCAST",offset:7,isdst:!1,text:"(UTC+07:00) Novosibirsk",utc:["Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk"]},{value:"China Standard Time",abbr:"CST",offset:8,isdst:!1,text:"(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi",utc:["Asia/Hong_Kong","Asia/Macau","Asia/Shanghai"]},{value:"North Asia Standard Time",abbr:"NAST",offset:8,isdst:!1,text:"(UTC+08:00) Krasnoyarsk",utc:["Asia/Krasnoyarsk"]},{value:"Singapore Standard Time",abbr:"MPST",offset:8,isdst:!1,text:"(UTC+08:00) Kuala Lumpur, Singapore",utc:["Asia/Brunei","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Makassar","Asia/Manila","Asia/Singapore","Etc/GMT-8"]},{value:"W. Australia Standard Time",abbr:"WAST",offset:8,isdst:!1,text:"(UTC+08:00) Perth",utc:["Antarctica/Casey","Australia/Perth"]},{value:"Taipei Standard Time",abbr:"TST",offset:8,isdst:!1,text:"(UTC+08:00) Taipei",utc:["Asia/Taipei"]},{value:"Ulaanbaatar Standard Time",abbr:"UST",offset:8,isdst:!1,text:"(UTC+08:00) Ulaanbaatar",utc:["Asia/Choibalsan","Asia/Ulaanbaatar"]},{value:"North Asia East Standard Time",abbr:"NAEST",offset:8,isdst:!1,text:"(UTC+08:00) Irkutsk",utc:["Asia/Irkutsk"]},{value:"Japan Standard Time",abbr:"JST",offset:9,isdst:!1,text:"(UTC+09:00) Osaka, Sapporo, Tokyo",utc:["Asia/Dili","Asia/Jayapura","Asia/Tokyo","Etc/GMT-9","Pacific/Palau"]},{value:"Korea Standard Time",abbr:"KST",offset:9,isdst:!1,text:"(UTC+09:00) Seoul",utc:["Asia/Pyongyang","Asia/Seoul"]},{value:"Cen. Australia Standard Time",abbr:"CAST",offset:9.5,isdst:!1,text:"(UTC+09:30) Adelaide",utc:["Australia/Adelaide","Australia/Broken_Hill"]},{value:"AUS Central Standard Time",abbr:"ACST",offset:9.5,isdst:!1,text:"(UTC+09:30) Darwin",utc:["Australia/Darwin"]},{value:"E. Australia Standard Time",abbr:"EAST",offset:10,isdst:!1,text:"(UTC+10:00) Brisbane",utc:["Australia/Brisbane","Australia/Lindeman"]},{value:"AUS Eastern Standard Time",abbr:"AEST",offset:10,isdst:!1,text:"(UTC+10:00) Canberra, Melbourne, Sydney",utc:["Australia/Melbourne","Australia/Sydney"]},{value:"West Pacific Standard Time",abbr:"WPST",offset:10,isdst:!1,text:"(UTC+10:00) Guam, Port Moresby",utc:["Antarctica/DumontDUrville","Etc/GMT-10","Pacific/Guam","Pacific/Port_Moresby","Pacific/Saipan","Pacific/Truk"]},{value:"Tasmania Standard Time",abbr:"TST",offset:10,isdst:!1,text:"(UTC+10:00) Hobart",utc:["Australia/Currie","Australia/Hobart"]},{value:"Yakutsk Standard Time",abbr:"YST",offset:9,isdst:!1,text:"(UTC+09:00) Yakutsk",utc:["Asia/Chita","Asia/Khandyga","Asia/Yakutsk"]},{value:"Central Pacific Standard Time",abbr:"CPST",offset:11,isdst:!1,text:"(UTC+11:00) Solomon Is., New Caledonia",utc:["Antarctica/Macquarie","Etc/GMT-11","Pacific/Efate","Pacific/Guadalcanal","Pacific/Kosrae","Pacific/Noumea","Pacific/Ponape"]},{value:"Vladivostok Standard Time",abbr:"VST",offset:11,isdst:!1,text:"(UTC+11:00) Vladivostok",utc:["Asia/Sakhalin","Asia/Ust-Nera","Asia/Vladivostok"]},{value:"New Zealand Standard Time",abbr:"NZST",offset:12,isdst:!1,text:"(UTC+12:00) Auckland, Wellington",utc:["Antarctica/McMurdo","Pacific/Auckland"]},{value:"UTC+12",abbr:"U",offset:12,isdst:!1,text:"(UTC+12:00) Coordinated Universal Time+12",utc:["Etc/GMT-12","Pacific/Funafuti","Pacific/Kwajalein","Pacific/Majuro","Pacific/Nauru","Pacific/Tarawa","Pacific/Wake","Pacific/Wallis"]},{value:"Fiji Standard Time",abbr:"FST",offset:12,isdst:!1,text:"(UTC+12:00) Fiji",utc:["Pacific/Fiji"]},{value:"Magadan Standard Time",abbr:"MST",offset:12,isdst:!1,text:"(UTC+12:00) Magadan",utc:["Asia/Anadyr","Asia/Kamchatka","Asia/Magadan","Asia/Srednekolymsk"]},{value:"Kamchatka Standard Time",abbr:"KDT",offset:13,isdst:!0,text:"(UTC+12:00) Petropavlovsk-Kamchatsky - Old",utc:["Asia/Kamchatka"]},{value:"Tonga Standard Time",abbr:"TST",offset:13,isdst:!1,text:"(UTC+13:00) Nuku'alofa",utc:["Etc/GMT-13","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Tongatapu"]},{value:"Samoa Standard Time",abbr:"SST",offset:13,isdst:!1,text:"(UTC+13:00) Samoa",utc:["Pacific/Apia"]}].filter(e=>e.utc.length).reduce((e,s)=>{let t=s.utc;for(let a=0;a<t.length;a++){const r=t[a],n=s.text;let i=n.substring(n.indexOf("(")+1,n.indexOf(")"));-1!==i.indexOf("UTC")&&e.push({value:r,abbr:s.abbr,offset:s.offset,isdst:s.isdst,text:`(${i}) ${r}`,utc:["Etc/GMT-13","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Tongatapu"]})}return e},[]).filter((e,s,t)=>s===t.findIndex(s=>s.value===e.value));function Rn({value:s,onChange:t}){const{t:a}=ds(),r=Un.map(e=>({value:e.value,label:e.text}));return e.jsx(wn,{options:r,value:s,onChange:t,placeholder:a("dropdowns.searchTimezone"),emptyLabel:a("dropdowns.chooseTimezone")})}const Mn=({workspace:t})=>{const{t:a}=ds(),{updateUserProfile:r,getProfile:n}=pi(),[i,o]=s.useState(!1),[c,l]=s.useState(),[d,u]=s.useState(0),p=Ar(),g=h.z.object({name:h.z.string().min(2,{message:a("profile.nameMinLength")}),country:h.z.string().optional(),timezone:h.z.string().optional(),language:h.z.string().optional(),currency:h.z.string().optional()}),f=m.useForm({resolver:Fr(g),defaultValues:{name:c?.name||"",country:c?.country||"",timezone:c?.timezone||"",language:c?.language||"",currency:c?.currency||""}});return s.useEffect(()=>{n().then(e=>{l(e),f.setValue("name",e.name),f.setValue("country",e.country),f.setValue("timezone",e.timezone),f.setValue("language",e.language),f.setValue("currency",e.currency)})},[d]),c?e.jsxs("div",{children:[p.message&&e.jsxs("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-4",children:[e.jsx("p",{className:"font-medium",children:a("settings.common.success")}),e.jsx("p",{className:"text-sm",children:p.message})]}),e.jsx("div",{className:"space-y-4",children:e.jsx(Lr,{...f,children:e.jsxs("form",{onSubmit:f.handleSubmit(async function(e){o(!0),p.clear();try{await r({name:e.name,country:e.country,timezone:e.timezone,language:e.language,currency:e.currency}),p.show(a("profile.success"))}catch(e){z(e,{component:"WorkspaceSettingsProfile",action:"updateUserProfile",metadata:{workspaceId:t._id}})}finally{o(!1)}}),className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:a("profile.email")}),e.jsx(Yr,{disabled:!0,className:"w-full border rounded px-3 py-2 bg-gray-100",value:c?.email})]}),e.jsx(Gr,{disabled:i,control:f.control,name:"name",render:({field:s})=>e.jsxs(zr,{children:[e.jsx($r,{children:a("profile.name")}),e.jsx(qr,{children:e.jsx(Yr,{...s})}),e.jsx(Jr,{})]})}),e.jsxs("div",{className:"flex gap-y-2 my-4 flex-col",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("div",{className:"text-sm font-medium",children:a("profile.language")}),e.jsx(In,{value:f.watch("language"),onChange:e=>{f.setValue("language",e)}})]}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("div",{className:"text-sm font-medium",children:a("profile.country")}),e.jsx(kn,{value:f.watch("country"),onChange:e=>{f.setValue("country",e)}})]}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("div",{className:"text-sm font-medium",children:a("profile.currency")}),e.jsx(Tn,{value:f.watch("currency"),onChange:e=>{f.setValue("currency",e)}})]}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("div",{className:"text-sm font-medium",children:a("profile.timezone")}),e.jsx(Rn,{value:f.watch("timezone"),onChange:e=>{f.setValue("timezone",e)}})]})]}),e.jsxs("div",{className:"flex justify-end gap-x-2",children:[e.jsx(Pa,{type:"submit",progress:i,disabled:i,children:a("profile.save")}),e.jsx(Pa,{type:"button",variant:"outline",onClick:()=>{u(e=>e+1)},disabled:i,children:a("profile.reset")})]})]})})}),c?.image&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:a("profile.profileImage")}),e.jsx("div",{className:"w-16 h-16 rounded-full overflow-hidden",children:e.jsx("img",{src:c.image,alt:c.name,className:"w-full h-full object-cover"})})]})]}):e.jsx(or,{})},Dn=(e,s)=>{const t=new Date(e);return Number.isNaN(t.getTime())?"":new Intl.DateTimeFormat(s,{dateStyle:"medium"}).format(t)},Wn=()=>{const{t:t,formattingLocale:a}=ds(),{api:r}=Us(),[i,o]=s.useState(!0),[c,l]=s.useState([]),[d,u]=s.useState(null),[m,p]=s.useState(null),[h,g]=s.useState(""),f=s.useCallback(async()=>{try{const e=await r.getPasskeys();l(e)}catch(e){z(e,{component:"WorkspaceSettingsSecurity"})}finally{o(!1)}},[r]);return s.useEffect(()=>{f()},[f]),i?e.jsx(or,{}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-medium",children:t("security.passkeysTitle")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t("security.passkeysDescription")})]}),0===c.length?e.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-md border border-dashed p-6 text-center",children:[e.jsx(n.KeyRound,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t("security.noPasskeys")})]}):e.jsx("div",{className:"space-y-2",children:c.map(s=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border p-3 "+(!1===s.active?"opacity-70":""),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(n.KeyRound,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("div",{className:"min-w-0",children:m===s.id?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yr,{value:h,onChange:e=>g(e.target.value),placeholder:t("security.renamePlaceholder"),className:"h-8"}),e.jsx(Pa,{size:"icon",variant:"ghost",className:"h-8 w-8 shrink-0",disabled:d===s.id,onClick:()=>async function(e){const s=h.trim();if(s){u(e);try{await r.renamePasskey(e,s),l(t=>t.map(t=>t.id===e?{...t,name:s}:t)),p(null)}catch(e){z(e,{component:"WorkspaceSettingsSecurity"})}finally{u(null)}}}(s.id),children:e.jsx(n.Check,{className:"h-4 w-4"})}),e.jsx(Pa,{size:"icon",variant:"ghost",className:"h-8 w-8 shrink-0",onClick:()=>p(null),children:e.jsx(n.X,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:s.name}),!1===s.active&&e.jsx("span",{className:"shrink-0 rounded-full border border-amber-300 bg-amber-50 px-2 py-0.5 text-[10px] font-medium text-amber-700",title:t("security.inactiveHint"),children:t("security.inactive")})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:!1===s.active?t("security.inactiveHint"):s.lastUsedAt?`${t("security.lastUsed")}: ${Dn(s.lastUsedAt,a)}`:s.createdAt?`${t("security.added")}: ${Dn(s.createdAt,a)}`:null})]})})]}),m!==s.id&&e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(Pa,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":t("security.rename"),onClick:()=>{p(s.id),g(s.name)},children:e.jsx(n.Pencil,{className:"h-4 w-4"})}),e.jsxs(hr,{children:[e.jsx(gr,{asChild:!0,children:e.jsx(Pa,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive","aria-label":t("security.remove"),disabled:d===s.id,children:e.jsx(n.Trash2,{className:"h-4 w-4"})})}),e.jsxs(br,{children:[e.jsxs(yr,{children:[e.jsx(wr,{children:t("security.removeTitle")}),e.jsx(Sr,{children:t("security.removeDescription")})]}),e.jsxs(vr,{children:[e.jsx(jr,{children:t("settings.common.cancel")}),e.jsx(Nr,{onClick:()=>async function(e){u(e);try{await r.deletePasskey(e),l(s=>s.filter(s=>s.id!==e))}catch(e){z(e,{component:"WorkspaceSettingsSecurity"})}finally{u(null)}}(s.id),children:t("security.remove")})]})]})]})]})]},s.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("security.addHint")})]})};function Fn(e,s){if(null==e)return null;const t=e[s??"monthly"];return t?{included:t.included,...void 0!==t.overage&&{overage:t.overage},...void 0!==t.unitSize&&{unitSize:t.unitSize},allowOverage:!1!==e.allowOverage}:null}function _n(e,s,t={}){if(null==e)return null;const{overageInCents:a=!0,currency:r,locale:n="en"}=t,{included:i,overage:o}=e;if(!(!1!==e.allowOverage))return{included:i,hasOverage:!1,allowOverage:!1,price:"",unit:""};if(null==o)return{included:i,hasOverage:!1,allowOverage:!0,price:"",unit:""};const c=a?o/100:o,l=(r??"").trim().toUpperCase();let d;if(l&&"number"==typeof c&&Number.isFinite(c))try{d=new Intl.NumberFormat(n,{style:"currency",currency:l,minimumFractionDigits:2}).format(c)}catch{d=`${t.currencySymbol??ar(r??"")}${c.toFixed(2)}`}else{d=`${t.currencySymbol??ar(r??"")}${"number"==typeof c?c.toFixed(2):String(o)}`}return{included:i,hasOverage:!0,allowOverage:!0,price:d,unit:s&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(n)} ${s}`:s||""}}const On={Personal:"personal"},Ln=(e,s,t="en-US")=>{const a=(s??"").trim();return a?new Intl.NumberFormat(t,{style:"currency",currency:a.toUpperCase(),minimumFractionDigits:2}).format(e/100):(e/100).toFixed(2)},Bn=e=>{switch(e){case Yt:return"bg-green-100 text-green-800";case Jt:return"bg-yellow-100 text-yellow-800";case Ht:return"bg-gray-100 text-gray-800";case Zt:return"bg-red-100 text-red-800";default:return"bg-gray-100 text-gray-800"}},Gn=({workspaceId:s,hasActiveSubscription:t=!1,onViewPricingPlans:a,limit:r=20})=>{const{t:i,formattingLocale:o}=ds(),{can:c}=Xa(),l=c(Ha.WORKSPACE_BILLING_VIEW),{invoices:d,loading:u,error:m,refetch:p}=Ls(s,r);if(!l)return e.jsx(nr,{});const h=d.length>0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:i("invoices.title")}),e.jsx("p",{className:"text-sm text-gray-600",children:i("invoices.description")})]}),e.jsx(Pa,{variant:"ghost",size:"sm",progress:u,onClick:p,disabled:u,children:i("settings.common.refreshAction",{loading:String(u)})})]}),m&&e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:i("invoices.errorLoading")}),e.jsx("p",{className:"text-sm mt-1",children:m})]}),e.jsx(Pa,{variant:"outline",size:"sm",onClick:p,disabled:u,className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:i("settings.common.retryAction",{loading:String(u)})})]}),u&&!h?e.jsx("div",{className:"border rounded-lg p-6",children:e.jsx(or,{})}):h?e.jsx("div",{className:"space-y-2",children:d.map(s=>{const t=(e=>{switch(e.status){case Ht:case Jt:return{textKey:"invoices.pay",color:"bg-blue-600 hover:bg-blue-700"};case Yt:return{textKey:"invoices.view",color:"bg-green-600 hover:bg-green-700"};case Zt:case Qt:return{textKey:"invoices.viewDetails",color:"bg-gray-600 hover:bg-gray-700"};default:return{textKey:"invoices.view",color:"bg-gray-600 hover:bg-gray-700"}}})(s);return e.jsxs("div",{className:"border rounded-lg bg-white hover:shadow-sm transition-shadow p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900 truncate min-w-0",children:s.description||s.number||s.id.slice(-8)}),e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium shrink-0 ${Bn(s.status)}`,children:i(`invoices.status.${s.status}`)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-0.5 text-sm text-gray-600 mb-2.5",children:[e.jsx("span",{className:"font-medium text-gray-900",children:Ln(s.amount_due,s.currency,o)}),s.created&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-gray-300 hidden sm:inline",children:"·"}),e.jsx("span",{children:dr(s.created,o)})]}),s.amount_paid>0&&s.amount_due>0&&e.jsx("span",{className:"text-xs text-gray-500",children:i("invoices.paidAmount",{amount:Ln(s.amount_paid,s.currency,o)})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Pa,{size:"sm",disabled:!s.hosted_invoice_url,onClick:()=>s.hosted_invoice_url&&window.open(s.hosted_invoice_url,"_blank","noopener,noreferrer"),className:t.color,children:[i(t.textKey),e.jsx(n.ExternalLink,{className:"h-3 w-3 ms-1.5"})]}),s.invoice_pdf&&e.jsxs(Pa,{size:"sm",variant:"outline",onClick:()=>window.open(s.invoice_pdf,"_blank","noopener,noreferrer"),children:[e.jsx(n.Download,{className:"h-3 w-3 me-1.5"}),i("invoices.download")]})]})]},s.id)})}):e.jsxs("div",{className:"border rounded-lg p-6 text-center",children:[e.jsx(n.FileText,{className:"h-12 w-12 mx-auto text-gray-400 mb-3"}),e.jsx("p",{className:"text-sm text-gray-500",children:i(t?"invoices.noInvoicesWithSub":"invoices.noInvoices")}),!t&&a&&e.jsx(Pa,{size:"sm",className:"mt-4",onClick:a,children:i("subscription.viewPricingPlans")})]})]})},Kn=s.lazy(()=>Promise.resolve().then(function(){return require("./SubscriptionDialog-A6oETKbb.cjs")}).then(e=>({default:e.default}))),Vn=(e,s)=>{if(!s)return"";try{const t=new Date(s);return isNaN(t.getTime())?"":new Intl.DateTimeFormat(e,{month:"long",day:"numeric",year:"numeric"}).format(t)}catch{return""}},zn=({workspace:t})=>{const a=t._id?.toString(),{t:r,formattingLocale:i,fmtNum:o,fmtCents:c}=ds(),{api:l}=Us(),{can:d}=Xa(),{settings:u}=Is(),m=d(Ha.WORKSPACE_BILLING_VIEW),p=d(Ha.WORKSPACE_BILLING_MANAGE),h=u?.workspace?.mode===On.Personal,{subscription:g,loading:f,error:x,updateSubscription:b,refetch:y}=Os(a),{createCheckoutSession:v}=Fs(a),{cancelSubscription:w,loading:S}=Gs(a),{resumeSubscription:N,loading:j}=Ks(a),{openBillingPortal:k,loading:C}=Bs(a),{versions:A,loading:T,error:E,refetch:P}=Ws(a),I=f||T,U=x||E,{currentVersion:R,latestVersion:M,isDeprecated:D,plansToShow:W}=s.useMemo(()=>{const e=A?.currentVersion,s=A?.availableVersions||[],t=null!=g?.subscription;let a=null;s.length>0?a=s.reduce((e,s)=>s.version>e.version?s:e):e&&(a=e);const r=!!(t&&a&&e)&&a.version>e.version;return{currentVersion:e,latestVersion:a,hasNewerVersion:r,isDeprecated:r&&t,plansToShow:a?.plans&&a.plans.length>0?a.plans:[]}},[A,g?.subscription]),[F,_]=s.useState(!1),[O,L]=s.useState(null),[B,G]=s.useState(null),K=s.useRef(null),[V,z]=s.useState(!1),[$,q]=s.useState(!1),H=s.useRef(void 0),J=s.useRef(!1);s.useEffect(()=>{if(J.current)return;if(f||!W||0===W.length)return;const e=mi.getState(),s=e.params?.action===Pt;g?.subscription&&!s||(J.current=!0,s&&(H.current=e.params,mi.clearParams()),z(!0))},[f,g?.subscription,W]),s.useEffect(()=>()=>{K.current&&clearTimeout(K.current)},[]);const[Y,Z]=s.useState(!1),[Q,X]=s.useState("subscription"),ee=async()=>{await Promise.all([y(),P()])},se=s.useMemo(()=>ha(g?.subscription?.stripePriceId,W??[]),[g?.subscription?.stripePriceId,W]),te=async()=>{if(a){q(!1),_(!0),L(null),G(null);try{await w(),G(r("subscription.cancelSuccess")),await ee()}catch(e){const s=e instanceof Error?e.message:r("subscription.errorCanceling");L(s)}finally{_(!1),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{L(null),G(null)},5e3)}}};if(I&&!g&&!A)return e.jsx(or,{});if(!m)return null;const ae=g?.planVersion?._id||null;return a?e.jsxs("div",{className:"space-y-6",children:[U&&e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r("subscription.errorLoading")}),e.jsx("p",{className:"text-sm mt-1",children:U}),e.jsx("p",{className:"text-xs mt-2 text-red-600",children:r("subscription.errorLoadingDescription")})]}),e.jsx(Pa,{variant:"outline",size:"sm",onClick:ee,disabled:I,className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:r("settings.common.retryAction",{loading:String(I)})})]}),O&&e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r("subscription.updateFailed")}),e.jsx("p",{className:"text-sm mt-1",children:O})]}),e.jsx(Pa,{variant:"outline",size:"sm",onClick:()=>L(null),className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:r("settings.common.dismiss")})]}),B&&e.jsxs("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r("settings.common.success")}),e.jsx("p",{className:"text-sm mt-1",children:B})]}),e.jsx(Pa,{variant:"outline",size:"sm",onClick:()=>G(null),className:"flex-shrink-0 border-green-200 text-green-700 hover:bg-green-100",children:r("settings.common.dismiss")})]}),e.jsx("div",{className:"border-b border-gray-200",children:e.jsxs("nav",{className:"-mb-px flex gap-6","aria-label":"Subscription tabs",children:[e.jsx("button",{type:"button",onClick:()=>X("subscription"),className:"border-b-2 py-3 text-sm font-medium transition-colors "+("subscription"===Q?"border-primary text-primary":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700"),children:r("subscription.plan")}),e.jsx("button",{type:"button",onClick:()=>X("invoices"),className:"border-b-2 py-3 text-sm font-medium transition-colors "+("invoices"===Q?"border-primary text-primary":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700"),children:r("subscription.invoicesTab")})]})}),"subscription"===Q&&e.jsxs(e.Fragment,{children:[I&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-600",children:[e.jsx(n.Loader2,{className:"h-4 w-4 animate-spin flex-shrink-0"}),e.jsx("span",{children:r("settings.common.loading")})]}),D&&g?.subscription&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg px-4 py-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(n.AlertTriangle,{className:"h-4 w-4 text-amber-600 shrink-0"}),e.jsxs("span",{className:"text-sm text-amber-800",children:[e.jsx("span",{className:"font-medium",children:r("subscription.planUpdateAvailable")}),e.jsxs("span",{className:"text-amber-600",children:[" ","— v",R?.version||"?"," → v",M?.version||"?"]})]})]}),e.jsx(Pa,{size:"sm",variant:"outline",className:"shrink-0 border-amber-300 text-amber-700 hover:bg-amber-100",onClick:()=>z(!0),children:r("subscription.viewPlans")})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsx("p",{className:"text-sm text-gray-600",children:r("subscription.managePlan")})}),e.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const s=g?.subscription?.subscriptionStatus===zt,t=g?.subscription?.cancelAtPeriodEnd;return t||S?null:s&&W&&W.length>0?e.jsx(Pa,{size:"sm",onClick:()=>z(!0),children:r("subscription.viewPricingPlans")}):g?.subscription&&!s&&p?e.jsx(Pa,{variant:"outline",size:"sm",onClick:()=>z(!0),children:r("subscription.changePlanButton")}):!g?.subscription&&W&&W.length>0?e.jsx(Pa,{size:"sm",onClick:()=>z(!0),children:r("subscription.viewPricingPlans")}):null})(),e.jsx(Pa,{variant:"ghost",size:"sm",progress:I,onClick:ee,disabled:I||F,children:r("settings.common.refreshAction",{loading:String(I)})})]})]}),g?.subscription?(()=>{const s=ha(g.subscription.stripePriceId,W??[]),a=s?.interval??null,l=s?.currency??g.plan?.currency??t?.billingCurrency??"",d=a&&g.planVersion?ua(g.planVersion,l,a):null,u=l,m=g.planVersion?ga(g.planVersion,l):null,f=m&&a?fa(g.planVersion,l,a):null,x=Array.isArray(t?.users)?t.users.length:1,b=m?.includedSeats??0,y=Math.max(0,x-b),v=!!g.plan?.isFreemium,w=null!=d?0===d?r("subscription.free"):c(d,u):v?r("subscription.free"):null,N=a===Gt.Monthly?r("subscription.billingInterval.perMonth"):a===Gt.Quarterly?r("subscription.billingInterval.perQuarter"):a===Gt.Yearly?r("subscription.billingInterval.perYear"):"";return e.jsxs("div",{className:"border rounded-lg overflow-hidden "+(D?"border-amber-300":"border-gray-200"),children:[g.subscription.subscriptionStatus===Vt&&!g.subscription.cancelAtPeriodEnd&&(()=>{const s=g.subscription.trialEnd||g.subscription.stripeCurrentPeriodEnd,t=s?new Date(s):null,a=t&&!isNaN(t.getTime())?t:null,n=a?Math.max(0,Math.ceil((a.getTime()-Date.now())/864e5)):null,i=null!==n&&n<=3;return e.jsxs("div",{className:"px-4 py-3 sm:px-5 text-sm flex flex-col sm:flex-row sm:items-center justify-between gap-2 "+(i?"bg-amber-50 text-amber-800 border-b border-amber-200":"bg-blue-50 text-blue-800 border-b border-blue-200"),children:[e.jsxs("span",{children:[null!==n&&n<=0?r("subscription.trialEnded"):null!==n?r("subscription.trialEndsIn",{days:n}):r("subscription.onTrial")," ",r("subscription.upgradeToKeepAccess")]}),e.jsx(Pa,{size:"sm",variant:i?"default":"outline",className:"shrink-0 "+(i?"":"border-blue-300 text-blue-700 hover:bg-blue-100"),onClick:()=>z(!0),children:r("subscription.upgradePlan")})]})})(),e.jsxs("div",{className:"p-4 sm:p-5 "+(D?"bg-amber-50/50":"bg-gray-50/50"),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:g.plan?.name||r("subscription.noPlanAssigned")}),e.jsxs("span",{className:"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium "+(g.subscription.subscriptionStatus===Kt?g.subscription.cancelAtPeriodEnd?"bg-amber-100 text-amber-800":"bg-green-100 text-green-800":g.subscription.subscriptionStatus===Vt?"bg-blue-100 text-blue-800":g.subscription.subscriptionStatus===zt?"bg-gray-100 text-gray-800":"bg-red-100 text-red-800"),children:[g.subscription.subscriptionStatus===Kt&&(g.subscription.cancelAtPeriodEnd?r("subscription.status.canceling"):r("subscription.status.active")),g.subscription.subscriptionStatus===Vt&&r("subscription.status.trial"),g.subscription.subscriptionStatus===zt&&r("subscription.status.canceled"),g.subscription.subscriptionStatus===$t&&r("subscription.status.pastDue")]}),g.subscription.subscriptionStatus===Vt&&Vn(i,g.subscription.trialEnd||g.subscription.stripeCurrentPeriodEnd)&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(ends"," ",Vn(i,g.subscription.trialEnd||g.subscription.stripeCurrentPeriodEnd),")"]}),D&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800",children:[e.jsx(n.AlertTriangle,{className:"h-3 w-3"}),r("subscription.status.deprecated")]})]}),g.plan?.description&&e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:g.plan.description}),!v&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline gap-1 whitespace-nowrap",children:[e.jsx("span",{className:"text-2xl font-bold text-gray-900",children:w||r("invoices.na")}),w&&w!==r("subscription.free")&&N&&e.jsx("span",{className:"text-sm text-gray-500",children:N})]}),m&&f&&f>0&&!h&&e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:r("subscription.perSeatDisplay",{price:c(f,u),interval:N})}),!h&&m&&f&&f>0&&y>0&&w&&w!==r("subscription.free")&&null!=d&&e.jsx("div",{className:"text-xs text-gray-500 mt-1 pt-1 border-t border-gray-200",children:r("subscription.estTotalDisplay",{total:c(d+f*y,u),interval:N,count:y})})]}),(g.subscription.subscriptionStatus===Kt||g.subscription.subscriptionStatus===Vt)&&!g.subscription.cancelAtPeriodEnd&&Vn(i,g.subscription.stripeCurrentPeriodEnd)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx(n.Calendar,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{children:r("subscription.nextBillingDisplay",{date:Vn(i,g.subscription.stripeCurrentPeriodEnd)??""})})]})]}),D&&e.jsxs("p",{className:"text-xs text-amber-600 mt-2",children:["Version ",R?.version||r("invoices.na")]}),!v&&(g.subscription.subscriptionStatus===Kt||g.subscription.subscriptionStatus===Vt||g.subscription.subscriptionStatus===$t)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mt-4 pt-4 border-t border-gray-200",children:[g.subscription&&p&&g.subscription?.subscriptionId&&e.jsx(Pa,{variant:"outline",size:"sm",onClick:()=>k(),disabled:C,progress:C,children:r(C?"subscription.openingPortal":"subscription.managePayment")}),p&&g.subscription?.subscriptionId&&(g.subscription.subscriptionStatus===Kt||g.subscription.subscriptionStatus===Vt)&&e.jsx(e.Fragment,{children:g.subscription.cancelAtPeriodEnd?e.jsx(Pa,{variant:"outline",size:"sm",onClick:()=>Z(!0),disabled:F||S||j,progress:j,children:g.subscription.subscriptionStatus===Vt?r("subscription.resumeTrial"):r("subscription.resumeTitle")}):e.jsx(Pa,{variant:"outline",size:"sm",className:"text-red-600 hover:text-red-700 hover:bg-red-50 border-red-200",onClick:()=>q(!0),disabled:F||S||j,progress:S||F,children:S||F?r("subscription.canceling"):g.subscription.subscriptionStatus===Vt?r("subscription.cancelTrial"):r("subscription.cancelTitle")})})]})]}),g.subscription.subscriptionStatus===$t&&e.jsx("div",{className:"px-5 py-3 bg-red-50 border-t border-red-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(n.AlertTriangle,{className:"h-5 w-5 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-red-800",children:r("subscription.paymentPastDue")}),e.jsx("p",{className:"text-sm text-red-700 mt-0.5",children:r("subscription.paymentPastDueDescription")}),e.jsx(Pa,{variant:"outline",size:"sm",className:"mt-2 border-red-200 text-red-700 hover:bg-red-100",onClick:()=>X("invoices"),children:r("subscription.viewInvoices")})]})]})}),g.subscription.subscriptionStatus===$t&&g.subscription.dunningState&&g.subscription.dunningState!==ea&&e.jsx("div",{className:"px-5 py-3 bg-red-50 border-t border-red-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(n.AlertTriangle,{className:"h-5 w-5 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-red-800",children:g.subscription.dunningState===sa?r("subscription.dunningFinal"):g.subscription.dunningState===ta?r("subscription.dunningSuspended"):r("subscription.dunningRecovery")}),e.jsx("p",{className:"text-sm text-red-700 mt-0.5",children:g.subscription.dunningState===ta?r("subscription.dunningSuspendedDescription"):r("subscription.dunningRecoveryDescription")})]})]})}),g.subscription.subscriptionStatus===qt&&e.jsx("div",{className:"px-5 py-3 bg-blue-50 border-t border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(n.Calendar,{className:"h-5 w-5 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-blue-800",children:r("subscription.subscriptionPaused")}),e.jsx("p",{className:"text-sm text-blue-700 mt-0.5",children:r("subscription.subscriptionPausedDescription")})]})]})}),g.subscription.cancelAtPeriodEnd&&e.jsx("div",{className:"px-5 py-3 bg-amber-50 border-t border-amber-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(n.Calendar,{className:"h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-amber-800",children:g.subscription.subscriptionStatus===Vt?r("subscription.scheduledTrialCancellation"):r("subscription.scheduledCancellation")}),e.jsx("p",{className:"text-sm text-amber-700 mt-0.5",children:Vn(i,g.subscription.subscriptionStatus===Vt&&g.subscription.trialEnd||g.subscription.stripeCurrentPeriodEnd)?e.jsxs(e.Fragment,{children:[g.subscription.subscriptionStatus===Vt?r("subscription.trialEndDescription"):r("subscription.cancelEndDescription")," ",e.jsx("span",{className:"font-medium",children:Vn(i,g.subscription.subscriptionStatus===Vt&&g.subscription.trialEnd||g.subscription.stripeCurrentPeriodEnd)}),"."]}):r("subscription.cancelEndFallback")})]})]})}),g.planVersion&&(()=>{const s=((e,s,t=Gt.Monthly)=>{if(!e?.subscriptionItems)return{features:[],limits:[],quotas:[]};const a=[],r=[],n=[];return e.subscriptionItems.forEach(i=>{const o=i.slug;if(i.type===Xt.Feature){const s=e.features?.[o]??!1;a.push({item:i,enabled:s})}else if(i.type===Xt.Limit){const s=e.limits?.[o]??0;r.push({item:i,value:s})}else if(i.type===Xt.Quota){const a=s&&e.pricingVariants?.length?pa(e,s,o,t):Fn(e.quotas?.[o],t);null!=a&&n.push({item:i,value:a})}}),{features:a,limits:r,quotas:n}})(g.planVersion,l,a??"monthly");return s.features.length>0||s.limits.length>0||s.quotas.length>0?e.jsx("div",{className:"px-4 py-4 sm:px-5 sm:py-5 border-t border-gray-100",children:e.jsxs("div",{className:"space-y-5",children:[s.features.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:r("subscription.items.features")}),e.jsx("ul",{className:"space-y-1.5",children:s.features.sort(e=>e.enabled?-1:1).map(({item:s,enabled:t})=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"w-4 text-center shrink-0 "+(t?"text-green-500":"text-gray-300"),children:t?"✓":"✕"}),e.jsx("span",{className:t?"text-gray-700":"text-gray-400",children:s.name})]},s._id))})]}),s.limits.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:r("subscription.items.limits")}),e.jsx("ul",{className:"space-y-1.5",children:s.limits.map(({item:s,value:t})=>e.jsxs("li",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:s.name}),e.jsx("span",{className:"font-medium text-gray-900",children:o(t)})]},s._id))})]}),s.quotas.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:r("subscription.items.quotas")}),e.jsx("ul",{className:"space-y-1.5",children:s.quotas.map(({item:s,value:t})=>{const a=_n(t,s.name.toLowerCase(),{currency:l,locale:i}),n=a?a.hasOverage?r("quota.includedWithOverage",{count:a.included,price:a.price,unit:a.unit}):r("quota.includedOnly",{count:a.included}):"—";return e.jsx("li",{className:"text-sm",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-0.5",children:[e.jsx("span",{className:"text-gray-600",children:s.name}),e.jsx("span",{className:"font-medium text-gray-900 text-xs sm:text-sm",children:n})]})},s._id)})})]}),m&&!h&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:r("subscription.seats.title")}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:r("subscription.seats.members")}),e.jsx("span",{className:"font-semibold text-gray-900",children:o(x)})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:r("subscription.seats.included")}),e.jsx("span",{className:"text-gray-900",children:o(b)})]}),y>0&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:r("subscription.seats.billable")}),e.jsxs("span",{className:"font-medium text-amber-600",children:[o(y)," ",r("subscription.seats.extra")]})]}),f&&f>0&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:r("subscription.seats.perExtraSeat")}),e.jsxs("span",{className:"text-gray-900",children:[c(f,l),N]})]}),(m?.maxSeats??0)>0&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:r("subscription.seats.limit")}),e.jsx("span",{className:"text-gray-900",children:o(m.maxSeats)})]})]})]}),g.planVersion?.creditGrant?.enabled&&"object"==typeof g.planVersion.creditGrant.creditPackage&&null!==g.planVersion.creditGrant.creditPackage&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:r("subscription.items.credits")}),e.jsxs("div",{className:"bg-purple-50 rounded-lg p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:g.planVersion.creditGrant.renewOnPeriod?r("subscription.items.creditsPerMonth"):r("subscription.items.creditsOneTime")}),e.jsx("span",{className:"font-semibold text-purple-700",children:o("object"==typeof g.planVersion.creditGrant.creditPackage?g.planVersion.creditGrant.creditPackage.creditAmount:0)})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:r("subscription.items.creditRenewal")}),e.jsx("span",{className:"font-medium text-gray-900",children:g.planVersion.creditGrant.renewOnPeriod?"reset"===g.planVersion.creditGrant.mode?r("subscription.items.creditModeReset"):r("subscription.items.creditModeTopup"):r("subscription.items.creditModeLifetime")})]})]})]})]})}):null})()]})})():e.jsxs("div",{className:"border rounded-lg p-6 text-center",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx(n.CreditCard,{className:"h-12 w-12 mx-auto text-gray-400 mb-3"}),e.jsx("p",{className:"text-lg font-medium text-gray-700",children:r("subscription.noSubscription")}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:r("subscription.noSubscriptionDescription")})]}),W&&W.length>0&&e.jsx(Pa,{size:"sm",onClick:()=>z(!0),children:r("subscription.viewPricingPlans")})]})]}),!A&&!I&&e.jsxs("div",{className:"border rounded-lg p-4 text-center",children:[e.jsxs("div",{className:"text-gray-500 mb-2",children:[e.jsx("p",{className:"font-medium",children:r("subscription.errorLoading")}),U&&e.jsxs("p",{className:"text-sm mt-2 text-red-600",children:["Error: ",U]}),!U&&e.jsx("p",{className:"text-sm mt-2",children:r("subscription.noPlansAvailable")})]}),e.jsx(Pa,{variant:"outline",size:"sm",progress:I,onClick:ee,disabled:I,className:"mt-4",children:r("settings.common.refreshAction",{loading:String(I)})})]})]}),"invoices"===Q&&e.jsxs(e.Fragment,{children:[I&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-600",children:[e.jsx(n.Loader2,{className:"h-4 w-4 animate-spin flex-shrink-0"}),e.jsx("span",{children:r("settings.common.loading")})]}),e.jsx(Gn,{workspaceId:a,hasActiveSubscription:null!==g?.subscription,onViewPricingPlans:()=>X("subscription"),limit:20})]}),W&&W.length>0&&e.jsx(s.Suspense,{fallback:V?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(n.Loader2,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:r("settings.common.loading")})]})}):null,children:e.jsx(Kn,{open:V,onOpenChange:z,planVersions:W,currentPlanVersionId:ae||null,currentStripePriceId:g?.subscription?.stripePriceId,billingCurrency:t.billingCurrency,trialUsedAt:t.trialUsedAt,workspaceName:t.name,initialInterval:H.current?.interval,initialCurrency:H.current?.currency,currentMemberCount:Array.isArray(t?.users)?t.users.length:void 0,onSelectPlan:async(e,s=Gt.Monthly,n)=>{if(!a)return;const i=W?.find(s=>s._id===e),o=n??se?.currency??g?.plan?.currency??t?.billingCurrency??"",c=i?function(e,s,t){const a=da(e,s);if(!a?.stripePrices)return null;const r=t===Gt.Monthly?"monthlyPriceId":t===Gt.Yearly?"yearlyPriceId":"quarterlyPriceId",n=t===Gt.Monthly?"monthly":t===Gt.Yearly?"yearly":void 0;return a.stripePrices[r]??(n?a.stripePrices[n]:void 0)??null}(i,o,s):null,d=g?.subscription?.stripePriceId;if(!c||!d||c!==d){_(!0),L(null),G(null);try{const{successUrl:t,cancelUrl:n}=function(e){const s="undefined"!=typeof window?window.location.href:void 0;return{successUrl:_t({action:Tt,status:Rt,ws:e,screen:Wt},s),cancelUrl:_t({action:Tt,status:Mt,ws:e,screen:Wt},s)}}(a);let c;if(i?.plan?.isFreemium){return g?.subscription?.subscriptionId?(z(!1),void q(!0)):(await l.selectFreePlan(a,e),z(!1),Ze(),await ee(),void G(r("subscription.updateSuccess")))}const d=g?.subscription?.subscriptionStatus===zt;if(c=g?.subscription&&!d?await b(e,{billingInterval:s,successUrl:t,cancelUrl:n}):await v({planVersionId:e,billingInterval:s,currency:o||void 0,successUrl:t,cancelUrl:n}),c&&"checkoutUrl"in c&&c.checkoutUrl)return void yt(c.checkoutUrl);G(r("subscription.updateSuccess")),await ee()}catch(e){const s=e instanceof Error?e.message:r("subscription.errorProcessing");L(s)}finally{_(!1),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{L(null),G(null)},5e3)}}},loading:F||I})}),e.jsx(hr,{open:Y,onOpenChange:Z,children:e.jsxs(br,{children:[e.jsxs(yr,{children:[e.jsx(wr,{children:r("subscription.resumeTitle")}),e.jsx(Sr,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{children:r("subscription.resumeConfirm")}),e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 space-y-2 text-sm",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(n.AlertTriangle,{className:"h-4 w-4 text-amber-600 mt-0.5 flex-shrink-0"}),e.jsxs("span",{children:[r("subscription.resumeChargeDate")," ",g?.subscription?.stripeCurrentPeriodEnd&&Vn(i,g.subscription.stripeCurrentPeriodEnd)?e.jsx("span",{className:"font-medium",children:Vn(i,g.subscription.stripeCurrentPeriodEnd)}):r("subscription.resumeChargeFallback")]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-amber-600 mt-0.5",children:"•"}),e.jsx("span",{children:r("subscription.resumeContinue")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-blue-600 mt-0.5",children:"ℹ"}),e.jsx("span",{children:r("subscription.resumeCancelAnytime")})]})]})]})})]}),e.jsxs(vr,{children:[e.jsx(jr,{disabled:j,children:r("subscription.resumeKeep")}),e.jsx(Nr,{onClick:async()=>{if(a){Z(!1),_(!0),L(null),G(null);try{await N(),G(r("subscription.resumeSuccess")),await ee()}catch(e){const s=e instanceof Error?e.message:r("subscription.errorResuming");L(s)}finally{_(!1),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{L(null),G(null)},5e3)}}},disabled:j,children:r(j?"subscription.resuming":"subscription.resumeButton")})]})]})}),(()=>{const s=g?.subscription?.subscriptionStatus===Vt,t=s&&g?.subscription?.trialEnd||g?.subscription?.stripeCurrentPeriodEnd;return e.jsx(hr,{open:$,onOpenChange:q,children:e.jsxs(br,{children:[e.jsxs(yr,{children:[e.jsx(wr,{children:r(s?"subscription.cancelTrialTitle":"subscription.cancelTitle")}),e.jsx(Sr,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{children:r(s?"subscription.cancelTrialConfirm":"subscription.cancelConfirm")}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4 space-y-2 text-sm",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-green-600 mt-0.5",children:"✓"}),e.jsxs("span",{children:[r(s?"subscription.cancelTrialAccess":"subscription.retainAccess")," ",t&&Vn(i,t)?e.jsx("span",{className:"font-medium",children:Vn(i,t)}):r("subscription.retainAccessFallback")]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-green-600 mt-0.5",children:"✓"}),e.jsx("span",{children:r(s?"subscription.cancelTrialNoCharge":"subscription.cancelNotCharged")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-blue-600 mt-0.5",children:"ℹ"}),e.jsx("span",{children:r(s?"subscription.cancelTrialResume":"subscription.cancelResumeAnytime")})]})]})]})})]}),e.jsxs(vr,{children:[e.jsx(jr,{disabled:S,children:r(s?"subscription.cancelTrialKeep":"subscription.cancelKeep")}),e.jsx(Nr,{onClick:te,disabled:S,className:"bg-red-600 hover:bg-red-700 focus:ring-red-600",children:r(S?"subscription.canceling":s?"subscription.cancelTrialButton":"subscription.cancelButton")})]})]})})})()]}):e.jsx("div",{className:"border rounded-lg p-4 text-center text-gray-500",children:e.jsx("p",{children:r("subscription.invalidWorkspace")})})};function $n(e){return e.replace(/[_-]/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function qn(e,s,t){return s+e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2})}function Hn(e){try{const s=new Date(e);if(isNaN(s.getTime()))return null;const t=new Date;return Math.ceil((s.getTime()-t.getTime())/864e5)}catch{return null}}const Jn=()=>{const{quotas:t,loading:a,error:r,refetch:i}=xt(),{t:o,formattingLocale:c,fmtNum:l}=ds(),{can:d}=Xa(),u=(e,s)=>qn(e,s,c),{response:m}=qs(),[p,h]=s.useState(!1),g=s.useMemo(()=>{const e={};if(!m?.planVersion||!m?.subscription)return e;const s=m.planVersion,a=m.subscription,r=a.billingInterval??"monthly",n=a.plan?.currency??"usd",i=ar(n);if(!t)return e;for(const a of Object.keys(t)){const o=ma(s,n,a,r);if(null==o||o<=0)continue;const c=s.quotas?.[a],l=c?.[r],d=l?.unitSize??1,u=t[a].overage,m=(d>1?Math.ceil(u/d):u)*o/100;e[a]={overageCents:o,unitSize:d,currency:n,currencySymbol:i,estimatedCost:m}}return e},[m,t]),f=s.useMemo(()=>{const e=m?.subscription?.usageCurrentPeriodEnd||m?.subscription?.stripeCurrentPeriodEnd;if(!e)return null;const s=cr(e,c);return s?{endDate:s,daysRemaining:Hn(e)}:null},[m,c]),x=async()=>{h(!0);try{await i()}finally{h(!1)}};if(a&&!t)return e.jsx(or,{});if(!d(Ha.WORKSPACE_USAGE_VIEW))return null;if(r)return e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o("usage.errorLoading")}),e.jsx("p",{className:"text-sm mt-1",children:r})]}),e.jsx(Pa,{variant:"outline",size:"sm",onClick:x,disabled:p,className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:o("settings.common.retryAction",{loading:String(p)})})]});const b=function(e){return[...e].sort(([,e],[,s])=>{if(e.hasOverage&&!s.hasOverage)return-1;if(!e.hasOverage&&s.hasOverage)return 1;const t=e.included>0?e.consumed/e.included:e.consumed>0?1:0;return(s.included>0?s.consumed/s.included:s.consumed>0?1:0)-t})}(t?Object.entries(t):[]);if(0===b.length)return e.jsxs("div",{className:"border rounded-lg p-8 text-center",children:[e.jsx(n.BarChart3,{className:"h-10 w-10 text-gray-300 mx-auto mb-3"}),e.jsx("p",{className:"text-sm text-gray-600",children:o("usage.noData")}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:o("usage.noDataHint")})]});const y=b.filter(([,e])=>e.hasOverage).length,v=b.length>0?Math.round(b.reduce((e,[,s])=>e+(s.included>0?s.consumed/s.included*100:0),0)/b.length):0,w=Object.values(g).reduce((e,s)=>e+s.estimatedCost,0),S=Object.values(g)[0]?.currencySymbol??"$";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-gray-600",children:o("usage.description")}),e.jsxs(Pa,{variant:"ghost",size:"sm",onClick:x,disabled:p,children:[e.jsx(n.RefreshCw,{className:W("h-3.5 w-3.5 me-1.5",p&&"animate-spin")}),o("settings.common.refreshAction",{loading:String(p)})]})]}),f&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50/50 px-4 py-3 text-sm text-gray-600",children:[e.jsx(n.Calendar,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{children:[o("usage.resetDateDisplay",{date:f.endDate}),null!==f.daysRemaining&&f.daysRemaining>0&&e.jsxs("span",{className:"text-gray-500",children:[" ","(",o("usage.daysRemainingDisplay",{count:f.daysRemaining}),")"]}),null!==f.daysRemaining&&f.daysRemaining<=0&&e.jsxs("span",{className:"text-amber-600 font-medium",children:[" (",o("usage.renewingSoon"),")"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 sm:gap-3",children:[e.jsxs("div",{className:"border border-gray-200 rounded-lg p-3 sm:p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:o("usage.totalResources")}),e.jsx("p",{className:"text-lg sm:text-xl font-semibold text-gray-900 mt-1",children:l(b.length)})]}),e.jsxs("div",{className:"border border-gray-200 rounded-lg p-3 sm:p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:o("usage.overallUsage")}),e.jsx("p",{className:"text-lg sm:text-xl font-semibold text-gray-900 mt-1",children:l(v)+"%"})]}),e.jsxs("div",{className:W("border rounded-lg p-3 sm:p-4",y>0?"border-red-200 bg-red-50":"border-gray-200"),children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:o("usage.inOverage")}),e.jsx("p",{className:W("text-lg sm:text-xl font-semibold mt-1",y>0?"text-red-600":"text-gray-900"),children:l(y)})]}),y>0&&w>0&&e.jsxs("div",{className:"border border-red-200 bg-red-50 rounded-lg p-3 sm:p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:o("usage.estOverageCost")}),e.jsx("p",{className:"text-lg sm:text-xl font-semibold mt-1 text-red-600",children:u(w,S)})]})]}),y>0&&e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(n.AlertTriangle,{className:"h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5 hidden sm:block"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-sm font-semibold text-amber-800 mb-1",children:o("usage.overageDetected")}),e.jsx("p",{className:"text-sm text-amber-700",children:o("usage.overageWarning",{count:y})}),w>0&&e.jsx("p",{className:"text-sm text-amber-700 font-medium mt-1",children:o("usage.estOverageCharges",{amount:u(w,S)})})]})]})}),e.jsx("div",{className:"space-y-3",children:b.map(([s,t])=>{const a=(r=t.consumed,(n=t.included)<=0?r>0?100:0:Math.min(r/n*100,100));var r,n;const i=function(e,s){return s?{bar:"bg-red-500",bg:"bg-red-100",badge:"bg-red-100",badgeText:"text-red-800"}:e>=90?{bar:"bg-amber-500",bg:"bg-amber-100",badge:"bg-amber-100",badgeText:"text-amber-800"}:e>=75?{bar:"bg-yellow-500",bg:"bg-yellow-100",badge:"bg-yellow-100",badgeText:"text-yellow-800"}:{bar:"bg-blue-500",bg:"bg-blue-100",badge:"bg-blue-100",badgeText:"text-blue-800"}}(a,t.hasOverage),o=g[s];return e.jsx(Yn,{slug:s,quota:t,percent:a,colors:i,pricing:o},s)})})]})};function Yn({slug:s,quota:t,percent:a,colors:r,pricing:n}){const{t:i,formattingLocale:o}=ds(),c=e=>function(e,s){return e>=1e6?(e/1e6).toLocaleString(s,{maximumFractionDigits:1})+"M":e>=1e3?(e/1e3).toLocaleString(s,{maximumFractionDigits:1})+"K":e.toLocaleString(s)}(e,o),l=(e,s)=>qn(e,s,o);return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-y-1 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 truncate",children:$n(s)}),t.hasOverage&&e.jsx("span",{className:W("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",r.badge,r.badgeText),children:i("usage.overage")}),!t.hasOverage&&a>=90&&e.jsx("span",{className:W("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",r.badge,r.badgeText),children:i("usage.almostFull")})]}),e.jsxs("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:[c(t.consumed)," / ",c(t.included)]})]}),e.jsx("div",{className:W("h-2 rounded-full w-full",r.bg),children:e.jsx("div",{className:W("h-2 rounded-full transition-all duration-500",r.bar),style:{width:`${a}%`}})}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-xs text-gray-500",children:[e.jsx("span",{children:i("usage.percentUsed",{percent:Math.round(a)})}),e.jsx("span",{children:t.available>0?i("usage.availableRemaining",{count:c(t.available)}):t.hasOverage?i("usage.overLimitCount",{count:c(t.overage)}):i("usage.fullyUsed")})]}),t.hasOverage&&n&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-gray-200 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-500",children:i("usage.overageUnits")}),e.jsx("span",{className:"font-medium text-gray-900",children:c(t.overage)})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-500",children:i("usage.rate")}),e.jsx("span",{className:"font-medium text-gray-900",children:i("usage.rateDisplay",{rate:l(n.overageCents/100,n.currencySymbol),unitSize:n.unitSize})})]}),n.unitSize>1&&e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-500",children:i("usage.billableBlocks")}),e.jsx("span",{className:"font-medium text-gray-900",children:c(Math.ceil(t.overage/n.unitSize))})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs pt-2 border-t border-gray-200",children:[e.jsx("span",{className:"font-medium text-red-600",children:i("usage.estimatedCharge")}),e.jsx("span",{className:"font-semibold text-red-600",children:l(n.estimatedCost,n.currencySymbol)})]})]}),!t.hasOverage&&n&&e.jsx("div",{className:"mt-2 text-xs text-gray-500",children:i("usage.overageRateDisplay",{rate:i("usage.rateDisplay",{rate:l(n.overageCents/100,n.currencySymbol),unitSize:n.unitSize})})})]})}const Zn=R.Root,Qn=j.forwardRef(({className:s,children:t,...a},r)=>e.jsxs(R.Trigger,{ref:r,className:W("flex h-9 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",s),...a,children:[t,e.jsx(R.Icon,{asChild:!0,children:e.jsx(l.CaretSortIcon,{className:"h-4 w-4 opacity-50"})})]}));Qn.displayName=R.Trigger.displayName;const Xn=j.forwardRef(({className:s,children:t,position:a="popper",...r},n)=>{const{container:i}=j.useContext(Ia);return e.jsx(R.Portal,{container:i,children:e.jsx(R.Content,{ref:n,className:W("relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===a&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:a,...r,children:e.jsx(R.Viewport,{className:W("p-1","popper"===a&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t})})})});Xn.displayName=R.Content.displayName;j.forwardRef(({className:s,...t},a)=>e.jsx(R.Label,{ref:a,className:W("px-2 py-1.5 text-sm font-semibold",s),...t})).displayName=R.Label.displayName;const ei=j.forwardRef(({className:s,children:t,...a},r)=>e.jsxs(R.Item,{ref:r,className:W("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 ps-2 pe-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...a,children:[e.jsx("span",{className:"absolute end-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(R.ItemIndicator,{children:e.jsx(l.CheckIcon,{className:"h-4 w-4"})})}),e.jsx(R.ItemText,{children:t})]}));ei.displayName=R.Item.displayName;function si(e,t){const{response:a}=qs();return s.useMemo(()=>{if(!e)return{hasSeatPricing:!1,memberCount:0,includedSeats:0,maxUsers:0,maxSeats:0,limitSource:"none",billableSeats:0,availableSeats:1/0,isAtMax:!1,isNearMax:!1,perSeatPriceCents:null,currency:"",canInvite:!0,inviteBlockReason:null,inviteBlockMessageKey:null,inviteBlockMessageValues:null};const s=e.users?.length??0,r=a?.planVersion,n=a?.subscription,i=e.billingCurrency||"usd",o=xa({planVersion:r,currency:i,settingsMaxUsers:t?.settingsMaxUsers}),{maxUsers:c,hasSeatPricing:l,includedSeats:d}=o,u=l?Math.max(0,s-d):0,m=c>0?Math.max(0,c-s):1/0,p=c>0&&s>=c,h=c>0&&s>=.8*c&&!p,g=l&&r?fa(r,i,n?.billingInterval??"monthly"):null,f=ba({memberCount:s,maxUsersConfig:o});return{hasSeatPricing:l,memberCount:s,includedSeats:d,maxUsers:c,maxSeats:c,limitSource:o.source,billableSeats:u,availableSeats:m,isAtMax:p,isNearMax:h,perSeatPriceCents:g,currency:i,canInvite:f.canInvite,inviteBlockReason:f.blockReason,inviteBlockMessageKey:f.blockMessageKey,inviteBlockMessageValues:f.blockMessageValues}},[a,e,t?.settingsMaxUsers])}j.forwardRef(({className:s,...t},a)=>e.jsx(R.Separator,{ref:a,className:W("-mx-1 my-1 h-px bg-muted",s),...t})).displayName=R.Separator.displayName;const ti=({workspace:t})=>{const{user:a}=xi(),{t:r,fmtNum:i,fmtCents:o}=ds(),[c,l]=s.useState(0),[d,u]=s.useState(!1),[m,p]=s.useState([]),[h,g]=s.useState(null),{getUsers:f,removeUser:x,updateUser:b}=pi(),{settings:y}=Is(),{can:w}=Xa(),{response:S}=qs(),N=si(t,{settingsMaxUsers:y?.workspace?.maxWorkspaceUsers});s.useEffect(()=>{t&&(u(!0),f(t._id).then(e=>{p(e)}).catch(e=>{z(e,{component:"WorkspaceSettingsUsers",action:"getUsers",metadata:{workspaceId:t._id}})}).finally(()=>{u(!1)}))},[t,c,f]);const j=()=>{l(e=>e+1)},k=y?.workspace?.mode===On.Personal;if(d||!t)return e.jsx(or,{});if(k)return null;const C=e=>"string"==typeof e?{name:r("users.unknownUser"),email:e,id:e,role:"-"}:{name:e.name||r("users.unknownUser"),email:e.email,id:e._id},A=m.map(e=>({...e,...C(e.user)})),T=w(Ha.WORKSPACE_MEMBERS_INVITE),E=w(Ha.WORKSPACE_MEMBERS_REMOVE),P=w(Ha.WORKSPACE_MEMBERS_ROLE_CHANGE),{hasSeatPricing:I,includedSeats:U,maxUsers:R,canInvite:M,inviteBlockReason:D,inviteBlockMessageKey:W,inviteBlockMessageValues:F,perSeatPriceCents:_,currency:O}=N,L=m.length,B=S?.subscription?.billingInterval??"monthly",G=I&&L>=U;return e.jsxs("div",{children:[!T&&!E&&!P&&e.jsx(nr,{descriptionKey:"users.adminOnly"}),T&&e.jsx("div",{className:"mb-4",children:M?e.jsxs("div",{children:[e.jsx(ai,{onInvite:j,workspaceId:t._id}),G&&_&&_>0&&e.jsx("div",{className:"flex items-center gap-1.5 mt-2 text-xs text-amber-600 bg-amber-50 px-3 py-1.5 rounded-md",children:e.jsx("span",{children:r("users.extraSeatCost",{price:o(_,O),interval:B})})})]}):e.jsx("div",{className:"flex items-center justify-between p-3 bg-red-50 border border-red-100 rounded-md",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-red-700",children:r("users.limitReached",{reason:D??"member_limit_reached"})}),e.jsx("p",{className:"text-xs text-red-600 mt-0.5",children:W?r(W,F??void 0):""})]})})}),(I||R>0)&&e.jsxs("div",{className:"mb-4 rounded-lg border bg-gray-50 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900",children:r("users.seatHeading",{hasSeatPricing:String(I)})}),R>0&&e.jsxs("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full "+(L>=R?"bg-red-100 text-red-700":L>=.8*R?"bg-amber-100 text-amber-700":"bg-emerald-100 text-emerald-700"),children:[i(L)," / ",i(R)]})]}),R>0&&e.jsx("div",{className:"w-full h-1.5 bg-gray-200 rounded-full mb-3",children:e.jsx("div",{className:"h-1.5 rounded-full transition-all "+(L>=R?"bg-red-500":L>=.8*R?"bg-amber-500":"bg-emerald-500"),style:{width:`${Math.min(100,L/R*100)}%`}})}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-gray-600",children:[e.jsx("div",{children:I?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-gray-900 font-medium",children:i(U)})," ",r("users.included"),_&&_>0&&e.jsxs("span",{className:"text-gray-400",children:[" ","· ",o(_,O),r("users.perExtraSeat")]})]}):e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-900 font-medium",children:i(R)})," ",r("users.maxMembers")]})}),R>0?e.jsxs("span",{children:[i(Math.max(0,R-L))," ",r("users.available")]}):e.jsx("span",{className:"text-gray-400",children:r("users.noMemberLimit")})]})]}),e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("div",{children:e.jsx("div",{className:"text-sm text-gray-600",children:r("users.memberCount",{count:L})})}),e.jsx("div",{children:e.jsx(Pa,{variant:"ghost",size:"sm",onClick:j,progress:d,children:r("settings.common.refreshAction",{loading:String(d)})})})]}),e.jsx("ul",{className:"space-y-2",children:A.map((s,i)=>{const o=s.id===a?.id,c=("object"==typeof t.createdBy&&null!==t.createdBy?t.createdBy._id:t.createdBy)===s.id;return e.jsxs("li",{className:"border rounded p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-200 rounded-full flex items-center justify-center text-sm font-medium shrink-0",children:s.name.charAt(0).toUpperCase()}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:s.name}),e.jsx("div",{className:"text-xs text-gray-500 truncate",children:s.email})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[o&&e.jsx("span",{className:"text-xs bg-blue-100 text-blue-800 px-2 py-0.5 rounded",children:r("users.you")}),c&&e.jsx("span",{className:"text-xs bg-purple-100 text-purple-800 px-2 py-0.5 rounded",children:r("users.owner")})]})]}),P&&e.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-gray-100 sm:mt-0 sm:pt-0 sm:border-0",children:[e.jsxs("div",{className:"relative flex-1 sm:flex-initial",children:[e.jsxs(Zn,{disabled:o||!P||c||h===s.id,value:s.role,onValueChange:e=>{return a=t._id,r=s.id,n=e,void($a(t,r)?z(new Error("Cannot change the role of the workspace owner"),{component:"WorkspaceSettingsUsers",action:"handleUpdateRole",metadata:{workspaceId:a,userId:r,role:n}}):(g(r),b(a,r,{role:n}).then(()=>{j()}).catch(e=>{z(e,{component:"WorkspaceSettingsUsers",action:"handleUpdateRole",metadata:{workspaceId:a,userId:r,role:n}})}).finally(()=>{g(null)})));var a,r,n},children:[e.jsx(Qn,{children:e.jsx(v.SelectValue,{placeholder:r("users.selectRole")})}),e.jsx(Xn,{children:t?.roles.map(s=>e.jsx(ei,{value:s,children:s},s))})]}),h===s.id&&e.jsx("div",{className:"absolute end-8 top-1/2 -translate-y-1/2 pointer-events-none",children:e.jsx(n.Loader2,{className:"h-4 w-4 animate-spin text-gray-500"})})]}),!o&&!c&&E&&e.jsx(Pa,{variant:"destructive",size:"sm",startIcon:e.jsx(n.TrashIcon,{}),onClick:()=>{return e=s.id,void($a(t,e)?z(new Error("Cannot remove the workspace owner"),{component:"WorkspaceSettingsUsers",action:"handleRemoveUser",metadata:{workspaceId:t._id,userId:e}}):x(t._id,e).then(()=>{j()}).catch(s=>{z(s,{component:"WorkspaceSettingsUsers",action:"handleRemoveUser",metadata:{workspaceId:t._id,userId:e}})}));var e}})]})]},i)})}),0===m.length&&e.jsx("div",{className:"text-center py-8 text-gray-500",children:r("users.noMembers")})]})};function ai({onInvite:t,workspaceId:a}){const{t:r}=ds(),{addUser:n,getWorkspace:i}=pi(),{settings:o}=Is(),[c,l]=s.useState(""),[d,u]=s.useState("admin"),[m,p]=s.useState(!1),[h,g]=s.useState(null),[f,x]=s.useState(null),[b,y]=s.useState(null),w=s.useRef(null),S=o?.workspace.roles??b?.roles??[];s.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]),s.useEffect(()=>{a&&i(a).then(y)},[a]);const N=()=>{g(null),x(null),l(""),u("admin")};return e.jsxs("div",{className:"flex gap-2 flex-col gap-y-2",children:[h&&e.jsx("div",{className:"text-red-500",children:h}),f&&e.jsx("div",{className:"text-green-500",children:f}),e.jsxs("div",{children:[e.jsx(Or,{children:r("users.inviteByEmail")}),e.jsx(Yr,{type:"email",value:c,onChange:e=>l(e.target.value),placeholder:"example@example.com"})]}),e.jsxs("div",{children:[e.jsx(Or,{children:r("users.role")}),e.jsxs(Zn,{value:d,onValueChange:u,children:[e.jsx(Qn,{children:e.jsx(v.SelectValue,{placeholder:r("users.selectRole")})}),e.jsx(Xn,{children:S.map(s=>e.jsx(ei,{value:s,children:s},s))})]})]}),e.jsx("div",{children:e.jsx(Pa,{progress:m,onClick:async()=>{const e=c.trim();if(!e)return void g(r("users.emailRequired"));/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?(p(!0),await n(a,e,d).then(()=>{x(r("users.inviteSuccess")),t?.()}).catch(s=>{z(s,{component:"InviteMember",action:"addUser",metadata:{workspaceId:a,email:e,role:d}}),g(s instanceof Error?s.message:r("users.inviteFailed"))}).finally(()=>{p(!1),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{N()},6e3)})):g(r("users.invalidEmail"))},disabled:m||!c||!d,children:m?r("users.inviting"):r("users.inviteAs",{role:d})})})]})}const ri=({workspace:s,section:t,setSection:a})=>{const{t:r}=ds(),{settings:i}=Is(),{can:o}=Xa(),{appPermissions:c}=ht(),l=i?.workspace?.mode===On.Personal,d=o(Ha.WORKSPACE_DELETE),u=c&&Object.keys(c).length>0;return e.jsxs("div",{className:"w-44 sm:w-56 h-full flex flex-col space-y-4 sm:space-y-6 shrink-0",children:[s&&e.jsx("div",{className:"border-b p-2 py-4",children:e.jsxs("div",{className:"flex items-center gap-x-2",children:[s.image&&s.image.trim()&&e.jsx("div",{className:"bg-blue-100 rounded flex items-center justify-center text-blue-600 font-medium px-0.5 py-0.5",style:{width:"40px",height:"40px",minWidth:"40px",minHeight:"40px"},children:e.jsx("img",{src:s.image,className:"w-full h-full object-contain",style:{width:"36px",height:"36px",maxWidth:"36px",maxHeight:"36px",objectFit:"contain"},alt:s.name})}),e.jsxs("div",{className:W("flex-1 min-w-0",s.image?"":"ps-2"),children:[e.jsx("div",{className:"font-medium text-sm line-clamp-1 text-ellipsis overflow-hidden",children:s.name}),e.jsx("div",{className:"text-xs text-gray-500",children:s.workspaceId})]})]})}),e.jsxs(ni,{title:r("settings.sidebar.account"),children:[e.jsx(ii,{activeSection:t,icon:e.jsx(n.UserIcon,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.profile"),section:oi.Profile,onClick:()=>a(oi.Profile)}),e.jsx(ii,{activeSection:t,icon:e.jsx(n.KeyRound,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.security"),section:oi.Security,onClick:()=>a(oi.Security)})]}),e.jsxs(ni,{title:r("settings.sidebar.workspace"),children:[o(Ha.WORKSPACE_SETTINGS_VIEW)&&e.jsx(ii,{activeSection:t,icon:e.jsx(n.SettingsIcon,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.general"),section:oi.General,onClick:()=>a(oi.General)}),!l&&o(Ha.WORKSPACE_MEMBERS_VIEW)&&e.jsx(ii,{activeSection:t,icon:e.jsx(n.UsersIcon,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.users"),section:oi.Users,onClick:()=>a(oi.Users)}),o(Ha.WORKSPACE_BILLING_VIEW)&&e.jsx(ii,{activeSection:t,icon:e.jsx(n.CreditCard,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.subscription"),section:oi.Subscription,onClick:()=>a(oi.Subscription)}),o(Ha.WORKSPACE_USAGE_VIEW)&&e.jsx(ii,{activeSection:t,icon:e.jsx(n.BarChart3,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.usage"),section:oi.Usage,onClick:()=>a(oi.Usage)}),o(Ha.WORKSPACE_BILLING_VIEW)&&e.jsx(ii,{activeSection:t,icon:e.jsx(n.Coins,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.credits"),section:oi.Credits,onClick:()=>a(oi.Credits)}),o(Ha.WORKSPACE_FEATURES_VIEW)&&e.jsx(ii,{activeSection:t,icon:e.jsx(n.ToggleRight,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.features"),section:oi.Features,onClick:()=>a(oi.Features)}),e.jsx(ii,{activeSection:t,icon:e.jsx(n.Bell,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.notifications"),section:oi.Notifications,onClick:()=>a(oi.Notifications)}),u&&!l&&e.jsx(ii,{activeSection:t,icon:e.jsx(n.Shield,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.permissions"),section:oi.Permissions,onClick:()=>a(oi.Permissions)}),d&&!l&&e.jsx(ii,{activeSection:t,icon:e.jsx(n.AlertTriangle,{className:"h-3.5 w-3.5"}),label:r("settings.sidebar.danger"),section:oi.Danger,onClick:()=>a(oi.Danger)})]})]})};function ni({title:s,children:t}){return e.jsxs("div",{className:"px-2 flex flex-col space-y-1",children:[e.jsx("div",{className:"text-xs font-bold mb-2 text-gray-500 uppercase tracking-wide px-2",children:s}),t]})}function ii({icon:s,label:t,section:a,onClick:r,activeSection:n}){return e.jsxs("button",{className:W("flex w-full text-start px-2 py-1 rounded text-sm items-center gap-x-1",a===n?"bg-blue-100 text-blue-700 font-medium":"hover:bg-gray-200 hover:text-gray-700"),onClick:()=>r(a),children:[s,t]})}const oi={Profile:"profile",Security:"security",General:"general",Users:"users",Subscription:"subscription",Usage:"usage",Credits:"credits",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"},ci=new Set(Object.values(oi)),li={[oi.Profile]:"settings.titles.profile",[oi.Security]:"settings.titles.security",[oi.General]:"settings.titles.general",[oi.Users]:"settings.titles.users",[oi.Subscription]:"settings.titles.subscription",[oi.Usage]:"settings.titles.usage",[oi.Credits]:"settings.titles.credits",[oi.Features]:"settings.titles.features",[oi.Notifications]:"settings.titles.notifications",[oi.Permissions]:"settings.titles.permissions",[oi.Danger]:"settings.titles.danger"},di=({workspace:t,onClose:a,open:r,onOpenChange:i,defaultSection:o=oi.Profile,section:c,onSectionChange:l,showTrigger:d=!0,trigger:u})=>{const{t:m,dir:p}=ds(),[h,g]=s.useState(!1),[f,x]=s.useState(o),b=void 0!==r?r:h,y=i||g,v=void 0!==c?c:f,w=l||x;if(!t)return null;const S=e.jsx(Pa,{variant:"outline",size:"icon",children:e.jsx(n.Settings,{className:"h-4 w-4"})});return e.jsxs(Ra,{open:b,onOpenChange:e=>{y(e),!e&&a&&a()},children:[d&&e.jsx(Ma,{asChild:!0,children:u||S}),e.jsxs(Fa,{dir:p,className:"flex max-w-2xl min-w-full sm:min-w-[800px] p-0 m-0 bg-muted sm:min-h-[600px] min-h-full gap-x-0 space-x-0",children:[e.jsx(La,{className:"sr-only",children:m(li[v])}),e.jsx(ri,{workspace:t,section:v,setSection:w}),e.jsxs("div",{className:"flex-1 p-6 overflow-auto flex flex-col bg-background",children:[e.jsx(Oa,{className:"text-xl font-bold mb-4",children:m(li[v])}),e.jsxs("div",{className:"sm:max-h-[500px] overflow-y-auto",children:[v===oi.Profile&&e.jsx(Mn,{workspace:t}),v===oi.Security&&e.jsx(Wn,{}),v===oi.General&&e.jsx(an,{workspace:t}),v===oi.Users&&e.jsx(ti,{workspace:t}),v===oi.Subscription&&e.jsx(zn,{workspace:t}),v===oi.Usage&&e.jsx(Jn,{}),v===oi.Credits&&e.jsx(mr,{workspace:t}),v===oi.Features&&e.jsx(Tr,{workspaceId:t._id?.toString()}),v===oi.Notifications&&e.jsx(un,{workspace:t}),v===oi.Permissions&&e.jsx(mn,{workspace:t}),v===oi.Danger&&e.jsx(kr,{workspace:t})]})]})]})]})};var ui=Object.freeze({__proto__:null,SETTINGS_SCREENS:ci,SettingsScreen:oi,WorkspaceSettingsDialog:di,default:di});const mi=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:oi.Profile}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getState(){return{...this.currentState}}openWorkspaceSettings(e,s){this.currentState={open:!0,section:e||oi.Profile,params:s},this.notifyListeners()}closeSettings(){this.currentState={...this.currentState,open:!1,params:void 0},this.notifyListeners()}setSection(e){this.currentState={...this.currentState,section:e},this.notifyListeners()}clearParams(){this.currentState={...this.currentState,params:void 0}}notifyListeners(){this.listeners.forEach(e=>{e(this.currentState)})}},pi=()=>{const e=ks(),{os:t,api:a}=Us(),{settings:r}=Is(),n=Cs(e=>e.workspaces),i=Cs(e=>e.auth.session?.user),o=s.useCallback((s,t)=>{if((!(s._id===n.currentWorkspace?._id)||t?.forceEmit)&&s){const t=n.currentWorkspace;Ga(s),e.workspaces(Ee(s)),Ta.emitWorkspaceChanged(s,t).catch(e=>{z(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceChanged",metadata:{workspaceId:s._id}})})}},[n.currentWorkspace,e]),c=s.useCallback(async(s,a)=>{const r=++p.current;e.workspaces(De(s._id));try{const e=t.auth?.callbacks?.onWorkspaceChange;if(e){const t=qa(s,i?.id);try{await e({workspace:s,user:i??null,role:t})}catch(e){throw z(e,{component:"useSaaSWorkspaces",action:"onWorkspaceChange",metadata:{workspaceId:s._id}}),e}if(r!==p.current)return}o(s,a)}finally{r===p.current&&e.workspaces(De(null))}},[e,t.auth?.callbacks?.onWorkspaceChange,o,i]),l=s.useRef(c);l.current=c,s.useEffect(()=>{if(!n.isInitialized){const s=Ka();if(e.workspaces(Ie(!0)),s){const e=n.workspaces.find(e=>e._id===s);e&&l.current(e,{forceEmit:!0}).catch(e=>{z(e,{component:"useSaaSWorkspaces",action:"initWorkspaceSwitch",metadata:{savedWorkspaceId:s}})})}}},[n.isInitialized,n.workspaces,e]);const d=s.useCallback(()=>{Va(),e.workspaces(Pe())},[e]),u=s.useRef(!1),m=s.useRef(!1),p=s.useRef(0),h=s.useCallback(async()=>{if(!n.loading&&!u.current){u.current=!0,e.workspaces(Ue(!0)),e.workspaces(Re(null));try{const s=await a.getWorkspaces();if(e.workspaces(je(s)),s.length>0){const e=Ka();if(e&&za(e,s)){const t=s.find(s=>s._id===e);if(t)try{await c(t,{forceEmit:!0})}catch{}}else{const e=s[0];try{await c(e,{forceEmit:!0})}catch{}}}}catch(s){e.workspaces(Re(s instanceof Error?s.message:"Failed to fetch workspaces"))}finally{e.workspaces(Ue(!1)),u.current=!1}}},[a,n.loading,e,c]),g=s.useCallback(async()=>{if(!n.refreshing&&!u.current){u.current=!0,e.workspaces(Me(!0));try{const s=await a.getWorkspaces();e.workspaces(je(s))}catch(e){}finally{e.workspaces(Me(!1)),u.current=!1}}},[a,n.refreshing,e]),f=s.useCallback(async(s,t)=>{const r=await a.createWorkspace({name:s,image:t});e.workspaces(ke(r)),await c(r),Ta.emitWorkspaceCreated(r).catch(e=>{z(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceCreated",metadata:{workspaceId:r._id}})}),setTimeout(()=>{mi.openWorkspaceSettings(oi.Subscription)},300)},[a,e,c]),x=s.useCallback(async(s,t)=>{const r=await a.updateWorkspace(s._id,t);e.workspaces(Ce(r)),Ta.emitWorkspaceUpdated(r).catch(e=>{z(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceUpdated",metadata:{workspaceId:r._id}})})},[a,e]),b=s.useCallback(async()=>{if(m.current)return n.allFeatures.length>0?n.allFeatures:null;if(n.allFeatures.length>0)return n.allFeatures;m.current=!0;try{const s=await a.getFeatures();return e.workspaces(Te(s)),s}catch(e){return z(e,{component:"useSaaSWorkspaces",action:"getFeatures"}),null}finally{m.current=!1}},[a,e,n.allFeatures]),y=s.useCallback(async(e,s,t)=>await a.updateFeature(e,s,t),[a]),v=s.useCallback(async e=>a.updateSettings(e),[a]),w=s.useCallback(async(e,s)=>{const t=await a.updateWorkspacePermissions(e,s);return await g(),t},[a,g]);s.useEffect(()=>{if(!n.currentWorkspace?._id||0===n.workspaces.length)return;const s=n.currentWorkspace._id,t=n.workspaces.find(e=>e._id===s);if(t)t!==n.currentWorkspace&&(Ga(t),e.workspaces(Ee(t)));else if(n.workspaces.length>0){const e=n.workspaces[0];e._id!==s&&c(e).catch(s=>{z(s,{component:"useSaaSWorkspaces",action:"fallbackWorkspaceSwitch",metadata:{workspaceId:e._id}})})}},[n.workspaces,n.currentWorkspace,e,c]);const S=s.useCallback(async e=>await a.getWorkspaceUsers(e),[a]),N=s.useCallback(async(e,s,t)=>{const i=n.workspaces.find(s=>s._id===e);if(i){const e=xa({settingsMaxUsers:r?.workspace?.maxWorkspaceUsers}),s=ba({memberCount:i.users?.length??0,maxUsersConfig:e});if(!s.canInvite)throw new Error(s.blockMessageKey||"users.memberLimitReached")}const o=await a.addUser(e,{email:s,role:t});return i&&Ta.emitWorkspaceUserAdded(o.userId,i,t).catch(s=>{z(s,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:o.userId,role:t}})}),g().catch(e=>{z(e,{component:"useSaaSWorkspaces",action:"refreshAfterAddUser"})}),Ze(),o},[a,n.workspaces,g,r]),j=s.useCallback(async(e,s)=>{const t=n.workspaces.find(s=>s._id===e);if(t&&$a(t,s))throw new Error("Cannot remove the workspace owner");const r=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===s),i=await a.removeUser(e,s);if(t&&r){const s=r.role;Ta.emitWorkspaceUserRemoved(i.userId,t,s).catch(t=>{z(t,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:i.userId,role:s}})})}return g().catch(e=>{z(e,{component:"useSaaSWorkspaces",action:"refreshAfterRemoveUser"})}),Ze(),i},[a,n.workspaces,g]),k=s.useCallback(async(e,s,t)=>{if(t.role){const t=n.workspaces.find(s=>s._id===e);if(t&&$a(t,s))throw new Error("Cannot change the role of the workspace owner")}let r;if(t.role){const t=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===s);r=t?.role}const i=await a.updateUser(e,s,t);return t.role&&r&&r!==t.role&&Ta.emitWorkspaceUserRoleChanged(i.userId,i.workspace,r,t.role).catch(a=>{z(a,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:s,previousRole:r,newRole:t.role}})}),i},[a,n.workspaces]),C=s.useCallback(async e=>{const s=await a.getProfile().catch(()=>null),t=await a.updateUserProfile(e);return Ta.emitUserUpdated(t,s||void 0).catch(e=>{z(e,{component:"useSaaSWorkspaces",action:"emitUserUpdated",metadata:{userId:t._id}})}),t},[a]),A=s.useCallback(async()=>await a.getProfile(),[a]),T=s.useCallback(async e=>await a.getWorkspace(e),[a]),E=s.useCallback(async s=>{if(!i)throw new Error("User must be authenticated to delete a workspace");const t=n.workspaces.find(e=>e._id===s);if(!t)throw new Error("Workspace not found");if(!$a(t,i.id))throw new Error("Only the workspace creator can delete the workspace");const r=await a.deleteWorkspace(s);return e.workspaces(Ae(s)),n.currentWorkspace?._id===s&&(Va(),e.workspaces(Pe())),t&&Ta.emitWorkspaceDeleted(t).catch(e=>{z(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceDeleted",metadata:{workspaceId:s}})}),r},[a,n.workspaces,n.currentWorkspace,e,i]);return{workspaces:n.workspaces,loading:n.loading,error:n.error,fetchWorkspaces:h,refreshWorkspaces:g,refreshing:n.refreshing,currentWorkspace:n.currentWorkspace,setCurrentWorkspace:o,switchToWorkspace:c,resetCurrentWorkspace:d,createWorkspace:f,allFeatures:n.allFeatures,getFeatures:b,updateFeature:y,updateWorkspaceSettings:v,updateWorkspacePermissions:w,getWorkspace:T,updateWorkspace:x,getUsers:S,addUser:N,removeUser:j,updateUser:k,getProfile:A,updateUserProfile:C,deleteWorkspace:E,switching:null!==n.switchingToId,switchingToId:n.switchingToId}};function hi(e,s,t){const a=e._id||e.id;if(!a||"string"!=typeof a)throw new Error("User data missing required ID field");if(!e.email||"string"!=typeof e.email)throw new Error("User data missing required email field");return{id:a,name:e.name||"",org:s,email:e.email,emailVerified:!1!==e.emailVerified,clientId:t,role:e.role||"",image:e.image}}function gi(e,s){return{user:e,sessionId:s,expires:new Date(Date.now()+864e5).toISOString()}}function fi(){return Cs(e=>e.auth)}function xi(){const{t:e}=ds(),t=ks(),a=fi(),r=Es(),{serverUrl:n,orgId:i,auth:o}=r,{resetCurrentWorkspace:c,currentWorkspace:l}=pi(),d=ut(),u=s.useMemo(()=>new Ct({serverUrl:n,version:r.version}),[n,r.version]),m=s.useCallback(async s=>{St(s||window.location.href),t.auth(J()),d.show(e("loading.redirecting"));try{const s=function(){const e=new Uint8Array(32);crypto.getRandomValues(e);const s=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return ms(jt,s),s}(),a=await u.requestAuth({orgId:i,clientId:o?.clientId??"",redirect:{success:o?.redirectUrl||window.location.href,error:o?.redirectUrl||window.location.href},state:s});if(!a.success)throw d.hide(),t.auth(Z()),new Error(a.message||e("errors.generic"));yt(a.data.redirectUrl)}catch(e){throw d.hide(),t.auth(Z()),z(e,{component:"useSaaSAuth",action:"signIn"}),e}},[u,i,o,t,d,e]),p=s.useCallback(async()=>{try{o?.callbacks?.onSignOut&&"function"==typeof o.callbacks.onSignOut&&await o.callbacks.onSignOut()}catch(e){z(e,{component:"useSaaSAuth",action:"signOut"})}finally{ps(hs),t.auth(X()),c()}},[t,c,o?.callbacks?.onSignOut]),h=s.useCallback(e=>{l?mi.openWorkspaceSettings(e):z(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),g=s.useCallback(()=>{l?mi.openWorkspaceSettings(oi.Credits,{action:Ut}):z(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),f=s.useCallback(()=>{l?mi.openWorkspaceSettings(oi.Subscription,{action:Pt}):z(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),x=s.useMemo(()=>ae(a.status),[a.status]);return s.useMemo(()=>({user:a.session?.user,session:a.session,status:a.status,...x,signIn:m,signOut:p,openWorkspaceSettings:h,openCreditStore:g,openPlanPicker:f}),[a.session,a.status,x,m,p,h,g,f])}const bi=s.memo(({children:t,callbacks:a})=>{const{t:r}=ds(),n=ks(),i=fi(),o=Es(),c=ae(i.status).isAuthenticated,l=ut(),d=s.useRef(!1),u=s.useRef(null),m=s.useRef(!1),p=s.useRef(null),h=s.useCallback(async e=>{try{if(a?.handleAuthentication){l.show(r("loading.signingIn"));const{sessionId:s}=await a.handleAuthentication(e);if(!s||"string"!=typeof s||""===s.trim())throw new Error("Invalid sessionId received from authentication callback");const t=o;if(!fe(t))throw new Error("OS configuration is not available");const{serverUrl:i,version:c,orgId:d}=t;l.show(r("loading.verifyingAccount"));const u=new Ct({serverUrl:i,version:c}),m=await u.getProfile(s),p=gi(hi(m,d,t.auth?.clientId||""),s);l.show(r("loading.almostThere")),xs(p.sessionId),n.auth(Q(p)),vs();const h=Nt();h&&h!==window.location.href&&yt(h),l.hide()}}catch(s){throw l.hide(),Nt(),z(s,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),n.auth(Z()),s}},[n,a,o,l,r]);return s.useEffect(()=>{if("undefined"==typeof window)return;if(c)return;if(m.current)return;if(p.current)return;if(!fe(o))return;if(ys())return;if(!a?.getSession)return m.current=!0,void n.auth(Z());const e=a.getSession,{serverUrl:s,version:t,orgId:i}=o,d=o.auth?.clientId||"";p.current=(async()=>{l.show(r("loading.restoringSession"));let o=null;try{o=await e()}catch(e){z(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!o)return m.current=!0,n.auth(Z()),l.hide(),"undefined"!=typeof window&&St(window.location.href),void a?.onSessionExpired?.("missing");try{l.show(r("loading.verifyingAccount"));const e=new Ct({serverUrl:s,version:t}),a=await e.getProfile(o),c=gi(hi(a,i,d),o);xs(c.sessionId),m.current=!0,n.auth(Q(c)),l.hide();const u=Nt();u&&u!==window.location.href&&yt(u)}catch(e){z(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),m.current=!0,n.auth(Z()),l.hide(),"undefined"!=typeof window&&St(window.location.href),a?.onSessionExpired?.("expired")}finally{p.current=null}})()},[c,n,o,a]),s.useEffect(()=>{const e=ys();if(!e)return;if(d.current||u.current===e)return;if(!fe(o))return;const s=function(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(fs)}catch(e){return z(e,{component:"auth-utils",action:"getStateFromUrl",metadata:{param:fs}}),null}}();if(s&&!function(e){if(!e)return!1;const s=us(jt);if(ps(jt),!s)return!1;if(s.length!==e.length)return!1;let t=0;for(let a=0;a<s.length;a++)t|=s.charCodeAt(a)^e.charCodeAt(a);return 0===t}(s))return kt(),vs(),z(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void n.auth(Z());kt(),d.current=!0,u.current=e;let t=!1;return n.auth(Y()),h(e).then(()=>{t||(u.current=null)}).catch(e=>{t||(z(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),vs(),u.current=null)}).finally(()=>{d.current=!1}),()=>{t=!0}},[h,o.serverUrl,o.version,o.orgId]),e.jsx(e.Fragment,{children:t})});bi.displayName="AuthProviderWrapper";const yi=s.memo(({config:t,auth:a,children:r})=>{const n=ks();Es();const i=s.useMemo(()=>({clientId:a?.clientId||"",redirectUrl:a?.redirectUrl||"",callbacks:a?.callbacks}),[a?.clientId,a?.redirectUrl,a?.callbacks]);return s.useEffect(()=>{n.os(pe({...t,auth:i}))},[t,i,n]),e.jsx(e.Fragment,{children:r})});yi.displayName="ContextConfigProvider";class vi extends Ns{constructor(e){super(e)}async getAttributes(e){const s=await this.fetchResponse("users/attributes",{signal:e});s.ok||await this.throwResponseError(s,"Failed to fetch user attributes");const t=await this.unwrapResponse(s,"Failed to fetch user attributes");return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,s){return this.fetchJson(`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:s})},"Failed to update user attribute")}async getFeatures(e){const s=await this.fetchResponse("users/features",{signal:e});s.ok||await this.throwResponseError(s,"Failed to fetch user features");const t=await this.unwrapResponse(s,"Failed to fetch user features");return"object"==typeof t&&null!==t?t:{}}}const wi=s.createContext(void 0),Si=s.memo(({children:t})=>{const{t:a}=ds(),r=Es(),n=function(){const e=Es();return s.useMemo(()=>new vi(e),[e.serverUrl,e.version])}(),{isAuthenticated:i}=xi(),{serverUrl:o,version:c}=r,[l,d]=s.useState({}),[u,m]=s.useState({}),[p,h]=s.useState(!1),[g,f]=s.useState(null),x=s.useCallback(async e=>{if(o&&c&&i)try{const s=await n.getAttributes(e);d(s)}catch(e){if(L(e))return;const s=e instanceof Error?e:new Error(a("errors.generic"));f(s),z(e,{component:"UserProvider",action:"fetchAttributes"})}else d({})},[n,o,c,i]),b=s.useCallback(async()=>{if(o&&c&&i){h(!0),f(null);try{await x()}finally{h(!1)}}},[o,c,i,x]),y=s.useCallback(async e=>{h(!0),f(null);try{const s=await n.updateAttributes(e);return await x(),s}catch(s){const t=s instanceof Error?s:new Error(a("errors.generic"));throw f(t),z(s,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),s}finally{h(!1)}},[n,x]),v=s.useCallback(async(e,s)=>{h(!0),f(null);try{const t=await n.updateAttribute(e,s);return await x(),t}catch(t){const r=t instanceof Error?t:new Error(a("errors.generic"));throw f(r),z(t,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:s}}),t}finally{h(!1)}},[n,x]),w=s.useCallback(async e=>{if(o&&c&&i)try{const s=await n.getFeatures(e);m(s)}catch(e){if(L(e))return;const s=e instanceof Error?e:new Error(a("errors.generic"));f(s),z(e,{component:"UserProvider",action:"fetchFeatures"})}else m({})},[n,o,c,i]),S=s.useCallback(async()=>{if(o&&c&&i){h(!0),f(null);try{await w()}finally{h(!1)}}},[o,c,i,w]);As(async e=>{if(!i||!o||!c)return d({}),void m({});h(!0),f(null);try{await Promise.all([x(e),w(e)])}finally{h(!1)}},[i,o,c,x,w],{onError:e=>z(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const N=s.useMemo(()=>({attributes:l,features:u,isLoading:p,error:g,updateAttributes:y,updateAttribute:v,refreshAttributes:b,refreshFeatures:S}),[l,u,p,g,y,v,b,S]);return e.jsx(wi.Provider,{value:N,children:t})});Si.displayName="UserProvider";const Ni=s.lazy(()=>Promise.resolve().then(function(){return ui}).then(e=>({default:e.default})));const ji=({children:t})=>{const{currentWorkspace:a,switchToWorkspace:r,workspaces:n}=pi(),[i,o]=s.useState(!1),[c,l]=s.useState(oi.Profile),d=s.useRef(!1);return s.useEffect(()=>{const e=mi.getState();o(e.open),l(e.section);return mi.subscribe(e=>{o(e.open),l(e.section)})},[]),s.useEffect(()=>{if(d.current)return;if(!a)return;const e=Lt();if(!e)return;const s=function(e){if(e.screen&&ci.has(e.screen))return e.screen;switch(e.action){case Tt:case Et:case Pt:return oi.Subscription;case It:return oi.Credits;default:return null}}(e);if(!s)return d.current=!0,void Bt();const t=e.ws;if(t&&t!==a._id){const e=n.find(e=>e._id===t);return e?void r(e).catch(e=>{z(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:t}}),d.current=!0,Bt()}):(d.current=!0,void Bt())}d.current=!0,mi.openWorkspaceSettings(s,e),Bt()},[a,n,r]),e.jsxs(e.Fragment,{children:[t,a&&i&&e.jsx(H,{fallback:null,children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ni,{workspace:a,open:i,onOpenChange:e=>{e||mi.closeSettings()},section:c,onSectionChange:e=>{mi.setSection(e)},showTrigger:!1})})})]})},ki=(e,s,t)=>{if(s!==ge.V1)throw new Error(`Invalid version: "${s}". Only "${ge.V1}" is currently supported.`);if(!e||"string"!=typeof e)throw new Error("serverUrl is required and must be a string");if(!(e=>{try{return new URL(e),!0}catch{return!1}})(e))throw new Error(`Invalid serverUrl: "${e}". Must be a valid URL.`);if(!t||"string"!=typeof t)throw new Error("orgId is required and must be a string");if(!/^[0-9a-fA-F]{24}$/.test(t))throw new Error(`Invalid orgId: "${t}". Must be a valid MongoDB ObjectId (24 hexadecimal characters).`)},Ci=s.memo(({serverUrl:t,version:a,orgId:r,auth:n,locale:i,defaultPermissions:o,getCheckoutStripeParams:c,loadingComponent:l,children:d})=>{ki(t,a,r);const u=s.useMemo(()=>({serverUrl:t,version:a,orgId:r}),[t,a,r]),m=s.useMemo(()=>n?.callbacks,[n?.callbacks?.handleAuthentication,n?.callbacks?.onSignOut,n?.callbacks?.getSession,n?.callbacks?.onSessionExpired,n?.callbacks?.handleEvent,n?.callbacks?.onWorkspaceChange]),p=n?.callbacks?.handleEvent;return s.useEffect(()=>(Ta.setCallbacks(p?{handleEvent:p}:null),()=>{Ta.setCallbacks(null)}),[p]),e.jsx(as,{locale:i,children:e.jsx(Ge,{children:e.jsx(dt,{loadingComponent:l,children:e.jsx(bi,{callbacks:m,children:e.jsx(Ua,{children:e.jsx(yi,{config:u,auth:n,children:e.jsx(Ve,{getCheckoutStripeParams:c,children:e.jsx(pt,{appPermissions:o,children:e.jsx(Si,{children:e.jsx($s,{children:e.jsx(ft,{children:e.jsx(nt,{children:e.jsx(cn,{children:e.jsx(ji,{children:d})})})})})})})})})})})})})})});Ci.displayName="SaaSOSProviderInner";const Ai=({children:s,...t})=>e.jsx(H,{children:e.jsx(Ci,{...t,children:s})});Ai.displayName="SaaSOSProvider";const Ti=e=>{const{children:s}=e,{status:t}=xi();return t!==te.authenticated?null:s},Ei=e=>{const{children:s}=e,{status:t}=xi();return t!==te.unauthenticated?null:s};Ti.displayName="WhenAuthenticated",Ei.displayName="WhenUnauthenticated";const Pi=e=>{const{children:s,fallback:t,roles:a}=e,{user:r}=xi();return a.includes(r?.role??"")?s:t||null},Ii=e=>{const{children:s,fallback:t,roles:a}=e,{user:r}=xi(),{currentWorkspace:n}=pi(),i=n?.users.find(e=>e._id===r?.id);return i&&a.includes(i?.role??"")?s:t||null};Pi.displayName="WhenRoles",Ii.displayName="WhenWorkspaceRoles";const Ui=e=>{const{children:s,fallback:t,permission:a}=e,{can:r}=Xa();return r(a)?s:t??null};function Ri(){const e=s.useContext(wi);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return{features:e.features,isLoading:e.isLoading,error:e.error,refreshFeatures:e.refreshFeatures,isFeatureEnabled:s=>Boolean(e.features[s])}}Ui.displayName="WhenPermission";const Mi=e=>{const{children:s,slug:t}=e,{currentWorkspace:a}=pi(),r=a?.features?.[t];return r?s:null},Di=e=>{const{children:s,slug:t}=e,{currentWorkspace:a}=pi(),r=a?.features?.[t];return r?null:s},Wi=e=>{const{children:s,slug:t}=e,{isFeatureEnabled:a}=Ri();return a(t)?s:null},Fi=e=>{const{children:s,slug:t}=e,{isFeatureEnabled:a}=Ri();return a(t)?null:s};Mi.displayName="WhenWorkspaceFeatureEnabled",Di.displayName="WhenWorkspaceFeatureDisabled",Wi.displayName="WhenUserFeatureEnabled",Fi.displayName="WhenUserFeatureDisabled";const _i=e=>{const{children:s,loadingComponent:t,fallbackComponent:a}=e,{response:r,loading:n}=qs();return n?t??null:r?.subscription?s:a??null},Oi=e=>{const{children:s,loadingComponent:t,fallbackComponent:a}=e,{response:r,loading:n}=qs();return n?t??null:r?.subscription?a??null:s},Li=e=>{const{children:s,plans:t,loadingComponent:a,fallbackComponent:r}=e,{response:n,loading:i}=qs();if(i)return a??null;if(!n?.subscription)return r??null;const o=n.plan??n.subscription?.plan;if(!o)return r??null;const c=t.map(e=>e.trim().toLowerCase()),l=(o.slug??"").toLowerCase();return c.includes(l)?s:r??null},Bi=e=>{const{children:s,loadingComponent:t,fallbackComponent:a}=e,{response:r,loading:n}=qs();return n?t??null:"trialing"!==r?.subscription?.subscriptionStatus?a??null:s},Gi=e=>{const{children:s,loadingComponent:t,fallbackComponent:a}=e,{response:r,loading:n}=qs();return n?t??null:r?.subscription?.subscriptionStatus===Vt?a??null:s},Ki=e=>{const{children:s,loadingComponent:t,fallbackComponent:a,daysThreshold:r=3}=e,{response:n,loading:i}=qs();if(i)return t??null;const o=n?.subscription;if(!o||"trialing"!==o.subscriptionStatus)return a??null;const c=o.trialEnd||o.stripeCurrentPeriodEnd;if(!c)return a??null;const l=new Date(c);if(isNaN(l.getTime()))return a??null;return Math.max(0,Math.ceil((l.getTime()-Date.now())/864e5))>r?a??null:s};_i.displayName="WhenSubscription",Oi.displayName="WhenNoSubscription",Li.displayName="WhenSubscriptionToPlans",Bi.displayName="WhenTrialing",Gi.displayName="WhenNotTrialing",Ki.displayName="WhenTrialEnding";const Vi=e=>{const{slug:s,children:t,loadingComponent:a,fallbackComponent:r}=e,{quotas:n,loading:i}=xt();if(i)return a??null;const o=n?.[s];return o?o.available<=0?r??null:t:r??null},zi=e=>{const{slug:s,children:t,loadingComponent:a,fallbackComponent:r}=e,{quotas:n,loading:i}=xt();if(i)return a??null;const o=n?.[s];return o?o.available>0?r??null:t:r??null},$i=e=>{const{slug:s,children:t,loadingComponent:a,fallbackComponent:r}=e,{quotas:n,loading:i}=xt();if(i)return a??null;const o=n?.[s];return o&&o.hasOverage&&!1!==o.allowOverage?t:r??null},qi=e=>{const{slug:s,threshold:t,children:a,loadingComponent:r,fallbackComponent:n}=e,{quotas:i,loading:o}=xt();if(o)return r??null;const c=i?.[s];if(!c)return n??null;return(c.included>0?c.consumed/c.included*100:c.consumed>0?100:0)<t?n??null:a};Vi.displayName="WhenQuotaAvailable",zi.displayName="WhenQuotaExhausted",$i.displayName="WhenQuotaOverage",qi.displayName="WhenQuotaThreshold";const Hi=({children:e})=>{const{currentWorkspace:s}=pi(),t=s?._id,{balance:a,loading:r,error:n,refetch:i}=it(),{packages:o,loading:c}=et(t),{consumeCredits:l,loading:d,error:u}=Qs(t),{purchaseCredits:m,loading:p,error:h}=Xs(t);return e({balance:a,loading:r,packages:o,packagesLoading:c,consume:l,consuming:d,purchase:async e=>{if(!t)throw new Error("No workspace selected");const{successUrl:s,cancelUrl:a}=Ot(t),r=await m({creditPackageId:e._id,successUrl:s,cancelUrl:a});r.url&&yt(r.url)},purchasing:p,refetch:i,error:u||h||n})};Hi.displayName="CreditActionsProvider";const Ji=({children:e})=>{const{balance:s,loading:t,error:a,refetch:r}=it();return e({balance:s,loading:t,error:a,refetch:r})};Ji.displayName="CreditBalance";const Yi=e=>{const{min:s=1,children:t,loadingComponent:a,fallbackComponent:r}=e,{balance:n,loading:i}=it();return i?a??null:n?n.available<s?r??null:t:r??null},Zi=e=>{const{children:s,loadingComponent:t,fallbackComponent:a}=e,{balance:r,loading:n}=it();return n?t??null:r?r.available>0?a??null:s:a??null},Qi=e=>{const{threshold:s,children:t,loadingComponent:a,fallbackComponent:r}=e,{balance:n,loading:i}=it();return i?a??null:n?n.available>s?r??null:t:r??null};function Xi(e){if(!e)return null;const s=new Date(e);return isNaN(s.getTime())?null:s}Yi.displayName="WhenCreditsAvailable",Zi.displayName="WhenCreditsExhausted",Qi.displayName="WhenCreditsLow";class eo extends Ns{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}let so=class{constructor(e){this.api=new eo(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const s=e?.context??{},t=s?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),a=s?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),r=s?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),n=s?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:t,language:a,timezone:r,currency:n}})}};const to=h.z.object({name:h.z.string().min(1,"Please enter your name").max(50,"Name must be less than 50 characters").regex(/^[\p{L}\p{M}\s'-]*$/u,"Name can only contain letters and spaces"),email:h.z.string().min(1,"Please enter your email address").email("Please enter a valid email address").max(100,"Email must be less than 100 characters").regex(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,"Please enter a valid email format (e.g., name@domain.com)")});function ao({screen:s}){return e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[e.jsx("p",{className:"text-2xl font-bold",children:s?.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s?.description})]})}function ro({logo:s}){return"string"==typeof s?e.jsx("img",{src:s,alt:"Logo",className:"max-h-24"}):e.jsx("img",{src:s.bucket?.url,alt:"Logo",className:"max-h-24"})}const no=j.forwardRef(({className:s,...t},a)=>e.jsx(M.Root,{ref:a,className:W("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));no.displayName=M.Root.displayName;const io=j.forwardRef(({className:s,...t},a)=>e.jsx(M.Image,{ref:a,className:W("aspect-square h-full w-full",s),...t}));io.displayName=M.Image.displayName;const oo=j.forwardRef(({className:s,...t},a)=>e.jsx(M.Fallback,{ref:a,className:W("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));oo.displayName=M.Fallback.displayName;const co=j.forwardRef(({className:s,orientation:t="horizontal",decorative:a=!0,...r},n)=>e.jsx(D.Root,{ref:n,decorative:a,orientation:t,className:W("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",s),...r}));function lo(s){const{t:t}=ds(),{workspace:a,setCurrentWorkspace:r,setOpen:i,workspacesToUse:o,switchingToId:c}=s,l=s.isCurrentWorkspace??!1,d=c===a._id,u=a.subscription??null,m=null!=u&&"object"==typeof u?u.plan??null:null,p=m?.name??"";return e.jsxs("div",{className:W("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":l}),children:[e.jsxs(no,{className:"h-8 w-8 flex items-center justify-center",children:[e.jsx("div",{children:e.jsx(io,{src:a.image&&a.image.trim()?a.image:void 0})}),e.jsx(oo,{children:(h=a.name,h.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2))})]}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-full",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"font-medium line-clamp-1 text-ellipsis overflow-hidden max-w-full",children:a.name})}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(n.Users,{className:"h-3 w-3"}),e.jsx("span",{children:t("workspace.membersCount",{count:a.users?.length||0})})]}),p&&e.jsx("div",{className:"max-w-fit",children:e.jsx("div",{className:"flex items-center gap-1 text-sm text-muted-foreground bg-green-500 text-white rounded-full px-2 py-0.5",children:e.jsx("span",{className:"text-xs",children:p})})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l?null:e.jsx(Pa,{size:"sm",disabled:null!==c||d,progress:d,onClick:()=>{s.switchToWorkspace(a).then(()=>i(!1)).catch(e=>{z(e,{component:"WorkspaceItem",action:"switchToWorkspace",metadata:{workspaceId:a._id}})})},children:t("workspace.switchTo")}),e.jsx(di,{workspace:a,onClose:()=>{if(l){const e=o.findIndex(e=>e._id?.toString()===a._id?.toString());-1!==e&&r(o[e])}}})]})]});var h}function uo(t){const{t:a,dir:r}=ds(),{switching:i}=pi(),[o,c]=s.useState(!1),[l,d]=s.useState("emoji"),[u,p]=s.useState("🏢"),[g,f]=s.useState(!1),{createWorkspace:x}=pi(),b=h.z.object({name:h.z.string().min(2,{message:a("workspace.workspaceNameMinLength")}),image:h.z.string().optional()}),y=m.useForm({resolver:Fr(b),defaultValues:{name:"",image:""}});return e.jsxs(Ra,{open:o,onOpenChange:c,children:[e.jsx(Ma,{asChild:!0,children:e.jsxs(Pa,{className:"w-full rounded-none",disabled:i,children:[e.jsx(n.Plus,{className:"h-4 w-4 me-2"}),a("workspace.createNew")]})}),e.jsxs(Fa,{dir:r,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e.jsxs(_a,{children:[e.jsx(Oa,{children:a("workspace.createTitle")}),e.jsx(La,{children:a("workspace.createDescription")})]}),e.jsx(Lr,{...y,children:e.jsxs("form",{onSubmit:y.handleSubmit(async function(e){let s="";if("emoji"===l)s=sn(u);else if("url"===l&&e.image)try{new URL(e.image),s=e.image}catch{return void y.setError("image",{message:a("workspace.invalidUrl")})}f(!0);try{await x(e.name,s),c(!1),y.reset(),p("🏢"),d("emoji"),t?.onCreated?.()}catch(s){z(s,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{f(!1)}}),children:[e.jsx(Gr,{control:y.control,name:"name",render:({field:s})=>e.jsxs(zr,{children:[e.jsx($r,{children:a("workspace.workspaceName")}),e.jsx(qr,{children:e.jsx(Yr,{placeholder:a("workspace.workspaceNamePlaceholder"),...s})}),e.jsx(Jr,{})]})}),e.jsxs("div",{className:"flex flex-col gap-y-2 my-2",children:[e.jsxs("div",{children:[e.jsx(Or,{className:"text-sm font-medium",children:a("workspace.workspaceIcon")}),e.jsx(Hr,{children:a("workspace.iconDescription")})]}),e.jsxs(Zr,{value:l,onValueChange:e=>d(e),className:"flex flex-col gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-x-2 my-1",children:[e.jsx(Qr,{value:"emoji",id:"emoji"}),e.jsxs(Or,{htmlFor:"emoji",className:"flex items-center gap-2",children:[e.jsx(n.Smile,{className:"h-4 w-4"}),a("workspace.chooseEmoji")]})]}),e.jsxs("div",{className:"flex items-center gap-x-2 my-1",children:[e.jsx(Qr,{value:"url",id:"url"}),e.jsxs(Or,{htmlFor:"url",className:"flex items-center gap-2",children:[e.jsx(n.Image,{className:"h-4 w-4"}),a("workspace.customImageUrl")]})]})]}),"emoji"===l&&e.jsxs("div",{className:"flex flex-col gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:a("general.previewLabel")}),e.jsx("div",{className:"w-12 h-12 rounded-lg border-2 border-border flex items-center justify-center text-2xl bg-muted",children:u})]}),e.jsx(Xr,{className:"h-32 w-full rounded-md border",children:e.jsx("div",{className:"p-4 grid grid-cols-8 gap-2",children:tn.map((s,t)=>e.jsx("button",{type:"button",onClick:()=>(e=>{p(e),y.setValue("image",sn(e))})(s),className:"w-8 h-8 rounded flex items-center justify-center text-lg hover:bg-muted transition-colors "+(u===s?"bg-primary text-primary-foreground":""),children:s},t))})})]}),"url"===l&&e.jsxs("div",{className:"flex flex-col gap-y-2",children:[e.jsx(Gr,{control:y.control,name:"image",render:({field:s})=>e.jsxs(zr,{children:[e.jsx($r,{children:a("workspace.imageUrl")}),e.jsx(qr,{children:e.jsx(Yr,{placeholder:a("workspace.imageUrlPlaceholder"),...s})}),e.jsx(Hr,{children:a("workspace.imageUrlDescription")}),e.jsx(Jr,{})]})}),y.watch("image")&&y.watch("image")?.trim()&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:a("general.previewLabel")}),e.jsx("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:e.jsx("img",{src:y.watch("image")||void 0,alt:"Workspace preview",className:"w-full h-full object-cover",onError:e=>{e.currentTarget.style.display="none"}})})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[e.jsx(Pa,{type:"button",variant:"outline",onClick:()=>{c(!1),y.reset(),p("🏢"),d("emoji")},disabled:g,children:a("settings.common.cancel")}),e.jsx(Pa,{type:"submit",disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(n.Loader2,{className:"me-2 h-4 w-4 animate-spin"}),a("workspace.creating")]}):a("workspace.createWorkspace")})]})]})})]})]})}co.displayName=D.Root.displayName,exports.BetaForm=({onSuccess:t,onError:a,className:r="w-full",fieldClassName:n="flex flex-col gap-1.5 w-full",autoFocus:i=!0,showSuccessMessage:o=!0,hideLogo:c=!1,hideTitles:l=!1})=>{const{t:d}=ds(),[u,p]=s.useState(!1),[h,g]=s.useState(!1),{submitBetaForm:f,isLoading:x,isSubmitting:b,error:y,config:v,success:w,message:S}=(()=>{const{t:e}=ds(),t=Es(),[a,r]=s.useState(null),[n,i]=s.useState(!0),[o,c]=s.useState(!1),[l,d]=s.useState(null),[u,m]=s.useState(!1),[p,h]=s.useState(null);return s.useEffect(()=>{let s=!1;return(async()=>{i(!0),d(null);try{const e=new so(t),a=await e.fetchConfig();s||r(a)}catch(t){s||d(t instanceof Error?t.message:e("beta.errorMessage"))}finally{s||i(!1)}})(),()=>{s=!0}},[t]),{isLoading:n,isSubmitting:o,config:a,error:l,success:u,message:p,submitBetaForm:s.useCallback(async s=>{if(!t){const s=e("errors.generic");return d(s),{success:!1,message:s}}try{c(!0),d(null),m(!1),h(null);const e=new so(t),a=await e.submitBetaUser({name:s.name||"",email:s.email}),r="success"===a.status;return m(r),h(a.message),{success:r,message:a.message}}catch(s){const t=s instanceof Error?s.message:e("beta.errorMessage");return d(t),m(!1),h(t),{success:!1,message:t}}finally{c(!1)}},[t])}})();s.useEffect(()=>{w&&o&&(p(!0),g(!0)),y&&g(!0)},[w,o,y]);const N=m.useForm({resolver:Fr(to),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});s.useEffect(()=>{i&&N.setFocus("name")},[i,N]);const j=N.formState.isValid&&!b;return e.jsx("div",{className:"saas-os-ui",style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:x?e.jsxs("div",{className:W("flex flex-col items-center justify-center w-full px-2.5 sm:px-6 py-2.5 sm:py-6 gap-y-2.5 sm:gap-y-4",r),children:[e.jsx(ir,{className:"h-24 w-24 rounded-lg"}),e.jsx(ir,{className:"h-6 w-32"}),e.jsxs("div",{className:"w-full space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ir,{className:"h-4 w-16"}),e.jsx(ir,{className:"h-10 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ir,{className:"h-4 w-16"}),e.jsx(ir,{className:"h-10 w-full"})]}),e.jsx(ir,{className:"h-10 w-full"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center w-full px-2.5 sm:px-6 py-2.5 sm:py-6 gap-y-2.5 sm:gap-y-4",children:[!c&&e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[v?.logo&&e.jsx(ro,{logo:v?.logo}),v?.name&&e.jsx("div",{children:v?.name})]}),e.jsx(m.FormProvider,{...N,children:e.jsxs("form",{onSubmit:N.handleSubmit(async e=>{try{const s=await f(e);s.success?(t?.(),N.reset(),o&&p(!0),g(!0)):(a?.(s.message),g(!0))}catch(e){a?.(e instanceof Error?e.message:d("beta.errorMessage")),g(!0)}}),className:r,noValidate:!0,"aria-busy":b,children:[!h&&e.jsxs(e.Fragment,{children:[!l&&v?.screen?.register&&e.jsx(ao,{screen:v?.screen?.register}),e.jsx(Gr,{control:N.control,name:"name",render:({field:s})=>e.jsxs(zr,{className:n,children:[e.jsx($r,{children:d("beta.nameLabel")}),e.jsx(qr,{children:e.jsx(Yr,{...s})}),e.jsx(Hr,{}),e.jsx(Jr,{})]})}),e.jsx(Gr,{control:N.control,name:"email",render:({field:s})=>e.jsxs(zr,{className:n,children:[e.jsx($r,{children:d("beta.emailLabel")}),e.jsx(qr,{children:e.jsx(Yr,{...s})}),e.jsx(Hr,{}),e.jsx(Jr,{})]})}),e.jsx(Pa,{type:"submit",disabled:!j,className:n,children:d(b?"beta.submittingText":"beta.submitText")})]}),h&&y&&e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[e.jsxs("div",{className:"border-red-300 text-red-700",role:"alert","aria-live":"assertive","aria-atomic":!0,children:[e.jsx("span",{className:"text-4xl mb-2",role:"img","aria-label":d("settings.common.error"),children:"❗"}),y]}),e.jsx("div",{className:"mt-4 flex justify-center",children:e.jsx(Pa,{type:"button",onClick:()=>{g(!1),N.reset()},className:n,children:d("beta.tryAgain")})})]}),h&&u&&S&&e.jsx("div",{className:"flex flex-col items-center justify-center w-full text-green-700 border-green-300 text-center",children:v?.screen?.thankYou&&e.jsx(ao,{screen:v?.screen?.thankYou})})]})}),!h&&e.jsx("div",{children:e.jsxs("div",{children:[d("beta.privacyConsent")," ",e.jsx("a",{href:v?.privacyPolicy,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-700",children:d("beta.privacyPolicy")})," ",d("beta.and")," ",e.jsx("a",{href:v?.termsOfService,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-700",children:d("beta.termsOfService")}),"."]})})]})})},exports.BillingIntervals=Gt,exports.Button=Pa,exports.CreditActionsProvider=Hi,exports.CreditBalance=Ji,exports.CreditBalanceContextProvider=nt,exports.CreditStorePage=function({children:t,loadingFallback:a,errorFallback:r,redirectBaseUrl:n}){const{packages:i,notes:o,loading:c,error:l,refetch:d}=at(),{isAuthenticated:u,signIn:m}=xi(),p=s.useCallback(e=>{if(u)mi.openWorkspaceSettings(oi.Credits,{action:It,packageId:e});else if(n){const s=_t({action:It,screen:"credits",packageId:e},n);m(s)}else m()},[u,m,n]);return c?void 0!==a?e.jsx(e.Fragment,{children:a}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(ir,{className:"h-8 w-48"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(s=>e.jsx(ir,{className:"h-48 rounded-lg"},s))})]}):l?r?e.jsx(e.Fragment,{children:r(l)}):e.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:l}):e.jsx(e.Fragment,{children:t({loading:c,error:l,packages:i,notes:o,refetch:d,selectPackage:p})})},exports.Dialog=Ra,exports.DialogContent=Fa,exports.DialogDescription=La,exports.DialogTitle=Oa,exports.FullScreenLoader=ct,exports.PricingPage=function({slug:t,children:a,loadingFallback:r,errorFallback:n,redirectBaseUrl:i}){const{items:o,plans:c,notes:l,loading:d,error:u,refetch:m}=Rs(t),{isAuthenticated:p,signIn:h}=xi(),g=s.useCallback((e,s,t)=>i?_t({action:"selectPlan",plan:e,interval:s,currency:t},i):null,[i]),f=s.useCallback((e,s,t)=>{if(p)return void mi.openWorkspaceSettings(oi.Subscription,{action:"selectPlan",plan:e,interval:s,currency:t});const a=g(e,s,t);h(a??void 0)},[p,h,g]);return d?void 0!==r?e.jsx(e.Fragment,{children:r}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(ir,{className:"h-8 w-48"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(s=>e.jsx(ir,{className:"h-64 rounded-lg"},s))})]}):u?n?e.jsx(e.Fragment,{children:n(u)}):e.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:u}):e.jsx(e.Fragment,{children:a({loading:d,error:u,items:o,plans:c,notes:l,refetch:m,selectPlan:f})})},exports.PushNotificationProvider=cn,exports.QuotaUsageContextProvider=ft,exports.SETTINGS_SCREENS=ci,exports.SUPPORTED_LOCALES=es,exports.SaaSOSProvider=Ai,exports.SettingsScreen=oi,exports.SubscriptionContextProvider=$s,exports.SubscriptionItemType=Xt,exports.WhenAuthenticated=Ti,exports.WhenCreditsAvailable=Yi,exports.WhenCreditsExhausted=Zi,exports.WhenCreditsLow=Qi,exports.WhenNoSubscription=Oi,exports.WhenNotTrialing=Gi,exports.WhenPermission=Ui,exports.WhenQuotaAvailable=Vi,exports.WhenQuotaExhausted=zi,exports.WhenQuotaOverage=$i,exports.WhenQuotaThreshold=qi,exports.WhenRoles=Pi,exports.WhenSubscription=_i,exports.WhenSubscriptionToPlans=Li,exports.WhenTrialEnding=Ki,exports.WhenTrialing=Bi,exports.WhenUnauthenticated=Ei,exports.WhenUserFeatureDisabled=Fi,exports.WhenUserFeatureEnabled=Wi,exports.WhenWorkspaceFeatureDisabled=Di,exports.WhenWorkspaceFeatureEnabled=Mi,exports.WhenWorkspaceRoles=Ii,exports.WorkspaceModes=On,exports.WorkspaceSwitcher=function(t){const{t:a,dir:r}=ds(),{isAuthenticated:i,user:o}=xi(),c=fe(Es()),{workspaces:l,currentWorkspace:d,loading:u,refreshing:m,switchingToId:p,fetchWorkspaces:h,getFeatures:g,refreshWorkspaces:f,setCurrentWorkspace:x,switchToWorkspace:b}=pi(),{settings:y}=Is(),[v,w]=s.useState(!1),[S,N]=s.useState(0),[j,k]=s.useState(""),C=u||m;s.useEffect(()=>{i&&c&&(0===l.length?(h(),g()):g())},[i,c]),s.useEffect(()=>{i&&c&&S>0&&f()},[S,i,c]);const A=l,T=A.filter(e=>e._id!==d?._id).filter(e=>e.name.toLowerCase().includes(j.toLowerCase())),E=y?.workspace?.canCreateWorkspace??!0,P=y?.workspace?.showSwitcher??!0,I=y?.workspace?.maxWorkspacesPerUser??0,U=A?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===o?.id?.toString()).length??0,R=!1!==E&&(0===I||U<I);return s.useEffect(()=>{!P&&l.length>0&&!d&&b(l[0]).catch(e=>{z(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[P,l,d]),!P&&d?e.jsxs(e.Fragment,{children:[e.jsx("div",{onClick:()=>w(!0),children:t.trigger?.(C,d)}),e.jsx(di,{workspace:d,open:v,onOpenChange:w,showTrigger:!1})]}):e.jsxs(Ra,{open:v,onOpenChange:w,children:[e.jsx(Ma,{children:t.trigger?.(C,d)}),e.jsxs(Fa,{dir:r,className:"max-w-2xl min-w-full sm:min-w-[800px]",children:[e.jsxs(_a,{dir:r,children:[e.jsxs(Oa,{className:"flex items-center gap-2",children:[e.jsx(n.Building2,{className:"h-5 w-5"}),a("workspace.switchTitle")]}),e.jsx(La,{children:a("workspace.switchDescription")})]}),!o&&e.jsx("div",{className:"flex flex-col items-center justify-center h-full py-4 sm:py-8",children:e.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:a("workspace.notLoggedIn")})}),o&&e.jsxs("div",{dir:r,className:"flex flex-col gap-4",children:[d&&e.jsx(lo,{workspace:d,isCurrentWorkspace:!0,switchToWorkspace:b,switchingToId:p,onClose:()=>w(!1),setCurrentWorkspace:x,setOpen:w,workspacesToUse:A}),e.jsx(co,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:a("workspace.availableWorkspaces",{count:T.length})}),e.jsx("div",{children:e.jsx(Pa,{progress:m,disabled:m,variant:"ghost",onClick:function(){i&&c&&N(e=>e+1)},startIcon:e.jsx(n.RefreshCcw,{}),children:a("settings.common.refreshAction",{loading:String(m)})})})]}),e.jsxs("div",{className:"relative",children:[e.jsx(n.Search,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(Yr,{placeholder:a("workspace.searchPlaceholder"),value:j,onChange:e=>k(e.target.value),className:"ps-10"})]}),u?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(n.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ms-2 text-sm text-muted-foreground",children:a("workspace.loadingWorkspaces")})]}):0===T.length?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(n.Building2,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:a(j?"workspace.noWorkspacesFound":"workspace.noWorkspacesAvailable")})]}):e.jsx(Xr,{className:"h-64",dir:r,children:e.jsx("div",{dir:r,className:"flex flex-col gap-2 my-2.5",children:T.map(s=>{const t=s._id===d?._id;return e.jsx(lo,{workspace:s,isCurrentWorkspace:t,switchToWorkspace:b,switchingToId:p,onClose:()=>w(!1),setCurrentWorkspace:x,setOpen:w,workspacesToUse:A},s._id)})})})]}),R&&e.jsxs(e.Fragment,{children:[e.jsx(co,{}),e.jsx(uo,{onCreated:()=>{h()}})]})]})]})]})},exports.getAvailableCurrenciesFromPlans=function(e){const s=new Set;for(const t of e)t.pricingVariants?.forEach(e=>{e.currency&&s.add(e.currency.toLowerCase())});return Array.from(s).sort()},exports.getBasePriceCents=ua,exports.getBillingIntervalAndCurrencyFromPriceId=ha,exports.getCurrencyFlag=tr,exports.getPerSeatPriceCents=fa,exports.getQuotaDisplayParts=_n,exports.getQuotaDisplayValue=Fn,exports.getQuotaDisplayWithVariant=pa,exports.getSeatPricing=ga,exports.useAllQuotaUsage=Vs,exports.useBillingPortal=Bs,exports.useCancelSubscription=Gs,exports.useConsumeCredits=Qs,exports.useCreateCheckoutSession=Fs,exports.useCreditBalance=Zs,exports.useCreditBalanceContext=it,exports.useCreditPackages=et,exports.useCreditTransactions=st,exports.useExpiringCredits=tt,exports.useFullScreenLoader=ut,exports.useInvoice=(e,t)=>{const{t:a}=ds(),{api:r}=Us(),[n,i]=s.useState(null),[o,c]=s.useState(!1),[l,d]=s.useState(null),u=s.useCallback(async()=>{if(e&&t){c(!0),d(null);try{const s=await r.getInvoice(e,t);i(s.invoice)}catch(s){const r=q(s,"errors.fetchInvoice",a);d(r),z(s,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:t}})}finally{c(!1)}}else i(null)},[r,e,t]);return s.useEffect(()=>{u()},[u]),{invoice:n,loading:o,error:l,refetch:u}},exports.useInvoices=Ls,exports.usePermissions=Xa,exports.usePlanGroup=Ds,exports.usePlanGroupVersions=Ws,exports.usePublicCreditPackages=at,exports.usePublicPlanGroupVersion=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(null),[i,o]=s.useState(!1),[c,l]=s.useState(null),d=s.useCallback(async()=>{if(e){o(!0),l(null);try{const s=await a.getPlanGroupVersion(e);n(s)}catch(s){const a=q(s,"errors.fetchPlanGroupVersion",t);l(a),z(s,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{o(!1)}}else n(null)},[a,e]);return s.useEffect(()=>{d()},[d]),{planGroupVersion:r,loading:i,error:c,refetch:d}},exports.usePublicPlans=Rs,exports.usePurchaseCredits=Xs,exports.usePushNotifications=ln,exports.useQuotaUsageContext=xt,exports.useQuotaUsageStatus=(e,t)=>{const{t:a}=ds(),{api:r}=Us(),[n,i]=s.useState(null),[o,c]=s.useState(!1),[l,d]=s.useState(null),u=s.useCallback(async()=>{if(e&&t){c(!0),d(null);try{const s=await r.getQuotaUsageStatus(e,t);i(s)}catch(s){const r=q(s,"errors.fetchQuotaUsage",a);d(r),z(s,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:t}})}finally{c(!1)}}else i(null)},[r,e,t]);return s.useEffect(()=>{u()},[u]),{status:n,loading:o,error:l,refetch:u}},exports.useRecordUsage=e=>{const{t:t}=ds(),{api:a}=Us(),[r,n]=s.useState(!1),[i,o]=s.useState(null);return{recordUsage:s.useCallback(async s=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const t=await a.recordUsage(e,s);return He(),t}catch(a){const r=q(a,"errors.recordUsage",t);throw o(r),z(a,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:s}}),a}finally{n(!1)}},[a,e]),loading:r,error:i}},exports.useResumeSubscription=Ks,exports.useSaaSAuth=xi,exports.useSaaSOs=Es,exports.useSaaSSettings=Is,exports.useSaaSWorkspaces=pi,exports.useSeatStatus=si,exports.useSubscription=Ms,exports.useSubscriptionContext=qs,exports.useSubscriptionManagement=Os,exports.useTranslation=ds,exports.useTrialStatus=function(){const{response:e}=qs();return s.useMemo(()=>{const s=e?.subscription;if(!s||"trialing"!==s.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const t=Xi(s.trialEnd)??Xi(s.stripeCurrentPeriodEnd),a=Xi(s.trialStart),r=t?Math.max(0,Math.ceil((t.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:r,trialEndsAt:t,trialStartedAt:a,isTrialEnding:r<=3}},[e])},exports.useUpdateSubscription=_s,exports.useUsageLogs=(e,t,a)=>{const{t:r}=ds(),{api:n}=Us(),[i,o]=s.useState([]),[c,l]=s.useState(0),[d,u]=s.useState(0),[m,p]=s.useState(1),[h,g]=s.useState(!1),[f,x]=s.useState(!1),[b,y]=s.useState(!1),[v,w]=s.useState(null),S=a?.from,N=a?.to,j=a?.source,k=a?.page,C=a?.limit,A=s.useCallback(async()=>{if(!e)return o([]),l(0),u(0),p(1),g(!1),void x(!1);y(!0),w(null);try{const s={...t&&{quotaSlug:t},...S&&{from:S},...N&&{to:N},...j&&{source:j},...k&&{page:k},...C&&{limit:C}},a=await n.getUsageLogs(e,s);o(a.docs||[]),l(a.totalDocs||0),u(a.totalPages||0),p(a.page||1),g(a.hasNextPage||!1),x(a.hasPrevPage||!1)}catch(s){const a=q(s,"errors.fetchUsageLogs",r);w(a),z(s,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:t}})}finally{y(!1)}},[n,e,t,S,N,j,k,C]);return s.useEffect(()=>{A()},[A]),{logs:i,totalDocs:c,totalPages:d,page:m,hasNextPage:h,hasPrevPage:f,loading:b,error:v,refetch:A}},exports.useUserAttributes=function(){const e=s.useContext(wi);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return e},exports.useUserFeatures=Ri,exports.workspaceSettingsManager=mi;