@buildbase/sdk 0.0.48 → 0.0.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +119 -0
- package/CHANGELOG.md +42 -0
- package/README.md +203 -0
- package/dist/data/index.cjs +1 -0
- package/dist/data/index.mjs +1 -1
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +469 -4
- package/dist/index.mjs +1 -1
- package/dist/react/chunks/SubscriptionDialog-A6oETKbb.cjs +2 -0
- package/dist/react/chunks/SubscriptionDialog-nuMunBn4.mjs +2 -0
- package/dist/react/chunks/ar-BRvKHRYS.cjs +2 -0
- package/dist/react/chunks/ar-IhPhJAZA.mjs +2 -0
- package/dist/react/chunks/de-D3q0vQBG.cjs +2 -0
- package/dist/react/chunks/de-bvh5IFSx.mjs +2 -0
- package/dist/react/chunks/es-B9kiwJmF.cjs +2 -0
- package/dist/react/chunks/es-TyUz4_E1.mjs +2 -0
- package/dist/react/chunks/fr-C500Ytao.cjs +2 -0
- package/dist/react/chunks/fr-CKm-bSvG.mjs +2 -0
- package/dist/react/chunks/hi-CfFhH2uQ.cjs +2 -0
- package/dist/react/chunks/hi-Ck9cPpd-.mjs +2 -0
- package/dist/react/chunks/ja-AM4H1tXw.mjs +2 -0
- package/dist/react/chunks/ja-DfROrx_j.cjs +2 -0
- package/dist/react/chunks/react-CTX0_nOV.cjs +2 -0
- package/dist/react/chunks/react-DzQupoqH.mjs +2 -0
- package/dist/react/chunks/zh-CLmBh-it.cjs +2 -0
- package/dist/react/chunks/zh-DCVPxie-.mjs +2 -0
- package/dist/react/index.cjs +2 -0
- package/dist/react/index.d.ts +9 -1
- package/dist/react/index.mjs +1 -35
- package/package.json +25 -9
- package/dist/data/index.js +0 -1
- package/dist/index.js +0 -1
- package/dist/react/index.js +0 -36
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import{jsxs as e,jsx as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import s,{Component as n,useRef as i,useMemo as o,createContext as c,useReducer as l,useContext as d,useEffect as u,useCallback as m,useState as p,Suspense as h,lazy as g}from"react";import{clsx as f}from"clsx";import{twMerge as b}from"tailwind-merge";import y from"intl-messageformat";import{Loader2 as w,Coins as v,ShieldAlert as x,ShoppingCart as N,RefreshCw as S,CheckCircle2 as k,Trash2 as C,Smile as A,ImageIcon as T,Bell as E,BellOff as P,Mail as I,Smartphone as U,ChevronsUpDown as R,CheckCheck as D,KeyRound as M,Check as _,X as W,Pencil as F,FileText as O,ExternalLink as L,Download as B,AlertTriangle as G,Calendar as K,CreditCard as V,BarChart3 as j,TrashIcon as z,UserIcon as $,SettingsIcon as H,UsersIcon as J,ToggleRight as q,Shield as Y,Settings as Z,Building2 as Q,RefreshCcw as X,Search as ee,Users as ae,Plus as te,Image as re}from"lucide-react";import{Slot as se}from"@radix-ui/react-slot";import{cva as ne}from"class-variance-authority";import*as ie from"@radix-ui/react-dialog";import{Cross2Icon as oe,CheckIcon as ce,MagnifyingGlassIcon as le,CaretSortIcon as de}from"@radix-ui/react-icons";import*as ue from"@radix-ui/react-alert-dialog";import*as me from"@radix-ui/react-switch";import{get as pe,set as he,appendErrors as ge,Controller as fe,FormProvider as be,useFormContext as ye,useForm as we}from"react-hook-form";import*as ve from"zod/v4/core";import{z as xe}from"zod";import*as Ne from"@radix-ui/react-label";import*as Se from"@radix-ui/react-radio-group";import*as ke from"@radix-ui/react-scroll-area";import{Command as Ce}from"cmdk";import*as Ae from"@radix-ui/react-popover";import*as Te from"@radix-ui/react-select";import{SelectValue as Ee}from"@radix-ui/react-select";import*as Pe from"@radix-ui/react-avatar";import*as Ie from"@radix-ui/react-separator";function Ue(...e){return b(f(e))}let Re=!0;function De(e,...a){Re&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...a)}function Me(e,...a){console.error(e,...a)}function _e(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function We(e){const a=await e.text();if(!a)throw new Error("Empty response body");try{return JSON.parse(a)}catch(e){throw new Error(`Invalid JSON response: ${a.substring(0,100)}${a.length>100?"...":""}`)}}async function Fe(e,a="Request failed"){if(!e.ok){let t=a;try{const a=await We(e);t=a.message||a.error||t}catch{t=function(e,a){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||a;return new Error(`${a} (${e.status}: ${t})`)}(e,a).message}throw new Error(t)}try{return await We(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class Oe extends Error{constructor(e,a,t,r){super(e),this.code=a,this.context=t,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,Oe)}}const Le=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&&(Re=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,a={}){if(_e(e))return;const t=e instanceof Error?e:new Oe("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",a),r=t instanceof Oe?t:new Oe(t.message,"SDK_ERROR",a,t);if(this.config.enableConsoleLogging&&De(`[SDK Error] ${a.component||"Unknown"}:`,{message:r.message,code:r.code,context:r.context,originalError:r.originalError,stack:r.stack}),this.config.onError)try{this.config.onError(r,a)}catch(e){Me("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(r,a)}notifyUser(e,a){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:a}}))}wrapAsync(e,a){return(...t)=>e(...t).catch(e=>{throw this.handleError(e,a),e})}wrapSync(e,a){return(...t)=>{try{return e(...t)}catch(e){throw this.handleError(e,a),e}}}};function Be(e,a={}){Le.handleError(e,a)}function Ge(e,a={}){return!_e(e)&&(Le.handleError(e,a),!0)}function Ke(e,a,t){return e instanceof Error?e.message:t(a)}class Ve extends n{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,a){if(Be(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:a.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,a)}catch(e){Me("[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("div",{style:{padding:"1rem",border:"1px solid #ef4444",borderRadius:"0.5rem",backgroundColor:"#fef2f2",color:"#991b1b"},children:[a("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:"Something went wrong"}),a("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),a("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 je=()=>({type:"AUTHENTICATION_STARTED"}),ze=()=>({type:"AUTHENTICATION_PROCESSING"}),$e=()=>({type:"AUTHENTICATION_FAILED"}),He=e=>({type:"SET_SESSION",payload:e}),Je=()=>({type:"REMOVE_SESSION"});function qe(e,a,t){const r=i(a),s=i(t),n=i(void 0),c=i(!1),l=r.current!==a,d=s.current!==t,u=l||d;r.current=a,s.current=t;const m=i(0);u&&(m.current+=1);const p=m.current;return o(()=>{const r=a(e);if(c.current){if(t?t(n.current,r):Object.is(n.current,r))return n.current}return n.current=r,c.current=!0,r},[e,p])}function Ye({name:e,initialState:t,reducer:r,initializer:n}){const i=c(null),d=c(null),u=c(null),m=s.memo(({children:e})=>{const[s,c]=l(r,t,n||(e=>e)),m=o(()=>({state:s,dispatch:c}),[s,c]);return a(u.Provider,{value:m,children:a(i.Provider,{value:s,children:a(d.Provider,{value:c,children:e})})})});m.displayName=`${e}Provider`;const p=a=>new Error(`use${e}${a} must be used within a ${e}Provider. Make sure SaaSOSProvider is wrapping your application.`),h=()=>{const e=s.useContext(i);if(null===e)throw p("State");return e};return{Provider:m,useContext:()=>{const e=s.useContext(u);if(!e)throw p("Context");return e},useState:h,useDispatch:()=>{const e=s.useContext(d);if(null===e)throw p("Dispatch");return e},useSelector:(e,a)=>{const t=e||(e=>e);return qe(h(),t,a)}}}var Ze;function Qe(e){return{isAuthenticated:e===Ze.authenticated,isLoading:e===Ze.loading||e===Ze.redirecting||e===Ze.authenticating,isRedirecting:e===Ze.redirecting}}function Xe(e,a,t){return{...e,[a]:t}}function ea(e,a){return{...e,...a}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(Ze||(Ze={}));const aa=()=>({session:null,status:Ze.loading}),{Provider:ta,useState:ra,useDispatch:sa}=Ye({name:"Auth",initialState:aa(),reducer:(e,a)=>{switch(a.type){case"AUTHENTICATION_STARTED":return Xe(e,"status",Ze.redirecting);case"AUTHENTICATION_PROCESSING":return Xe(e,"status",Ze.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return ea(e,{session:null,status:Ze.unauthenticated});case"SET_SESSION":return ea(e,{session:a.payload,status:Ze.authenticated});default:return e}},initializer:aa}),na=ta,ia=ra,oa=sa,ca=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),la=e=>({type:"SET_SETTINGS",payload:e});var da;function ua(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}!function(e){e.V1="v1"}(da||(da={}));const ma=()=>({serverUrl:"",version:da.V1,orgId:"",settings:null}),{Provider:pa,useState:ha,useDispatch:ga}=Ye({name:"OS",initialState:ma(),reducer:(e,a)=>{switch(a.type){case"SET_SAAS_OS_CONFIG":return ea(e,a.payload);case"REMOVE_SAAS_OS_CONFIG":return ma();case"SET_SETTINGS":return Xe(e,"settings",a.payload);default:return e}}}),fa=pa,ba=ha,ya=ga,wa=e=>({type:"SET_WORKSPACES",payload:e}),va=e=>({type:"ADD_WORKSPACE",payload:e}),xa=e=>({type:"UPDATE_WORKSPACE",payload:e}),Na=e=>({type:"REMOVE_WORKSPACE",payload:e}),Sa=e=>({type:"SET_ALL_FEATURES",payload:e}),ka=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),Ca=()=>({type:"RESET_CURRENT_WORKSPACE"}),Aa=e=>({type:"SET_IS_INITIALIZED",payload:e}),Ta=e=>({type:"SET_LOADING",payload:e}),Ea=e=>({type:"SET_ERROR",payload:e}),Pa=e=>({type:"SET_REFRESHING",payload:e}),Ia=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:Ua,useState:Ra,useDispatch:Da}=Ye({name:"Workspace",initialState:{workspaces:[],loading:!1,error:null,currentWorkspace:null,refreshing:!1,switchingToId:null,isInitialized:!1,allFeatures:[]},reducer:(e,a)=>{switch(a.type){case"SET_WORKSPACES":return Xe(e,"workspaces",a.payload);case"ADD_WORKSPACE":return Xe(e,"workspaces",[...e.workspaces,a.payload]);case"UPDATE_WORKSPACE":return Xe(e,"workspaces",e.workspaces.map(e=>e._id===a.payload._id?a.payload:e));case"REMOVE_WORKSPACE":return Xe(e,"workspaces",e.workspaces.filter(e=>e._id!==a.payload));case"SET_ALL_FEATURES":return Xe(e,"allFeatures",a.payload);case"SET_CURRENT_WORKSPACE":return Xe(e,"currentWorkspace",a.payload);case"RESET_CURRENT_WORKSPACE":return Xe(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return Xe(e,"isInitialized",a.payload);case"SET_LOADING":return Xe(e,"loading",a.payload);case"SET_ERROR":return Xe(e,"error",a.payload);case"SET_REFRESHING":return Xe(e,"refreshing",a.payload);case"SET_SWITCHING_TO_ID":return Xe(e,"switchingToId",a.payload);default:return e}}}),Ma=Ua,_a=Ra,Wa=Da,Fa=s.memo(({children:e})=>a(fa,{children:a(na,{children:a(Ma,{children:e})})}));Fa.displayName="SDKContextProvider";const Oa=c({});Oa.displayName="CheckoutConfigContext";const La=s.memo(({getCheckoutStripeParams:e,children:t})=>{const r=s.useMemo(()=>({getCheckoutStripeParams:e}),[e]);return a(Oa.Provider,{value:r,children:t})});function Ba(){const e=new Set;return{subscribe:a=>(e.add(a),()=>{e.delete(a)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}La.displayName="CheckoutConfigProvider";const Ga=Ba(),Ka=Ga.subscribe,Va=Ga.invalidate,ja=Ba(),za=ja.subscribe,$a=ja.invalidate,Ha={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"}},Ja={en:async()=>Ha,es:async()=>(await import("./es-TyUz4_E1.mjs")).es,fr:async()=>(await import("./fr-CKm-bSvG.mjs")).fr,de:async()=>(await import("./de-bvh5IFSx.mjs")).de,ja:async()=>(await import("./ja-AM4H1tXw.mjs")).ja,zh:async()=>(await import("./zh-DCVPxie-.mjs")).zh,hi:async()=>(await import("./hi-Ck9cPpd-.mjs")).hi,ar:async()=>(await import("./ar-IhPhJAZA.mjs")).ar},qa=["en","es","fr","de","ja","zh","hi","ar"];const Ya={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};const Za=c({messages:Ha,locale:"en",formattingLocale:"en"});function Qa({locale:e="en",children:a}){const t=function(e){const a=e.toLowerCase().replace("_","-");if(qa.includes(a))return a;const t=a.split("-")[0];return qa.includes(t)?t:"en"}(e),[r,n]=s.useState(Ha);s.useEffect(()=>{if("en"===t)return void n(Ha);let e=!1;const a=Ja[t];return a&&a().then(a=>{e||n(a)}),()=>{e=!0}},[t]);const i=function(e){return Ya[e]??e}(t),c=o(()=>({messages:r,locale:t,formattingLocale:i}),[r,t,i]);return s.createElement(Za.Provider,{value:c},a)}const Xa=new Map,et=new Map,at=new Map;function tt(e,a){return a?`${e}:${JSON.stringify(a)}`:e}const rt={getNumberFormat(e,a){const t=tt(e,a);let r=Xa.get(t);return r||(r=new Intl.NumberFormat(e,a),Xa.set(t,r)),r},getDateTimeFormat(e,a){const t=tt(e,a);let r=et.get(t);return r||(r=new Intl.DateTimeFormat(e,a),et.set(t,r)),r},getPluralRules(e,a){const t=tt(e,a);let r=at.get(t);return r||(r=new Intl.PluralRules(e,a),at.set(t,r)),r}},st=new Map;function nt(){const{messages:e,locale:a,formattingLocale:t}=d(Za),r=o(()=>(a,r)=>{const s=a.split(".");let n=e;for(const e of s){if(!n||"object"!=typeof n||!(e in n))return a;n=n[e]}const i="string"==typeof n?n:a;if(!r)return i;try{const e=function(e,a){const t=`${a}:${e}`;let r=st.get(t);return r||(r=new y(e,a,void 0,{formatters:rt}),st.set(t,r)),r}(i,t),a=e.format(r);return"string"==typeof a?a:String(a)}catch{return i.replace(/\{(\w+)\}/g,(e,a)=>String(r[a]??`{${a}}`))}},[e,t]),s="ar"===a?"rtl":"ltr",n=o(()=>e=>e.toLocaleString(t),[t]),i=o(()=>(e,a)=>{const r=(a??"").trim().toUpperCase();if(!r)return(e/100).toLocaleString(t,{minimumFractionDigits:2});try{return new Intl.NumberFormat(t,{style:"currency",currency:r,minimumFractionDigits:2}).format(e/100)}catch{return(e/100).toLocaleString(t,{minimumFractionDigits:2})}},[t]);return{t:r,locale:a,formattingLocale:t,dir:s,fmtNum:n,fmtCents:i,messages:e}}function it(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(a){return Be(a,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function ot(e,a){if("undefined"!=typeof window)try{localStorage.setItem(e,a)}catch(a){Be(a,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function ct(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(a){Be(a,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}const lt="saas-session-id",dt="code",ut="state";function mt(e){ot(lt,e)}function pt(){return function(){if("undefined"==typeof window)return null;try{return it(lt)}catch(e){return Be(e,{component:"auth-utils",action:"getSessionId",metadata:{key:lt}}),null}}()}function ht(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(dt)}catch(e){return Be(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:dt}}),null}}function gt(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(dt),e.searchParams.delete(ut),window.history.replaceState({},"",e.toString())}catch(e){Be(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:dt}})}}const ft=new WeakSet,bt="SDK is not ready (missing serverUrl, version, or orgId)";class yt{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(bt);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(bt)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=pt(),a={};return e&&(a["x-session-id"]=e),a}()}url(e){const a=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${a}`}buildHeaders(e){const a={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(a,e.headers),null==e.body||a["Content-Type"]||(a["Content-Type"]="application/json"),a}reportError(e,a){ft.has(e)||(ft.add(e),this._onError?.(e,a))}async executeFetch(e,a){return this.executeFetchUrl(this.url(e),a,e)}async executeFetchUrl(e,a,t){const r=(a.method??"GET").toUpperCase(),s=t??e,n=this.buildHeaders(a),i={...a,headers:n};let o;if(this._timeout>0){const e=new AbortController;o=setTimeout(()=>e.abort(),this._timeout),i.signal=a.signal?function(e,a){const t=AbortSignal.any;if("function"==typeof t)return t([e,a]);const r=new AbortController,s=e=>{r.signal.aborted||r.abort(e.reason)};for(const t of[e,a]){if(t.aborted){s(t);break}t.addEventListener("abort",()=>s(t),{once:!0})}return r.signal}(a.signal,e.signal):e.signal}const c=async a=>{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),s=await t(e,i);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&a<this._maxRetries){const e=Math.min(1e3*Math.pow(2,a),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${a+1}/${this._maxRetries})`),await new Promise(a=>setTimeout(a,e)),c(a+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(void 0!==o){const e=new Error(`Request timeout after ${this._timeout}ms: ${r} ${s}`);throw this.reportError(e,{method:r,path:s}),e}throw e}if(a<this._maxRetries){const e=Math.min(1e3*Math.pow(2,a),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${a+1}/${this._maxRetries})`),await new Promise(a=>setTimeout(a,e)),c(a+1)}throw e instanceof Error&&this.reportError(e,{method:r,path:s}),e}};try{return await c(0)}finally{void 0!==o&&clearTimeout(o)}}async fetchJson(e,a={},t="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,a);return await Fe(r,t)}catch(t){throw t instanceof Error&&this.reportError(t,{method:(a.method??"GET").toUpperCase(),path:e}),t}}async fetchResponse(e,a={}){return this.ensureReady(),this.executeFetch(e,a)}async fetchAbsoluteUrl(e,a={}){return this.ensureReady(),this.executeFetchUrl(e,a)}async throwResponseError(e,a){let t=a;try{t=(await e.json()).message||t}catch{t=`${a} (${e.status}: ${e.statusText})`}throw new Error(t)}async unwrapResponse(e,a){const t=await e.json();if(void 0!==t.success){if(!t.success)throw new Error(t.message||a);return t.data||t}return t}}class wt extends yt{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,a){return this.fetchJson(`workspaces/${e}`,{method:"PUT",body:JSON.stringify(a)},"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,a){return this.fetchJson(`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(a)},"Failed to invite member")}async removeUser(e,a){return this.fetchJson(`workspaces/${e}/users/${a}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,a,t){return this.fetchJson(`workspaces/${e}/users/${a}`,{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,a){return this.fetchJson(`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:a})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,a,t){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[a]: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,a){await this.fetchJson(`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:a})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const a=await this.fetchResponse(`workspaces/${e}/subscription`);return a.ok||await this.throwResponseError(a,"Failed to fetch subscription"),this.unwrapResponse(a,"Failed to fetch subscription")}async getPlanGroup(e){const a=await this.fetchResponse(`workspaces/${e}/subscription/plan-group`);return a.ok||await this.throwResponseError(a,"Failed to fetch plan group"),this.unwrapResponse(a,"Failed to fetch plan group")}async getPlanGroupByVersion(e,a){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${encodeURIComponent(a)}`);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 a=await this.fetchResponse(`workspaces/${e}/subscription/plan-group/versions`);return a.ok||await this.throwResponseError(a,"Failed to fetch plan group versions"),this.unwrapResponse(a,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const a=await this.fetchResponse(`${this.orgId}/plans/${encodeURIComponent(e)}`);return a.ok||await this.throwResponseError(a,"Failed to fetch plans"),this.unwrapResponse(a,"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 a=await this.fetchResponse(`plan-group-versions/${e}`);return a.ok||await this.throwResponseError(a,"Failed to fetch plan group version"),this.unwrapResponse(a,"Failed to fetch plan group version")}async createCheckoutSession(e,a){const t=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(a)});return t.ok||await this.throwResponseError(t,"Failed to create checkout session"),this.unwrapResponse(t,"Failed to create checkout session")}async selectFreePlan(e,a){const t=await this.fetchResponse(`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:a})});return t.ok||await this.throwResponseError(t,"Failed to select free plan"),t.json()}async updateSubscription(e,a){const t=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(a)});return t.ok||await this.throwResponseError(t,"Failed to update subscription"),this.unwrapResponse(t,"Failed to update subscription")}async createBillingPortalSession(e,a){return this.fetchJson(`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(a?{returnUrl:a}:{})})}async listInvoices(e,a=10,t){const r=new URLSearchParams;r.append("limit",a.toString()),t&&r.append("starting_after",t);const s=await this.fetchResponse(`workspaces/${e}/subscription/invoices?${r.toString()}`);return s.ok||await this.throwResponseError(s,"Failed to fetch invoices"),this.unwrapResponse(s,"Failed to fetch invoices")}async getInvoice(e,a){const t=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${a}`);return t.ok||await this.throwResponseError(t,"Failed to fetch invoice"),this.unwrapResponse(t,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const a=await this.fetchResponse(`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return a.ok||await this.throwResponseError(a,"Failed to cancel subscription"),this.unwrapResponse(a,"Failed to cancel subscription")}async resumeSubscription(e){const a=await this.fetchResponse(`workspaces/${e}/subscription/resume`,{method:"POST"});return a.ok||await this.throwResponseError(a,"Failed to resume subscription"),this.unwrapResponse(a,"Failed to resume subscription")}async recordUsage(e,a){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(a)});return t.ok||await this.throwResponseError(t,"Failed to record usage"),this.unwrapResponse(t,"Failed to record usage")}async recordUsageBatch(e,a){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(a)});return t.ok||await this.throwResponseError(t,"Failed to record batch usage"),this.unwrapResponse(t,"Failed to record batch usage")}async getQuotaUsageStatus(e,a){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(a)}`);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 a=await this.fetchResponse(`workspaces/${e}/subscription/usage/all`);return a.ok||await this.throwResponseError(a,"Failed to fetch all quota usage"),this.unwrapResponse(a,"Failed to fetch all quota usage")}async getUsageLogs(e,a){const t=new URLSearchParams;a?.quotaSlug&&t.append("quotaSlug",a.quotaSlug),a?.from&&t.append("from",a.from),a?.to&&t.append("to",a.to),a?.source&&t.append("source",a.source),a?.page&&t.append("page",a.page.toString()),a?.limit&&t.append("limit",a.limit.toString());const r=t.toString(),s=`workspaces/${e}/subscription/usage/logs${r?`?${r}`:""}`,n=await this.fetchResponse(s);return n.ok||await this.throwResponseError(n,"Failed to fetch usage logs"),this.unwrapResponse(n,"Failed to fetch usage logs")}async sendNotification(e,a,t,r){const s={event:a};return t&&(s.userId=t),r&&(s.data=r),this.fetchJson(`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(s)},"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,a){return(await this.fetchJson(`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:a})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const a=await this.fetchResponse(`workspaces/${e}/credits`);return a.ok||await this.throwResponseError(a,"Failed to fetch credit balance"),this.unwrapResponse(a,"Failed to fetch credit balance")}async consumeCredits(e,a){const t=await this.fetchResponse(`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(a)});if(!t.ok){if(402===t.status){const e=await t.json().catch(()=>({})),a=new Error(e.message||"Insufficient credits");throw a.available=e.available,a.requested=e.requested,a.code="INSUFFICIENT_CREDITS",a}await this.throwResponseError(t,"Failed to consume credits")}return this.unwrapResponse(t,"Failed to consume credits")}async purchaseCredits(e,a){const t=await this.fetchResponse(`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(a)});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 a=await this.fetchResponse(`workspaces/${e}/credits/packages`);a.ok||await this.throwResponseError(a,"Failed to fetch credit packages");const t=await this.unwrapResponse(a,"Failed to fetch credit packages");return t.docs??t}async getCreditTransactions(e,a){const t=new URLSearchParams;a?.type&&t.append("type",a.type),a?.page&&t.append("page",a.page.toString()),a?.limit&&t.append("limit",a.limit.toString());const r=t.toString(),s=`workspaces/${e}/credits/transactions${r?`?${r}`:""}`,n=await this.fetchResponse(s);return n.ok||await this.throwResponseError(n,"Failed to fetch credit transactions"),this.unwrapResponse(n,"Failed to fetch credit transactions")}async getCreditBuckets(e,a){const t=new URLSearchParams;a?.status&&t.append("status",a.status),a?.source&&t.append("source",a.source),a?.page&&t.append("page",a.page.toString()),a?.limit&&t.append("limit",a.limit.toString());const r=t.toString(),s=`workspaces/${e}/credits/buckets${r?`?${r}`:""}`,n=await this.fetchResponse(s);return n.ok||await this.throwResponseError(n,"Failed to fetch credit buckets"),this.unwrapResponse(n,"Failed to fetch credit buckets")}async getExpiringCredits(e,a){const t=a?`?days=${a}`:"",r=await this.fetchResponse(`workspaces/${e}/credits/expiring${t}`);return r.ok||await this.throwResponseError(r,"Failed to fetch expiring credits"),this.unwrapResponse(r,"Failed to fetch expiring credits")}}function vt(){const e=oa(),a=ya(),t=Wa();return o(()=>({auth:e,os:a,workspaces:t}),[e,a,t])}function xt(e,a){const t=ba(),r=ia(),s=_a(),n=e||(e=>e);return qe(o(()=>({os:t,auth:r,workspaces:s}),[t,r,s]),n,a)}function Nt(e,a,t){u(()=>{const a=new AbortController;return e(a.signal).catch(e=>{_e(e)||(t?.onError?t.onError(e):Be(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>a.abort()},a)}class St extends yt{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}function kt(){return xt(e=>e.os)}let Ct=null;function At(){const e=vt(),a=kt(),{serverUrl:t,version:r,orgId:s,settings:n}=a,i=o(()=>ua(a)?new St({serverUrl:t,version:r,orgId:s}):null,[t,r,s]),c=m(async a=>i?Ct||(Ct=(async()=>{try{const t=await i.getSettings(a);return e.os(la(t)),t}catch(e){return Ge(e,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:t,version:r,orgId:s}}),null}finally{Ct=null}})(),Ct):null,[i,e,t,r,s]);return Nt(async e=>{n||ua(a)&&await c(e)},[t,r,s],{onError:e=>Ge(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:t,version:r,orgId:s}})}),o(()=>({settings:n,getSettings:c}),[n,c])}function Tt(){const e=kt(),a=m(()=>{e.auth?.callbacks?.onSessionExpired?.("expired")},[e.auth?.callbacks?.onSessionExpired]),t=function(e,a){return o(()=>new wt({...e,onUnauthorized:a}),[e.serverUrl,e.version,e.orgId,a])}(e,a);return o(()=>({os:e,api:t}),[e,t])}const Et=e=>{const{t:a}=nt(),{os:t,api:r}=Tt(),s=ua(t),[n,i]=p(null),[o,c]=p(!1),[l,d]=p(null),h=m(async()=>{if(e&&s){c(!0),d(null);try{const a=await r.getPublicPlans(e);i(a)}catch(t){const r=Ke(t,"errors.fetchPlans",a);d(r),Be(t,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{c(!1)}}else i(null)},[r,e,s]);u(()=>{h()},[h]);const g=e&&!s||o;return{items:n?.items??[],plans:n?.plans??[],notes:n?.notes,loading:g,error:l,refetch:h}},Pt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(null),[n,i]=p(!1),[o,c]=p(null),l=m(async()=>{if(e){i(!0),c(null);try{const a=await t.getPlanGroupVersion(e);s(a)}catch(t){const r=Ke(t,"errors.fetchPlanGroupVersion",a);c(r),Be(t,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{i(!1)}}else s(null)},[t,e]);return u(()=>{l()},[l]),{planGroupVersion:r,loading:n,error:o,refetch:l}},It=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(null),[n,i]=p(!1),[o,c]=p(null),l=m(async()=>{if(e){i(!0),c(null);try{const a=await t.getCurrentSubscription(e);s(a)}catch(t){const r=Ke(t,"errors.fetchSubscription",a);c(r),Be(t,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{i(!1)}}else s(null)},[t,e]);return u(()=>{l()},[l]),{subscription:r,loading:n,error:o,refetch:l}},Ut=(e,a)=>{const{t:t}=nt(),{api:r}=Tt(),[s,n]=p(null),[i,o]=p(!1),[c,l]=p(null),d=m(async()=>{if(e){o(!0),l(null);try{const t=a?await r.getPlanGroupByVersion(e,a):await r.getPlanGroup(e);n(t)}catch(r){const s=Ke(r,"errors.fetchPlanGroup",t);l(s),Be(r,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:a}})}finally{o(!1)}}else n(null)},[r,e,a]);return u(()=>{d()},[d]),{planGroup:s,loading:i,error:c,refetch:d}},Rt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(null),[n,i]=p(!1),[o,c]=p(null),l=m(async()=>{if(e){i(!0),c(null);try{const a=await t.getPlanGroupVersions(e);s(a)}catch(t){const r=Ke(t,"errors.fetchPlanGroupVersions",a);c(r),Be(t,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{i(!1)}}else s(null)},[t,e]);return u(()=>{l()},[l]),{versions:r,loading:n,error:o,refetch:l}},Dt=e=>{const{t:a}=nt(),{api:t}=Tt(),{getCheckoutStripeParams:r}=d(Oa),[s,n]=p(!1),[i,o]=p(null);return{createCheckoutSession:m(async s=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{let a=s;if(r){const e=await r(s);e&&(a={...s,stripeOptions:{...s.stripeOptions,...e,metadata:{...s.stripeOptions?.metadata,...e.metadata},subscriptionMetadata:{...s.stripeOptions?.subscriptionMetadata,...e.subscriptionMetadata}}})}const n=await t.createCheckoutSession(e,a);return"trial_started"===n.type&&($a(),Va()),n}catch(t){const r=Ke(t,"errors.createCheckout",a);throw o(r),Be(t,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:s}}),t}finally{n(!1)}},[t,e,r]),loading:s,error:i}},Mt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(!1),[n,i]=p(null);return{updateSubscription:m(async(r,n)=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const a={planVersionId:r,...n?.billingInterval&&{billingInterval:n.billingInterval},...n?.successUrl&&{successUrl:n.successUrl},...n?.cancelUrl&&{cancelUrl:n.cancelUrl}},s=await t.updateSubscription(e,a);return $a(),s}catch(t){const s=Ke(t,"errors.updateSubscription",a);throw i(s),Be(t,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:r,options:n}}),t}finally{s(!1)}},[t,e]),loading:r,error:n}},_t=(e,a)=>{const t=It(e),r=Ut(e,a),s=Mt(e),n=m(async()=>{await Promise.all([t.refetch(),r.refetch()])},[t.refetch,r.refetch]);return{subscription:t.subscription,planGroup:r.planGroup,loading:t.loading||r.loading||s.loading,error:t.error||r.error||s.error,updateSubscription:s.updateSubscription,refetch:n}},Wt=(e,a=10,t)=>{const{t:r}=nt(),{api:s}=Tt(),[n,i]=p([]),[o,c]=p(!1),[l,d]=p(!1),[h,g]=p(null),f=m(async()=>{if(!e)return i([]),void c(!1);d(!0),g(null);try{const r=await s.listInvoices(e,a,t);i(r.invoices||[]),c(r.has_more||!1)}catch(s){const n=Ke(s,"errors.fetchInvoices",r);g(n),Be(s,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:a,startingAfter:t}})}finally{d(!1)}},[s,e,a,t]);return u(()=>{f()},[f]),{invoices:n,hasMore:o,loading:l,error:h,refetch:f}},Ft=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(!1),[n,i]=p(null);return{openBillingPortal:m(async r=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const a=r||window.location.href,s=await t.createBillingPortalSession(e,a);return s.url&&window.open(s.url,"_blank","noopener,noreferrer"),s}catch(t){const r=Ke(t,"errors.openBillingPortal",a);throw i(r),Be(t,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),t}finally{s(!1)}},[e,t]),loading:r,error:n}},Ot=(e,a)=>{const{t:t}=nt(),{api:r}=Tt(),[s,n]=p(null),[i,o]=p(!1),[c,l]=p(null),d=m(async()=>{if(e&&a){o(!0),l(null);try{const t=await r.getInvoice(e,a);n(t.invoice)}catch(r){const s=Ke(r,"errors.fetchInvoice",t);l(s),Be(r,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:a}})}finally{o(!1)}}else n(null)},[r,e,a]);return u(()=>{d()},[d]),{invoice:s,loading:i,error:c,refetch:d}},Lt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(!1),[n,i]=p(null);return{cancelSubscription:m(async()=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const a=await t.cancelSubscriptionAtPeriodEnd(e);return $a(),a}catch(t){const r=Ke(t,"errors.cancelSubscription",a);throw i(r),Be(t,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),t}finally{s(!1)}},[t,e]),loading:r,error:n}},Bt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(!1),[n,i]=p(null);return{resumeSubscription:m(async()=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const a=await t.resumeSubscription(e);return $a(),a}catch(t){const r=Ke(t,"errors.resumeSubscription",a);throw i(r),Be(t,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),t}finally{s(!1)}},[t,e]),loading:r,error:n}},Gt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(!1),[n,i]=p(null);return{recordUsage:m(async r=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const a=await t.recordUsage(e,r);return Va(),a}catch(t){const s=Ke(t,"errors.recordUsage",a);throw i(s),Be(t,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:r}}),t}finally{s(!1)}},[t,e]),loading:r,error:n}},Kt=(e,a)=>{const{t:t}=nt(),{api:r}=Tt(),[s,n]=p(null),[i,o]=p(!1),[c,l]=p(null),d=m(async()=>{if(e&&a){o(!0),l(null);try{const t=await r.getQuotaUsageStatus(e,a);n(t)}catch(r){const s=Ke(r,"errors.fetchQuotaUsage",t);l(s),Be(r,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:a}})}finally{o(!1)}}else n(null)},[r,e,a]);return u(()=>{d()},[d]),{status:s,loading:i,error:c,refetch:d}},Vt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(null),[n,i]=p(!1),[o,c]=p(null),l=m(async()=>{if(e){i(!0),c(null);try{const a=await t.getAllQuotaUsage(e);s(a.quotas)}catch(t){const r=Ke(t,"errors.fetchAllQuotaUsage",a);c(r),Be(t,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{i(!1)}}else s(null)},[t,e]);return u(()=>{l()},[l]),{quotas:r,loading:n,error:o,refetch:l}},jt=(e,a,t)=>{const{t:r}=nt(),{api:s}=Tt(),[n,i]=p([]),[o,c]=p(0),[l,d]=p(0),[h,g]=p(1),[f,b]=p(!1),[y,w]=p(!1),[v,x]=p(!1),[N,S]=p(null),k=t?.from,C=t?.to,A=t?.source,T=t?.page,E=t?.limit,P=m(async()=>{if(!e)return i([]),c(0),d(0),g(1),b(!1),void w(!1);x(!0),S(null);try{const t={...a&&{quotaSlug:a},...k&&{from:k},...C&&{to:C},...A&&{source:A},...T&&{page:T},...E&&{limit:E}},r=await s.getUsageLogs(e,t);i(r.docs||[]),c(r.totalDocs||0),d(r.totalPages||0),g(r.page||1),b(r.hasNextPage||!1),w(r.hasPrevPage||!1)}catch(t){const s=Ke(t,"errors.fetchUsageLogs",r);S(s),Be(t,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:a}})}finally{x(!1)}},[s,e,a,k,C,A,T,E]);return u(()=>{P()},[P]),{logs:n,totalDocs:o,totalPages:l,page:h,hasNextPage:f,hasPrevPage:y,loading:v,error:N,refetch:P}},zt=c(null);zt.displayName="SubscriptionContext";const $t=s.memo(function({children:e}){const t=xt(e=>e.workspaces.currentWorkspace),{subscription:r,loading:s,error:n,refetch:i}=It(t?._id);u(()=>za(i),[i]);const c=o(()=>({response:r,loading:s,error:n,refetch:i}),[r,s,n,i]);return a(zt.Provider,{value:c,children:e})});function Ht(){const e=d(zt);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}$t.displayName="SubscriptionContextProvider";const Jt=Ba(),qt=Jt.subscribe,Yt=Jt.invalidate,Zt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(null),[n,i]=p(!1),[o,c]=p(null),l=m(async()=>{if(e){i(!0),c(null);try{const a=await t.getCreditBalance(e);s(a)}catch(t){const r=Ke(t,"errors.fetchCreditBalance",a);c(r),Be(t,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{i(!1)}}else s(null)},[t,e]);return u(()=>{l()},[l]),{balance:r,loading:n,error:o,refetch:l}},Qt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(!1),[n,i]=p(null);return{consumeCredits:m(async r=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const a=await t.consumeCredits(e,r);return Yt(),a}catch(t){const s="INSUFFICIENT_CREDITS"===t.code?`Insufficient credits. Available: ${t.available}, requested: ${t.requested}`:Ke(t,"errors.consumeCredits",a);throw i(s),Be(t,{component:"useConsumeCredits",action:"consumeCredits",metadata:{workspaceId:e,request:r}}),t}finally{s(!1)}},[t,e]),loading:r,error:n}},Xt=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p(!1),[n,i]=p(null);return{purchaseCredits:m(async r=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{return await t.purchaseCredits(e,r)}catch(t){const s=Ke(t,"errors.purchaseCredits",a);throw i(s),Be(t,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:r}}),t}finally{s(!1)}},[t,e]),loading:r,error:n}},er=e=>{const{t:a}=nt(),{api:t}=Tt(),[r,s]=p([]),[n,i]=p(!1),[o,c]=p(null),l=m(async()=>{if(e){i(!0),c(null);try{const a=await t.getCreditPackages(e);s(a)}catch(t){const r=Ke(t,"errors.fetchCreditPackages",a);c(r),Be(t,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{i(!1)}}else s([])},[t,e]);return u(()=>{l()},[l]),{packages:r,loading:n,error:o,refetch:l}},ar=(e,a)=>{const{t:t}=nt(),{api:r}=Tt(),[s,n]=p([]),[i,o]=p(0),[c,l]=p(0),[d,h]=p(1),[g,f]=p(!1),[b,y]=p(!1),[w,v]=p(!1),[x,N]=p(null),S=a?.type,k=a?.page,C=a?.limit,A=m(async()=>{if(!e)return n([]),o(0),l(0),h(1),f(!1),void y(!1);v(!0),N(null);try{const a=await r.getCreditTransactions(e,{type:S,page:k,limit:C});n(a.docs||[]),o(a.totalDocs||0),l(a.totalPages||0),h(a.page||1),f(a.hasNextPage||!1),y(a.hasPrevPage||!1)}catch(a){const r=Ke(a,"errors.fetchCreditTransactions",t);N(r),Be(a,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{v(!1)}},[r,e,S,k,C]);return u(()=>{A()},[A]),{transactions:s,totalDocs:i,totalPages:c,page:d,hasNextPage:g,hasPrevPage:b,loading:w,error:x,refetch:A}},tr=(e,a)=>{const{t:t}=nt(),{api:r}=Tt(),[s,n]=p(null),[i,o]=p(!1),[c,l]=p(null),d=m(async()=>{if(e){o(!0),l(null);try{const t=await r.getExpiringCredits(e,a);n(t)}catch(r){const s=Ke(r,"errors.fetchExpiringCredits",t);l(s),Be(r,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:a}})}finally{o(!1)}}else n(null)},[r,e,a]);return u(()=>{d()},[d]),{expiringCredits:s?.expiringCredits??0,buckets:s?.buckets??[],days:s?.days??a??7,loading:i,error:c,refetch:d}},rr=()=>{const{t:e}=nt(),{os:a,api:t}=Tt(),r=ua(a),[s,n]=p([]),[i,o]=p(),[c,l]=p(!1),[d,h]=p(null),g=m(async()=>{if(r){l(!0),h(null);try{const e=await t.getPublicCreditPackages();n(e.packages||[]),o(e.notes)}catch(a){const t=Ke(a,"errors.fetchCreditPackages",e);h(t),Be(a,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{l(!1)}}else n([])},[t,r]);u(()=>{g()},[g]);return{packages:s,notes:i,loading:!r||c,error:d,refetch:g}},sr=c(null);sr.displayName="CreditBalanceContext";const nr=s.memo(function({children:e}){const t=xt(e=>e.workspaces.currentWorkspace),{balance:r,loading:s,error:n,refetch:i}=Zt(t?._id);u(()=>qt(i),[i]);const c=o(()=>({balance:r,loading:s,error:n,refetch:i}),[r,s,n,i]);return a(sr.Provider,{value:c,children:e})});function ir(){const e=d(sr);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}nr.displayName="CreditBalanceContextProvider";const or=({message:r})=>e(t,{children:[a("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"}}),a("p",{"aria-hidden":"true",style:{marginTop:16,color:"#6b7280",fontSize:14},children:r}),a("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 "})]}),cr=({children:t,message:r="Loading...",backgroundColor:s})=>e("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:s??void 0},children:[a("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:r}),t??a(or,{message:r}),a("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 "})]});cr.displayName="FullScreenLoader";const lr=c(null),dr=({children:t,loadingComponent:r})=>{const[s,n]=p({visible:!1,message:""}),c=i(null),l=m(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),d=m(()=>{l(),n({visible:!1,message:""})},[l]),h=m(e=>{l(),n({visible:!0,message:e}),c.current=setTimeout(()=>{Be(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),n({visible:!1,message:""})},6e4)},[l]);u(()=>()=>l(),[l]);const g=o(()=>({show:h,hide:d,visible:s.visible,message:s.message}),[h,d,s.visible,s.message]),f="function"==typeof r?r({message:s.message}):r;return e(lr.Provider,{value:g,children:[t,s.visible&&a(cr,{message:s.message,children:f})]})};function ur(){const e=d(lr);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}dr.displayName="FullScreenLoaderProvider";const mr=c({appPermissions:void 0});function pr({appPermissions:e,children:t}){const r=o(()=>({appPermissions:e}),[e]);return a(mr.Provider,{value:r,children:t})}function hr(){return d(mr)}const gr=c(null);gr.displayName="QuotaUsageContext";const fr=s.memo(function({children:e}){const t=xt(e=>e.workspaces.currentWorkspace),{quotas:r,loading:s,error:n,refetch:i}=Vt(t?._id);u(()=>Ka(i),[i]);const c=o(()=>({quotas:r,loading:s,error:n,refetch:i}),[r,s,n,i]);return a(gr.Provider,{value:c,children:e})});function br(){const e=d(gr);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 yr(e){if(!e||"string"!=typeof e)return null;try{const a=new URL(e);return"https:"===a.protocol?e:"http:"!==a.protocol||"localhost"!==a.hostname&&"127.0.0.1"!==a.hostname&&"::1"!==a.hostname?null:e}catch{return null}}function wr(e,a="/"){if("undefined"==typeof window||!window.location)return!1;const t=yr(e);return window.location.href=t??a,!0}fr.displayName="QuotaUsageContextProvider";const vr="saas-auth-intent";function xr(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function Nr(e){yr(e)&&function(e,a){try{ot(e,JSON.stringify(a))}catch(a){Be(a,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}(vr,{returnUrl:e,createdAt:Date.now()})}function Sr(){const e=function(e,a){const t=it(e);if(!t)return null;try{const r=JSON.parse(t);return a&&!a(r)?(Be(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),ct(e),null):r}catch(a){return Be(a,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),ct(e),null}}(vr,xr);return ct(vr),e?Date.now()-e.createdAt>6e5?null:yr(e.returnUrl):null}const kr="saas-oauth-state";function Cr(){ct(kr)}class Ar extends yt{constructor(e){super(e)}async requestAuth(e){const a=`${this.serverUrl}/api/${this.version}/auth/request`,t=await this.fetchAbsoluteUrl(a,{method:"POST",body:JSON.stringify(e)});return t.ok||await this.throwResponseError(t,"Failed to initiate authentication"),t.json()}async getProfile(e,a){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:a},"Failed to fetch user profile")}}const Tr="bb",Er="checkout",Pr="billing",Ir="selectPlan",Ur="creditPurchase",Rr="openCreditStore",Dr="success",Mr="cancel",_r="error",Wr="subscription",Fr="credits";function Or(e,a){let t;try{const e=a||("undefined"!=typeof window?window.location.href:"https://localhost");t=new URL(e),t.search=""}catch{t=new URL("https://localhost")}return t.searchParams.set(Tr,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,a])=>`${encodeURIComponent(e)}:${encodeURIComponent(a)}`).join(",")}(e)),t.toString()}function Lr(e,a){const t="undefined"!=typeof window?window.location.href:void 0;return{successUrl:Or({action:Ur,status:Dr,ws:e,screen:Fr},t),cancelUrl:Or({action:Ur,status:Mr,ws:e,screen:Fr},t)}}function Br(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(Tr);if(!e)return null;const a=function(e){const a={};if(!e)return a;const t=e.split(",");for(const e of t){const t=e.indexOf(":");if(-1===t)continue;const r=decodeURIComponent(e.slice(0,t)),s=decodeURIComponent(e.slice(t+1));r&&(a[r]=s)}return a}(e);return Object.keys(a).length>0?a:null}catch{return null}}function Gr(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(Tr)&&(e.searchParams.delete(Tr),window.history.replaceState({},"",e.toString()))}catch{}}const Kr={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},Vr="active",jr="trialing",zr="canceled",$r="past_due",Hr="paused",Jr="draft",qr="open",Yr="paid",Zr="uncollectible",Qr="void",Xr={Feature:"feature",Limit:"limit",Quota:"quota"},es="none",as="final",ts="suspended",rs="plan_grant",ss="pack_purchased",ns="consumed",is="expired",os="admin_grant",cs="admin_revoke",ls="refund";function ds(e,a){const t=e.pricingVariants;if(!t?.length)return null;const r=a.toLowerCase();return t.find(e=>e.currency?.toLowerCase()===r)??null}function us(e,a,t){const r=ds(e,a);if(!r?.basePricing)return null;const s=r.basePricing[t];return null!=s?s:null}function ms(e,a,t,r){const s=ds(e,a),n=s?.quotaOverages?.[t];if(n)return n[r]}function ps(e){const a=new Set;for(const t of e)t.pricingVariants?.forEach(e=>{e.currency&&a.add(e.currency.toLowerCase())});return Array.from(a).sort()}function hs(e,a,t,r){const s=e.quotas?.[t];if(null==s)return null;const n=s[r];if(!n)return null;const i=ms(e,a,t,r);return{included:n.included,...void 0!==n.unitSize&&{unitSize:n.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==s.allowOverage}}function gs(e,a){if(!e)return null;for(const t of a){const a=t.pricingVariants;if(a?.length)for(const t of a){const a=t.stripePrices;if(a){if(a.monthlyPriceId===e||a.monthly===e)return{interval:"monthly",currency:t.currency};if(a.yearlyPriceId===e||a.yearly===e)return{interval:"yearly",currency:t.currency};if(a.quarterlyPriceId===e)return{interval:"quarterly",currency:t.currency}}}}return null}function fs(e,a){const t=ds(e,a);return t?.seatPricing?.enabled?t.seatPricing:null}function bs(e,a,t){const r=fs(e,a);return r?.perSeat?r.perSeat[t]??null:null}function ys(e){const{planVersion:a,currency:t="usd",settingsMaxUsers:r}=e;if(a){const e=fs(a,t);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function ws(e){const{memberCount:a,maxUsersConfig:t,hasSubscription:r=!0,requireSubscription:s=!1}=e;if(s&&!r)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(a>=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 vs="user:created",xs="user:updated",Ns="workspace:changed",Ss="workspace:updated",ks="workspace:user-added",Cs="workspace:user-removed",As="workspace:user-role-changed",Ts="workspace:created",Es="workspace:deleted";const Ps=new class{constructor(){this.callbacks=null}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,a){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,a)}catch(a){Be(a,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(vs,{user:e})}async emitUserUpdated(e,a){await this.emit(xs,{user:e,previousUser:a})}async emitWorkspaceChanged(e,a){await this.emit(Ns,{workspace:e,previousWorkspace:a})}async emitWorkspaceUpdated(e){await this.emit(Ss,{workspace:e})}async emitWorkspaceUserAdded(e,a,t){await this.emit(ks,{userId:e,workspace:a,role:t})}async emitWorkspaceUserRemoved(e,a,t){await this.emit(Cs,{userId:e,workspace:a,role:t})}async emitWorkspaceUserRoleChanged(e,a,t,r){await this.emit(As,{userId:e,workspace:a,previousRole:t,newRole:r})}async emitWorkspaceCreated(e){await this.emit(Ts,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(Es,{workspace:e})}},Is=ne("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"}}),Us=r.forwardRef(({className:t,variant:s,progress:n,size:i,startIcon:o,endIcon:c,asChild:l=!1,...d},u)=>{const m=l?se:"button",p=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(i);return e(m,{disabled:n||d.disabled,className:Ue(Is({variant:s,size:i,withIcon:null!=n||null!=o||null!=c,className:t})),ref:u,...d,children:[n&&a(w,{size:p,className:"animate-spin"}),o&&r.cloneElement(o,{size:p}),d.children,c&&r.cloneElement(c,{size:p})]})});Us.displayName="Button";const Rs=c({container:null,setContainer:()=>{}}),Ds=s.memo(({children:t})=>{const[r,n]=s.useState(null),i=s.useMemo(()=>({container:r,setContainer:n}),[r]);return e(Rs.Provider,{value:i,children:[t,a("div",{ref:n,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});Ds.displayName="PortalProvider";const Ms=ie.Root,_s=ie.Trigger,Ws=ie.Portal,Fs=r.forwardRef(({className:e,...t},r)=>a(ie.Overlay,{ref:r,className:Ue("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",e),...t}));Fs.displayName=ie.Overlay.displayName;const Os=r.forwardRef(({className:t,children:s,...n},i)=>{const{container:o}=r.useContext(Rs);return e(Ws,{container:o,children:[a(Fs,{}),e(ie.Content,{ref:i,className:Ue("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",t),...n,children:[s,e(ie.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:[a(oe,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Close"})]})]})]})});Os.displayName=ie.Content.displayName;const Ls=({className:e,...t})=>a("div",{className:Ue("flex flex-col space-y-1.5 text-center sm:text-start",e),...t});Ls.displayName="DialogHeader";const Bs=r.forwardRef(({className:e,...t},r)=>a(ie.Title,{ref:r,className:Ue("text-lg font-semibold leading-none tracking-tight",e),...t}));Bs.displayName=ie.Title.displayName;const Gs=r.forwardRef(({className:e,...t},r)=>a(ie.Description,{ref:r,className:Ue("text-sm text-muted-foreground",e),...t}));Gs.displayName=ie.Description.displayName;const Ks="saas-workspace-current",Vs=e=>{e?ot(Ks,e._id):ct(Ks)},js=()=>it(Ks),zs=()=>{ct(Ks)},$s=(e,a)=>!!e&&a.some(a=>a._id===e);function Hs(e,a){if(!a)return!1;const t=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==t&&t===a}function Js(e,a){if(!a||!e.users||!Array.isArray(e.users))return null;const t=e.users.find(e=>"string"==typeof e?e===a:"object"==typeof e&&null!==e&&"_id"in e&&e._id===a);return t&&"object"==typeof t&&"role"in t&&"string"==typeof t.role?t.role:null}const qs={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"},Ys=Object.values(qs),Zs={admin:Ys.filter(e=>e!==qs.WORKSPACE_DELETE),member:[qs.WORKSPACE_SETTINGS_VIEW,qs.WORKSPACE_MEMBERS_VIEW,qs.WORKSPACE_FEATURES_VIEW,qs.WORKSPACE_BILLING_VIEW,qs.WORKSPACE_USAGE_VIEW],viewer:[qs.WORKSPACE_SETTINGS_VIEW,qs.WORKSPACE_MEMBERS_VIEW]};function Qs(e){const a=new Set;for(const t of Object.values(e))for(const e of t)a.add(e);return Array.from(a)}function Xs(e){const{userId:a,workspace:t,settings:r,appPermissions:s}=e;if(!t||!a)return new Set;if(Hs(t,a)){const e=new Set(Ys);if(s)for(const a of Qs(s))e.add(a);if(t.permissions)for(const a of Qs(t.permissions))e.add(a);if(r?.workspace?.permissions)for(const a of Qs(r.workspace.permissions))e.add(a);return e}const n=e.workspaceRole??Js(t,a);if(!n)return new Set;const i=t.permissions,o=r?.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=Zs[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=Zs[r?.workspace?.defaultRole??"member"]??Zs.member??[]}const h=new Set(p),g=i?.[n]?l(i[n]):[],f=s?.[n]?l(s[n]):[],b=g.length>0?g:f;for(const e of b)h.add(e);return function(e,a,t){if(!t?.workspace)return;const{canInviteMembers:r}=t.workspace;(!1===r||"admin-only"===r&&"admin"!==a)&&e.delete(qs.WORKSPACE_MEMBERS_INVITE)}(h,n,r),h}function en(e){const{user:a}=wo(),{currentWorkspace:t}=go(),{settings:r}=At(),{appPermissions:s}=hr(),n=e??t??null,i=a?.id??null,c=o(()=>n?Js(n,i):null,[n,i]),l=o(()=>!!n&&Hs(n,i),[n,i]),d=o(()=>Xs({userId:i,workspaceRole:c,workspace:n,settings:r,appPermissions:s}),[i,c,n,r,s]);return{can:m(e=>Array.isArray(e)?e.every(e=>d.has(e)):d.has(e),[d]),permissions:d,isOwner:l,role:c}}const an={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:"฿"},tn={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function rn(e){return e&&e.trim()?tn[e.trim().toLowerCase()]??"":""}function sn(e){if(!e||!e.trim())return"";const a=e.trim().toLowerCase();return an[a]??a.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()} (${sn(e)})`}));const nn=({open:t,onOpenChange:r,packages:s,billingCurrency:n,workspaceName:i,onSelectPackage:c,purchasingPackageId:l,loading:d=!1})=>{const{t:u,dir:m,fmtNum:h,fmtCents:g}=nt(),f=o(()=>{const e=new Set;return s.forEach(a=>{a.pricingVariants?.forEach(a=>{a.currency&&e.add(a.currency.toLowerCase())})}),Array.from(e)},[s]),b=o(()=>{const e=n?.trim().toLowerCase();return e?f.includes(e)?[e]:[]:f},[n,f]),[y,w]=p(()=>b.length>0?b[0]:""),x=n?.trim().toLowerCase()||y,N=d||!!l;return a(Ms,{open:t,onOpenChange:r,children:e(Os,{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("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("div",{children:[a(Bs,{className:"text-xl sm:text-2xl font-bold",children:u("credits.dialogTitle")}),e(Gs,{className:"mt-1 text-sm",children:[u("credits.dialogDescription"),i&&a("span",{className:"ms-1 font-medium text-foreground",children:u("credits.dialogDescriptionWorkspace",{workspace:i})})]})]}),!n?.trim()&&b.length>1&&e("div",{className:"flex items-center gap-2",children:[a("span",{className:"text-sm text-slate-600",children:u("pricing.currency")}),a("div",{className:"flex gap-1 rounded-lg border border-gray-200 bg-gray-50/50 p-1",children:b.map(a=>e("button",{type:"button",onClick:()=>w(a),className:Ue("rounded-md px-3 py-1.5 text-sm font-medium transition-colors",x===a?"bg-white text-gray-900 shadow-sm":"text-gray-500 hover:text-gray-700"),children:[sn(a)," ",a.toUpperCase()]},a))})]})]}),a("div",{className:"flex-1 overflow-y-auto",children:0===s.length?e("div",{className:"flex flex-col items-center justify-center py-16 text-gray-400",children:[a(v,{className:"h-12 w-12 mb-3"}),a("p",{className:"text-sm",children:u("credits.noPackages")})]}):a("div",{className:"max-w-2xl mx-auto px-4 py-6 sm:px-6 space-y-4",children:s.map(t=>{const r=t.pricingVariants?.find(e=>e.currency?.toLowerCase()===x)??t.pricingVariants?.[0],s=r?.amount,n=r?.currency??x,i=l===t._id,o=null!=s&&s>0&&t.creditAmount>0?Math.round(s/t.creditAmount):null;return e("div",{className:Ue("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("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 mb-1",children:[a("h3",{className:"text-lg font-semibold text-gray-900",children:t.name}),e("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:[a(v,{className:"h-3 w-3"}),u("credits.creditsAmount",{count:h(t.creditAmount)})]})]}),t.description&&a("p",{className:"text-sm text-gray-500 mb-2",children:t.description}),e("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-400",children:[a("span",{children:t.validityDays?u("credits.validityDays",{count:t.validityDays}):u("credits.validityUnlimited")}),null!=o&&a("span",{children:u("credits.perCredit",{price:g(o,n)})})]})]}),e("div",{className:"flex items-center gap-4 sm:flex-col sm:items-end sm:gap-2 shrink-0",children:[null!=s&&a("span",{className:"text-2xl sm:text-3xl font-bold text-gray-900 whitespace-nowrap",children:g(s,n)}),a(Us,{size:"sm",onClick:()=>c(t),disabled:N,progress:i,className:"whitespace-nowrap",children:i?u("credits.purchasing"):u("credits.buyAmount",{count:h(t.creditAmount)})})]})]},t._id)})})})]})})},on=({titleKey:t,descriptionKey:r})=>{const{t:s}=nt();return a("div",{className:"border border-amber-200 bg-amber-50 rounded-lg p-4",children:e("div",{className:"flex items-start gap-3",children:[a(x,{className:"h-5 w-5 text-amber-600 shrink-0 mt-0.5"}),e("div",{children:[a("h4",{className:"text-sm font-medium text-amber-800",children:s(t??"settings.common.noPermissionTitle")}),a("p",{className:"text-xs text-amber-700 mt-1",children:s(r??"settings.common.noPermissionDescription")})]})]})})};function cn({className:e,...t}){return a("div",{className:Ue("animate-pulse rounded-md bg-primary/10",e),...t})}function ln(){return e("div",{className:"space-y-3.5",children:[a(cn,{className:"h-10 w-full"}),a(cn,{className:"h-10 w-full"}),a(cn,{className:"h-10 w-full"})]})}function dn(e,a="en-US",t){try{const r=new Date(e);return isNaN(r.getTime())?"":new Intl.DateTimeFormat(a,t??{month:"short",day:"numeric",year:"numeric"}).format(r)}catch{return""}}function un(e,a="en-US"){return dn(e,a,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function mn(e,a="en-US"){return e?new Date(1e3*e).toLocaleDateString(a,{year:"numeric",month:"short",day:"numeric"}):""}const pn={[rs]:"credits.type.plan_grant",[ss]:"credits.type.pack_purchased",[ns]:"credits.type.consumed",[is]:"credits.type.expired",[os]:"credits.type.admin_grant",[cs]:"credits.type.admin_revoke",[ls]:"credits.type.refund"};const hn=({workspace:r})=>{const s=r._id?.toString(),{t:n,fmtNum:o}=nt(),{can:c}=en(),l=c(qs.WORKSPACE_BILLING_VIEW),d=c(qs.WORKSPACE_BILLING_MANAGE),{balance:h,loading:g,error:f,refetch:b}=ir(),{packages:y,loading:x}=er(s),{expiringCredits:C,loading:A}=tr(s,7),[T,E]=p(1),{transactions:P,hasNextPage:I,loading:U}=ar(s,{limit:10,page:T}),[R,D]=p([]);u(()=>{U||0===P.length||D(1===T?P:e=>{const a=new Set(e.map(e=>e._id)),t=P.filter(e=>!a.has(e._id));return t.length>0?[...e,...t]:e})},[P,T,U]);const M=m(()=>{I&&!U&&E(e=>e+1)},[I,U]),_=R,{purchaseCredits:W,loading:F}=Xt(s),[O,L]=p(!1),[B,G]=p(null),[K,V]=p(!1),[j,z]=p(!1),[$,H]=p(null),[J,q]=p(!1),Y=i(!1),Z=g&&!h;u(()=>{if(Y.current)return;const e=ho.getState();if(!e.params?.action)return;if(e.params.action===Rr)return Y.current=!0,ho.clearParams(),void q(!0);if(e.params.action!==Ur)return;Y.current=!0;const a=e.params.status;if(ho.clearParams(),a===Dr){V(!0),Yt();const e=setTimeout(()=>V(!1),8e3);return()=>clearTimeout(e)}if(a===Mr){z(!0);const e=setTimeout(()=>z(!1),5e3);return()=>clearTimeout(e)}a===_r&&G(n("credits.purchaseFailed"))},[]);if(Z)return a(ln,{});if(!l)return a(on,{});if(!s)return a("div",{className:"border rounded-lg p-4 text-center text-gray-500",children:a("p",{children:n("subscription.invalidWorkspace")})});const Q=!x&&y.length>0;return e("div",{className:"space-y-6",children:[e("div",{className:"space-y-3",children:[a("p",{className:"text-sm text-gray-600",children:n("credits.description")}),e("div",{className:"flex flex-wrap items-center gap-2",children:[Q&&d&&e(Us,{size:"sm",onClick:()=>q(!0),children:[a(N,{className:"h-3.5 w-3.5 me-1.5"}),n("credits.buyCredits")]}),e(Us,{variant:"ghost",size:"sm",onClick:async()=>{L(!0);try{await b()}finally{L(!1)}},disabled:O,children:[a(S,{className:Ue("h-3.5 w-3.5 me-1.5",O&&"animate-spin")}),n("settings.common.refreshAction",{loading:String(O)})]})]})]}),f&&e("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg",children:[a("p",{className:"font-medium",children:n("credits.errorLoading")}),a("p",{className:"text-sm mt-1",children:f})]}),K&&e("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("div",{className:"flex items-center gap-2",children:[a(k,{className:"h-4 w-4 flex-shrink-0"}),a("p",{className:"text-sm font-medium",children:n("credits.purchaseSuccess")})]}),a(Us,{variant:"outline",size:"sm",onClick:()=>V(!1),className:"flex-shrink-0 border-green-200 text-green-700 hover:bg-green-100",children:n("settings.common.dismiss")})]}),j&&e("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:[a("p",{className:"text-sm font-medium",children:n("credits.purchaseCanceled")}),a(Us,{variant:"outline",size:"sm",onClick:()=>z(!1),className:"flex-shrink-0 border-amber-200 text-amber-700 hover:bg-amber-100",children:n("settings.common.dismiss")})]}),B&&e("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:[a("p",{className:"text-sm",children:B}),a(Us,{variant:"outline",size:"sm",onClick:()=>G(null),className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:n("settings.common.dismiss")})]}),e("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[e("div",{className:"bg-gray-50/50 p-4 sm:p-5",children:[e("div",{className:"flex items-center justify-between mb-3",children:[a("h3",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wider",children:n("credits.balance")}),a(v,{className:"h-5 w-5 text-gray-400"})]}),h?e(t,{children:[a("div",{className:"text-3xl font-bold text-gray-900 mb-4",children:o(h.available)}),e("div",{className:"grid grid-cols-2 gap-3",children:[e("div",{children:[a("p",{className:"text-xs text-gray-500",children:n("credits.totalGranted")}),a("p",{className:"text-sm font-medium text-gray-900",children:o(h.totalGranted)})]}),e("div",{children:[a("p",{className:"text-xs text-gray-500",children:n("credits.totalConsumed")}),a("p",{className:"text-sm font-medium text-gray-900",children:o(h.totalConsumed)})]}),e("div",{children:[a("p",{className:"text-xs text-gray-500",children:n("credits.totalExpired")}),a("p",{className:"text-sm font-medium text-gray-900",children:o(h.totalExpired)})]}),e("div",{children:[a("p",{className:"text-xs text-gray-500",children:n("credits.available")}),a("p",{className:"text-sm font-semibold text-green-600",children:o(h.available)})]})]})]}):e("div",{className:"text-center py-4",children:[a(v,{className:"h-10 w-10 text-gray-300 mx-auto mb-2"}),a("p",{className:"text-sm text-gray-600",children:n("credits.noCredits")}),a("p",{className:"text-xs text-gray-500 mt-1",children:n("credits.noCreditsHint")}),Q&&d&&e(Us,{size:"sm",className:"mt-3",onClick:()=>q(!0),children:[a(N,{className:"h-3.5 w-3.5 me-1.5"}),n("credits.buyCredits")]})]})]}),!A&&C>0&&a("div",{className:"px-4 py-3 bg-amber-50 border-t border-amber-200 text-sm text-amber-800",children:n("credits.expiringInDays",{count:C,days:7})})]}),e("div",{children:[a("h3",{className:"text-sm font-semibold text-gray-900 mb-3",children:n("credits.transactions")}),U&&0===_.length?e("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:[a(w,{className:"h-4 w-4 animate-spin flex-shrink-0"}),a("span",{children:n("settings.common.loading")})]}):0===_.length?a("div",{className:"border rounded-lg p-6 text-center",children:a("p",{className:"text-sm text-gray-500",children:n("credits.noTransactions")})}):e("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[a("div",{className:"divide-y divide-gray-100",children:_.map(e=>a(gn,{tx:e},e._id))}),I&&a("div",{className:"border-t border-gray-200 px-4 py-3 text-center",children:a(Us,{variant:"ghost",size:"sm",onClick:M,disabled:U,progress:U&&T>1,children:n("credits.loadMore")})})]})]}),Q&&d&&a(nn,{open:J,onOpenChange:q,packages:y,billingCurrency:r.billingCurrency,workspaceName:r.name,onSelectPackage:async e=>{if(s){G(null),H(e._id);try{const{successUrl:a,cancelUrl:t}=Lr(s),r=await W({creditPackageId:e._id,successUrl:a,cancelUrl:t});r.url&&wr(r.url)}catch(e){G(e instanceof Error?e.message:n("errors.purchaseCredits")),H(null)}}},purchasingPackageId:$,loading:F})]})};function gn({tx:t}){const{t:r,formattingLocale:s,fmtNum:n}=nt(),i=pn[t.type]??"credits.type.consumed",o=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"}}(t.type),c=t.amount>0;return a("div",{className:"px-3 py-3 sm:px-4",children:e("div",{className:"flex items-start justify-between gap-2",children:[e("div",{className:"min-w-0 flex-1",children:[e("div",{className:"flex flex-wrap items-center gap-1.5 mb-0.5",children:[a("span",{className:Ue("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium shrink-0",o),children:r(i)}),t.description&&a("p",{className:"text-sm text-gray-700 truncate",children:t.description})]}),a("p",{className:"text-xs text-gray-400",children:un(t.createdAt,s)})]}),e("div",{className:"text-end shrink-0",children:[e("span",{className:Ue("text-sm font-semibold",c?"text-green-600":"text-gray-900"),children:[c?"+":"",n(t.amount)]}),a("p",{className:"text-xs text-gray-400",children:n(t.balanceAfter)})]})]})})}const fn=ue.Root,bn=ue.Trigger,yn=ue.Portal,wn=r.forwardRef(({className:e,...t},r)=>a(ue.Overlay,{className:Ue("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",e),...t,ref:r}));wn.displayName=ue.Overlay.displayName;const vn=r.forwardRef(({className:t,...s},n)=>{const{container:i}=r.useContext(Rs);return e(yn,{container:i,children:[a(wn,{}),a(ue.Content,{ref:n,className:Ue("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",t),...s})]})});vn.displayName=ue.Content.displayName;const xn=({className:e,...t})=>a("div",{className:Ue("flex flex-col space-y-2 text-center sm:text-start",e),...t});xn.displayName="AlertDialogHeader";const Nn=({className:e,...t})=>a("div",{className:Ue("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});Nn.displayName="AlertDialogFooter";const Sn=r.forwardRef(({className:e,...t},r)=>a(ue.Title,{ref:r,className:Ue("text-lg font-semibold",e),...t}));Sn.displayName=ue.Title.displayName;const kn=r.forwardRef(({className:e,...t},r)=>a(ue.Description,{ref:r,className:Ue("text-sm text-muted-foreground",e),...t}));kn.displayName=ue.Description.displayName;const Cn=r.forwardRef(({className:e,...t},r)=>a(ue.Action,{ref:r,className:Ue(Is(),e),...t}));Cn.displayName=ue.Action.displayName;const An=r.forwardRef(({className:e,...t},r)=>a(ue.Cancel,{ref:r,className:Ue(Is({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));An.displayName=ue.Cancel.displayName;const Tn=({workspace:r})=>{const[s,n]=p(!1),{deleteWorkspace:i}=go(),{can:o}=en(),{settings:c}=At(),{t:l}=nt();if(1===(c?.workspace?.maxWorkspacesPerUser??0))return null;if(!r)return a(ln,{});return o(qs.WORKSPACE_DELETE)?e("div",{className:"space-y-4",children:[e("div",{children:[a("h3",{className:"text-lg font-semibold text-destructive",children:l("danger.title")}),a("p",{className:"text-sm text-muted-foreground mt-2",children:l("danger.deleteDescription")})]}),e(fn,{children:[a(bn,{asChild:!0,children:e(Us,{variant:"destructive",disabled:s,progress:s,children:[a(C,{className:"h-4 w-4 me-2"}),l("danger.deleteWorkspace")]})}),e(vn,{children:[e(xn,{children:[a(Sn,{children:l("danger.deleteConfirm")}),a(kn,{children:l("danger.deleteConfirmDescription")})]}),e(Nn,{children:[a(An,{disabled:s,children:l("settings.common.cancel")}),a(Cn,{onClick:async()=>{n(!0);try{await i(r._id)}catch(e){Be(e,{component:"WorkspaceSettingsDanger",action:"handleDeleteWorkspace",metadata:{workspaceId:r._id}}),alert(e instanceof Error?e.message:l("danger.failedToDelete"))}finally{n(!1)}},disabled:s,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:s?e(t,{children:[a(w,{className:"me-2 h-4 w-4 animate-spin"}),l("danger.deleting")]}):l("danger.deleteWorkspace")})]})]})]})]}):a(on,{descriptionKey:"danger.adminOnly"})},En=r.forwardRef(({className:e,...t},r)=>a(me.Root,{className:Ue("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",e),...t,ref:r,children:a(me.Thumb,{className:Ue("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 Pn(e=5e3){const[a,t]=p(null),r=i(null);u(()=>()=>{r.current&&clearTimeout(r.current)},[]);return{message:a,show:m(a=>{t(a),r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{t(null)},e)},[e]),clear:m(()=>{t(null),r.current&&clearTimeout(r.current)},[])}}En.displayName=me.Root.displayName;const In=({workspaceId:t})=>{const{t:r}=nt(),{allFeatures:s,updateFeature:n,getWorkspace:i}=go(),{can:o}=en(),[c,l]=p({}),d=Pn(),[m,h]=p(null);if(u(()=>{i(t).then(h)},[t]),!m)return a(ln,{});const g=o(qs.WORKSPACE_FEATURES_EDIT);return e("div",{children:[d.message&&e("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-4",children:[a("p",{className:"font-medium",children:r("settings.common.success")}),a("p",{className:"text-sm",children:d.message})]}),e("div",{className:"flex flex-col gap-y-3.5 pe-4",children:[!g&&a(on,{descriptionKey:"features.ownerOnly"}),!s.length&&a("div",{className:"text-muted-foreground",children:r("features.noFeatures")}),s.length>0&&a("div",{className:"flex flex-col gap-y-3.5",children:s.map(t=>{const i=m?.features?.[t.slug],o=null!==c[t.slug]&&void 0!==c[t.slug],u=c[t.slug],p=r("features.actionStatus",{action:!0===u?"enabling":!1===u?"disabling":"none"});return e("div",{className:"flex items-center gap-x-2 justify-between w-full",children:[e("div",{className:"flex gap-x-2 flex-col",children:[a("h3",{className:"font-medium text-ellipsis",children:t.name}),a("p",{className:"text-muted-foreground",children:t.description})]}),o?e("div",{className:"flex items-center gap-x-1",children:[a(w,{className:"h-4 w-4 animate-spin text-gray-500"}),e("span",{className:"text-sm text-gray-600",children:[p,"..."]})]}):a(En,{disabled:!g,checked:i??t.defaultValue,onCheckedChange:e=>async function(e,a){if(m){l(t=>({...t,[e]:a})),d.clear();try{const t=await n(m._id,e,a);h(t);const i=s.find(a=>a.slug===e),o=i?.name||"Feature";d.show(r("features.updateSuccess",{feature:o,enabled:String(a)}))}catch(a){Be(a,{component:"WorkspaceSettingsFeatures",action:"updateFeature",metadata:{workspaceId:m._id,featureKey:e}})}finally{l(a=>({...a,[e]:null}))}}}(t.slug,e)})]},t._id)})})]})]})},Un=(e,a,t)=>{if(e&&"reportValidity"in e){const r=pe(t,a);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},Rn=(e,a)=>{for(const t in a.fields){const r=a.fields[t];r&&r.ref&&"reportValidity"in r.ref?Un(r.ref,t,e):r&&r.refs&&r.refs.forEach(a=>Un(a,t,e))}},Dn=(e,a)=>{a.shouldUseNativeValidation&&Rn(e,a);const t={};for(const r in e){const s=pe(a.fields,r),n=Object.assign(e[r]||{},{ref:s&&s.ref});if(Mn(a.names||Object.keys(e),r)){const e=Object.assign({},pe(t,r));he(e,"root",n),he(t,r,e)}else he(t,r,n)}return t},Mn=(e,a)=>{const t=_n(a);return e.some(e=>_n(e).match(`^${t}\\.\\d+`))};function _n(e){return e.replace(/\]|\[/g,"")}function Wn(e,a){try{var t=e()}catch(e){return a(e)}return t&&t.then?t.then(void 0,a):t}function Fn(e,a){for(var t={};e.length;){var r=e[0],s=r.code,n=r.message,i=r.path.join(".");if(!t[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:n,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var c=t[i].types,l=c&&c[r.code];t[i]=ge(i,a,t,s,l?[].concat(l,r.message):r.message)}e.shift()}return t}function On(e,a){for(var t={};e.length;){var r=e[0],s=r.code,n=r.message,i=r.path.join(".");if(!t[i])if("invalid_union"===r.code&&r.errors.length>0){var o=r.errors[0][0];t[i]={message:o.message,type:o.code}}else t[i]={message:n,type:s};if("invalid_union"===r.code&&r.errors.forEach(function(a){return a.forEach(function(a){return e.push(a)})}),a){var c=t[i].types,l=c&&c[r.code];t[i]=ge(i,a,t,s,l?[].concat(l,r.message):r.message)}e.shift()}return t}function Ln(e,a,t){if(void 0===t&&(t={}),function(e){return"_def"in e&&"object"==typeof e._def&&"typeName"in e._def}(e))return function(r,s,n){try{return Promise.resolve(Wn(function(){return Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return n.shouldUseNativeValidation&&Rn({},n),{errors:{},values:t.raw?Object.assign({},r):e}})},function(e){if(function(e){return Array.isArray(null==e?void 0:e.issues)}(e))return{values:{},errors:Dn(Fn(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(r,s,n){try{return Promise.resolve(Wn(function(){return Promise.resolve(("sync"===t.mode?ve.parse:ve.parseAsync)(e,r,a)).then(function(e){return n.shouldUseNativeValidation&&Rn({},n),{errors:{},values:t.raw?Object.assign({},r):e}})},function(e){if(function(e){return e instanceof ve.$ZodError}(e))return{values:{},errors:Dn(On(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 Bn=ne("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gn=r.forwardRef(({className:e,...t},r)=>a(Ne.Root,{ref:r,className:Ue(Bn(),e),...t}));Gn.displayName=Ne.Root.displayName;const Kn=be,Vn=r.createContext({}),jn=({...e})=>a(Vn.Provider,{value:{name:e.name},children:a(fe,{...e})}),zn=()=>{const e=r.useContext(Vn),a=r.useContext($n),{getFieldState:t,formState:s}=ye(),n=t(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=a;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...n}},$n=r.createContext({}),Hn=r.forwardRef(({className:e,...t},s)=>{const n=r.useId();return a($n.Provider,{value:{id:n},children:a("div",{ref:s,className:Ue("space-y-2",e),...t})})});Hn.displayName="FormItem";const Jn=r.forwardRef(({className:e,...t},r)=>{const{error:s,formItemId:n}=zn();return a(Gn,{ref:r,className:Ue(s&&"text-destructive",e),htmlFor:n,...t})});Jn.displayName="FormLabel";const qn=r.forwardRef(({...e},t)=>{const{error:r,formItemId:s,formDescriptionId:n,formMessageId:i}=zn();return a(se,{ref:t,id:s,"aria-describedby":r?`${n} ${i}`:`${n}`,"aria-invalid":!!r,...e})});qn.displayName="FormControl";const Yn=r.forwardRef(({className:e,...t},r)=>{const{formDescriptionId:s}=zn();return a("p",{ref:r,id:s,className:Ue("text-sm text-muted-foreground",e),...t})});Yn.displayName="FormDescription";const Zn=r.forwardRef(({className:e,children:t,...r},s)=>{const{error:n,formMessageId:i}=zn(),o=n?String(n?.message):t;return o?a("p",{ref:s,id:i,className:Ue("text-sm font-medium text-destructive",e),...r,children:o}):null});Zn.displayName="FormMessage";const Qn=r.forwardRef(({className:e,type:t,...r},s)=>a("input",{type:t,className:Ue("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",e),ref:s,...r}));Qn.displayName="Input";const Xn=r.forwardRef(({className:e,...t},r)=>a(Se.Root,{className:Ue("grid gap-2",e),...t,ref:r}));Xn.displayName=Se.Root.displayName;const ei=r.forwardRef(({className:e,...t},r)=>a(Se.Item,{ref:r,className:Ue("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",e),...t,children:a(Se.Indicator,{className:"flex items-center justify-center",children:a(ce,{className:"h-3.5 w-3.5 fill-primary"})})}));ei.displayName=Se.Item.displayName;const ai=r.forwardRef(({className:t,children:r,...s},n)=>e(ke.Root,{ref:n,className:Ue("relative overflow-hidden",t),...s,children:[a(ke.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),a(ti,{}),a(ke.Corner,{})]}));ai.displayName=ke.Root.displayName;const ti=r.forwardRef(({className:e,orientation:t="vertical",...r},s)=>a(ke.ScrollAreaScrollbar,{ref:s,orientation:t,className:Ue("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]",e),...r,children:a(ke.ScrollAreaThumb,{className:Ue("relative rounded-full bg-border","vertical"===t&&"flex-1")})}));function ri(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</text></svg>`}ti.displayName=ke.ScrollAreaScrollbar.displayName;const si=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑💻","👨💻","👩💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨💼","👩💼","👨🏫","👩🏫","👨🔬","👩🔬","👨🎨","👩🎨","👨🔧","👩🔧","👨🚀","👩🚀","👨⚖️","👩⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️🌈","🎟️","🎫"],ni=({workspace:t})=>{const{t:r}=nt(),{updateWorkspace:s}=go(),{can:n}=en(),[i,o]=p(!1),[c,l]=p("emoji"),[d,u]=p(),m=Pn(),h=xe.object({name:xe.string().min(2,{message:r("general.nameMinLength")}),image:xe.string().optional()}),g=we({resolver:Ln(h),defaultValues:{name:t.name||"",image:t.image||""}});if(!t)return a(ln,{});const f=n(qs.WORKSPACE_SETTINGS_EDIT);return e("div",{children:[m.message&&e("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-4",children:[a("p",{className:"font-medium",children:r("settings.common.success")}),a("p",{className:"text-sm",children:m.message})]}),!f&&a(on,{descriptionKey:"general.ownerOnly"}),a(Kn,{...g,children:e("form",{onSubmit:g.handleSubmit(async function(e){o(!0),m.clear();try{await s(t,e),m.show(r("general.success"))}catch(e){Be(e,{component:"WorkspaceSettingsGeneral",action:"updateWorkspace",metadata:{workspaceId:t._id}})}finally{o(!1)}}),className:"space-y-6",children:[a(jn,{control:g.control,name:"name",render:({field:t})=>e(Hn,{children:[a(Jn,{children:r("general.name")}),a(qn,{children:a(Qn,{placeholder:r("general.namePlaceholder"),...t,disabled:!f})}),a(Zn,{})]})}),t.billingCurrency?.trim()&&e("div",{className:"space-y-1.5",children:[a(Gn,{className:"text-sm font-medium text-muted-foreground",children:r("general.billingCurrency")}),e("div",{className:"flex items-center gap-2 text-sm",children:[rn(t.billingCurrency)&&a("span",{className:"text-base",children:rn(t.billingCurrency)}),a("span",{children:t.billingCurrency.trim().toUpperCase()})]})]}),e("div",{className:"space-y-4",children:[e("div",{children:[a(Gn,{className:"text-sm font-medium",children:r("general.icon")}),a(Yn,{children:r("general.iconDescription")})]}),e(Xn,{value:c,disabled:!f,onValueChange:e=>l(e),className:"flex flex-col space-y-3",children:[e("div",{className:"flex items-center space-x-2",children:[a(ei,{value:"emoji",id:"emoji"}),e(Gn,{htmlFor:"emoji",className:"flex items-center gap-2",children:[a(A,{className:"h-4 w-4"}),r("general.chooseEmoji")]})]}),e("div",{className:"flex items-center space-x-2",children:[a(ei,{value:"url",id:"url"}),e(Gn,{htmlFor:"url",className:"flex items-center gap-2",children:[a(T,{className:"h-4 w-4"}),r("general.customImageUrl")]})]})]}),"emoji"===c&&e("div",{className:"space-y-3",children:[e("div",{className:"flex items-center gap-3",children:[a("span",{className:"text-sm font-medium",children:r("general.previewLabel")}),e("div",{className:"w-12 h-12 rounded-lg border-2 border-border flex items-center justify-center text-2xl bg-muted",children:[d&&a("span",{className:"text-2xl",children:d}),!d&&g.watch("image")?.trim()&&a("img",{src:g.watch("image")||void 0,alt:"Workspace preview"})]})]}),f&&a(ai,{className:"h-32 w-full rounded-md border",children:a("div",{className:"p-4 grid grid-cols-8 gap-2",children:si.map((e,t)=>a("button",{type:"button",onClick:()=>(e=>{u(e),g.setValue("image",ri(e))})(e),disabled:!f,className:"w-8 h-8 rounded flex items-center justify-center text-lg hover:bg-muted transition-colors "+(d===e?"bg-primary text-primary-foreground":""),children:e},t))})})]}),"url"===c&&e("div",{className:"space-y-3",children:[a(jn,{control:g.control,name:"image",render:({field:t})=>e(Hn,{children:[a(Jn,{children:r("general.imageUrl")}),a(qn,{children:a(Qn,{placeholder:r("general.imageUrlPlaceholder"),...t,disabled:!f})}),a(Yn,{children:r("general.imageUrlDescription")}),a(Zn,{})]})}),g.watch("image")&&g.watch("image")?.trim()&&e("div",{className:"flex items-center gap-3",children:[a("span",{className:"text-sm font-medium",children:r("general.previewLabel")}),a("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:a("img",{src:g.watch("image")||void 0,className:"w-full h-full object-cover",alt:"Workspace preview"})})]})]})]}),a("div",{className:"flex justify-end gap-3 pt-4",children:f&&a(Us,{type:"submit",disabled:i,progress:i,children:r("general.updateWorkspace")})})]})})]})};class ii extends yt{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,a){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:a})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}const oi=c(null);function ci(e){const a=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),t=atob(a),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}const li=s.memo(function({children:e,serviceWorkerPath:t="/push-sw.js",autoSubscribe:r=!1}){const{t:s}=nt(),n=kt(),{isAuthenticated:i}=wo(),c=o(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=o(()=>new ii({serverUrl:n.serverUrl,version:n.version,orgId:n.orgId}),[n.serverUrl,n.version,n.orgId]),[d,h]=p({permission:c?Notification.permission:"default",isSubscribed:!1,isSupported:c,loading:!1,error:null});u(()=>{if(!i||!c)return;let e=!1;return(async()=>{try{const a=await navigator.serviceWorker.getRegistration(t);if(e)return;if(!a)return void h(e=>({...e,isSubscribed:!1}));const r=await a.pushManager.getSubscription();if(e)return;h(e=>({...e,isSubscribed:!!r,permission:Notification.permission}))}catch{e||h(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[i,c,t]);const g=m(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return h(a=>({...a,permission:e})),"granted"===e},[c]),f=m(async()=>{if(c&&i){h(e=>({...e,loading:!0,error:null}));try{if(!await g())return void h(e=>({...e,loading:!1,error:s("notifications.permissionDenied")}));const{publicKey:e}=await l.getVapidPublicKey(),a=await navigator.serviceWorker.register(t);await navigator.serviceWorker.ready;const r=(await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ci(e)})).toJSON();await l.subscribe({endpoint:r.endpoint,keys:{p256dh:r.keys.p256dh,auth:r.keys.auth}},navigator.userAgent),h(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const a=e instanceof Error?e.message:s("push.failedToSubscribe");h(e=>({...e,loading:!1,error:a})),Be(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,i,l,t,g]),b=m(async()=>{if(c){h(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(t);if(e){const a=await e.pushManager.getSubscription();if(a){const e=a.endpoint;await a.unsubscribe(),await l.unsubscribe(e)}}h(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const a=e instanceof Error?e.message:s("push.failedToUnsubscribe");h(e=>({...e,loading:!1,error:a})),Be(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,t]),y=o(()=>({...d,requestPermission:g,subscribe:f,unsubscribe:b}),[d,g,f,b]);return a(oi.Provider,{value:y,children:e})});function di(){const e=d(oi);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e}const ui={firefox:4,safari:4,edge:4,chrome:4},mi=({workspace:r})=>{const{isSupported:s,permission:n,isSubscribed:c,loading:l,error:d,subscribe:h,unsubscribe:g}=di(),{t:f}=nt(),{api:b}=Tt(),{can:y}=en(),w=y(qs.WORKSPACE_SETTINGS_EDIT),v=o(()=>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"}(),[]),N=ui[v],[S,k]=p([]),[C,A]=p(!0),[T,R]=p({}),[D,M]=p(!0),[_,W]=p(null),[F,O]=p(null),L=i(null);u(()=>()=>{L.current&&clearTimeout(L.current)},[]),u(()=>{if(!r?._id)return;const e=r._id.toString();A(!0),M(!0),Promise.all([b.getNotificationEvents(e).catch(()=>[]),b.getNotificationPreferences(e).catch(()=>({}))]).then(([e,a])=>{k(e),R(a)}).finally(()=>{A(!1),M(!1)})},[r?._id]);const B=m(async(e,a,t)=>{if(!r?._id||!w)return;const s=!t;W(`${e}.${a}`),O(null),R(t=>({...t,[e]:{...t[e],[a]:s}}));try{const t=await b.updateNotificationPreferences(r._id.toString(),{[e]:{[a]:s}});R(t),O(f("notifications.prefsSaved")),L.current&&clearTimeout(L.current),L.current=setTimeout(()=>O(null),3e3)}catch(r){R(r=>({...r,[e]:{...r[e],[a]:t}})),Be(r,{component:"SettingsNotifications",action:"toggleChannel"})}finally{W(null)}},[r?._id,w,b,f]),G=(e,a)=>!1!==T[e]?.[a],K=o(()=>{const e=new Map;for(const a of S){const t=a.category||"general";e.has(t)||e.set(t,[]),e.get(t).push(a)}return Array.from(e.entries())},[S]),V=C||D,j=S.length>0;return e("div",{className:"space-y-6",children:[a("p",{className:"text-sm text-gray-600",children:f("notifications.manageDescription")}),s&&e(t,{children:[d&&"denied"!==n&&a("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm",children:d}),"denied"===n&&a("div",{className:"border border-amber-200 bg-amber-50 rounded-lg p-4",children:e("div",{className:"flex items-start gap-3",children:[a(x,{className:"h-5 w-5 text-amber-600 shrink-0 mt-0.5"}),e("div",{children:[a("h4",{className:"text-sm font-medium text-amber-800",children:f("notifications.blocked")}),a("p",{className:"text-xs text-amber-700 mt-1",children:f("notifications.blockedDescription")}),a("ol",{className:"text-xs text-amber-700 mt-2 space-y-1 list-decimal list-inside",children:Array.from({length:N},(e,t)=>a("li",{children:f(`notifications.unblock.${v}.step${t+1}`)},t))})]})]})}),"denied"!==n&&e("div",{className:"border rounded-lg p-4",children:[e("div",{className:"flex items-start justify-between gap-4",children:[e("div",{className:"flex items-start gap-3",children:[a("div",{className:"mt-0.5 p-2 rounded-lg "+(c?"bg-green-100":"bg-gray-100"),children:c?a(E,{className:"h-4 w-4 text-green-600"}):a(P,{className:"h-4 w-4 text-gray-400"})}),e("div",{children:[a("h4",{className:"text-sm font-medium text-gray-900",children:f("notifications.pushTitle")}),a("p",{className:"text-xs text-gray-500 mt-0.5",children:f("notifications.pushDescription",{subscribed:String(c)})})]})]}),a(Us,{variant:c?"outline":"default",size:"sm",className:"shrink-0",onClick:c?g:h,disabled:l,progress:l,children:f("notifications.toggleAction",{loading:String(l),subscribed:String(c)})})]}),c&&a("div",{className:"mt-3 pt-3 border-t border-gray-100 text-xs text-gray-500",children:f("notifications.deviceNote")})]})]}),V&&a("div",{className:"text-center text-sm text-gray-400 py-4",children:f("notifications.loadingPrefs")}),!V&&j&&w&&e(t,{children:[F&&a("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg text-sm",children:F}),K.map(([t,r])=>e("div",{className:"border rounded-lg overflow-hidden",children:[a("div",{className:"bg-gray-50 px-4 py-2.5 border-b",children:a("h4",{className:"text-sm font-medium text-gray-700 capitalize",children:t})}),e("div",{className:"divide-y",children:[e("div",{className:"flex items-center px-4 py-2 bg-gray-50/50",children:[a("div",{className:"flex-1"}),e("div",{className:"flex items-center gap-6",children:[a("div",{className:"w-12 flex justify-center",children:a(I,{className:"h-3.5 w-3.5 text-gray-400"})}),a("div",{className:"w-12 flex justify-center",children:a(U,{className:"h-3.5 w-3.5 text-gray-400"})})]})]}),r.map(t=>{const r=G(t.slug,"email"),s=G(t.slug,"push"),n=_===`${t.slug}.email`,i=_===`${t.slug}.push`;return e("div",{className:"flex items-center px-4 py-3",children:[e("div",{className:"flex-1 min-w-0",children:[a("div",{className:"text-sm font-medium text-gray-900",children:t.name}),t.description&&a("div",{className:"text-xs text-gray-500 mt-0.5",children:t.description})]}),e("div",{className:"flex items-center gap-6 shrink-0",children:[a("div",{className:"w-12 flex justify-center",children:t.channels.email?a(En,{checked:r,onCheckedChange:()=>B(t.slug,"email",r),disabled:n}):a("span",{className:"text-xs text-gray-300",children:"—"})}),a("div",{className:"w-12 flex justify-center",children:t.channels.push?a(En,{checked:s,onCheckedChange:()=>B(t.slug,"push",s),disabled:i}):a("span",{className:"text-xs text-gray-300",children:"—"})})]})]},t.slug)})]})]},t))]})]})},pi=({workspace:t})=>{const{t:r}=nt(),{isOwner:s}=en(),{settings:n}=At(),{appPermissions:i}=hr(),{updateWorkspacePermissions:c}=go(),[l,d]=p(!1),m=Pn(),h=o(()=>n?.workspace?.roles??t.roles??[],[n?.workspace?.roles,t.roles]),g=o(()=>{if(!i)return[];const e=new Set;for(const a of Object.values(i))for(const t of a)t.startsWith("workspace:")||e.add(t);return Array.from(e).sort()},[i]),[f,b]=p({});if(u(()=>{if(!i)return;const e=t.permissions,a={};for(const t of h)a[t]=e&&t in e?e[t].filter(e=>!e.startsWith("workspace:")):t in i?i[t].filter(e=>!e.startsWith("workspace:")):[];b(a)},[t.permissions,i,h]),!t)return a(ln,{});if(!i||0===g.length)return null;return e("div",{children:[m.message&&e("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-4",children:[a("p",{className:"font-medium",children:r("settings.common.success")}),a("p",{className:"text-sm",children:m.message})]}),!s&&a(on,{descriptionKey:"permissions.ownerOnly"}),a("p",{className:"text-sm text-muted-foreground mb-4",children:r("permissions.description")}),a("div",{className:"overflow-x-auto",children:e("table",{className:"w-full text-sm",children:[a("thead",{children:e("tr",{className:"border-b",children:[a("th",{className:"text-start py-2 pe-4 font-medium text-gray-500 min-w-[160px]"}),h.map(e=>a("th",{className:"text-center py-2 px-3 font-medium text-gray-700 capitalize min-w-[80px]",children:e},e))]})}),a("tbody",{children:g.map(t=>e("tr",{className:"border-b border-gray-50 hover:bg-gray-50/50",children:[a("td",{className:"py-2 pe-4 text-gray-700 font-mono text-xs",children:t}),h.map(e=>{const r="admin"===e,n=r||(f[e]??[]).includes(t);return a("td",{className:"text-center py-2 px-3",children:a(En,{checked:n,disabled:!s||r,onCheckedChange:()=>((e,a)=>{b(t=>{const r=t[e]??[],s=r.includes(a);return{...t,[e]:s?r.filter(e=>e!==a):[...r,a]}})})(e,t),className:"mx-auto"})},e)})]},t))})]})}),s&&a("div",{className:"mt-6",children:a(Us,{onClick:async()=>{d(!0),m.clear();try{const e=t.permissions??{},a={},s=new Set([...Object.keys(e),...Object.keys(f)]);for(const t of s){const r=(e[t]??[]).filter(e=>e.startsWith("workspace:")),s=f[t]??[];a[t]=[...r,...s]}await c(t._id,a),m.show(r("permissions.saveSuccess"))}catch(e){Be(e,{component:"WorkspaceSettingsPermissions",action:"savePermissions",metadata:{workspaceId:t._id}})}finally{d(!1)}},disabled:l,progress:l,children:r(l?"permissions.saving":"permissions.save")})})]})},hi=r.forwardRef(({className:e,...t},r)=>a(Ce,{ref:r,className:Ue("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));hi.displayName=Ce.displayName;const gi=r.forwardRef(({className:t,...r},s)=>e("div",{className:"flex items-center border-b px-3","data-cmdk-input-wrapper":"",children:[a(le,{className:"me-2 h-4 w-4 shrink-0 opacity-50"}),a(Ce.Input,{ref:s,className:Ue("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",t),...r})]}));gi.displayName=Ce.Input.displayName;const fi=r.forwardRef(({className:e,...t},r)=>a(Ce.List,{ref:r,className:Ue("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));fi.displayName=Ce.List.displayName;r.forwardRef((e,t)=>a(Ce.Empty,{ref:t,className:"py-6 text-center text-sm",...e})).displayName=Ce.Empty.displayName;const bi=r.forwardRef(({className:e,...t},r)=>a(Ce.Group,{ref:r,className:Ue("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",e),...t}));bi.displayName=Ce.Group.displayName;r.forwardRef(({className:e,...t},r)=>a(Ce.Separator,{ref:r,className:Ue("-mx-1 h-px bg-border",e),...t})).displayName=Ce.Separator.displayName;const yi=r.forwardRef(({className:e,...t},r)=>a(Ce.Item,{ref:r,className:Ue("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",e),...t}));yi.displayName=Ce.Item.displayName;const wi=Ae.Root,vi=Ae.Trigger,xi=r.forwardRef(({className:e,align:t="center",sideOffset:s=4,...n},i)=>{const{container:o}=r.useContext(Rs);return a(Ae.Portal,{container:o,children:a(Ae.Content,{ref:i,align:t,sideOffset:s,className:Ue("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",e),...n})})});function Ni({options:t,value:r,onChange:s,placeholder:n="Search...",emptyLabel:i="Choose option"}){const[o,c]=p(r??""),[l,d]=p(!1);u(()=>{void 0!==r&&c(r)},[r]);const m=t.find(e=>e.value===o);return e(wi,{open:l,onOpenChange:d,children:[a(vi,{asChild:!0,children:e(Us,{variant:"outline",role:"combobox","aria-expanded":l,className:"justify-between overflow-hidden text-ellipsis",children:[m?e("div",{children:[String(m.label).trim(),m.icon&&a("span",{className:"ms-2 text-xs text-muted-foreground",children:m.icon})]}):a("span",{className:"text-muted-foreground",children:i}),a(R,{className:"ms-2 h-4 w-4 shrink-0 opacity-50"})]})}),a(xi,{className:"p-0 overflow-hidden text-ellipsis",children:e(hi,{children:[a(gi,{placeholder:n}),a(fi,{children:a(bi,{children:t.map(t=>e(yi,{className:Ue("whitespace-nowrap text-start",{"text-green-500":o===t.value}),value:t.value,defaultValue:t.value,onSelect:()=>{return e=t.value,c(e),s?.(e),void d(!1);var e},children:[o===t.value&&a(D,{className:Ue("me-2 h-4 w-4 text-green-400",o===t.value?"opacity-100":"opacity-0")}),String(t.label).trim(),t.icon&&a("span",{className:"ms-2 text-xs text-muted-foreground",children:t.icon})]},t.value))})})]})})]})}xi.displayName=Ae.Content.displayName;const Si={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"},ki={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"},Ci=[{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 a=ki[e.code]||"USD",t=Si[a]||"";return{value:e.code,flag:(r=e.code,r.toUpperCase().replace(/./g,e=>String.fromCodePoint(127397+e.charCodeAt(0)))),text:e.name,currencyCode:a,currencyIcon:t};var r});function Ai({value:e,onChange:t}){const{t:r}=nt(),s=Ci.map(e=>({value:e.value,label:e.text,icon:e.flag}));return a(Ni,{options:s,value:e,onChange:t,placeholder:r("dropdowns.searchCountry"),emptyLabel:r("dropdowns.chooseCountry")})}const Ti=Ci.map(e=>({value:e.currencyCode,text:e.currencyCode,icon:e.currencyIcon??null})),Ei=Array.from(new Set(Ti.map(e=>e.value))).map(e=>Ti.find(a=>a.value===e)).filter(e=>void 0!==e);function Pi({value:e,onChange:t}){const{t:r}=nt(),s=Ei.map(e=>({value:e.value,label:e.text,icon:e.icon??void 0}));return a(Ni,{options:s,value:e,onChange:t,placeholder:r("dropdowns.searchCurrency"),emptyLabel:r("dropdowns.chooseCurrency")})}let Ii=[{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:"🇮🇱"}];Ii=Ii.filter((e,a,t)=>a===t.findIndex(a=>a.code===e.code&&a.label===e.label)),Ii.sort((e,a)=>e.label<a.label?-1:e.label>a.label?1:0);const Ui=Ii.filter(e=>function(e){try{const a=new Intl.DateTimeFormat(e);return a.resolvedOptions().locale===e||a.resolvedOptions().locale.startsWith(e)}catch{return!1}}(e.code)).filter((e,a,t)=>a===t.findIndex(a=>a.code===e.code&&a.label===e.label)).map(e=>({value:e.code,label:e.label,flag:e.flag}));function Ri({value:e,onChange:t}){const{t:r}=nt(),s=Ui.map(e=>({value:e.value,label:e.label,icon:e.flag}));return a(Ni,{options:s,value:e,onChange:t,placeholder:r("dropdowns.searchLanguage"),emptyLabel:r("dropdowns.chooseLanguage")})}const Di=[{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,a)=>{let t=a.utc;for(let r=0;r<t.length;r++){const s=t[r],n=a.text;let i=n.substring(n.indexOf("(")+1,n.indexOf(")"));-1!==i.indexOf("UTC")&&e.push({value:s,abbr:a.abbr,offset:a.offset,isdst:a.isdst,text:`(${i}) ${s}`,utc:["Etc/GMT-13","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Tongatapu"]})}return e},[]).filter((e,a,t)=>a===t.findIndex(a=>a.value===e.value));function Mi({value:e,onChange:t}){const{t:r}=nt(),s=Di.map(e=>({value:e.value,label:e.text}));return a(Ni,{options:s,value:e,onChange:t,placeholder:r("dropdowns.searchTimezone"),emptyLabel:r("dropdowns.chooseTimezone")})}const _i=({workspace:t})=>{const{t:r}=nt(),{updateUserProfile:s,getProfile:n}=go(),[i,o]=p(!1),[c,l]=p(),[d,m]=p(0),h=Pn(),g=xe.object({name:xe.string().min(2,{message:r("profile.nameMinLength")}),country:xe.string().optional(),timezone:xe.string().optional(),language:xe.string().optional(),currency:xe.string().optional()}),f=we({resolver:Ln(g),defaultValues:{name:c?.name||"",country:c?.country||"",timezone:c?.timezone||"",language:c?.language||"",currency:c?.currency||""}});return u(()=>{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("div",{children:[h.message&&e("div",{className:"bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-4",children:[a("p",{className:"font-medium",children:r("settings.common.success")}),a("p",{className:"text-sm",children:h.message})]}),a("div",{className:"space-y-4",children:a(Kn,{...f,children:e("form",{onSubmit:f.handleSubmit(async function(e){o(!0),h.clear();try{await s({name:e.name,country:e.country,timezone:e.timezone,language:e.language,currency:e.currency}),h.show(r("profile.success"))}catch(e){Be(e,{component:"WorkspaceSettingsProfile",action:"updateUserProfile",metadata:{workspaceId:t._id}})}finally{o(!1)}}),className:"space-y-4",children:[e("div",{children:[a("label",{className:"block text-sm font-medium mb-1",children:r("profile.email")}),a(Qn,{disabled:!0,className:"w-full border rounded px-3 py-2 bg-gray-100",value:c?.email})]}),a(jn,{disabled:i,control:f.control,name:"name",render:({field:t})=>e(Hn,{children:[a(Jn,{children:r("profile.name")}),a(qn,{children:a(Qn,{...t})}),a(Zn,{})]})}),e("div",{className:"flex gap-y-2 my-4 flex-col",children:[e("div",{className:"flex flex-col gap-0.5",children:[a("div",{className:"text-sm font-medium",children:r("profile.language")}),a(Ri,{value:f.watch("language"),onChange:e=>{f.setValue("language",e)}})]}),e("div",{className:"flex flex-col gap-0.5",children:[a("div",{className:"text-sm font-medium",children:r("profile.country")}),a(Ai,{value:f.watch("country"),onChange:e=>{f.setValue("country",e)}})]}),e("div",{className:"flex flex-col gap-0.5",children:[a("div",{className:"text-sm font-medium",children:r("profile.currency")}),a(Pi,{value:f.watch("currency"),onChange:e=>{f.setValue("currency",e)}})]}),e("div",{className:"flex flex-col gap-0.5",children:[a("div",{className:"text-sm font-medium",children:r("profile.timezone")}),a(Mi,{value:f.watch("timezone"),onChange:e=>{f.setValue("timezone",e)}})]})]}),e("div",{className:"flex justify-end gap-x-2",children:[a(Us,{type:"submit",progress:i,disabled:i,children:r("profile.save")}),a(Us,{type:"button",variant:"outline",onClick:()=>{m(e=>e+1)},disabled:i,children:r("profile.reset")})]})]})})}),c?.image&&e("div",{children:[a("label",{className:"block text-sm font-medium mb-1",children:r("profile.profileImage")}),a("div",{className:"w-16 h-16 rounded-full overflow-hidden",children:a("img",{src:c.image,alt:c.name,className:"w-full h-full object-cover"})})]})]}):a(ln,{})},Wi=(e,a)=>{const t=new Date(e);return Number.isNaN(t.getTime())?"":new Intl.DateTimeFormat(a,{dateStyle:"medium"}).format(t)},Fi=()=>{const{t:r,formattingLocale:s}=nt(),{api:n}=Tt(),[i,o]=p(!0),[c,l]=p([]),[d,h]=p(null),[g,f]=p(null),[b,y]=p(""),w=m(async()=>{try{const e=await n.getPasskeys();l(e)}catch(e){Be(e,{component:"WorkspaceSettingsSecurity"})}finally{o(!1)}},[n]);return u(()=>{w()},[w]),i?a(ln,{}):e("div",{className:"space-y-4",children:[e("div",{children:[a("h3",{className:"text-sm font-medium",children:r("security.passkeysTitle")}),a("p",{className:"text-sm text-muted-foreground",children:r("security.passkeysDescription")})]}),0===c.length?e("div",{className:"flex flex-col items-center gap-2 rounded-md border border-dashed p-6 text-center",children:[a(M,{className:"h-5 w-5 text-muted-foreground"}),a("p",{className:"text-sm text-muted-foreground",children:r("security.noPasskeys")})]}):a("div",{className:"space-y-2",children:c.map(i=>e("div",{className:"flex items-center justify-between gap-3 rounded-md border p-3 "+(!1===i.active?"opacity-70":""),children:[e("div",{className:"flex min-w-0 items-center gap-3",children:[a(M,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a("div",{className:"min-w-0",children:g===i.id?e("div",{className:"flex items-center gap-2",children:[a(Qn,{value:b,onChange:e=>y(e.target.value),placeholder:r("security.renamePlaceholder"),className:"h-8"}),a(Us,{size:"icon",variant:"ghost",className:"h-8 w-8 shrink-0",disabled:d===i.id,onClick:()=>async function(e){const a=b.trim();if(a){h(e);try{await n.renamePasskey(e,a),l(t=>t.map(t=>t.id===e?{...t,name:a}:t)),f(null)}catch(e){Be(e,{component:"WorkspaceSettingsSecurity"})}finally{h(null)}}}(i.id),children:a(_,{className:"h-4 w-4"})}),a(Us,{size:"icon",variant:"ghost",className:"h-8 w-8 shrink-0",onClick:()=>f(null),children:a(W,{className:"h-4 w-4"})})]}):e(t,{children:[e("div",{className:"flex items-center gap-2",children:[a("p",{className:"truncate text-sm font-medium",children:i.name}),!1===i.active&&a("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:r("security.inactiveHint"),children:r("security.inactive")})]}),a("p",{className:"text-xs text-muted-foreground",children:!1===i.active?r("security.inactiveHint"):i.lastUsedAt?`${r("security.lastUsed")}: ${Wi(i.lastUsedAt,s)}`:i.createdAt?`${r("security.added")}: ${Wi(i.createdAt,s)}`:null})]})})]}),g!==i.id&&e("div",{className:"flex shrink-0 items-center gap-1",children:[a(Us,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":r("security.rename"),onClick:()=>{f(i.id),y(i.name)},children:a(F,{className:"h-4 w-4"})}),e(fn,{children:[a(bn,{asChild:!0,children:a(Us,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive","aria-label":r("security.remove"),disabled:d===i.id,children:a(C,{className:"h-4 w-4"})})}),e(vn,{children:[e(xn,{children:[a(Sn,{children:r("security.removeTitle")}),a(kn,{children:r("security.removeDescription")})]}),e(Nn,{children:[a(An,{children:r("settings.common.cancel")}),a(Cn,{onClick:()=>async function(e){h(e);try{await n.deletePasskey(e),l(a=>a.filter(a=>a.id!==e))}catch(e){Be(e,{component:"WorkspaceSettingsSecurity"})}finally{h(null)}}(i.id),children:r("security.remove")})]})]})]})]})]},i.id))}),a("p",{className:"text-xs text-muted-foreground",children:r("security.addHint")})]})};function Oi(e,a){if(null==e)return null;const t=e[a??"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 Li(e,a,t={}){if(null==e)return null;const{overageInCents:r=!0,currency:s,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=r?o/100:o,l=(s??"").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??sn(s??"")}${c.toFixed(2)}`}else{d=`${t.currencySymbol??sn(s??"")}${"number"==typeof c?c.toFixed(2):String(o)}`}return{included:i,hasOverage:!0,allowOverage:!0,price:d,unit:a&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(n)} ${a}`:a||""}}const Bi={Personal:"personal"},Gi=(e,a,t="en-US")=>{const r=(a??"").trim();return r?new Intl.NumberFormat(t,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:2}).format(e/100):(e/100).toFixed(2)},Ki=e=>{switch(e){case Yr:return"bg-green-100 text-green-800";case qr:return"bg-yellow-100 text-yellow-800";case Jr:return"bg-gray-100 text-gray-800";case Zr:return"bg-red-100 text-red-800";default:return"bg-gray-100 text-gray-800"}},Vi=({workspaceId:r,hasActiveSubscription:s=!1,onViewPricingPlans:n,limit:i=20})=>{const{t:o,formattingLocale:c}=nt(),{can:l}=en(),d=l(qs.WORKSPACE_BILLING_VIEW),{invoices:u,loading:m,error:p,refetch:h}=Wt(r,i);if(!d)return a(on,{});const g=u.length>0;return e("div",{className:"space-y-4",children:[e("div",{className:"flex items-center justify-between",children:[e("div",{children:[a("h3",{className:"text-lg font-semibold",children:o("invoices.title")}),a("p",{className:"text-sm text-gray-600",children:o("invoices.description")})]}),a(Us,{variant:"ghost",size:"sm",progress:m,onClick:h,disabled:m,children:o("settings.common.refreshAction",{loading:String(m)})})]}),p&&e("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("div",{children:[a("p",{className:"font-medium",children:o("invoices.errorLoading")}),a("p",{className:"text-sm mt-1",children:p})]}),a(Us,{variant:"outline",size:"sm",onClick:h,disabled:m,className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:o("settings.common.retryAction",{loading:String(m)})})]}),m&&!g?a("div",{className:"border rounded-lg p-6",children:a(ln,{})}):g?a("div",{className:"space-y-2",children:u.map(r=>{const s=(e=>{switch(e.status){case Jr:case qr:return{textKey:"invoices.pay",color:"bg-blue-600 hover:bg-blue-700"};case Yr:return{textKey:"invoices.view",color:"bg-green-600 hover:bg-green-700"};case Zr:case Qr: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"}}})(r);return e("div",{className:"border rounded-lg bg-white hover:shadow-sm transition-shadow p-3",children:[e("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[a("span",{className:"text-sm font-medium text-gray-900 truncate min-w-0",children:r.description||r.number||r.id.slice(-8)}),a("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium shrink-0 ${Ki(r.status)}`,children:o(`invoices.status.${r.status}`)})]}),e("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-0.5 text-sm text-gray-600 mb-2.5",children:[a("span",{className:"font-medium text-gray-900",children:Gi(r.amount_due,r.currency,c)}),r.created&&e(t,{children:[a("span",{className:"text-gray-300 hidden sm:inline",children:"·"}),a("span",{children:mn(r.created,c)})]}),r.amount_paid>0&&r.amount_due>0&&a("span",{className:"text-xs text-gray-500",children:o("invoices.paidAmount",{amount:Gi(r.amount_paid,r.currency,c)})})]}),e("div",{className:"flex items-center gap-2",children:[e(Us,{size:"sm",disabled:!r.hosted_invoice_url,onClick:()=>r.hosted_invoice_url&&window.open(r.hosted_invoice_url,"_blank","noopener,noreferrer"),className:s.color,children:[o(s.textKey),a(L,{className:"h-3 w-3 ms-1.5"})]}),r.invoice_pdf&&e(Us,{size:"sm",variant:"outline",onClick:()=>window.open(r.invoice_pdf,"_blank","noopener,noreferrer"),children:[a(B,{className:"h-3 w-3 me-1.5"}),o("invoices.download")]})]})]},r.id)})}):e("div",{className:"border rounded-lg p-6 text-center",children:[a(O,{className:"h-12 w-12 mx-auto text-gray-400 mb-3"}),a("p",{className:"text-sm text-gray-500",children:o(s?"invoices.noInvoicesWithSub":"invoices.noInvoices")}),!s&&n&&a(Us,{size:"sm",className:"mt-4",onClick:n,children:o("subscription.viewPricingPlans")})]})]})},ji=g(()=>import("./SubscriptionDialog-nuMunBn4.mjs").then(e=>({default:e.default}))),zi=(e,a)=>{if(!a)return"";try{const t=new Date(a);return isNaN(t.getTime())?"":new Intl.DateTimeFormat(e,{month:"long",day:"numeric",year:"numeric"}).format(t)}catch{return""}},$i=({workspace:r})=>{const s=r._id?.toString(),{t:n,formattingLocale:c,fmtNum:l,fmtCents:d}=nt(),{api:m}=Tt(),{can:g}=en(),{settings:f}=At(),b=g(qs.WORKSPACE_BILLING_VIEW),y=g(qs.WORKSPACE_BILLING_MANAGE),v=f?.workspace?.mode===Bi.Personal,{subscription:x,loading:N,error:S,updateSubscription:k,refetch:C}=_t(s),{createCheckoutSession:A}=Dt(s),{cancelSubscription:T,loading:E}=Lt(s),{resumeSubscription:P,loading:I}=Bt(s),{openBillingPortal:U,loading:R}=Ft(s),{versions:D,loading:M,error:_,refetch:W}=Rt(s),F=N||M,O=S||_,{currentVersion:L,latestVersion:B,isDeprecated:j,plansToShow:z}=o(()=>{const e=D?.currentVersion,a=D?.availableVersions||[],t=null!=x?.subscription;let r=null;a.length>0?r=a.reduce((e,a)=>a.version>e.version?a:e):e&&(r=e);const s=!!(t&&r&&e)&&r.version>e.version;return{currentVersion:e,latestVersion:r,hasNewerVersion:s,isDeprecated:s&&t,plansToShow:r?.plans&&r.plans.length>0?r.plans:[]}},[D,x?.subscription]),[$,H]=p(!1),[J,q]=p(null),[Y,Z]=p(null),Q=i(null),[X,ee]=p(!1),[ae,te]=p(!1),re=i(void 0),se=i(!1);u(()=>{if(se.current)return;if(N||!z||0===z.length)return;const e=ho.getState(),a=e.params?.action===Ir;x?.subscription&&!a||(se.current=!0,a&&(re.current=e.params,ho.clearParams()),ee(!0))},[N,x?.subscription,z]),u(()=>()=>{Q.current&&clearTimeout(Q.current)},[]);const[ne,ie]=p(!1),[oe,ce]=p("subscription"),le=async()=>{await Promise.all([C(),W()])},de=o(()=>gs(x?.subscription?.stripePriceId,z??[]),[x?.subscription?.stripePriceId,z]),ue=async()=>{if(s){te(!1),H(!0),q(null),Z(null);try{await T(),Z(n("subscription.cancelSuccess")),await le()}catch(e){const a=e instanceof Error?e.message:n("subscription.errorCanceling");q(a)}finally{H(!1),Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{q(null),Z(null)},5e3)}}};if(F&&!x&&!D)return a(ln,{});if(!b)return null;const me=x?.planVersion?._id||null;return s?e("div",{className:"space-y-6",children:[O&&e("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("div",{children:[a("p",{className:"font-medium",children:n("subscription.errorLoading")}),a("p",{className:"text-sm mt-1",children:O}),a("p",{className:"text-xs mt-2 text-red-600",children:n("subscription.errorLoadingDescription")})]}),a(Us,{variant:"outline",size:"sm",onClick:le,disabled:F,className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:n("settings.common.retryAction",{loading:String(F)})})]}),J&&e("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("div",{children:[a("p",{className:"font-medium",children:n("subscription.updateFailed")}),a("p",{className:"text-sm mt-1",children:J})]}),a(Us,{variant:"outline",size:"sm",onClick:()=>q(null),className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:n("settings.common.dismiss")})]}),Y&&e("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("div",{children:[a("p",{className:"font-medium",children:n("settings.common.success")}),a("p",{className:"text-sm mt-1",children:Y})]}),a(Us,{variant:"outline",size:"sm",onClick:()=>Z(null),className:"flex-shrink-0 border-green-200 text-green-700 hover:bg-green-100",children:n("settings.common.dismiss")})]}),a("div",{className:"border-b border-gray-200",children:e("nav",{className:"-mb-px flex gap-6","aria-label":"Subscription tabs",children:[a("button",{type:"button",onClick:()=>ce("subscription"),className:"border-b-2 py-3 text-sm font-medium transition-colors "+("subscription"===oe?"border-primary text-primary":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700"),children:n("subscription.plan")}),a("button",{type:"button",onClick:()=>ce("invoices"),className:"border-b-2 py-3 text-sm font-medium transition-colors "+("invoices"===oe?"border-primary text-primary":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700"),children:n("subscription.invoicesTab")})]})}),"subscription"===oe&&e(t,{children:[F&&e("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:[a(w,{className:"h-4 w-4 animate-spin flex-shrink-0"}),a("span",{children:n("settings.common.loading")})]}),j&&x?.subscription&&e("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("div",{className:"flex items-center gap-2 min-w-0",children:[a(G,{className:"h-4 w-4 text-amber-600 shrink-0"}),e("span",{className:"text-sm text-amber-800",children:[a("span",{className:"font-medium",children:n("subscription.planUpdateAvailable")}),e("span",{className:"text-amber-600",children:[" ","— v",L?.version||"?"," → v",B?.version||"?"]})]})]}),a(Us,{size:"sm",variant:"outline",className:"shrink-0 border-amber-300 text-amber-700 hover:bg-amber-100",onClick:()=>ee(!0),children:n("subscription.viewPlans")})]}),e("div",{className:"space-y-4",children:[e("div",{className:"flex items-center justify-between",children:[a("div",{children:a("p",{className:"text-sm text-gray-600",children:n("subscription.managePlan")})}),e("div",{className:"flex items-center gap-2",children:[(()=>{const e=x?.subscription?.subscriptionStatus===zr,t=x?.subscription?.cancelAtPeriodEnd;return t||E?null:e&&z&&z.length>0?a(Us,{size:"sm",onClick:()=>ee(!0),children:n("subscription.viewPricingPlans")}):x?.subscription&&!e&&y?a(Us,{variant:"outline",size:"sm",onClick:()=>ee(!0),children:n("subscription.changePlanButton")}):!x?.subscription&&z&&z.length>0?a(Us,{size:"sm",onClick:()=>ee(!0),children:n("subscription.viewPricingPlans")}):null})(),a(Us,{variant:"ghost",size:"sm",progress:F,onClick:le,disabled:F||$,children:n("settings.common.refreshAction",{loading:String(F)})})]})]}),x?.subscription?(()=>{const s=gs(x.subscription.stripePriceId,z??[]),i=s?.interval??null,o=s?.currency??x.plan?.currency??r?.billingCurrency??"",u=i&&x.planVersion?us(x.planVersion,o,i):null,m=o,p=x.planVersion?fs(x.planVersion,o):null,h=p&&i?bs(x.planVersion,o,i):null,g=Array.isArray(r?.users)?r.users.length:1,f=p?.includedSeats??0,b=Math.max(0,g-f),w=!!x.plan?.isFreemium,N=null!=u?0===u?n("subscription.free"):d(u,m):w?n("subscription.free"):null,S=i===Kr.Monthly?n("subscription.billingInterval.perMonth"):i===Kr.Quarterly?n("subscription.billingInterval.perQuarter"):i===Kr.Yearly?n("subscription.billingInterval.perYear"):"";return e("div",{className:"border rounded-lg overflow-hidden "+(j?"border-amber-300":"border-gray-200"),children:[x.subscription.subscriptionStatus===jr&&!x.subscription.cancelAtPeriodEnd&&(()=>{const t=x.subscription.trialEnd||x.subscription.stripeCurrentPeriodEnd,r=t?new Date(t):null,s=r&&!isNaN(r.getTime())?r:null,i=s?Math.max(0,Math.ceil((s.getTime()-Date.now())/864e5)):null,o=null!==i&&i<=3;return e("div",{className:"px-4 py-3 sm:px-5 text-sm flex flex-col sm:flex-row sm:items-center justify-between gap-2 "+(o?"bg-amber-50 text-amber-800 border-b border-amber-200":"bg-blue-50 text-blue-800 border-b border-blue-200"),children:[e("span",{children:[null!==i&&i<=0?n("subscription.trialEnded"):null!==i?n("subscription.trialEndsIn",{days:i}):n("subscription.onTrial")," ",n("subscription.upgradeToKeepAccess")]}),a(Us,{size:"sm",variant:o?"default":"outline",className:"shrink-0 "+(o?"":"border-blue-300 text-blue-700 hover:bg-blue-100"),onClick:()=>ee(!0),children:n("subscription.upgradePlan")})]})})(),e("div",{className:"p-4 sm:p-5 "+(j?"bg-amber-50/50":"bg-gray-50/50"),children:[e("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[a("h3",{className:"text-lg font-semibold text-gray-900",children:x.plan?.name||n("subscription.noPlanAssigned")}),e("span",{className:"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium "+(x.subscription.subscriptionStatus===Vr?x.subscription.cancelAtPeriodEnd?"bg-amber-100 text-amber-800":"bg-green-100 text-green-800":x.subscription.subscriptionStatus===jr?"bg-blue-100 text-blue-800":x.subscription.subscriptionStatus===zr?"bg-gray-100 text-gray-800":"bg-red-100 text-red-800"),children:[x.subscription.subscriptionStatus===Vr&&(x.subscription.cancelAtPeriodEnd?n("subscription.status.canceling"):n("subscription.status.active")),x.subscription.subscriptionStatus===jr&&n("subscription.status.trial"),x.subscription.subscriptionStatus===zr&&n("subscription.status.canceled"),x.subscription.subscriptionStatus===$r&&n("subscription.status.pastDue")]}),x.subscription.subscriptionStatus===jr&&zi(c,x.subscription.trialEnd||x.subscription.stripeCurrentPeriodEnd)&&e("span",{className:"text-xs text-gray-500",children:["(ends"," ",zi(c,x.subscription.trialEnd||x.subscription.stripeCurrentPeriodEnd),")"]}),j&&e("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:[a(G,{className:"h-3 w-3"}),n("subscription.status.deprecated")]})]}),x.plan?.description&&a("p",{className:"text-sm text-gray-600 mb-3",children:x.plan.description}),!w&&e("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4",children:[e("div",{children:[e("div",{className:"flex items-baseline gap-1 whitespace-nowrap",children:[a("span",{className:"text-2xl font-bold text-gray-900",children:N||n("invoices.na")}),N&&N!==n("subscription.free")&&S&&a("span",{className:"text-sm text-gray-500",children:S})]}),p&&h&&h>0&&!v&&a("div",{className:"text-xs text-gray-500 mt-1",children:n("subscription.perSeatDisplay",{price:d(h,m),interval:S})}),!v&&p&&h&&h>0&&b>0&&N&&N!==n("subscription.free")&&null!=u&&a("div",{className:"text-xs text-gray-500 mt-1 pt-1 border-t border-gray-200",children:n("subscription.estTotalDisplay",{total:d(u+h*b,m),interval:S,count:b})})]}),(x.subscription.subscriptionStatus===Vr||x.subscription.subscriptionStatus===jr)&&!x.subscription.cancelAtPeriodEnd&&zi(c,x.subscription.stripeCurrentPeriodEnd)&&e("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[a(K,{className:"h-3.5 w-3.5 flex-shrink-0"}),a("span",{children:n("subscription.nextBillingDisplay",{date:zi(c,x.subscription.stripeCurrentPeriodEnd)??""})})]})]}),j&&e("p",{className:"text-xs text-amber-600 mt-2",children:["Version ",L?.version||n("invoices.na")]}),!w&&(x.subscription.subscriptionStatus===Vr||x.subscription.subscriptionStatus===jr||x.subscription.subscriptionStatus===$r)&&e("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mt-4 pt-4 border-t border-gray-200",children:[x.subscription&&y&&x.subscription?.subscriptionId&&a(Us,{variant:"outline",size:"sm",onClick:()=>U(),disabled:R,progress:R,children:n(R?"subscription.openingPortal":"subscription.managePayment")}),y&&x.subscription?.subscriptionId&&(x.subscription.subscriptionStatus===Vr||x.subscription.subscriptionStatus===jr)&&a(t,{children:x.subscription.cancelAtPeriodEnd?a(Us,{variant:"outline",size:"sm",onClick:()=>ie(!0),disabled:$||E||I,progress:I,children:x.subscription.subscriptionStatus===jr?n("subscription.resumeTrial"):n("subscription.resumeTitle")}):a(Us,{variant:"outline",size:"sm",className:"text-red-600 hover:text-red-700 hover:bg-red-50 border-red-200",onClick:()=>te(!0),disabled:$||E||I,progress:E||$,children:E||$?n("subscription.canceling"):x.subscription.subscriptionStatus===jr?n("subscription.cancelTrial"):n("subscription.cancelTitle")})})]})]}),x.subscription.subscriptionStatus===$r&&a("div",{className:"px-5 py-3 bg-red-50 border-t border-red-200",children:e("div",{className:"flex items-start gap-3",children:[a(G,{className:"h-5 w-5 text-red-600 flex-shrink-0 mt-0.5"}),e("div",{children:[a("p",{className:"text-sm font-medium text-red-800",children:n("subscription.paymentPastDue")}),a("p",{className:"text-sm text-red-700 mt-0.5",children:n("subscription.paymentPastDueDescription")}),a(Us,{variant:"outline",size:"sm",className:"mt-2 border-red-200 text-red-700 hover:bg-red-100",onClick:()=>ce("invoices"),children:n("subscription.viewInvoices")})]})]})}),x.subscription.subscriptionStatus===$r&&x.subscription.dunningState&&x.subscription.dunningState!==es&&a("div",{className:"px-5 py-3 bg-red-50 border-t border-red-200",children:e("div",{className:"flex items-start gap-3",children:[a(G,{className:"h-5 w-5 text-red-600 flex-shrink-0 mt-0.5"}),e("div",{children:[a("p",{className:"text-sm font-medium text-red-800",children:x.subscription.dunningState===as?n("subscription.dunningFinal"):x.subscription.dunningState===ts?n("subscription.dunningSuspended"):n("subscription.dunningRecovery")}),a("p",{className:"text-sm text-red-700 mt-0.5",children:x.subscription.dunningState===ts?n("subscription.dunningSuspendedDescription"):n("subscription.dunningRecoveryDescription")})]})]})}),x.subscription.subscriptionStatus===Hr&&a("div",{className:"px-5 py-3 bg-blue-50 border-t border-blue-200",children:e("div",{className:"flex items-start gap-3",children:[a(K,{className:"h-5 w-5 text-blue-600 flex-shrink-0 mt-0.5"}),e("div",{children:[a("p",{className:"text-sm font-medium text-blue-800",children:n("subscription.subscriptionPaused")}),a("p",{className:"text-sm text-blue-700 mt-0.5",children:n("subscription.subscriptionPausedDescription")})]})]})}),x.subscription.cancelAtPeriodEnd&&a("div",{className:"px-5 py-3 bg-amber-50 border-t border-amber-200",children:e("div",{className:"flex items-start gap-3",children:[a(K,{className:"h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5"}),e("div",{children:[a("p",{className:"text-sm font-medium text-amber-800",children:x.subscription.subscriptionStatus===jr?n("subscription.scheduledTrialCancellation"):n("subscription.scheduledCancellation")}),a("p",{className:"text-sm text-amber-700 mt-0.5",children:zi(c,x.subscription.subscriptionStatus===jr&&x.subscription.trialEnd||x.subscription.stripeCurrentPeriodEnd)?e(t,{children:[x.subscription.subscriptionStatus===jr?n("subscription.trialEndDescription"):n("subscription.cancelEndDescription")," ",a("span",{className:"font-medium",children:zi(c,x.subscription.subscriptionStatus===jr&&x.subscription.trialEnd||x.subscription.stripeCurrentPeriodEnd)}),"."]}):n("subscription.cancelEndFallback")})]})]})}),x.planVersion&&(()=>{const t=((e,a,t=Kr.Monthly)=>{if(!e?.subscriptionItems)return{features:[],limits:[],quotas:[]};const r=[],s=[],n=[];return e.subscriptionItems.forEach(i=>{const o=i.slug;if(i.type===Xr.Feature){const a=e.features?.[o]??!1;r.push({item:i,enabled:a})}else if(i.type===Xr.Limit){const a=e.limits?.[o]??0;s.push({item:i,value:a})}else if(i.type===Xr.Quota){const r=a&&e.pricingVariants?.length?hs(e,a,o,t):Oi(e.quotas?.[o],t);null!=r&&n.push({item:i,value:r})}}),{features:r,limits:s,quotas:n}})(x.planVersion,o,i??"monthly");return t.features.length>0||t.limits.length>0||t.quotas.length>0?a("div",{className:"px-4 py-4 sm:px-5 sm:py-5 border-t border-gray-100",children:e("div",{className:"space-y-5",children:[t.features.length>0&&e("div",{children:[a("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:n("subscription.items.features")}),a("ul",{className:"space-y-1.5",children:t.features.sort(e=>e.enabled?-1:1).map(({item:t,enabled:r})=>e("li",{className:"flex items-center gap-2 text-sm",children:[a("span",{className:"w-4 text-center shrink-0 "+(r?"text-green-500":"text-gray-300"),children:r?"✓":"✕"}),a("span",{className:r?"text-gray-700":"text-gray-400",children:t.name})]},t._id))})]}),t.limits.length>0&&e("div",{children:[a("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:n("subscription.items.limits")}),a("ul",{className:"space-y-1.5",children:t.limits.map(({item:t,value:r})=>e("li",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-gray-600",children:t.name}),a("span",{className:"font-medium text-gray-900",children:l(r)})]},t._id))})]}),t.quotas.length>0&&e("div",{children:[a("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:n("subscription.items.quotas")}),a("ul",{className:"space-y-1.5",children:t.quotas.map(({item:t,value:r})=>{const s=Li(r,t.name.toLowerCase(),{currency:o,locale:c}),i=s?s.hasOverage?n("quota.includedWithOverage",{count:s.included,price:s.price,unit:s.unit}):n("quota.includedOnly",{count:s.included}):"—";return a("li",{className:"text-sm",children:e("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-0.5",children:[a("span",{className:"text-gray-600",children:t.name}),a("span",{className:"font-medium text-gray-900 text-xs sm:text-sm",children:i})]})},t._id)})})]}),p&&!v&&e("div",{children:[a("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:n("subscription.seats.title")}),e("div",{className:"bg-gray-50 rounded-lg p-3 space-y-1.5",children:[e("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-gray-600",children:n("subscription.seats.members")}),a("span",{className:"font-semibold text-gray-900",children:l(g)})]}),e("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-gray-600",children:n("subscription.seats.included")}),a("span",{className:"text-gray-900",children:l(f)})]}),b>0&&e("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-gray-600",children:n("subscription.seats.billable")}),e("span",{className:"font-medium text-amber-600",children:[l(b)," ",n("subscription.seats.extra")]})]}),h&&h>0&&e("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-gray-600",children:n("subscription.seats.perExtraSeat")}),e("span",{className:"text-gray-900",children:[d(h,o),S]})]}),(p?.maxSeats??0)>0&&e("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-gray-600",children:n("subscription.seats.limit")}),a("span",{className:"text-gray-900",children:l(p.maxSeats)})]})]})]}),x.planVersion?.creditGrant?.enabled&&"object"==typeof x.planVersion.creditGrant.creditPackage&&null!==x.planVersion.creditGrant.creditPackage&&e("div",{children:[a("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:n("subscription.items.credits")}),e("div",{className:"bg-purple-50 rounded-lg p-3 space-y-1.5",children:[e("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-gray-600",children:x.planVersion.creditGrant.renewOnPeriod?n("subscription.items.creditsPerMonth"):n("subscription.items.creditsOneTime")}),a("span",{className:"font-semibold text-purple-700",children:l("object"==typeof x.planVersion.creditGrant.creditPackage?x.planVersion.creditGrant.creditPackage.creditAmount:0)})]}),e("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-gray-600",children:n("subscription.items.creditRenewal")}),a("span",{className:"font-medium text-gray-900",children:x.planVersion.creditGrant.renewOnPeriod?"reset"===x.planVersion.creditGrant.mode?n("subscription.items.creditModeReset"):n("subscription.items.creditModeTopup"):n("subscription.items.creditModeLifetime")})]})]})]})]})}):null})()]})})():e("div",{className:"border rounded-lg p-6 text-center",children:[e("div",{className:"mb-4",children:[a(V,{className:"h-12 w-12 mx-auto text-gray-400 mb-3"}),a("p",{className:"text-lg font-medium text-gray-700",children:n("subscription.noSubscription")}),a("p",{className:"text-sm text-gray-500 mt-1",children:n("subscription.noSubscriptionDescription")})]}),z&&z.length>0&&a(Us,{size:"sm",onClick:()=>ee(!0),children:n("subscription.viewPricingPlans")})]})]}),!D&&!F&&e("div",{className:"border rounded-lg p-4 text-center",children:[e("div",{className:"text-gray-500 mb-2",children:[a("p",{className:"font-medium",children:n("subscription.errorLoading")}),O&&e("p",{className:"text-sm mt-2 text-red-600",children:["Error: ",O]}),!O&&a("p",{className:"text-sm mt-2",children:n("subscription.noPlansAvailable")})]}),a(Us,{variant:"outline",size:"sm",progress:F,onClick:le,disabled:F,className:"mt-4",children:n("settings.common.refreshAction",{loading:String(F)})})]})]}),"invoices"===oe&&e(t,{children:[F&&e("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:[a(w,{className:"h-4 w-4 animate-spin flex-shrink-0"}),a("span",{children:n("settings.common.loading")})]}),a(Vi,{workspaceId:s,hasActiveSubscription:null!==x?.subscription,onViewPricingPlans:()=>ce("subscription"),limit:20})]}),z&&z.length>0&&a(h,{fallback:X?a("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",children:e("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[a(w,{className:"h-5 w-5 animate-spin"}),a("span",{children:n("settings.common.loading")})]})}):null,children:a(ji,{open:X,onOpenChange:ee,planVersions:z,currentPlanVersionId:me||null,currentStripePriceId:x?.subscription?.stripePriceId,billingCurrency:r.billingCurrency,trialUsedAt:r.trialUsedAt,workspaceName:r.name,initialInterval:re.current?.interval,initialCurrency:re.current?.currency,currentMemberCount:Array.isArray(r?.users)?r.users.length:void 0,onSelectPlan:async(e,a=Kr.Monthly,t)=>{if(!s)return;const i=z?.find(a=>a._id===e),o=t??de?.currency??x?.plan?.currency??r?.billingCurrency??"",c=i?function(e,a,t){const r=ds(e,a);if(!r?.stripePrices)return null;const s=t===Kr.Monthly?"monthlyPriceId":t===Kr.Yearly?"yearlyPriceId":"quarterlyPriceId",n=t===Kr.Monthly?"monthly":t===Kr.Yearly?"yearly":void 0;return r.stripePrices[s]??(n?r.stripePrices[n]:void 0)??null}(i,o,a):null,l=x?.subscription?.stripePriceId;if(!c||!l||c!==l){H(!0),q(null),Z(null);try{const{successUrl:t,cancelUrl:r}=function(e){const a="undefined"!=typeof window?window.location.href:void 0;return{successUrl:Or({action:Er,status:Dr,ws:e,screen:Wr},a),cancelUrl:Or({action:Er,status:Mr,ws:e,screen:Wr},a)}}(s);let c;if(i?.plan?.isFreemium){return x?.subscription?.subscriptionId?(ee(!1),void te(!0)):(await m.selectFreePlan(s,e),ee(!1),$a(),await le(),void Z(n("subscription.updateSuccess")))}const l=x?.subscription?.subscriptionStatus===zr;if(c=x?.subscription&&!l?await k(e,{billingInterval:a,successUrl:t,cancelUrl:r}):await A({planVersionId:e,billingInterval:a,currency:o||void 0,successUrl:t,cancelUrl:r}),c&&"checkoutUrl"in c&&c.checkoutUrl)return void wr(c.checkoutUrl);Z(n("subscription.updateSuccess")),await le()}catch(e){const a=e instanceof Error?e.message:n("subscription.errorProcessing");q(a)}finally{H(!1),Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{q(null),Z(null)},5e3)}}},loading:$||F})}),a(fn,{open:ne,onOpenChange:ie,children:e(vn,{children:[e(xn,{children:[a(Sn,{children:n("subscription.resumeTitle")}),a(kn,{asChild:!0,children:e("div",{className:"space-y-3",children:[a("p",{children:n("subscription.resumeConfirm")}),e("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 space-y-2 text-sm",children:[e("div",{className:"flex items-start gap-2",children:[a(G,{className:"h-4 w-4 text-amber-600 mt-0.5 flex-shrink-0"}),e("span",{children:[n("subscription.resumeChargeDate")," ",x?.subscription?.stripeCurrentPeriodEnd&&zi(c,x.subscription.stripeCurrentPeriodEnd)?a("span",{className:"font-medium",children:zi(c,x.subscription.stripeCurrentPeriodEnd)}):n("subscription.resumeChargeFallback")]})]}),e("div",{className:"flex items-start gap-2",children:[a("span",{className:"text-amber-600 mt-0.5",children:"•"}),a("span",{children:n("subscription.resumeContinue")})]}),e("div",{className:"flex items-start gap-2",children:[a("span",{className:"text-blue-600 mt-0.5",children:"ℹ"}),a("span",{children:n("subscription.resumeCancelAnytime")})]})]})]})})]}),e(Nn,{children:[a(An,{disabled:I,children:n("subscription.resumeKeep")}),a(Cn,{onClick:async()=>{if(s){ie(!1),H(!0),q(null),Z(null);try{await P(),Z(n("subscription.resumeSuccess")),await le()}catch(e){const a=e instanceof Error?e.message:n("subscription.errorResuming");q(a)}finally{H(!1),Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{q(null),Z(null)},5e3)}}},disabled:I,children:n(I?"subscription.resuming":"subscription.resumeButton")})]})]})}),(()=>{const t=x?.subscription?.subscriptionStatus===jr,r=t&&x?.subscription?.trialEnd||x?.subscription?.stripeCurrentPeriodEnd;return a(fn,{open:ae,onOpenChange:te,children:e(vn,{children:[e(xn,{children:[a(Sn,{children:n(t?"subscription.cancelTrialTitle":"subscription.cancelTitle")}),a(kn,{asChild:!0,children:e("div",{className:"space-y-3",children:[a("p",{children:n(t?"subscription.cancelTrialConfirm":"subscription.cancelConfirm")}),e("div",{className:"bg-gray-50 rounded-lg p-4 space-y-2 text-sm",children:[e("div",{className:"flex items-start gap-2",children:[a("span",{className:"text-green-600 mt-0.5",children:"✓"}),e("span",{children:[n(t?"subscription.cancelTrialAccess":"subscription.retainAccess")," ",r&&zi(c,r)?a("span",{className:"font-medium",children:zi(c,r)}):n("subscription.retainAccessFallback")]})]}),e("div",{className:"flex items-start gap-2",children:[a("span",{className:"text-green-600 mt-0.5",children:"✓"}),a("span",{children:n(t?"subscription.cancelTrialNoCharge":"subscription.cancelNotCharged")})]}),e("div",{className:"flex items-start gap-2",children:[a("span",{className:"text-blue-600 mt-0.5",children:"ℹ"}),a("span",{children:n(t?"subscription.cancelTrialResume":"subscription.cancelResumeAnytime")})]})]})]})})]}),e(Nn,{children:[a(An,{disabled:E,children:n(t?"subscription.cancelTrialKeep":"subscription.cancelKeep")}),a(Cn,{onClick:ue,disabled:E,className:"bg-red-600 hover:bg-red-700 focus:ring-red-600",children:n(E?"subscription.canceling":t?"subscription.cancelTrialButton":"subscription.cancelButton")})]})]})})})()]}):a("div",{className:"border rounded-lg p-4 text-center text-gray-500",children:a("p",{children:n("subscription.invalidWorkspace")})})};function Hi(e){return e.replace(/[_-]/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Ji(e,a,t){return a+e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2})}function qi(e){try{const a=new Date(e);if(isNaN(a.getTime()))return null;const t=new Date;return Math.ceil((a.getTime()-t.getTime())/864e5)}catch{return null}}const Yi=()=>{const{quotas:t,loading:r,error:s,refetch:n}=br(),{t:i,formattingLocale:c,fmtNum:l}=nt(),{can:d}=en(),u=(e,a)=>Ji(e,a,c),{response:m}=Ht(),[h,g]=p(!1),f=o(()=>{const e={};if(!m?.planVersion||!m?.subscription)return e;const a=m.planVersion,r=m.subscription,s=r.billingInterval??"monthly",n=r.plan?.currency??"usd",i=sn(n);if(!t)return e;for(const r of Object.keys(t)){const o=ms(a,n,r,s);if(null==o||o<=0)continue;const c=a.quotas?.[r],l=c?.[s],d=l?.unitSize??1,u=t[r].overage,m=(d>1?Math.ceil(u/d):u)*o/100;e[r]={overageCents:o,unitSize:d,currency:n,currencySymbol:i,estimatedCost:m}}return e},[m,t]),b=o(()=>{const e=m?.subscription?.usageCurrentPeriodEnd||m?.subscription?.stripeCurrentPeriodEnd;if(!e)return null;const a=dn(e,c);return a?{endDate:a,daysRemaining:qi(e)}:null},[m,c]),y=async()=>{g(!0);try{await n()}finally{g(!1)}};if(r&&!t)return a(ln,{});if(!d(qs.WORKSPACE_USAGE_VIEW))return null;if(s)return e("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("div",{children:[a("p",{className:"font-medium",children:i("usage.errorLoading")}),a("p",{className:"text-sm mt-1",children:s})]}),a(Us,{variant:"outline",size:"sm",onClick:y,disabled:h,className:"flex-shrink-0 border-red-200 text-red-700 hover:bg-red-100",children:i("settings.common.retryAction",{loading:String(h)})})]});const w=function(e){return[...e].sort(([,e],[,a])=>{if(e.hasOverage&&!a.hasOverage)return-1;if(!e.hasOverage&&a.hasOverage)return 1;const t=e.included>0?e.consumed/e.included:e.consumed>0?1:0;return(a.included>0?a.consumed/a.included:a.consumed>0?1:0)-t})}(t?Object.entries(t):[]);if(0===w.length)return e("div",{className:"border rounded-lg p-8 text-center",children:[a(j,{className:"h-10 w-10 text-gray-300 mx-auto mb-3"}),a("p",{className:"text-sm text-gray-600",children:i("usage.noData")}),a("p",{className:"text-xs text-gray-500 mt-1",children:i("usage.noDataHint")})]});const v=w.filter(([,e])=>e.hasOverage).length,x=w.length>0?Math.round(w.reduce((e,[,a])=>e+(a.included>0?a.consumed/a.included*100:0),0)/w.length):0,N=Object.values(f).reduce((e,a)=>e+a.estimatedCost,0),k=Object.values(f)[0]?.currencySymbol??"$";return e("div",{className:"space-y-6",children:[e("div",{className:"flex items-center justify-between",children:[a("p",{className:"text-sm text-gray-600",children:i("usage.description")}),e(Us,{variant:"ghost",size:"sm",onClick:y,disabled:h,children:[a(S,{className:Ue("h-3.5 w-3.5 me-1.5",h&&"animate-spin")}),i("settings.common.refreshAction",{loading:String(h)})]})]}),b&&e("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:[a(K,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e("span",{children:[i("usage.resetDateDisplay",{date:b.endDate}),null!==b.daysRemaining&&b.daysRemaining>0&&e("span",{className:"text-gray-500",children:[" ","(",i("usage.daysRemainingDisplay",{count:b.daysRemaining}),")"]}),null!==b.daysRemaining&&b.daysRemaining<=0&&e("span",{className:"text-amber-600 font-medium",children:[" (",i("usage.renewingSoon"),")"]})]})]}),e("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 sm:gap-3",children:[e("div",{className:"border border-gray-200 rounded-lg p-3 sm:p-4",children:[a("p",{className:"text-xs text-gray-500 font-medium",children:i("usage.totalResources")}),a("p",{className:"text-lg sm:text-xl font-semibold text-gray-900 mt-1",children:l(w.length)})]}),e("div",{className:"border border-gray-200 rounded-lg p-3 sm:p-4",children:[a("p",{className:"text-xs text-gray-500 font-medium",children:i("usage.overallUsage")}),a("p",{className:"text-lg sm:text-xl font-semibold text-gray-900 mt-1",children:l(x)+"%"})]}),e("div",{className:Ue("border rounded-lg p-3 sm:p-4",v>0?"border-red-200 bg-red-50":"border-gray-200"),children:[a("p",{className:"text-xs text-gray-500 font-medium",children:i("usage.inOverage")}),a("p",{className:Ue("text-lg sm:text-xl font-semibold mt-1",v>0?"text-red-600":"text-gray-900"),children:l(v)})]}),v>0&&N>0&&e("div",{className:"border border-red-200 bg-red-50 rounded-lg p-3 sm:p-4",children:[a("p",{className:"text-xs text-gray-500 font-medium",children:i("usage.estOverageCost")}),a("p",{className:"text-lg sm:text-xl font-semibold mt-1 text-red-600",children:u(N,k)})]})]}),v>0&&a("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4",children:e("div",{className:"flex items-start gap-3",children:[a(G,{className:"h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5 hidden sm:block"}),e("div",{className:"flex-1",children:[a("h3",{className:"text-sm font-semibold text-amber-800 mb-1",children:i("usage.overageDetected")}),a("p",{className:"text-sm text-amber-700",children:i("usage.overageWarning",{count:v})}),N>0&&a("p",{className:"text-sm text-amber-700 font-medium mt-1",children:i("usage.estOverageCharges",{amount:u(N,k)})})]})]})}),a("div",{className:"space-y-3",children:w.map(([e,t])=>{const r=(s=t.consumed,(n=t.included)<=0?s>0?100:0:Math.min(s/n*100,100));var s,n;const i=function(e,a){return a?{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"}}(r,t.hasOverage),o=f[e];return a(Zi,{slug:e,quota:t,percent:r,colors:i,pricing:o},e)})})]})};function Zi({slug:t,quota:r,percent:s,colors:n,pricing:i}){const{t:o,formattingLocale:c}=nt(),l=e=>function(e,a){return e>=1e6?(e/1e6).toLocaleString(a,{maximumFractionDigits:1})+"M":e>=1e3?(e/1e3).toLocaleString(a,{maximumFractionDigits:1})+"K":e.toLocaleString(a)}(e,c),d=(e,a)=>Ji(e,a,c);return e("div",{className:"border border-gray-200 rounded-lg p-4 sm:p-5",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-y-1 mb-3",children:[e("div",{className:"flex items-center gap-2 min-w-0",children:[a("h3",{className:"text-sm font-semibold text-gray-900 truncate",children:Hi(t)}),r.hasOverage&&a("span",{className:Ue("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",n.badge,n.badgeText),children:o("usage.overage")}),!r.hasOverage&&s>=90&&a("span",{className:Ue("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",n.badge,n.badgeText),children:o("usage.almostFull")})]}),e("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:[l(r.consumed)," / ",l(r.included)]})]}),a("div",{className:Ue("h-2 rounded-full w-full",n.bg),children:a("div",{className:Ue("h-2 rounded-full transition-all duration-500",n.bar),style:{width:`${s}%`}})}),e("div",{className:"flex items-center justify-between mt-2 text-xs text-gray-500",children:[a("span",{children:o("usage.percentUsed",{percent:Math.round(s)})}),a("span",{children:r.available>0?o("usage.availableRemaining",{count:l(r.available)}):r.hasOverage?o("usage.overLimitCount",{count:l(r.overage)}):o("usage.fullyUsed")})]}),r.hasOverage&&i&&e("div",{className:"mt-3 pt-3 border-t border-gray-200 space-y-2",children:[e("div",{className:"flex items-center justify-between text-xs",children:[a("span",{className:"text-gray-500",children:o("usage.overageUnits")}),a("span",{className:"font-medium text-gray-900",children:l(r.overage)})]}),e("div",{className:"flex items-center justify-between text-xs",children:[a("span",{className:"text-gray-500",children:o("usage.rate")}),a("span",{className:"font-medium text-gray-900",children:o("usage.rateDisplay",{rate:d(i.overageCents/100,i.currencySymbol),unitSize:i.unitSize})})]}),i.unitSize>1&&e("div",{className:"flex items-center justify-between text-xs",children:[a("span",{className:"text-gray-500",children:o("usage.billableBlocks")}),a("span",{className:"font-medium text-gray-900",children:l(Math.ceil(r.overage/i.unitSize))})]}),e("div",{className:"flex items-center justify-between text-xs pt-2 border-t border-gray-200",children:[a("span",{className:"font-medium text-red-600",children:o("usage.estimatedCharge")}),a("span",{className:"font-semibold text-red-600",children:d(i.estimatedCost,i.currencySymbol)})]})]}),!r.hasOverage&&i&&a("div",{className:"mt-2 text-xs text-gray-500",children:o("usage.overageRateDisplay",{rate:o("usage.rateDisplay",{rate:d(i.overageCents/100,i.currencySymbol),unitSize:i.unitSize})})})]})}const Qi=Te.Root,Xi=r.forwardRef(({className:t,children:r,...s},n)=>e(Te.Trigger,{ref:n,className:Ue("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",t),...s,children:[r,a(Te.Icon,{asChild:!0,children:a(de,{className:"h-4 w-4 opacity-50"})})]}));Xi.displayName=Te.Trigger.displayName;const eo=r.forwardRef(({className:e,children:t,position:s="popper",...n},i)=>{const{container:o}=r.useContext(Rs);return a(Te.Portal,{container:o,children:a(Te.Content,{ref:i,className:Ue("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"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:s,...n,children:a(Te.Viewport,{className:Ue("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t})})})});eo.displayName=Te.Content.displayName;r.forwardRef(({className:e,...t},r)=>a(Te.Label,{ref:r,className:Ue("px-2 py-1.5 text-sm font-semibold",e),...t})).displayName=Te.Label.displayName;const ao=r.forwardRef(({className:t,children:r,...s},n)=>e(Te.Item,{ref:n,className:Ue("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",t),...s,children:[a("span",{className:"absolute end-2 flex h-3.5 w-3.5 items-center justify-center",children:a(Te.ItemIndicator,{children:a(ce,{className:"h-4 w-4"})})}),a(Te.ItemText,{children:r})]}));ao.displayName=Te.Item.displayName;function to(e,a){const{response:t}=Ht();return o(()=>{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 r=e.users?.length??0,s=t?.planVersion,n=t?.subscription,i=e.billingCurrency||"usd",o=ys({planVersion:s,currency:i,settingsMaxUsers:a?.settingsMaxUsers}),{maxUsers:c,hasSeatPricing:l,includedSeats:d}=o,u=l?Math.max(0,r-d):0,m=c>0?Math.max(0,c-r):1/0,p=c>0&&r>=c,h=c>0&&r>=.8*c&&!p,g=l&&s?bs(s,i,n?.billingInterval??"monthly"):null,f=ws({memberCount:r,maxUsersConfig:o});return{hasSeatPricing:l,memberCount:r,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}},[t,e,a?.settingsMaxUsers])}r.forwardRef(({className:e,...t},r)=>a(Te.Separator,{ref:r,className:Ue("-mx-1 my-1 h-px bg-muted",e),...t})).displayName=Te.Separator.displayName;const ro=({workspace:r})=>{const{user:s}=wo(),{t:n,fmtNum:i,fmtCents:o}=nt(),[c,l]=p(0),[d,m]=p(!1),[h,g]=p([]),[f,b]=p(null),{getUsers:y,removeUser:v,updateUser:x}=go(),{settings:N}=At(),{can:S}=en(),{response:k}=Ht(),C=to(r,{settingsMaxUsers:N?.workspace?.maxWorkspaceUsers});u(()=>{r&&(m(!0),y(r._id).then(e=>{g(e)}).catch(e=>{Be(e,{component:"WorkspaceSettingsUsers",action:"getUsers",metadata:{workspaceId:r._id}})}).finally(()=>{m(!1)}))},[r,c,y]);const A=()=>{l(e=>e+1)},T=N?.workspace?.mode===Bi.Personal;if(d||!r)return a(ln,{});if(T)return null;const E=e=>"string"==typeof e?{name:n("users.unknownUser"),email:e,id:e,role:"-"}:{name:e.name||n("users.unknownUser"),email:e.email,id:e._id},P=h.map(e=>({...e,...E(e.user)})),I=S(qs.WORKSPACE_MEMBERS_INVITE),U=S(qs.WORKSPACE_MEMBERS_REMOVE),R=S(qs.WORKSPACE_MEMBERS_ROLE_CHANGE),{hasSeatPricing:D,includedSeats:M,maxUsers:_,canInvite:W,inviteBlockReason:F,inviteBlockMessageKey:O,inviteBlockMessageValues:L,perSeatPriceCents:B,currency:G}=C,K=h.length,V=k?.subscription?.billingInterval??"monthly",j=D&&K>=M;return e("div",{children:[!I&&!U&&!R&&a(on,{descriptionKey:"users.adminOnly"}),I&&a("div",{className:"mb-4",children:W?e("div",{children:[a(so,{onInvite:A,workspaceId:r._id}),j&&B&&B>0&&a("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:a("span",{children:n("users.extraSeatCost",{price:o(B,G),interval:V})})})]}):a("div",{className:"flex items-center justify-between p-3 bg-red-50 border border-red-100 rounded-md",children:e("div",{children:[a("p",{className:"text-sm font-medium text-red-700",children:n("users.limitReached",{reason:F??"member_limit_reached"})}),a("p",{className:"text-xs text-red-600 mt-0.5",children:O?n(O,L??void 0):""})]})})}),(D||_>0)&&e("div",{className:"mb-4 rounded-lg border bg-gray-50 p-4",children:[e("div",{className:"flex items-center justify-between mb-2",children:[a("h4",{className:"text-sm font-semibold text-gray-900",children:n("users.seatHeading",{hasSeatPricing:String(D)})}),_>0&&e("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full "+(K>=_?"bg-red-100 text-red-700":K>=.8*_?"bg-amber-100 text-amber-700":"bg-emerald-100 text-emerald-700"),children:[i(K)," / ",i(_)]})]}),_>0&&a("div",{className:"w-full h-1.5 bg-gray-200 rounded-full mb-3",children:a("div",{className:"h-1.5 rounded-full transition-all "+(K>=_?"bg-red-500":K>=.8*_?"bg-amber-500":"bg-emerald-500"),style:{width:`${Math.min(100,K/_*100)}%`}})}),e("div",{className:"flex items-center justify-between text-sm text-gray-600",children:[a("div",{children:D?e(t,{children:[a("span",{className:"text-gray-900 font-medium",children:i(M)})," ",n("users.included"),B&&B>0&&e("span",{className:"text-gray-400",children:[" ","· ",o(B,G),n("users.perExtraSeat")]})]}):e("span",{children:[a("span",{className:"text-gray-900 font-medium",children:i(_)})," ",n("users.maxMembers")]})}),_>0?e("span",{children:[i(Math.max(0,_-K))," ",n("users.available")]}):a("span",{className:"text-gray-400",children:n("users.noMemberLimit")})]})]}),e("div",{className:"mb-4 flex items-center justify-between",children:[a("div",{children:a("div",{className:"text-sm text-gray-600",children:n("users.memberCount",{count:K})})}),a("div",{children:a(Us,{variant:"ghost",size:"sm",onClick:A,progress:d,children:n("settings.common.refreshAction",{loading:String(d)})})})]}),a("ul",{className:"space-y-2",children:P.map((t,i)=>{const o=t.id===s?.id,c=("object"==typeof r.createdBy&&null!==r.createdBy?r.createdBy._id:r.createdBy)===t.id;return e("li",{className:"border rounded p-3",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0",children:[a("div",{className:"w-8 h-8 bg-gray-200 rounded-full flex items-center justify-center text-sm font-medium shrink-0",children:t.name.charAt(0).toUpperCase()}),e("div",{className:"min-w-0",children:[a("div",{className:"font-medium text-sm truncate",children:t.name}),a("div",{className:"text-xs text-gray-500 truncate",children:t.email})]})]}),e("div",{className:"flex items-center gap-1 shrink-0",children:[o&&a("span",{className:"text-xs bg-blue-100 text-blue-800 px-2 py-0.5 rounded",children:n("users.you")}),c&&a("span",{className:"text-xs bg-purple-100 text-purple-800 px-2 py-0.5 rounded",children:n("users.owner")})]})]}),R&&e("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("div",{className:"relative flex-1 sm:flex-initial",children:[e(Qi,{disabled:o||!R||c||f===t.id,value:t.role,onValueChange:e=>{return a=r._id,s=t.id,n=e,void(Hs(r,s)?Be(new Error("Cannot change the role of the workspace owner"),{component:"WorkspaceSettingsUsers",action:"handleUpdateRole",metadata:{workspaceId:a,userId:s,role:n}}):(b(s),x(a,s,{role:n}).then(()=>{A()}).catch(e=>{Be(e,{component:"WorkspaceSettingsUsers",action:"handleUpdateRole",metadata:{workspaceId:a,userId:s,role:n}})}).finally(()=>{b(null)})));var a,s,n},children:[a(Xi,{children:a(Ee,{placeholder:n("users.selectRole")})}),a(eo,{children:r?.roles.map(e=>a(ao,{value:e,children:e},e))})]}),f===t.id&&a("div",{className:"absolute end-8 top-1/2 -translate-y-1/2 pointer-events-none",children:a(w,{className:"h-4 w-4 animate-spin text-gray-500"})})]}),!o&&!c&&U&&a(Us,{variant:"destructive",size:"sm",startIcon:a(z,{}),onClick:()=>{return e=t.id,void(Hs(r,e)?Be(new Error("Cannot remove the workspace owner"),{component:"WorkspaceSettingsUsers",action:"handleRemoveUser",metadata:{workspaceId:r._id,userId:e}}):v(r._id,e).then(()=>{A()}).catch(a=>{Be(a,{component:"WorkspaceSettingsUsers",action:"handleRemoveUser",metadata:{workspaceId:r._id,userId:e}})}));var e}})]})]},i)})}),0===h.length&&a("div",{className:"text-center py-8 text-gray-500",children:n("users.noMembers")})]})};function so({onInvite:t,workspaceId:r}){const{t:s}=nt(),{addUser:n,getWorkspace:o}=go(),{settings:c}=At(),[l,d]=p(""),[m,h]=p("admin"),[g,f]=p(!1),[b,y]=p(null),[w,v]=p(null),[x,N]=p(null),S=i(null),k=c?.workspace.roles??x?.roles??[];u(()=>()=>{S.current&&clearTimeout(S.current)},[]),u(()=>{r&&o(r).then(N)},[r]);const C=()=>{y(null),v(null),d(""),h("admin")};return e("div",{className:"flex gap-2 flex-col gap-y-2",children:[b&&a("div",{className:"text-red-500",children:b}),w&&a("div",{className:"text-green-500",children:w}),e("div",{children:[a(Gn,{children:s("users.inviteByEmail")}),a(Qn,{type:"email",value:l,onChange:e=>d(e.target.value),placeholder:"example@example.com"})]}),e("div",{children:[a(Gn,{children:s("users.role")}),e(Qi,{value:m,onValueChange:h,children:[a(Xi,{children:a(Ee,{placeholder:s("users.selectRole")})}),a(eo,{children:k.map(e=>a(ao,{value:e,children:e},e))})]})]}),a("div",{children:a(Us,{progress:g,onClick:async()=>{const e=l.trim();if(!e)return void y(s("users.emailRequired"));/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?(f(!0),await n(r,e,m).then(()=>{v(s("users.inviteSuccess")),t?.()}).catch(a=>{Be(a,{component:"InviteMember",action:"addUser",metadata:{workspaceId:r,email:e,role:m}}),y(a instanceof Error?a.message:s("users.inviteFailed"))}).finally(()=>{f(!1),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{C()},6e3)})):y(s("users.invalidEmail"))},disabled:g||!l||!m,children:g?s("users.inviting"):s("users.inviteAs",{role:m})})})]})}const no=({workspace:t,section:r,setSection:s})=>{const{t:n}=nt(),{settings:i}=At(),{can:o}=en(),{appPermissions:c}=hr(),l=i?.workspace?.mode===Bi.Personal,d=o(qs.WORKSPACE_DELETE),u=c&&Object.keys(c).length>0;return e("div",{className:"w-44 sm:w-56 h-full flex flex-col space-y-4 sm:space-y-6 shrink-0",children:[t&&a("div",{className:"border-b p-2 py-4",children:e("div",{className:"flex items-center gap-x-2",children:[t.image&&t.image.trim()&&a("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:a("img",{src:t.image,className:"w-full h-full object-contain",style:{width:"36px",height:"36px",maxWidth:"36px",maxHeight:"36px",objectFit:"contain"},alt:t.name})}),e("div",{className:Ue("flex-1 min-w-0",t.image?"":"ps-2"),children:[a("div",{className:"font-medium text-sm line-clamp-1 text-ellipsis overflow-hidden",children:t.name}),a("div",{className:"text-xs text-gray-500",children:t.workspaceId})]})]})}),e(io,{title:n("settings.sidebar.account"),children:[a(oo,{activeSection:r,icon:a($,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.profile"),section:co.Profile,onClick:()=>s(co.Profile)}),a(oo,{activeSection:r,icon:a(M,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.security"),section:co.Security,onClick:()=>s(co.Security)})]}),e(io,{title:n("settings.sidebar.workspace"),children:[o(qs.WORKSPACE_SETTINGS_VIEW)&&a(oo,{activeSection:r,icon:a(H,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.general"),section:co.General,onClick:()=>s(co.General)}),!l&&o(qs.WORKSPACE_MEMBERS_VIEW)&&a(oo,{activeSection:r,icon:a(J,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.users"),section:co.Users,onClick:()=>s(co.Users)}),o(qs.WORKSPACE_BILLING_VIEW)&&a(oo,{activeSection:r,icon:a(V,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.subscription"),section:co.Subscription,onClick:()=>s(co.Subscription)}),o(qs.WORKSPACE_USAGE_VIEW)&&a(oo,{activeSection:r,icon:a(j,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.usage"),section:co.Usage,onClick:()=>s(co.Usage)}),o(qs.WORKSPACE_BILLING_VIEW)&&a(oo,{activeSection:r,icon:a(v,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.credits"),section:co.Credits,onClick:()=>s(co.Credits)}),o(qs.WORKSPACE_FEATURES_VIEW)&&a(oo,{activeSection:r,icon:a(q,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.features"),section:co.Features,onClick:()=>s(co.Features)}),a(oo,{activeSection:r,icon:a(E,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.notifications"),section:co.Notifications,onClick:()=>s(co.Notifications)}),u&&!l&&a(oo,{activeSection:r,icon:a(Y,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.permissions"),section:co.Permissions,onClick:()=>s(co.Permissions)}),d&&!l&&a(oo,{activeSection:r,icon:a(G,{className:"h-3.5 w-3.5"}),label:n("settings.sidebar.danger"),section:co.Danger,onClick:()=>s(co.Danger)})]})]})};function io({title:t,children:r}){return e("div",{className:"px-2 flex flex-col space-y-1",children:[a("div",{className:"text-xs font-bold mb-2 text-gray-500 uppercase tracking-wide px-2",children:t}),r]})}function oo({icon:a,label:t,section:r,onClick:s,activeSection:n}){return e("button",{className:Ue("flex w-full text-start px-2 py-1 rounded text-sm items-center gap-x-1",r===n?"bg-blue-100 text-blue-700 font-medium":"hover:bg-gray-200 hover:text-gray-700"),onClick:()=>s(r),children:[a,t]})}const co={Profile:"profile",Security:"security",General:"general",Users:"users",Subscription:"subscription",Usage:"usage",Credits:"credits",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"},lo=new Set(Object.values(co)),uo={[co.Profile]:"settings.titles.profile",[co.Security]:"settings.titles.security",[co.General]:"settings.titles.general",[co.Users]:"settings.titles.users",[co.Subscription]:"settings.titles.subscription",[co.Usage]:"settings.titles.usage",[co.Credits]:"settings.titles.credits",[co.Features]:"settings.titles.features",[co.Notifications]:"settings.titles.notifications",[co.Permissions]:"settings.titles.permissions",[co.Danger]:"settings.titles.danger"},mo=({workspace:t,onClose:r,open:s,onOpenChange:n,defaultSection:i=co.Profile,section:o,onSectionChange:c,showTrigger:l=!0,trigger:d})=>{const{t:u,dir:m}=nt(),[h,g]=p(!1),[f,b]=p(i),y=void 0!==s?s:h,w=n||g,v=void 0!==o?o:f,x=c||b;if(!t)return null;const N=a(Us,{variant:"outline",size:"icon",children:a(Z,{className:"h-4 w-4"})});return e(Ms,{open:y,onOpenChange:e=>{w(e),!e&&r&&r()},children:[l&&a(_s,{asChild:!0,children:d||N}),e(Os,{dir:m,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:[a(Gs,{className:"sr-only",children:u(uo[v])}),a(no,{workspace:t,section:v,setSection:x}),e("div",{className:"flex-1 p-6 overflow-auto flex flex-col bg-background",children:[a(Bs,{className:"text-xl font-bold mb-4",children:u(uo[v])}),e("div",{className:"sm:max-h-[500px] overflow-y-auto",children:[v===co.Profile&&a(_i,{workspace:t}),v===co.Security&&a(Fi,{}),v===co.General&&a(ni,{workspace:t}),v===co.Users&&a(ro,{workspace:t}),v===co.Subscription&&a($i,{workspace:t}),v===co.Usage&&a(Yi,{}),v===co.Credits&&a(hn,{workspace:t}),v===co.Features&&a(In,{workspaceId:t._id?.toString()}),v===co.Notifications&&a(mi,{workspace:t}),v===co.Permissions&&a(pi,{workspace:t}),v===co.Danger&&a(Tn,{workspace:t})]})]})]})]})};var po=Object.freeze({__proto__:null,SETTINGS_SCREENS:lo,SettingsScreen:co,WorkspaceSettingsDialog:mo,default:mo});const ho=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:co.Profile}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getState(){return{...this.currentState}}openWorkspaceSettings(e,a){this.currentState={open:!0,section:e||co.Profile,params:a},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)})}},go=()=>{const e=vt(),{os:a,api:t}=Tt(),{settings:r}=At(),n=xt(e=>e.workspaces),i=xt(e=>e.auth.session?.user),o=m((a,t)=>{if((!(a._id===n.currentWorkspace?._id)||t?.forceEmit)&&a){const t=n.currentWorkspace;Vs(a),e.workspaces(ka(a)),Ps.emitWorkspaceChanged(a,t).catch(e=>{Be(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceChanged",metadata:{workspaceId:a._id}})})}},[n.currentWorkspace,e]),c=m(async(t,r)=>{const s=++g.current;e.workspaces(Ia(t._id));try{const e=a.auth?.callbacks?.onWorkspaceChange;if(e){const a=Js(t,i?.id);try{await e({workspace:t,user:i??null,role:a})}catch(e){throw Be(e,{component:"useSaaSWorkspaces",action:"onWorkspaceChange",metadata:{workspaceId:t._id}}),e}if(s!==g.current)return}o(t,r)}finally{s===g.current&&e.workspaces(Ia(null))}},[e,a.auth?.callbacks?.onWorkspaceChange,o,i]),l=s.useRef(c);l.current=c,u(()=>{if(!n.isInitialized){const a=js();if(e.workspaces(Aa(!0)),a){const e=n.workspaces.find(e=>e._id===a);e&&l.current(e,{forceEmit:!0}).catch(e=>{Be(e,{component:"useSaaSWorkspaces",action:"initWorkspaceSwitch",metadata:{savedWorkspaceId:a}})})}}},[n.isInitialized,n.workspaces,e]);const d=m(()=>{zs(),e.workspaces(Ca())},[e]),p=s.useRef(!1),h=s.useRef(!1),g=s.useRef(0),f=m(async()=>{if(!n.loading&&!p.current){p.current=!0,e.workspaces(Ta(!0)),e.workspaces(Ea(null));try{const a=await t.getWorkspaces();if(e.workspaces(wa(a)),a.length>0){const e=js();if(e&&$s(e,a)){const t=a.find(a=>a._id===e);if(t)try{await c(t,{forceEmit:!0})}catch{}}else{const e=a[0];try{await c(e,{forceEmit:!0})}catch{}}}}catch(a){e.workspaces(Ea(a instanceof Error?a.message:"Failed to fetch workspaces"))}finally{e.workspaces(Ta(!1)),p.current=!1}}},[t,n.loading,e,c]),b=m(async()=>{if(!n.refreshing&&!p.current){p.current=!0,e.workspaces(Pa(!0));try{const a=await t.getWorkspaces();e.workspaces(wa(a))}catch(e){}finally{e.workspaces(Pa(!1)),p.current=!1}}},[t,n.refreshing,e]),y=m(async(a,r)=>{const s=await t.createWorkspace({name:a,image:r});e.workspaces(va(s)),await c(s),Ps.emitWorkspaceCreated(s).catch(e=>{Be(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceCreated",metadata:{workspaceId:s._id}})}),setTimeout(()=>{ho.openWorkspaceSettings(co.Subscription)},300)},[t,e,c]),w=m(async(a,r)=>{const s=await t.updateWorkspace(a._id,r);e.workspaces(xa(s)),Ps.emitWorkspaceUpdated(s).catch(e=>{Be(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceUpdated",metadata:{workspaceId:s._id}})})},[t,e]),v=m(async()=>{if(h.current)return n.allFeatures.length>0?n.allFeatures:null;if(n.allFeatures.length>0)return n.allFeatures;h.current=!0;try{const a=await t.getFeatures();return e.workspaces(Sa(a)),a}catch(e){return Be(e,{component:"useSaaSWorkspaces",action:"getFeatures"}),null}finally{h.current=!1}},[t,e,n.allFeatures]),x=m(async(e,a,r)=>await t.updateFeature(e,a,r),[t]),N=m(async e=>t.updateSettings(e),[t]),S=m(async(e,a)=>{const r=await t.updateWorkspacePermissions(e,a);return await b(),r},[t,b]);u(()=>{if(!n.currentWorkspace?._id||0===n.workspaces.length)return;const a=n.currentWorkspace._id,t=n.workspaces.find(e=>e._id===a);if(t)t!==n.currentWorkspace&&(Vs(t),e.workspaces(ka(t)));else if(n.workspaces.length>0){const e=n.workspaces[0];e._id!==a&&c(e).catch(a=>{Be(a,{component:"useSaaSWorkspaces",action:"fallbackWorkspaceSwitch",metadata:{workspaceId:e._id}})})}},[n.workspaces,n.currentWorkspace,e,c]);const k=m(async e=>await t.getWorkspaceUsers(e),[t]),C=m(async(e,a,s)=>{const i=n.workspaces.find(a=>a._id===e);if(i){const e=ys({settingsMaxUsers:r?.workspace?.maxWorkspaceUsers}),a=ws({memberCount:i.users?.length??0,maxUsersConfig:e});if(!a.canInvite)throw new Error(a.blockMessageKey||"users.memberLimitReached")}const o=await t.addUser(e,{email:a,role:s});return i&&Ps.emitWorkspaceUserAdded(o.userId,i,s).catch(a=>{Be(a,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:o.userId,role:s}})}),b().catch(e=>{Be(e,{component:"useSaaSWorkspaces",action:"refreshAfterAddUser"})}),$a(),o},[t,n.workspaces,b,r]),A=m(async(e,a)=>{const r=n.workspaces.find(a=>a._id===e);if(r&&Hs(r,a))throw new Error("Cannot remove the workspace owner");const s=(await t.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===a),i=await t.removeUser(e,a);if(r&&s){const a=s.role;Ps.emitWorkspaceUserRemoved(i.userId,r,a).catch(t=>{Be(t,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:i.userId,role:a}})})}return b().catch(e=>{Be(e,{component:"useSaaSWorkspaces",action:"refreshAfterRemoveUser"})}),$a(),i},[t,n.workspaces,b]),T=m(async(e,a,r)=>{if(r.role){const t=n.workspaces.find(a=>a._id===e);if(t&&Hs(t,a))throw new Error("Cannot change the role of the workspace owner")}let s;if(r.role){const r=(await t.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===a);s=r?.role}const i=await t.updateUser(e,a,r);return r.role&&s&&s!==r.role&&Ps.emitWorkspaceUserRoleChanged(i.userId,i.workspace,s,r.role).catch(t=>{Be(t,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:a,previousRole:s,newRole:r.role}})}),i},[t,n.workspaces]),E=m(async e=>{const a=await t.getProfile().catch(()=>null),r=await t.updateUserProfile(e);return Ps.emitUserUpdated(r,a||void 0).catch(e=>{Be(e,{component:"useSaaSWorkspaces",action:"emitUserUpdated",metadata:{userId:r._id}})}),r},[t]),P=m(async()=>await t.getProfile(),[t]),I=m(async e=>await t.getWorkspace(e),[t]),U=m(async a=>{if(!i)throw new Error("User must be authenticated to delete a workspace");const r=n.workspaces.find(e=>e._id===a);if(!r)throw new Error("Workspace not found");if(!Hs(r,i.id))throw new Error("Only the workspace creator can delete the workspace");const s=await t.deleteWorkspace(a);return e.workspaces(Na(a)),n.currentWorkspace?._id===a&&(zs(),e.workspaces(Ca())),r&&Ps.emitWorkspaceDeleted(r).catch(e=>{Be(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceDeleted",metadata:{workspaceId:a}})}),s},[t,n.workspaces,n.currentWorkspace,e,i]);return{workspaces:n.workspaces,loading:n.loading,error:n.error,fetchWorkspaces:f,refreshWorkspaces:b,refreshing:n.refreshing,currentWorkspace:n.currentWorkspace,setCurrentWorkspace:o,switchToWorkspace:c,resetCurrentWorkspace:d,createWorkspace:y,allFeatures:n.allFeatures,getFeatures:v,updateFeature:x,updateWorkspaceSettings:N,updateWorkspacePermissions:S,getWorkspace:I,updateWorkspace:w,getUsers:k,addUser:C,removeUser:A,updateUser:T,getProfile:P,updateUserProfile:E,deleteWorkspace:U,switching:null!==n.switchingToId,switchingToId:n.switchingToId}};function fo(e,a,t){const r=e._id||e.id;if(!r||"string"!=typeof r)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:r,name:e.name||"",org:a,email:e.email,emailVerified:!1!==e.emailVerified,clientId:t,role:e.role||"",image:e.image}}function bo(e,a){return{user:e,sessionId:a,expires:new Date(Date.now()+864e5).toISOString()}}function yo(){return xt(e=>e.auth)}function wo(){const{t:e}=nt(),a=vt(),t=yo(),r=kt(),{serverUrl:s,orgId:n,auth:i}=r,{resetCurrentWorkspace:c,currentWorkspace:l}=go(),d=ur(),u=o(()=>new Ar({serverUrl:s,version:r.version}),[s,r.version]),p=m(async t=>{Nr(t||window.location.href),a.auth(je()),d.show(e("loading.redirecting"));try{const t=function(){const e=new Uint8Array(32);crypto.getRandomValues(e);const a=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return ot(kr,a),a}(),r=await u.requestAuth({orgId:n,clientId:i?.clientId??"",redirect:{success:i?.redirectUrl||window.location.href,error:i?.redirectUrl||window.location.href},state:t});if(!r.success)throw d.hide(),a.auth($e()),new Error(r.message||e("errors.generic"));wr(r.data.redirectUrl)}catch(e){throw d.hide(),a.auth($e()),Be(e,{component:"useSaaSAuth",action:"signIn"}),e}},[u,n,i,a,d,e]),h=m(async()=>{try{i?.callbacks?.onSignOut&&"function"==typeof i.callbacks.onSignOut&&await i.callbacks.onSignOut()}catch(e){Be(e,{component:"useSaaSAuth",action:"signOut"})}finally{ct(lt),a.auth(Je()),c()}},[a,c,i?.callbacks?.onSignOut]),g=m(e=>{l?ho.openWorkspaceSettings(e):Be(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),f=m(()=>{l?ho.openWorkspaceSettings(co.Credits,{action:Rr}):Be(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),b=m(()=>{l?ho.openWorkspaceSettings(co.Subscription,{action:Ir}):Be(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),y=o(()=>Qe(t.status),[t.status]);return o(()=>({user:t.session?.user,session:t.session,status:t.status,...y,signIn:p,signOut:h,openWorkspaceSettings:g,openCreditStore:f,openPlanPicker:b}),[t.session,t.status,y,p,h,g,f,b])}const vo=s.memo(({children:e,callbacks:r})=>{const{t:n}=nt(),i=vt(),o=yo(),c=kt(),l=Qe(o.status).isAuthenticated,d=ur(),p=s.useRef(!1),h=s.useRef(null),g=s.useRef(!1),f=s.useRef(null),b=m(async e=>{try{if(r?.handleAuthentication){d.show(n("loading.signingIn"));const{sessionId:a}=await r.handleAuthentication(e);if(!a||"string"!=typeof a||""===a.trim())throw new Error("Invalid sessionId received from authentication callback");const t=c;if(!ua(t))throw new Error("OS configuration is not available");const{serverUrl:s,version:o,orgId:l}=t;d.show(n("loading.verifyingAccount"));const u=new Ar({serverUrl:s,version:o}),m=await u.getProfile(a),p=bo(fo(m,l,t.auth?.clientId||""),a);d.show(n("loading.almostThere")),mt(p.sessionId),i.auth(He(p)),gt();const h=Sr();h&&h!==window.location.href&&wr(h),d.hide()}}catch(a){throw d.hide(),Sr(),Be(a,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),i.auth($e()),a}},[i,r,c,d,n]);return s.useEffect(()=>{if("undefined"==typeof window)return;if(l)return;if(g.current)return;if(f.current)return;if(!ua(c))return;if(ht())return;if(!r?.getSession)return g.current=!0,void i.auth($e());const e=r.getSession,{serverUrl:a,version:t,orgId:s}=c,o=c.auth?.clientId||"";f.current=(async()=>{d.show(n("loading.restoringSession"));let c=null;try{c=await e()}catch(e){Be(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!c)return g.current=!0,i.auth($e()),d.hide(),"undefined"!=typeof window&&Nr(window.location.href),void r?.onSessionExpired?.("missing");try{d.show(n("loading.verifyingAccount"));const e=new Ar({serverUrl:a,version:t}),r=await e.getProfile(c),l=bo(fo(r,s,o),c);mt(l.sessionId),g.current=!0,i.auth(He(l)),d.hide();const u=Sr();u&&u!==window.location.href&&wr(u)}catch(e){Be(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),g.current=!0,i.auth($e()),d.hide(),"undefined"!=typeof window&&Nr(window.location.href),r?.onSessionExpired?.("expired")}finally{f.current=null}})()},[l,i,c,r]),u(()=>{const e=ht();if(!e)return;if(p.current||h.current===e)return;if(!ua(c))return;const a=function(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(ut)}catch(e){return Be(e,{component:"auth-utils",action:"getStateFromUrl",metadata:{param:ut}}),null}}();if(a&&!function(e){if(!e)return!1;const a=it(kr);if(ct(kr),!a)return!1;if(a.length!==e.length)return!1;let t=0;for(let r=0;r<a.length;r++)t|=a.charCodeAt(r)^e.charCodeAt(r);return 0===t}(a))return Cr(),gt(),Be(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void i.auth($e());Cr(),p.current=!0,h.current=e;let t=!1;return i.auth(ze()),b(e).then(()=>{t||(h.current=null)}).catch(e=>{t||(Be(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),gt(),h.current=null)}).finally(()=>{p.current=!1}),()=>{t=!0}},[b,c.serverUrl,c.version,c.orgId]),a(t,{children:e})});vo.displayName="AuthProviderWrapper";const xo=s.memo(({config:e,auth:r,children:n})=>{const i=vt();kt();const o=s.useMemo(()=>({clientId:r?.clientId||"",redirectUrl:r?.redirectUrl||"",callbacks:r?.callbacks}),[r?.clientId,r?.redirectUrl,r?.callbacks]);return u(()=>{i.os(ca({...e,auth:o}))},[e,o,i]),a(t,{children:n})});xo.displayName="ContextConfigProvider";class No extends yt{constructor(e){super(e)}async getAttributes(e){const a=await this.fetchResponse("users/attributes",{signal:e});a.ok||await this.throwResponseError(a,"Failed to fetch user attributes");const t=await this.unwrapResponse(a,"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,a){return this.fetchJson(`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:a})},"Failed to update user attribute")}async getFeatures(e){const a=await this.fetchResponse("users/features",{signal:e});a.ok||await this.throwResponseError(a,"Failed to fetch user features");const t=await this.unwrapResponse(a,"Failed to fetch user features");return"object"==typeof t&&null!==t?t:{}}}const So=s.createContext(void 0),ko=s.memo(({children:e})=>{const{t:t}=nt(),r=kt(),n=function(){const e=kt();return o(()=>new No(e),[e.serverUrl,e.version])}(),{isAuthenticated:i}=wo(),{serverUrl:c,version:l}=r,[d,u]=p({}),[h,g]=p({}),[f,b]=p(!1),[y,w]=p(null),v=m(async e=>{if(c&&l&&i)try{const a=await n.getAttributes(e);u(a)}catch(e){if(_e(e))return;const a=e instanceof Error?e:new Error(t("errors.generic"));w(a),Be(e,{component:"UserProvider",action:"fetchAttributes"})}else u({})},[n,c,l,i]),x=m(async()=>{if(c&&l&&i){b(!0),w(null);try{await v()}finally{b(!1)}}},[c,l,i,v]),N=m(async e=>{b(!0),w(null);try{const a=await n.updateAttributes(e);return await v(),a}catch(a){const r=a instanceof Error?a:new Error(t("errors.generic"));throw w(r),Be(a,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),a}finally{b(!1)}},[n,v]),S=m(async(e,a)=>{b(!0),w(null);try{const t=await n.updateAttribute(e,a);return await v(),t}catch(r){const s=r instanceof Error?r:new Error(t("errors.generic"));throw w(s),Be(r,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:a}}),r}finally{b(!1)}},[n,v]),k=m(async e=>{if(c&&l&&i)try{const a=await n.getFeatures(e);g(a)}catch(e){if(_e(e))return;const a=e instanceof Error?e:new Error(t("errors.generic"));w(a),Be(e,{component:"UserProvider",action:"fetchFeatures"})}else g({})},[n,c,l,i]),C=m(async()=>{if(c&&l&&i){b(!0),w(null);try{await k()}finally{b(!1)}}},[c,l,i,k]);Nt(async e=>{if(!i||!c||!l)return u({}),void g({});b(!0),w(null);try{await Promise.all([v(e),k(e)])}finally{b(!1)}},[i,c,l,v,k],{onError:e=>Be(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const A=s.useMemo(()=>({attributes:d,features:h,isLoading:f,error:y,updateAttributes:N,updateAttribute:S,refreshAttributes:x,refreshFeatures:C}),[d,h,f,y,N,S,x,C]);return a(So.Provider,{value:A,children:e})});ko.displayName="UserProvider";const Co=g(()=>Promise.resolve().then(function(){return po}).then(e=>({default:e.default})));const Ao=({children:r})=>{const{currentWorkspace:s,switchToWorkspace:n,workspaces:o}=go(),[c,l]=p(!1),[d,m]=p(co.Profile),g=i(!1);return u(()=>{const e=ho.getState();l(e.open),m(e.section);return ho.subscribe(e=>{l(e.open),m(e.section)})},[]),u(()=>{if(g.current)return;if(!s)return;const e=Br();if(!e)return;const a=function(e){if(e.screen&&lo.has(e.screen))return e.screen;switch(e.action){case Er:case Pr:case Ir:return co.Subscription;case Ur:return co.Credits;default:return null}}(e);if(!a)return g.current=!0,void Gr();const t=e.ws;if(t&&t!==s._id){const e=o.find(e=>e._id===t);return e?void n(e).catch(e=>{Be(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:t}}),g.current=!0,Gr()}):(g.current=!0,void Gr())}g.current=!0,ho.openWorkspaceSettings(a,e),Gr()},[s,o,n]),e(t,{children:[r,s&&c&&a(Ve,{fallback:null,children:a(h,{fallback:null,children:a(Co,{workspace:s,open:c,onOpenChange:e=>{e||ho.closeSettings()},section:d,onSectionChange:e=>{ho.setSection(e)},showTrigger:!1})})})]})},To=(e,a,t)=>{if(a!==da.V1)throw new Error(`Invalid version: "${a}". Only "${da.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).`)},Eo=s.memo(({serverUrl:e,version:t,orgId:r,auth:n,locale:i,defaultPermissions:o,getCheckoutStripeParams:c,loadingComponent:l,children:d})=>{To(e,t,r);const m=s.useMemo(()=>({serverUrl:e,version:t,orgId:r}),[e,t,r]),p=s.useMemo(()=>n?.callbacks,[n?.callbacks?.handleAuthentication,n?.callbacks?.onSignOut,n?.callbacks?.getSession,n?.callbacks?.onSessionExpired,n?.callbacks?.handleEvent,n?.callbacks?.onWorkspaceChange]),h=n?.callbacks?.handleEvent;return u(()=>(Ps.setCallbacks(h?{handleEvent:h}:null),()=>{Ps.setCallbacks(null)}),[h]),a(Qa,{locale:i,children:a(Fa,{children:a(dr,{loadingComponent:l,children:a(vo,{callbacks:p,children:a(Ds,{children:a(xo,{config:m,auth:n,children:a(La,{getCheckoutStripeParams:c,children:a(pr,{appPermissions:o,children:a(ko,{children:a($t,{children:a(fr,{children:a(nr,{children:a(li,{children:a(Ao,{children:d})})})})})})})})})})})})})})});Eo.displayName="SaaSOSProviderInner";const Po=({children:e,...t})=>a(Ve,{children:a(Eo,{...t,children:e})});Po.displayName="SaaSOSProvider";const Io=e=>{const{children:a}=e,{status:t}=wo();return t!==Ze.authenticated?null:a},Uo=e=>{const{children:a}=e,{status:t}=wo();return t!==Ze.unauthenticated?null:a};Io.displayName="WhenAuthenticated",Uo.displayName="WhenUnauthenticated";const Ro=e=>{const{children:a,fallback:t,roles:r}=e,{user:s}=wo();return r.includes(s?.role??"")?a:t||null},Do=e=>{const{children:a,fallback:t,roles:r}=e,{user:s}=wo(),{currentWorkspace:n}=go(),i=n?.users.find(e=>e._id===s?.id);return i&&r.includes(i?.role??"")?a:t||null};Ro.displayName="WhenRoles",Do.displayName="WhenWorkspaceRoles";const Mo=e=>{const{children:a,fallback:t,permission:r}=e,{can:s}=en();return s(r)?a:t??null};function _o(){const e=d(So);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return e}function Wo(){const e=d(So);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:a=>Boolean(e.features[a])}}Mo.displayName="WhenPermission";const Fo=e=>{const{children:a,slug:t}=e,{currentWorkspace:r}=go(),s=r?.features?.[t];return s?a:null},Oo=e=>{const{children:a,slug:t}=e,{currentWorkspace:r}=go(),s=r?.features?.[t];return s?null:a},Lo=e=>{const{children:a,slug:t}=e,{isFeatureEnabled:r}=Wo();return r(t)?a:null},Bo=e=>{const{children:a,slug:t}=e,{isFeatureEnabled:r}=Wo();return r(t)?null:a};Fo.displayName="WhenWorkspaceFeatureEnabled",Oo.displayName="WhenWorkspaceFeatureDisabled",Lo.displayName="WhenUserFeatureEnabled",Bo.displayName="WhenUserFeatureDisabled";const Go=e=>{const{children:a,loadingComponent:t,fallbackComponent:r}=e,{response:s,loading:n}=Ht();return n?t??null:s?.subscription?a:r??null},Ko=e=>{const{children:a,loadingComponent:t,fallbackComponent:r}=e,{response:s,loading:n}=Ht();return n?t??null:s?.subscription?r??null:a},Vo=e=>{const{children:a,plans:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:i}=Ht();if(i)return r??null;if(!n?.subscription)return s??null;const o=n.plan??n.subscription?.plan;if(!o)return s??null;const c=t.map(e=>e.trim().toLowerCase()),l=(o.slug??"").toLowerCase();return c.includes(l)?a:s??null},jo=e=>{const{children:a,loadingComponent:t,fallbackComponent:r}=e,{response:s,loading:n}=Ht();return n?t??null:"trialing"!==s?.subscription?.subscriptionStatus?r??null:a},zo=e=>{const{children:a,loadingComponent:t,fallbackComponent:r}=e,{response:s,loading:n}=Ht();return n?t??null:s?.subscription?.subscriptionStatus===jr?r??null:a},$o=e=>{const{children:a,loadingComponent:t,fallbackComponent:r,daysThreshold:s=3}=e,{response:n,loading:i}=Ht();if(i)return t??null;const o=n?.subscription;if(!o||"trialing"!==o.subscriptionStatus)return r??null;const c=o.trialEnd||o.stripeCurrentPeriodEnd;if(!c)return r??null;const l=new Date(c);if(isNaN(l.getTime()))return r??null;return Math.max(0,Math.ceil((l.getTime()-Date.now())/864e5))>s?r??null:a};Go.displayName="WhenSubscription",Ko.displayName="WhenNoSubscription",Vo.displayName="WhenSubscriptionToPlans",jo.displayName="WhenTrialing",zo.displayName="WhenNotTrialing",$o.displayName="WhenTrialEnding";const Ho=e=>{const{slug:a,children:t,loadingComponent:r,fallbackComponent:s}=e,{quotas:n,loading:i}=br();if(i)return r??null;const o=n?.[a];return o?o.available<=0?s??null:t:s??null},Jo=e=>{const{slug:a,children:t,loadingComponent:r,fallbackComponent:s}=e,{quotas:n,loading:i}=br();if(i)return r??null;const o=n?.[a];return o?o.available>0?s??null:t:s??null},qo=e=>{const{slug:a,children:t,loadingComponent:r,fallbackComponent:s}=e,{quotas:n,loading:i}=br();if(i)return r??null;const o=n?.[a];return o&&o.hasOverage&&!1!==o.allowOverage?t:s??null},Yo=e=>{const{slug:a,threshold:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:i,loading:o}=br();if(o)return s??null;const c=i?.[a];if(!c)return n??null;return(c.included>0?c.consumed/c.included*100:c.consumed>0?100:0)<t?n??null:r};Ho.displayName="WhenQuotaAvailable",Jo.displayName="WhenQuotaExhausted",qo.displayName="WhenQuotaOverage",Yo.displayName="WhenQuotaThreshold";const Zo=({children:e})=>{const{currentWorkspace:a}=go(),t=a?._id,{balance:r,loading:s,error:n,refetch:i}=ir(),{packages:o,loading:c}=er(t),{consumeCredits:l,loading:d,error:u}=Qt(t),{purchaseCredits:m,loading:p,error:h}=Xt(t);return e({balance:r,loading:s,packages:o,packagesLoading:c,consume:l,consuming:d,purchase:async e=>{if(!t)throw new Error("No workspace selected");const{successUrl:a,cancelUrl:r}=Lr(t),s=await m({creditPackageId:e._id,successUrl:a,cancelUrl:r});s.url&&wr(s.url)},purchasing:p,refetch:i,error:u||h||n})};Zo.displayName="CreditActionsProvider";const Qo=({children:e})=>{const{balance:a,loading:t,error:r,refetch:s}=ir();return e({balance:a,loading:t,error:r,refetch:s})};function Xo({children:r,loadingFallback:s,errorFallback:n,redirectBaseUrl:i}){const{packages:o,notes:c,loading:l,error:d,refetch:u}=rr(),{isAuthenticated:p,signIn:h}=wo(),g=m(e=>{if(p)ho.openWorkspaceSettings(co.Credits,{action:Ur,packageId:e});else if(i){const a=Or({action:Ur,screen:"credits",packageId:e},i);h(a)}else h()},[p,h,i]);return l?void 0!==s?a(t,{children:s}):e("div",{className:"space-y-4",children:[a(cn,{className:"h-8 w-48"}),a("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(e=>a(cn,{className:"h-48 rounded-lg"},e))})]}):d?n?a(t,{children:n(d)}):a("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:d}):a(t,{children:r({loading:l,error:d,packages:o,notes:c,refetch:u,selectPackage:g})})}Qo.displayName="CreditBalance";const ec=e=>{const{min:a=1,children:t,loadingComponent:r,fallbackComponent:s}=e,{balance:n,loading:i}=ir();return i?r??null:n?n.available<a?s??null:t:s??null},ac=e=>{const{children:a,loadingComponent:t,fallbackComponent:r}=e,{balance:s,loading:n}=ir();return n?t??null:s?s.available>0?r??null:a:r??null},tc=e=>{const{threshold:a,children:t,loadingComponent:r,fallbackComponent:s}=e,{balance:n,loading:i}=ir();return i?r??null:n?n.available>a?s??null:t:s??null};function rc(e){if(!e)return null;const a=new Date(e);return isNaN(a.getTime())?null:a}function sc(){const{response:e}=Ht();return o(()=>{const a=e?.subscription;if(!a||"trialing"!==a.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const t=rc(a.trialEnd)??rc(a.stripeCurrentPeriodEnd),r=rc(a.trialStart),s=t?Math.max(0,Math.ceil((t.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:s,trialEndsAt:t,trialStartedAt:r,isTrialEnding:s<=3}},[e])}ec.displayName="WhenCreditsAvailable",ac.displayName="WhenCreditsExhausted",tc.displayName="WhenCreditsLow";class nc extends yt{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 ic=class{constructor(e){this.api=new nc(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const a=e?.context??{},t=a?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=a?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),s=a?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),n=a?.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:r,timezone:s,currency:n}})}};const oc=xe.object({name:xe.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:xe.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)")}),cc=({onSuccess:r,onError:s,className:n="w-full",fieldClassName:i="flex flex-col gap-1.5 w-full",autoFocus:o=!0,showSuccessMessage:c=!0,hideLogo:l=!1,hideTitles:d=!1})=>{const{t:h}=nt(),[g,f]=p(!1),[b,y]=p(!1),{submitBetaForm:w,isLoading:v,isSubmitting:x,error:N,config:S,success:k,message:C}=(()=>{const{t:e}=nt(),a=kt(),[t,r]=p(null),[s,n]=p(!0),[i,o]=p(!1),[c,l]=p(null),[d,h]=p(!1),[g,f]=p(null);return u(()=>{let t=!1;return(async()=>{n(!0),l(null);try{const e=new ic(a),s=await e.fetchConfig();t||r(s)}catch(a){t||l(a instanceof Error?a.message:e("beta.errorMessage"))}finally{t||n(!1)}})(),()=>{t=!0}},[a]),{isLoading:s,isSubmitting:i,config:t,error:c,success:d,message:g,submitBetaForm:m(async t=>{if(!a){const a=e("errors.generic");return l(a),{success:!1,message:a}}try{o(!0),l(null),h(!1),f(null);const e=new ic(a),r=await e.submitBetaUser({name:t.name||"",email:t.email}),s="success"===r.status;return h(s),f(r.message),{success:s,message:r.message}}catch(a){const t=a instanceof Error?a.message:e("beta.errorMessage");return l(t),h(!1),f(t),{success:!1,message:t}}finally{o(!1)}},[a])}})();u(()=>{k&&c&&(f(!0),y(!0)),N&&y(!0)},[k,c,N]);const A=we({resolver:Ln(oc),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});u(()=>{o&&A.setFocus("name")},[o,A]);const T=A.formState.isValid&&!x;return a("div",{className:"saas-os-ui",style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:e("div",v?{className:Ue("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",n),children:[a(cn,{className:"h-24 w-24 rounded-lg"}),a(cn,{className:"h-6 w-32"}),e("div",{className:"w-full space-y-4",children:[e("div",{className:"space-y-2",children:[a(cn,{className:"h-4 w-16"}),a(cn,{className:"h-10 w-full"})]}),e("div",{className:"space-y-2",children:[a(cn,{className:"h-4 w-16"}),a(cn,{className:"h-10 w-full"})]}),a(cn,{className:"h-10 w-full"})]})]}:{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:[!l&&e("div",{className:"flex flex-col items-center justify-center w-full",children:[S?.logo&&a(dc,{logo:S?.logo}),S?.name&&a("div",{children:S?.name})]}),a(be,{...A,children:e("form",{onSubmit:A.handleSubmit(async e=>{try{const a=await w(e);a.success?(r?.(),A.reset(),c&&f(!0),y(!0)):(s?.(a.message),y(!0))}catch(e){s?.(e instanceof Error?e.message:h("beta.errorMessage")),y(!0)}}),className:n,noValidate:!0,"aria-busy":x,children:[!b&&e(t,{children:[!d&&S?.screen?.register&&a(lc,{screen:S?.screen?.register}),a(jn,{control:A.control,name:"name",render:({field:t})=>e(Hn,{className:i,children:[a(Jn,{children:h("beta.nameLabel")}),a(qn,{children:a(Qn,{...t})}),a(Yn,{}),a(Zn,{})]})}),a(jn,{control:A.control,name:"email",render:({field:t})=>e(Hn,{className:i,children:[a(Jn,{children:h("beta.emailLabel")}),a(qn,{children:a(Qn,{...t})}),a(Yn,{}),a(Zn,{})]})}),a(Us,{type:"submit",disabled:!T,className:i,children:h(x?"beta.submittingText":"beta.submitText")})]}),b&&N&&e("div",{className:"flex flex-col items-center justify-center w-full",children:[e("div",{className:"border-red-300 text-red-700",role:"alert","aria-live":"assertive","aria-atomic":!0,children:[a("span",{className:"text-4xl mb-2",role:"img","aria-label":h("settings.common.error"),children:"❗"}),N]}),a("div",{className:"mt-4 flex justify-center",children:a(Us,{type:"button",onClick:()=>{y(!1),A.reset()},className:i,children:h("beta.tryAgain")})})]}),b&&g&&C&&a("div",{className:"flex flex-col items-center justify-center w-full text-green-700 border-green-300 text-center",children:S?.screen?.thankYou&&a(lc,{screen:S?.screen?.thankYou})})]})}),!b&&a("div",{children:e("div",{children:[h("beta.privacyConsent")," ",a("a",{href:S?.privacyPolicy,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-700",children:h("beta.privacyPolicy")})," ",h("beta.and")," ",a("a",{href:S?.termsOfService,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-700",children:h("beta.termsOfService")}),"."]})})]})})};function lc({screen:t}){return e("div",{className:"flex flex-col items-center justify-center w-full",children:[a("p",{className:"text-2xl font-bold",children:t?.title}),a("p",{className:"text-sm text-muted-foreground",children:t?.description})]})}function dc({logo:e}){return a("img","string"==typeof e?{src:e,alt:"Logo",className:"max-h-24"}:{src:e.bucket?.url,alt:"Logo",className:"max-h-24"})}function uc({slug:r,children:s,loadingFallback:n,errorFallback:i,redirectBaseUrl:o}){const{items:c,plans:l,notes:d,loading:u,error:p,refetch:h}=Et(r),{isAuthenticated:g,signIn:f}=wo(),b=m((e,a,t)=>o?Or({action:"selectPlan",plan:e,interval:a,currency:t},o):null,[o]),y=m((e,a,t)=>{if(g)return void ho.openWorkspaceSettings(co.Subscription,{action:"selectPlan",plan:e,interval:a,currency:t});const r=b(e,a,t);f(r??void 0)},[g,f,b]);return u?void 0!==n?a(t,{children:n}):e("div",{className:"space-y-4",children:[a(cn,{className:"h-8 w-48"}),a("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(e=>a(cn,{className:"h-64 rounded-lg"},e))})]}):p?i?a(t,{children:i(p)}):a("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:p}):a(t,{children:s({loading:u,error:p,items:c,plans:l,notes:d,refetch:h,selectPlan:y})})}const mc=r.forwardRef(({className:e,...t},r)=>a(Pe.Root,{ref:r,className:Ue("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));mc.displayName=Pe.Root.displayName;const pc=r.forwardRef(({className:e,...t},r)=>a(Pe.Image,{ref:r,className:Ue("aspect-square h-full w-full",e),...t}));pc.displayName=Pe.Image.displayName;const hc=r.forwardRef(({className:e,...t},r)=>a(Pe.Fallback,{ref:r,className:Ue("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));hc.displayName=Pe.Fallback.displayName;const gc=r.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...s},n)=>a(Ie.Root,{ref:n,decorative:r,orientation:t,className:Ue("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",e),...s}));function fc(r){const{t:s,dir:n}=nt(),{isAuthenticated:i,user:o}=wo(),c=ua(kt()),{workspaces:l,currentWorkspace:d,loading:m,refreshing:h,switchingToId:g,fetchWorkspaces:f,getFeatures:b,refreshWorkspaces:y,setCurrentWorkspace:v,switchToWorkspace:x}=go(),{settings:N}=At(),[S,k]=p(!1),[C,A]=p(0),[T,E]=p(""),P=m||h;u(()=>{i&&c&&(0===l.length?(f(),b()):b())},[i,c]),u(()=>{i&&c&&C>0&&y()},[C,i,c]);const I=l,U=I.filter(e=>e._id!==d?._id).filter(e=>e.name.toLowerCase().includes(T.toLowerCase())),R=N?.workspace?.canCreateWorkspace??!0,D=N?.workspace?.showSwitcher??!0,M=N?.workspace?.maxWorkspacesPerUser??0,_=I?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===o?.id?.toString()).length??0,W=!1!==R&&(0===M||_<M);return u(()=>{!D&&l.length>0&&!d&&x(l[0]).catch(e=>{Be(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[D,l,d]),!D&&d?e(t,{children:[a("div",{onClick:()=>k(!0),children:r.trigger?.(P,d)}),a(mo,{workspace:d,open:S,onOpenChange:k,showTrigger:!1})]}):e(Ms,{open:S,onOpenChange:k,children:[a(_s,{children:r.trigger?.(P,d)}),e(Os,{dir:n,className:"max-w-2xl min-w-full sm:min-w-[800px]",children:[e(Ls,{dir:n,children:[e(Bs,{className:"flex items-center gap-2",children:[a(Q,{className:"h-5 w-5"}),s("workspace.switchTitle")]}),a(Gs,{children:s("workspace.switchDescription")})]}),!o&&a("div",{className:"flex flex-col items-center justify-center h-full py-4 sm:py-8",children:a("div",{className:"text-sm font-medium text-muted-foreground",children:s("workspace.notLoggedIn")})}),o&&e("div",{dir:n,className:"flex flex-col gap-4",children:[d&&a(bc,{workspace:d,isCurrentWorkspace:!0,switchToWorkspace:x,switchingToId:g,onClose:()=>k(!1),setCurrentWorkspace:v,setOpen:k,workspacesToUse:I}),a(gc,{}),e("div",{children:[e("div",{className:"flex items-center justify-between",children:[a("div",{className:"text-sm font-medium text-muted-foreground",children:s("workspace.availableWorkspaces",{count:U.length})}),a("div",{children:a(Us,{progress:h,disabled:h,variant:"ghost",onClick:function(){i&&c&&A(e=>e+1)},startIcon:a(X,{}),children:s("settings.common.refreshAction",{loading:String(h)})})})]}),e("div",{className:"relative",children:[a(ee,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),a(Qn,{placeholder:s("workspace.searchPlaceholder"),value:T,onChange:e=>E(e.target.value),className:"ps-10"})]}),m?e("div",{className:"flex items-center justify-center py-8",children:[a(w,{className:"h-6 w-6 animate-spin text-muted-foreground"}),a("span",{className:"ms-2 text-sm text-muted-foreground",children:s("workspace.loadingWorkspaces")})]}):0===U.length?e("div",{className:"text-center py-8",children:[a(Q,{className:"mx-auto h-12 w-12 text-muted-foreground"}),a("p",{className:"mt-2 text-sm text-muted-foreground",children:s(T?"workspace.noWorkspacesFound":"workspace.noWorkspacesAvailable")})]}):a(ai,{className:"h-64",dir:n,children:a("div",{dir:n,className:"flex flex-col gap-2 my-2.5",children:U.map(e=>{const t=e._id===d?._id;return a(bc,{workspace:e,isCurrentWorkspace:t,switchToWorkspace:x,switchingToId:g,onClose:()=>k(!1),setCurrentWorkspace:v,setOpen:k,workspacesToUse:I},e._id)})})})]}),W&&e(t,{children:[a(gc,{}),a(yc,{onCreated:()=>{f()}})]})]})]})]})}function bc(t){const{t:r}=nt(),{workspace:s,setCurrentWorkspace:n,setOpen:i,workspacesToUse:o,switchingToId:c}=t,l=t.isCurrentWorkspace??!1,d=c===s._id,u=s.subscription??null,m=null!=u&&"object"==typeof u?u.plan??null:null,p=m?.name??"";return e("div",{className:Ue("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":l}),children:[e(mc,{className:"h-8 w-8 flex items-center justify-center",children:[a("div",{children:a(pc,{src:s.image&&s.image.trim()?s.image:void 0})}),a(hc,{children:(h=s.name,h.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2))})]}),e("div",{className:"flex-1 min-w-0 max-w-full",children:[a("div",{className:"flex items-center gap-2",children:a("span",{className:"font-medium line-clamp-1 text-ellipsis overflow-hidden max-w-full",children:s.name})}),e("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[a(ae,{className:"h-3 w-3"}),a("span",{children:r("workspace.membersCount",{count:s.users?.length||0})})]}),p&&a("div",{className:"max-w-fit",children:a("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:a("span",{className:"text-xs",children:p})})})]}),e("div",{className:"flex items-center gap-2",children:[l?null:a(Us,{size:"sm",disabled:null!==c||d,progress:d,onClick:()=>{t.switchToWorkspace(s).then(()=>i(!1)).catch(e=>{Be(e,{component:"WorkspaceItem",action:"switchToWorkspace",metadata:{workspaceId:s._id}})})},children:r("workspace.switchTo")}),a(mo,{workspace:s,onClose:()=>{if(l){const e=o.findIndex(e=>e._id?.toString()===s._id?.toString());-1!==e&&n(o[e])}}})]})]});var h}function yc(r){const{t:s,dir:n}=nt(),{switching:i}=go(),[o,c]=p(!1),[l,d]=p("emoji"),[u,m]=p("🏢"),[h,g]=p(!1),{createWorkspace:f}=go(),b=xe.object({name:xe.string().min(2,{message:s("workspace.workspaceNameMinLength")}),image:xe.string().optional()}),y=we({resolver:Ln(b),defaultValues:{name:"",image:""}});return e(Ms,{open:o,onOpenChange:c,children:[a(_s,{asChild:!0,children:e(Us,{className:"w-full rounded-none",disabled:i,children:[a(te,{className:"h-4 w-4 me-2"}),s("workspace.createNew")]})}),e(Os,{dir:n,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e(Ls,{children:[a(Bs,{children:s("workspace.createTitle")}),a(Gs,{children:s("workspace.createDescription")})]}),a(Kn,{...y,children:e("form",{onSubmit:y.handleSubmit(async function(e){let a="";if("emoji"===l)a=ri(u);else if("url"===l&&e.image)try{new URL(e.image),a=e.image}catch{return void y.setError("image",{message:s("workspace.invalidUrl")})}g(!0);try{await f(e.name,a),c(!1),y.reset(),m("🏢"),d("emoji"),r?.onCreated?.()}catch(a){Be(a,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{g(!1)}}),children:[a(jn,{control:y.control,name:"name",render:({field:t})=>e(Hn,{children:[a(Jn,{children:s("workspace.workspaceName")}),a(qn,{children:a(Qn,{placeholder:s("workspace.workspaceNamePlaceholder"),...t})}),a(Zn,{})]})}),e("div",{className:"flex flex-col gap-y-2 my-2",children:[e("div",{children:[a(Gn,{className:"text-sm font-medium",children:s("workspace.workspaceIcon")}),a(Yn,{children:s("workspace.iconDescription")})]}),e(Xn,{value:l,onValueChange:e=>d(e),className:"flex flex-col gap-y-2",children:[e("div",{className:"flex items-center gap-x-2 my-1",children:[a(ei,{value:"emoji",id:"emoji"}),e(Gn,{htmlFor:"emoji",className:"flex items-center gap-2",children:[a(A,{className:"h-4 w-4"}),s("workspace.chooseEmoji")]})]}),e("div",{className:"flex items-center gap-x-2 my-1",children:[a(ei,{value:"url",id:"url"}),e(Gn,{htmlFor:"url",className:"flex items-center gap-2",children:[a(re,{className:"h-4 w-4"}),s("workspace.customImageUrl")]})]})]}),"emoji"===l&&e("div",{className:"flex flex-col gap-y-2",children:[e("div",{className:"flex items-center gap-3",children:[a("span",{className:"text-sm font-medium",children:s("general.previewLabel")}),a("div",{className:"w-12 h-12 rounded-lg border-2 border-border flex items-center justify-center text-2xl bg-muted",children:u})]}),a(ai,{className:"h-32 w-full rounded-md border",children:a("div",{className:"p-4 grid grid-cols-8 gap-2",children:si.map((e,t)=>a("button",{type:"button",onClick:()=>(e=>{m(e),y.setValue("image",ri(e))})(e),className:"w-8 h-8 rounded flex items-center justify-center text-lg hover:bg-muted transition-colors "+(u===e?"bg-primary text-primary-foreground":""),children:e},t))})})]}),"url"===l&&e("div",{className:"flex flex-col gap-y-2",children:[a(jn,{control:y.control,name:"image",render:({field:t})=>e(Hn,{children:[a(Jn,{children:s("workspace.imageUrl")}),a(qn,{children:a(Qn,{placeholder:s("workspace.imageUrlPlaceholder"),...t})}),a(Yn,{children:s("workspace.imageUrlDescription")}),a(Zn,{})]})}),y.watch("image")&&y.watch("image")?.trim()&&e("div",{className:"flex items-center gap-3",children:[a("span",{className:"text-sm font-medium",children:s("general.previewLabel")}),a("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:a("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("div",{className:"flex justify-end gap-3 pt-4",children:[a(Us,{type:"button",variant:"outline",onClick:()=>{c(!1),y.reset(),m("🏢"),d("emoji")},disabled:h,children:s("settings.common.cancel")}),a(Us,{type:"submit",disabled:h,children:h?e(t,{children:[a(w,{className:"me-2 h-4 w-4 animate-spin"}),s("workspace.creating")]}):s("workspace.createWorkspace")})]})]})})]})]})}gc.displayName=Ie.Root.displayName;export{Fo as $,ec as A,Kr as B,Zo as C,Ms as D,ac as E,cr as F,tc as G,Ko as H,zo as I,Mo as J,Ho as K,Jo as L,qo as M,Yo as N,Ro as O,uc as P,fr as Q,Go as R,Xr as S,Vo as T,$o as U,jo as V,Bi as W,Uo as X,Bo as Y,Lo as Z,Oo as _,At as a,Do as a0,fc as a1,Vt as a2,Ft as a3,Lt as a4,Qt as a5,Dt as a6,Zt as a7,ir as a8,er as a9,jt as aA,_o as aB,Wo as aC,ho as aD,ar as aa,tr as ab,ur as ac,Ot as ad,Wt as ae,en as af,Ut as ag,Rt as ah,rr as ai,Pt as aj,Et as ak,Xt as al,di as am,br as an,Kt as ao,Gt as ap,Bt as aq,wo as ar,kt as as,go as at,to as au,It as av,Ht as aw,_t as ax,sc as ay,Mt as az,ps as b,Os as c,Bs as d,Gs as e,rn as f,gs as g,us as h,fs as i,bs as j,Us as k,hs as l,Oi as m,Li as n,cc as o,Qo as p,nr as q,Xo as r,li as s,lo as t,nt as u,qa as v,Po as w,co as x,$t as y,Io as z};
|