@cedros/login-react 0.0.8 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AuthenticationSettings-UOHce4G0.cjs → AuthenticationSettings-BxpBLsUX.cjs} +1 -1
- package/dist/{AuthenticationSettings-UOHce4G0.cjs.map → AuthenticationSettings-BxpBLsUX.cjs.map} +1 -1
- package/dist/{AuthenticationSettings-EaQzrn7-.js → AuthenticationSettings-eTN4qtHV.js} +1 -1
- package/dist/{AuthenticationSettings-EaQzrn7-.js.map → AuthenticationSettings-eTN4qtHV.js.map} +1 -1
- package/dist/{CreditSystemSettings-BClUVM4R.cjs → CreditSystemSettings-BuBKDfKL.cjs} +1 -1
- package/dist/{CreditSystemSettings-BClUVM4R.cjs.map → CreditSystemSettings-BuBKDfKL.cjs.map} +1 -1
- package/dist/{CreditSystemSettings-BcoLajmO.js → CreditSystemSettings-D7avf3PS.js} +1 -1
- package/dist/{CreditSystemSettings-BcoLajmO.js.map → CreditSystemSettings-D7avf3PS.js.map} +1 -1
- package/dist/{DepositsSection-DPr60Pty.cjs → DepositsSection-DEh9Oy0V.cjs} +1 -1
- package/dist/{DepositsSection-DPr60Pty.cjs.map → DepositsSection-DEh9Oy0V.cjs.map} +1 -1
- package/dist/{DepositsSection-C6DUs6iI.js → DepositsSection-Db4irTZb.js} +1 -1
- package/dist/{DepositsSection-C6DUs6iI.js.map → DepositsSection-Db4irTZb.js.map} +1 -1
- package/dist/{EmailSettings-BM7tGO1t.cjs → EmailSettings-CGocWYc0.cjs} +1 -1
- package/dist/{EmailSettings-BM7tGO1t.cjs.map → EmailSettings-CGocWYc0.cjs.map} +1 -1
- package/dist/{EmailSettings-DFVkODH_.js → EmailSettings-sN1OCw50.js} +1 -1
- package/dist/{EmailSettings-DFVkODH_.js.map → EmailSettings-sN1OCw50.js.map} +1 -1
- package/dist/{EmbeddedWalletSettings-DGJST5MD.cjs → EmbeddedWalletSettings-NZfbc5K8.cjs} +1 -1
- package/dist/{EmbeddedWalletSettings-DGJST5MD.cjs.map → EmbeddedWalletSettings-NZfbc5K8.cjs.map} +1 -1
- package/dist/{EmbeddedWalletSettings-BnHEtzpS.js → EmbeddedWalletSettings-qpRuCk4R.js} +1 -1
- package/dist/{EmbeddedWalletSettings-BnHEtzpS.js.map → EmbeddedWalletSettings-qpRuCk4R.js.map} +1 -1
- package/dist/{ServerSettings-B2YxkgLu.cjs → ServerSettings-Bkr_xuDx.cjs} +1 -1
- package/dist/{ServerSettings-B2YxkgLu.cjs.map → ServerSettings-Bkr_xuDx.cjs.map} +1 -1
- package/dist/{ServerSettings-jIwIl7mV.js → ServerSettings-CQn3-uuP.js} +1 -1
- package/dist/{ServerSettings-jIwIl7mV.js.map → ServerSettings-CQn3-uuP.js.map} +1 -1
- package/dist/{TeamSection-D_9-sbM5.js → TeamSection-DNozLdU4.js} +19 -19
- package/dist/TeamSection-DNozLdU4.js.map +1 -0
- package/dist/TeamSection-W9SC2Keh.cjs +1 -0
- package/dist/TeamSection-W9SC2Keh.cjs.map +1 -0
- package/dist/{UsersSection-nwTQCl2X.cjs → UsersSection-DDfHW_ao.cjs} +1 -1
- package/dist/{UsersSection-nwTQCl2X.cjs.map → UsersSection-DDfHW_ao.cjs.map} +1 -1
- package/dist/{UsersSection--yCs-uC9.js → UsersSection-DlfHGrJK.js} +1 -1
- package/dist/{UsersSection--yCs-uC9.js.map → UsersSection-DlfHGrJK.js.map} +1 -1
- package/dist/{WebhookSettings-CDLNe806.cjs → WebhookSettings-9dcnVNH_.cjs} +1 -1
- package/dist/{WebhookSettings-CDLNe806.cjs.map → WebhookSettings-9dcnVNH_.cjs.map} +1 -1
- package/dist/{WebhookSettings-C_3R0bqk.js → WebhookSettings-Cx30aHt_.js} +1 -1
- package/dist/{WebhookSettings-C_3R0bqk.js.map → WebhookSettings-Cx30aHt_.js.map} +1 -1
- package/dist/{WithdrawalsSection-wDptaqpp.cjs → WithdrawalsSection-MFj2muP6.cjs} +1 -1
- package/dist/{WithdrawalsSection-wDptaqpp.cjs.map → WithdrawalsSection-MFj2muP6.cjs.map} +1 -1
- package/dist/{WithdrawalsSection-5I0Ax4H0.js → WithdrawalsSection-ouu6VoQA.js} +1 -1
- package/dist/{WithdrawalsSection-5I0Ax4H0.js.map → WithdrawalsSection-ouu6VoQA.js.map} +1 -1
- package/dist/{index-RSdLR9t4.cjs → index-CCOKNxfU.cjs} +1 -1
- package/dist/{index-RSdLR9t4.cjs.map → index-CCOKNxfU.cjs.map} +1 -1
- package/dist/{index-BO6O-6S_.js → index-Djb8LQZ6.js} +1 -1
- package/dist/{index-BO6O-6S_.js.map → index-Djb8LQZ6.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/TeamSection-CnCzNEe9.cjs +0 -1
- package/dist/TeamSection-CnCzNEe9.cjs.map +0 -1
- package/dist/TeamSection-D_9-sbM5.js.map +0 -1
|
@@ -2046,7 +2046,7 @@ zebra
|
|
|
2046
2046
|
zero
|
|
2047
2047
|
zone
|
|
2048
2048
|
zoo`.split(`
|
|
2049
|
-
`),oe=12;function Fn(s){if(s.length!==16)throw new Error(`Invalid share length: expected 16, got ${s.length}`);const r=lr(s,me).split(" ");if(r.length!==oe)throw new Error(`Unexpected word count: expected ${oe}, got ${r.length}`);return r}function Bn(s){if(s.length!==oe)throw new Error(`Invalid word count: expected ${oe}, got ${s.length}`);const t=s.join(" ").toLowerCase().trim();if(!Hs(t,me))throw new Error("Invalid recovery phrase: checksum mismatch");const r=Vs(t,me);if(r.length!==16)throw new Error(`Invalid entropy length: expected 16, got ${r.length}`);return N.toShamirShare(r)}function On(s){if(s.length!==16)throw new Error(`Invalid seed length: expected 16, got ${s.length}`);const r=lr(s,me).split(" ");if(r.length!==oe)throw new Error(`Unexpected word count: expected ${oe}, got ${r.length}`);return r}function qn(s){if(s.length!==oe)throw new Error(`Invalid word count: expected ${oe}, got ${s.length}`);const t=s.join(" ").toLowerCase().trim();if(!Hs(t,me))throw new Error("Invalid recovery phrase: checksum mismatch");const r=Vs(t,me);if(r.length!==16)throw new Error(`Invalid entropy length: expected 16, got ${r.length}`);return N.toSeed(r)}function cr(s){if(s.length!==oe)return!1;const t=s.join(" ").toLowerCase().trim();return Hs(t,me)}function We(s){return me.includes(s.toLowerCase().trim())}function Wn(s,t=5){const r=s.toLowerCase().trim();return r.length===0?[]:me.filter(a=>a.startsWith(r)).slice(0,t)}function $n(s){const t=[];for(let r=0;r<s.length;r+=4)t.push(s.slice(r,r+4));return t}function zn(s){return s.toLowerCase().replace(/[,\n\r\t]+/g," ").split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function Vn({className:s="",variant:t="default",size:r="md",children:a,menuItems:n=[],hideSignOut:o=!1}){const{user:c,isAuthenticated:l,isLoading:d,openLoginModal:u,logout:g}=N.useAuth(),[m,h]=i.useState(!1),[b,f]=i.useState(-1),p=i.useRef(null),x=i.useRef(null),j=i.useMemo(()=>[...n,...o?[]:[{label:"Sign out",onClick:g}]],[n,o,g]);i.useEffect(()=>{if(!m)return;const w=P=>{p.current&&!p.current.contains(P.target)&&(h(!1),f(-1))},E=P=>{P.key==="Escape"&&(h(!1),f(-1),x.current?.focus())};return document.addEventListener("mousedown",w),document.addEventListener("keydown",E),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",E)}},[m]);const y=i.useCallback(w=>{if(!(!m||j.length===0))switch(w.key){case"ArrowDown":w.preventDefault(),f(E=>(E+1)%j.length);break;case"ArrowUp":w.preventDefault(),f(E=>(E-1+j.length)%j.length);break;case"Home":w.preventDefault(),f(0);break;case"End":w.preventDefault(),f(j.length-1);break;case"Enter":case" ":b>=0&&(w.preventDefault(),j[b].onClick(),h(!1),f(-1));break}},[m,b,j]),A=i.useCallback(()=>{j.length!==0&&(h(w=>!w),f(-1))},[j.length]),v={sm:"cedros-button-sm",md:"cedros-button-md",lg:"cedros-button-lg"},S={default:"cedros-button-primary",outline:"cedros-button-outline",ghost:"cedros-button-ghost"};if(d)return e.jsx("button",{type:"button",className:`cedros-button ${S[t]} ${v[r]} ${s}`,disabled:!0,children:e.jsx(N.LoadingSpinner,{size:"sm"})});if(l&&c){const w=c.name||c.email||"User",E=X.sanitizeImageUrl(c.picture);return e.jsxs("div",{className:"cedros-user-menu",ref:p,onKeyDown:y,children:[e.jsxs("button",{ref:x,type:"button",className:`cedros-button cedros-user-button ${v[r]} ${s}`,"aria-haspopup":"menu","aria-expanded":m,"aria-label":`User menu for ${w}`,onClick:A,children:[E?e.jsx("img",{src:E,alt:w,className:"cedros-user-avatar",referrerPolicy:"no-referrer",crossOrigin:"anonymous"}):e.jsx("div",{className:"cedros-user-avatar-placeholder",children:(w[0]||"?").toUpperCase()}),e.jsx("span",{className:"cedros-user-name",children:w})]}),m&&e.jsxs("div",{className:"cedros-dropdown cedros-dropdown-open",role:"menu",children:[n.map((P,L)=>e.jsxs("button",{type:"button",className:`cedros-dropdown-item ${b===L?"cedros-dropdown-item-focused":""}`,role:"menuitem",tabIndex:b===L?0:-1,onClick:()=>{P.onClick(),h(!1)},children:[P.icon&&e.jsx("span",{className:"cedros-dropdown-icon",children:P.icon}),P.label]},L)),n.length>0&&!o&&e.jsx("div",{className:"cedros-dropdown-divider",role:"separator"}),!o&&e.jsx("button",{type:"button",className:`cedros-dropdown-item cedros-dropdown-item-danger ${b===n.length?"cedros-dropdown-item-focused":""}`,role:"menuitem",tabIndex:b===n.length?0:-1,onClick:()=>{g(),h(!1)},children:"Sign out"})]})]})}return e.jsx("button",{type:"button",className:`cedros-button ${S[t]} ${v[r]} ${s}`,onClick:u,children:a||"Sign in"})}function Qs(){const{config:s}=N.useCedrosLogin(),[t,r]=i.useState(!1),[a,n]=i.useState(!1),[o,c]=i.useState(null),l=i.useMemo(()=>new N.ApiClient({baseUrl:s.serverUrl,timeoutMs:s.requestTimeout,retryAttempts:s.retryAttempts}),[s.serverUrl,s.requestTimeout,s.retryAttempts]),{checkLimit:d,getRemainingAttempts:u}=X.useRateLimiter({maxAttempts:3,windowMs:3e5}),g=i.useCallback(async f=>{if(!ts.validateEmail(f)){const p={code:"VALIDATION_ERROR",message:"Please enter a valid email address"};throw c(p),p}try{d()}catch(p){const x={code:"RATE_LIMITED",message:p instanceof Error?p.message:"Too many attempts"};throw c(x),x}r(!0),c(null),n(!1);try{await l.post("/forgot-password",{email:f}),n(!0)}catch(p){const x=N.handleApiError(p,"Failed to send reset email");throw c(x),x}finally{r(!1)}},[l,d]),m=i.useCallback(async(f,p)=>{r(!0),c(null),n(!1);try{await l.post("/reset-password",{token:f,newPassword:p}),n(!0)}catch(x){const j=N.handleApiError(x,"Failed to reset password");throw c(j),j}finally{r(!1)}},[l]),h=i.useCallback(()=>c(null),[]),b=i.useCallback(()=>{c(null),n(!1),r(!1)},[]);return{forgotPassword:g,resetPassword:m,isLoading:t,isSuccess:a,error:o,clearError:h,reset:b,remainingAttempts:u()}}function dr({onSuccess:s,onCancel:t,className:r=""}){const[a,n]=i.useState(""),{forgotPassword:o,isLoading:c,isSuccess:l,error:d,clearError:u}=Qs(),g=i.useId(),m=async h=>{h.preventDefault();try{await o(a),s?.()}catch{}};return l?e.jsxs("div",{className:`cedros-forgot-password-success ${r}`,children:[e.jsxs("svg",{className:"cedros-success-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"22",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M14 24l7 7 13-13",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),e.jsx("h3",{className:"cedros-success-title",children:"Check your email"}),e.jsxs("p",{className:"cedros-success-message",children:["If an account exists for ",e.jsx("strong",{children:a}),", you will receive a password reset link shortly."]}),t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-md cedros-button-outline",onClick:t,children:"Back to login"})]}):e.jsxs("form",{className:`cedros-forgot-password-form ${r}`,onSubmit:m,children:[e.jsxs("div",{className:"cedros-form-header",children:[e.jsx("h3",{className:"cedros-form-title",children:"Forgot password?"}),e.jsx("p",{className:"cedros-form-subtitle",children:"Enter your email address and we'll send you a link to reset your password."})]}),e.jsx(N.ErrorMessage,{error:d,onDismiss:u}),e.jsxs("div",{className:"cedros-form-field",children:[e.jsx("label",{htmlFor:g,className:"cedros-label",children:"Email address"}),e.jsx("input",{id:g,type:"email",className:"cedros-input",value:a,onChange:h=>n(h.target.value),placeholder:"you@example.com",required:!0,autoComplete:"email",disabled:c})]}),e.jsxs("div",{className:"cedros-form-actions",children:[e.jsx("button",{type:"submit",className:"cedros-button cedros-button-md cedros-button-primary cedros-button-full",disabled:c||!a,children:c?e.jsxs(e.Fragment,{children:[e.jsx(N.LoadingSpinner,{size:"sm"}),"Sending..."]}):"Send reset link"}),t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-md cedros-button-ghost cedros-button-full",onClick:t,disabled:c,children:"Back to login"})]})]})}const Hn={loading:!1,loaded:!1,error:null,callbacks:[],load(){return this.loaded?Promise.resolve():this.loading?new Promise((s,t)=>{this.callbacks.push({resolve:s,reject:t})}):(this.loading=!0,new Promise((s,t)=>{this.callbacks.push({resolve:s,reject:t});const r=document.getElementById("apple-signin-script");if(r){window.AppleID?(this.loaded=!0,this.loading=!1,this.callbacks.forEach(n=>n.resolve()),this.callbacks=[]):r.addEventListener("load",()=>{this.loaded=!0,this.loading=!1,this.callbacks.forEach(n=>n.resolve()),this.callbacks=[]});return}const a=document.createElement("script");a.src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js",a.async=!0,a.defer=!0,a.id="apple-signin-script",a.onload=()=>{this.loaded=!0,this.loading=!1,this.callbacks.forEach(n=>n.resolve()),this.callbacks=[]},a.onerror=()=>{this.loading=!1,a.remove();const n=new Error("Failed to load Apple Sign In script");this.callbacks.forEach(o=>o.reject(n)),this.callbacks=[]},document.head.appendChild(a)}))}};function ur(){const{config:s,_internal:t}=N.useCedrosLogin(),[r,a]=i.useState(!1),[n,o]=i.useState(!1),[c,l]=i.useState(null),d=i.useRef(s),u=i.useMemo(()=>new N.ApiClient({baseUrl:s.serverUrl,timeoutMs:s.requestTimeout,retryAttempts:s.retryAttempts}),[s.serverUrl,s.requestTimeout,s.retryAttempts]);i.useEffect(()=>{d.current=s},[s]),i.useEffect(()=>{if(!s.appleClientId)return;let h=!0;const b=()=>{if(h)try{window.AppleID?.auth?.init({clientId:s.appleClientId,scope:"name email",redirectURI:window.location.origin,usePopup:!0}),h&&o(!0)}catch{h&&l({code:"SERVER_ERROR",message:"Failed to initialize Apple Sign In"})}};return Hn.load().then(()=>{h&&b()}).catch(()=>{h&&l({code:"SERVER_ERROR",message:"Failed to load Apple Sign In"})}),()=>{h=!1}},[s.appleClientId]);const g=i.useCallback(async()=>{if(!s.appleClientId){const h={code:"VALIDATION_ERROR",message:"Apple Client ID not configured"};throw l(h),h}if(!n){const h={code:"VALIDATION_ERROR",message:"Apple Sign In not initialized"};throw l(h),h}a(!0),l(null);try{const h=await window.AppleID.auth.signIn(),b=h.authorization?.id_token;if(!b)throw new Error("No ID token received from Apple");const f=h.user?.name?`${h.user.name.firstName||""} ${h.user.name.lastName||""}`.trim():void 0,p=await u.post("/apple",{idToken:b,name:f||void 0});return d.current.callbacks?.onLoginSuccess?.(p.user,"apple"),t?.handleLoginSuccess(p.user,p.tokens),a(!1),p}catch(h){if(h.error==="popup_closed_by_user"){const p={code:"SERVER_ERROR",message:"Apple Sign In was cancelled"};throw l(p),a(!1),p}const f=N.handleApiError(h,"Apple sign-in failed");throw l(f),a(!1),f}},[s.appleClientId,n,u,t]),m=i.useCallback(()=>l(null),[]);return{signIn:g,isLoading:r,isInitialized:n,error:c,clearError:m}}function hr(){if(typeof window>"u"||typeof navigator>"u")return!1;const s=navigator.userAgent.toLowerCase(),t=(navigator.platform||"").toLowerCase();return!!(/iphone|ipad|ipod/.test(s)||t.includes("mac")||/macintosh/.test(s)||t==="macintel"&&navigator.maxTouchPoints>1)}function mr({onSuccess:s,onError:t,className:r="",variant:a="default",size:n="md",disabled:o=!1,hideOnNonApple:c=!0}){const{signIn:l,isLoading:d,isInitialized:u}=ur(),[g]=i.useState(()=>hr());if(c&&!g)return null;const m=async()=>{try{await l(),s?.()}catch(f){const p=f instanceof Error?f:new Error(String(f));t?.(p)}},h={sm:"cedros-button-sm",md:"cedros-button-md",lg:"cedros-button-lg"},b={default:"cedros-button-apple",outline:"cedros-button-apple-outline"};return e.jsxs("button",{type:"button",className:`cedros-button ${b[a]} ${h[n]} ${r}`,onClick:m,disabled:o||!u||d,"aria-label":"Sign in with Apple",children:[d?e.jsx(N.LoadingSpinner,{size:"sm"}):e.jsx("svg",{className:"cedros-button-icon",width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),e.jsx("span",{children:"Continue with Apple"})]})}function se(s,t){if(!s)throw new Error(t)}function Qn(s){return s.replace(/-/g,"+").replace(/_/g,"/")}function Ze(s){se(typeof s=="string"&&s.length>0,"Expected base64url string");const t=Qn(s),r=t+"=".repeat((4-t.length%4)%4),a=atob(r),n=new Uint8Array(a.length);for(let o=0;o<a.length;o++)n[o]=a.charCodeAt(o);return n.buffer}function je(s){const t=new Uint8Array(s);let r="";for(let n=0;n<t.length;n++)r+=String.fromCharCode(t[n]);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function pr(s){se(typeof s=="object"&&s!==null,"Invalid credential descriptor");const t=s;return se(typeof t.type=="string","Invalid credential descriptor type"),se(typeof t.id=="string","Invalid credential descriptor id"),{type:t.type,id:Ze(t.id),transports:Array.isArray(t.transports)?t.transports:void 0}}function Kn(s){se(s&&typeof s=="object","Missing creation options");const t=s.publicKey;se(t&&typeof t=="object","Missing creation options.publicKey"),se(typeof t.challenge=="string","Missing creation challenge"),se(typeof t.rp=="object"&&t.rp!==null,"Missing rp"),se(typeof t.user=="object"&&t.user!==null,"Missing user");const r=t.rp,a=t.user;se(typeof r.name=="string","Missing rp.name"),se(typeof a.id=="string","Missing user.id"),se(typeof a.name=="string","Missing user.name"),se(typeof a.displayName=="string","Missing user.displayName");const n=Array.isArray(t.excludeCredentials)?t.excludeCredentials.map(pr):void 0,o=Array.isArray(t.pubKeyCredParams)?t.pubKeyCredParams.map(c=>({type:c.type,alg:c.alg})):[];return{challenge:Ze(t.challenge),rp:{name:r.name,id:typeof r.id=="string"?r.id:void 0},user:{id:Ze(a.id),name:a.name,displayName:a.displayName},pubKeyCredParams:o,timeout:typeof t.timeout=="number"?t.timeout:void 0,attestation:typeof t.attestation=="string"?t.attestation:void 0,authenticatorSelection:typeof t.authenticatorSelection=="object"&&t.authenticatorSelection!==null?t.authenticatorSelection:void 0,excludeCredentials:n,extensions:typeof t.extensions=="object"&&t.extensions!==null?t.extensions:void 0}}function Gn(s){se(s&&typeof s=="object","Missing request options");const t=s.publicKey;se(t&&typeof t=="object","Missing request options.publicKey"),se(typeof t.challenge=="string","Missing request challenge");const r=Array.isArray(t.allowCredentials)?t.allowCredentials.map(pr):void 0;return{challenge:Ze(t.challenge),rpId:typeof t.rpId=="string"?t.rpId:void 0,timeout:typeof t.timeout=="number"?t.timeout:void 0,userVerification:typeof t.userVerification=="string"?t.userVerification:void 0,allowCredentials:r,extensions:typeof t.extensions=="object"&&t.extensions!==null?t.extensions:void 0}}function ct(s){const t=je(s.rawId),r=s.response,n={...{clientDataJSON:je(r.clientDataJSON)}};if("attestationObject"in r){const o=r;if(n.attestationObject=je(o.attestationObject),typeof o.getTransports=="function")try{n.transports=o.getTransports()}catch{}}if("authenticatorData"in r){const o=r;n.authenticatorData=je(o.authenticatorData),n.signature=je(o.signature),o.userHandle&&(n.userHandle=je(o.userHandle))}return{id:s.id,rawId:t,type:s.type,authenticatorAttachment:s.authenticatorAttachment??void 0,clientExtensionResults:s.getClientExtensionResults?.()??{},response:n}}function Yn(){if(typeof window<"u"){const s=window.location?.hostname,t=s==="localhost"||s==="127.0.0.1"||s?.endsWith(".localhost");if(!(window.isSecureContext===!0)&&!t)return!1}return typeof window<"u"&&typeof window.PublicKeyCredential<"u"&&typeof navigator<"u"&&typeof navigator.credentials<"u"}function dt(s){if(!(s instanceof Error))return null;const t=s.name;return t==="NotAllowedError"?{code:"SERVER_ERROR",message:"Passkey operation was cancelled or timed out"}:t==="InvalidStateError"?{code:"VALIDATION_ERROR",message:"Passkey is not available for this operation"}:t==="SecurityError"?{code:"VALIDATION_ERROR",message:"Passkeys require HTTPS and a correctly configured relying party (WEBAUTHN_RP_ID / WEBAUTHN_RP_ORIGIN)"}:null}function fr(){const{config:s,_internal:t}=N.useCedrosLogin(),[r,a]=i.useState(!1),[n,o]=i.useState(null),c=i.useMemo(()=>new N.ApiClient({baseUrl:s.serverUrl,timeoutMs:s.requestTimeout,retryAttempts:s.retryAttempts,getAccessToken:t?.getAccessToken}),[t?.getAccessToken,s.serverUrl,s.requestTimeout,s.retryAttempts]),l=i.useCallback(()=>o(null),[]),d=Yn(),u=i.useCallback(async m=>{if(!d){const h={code:"VALIDATION_ERROR",message:"Passkeys are not supported in this browser"};throw o(h),h}a(!0),o(null);try{const h=await c.post("/webauthn/auth/options",{email:m?.email}),b=Gn(h.options),f=await navigator.credentials.get({publicKey:b});if(!f)throw new Error("Passkey authentication returned no credential");const p=await c.post("/webauthn/auth/verify",{challengeId:h.challengeId,credential:ct(f)});return s.callbacks?.onLoginSuccess?.(p.user,"webauthn"),t?.handleLoginSuccess(p.user,p.tokens),p}catch(h){const f=dt(h)??N.handleApiError(h,"Passkey sign-in failed");throw o(f),f}finally{a(!1)}},[c,s.callbacks,t,d]),g=i.useCallback(async m=>{if(!d){const h={code:"VALIDATION_ERROR",message:"Passkeys are not supported in this browser"};throw o(h),h}a(!0),o(null);try{const h=await c.post("/webauthn/register/options",{}),b=Kn(h.options),f=await navigator.credentials.create({publicKey:b});if(!f)throw new Error("Passkey registration returned no credential");const p=await c.post("/webauthn/register/verify",{challengeId:h.challengeId,credential:ct(f),label:m?.label});if(!p.success)throw new Error("Passkey registration failed");return{credentialId:p.credentialId,label:p.label}}catch(h){const f=dt(h)??N.handleApiError(h,"Passkey registration failed");throw o(f),f}finally{a(!1)}},[c,d]);return{isSupported:d,isLoading:r,error:n,clearError:l,authenticatePasskey:u,registerPasskey:g}}function gr({onSuccess:s,className:t="",children:r,disabled:a}){const{authenticatePasskey:n,isLoading:o,isSupported:c}=fr(),l=a||!c||o;return e.jsxs("button",{type:"button",className:`cedros-button cedros-button-social ${t}`,onClick:async()=>{await n(),s?.()},disabled:l,"aria-disabled":l,children:[e.jsx("span",{className:"cedros-social-icon","aria-hidden":"true",children:e.jsx(Jn,{})}),e.jsx("span",{children:r??(o?"Continuing...":"Continue with Passkey")})]})}function Jn(){return e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4"}),e.jsx("path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88"}),e.jsx("path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02"}),e.jsx("path",{d:"M2 12a10 10 0 0 1 18-6"}),e.jsx("path",{d:"M2 16h.01"}),e.jsx("path",{d:"M21.8 16c.2-2 .131-5.354 0-6"}),e.jsx("path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2"}),e.jsx("path",{d:"M8.65 22c.21-.66.45-1.32.57-2"}),e.jsx("path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2"})]})}const Me=["login","register"];function rs({onSuccess:s,className:t="",defaultTab:r="login"}){const{config:a}=N.useCedrosLogin(),[n,o]=i.useState(r),[c,l]=i.useState("form"),[d,u]=i.useState(()=>ps.detectSolanaWallets()),[g]=i.useState(()=>hr());i.useEffect(()=>{const v=()=>u(ps.detectSolanaWallets());return v(),window.addEventListener("load",v),window.addEventListener("focus",v),()=>{window.removeEventListener("load",v),window.removeEventListener("focus",v)}},[]);const m=a.forms?.forgotPassword?.mode??"reset",h=i.useCallback(v=>{const S=Me.indexOf(n);let w=S;switch(v.key){case"ArrowLeft":case"ArrowUp":w=S===0?Me.length-1:S-1;break;case"ArrowRight":case"ArrowDown":w=S===Me.length-1?0:S+1;break;case"Home":w=0;break;case"End":w=Me.length-1;break;default:return}v.preventDefault();const E=Me[w];o(E),document.getElementById(`cedros-tab-${E}`)?.focus()},[n]),b=a.features??{email:!0,google:!0,apple:!0,solana:!0,webauthn:!0},f=b.email!==!1,p=b.google!==!1&&a.googleClientId,x=b.apple!==!1&&a.appleClientId&&g,j=b.solana!==!1&&d,y=b.webauthn!==!1,A=f&&(p||x||j||y);return c==="forgotPassword"?e.jsx("div",{className:`cedros-login-form ${t}`,children:e.jsx(dr,{onCancel:()=>l("form")})}):e.jsxs("div",{className:`cedros-login-form ${t}`,children:[(y||p||x||j)&&e.jsxs("div",{className:"cedros-social-buttons",children:[y&&e.jsx(gr,{onSuccess:s}),p&&e.jsx(Nn.GoogleLoginButton,{onSuccess:s}),x&&e.jsx(mr,{onSuccess:s}),j&&e.jsx(ps.SolanaLoginButton,{onSuccess:s})]}),A&&e.jsx("div",{className:"cedros-divider",children:e.jsx("span",{children:"Or continue with"})}),f&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-tabs",role:"tablist","aria-label":"Authentication method",children:[e.jsx("button",{type:"button",role:"tab",id:"cedros-tab-login",className:`cedros-tab ${n==="login"?"cedros-tab-active":""}`,onClick:()=>o("login"),onKeyDown:h,"aria-selected":n==="login","aria-controls":"cedros-tabpanel-login",tabIndex:n==="login"?0:-1,children:"Sign in"}),e.jsx("button",{type:"button",role:"tab",id:"cedros-tab-register",className:`cedros-tab ${n==="register"?"cedros-tab-active":""}`,onClick:()=>o("register"),onKeyDown:h,"aria-selected":n==="register","aria-controls":"cedros-tabpanel-register",tabIndex:n==="register"?0:-1,children:"Sign up"})]}),e.jsx("div",{role:"tabpanel",id:`cedros-tabpanel-${n}`,"aria-labelledby":`cedros-tab-${n}`,children:n==="login"?e.jsx(X.EmailLoginForm,{onSuccess:s,onSwitchToRegister:()=>o("register"),onForgotPassword:m==="reset"?()=>l("forgotPassword"):void 0}):e.jsx(X.EmailRegisterForm,{onSuccess:s,onSwitchToLogin:()=>o("login")})})]})]})}class br extends i.Component{constructor(t){super(t),this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){this.setState({errorInfo:r}),process.env.NODE_ENV==="development"&&(console.error("[Cedros Login] Error caught by ErrorBoundary:",t),console.error("[Cedros Login] Component stack:",r.componentStack)),this.props.onError?.(t,r)}handleRetry=()=>{this.setState({hasError:!1,error:null,errorInfo:null})};render(){const{hasError:t,error:r,errorInfo:a}=this.state,{children:n,fallback:o,showDetails:c=!1}=this.props;return t?o||e.jsx("div",{className:"cedros-error-boundary",role:"alert","aria-live":"assertive",children:e.jsxs("div",{className:"cedros-error-boundary-content",children:[e.jsxs("svg",{className:"cedros-error-boundary-icon",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),e.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),e.jsx("h2",{className:"cedros-error-boundary-title",children:"Something went wrong"}),e.jsx("p",{className:"cedros-error-boundary-message",children:"We encountered an unexpected error. Please try again."}),c&&r&&e.jsxs("details",{className:"cedros-error-boundary-details",children:[e.jsx("summary",{children:"Error details"}),e.jsxs("pre",{children:[r.toString(),a?.componentStack]})]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:this.handleRetry,children:"Try again"})]})}):n}}function Xn({className:s="",title:t="Sign in to your account"}){const{isModalOpen:r,closeModal:a}=N.useCedrosLogin(),n=i.useRef(null),o=i.useRef(null),c=i.useRef(a);if(i.useEffect(()=>{c.current=a},[a]),i.useEffect(()=>{if(!r)return;o.current=document.activeElement,n.current?.focus();const d=g=>{if(g.key==="Escape"&&c.current(),g.key==="Tab"&&n.current){const m=n.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),h=m[0],b=m[m.length-1];g.shiftKey&&document.activeElement===h?(g.preventDefault(),b?.focus()):!g.shiftKey&&document.activeElement===b&&(g.preventDefault(),h?.focus())}};document.addEventListener("keydown",d);const u=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",d),document.body.style.overflow=u,o.current instanceof HTMLElement&&o.current.focus()}},[r]),!r)return null;const l=d=>{d.target===d.currentTarget&&a()};return e.jsx("div",{className:`cedros-modal-backdrop ${s}`,onClick:l,role:"presentation",children:e.jsxs("div",{ref:n,className:"cedros-modal",role:"dialog","aria-modal":"true","aria-labelledby":"cedros-modal-title",tabIndex:-1,children:[e.jsxs("div",{className:"cedros-modal-header",children:[e.jsx("h2",{id:"cedros-modal-title",className:"cedros-modal-title",children:t}),e.jsx("button",{type:"button",className:"cedros-modal-close",onClick:a,"aria-label":"Close",children:e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:e.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),e.jsx("div",{className:"cedros-modal-content",children:e.jsx(br,{children:e.jsx(rs,{onSuccess:a})})})]})})}function Zn({token:s,onSuccess:t,onLoginClick:r,className:a=""}){const[n,o]=i.useState(""),[c,l]=i.useState(""),[d,u]=i.useState(null),{resetPassword:g,isLoading:m,isSuccess:h,error:b,clearError:f}=Qs(),p=n===c,x=d?.isValid&&p&&n.length>0,j=async y=>{if(y.preventDefault(),!!x)try{await g(s,n),t?.()}catch{}};return h?e.jsxs("div",{className:`cedros-reset-password-success ${a}`,children:[e.jsxs("svg",{className:"cedros-success-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"22",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M14 24l7 7 13-13",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),e.jsx("h3",{className:"cedros-success-title",children:"Password reset successful"}),e.jsx("p",{className:"cedros-success-message",children:"Your password has been reset. You can now log in with your new password."}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-md cedros-button-primary",onClick:r,children:"Go to login"})]}):e.jsxs("form",{className:`cedros-reset-password-form ${a}`,onSubmit:j,children:[e.jsxs("div",{className:"cedros-form-header",children:[e.jsx("h3",{className:"cedros-form-title",children:"Reset your password"}),e.jsx("p",{className:"cedros-form-subtitle",children:"Enter your new password below."})]}),e.jsx(N.ErrorMessage,{error:b,onDismiss:f}),e.jsx("div",{className:"cedros-form-field",children:e.jsx(X.PasswordInput,{label:"New password",value:n,onChange:y=>{o(y.target.value),u(ts.validatePassword(y.target.value))},showStrengthMeter:!0,onValidationChange:u,disabled:m,autoComplete:"new-password",error:d&&!d.isValid?Object.values(d.errors).find(Boolean):void 0})}),e.jsx("div",{className:"cedros-form-field",children:e.jsx(X.PasswordInput,{label:"Confirm password",value:c,onChange:y=>l(y.target.value),disabled:m,autoComplete:"new-password",error:c&&!p?"Passwords do not match":void 0})}),e.jsxs("div",{className:"cedros-form-actions",children:[e.jsx("button",{type:"submit",className:"cedros-button cedros-button-md cedros-button-primary cedros-button-full",disabled:m||!x,children:m?e.jsxs(e.Fragment,{children:[e.jsx(N.LoadingSpinner,{size:"sm"}),"Resetting..."]}):"Reset password"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-md cedros-button-ghost cedros-button-full",onClick:r,disabled:m,children:"Back to login"})]})]})}function zs({org:s,size:t="lg",className:r=""}){const a=X.sanitizeImageUrl(s.logoUrl),n=t==="lg"?"cedros-org-avatar-lg":"",o=["cedros-org-avatar",n,r].filter(Boolean).join(" "),c=["cedros-org-avatar-placeholder",n,r].filter(Boolean).join(" ");return a?e.jsx("img",{src:a,alt:s.name,className:o,referrerPolicy:"no-referrer"}):e.jsx("div",{className:c,children:s.name[0]?.toUpperCase()||"?"})}function ea({orgs:s,activeOrg:t,isLoading:r=!1,onSelect:a,onCreateClick:n,className:o="",placeholder:c="Select organization"}){const[l,d]=i.useState(!1),u=i.useRef(null);i.useEffect(()=>{const b=f=>{u.current&&!u.current.contains(f.target)&&d(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]),i.useEffect(()=>{const b=f=>{f.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[l]);const g=i.useCallback(b=>{a(b),d(!1)},[a]),m=i.useCallback(()=>{d(!1),n?.()},[n]),h=i.useCallback(()=>{d(b=>!b)},[]);return r?e.jsxs("div",{className:`cedros-org-selector cedros-org-selector-loading ${o}`,"aria-busy":"true","aria-live":"polite",children:[e.jsx(N.LoadingSpinner,{size:"sm"}),e.jsx("span",{children:"Loading..."})]}):e.jsxs("div",{ref:u,className:`cedros-org-selector ${o}`,children:[e.jsxs("button",{type:"button",className:"cedros-org-selector-trigger",onClick:h,"aria-haspopup":"listbox","aria-expanded":l,children:[t?e.jsxs(e.Fragment,{children:[e.jsx(zs,{org:t,size:"sm"}),e.jsx("span",{className:"cedros-org-selector-name",children:t.name}),e.jsx(ut,{role:t.membership.role})]}):e.jsx("span",{className:"cedros-org-selector-placeholder",children:c}),e.jsx(sa,{isOpen:l})]}),l&&e.jsxs("div",{className:"cedros-org-selector-dropdown",role:"listbox",children:[s.length===0?e.jsx("div",{className:"cedros-org-selector-empty",children:"No organizations"}):e.jsx("ul",{className:"cedros-org-selector-list",children:s.map(b=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:`cedros-org-selector-item ${b.id===t?.id?"cedros-org-selector-item-active":""}`,onClick:()=>g(b.id),role:"option","aria-selected":b.id===t?.id,children:[e.jsx(zs,{org:b,size:"sm"}),e.jsx("span",{className:"cedros-org-selector-item-name",children:b.name}),e.jsx(ut,{role:b.membership.role}),b.id===t?.id&&e.jsx(ta,{})]})},b.id))}),n&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cedros-org-selector-divider"}),e.jsxs("button",{type:"button",className:"cedros-org-selector-create",onClick:m,children:[e.jsx(ra,{}),e.jsx("span",{children:"Create organization"})]})]})]})]})}function ut({role:s}){return e.jsx("span",{className:`cedros-org-role cedros-org-role-${s}`,children:s})}function sa({isOpen:s}){return e.jsx("svg",{className:`cedros-org-chevron ${s?"cedros-org-chevron-open":""}`,width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function ta(){return e.jsx("svg",{className:"cedros-org-check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M3 8L6 11L13 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function ra(){return e.jsx("svg",{className:"cedros-org-plus",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M8 3V13M3 8H13",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function na(){return e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M5 5L15 15M15 5L5 15",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function aa(){return e.jsx("svg",{className:"cedros-org-check",width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M4 10L8 14L16 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function oa(){return e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M10 4V16M4 10H16",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function ia({orgs:s,activeOrg:t,isLoading:r,onSelect:a,onCreateClick:n}){return r?e.jsxs("div",{className:"cedros-org-switcher-loading",children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading organizations..."})]}):e.jsxs(e.Fragment,{children:[s.length===0?e.jsx("div",{className:"cedros-org-switcher-empty",children:e.jsx("p",{children:"You don't belong to any organizations yet."})}):e.jsx("ul",{className:"cedros-org-switcher-list",children:s.map(o=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:`cedros-org-switcher-item ${o.id===t?.id?"cedros-org-switcher-item-active":""}`,onClick:()=>a(o.id),children:[e.jsx(zs,{org:o}),e.jsxs("div",{className:"cedros-org-switcher-item-content",children:[e.jsx("span",{className:"cedros-org-switcher-item-name",children:o.name}),e.jsxs("span",{className:"cedros-org-switcher-item-slug",children:["@",o.slug]})]}),e.jsxs("div",{className:"cedros-org-switcher-item-meta",children:[e.jsx("span",{className:`cedros-org-role cedros-org-role-${o.membership.role}`,children:o.membership.role}),o.isPersonal&&e.jsx("span",{className:"cedros-org-personal-badge",children:"Personal"})]}),o.id===t?.id&&e.jsx(aa,{})]})},o.id))}),n&&e.jsxs("button",{type:"button",className:"cedros-org-switcher-create",onClick:n,children:[e.jsx(oa,{}),e.jsx("span",{children:"Create new organization"})]})]})}function la({isLoading:s,onSubmit:t,onCancel:r}){const[a,n]=i.useState(""),[o,c]=i.useState(""),[l,d]=i.useState(null),u=i.useCallback(m=>{n(m);const h=m.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").substring(0,50);c(h)},[]),g=i.useCallback(async m=>{if(m.preventDefault(),d(null),!a.trim()){d("Organization name is required");return}if(!o.trim()){d("Organization slug is required");return}try{await t({name:a.trim(),slug:o.trim()})}catch(h){d(h.message||"Failed to create organization")}},[a,o,t]);return e.jsxs("form",{className:"cedros-org-create-form",onSubmit:g,children:[l&&e.jsx(N.ErrorMessage,{error:l}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{htmlFor:"org-name",className:"cedros-form-label",children:"Organization Name"}),e.jsx("input",{id:"org-name",type:"text",className:"cedros-form-input",value:a,onChange:m=>u(m.target.value),placeholder:"My Organization",maxLength:255,disabled:s,autoFocus:!0})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{htmlFor:"org-slug",className:"cedros-form-label",children:"URL Slug"}),e.jsxs("div",{className:"cedros-form-input-prefix",children:[e.jsx("span",{className:"cedros-form-prefix",children:"@"}),e.jsx("input",{id:"org-slug",type:"text",className:"cedros-form-input",value:o,onChange:m=>c(m.target.value.toLowerCase()),placeholder:"my-organization",maxLength:100,pattern:"[a-z0-9-]+",disabled:s})]}),e.jsx("span",{className:"cedros-form-hint",children:"Only lowercase letters, numbers, and hyphens"})]}),e.jsxs("div",{className:"cedros-form-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:r,disabled:s,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:s||!a.trim()||!o.trim(),children:s?e.jsx(N.LoadingSpinner,{size:"sm"}):"Create Organization"})]})]})}function ca({isOpen:s,onClose:t,orgs:r,activeOrg:a,isLoading:n=!1,error:o,onSelect:c,onCreate:l,className:d=""}){return s?e.jsx(da,{onClose:t,orgs:r,activeOrg:a,isLoading:n,error:o,onSelect:c,onCreate:l,className:d}):null}function da({onClose:s,orgs:t,activeOrg:r,isLoading:a=!1,error:n,onSelect:o,onCreate:c,className:l}){const[d,u]=i.useState("list"),g=i.useRef(null),m=i.useRef(null);i.useEffect(()=>(m.current=document.activeElement,g.current?.querySelector(".cedros-modal-close")?.focus(),()=>{m.current?.focus()}),[]),i.useEffect(()=>{const p=x=>{if(x.key==="Escape"){s();return}if(x.key==="Tab"&&g.current){const j=g.current.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'),y=j[0],A=j[j.length-1];x.shiftKey?document.activeElement===y&&(x.preventDefault(),A?.focus()):document.activeElement===A&&(x.preventDefault(),y?.focus())}};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[s]);const h=i.useCallback(p=>{p.target===p.currentTarget&&s()},[s]),b=i.useCallback(p=>{o(p),s()},[o,s]),f=i.useCallback(async p=>{await c?.(p),s()},[c,s]);return e.jsx("div",{className:"cedros-modal-backdrop",onClick:h,children:e.jsxs("div",{ref:g,className:`cedros-modal cedros-org-switcher ${l}`,role:"dialog","aria-modal":"true","aria-labelledby":"org-switcher-title",children:[e.jsxs("div",{className:"cedros-modal-header",children:[e.jsx("h2",{id:"org-switcher-title",className:"cedros-modal-title",children:d==="list"?"Switch Organization":"Create Organization"}),e.jsx("button",{type:"button",className:"cedros-modal-close",onClick:s,"aria-label":"Close",children:e.jsx(na,{})})]}),e.jsxs("div",{className:"cedros-modal-body",children:[n&&e.jsx(N.ErrorMessage,{error:n}),d==="list"?e.jsx(ia,{orgs:t,activeOrg:r,isLoading:a,onSelect:b,onCreateClick:c?()=>u("create"):void 0}):e.jsx(la,{isLoading:a,onSubmit:f,onCancel:()=>u("list")})]})]})})}const ua=["owner","admin","member"];function yr({members:s,currentUserId:t,isLoading:r=!1,error:a,canManage:n=!1,canChangeRoles:o=!1,onUpdateRole:c,onRemove:l,className:d=""}){const[u,g]=i.useState("name"),[m,h]=i.useState("asc"),b=p=>{u===p?h(m==="asc"?"desc":"asc"):(g(p),h("asc"))},f=i.useMemo(()=>{const p={owner:0,admin:1,member:2};return[...s].sort((x,j)=>{let y,A;switch(u){case"name":y=(x.user.name||x.user.email||"").toLowerCase(),A=(j.user.name||j.user.email||"").toLowerCase();break;case"role":y=p[x.role]??99,A=p[j.role]??99;break;case"joinedAt":y=new Date(x.joinedAt).getTime(),A=new Date(j.joinedAt).getTime();break;default:return 0}return y<A?m==="asc"?-1:1:y>A?m==="asc"?1:-1:0})},[s,u,m]);return r&&s.length===0?e.jsxs("div",{className:`cedros-member-list cedros-member-list-loading ${d}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading members..."})]}):a?e.jsx("div",{className:`cedros-member-list ${d}`,children:e.jsx(N.ErrorMessage,{error:a})}):s.length===0?e.jsx("div",{className:`cedros-member-list cedros-member-list-empty ${d}`,children:e.jsx("p",{children:"No members found."})}):e.jsx("div",{className:`cedros-member-list ${d}`,children:e.jsxs("table",{className:"cedros-member-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${u==="name"?"cedros-admin-sort-active":""}`,onClick:()=>b("name"),children:["Member"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:u==="name"?m==="asc"?"↑":"↓":"↕"})]})}),e.jsx("th",{children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${u==="role"?"cedros-admin-sort-active":""}`,onClick:()=>b("role"),children:["Role"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:u==="role"?m==="asc"?"↑":"↓":"↕"})]})}),e.jsx("th",{children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${u==="joinedAt"?"cedros-admin-sort-active":""}`,onClick:()=>b("joinedAt"),children:["Joined"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:u==="joinedAt"?m==="asc"?"↑":"↓":"↕"})]})}),(n||o)&&e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:f.map(p=>e.jsx(ha,{member:p,isCurrentUser:p.userId===t,canManage:n,canChangeRoles:o,onUpdateRole:c,onRemove:l},p.id))})]})})}function ha({member:s,isCurrentUser:t,canManage:r,canChangeRoles:a,onUpdateRole:n,onRemove:o}){const[c,l]=i.useState(!1),[d,u]=i.useState(s.role),g=i.useCallback(async f=>{if(!(!n||f===s.role)){l(!0);try{await n(s.userId,f),u(f)}catch{u(s.role)}finally{l(!1)}}},[s.userId,s.role,n]),m=i.useCallback(async()=>{if(!(!o||!window.confirm(`Are you sure you want to remove ${s.user.name||s.user.email} from this organization?`))){l(!0);try{await o(s.userId)}finally{l(!1)}}},[s.userId,s.user.name,s.user.email,o]),h=s.role==="owner",b=!t&&!h;return e.jsxs("tr",{className:`cedros-member-row ${t?"cedros-member-row-current":""}`,children:[e.jsxs("td",{className:"cedros-member-info",children:[e.jsx(ma,{user:s.user}),e.jsxs("div",{className:"cedros-member-details",children:[e.jsxs("span",{className:"cedros-member-name",children:[s.user.name||"Unknown",t&&e.jsx("span",{className:"cedros-member-you",children:"(you)"})]}),e.jsx("span",{className:"cedros-member-email",children:s.user.email})]})]}),e.jsx("td",{className:"cedros-member-role",children:a&&b&&n?e.jsx("select",{value:d,onChange:f=>g(f.target.value),disabled:c,className:"cedros-role-select",children:ua.map(f=>e.jsx("option",{value:f,children:f.charAt(0).toUpperCase()+f.slice(1)},f))}):e.jsx("span",{className:`cedros-role-badge cedros-role-badge-${s.role}`,children:s.role.charAt(0).toUpperCase()+s.role.slice(1)})}),e.jsx("td",{className:"cedros-member-joined",children:pa(s.joinedAt)}),(r||a)&&e.jsx("td",{className:"cedros-member-actions",children:r&&b&&o&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-danger cedros-button-sm",onClick:m,disabled:c,"aria-label":`Remove ${s.user.name||s.user.email}`,children:c?e.jsx(N.LoadingSpinner,{size:"sm"}):"Remove"})})]})}function ma({user:s}){const t=X.sanitizeImageUrl(s.picture);if(t)return e.jsx("img",{src:t,alt:s.name||s.email||"Member",className:"cedros-member-avatar",referrerPolicy:"no-referrer"});const r=(s.name?.[0]||s.email?.[0]||"?").toUpperCase();return e.jsx("div",{className:"cedros-member-avatar-placeholder",children:r})}function pa(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}const fa=["admin","member"];function wr({onSubmit:s,isLoading:t=!1,error:r,availableRoles:a=fa,defaultRole:n="member",className:o=""}){const[c,l]=i.useState(""),[d,u]=i.useState(n),[g,m]=i.useState(null),[h,b]=i.useState(!1),f=i.useRef(null),p=i.useRef(!0);i.useEffect(()=>(p.current=!0,()=>{p.current=!1,f.current!==null&&(window.clearTimeout(f.current),f.current=null)}),[]);const x=i.useCallback(async j=>{j.preventDefault(),m(null),b(!1);const y=c.trim();if(!y){m("Email is required");return}if(!ts.validateEmail(y)){m("Please enter a valid email address");return}try{await s(y,d),l(""),u(n),b(!0),f.current!==null&&window.clearTimeout(f.current),f.current=window.setTimeout(()=>{p.current&&b(!1),f.current=null},3e3)}catch{}},[c,d,n,s]);return e.jsxs("form",{className:`cedros-invite-form ${o}`,onSubmit:x,children:[(r||g)&&e.jsx(N.ErrorMessage,{error:g??r??null}),h&&e.jsxs("div",{className:"cedros-invite-success",role:"status",children:[e.jsx(ga,{}),e.jsx("span",{children:"Invitation sent successfully!"})]}),e.jsxs("div",{className:"cedros-invite-form-row",children:[e.jsxs("div",{className:"cedros-form-group cedros-invite-email-group",children:[e.jsx("label",{htmlFor:"invite-email",className:"cedros-form-label",children:"Email Address"}),e.jsx("input",{id:"invite-email",type:"email",className:"cedros-form-input",value:c,onChange:j=>l(j.target.value),placeholder:"colleague@example.com",disabled:t,autoComplete:"email"})]}),e.jsxs("div",{className:"cedros-form-group cedros-invite-role-group",children:[e.jsx("label",{htmlFor:"invite-role",className:"cedros-form-label",children:"Role"}),e.jsx("select",{id:"invite-role",className:"cedros-form-select",value:d,onChange:j=>u(j.target.value),disabled:t,children:a.map(j=>e.jsx("option",{value:j,children:j.charAt(0).toUpperCase()+j.slice(1)},j))})]}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary cedros-invite-submit",disabled:t||!c.trim(),children:t?e.jsx(N.LoadingSpinner,{size:"sm"}):"Send Invite"})]}),e.jsx("p",{className:"cedros-form-hint",children:"The invited user will receive an email with a link to join your organization."})]})}function ga(){return e.jsx("svg",{className:"cedros-invite-check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M3 8L6 11L13 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function xr({invites:s,isLoading:t=!1,error:r,canManage:a=!1,onCancel:n,onResend:o,className:c=""}){return t&&s.length===0?e.jsxs("div",{className:`cedros-invite-list cedros-invite-list-loading ${c}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading invites..."})]}):r?e.jsx("div",{className:`cedros-invite-list ${c}`,children:e.jsx(N.ErrorMessage,{error:r})}):s.length===0?e.jsx("div",{className:`cedros-invite-list cedros-invite-list-empty ${c}`,children:e.jsx("p",{children:"No pending invites."})}):e.jsx("div",{className:`cedros-invite-list ${c}`,children:e.jsx("ul",{className:"cedros-invite-items",children:s.map(l=>e.jsx(ba,{invite:l,canManage:a,onCancel:n,onResend:o},l.id))})})}function ba({invite:s,canManage:t,onCancel:r,onResend:a}){const[n,o]=i.useState(!1),[c,l]=i.useState(!1),d=i.useRef(null),u=new Date(s.expiresAt)<new Date,g=i.useCallback(async()=>{if(!(!r||!window.confirm(`Are you sure you want to cancel the invite for ${s.email}?`))){o(!0);try{await r(s.id)}finally{o(!1)}}},[s.id,s.email,r]),m=i.useCallback(async()=>{if(a){o(!0),l(!1);try{await a(s.id),l(!0),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{l(!1),d.current=null},3e3)}finally{o(!1)}}},[s.id,a]);return i.useEffect(()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},[]),e.jsxs("li",{className:`cedros-invite-item ${u?"cedros-invite-item-expired":""}`,children:[e.jsxs("div",{className:"cedros-invite-item-info",children:[e.jsxs("div",{className:"cedros-invite-item-main",children:[e.jsx("span",{className:"cedros-invite-item-email",children:s.email}),e.jsx("span",{className:`cedros-role-badge cedros-role-badge-${s.role}`,children:s.role.charAt(0).toUpperCase()+s.role.slice(1)}),u&&e.jsx("span",{className:"cedros-invite-expired-badge",children:"Expired"})]}),e.jsxs("div",{className:"cedros-invite-item-meta",children:[e.jsxs("span",{className:"cedros-invite-item-date",children:["Invited ",vr(s.createdAt)]}),!u&&e.jsxs("span",{className:"cedros-invite-item-expires",children:["Expires ",ya(s.expiresAt)]})]})]}),t&&e.jsxs("div",{className:"cedros-invite-item-actions",children:[c&&e.jsx("span",{className:"cedros-invite-resend-success",children:"Sent!"}),a&&!u&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:m,disabled:n,"aria-label":`Resend invite to ${s.email}`,children:n?e.jsx(N.LoadingSpinner,{size:"sm"}):"Resend"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-danger cedros-button-sm",onClick:g,disabled:n,"aria-label":`Cancel invite for ${s.email}`,children:"Cancel"})]})]})}function vr(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ya(s){const t=new Date(s),r=new Date,a=t.getTime()-r.getTime(),n=Math.ceil(a/(1e3*60*60*24));return n<0?"expired":n===0?"today":n===1?"tomorrow":n<7?`in ${n} days`:vr(s)}function wa({sessions:s,isLoading:t=!1,error:r,onRevokeAll:a,className:n=""}){const[o,c]=i.useState(!1),[l,d]=i.useState(!1),u=i.useRef(null),g=i.useMemo(()=>s.filter(h=>!h.isCurrent).length,[s]),m=i.useCallback(async()=>{if(!a)return;const h=s.filter(f=>!f.isCurrent).length;if(!(h===0||!window.confirm(`Are you sure you want to sign out of ${h} other device(s)? This will log you out everywhere except this browser.`))){c(!0),d(!1);try{await a(),d(!0),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{d(!1),u.current=null},3e3)}finally{c(!1)}}},[a,s]);return i.useEffect(()=>()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]),t&&s.length===0?e.jsxs("div",{className:`cedros-session-list cedros-session-list-loading ${n}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading sessions..."})]}):r?e.jsx("div",{className:`cedros-session-list ${n}`,children:e.jsx(N.ErrorMessage,{error:r})}):s.length===0?e.jsx("div",{className:`cedros-session-list cedros-session-list-empty ${n}`,children:e.jsx("p",{children:"No active sessions found."})}):e.jsxs("div",{className:`cedros-session-list ${n}`,children:[l&&e.jsxs("div",{className:"cedros-session-success",role:"status",children:[e.jsx(Na,{}),e.jsx("span",{children:"All other sessions have been revoked."})]}),e.jsx("ul",{className:"cedros-session-items",children:s.map(h=>e.jsx(xa,{session:h},h.id))}),a&&g>0&&e.jsx("div",{className:"cedros-session-actions",children:e.jsx("button",{type:"button",className:"cedros-button cedros-button-danger",onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(N.LoadingSpinner,{size:"sm"}),e.jsx("span",{children:"Signing out..."})]}):`Sign out of ${g} other device${g>1?"s":""}`})})]})}function xa({session:s}){const t=va(s.userAgent),r=Aa(s.expiresAt);return e.jsxs("li",{className:`cedros-session-item ${s.isCurrent?"cedros-session-item-current":""}`,children:[e.jsx("div",{className:"cedros-session-item-icon",children:e.jsx(ka,{userAgent:s.userAgent})}),e.jsxs("div",{className:"cedros-session-item-info",children:[e.jsxs("div",{className:"cedros-session-item-main",children:[e.jsxs("span",{className:"cedros-session-item-device",children:[t.browser," on ",t.os]}),s.isCurrent&&e.jsx("span",{className:"cedros-session-current-badge",children:"Current session"})]}),e.jsxs("div",{className:"cedros-session-item-meta",children:[s.ipAddress&&e.jsxs("span",{className:"cedros-session-item-ip",children:["IP: ",s.ipAddress]}),e.jsxs("span",{className:"cedros-session-item-created",children:["Started ",ja(s.createdAt)]}),r&&e.jsx("span",{className:"cedros-session-expiring",children:"Expires soon"})]})]})]})}function va(s){if(!s)return{browser:"Unknown browser",os:"Unknown device"};let t="Unknown browser";s.includes("Chrome")&&!s.includes("Edg")?t="Chrome":s.includes("Safari")&&!s.includes("Chrome")?t="Safari":s.includes("Firefox")?t="Firefox":s.includes("Edg")&&(t="Edge");let r="Unknown device";return s.includes("Windows")?r="Windows":s.includes("Mac")?r="macOS":s.includes("Linux")?r="Linux":s.includes("iPhone")||s.includes("iPad")?r="iOS":s.includes("Android")&&(r="Android"),{browser:t,os:r}}function ja(s){const t=new Date(s),a=new Date().getTime()-t.getTime(),n=Math.floor(a/(1e3*60)),o=Math.floor(a/(1e3*60*60)),c=Math.floor(a/(1e3*60*60*24));return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:o<24?`${o} hour${o>1?"s":""} ago`:c<7?`${c} day${c>1?"s":""} ago`:t.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Aa(s){const t=new Date(s),r=new Date,a=3600*1e3;return t.getTime()-r.getTime()<a}function ka({userAgent:s}){return s?.includes("iPhone")||s?.includes("iPad")||s?.includes("Android")?e.jsxs("svg",{className:"cedros-session-device-icon",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("circle",{cx:"12",cy:"18",r:"1",fill:"currentColor"})]}):e.jsxs("svg",{className:"cedros-session-device-icon",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("rect",{x:"2",y:"4",width:"20",height:"14",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("path",{d:"M8 21H16",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),e.jsx("path",{d:"M12 18V21",stroke:"currentColor",strokeWidth:"1.5"})]})}function Na(){return e.jsx("svg",{className:"cedros-session-check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M3 8L6 11L13 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function jr({words:s,onConfirm:t,className:r=""}){const[a,n]=i.useState(!1),[o,c]=i.useState(!1),l=i.useRef(null),d=$n(s),u=i.useCallback(async()=>{try{await navigator.clipboard.writeText(s.join(" ")),n(!0),l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>n(!1),2e3)}catch{}},[s]);i.useEffect(()=>()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null)},[]);const g=i.useCallback(()=>{o&&t()},[o,t]);return e.jsxs("div",{className:`cedros-recovery-phrase-display ${r}`,children:[e.jsxs("div",{className:"cedros-recovery-header",children:[e.jsx("h3",{className:"cedros-recovery-title",children:"Recovery Phrase"}),e.jsx("p",{className:"cedros-recovery-warning",children:"Write down these 12 words in order and store them securely. This is the only way to recover your wallet if you lose access."})]}),e.jsx("div",{className:"cedros-recovery-grid",children:d.map((m,h)=>e.jsx("div",{className:"cedros-word-group",children:m.map((b,f)=>{const p=h*4+f+1;return e.jsxs("div",{className:"cedros-word-item",children:[e.jsxs("span",{className:"cedros-word-number",children:[p,"."]}),e.jsx("span",{className:"cedros-word-text",children:b})]},p)})},h))}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary cedros-copy-btn",onClick:u,children:a?"Copied!":"Copy to Clipboard"}),e.jsx("div",{className:"cedros-recovery-security",children:e.jsxs("div",{className:"cedros-warning-box",children:[e.jsx("svg",{className:"cedros-warning-icon",width:"20",height:"20",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:e.jsx("path",{d:"M10 6v4m0 4h.01M19 10a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})}),e.jsxs("div",{className:"cedros-warning-content",children:[e.jsx("strong",{children:"Security Warning"}),e.jsxs("ul",{children:[e.jsx("li",{children:"Never share this phrase with anyone"}),e.jsx("li",{children:"Store it offline in a secure location"}),e.jsx("li",{children:"Anyone with this phrase can access your wallet"}),e.jsx("li",{children:"Cedros cannot recover this phrase for you"})]})]})]})}),e.jsxs("div",{className:"cedros-recovery-confirm",children:[e.jsxs("label",{className:"cedros-checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:m=>c(m.target.checked),className:"cedros-checkbox"}),e.jsx("span",{children:"I have written down and securely stored my recovery phrase"})]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:g,disabled:!o,children:"Continue"})]})]})}function Ar({onSubmit:s,onCancel:t,isSubmitting:r=!1,error:a,className:n=""}){const[o,c]=i.useState(Array(oe).fill("")),[l,d]=i.useState(null),[u,g]=i.useState([]),[m,h]=i.useState(null),b=i.useId(),f=i.useRef(null),p=i.useCallback((w,E)=>{const P=[...o];if(P[w]=E.toLowerCase().trim(),c(P),E.length>0){const L=Wn(E,5);g(L)}else g([]);h(null)},[o]),x=i.useCallback(w=>{d(w),g([])},[]),j=i.useCallback(w=>{const E=o[w];E&&!We(E)&&h(`Word ${w+1} is not in the wordlist`),f.current!==null&&window.clearTimeout(f.current),f.current=window.setTimeout(()=>{l===w&&g([])},200)},[o,l]);i.useEffect(()=>()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},[]);const y=i.useCallback(w=>{if(l!==null){const E=[...o];E[l]=w,c(E),g([]),document.querySelector(`[data-word-index="${l+1}"]`)?.focus()}},[l,o]),A=i.useCallback(w=>{const E=w.clipboardData.getData("text"),P=zn(E);P.length===oe&&(w.preventDefault(),c(P),h(null))},[]),v=i.useCallback(w=>{if(w.preventDefault(),o.filter(L=>!L).length>0){h(`Please enter all ${oe} words`);return}const P=o.map((L,T)=>({word:L,index:T+1})).filter(({word:L})=>!We(L));if(P.length>0){h(`Invalid words: ${P.map(L=>`#${L.index}`).join(", ")}`);return}if(!cr(o)){h("Invalid recovery phrase - please check your words");return}s(o)},[o,s]),S=a||m;return e.jsxs("form",{className:`cedros-recovery-phrase-input ${n}`,onSubmit:v,onPaste:A,children:[e.jsxs("div",{className:"cedros-recovery-input-header",children:[e.jsx("h3",{className:"cedros-recovery-input-title",children:"Enter Recovery Phrase"}),e.jsx("p",{className:"cedros-recovery-input-description",children:"Enter your 12-word recovery phrase. You can paste the entire phrase at once."})]}),e.jsx("div",{className:"cedros-word-inputs",children:Array.from({length:oe},(w,E)=>e.jsxs("div",{className:"cedros-word-input-wrapper",children:[e.jsxs("label",{className:"cedros-word-label",children:[E+1,"."]}),e.jsx("input",{type:"text",className:`cedros-word-input ${o[E]&&!We(o[E])?"cedros-word-invalid":o[E]&&We(o[E])?"cedros-word-valid":""}`,value:o[E],onChange:P=>p(E,P.target.value),onFocus:()=>x(E),onBlur:()=>j(E),"data-word-index":E,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,disabled:r,"aria-label":`Word ${E+1}`})]},E))}),l!==null&&u.length>0&&e.jsx("div",{className:"cedros-suggestions",role:"listbox",id:`${b}-suggestions`,children:u.map(w=>e.jsx("button",{type:"button",className:"cedros-suggestion",onClick:()=>y(w),role:"option",children:w},w))}),S&&e.jsx("p",{className:"cedros-input-error",role:"alert",children:S}),e.jsxs("div",{className:"cedros-recovery-input-actions",children:[t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:t,disabled:r,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:r,children:r?"Recovering...":"Recover Wallet"})]})]})}function Sa({capabilities:s,className:t=""}){if(s.allSupported)return null;const r=N.getMissingCapabilitiesMessage(s),a=N.getBrowserSupportInfo();return e.jsxs("div",{className:`cedros-capability-warning ${t}`,role:"alert",children:[e.jsxs("div",{className:"cedros-warning-header",children:[e.jsx("svg",{className:"cedros-warning-icon",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:e.jsx("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})}),e.jsx("h3",{className:"cedros-warning-title",children:"Wallet Feature Unavailable"})]}),e.jsx("p",{className:"cedros-warning-message",children:r}),e.jsxs("div",{className:"cedros-capability-details",children:[e.jsx("h4",{children:"Browser Compatibility"}),e.jsxs("p",{children:["Detected: ",a.browser," ",a.version,a.likelySupported?" (likely supported)":" (may not be supported)"]}),e.jsx("h4",{children:"Required Features"}),e.jsxs("ul",{className:"cedros-capability-list",children:[e.jsxs("li",{className:s.webCrypto?"cedros-cap-ok":"cedros-cap-missing",children:["Web Crypto API: ",s.webCrypto?"Available":"Missing"]}),e.jsxs("li",{className:s.aesGcm?"cedros-cap-ok":"cedros-cap-missing",children:["AES-GCM Encryption: ",s.aesGcm?"Available":"Missing"]}),e.jsxs("li",{className:s.hkdf?"cedros-cap-ok":"cedros-cap-missing",children:["HKDF Key Derivation: ",s.hkdf?"Available":"Missing"]}),e.jsxs("li",{className:s.webAuthn?"cedros-cap-ok":"cedros-cap-missing",children:["WebAuthn/Passkeys: ",s.webAuthn?"Available":"Missing"]}),e.jsxs("li",{className:s.webAuthnPrf?"cedros-cap-ok":"cedros-cap-missing",children:["WebAuthn PRF Extension: ",s.webAuthnPrf?"Available":"Missing"]}),e.jsxs("li",{className:s.argon2?"cedros-cap-ok":"cedros-cap-missing",children:["Argon2 Password Hashing: ",s.argon2?"Available":"Missing"]})]})]}),e.jsxs("div",{className:"cedros-capability-help",children:[e.jsx("h4",{children:"Recommended Browsers"}),e.jsxs("ul",{children:[e.jsx("li",{children:"Chrome 116+ on Windows, macOS, or Android"}),e.jsx("li",{children:"Safari 17+ on macOS or iOS"}),e.jsx("li",{children:"Edge 116+ on Windows"})]}),e.jsx("p",{className:"cedros-capability-note",children:"A platform authenticator (Touch ID, Face ID, or Windows Hello) is required."})]})]})}const Ca=["share_c_only","full_seed","none"];function _a(s){return s&&Ca.includes(s)?s:"share_c_only"}const Ea={walletEnabled:!1,recoveryMode:"share_c_only",unlockTtlSeconds:900,isLoading:!1,error:null,refetch:async()=>{}};function kr(){const s=N.useCedrosLoginOptional(),[t,r]=i.useState(null),[a,n]=i.useState(!!s),[o,c]=i.useState(null),l=i.useMemo(()=>s?new N.ApiClient({baseUrl:s.config.serverUrl,timeoutMs:s.config.requestTimeout,retryAttempts:s.config.retryAttempts}):null,[s]),d=i.useCallback(async()=>{if(l){n(!0),c(null);try{const u=await l.get("/discovery");u.wallet?r({enabled:u.wallet.enabled,recoveryMode:_a(u.wallet.recoveryMode),unlockTtlSeconds:u.wallet.unlockTtlSeconds}):r({enabled:!1,recoveryMode:"share_c_only",unlockTtlSeconds:900})}catch(u){const g=u instanceof Error?u.message:"Failed to fetch wallet config";c(g),r({enabled:!1,recoveryMode:"share_c_only",unlockTtlSeconds:900})}finally{n(!1)}}},[l]);return i.useEffect(()=>{l&&d()},[l,d]),s?{walletEnabled:t?.enabled??!1,recoveryMode:t?.recoveryMode??"share_c_only",unlockTtlSeconds:t?.unlockTtlSeconds??900,isLoading:a,error:o,refetch:d}:Ea}function Nr(){const{user:s}=N.useCedrosLogin(),{enroll:t}=N.useWalletMaterial(),{recoveryMode:r}=kr(),[a,n]=i.useState({step:"idle"}),[o,c]=i.useState(!1),l=i.useRef([]),d=i.useCallback(()=>{N.wipeAll(...l.current),l.current=[]},[]);i.useEffect(()=>()=>{d()},[d]);const u=i.useCallback(async(f,p,x,j)=>{n({step:"generating_seed"});const y=N.generateSeed();l.current.push(y),n({step:"splitting_shares"});const{shareA:A,shareB:v,shareC:S}=le.splitSecret(y);l.current.push(A,v,S),n({step:"encrypting_shares"});const w=await N.aesGcmEncryptToBase64(A,N.toEncryptionKey(p)),E=le.getPublicKeyFromSeed(y),P=le.publicKeyToBase58(E);n({step:"uploading"});const L={solanaPubkey:P,shareAAuthMethod:f,shareACiphertext:w.ciphertext,shareANonce:w.nonce,shareB:N.uint8ArrayToBase64(v)};if(f==="password"){if(!x)throw new Error("KDF salt required for password method");L.shareAKdfSalt=N.uint8ArrayToBase64(x),L.shareAKdfParams=N.DEFAULT_KDF_PARAMS}if(f==="passkey"&&j&&(L.prfSalt=j),await t(L),r==="none")d(),n({step:"complete",solanaPubkey:P});else{const T=r==="full_seed"?On(y):Fn(N.toShamirShare(S));n({step:"showing_recovery",recoveryPhrase:T,solanaPubkey:P})}},[t,r,d]),g=i.useCallback(async f=>{if(!s){n({step:"error",error:"User not authenticated"});return}c(!0),d();try{const p=N.generateArgon2Salt(),x=await le.argon2DeriveInWorker(f,p,N.DEFAULT_KDF_PARAMS);l.current.push(x),await u("password",x,p)}catch(p){n({step:"error",error:p instanceof Error?p.message:"Enrollment failed"})}finally{c(!1)}},[s,d,u]),m=i.useCallback(async()=>{if(!s){n({step:"error",error:"User not authenticated"});return}c(!0),d();try{const f=N.generatePrfSalt(),p=N.uint8ArrayToBase64(f);n({step:"registering_passkey"});let x;try{const y=new TextEncoder().encode(s.id),A=s.name??s.email??"User",v=s.email??s.id;x=(await N.registerPasskeyWithPrf(y,v,A,f)).prfOutput}catch(y){if(y?.name!=="InvalidStateError")throw y;x=(await N.authenticateWithDiscoverablePrf(p)).prfOutput}l.current.push(x);const j=await N.deriveKeyFromPrf(x,f);l.current.push(j),await u("passkey",j,void 0,p)}catch(f){n({step:"error",error:f instanceof Error?f.message:"Enrollment failed"})}finally{c(!1)}},[s,d,u]),h=i.useCallback(()=>{const f=a.solanaPubkey;d(),n({step:"complete",solanaPubkey:f})},[a.solanaPubkey,d]),b=i.useCallback(()=>{d(),n({step:"idle"}),c(!1)},[d]);return{state:a,startEnrollmentWithPassword:g,startEnrollmentWithPasskey:m,confirmRecoveryPhrase:h,cancel:b,isEnrolling:o}}function Sr({onComplete:s,onCancel:t,className:r="",forceAuthMethod:a}){const{user:n}=N.useCedrosLogin(),{state:o,startEnrollmentWithPassword:c,startEnrollmentWithPasskey:l,confirmRecoveryPhrase:d,cancel:u,isEnrolling:g}=Nr(),m=()=>a||"password",[h,b]=i.useState(m),[f,p]=i.useState(""),[x,j]=i.useState(""),[y,A]=i.useState(null);i.useEffect(()=>{b(m())},[n?.id,a]);const v=i.useCallback(async P=>{if(P.preventDefault(),f!==x){A("Passwords do not match");return}if(f.length<8){A("Password must be at least 8 characters");return}A(null),await c(f)},[f,x,c]),S=i.useCallback(async()=>{await l()},[l]),w=i.useCallback(()=>{d(),o.solanaPubkey&&s?.(o.solanaPubkey)},[d,o.solanaPubkey,s]),E=i.useCallback(()=>{u(),t?.()},[u,t]);return o.step==="generating_seed"||o.step==="splitting_shares"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,"aria-busy":"true",children:e.jsxs("div",{className:"cedros-enrollment-progress",role:"status","aria-live":"polite",children:[e.jsx("div",{className:"cedros-spinner","aria-hidden":"true"}),e.jsx("p",{children:"Generating secure wallet..."})]})}):o.step==="encrypting_shares"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,"aria-busy":"true",children:e.jsxs("div",{className:"cedros-enrollment-progress",role:"status","aria-live":"polite",children:[e.jsx("div",{className:"cedros-spinner","aria-hidden":"true"}),e.jsx("p",{children:"Encrypting wallet shares..."})]})}):o.step==="registering_passkey"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,"aria-busy":"true",children:e.jsx("div",{className:"cedros-enrollment-progress",role:"status","aria-live":"polite",children:e.jsxs("div",{className:"cedros-passkey-prompt",children:[e.jsxs("svg",{className:"cedros-passkey-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("rect",{x:"8",y:"16",width:"32",height:"24",rx:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("circle",{cx:"24",cy:"28",r:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M24 32v4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),e.jsx("h3",{children:"Authenticate with Passkey"}),e.jsx("p",{children:"Follow your browser's prompt to use your passkey."})]})})}):o.step==="uploading"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,"aria-busy":"true",children:e.jsxs("div",{className:"cedros-enrollment-progress",role:"status","aria-live":"polite",children:[e.jsx("div",{className:"cedros-spinner","aria-hidden":"true"}),e.jsx("p",{children:"Saving wallet..."})]})}):o.step==="showing_recovery"&&o.recoveryPhrase?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,children:e.jsx(jr,{words:o.recoveryPhrase,onConfirm:w})}):o.step==="complete"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,children:e.jsxs("div",{className:"cedros-enrollment-complete",children:[e.jsxs("svg",{className:"cedros-success-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M16 24l6 6 12-12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),e.jsx("h3",{children:"Wallet Created!"}),e.jsxs("p",{className:"cedros-pubkey",children:[e.jsx("strong",{children:"Address:"})," ",o.solanaPubkey]}),e.jsx("p",{children:"Your non-custodial Solana wallet is ready to use."})]})}):o.step==="error"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,children:e.jsxs("div",{className:"cedros-enrollment-error",children:[e.jsxs("svg",{className:"cedros-error-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M24 16v12m0 6h.01",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),e.jsx("h3",{children:"Enrollment Failed"}),e.jsx("p",{className:"cedros-error-message",children:o.error}),e.jsxs("div",{className:"cedros-error-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,children:"Cancel"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:()=>u(),children:"Try Again"})]})]})}):e.jsxs("div",{className:`cedros-wallet-enrollment ${r}`,children:[e.jsxs("div",{className:"cedros-enrollment-header",children:[e.jsx("h2",{children:"Create Wallet"}),e.jsxs("p",{children:["Secure your wallet with a ",h==="passkey"?"passkey":"password","."]})]}),!a&&e.jsxs("div",{className:"cedros-auth-method-selector",children:[e.jsxs("label",{className:"cedros-radio-label",children:[e.jsx("input",{type:"radio",name:"authMethod",value:"password",checked:h==="password",onChange:()=>b("password"),disabled:g}),e.jsx("span",{children:"Password"})]}),e.jsxs("label",{className:"cedros-radio-label",children:[e.jsx("input",{type:"radio",name:"authMethod",value:"passkey",checked:h==="passkey",onChange:()=>b("passkey"),disabled:g}),e.jsx("span",{children:"Passkey"})]})]}),h==="password"&&e.jsxs("form",{onSubmit:v,className:"cedros-enrollment-form",children:[e.jsx(X.PasswordInput,{label:"Password",value:f,onChange:P=>p(P.target.value),showStrengthMeter:!0,disabled:g,required:!0,minLength:8,placeholder:"Enter a strong password"}),e.jsx(X.PasswordInput,{label:"Confirm Password",value:x,onChange:P=>j(P.target.value),error:y??void 0,disabled:g,required:!0,minLength:8,placeholder:"Confirm your password"}),e.jsx("div",{className:"cedros-password-info",children:e.jsx("p",{children:"This password will be used to sign transactions."})}),e.jsxs("div",{className:"cedros-enrollment-actions",children:[t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,disabled:g,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:g||!f||!x,children:g?"Creating...":"Continue"})]})]}),h==="passkey"&&e.jsxs("div",{className:"cedros-enrollment-form",children:[e.jsxs("div",{className:"cedros-passkey-info",children:[e.jsxs("svg",{className:"cedros-passkey-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("rect",{x:"8",y:"16",width:"32",height:"24",rx:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("circle",{cx:"24",cy:"28",r:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M24 32v4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),e.jsx("p",{children:"Use your passkey (Touch ID, Face ID, or Windows Hello) to secure your wallet."}),e.jsx("p",{children:"You'll use the same passkey to sign transactions."})]}),e.jsxs("div",{className:"cedros-enrollment-actions",children:[t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,disabled:g,children:"Cancel"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:S,disabled:g,children:g?"Creating...":"Use Passkey"})]})]})]})}function Cr(){const{user:s}=N.useCedrosLogin(),{signTransaction:t}=N.useWalletMaterial(),[r,a]=i.useState(!1),[n,o]=i.useState(null),c=i.useCallback(async(d,u)=>{if(!s){const g="User not authenticated";throw o(g),new Error(g)}a(!0),o(null);try{const g={transaction:N.uint8ArrayToBase64(d),...u?{credential:N.toCredentialRequest(u)}:{}},m=await t(g);return N.base64ToUint8Array(m.signature)}catch(g){const m=g instanceof Error?g.message:"Signing failed";throw o(m),g}finally{a(!1)}},[s,t]),l=i.useCallback(()=>o(null),[]);return{signTransaction:c,isSigning:r,error:n,clearError:l}}function _r(){const{getMaterial:s}=N.useWalletMaterial(),[t,r]=i.useState(!1),[a,n]=i.useState(null),o=i.useCallback(async()=>{r(!0),n(null);try{const l=await s();if(!l)throw new Error("No wallet enrolled");if(l.shareAAuthMethod!=="passkey")throw new Error("Wallet is not configured for passkey authentication");if(!l.prfSalt)throw new Error("No PRF salt configured for wallet");const d=await N.authenticateWithDiscoverablePrf(l.prfSalt);return{type:"prfOutput",prfOutput:N.uint8ArrayToBase64(d.prfOutput)}}catch(l){const d=l instanceof Error?l.message:"Passkey authentication failed";return n(d),null}finally{r(!1)}},[s]),c=i.useCallback(()=>n(null),[]);return{getPasskeyCredential:o,isAuthenticating:t,error:a,clearError:c}}function Er({mode:s,isLoading:t=!1,error:r,onPrompt:a,onRetry:n,onCancel:o,title:c,description:l,className:d=""}){const u=i.useCallback(()=>{t||a?.()},[t,a]),g=i.useCallback(()=>{n?.()},[n]),m=s==="register"?"Set Up Passkey":"Verify with Passkey",h=s==="register"?"Create a passkey to securely encrypt your wallet on this device. You will use your fingerprint, face, or device PIN.":"Use your passkey to unlock your wallet. You will be prompted for biometric verification.";return e.jsxs("div",{className:`cedros-passkey-prompt ${d}`,children:[e.jsx("div",{className:"cedros-passkey-icon",children:t?e.jsx(Pa,{}):r?e.jsx(La,{}):e.jsx(Ta,{})}),e.jsx("h3",{className:"cedros-passkey-title",children:c??m}),e.jsx("p",{className:"cedros-passkey-description",children:l??h}),r&&e.jsx("div",{className:"cedros-passkey-error",role:"alert",children:e.jsx("p",{children:r})}),e.jsx("div",{className:"cedros-passkey-actions",children:r?e.jsxs(e.Fragment,{children:[n&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:g,children:"Try Again"}),o&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:o,children:"Cancel"})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:u,disabled:t,children:t?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-button-spinner","aria-hidden":"true"}),"Waiting for passkey..."]}):s==="register"?"Create Passkey":"Use Passkey"}),o&&!t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:o,children:"Cancel"})]})}),t&&e.jsxs("p",{className:"cedros-passkey-hint",children:["Follow the prompts on your device to ",s==="register"?"create":"verify"," your passkey."]})]})}function Ta(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4"}),e.jsx("path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88"}),e.jsx("path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02"}),e.jsx("path",{d:"M2 12a10 10 0 0 1 18-6"}),e.jsx("path",{d:"M2 16h.01"}),e.jsx("path",{d:"M21.8 16c.2-2 .131-5.354 0-6"}),e.jsx("path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2"}),e.jsx("path",{d:"M8.65 22c.21-.66.45-1.32.57-2"}),e.jsx("path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2"})]})}function Pa(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",className:"cedros-spinner",children:[e.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),e.jsx("path",{d:"M12 3a9 9 0 0 1 9 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}function La(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 8v4M12 16h.01"})]})}function Tr({onUnlock:s,onCancel:t,showCancel:r=!0,authMethod:a,className:n=""}){N.useCedrosLogin();const{unlock:o,getMaterial:c,isLoading:l}=N.useWalletMaterial(),{getPasskeyCredential:d,isAuthenticating:u}=_r(),[g,m]=i.useState("idle"),[h,b]=i.useState(a??null),[f,p]=i.useState(""),[x,j]=i.useState(null);i.useEffect(()=>{a!==void 0&&b(a)},[a]);const y=h==="password",A=h==="passkey",v=i.useCallback(async()=>{if(m("credential"),j(null),!h)try{const C=await c();C?b(C.shareAAuthMethod):(j("No wallet enrolled"),m("error"))}catch(C){j(C instanceof Error?C.message:"Failed to get wallet info"),m("error")}},[h,c]),S=i.useCallback(async C=>{C.preventDefault(),j(null),m("unlocking");try{let k;if(y)k={type:"password",password:f};else throw new Error("Invalid auth method");await o(k),m("unlocked"),s?.()}catch(k){j(k instanceof Error?k.message:"Failed to unlock wallet"),m("error")}},[y,f,o,s]),w=i.useCallback(async()=>{j(null),m("unlocking");try{const C=await d();if(!C){m("credential");return}await o(C),m("unlocked"),s?.()}catch(C){j(C instanceof Error?C.message:"Failed to unlock wallet"),m("error")}},[d,o,s]),E=i.useCallback(()=>{p(""),m("idle"),j(null),t?.()},[t]),P=i.useCallback(()=>{p(""),m("credential"),j(null)},[]),L=l||u,T=()=>{switch(g){case"idle":return e.jsxs("div",{className:"cedros-wallet-unlock-idle",children:[e.jsx("div",{className:"cedros-wallet-unlock-icon",children:e.jsx(Ma,{})}),e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Wallet Locked"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Unlock your wallet to sign transactions."}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:v,children:"Unlock Wallet"})]});case"credential":return y?e.jsxs("form",{className:"cedros-wallet-unlock-form",onSubmit:S,children:[e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Enter Password"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Enter your wallet password to unlock."}),e.jsx(X.PasswordInput,{label:"Password",value:f,onChange:C=>p(C.target.value),disabled:L,autoComplete:"current-password",error:x??void 0}),e.jsxs("div",{className:"cedros-wallet-unlock-actions",children:[e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:L||f.length===0,children:L?"Unlocking...":"Unlock"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,disabled:L,children:"Cancel"})]})]}):A?e.jsxs("div",{className:"cedros-wallet-unlock-passkey",children:[e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Verify with Passkey"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Use your passkey to unlock your wallet."}),e.jsx(Er,{mode:"authenticate",isLoading:L,error:x??void 0,onPrompt:w,onRetry:w,onCancel:r?E:void 0})]}):e.jsxs("div",{className:"cedros-wallet-unlock-loading",children:[e.jsx(N.LoadingSpinner,{size:"xl"}),e.jsx("p",{children:"Loading wallet info..."})]});case"unlocking":return e.jsxs("div",{className:"cedros-wallet-unlock-progress",children:[e.jsx("div",{className:"cedros-wallet-unlock-icon",children:e.jsx(N.LoadingSpinner,{size:"xl"})}),e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Unlocking Wallet"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Verifying your credentials..."})]});case"unlocked":return e.jsxs("div",{className:"cedros-wallet-unlock-success",children:[e.jsx("div",{className:"cedros-wallet-unlock-icon",children:e.jsx(Da,{})}),e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Wallet Unlocked"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Your wallet is ready to sign transactions."})]});case"error":return e.jsxs("div",{className:"cedros-wallet-unlock-error",children:[e.jsx("div",{className:"cedros-wallet-unlock-icon",children:e.jsx(Ra,{})}),e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Unlock Failed"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:x??"Failed to unlock wallet. Please try again."}),e.jsxs("div",{className:"cedros-wallet-unlock-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:P,children:"Try Again"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,children:"Cancel"})]})]})}};return e.jsx("div",{className:`cedros-wallet-unlock ${n}`,children:T()})}function Ma(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("rect",{x:"10",y:"22",width:"28",height:"20",rx:"4",stroke:"currentColor",strokeWidth:"2",fill:"var(--cedros-muted, #f3f4f6)"}),e.jsx("path",{d:"M16 22V16a8 8 0 1 1 16 0v6",stroke:"currentColor",strokeWidth:"2",fill:"none"}),e.jsx("circle",{cx:"24",cy:"32",r:"3",fill:"currentColor"})]})}function Da(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-success, #22c55e)",strokeWidth:"2",fill:"var(--cedros-success-light, #dcfce7)"}),e.jsx("path",{d:"M16 24l6 6 10-10",stroke:"var(--cedros-success, #22c55e)",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function Ra(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-destructive, #ef4444)",strokeWidth:"2",fill:"var(--cedros-destructive-light, #fee2e2)"}),e.jsx("path",{d:"M24 16v10M24 30v2",stroke:"var(--cedros-destructive, #ef4444)",strokeWidth:"3",strokeLinecap:"round"})]})}function Pr(){const{recover:s,getShareBForRecovery:t}=N.useWalletMaterial(),{recoveryMode:r}=kr(),[a,n]=i.useState({step:"idle"}),[o,c]=i.useState(!1),l=i.useRef([]),d=i.useCallback(()=>{N.wipeAll(...l.current),l.current=[]},[]);i.useEffect(()=>()=>{d()},[d]);const u=i.useCallback(async(m,h,b)=>{c(!0),d();try{if(n({step:"validating"}),!cr(m))throw new Error("Invalid recovery phrase. Please check your words.");let f;if(r==="share_c_only"){const P=Bn(m);l.current.push(P);const L=N.uint8ArrayToBase64(P),T=await t({shareC:L}),C=N.base64ToUint8Array(T.shareB);l.current.push(C),f=le.combineShares(N.toShamirShare(C),N.toShamirShare(P)),l.current.push(f)}else f=qn(m),l.current.push(f);const p=le.getPublicKeyFromSeed(f),x=le.publicKeyToBase58(p),{shareA:j,shareB:y}=le.splitSecret(f);l.current.push(j,y),n({step:"encrypting"});let A,v,S;if(h==="passkey"){const P=N.generatePrfSalt();S=N.uint8ArrayToBase64(P);const L=await N.authenticateWithDiscoverablePrf(S);l.current.push(L.prfOutput),A=await N.deriveKeyFromPrf(L.prfOutput,P),l.current.push(A)}else v=N.generateArgon2Salt(),A=await le.argon2DeriveInWorker(b,v,N.DEFAULT_KDF_PARAMS),l.current.push(A);const w=await N.aesGcmEncryptToBase64(j,N.toEncryptionKey(A));n({step:"uploading"});const E={solanaPubkey:x,shareAAuthMethod:h,shareACiphertext:w.ciphertext,shareANonce:w.nonce,shareB:N.uint8ArrayToBase64(y)};h==="password"&&(E.shareAKdfSalt=N.uint8ArrayToBase64(v),E.shareAKdfParams=N.DEFAULT_KDF_PARAMS),h==="passkey"&&(E.prfSalt=S),await s(E),d(),n({step:"complete"})}catch(f){d(),n({step:"error",error:f instanceof Error?f.message:"Recovery failed"})}finally{c(!1)}},[s,t,r,d]),g=i.useCallback(()=>{d(),n({step:"idle"}),c(!1)},[d]);return{state:a,startRecovery:u,cancel:g,isRecovering:o}}function Lr({onComplete:s,onCancel:t,className:r="",defaultAuthMethod:a="password"}){const{state:n,startRecovery:o,cancel:c,isRecovering:l}=Pr(),[d,u]=i.useState([]),[g,m]=i.useState(!1),[h,b]=i.useState(a),[f,p]=i.useState(""),[x,j]=i.useState(""),[y,A]=i.useState(null),v=i.useCallback(L=>{u(L),m(!0)},[]),S=i.useCallback(async L=>{if(L.preventDefault(),A(null),h!=="passkey"){if(f!==x){A("Passwords do not match");return}if(h==="password"&&f.length<8){A("Password must be at least 8 characters");return}}await o(d,h,f)},[d,h,f,x,o]),w=i.useCallback(()=>{c(),u([]),m(!1),p(""),j(""),t?.()},[c,t]),E=i.useCallback(()=>{m(!1),p(""),j("")},[]),P=i.useCallback(()=>{s?.()},[s]);return n.step==="validating"||n.step==="encrypting"||n.step==="uploading"?e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("div",{className:"cedros-wallet-recovery-progress",children:[e.jsx("div",{className:"cedros-wallet-recovery-icon",children:e.jsx(Ia,{})}),e.jsxs("h3",{className:"cedros-wallet-recovery-title",children:[n.step==="validating"&&"Validating Recovery Phrase",n.step==="encrypting"&&"Encrypting Wallet",n.step==="uploading"&&"Saving to Server"]}),e.jsxs("p",{className:"cedros-wallet-recovery-description",children:[n.step==="validating"&&"Checking your recovery phrase...",n.step==="encrypting"&&"Securing your wallet with new encryption...",n.step==="uploading"&&"Uploading encrypted wallet data..."]})]})}):n.step==="complete"?e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("div",{className:"cedros-wallet-recovery-success",children:[e.jsx("div",{className:"cedros-wallet-recovery-icon",children:e.jsx(Ua,{})}),e.jsx("h3",{className:"cedros-wallet-recovery-title",children:"Wallet Recovered"}),e.jsxs("p",{className:"cedros-wallet-recovery-description",children:["Your wallet has been successfully recovered and secured with your new"," ",h==="passkey"?"passkey":"password","."]}),e.jsx("div",{className:"cedros-wallet-recovery-actions",children:e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:P,children:"Done"})})]})}):n.step==="error"?e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("div",{className:"cedros-wallet-recovery-error",children:[e.jsx("div",{className:"cedros-wallet-recovery-icon",children:e.jsx(Fa,{})}),e.jsx("h3",{className:"cedros-wallet-recovery-title",children:"Recovery Failed"}),e.jsx("p",{className:"cedros-wallet-recovery-description",children:n.error??"An error occurred during recovery. Please try again."}),e.jsx("div",{className:"cedros-wallet-recovery-actions",children:e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:w,children:"Start Over"})})]})}):g?e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("form",{className:"cedros-wallet-recovery-credential",onSubmit:S,children:[e.jsxs("div",{className:"cedros-wallet-recovery-header",children:[e.jsx("h3",{className:"cedros-wallet-recovery-title",children:"Set New Security"}),e.jsx("p",{className:"cedros-wallet-recovery-description",children:"Choose how to secure your recovered wallet."})]}),e.jsxs("div",{className:"cedros-auth-method-selector",children:[e.jsxs("label",{className:"cedros-radio-label",children:[e.jsx("input",{type:"radio",name:"authMethod",value:"password",checked:h==="password",onChange:()=>b("password"),disabled:l}),e.jsx("span",{children:"Password"})]}),e.jsxs("label",{className:"cedros-radio-label",children:[e.jsx("input",{type:"radio",name:"authMethod",value:"passkey",checked:h==="passkey",onChange:()=>b("passkey"),disabled:l}),e.jsx("span",{children:"Passkey"})]})]}),h==="password"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-password-input",children:[e.jsx("label",{htmlFor:"recovery-password",className:"cedros-label",children:"New Password"}),e.jsx("input",{id:"recovery-password",type:"password",className:"cedros-input",value:f,onChange:L=>p(L.target.value),disabled:l,minLength:8,placeholder:"Enter a strong password"})]}),e.jsxs("div",{className:"cedros-password-input",children:[e.jsx("label",{htmlFor:"recovery-password-confirm",className:"cedros-label",children:"Confirm Password"}),e.jsx("input",{id:"recovery-password-confirm",type:"password",className:"cedros-input",value:x,onChange:L=>j(L.target.value),disabled:l,"aria-invalid":y?"true":void 0,placeholder:"Confirm your password"}),y&&e.jsx("p",{className:"cedros-input-error",role:"alert",children:y})]})]}),h==="passkey"&&e.jsxs("div",{className:"cedros-passkey-info",children:[e.jsx(Ba,{}),e.jsx("p",{children:"Use your passkey (Touch ID, Face ID, or Windows Hello) to secure your wallet."})]}),e.jsxs("div",{className:"cedros-wallet-recovery-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,disabled:l,children:"Back"}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:l||h!=="passkey"&&(f.length===0||x.length===0),children:l?"Recovering...":"Recover Wallet"})]})]})}):e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("div",{className:"cedros-wallet-recovery-phrase",children:[e.jsxs("div",{className:"cedros-wallet-recovery-header",children:[e.jsx("h3",{className:"cedros-wallet-recovery-title",children:"Recover Your Wallet"}),e.jsx("p",{className:"cedros-wallet-recovery-description",children:"Enter your 12-word recovery phrase to restore your wallet."})]}),e.jsx(Ar,{onSubmit:v,onCancel:w,isSubmitting:!1})]})})}function Ia(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",className:"cedros-spinner",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-muted, #e5e7eb)",strokeWidth:"3",fill:"none"}),e.jsx("path",{d:"M24 4a20 20 0 0 1 20 20",stroke:"var(--cedros-primary, #6366f1)",strokeWidth:"3",strokeLinecap:"round",fill:"none"})]})}function Ua(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-success, #22c55e)",strokeWidth:"2",fill:"var(--cedros-success-light, #dcfce7)"}),e.jsx("path",{d:"M16 24l6 6 10-10",stroke:"var(--cedros-success, #22c55e)",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function Fa(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-destructive, #ef4444)",strokeWidth:"2",fill:"var(--cedros-destructive-light, #fee2e2)"}),e.jsx("path",{d:"M24 16v10M24 30v2",stroke:"var(--cedros-destructive, #ef4444)",strokeWidth:"3",strokeLinecap:"round"})]})}function Ba(){return e.jsxs("svg",{className:"cedros-passkey-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("rect",{x:"8",y:"16",width:"32",height:"24",rx:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("circle",{cx:"24",cy:"28",r:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M24 32v4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}function Mr({address:s,label:t="Wallet Address",showCopy:r=!0,showExplorerLink:a=!0,allowReveal:n=!0,className:o=""}){const c=N.useCedrosLoginOptional(),[l,d]=i.useState(!1),[u,g]=i.useState(null),[m,h]=i.useState(!1),b=i.useRef(null),f=c?.config.solana?.network??"mainnet-beta",p=i.useMemo(()=>{const A=`https://explorer.solana.com/address/${s}`;return f==="mainnet-beta"?A:`${A}?cluster=${encodeURIComponent(f)}`},[s,f]),x=n&&s.length>18,j=i.useMemo(()=>!x||m?s:`${s.slice(0,8)}...${s.slice(-8)}`,[s,x,m]),y=i.useCallback(async()=>{try{g(null),await navigator.clipboard.writeText(s),d(!0),b.current!==null&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{d(!1),b.current=null},2e3)}catch(A){d(!1),g(A instanceof Error?A.message:"Copy failed")}},[s]);return i.useEffect(()=>()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)},[]),e.jsxs("div",{className:`cedros-wallet-address-row ${o}`,children:[e.jsxs("div",{className:"cedros-wallet-address-row-header",children:[e.jsx("span",{className:"cedros-wallet-status-pubkey-label",children:t}),e.jsxs("div",{className:"cedros-wallet-address-row-actions",children:[x&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-sm cedros-button-ghost",onClick:()=>h(A=>!A),"aria-label":m?"Hide full wallet address":"Show full wallet address",children:m?e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[e.jsx("path",{d:"M3 3l18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M10.7 10.7a3 3 0 0 0 4.24 4.24",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M9.88 5.09A10.94 10.94 0 0 1 12 5c5 0 9.27 3.11 11 7-0.55 1.23-1.32 2.33-2.27 3.25",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M6.61 6.61C4.4 7.9 2.74 9.8 1 12c1.73 3.89 6 7 11 7 1.14 0 2.25-0.16 3.3-0.46",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}):e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[e.jsx("path",{d:"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})}),a&&e.jsx("a",{className:"cedros-button cedros-button-sm cedros-button-ghost",href:p,target:"_blank",rel:"noreferrer",children:"Explorer"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-sm cedros-button-outline",onClick:y,"aria-label":"Copy wallet address",children:l?"Copied":"Copy"})]})]}),e.jsx("code",{className:"cedros-wallet-status-pubkey-value",title:s,children:j}),u&&e.jsx("p",{className:"cedros-input-hint",role:"status",children:u})]})}function Dr({status:s,publicKey:t,onLock:r,onEnroll:a,onUnlock:n,onRecover:o,showActions:c=!0,compact:l=!1,className:d=""}){const u=s!==void 0,g=N.useWallet(),m=u?s:g.status,h=u?t??null:g.solanaPubkey,b=u?null:g.error,f=u?()=>{}:g.refresh,p=u?()=>{}:g.clearError,x=Oa(m,b);return l?e.jsxs("div",{className:`cedros-wallet-status cedros-wallet-status-compact ${d}`,children:[e.jsx("span",{className:`cedros-wallet-status-dot cedros-wallet-status-${x.color}`,title:x.label}),e.jsx("span",{className:"cedros-wallet-status-label",children:x.label}),h&&e.jsx("span",{className:"cedros-wallet-status-pubkey",title:h,children:qa(h)})]}):e.jsxs("div",{className:`cedros-wallet-status ${d}`,children:[e.jsxs("div",{className:"cedros-wallet-status-header",children:[e.jsx("div",{className:`cedros-wallet-status-icon cedros-wallet-status-icon-${x.color}`,children:e.jsx(Wa,{status:m})}),e.jsxs("div",{className:"cedros-wallet-status-info",children:[e.jsx("h4",{className:"cedros-wallet-status-title",children:x.title}),e.jsx("p",{className:"cedros-wallet-status-description",children:x.description})]})]}),h&&e.jsx("div",{className:"cedros-wallet-status-pubkey-full",children:e.jsx(Mr,{address:h})}),b&&e.jsxs("div",{className:"cedros-wallet-status-error-box",role:"alert",children:[e.jsx("p",{children:b}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-sm cedros-button-secondary",onClick:p,children:"Dismiss"})]}),c&&e.jsxs("div",{className:"cedros-wallet-status-actions",children:[m==="not_enrolled"&&a&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary cedros-button-sm",onClick:a,children:"Create Wallet"}),m==="enrolled_locked"&&n&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary cedros-button-sm",onClick:n,children:"Unlock Wallet"}),(m==="not_enrolled"||m==="error")&&o&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:o,children:"Recover Wallet"}),m==="error"&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:f,children:"Retry"})]})]})}function Oa(s,t){switch(s){case"loading":return{label:"Loading",title:"Checking Wallet",description:"Verifying wallet status...",color:"loading"};case"not_enrolled":return{label:"Not Set Up",title:"No Wallet",description:"Create a wallet to start using Solana.",color:"muted"};case"enrolled_locked":return{label:"Locked",title:"Wallet Locked",description:"Unlock your wallet to sign transactions.",color:"warning"};case"enrolled_unlocked":case"unlocked":return{label:"Ready",title:"Wallet Ready",description:"Your wallet is unlocked and ready to use.",color:"success"};case"error":default:return{label:"Error",title:"Wallet Error",description:t??"An error occurred with your wallet.",color:"error"}}}function qa(s){return s.length<=12?s:`${s.slice(0,4)}...${s.slice(-4)}`}function Wa({status:s}){switch(s){case"loading":return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",className:"cedros-spinner",children:[e.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),e.jsx("path",{d:"M12 3a9 9 0 0 1 9 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]});case"not_enrolled":return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M8 12h8M12 8v8"})]});case"enrolled_locked":return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),e.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]});case"enrolled_unlocked":case"unlocked":return e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"M20 6L9 17l-5-5"})});case"error":return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),e.jsx("path",{d:"M12 9v4M12 17h.01"})]});default:return null}}function $a({className:s="",showActions:t=!0}){const r=N.useWallet(),[a,n]=i.useState("status"),o=i.useMemo(()=>{switch(a){case"enroll":return{title:"Create Wallet",description:"Set up your embedded wallet."};case"unlock":return{title:"Unlock Wallet",description:"Unlock to sign transactions."};case"recover_intro":case"recover":return{title:"Recover Wallet",description:"Restore access using your recovery phrase."};case"status":default:return null}},[a]),c=i.useCallback(()=>n("status"),[]),l=i.useCallback(async()=>{n("status"),await r.refresh()},[r]),d=i.useCallback(async()=>{n("status"),await r.refresh()},[r]),u=i.useCallback(async()=>{n("status"),await r.refresh()},[r]);return e.jsxs("div",{className:`cedros-wallet-manager ${s}`,children:[a!=="status"&&o&&e.jsxs("div",{className:"cedros-wallet-manager-header",children:[e.jsxs("div",{className:"cedros-wallet-manager-header-text",children:[e.jsx("h3",{className:"cedros-wallet-manager-title",children:o.title}),e.jsx("p",{className:"cedros-wallet-manager-subtitle",children:o.description})]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-sm cedros-button-ghost",onClick:c,children:"Back"})]}),a==="status"&&e.jsx(Dr,{onEnroll:()=>n("enroll"),onUnlock:()=>n("unlock"),onRecover:()=>n("recover_intro"),showActions:t}),a==="enroll"&&e.jsx(Sr,{onComplete:()=>{l()},onCancel:c}),a==="unlock"&&e.jsx(Tr,{onUnlock:()=>{d()},onCancel:c}),a==="recover_intro"&&e.jsx("div",{className:"cedros-wallet-manager-intro",children:e.jsxs("div",{className:"cedros-wallet-manager-intro-card",children:[e.jsx("h4",{className:"cedros-wallet-manager-intro-title",children:"Before you start"}),e.jsxs("ul",{className:"cedros-wallet-manager-intro-list",children:[e.jsx("li",{children:"You’ll need your 12-word recovery phrase."}),e.jsx("li",{children:"You’ll set a new password or passkey for this wallet."}),e.jsx("li",{children:"If you’re on a shared device, avoid copying the phrase into other apps."})]}),e.jsxs("div",{className:"cedros-wallet-manager-intro-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:()=>n("recover"),children:"Start recovery"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:c,children:"Cancel"})]})]})}),a==="recover"&&e.jsx(Lr,{onComplete:()=>{u()},onCancel:c})]})}class za{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async getSettings(){try{return await this.client.get("/admin/settings")}catch(t){throw N.handleApiError(t,"Failed to fetch system settings")}}async updateSettings(t){try{return await this.client.patch("/admin/settings",{settings:t})}catch(r){throw N.handleApiError(r,"Failed to update system settings")}}}function Re(){const{config:s,authState:t,_internal:r}=N.useCedrosLogin(),[a,n]=i.useState({}),[o,c]=i.useState(!1),[l,d]=i.useState(!1),[u,g]=i.useState(null),m=i.useRef(0),h=i.useMemo(()=>new za(s.serverUrl,s.requestTimeout,s.retryAttempts,r?.getAccessToken),[s.serverUrl,s.requestTimeout,s.retryAttempts,r]),b=i.useRef(h);b.current=h;const f=i.useCallback(async()=>{if(t!=="authenticated"){n({});return}c(!0),g(null);const j=++m.current;try{const y=await b.current.getSettings();if(j!==m.current)return;n(y.settings)}catch(y){if(j!==m.current)return;g(y instanceof Error?y:new Error("Failed to fetch settings"))}finally{j===m.current&&c(!1)}},[t]),p=i.useCallback(async j=>{if(t!=="authenticated")throw new Error("Not authenticated");d(!0),g(null);try{await b.current.updateSettings(j),await f()}catch(y){const A=y instanceof Error?y:new Error("Failed to update settings");throw g(A),A}finally{d(!1)}},[t,f]),x=i.useCallback(j=>{for(const y of Object.values(a)){const A=y.find(v=>v.key===j);if(A)return A.value}},[a]);return{settings:a,isLoading:o,isUpdating:l,error:u,fetchSettings:f,updateSettings:p,getValue:x}}function Va(s){const t=Math.floor(s/86400),r=Math.floor(s%86400/3600),a=Math.floor(s%3600/60),n=s%60;return{days:t,hours:r,minutes:a,seconds:n}}function Ha(s){const{days:t,hours:r,minutes:a}=Va(s),n=[];return t>0&&n.push(`${t}d`),r>0&&n.push(`${r}h`),a>0&&n.push(`${a}m`),n.length===0&&n.push(`${s}s`),n.join(" ")}const Qa={auth_email_enabled:{key:"auth_email_enabled",label:"Enable Email Authentication",description:"Allow users to sign up and log in with email/password.",inputType:"boolean"},auth_email_require_verification:{key:"auth_email_require_verification",label:"Require Email Verification",description:"Users must verify their email address before they can log in.",inputType:"boolean"},auth_email_block_disposable:{key:"auth_email_block_disposable",label:"Block Disposable Emails",description:"Reject registrations from known disposable email providers.",inputType:"boolean"},auth_google_enabled:{key:"auth_google_enabled",label:"Enable Google Sign-In",description:"Allow users to authenticate with their Google account.",inputType:"boolean"},auth_google_client_id:{key:"auth_google_client_id",label:"Google Client ID",description:"OAuth 2.0 client ID from Google Cloud Console.",inputType:"text"},auth_google_client_secret:{key:"auth_google_client_secret",label:"Google Client Secret",description:"OAuth 2.0 client secret from Google Cloud Console.",inputType:"secret"},auth_apple_enabled:{key:"auth_apple_enabled",label:"Enable Sign in with Apple",description:"Allow users to authenticate with their Apple ID.",inputType:"boolean"},auth_apple_client_id:{key:"auth_apple_client_id",label:"Apple Services ID",description:"The Services ID configured in your Apple Developer account.",inputType:"text"},auth_apple_team_id:{key:"auth_apple_team_id",label:"Apple Team ID",description:"Your Apple Developer Team ID.",inputType:"text"},auth_apple_key_id:{key:"auth_apple_key_id",label:"Apple Key ID",description:"The Key ID for your Sign in with Apple private key.",inputType:"text"},auth_apple_private_key:{key:"auth_apple_private_key",label:"Apple Private Key",description:"The private key file contents (PEM format) for Sign in with Apple.",inputType:"secret",multiline:!0},auth_solana_enabled:{key:"auth_solana_enabled",label:"Enable Solana Wallet Auth",description:"Allow users to authenticate by signing with their Solana wallet.",inputType:"boolean"},auth_solana_challenge_expiry:{key:"auth_solana_challenge_expiry",label:"Challenge Expiry",description:"How long a wallet signature challenge is valid.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"10 minutes",value:"600"}]},auth_webauthn_enabled:{key:"auth_webauthn_enabled",label:"Enable WebAuthn/Passkeys",description:"Allow passwordless authentication with FIDO2/WebAuthn credentials.",inputType:"boolean"},auth_webauthn_rp_id:{key:"auth_webauthn_rp_id",label:"Relying Party ID",description:"Usually your domain (e.g., example.com). Passkeys are bound to this.",inputType:"text"},auth_webauthn_rp_name:{key:"auth_webauthn_rp_name",label:"Relying Party Name",description:"Display name shown to users during passkey registration.",inputType:"text"},auth_webauthn_rp_origin:{key:"auth_webauthn_rp_origin",label:"Allowed Origins",description:"Comma-separated origins allowed for WebAuthn (e.g., https://example.com).",inputType:"text"},feature_privacy_cash:{key:"feature_privacy_cash",label:"Privacy Cash",description:"Enable Privacy Cash deposits and timed withdrawals.",inputType:"boolean"},feature_wallet_signing:{key:"feature_wallet_signing",label:"Embedded Wallet Signing",description:"Enable the embedded wallet for transaction signing.",inputType:"boolean"},feature_sso:{key:"feature_sso",label:"Enterprise SSO",description:"Enable SAML/OIDC single sign-on for enterprise customers.",inputType:"boolean"},feature_organizations:{key:"feature_organizations",label:"Organizations",description:"Enable multi-user organizations with role-based access.",inputType:"boolean"},feature_mfa:{key:"feature_mfa",label:"Two-Factor Authentication",description:"Allow users to enable TOTP-based two-factor authentication.",inputType:"boolean"},feature_instant_link:{key:"feature_instant_link",label:"Instant Link Login",description:"Allow passwordless login via magic link sent to email.",inputType:"boolean"},security_cors_origins:{key:"security_cors_origins",label:"CORS Origins",description:"Allowed origins for cross-origin requests (comma-separated). Empty = same origin only.",inputType:"text"},security_cookie_domain:{key:"security_cookie_domain",label:"Cookie Domain",description:"Domain for auth cookies. Empty uses the request origin.",inputType:"text"},security_cookie_secure:{key:"security_cookie_secure",label:"Secure Cookies",description:"Require HTTPS for cookies. Disable only for local development.",inputType:"boolean"},security_cookie_same_site:{key:"security_cookie_same_site",label:"Cookie SameSite",description:'SameSite policy for cookies. Use "none" only if needed for cross-site embeds.',inputType:"select",presets:[{label:"Strict",value:"strict"},{label:"Lax (Recommended)",value:"lax"},{label:"None (cross-site)",value:"none"}]},security_session_timeout:{key:"security_session_timeout",label:"Session Timeout",description:"How long sessions remain valid before requiring re-authentication.",inputType:"duration",min:300,presets:[{label:"1 hour",value:"3600"},{label:"24 hours",value:"86400"},{label:"7 days",value:"604800"},{label:"30 days",value:"2592000"}]},security_jwt_issuer:{key:"security_jwt_issuer",label:"JWT Issuer",description:"Issuer claim for JWTs. Empty uses the server URL.",inputType:"text"},security_jwt_audience:{key:"security_jwt_audience",label:"JWT Audience",description:"Audience claim for JWTs. Empty uses default.",inputType:"text"},email_smtp_host:{key:"email_smtp_host",label:"SMTP Host",description:"SMTP server hostname (e.g., smtp.sendgrid.net).",inputType:"text"},email_smtp_port:{key:"email_smtp_port",label:"SMTP Port",description:"SMTP server port. Common: 587 (TLS), 465 (SSL), 25 (unencrypted).",inputType:"select",presets:[{label:"587 (TLS)",value:"587"},{label:"465 (SSL)",value:"465"},{label:"25 (Plain)",value:"25"}]},email_smtp_user:{key:"email_smtp_user",label:"SMTP Username",description:"Username for SMTP authentication.",inputType:"text"},email_smtp_password:{key:"email_smtp_password",label:"SMTP Password",description:"Password or API key for SMTP authentication.",inputType:"secret"},email_smtp_tls:{key:"email_smtp_tls",label:"Use TLS",description:"Enable TLS encryption for SMTP connections.",inputType:"boolean"},email_from_address:{key:"email_from_address",label:"From Address",description:"Default sender email address (e.g., noreply@example.com).",inputType:"text"},email_from_name:{key:"email_from_name",label:"From Name",description:'Default sender display name (e.g., "My App").',inputType:"text"},webhook_enabled:{key:"webhook_enabled",label:"Enable Webhooks",description:"Send HTTP notifications for auth events (signup, login, etc.).",inputType:"boolean"},webhook_url:{key:"webhook_url",label:"Webhook URL",description:"Endpoint to receive webhook POST requests.",inputType:"text"},webhook_secret:{key:"webhook_secret",label:"Webhook Secret",description:"Secret used to sign webhook payloads (HMAC-SHA256).",inputType:"secret"},webhook_timeout:{key:"webhook_timeout",label:"Timeout",description:"Maximum time to wait for webhook response.",inputType:"duration",min:5,presets:[{label:"10 seconds",value:"10"},{label:"30 seconds",value:"30"},{label:"60 seconds",value:"60"}]},webhook_retries:{key:"webhook_retries",label:"Max Retries",description:"Number of retry attempts for failed webhooks.",inputType:"select",presets:[{label:"0 (No retries)",value:"0"},{label:"3 (Recommended)",value:"3"},{label:"5",value:"5"}]},server_frontend_url:{key:"server_frontend_url",label:"Frontend URL",description:"URL of your frontend app (for redirects and email links).",inputType:"text"},server_base_path:{key:"server_base_path",label:"Base Path",description:"Base path for auth endpoints (e.g., /auth).",inputType:"text"},server_trust_proxy:{key:"server_trust_proxy",label:"Trust Proxy",description:"Trust X-Forwarded-For headers. Enable if behind a reverse proxy.",inputType:"boolean"},privacy_period_secs:{key:"privacy_period_secs",label:"Privacy Period",description:"How long deposits are held before withdrawal to provide timing privacy. Longer periods provide better privacy but delay user access to funds.",inputType:"duration",min:0,presets:[{label:"Disabled",value:"0"},{label:"1 hour",value:"3600"},{label:"6 hours",value:"21600"},{label:"24 hours",value:"86400"},{label:"7 days",value:"604800"},{label:"14 days",value:"1209600"},{label:"30 days",value:"2592000"}],warningThreshold:{below:3600,message:"Very short privacy periods may not provide adequate timing protection."}},withdrawal_poll_interval_secs:{key:"withdrawal_poll_interval_secs",label:"Worker Poll Interval",description:"How often the withdrawal worker checks for deposits ready to process. Lower values process faster but increase server load.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"},{label:"1 hour",value:"3600"},{label:"6 hours",value:"21600"}],warningThreshold:{below:60,message:"Polling more than once per minute may cause excessive load."}},withdrawal_batch_size:{key:"withdrawal_batch_size",label:"Batch Size",description:"Maximum number of withdrawals to process in a single batch. Higher values improve throughput but may cause timeouts.",inputType:"select",min:1,max:100,presets:[{label:"1 (Sequential)",value:"1"},{label:"5",value:"5"},{label:"10 (Recommended)",value:"10"},{label:"25",value:"25"},{label:"50",value:"50"},{label:"100 (Max)",value:"100"}]},withdrawal_timeout_secs:{key:"withdrawal_timeout_secs",label:"Transaction Timeout",description:"How long to wait for a withdrawal transaction to confirm before considering it failed.",inputType:"duration",min:30,presets:[{label:"30 seconds",value:"30"},{label:"1 minute",value:"60"},{label:"2 minutes",value:"120"},{label:"5 minutes",value:"300"}],warningThreshold:{below:30,message:"Very short timeouts may cause premature failure on slow networks."}},withdrawal_max_retries:{key:"withdrawal_max_retries",label:"Max Retries",description:"Number of times to retry a failed withdrawal before marking it as permanently failed.",inputType:"select",min:0,max:10,presets:[{label:"0 (No retries)",value:"0"},{label:"1",value:"1"},{label:"3 (Recommended)",value:"3"},{label:"5",value:"5"},{label:"10",value:"10"}]},withdrawal_percentage:{key:"withdrawal_percentage",label:"Withdrawal Percentage",description:"Percentage of ready funds to withdraw each cycle. Lower values spread withdrawals over time for better privacy.",inputType:"percentage",min:1,max:100,step:5,presets:[{label:"25%",value:"25"},{label:"50%",value:"50"},{label:"75%",value:"75"},{label:"100% (All at once)",value:"100"}],warningThreshold:{above:75,message:"High percentages may reduce timing privacy by processing most withdrawals together."}},partial_withdrawal_count:{key:"partial_withdrawal_count",label:"Partial Withdrawals",description:"Maximum partial withdrawals per batch. Partial withdrawals add noise to timing analysis. Set to 0 to disable.",inputType:"select",min:0,presets:[{label:"Disabled",value:"0"},{label:"1",value:"1"},{label:"3",value:"3"},{label:"5",value:"5"},{label:"10",value:"10"}]},partial_withdrawal_min_lamports:{key:"partial_withdrawal_min_lamports",label:"Min Balance for Partial",description:"Minimum account balance (in lamports) required before partial withdrawals are considered. 1 SOL = 1,000,000,000 lamports.",inputType:"select",min:0,presets:[{label:"0.1 SOL",value:"100000000"},{label:"0.5 SOL",value:"500000000"},{label:"1 SOL",value:"1000000000"},{label:"5 SOL",value:"5000000000"},{label:"10 SOL",value:"10000000000"}]},rate_limit_auth:{key:"rate_limit_auth",label:"Auth Request Limit",description:"Maximum authentication attempts (login, register, password reset) per IP per window. Protects against brute force attacks.",inputType:"select",min:1,unit:"requests",presets:[{label:"5 (Strict)",value:"5"},{label:"10 (Recommended)",value:"10"},{label:"20",value:"20"},{label:"50 (Permissive)",value:"50"}],warningThreshold:{above:20,message:"High auth limits may allow brute force attempts."}},rate_limit_general:{key:"rate_limit_general",label:"General Request Limit",description:"Maximum general API requests per IP per window. Affects all non-auth endpoints.",inputType:"select",min:1,unit:"requests",presets:[{label:"30",value:"30"},{label:"60 (Recommended)",value:"60"},{label:"120",value:"120"},{label:"300",value:"300"}]},rate_limit_credit:{key:"rate_limit_credit",label:"Credit Request Limit",description:"Maximum credit/balance check requests per IP per window. Higher for apps that poll balance frequently.",inputType:"select",min:1,unit:"requests",presets:[{label:"10",value:"10"},{label:"30 (Recommended)",value:"30"},{label:"60",value:"60"},{label:"120",value:"120"}]},rate_limit_window:{key:"rate_limit_window",label:"Rate Limit Window",description:'Time window for rate limiting. All limits above are "per window". Shorter windows are stricter.',inputType:"duration",min:1,presets:[{label:"30 seconds",value:"30"},{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"}]},deposit_quick_action_tokens:{key:"deposit_quick_action_tokens",label:"Quick Action Tokens",description:"Comma-separated token symbols shown as quick action buttons. First token is the default.",inputType:"tokenSymbolList"},deposit_custom_tokens:{key:"deposit_custom_tokens",label:"Custom Dropdown Tokens",description:'Comma-separated token symbols shown in the "Custom" dropdown. Leave empty to show all.',inputType:"tokenSymbolList"},deposit_custom_tokens_json:{key:"deposit_custom_tokens_json",label:"Custom Token Definitions",description:"Add tokens beyond the built-in list. Define symbol, mint address, decimals, and logo URL.",inputType:"tokenList"}},Ka={"auth.apple":{label:"Apple Sign-In",description:"Configure Sign in with Apple OAuth integration.",icon:""},"auth.email":{label:"Email Authentication",description:"Configure email/password authentication settings.",icon:""},"auth.google":{label:"Google Sign-In",description:"Configure Google OAuth integration.",icon:""},"auth.solana":{label:"Solana Wallet Auth",description:"Configure Solana wallet signature authentication.",icon:""},"auth.webauthn":{label:"WebAuthn / Passkeys",description:"Configure FIDO2/WebAuthn passwordless authentication.",icon:""},deposit:{label:"Deposit Settings",description:"Configure token lists and deposit flow display options.",icon:""},email:{label:"Email / SMTP",description:"Configure outbound email delivery for verification, password reset, and notifications.",icon:""},features:{label:"Feature Flags",description:"Enable or disable major platform features.",icon:""},privacy:{label:"Privacy Settings",description:"Control the privacy period for deposits. Longer periods provide better timing privacy but delay fund availability.",icon:""},rate_limit:{label:"Rate Limiting",description:"Protect the system from abuse by limiting request rates. Balance security with user experience.",icon:""},security:{label:"Security",description:"Configure CORS, cookies, sessions, and JWT settings.",icon:""},server:{label:"Server",description:"Server infrastructure settings. Some may be overridden by environment variables.",icon:""},webhook:{label:"Webhooks",description:"Configure HTTP webhook notifications for auth events.",icon:""},withdrawal:{label:"Withdrawal Worker",description:"Configure how the automated withdrawal processor handles pending withdrawals. These settings affect throughput and privacy.",icon:""}};function Ga({showDescriptions:s=!0,className:t="",onSave:r}){const{settings:a,isLoading:n,isUpdating:o,error:c,fetchSettings:l,updateSettings:d}=Re(),[u,g]=i.useState({}),[m,h]=i.useState(null),[b,f]=i.useState(!1);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{if(b){const S=setTimeout(()=>f(!1),3e3);return()=>clearTimeout(S)}},[b]);const p=i.useCallback((S,w)=>{g(E=>({...E,[S]:w})),h(null),f(!1)},[]),x=i.useCallback(async()=>{const S=Object.entries(u).map(([w,E])=>({key:w,value:E}));if(S.length!==0)try{await d(S),g({}),h(null),f(!0),r?.()}catch(w){h(w instanceof Error?w.message:"Failed to save settings")}},[u,d,r]),j=i.useCallback(()=>{g({}),h(null),f(!1)},[]),y=Object.keys(u).length>0,A=Object.keys(u).length;if(n&&Object.keys(a).length===0)return e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${t}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]});if(c)return e.jsx("div",{className:`cedros-system-settings ${t}`,children:e.jsx(N.ErrorMessage,{error:c.message})});const v=Object.keys(a).sort();return v.length===0?e.jsx("div",{className:`cedros-system-settings cedros-system-settings-empty ${t}`,children:e.jsx("p",{children:"No system settings found."})}):e.jsxs("div",{className:`cedros-system-settings ${t}`,children:[m&&e.jsx(N.ErrorMessage,{error:m}),b&&e.jsx("div",{className:"cedros-settings-success",children:"Settings saved successfully."}),v.map(S=>e.jsx(Ya,{category:S,settings:a[S],edits:u,showDescription:s,onChange:p},S)),e.jsxs("div",{className:"cedros-system-settings-actions",children:[y&&e.jsxs("span",{className:"cedros-settings-change-count",children:[A," unsaved change",A!==1?"s":""]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:j,disabled:!y||o,children:"Reset"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:x,disabled:!y||o,children:o?e.jsx(N.LoadingSpinner,{size:"sm"}):"Save Changes"})]})]})}function Ya({category:s,settings:t,edits:r,showDescription:a,onChange:n}){const o=Ka[s]||{label:s,description:"",icon:"⚙️"};return e.jsxs("section",{className:"cedros-settings-section",children:[e.jsxs("div",{className:"cedros-settings-section-header",children:[e.jsx("span",{className:"cedros-settings-section-icon",children:o.icon}),e.jsxs("div",{children:[e.jsx("h3",{className:"cedros-settings-section-title",children:o.label}),a&&o.description&&e.jsx("p",{className:"cedros-settings-section-description",children:o.description})]})]}),e.jsx("div",{className:"cedros-settings-grid",children:t.map(c=>e.jsx(Ja,{setting:c,editValue:r[c.key],onChange:n},c.key))})]})}function Ja({setting:s,editValue:t,onChange:r}){const a=Qa[s.key],n=t??s.value,o=t!==void 0&&t!==s.value,c=i.useMemo(()=>{if(!a?.warningThreshold)return null;const l=parseInt(n,10);if(isNaN(l))return null;const{above:d,below:u,message:g}=a.warningThreshold;return d!==void 0&&l>d||u!==void 0&&l<u?g:null},[n,a?.warningThreshold]);return a?e.jsxs("div",{className:`cedros-setting-row ${o?"cedros-setting-row-changed":""} ${c?"cedros-setting-row-warning":""}`,children:[e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:a.label}),e.jsx("span",{className:"cedros-setting-description",children:a.description})]}),e.jsxs("div",{className:"cedros-setting-control",children:[a.inputType==="duration"&&e.jsx(Xa,{value:n,onChange:l=>r(s.key,l),presets:a.presets,min:a.min}),a.inputType==="percentage"&&e.jsx(Za,{value:n,onChange:l=>r(s.key,l),min:a.min??1,max:a.max??100,step:a.step??5,presets:a.presets}),a.inputType==="select"&&e.jsx(eo,{value:n,onChange:l=>r(s.key,l),presets:a.presets??[],unit:a.unit}),a.inputType==="number"&&e.jsx(so,{value:n,onChange:l=>r(s.key,l),min:a.min,max:a.max,unit:a.unit}),a.inputType==="tokenList"&&e.jsx(no,{value:n,onChange:l=>r(s.key,l)}),a.inputType==="text"&&e.jsx("input",{type:"text",value:n,onChange:l=>r(s.key,l.target.value),className:"cedros-setting-input",placeholder:a.label}),a.inputType==="boolean"&&e.jsx(to,{value:n,onChange:l=>r(s.key,l)}),a.inputType==="secret"&&e.jsx(ro,{value:n,onChange:l=>r(s.key,l),multiline:a.multiline}),a.inputType==="tokenSymbolList"&&e.jsx(ao,{value:n,onChange:l=>r(s.key,l)}),c&&e.jsx("div",{className:"cedros-setting-warning",children:c})]})]}):e.jsxs("div",{className:`cedros-setting-row ${o?"cedros-setting-row-changed":""}`,children:[e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:s.key}),s.description&&e.jsx("span",{className:"cedros-setting-description",children:s.description})]}),e.jsx("div",{className:"cedros-setting-input-wrapper",children:e.jsx("input",{type:"text",value:n,onChange:l=>r(s.key,l.target.value),className:"cedros-setting-input"})})]})}function Xa({value:s,onChange:t,presets:r,min:a=0}){const n=parseInt(s,10)||0,o=Ha(n),c=i.useCallback(d=>{d.target.value&&t(d.target.value)},[t]),l=i.useCallback(d=>{const u=Math.max(a,parseInt(d.target.value,10)||0);t(String(u))},[t,a]);return e.jsxs("div",{className:"cedros-duration-input",children:[r&&r.length>0&&e.jsxs("select",{value:r.find(d=>d.value===s)?.value??"",onChange:c,className:"cedros-setting-select",children:[e.jsx("option",{value:"",children:"Custom..."}),r.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))]}),e.jsxs("div",{className:"cedros-duration-custom",children:[e.jsx("input",{type:"number",value:n,onChange:l,min:a,className:"cedros-setting-input cedros-setting-input-sm"}),e.jsx("span",{className:"cedros-setting-unit",children:"seconds"}),e.jsxs("span",{className:"cedros-duration-display",children:["= ",o]})]})]})}function Za({value:s,onChange:t,min:r,max:a,step:n,presets:o}){const c=parseInt(s,10)||r,l=i.useCallback(u=>{t(u.target.value)},[t]),d=i.useCallback(u=>{t(u)},[t]);return e.jsxs("div",{className:"cedros-percentage-input",children:[e.jsxs("div",{className:"cedros-percentage-slider-row",children:[e.jsx("input",{type:"range",value:c,onChange:l,min:r,max:a,step:n,className:"cedros-percentage-slider"}),e.jsxs("span",{className:"cedros-percentage-value",children:[c,"%"]})]}),o&&o.length>0&&e.jsx("div",{className:"cedros-preset-buttons",children:o.map(u=>e.jsx("button",{type:"button",className:`cedros-preset-button ${u.value===s?"cedros-preset-button-active":""}`,onClick:()=>d(u.value),children:u.label},u.value))})]})}function eo({value:s,onChange:t,presets:r,unit:a}){const n=!r.some(l=>l.value===s),o=i.useCallback(l=>{l.target.value!=="__custom__"&&t(l.target.value)},[t]),c=i.useCallback(l=>{t(l.target.value)},[t]);return e.jsxs("div",{className:"cedros-select-input",children:[e.jsxs("select",{value:n?"__custom__":s,onChange:o,className:"cedros-setting-select",children:[r.map(l=>e.jsx("option",{value:l.value,children:l.label},l.value)),e.jsx("option",{value:"__custom__",children:"Custom..."})]}),n&&e.jsxs("div",{className:"cedros-select-custom",children:[e.jsx("input",{type:"number",value:s,onChange:c,className:"cedros-setting-input cedros-setting-input-sm"}),a&&e.jsx("span",{className:"cedros-setting-unit",children:a})]})]})}function so({value:s,onChange:t,min:r,max:a,unit:n}){const o=i.useCallback(c=>{t(c.target.value)},[t]);return e.jsxs("div",{className:"cedros-number-input",children:[e.jsx("input",{type:"number",value:s,onChange:o,min:r,max:a,className:"cedros-setting-input"}),n&&e.jsx("span",{className:"cedros-setting-unit",children:n})]})}function to({value:s,onChange:t}){const r=s==="true",a=i.useCallback(()=>{t(r?"false":"true")},[r,t]);return e.jsxs("button",{type:"button",role:"switch","aria-checked":r,className:`cedros-toggle ${r?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:a,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:r?"Enabled":"Disabled"})]})}function ro({value:s,onChange:t,multiline:r}){const[a,n]=i.useState(!1),[o,c]=i.useState(!1),l=s&&s.length>0,d=i.useCallback(()=>{n(!0),c(!0)},[]),u=i.useCallback(()=>{n(!1),c(!1)},[]),g=i.useCallback(m=>{t(m.target.value)},[t]);return!a&&l?e.jsxs("div",{className:"cedros-secret-input cedros-secret-input-masked",children:[e.jsx("span",{className:"cedros-secret-masked",children:"•".repeat(Math.min(s.length,20))}),e.jsx("button",{type:"button",className:"cedros-secret-edit-btn",onClick:d,children:"Edit"})]}):e.jsxs("div",{className:"cedros-secret-input",children:[r?e.jsx("textarea",{value:s,onChange:g,className:"cedros-setting-input cedros-setting-textarea",placeholder:"Enter secret value...",rows:4}):e.jsx("input",{type:o?"text":"password",value:s,onChange:g,className:"cedros-setting-input",placeholder:"Enter secret value..."}),e.jsxs("div",{className:"cedros-secret-actions",children:[!r&&e.jsx("button",{type:"button",className:"cedros-secret-toggle-btn",onClick:()=>c(!o),children:o?"Hide":"Show"}),a&&e.jsx("button",{type:"button",className:"cedros-secret-done-btn",onClick:u,children:"Done"})]})]})}const Rr=["SOL","USDC","USDT","EURC","USD1","PYUSD","USDH","CASH","BONK","ORE"];function no({value:s,onChange:t}){const r=i.useMemo(()=>{try{return JSON.parse(s||"[]")}catch{return[]}},[s]),a=i.useCallback(l=>{t(JSON.stringify(l))},[t]),n=i.useCallback(()=>{a([...r,{symbol:"",mint:"",decimals:6}])},[r,a]),o=i.useCallback((l,d,u)=>{const g=[...r];g[l]={...g[l],[d]:u},a(g)},[r,a]),c=i.useCallback(l=>{a(r.filter((d,u)=>u!==l))},[r,a]);return e.jsxs("div",{className:"cedros-token-list-input",children:[e.jsxs("div",{className:"cedros-token-presets",children:[e.jsx("span",{className:"cedros-token-presets-label",children:"Built-in tokens:"}),e.jsx("div",{className:"cedros-token-presets-list",children:Rr.map(l=>e.jsx("span",{className:"cedros-token-preset-chip",children:l},l))})]}),r.length===0&&e.jsx("p",{className:"cedros-token-list-empty",children:"No custom tokens added. Use the built-in tokens above or add your own."}),r.map((l,d)=>e.jsxs("div",{className:"cedros-token-row",children:[e.jsxs("div",{className:"cedros-token-row-fields",children:[e.jsx("input",{type:"text",placeholder:"Symbol",value:l.symbol,onChange:u=>o(d,"symbol",u.target.value.toUpperCase()),className:"cedros-setting-input cedros-token-input-symbol",maxLength:10}),e.jsx("input",{type:"text",placeholder:"Mint address",value:l.mint,onChange:u=>o(d,"mint",u.target.value),className:"cedros-setting-input cedros-token-input-mint"}),e.jsx("input",{type:"number",placeholder:"Decimals",value:l.decimals,onChange:u=>o(d,"decimals",parseInt(u.target.value,10)||0),className:"cedros-setting-input cedros-token-input-decimals",min:0,max:18}),e.jsx("input",{type:"text",placeholder:"Logo URL (optional)",value:l.logoUrl||"",onChange:u=>o(d,"logoUrl",u.target.value||void 0),className:"cedros-setting-input cedros-token-input-logo"})]}),e.jsx("button",{type:"button",className:"cedros-token-remove-btn",onClick:()=>c(d),title:"Remove token",children:"×"})]},d)),e.jsx("button",{type:"button",className:"cedros-token-add-btn",onClick:n,children:"+ Add Token"})]})}function ao({value:s,onChange:t}){const r=i.useMemo(()=>s.split(",").map(o=>o.trim()).filter(Boolean),[s]),a=i.useCallback(o=>{if(!o||r.includes(o))return;const c=[...r,o].join(", ");t(c)},[r,t]),n=i.useCallback(o=>{const c=r.filter(l=>l!==o).join(", ");t(c)},[r,t]);return e.jsxs("div",{className:"cedros-token-symbol-list-input",children:[e.jsxs("div",{className:"cedros-token-presets",children:[e.jsx("span",{className:"cedros-token-presets-label",children:"Click to add:"}),e.jsx("div",{className:"cedros-token-presets-list",children:Rr.map(o=>{const c=r.includes(o);return e.jsxs("button",{type:"button",className:`cedros-token-preset-chip ${c?"cedros-token-preset-chip-selected":""}`,onClick:()=>c?n(o):a(o),title:c?`Remove ${o}`:`Add ${o}`,children:[o,c&&e.jsx("span",{className:"cedros-token-chip-check",children:"✓"})]},o)})})]}),e.jsx("input",{type:"text",value:s,onChange:o=>t(o.target.value),className:"cedros-setting-input",placeholder:"USDC, SOL, BONK..."})]})}class oo{client;constructor(t,r,a){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a})}async getStatus(){try{return await this.client.get("/setup/status")}catch(t){throw N.handleApiError(t,"Failed to check setup status")}}async createFirstAdmin(t){try{return await this.client.post("/setup/admin",t)}catch(r){throw N.handleApiError(r,"Failed to create admin account")}}}function Ks(){const{config:s}=N.useCedrosLogin(),[t,r]=i.useState(null),[a,n]=i.useState(!1),[o,c]=i.useState(!1),[l,d]=i.useState(null),u=i.useRef(0),g=i.useMemo(()=>new oo(s.serverUrl,s.requestTimeout,s.retryAttempts),[s.serverUrl,s.requestTimeout,s.retryAttempts]),m=i.useRef(g);m.current=g;const h=i.useCallback(async()=>{n(!0),d(null);const f=++u.current;try{const p=await m.current.getStatus();if(f!==u.current)return;r(p)}catch(p){if(f!==u.current)return;d(p instanceof Error?p:new Error("Failed to check setup status"))}finally{f===u.current&&n(!1)}},[]),b=i.useCallback(async f=>{c(!0),d(null);try{const p=await m.current.createFirstAdmin(f);return await h(),p}catch(p){const x=p instanceof Error?p:new Error("Failed to create admin");throw d(x),x}finally{c(!1)}},[h]);return{status:t,isLoading:a,isCreating:o,error:l,checkStatus:h,createAdmin:b}}const io=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,ht=8;function lo(s){const t={};return s.email?io.test(s.email)||(t.email="Invalid email format"):t.email="Email is required",s.password?s.password.length<ht&&(t.password=`Password must be at least ${ht} characters`):t.password="Password is required",s.confirmPassword?s.password!==s.confirmPassword&&(t.confirmPassword="Passwords do not match"):t.confirmPassword="Please confirm your password",t}function Ir({onComplete:s,className:t=""}){const{status:r,isLoading:a,isCreating:n,error:o,checkStatus:c,createAdmin:l}=Ks(),[d,u]=i.useState({email:"",password:"",confirmPassword:"",name:"",orgName:""}),[g,m]=i.useState({}),[h,b]=i.useState(!1);i.useEffect(()=>{c()},[c]);const f=i.useCallback(x=>j=>{u(y=>({...y,[x]:j.target.value})),m(y=>({...y,[x]:void 0}))},[]),p=i.useCallback(async x=>{x.preventDefault();const j=lo(d);if(Object.keys(j).length>0){m(j);return}try{await l({email:d.email,password:d.password,name:d.name||void 0,orgName:d.orgName||void 0}),b(!0),s?.()}catch{}},[d,l,s]);return a?e.jsx("div",{className:`cedros-setup ${t}`,children:e.jsxs("div",{className:"cedros-setup__loading",children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{className:"cedros-setup__loading-text",children:"Checking setup status..."})]})}):r&&!r.needsSetup?e.jsx("div",{className:`cedros-setup ${t}`,children:e.jsxs("div",{className:"cedros-setup__complete",children:[e.jsx("div",{className:"cedros-setup__icon cedros-setup__icon--success",children:e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),e.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}),e.jsx("h2",{className:"cedros-setup__title",children:"Setup Complete"}),e.jsx("p",{className:"cedros-setup__text",children:"An admin account already exists. You can now log in."})]})}):h?e.jsx("div",{className:`cedros-setup ${t}`,children:e.jsxs("div",{className:"cedros-setup__complete",children:[e.jsx("div",{className:"cedros-setup__icon cedros-setup__icon--success",children:e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),e.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}),e.jsx("h2",{className:"cedros-setup__title",children:"Admin Account Created"}),e.jsx("p",{className:"cedros-setup__text",children:"Your admin account has been created successfully. You can now log in with your credentials."})]})}):e.jsx("div",{className:`cedros-setup ${t}`,children:e.jsxs("div",{className:"cedros-setup__container",children:[e.jsxs("div",{className:"cedros-setup__header",children:[e.jsx("div",{className:"cedros-setup__logo",children:e.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),e.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]})}),e.jsx("h1",{className:"cedros-setup__title",children:"Welcome to Cedros"}),e.jsx("p",{className:"cedros-setup__subtitle",children:"Let's set up your admin account to get started."})]}),e.jsxs("form",{className:"cedros-setup__form",onSubmit:p,children:[o&&e.jsx(N.ErrorMessage,{error:o.message}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsxs("label",{htmlFor:"setup-email",className:"cedros-setup__label",children:["Email Address ",e.jsx("span",{className:"cedros-setup__required",children:"*"})]}),e.jsx("input",{id:"setup-email",type:"email",className:`cedros-setup__input ${g.email?"cedros-setup__input--error":""}`,value:d.email,onChange:f("email"),placeholder:"admin@example.com",autoComplete:"email",autoFocus:!0,disabled:n}),g.email&&e.jsx("span",{className:"cedros-setup__error",children:g.email})]}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsx("label",{htmlFor:"setup-name",className:"cedros-setup__label",children:"Display Name"}),e.jsx("input",{id:"setup-name",type:"text",className:"cedros-setup__input",value:d.name,onChange:f("name"),placeholder:"Admin",autoComplete:"name",disabled:n})]}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsx("label",{htmlFor:"setup-org-name",className:"cedros-setup__label",children:"Organization Name"}),e.jsx("input",{id:"setup-org-name",type:"text",className:"cedros-setup__input",value:d.orgName,onChange:f("orgName"),placeholder:"My Organization",disabled:n})]}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsxs("label",{htmlFor:"setup-password",className:"cedros-setup__label",children:["Password ",e.jsx("span",{className:"cedros-setup__required",children:"*"})]}),e.jsx("input",{id:"setup-password",type:"password",className:`cedros-setup__input ${g.password?"cedros-setup__input--error":""}`,value:d.password,onChange:f("password"),placeholder:"At least 8 characters",autoComplete:"new-password",disabled:n}),g.password&&e.jsx("span",{className:"cedros-setup__error",children:g.password})]}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsxs("label",{htmlFor:"setup-confirm-password",className:"cedros-setup__label",children:["Confirm Password ",e.jsx("span",{className:"cedros-setup__required",children:"*"})]}),e.jsx("input",{id:"setup-confirm-password",type:"password",className:`cedros-setup__input ${g.confirmPassword?"cedros-setup__input--error":""}`,value:d.confirmPassword,onChange:f("confirmPassword"),placeholder:"Confirm your password",autoComplete:"new-password",disabled:n}),g.confirmPassword&&e.jsx("span",{className:"cedros-setup__error",children:g.confirmPassword})]}),e.jsx("button",{type:"submit",className:"cedros-setup__button",disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Creating Account..."})]}):"Create Admin Account"})]}),e.jsxs("div",{className:"cedros-setup__footer",children:[e.jsx("p",{className:"cedros-setup__note",children:"This will be the first administrator account for your installation."}),r?.serverVersion&&e.jsxs("p",{className:"cedros-setup__version",children:["Server version: ",r.serverVersion]})]})]})})}const co=800,uo=2e3;function Ee(){const{settings:s,isLoading:t,error:r,fetchSettings:a,updateSettings:n}=Re(),[o,c]=i.useState({}),[l,d]=i.useState("idle"),[u,g]=i.useState(null),m=i.useRef(null),h=i.useRef(null),b=i.useRef({});i.useEffect(()=>()=>{m.current&&clearTimeout(m.current),h.current&&clearTimeout(h.current)},[]);const f=i.useCallback(async()=>{const j={...b.current};if(Object.keys(j).length===0){d("idle");return}d("saving"),g(null);const y=Object.entries(j).map(([A,v])=>({key:A,value:v}));try{await n(y),c(A=>{const v={...A};for(const S of Object.keys(j))delete v[S];return v});for(const A of Object.keys(j))delete b.current[A];d("saved"),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{d("idle")},uo)}catch(A){d("error"),g(A instanceof Error?A.message:"Failed to save")}},[n]),p=i.useCallback((j,y)=>{c(A=>({...A,[j]:y})),b.current[j]=y,g(null),d("pending"),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{f()},co)},[f]),x=i.useCallback(j=>{if(o[j]!==void 0)return o[j];for(const y of Object.values(s)){const A=y.find(v=>v.key===j);if(A)return A.value}return""},[o,s]);return{settings:s,edits:o,isLoading:t,autosaveStatus:l,autosaveError:u,error:r,fetchSettings:a,handleChange:p,getEffectiveValue:x}}function ho(s){const t=Math.floor(s/86400),r=Math.floor(s%86400/3600),a=Math.floor(s%3600/60),n=s%60;return{days:t,hours:r,minutes:a,seconds:n}}function mo(s){const{days:t,hours:r,minutes:a}=ho(s),n=[];return t>0&&n.push(`${t}d`),r>0&&n.push(`${r}h`),a>0&&n.push(`${a}m`),n.length===0&&n.push(`${s}s`),n.join(" ")}const po={auth_email_enabled:{key:"auth_email_enabled",label:"Enable Email Authentication",description:"Allow users to sign up and log in with email/password.",inputType:"boolean"},auth_email_require_verification:{key:"auth_email_require_verification",label:"Require Email Verification",description:"Users must verify their email address before they can log in.",inputType:"boolean"},auth_email_block_disposable:{key:"auth_email_block_disposable",label:"Block Disposable Emails",description:"Reject registrations from known disposable email providers.",inputType:"boolean"},auth_google_enabled:{key:"auth_google_enabled",label:"Enable Google Sign-In",description:"Allow users to authenticate with their Google account.",inputType:"boolean"},auth_google_client_id:{key:"auth_google_client_id",label:"Google Client ID",description:"OAuth 2.0 client ID from Google Cloud Console.",inputType:"text"},auth_google_client_secret:{key:"auth_google_client_secret",label:"Google Client Secret",description:"OAuth 2.0 client secret from Google Cloud Console.",inputType:"secret"},auth_apple_enabled:{key:"auth_apple_enabled",label:"Enable Sign in with Apple",description:"Allow users to authenticate with their Apple ID.",inputType:"boolean"},auth_apple_client_id:{key:"auth_apple_client_id",label:"Apple Services ID",description:"The Services ID configured in your Apple Developer account.",inputType:"text"},auth_apple_team_id:{key:"auth_apple_team_id",label:"Apple Team ID",description:"Your Apple Developer Team ID.",inputType:"text"},auth_apple_key_id:{key:"auth_apple_key_id",label:"Apple Key ID",description:"The Key ID for your Sign in with Apple private key.",inputType:"text"},auth_apple_private_key:{key:"auth_apple_private_key",label:"Apple Private Key",description:"The private key file contents (PEM format) for Sign in with Apple.",inputType:"secret",multiline:!0},auth_solana_enabled:{key:"auth_solana_enabled",label:"Enable Solana Wallet Auth",description:"Allow users to authenticate by signing with their Solana wallet.",inputType:"boolean"},auth_solana_challenge_expiry:{key:"auth_solana_challenge_expiry",label:"Challenge Expiry",description:"How long a wallet signature challenge is valid.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"10 minutes",value:"600"}]},auth_webauthn_enabled:{key:"auth_webauthn_enabled",label:"Enable WebAuthn/Passkeys",description:"Allow passwordless authentication with FIDO2/WebAuthn credentials.",inputType:"boolean"},auth_webauthn_rp_id:{key:"auth_webauthn_rp_id",label:"Relying Party ID",description:"Usually your domain (e.g., example.com). Passkeys are bound to this.",inputType:"text"},auth_webauthn_rp_name:{key:"auth_webauthn_rp_name",label:"Relying Party Name",description:"Display name shown to users during passkey registration.",inputType:"text"},auth_webauthn_rp_origin:{key:"auth_webauthn_rp_origin",label:"Allowed Origins",description:"Comma-separated origins allowed for WebAuthn (e.g., https://example.com).",inputType:"text"},auth_instantlink_enabled:{key:"auth_instantlink_enabled",label:"Enable Instant Link",description:"Allow passwordless login via magic link sent to email.",inputType:"boolean"},auth_instantlink_expiry:{key:"auth_instantlink_expiry",label:"Link Expiry",description:"How long the magic link remains valid.",inputType:"duration",min:60,presets:[{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"},{label:"30 minutes",value:"1800"},{label:"1 hour",value:"3600"}]},auth_instantlink_rate_limit:{key:"auth_instantlink_rate_limit",label:"Rate Limit",description:"Maximum instant link requests per email per hour.",inputType:"select",presets:[{label:"3 per hour",value:"3"},{label:"5 per hour",value:"5"},{label:"10 per hour",value:"10"}]},feature_organizations:{key:"feature_organizations",label:"Organizations",description:"Enable multi-user organizations with role-based access.",inputType:"boolean"},feature_sso:{key:"feature_sso",label:"Enterprise SSO",description:"Enable SAML/OIDC single sign-on for enterprise customers.",inputType:"boolean"},feature_mfa:{key:"feature_mfa",label:"Two-Factor Authentication",description:"Allow users to enable TOTP-based two-factor authentication.",inputType:"boolean"},feature_wallet_signing:{key:"feature_wallet_signing",label:"Enable Embedded Wallet",description:"Enable the embedded wallet for transaction signing.",inputType:"boolean"},wallet_recovery_mode:{key:"wallet_recovery_mode",label:"Recovery Mode",description:"How users can recover their wallet if they lose access.",inputType:"select",presets:[{label:"Share C Only (Recommended)",value:"share_c_only"},{label:"Full Seed Phrase",value:"full_seed"},{label:"No Recovery",value:"none"}]},feature_credits:{key:"feature_credits",label:"Credit System",description:"Enable the deposits and credits system. Users can deposit tokens to receive platform credits.",inputType:"boolean"},security_cors_origins:{key:"security_cors_origins",label:"CORS Origins",description:"Allowed origins for cross-origin requests (comma-separated). Empty = same origin only.",inputType:"text"},security_cookie_domain:{key:"security_cookie_domain",label:"Cookie Domain",description:"Domain for auth cookies. Empty uses the request origin.",inputType:"text"},security_cookie_secure:{key:"security_cookie_secure",label:"Secure Cookies",description:"Require HTTPS for cookies. Disable only for local development.",inputType:"boolean"},security_cookie_same_site:{key:"security_cookie_same_site",label:"Cookie SameSite",description:'SameSite policy for cookies. Use "none" only if needed for cross-site embeds.',inputType:"select",presets:[{label:"Strict",value:"strict"},{label:"Lax (Recommended)",value:"lax"},{label:"None (cross-site)",value:"none"}]},security_session_timeout:{key:"security_session_timeout",label:"Session Timeout",description:"How long sessions remain valid before requiring re-authentication.",inputType:"duration",min:300,presets:[{label:"1 hour",value:"3600"},{label:"24 hours",value:"86400"},{label:"7 days",value:"604800"},{label:"30 days",value:"2592000"}]},security_jwt_issuer:{key:"security_jwt_issuer",label:"JWT Issuer",description:"Issuer claim for JWTs. Empty uses the server URL.",inputType:"text"},security_jwt_audience:{key:"security_jwt_audience",label:"JWT Audience",description:"Audience claim for JWTs. Empty uses default.",inputType:"text"},email_provider:{key:"email_provider",label:"Email Provider",description:"Select your email service provider for automatic configuration.",inputType:"select",presets:[{label:"Mailgun",value:"mailgun"},{label:"SendGrid",value:"sendgrid"},{label:"Postmark",value:"postmark"},{label:"AWS SES",value:"ses"},{label:"Resend",value:"resend"},{label:"Custom SMTP",value:"custom"}]},email_smtp_host:{key:"email_smtp_host",label:"SMTP Host",description:"SMTP server hostname (e.g., smtp.sendgrid.net).",inputType:"text"},email_smtp_port:{key:"email_smtp_port",label:"SMTP Port",description:"SMTP server port. Common: 587 (TLS), 465 (SSL), 25 (unencrypted).",inputType:"select",presets:[{label:"587 (TLS)",value:"587"},{label:"465 (SSL)",value:"465"},{label:"25 (Plain)",value:"25"}]},email_smtp_user:{key:"email_smtp_user",label:"SMTP Username",description:"Username for SMTP authentication.",inputType:"text"},email_smtp_password:{key:"email_smtp_password",label:"API Key",description:"API key or password for your email provider.",inputType:"secret"},email_smtp_tls:{key:"email_smtp_tls",label:"Use TLS",description:"Enable TLS encryption for SMTP connections.",inputType:"boolean"},email_from_address:{key:"email_from_address",label:"From Address",description:"Default sender email address (e.g., noreply@example.com).",inputType:"text"},email_from_name:{key:"email_from_name",label:"From Name",description:'Default sender display name (e.g., "My App").',inputType:"text"},webhook_enabled:{key:"webhook_enabled",label:"Enable Webhooks",description:"Send notifications to a Discord or Slack webhook URL.",inputType:"boolean"},webhook_url:{key:"webhook_url",label:"Webhook URL",description:"Discord or Slack webhook URL to receive notifications.",inputType:"text",placeholder:"https://discord.com/api/webhooks/..."},webhook_notify_registrations:{key:"webhook_notify_registrations",label:"New Registrations",description:"Notify when a new user registers.",inputType:"boolean"},webhook_notify_signins:{key:"webhook_notify_signins",label:"Sign-Ins",description:"Notify when a user signs in.",inputType:"boolean"},webhook_notify_deposits:{key:"webhook_notify_deposits",label:"Deposits",description:"Notify when a user makes a deposit.",inputType:"boolean"},server_frontend_url:{key:"server_frontend_url",label:"Frontend URL",description:"URL of your frontend app (for redirects and email links).",inputType:"text"},server_base_path:{key:"server_base_path",label:"Base Path",description:"Base path for auth endpoints (e.g., /auth).",inputType:"text"},server_trust_proxy:{key:"server_trust_proxy",label:"Trust Proxy",description:"Trust X-Forwarded-For headers. Enable if behind a reverse proxy.",inputType:"boolean"},server_cedros_pay_api_key:{key:"server_cedros_pay_api_key",label:"Cedros Pay API Key",description:"API key for Cedros Pay to authenticate with this server. Copy this into your Cedros Pay settings.",inputType:"secret"},jupiter_api_key:{key:"jupiter_api_key",label:"Jupiter API Key",description:'API key for Jupiter Ultra API (gasless swaps). Get a free key at <a href="https://portal.jup.ag" target="_blank" rel="noopener">portal.jup.ag</a>.',inputType:"secret"},server_metrics_api_key:{key:"server_metrics_api_key",label:"Metrics API Key",description:"API key for Prometheus/Grafana to scrape the /metrics endpoint. Use with Authorization: Bearer header.",inputType:"secret"},server_log_level:{key:"server_log_level",label:"Log Level",description:"Minimum severity level for log output. Lower levels are more verbose.",inputType:"select",presets:[{label:"Trace (most verbose)",value:"trace"},{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error (least verbose)",value:"error"}]},server_log_format:{key:"server_log_format",label:"Log Format",description:"Output format for log messages.",inputType:"select",presets:[{label:"JSON (structured)",value:"json"},{label:"Pretty (human-readable)",value:"pretty"}]},server_environment:{key:"server_environment",label:"Environment",description:"Deployment environment. Affects default behaviors and log verbosity.",inputType:"select",presets:[{label:"Development",value:"development"},{label:"Staging",value:"staging"},{label:"Production",value:"production"}]},privacy_period_secs:{key:"privacy_period_secs",label:"Privacy Period",description:"How long deposits are held before withdrawal to provide timing privacy. Longer periods provide better privacy but delay user access to funds.",inputType:"duration",min:0,presets:[{label:"Disabled",value:"0"},{label:"1 hour",value:"3600"},{label:"6 hours",value:"21600"},{label:"24 hours",value:"86400"},{label:"7 days",value:"604800"},{label:"14 days",value:"1209600"},{label:"30 days",value:"2592000"}],warningThreshold:{below:3600,message:"Very short privacy periods may not provide adequate timing protection."}},treasury_wallet_address:{key:"treasury_wallet_address",label:"Treasury Wallet Address",description:"Solana wallet address where funds are sent. Used for privacy cash withdrawals, micro payment batches, and direct payments.",inputType:"text",placeholder:"e.g., 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"},withdrawal_poll_interval_secs:{key:"withdrawal_poll_interval_secs",label:"Worker Poll Interval",description:"How often the withdrawal worker checks for deposits ready to process. Lower values process faster but increase server load.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"},{label:"1 hour",value:"3600"},{label:"6 hours",value:"21600"}],warningThreshold:{below:60,message:"Polling more than once per minute may cause excessive load."}},withdrawal_batch_size:{key:"withdrawal_batch_size",label:"Batch Size",description:"Maximum number of withdrawals to process in a single batch. Higher values improve throughput but may cause timeouts.",inputType:"select",min:1,max:100,presets:[{label:"1 (Sequential)",value:"1"},{label:"5",value:"5"},{label:"10 (Recommended)",value:"10"},{label:"25",value:"25"},{label:"50",value:"50"},{label:"100 (Max)",value:"100"}]},withdrawal_timeout_secs:{key:"withdrawal_timeout_secs",label:"Transaction Timeout",description:"How long to wait for a withdrawal transaction to confirm before considering it failed.",inputType:"duration",min:30,presets:[{label:"30 seconds",value:"30"},{label:"1 minute",value:"60"},{label:"2 minutes",value:"120"},{label:"5 minutes",value:"300"}],warningThreshold:{below:30,message:"Very short timeouts may cause premature failure on slow networks."}},withdrawal_max_retries:{key:"withdrawal_max_retries",label:"Max Retries",description:"Number of times to retry a failed withdrawal before marking it as permanently failed.",inputType:"select",min:0,max:10,presets:[{label:"0 (No retries)",value:"0"},{label:"1",value:"1"},{label:"3 (Recommended)",value:"3"},{label:"5",value:"5"},{label:"10",value:"10"}]},withdrawal_percentage:{key:"withdrawal_percentage",label:"Withdrawal Percentage",description:"Percentage of ready funds to withdraw each cycle. Lower values spread withdrawals over time for better privacy.",inputType:"percentage",min:1,max:100,step:5,presets:[{label:"25%",value:"25"},{label:"50%",value:"50"},{label:"75%",value:"75"},{label:"100% (All at once)",value:"100"}],warningThreshold:{above:75,message:"High percentages may reduce timing privacy by processing most withdrawals together."}},partial_withdrawal_count:{key:"partial_withdrawal_count",label:"Partial Withdrawals",description:"Maximum partial withdrawals per batch. Partial withdrawals add noise to timing analysis. Set to 0 to disable.",inputType:"select",min:0,presets:[{label:"Disabled",value:"0"},{label:"1",value:"1"},{label:"3",value:"3"},{label:"5",value:"5"},{label:"10",value:"10"}]},partial_withdrawal_min_lamports:{key:"partial_withdrawal_min_lamports",label:"Min Balance for Partial",description:"Minimum account balance (in lamports) required before partial withdrawals are considered. 1 SOL = 1,000,000,000 lamports.",inputType:"select",min:0,presets:[{label:"0.1 SOL",value:"100000000"},{label:"0.5 SOL",value:"500000000"},{label:"1 SOL",value:"1000000000"},{label:"5 SOL",value:"5000000000"},{label:"10 SOL",value:"10000000000"}]},rate_limit_auth:{key:"rate_limit_auth",label:"Auth Request Limit",description:"Maximum authentication attempts (login, register, password reset) per IP per window. Protects against brute force attacks.",inputType:"select",min:1,unit:"requests",presets:[{label:"5 (Strict)",value:"5"},{label:"10 (Recommended)",value:"10"},{label:"20",value:"20"},{label:"50 (Permissive)",value:"50"}],warningThreshold:{above:20,message:"High auth limits may allow brute force attempts."}},rate_limit_general:{key:"rate_limit_general",label:"General Request Limit",description:"Maximum general API requests per IP per window. Affects all non-auth endpoints.",inputType:"select",min:1,unit:"requests",presets:[{label:"30",value:"30"},{label:"60 (Recommended)",value:"60"},{label:"120",value:"120"},{label:"300",value:"300"}]},rate_limit_credit:{key:"rate_limit_credit",label:"Credit Request Limit",description:"Maximum credit/balance check requests per IP per window. Higher for apps that poll balance frequently.",inputType:"select",min:1,unit:"requests",presets:[{label:"10",value:"10"},{label:"30 (Recommended)",value:"30"},{label:"60",value:"60"},{label:"120",value:"120"}]},rate_limit_window:{key:"rate_limit_window",label:"Rate Limit Window",description:'Time window for rate limiting. All limits above are "per window". Shorter windows are stricter.',inputType:"duration",min:1,presets:[{label:"30 seconds",value:"30"},{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"}]},solana_rpc_url:{key:"solana_rpc_url",label:"Solana RPC URL",description:'Get a fast RPC endpoint from <a href="https://helius.dev" target="_blank" rel="noopener">Helius</a> or <a href="https://quicknode.com" target="_blank" rel="noopener">QuickNode</a>.',inputType:"text",placeholder:"https://api.mainnet-beta.solana.com"},solana_network:{key:"solana_network",label:"Solana Network",description:"The Solana network to use for deposits and withdrawals.",inputType:"select",presets:[{label:"Mainnet",value:"mainnet-beta"},{label:"Devnet",value:"devnet"}]},deposit_privacy_enabled:{key:"deposit_privacy_enabled",label:"Enable Private Deposits",description:"When enabled, deposits are held for a privacy period before withdrawal. Provides timing privacy but delays fund availability.",inputType:"boolean"},deposit_company_token:{key:"deposit_company_token",label:"Platform Token",description:"The token that represents platform credits. Deposits are converted to this token. Common choices: USDC, SOL.",inputType:"select",presets:[{label:"USDC",value:"USDC"},{label:"USDT",value:"USDT"},{label:"SOL",value:"SOL"},{label:"EURC",value:"EURC"}]},deposit_micro_enabled:{key:"deposit_micro_enabled",label:"SOL Micro Payments",description:"Allow small SOL deposits (under $10) that are batched together for efficiency.",inputType:"boolean"},deposit_gasless_swap_enabled:{key:"deposit_gasless_swap_enabled",label:"Gasless Swap Payments",description:"Allow deposits via Jupiter swaps.",inputType:"boolean"},deposit_min_usd:{key:"deposit_min_usd",label:"Minimum Deposit",description:"Minimum deposit amount in USD equivalent.",inputType:"select",unit:"USD",presets:[{label:"$1",value:"1"},{label:"$5",value:"5"},{label:"$10",value:"10"},{label:"$25",value:"25"}]},deposit_max_usd:{key:"deposit_max_usd",label:"Maximum Deposit",description:"Maximum deposit amount per transaction in USD equivalent. Set to 0 for unlimited.",inputType:"select",unit:"USD",presets:[{label:"Unlimited",value:"0"},{label:"$1,000",value:"1000"},{label:"$10,000",value:"10000"},{label:"$100,000",value:"100000"}]},deposit_show_explainer:{key:"deposit_show_explainer",label:"Show Explainer Screen",description:"Show the introductory explainer screen at the start of the deposit flow.",inputType:"boolean"},deposit_quick_action_tokens:{key:"deposit_quick_action_tokens",label:"Quick Action Tokens",description:"Comma-separated token symbols shown as quick action buttons. First token is the default.",inputType:"tokenSymbolList"},deposit_custom_tokens:{key:"deposit_custom_tokens",label:"Custom Dropdown Tokens",description:'Comma-separated token symbols shown in the "Custom" dropdown. Leave empty to show all.',inputType:"tokenSymbolList"},deposit_custom_tokens_json:{key:"deposit_custom_tokens_json",label:"Custom Token Definitions",description:"Add tokens beyond the built-in list. Define symbol, mint address, decimals, and logo URL.",inputType:"tokenList"},deposit_fee_policy:{key:"deposit_fee_policy",label:"Fee Policy",description:"Who pays deposit fees: company absorbs all, or user pays swap/privacy/all fees.",inputType:"select",presets:[{label:"Company Pays All",value:"company_pays_all"},{label:"User Pays Swap Fees",value:"user_pays_swap"},{label:"User Pays Privacy Fees",value:"user_pays_privacy"},{label:"User Pays All Fees",value:"user_pays_all"}]},privacy_fee_fixed_lamports:{key:"privacy_fee_fixed_lamports",label:"Privacy Fixed Fee",description:"Fixed fee for Privacy Cash deposits in lamports. 1 SOL = 1,000,000,000 lamports.",inputType:"select",unit:"lamports",presets:[{label:"0 SOL",value:"0"},{label:"0.001 SOL",value:"1000000"},{label:"0.005 SOL",value:"5000000"},{label:"0.006 SOL (Default)",value:"6000000"},{label:"0.01 SOL",value:"10000000"}]},privacy_fee_percent_bps:{key:"privacy_fee_percent_bps",label:"Privacy Percentage Fee",description:"Percentage fee for Privacy Cash deposits in basis points. 100 bps = 1%.",inputType:"select",unit:"bps",presets:[{label:"0%",value:"0"},{label:"0.25%",value:"25"},{label:"0.35% (Default)",value:"35"},{label:"0.5%",value:"50"},{label:"1%",value:"100"}]},swap_fee_fixed_lamports:{key:"swap_fee_fixed_lamports",label:"Swap Fixed Fee",description:"Fixed fee for Jupiter swaps in lamports. Covers transaction costs.",inputType:"select",unit:"lamports",presets:[{label:"0 SOL",value:"0"},{label:"0.001 SOL (Default)",value:"1000000"},{label:"0.002 SOL",value:"2000000"},{label:"0.005 SOL",value:"5000000"}]},swap_fee_percent_bps:{key:"swap_fee_percent_bps",label:"Swap Percentage Fee",description:"Percentage fee for Jupiter swaps in basis points. 100 bps = 1%.",inputType:"select",unit:"bps",presets:[{label:"0%",value:"0"},{label:"0.1% (Default)",value:"10"},{label:"0.25%",value:"25"},{label:"0.5%",value:"50"}]},company_fee_fixed_lamports:{key:"company_fee_fixed_lamports",label:"Company Fixed Fee",description:"Additional fixed processing fee in lamports. Set to 0 to disable.",inputType:"select",unit:"lamports",presets:[{label:"Disabled",value:"0"},{label:"0.001 SOL",value:"1000000"},{label:"0.005 SOL",value:"5000000"},{label:"0.01 SOL",value:"10000000"}]},company_fee_percent_bps:{key:"company_fee_percent_bps",label:"Company Percentage Fee",description:"Additional percentage processing fee in basis points. 100 bps = 1%.",inputType:"select",unit:"bps",presets:[{label:"Disabled",value:"0"},{label:"0.1%",value:"10"},{label:"0.25%",value:"25"},{label:"0.5%",value:"50"},{label:"1%",value:"100"}]},micro_batch_threshold_usd:{key:"micro_batch_threshold_usd",label:"Batch Threshold",description:"Minimum accumulated USD value before triggering a batch swap. Jupiter requires ~$10 minimum.",inputType:"select",unit:"USD",presets:[{label:"$10 (Minimum)",value:"10"},{label:"$25",value:"25"},{label:"$50",value:"50"},{label:"$100",value:"100"}]},micro_batch_poll_secs:{key:"micro_batch_poll_secs",label:"Batch Poll Interval",description:"How often to check for batchable micro deposits. Lower values process faster but increase load.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes (Default)",value:"300"},{label:"15 minutes",value:"900"},{label:"1 hour",value:"3600"}]},private_deposit_min_lamports:{key:"private_deposit_min_lamports",label:"Min Private Deposit",description:"Minimum amount for Privacy Cash deposits in lamports. Smaller deposits use micro batching.",inputType:"select",unit:"lamports",presets:[{label:"0.1 SOL",value:"100000000"},{label:"0.25 SOL (Default)",value:"250000000"},{label:"0.5 SOL",value:"500000000"},{label:"1 SOL",value:"1000000000"}]},withdrawal_min_lamports:{key:"withdrawal_min_lamports",label:"Min Withdrawal Amount",description:"Minimum amount to withdraw in lamports. Deposits below this remain pending. Fees are ~0.006 SOL + 0.35% + Jupiter.",inputType:"select",unit:"lamports",presets:[{label:"0.5 SOL",value:"500000000"},{label:"1 SOL (Default)",value:"1000000000"},{label:"2 SOL",value:"2000000000"},{label:"5 SOL",value:"5000000000"}],warningThreshold:{below:5e8,message:"Very small withdrawals may lose significant value to fees."}}},Ur=["SOL","USDC","USDT","EURC","USD1","PYUSD","USDH","CASH","BONK","ORE"];function be({settings:s,edits:t,onChange:r,externalWarnings:a}){return e.jsx("div",{className:"cedros-settings-grid",children:s.map(n=>e.jsx(fo,{setting:n,editValue:t[n.key],onChange:r,externalWarning:a?.[n.key]},n.key))})}function fo({setting:s,editValue:t,onChange:r,externalWarning:a}){const n=po[s.key],o=t??s.value,c=t!==void 0&&t!==s.value,l=n?.inputType==="boolean",d=i.useMemo(()=>{if(a)return a;if(!n?.warningThreshold)return null;const u=parseInt(o,10);if(isNaN(u))return null;const{above:g,below:m,message:h}=n.warningThreshold;return g!==void 0&&u>g||m!==void 0&&u<m?h:null},[o,n?.warningThreshold,a]);return n?e.jsx("div",{className:`cedros-setting-row ${c?"cedros-setting-row-changed":""} ${d?"cedros-setting-row-warning":""} ${l?"cedros-setting-row-toggle":""}`,children:l?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-setting-control cedros-setting-control-toggle",children:[e.jsx(mt,{meta:n,value:o,onChange:u=>r(s.key,u)}),d&&e.jsx("div",{className:"cedros-setting-warning",children:d})]}),e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:n.label}),e.jsx("span",{className:"cedros-setting-description",dangerouslySetInnerHTML:{__html:n.description}})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:n.label}),e.jsx("span",{className:"cedros-setting-description",dangerouslySetInnerHTML:{__html:n.description}})]}),e.jsxs("div",{className:"cedros-setting-control",children:[e.jsx(mt,{meta:n,value:o,onChange:u=>r(s.key,u)}),d&&e.jsx("div",{className:"cedros-setting-warning",children:d})]})]})}):e.jsxs("div",{className:`cedros-setting-row ${c?"cedros-setting-row-changed":""}`,children:[e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:s.key}),s.description&&e.jsx("span",{className:"cedros-setting-description",children:s.description})]}),e.jsx("div",{className:"cedros-setting-input-wrapper",children:e.jsx("input",{type:"text",value:o,onChange:u=>r(s.key,u.target.value),className:"cedros-setting-input"})})]})}function mt({meta:s,value:t,onChange:r}){switch(s.inputType){case"duration":return e.jsx(go,{value:t,onChange:r,presets:s.presets,min:s.min});case"percentage":return e.jsx(bo,{value:t,onChange:r,min:s.min??1,max:s.max??100,step:s.step??5,presets:s.presets});case"select":return e.jsx(yo,{value:t,onChange:r,presets:s.presets??[],unit:s.unit});case"number":return e.jsx(wo,{value:t,onChange:r,min:s.min,max:s.max,unit:s.unit});case"tokenList":return e.jsx(jo,{value:t,onChange:r});case"text":return e.jsx("input",{type:"text",value:t,onChange:a=>r(a.target.value),className:"cedros-setting-input",placeholder:s.label});case"boolean":return e.jsx(xo,{value:t,onChange:r});case"secret":return e.jsx(vo,{value:t,onChange:r,multiline:s.multiline});case"tokenSymbolList":return e.jsx(Ao,{value:t,onChange:r});default:return e.jsx("input",{type:"text",value:t,onChange:a=>r(a.target.value),className:"cedros-setting-input"})}}function go({value:s,onChange:t,presets:r,min:a=0}){const n=parseInt(s,10)||0,o=mo(n),c=i.useCallback(d=>{d.target.value&&t(d.target.value)},[t]),l=i.useCallback(d=>{const u=Math.max(a,parseInt(d.target.value,10)||0);t(String(u))},[t,a]);return e.jsxs("div",{className:"cedros-duration-input",children:[r&&r.length>0&&e.jsxs("select",{value:r.find(d=>d.value===s)?.value??"",onChange:c,className:"cedros-setting-select",children:[e.jsx("option",{value:"",children:"Custom..."}),r.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))]}),e.jsxs("div",{className:"cedros-duration-custom",children:[e.jsx("input",{type:"number",value:n,onChange:l,min:a,className:"cedros-setting-input cedros-setting-input-sm"}),e.jsx("span",{className:"cedros-setting-unit",children:"seconds"}),e.jsxs("span",{className:"cedros-duration-display",children:["= ",o]})]})]})}function bo({value:s,onChange:t,min:r,max:a,step:n,presets:o}){const c=parseInt(s,10)||r,l=i.useCallback(u=>{t(u.target.value)},[t]),d=i.useCallback(u=>{t(u)},[t]);return e.jsxs("div",{className:"cedros-percentage-input",children:[e.jsxs("div",{className:"cedros-percentage-slider-row",children:[e.jsx("input",{type:"range",value:c,onChange:l,min:r,max:a,step:n,className:"cedros-percentage-slider"}),e.jsxs("span",{className:"cedros-percentage-value",children:[c,"%"]})]}),o&&o.length>0&&e.jsx("div",{className:"cedros-preset-buttons",children:o.map(u=>e.jsx("button",{type:"button",className:`cedros-preset-button ${u.value===s?"cedros-preset-button-active":""}`,onClick:()=>d(u.value),children:u.label},u.value))})]})}function yo({value:s,onChange:t,presets:r,unit:a}){const n=!r.some(l=>l.value===s),o=i.useCallback(l=>{l.target.value!=="__custom__"&&t(l.target.value)},[t]),c=i.useCallback(l=>{t(l.target.value)},[t]);return e.jsxs("div",{className:"cedros-select-input",children:[e.jsxs("select",{value:n?"__custom__":s,onChange:o,className:"cedros-setting-select",children:[r.map(l=>e.jsx("option",{value:l.value,children:l.label},l.value)),e.jsx("option",{value:"__custom__",children:"Custom..."})]}),n&&e.jsxs("div",{className:"cedros-select-custom",children:[e.jsx("input",{type:"number",value:s,onChange:c,className:"cedros-setting-input cedros-setting-input-sm"}),a&&e.jsx("span",{className:"cedros-setting-unit",children:a})]})]})}function wo({value:s,onChange:t,min:r,max:a,unit:n}){const o=i.useCallback(c=>{t(c.target.value)},[t]);return e.jsxs("div",{className:"cedros-number-input",children:[e.jsx("input",{type:"number",value:s,onChange:o,min:r,max:a,className:"cedros-setting-input"}),n&&e.jsx("span",{className:"cedros-setting-unit",children:n})]})}function xo({value:s,onChange:t}){const r=s==="true",a=i.useCallback(()=>{t(r?"false":"true")},[r,t]);return e.jsxs("button",{type:"button",role:"switch","aria-checked":r,className:`cedros-toggle ${r?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:a,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:r?"Enabled":"Disabled"})]})}function vo({value:s,onChange:t,multiline:r}){const[a,n]=i.useState(!1),[o,c]=i.useState(!1),l=s&&s.length>0,d=i.useCallback(()=>{n(!0),c(!0)},[]),u=i.useCallback(()=>{n(!1),c(!1)},[]),g=i.useCallback(m=>{t(m.target.value)},[t]);return!a&&l?e.jsxs("div",{className:"cedros-secret-input cedros-secret-input-masked",children:[e.jsx("span",{className:"cedros-secret-masked",children:"•".repeat(Math.min(s.length,20))}),e.jsx("button",{type:"button",className:"cedros-secret-edit-btn",onClick:d,children:"Edit"})]}):e.jsxs("div",{className:"cedros-secret-input",children:[r?e.jsx("textarea",{value:s,onChange:g,className:"cedros-setting-input cedros-setting-textarea",placeholder:"Enter secret value...",rows:4}):e.jsx("input",{type:o?"text":"password",value:s,onChange:g,className:"cedros-setting-input",placeholder:"Enter secret value..."}),e.jsxs("div",{className:"cedros-secret-actions",children:[!r&&e.jsx("button",{type:"button",className:"cedros-secret-toggle-btn",onClick:()=>c(!o),children:o?"Hide":"Show"}),a&&e.jsx("button",{type:"button",className:"cedros-secret-done-btn",onClick:u,children:"Done"})]})]})}function jo({value:s,onChange:t}){const r=i.useMemo(()=>{try{return JSON.parse(s||"[]")}catch{return[]}},[s]),a=i.useCallback(l=>{t(JSON.stringify(l))},[t]),n=i.useCallback(()=>{a([...r,{symbol:"",mint:"",decimals:6}])},[r,a]),o=i.useCallback((l,d,u)=>{const g=[...r];g[l]={...g[l],[d]:u},a(g)},[r,a]),c=i.useCallback(l=>{a(r.filter((d,u)=>u!==l))},[r,a]);return e.jsxs("div",{className:"cedros-token-list-input",children:[e.jsxs("div",{className:"cedros-token-presets",children:[e.jsx("span",{className:"cedros-token-presets-label",children:"Built-in tokens:"}),e.jsx("div",{className:"cedros-token-presets-list",children:Ur.map(l=>e.jsx("span",{className:"cedros-token-preset-chip",children:l},l))})]}),r.length===0&&e.jsx("p",{className:"cedros-token-list-empty",children:"No custom tokens added. Use the built-in tokens above or add your own."}),r.map((l,d)=>e.jsxs("div",{className:"cedros-token-row",children:[e.jsxs("div",{className:"cedros-token-row-fields",children:[e.jsx("input",{type:"text",placeholder:"Symbol",value:l.symbol,onChange:u=>o(d,"symbol",u.target.value.toUpperCase()),className:"cedros-setting-input cedros-token-input-symbol",maxLength:10}),e.jsx("input",{type:"text",placeholder:"Mint address",value:l.mint,onChange:u=>o(d,"mint",u.target.value),className:"cedros-setting-input cedros-token-input-mint"}),e.jsx("input",{type:"number",placeholder:"Decimals",value:l.decimals,onChange:u=>o(d,"decimals",parseInt(u.target.value,10)||0),className:"cedros-setting-input cedros-token-input-decimals",min:0,max:18}),e.jsx("input",{type:"text",placeholder:"Logo URL (optional)",value:l.logoUrl||"",onChange:u=>o(d,"logoUrl",u.target.value||void 0),className:"cedros-setting-input cedros-token-input-logo"})]}),e.jsx("button",{type:"button",className:"cedros-token-remove-btn",onClick:()=>c(d),title:"Remove token",children:"×"})]},d)),e.jsx("button",{type:"button",className:"cedros-token-add-btn",onClick:n,children:"+ Add Token"})]})}function Ao({value:s,onChange:t}){const r=i.useMemo(()=>s.split(",").map(o=>o.trim()).filter(Boolean),[s]),a=i.useCallback(o=>{if(!o||r.includes(o))return;const c=[...r,o].join(", ");t(c)},[r,t]),n=i.useCallback(o=>{const c=r.filter(l=>l!==o).join(", ");t(c)},[r,t]);return e.jsxs("div",{className:"cedros-token-symbol-list-input",children:[e.jsxs("div",{className:"cedros-token-presets",children:[e.jsx("span",{className:"cedros-token-presets-label",children:"Click to add:"}),e.jsx("div",{className:"cedros-token-presets-list",children:Ur.map(o=>{const c=r.includes(o);return e.jsxs("button",{type:"button",className:`cedros-token-preset-chip ${c?"cedros-token-preset-chip-selected":""}`,onClick:()=>c?n(o):a(o),title:c?`Remove ${o}`:`Add ${o}`,children:[o,c&&e.jsx("span",{className:"cedros-token-chip-check",children:"✓"})]},o)})})]}),e.jsx("input",{type:"text",value:s,onChange:o=>t(o.target.value),className:"cedros-setting-input",placeholder:"USDC, SOL, BONK..."})]})}function Te({status:s,error:t}){return s==="idle"?null:e.jsxs("div",{className:`cedros-autosave-status cedros-autosave-status--${s}`,children:[s==="pending"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-autosave-dot"}),e.jsx("span",{children:"Unsaved changes"})]}),s==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-autosave-spinner"}),e.jsx("span",{children:"Saving..."})]}),s==="saved"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-autosave-check",children:"✓"}),e.jsx("span",{children:"Saved"})]}),s==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-autosave-error-icon",children:"!"}),e.jsx("span",{children:t||"Save failed"})]})]})}function ns({title:s,description:t,categories:r,className:a=""}){const{settings:n,edits:o,isLoading:c,autosaveStatus:l,autosaveError:d,error:u,fetchSettings:g,handleChange:m}=Ee();i.useEffect(()=>{g()},[g]);const h=r.filter(b=>n[b]?.length>0);return c&&Object.keys(n).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${a}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):u?e.jsx("div",{className:`cedros-system-settings ${a}`,children:e.jsx(N.ErrorMessage,{error:u.message})}):e.jsxs("div",{className:`cedros-system-settings ${a}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:s}),e.jsx("p",{className:"cedros-settings-page-description",children:t})]}),e.jsx(Te,{status:l,error:d})]}),h.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsx("p",{children:"No settings found for this section."})}):h.map(b=>e.jsx(be,{settings:n[b],edits:o,onChange:m},b))]})}function ko(){const{config:s,_internal:t}=N.useCedrosLogin(),r=s.serverUrl,a=i.useRef(t?.getAccessToken??(()=>null));a.current=t?.getAccessToken??(()=>null);const[n,o]=i.useState([]),[c,l]=i.useState(0),[d,u]=i.useState(!1),[g,m]=i.useState(null),h=i.useCallback(()=>{const y=a.current();return{"Content-Type":"application/json",...y?{Authorization:`Bearer ${y}`}:{}}},[]),b=i.useCallback(async(y,A=50,v=0)=>{u(!0),m(null);try{const S=new URLSearchParams;y&&S.set("org_id",y),S.set("limit",String(A)),S.set("offset",String(v));const w=await fetch(`${r}/admin/sso-providers?${S}`,{headers:h()});if(!w.ok){const P=await w.json().catch(()=>({}));throw new Error(P.error||`Failed to fetch SSO providers: ${w.status}`)}const E=await w.json();return o(E.providers),l(E.total),E}catch(S){const w=S instanceof Error?S:new Error(String(S));throw m(w),w}finally{u(!1)}},[r,h]),f=i.useCallback(async y=>{u(!0),m(null);try{const A=await fetch(`${r}/admin/sso-providers`,{method:"POST",headers:h(),body:JSON.stringify(y)});if(!A.ok){const S=await A.json().catch(()=>({}));throw new Error(S.error||`Failed to create SSO provider: ${A.status}`)}const v=await A.json();return o(S=>[...S,v]),l(S=>S+1),v}catch(A){const v=A instanceof Error?A:new Error(String(A));throw m(v),v}finally{u(!1)}},[r,h]),p=i.useCallback(async(y,A)=>{u(!0),m(null);try{const v=await fetch(`${r}/admin/sso-providers/${y}`,{method:"PUT",headers:h(),body:JSON.stringify(A)});if(!v.ok){const w=await v.json().catch(()=>({}));throw new Error(w.error||`Failed to update SSO provider: ${v.status}`)}const S=await v.json();return o(w=>w.map(E=>E.id===y?S:E)),S}catch(v){const S=v instanceof Error?v:new Error(String(v));throw m(S),S}finally{u(!1)}},[r,h]),x=i.useCallback(async y=>{u(!0),m(null);try{const A=await fetch(`${r}/admin/sso-providers/${y}`,{method:"DELETE",headers:h()});if(!A.ok){const v=await A.json().catch(()=>({}));throw new Error(v.error||`Failed to delete SSO provider: ${A.status}`)}o(v=>v.filter(S=>S.id!==y)),l(v=>v-1)}catch(A){const v=A instanceof Error?A:new Error(String(A));throw m(v),v}finally{u(!1)}},[r,h]),j=i.useCallback(async(y,A)=>p(y,{enabled:A}),[p]);return{providers:n,total:c,isLoading:d,error:g,fetchProviders:b,createProvider:f,updateProvider:p,deleteProvider:x,toggleProvider:j}}class Fr{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async listOrgs(){try{return(await this.client.get("/orgs")).orgs.map(r=>({...r,membership:{orgId:r.id,role:r.role}}))}catch(t){throw N.handleApiError(t,"Failed to list organizations")}}async getOrg(t){try{return await this.client.get(`/orgs/${t}`)}catch(r){throw N.handleApiError(r,"Failed to get organization")}}async createOrg(t){try{return await this.client.post("/orgs",t)}catch(r){throw N.handleApiError(r,"Failed to create organization")}}async updateOrg(t,r){try{return await this.client.patch(`/orgs/${t}`,r)}catch(a){throw N.handleApiError(a,"Failed to update organization")}}async deleteOrg(t){try{await this.client.delete(`/orgs/${t}`)}catch(r){throw N.handleApiError(r,"Failed to delete organization")}}async authorize(t){try{return await this.client.post("/authorize",t)}catch(r){throw N.handleApiError(r,"Failed to check authorization")}}async getPermissions(t){try{return await this.client.post("/permissions",{orgId:t})}catch(r){throw N.handleApiError(r,"Failed to get permissions")}}}const gs="cedros_active_org";function No(s){try{return localStorage.getItem(s)}catch{return null}}function pt(s,t){try{localStorage.setItem(s,t)}catch{}}function as(){const{config:s,user:t,authState:r,_internal:a}=N.useCedrosLogin(),n=typeof window<"u"&&!!window.localStorage,[o,c]=i.useState([]),[l,d]=i.useState(null),[u,g]=i.useState([]),[m,h]=i.useState(null),[b,f]=i.useState(!1),[p,x]=i.useState(null),j=i.useMemo(()=>new Fr(s.serverUrl,s.requestTimeout,s.retryAttempts,a?.getAccessToken),[s.serverUrl,s.requestTimeout,s.retryAttempts,a]),y=i.useRef(j);i.useEffect(()=>{y.current=j},[j]);const A=i.useCallback(async T=>{try{const C=await y.current.getPermissions(T);g(C.permissions),h(C.role)}catch{g([]),h(null)}},[]),v=i.useCallback(async()=>{if(r!=="authenticated"||!t){c([]),d(null),g([]),h(null);return}f(!0),x(null);try{const T=await y.current.listOrgs();c(T);const C=n?No(gs):null;let k=T.find(_=>_.id===C);!k&&T.length>0&&(k=T.find(_=>_.isPersonal)||T[0]),k?(d(k),n&&pt(gs,k.id),await A(k.id)):(d(null),g([]),h(null))}catch(T){x(T)}finally{f(!1)}},[r,t,A,n]),S=i.useCallback(async T=>{const C=o.find(k=>k.id===T);if(!C){x({code:"UNKNOWN_ERROR",message:"Organization not found"});return}d(C),n&&pt(gs,T),await A(T)},[o,A,n]),w=i.useCallback(async T=>{f(!0),x(null);try{const C=await y.current.createOrg(T);return await v(),C}catch(C){throw x(C),C}finally{f(!1)}},[v]),E=i.useCallback(async(T,C)=>{f(!0),x(null);try{const k=await y.current.updateOrg(T,C);return await v(),k}catch(k){throw x(k),k}finally{f(!1)}},[v]),P=i.useCallback(async T=>{f(!0),x(null);try{await y.current.deleteOrg(T),await v()}catch(C){throw x(C),C}finally{f(!1)}},[v]),L=i.useCallback(T=>u.includes(T),[u]);return{orgs:o,activeOrg:l,permissions:u,role:m,isLoading:b,error:p,fetchOrgs:v,switchOrg:S,createOrg:w,updateOrg:E,deleteOrg:P,hasPermission:L}}function So({className:s}){const{providers:t,isLoading:r,error:a,fetchProviders:n,createProvider:o,updateProvider:c,deleteProvider:l,toggleProvider:d}=ko(),{activeOrg:u}=as(),[g,m]=i.useState("list"),[h,b]=i.useState(null),[f,p]=i.useState(null);i.useEffect(()=>{n(u?.id)},[n,u?.id]);const x=()=>{b(null),p(null),m("add")},j=w=>{b(w),p(null),m("edit")},y=()=>{m("list"),b(null),p(null)},A=async w=>{if(confirm(`Delete SSO provider "${w.name}"? This cannot be undone.`))try{await l(w.id)}catch{}},v=async w=>{try{await d(w.id,!w.enabled)}catch{}},S=async w=>{p(null);try{g==="add"?await o(w):h&&await c(h.id,w),m("list"),b(null)}catch(E){p(E instanceof Error?E.message:"Failed to save provider")}};return r&&t.length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading SSO providers..."})]}):g==="add"||g==="edit"?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(_o,{provider:h,orgId:u?.id,error:f,isLoading:r,onSave:S,onCancel:y})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"SSO Providers"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure OIDC identity providers for enterprise single sign-on."})]}),e.jsx("button",{type:"button",className:"cedros-btn cedros-btn-primary",onClick:x,children:"Add Provider"})]}),a&&e.jsx(N.ErrorMessage,{error:a.message}),t.length===0?e.jsxs("div",{className:"cedros-system-settings-empty",children:[e.jsx("p",{children:"No SSO providers configured."}),e.jsx("p",{className:"cedros-text-muted",children:"Add an OIDC provider like Okta, Azure AD, or Auth0 to enable enterprise SSO."})]}):e.jsx("div",{className:"cedros-sso-provider-list",children:t.map(w=>e.jsx(Co,{provider:w,onEdit:()=>j(w),onDelete:()=>A(w),onToggle:()=>v(w)},w.id))})]})}function Co({provider:s,onEdit:t,onDelete:r,onToggle:a}){return e.jsxs("div",{className:`cedros-sso-provider-card ${s.enabled?"":"cedros-sso-provider-card--disabled"}`,children:[e.jsxs("div",{className:"cedros-sso-provider-card-header",children:[e.jsxs("div",{className:"cedros-sso-provider-card-info",children:[e.jsx("h3",{className:"cedros-sso-provider-card-name",children:s.name}),e.jsx("p",{className:"cedros-sso-provider-card-issuer",children:s.issuerUrl})]}),e.jsxs("button",{type:"button",role:"switch","aria-checked":s.enabled,className:`cedros-toggle ${s.enabled?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:a,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:s.enabled?"Enabled":"Disabled"})]})]}),e.jsxs("div",{className:"cedros-sso-provider-card-details",children:[e.jsxs("div",{className:"cedros-sso-provider-card-detail",children:[e.jsx("span",{className:"cedros-sso-provider-card-detail-label",children:"Client ID"}),e.jsx("code",{className:"cedros-sso-provider-card-detail-value",children:s.clientId})]}),s.emailDomain&&e.jsxs("div",{className:"cedros-sso-provider-card-detail",children:[e.jsx("span",{className:"cedros-sso-provider-card-detail-label",children:"Email Domain"}),e.jsxs("span",{className:"cedros-sso-provider-card-detail-value",children:["@",s.emailDomain]})]}),e.jsxs("div",{className:"cedros-sso-provider-card-detail",children:[e.jsx("span",{className:"cedros-sso-provider-card-detail-label",children:"Registration"}),e.jsx("span",{className:"cedros-sso-provider-card-detail-value",children:s.allowRegistration?"Allowed":"Existing users only"})]})]}),e.jsxs("div",{className:"cedros-sso-provider-card-actions",children:[e.jsx("button",{type:"button",className:"cedros-btn cedros-btn-ghost",onClick:t,children:"Edit"}),e.jsx("button",{type:"button",className:"cedros-btn cedros-btn-ghost cedros-btn-danger",onClick:r,children:"Delete"})]})]})}function _o({provider:s,orgId:t,error:r,isLoading:a,onSave:n,onCancel:o}){const c=!!s,[l,d]=i.useState(s?.name??""),[u,g]=i.useState(s?.issuerUrl??""),[m,h]=i.useState(s?.clientId??""),[b,f]=i.useState(""),[p,x]=i.useState(s?.emailDomain??""),[j,y]=i.useState(s?.allowRegistration??!0),[A,v]=i.useState(s?.enabled??!0),S=i.useCallback(w=>{if(w.preventDefault(),c){const E={name:l,issuerUrl:u,clientId:m,emailDomain:p||null,allowRegistration:j,enabled:A};b&&(E.clientSecret=b),n(E)}else{if(!t)return;n({orgId:t,name:l,issuerUrl:u,clientId:m,clientSecret:b,emailDomain:p||null,allowRegistration:j,enabled:A})}},[c,t,l,u,m,b,p,j,A,n]);return e.jsxs("form",{className:"cedros-sso-provider-form",onSubmit:S,children:[e.jsx("div",{className:"cedros-settings-page-header",children:e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:c?"Edit SSO Provider":"Add SSO Provider"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure an OIDC identity provider for enterprise single sign-on."})]})}),r&&e.jsx(N.ErrorMessage,{error:r}),e.jsxs("div",{className:"cedros-form-section",children:[e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{className:"cedros-form-label",htmlFor:"sso-name",children:"Provider Name"}),e.jsx("input",{id:"sso-name",type:"text",className:"cedros-form-input",value:l,onChange:w=>d(w.target.value),placeholder:"e.g., Okta, Azure AD",required:!0})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{className:"cedros-form-label",htmlFor:"sso-issuer",children:"Issuer URL"}),e.jsx("input",{id:"sso-issuer",type:"url",className:"cedros-form-input",value:u,onChange:w=>g(w.target.value),placeholder:"https://your-org.okta.com",required:!0}),e.jsx("p",{className:"cedros-form-hint",children:"The OIDC issuer URL. Must support discovery at /.well-known/openid-configuration"})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{className:"cedros-form-label",htmlFor:"sso-client-id",children:"Client ID"}),e.jsx("input",{id:"sso-client-id",type:"text",className:"cedros-form-input",value:m,onChange:w=>h(w.target.value),placeholder:"OAuth client ID",required:!0})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsxs("label",{className:"cedros-form-label",htmlFor:"sso-client-secret",children:["Client Secret ",c&&e.jsx("span",{className:"cedros-form-hint-inline",children:"(leave blank to keep current)"})]}),e.jsx("input",{id:"sso-client-secret",type:"password",className:"cedros-form-input",value:b,onChange:w=>f(w.target.value),placeholder:c?"••••••••":"OAuth client secret",required:!c})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{className:"cedros-form-label",htmlFor:"sso-email-domain",children:"Email Domain (optional)"}),e.jsx("input",{id:"sso-email-domain",type:"text",className:"cedros-form-input",value:p,onChange:w=>x(w.target.value),placeholder:"company.com"}),e.jsx("p",{className:"cedros-form-hint",children:"Restrict to users with emails from this domain"})]}),e.jsx("div",{className:"cedros-form-group",children:e.jsxs("label",{className:"cedros-form-checkbox",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:w=>y(w.target.checked)}),e.jsx("span",{children:"Allow new user registration via SSO"})]})}),e.jsx("div",{className:"cedros-form-group",children:e.jsxs("label",{className:"cedros-form-checkbox",children:[e.jsx("input",{type:"checkbox",checked:A,onChange:w=>v(w.target.checked)}),e.jsx("span",{children:"Enable this provider"})]})})]}),e.jsxs("div",{className:"cedros-form-actions",children:[e.jsx("button",{type:"button",className:"cedros-btn cedros-btn-ghost",onClick:o,disabled:a,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-btn cedros-btn-primary",disabled:a,children:a?"Saving...":c?"Save Changes":"Add Provider"})]})]})}const ft=[{id:"email",label:"Email",categories:["auth.email"]},{id:"google",label:"Google",categories:["auth.google"]},{id:"apple",label:"Apple",categories:["auth.apple"]},{id:"solana",label:"Solana",categories:["auth.solana"]},{id:"passkeys",label:"Passkeys",categories:["auth.webauthn"]},{id:"instantlink",label:"Instant Link",categories:["auth.instantlink"]},{id:"sso",label:"SSO Providers",categories:[],isCustom:!0}];function Br({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d}=Ee(),[u,g]=i.useState("email");i.useEffect(()=>{l()},[l]);const m=ft.find(f=>f.id===u),h=i.useMemo(()=>{if(!m)return[];const f=[];for(const p of m.categories){const x=t[p]??[];f.push(...x)}return f},[t,m]),b=i.useMemo(()=>m?.keys?h.filter(f=>m.keys.includes(f.key)).sort((f,p)=>m.keys.indexOf(f.key)-m.keys.indexOf(p.key)):h,[h,m]);return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Authentication"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure authentication providers and methods for user sign-in."})]}),e.jsx(Te,{status:n,error:o})]}),e.jsx("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:ft.map(f=>e.jsx("button",{type:"button",className:`cedros-admin-tab ${u===f.id?"cedros-admin-tab-active":""}`,onClick:()=>g(f.id),"aria-selected":u===f.id,role:"tab",children:f.label},f.id))}),e.jsx("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:m?.isCustom?e.jsx(So,{}):b.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsxs("p",{children:["No settings found for ",m?.label??"this provider","."]})}):e.jsx(be,{settings:b,edits:r,onChange:d})})]})}const bs=["wallet_recovery_mode"];function Or({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d,getEffectiveValue:u}=Ee();i.useEffect(()=>{l()},[l]);const m=(t.features??[]).filter(f=>bs.includes(f.key)).sort((f,p)=>bs.indexOf(f.key)-bs.indexOf(p.key)),h=u("feature_wallet_signing")==="true",b=()=>{d("feature_wallet_signing",h?"false":"true")};return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Embedded Wallet"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure the embedded wallet for transaction signing."})]}),e.jsxs("div",{className:"cedros-settings-page-header-actions",children:[e.jsxs("button",{type:"button",role:"switch","aria-checked":h,className:`cedros-toggle ${h?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:b,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:h?"Enabled":"Disabled"})]}),e.jsx(Te,{status:n,error:o})]})]}),e.jsx("div",{className:"cedros-admin-tab-content",children:m.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsx("p",{children:"No additional settings available."})}):e.jsx(be,{settings:m,edits:r,onChange:d})})]})}const Eo=["security","rate_limit"];function To({className:s}){return e.jsx(ns,{title:"Security",description:"Configure CORS, cookies, sessions, JWT, and rate limiting settings.",categories:Eo,className:s})}const Po=["email"];function Lo({className:s}){return e.jsx(ns,{title:"Email & SMTP",description:"Configure outbound email delivery for verification, password reset, and notifications.",categories:Po,className:s})}const Mo=["webhook"];function Do({className:s}){return e.jsx(ns,{title:"Webhooks",description:"Configure HTTP webhook notifications for authentication events.",categories:Mo,className:s})}const gt=[{id:"email",label:"Email",category:"email"},{id:"webhooks",label:"Webhooks",category:"webhook"}],Ro={mailgun:"smtp.mailgun.org",sendgrid:"smtp.sendgrid.net",postmark:"smtp.postmarkapp.com",ses:"email-smtp.us-east-1.amazonaws.com",resend:"smtp.resend.com"},Io=["email_provider","email_smtp_password","email_from_address","email_from_name"],Uo=["email_provider","email_smtp_host","email_smtp_port","email_smtp_user","email_smtp_password","email_smtp_tls","email_from_address","email_from_name"];function Fo({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d,getEffectiveValue:u}=Ee(),[g,m]=i.useState("email");i.useEffect(()=>{l()},[l]);const h=gt.find(y=>y.id===g),b=h?.category??"",p=(u("email_provider")||"custom")==="custom",x=i.useMemo(()=>{const y=t[b]??[];if(g!=="email")return y;const A=p?Uo:Io;return y.filter(v=>A.includes(v.key)).sort((v,S)=>A.indexOf(v.key)-A.indexOf(S.key))},[t,b,g,p]),j=(y,A)=>{if(d(y,A),y==="email_provider"&&A!=="custom"){const v=Ro[A];v&&(d("email_smtp_host",v),d("email_smtp_port","587"),d("email_smtp_tls","true"))}};return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Auth Messages"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure email delivery and webhook notifications."})]}),e.jsx(Te,{status:n,error:o})]}),e.jsx("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:gt.map(y=>e.jsx("button",{type:"button",className:`cedros-admin-tab ${g===y.id?"cedros-admin-tab-active":""}`,onClick:()=>m(y.id),"aria-selected":g===y.id,role:"tab",children:y.label},y.id))}),e.jsx("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:x.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsxs("p",{children:["No settings found for ",h?.label??"this section","."]})}):e.jsx(be,{settings:x,edits:r,onChange:g==="email"?j:d})})]})}const bt=[{id:"deposits",label:"Deposits",categories:["deposit.general"],includeKeys:["deposit_company_token","deposit_max_usd","deposit_min_usd","deposit_micro_enabled","deposit_gasless_swap_enabled","solana_rpc_url","jupiter_api_key"]},{id:"tokens",label:"Component",categories:["deposit"],includeKeys:["deposit_show_explainer","deposit_quick_action_tokens","deposit_custom_tokens","deposit_custom_tokens_json"]},{id:"fees",label:"Fees",categories:["deposit"],includeKeys:["deposit_fee_policy","privacy_fee_fixed_lamports","privacy_fee_percent_bps","swap_fee_fixed_lamports","swap_fee_percent_bps","company_fee_fixed_lamports","company_fee_percent_bps","private_deposit_min_lamports"]},{id:"privacy",label:"Privacy",categories:["deposit.general","privacy","withdrawal"],includeKeys:["deposit_privacy_enabled","privacy_period_secs","withdrawal_percentage","withdrawal_min_lamports","partial_withdrawal_count","partial_withdrawal_min_lamports"],sections:[{title:"Privacy Pool Worker",description:"Background worker for processing withdrawals from the privacy cash pool.",keys:["withdrawal_poll_interval_secs","withdrawal_batch_size"]}]},{id:"treasury",label:"Treasury",categories:["withdrawal","deposit"],includeKeys:["treasury_wallet_address"],sections:[{title:"Micropayment Batch Worker",description:"Background worker for batching small SOL deposits together.",keys:["micro_batch_threshold_usd","micro_batch_poll_secs"]}]}];function qr({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d,getEffectiveValue:u}=Ee(),[g,m]=i.useState("deposits");i.useEffect(()=>{l()},[l]);const h=bt.find(v=>v.id===g),b=i.useMemo(()=>{if(!h)return[];const v=[];for(const S of h.categories){const w=t[S]??[];v.push(...w)}return v},[t,h]),f=u("deposit_fee_policy")||"company_pays_all",p=i.useMemo(()=>{if(!h)return[];let v=b;if(h.includeKeys&&h.includeKeys.length>0?(v=v.filter(S=>h.includeKeys.includes(S.key)),v.sort((S,w)=>h.includeKeys.indexOf(S.key)-h.includeKeys.indexOf(w.key))):h.excludeKeys&&h.excludeKeys.length>0&&(v=v.filter(S=>!h.excludeKeys.includes(S.key))),h.id==="deposits"&&(parseFloat(u("deposit_min_usd"))||0)>10&&(v=v.filter(w=>w.key!=="deposit_micro_enabled")),h.id==="fees"){const S=["privacy_fee_fixed_lamports","privacy_fee_percent_bps","private_deposit_min_lamports"],w=["swap_fee_fixed_lamports","swap_fee_percent_bps"],E=["company_fee_fixed_lamports","company_fee_percent_bps"];v=v.filter(P=>P.key==="deposit_fee_policy"?!0:f==="company_pays_all"?!1:S.includes(P.key)?f==="user_pays_privacy"||f==="user_pays_all":w.includes(P.key)?f==="user_pays_swap"||f==="user_pays_all":E.includes(P.key)?f==="user_pays_all":!0)}return v},[b,h,u,f]),x=i.useCallback(v=>b.filter(S=>v.includes(S.key)).sort((S,w)=>v.indexOf(S.key)-v.indexOf(w.key)),[b]),j=i.useMemo(()=>{if(h?.id!=="deposits")return;const v={},S=parseFloat(u("deposit_min_usd"))||0,w=u("deposit_micro_enabled");return(w==="false"||w==="0"||w==="")&&S<10&&(v.deposit_min_usd="SOL micro payments must be enabled for minimum deposits under $10."),Object.keys(v).length>0?v:void 0},[h?.id,u]),y=u("feature_credits")==="true",A=()=>{d("feature_credits",y?"false":"true")};return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Credit System"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure credit deposits, timed withdrawals, and privacy period settings."})]}),e.jsxs("div",{className:"cedros-settings-page-header-actions",children:[e.jsxs("button",{type:"button",role:"switch","aria-checked":y,className:`cedros-toggle ${y?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:A,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:y?"Enabled":"Disabled"})]}),e.jsx(Te,{status:n,error:o})]})]}),e.jsx("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:bt.map(v=>e.jsx("button",{type:"button",className:`cedros-admin-tab ${g===v.id?"cedros-admin-tab-active":""}`,onClick:()=>m(v.id),"aria-selected":g===v.id,role:"tab",children:v.label},v.id))}),e.jsx("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:p.length===0&&!h?.sections?.length?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsxs("p",{children:["No settings found for ",h?.label??"this section","."]})}):e.jsxs(e.Fragment,{children:[p.length>0&&e.jsx(be,{settings:p,edits:r,onChange:d,externalWarnings:j}),h?.sections?.map(v=>{const S=x(v.keys);return S.length===0?null:e.jsxs("div",{className:"cedros-settings-subsection",children:[e.jsxs("div",{className:"cedros-settings-subsection-header",children:[e.jsx("h4",{className:"cedros-settings-subsection-title",children:v.title}),v.description&&e.jsx("p",{className:"cedros-settings-subsection-description",children:v.description})]}),e.jsx(be,{settings:S,edits:r,onChange:d})]},v.title)})]})})]})}const yt=[{id:"general",label:"Integrations",keys:["server_cedros_pay_api_key"]},{id:"logging",label:"Logging",keys:["server_log_level"]},{id:"metrics",label:"Metrics",keys:["server_metrics_api_key"]},{id:"security",label:"Security",categories:["security","features"],keys:["feature_mfa","security_cors_origins","security_session_timeout"]}];function Wr({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d}=Ee(),[u,g]=i.useState("general");i.useEffect(()=>{l()},[l]);const m=yt.find(b=>b.id===u),h=i.useMemo(()=>{if(!m)return[];const b=m.categories??["server"],f=[];for(const p of b){const x=t[p]??[];f.push(...x)}return f.filter(p=>m.keys.includes(p.key)).sort((p,x)=>m.keys.indexOf(p.key)-m.keys.indexOf(x.key))},[t,m]);return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Auth Server"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Server infrastructure settings. Some may be overridden by environment variables."})]}),e.jsx(Te,{status:n,error:o})]}),e.jsx("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:yt.map(b=>e.jsx("button",{type:"button",className:`cedros-admin-tab ${u===b.id?"cedros-admin-tab-active":""}`,onClick:()=>g(b.id),"aria-selected":u===b.id,role:"tab",children:b.label},b.id))}),e.jsx("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:h.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsxs("p",{children:["No settings found for ",m?.label??"this section","."]})}):e.jsx(be,{settings:h,edits:r,onChange:d})})]})}class Bo{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async listMembers(t,r=50,a=0){try{const n=await this.client.get(`/orgs/${t}/members?limit=${r}&offset=${a}`);return{members:n.members.map(o=>({id:o.id,userId:o.userId,orgId:t,role:o.role,joinedAt:o.joinedAt,user:{id:o.userId,email:o.email,name:o.name}})),total:n.total}}catch(n){throw N.handleApiError(n,"Failed to list members")}}async updateMemberRole(t,r,a){try{return await this.client.patch(`/orgs/${t}/members/${r}`,a)}catch(n){throw N.handleApiError(n,"Failed to update member role")}}async removeMember(t,r){try{await this.client.delete(`/orgs/${t}/members/${r}`)}catch(a){throw N.handleApiError(a,"Failed to remove member")}}}function $r(s){const{config:t,authState:r,_internal:a}=N.useCedrosLogin(),[n,o]=i.useState([]),[c,l]=i.useState(0),[d,u]=i.useState(!1),[g,m]=i.useState(null),h=i.useRef(void 0),b=i.useRef(0),f=i.useMemo(()=>new Bo(t.serverUrl,t.requestTimeout,t.retryAttempts,a?.getAccessToken),[t.serverUrl,t.requestTimeout,t.retryAttempts,a]),p=i.useRef(f);p.current=f;const x=i.useCallback(async A=>{if(!s||r!=="authenticated"){o([]),l(0);return}u(!0),m(null);const v=++b.current;try{const{limit:S=50,offset:w=0}=A??{},E=await p.current.listMembers(s,S,w);if(v!==b.current)return;o(E.members),l(E.total)}catch(S){if(v!==b.current)return;m(S)}finally{v===b.current&&u(!1)}},[s,r]);i.useEffect(()=>{if(r!=="authenticated"){h.current=void 0;return}s!==h.current&&(h.current=s,x())},[s,r,x]);const j=i.useCallback(async(A,v)=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.updateMemberRole(s,A,{role:v}),await x()}catch(S){throw m(S),S}finally{u(!1)}},[s,x]),y=i.useCallback(async A=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.removeMember(s,A),await x()}catch(v){throw m(v),v}finally{u(!1)}},[s,x]);return{members:n,total:c,isLoading:d,error:g,fetchMembers:x,updateMemberRole:j,removeMember:y}}class Oo{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async listInvites(t,r=50,a=0){try{const n=await this.client.get(`/orgs/${t}/invites?limit=${r}&offset=${a}`);return{invites:n.invites.map(o=>({id:o.id,orgId:o.orgId,email:o.email,role:o.role,invitedBy:o.invitedBy,createdAt:o.createdAt,expiresAt:o.expiresAt})),total:n.total}}catch(n){throw N.handleApiError(n,"Failed to list invites")}}async createInvite(t,r){try{return await this.client.post(`/orgs/${t}/invites`,r)}catch(a){throw N.handleApiError(a,"Failed to create invite")}}async cancelInvite(t,r){try{await this.client.delete(`/orgs/${t}/invites/${r}`)}catch(a){throw N.handleApiError(a,"Failed to cancel invite")}}async resendInvite(t,r){try{await this.client.post(`/orgs/${t}/invites/${r}/resend`,{})}catch(a){throw N.handleApiError(a,"Failed to resend invite")}}async acceptInvite(t){try{return await this.client.post("/invites/accept",t)}catch(r){throw N.handleApiError(r,"Failed to accept invite")}}}function zr(s){const{config:t,authState:r,_internal:a}=N.useCedrosLogin(),[n,o]=i.useState([]),[c,l]=i.useState(0),[d,u]=i.useState(!1),[g,m]=i.useState(null),h=i.useRef(void 0),b=i.useRef(0),f=i.useMemo(()=>new Oo(t.serverUrl,t.requestTimeout,t.retryAttempts,a?.getAccessToken),[t.serverUrl,t.requestTimeout,t.retryAttempts,a]),p=i.useRef(f);p.current=f;const x=i.useCallback(async S=>{if(!s||r!=="authenticated"){o([]),l(0);return}u(!0),m(null);const w=++b.current;try{const{limit:E=50,offset:P=0}=S??{},L=await p.current.listInvites(s,E,P);if(w!==b.current)return;o(L.invites),l(L.total)}catch(E){if(w!==b.current)return;m(E)}finally{w===b.current&&u(!1)}},[s,r]);i.useEffect(()=>{if(r!=="authenticated"){h.current=void 0;return}s!==h.current&&(h.current=s,x())},[s,r,x]);const j=i.useCallback(async(S,w="member")=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.createInvite(s,{email:S,role:w}),await x()}catch(E){throw m(E),E}finally{u(!1)}},[s,x]),y=i.useCallback(async S=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.cancelInvite(s,S),await x()}catch(w){throw m(w),w}finally{u(!1)}},[s,x]),A=i.useCallback(async S=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.resendInvite(s,S)}catch(w){throw m(w),w}finally{u(!1)}},[s]),v=i.useCallback(async S=>{u(!0),m(null);try{return await p.current.acceptInvite({token:S})}catch(w){throw m(w),w}finally{u(!1)}},[]);return{invites:n,total:c,isLoading:d,error:g,fetchInvites:x,createInvite:j,cancelInvite:y,resendInvite:A,acceptInvite:v}}const qo={organizations:!1,sso:!1,mfa:!1,walletSigning:!1,credits:!1,cedrosPay:!1};function Gs(){const{settings:s,isLoading:t,error:r,fetchSettings:a,getValue:n}=Re(),[o,c]=i.useState(!1);i.useEffect(()=>{o||(a(),c(!0))},[a,o]);const l=i.useCallback(m=>m===void 0?!1:m==="true"||m==="1",[]),d=i.useMemo(()=>Object.keys(s).length===0?qo:{organizations:l(n("feature_organizations")),sso:l(n("feature_sso")),mfa:l(n("feature_mfa")),walletSigning:l(n("feature_wallet_signing")),credits:l(n("feature_credits")),cedrosPay:l(n("feature_cedros_pay"))},[s,n,l]),u=i.useCallback(async()=>{await a()},[a]),g=i.useCallback(m=>d[m],[d]);return{features:d,isLoading:t,error:r,refetch:u,isEnabled:g}}class Wo{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async listUsers(t){try{const r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));const a=r.toString(),n=`/admin/users${a?`?${a}`:""}`;return await this.client.get(n)}catch(r){throw N.handleApiError(r,"Failed to list users")}}async getUser(t){try{return await this.client.get(`/admin/users/${t}`)}catch(r){throw N.handleApiError(r,"Failed to get user")}}async setSystemAdmin(t,r){try{await this.client.patch(`/admin/users/${t}/system-admin`,{isAdmin:r})}catch(a){throw N.handleApiError(a,"Failed to update system admin status")}}async updateUser(t,r){try{return await this.client.patch(`/admin/users/${t}`,r)}catch(a){throw N.handleApiError(a,"Failed to update user")}}async deleteUser(t){try{await this.client.delete(`/admin/users/${t}`)}catch(r){throw N.handleApiError(r,"Failed to delete user")}}async forcePasswordReset(t){try{await this.client.post(`/admin/users/${t}/force-password-reset`,{})}catch(r){throw N.handleApiError(r,"Failed to send password reset email")}}async adjustCredits(t,r){try{await this.client.post(`/admin/users/${t}/credits`,r)}catch(a){throw N.handleApiError(a,"Failed to adjust credits")}}async getUserDeposits(t,r){try{const a=new URLSearchParams;r?.limit&&a.set("limit",String(r.limit)),r?.offset&&a.set("offset",String(r.offset));const n=a.toString(),o=`/admin/users/${t}/deposits${n?`?${n}`:""}`;return await this.client.get(o)}catch(a){throw N.handleApiError(a,"Failed to get user deposits")}}async getUserCredits(t,r){try{const a=new URLSearchParams;r?.limit&&a.set("limit",String(r.limit)),r?.offset&&a.set("offset",String(r.offset));const n=a.toString(),o=`/admin/users/${t}/credits${n?`?${n}`:""}`;return await this.client.get(o)}catch(a){throw N.handleApiError(a,"Failed to get user credits")}}async getUserWithdrawalHistory(t,r){try{const a=new URLSearchParams;r?.limit&&a.set("limit",String(r.limit)),r?.offset&&a.set("offset",String(r.offset));const n=a.toString(),o=`/admin/users/${t}/withdrawal-history${n?`?${n}`:""}`;return await this.client.get(o)}catch(a){throw N.handleApiError(a,"Failed to get user withdrawal history")}}async getUserChats(t,r){try{const a=new URLSearchParams;r?.limit&&a.set("limit",String(r.limit)),r?.offset&&a.set("offset",String(r.offset));const n=a.toString(),o=`/admin/users/${t}/chats${n?`?${n}`:""}`;return await this.client.get(o)}catch(a){throw N.handleApiError(a,"Failed to get user chat history")}}async getStats(){try{return await this.client.get("/admin/users/stats")}catch(t){throw N.handleApiError(t,"Failed to get user stats")}}}function os(){const{config:s,_internal:t}=N.useCedrosLogin(),[r,a]=i.useState([]),[n,o]=i.useState(0),[c,l]=i.useState(!1),[d,u]=i.useState(null),[g,m]=i.useState({}),h=i.useMemo(()=>new Wo(s.serverUrl,s.requestTimeout,s.retryAttempts,t?.getAccessToken),[s.serverUrl,s.requestTimeout,s.retryAttempts,t]),b=i.useCallback(async C=>{l(!0),u(null),m(C||{});try{const k=await h.listUsers(C);return a(k.users),o(k.total),k}catch(k){const _=k instanceof Error?k:new Error("Failed to list users");throw u(_),_}finally{l(!1)}},[h]),f=i.useCallback(async C=>{l(!0),u(null);try{return await h.getUser(C)}catch(k){const _=k instanceof Error?k:new Error("Failed to get user");throw u(_),_}finally{l(!1)}},[h]),p=i.useCallback(async(C,k)=>{l(!0),u(null);try{await h.setSystemAdmin(C,k),a(_=>_.map(M=>M.id===C?{...M,isSystemAdmin:k}:M))}catch(_){const M=_ instanceof Error?_:new Error("Failed to update admin status");throw u(M),M}finally{l(!1)}},[h]),x=i.useCallback(async(C,k)=>{l(!0),u(null);try{const _=await h.updateUser(C,k);return a(M=>M.map(D=>D.id===C?_:D)),_}catch(_){const M=_ instanceof Error?_:new Error("Failed to update user");throw u(M),M}finally{l(!1)}},[h]),j=i.useCallback(async C=>{l(!0),u(null);try{await h.deleteUser(C),a(k=>k.filter(_=>_.id!==C)),o(k=>k-1)}catch(k){const _=k instanceof Error?k:new Error("Failed to delete user");throw u(_),_}finally{l(!1)}},[h]),y=i.useCallback(async C=>{l(!0),u(null);try{await h.forcePasswordReset(C)}catch(k){const _=k instanceof Error?k:new Error("Failed to send password reset");throw u(_),_}finally{l(!1)}},[h]),A=i.useCallback(async(C,k,_)=>{l(!0),u(null);try{await h.adjustCredits(C,{amount:k,reason:_})}catch(M){const D=M instanceof Error?M:new Error("Failed to adjust credits");throw u(D),D}finally{l(!1)}},[h]),v=i.useCallback(async(C,k)=>{l(!0),u(null);try{return await h.getUserDeposits(C,k)}catch(_){const M=_ instanceof Error?_:new Error("Failed to get user deposits");throw u(M),M}finally{l(!1)}},[h]),S=i.useCallback(async(C,k)=>{l(!0),u(null);try{return await h.getUserCredits(C,k)}catch(_){const M=_ instanceof Error?_:new Error("Failed to get user credits");throw u(M),M}finally{l(!1)}},[h]),w=i.useCallback(async(C,k)=>{l(!0),u(null);try{return await h.getUserWithdrawalHistory(C,k)}catch(_){const M=_ instanceof Error?_:new Error("Failed to get user withdrawal history");throw u(M),M}finally{l(!1)}},[h]),E=i.useCallback(async(C,k)=>{l(!0),u(null);try{return await h.getUserChats(C,k)}catch(_){const M=_ instanceof Error?_:new Error("Failed to get user chat history");throw u(M),M}finally{l(!1)}},[h]),P=i.useCallback(async()=>{l(!0),u(null);try{return await h.getStats()}catch(C){const k=C instanceof Error?C:new Error("Failed to get user stats");throw u(k),k}finally{l(!1)}},[h]),L=i.useCallback(async()=>{await b(g)},[b,g]),T=i.useCallback(()=>{u(null)},[]);return{users:r,total:n,isLoading:c,error:d,listUsers:b,getUser:f,setSystemAdmin:p,updateUser:x,deleteUser:j,forcePasswordReset:y,adjustCredits:A,getUserDeposits:v,getUserCredits:S,getUserWithdrawalHistory:w,getUserChats:E,getStats:P,refresh:L,clearError:T}}const $o=["users","team","deposits","withdrawals","settings-wallet","settings-auth","settings-messaging","settings-credits","settings-server"],zo=["pay-products","pay-subscriptions","pay-transactions","pay-coupons","pay-refunds","pay-storefront","pay-ai","pay-payment","pay-messaging","pay-settings"],Ae={users:"Users",team:"Team",deposits:"Deposits",withdrawals:"Withdrawals","settings-wallet":"Wallet Settings","settings-auth":"Auth Settings","settings-messaging":"Messages Settings","settings-credits":"Credits Settings","settings-server":"Server Settings","pay-products":"Products","pay-subscriptions":"Subscriptions","pay-transactions":"Transactions","pay-coupons":"Coupons","pay-refunds":"Refunds","pay-storefront":"Storefront","pay-ai":"Store AI","pay-payment":"Payment Options","pay-messaging":"Store Messages","pay-settings":"Store Server"},$e={admin:{users:!0,team:!0,deposits:!0,withdrawals:!0,"settings-wallet":!0,"settings-auth":!0,"settings-messaging":!0,"settings-credits":!0,"settings-server":!0,"pay-products":!0,"pay-subscriptions":!0,"pay-transactions":!0,"pay-coupons":!0,"pay-refunds":!0,"pay-storefront":!0,"pay-ai":!0,"pay-payment":!0,"pay-messaging":!0,"pay-settings":!0},member:{users:!1,team:!0,deposits:!1,withdrawals:!1,"settings-wallet":!1,"settings-auth":!1,"settings-messaging":!1,"settings-credits":!1,"settings-server":!1,"pay-products":!1,"pay-subscriptions":!1,"pay-transactions":!1,"pay-coupons":!1,"pay-refunds":!1,"pay-storefront":!1,"pay-ai":!1,"pay-payment":!1,"pay-messaging":!1,"pay-settings":!1}};function Vr(){const{config:s,authState:t,_internal:r}=N.useCedrosLogin(),{activeOrg:a,role:n}=as(),[o,c]=i.useState($e),[l,d]=i.useState(!1),[u,g]=i.useState(!1),[m,h]=i.useState(null),b=i.useRef(0),f=i.useMemo(()=>new N.ApiClient({baseUrl:s.serverUrl,timeoutMs:s.requestTimeout,retryAttempts:s.retryAttempts,getAccessToken:r?.getAccessToken}),[s.serverUrl,s.requestTimeout,s.retryAttempts,r]),p=i.useRef(f);p.current=f;const x=i.useCallback(async()=>{if(t!=="authenticated"||!a){c($e);return}d(!0),h(null);const A=++b.current;try{const v=await p.current.get("/admin/dashboard-permissions");if(A!==b.current)return;c(v.permissions)}catch(v){if(A!==b.current)return;if(v instanceof Error&&v.message.includes("404"))c($e);else{const S=v instanceof Error?v.message:"Failed to fetch permissions";h({code:"NETWORK_ERROR",message:S}),c($e)}}finally{A===b.current&&d(!1)}},[t,a]),j=i.useCallback(async A=>{if(t!=="authenticated"||!a)throw new Error("Not authenticated");if(n!=="owner")throw new Error("Only owners can modify dashboard permissions");g(!0),h(null);try{await p.current.request({method:"PUT",path:"/admin/dashboard-permissions",body:A}),c(A)}catch(v){const S=v instanceof Error?v.message:"Failed to update permissions";throw h({code:"NETWORK_ERROR",message:S}),new Error(S)}finally{g(!1)}},[t,a,n]),y=i.useCallback(A=>!a||!n||n==="owner"?!0:o[n]?.[A]??!1,[a,n,o]);return i.useEffect(()=>{a?.id&&x()},[a?.id,x]),{permissions:o,canAccess:y,updatePermissions:j,isLoading:l,isUpdating:u,error:m,fetchPermissions:x}}function ye(){const s=N.useCedrosLoginOptional(),[t,r]=i.useState(!1),[a,n]=i.useState(null),o=i.useMemo(()=>s?new N.ApiClient({baseUrl:s.config.serverUrl,timeoutMs:s.config.requestTimeout,retryAttempts:s.config.retryAttempts,getAccessToken:s._internal?.getAccessToken}):null,[s]),c=i.useCallback(()=>{n(null)},[]),l=i.useCallback(async p=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{const x=new URLSearchParams;p?.status&&x.set("status",p.status),p?.limit!==void 0&&x.set("limit",String(p.limit)),p?.offset!==void 0&&x.set("offset",String(p.offset));const j=x.toString(),y=j?`/admin/deposits?${j}`:"/admin/deposits";return await o.get(y)}catch(x){const j=N.handleApiError(x,"Failed to list deposits");throw n(j.message),j}finally{r(!1)}},[o]),d=i.useCallback(async()=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.get("/admin/deposits/stats")}catch(p){const x=N.handleApiError(p,"Failed to get deposit stats");throw n(x.message),x}finally{r(!1)}},[o]),u=i.useCallback(async p=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{const x=new URLSearchParams;p?.limit!==void 0&&x.set("limit",String(p.limit)),p?.offset!==void 0&&x.set("offset",String(p.offset));const j=x.toString(),y=j?`/admin/deposits/in-privacy-period?${j}`:"/admin/deposits/in-privacy-period";return await o.get(y)}catch(x){const j=N.handleApiError(x,"Failed to list deposits in privacy period");throw n(j.message),j}finally{r(!1)}},[o]),g=i.useCallback(async p=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{const x=new URLSearchParams;p?.limit!==void 0&&x.set("limit",String(p.limit)),p?.offset!==void 0&&x.set("offset",String(p.offset));const j=x.toString(),y=j?`/admin/withdrawals/pending?${j}`:"/admin/withdrawals/pending";return await o.get(y)}catch(x){const j=N.handleApiError(x,"Failed to list pending withdrawals");throw n(j.message),j}finally{r(!1)}},[o]),m=i.useCallback(async(p,x)=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.post(`/admin/withdrawals/${p}/process`,x??{})}catch(j){const y=N.handleApiError(j,"Failed to process withdrawal");throw n(y.message),y}finally{r(!1)}},[o]),h=i.useCallback(async()=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.post("/admin/withdrawals/process-all",{})}catch(p){const x=N.handleApiError(p,"Failed to process withdrawals");throw n(x.message),x}finally{r(!1)}},[o]),b=i.useCallback(async()=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.get("/admin/privacy/status")}catch(p){const x=N.handleApiError(p,"Failed to get privacy status");throw n(x.message),x}finally{r(!1)}},[o]),f=i.useCallback(async()=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.get("/admin/credits/stats")}catch(p){const x=N.handleApiError(p,"Failed to get credit stats");throw n(x.message),x}finally{r(!1)}},[o]);return{listDeposits:l,getStats:d,listInPrivacyPeriod:u,listPendingWithdrawals:g,processWithdrawal:m,processAllWithdrawals:h,getPrivacyStatus:b,getCreditStats:f,isLoading:t,error:a,clearError:c}}const wt={loading:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:e.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),e.jsx("path",{d:"M21 3v5h-5"}),e.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),e.jsx("path",{d:"M8 16H3v5"})]})};function Ce({stats:s,isLoading:t=!1,onRefresh:r}){return e.jsxs("div",{className:"cedros-admin__stats-bar",children:[e.jsx("div",{className:"cedros-admin__stats-bar-grid",children:s.map((a,n)=>e.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[e.jsx("span",{className:"cedros-admin__stats-bar-label",children:a.label}),e.jsx("span",{className:`cedros-admin__stats-bar-value ${a.variant?`cedros-admin__stats-bar-value--${a.variant}`:""}`,children:t?e.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):a.value}),a.description&&e.jsx("span",{className:"cedros-admin__stats-bar-desc",children:a.description})]},n))}),r&&e.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:r,disabled:t,title:"Refresh stats",children:t?wt.loading:wt.refresh})]})}function Hr({refreshInterval:s=0,className:t="",onLoad:r}){const{getStats:a,isLoading:n,error:o,clearError:c}=ye(),[l,d]=i.useState(null),[u,g]=i.useState(null),m=i.useCallback(async()=>{try{const b=await a();d(b),r?.(b),g(null)}catch(b){const f=b&&typeof b=="object"&&"message"in b?String(b.message):"Failed to load stats";g(f)}},[a,r]);i.useEffect(()=>{m()},[m]),i.useEffect(()=>{if(s<=0)return;const b=setInterval(m,s);return()=>clearInterval(b)},[s,m]);const h=u||o;return h?e.jsxs("div",{className:`cedros-admin-stats cedros-admin-stats-error ${t}`,children:[e.jsx("p",{className:"cedros-admin-error",children:h}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{c(),g(null),m()},children:"Retry"})]}):n&&!l?e.jsxs("div",{className:`cedros-admin-stats cedros-admin-stats-loading ${t}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading statistics..."})]}):l?e.jsx("div",{className:`cedros-admin-stats ${t}`,children:e.jsx(Ce,{stats:[{label:"Total Deposits",value:l.totalDeposits},{label:"Private Deposits",value:l.inPrivacyPeriodCount??0},{label:"Standard Deposits",value:l.readyForWithdrawalCount??0},{label:"Microdeposits",value:l.nativeSolDepositCount??0}],isLoading:n,onRefresh:m})}):null}function Qr({refreshInterval:s=0,className:t="",onLoad:r}){const{getStats:a,isLoading:n,error:o,clearError:c}=ye(),[l,d]=i.useState(null),[u,g]=i.useState(null),m=i.useCallback(async()=>{try{const b=await a();d(b),r?.(b),g(null)}catch(b){const f=b&&typeof b=="object"&&"message"in b?String(b.message):"Failed to load stats";g(f)}},[a,r]);i.useEffect(()=>{m()},[m]),i.useEffect(()=>{if(s<=0)return;const b=setInterval(m,s);return()=>clearInterval(b)},[s,m]);const h=u||o;return h?e.jsxs("div",{className:`cedros-admin-stats ${t}`,children:[e.jsx("p",{className:"cedros-admin-error",children:h}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{c(),g(null),m()},children:"Retry"})]}):n&&!l?e.jsx("div",{className:`cedros-admin-stats ${t}`,children:e.jsx(Ce,{stats:[{label:"Total Withdrawn",value:0},{label:"Pending Withdraw",value:0},{label:"In Privacy Period",value:0},{label:"Microbatch (SOL)",value:"0.0000"}],isLoading:!0})}):l?e.jsx("div",{className:`cedros-admin-stats ${t}`,children:e.jsx(Ce,{stats:[{label:"Total Withdrawn",value:l.totalWithdrawnCount},{label:"Pending Withdraw",value:l.pendingWithdrawalCount},{label:"In Privacy Period",value:l.inPrivacyPeriodCount??0},{label:"Microbatch (SOL)",value:l.readyForWithdrawalSol?.toFixed(4)??"0.0000"}],isLoading:n,onRefresh:m})}):null}function Vo(s){return{pending:"Pending",detected:"Detected",processing:"Processing",completed:"Completed",withdrawn:"Withdrawn",partially_withdrawn:"Partially Withdrawn",expired:"Expired",failed:"Failed"}[s]||s}function Ho(s){return s==="completed"||s==="withdrawn"||s==="partially_withdrawn"?"cedros-admin-deposit-success":s==="failed"||s==="expired"?"cedros-admin-deposit-error":s==="processing"||s==="detected"?"cedros-admin-deposit-processing":"cedros-admin-deposit-pending"}function Qo(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function Ko(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function xt(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function Kr({statusFilter:s,pageSize:t=20,refreshInterval:r=0,className:a="",onLoad:n,onDepositClick:o}){const{listDeposits:c,isLoading:l,error:d,clearError:u}=ye(),[g,m]=i.useState([]),[h,b]=i.useState(0),[f,p]=i.useState(0),[x,j]=i.useState(null),[y,A]=i.useState("createdAt"),[v,S]=i.useState("desc"),w=_=>{y===_?S(v==="asc"?"desc":"asc"):(A(_),S("desc"))},E=i.useMemo(()=>[...g].sort((_,M)=>{let D,B;switch(y){case"userId":D=_.userId.toLowerCase(),B=M.userId.toLowerCase();break;case"amountLamports":D=_.amountLamports??0,B=M.amountLamports??0;break;case"status":D=_.status,B=M.status;break;case"createdAt":D=new Date(_.createdAt).getTime(),B=new Date(M.createdAt).getTime();break;case"txSignature":D=_.txSignature||"",B=M.txSignature||"";break;default:return 0}return D<B?v==="asc"?-1:1:D>B?v==="asc"?1:-1:0}),[g,y,v]),P=i.useCallback(async()=>{try{const _=await c({status:s,limit:t,offset:f});m(_.deposits),b(_.total),n?.(_),j(null)}catch(_){const M=_&&typeof _=="object"&&"message"in _?String(_.message):"Failed to load deposits";j(M)}},[s,t,f,c,n]);i.useEffect(()=>{p(0)},[s,t]),i.useEffect(()=>{P()},[P]),i.useEffect(()=>{if(r<=0)return;const _=setInterval(P,r);return()=>clearInterval(_)},[r,P]);const L=Math.ceil(h/t),T=Math.floor(f/t)+1,C=_=>{const M=(_-1)*t;p(Math.max(0,Math.min(M,Math.max(0,h-1))))},k=x||d;return k?e.jsxs("div",{className:`cedros-admin-deposit-list cedros-admin-deposit-list-error ${a}`,children:[e.jsx("p",{className:"cedros-admin-error",children:k}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{u(),j(null),P()},children:"Retry"})]}):l&&g.length===0?e.jsxs("div",{className:`cedros-admin-deposit-list cedros-admin-deposit-list-loading ${a}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading deposits..."})]}):e.jsxs("div",{className:`cedros-admin-deposit-list ${a}`,children:[e.jsxs("div",{className:"cedros-admin-deposit-list-header",children:[e.jsx("h4",{className:"cedros-admin-deposit-list-title",children:"All Deposits"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:P,disabled:l,title:"Refresh deposits","aria-label":"Refresh deposits",children:l?"...":"↻"})]}),g.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No deposits found."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-deposit-table",children:[e.jsxs("div",{className:"cedros-admin-deposit-thead",children:[e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="userId"?"cedros-admin-sort-active":""}`,onClick:()=>w("userId"),"aria-label":"Sort by user",children:["User"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="userId"?v==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="amountLamports"?"cedros-admin-sort-active":""}`,onClick:()=>w("amountLamports"),"aria-label":"Sort by amount",children:["Amount"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="amountLamports"?v==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="status"?"cedros-admin-sort-active":""}`,onClick:()=>w("status"),"aria-label":"Sort by status",children:["Status"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="status"?v==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="createdAt"?"cedros-admin-sort-active":""}`,onClick:()=>w("createdAt"),"aria-label":"Sort by created",children:["Created"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="createdAt"?v==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="txSignature"?"cedros-admin-sort-active":""}`,onClick:()=>w("txSignature"),"aria-label":"Sort by transaction",children:["Tx"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="txSignature"?v==="asc"?"↑":"↓":"↕"})]})})]}),E.map(_=>e.jsxs("div",{className:`cedros-admin-deposit-row ${Ho(_.status)}`,onClick:()=>o?.(_),onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),o?.(_))},role:o?"button":void 0,tabIndex:o?0:void 0,children:[e.jsx("div",{className:"cedros-admin-deposit-td",title:_.userId,children:xt(_.userId)}),e.jsx("div",{className:"cedros-admin-deposit-td",children:Qo(_.amountLamports)}),e.jsx("div",{className:"cedros-admin-deposit-td",children:e.jsx("span",{className:"cedros-admin-status-badge",children:Vo(_.status)})}),e.jsx("div",{className:"cedros-admin-deposit-td",children:Ko(_.createdAt)}),e.jsx("div",{className:"cedros-admin-deposit-td",title:_.txSignature||void 0,children:_.txSignature?xt(_.txSignature):"—"})]},_.id))]}),L>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>C(T-1),disabled:T<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",T," of ",L," (",h," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>C(T+1),disabled:T>=L,children:"Next"})]})]})]})}function vt(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function jt(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function At(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function Go(s){const t=new Date(s),a=new Date().getTime()-t.getTime(),n=Math.floor(a/6e4),o=Math.floor(n/60),c=Math.floor(o/24);return c>0?`${c}d ago`:o>0?`${o}h ago`:n>0?`${n}m ago`:"just now"}function kt(s){return s?new Date(s)>new Date:!0}function Gr({pageSize:s=20,refreshInterval:t=0,className:r="",onLoad:a,onItemClick:n,onWithdrawalProcessed:o,onAllProcessed:c}){const{listPendingWithdrawals:l,processWithdrawal:d,processAllWithdrawals:u,isLoading:g,error:m,clearError:h}=ye(),[b,f]=i.useState([]),[p,x]=i.useState(0),[j,y]=i.useState(0),[A,v]=i.useState(null),[S,w]=i.useState("withdrawalAvailableAt"),[E,P]=i.useState("asc"),L=R=>{S===R?P(E==="asc"?"desc":"asc"):(w(R),P(R==="withdrawalAvailableAt"?"asc":"desc"))},T=i.useMemo(()=>[...b].sort((R,F)=>{let U,q;switch(S){case"userId":U=R.userId.toLowerCase(),q=F.userId.toLowerCase();break;case"amountLamports":U=R.amountLamports??0,q=F.amountLamports??0;break;case"withdrawalAvailableAt":U=R.withdrawalAvailableAt?new Date(R.withdrawalAvailableAt).getTime():0,q=F.withdrawalAvailableAt?new Date(F.withdrawalAvailableAt).getTime():0;break;default:return 0}return U<q?E==="asc"?-1:1:U>q?E==="asc"?1:-1:0}),[b,S,E]),[C,k]=i.useState(null),[_,M]=i.useState(!1),[D,B]=i.useState(null),[Q,Y]=i.useState(null),O=i.useCallback(async()=>{try{const R=await l({limit:s,offset:j});f(R.deposits),x(R.total),a?.(R),v(null)}catch(R){const F=R&&typeof R=="object"&&"message"in R?String(R.message):"Failed to load pending withdrawals";v(F)}},[s,j,l,a]);i.useEffect(()=>{y(0)},[s]),i.useEffect(()=>{O()},[O]),i.useEffect(()=>{if(t<=0)return;const R=setInterval(O,t);return()=>clearInterval(R)},[t,O]),i.useEffect(()=>{if(!D)return;const R=setTimeout(()=>B(null),5e3);return()=>clearTimeout(R)},[D]);const $=Math.ceil(p/s),I=Math.floor(j/s)+1,H=R=>{const F=(R-1)*s;y(Math.max(0,Math.min(F,Math.max(0,p-1))))},ee=async(R,F=!1)=>{if(!F&&kt(R.withdrawalAvailableAt)){Y(R);return}k(R.id),B(null);try{const U=await d(R.id,{force:F});U.success?(B({type:"success",message:`Withdrawal processed: ${U.txSignature?.slice(0,12)}...`}),o?.(U),await O()):B({type:"error",message:U.error||"Failed to process withdrawal"})}catch(U){B({type:"error",message:U instanceof Error?U.message:"Failed to process withdrawal"})}finally{k(null),Y(null)}},Z=async()=>{if(b.length!==0){M(!0),B(null);try{const R=await u();R.totalSucceeded>0?B({type:"success",message:`Processed ${R.totalSucceeded}/${R.totalProcessed} withdrawals`}):R.totalFailed>0&&B({type:"error",message:`Failed to process ${R.totalFailed} withdrawals`}),c?.(R),await O()}catch(R){B({type:"error",message:R instanceof Error?R.message:"Failed to process withdrawals"})}finally{M(!1)}}},K=A||m;return K?e.jsxs("div",{className:`cedros-admin-withdrawal-queue cedros-admin-withdrawal-queue-error ${r}`,children:[e.jsx("p",{className:"cedros-admin-error",children:K}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{h(),v(null),O()},children:"Retry"})]}):g&&b.length===0&&!C&&!_?e.jsxs("div",{className:`cedros-admin-withdrawal-queue cedros-admin-withdrawal-queue-loading ${r}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading withdrawal queue..."})]}):e.jsxs("div",{className:`cedros-admin-withdrawal-queue ${r}`,children:[Q&&e.jsx("div",{className:"cedros-admin-modal-overlay",onClick:()=>Y(null),onKeyDown:R=>R.key==="Escape"&&Y(null),role:"dialog","aria-modal":"true","aria-labelledby":"early-withdrawal-title",children:e.jsxs("div",{className:"cedros-admin-modal cedros-admin-modal-warning",onClick:R=>R.stopPropagation(),onKeyDown:()=>{},role:"document",children:[e.jsx("h3",{id:"early-withdrawal-title",className:"cedros-admin-modal-title",children:"Early Withdrawal Warning"}),e.jsxs("div",{className:"cedros-admin-modal-content",children:[e.jsx("p",{className:"cedros-admin-modal-warning-text",children:e.jsx("strong",{children:"This deposit is still within its privacy period."})}),e.jsx("p",{children:"Processing this withdrawal early may compromise user privacy. The privacy period exists to provide plausible deniability for deposits."}),e.jsxs("p",{className:"cedros-admin-modal-details",children:["User: ",At(Q.userId),e.jsx("br",{}),"Amount: ",vt(Q.amountLamports),e.jsx("br",{}),"Available at:"," ",Q.withdrawalAvailableAt?jt(Q.withdrawalAvailableAt):"—"]}),e.jsx("p",{children:"Are you sure you want to process this withdrawal early?"})]}),e.jsxs("div",{className:"cedros-admin-modal-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>Y(null),children:"Cancel"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-danger",onClick:()=>ee(Q,!0),disabled:C===Q.id,children:C===Q.id?"Processing...":"Process Early"})]})]})}),D&&e.jsx("div",{className:`cedros-admin-result cedros-admin-result-${D.type}`,role:"status","aria-live":"polite",children:D.message}),e.jsxs("div",{className:"cedros-admin-withdrawal-queue-header",children:[e.jsx("h4",{className:"cedros-admin-withdrawal-queue-title",children:"Pending Withdrawals"}),e.jsxs("div",{className:"cedros-admin-withdrawal-queue-actions",children:[e.jsxs("span",{className:"cedros-admin-queue-count",children:[p," pending"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:O,disabled:g||_,title:"Refresh queue","aria-label":"Refresh queue",children:g&&!_?"...":"↻"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary cedros-button-sm",onClick:Z,disabled:g||_||b.length===0,title:"Process all ready withdrawals",children:_?"Processing...":"Process All"})]})]}),b.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No pending withdrawals."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-withdrawal-table",children:[e.jsxs("div",{className:"cedros-admin-withdrawal-thead",children:[e.jsx("div",{className:"cedros-admin-withdrawal-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${S==="userId"?"cedros-admin-sort-active":""}`,onClick:()=>L("userId"),"aria-label":"Sort by user",children:["User"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:S==="userId"?E==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-withdrawal-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${S==="amountLamports"?"cedros-admin-sort-active":""}`,onClick:()=>L("amountLamports"),"aria-label":"Sort by amount",children:["Amount"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:S==="amountLamports"?E==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-withdrawal-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${S==="withdrawalAvailableAt"?"cedros-admin-sort-active":""}`,onClick:()=>L("withdrawalAvailableAt"),"aria-label":"Sort by ready since",children:["Ready Since"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:S==="withdrawalAvailableAt"?E==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-withdrawal-th",children:"Waiting"}),e.jsx("div",{className:"cedros-admin-withdrawal-th cedros-admin-withdrawal-th-action",children:"Action"})]}),T.map(R=>{const F=kt(R.withdrawalAvailableAt),U=C===R.id;return e.jsxs("div",{className:`cedros-admin-withdrawal-row ${F?"cedros-admin-withdrawal-row-early":""}`,onClick:()=>n?.(R),onKeyDown:q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),n?.(R))},role:n?"button":void 0,tabIndex:n?0:void 0,children:[e.jsx("div",{className:"cedros-admin-withdrawal-td",title:R.userId,children:At(R.userId)}),e.jsx("div",{className:"cedros-admin-withdrawal-td",children:vt(R.amountLamports)}),e.jsx("div",{className:"cedros-admin-withdrawal-td",children:R.withdrawalAvailableAt?jt(R.withdrawalAvailableAt):"—"}),e.jsx("div",{className:"cedros-admin-withdrawal-td cedros-admin-withdrawal-waiting",children:R.withdrawalAvailableAt?F?"In privacy period":Go(R.withdrawalAvailableAt):"—"}),e.jsx("div",{className:"cedros-admin-withdrawal-td cedros-admin-withdrawal-td-action",children:e.jsx("button",{type:"button",className:`cedros-button cedros-button-sm ${F?"cedros-button-warning":"cedros-button-primary"}`,onClick:q=>{q.stopPropagation(),ee(R)},disabled:U||_,title:F?"Early withdrawal (requires confirmation)":"Process this withdrawal",children:U?"...":F?"Early":"Process"})})]},R.id)})]}),$>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>H(I-1),disabled:I<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",I," of ",$," (",p," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>H(I+1),disabled:I>=$,children:"Next"})]})]})]})}function Yo(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function Jo(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Xo(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function Zo(s){const t=new Date(s),r=new Date,a=t.getTime()-r.getTime();if(a<=0)return"Ready";const n=Math.floor(a/6e4),o=Math.floor(n/60),c=Math.floor(o/24);if(c>0){const l=o%24;return l>0?`${c}d ${l}h`:`${c}d`}if(o>0){const l=n%60;return l>0?`${o}h ${l}m`:`${o}h`}return`${n}m`}function Yr({pageSize:s=20,refreshInterval:t=0,className:r="",onLoad:a,onItemClick:n}){const{listInPrivacyPeriod:o,isLoading:c,error:l,clearError:d}=ye(),[u,g]=i.useState([]),[m,h]=i.useState(0),[b,f]=i.useState(0),[p,x]=i.useState(null),j=i.useCallback(async()=>{try{const w=await o({limit:s,offset:b});g(w.deposits),h(w.total),a?.(w),x(null)}catch(w){const E=w&&typeof w=="object"&&"message"in w?String(w.message):"Failed to load deposits";x(E)}},[s,b,o,a]);i.useEffect(()=>{f(0)},[s]),i.useEffect(()=>{j()},[j]),i.useEffect(()=>{if(t<=0)return;const w=setInterval(j,t);return()=>clearInterval(w)},[t,j]);const y=Math.ceil(m/s),A=Math.floor(b/s)+1,v=w=>{const E=(w-1)*s;f(Math.max(0,Math.min(E,Math.max(0,m-1))))},S=p||l;return S?e.jsxs("div",{className:`cedros-admin-privacy-deposits cedros-admin-privacy-deposits-error ${r}`,children:[e.jsx("p",{className:"cedros-admin-error",children:S}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{d(),x(null),j()},children:"Retry"})]}):c&&u.length===0?e.jsxs("div",{className:`cedros-admin-privacy-deposits cedros-admin-privacy-deposits-loading ${r}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading deposits..."})]}):e.jsxs("div",{className:`cedros-admin-privacy-deposits ${r}`,children:[e.jsxs("div",{className:"cedros-admin-privacy-deposits-header",children:[e.jsx("h4",{className:"cedros-admin-privacy-deposits-title",children:"In Privacy Period"}),e.jsxs("div",{className:"cedros-admin-privacy-deposits-actions",children:[e.jsxs("span",{className:"cedros-admin-queue-count",children:[m," deposit",m!==1?"s":""]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:j,disabled:c,title:"Refresh list","aria-label":"Refresh list",children:c?"...":"↻"})]})]}),u.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No deposits in privacy period."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-privacy-table",children:[e.jsxs("div",{className:"cedros-admin-privacy-thead",children:[e.jsx("div",{className:"cedros-admin-privacy-th",children:e.jsxs("button",{type:"button",className:"cedros-admin-sort-button","aria-label":"Sort by user",children:["User ",e.jsx("span",{className:"cedros-admin-sort-icon",children:"↕"})]})}),e.jsx("div",{className:"cedros-admin-privacy-th",children:e.jsxs("button",{type:"button",className:"cedros-admin-sort-button","aria-label":"Sort by amount",children:["Amount ",e.jsx("span",{className:"cedros-admin-sort-icon",children:"↕"})]})}),e.jsx("div",{className:"cedros-admin-privacy-th",children:e.jsxs("button",{type:"button",className:"cedros-admin-sort-button","aria-label":"Sort by deposited",children:["Deposited ",e.jsx("span",{className:"cedros-admin-sort-icon",children:"↕"})]})}),e.jsx("div",{className:"cedros-admin-privacy-th",children:e.jsxs("button",{type:"button",className:"cedros-admin-sort-button","aria-label":"Sort by ready in",children:["Ready In ",e.jsx("span",{className:"cedros-admin-sort-icon",children:"↕"})]})})]}),u.map(w=>e.jsxs("div",{className:"cedros-admin-privacy-row",onClick:()=>n?.(w),onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),n?.(w))},role:n?"button":void 0,tabIndex:n?0:void 0,children:[e.jsx("div",{className:"cedros-admin-privacy-td",title:w.userId,children:Xo(w.userId)}),e.jsx("div",{className:"cedros-admin-privacy-td",children:Yo(w.amountLamports)}),e.jsx("div",{className:"cedros-admin-privacy-td",children:w.completedAt?Jo(w.completedAt):"—"}),e.jsx("div",{className:"cedros-admin-privacy-td cedros-admin-privacy-remaining",children:w.withdrawalAvailableAt?Zo(w.withdrawalAvailableAt):"—"})]},w.id))]}),y>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>v(A-1),disabled:A<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",A," of ",y," (",m," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>v(A+1),disabled:A>=y,children:"Next"})]})]})]})}function ei(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function si(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ti(s){return s.length<=16?s:`${s.slice(0,8)}...${s.slice(-6)}`}function ri(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function Jr({pageSize:s=20,refreshInterval:t=0,className:r="",onLoad:a,onItemClick:n}){const{listDeposits:o,isLoading:c,error:l,clearError:d}=ye(),[u,g]=i.useState([]),[m,h]=i.useState(0),[b,f]=i.useState(0),[p,x]=i.useState(null),[j,y]=i.useState("completedAt"),[A,v]=i.useState("desc"),S=k=>{j===k?v(A==="asc"?"desc":"asc"):(y(k),v("desc"))},w=i.useMemo(()=>[...u].sort((k,_)=>{let M,D;switch(j){case"userId":M=k.userId.toLowerCase(),D=_.userId.toLowerCase();break;case"amountLamports":M=k.amountLamports??0,D=_.amountLamports??0;break;case"completedAt":M=k.completedAt?new Date(k.completedAt).getTime():0,D=_.completedAt?new Date(_.completedAt).getTime():0;break;case"withdrawalTxSignature":M=k.withdrawalTxSignature||"",D=_.withdrawalTxSignature||"";break;default:return 0}return M<D?A==="asc"?-1:1:M>D?A==="asc"?1:-1:0}),[u,j,A]),E=i.useCallback(async()=>{try{const k=await o({status:"withdrawn",limit:s,offset:b});g(k.deposits),h(k.total),a?.(k),x(null)}catch(k){const _=k&&typeof k=="object"&&"message"in k?String(k.message):"Failed to load withdrawal history";x(_)}},[s,b,o,a]);i.useEffect(()=>{f(0)},[s]),i.useEffect(()=>{E()},[E]),i.useEffect(()=>{if(t<=0)return;const k=setInterval(E,t);return()=>clearInterval(k)},[t,E]);const P=Math.ceil(m/s),L=Math.floor(b/s)+1,T=k=>{const _=(k-1)*s;f(Math.max(0,Math.min(_,Math.max(0,m-1))))},C=p||l;return C?e.jsxs("div",{className:`cedros-admin-withdrawal-history cedros-admin-withdrawal-history-error ${r}`,children:[e.jsx("p",{className:"cedros-admin-error",children:C}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{d(),x(null),E()},children:"Retry"})]}):c&&u.length===0?e.jsxs("div",{className:`cedros-admin-withdrawal-history cedros-admin-withdrawal-history-loading ${r}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading withdrawal history..."})]}):e.jsxs("div",{className:`cedros-admin-withdrawal-history ${r}`,children:[e.jsxs("div",{className:"cedros-admin-withdrawal-history-header",children:[e.jsx("h4",{className:"cedros-admin-withdrawal-history-title",children:"Withdrawal History"}),e.jsxs("div",{className:"cedros-admin-withdrawal-history-actions",children:[e.jsxs("span",{className:"cedros-admin-queue-count",children:[m," withdrawal",m!==1?"s":""]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:E,disabled:c,title:"Refresh list","aria-label":"Refresh list",children:c?"...":"↻"})]})]}),u.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No withdrawals processed yet."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-history-table",children:[e.jsxs("div",{className:"cedros-admin-history-thead",children:[e.jsx("div",{className:"cedros-admin-history-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${j==="userId"?"cedros-admin-sort-active":""}`,onClick:()=>S("userId"),"aria-label":"Sort by user",children:["User"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:j==="userId"?A==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-history-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${j==="amountLamports"?"cedros-admin-sort-active":""}`,onClick:()=>S("amountLamports"),"aria-label":"Sort by amount",children:["Amount"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:j==="amountLamports"?A==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-history-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${j==="completedAt"?"cedros-admin-sort-active":""}`,onClick:()=>S("completedAt"),"aria-label":"Sort by processed",children:["Processed"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:j==="completedAt"?A==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-history-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${j==="withdrawalTxSignature"?"cedros-admin-sort-active":""}`,onClick:()=>S("withdrawalTxSignature"),"aria-label":"Sort by transaction",children:["Transaction"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:j==="withdrawalTxSignature"?A==="asc"?"↑":"↓":"↕"})]})})]}),w.map(k=>e.jsxs("div",{className:"cedros-admin-history-row",onClick:()=>n?.(k),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),n?.(k))},role:n?"button":void 0,tabIndex:n?0:void 0,children:[e.jsx("div",{className:"cedros-admin-history-td",title:k.userId,children:ri(k.userId)}),e.jsx("div",{className:"cedros-admin-history-td",children:ei(k.amountLamports)}),e.jsx("div",{className:"cedros-admin-history-td",children:k.completedAt?si(k.completedAt):"—"}),e.jsx("div",{className:"cedros-admin-history-td",children:k.withdrawalTxSignature?e.jsx("a",{href:`https://orbmarkets.io/tx/${k.withdrawalTxSignature}`,target:"_blank",rel:"noopener noreferrer",className:"cedros-admin-tx-link",onClick:_=>_.stopPropagation(),title:k.withdrawalTxSignature,children:ti(k.withdrawalTxSignature)}):"—"})]},k.id))]}),P>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>T(L-1),disabled:L<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",L," of ",P," (",m," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>T(L+1),disabled:L>=P,children:"Next"})]})]})]})}function Nt(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ni(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function ai(s){return s==null?"-":(s/1e9).toFixed(4)}function Xr({pageSize:s=20,refreshInterval:t=0,currentUserId:r,className:a="",onLoad:n,onUserClick:o}){const{users:c,total:l,isLoading:d,error:u,listUsers:g,clearError:m}=os(),[h,b]=i.useState(0),[f,p]=i.useState(null),[x,j]=i.useState("createdAt"),[y,A]=i.useState("desc"),v=T=>{x===T?A(y==="asc"?"desc":"asc"):(j(T),A("desc"))},S=i.useMemo(()=>[...c].sort((T,C)=>{let k,_;switch(x){case"name":k=(T.name||T.email||"").toLowerCase(),_=(C.name||C.email||"").toLowerCase();break;case"createdAt":k=new Date(T.createdAt).getTime(),_=new Date(C.createdAt).getTime();break;case"lastLoginAt":k=T.lastLoginAt?new Date(T.lastLoginAt).getTime():0,_=C.lastLoginAt?new Date(C.lastLoginAt).getTime():0;break;case"balanceLamports":k=T.balanceLamports??0,_=C.balanceLamports??0;break;default:return 0}return k<_?y==="asc"?-1:1:k>_?y==="asc"?1:-1:0}),[c,x,y]),w=i.useCallback(async()=>{try{const T=await g({limit:s,offset:h});n?.(T),p(null)}catch(T){p(T instanceof Error?T.message:"Failed to load users")}},[s,h,g,n]);i.useEffect(()=>{b(0)},[s]),i.useEffect(()=>{w()},[w]),i.useEffect(()=>{if(t<=0)return;const T=setInterval(w,t);return()=>clearInterval(T)},[t,w]);const E=Math.ceil(l/s),P=Math.floor(h/s)+1,L=T=>{const C=(T-1)*s;b(Math.max(0,Math.min(C,Math.max(0,l-1))))};return f||u?e.jsxs("div",{className:`cedros-admin-user-list cedros-admin-user-list-error ${a}`,children:[e.jsx("p",{className:"cedros-admin-error",children:f||u?.message}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{m(),p(null),w()},children:"Retry"})]}):d&&c.length===0?e.jsxs("div",{className:`cedros-admin-user-list cedros-admin-user-list-loading ${a}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading users..."})]}):e.jsxs("div",{className:`cedros-admin-user-list ${a}`,children:[e.jsxs("div",{className:"cedros-admin-user-list-header",children:[e.jsx("h4",{className:"cedros-admin-user-list-title",children:"All Users"}),e.jsxs("div",{className:"cedros-admin-user-list-actions",children:[e.jsxs("span",{className:"cedros-admin-queue-count",children:[l," user",l!==1?"s":""]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:w,disabled:d,title:"Refresh list","aria-label":"Refresh list",children:d?"...":"↻"})]})]}),c.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No users found."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-user-table",children:[e.jsxs("div",{className:"cedros-admin-user-thead",children:[e.jsx("div",{className:"cedros-admin-user-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${x==="name"?"cedros-admin-sort-active":""}`,onClick:()=>v("name"),"aria-label":"Sort by user",children:["User"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:x==="name"?y==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-user-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${x==="createdAt"?"cedros-admin-sort-active":""}`,onClick:()=>v("createdAt"),"aria-label":"Sort by registered date",children:["Registered"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:x==="createdAt"?y==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-user-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${x==="lastLoginAt"?"cedros-admin-sort-active":""}`,onClick:()=>v("lastLoginAt"),"aria-label":"Sort by last login",children:["Last Login"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:x==="lastLoginAt"?y==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-user-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${x==="balanceLamports"?"cedros-admin-sort-active":""}`,onClick:()=>v("balanceLamports"),"aria-label":"Sort by balance",children:["Balance"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:x==="balanceLamports"?y==="asc"?"↑":"↓":"↕"})]})})]}),S.map(T=>{const C=T.id===r;return e.jsxs("div",{className:`cedros-admin-user-row ${C?"cedros-admin-user-row-current":""}`,onClick:()=>o?.(T),onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),o?.(T))},role:o?"button":void 0,tabIndex:o?0:void 0,children:[e.jsxs("div",{className:"cedros-admin-user-td cedros-admin-user-info",children:[e.jsx("div",{className:"cedros-admin-user-avatar",children:T.picture?e.jsx("img",{src:T.picture,alt:T.name||T.email||"User",className:"cedros-admin-user-avatar-img",referrerPolicy:"no-referrer"}):e.jsx("span",{className:"cedros-admin-user-avatar-placeholder",children:(T.name?.[0]||T.email?.[0]||"?").toUpperCase()})}),e.jsxs("div",{className:"cedros-admin-user-details",children:[e.jsxs("span",{className:"cedros-admin-user-name",children:[T.name||"Unknown",C&&e.jsx("span",{className:"cedros-admin-user-you",children:"(you)"})]}),e.jsx("span",{className:"cedros-admin-user-email",title:T.email,children:T.email||ni(T.id)})]})]}),e.jsx("div",{className:"cedros-admin-user-td",children:Nt(T.createdAt)}),e.jsx("div",{className:"cedros-admin-user-td",children:T.lastLoginAt?Nt(T.lastLoginAt):"-"}),e.jsx("div",{className:"cedros-admin-user-td",children:ai(T.balanceLamports)})]},T.id)})]}),E>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>L(P-1),disabled:P<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",P," of ",E," (",l," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>L(P+1),disabled:P>=E,children:"Next"})]})]})]})}function St(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Ys(s){return new Date(s).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function oi(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function He(s){return s==null?"—":(s/1e9).toFixed(4)}function ii(s){return{DEPOSIT:"Deposit",SPEND:"Spend",ADJUSTMENT:"Adjustment",REFUND:"Refund"}[s.toUpperCase()]||s}function li(s,t){return t?{deposit:"Credit deposit",purchase:"Purchase",api_call:"API usage",subscription:"Subscription",refund:"Refund",bonus:"Bonus credit",promo:"Promotional credit",correction:"Balance correction"}[t.toLowerCase()]||t:{DEPOSIT:"Credit added",SPEND:"Credit used",ADJUSTMENT:"Manual adjustment",REFUND:"Credit refunded"}[s.toUpperCase()]||"—"}function Zr({userId:s,onBack:t,currentUserId:r,onEditUser:a,onAdjustCredits:n,cedrosPayEnabled:o=!1,className:c=""}){const{isLoading:l,getUser:d,getUserDeposits:u,getUserCredits:g,getUserChats:m,deleteUser:h,forcePasswordReset:b,clearError:f}=os(),[p,x]=i.useState(null),[j,y]=i.useState(null),[A,v]=i.useState(null),[S,w]=i.useState(null),[E,P]=i.useState("deposits"),[L,T]=i.useState(null),[C,k]=i.useState(null),[_,M]=i.useState(null),[D,B]=i.useState(null),[Q,Y]=i.useState(!1),[O,$]=i.useState(0),[I,H]=i.useState(0),[ee,Z]=i.useState(0),K=10,R=i.useCallback(async()=>{try{const z=await d(s);x(z),T(null)}catch(z){T(z instanceof Error?z.message:"Failed to load user")}},[s,d]),F=i.useCallback(async()=>{try{const he=await u(s,{limit:K,offset:O});v(he),M(null)}catch(z){M(z instanceof Error?z.message:"Failed to load deposits")}},[s,u,O]),U=i.useCallback(async()=>{try{const he=await g(s,{limit:K,offset:I});y(he),k(null)}catch(z){k(z instanceof Error?z.message:"Failed to load credits")}},[s,g,I]),q=i.useCallback(async()=>{if(o)try{const he=await m(s,{limit:K,offset:ee});w(he),B(null)}catch(z){B(z instanceof Error?z.message:"Failed to load chat history")}},[s,m,ee,o]);i.useEffect(()=>{R(),F(),U(),o&&q()},[R,F,U,q,o]);const re=async()=>{if(!p)return;if(p.id===r){alert("You cannot delete your own account");return}if(p.isSystemAdmin){alert("Cannot delete a system admin. Remove admin status first.");return}if(window.confirm(`Are you sure you want to delete ${p.name||p.email||"this user"}? This action cannot be undone.`)){Y(!0);try{await h(p.id),t()}catch{}finally{Y(!1)}}},de=async()=>{if(!p?.email){alert("User has no email address");return}if(window.confirm(`Send a password reset email to ${p.email}?`)){Y(!0);try{await b(p.id),alert("Password reset email sent")}catch{}finally{Y(!1)}}},Ie=A?Math.ceil(A.total/K):0,Pe=Math.floor(O/K)+1,fe=j?Math.ceil(j.totalTransactions/K):0,cs=Math.floor(I/K)+1,Le=z=>{$((z-1)*K)},ve=z=>{H((z-1)*K)},Ue=S?Math.ceil(S.total/K):0,ds=Math.floor(ee/K)+1,us=z=>{Z((z-1)*K)};if(L)return e.jsxs("div",{className:`cedros-admin-user-detail cedros-admin-user-detail-error ${c}`,children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:t,children:"Back"}),e.jsx("p",{className:"cedros-admin-error",children:L}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{f(),T(null),R()},children:"Retry"})]});if(l&&!p)return e.jsxs("div",{className:`cedros-admin-user-detail cedros-admin-user-detail-loading ${c}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading user..."})]});if(!p)return e.jsxs("div",{className:`cedros-admin-user-detail ${c}`,children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:t,children:"Back"}),e.jsx("p",{className:"cedros-admin-empty-message",children:"User not found."})]});const ge=p.id===r;return e.jsxs("div",{className:`cedros-admin-user-detail ${c}`,children:[e.jsxs("div",{className:"cedros-admin-user-detail-header",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-back-btn",onClick:t,children:"Back to Users"}),e.jsxs("div",{className:"cedros-admin-user-detail-actions",children:[a&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>a(p),disabled:Q,children:"Edit"}),p.email&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:de,disabled:Q,children:"Reset Password"}),n&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>n(p),disabled:Q,children:"Adjust Credits"}),!ge&&!p.isSystemAdmin&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-btn-danger",onClick:re,disabled:Q,children:"Delete"})]})]}),e.jsxs("div",{className:"cedros-admin-user-detail-info",children:[e.jsx("div",{className:"cedros-admin-user-detail-avatar",children:p.picture?e.jsx("img",{src:p.picture,alt:p.name||p.email||"User",className:"cedros-admin-user-detail-avatar-img",referrerPolicy:"no-referrer"}):e.jsx("span",{className:"cedros-admin-user-detail-avatar-placeholder",children:(p.name?.[0]||p.email?.[0]||"?").toUpperCase()})}),e.jsxs("div",{className:"cedros-admin-user-detail-meta",children:[e.jsxs("h2",{className:"cedros-admin-user-detail-name",children:[p.name||"Unknown",ge&&e.jsx("span",{className:"cedros-admin-user-you",children:"(you)"})]}),e.jsxs("p",{className:"cedros-admin-user-detail-email",children:[p.email||"No email",p.emailVerified&&e.jsx("span",{className:"cedros-admin-verified-badge",title:"Email verified",children:"Verified"})]}),p.isSystemAdmin&&e.jsx("div",{className:"cedros-admin-user-detail-badges",children:e.jsx("span",{className:"cedros-admin-admin-badge cedros-admin-admin-badge-yes",children:"System Admin"})}),e.jsxs("div",{className:"cedros-admin-user-detail-methods",children:[e.jsx("span",{className:"cedros-admin-user-detail-methods-label",children:"Auth Methods:"}),p.authMethods.length>0?p.authMethods.map(z=>e.jsx("span",{className:`cedros-admin-auth-badge cedros-admin-auth-badge-${z}`,children:z},z)):e.jsx("span",{className:"cedros-admin-auth-badge cedros-admin-auth-badge-none",children:"none"})]}),e.jsxs("p",{className:"cedros-admin-user-detail-dates",children:["Registered: ",St(p.createdAt)," | Updated: ",St(p.updatedAt)]})]})]}),C?e.jsxs("div",{className:"cedros-admin-stats-error",children:[e.jsx("p",{className:"cedros-admin-error-inline",children:C}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>{k(null),U()},children:"Retry"})]}):j?e.jsxs("div",{className:"cedros-admin-user-detail-stats",children:[e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Credit Balance"}),e.jsx("span",{className:"cedros-admin-stat-value",children:He(j.stats.currentBalanceLamports)})]}),e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Total Credited"}),e.jsx("span",{className:"cedros-admin-stat-value",children:He(j.stats.totalDepositedLamports)})]}),e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Total Spent"}),e.jsx("span",{className:"cedros-admin-stat-value",children:He(j.stats.totalSpentLamports)})]}),e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Deposits"}),e.jsx("span",{className:"cedros-admin-stat-value",children:j.stats.depositCount})]}),e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Transactions"}),e.jsx("span",{className:"cedros-admin-stat-value",children:j.stats.spendCount})]})]}):e.jsxs("div",{className:"cedros-admin-stats-loading",children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{children:"Loading credit stats..."})]}),e.jsxs("div",{className:"cedros-admin-user-detail-tabs",children:[e.jsxs("button",{type:"button",className:`cedros-admin-tab ${E==="deposits"?"cedros-admin-tab-active":""}`,onClick:()=>P("deposits"),children:["Deposits (",A?.total??0,")"]}),e.jsxs("button",{type:"button",className:`cedros-admin-tab ${E==="transactions"?"cedros-admin-tab-active":""}`,onClick:()=>P("transactions"),children:["Credits (",j?.totalTransactions??0,")"]}),o&&e.jsxs("button",{type:"button",className:`cedros-admin-tab ${E==="chats"?"cedros-admin-tab-active":""}`,onClick:()=>P("chats"),children:["Chats (",S?.total??0,")"]})]}),e.jsxs("div",{className:"cedros-admin-user-detail-content",children:[E==="deposits"&&e.jsx(ci,{deposits:A?.deposits??[],total:A?.total??0,currentPage:Pe,totalPages:Ie,onPageChange:Le,isLoading:l,error:_,onRetry:()=>{M(null),F()}}),E==="transactions"&&e.jsx(di,{transactions:j?.transactions??[],total:j?.totalTransactions??0,currentPage:cs,totalPages:fe,onPageChange:ve,error:C,onRetry:()=>{k(null),U()},isLoading:l}),E==="chats"&&o&&e.jsx(ui,{sessions:S?.sessions??[],total:S?.total??0,currentPage:ds,totalPages:Ue,onPageChange:us,error:D,onRetry:()=>{B(null),q()},isLoading:l})]})]})}function ci({deposits:s,total:t,currentPage:r,totalPages:a,onPageChange:n,isLoading:o,error:c,onRetry:l}){return c?e.jsxs("div",{className:"cedros-admin-tab-error",children:[e.jsx("p",{className:"cedros-admin-error-inline",children:c}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:l,children:"Retry"})]}):o&&s.length===0?e.jsxs("div",{className:"cedros-admin-tab-loading",children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{children:"Loading deposits..."})]}):t===0?e.jsx("div",{className:"cedros-admin-empty-message",children:"No deposits found."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-list-table",children:[e.jsxs("div",{className:"cedros-admin-list-thead",children:[e.jsx("div",{className:"cedros-admin-list-th",children:"Date"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Amount"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Status"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Transaction"})]}),s.map(d=>e.jsxs("div",{className:"cedros-admin-list-row",children:[e.jsx("div",{className:"cedros-admin-list-td",children:Ys(d.createdAt)}),e.jsx("div",{className:"cedros-admin-list-td",children:oi(d.amountLamports)}),e.jsx("div",{className:"cedros-admin-list-td",children:e.jsx("span",{className:`cedros-admin-status-badge cedros-admin-status-${d.status}`,children:d.status})}),e.jsx("div",{className:"cedros-admin-list-td cedros-admin-list-td-actions",children:d.txSignature?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"cedros-admin-list-td-mono",title:d.txSignature,children:[d.txSignature.slice(0,8),"..."]}),e.jsx("a",{href:`https://orbmarkets.io/tx/${d.txSignature}`,target:"_blank",rel:"noopener noreferrer",className:"cedros-admin-icon-link",title:"View on Orbmarkets","aria-label":"View transaction on Orbmarkets",children:"↗"})]}):e.jsx("span",{className:"cedros-admin-list-td-muted",children:"—"})})]},d.id))]}),a>1&&e.jsx(Js,{currentPage:r,totalPages:a,total:t,onPageChange:n})]})}function di({transactions:s,total:t,currentPage:r,totalPages:a,onPageChange:n,isLoading:o,error:c,onRetry:l}){return c?e.jsxs("div",{className:"cedros-admin-tab-error",children:[e.jsx("p",{className:"cedros-admin-error-inline",children:c}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:l,children:"Retry"})]}):o&&s.length===0?e.jsxs("div",{className:"cedros-admin-tab-loading",children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{children:"Loading transactions..."})]}):t===0?e.jsx("div",{className:"cedros-admin-empty-message",children:"No credit transactions found."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-list-table",children:[e.jsxs("div",{className:"cedros-admin-list-thead",children:[e.jsx("div",{className:"cedros-admin-list-th",children:"Date"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Type"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Description"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Amount"})]}),s.map(d=>e.jsxs("div",{className:"cedros-admin-list-row",children:[e.jsx("div",{className:"cedros-admin-list-td",children:Ys(d.createdAt)}),e.jsx("div",{className:"cedros-admin-list-td",children:e.jsx("span",{className:`cedros-admin-tx-type cedros-admin-tx-type-${d.txType.toLowerCase()}`,children:ii(d.txType)})}),e.jsx("div",{className:"cedros-admin-list-td",children:li(d.txType,d.referenceType)}),e.jsxs("div",{className:`cedros-admin-list-td ${d.amountLamports>=0?"cedros-admin-amount-positive":"cedros-admin-amount-negative"}`,children:[d.amountLamports>=0?"+":"",He(d.amountLamports)]})]},d.id))]}),a>1&&e.jsx(Js,{currentPage:r,totalPages:a,total:t,onPageChange:n})]})}function ui({sessions:s,total:t,currentPage:r,totalPages:a,onPageChange:n,isLoading:o,error:c,onRetry:l}){return c?e.jsxs("div",{className:"cedros-admin-tab-error",children:[e.jsx("p",{className:"cedros-admin-error-inline",children:c}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:l,children:"Retry"})]}):o&&s.length===0?e.jsxs("div",{className:"cedros-admin-tab-loading",children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{children:"Loading chat history..."})]}):t===0?e.jsx("div",{className:"cedros-admin-empty-message",children:"No chat sessions found."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-list-table",children:[e.jsxs("div",{className:"cedros-admin-list-thead",children:[e.jsx("div",{className:"cedros-admin-list-th",children:"Date"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Session"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Messages"})]}),s.map(d=>e.jsxs("div",{className:"cedros-admin-list-row",children:[e.jsx("div",{className:"cedros-admin-list-td",children:Ys(d.createdAt)}),e.jsx("div",{className:"cedros-admin-list-td",children:d.title||`Chat ${d.id.slice(0,8)}...`}),e.jsx("div",{className:"cedros-admin-list-td",children:d.messageCount})]},d.id))]}),a>1&&e.jsx(Js,{currentPage:r,totalPages:a,total:t,onPageChange:n})]})}function Js({currentPage:s,totalPages:t,total:r,onPageChange:a}){return e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>a(s-1),disabled:s<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",s," of ",t," (",r," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>a(s+1),disabled:s>=t,children:"Next"})]})}function ze({checked:s,onChange:t,disabled:r,label:a}){return e.jsx("button",{type:"button",role:"switch","aria-checked":s,"aria-label":a,disabled:r,className:`cedros-toggle cedros-toggle-sm ${s?"cedros-toggle-on":"cedros-toggle-off"} ${r?"cedros-toggle-disabled":""}`,onClick:()=>!r&&t(!s),children:e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})})})}function en({userRole:s}){const{permissions:t,updatePermissions:r,isLoading:a,isUpdating:n,error:o}=Vr(),{features:c,isLoading:l}=Gs(),d=i.useRef(null),u=i.useRef(null),g=s==="owner",m=c.cedrosPay,h=i.useCallback(f=>{u.current=f,d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{u.current&&(r(u.current).catch(()=>{}),u.current=null)},500)},[r]);i.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const b=i.useCallback((f,p,x)=>{const j={...t,[f]:{...t[f],[p]:x}};h(j)},[t,h]);return a||l?e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx("div",{className:"cedros-dashboard__loading",children:"Loading permissions..."})}):g?e.jsxs("div",{className:"cedros-dashboard__section cedros-permissions-section",children:[e.jsxs("div",{className:"cedros-permissions-header",children:[e.jsx("p",{className:"cedros-permissions-description",children:"Configure which dashboard sections each role can access. Owners always have full access."}),o&&e.jsx("div",{className:"cedros-permissions-error",children:o.message}),n&&e.jsx("span",{className:"cedros-permissions-saving",children:"Saving..."})]}),e.jsx("div",{className:"cedros-permissions-matrix",children:e.jsx("table",{className:"cedros-permissions-table",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"cedros-permissions-group-header",children:[e.jsx("th",{className:"cedros-permissions-section-header",children:"Cedros Login"}),e.jsx("th",{className:"cedros-permissions-role-header",children:"Admin"}),e.jsx("th",{className:"cedros-permissions-role-header",children:"Member"})]}),$o.map(f=>e.jsxs("tr",{className:"cedros-permissions-row",children:[e.jsx("td",{className:"cedros-permissions-section-label",children:Ae[f]}),e.jsx("td",{className:"cedros-permissions-toggle-cell",children:e.jsx(ze,{checked:t.admin[f]??!1,onChange:p=>b("admin",f,p),disabled:n,label:`Admin access to ${Ae[f]}`})}),e.jsx("td",{className:"cedros-permissions-toggle-cell",children:e.jsx(ze,{checked:t.member[f]??!1,onChange:p=>b("member",f,p),disabled:n,label:`Member access to ${Ae[f]}`})})]},f)),m&&e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"cedros-permissions-group-header",children:[e.jsx("th",{className:"cedros-permissions-section-header",children:"Cedros Pay"}),e.jsx("th",{className:"cedros-permissions-role-header",children:"Admin"}),e.jsx("th",{className:"cedros-permissions-role-header",children:"Member"})]}),zo.map(f=>e.jsxs("tr",{className:"cedros-permissions-row",children:[e.jsx("td",{className:"cedros-permissions-section-label",children:Ae[f]}),e.jsx("td",{className:"cedros-permissions-toggle-cell",children:e.jsx(ze,{checked:t.admin[f]??!1,onChange:p=>b("admin",f,p),disabled:n,label:`Admin access to ${Ae[f]}`})}),e.jsx("td",{className:"cedros-permissions-toggle-cell",children:e.jsx(ze,{checked:t.member[f]??!1,onChange:p=>b("member",f,p),disabled:n,label:`Member access to ${Ae[f]}`})})]},f))]})]})})})]}):e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx("div",{className:"cedros-dashboard__empty",children:"Only organization owners can configure dashboard permissions."})})}function Xs({name:s,email:t,picture:r,onSettings:a,onLogout:n,className:o=""}){const[c,l]=i.useState(!1),d=i.useRef(null);i.useEffect(()=>{function b(f){d.current&&!d.current.contains(f.target)&&l(!1)}if(c)return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[c]),i.useEffect(()=>{function b(f){f.key==="Escape"&&l(!1)}if(c)return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[c]);const u=i.useCallback(()=>{l(!1),a?.()},[a]),g=i.useCallback(()=>{l(!1),n?.()},[n]),m=s||"User",h=(s?.[0]||t?.[0]||"?").toUpperCase();return e.jsxs("div",{className:`cedros-profile-dropdown ${o}`,ref:d,children:[e.jsxs("button",{type:"button",className:"cedros-profile-dropdown__trigger",onClick:()=>l(!c),"aria-expanded":c,"aria-haspopup":"menu",children:[e.jsx("div",{className:"cedros-profile-dropdown__avatar",children:r?e.jsx("img",{src:r,alt:m,className:"cedros-profile-dropdown__avatar-img",referrerPolicy:"no-referrer"}):e.jsx("span",{className:"cedros-profile-dropdown__avatar-placeholder",children:h})}),e.jsxs("div",{className:"cedros-profile-dropdown__info",children:[e.jsx("span",{className:"cedros-profile-dropdown__name",children:m}),t&&e.jsx("span",{className:"cedros-profile-dropdown__email",children:t})]}),e.jsx("svg",{className:`cedros-profile-dropdown__chevron ${c?"cedros-profile-dropdown__chevron--open":""}`,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"m6 9 6 6 6-6"})})]}),c&&e.jsxs("div",{className:"cedros-profile-dropdown__menu",role:"menu",children:[a&&e.jsxs("button",{type:"button",className:"cedros-profile-dropdown__item",onClick:u,role:"menuitem",children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),"Settings"]}),n&&e.jsxs("button",{type:"button",className:"cedros-profile-dropdown__item cedros-profile-dropdown__item--danger",onClick:g,role:"menuitem",children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),e.jsx("polyline",{points:"16 17 21 12 16 7"}),e.jsx("line",{x1:"21",x2:"9",y1:"12",y2:"12"})]}),"Log out"]})]})]})}const ie={users:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),members:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),deposits:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"}),e.jsx("path",{d:"M12 18V6"})]}),withdrawals:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2"}),e.jsx("path",{d:"M9 22v-4h6v4"}),e.jsx("path",{d:"M8 6h.01"}),e.jsx("path",{d:"M16 6h.01"}),e.jsx("path",{d:"M12 6h.01"}),e.jsx("path",{d:"M12 10h.01"}),e.jsx("path",{d:"M12 14h.01"}),e.jsx("path",{d:"M16 10h.01"}),e.jsx("path",{d:"M16 14h.01"}),e.jsx("path",{d:"M8 10h.01"}),e.jsx("path",{d:"M8 14h.01"})]}),wallet:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),e.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),key:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})}),mail:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),e.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),coins:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"8",cy:"8",r:"6"}),e.jsx("path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18"}),e.jsx("path",{d:"M7 6h1v4"}),e.jsx("path",{d:"m16.71 13.88.7.71-2.82 2.82"})]}),server:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),e.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),e.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),e.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]})},hi=[{id:"users",label:"Users",icon:ie.users},{id:"team",label:"Team",icon:ie.members},{id:"deposits",label:"Deposits",icon:ie.deposits,requiredFeature:"credits"},{id:"withdrawals",label:"Withdrawals",icon:ie.withdrawals,requiredFeature:"credits"},{id:"settings-auth",label:"Authentication",icon:ie.key,group:"Configuration"},{id:"settings-messaging",label:"Auth Messages",icon:ie.mail,group:"Configuration"},{id:"settings-wallet",label:"User Wallets",icon:ie.wallet,group:"Configuration"},{id:"settings-credits",label:"Credit System",icon:ie.coins,group:"Configuration",requiredFeature:"credits"},{id:"settings-server",label:"Auth Server",icon:ie.server,group:"Configuration"}];function mi({title:s="Dashboard",sections:t=["users","team","deposits","withdrawals","settings-wallet","settings-auth","settings-messaging","settings-credits","settings-server"],defaultSection:r="users",refreshInterval:a=0,pageSize:n=20,onSectionChange:o,onSettingsClick:c,onLogoutClick:l,className:d=""}){const[u,g]=i.useState(r),[m,h]=i.useState(!0),{user:b,logout:f}=N.useCedrosLogin(),{activeOrg:p,role:x,isLoading:j,fetchOrgs:y,hasPermission:A}=as(),{status:v,isLoading:S,checkStatus:w}=Ks(),{features:E,isLoading:P}=Gs(),{canAccess:L}=Vr(),T=i.useCallback(D=>{g(D),o?.(D)},[o]),C=hi.filter(D=>!(!t.includes(D.id)||D.requiredFeature&&!E[D.requiredFeature]||!L(D.id))),k=C.find(D=>D.id===u),_=!k&&!P;return i.useEffect(()=>{y(),w()},[y,w]),i.useEffect(()=>{_&&C.length>0&&g("users")},[_,C.length]),!S&&v?.needsSetup?e.jsx("div",{className:`cedros-admin cedros-dashboard cedros-dashboard--setup ${d}`,children:e.jsx(Ir,{onComplete:()=>w()})}):(j||S||P)&&!p?e.jsxs("div",{className:`cedros-admin cedros-dashboard cedros-dashboard--loading ${d}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{className:"cedros-dashboard__loading-text",children:"Loading..."})]}):u==="team"&&!p?e.jsx("div",{className:`cedros-admin cedros-dashboard ${d}`,children:e.jsx(N.ErrorMessage,{error:"No organization selected. Please select an organization first."})}):e.jsxs("div",{className:`cedros-admin cedros-dashboard ${d}`,children:[e.jsxs("aside",{className:"cedros-dashboard__sidebar",children:[e.jsx("div",{className:"cedros-dashboard__sidebar-header",children:e.jsxs("div",{className:"cedros-dashboard__logo",children:[ie.wallet,e.jsx("span",{className:"cedros-dashboard__logo-text",children:s})]})}),e.jsxs("nav",{className:"cedros-dashboard__nav",children:[e.jsxs("div",{className:"cedros-dashboard__nav-group",children:[e.jsx("span",{className:"cedros-dashboard__nav-label",children:"Menu"}),C.filter(D=>!D.group).map(D=>e.jsxs("button",{type:"button",className:`cedros-dashboard__nav-item ${u===D.id?"cedros-dashboard__nav-item--active":""}`,onClick:()=>T(D.id),"aria-current":u===D.id?"page":void 0,children:[e.jsx("span",{className:"cedros-dashboard__nav-icon",children:D.icon}),e.jsx("span",{className:"cedros-dashboard__nav-text",children:D.label})]},D.id))]}),C.some(D=>D.group==="Configuration")&&e.jsxs("div",{className:"cedros-dashboard__nav-group",children:[e.jsxs("button",{type:"button",className:"cedros-dashboard__nav-label cedros-dashboard__nav-label--collapsible",onClick:()=>h(!m),"aria-expanded":m,children:[e.jsx("span",{children:"Configuration"}),e.jsx("span",{className:`cedros-dashboard__nav-chevron ${m?"cedros-dashboard__nav-chevron--expanded":""}`,children:ie.chevronRight})]}),m&&C.filter(D=>D.group==="Configuration").map(D=>e.jsxs("button",{type:"button",className:`cedros-dashboard__nav-item ${u===D.id?"cedros-dashboard__nav-item--active":""}`,onClick:()=>T(D.id),"aria-current":u===D.id?"page":void 0,children:[e.jsx("span",{className:"cedros-dashboard__nav-icon",children:D.icon}),e.jsx("span",{className:"cedros-dashboard__nav-text",children:D.label})]},D.id))]})]}),b&&e.jsx("div",{className:"cedros-dashboard__sidebar-footer",children:e.jsx(Xs,{name:b.name,email:b.email,picture:b.picture,onSettings:c,onLogout:l??f})})]}),e.jsxs("main",{className:"cedros-dashboard__main",children:[e.jsx("header",{className:"cedros-dashboard__header",children:e.jsxs("div",{className:"cedros-dashboard__breadcrumb",children:[e.jsx("span",{className:"cedros-dashboard__breadcrumb-root",children:s}),e.jsx("span",{className:"cedros-dashboard__breadcrumb-sep",children:ie.chevronRight}),e.jsx("span",{className:"cedros-dashboard__breadcrumb-current",children:k?.label})]})}),e.jsxs("div",{className:"cedros-dashboard__content",children:[u==="users"&&e.jsx(pi,{pageSize:n,currentUserId:b?.id}),u==="team"&&p&&e.jsx(fi,{orgId:p.id,currentUserId:b?.id,hasPermission:A,role:x}),u==="deposits"&&e.jsx(gi,{pageSize:n,refreshInterval:a}),u==="withdrawals"&&e.jsx(bi,{pageSize:n,refreshInterval:a}),u==="settings-auth"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Br,{})}),u==="settings-wallet"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Or,{})}),u==="settings-messaging"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Fo,{})}),u==="settings-credits"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(qr,{})}),u==="settings-server"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Wr,{})})]})]})]})}function pi({pageSize:s,currentUserId:t}){const[r,a]=i.useState(null),[n,o]=i.useState(null),[c,l]=i.useState(!1),[d,u]=i.useState(null),{getStats:g}=os(),{fetchSettings:m,getValue:h}=Re(),[b,f]=i.useState(!1);i.useEffect(()=>{b||(m(),f(!0))},[m,b]);const p=i.useCallback(y=>{const A=h(y);return A===void 0?!1:A==="true"||A==="1"},[h]),x=i.useCallback(async()=>{l(!0),u(null);try{const y=await g();o(y)}catch(y){u(y instanceof Error?y.message:"Failed to load user stats")}finally{l(!1)}},[g]);i.useEffect(()=>{x()},[x]);const j=i.useMemo(()=>{const y=[{label:"Total Users",value:n?.total??"—"}],A=p("auth_email_enabled"),v=p("auth_google_enabled"),S=p("auth_apple_enabled"),w=p("auth_solana_enabled"),E=p("auth_webauthn_enabled"),P=p("feature_sso");return A&&y.push({label:"Email Users",value:n?.authMethodCounts.email??0}),v&&y.push({label:"Google Users",value:n?.authMethodCounts.google??0}),S&&y.push({label:"Apple Users",value:n?.authMethodCounts.apple??0}),w&&y.push({label:"Solana Users",value:n?.authMethodCounts.solana??0}),E&&y.push({label:"Passkey Users",value:n?.authMethodCounts.webauthn??0}),P&&y.push({label:"SSO Provider Users",value:n?.authMethodCounts.sso??0}),y},[n,p]);return r?e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Zr,{userId:r.id,currentUserId:t,onBack:()=>a(null)})}):e.jsxs("div",{className:"cedros-dashboard__section",children:[e.jsx(Ce,{stats:j,isLoading:c,onRefresh:x}),d&&e.jsx("p",{className:"cedros-admin-error-inline",children:d}),e.jsx(Xr,{pageSize:s,currentUserId:t,onUserClick:y=>a(y)})]})}function fi({orgId:s,currentUserId:t,hasPermission:r,role:a}){const[n,o]=i.useState("members"),{members:c,isLoading:l,error:d,fetchMembers:u,updateMemberRole:g,removeMember:m}=$r(s),{invites:h,isLoading:b,error:f,fetchInvites:p,createInvite:x,cancelInvite:j,resendInvite:y}=zr(s);i.useEffect(()=>{u(),p()},[u,p]);const A=r("invite:create"),v=r("invite:cancel"),S=h.length,w=c.reduce((T,C)=>(T[C.role]=(T[C.role]??0)+1,T),{}),E=w.owner??0,P=w.admin??0,L=w.member??0;return e.jsxs("div",{className:"cedros-dashboard__team",children:[e.jsx(Ce,{stats:[{label:"Owners",value:E},{label:"Admins",value:P},{label:"Members",value:L},{label:"Pending Invites",value:S}]}),e.jsxs("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:[e.jsx("button",{type:"button",className:`cedros-admin-tab ${n==="members"?"cedros-admin-tab-active":""}`,onClick:()=>o("members"),"aria-selected":n==="members",role:"tab",children:"Members"}),e.jsxs("button",{type:"button",className:`cedros-admin-tab ${n==="invites"?"cedros-admin-tab-active":""}`,onClick:()=>o("invites"),"aria-selected":n==="invites",role:"tab",children:["Pending Invites",S>0&&` (${S})`]}),a==="owner"&&e.jsx("button",{type:"button",className:`cedros-admin-tab ${n==="permissions"?"cedros-admin-tab-active":""}`,onClick:()=>o("permissions"),"aria-selected":n==="permissions",role:"tab",children:"Permissions"})]}),e.jsxs("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:[n==="members"&&e.jsx(yr,{members:c,currentUserId:t,isLoading:l,error:d?.message,canManage:r("member:remove"),canChangeRoles:r("member:role_change"),onUpdateRole:g,onRemove:m}),n==="invites"&&e.jsxs("div",{className:"cedros-dashboard__invites",children:[A&&e.jsxs("div",{className:"cedros-dashboard__section",children:[e.jsx("div",{className:"cedros-dashboard__section-header",children:e.jsx("h3",{className:"cedros-dashboard__section-title",children:"Send Invitation"})}),e.jsx(wr,{onSubmit:x,isLoading:b,error:f?.message})]}),e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(xr,{invites:h,isLoading:b,error:f?.message,canManage:v||A,onCancel:v?j:void 0,onResend:A?y:void 0})})]}),n==="permissions"&&a==="owner"&&e.jsx(en,{userRole:a})]})]})}function gi({pageSize:s,refreshInterval:t}){const[r,a]=i.useState("");return e.jsxs("div",{className:"cedros-dashboard__deposits",children:[e.jsx(Hr,{refreshInterval:t}),e.jsxs("div",{className:"cedros-dashboard__deposits-list",children:[e.jsx("div",{className:"cedros-dashboard__toolbar",children:e.jsxs("div",{className:"cedros-dashboard__filter",children:[e.jsx("label",{className:"cedros-dashboard__filter-label",htmlFor:"status-filter",children:"Status"}),e.jsxs("select",{id:"status-filter",className:"cedros-dashboard__select",value:r,onChange:n=>a(n.target.value),children:[e.jsx("option",{value:"",children:"All statuses"}),e.jsx("option",{value:"pending",children:"Pending"}),e.jsx("option",{value:"detected",children:"Detected"}),e.jsx("option",{value:"processing",children:"Processing"}),e.jsx("option",{value:"completed",children:"Completed"}),e.jsx("option",{value:"withdrawn",children:"Withdrawn"}),e.jsx("option",{value:"expired",children:"Expired"}),e.jsx("option",{value:"failed",children:"Failed"})]})]})}),e.jsx(Kr,{statusFilter:r||void 0,pageSize:s,refreshInterval:t})]})]})}function bi({pageSize:s,refreshInterval:t}){return e.jsxs("div",{className:"cedros-dashboard__withdrawals",children:[e.jsx(Qr,{refreshInterval:t}),e.jsx("p",{className:"cedros-dashboard__text-muted",children:"Track deposits through the withdrawal pipeline: privacy period, ready for processing, and completed."}),e.jsxs("div",{className:"cedros-dashboard__pipeline",children:[e.jsx(Yr,{pageSize:s,refreshInterval:t}),e.jsx(Gr,{pageSize:s,refreshInterval:t}),e.jsx(Jr,{pageSize:s,refreshInterval:t})]})]})}class yi{plugins=new Map;listeners=new Set;register(t){this.plugins.has(t.id)&&console.warn(`Plugin ${t.id} already registered, replacing...`),this.plugins.set(t.id,t),t.onRegister?.(this),this.notify()}unregister(t){const r=this.plugins.get(t);r&&(r.onUnregister?.(),this.plugins.delete(t),this.notify())}get(t){return this.plugins.get(t)}getAll(){return Array.from(this.plugins.values())}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){const t=this.getAll();this.listeners.forEach(r=>r(t))}}const sn=i.createContext(null);function wi(){const s=i.useContext(sn);if(!s)throw new Error("useAdminShell must be used within AdminShell");return s}function xi(s){const t=new Map;for(const r of s)for(const a of r.groups??[])t.has(a.label)||t.set(a.label,a.order);return t}function vi({title:s="Admin",plugins:t=[],hostContext:r,defaultSection:a,pageSize:n=20,refreshInterval:o=0,onSectionChange:c,logo:l,sidebarFooter:d,onSettingsClick:u,onLogoutClick:g,className:m=""}){const[h]=i.useState(()=>{const C=new yi;return t.forEach(k=>C.register(k)),C}),[b,f]=i.useState(()=>h.getAll());i.useEffect(()=>h.subscribe(f),[h]);const p=i.useMemo(()=>b.flatMap(C=>C.sections.filter(k=>!(k.requiredPermission&&!C.checkPermission(k.requiredPermission,r)||r.dashboardPermissions&&!r.dashboardPermissions.canAccess(k.id))).map(k=>({...k,qualifiedId:`${C.id}:${k.id}`,pluginId:C.id,cssNamespace:C.cssNamespace}))),[b,r]),[x,j]=i.useState(()=>a??p[0]?.qualifiedId??null),[y,A]=i.useState(new Set),v=i.useCallback(C=>{A(k=>{const _=new Set(k);return _.has(C)?_.delete(C):_.add(C),_})},[]);i.useEffect(()=>{x&&!p.find(C=>C.qualifiedId===x)&&j(p[0]?.qualifiedId??null)},[p,x]);const S=i.useCallback(C=>{j(C),c?.(C)},[c]),w=i.useCallback(C=>{const k=h.get(C);return k?k.createPluginContext(r):null},[h,r]),E=i.useMemo(()=>{const C=xi(b),k=new Map;return p.forEach(M=>{const D=M.group??"Menu",B=k.get(D)??[];k.set(D,[...B,M])}),Array.from(k.entries()).sort(([M],[D])=>{const B=C.get(M)??99,Q=C.get(D)??99;return B-Q})},[p,b]),P=i.useMemo(()=>{if(!x)return null;const[C,k]=x.split(":"),_=h.get(C);if(!_)return null;const M=_.components[k];if(!M)return null;const D=_.createPluginContext(r);return{Component:M,pluginContext:D,plugin:_}},[x,h,r]),L=i.useMemo(()=>({registry:h,hostContext:r,activeSection:x,setActiveSection:S,getPluginContext:w}),[h,r,x,S,w]),T=i.useMemo(()=>{const C=r.cedrosLogin;if(!C)return null;const k=C.user?{authMethods:[],emailVerified:!1,createdAt:"",updatedAt:"",...C.user}:null;return{config:{serverUrl:C.serverUrl},user:k,authState:C.user?"authenticated":"unauthenticated",error:null,logout:async()=>{},refreshUser:async()=>{},isModalOpen:!1,openModal:()=>{},closeModal:()=>{},_internal:{handleLoginSuccess:()=>{},getAccessToken:C.getAccessToken}}},[r.cedrosLogin]);return e.jsx(sn.Provider,{value:L,children:e.jsx(N.CedrosLoginContext.Provider,{value:T,children:e.jsxs("div",{className:`cedros-admin cedros-admin-shell ${m||""}`,children:[e.jsxs("aside",{className:"cedros-admin-shell__sidebar",children:[e.jsx("div",{className:"cedros-admin-shell__sidebar-header",children:l??e.jsx("div",{className:"cedros-admin-shell__logo",children:e.jsx("span",{className:"cedros-admin-shell__logo-text",children:s})})}),e.jsx("nav",{className:"cedros-admin-shell__nav",children:E.map(([C,k])=>{const _=C==="Configuration",M=y.has(C);return e.jsxs("div",{className:"cedros-admin-shell__nav-group",children:[_?e.jsxs("button",{type:"button",className:"cedros-admin-shell__nav-label cedros-admin-shell__nav-label--collapsible",onClick:()=>v(C),"aria-expanded":!M,children:[e.jsx("span",{children:C}),e.jsx("span",{className:`cedros-admin-shell__nav-chevron ${M?"":"cedros-admin-shell__nav-chevron--expanded"}`,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"m9 18 6-6-6-6"})})})]}):e.jsx("span",{className:"cedros-admin-shell__nav-label",children:C}),(!_||!M)&&k.sort((D,B)=>(D.order??0)-(B.order??0)).map(D=>e.jsxs("button",{type:"button",className:`cedros-admin-shell__nav-item ${x===D.qualifiedId?"cedros-admin-shell__nav-item--active":""}`,onClick:()=>S(D.qualifiedId),"aria-current":x===D.qualifiedId?"page":void 0,children:[e.jsx("span",{className:"cedros-admin-shell__nav-icon",children:D.icon}),e.jsx("span",{className:"cedros-admin-shell__nav-text",children:D.label}),D.badge&&e.jsx("span",{className:"cedros-admin-shell__nav-badge",children:D.badge})]},D.qualifiedId))]},C)})}),(r.cedrosLogin?.user||d)&&e.jsxs("div",{className:"cedros-admin-shell__sidebar-footer",children:[r.cedrosLogin?.user&&e.jsx(Xs,{name:r.cedrosLogin.user.name,email:r.cedrosLogin.user.email,picture:r.cedrosLogin.user.picture,onSettings:u,onLogout:g}),d]})]}),e.jsx("main",{className:"cedros-admin-shell__main",children:P?e.jsx(i.Suspense,{fallback:e.jsx(ji,{}),children:e.jsx("div",{className:"cedros-admin-shell__section","data-plugin-namespace":P.plugin.cssNamespace,children:e.jsx(P.Component,{pluginContext:P.pluginContext,pageSize:n,refreshInterval:o})})}):e.jsx("div",{className:"cedros-admin-shell__empty",children:p.length===0?"No plugins loaded":"Select a section from the sidebar"})})]})})})}function ji(){return e.jsxs("div",{className:"cedros-admin-shell__loading",children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading..."})]})}const te={width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},ce={users:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),members:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),invites:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),e.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),deposits:e.jsxs("svg",{...te,children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"}),e.jsx("path",{d:"M12 18V6"})]}),withdrawals:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2"}),e.jsx("path",{d:"M9 22v-4h6v4"}),e.jsx("path",{d:"M8 6h.01"}),e.jsx("path",{d:"M16 6h.01"}),e.jsx("path",{d:"M12 6h.01"}),e.jsx("path",{d:"M12 10h.01"}),e.jsx("path",{d:"M12 14h.01"}),e.jsx("path",{d:"M16 10h.01"}),e.jsx("path",{d:"M16 14h.01"}),e.jsx("path",{d:"M8 10h.01"}),e.jsx("path",{d:"M8 14h.01"})]}),settings:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),e.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:e.jsx("svg",{...te,children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),key:e.jsx("svg",{...te,children:e.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})}),toggles:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"20",height:"12",x:"2",y:"6",rx:"6"}),e.jsx("circle",{cx:"8",cy:"12",r:"2"})]}),shield:e.jsx("svg",{...te,children:e.jsx("path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"})}),mail:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),e.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),webhook:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2"}),e.jsx("path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06"}),e.jsx("path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8"})]}),coins:e.jsxs("svg",{...te,children:[e.jsx("circle",{cx:"8",cy:"8",r:"6"}),e.jsx("path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18"}),e.jsx("path",{d:"M7 6h1v4"}),e.jsx("path",{d:"m16.71 13.88.7.71-2.82 2.82"})]}),server:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),e.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),e.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),e.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]})},Ai=i.lazy(()=>Promise.resolve().then(()=>require("./UsersSection-nwTQCl2X.cjs"))),ki=i.lazy(()=>Promise.resolve().then(()=>require("./TeamSection-CnCzNEe9.cjs"))),Ni=i.lazy(()=>Promise.resolve().then(()=>require("./DepositsSection-DPr60Pty.cjs"))),Si=i.lazy(()=>Promise.resolve().then(()=>require("./WithdrawalsSection-wDptaqpp.cjs"))),Ci=i.lazy(()=>Promise.resolve().then(()=>require("./AuthenticationSettings-UOHce4G0.cjs"))),_i=i.lazy(()=>Promise.resolve().then(()=>require("./EmbeddedWalletSettings-DGJST5MD.cjs"))),Ei=i.lazy(()=>Promise.resolve().then(()=>require("./EmailSettings-BM7tGO1t.cjs"))),Ti=i.lazy(()=>Promise.resolve().then(()=>require("./WebhookSettings-CDLNe806.cjs"))),Pi=i.lazy(()=>Promise.resolve().then(()=>require("./CreditSystemSettings-BClUVM4R.cjs"))),Li=i.lazy(()=>Promise.resolve().then(()=>require("./ServerSettings-B2YxkgLu.cjs"))),Mi={"login:users:read":["admin","owner"],"login:users:write":["admin","owner"],"login:members:read":["member:read","admin","owner"],"login:members:write":["member:remove","member:role_change"],"login:invites:read":["invite:read","admin","owner"],"login:invites:write":["invite:create","invite:cancel"],"login:deposits:read":["admin","owner"],"login:deposits:write":["admin","owner"],"login:settings:read":["admin","owner"],"login:settings:write":["admin","owner"]},Di=[{id:"users",label:"Users",icon:ce.users,group:"Users",order:0,requiredPermission:"login:users:read"},{id:"team",label:"Team",icon:ce.members,group:"Users",order:1,requiredPermission:"login:members:read"},{id:"deposits",label:"Deposits",icon:ce.deposits,group:"Users",order:2,requiredPermission:"login:deposits:read"},{id:"withdrawals",label:"Withdrawals",icon:ce.withdrawals,group:"Users",order:3,requiredPermission:"login:deposits:read"},{id:"settings-auth",label:"Authentication",icon:ce.key,group:"Configuration",order:0,requiredPermission:"login:settings:read"},{id:"settings-email",label:"Email & SMTP",icon:ce.mail,group:"Configuration",order:1,requiredPermission:"login:settings:read"},{id:"settings-webhooks",label:"Webhooks",icon:ce.webhook,group:"Configuration",order:2,requiredPermission:"login:settings:read"},{id:"settings-wallet",label:"User Wallets",icon:ce.wallet,group:"Configuration",order:3,requiredPermission:"login:settings:read"},{id:"settings-credits",label:"Credit System",icon:ce.coins,group:"Configuration",order:4,requiredPermission:"login:settings:read"},{id:"settings-server",label:"Auth Server",icon:ce.server,group:"Configuration",order:5,requiredPermission:"login:settings:read"}],Ri={id:"cedros-login",name:"Cedros Login",version:"1.0.0",sections:Di,groups:[{id:"users",label:"Users",order:0},{id:"configuration",label:"Configuration",order:2}],components:{users:Ai,team:ki,deposits:Ni,withdrawals:Si,"settings-auth":Ci,"settings-wallet":_i,"settings-email":Ei,"settings-webhooks":Ti,"settings-credits":Pi,"settings-server":Li},createPluginContext(s){const t=s.cedrosLogin;if(!t)throw new Error("cedros-login plugin requires cedrosLogin in hostContext");return{serverUrl:t.serverUrl,userId:t.user?.id,getAccessToken:t.getAccessToken,hasPermission:r=>this.checkPermission(r,s),orgId:s.org?.orgId,pluginData:{user:t.user,orgRole:s.org?.role}}},checkPermission(s,t){const r=t.org;if(!r)return!!t.cedrosLogin?.user;const a=Mi[s];return a?a.some(n=>r.permissions.includes(n)||n===r.role||n==="admin"&&["admin","owner"].includes(r.role)||n==="owner"&&r.role==="owner"):!1},cssNamespace:"cedros-dashboard"};var ke={},ys,Ct;function Ii(){return Ct||(Ct=1,ys=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ys}var ws={},pe={},_t;function we(){if(_t)return pe;_t=1;let s;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return pe.getSymbolSize=function(a){if(!a)throw new Error('"version" cannot be null or undefined');if(a<1||a>40)throw new Error('"version" should be in range from 1 to 40');return a*4+17},pe.getSymbolTotalCodewords=function(a){return t[a]},pe.getBCHDigit=function(r){let a=0;for(;r!==0;)a++,r>>>=1;return a},pe.setToSJISFunction=function(a){if(typeof a!="function")throw new Error('"toSJISFunc" is not a valid function.');s=a},pe.isKanjiModeEnabled=function(){return typeof s<"u"},pe.toSJIS=function(a){return s(a)},pe}var xs={},Et;function Zs(){return Et||(Et=1,(function(s){s.L={bit:1},s.M={bit:0},s.Q={bit:3},s.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return s.L;case"m":case"medium":return s.M;case"q":case"quartile":return s.Q;case"h":case"high":return s.H;default:throw new Error("Unknown EC Level: "+r)}}s.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},s.from=function(a,n){if(s.isValid(a))return a;try{return t(a)}catch{return n}}})(xs)),xs}var vs,Tt;function Ui(){if(Tt)return vs;Tt=1;function s(){this.buffer=[],this.length=0}return s.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let a=0;a<r;a++)this.putBit((t>>>r-a-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},vs=s,vs}var js,Pt;function Fi(){if(Pt)return js;Pt=1;function s(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return s.prototype.set=function(t,r,a,n){const o=t*this.size+r;this.data[o]=a,n&&(this.reservedBit[o]=!0)},s.prototype.get=function(t,r){return this.data[t*this.size+r]},s.prototype.xor=function(t,r,a){this.data[t*this.size+r]^=a},s.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},js=s,js}var As={},Lt;function Bi(){return Lt||(Lt=1,(function(s){const t=we().getSymbolSize;s.getRowColCoords=function(a){if(a===1)return[];const n=Math.floor(a/7)+2,o=t(a),c=o===145?26:Math.ceil((o-13)/(2*n-2))*2,l=[o-7];for(let d=1;d<n-1;d++)l[d]=l[d-1]-c;return l.push(6),l.reverse()},s.getPositions=function(a){const n=[],o=s.getRowColCoords(a),c=o.length;for(let l=0;l<c;l++)for(let d=0;d<c;d++)l===0&&d===0||l===0&&d===c-1||l===c-1&&d===0||n.push([o[l],o[d]]);return n}})(As)),As}var ks={},Mt;function Oi(){if(Mt)return ks;Mt=1;const s=we().getSymbolSize,t=7;return ks.getPositions=function(a){const n=s(a);return[[0,0],[n-t,0],[0,n-t]]},ks}var Ns={},Dt;function qi(){return Dt||(Dt=1,(function(s){s.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};s.isValid=function(n){return n!=null&&n!==""&&!isNaN(n)&&n>=0&&n<=7},s.from=function(n){return s.isValid(n)?parseInt(n,10):void 0},s.getPenaltyN1=function(n){const o=n.size;let c=0,l=0,d=0,u=null,g=null;for(let m=0;m<o;m++){l=d=0,u=g=null;for(let h=0;h<o;h++){let b=n.get(m,h);b===u?l++:(l>=5&&(c+=t.N1+(l-5)),u=b,l=1),b=n.get(h,m),b===g?d++:(d>=5&&(c+=t.N1+(d-5)),g=b,d=1)}l>=5&&(c+=t.N1+(l-5)),d>=5&&(c+=t.N1+(d-5))}return c},s.getPenaltyN2=function(n){const o=n.size;let c=0;for(let l=0;l<o-1;l++)for(let d=0;d<o-1;d++){const u=n.get(l,d)+n.get(l,d+1)+n.get(l+1,d)+n.get(l+1,d+1);(u===4||u===0)&&c++}return c*t.N2},s.getPenaltyN3=function(n){const o=n.size;let c=0,l=0,d=0;for(let u=0;u<o;u++){l=d=0;for(let g=0;g<o;g++)l=l<<1&2047|n.get(u,g),g>=10&&(l===1488||l===93)&&c++,d=d<<1&2047|n.get(g,u),g>=10&&(d===1488||d===93)&&c++}return c*t.N3},s.getPenaltyN4=function(n){let o=0;const c=n.data.length;for(let d=0;d<c;d++)o+=n.data[d];return Math.abs(Math.ceil(o*100/c/5)-10)*t.N4};function r(a,n,o){switch(a){case s.Patterns.PATTERN000:return(n+o)%2===0;case s.Patterns.PATTERN001:return n%2===0;case s.Patterns.PATTERN010:return o%3===0;case s.Patterns.PATTERN011:return(n+o)%3===0;case s.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(o/3))%2===0;case s.Patterns.PATTERN101:return n*o%2+n*o%3===0;case s.Patterns.PATTERN110:return(n*o%2+n*o%3)%2===0;case s.Patterns.PATTERN111:return(n*o%3+(n+o)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}s.applyMask=function(n,o){const c=o.size;for(let l=0;l<c;l++)for(let d=0;d<c;d++)o.isReserved(d,l)||o.xor(d,l,r(n,d,l))},s.getBestMask=function(n,o){const c=Object.keys(s.Patterns).length;let l=0,d=1/0;for(let u=0;u<c;u++){o(u),s.applyMask(u,n);const g=s.getPenaltyN1(n)+s.getPenaltyN2(n)+s.getPenaltyN3(n)+s.getPenaltyN4(n);s.applyMask(u,n),g<d&&(d=g,l=u)}return l}})(Ns)),Ns}var Ve={},Rt;function tn(){if(Rt)return Ve;Rt=1;const s=Zs(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Ve.getBlocksCount=function(n,o){switch(o){case s.L:return t[(n-1)*4+0];case s.M:return t[(n-1)*4+1];case s.Q:return t[(n-1)*4+2];case s.H:return t[(n-1)*4+3];default:return}},Ve.getTotalCodewordsCount=function(n,o){switch(o){case s.L:return r[(n-1)*4+0];case s.M:return r[(n-1)*4+1];case s.Q:return r[(n-1)*4+2];case s.H:return r[(n-1)*4+3];default:return}},Ve}var Ss={},De={},It;function Wi(){if(It)return De;It=1;const s=new Uint8Array(512),t=new Uint8Array(256);return(function(){let a=1;for(let n=0;n<255;n++)s[n]=a,t[a]=n,a<<=1,a&256&&(a^=285);for(let n=255;n<512;n++)s[n]=s[n-255]})(),De.log=function(a){if(a<1)throw new Error("log("+a+")");return t[a]},De.exp=function(a){return s[a]},De.mul=function(a,n){return a===0||n===0?0:s[t[a]+t[n]]},De}var Ut;function $i(){return Ut||(Ut=1,(function(s){const t=Wi();s.mul=function(a,n){const o=new Uint8Array(a.length+n.length-1);for(let c=0;c<a.length;c++)for(let l=0;l<n.length;l++)o[c+l]^=t.mul(a[c],n[l]);return o},s.mod=function(a,n){let o=new Uint8Array(a);for(;o.length-n.length>=0;){const c=o[0];for(let d=0;d<n.length;d++)o[d]^=t.mul(n[d],c);let l=0;for(;l<o.length&&o[l]===0;)l++;o=o.slice(l)}return o},s.generateECPolynomial=function(a){let n=new Uint8Array([1]);for(let o=0;o<a;o++)n=s.mul(n,new Uint8Array([1,t.exp(o)]));return n}})(Ss)),Ss}var Cs,Ft;function zi(){if(Ft)return Cs;Ft=1;const s=$i();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(a){this.degree=a,this.genPoly=s.generateECPolynomial(this.degree)},t.prototype.encode=function(a){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(a.length+this.degree);n.set(a);const o=s.mod(n,this.genPoly),c=this.degree-o.length;if(c>0){const l=new Uint8Array(this.degree);return l.set(o,c),l}return o},Cs=t,Cs}var _s={},Es={},Ts={},Bt;function rn(){return Bt||(Bt=1,Ts.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Ts}var ue={},Ot;function nn(){if(Ot)return ue;Ot=1;const s="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const a="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
2049
|
+
`),oe=12;function Fn(s){if(s.length!==16)throw new Error(`Invalid share length: expected 16, got ${s.length}`);const r=lr(s,me).split(" ");if(r.length!==oe)throw new Error(`Unexpected word count: expected ${oe}, got ${r.length}`);return r}function Bn(s){if(s.length!==oe)throw new Error(`Invalid word count: expected ${oe}, got ${s.length}`);const t=s.join(" ").toLowerCase().trim();if(!Hs(t,me))throw new Error("Invalid recovery phrase: checksum mismatch");const r=Vs(t,me);if(r.length!==16)throw new Error(`Invalid entropy length: expected 16, got ${r.length}`);return N.toShamirShare(r)}function On(s){if(s.length!==16)throw new Error(`Invalid seed length: expected 16, got ${s.length}`);const r=lr(s,me).split(" ");if(r.length!==oe)throw new Error(`Unexpected word count: expected ${oe}, got ${r.length}`);return r}function qn(s){if(s.length!==oe)throw new Error(`Invalid word count: expected ${oe}, got ${s.length}`);const t=s.join(" ").toLowerCase().trim();if(!Hs(t,me))throw new Error("Invalid recovery phrase: checksum mismatch");const r=Vs(t,me);if(r.length!==16)throw new Error(`Invalid entropy length: expected 16, got ${r.length}`);return N.toSeed(r)}function cr(s){if(s.length!==oe)return!1;const t=s.join(" ").toLowerCase().trim();return Hs(t,me)}function We(s){return me.includes(s.toLowerCase().trim())}function Wn(s,t=5){const r=s.toLowerCase().trim();return r.length===0?[]:me.filter(a=>a.startsWith(r)).slice(0,t)}function $n(s){const t=[];for(let r=0;r<s.length;r+=4)t.push(s.slice(r,r+4));return t}function zn(s){return s.toLowerCase().replace(/[,\n\r\t]+/g," ").split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function Vn({className:s="",variant:t="default",size:r="md",children:a,menuItems:n=[],hideSignOut:o=!1}){const{user:c,isAuthenticated:l,isLoading:d,openLoginModal:u,logout:g}=N.useAuth(),[m,h]=i.useState(!1),[b,f]=i.useState(-1),p=i.useRef(null),x=i.useRef(null),j=i.useMemo(()=>[...n,...o?[]:[{label:"Sign out",onClick:g}]],[n,o,g]);i.useEffect(()=>{if(!m)return;const w=P=>{p.current&&!p.current.contains(P.target)&&(h(!1),f(-1))},E=P=>{P.key==="Escape"&&(h(!1),f(-1),x.current?.focus())};return document.addEventListener("mousedown",w),document.addEventListener("keydown",E),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",E)}},[m]);const y=i.useCallback(w=>{if(!(!m||j.length===0))switch(w.key){case"ArrowDown":w.preventDefault(),f(E=>(E+1)%j.length);break;case"ArrowUp":w.preventDefault(),f(E=>(E-1+j.length)%j.length);break;case"Home":w.preventDefault(),f(0);break;case"End":w.preventDefault(),f(j.length-1);break;case"Enter":case" ":b>=0&&(w.preventDefault(),j[b].onClick(),h(!1),f(-1));break}},[m,b,j]),A=i.useCallback(()=>{j.length!==0&&(h(w=>!w),f(-1))},[j.length]),v={sm:"cedros-button-sm",md:"cedros-button-md",lg:"cedros-button-lg"},S={default:"cedros-button-primary",outline:"cedros-button-outline",ghost:"cedros-button-ghost"};if(d)return e.jsx("button",{type:"button",className:`cedros-button ${S[t]} ${v[r]} ${s}`,disabled:!0,children:e.jsx(N.LoadingSpinner,{size:"sm"})});if(l&&c){const w=c.name||c.email||"User",E=X.sanitizeImageUrl(c.picture);return e.jsxs("div",{className:"cedros-user-menu",ref:p,onKeyDown:y,children:[e.jsxs("button",{ref:x,type:"button",className:`cedros-button cedros-user-button ${v[r]} ${s}`,"aria-haspopup":"menu","aria-expanded":m,"aria-label":`User menu for ${w}`,onClick:A,children:[E?e.jsx("img",{src:E,alt:w,className:"cedros-user-avatar",referrerPolicy:"no-referrer",crossOrigin:"anonymous"}):e.jsx("div",{className:"cedros-user-avatar-placeholder",children:(w[0]||"?").toUpperCase()}),e.jsx("span",{className:"cedros-user-name",children:w})]}),m&&e.jsxs("div",{className:"cedros-dropdown cedros-dropdown-open",role:"menu",children:[n.map((P,L)=>e.jsxs("button",{type:"button",className:`cedros-dropdown-item ${b===L?"cedros-dropdown-item-focused":""}`,role:"menuitem",tabIndex:b===L?0:-1,onClick:()=>{P.onClick(),h(!1)},children:[P.icon&&e.jsx("span",{className:"cedros-dropdown-icon",children:P.icon}),P.label]},L)),n.length>0&&!o&&e.jsx("div",{className:"cedros-dropdown-divider",role:"separator"}),!o&&e.jsx("button",{type:"button",className:`cedros-dropdown-item cedros-dropdown-item-danger ${b===n.length?"cedros-dropdown-item-focused":""}`,role:"menuitem",tabIndex:b===n.length?0:-1,onClick:()=>{g(),h(!1)},children:"Sign out"})]})]})}return e.jsx("button",{type:"button",className:`cedros-button ${S[t]} ${v[r]} ${s}`,onClick:u,children:a||"Sign in"})}function Qs(){const{config:s}=N.useCedrosLogin(),[t,r]=i.useState(!1),[a,n]=i.useState(!1),[o,c]=i.useState(null),l=i.useMemo(()=>new N.ApiClient({baseUrl:s.serverUrl,timeoutMs:s.requestTimeout,retryAttempts:s.retryAttempts}),[s.serverUrl,s.requestTimeout,s.retryAttempts]),{checkLimit:d,getRemainingAttempts:u}=X.useRateLimiter({maxAttempts:3,windowMs:3e5}),g=i.useCallback(async f=>{if(!ts.validateEmail(f)){const p={code:"VALIDATION_ERROR",message:"Please enter a valid email address"};throw c(p),p}try{d()}catch(p){const x={code:"RATE_LIMITED",message:p instanceof Error?p.message:"Too many attempts"};throw c(x),x}r(!0),c(null),n(!1);try{await l.post("/forgot-password",{email:f}),n(!0)}catch(p){const x=N.handleApiError(p,"Failed to send reset email");throw c(x),x}finally{r(!1)}},[l,d]),m=i.useCallback(async(f,p)=>{r(!0),c(null),n(!1);try{await l.post("/reset-password",{token:f,newPassword:p}),n(!0)}catch(x){const j=N.handleApiError(x,"Failed to reset password");throw c(j),j}finally{r(!1)}},[l]),h=i.useCallback(()=>c(null),[]),b=i.useCallback(()=>{c(null),n(!1),r(!1)},[]);return{forgotPassword:g,resetPassword:m,isLoading:t,isSuccess:a,error:o,clearError:h,reset:b,remainingAttempts:u()}}function dr({onSuccess:s,onCancel:t,className:r=""}){const[a,n]=i.useState(""),{forgotPassword:o,isLoading:c,isSuccess:l,error:d,clearError:u}=Qs(),g=i.useId(),m=async h=>{h.preventDefault();try{await o(a),s?.()}catch{}};return l?e.jsxs("div",{className:`cedros-forgot-password-success ${r}`,children:[e.jsxs("svg",{className:"cedros-success-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"22",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M14 24l7 7 13-13",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),e.jsx("h3",{className:"cedros-success-title",children:"Check your email"}),e.jsxs("p",{className:"cedros-success-message",children:["If an account exists for ",e.jsx("strong",{children:a}),", you will receive a password reset link shortly."]}),t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-md cedros-button-outline",onClick:t,children:"Back to login"})]}):e.jsxs("form",{className:`cedros-forgot-password-form ${r}`,onSubmit:m,children:[e.jsxs("div",{className:"cedros-form-header",children:[e.jsx("h3",{className:"cedros-form-title",children:"Forgot password?"}),e.jsx("p",{className:"cedros-form-subtitle",children:"Enter your email address and we'll send you a link to reset your password."})]}),e.jsx(N.ErrorMessage,{error:d,onDismiss:u}),e.jsxs("div",{className:"cedros-form-field",children:[e.jsx("label",{htmlFor:g,className:"cedros-label",children:"Email address"}),e.jsx("input",{id:g,type:"email",className:"cedros-input",value:a,onChange:h=>n(h.target.value),placeholder:"you@example.com",required:!0,autoComplete:"email",disabled:c})]}),e.jsxs("div",{className:"cedros-form-actions",children:[e.jsx("button",{type:"submit",className:"cedros-button cedros-button-md cedros-button-primary cedros-button-full",disabled:c||!a,children:c?e.jsxs(e.Fragment,{children:[e.jsx(N.LoadingSpinner,{size:"sm"}),"Sending..."]}):"Send reset link"}),t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-md cedros-button-ghost cedros-button-full",onClick:t,disabled:c,children:"Back to login"})]})]})}const Hn={loading:!1,loaded:!1,error:null,callbacks:[],load(){return this.loaded?Promise.resolve():this.loading?new Promise((s,t)=>{this.callbacks.push({resolve:s,reject:t})}):(this.loading=!0,new Promise((s,t)=>{this.callbacks.push({resolve:s,reject:t});const r=document.getElementById("apple-signin-script");if(r){window.AppleID?(this.loaded=!0,this.loading=!1,this.callbacks.forEach(n=>n.resolve()),this.callbacks=[]):r.addEventListener("load",()=>{this.loaded=!0,this.loading=!1,this.callbacks.forEach(n=>n.resolve()),this.callbacks=[]});return}const a=document.createElement("script");a.src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js",a.async=!0,a.defer=!0,a.id="apple-signin-script",a.onload=()=>{this.loaded=!0,this.loading=!1,this.callbacks.forEach(n=>n.resolve()),this.callbacks=[]},a.onerror=()=>{this.loading=!1,a.remove();const n=new Error("Failed to load Apple Sign In script");this.callbacks.forEach(o=>o.reject(n)),this.callbacks=[]},document.head.appendChild(a)}))}};function ur(){const{config:s,_internal:t}=N.useCedrosLogin(),[r,a]=i.useState(!1),[n,o]=i.useState(!1),[c,l]=i.useState(null),d=i.useRef(s),u=i.useMemo(()=>new N.ApiClient({baseUrl:s.serverUrl,timeoutMs:s.requestTimeout,retryAttempts:s.retryAttempts}),[s.serverUrl,s.requestTimeout,s.retryAttempts]);i.useEffect(()=>{d.current=s},[s]),i.useEffect(()=>{if(!s.appleClientId)return;let h=!0;const b=()=>{if(h)try{window.AppleID?.auth?.init({clientId:s.appleClientId,scope:"name email",redirectURI:window.location.origin,usePopup:!0}),h&&o(!0)}catch{h&&l({code:"SERVER_ERROR",message:"Failed to initialize Apple Sign In"})}};return Hn.load().then(()=>{h&&b()}).catch(()=>{h&&l({code:"SERVER_ERROR",message:"Failed to load Apple Sign In"})}),()=>{h=!1}},[s.appleClientId]);const g=i.useCallback(async()=>{if(!s.appleClientId){const h={code:"VALIDATION_ERROR",message:"Apple Client ID not configured"};throw l(h),h}if(!n){const h={code:"VALIDATION_ERROR",message:"Apple Sign In not initialized"};throw l(h),h}a(!0),l(null);try{const h=await window.AppleID.auth.signIn(),b=h.authorization?.id_token;if(!b)throw new Error("No ID token received from Apple");const f=h.user?.name?`${h.user.name.firstName||""} ${h.user.name.lastName||""}`.trim():void 0,p=await u.post("/apple",{idToken:b,name:f||void 0});return d.current.callbacks?.onLoginSuccess?.(p.user,"apple"),t?.handleLoginSuccess(p.user,p.tokens),a(!1),p}catch(h){if(h.error==="popup_closed_by_user"){const p={code:"SERVER_ERROR",message:"Apple Sign In was cancelled"};throw l(p),a(!1),p}const f=N.handleApiError(h,"Apple sign-in failed");throw l(f),a(!1),f}},[s.appleClientId,n,u,t]),m=i.useCallback(()=>l(null),[]);return{signIn:g,isLoading:r,isInitialized:n,error:c,clearError:m}}function hr(){if(typeof window>"u"||typeof navigator>"u")return!1;const s=navigator.userAgent.toLowerCase(),t=(navigator.platform||"").toLowerCase();return!!(/iphone|ipad|ipod/.test(s)||t.includes("mac")||/macintosh/.test(s)||t==="macintel"&&navigator.maxTouchPoints>1)}function mr({onSuccess:s,onError:t,className:r="",variant:a="default",size:n="md",disabled:o=!1,hideOnNonApple:c=!0}){const{signIn:l,isLoading:d,isInitialized:u}=ur(),[g]=i.useState(()=>hr());if(c&&!g)return null;const m=async()=>{try{await l(),s?.()}catch(f){const p=f instanceof Error?f:new Error(String(f));t?.(p)}},h={sm:"cedros-button-sm",md:"cedros-button-md",lg:"cedros-button-lg"},b={default:"cedros-button-apple",outline:"cedros-button-apple-outline"};return e.jsxs("button",{type:"button",className:`cedros-button ${b[a]} ${h[n]} ${r}`,onClick:m,disabled:o||!u||d,"aria-label":"Sign in with Apple",children:[d?e.jsx(N.LoadingSpinner,{size:"sm"}):e.jsx("svg",{className:"cedros-button-icon",width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),e.jsx("span",{children:"Continue with Apple"})]})}function se(s,t){if(!s)throw new Error(t)}function Qn(s){return s.replace(/-/g,"+").replace(/_/g,"/")}function Ze(s){se(typeof s=="string"&&s.length>0,"Expected base64url string");const t=Qn(s),r=t+"=".repeat((4-t.length%4)%4),a=atob(r),n=new Uint8Array(a.length);for(let o=0;o<a.length;o++)n[o]=a.charCodeAt(o);return n.buffer}function je(s){const t=new Uint8Array(s);let r="";for(let n=0;n<t.length;n++)r+=String.fromCharCode(t[n]);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function pr(s){se(typeof s=="object"&&s!==null,"Invalid credential descriptor");const t=s;return se(typeof t.type=="string","Invalid credential descriptor type"),se(typeof t.id=="string","Invalid credential descriptor id"),{type:t.type,id:Ze(t.id),transports:Array.isArray(t.transports)?t.transports:void 0}}function Kn(s){se(s&&typeof s=="object","Missing creation options");const t=s.publicKey;se(t&&typeof t=="object","Missing creation options.publicKey"),se(typeof t.challenge=="string","Missing creation challenge"),se(typeof t.rp=="object"&&t.rp!==null,"Missing rp"),se(typeof t.user=="object"&&t.user!==null,"Missing user");const r=t.rp,a=t.user;se(typeof r.name=="string","Missing rp.name"),se(typeof a.id=="string","Missing user.id"),se(typeof a.name=="string","Missing user.name"),se(typeof a.displayName=="string","Missing user.displayName");const n=Array.isArray(t.excludeCredentials)?t.excludeCredentials.map(pr):void 0,o=Array.isArray(t.pubKeyCredParams)?t.pubKeyCredParams.map(c=>({type:c.type,alg:c.alg})):[];return{challenge:Ze(t.challenge),rp:{name:r.name,id:typeof r.id=="string"?r.id:void 0},user:{id:Ze(a.id),name:a.name,displayName:a.displayName},pubKeyCredParams:o,timeout:typeof t.timeout=="number"?t.timeout:void 0,attestation:typeof t.attestation=="string"?t.attestation:void 0,authenticatorSelection:typeof t.authenticatorSelection=="object"&&t.authenticatorSelection!==null?t.authenticatorSelection:void 0,excludeCredentials:n,extensions:typeof t.extensions=="object"&&t.extensions!==null?t.extensions:void 0}}function Gn(s){se(s&&typeof s=="object","Missing request options");const t=s.publicKey;se(t&&typeof t=="object","Missing request options.publicKey"),se(typeof t.challenge=="string","Missing request challenge");const r=Array.isArray(t.allowCredentials)?t.allowCredentials.map(pr):void 0;return{challenge:Ze(t.challenge),rpId:typeof t.rpId=="string"?t.rpId:void 0,timeout:typeof t.timeout=="number"?t.timeout:void 0,userVerification:typeof t.userVerification=="string"?t.userVerification:void 0,allowCredentials:r,extensions:typeof t.extensions=="object"&&t.extensions!==null?t.extensions:void 0}}function ct(s){const t=je(s.rawId),r=s.response,n={...{clientDataJSON:je(r.clientDataJSON)}};if("attestationObject"in r){const o=r;if(n.attestationObject=je(o.attestationObject),typeof o.getTransports=="function")try{n.transports=o.getTransports()}catch{}}if("authenticatorData"in r){const o=r;n.authenticatorData=je(o.authenticatorData),n.signature=je(o.signature),o.userHandle&&(n.userHandle=je(o.userHandle))}return{id:s.id,rawId:t,type:s.type,authenticatorAttachment:s.authenticatorAttachment??void 0,clientExtensionResults:s.getClientExtensionResults?.()??{},response:n}}function Yn(){if(typeof window<"u"){const s=window.location?.hostname,t=s==="localhost"||s==="127.0.0.1"||s?.endsWith(".localhost");if(!(window.isSecureContext===!0)&&!t)return!1}return typeof window<"u"&&typeof window.PublicKeyCredential<"u"&&typeof navigator<"u"&&typeof navigator.credentials<"u"}function dt(s){if(!(s instanceof Error))return null;const t=s.name;return t==="NotAllowedError"?{code:"SERVER_ERROR",message:"Passkey operation was cancelled or timed out"}:t==="InvalidStateError"?{code:"VALIDATION_ERROR",message:"Passkey is not available for this operation"}:t==="SecurityError"?{code:"VALIDATION_ERROR",message:"Passkeys require HTTPS and a correctly configured relying party (WEBAUTHN_RP_ID / WEBAUTHN_RP_ORIGIN)"}:null}function fr(){const{config:s,_internal:t}=N.useCedrosLogin(),[r,a]=i.useState(!1),[n,o]=i.useState(null),c=i.useMemo(()=>new N.ApiClient({baseUrl:s.serverUrl,timeoutMs:s.requestTimeout,retryAttempts:s.retryAttempts,getAccessToken:t?.getAccessToken}),[t?.getAccessToken,s.serverUrl,s.requestTimeout,s.retryAttempts]),l=i.useCallback(()=>o(null),[]),d=Yn(),u=i.useCallback(async m=>{if(!d){const h={code:"VALIDATION_ERROR",message:"Passkeys are not supported in this browser"};throw o(h),h}a(!0),o(null);try{const h=await c.post("/webauthn/auth/options",{email:m?.email}),b=Gn(h.options),f=await navigator.credentials.get({publicKey:b});if(!f)throw new Error("Passkey authentication returned no credential");const p=await c.post("/webauthn/auth/verify",{challengeId:h.challengeId,credential:ct(f)});return s.callbacks?.onLoginSuccess?.(p.user,"webauthn"),t?.handleLoginSuccess(p.user,p.tokens),p}catch(h){const f=dt(h)??N.handleApiError(h,"Passkey sign-in failed");throw o(f),f}finally{a(!1)}},[c,s.callbacks,t,d]),g=i.useCallback(async m=>{if(!d){const h={code:"VALIDATION_ERROR",message:"Passkeys are not supported in this browser"};throw o(h),h}a(!0),o(null);try{const h=await c.post("/webauthn/register/options",{}),b=Kn(h.options),f=await navigator.credentials.create({publicKey:b});if(!f)throw new Error("Passkey registration returned no credential");const p=await c.post("/webauthn/register/verify",{challengeId:h.challengeId,credential:ct(f),label:m?.label});if(!p.success)throw new Error("Passkey registration failed");return{credentialId:p.credentialId,label:p.label}}catch(h){const f=dt(h)??N.handleApiError(h,"Passkey registration failed");throw o(f),f}finally{a(!1)}},[c,d]);return{isSupported:d,isLoading:r,error:n,clearError:l,authenticatePasskey:u,registerPasskey:g}}function gr({onSuccess:s,className:t="",children:r,disabled:a}){const{authenticatePasskey:n,isLoading:o,isSupported:c}=fr(),l=a||!c||o;return e.jsxs("button",{type:"button",className:`cedros-button cedros-button-social ${t}`,onClick:async()=>{await n(),s?.()},disabled:l,"aria-disabled":l,children:[e.jsx("span",{className:"cedros-social-icon","aria-hidden":"true",children:e.jsx(Jn,{})}),e.jsx("span",{children:r??(o?"Continuing...":"Continue with Passkey")})]})}function Jn(){return e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4"}),e.jsx("path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88"}),e.jsx("path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02"}),e.jsx("path",{d:"M2 12a10 10 0 0 1 18-6"}),e.jsx("path",{d:"M2 16h.01"}),e.jsx("path",{d:"M21.8 16c.2-2 .131-5.354 0-6"}),e.jsx("path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2"}),e.jsx("path",{d:"M8.65 22c.21-.66.45-1.32.57-2"}),e.jsx("path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2"})]})}const Me=["login","register"];function rs({onSuccess:s,className:t="",defaultTab:r="login"}){const{config:a}=N.useCedrosLogin(),[n,o]=i.useState(r),[c,l]=i.useState("form"),[d,u]=i.useState(()=>ps.detectSolanaWallets()),[g]=i.useState(()=>hr());i.useEffect(()=>{const v=()=>u(ps.detectSolanaWallets());return v(),window.addEventListener("load",v),window.addEventListener("focus",v),()=>{window.removeEventListener("load",v),window.removeEventListener("focus",v)}},[]);const m=a.forms?.forgotPassword?.mode??"reset",h=i.useCallback(v=>{const S=Me.indexOf(n);let w=S;switch(v.key){case"ArrowLeft":case"ArrowUp":w=S===0?Me.length-1:S-1;break;case"ArrowRight":case"ArrowDown":w=S===Me.length-1?0:S+1;break;case"Home":w=0;break;case"End":w=Me.length-1;break;default:return}v.preventDefault();const E=Me[w];o(E),document.getElementById(`cedros-tab-${E}`)?.focus()},[n]),b=a.features??{email:!0,google:!0,apple:!0,solana:!0,webauthn:!0},f=b.email!==!1,p=b.google!==!1&&a.googleClientId,x=b.apple!==!1&&a.appleClientId&&g,j=b.solana!==!1&&d,y=b.webauthn!==!1,A=f&&(p||x||j||y);return c==="forgotPassword"?e.jsx("div",{className:`cedros-login-form ${t}`,children:e.jsx(dr,{onCancel:()=>l("form")})}):e.jsxs("div",{className:`cedros-login-form ${t}`,children:[(y||p||x||j)&&e.jsxs("div",{className:"cedros-social-buttons",children:[y&&e.jsx(gr,{onSuccess:s}),p&&e.jsx(Nn.GoogleLoginButton,{onSuccess:s}),x&&e.jsx(mr,{onSuccess:s}),j&&e.jsx(ps.SolanaLoginButton,{onSuccess:s})]}),A&&e.jsx("div",{className:"cedros-divider",children:e.jsx("span",{children:"Or continue with"})}),f&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-tabs",role:"tablist","aria-label":"Authentication method",children:[e.jsx("button",{type:"button",role:"tab",id:"cedros-tab-login",className:`cedros-tab ${n==="login"?"cedros-tab-active":""}`,onClick:()=>o("login"),onKeyDown:h,"aria-selected":n==="login","aria-controls":"cedros-tabpanel-login",tabIndex:n==="login"?0:-1,children:"Sign in"}),e.jsx("button",{type:"button",role:"tab",id:"cedros-tab-register",className:`cedros-tab ${n==="register"?"cedros-tab-active":""}`,onClick:()=>o("register"),onKeyDown:h,"aria-selected":n==="register","aria-controls":"cedros-tabpanel-register",tabIndex:n==="register"?0:-1,children:"Sign up"})]}),e.jsx("div",{role:"tabpanel",id:`cedros-tabpanel-${n}`,"aria-labelledby":`cedros-tab-${n}`,children:n==="login"?e.jsx(X.EmailLoginForm,{onSuccess:s,onSwitchToRegister:()=>o("register"),onForgotPassword:m==="reset"?()=>l("forgotPassword"):void 0}):e.jsx(X.EmailRegisterForm,{onSuccess:s,onSwitchToLogin:()=>o("login")})})]})]})}class br extends i.Component{constructor(t){super(t),this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){this.setState({errorInfo:r}),process.env.NODE_ENV==="development"&&(console.error("[Cedros Login] Error caught by ErrorBoundary:",t),console.error("[Cedros Login] Component stack:",r.componentStack)),this.props.onError?.(t,r)}handleRetry=()=>{this.setState({hasError:!1,error:null,errorInfo:null})};render(){const{hasError:t,error:r,errorInfo:a}=this.state,{children:n,fallback:o,showDetails:c=!1}=this.props;return t?o||e.jsx("div",{className:"cedros-error-boundary",role:"alert","aria-live":"assertive",children:e.jsxs("div",{className:"cedros-error-boundary-content",children:[e.jsxs("svg",{className:"cedros-error-boundary-icon",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),e.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),e.jsx("h2",{className:"cedros-error-boundary-title",children:"Something went wrong"}),e.jsx("p",{className:"cedros-error-boundary-message",children:"We encountered an unexpected error. Please try again."}),c&&r&&e.jsxs("details",{className:"cedros-error-boundary-details",children:[e.jsx("summary",{children:"Error details"}),e.jsxs("pre",{children:[r.toString(),a?.componentStack]})]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:this.handleRetry,children:"Try again"})]})}):n}}function Xn({className:s="",title:t="Sign in to your account"}){const{isModalOpen:r,closeModal:a}=N.useCedrosLogin(),n=i.useRef(null),o=i.useRef(null),c=i.useRef(a);if(i.useEffect(()=>{c.current=a},[a]),i.useEffect(()=>{if(!r)return;o.current=document.activeElement,n.current?.focus();const d=g=>{if(g.key==="Escape"&&c.current(),g.key==="Tab"&&n.current){const m=n.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),h=m[0],b=m[m.length-1];g.shiftKey&&document.activeElement===h?(g.preventDefault(),b?.focus()):!g.shiftKey&&document.activeElement===b&&(g.preventDefault(),h?.focus())}};document.addEventListener("keydown",d);const u=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",d),document.body.style.overflow=u,o.current instanceof HTMLElement&&o.current.focus()}},[r]),!r)return null;const l=d=>{d.target===d.currentTarget&&a()};return e.jsx("div",{className:`cedros-modal-backdrop ${s}`,onClick:l,role:"presentation",children:e.jsxs("div",{ref:n,className:"cedros-modal",role:"dialog","aria-modal":"true","aria-labelledby":"cedros-modal-title",tabIndex:-1,children:[e.jsxs("div",{className:"cedros-modal-header",children:[e.jsx("h2",{id:"cedros-modal-title",className:"cedros-modal-title",children:t}),e.jsx("button",{type:"button",className:"cedros-modal-close",onClick:a,"aria-label":"Close",children:e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:e.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),e.jsx("div",{className:"cedros-modal-content",children:e.jsx(br,{children:e.jsx(rs,{onSuccess:a})})})]})})}function Zn({token:s,onSuccess:t,onLoginClick:r,className:a=""}){const[n,o]=i.useState(""),[c,l]=i.useState(""),[d,u]=i.useState(null),{resetPassword:g,isLoading:m,isSuccess:h,error:b,clearError:f}=Qs(),p=n===c,x=d?.isValid&&p&&n.length>0,j=async y=>{if(y.preventDefault(),!!x)try{await g(s,n),t?.()}catch{}};return h?e.jsxs("div",{className:`cedros-reset-password-success ${a}`,children:[e.jsxs("svg",{className:"cedros-success-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"22",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M14 24l7 7 13-13",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),e.jsx("h3",{className:"cedros-success-title",children:"Password reset successful"}),e.jsx("p",{className:"cedros-success-message",children:"Your password has been reset. You can now log in with your new password."}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-md cedros-button-primary",onClick:r,children:"Go to login"})]}):e.jsxs("form",{className:`cedros-reset-password-form ${a}`,onSubmit:j,children:[e.jsxs("div",{className:"cedros-form-header",children:[e.jsx("h3",{className:"cedros-form-title",children:"Reset your password"}),e.jsx("p",{className:"cedros-form-subtitle",children:"Enter your new password below."})]}),e.jsx(N.ErrorMessage,{error:b,onDismiss:f}),e.jsx("div",{className:"cedros-form-field",children:e.jsx(X.PasswordInput,{label:"New password",value:n,onChange:y=>{o(y.target.value),u(ts.validatePassword(y.target.value))},showStrengthMeter:!0,onValidationChange:u,disabled:m,autoComplete:"new-password",error:d&&!d.isValid?Object.values(d.errors).find(Boolean):void 0})}),e.jsx("div",{className:"cedros-form-field",children:e.jsx(X.PasswordInput,{label:"Confirm password",value:c,onChange:y=>l(y.target.value),disabled:m,autoComplete:"new-password",error:c&&!p?"Passwords do not match":void 0})}),e.jsxs("div",{className:"cedros-form-actions",children:[e.jsx("button",{type:"submit",className:"cedros-button cedros-button-md cedros-button-primary cedros-button-full",disabled:m||!x,children:m?e.jsxs(e.Fragment,{children:[e.jsx(N.LoadingSpinner,{size:"sm"}),"Resetting..."]}):"Reset password"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-md cedros-button-ghost cedros-button-full",onClick:r,disabled:m,children:"Back to login"})]})]})}function zs({org:s,size:t="lg",className:r=""}){const a=X.sanitizeImageUrl(s.logoUrl),n=t==="lg"?"cedros-org-avatar-lg":"",o=["cedros-org-avatar",n,r].filter(Boolean).join(" "),c=["cedros-org-avatar-placeholder",n,r].filter(Boolean).join(" ");return a?e.jsx("img",{src:a,alt:s.name,className:o,referrerPolicy:"no-referrer"}):e.jsx("div",{className:c,children:s.name[0]?.toUpperCase()||"?"})}function ea({orgs:s,activeOrg:t,isLoading:r=!1,onSelect:a,onCreateClick:n,className:o="",placeholder:c="Select organization"}){const[l,d]=i.useState(!1),u=i.useRef(null);i.useEffect(()=>{const b=f=>{u.current&&!u.current.contains(f.target)&&d(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]),i.useEffect(()=>{const b=f=>{f.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[l]);const g=i.useCallback(b=>{a(b),d(!1)},[a]),m=i.useCallback(()=>{d(!1),n?.()},[n]),h=i.useCallback(()=>{d(b=>!b)},[]);return r?e.jsxs("div",{className:`cedros-org-selector cedros-org-selector-loading ${o}`,"aria-busy":"true","aria-live":"polite",children:[e.jsx(N.LoadingSpinner,{size:"sm"}),e.jsx("span",{children:"Loading..."})]}):e.jsxs("div",{ref:u,className:`cedros-org-selector ${o}`,children:[e.jsxs("button",{type:"button",className:"cedros-org-selector-trigger",onClick:h,"aria-haspopup":"listbox","aria-expanded":l,children:[t?e.jsxs(e.Fragment,{children:[e.jsx(zs,{org:t,size:"sm"}),e.jsx("span",{className:"cedros-org-selector-name",children:t.name}),e.jsx(ut,{role:t.membership.role})]}):e.jsx("span",{className:"cedros-org-selector-placeholder",children:c}),e.jsx(sa,{isOpen:l})]}),l&&e.jsxs("div",{className:"cedros-org-selector-dropdown",role:"listbox",children:[s.length===0?e.jsx("div",{className:"cedros-org-selector-empty",children:"No organizations"}):e.jsx("ul",{className:"cedros-org-selector-list",children:s.map(b=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:`cedros-org-selector-item ${b.id===t?.id?"cedros-org-selector-item-active":""}`,onClick:()=>g(b.id),role:"option","aria-selected":b.id===t?.id,children:[e.jsx(zs,{org:b,size:"sm"}),e.jsx("span",{className:"cedros-org-selector-item-name",children:b.name}),e.jsx(ut,{role:b.membership.role}),b.id===t?.id&&e.jsx(ta,{})]})},b.id))}),n&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cedros-org-selector-divider"}),e.jsxs("button",{type:"button",className:"cedros-org-selector-create",onClick:m,children:[e.jsx(ra,{}),e.jsx("span",{children:"Create organization"})]})]})]})]})}function ut({role:s}){return e.jsx("span",{className:`cedros-org-role cedros-org-role-${s}`,children:s})}function sa({isOpen:s}){return e.jsx("svg",{className:`cedros-org-chevron ${s?"cedros-org-chevron-open":""}`,width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function ta(){return e.jsx("svg",{className:"cedros-org-check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M3 8L6 11L13 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function ra(){return e.jsx("svg",{className:"cedros-org-plus",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M8 3V13M3 8H13",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function na(){return e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M5 5L15 15M15 5L5 15",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function aa(){return e.jsx("svg",{className:"cedros-org-check",width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M4 10L8 14L16 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function oa(){return e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M10 4V16M4 10H16",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function ia({orgs:s,activeOrg:t,isLoading:r,onSelect:a,onCreateClick:n}){return r?e.jsxs("div",{className:"cedros-org-switcher-loading",children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading organizations..."})]}):e.jsxs(e.Fragment,{children:[s.length===0?e.jsx("div",{className:"cedros-org-switcher-empty",children:e.jsx("p",{children:"You don't belong to any organizations yet."})}):e.jsx("ul",{className:"cedros-org-switcher-list",children:s.map(o=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:`cedros-org-switcher-item ${o.id===t?.id?"cedros-org-switcher-item-active":""}`,onClick:()=>a(o.id),children:[e.jsx(zs,{org:o}),e.jsxs("div",{className:"cedros-org-switcher-item-content",children:[e.jsx("span",{className:"cedros-org-switcher-item-name",children:o.name}),e.jsxs("span",{className:"cedros-org-switcher-item-slug",children:["@",o.slug]})]}),e.jsxs("div",{className:"cedros-org-switcher-item-meta",children:[e.jsx("span",{className:`cedros-org-role cedros-org-role-${o.membership.role}`,children:o.membership.role}),o.isPersonal&&e.jsx("span",{className:"cedros-org-personal-badge",children:"Personal"})]}),o.id===t?.id&&e.jsx(aa,{})]})},o.id))}),n&&e.jsxs("button",{type:"button",className:"cedros-org-switcher-create",onClick:n,children:[e.jsx(oa,{}),e.jsx("span",{children:"Create new organization"})]})]})}function la({isLoading:s,onSubmit:t,onCancel:r}){const[a,n]=i.useState(""),[o,c]=i.useState(""),[l,d]=i.useState(null),u=i.useCallback(m=>{n(m);const h=m.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").substring(0,50);c(h)},[]),g=i.useCallback(async m=>{if(m.preventDefault(),d(null),!a.trim()){d("Organization name is required");return}if(!o.trim()){d("Organization slug is required");return}try{await t({name:a.trim(),slug:o.trim()})}catch(h){d(h.message||"Failed to create organization")}},[a,o,t]);return e.jsxs("form",{className:"cedros-org-create-form",onSubmit:g,children:[l&&e.jsx(N.ErrorMessage,{error:l}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{htmlFor:"org-name",className:"cedros-form-label",children:"Organization Name"}),e.jsx("input",{id:"org-name",type:"text",className:"cedros-form-input",value:a,onChange:m=>u(m.target.value),placeholder:"My Organization",maxLength:255,disabled:s,autoFocus:!0})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{htmlFor:"org-slug",className:"cedros-form-label",children:"URL Slug"}),e.jsxs("div",{className:"cedros-form-input-prefix",children:[e.jsx("span",{className:"cedros-form-prefix",children:"@"}),e.jsx("input",{id:"org-slug",type:"text",className:"cedros-form-input",value:o,onChange:m=>c(m.target.value.toLowerCase()),placeholder:"my-organization",maxLength:100,pattern:"[a-z0-9-]+",disabled:s})]}),e.jsx("span",{className:"cedros-form-hint",children:"Only lowercase letters, numbers, and hyphens"})]}),e.jsxs("div",{className:"cedros-form-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:r,disabled:s,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:s||!a.trim()||!o.trim(),children:s?e.jsx(N.LoadingSpinner,{size:"sm"}):"Create Organization"})]})]})}function ca({isOpen:s,onClose:t,orgs:r,activeOrg:a,isLoading:n=!1,error:o,onSelect:c,onCreate:l,className:d=""}){return s?e.jsx(da,{onClose:t,orgs:r,activeOrg:a,isLoading:n,error:o,onSelect:c,onCreate:l,className:d}):null}function da({onClose:s,orgs:t,activeOrg:r,isLoading:a=!1,error:n,onSelect:o,onCreate:c,className:l}){const[d,u]=i.useState("list"),g=i.useRef(null),m=i.useRef(null);i.useEffect(()=>(m.current=document.activeElement,g.current?.querySelector(".cedros-modal-close")?.focus(),()=>{m.current?.focus()}),[]),i.useEffect(()=>{const p=x=>{if(x.key==="Escape"){s();return}if(x.key==="Tab"&&g.current){const j=g.current.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'),y=j[0],A=j[j.length-1];x.shiftKey?document.activeElement===y&&(x.preventDefault(),A?.focus()):document.activeElement===A&&(x.preventDefault(),y?.focus())}};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[s]);const h=i.useCallback(p=>{p.target===p.currentTarget&&s()},[s]),b=i.useCallback(p=>{o(p),s()},[o,s]),f=i.useCallback(async p=>{await c?.(p),s()},[c,s]);return e.jsx("div",{className:"cedros-modal-backdrop",onClick:h,children:e.jsxs("div",{ref:g,className:`cedros-modal cedros-org-switcher ${l}`,role:"dialog","aria-modal":"true","aria-labelledby":"org-switcher-title",children:[e.jsxs("div",{className:"cedros-modal-header",children:[e.jsx("h2",{id:"org-switcher-title",className:"cedros-modal-title",children:d==="list"?"Switch Organization":"Create Organization"}),e.jsx("button",{type:"button",className:"cedros-modal-close",onClick:s,"aria-label":"Close",children:e.jsx(na,{})})]}),e.jsxs("div",{className:"cedros-modal-body",children:[n&&e.jsx(N.ErrorMessage,{error:n}),d==="list"?e.jsx(ia,{orgs:t,activeOrg:r,isLoading:a,onSelect:b,onCreateClick:c?()=>u("create"):void 0}):e.jsx(la,{isLoading:a,onSubmit:f,onCancel:()=>u("list")})]})]})})}const ua=["owner","admin","member"];function yr({members:s,currentUserId:t,isLoading:r=!1,error:a,canManage:n=!1,canChangeRoles:o=!1,onUpdateRole:c,onRemove:l,className:d=""}){const[u,g]=i.useState("name"),[m,h]=i.useState("asc"),b=p=>{u===p?h(m==="asc"?"desc":"asc"):(g(p),h("asc"))},f=i.useMemo(()=>{const p={owner:0,admin:1,member:2};return[...s].sort((x,j)=>{let y,A;switch(u){case"name":y=(x.user.name||x.user.email||"").toLowerCase(),A=(j.user.name||j.user.email||"").toLowerCase();break;case"role":y=p[x.role]??99,A=p[j.role]??99;break;case"joinedAt":y=new Date(x.joinedAt).getTime(),A=new Date(j.joinedAt).getTime();break;default:return 0}return y<A?m==="asc"?-1:1:y>A?m==="asc"?1:-1:0})},[s,u,m]);return r&&s.length===0?e.jsxs("div",{className:`cedros-member-list cedros-member-list-loading ${d}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading members..."})]}):a?e.jsx("div",{className:`cedros-member-list ${d}`,children:e.jsx(N.ErrorMessage,{error:a})}):s.length===0?e.jsx("div",{className:`cedros-member-list cedros-member-list-empty ${d}`,children:e.jsx("p",{children:"No members found."})}):e.jsx("div",{className:`cedros-member-list ${d}`,children:e.jsxs("table",{className:"cedros-member-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${u==="name"?"cedros-admin-sort-active":""}`,onClick:()=>b("name"),children:["Member"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:u==="name"?m==="asc"?"↑":"↓":"↕"})]})}),e.jsx("th",{children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${u==="role"?"cedros-admin-sort-active":""}`,onClick:()=>b("role"),children:["Role"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:u==="role"?m==="asc"?"↑":"↓":"↕"})]})}),e.jsx("th",{children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${u==="joinedAt"?"cedros-admin-sort-active":""}`,onClick:()=>b("joinedAt"),children:["Joined"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:u==="joinedAt"?m==="asc"?"↑":"↓":"↕"})]})}),(n||o)&&e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:f.map(p=>e.jsx(ha,{member:p,isCurrentUser:p.userId===t,canManage:n,canChangeRoles:o,onUpdateRole:c,onRemove:l},p.id))})]})})}function ha({member:s,isCurrentUser:t,canManage:r,canChangeRoles:a,onUpdateRole:n,onRemove:o}){const[c,l]=i.useState(!1),[d,u]=i.useState(s.role),g=i.useCallback(async f=>{if(!(!n||f===s.role)){l(!0);try{await n(s.userId,f),u(f)}catch{u(s.role)}finally{l(!1)}}},[s.userId,s.role,n]),m=i.useCallback(async()=>{if(!(!o||!window.confirm(`Are you sure you want to remove ${s.user.name||s.user.email} from this organization?`))){l(!0);try{await o(s.userId)}finally{l(!1)}}},[s.userId,s.user.name,s.user.email,o]),h=s.role==="owner",b=!t&&!h;return e.jsxs("tr",{className:`cedros-member-row ${t?"cedros-member-row-current":""}`,children:[e.jsxs("td",{className:"cedros-member-info",children:[e.jsx(ma,{user:s.user}),e.jsxs("div",{className:"cedros-member-details",children:[e.jsxs("span",{className:"cedros-member-name",children:[s.user.name||"Unknown",t&&e.jsx("span",{className:"cedros-member-you",children:"(you)"})]}),e.jsx("span",{className:"cedros-member-email",children:s.user.email})]})]}),e.jsx("td",{className:"cedros-member-role",children:a&&b&&n?e.jsx("select",{value:d,onChange:f=>g(f.target.value),disabled:c,className:"cedros-role-select",children:ua.map(f=>e.jsx("option",{value:f,children:f.charAt(0).toUpperCase()+f.slice(1)},f))}):e.jsx("span",{className:`cedros-role-badge cedros-role-badge-${s.role}`,children:s.role.charAt(0).toUpperCase()+s.role.slice(1)})}),e.jsx("td",{className:"cedros-member-joined",children:pa(s.joinedAt)}),(r||a)&&e.jsx("td",{className:"cedros-member-actions",children:r&&b&&o&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-danger cedros-button-sm",onClick:m,disabled:c,"aria-label":`Remove ${s.user.name||s.user.email}`,children:c?e.jsx(N.LoadingSpinner,{size:"sm"}):"Remove"})})]})}function ma({user:s}){const t=X.sanitizeImageUrl(s.picture);if(t)return e.jsx("img",{src:t,alt:s.name||s.email||"Member",className:"cedros-member-avatar",referrerPolicy:"no-referrer"});const r=(s.name?.[0]||s.email?.[0]||"?").toUpperCase();return e.jsx("div",{className:"cedros-member-avatar-placeholder",children:r})}function pa(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}const fa=["admin","member"];function wr({onSubmit:s,isLoading:t=!1,error:r,availableRoles:a=fa,defaultRole:n="member",className:o=""}){const[c,l]=i.useState(""),[d,u]=i.useState(n),[g,m]=i.useState(null),[h,b]=i.useState(!1),f=i.useRef(null),p=i.useRef(!0);i.useEffect(()=>(p.current=!0,()=>{p.current=!1,f.current!==null&&(window.clearTimeout(f.current),f.current=null)}),[]);const x=i.useCallback(async j=>{j.preventDefault(),m(null),b(!1);const y=c.trim();if(!y){m("Email is required");return}if(!ts.validateEmail(y)){m("Please enter a valid email address");return}try{await s(y,d),l(""),u(n),b(!0),f.current!==null&&window.clearTimeout(f.current),f.current=window.setTimeout(()=>{p.current&&b(!1),f.current=null},3e3)}catch{}},[c,d,n,s]);return e.jsxs("form",{className:`cedros-invite-form ${o}`,onSubmit:x,children:[(r||g)&&e.jsx(N.ErrorMessage,{error:g??r??null}),h&&e.jsxs("div",{className:"cedros-invite-success",role:"status",children:[e.jsx(ga,{}),e.jsx("span",{children:"Invitation sent successfully!"})]}),e.jsxs("div",{className:"cedros-invite-form-row",children:[e.jsxs("div",{className:"cedros-form-group cedros-invite-email-group",children:[e.jsx("label",{htmlFor:"invite-email",className:"cedros-form-label",children:"Email Address"}),e.jsx("input",{id:"invite-email",type:"email",className:"cedros-form-input",value:c,onChange:j=>l(j.target.value),placeholder:"colleague@example.com",disabled:t,autoComplete:"email"})]}),e.jsxs("div",{className:"cedros-form-group cedros-invite-role-group",children:[e.jsx("label",{htmlFor:"invite-role",className:"cedros-form-label",children:"Role"}),e.jsx("select",{id:"invite-role",className:"cedros-form-select",value:d,onChange:j=>u(j.target.value),disabled:t,children:a.map(j=>e.jsx("option",{value:j,children:j.charAt(0).toUpperCase()+j.slice(1)},j))})]}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary cedros-invite-submit",disabled:t||!c.trim(),children:t?e.jsx(N.LoadingSpinner,{size:"sm"}):"Send Invite"})]}),e.jsx("p",{className:"cedros-form-hint",children:"The invited user will receive an email with a link to join your organization."})]})}function ga(){return e.jsx("svg",{className:"cedros-invite-check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M3 8L6 11L13 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function xr({invites:s,isLoading:t=!1,error:r,canManage:a=!1,onCancel:n,onResend:o,className:c=""}){return t&&s.length===0?e.jsxs("div",{className:`cedros-invite-list cedros-invite-list-loading ${c}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading invites..."})]}):r?e.jsx("div",{className:`cedros-invite-list ${c}`,children:e.jsx(N.ErrorMessage,{error:r})}):s.length===0?e.jsx("div",{className:`cedros-invite-list cedros-invite-list-empty ${c}`,children:e.jsx("p",{children:"No pending invites."})}):e.jsx("div",{className:`cedros-invite-list ${c}`,children:e.jsx("ul",{className:"cedros-invite-items",children:s.map(l=>e.jsx(ba,{invite:l,canManage:a,onCancel:n,onResend:o},l.id))})})}function ba({invite:s,canManage:t,onCancel:r,onResend:a}){const[n,o]=i.useState(!1),[c,l]=i.useState(!1),d=i.useRef(null),u=new Date(s.expiresAt)<new Date,g=i.useCallback(async()=>{if(!(!r||!window.confirm(`Are you sure you want to cancel the invite for ${s.email}?`))){o(!0);try{await r(s.id)}finally{o(!1)}}},[s.id,s.email,r]),m=i.useCallback(async()=>{if(a){o(!0),l(!1);try{await a(s.id),l(!0),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{l(!1),d.current=null},3e3)}finally{o(!1)}}},[s.id,a]);return i.useEffect(()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},[]),e.jsxs("li",{className:`cedros-invite-item ${u?"cedros-invite-item-expired":""}`,children:[e.jsxs("div",{className:"cedros-invite-item-info",children:[e.jsxs("div",{className:"cedros-invite-item-main",children:[e.jsx("span",{className:"cedros-invite-item-email",children:s.email}),e.jsx("span",{className:`cedros-role-badge cedros-role-badge-${s.role}`,children:s.role.charAt(0).toUpperCase()+s.role.slice(1)}),u&&e.jsx("span",{className:"cedros-invite-expired-badge",children:"Expired"})]}),e.jsxs("div",{className:"cedros-invite-item-meta",children:[e.jsxs("span",{className:"cedros-invite-item-date",children:["Invited ",vr(s.createdAt)]}),!u&&e.jsxs("span",{className:"cedros-invite-item-expires",children:["Expires ",ya(s.expiresAt)]})]})]}),t&&e.jsxs("div",{className:"cedros-invite-item-actions",children:[c&&e.jsx("span",{className:"cedros-invite-resend-success",children:"Sent!"}),a&&!u&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:m,disabled:n,"aria-label":`Resend invite to ${s.email}`,children:n?e.jsx(N.LoadingSpinner,{size:"sm"}):"Resend"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-danger cedros-button-sm",onClick:g,disabled:n,"aria-label":`Cancel invite for ${s.email}`,children:"Cancel"})]})]})}function vr(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ya(s){const t=new Date(s),r=new Date,a=t.getTime()-r.getTime(),n=Math.ceil(a/(1e3*60*60*24));return n<0?"expired":n===0?"today":n===1?"tomorrow":n<7?`in ${n} days`:vr(s)}function wa({sessions:s,isLoading:t=!1,error:r,onRevokeAll:a,className:n=""}){const[o,c]=i.useState(!1),[l,d]=i.useState(!1),u=i.useRef(null),g=i.useMemo(()=>s.filter(h=>!h.isCurrent).length,[s]),m=i.useCallback(async()=>{if(!a)return;const h=s.filter(f=>!f.isCurrent).length;if(!(h===0||!window.confirm(`Are you sure you want to sign out of ${h} other device(s)? This will log you out everywhere except this browser.`))){c(!0),d(!1);try{await a(),d(!0),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{d(!1),u.current=null},3e3)}finally{c(!1)}}},[a,s]);return i.useEffect(()=>()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]),t&&s.length===0?e.jsxs("div",{className:`cedros-session-list cedros-session-list-loading ${n}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading sessions..."})]}):r?e.jsx("div",{className:`cedros-session-list ${n}`,children:e.jsx(N.ErrorMessage,{error:r})}):s.length===0?e.jsx("div",{className:`cedros-session-list cedros-session-list-empty ${n}`,children:e.jsx("p",{children:"No active sessions found."})}):e.jsxs("div",{className:`cedros-session-list ${n}`,children:[l&&e.jsxs("div",{className:"cedros-session-success",role:"status",children:[e.jsx(Na,{}),e.jsx("span",{children:"All other sessions have been revoked."})]}),e.jsx("ul",{className:"cedros-session-items",children:s.map(h=>e.jsx(xa,{session:h},h.id))}),a&&g>0&&e.jsx("div",{className:"cedros-session-actions",children:e.jsx("button",{type:"button",className:"cedros-button cedros-button-danger",onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(N.LoadingSpinner,{size:"sm"}),e.jsx("span",{children:"Signing out..."})]}):`Sign out of ${g} other device${g>1?"s":""}`})})]})}function xa({session:s}){const t=va(s.userAgent),r=Aa(s.expiresAt);return e.jsxs("li",{className:`cedros-session-item ${s.isCurrent?"cedros-session-item-current":""}`,children:[e.jsx("div",{className:"cedros-session-item-icon",children:e.jsx(ka,{userAgent:s.userAgent})}),e.jsxs("div",{className:"cedros-session-item-info",children:[e.jsxs("div",{className:"cedros-session-item-main",children:[e.jsxs("span",{className:"cedros-session-item-device",children:[t.browser," on ",t.os]}),s.isCurrent&&e.jsx("span",{className:"cedros-session-current-badge",children:"Current session"})]}),e.jsxs("div",{className:"cedros-session-item-meta",children:[s.ipAddress&&e.jsxs("span",{className:"cedros-session-item-ip",children:["IP: ",s.ipAddress]}),e.jsxs("span",{className:"cedros-session-item-created",children:["Started ",ja(s.createdAt)]}),r&&e.jsx("span",{className:"cedros-session-expiring",children:"Expires soon"})]})]})]})}function va(s){if(!s)return{browser:"Unknown browser",os:"Unknown device"};let t="Unknown browser";s.includes("Chrome")&&!s.includes("Edg")?t="Chrome":s.includes("Safari")&&!s.includes("Chrome")?t="Safari":s.includes("Firefox")?t="Firefox":s.includes("Edg")&&(t="Edge");let r="Unknown device";return s.includes("Windows")?r="Windows":s.includes("Mac")?r="macOS":s.includes("Linux")?r="Linux":s.includes("iPhone")||s.includes("iPad")?r="iOS":s.includes("Android")&&(r="Android"),{browser:t,os:r}}function ja(s){const t=new Date(s),a=new Date().getTime()-t.getTime(),n=Math.floor(a/(1e3*60)),o=Math.floor(a/(1e3*60*60)),c=Math.floor(a/(1e3*60*60*24));return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:o<24?`${o} hour${o>1?"s":""} ago`:c<7?`${c} day${c>1?"s":""} ago`:t.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Aa(s){const t=new Date(s),r=new Date,a=3600*1e3;return t.getTime()-r.getTime()<a}function ka({userAgent:s}){return s?.includes("iPhone")||s?.includes("iPad")||s?.includes("Android")?e.jsxs("svg",{className:"cedros-session-device-icon",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("circle",{cx:"12",cy:"18",r:"1",fill:"currentColor"})]}):e.jsxs("svg",{className:"cedros-session-device-icon",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("rect",{x:"2",y:"4",width:"20",height:"14",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("path",{d:"M8 21H16",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),e.jsx("path",{d:"M12 18V21",stroke:"currentColor",strokeWidth:"1.5"})]})}function Na(){return e.jsx("svg",{className:"cedros-session-check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M3 8L6 11L13 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function jr({words:s,onConfirm:t,className:r=""}){const[a,n]=i.useState(!1),[o,c]=i.useState(!1),l=i.useRef(null),d=$n(s),u=i.useCallback(async()=>{try{await navigator.clipboard.writeText(s.join(" ")),n(!0),l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>n(!1),2e3)}catch{}},[s]);i.useEffect(()=>()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null)},[]);const g=i.useCallback(()=>{o&&t()},[o,t]);return e.jsxs("div",{className:`cedros-recovery-phrase-display ${r}`,children:[e.jsxs("div",{className:"cedros-recovery-header",children:[e.jsx("h3",{className:"cedros-recovery-title",children:"Recovery Phrase"}),e.jsx("p",{className:"cedros-recovery-warning",children:"Write down these 12 words in order and store them securely. This is the only way to recover your wallet if you lose access."})]}),e.jsx("div",{className:"cedros-recovery-grid",children:d.map((m,h)=>e.jsx("div",{className:"cedros-word-group",children:m.map((b,f)=>{const p=h*4+f+1;return e.jsxs("div",{className:"cedros-word-item",children:[e.jsxs("span",{className:"cedros-word-number",children:[p,"."]}),e.jsx("span",{className:"cedros-word-text",children:b})]},p)})},h))}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary cedros-copy-btn",onClick:u,children:a?"Copied!":"Copy to Clipboard"}),e.jsx("div",{className:"cedros-recovery-security",children:e.jsxs("div",{className:"cedros-warning-box",children:[e.jsx("svg",{className:"cedros-warning-icon",width:"20",height:"20",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:e.jsx("path",{d:"M10 6v4m0 4h.01M19 10a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})}),e.jsxs("div",{className:"cedros-warning-content",children:[e.jsx("strong",{children:"Security Warning"}),e.jsxs("ul",{children:[e.jsx("li",{children:"Never share this phrase with anyone"}),e.jsx("li",{children:"Store it offline in a secure location"}),e.jsx("li",{children:"Anyone with this phrase can access your wallet"}),e.jsx("li",{children:"Cedros cannot recover this phrase for you"})]})]})]})}),e.jsxs("div",{className:"cedros-recovery-confirm",children:[e.jsxs("label",{className:"cedros-checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:m=>c(m.target.checked),className:"cedros-checkbox"}),e.jsx("span",{children:"I have written down and securely stored my recovery phrase"})]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:g,disabled:!o,children:"Continue"})]})]})}function Ar({onSubmit:s,onCancel:t,isSubmitting:r=!1,error:a,className:n=""}){const[o,c]=i.useState(Array(oe).fill("")),[l,d]=i.useState(null),[u,g]=i.useState([]),[m,h]=i.useState(null),b=i.useId(),f=i.useRef(null),p=i.useCallback((w,E)=>{const P=[...o];if(P[w]=E.toLowerCase().trim(),c(P),E.length>0){const L=Wn(E,5);g(L)}else g([]);h(null)},[o]),x=i.useCallback(w=>{d(w),g([])},[]),j=i.useCallback(w=>{const E=o[w];E&&!We(E)&&h(`Word ${w+1} is not in the wordlist`),f.current!==null&&window.clearTimeout(f.current),f.current=window.setTimeout(()=>{l===w&&g([])},200)},[o,l]);i.useEffect(()=>()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},[]);const y=i.useCallback(w=>{if(l!==null){const E=[...o];E[l]=w,c(E),g([]),document.querySelector(`[data-word-index="${l+1}"]`)?.focus()}},[l,o]),A=i.useCallback(w=>{const E=w.clipboardData.getData("text"),P=zn(E);P.length===oe&&(w.preventDefault(),c(P),h(null))},[]),v=i.useCallback(w=>{if(w.preventDefault(),o.filter(L=>!L).length>0){h(`Please enter all ${oe} words`);return}const P=o.map((L,T)=>({word:L,index:T+1})).filter(({word:L})=>!We(L));if(P.length>0){h(`Invalid words: ${P.map(L=>`#${L.index}`).join(", ")}`);return}if(!cr(o)){h("Invalid recovery phrase - please check your words");return}s(o)},[o,s]),S=a||m;return e.jsxs("form",{className:`cedros-recovery-phrase-input ${n}`,onSubmit:v,onPaste:A,children:[e.jsxs("div",{className:"cedros-recovery-input-header",children:[e.jsx("h3",{className:"cedros-recovery-input-title",children:"Enter Recovery Phrase"}),e.jsx("p",{className:"cedros-recovery-input-description",children:"Enter your 12-word recovery phrase. You can paste the entire phrase at once."})]}),e.jsx("div",{className:"cedros-word-inputs",children:Array.from({length:oe},(w,E)=>e.jsxs("div",{className:"cedros-word-input-wrapper",children:[e.jsxs("label",{className:"cedros-word-label",children:[E+1,"."]}),e.jsx("input",{type:"text",className:`cedros-word-input ${o[E]&&!We(o[E])?"cedros-word-invalid":o[E]&&We(o[E])?"cedros-word-valid":""}`,value:o[E],onChange:P=>p(E,P.target.value),onFocus:()=>x(E),onBlur:()=>j(E),"data-word-index":E,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,disabled:r,"aria-label":`Word ${E+1}`})]},E))}),l!==null&&u.length>0&&e.jsx("div",{className:"cedros-suggestions",role:"listbox",id:`${b}-suggestions`,children:u.map(w=>e.jsx("button",{type:"button",className:"cedros-suggestion",onClick:()=>y(w),role:"option",children:w},w))}),S&&e.jsx("p",{className:"cedros-input-error",role:"alert",children:S}),e.jsxs("div",{className:"cedros-recovery-input-actions",children:[t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:t,disabled:r,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:r,children:r?"Recovering...":"Recover Wallet"})]})]})}function Sa({capabilities:s,className:t=""}){if(s.allSupported)return null;const r=N.getMissingCapabilitiesMessage(s),a=N.getBrowserSupportInfo();return e.jsxs("div",{className:`cedros-capability-warning ${t}`,role:"alert",children:[e.jsxs("div",{className:"cedros-warning-header",children:[e.jsx("svg",{className:"cedros-warning-icon",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:e.jsx("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})}),e.jsx("h3",{className:"cedros-warning-title",children:"Wallet Feature Unavailable"})]}),e.jsx("p",{className:"cedros-warning-message",children:r}),e.jsxs("div",{className:"cedros-capability-details",children:[e.jsx("h4",{children:"Browser Compatibility"}),e.jsxs("p",{children:["Detected: ",a.browser," ",a.version,a.likelySupported?" (likely supported)":" (may not be supported)"]}),e.jsx("h4",{children:"Required Features"}),e.jsxs("ul",{className:"cedros-capability-list",children:[e.jsxs("li",{className:s.webCrypto?"cedros-cap-ok":"cedros-cap-missing",children:["Web Crypto API: ",s.webCrypto?"Available":"Missing"]}),e.jsxs("li",{className:s.aesGcm?"cedros-cap-ok":"cedros-cap-missing",children:["AES-GCM Encryption: ",s.aesGcm?"Available":"Missing"]}),e.jsxs("li",{className:s.hkdf?"cedros-cap-ok":"cedros-cap-missing",children:["HKDF Key Derivation: ",s.hkdf?"Available":"Missing"]}),e.jsxs("li",{className:s.webAuthn?"cedros-cap-ok":"cedros-cap-missing",children:["WebAuthn/Passkeys: ",s.webAuthn?"Available":"Missing"]}),e.jsxs("li",{className:s.webAuthnPrf?"cedros-cap-ok":"cedros-cap-missing",children:["WebAuthn PRF Extension: ",s.webAuthnPrf?"Available":"Missing"]}),e.jsxs("li",{className:s.argon2?"cedros-cap-ok":"cedros-cap-missing",children:["Argon2 Password Hashing: ",s.argon2?"Available":"Missing"]})]})]}),e.jsxs("div",{className:"cedros-capability-help",children:[e.jsx("h4",{children:"Recommended Browsers"}),e.jsxs("ul",{children:[e.jsx("li",{children:"Chrome 116+ on Windows, macOS, or Android"}),e.jsx("li",{children:"Safari 17+ on macOS or iOS"}),e.jsx("li",{children:"Edge 116+ on Windows"})]}),e.jsx("p",{className:"cedros-capability-note",children:"A platform authenticator (Touch ID, Face ID, or Windows Hello) is required."})]})]})}const Ca=["share_c_only","full_seed","none"];function _a(s){return s&&Ca.includes(s)?s:"share_c_only"}const Ea={walletEnabled:!1,recoveryMode:"share_c_only",unlockTtlSeconds:900,isLoading:!1,error:null,refetch:async()=>{}};function kr(){const s=N.useCedrosLoginOptional(),[t,r]=i.useState(null),[a,n]=i.useState(!!s),[o,c]=i.useState(null),l=i.useMemo(()=>s?new N.ApiClient({baseUrl:s.config.serverUrl,timeoutMs:s.config.requestTimeout,retryAttempts:s.config.retryAttempts}):null,[s]),d=i.useCallback(async()=>{if(l){n(!0),c(null);try{const u=await l.get("/discovery");u.wallet?r({enabled:u.wallet.enabled,recoveryMode:_a(u.wallet.recoveryMode),unlockTtlSeconds:u.wallet.unlockTtlSeconds}):r({enabled:!1,recoveryMode:"share_c_only",unlockTtlSeconds:900})}catch(u){const g=u instanceof Error?u.message:"Failed to fetch wallet config";c(g),r({enabled:!1,recoveryMode:"share_c_only",unlockTtlSeconds:900})}finally{n(!1)}}},[l]);return i.useEffect(()=>{l&&d()},[l,d]),s?{walletEnabled:t?.enabled??!1,recoveryMode:t?.recoveryMode??"share_c_only",unlockTtlSeconds:t?.unlockTtlSeconds??900,isLoading:a,error:o,refetch:d}:Ea}function Nr(){const{user:s}=N.useCedrosLogin(),{enroll:t}=N.useWalletMaterial(),{recoveryMode:r}=kr(),[a,n]=i.useState({step:"idle"}),[o,c]=i.useState(!1),l=i.useRef([]),d=i.useCallback(()=>{N.wipeAll(...l.current),l.current=[]},[]);i.useEffect(()=>()=>{d()},[d]);const u=i.useCallback(async(f,p,x,j)=>{n({step:"generating_seed"});const y=N.generateSeed();l.current.push(y),n({step:"splitting_shares"});const{shareA:A,shareB:v,shareC:S}=le.splitSecret(y);l.current.push(A,v,S),n({step:"encrypting_shares"});const w=await N.aesGcmEncryptToBase64(A,N.toEncryptionKey(p)),E=le.getPublicKeyFromSeed(y),P=le.publicKeyToBase58(E);n({step:"uploading"});const L={solanaPubkey:P,shareAAuthMethod:f,shareACiphertext:w.ciphertext,shareANonce:w.nonce,shareB:N.uint8ArrayToBase64(v)};if(f==="password"){if(!x)throw new Error("KDF salt required for password method");L.shareAKdfSalt=N.uint8ArrayToBase64(x),L.shareAKdfParams=N.DEFAULT_KDF_PARAMS}if(f==="passkey"&&j&&(L.prfSalt=j),await t(L),r==="none")d(),n({step:"complete",solanaPubkey:P});else{const T=r==="full_seed"?On(y):Fn(N.toShamirShare(S));n({step:"showing_recovery",recoveryPhrase:T,solanaPubkey:P})}},[t,r,d]),g=i.useCallback(async f=>{if(!s){n({step:"error",error:"User not authenticated"});return}c(!0),d();try{const p=N.generateArgon2Salt(),x=await le.argon2DeriveInWorker(f,p,N.DEFAULT_KDF_PARAMS);l.current.push(x),await u("password",x,p)}catch(p){n({step:"error",error:p instanceof Error?p.message:"Enrollment failed"})}finally{c(!1)}},[s,d,u]),m=i.useCallback(async()=>{if(!s){n({step:"error",error:"User not authenticated"});return}c(!0),d();try{const f=N.generatePrfSalt(),p=N.uint8ArrayToBase64(f);n({step:"registering_passkey"});let x;try{const y=new TextEncoder().encode(s.id),A=s.name??s.email??"User",v=s.email??s.id;x=(await N.registerPasskeyWithPrf(y,v,A,f)).prfOutput}catch(y){if(y?.name!=="InvalidStateError")throw y;x=(await N.authenticateWithDiscoverablePrf(p)).prfOutput}l.current.push(x);const j=await N.deriveKeyFromPrf(x,f);l.current.push(j),await u("passkey",j,void 0,p)}catch(f){n({step:"error",error:f instanceof Error?f.message:"Enrollment failed"})}finally{c(!1)}},[s,d,u]),h=i.useCallback(()=>{const f=a.solanaPubkey;d(),n({step:"complete",solanaPubkey:f})},[a.solanaPubkey,d]),b=i.useCallback(()=>{d(),n({step:"idle"}),c(!1)},[d]);return{state:a,startEnrollmentWithPassword:g,startEnrollmentWithPasskey:m,confirmRecoveryPhrase:h,cancel:b,isEnrolling:o}}function Sr({onComplete:s,onCancel:t,className:r="",forceAuthMethod:a}){const{user:n}=N.useCedrosLogin(),{state:o,startEnrollmentWithPassword:c,startEnrollmentWithPasskey:l,confirmRecoveryPhrase:d,cancel:u,isEnrolling:g}=Nr(),m=()=>a||"password",[h,b]=i.useState(m),[f,p]=i.useState(""),[x,j]=i.useState(""),[y,A]=i.useState(null);i.useEffect(()=>{b(m())},[n?.id,a]);const v=i.useCallback(async P=>{if(P.preventDefault(),f!==x){A("Passwords do not match");return}if(f.length<8){A("Password must be at least 8 characters");return}A(null),await c(f)},[f,x,c]),S=i.useCallback(async()=>{await l()},[l]),w=i.useCallback(()=>{d(),o.solanaPubkey&&s?.(o.solanaPubkey)},[d,o.solanaPubkey,s]),E=i.useCallback(()=>{u(),t?.()},[u,t]);return o.step==="generating_seed"||o.step==="splitting_shares"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,"aria-busy":"true",children:e.jsxs("div",{className:"cedros-enrollment-progress",role:"status","aria-live":"polite",children:[e.jsx("div",{className:"cedros-spinner","aria-hidden":"true"}),e.jsx("p",{children:"Generating secure wallet..."})]})}):o.step==="encrypting_shares"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,"aria-busy":"true",children:e.jsxs("div",{className:"cedros-enrollment-progress",role:"status","aria-live":"polite",children:[e.jsx("div",{className:"cedros-spinner","aria-hidden":"true"}),e.jsx("p",{children:"Encrypting wallet shares..."})]})}):o.step==="registering_passkey"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,"aria-busy":"true",children:e.jsx("div",{className:"cedros-enrollment-progress",role:"status","aria-live":"polite",children:e.jsxs("div",{className:"cedros-passkey-prompt",children:[e.jsxs("svg",{className:"cedros-passkey-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("rect",{x:"8",y:"16",width:"32",height:"24",rx:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("circle",{cx:"24",cy:"28",r:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M24 32v4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),e.jsx("h3",{children:"Authenticate with Passkey"}),e.jsx("p",{children:"Follow your browser's prompt to use your passkey."})]})})}):o.step==="uploading"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,"aria-busy":"true",children:e.jsxs("div",{className:"cedros-enrollment-progress",role:"status","aria-live":"polite",children:[e.jsx("div",{className:"cedros-spinner","aria-hidden":"true"}),e.jsx("p",{children:"Saving wallet..."})]})}):o.step==="showing_recovery"&&o.recoveryPhrase?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,children:e.jsx(jr,{words:o.recoveryPhrase,onConfirm:w})}):o.step==="complete"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,children:e.jsxs("div",{className:"cedros-enrollment-complete",children:[e.jsxs("svg",{className:"cedros-success-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M16 24l6 6 12-12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),e.jsx("h3",{children:"Wallet Created!"}),e.jsxs("p",{className:"cedros-pubkey",children:[e.jsx("strong",{children:"Address:"})," ",o.solanaPubkey]}),e.jsx("p",{children:"Your non-custodial Solana wallet is ready to use."})]})}):o.step==="error"?e.jsx("div",{className:`cedros-wallet-enrollment ${r}`,children:e.jsxs("div",{className:"cedros-enrollment-error",children:[e.jsxs("svg",{className:"cedros-error-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M24 16v12m0 6h.01",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),e.jsx("h3",{children:"Enrollment Failed"}),e.jsx("p",{className:"cedros-error-message",children:o.error}),e.jsxs("div",{className:"cedros-error-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,children:"Cancel"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:()=>u(),children:"Try Again"})]})]})}):e.jsxs("div",{className:`cedros-wallet-enrollment ${r}`,children:[e.jsxs("div",{className:"cedros-enrollment-header",children:[e.jsx("h2",{children:"Create Wallet"}),e.jsxs("p",{children:["Secure your wallet with a ",h==="passkey"?"passkey":"password","."]})]}),!a&&e.jsxs("div",{className:"cedros-auth-method-selector",children:[e.jsxs("label",{className:"cedros-radio-label",children:[e.jsx("input",{type:"radio",name:"authMethod",value:"password",checked:h==="password",onChange:()=>b("password"),disabled:g}),e.jsx("span",{children:"Password"})]}),e.jsxs("label",{className:"cedros-radio-label",children:[e.jsx("input",{type:"radio",name:"authMethod",value:"passkey",checked:h==="passkey",onChange:()=>b("passkey"),disabled:g}),e.jsx("span",{children:"Passkey"})]})]}),h==="password"&&e.jsxs("form",{onSubmit:v,className:"cedros-enrollment-form",children:[e.jsx(X.PasswordInput,{label:"Password",value:f,onChange:P=>p(P.target.value),showStrengthMeter:!0,disabled:g,required:!0,minLength:8,placeholder:"Enter a strong password"}),e.jsx(X.PasswordInput,{label:"Confirm Password",value:x,onChange:P=>j(P.target.value),error:y??void 0,disabled:g,required:!0,minLength:8,placeholder:"Confirm your password"}),e.jsx("div",{className:"cedros-password-info",children:e.jsx("p",{children:"This password will be used to sign transactions."})}),e.jsxs("div",{className:"cedros-enrollment-actions",children:[t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,disabled:g,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:g||!f||!x,children:g?"Creating...":"Continue"})]})]}),h==="passkey"&&e.jsxs("div",{className:"cedros-enrollment-form",children:[e.jsxs("div",{className:"cedros-passkey-info",children:[e.jsxs("svg",{className:"cedros-passkey-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("rect",{x:"8",y:"16",width:"32",height:"24",rx:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("circle",{cx:"24",cy:"28",r:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M24 32v4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),e.jsx("p",{children:"Use your passkey (Touch ID, Face ID, or Windows Hello) to secure your wallet."}),e.jsx("p",{children:"You'll use the same passkey to sign transactions."})]}),e.jsxs("div",{className:"cedros-enrollment-actions",children:[t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,disabled:g,children:"Cancel"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:S,disabled:g,children:g?"Creating...":"Use Passkey"})]})]})]})}function Cr(){const{user:s}=N.useCedrosLogin(),{signTransaction:t}=N.useWalletMaterial(),[r,a]=i.useState(!1),[n,o]=i.useState(null),c=i.useCallback(async(d,u)=>{if(!s){const g="User not authenticated";throw o(g),new Error(g)}a(!0),o(null);try{const g={transaction:N.uint8ArrayToBase64(d),...u?{credential:N.toCredentialRequest(u)}:{}},m=await t(g);return N.base64ToUint8Array(m.signature)}catch(g){const m=g instanceof Error?g.message:"Signing failed";throw o(m),g}finally{a(!1)}},[s,t]),l=i.useCallback(()=>o(null),[]);return{signTransaction:c,isSigning:r,error:n,clearError:l}}function _r(){const{getMaterial:s}=N.useWalletMaterial(),[t,r]=i.useState(!1),[a,n]=i.useState(null),o=i.useCallback(async()=>{r(!0),n(null);try{const l=await s();if(!l)throw new Error("No wallet enrolled");if(l.shareAAuthMethod!=="passkey")throw new Error("Wallet is not configured for passkey authentication");if(!l.prfSalt)throw new Error("No PRF salt configured for wallet");const d=await N.authenticateWithDiscoverablePrf(l.prfSalt);return{type:"prfOutput",prfOutput:N.uint8ArrayToBase64(d.prfOutput)}}catch(l){const d=l instanceof Error?l.message:"Passkey authentication failed";return n(d),null}finally{r(!1)}},[s]),c=i.useCallback(()=>n(null),[]);return{getPasskeyCredential:o,isAuthenticating:t,error:a,clearError:c}}function Er({mode:s,isLoading:t=!1,error:r,onPrompt:a,onRetry:n,onCancel:o,title:c,description:l,className:d=""}){const u=i.useCallback(()=>{t||a?.()},[t,a]),g=i.useCallback(()=>{n?.()},[n]),m=s==="register"?"Set Up Passkey":"Verify with Passkey",h=s==="register"?"Create a passkey to securely encrypt your wallet on this device. You will use your fingerprint, face, or device PIN.":"Use your passkey to unlock your wallet. You will be prompted for biometric verification.";return e.jsxs("div",{className:`cedros-passkey-prompt ${d}`,children:[e.jsx("div",{className:"cedros-passkey-icon",children:t?e.jsx(Pa,{}):r?e.jsx(La,{}):e.jsx(Ta,{})}),e.jsx("h3",{className:"cedros-passkey-title",children:c??m}),e.jsx("p",{className:"cedros-passkey-description",children:l??h}),r&&e.jsx("div",{className:"cedros-passkey-error",role:"alert",children:e.jsx("p",{children:r})}),e.jsx("div",{className:"cedros-passkey-actions",children:r?e.jsxs(e.Fragment,{children:[n&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:g,children:"Try Again"}),o&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:o,children:"Cancel"})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:u,disabled:t,children:t?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-button-spinner","aria-hidden":"true"}),"Waiting for passkey..."]}):s==="register"?"Create Passkey":"Use Passkey"}),o&&!t&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:o,children:"Cancel"})]})}),t&&e.jsxs("p",{className:"cedros-passkey-hint",children:["Follow the prompts on your device to ",s==="register"?"create":"verify"," your passkey."]})]})}function Ta(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4"}),e.jsx("path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88"}),e.jsx("path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02"}),e.jsx("path",{d:"M2 12a10 10 0 0 1 18-6"}),e.jsx("path",{d:"M2 16h.01"}),e.jsx("path",{d:"M21.8 16c.2-2 .131-5.354 0-6"}),e.jsx("path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2"}),e.jsx("path",{d:"M8.65 22c.21-.66.45-1.32.57-2"}),e.jsx("path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2"})]})}function Pa(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",className:"cedros-spinner",children:[e.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),e.jsx("path",{d:"M12 3a9 9 0 0 1 9 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}function La(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 8v4M12 16h.01"})]})}function Tr({onUnlock:s,onCancel:t,showCancel:r=!0,authMethod:a,className:n=""}){N.useCedrosLogin();const{unlock:o,getMaterial:c,isLoading:l}=N.useWalletMaterial(),{getPasskeyCredential:d,isAuthenticating:u}=_r(),[g,m]=i.useState("idle"),[h,b]=i.useState(a??null),[f,p]=i.useState(""),[x,j]=i.useState(null);i.useEffect(()=>{a!==void 0&&b(a)},[a]);const y=h==="password",A=h==="passkey",v=i.useCallback(async()=>{if(m("credential"),j(null),!h)try{const C=await c();C?b(C.shareAAuthMethod):(j("No wallet enrolled"),m("error"))}catch(C){j(C instanceof Error?C.message:"Failed to get wallet info"),m("error")}},[h,c]),S=i.useCallback(async C=>{C.preventDefault(),j(null),m("unlocking");try{let k;if(y)k={type:"password",password:f};else throw new Error("Invalid auth method");await o(k),m("unlocked"),s?.()}catch(k){j(k instanceof Error?k.message:"Failed to unlock wallet"),m("error")}},[y,f,o,s]),w=i.useCallback(async()=>{j(null),m("unlocking");try{const C=await d();if(!C){m("credential");return}await o(C),m("unlocked"),s?.()}catch(C){j(C instanceof Error?C.message:"Failed to unlock wallet"),m("error")}},[d,o,s]),E=i.useCallback(()=>{p(""),m("idle"),j(null),t?.()},[t]),P=i.useCallback(()=>{p(""),m("credential"),j(null)},[]),L=l||u,T=()=>{switch(g){case"idle":return e.jsxs("div",{className:"cedros-wallet-unlock-idle",children:[e.jsx("div",{className:"cedros-wallet-unlock-icon",children:e.jsx(Ma,{})}),e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Wallet Locked"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Unlock your wallet to sign transactions."}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:v,children:"Unlock Wallet"})]});case"credential":return y?e.jsxs("form",{className:"cedros-wallet-unlock-form",onSubmit:S,children:[e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Enter Password"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Enter your wallet password to unlock."}),e.jsx(X.PasswordInput,{label:"Password",value:f,onChange:C=>p(C.target.value),disabled:L,autoComplete:"current-password",error:x??void 0}),e.jsxs("div",{className:"cedros-wallet-unlock-actions",children:[e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:L||f.length===0,children:L?"Unlocking...":"Unlock"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,disabled:L,children:"Cancel"})]})]}):A?e.jsxs("div",{className:"cedros-wallet-unlock-passkey",children:[e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Verify with Passkey"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Use your passkey to unlock your wallet."}),e.jsx(Er,{mode:"authenticate",isLoading:L,error:x??void 0,onPrompt:w,onRetry:w,onCancel:r?E:void 0})]}):e.jsxs("div",{className:"cedros-wallet-unlock-loading",children:[e.jsx(N.LoadingSpinner,{size:"xl"}),e.jsx("p",{children:"Loading wallet info..."})]});case"unlocking":return e.jsxs("div",{className:"cedros-wallet-unlock-progress",children:[e.jsx("div",{className:"cedros-wallet-unlock-icon",children:e.jsx(N.LoadingSpinner,{size:"xl"})}),e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Unlocking Wallet"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Verifying your credentials..."})]});case"unlocked":return e.jsxs("div",{className:"cedros-wallet-unlock-success",children:[e.jsx("div",{className:"cedros-wallet-unlock-icon",children:e.jsx(Da,{})}),e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Wallet Unlocked"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:"Your wallet is ready to sign transactions."})]});case"error":return e.jsxs("div",{className:"cedros-wallet-unlock-error",children:[e.jsx("div",{className:"cedros-wallet-unlock-icon",children:e.jsx(Ra,{})}),e.jsx("h3",{className:"cedros-wallet-unlock-title",children:"Unlock Failed"}),e.jsx("p",{className:"cedros-wallet-unlock-description",children:x??"Failed to unlock wallet. Please try again."}),e.jsxs("div",{className:"cedros-wallet-unlock-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:P,children:"Try Again"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,children:"Cancel"})]})]})}};return e.jsx("div",{className:`cedros-wallet-unlock ${n}`,children:T()})}function Ma(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("rect",{x:"10",y:"22",width:"28",height:"20",rx:"4",stroke:"currentColor",strokeWidth:"2",fill:"var(--cedros-muted, #f3f4f6)"}),e.jsx("path",{d:"M16 22V16a8 8 0 1 1 16 0v6",stroke:"currentColor",strokeWidth:"2",fill:"none"}),e.jsx("circle",{cx:"24",cy:"32",r:"3",fill:"currentColor"})]})}function Da(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-success, #22c55e)",strokeWidth:"2",fill:"var(--cedros-success-light, #dcfce7)"}),e.jsx("path",{d:"M16 24l6 6 10-10",stroke:"var(--cedros-success, #22c55e)",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function Ra(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-destructive, #ef4444)",strokeWidth:"2",fill:"var(--cedros-destructive-light, #fee2e2)"}),e.jsx("path",{d:"M24 16v10M24 30v2",stroke:"var(--cedros-destructive, #ef4444)",strokeWidth:"3",strokeLinecap:"round"})]})}function Pr(){const{recover:s,getShareBForRecovery:t}=N.useWalletMaterial(),{recoveryMode:r}=kr(),[a,n]=i.useState({step:"idle"}),[o,c]=i.useState(!1),l=i.useRef([]),d=i.useCallback(()=>{N.wipeAll(...l.current),l.current=[]},[]);i.useEffect(()=>()=>{d()},[d]);const u=i.useCallback(async(m,h,b)=>{c(!0),d();try{if(n({step:"validating"}),!cr(m))throw new Error("Invalid recovery phrase. Please check your words.");let f;if(r==="share_c_only"){const P=Bn(m);l.current.push(P);const L=N.uint8ArrayToBase64(P),T=await t({shareC:L}),C=N.base64ToUint8Array(T.shareB);l.current.push(C),f=le.combineShares(N.toShamirShare(C),N.toShamirShare(P)),l.current.push(f)}else f=qn(m),l.current.push(f);const p=le.getPublicKeyFromSeed(f),x=le.publicKeyToBase58(p),{shareA:j,shareB:y}=le.splitSecret(f);l.current.push(j,y),n({step:"encrypting"});let A,v,S;if(h==="passkey"){const P=N.generatePrfSalt();S=N.uint8ArrayToBase64(P);const L=await N.authenticateWithDiscoverablePrf(S);l.current.push(L.prfOutput),A=await N.deriveKeyFromPrf(L.prfOutput,P),l.current.push(A)}else v=N.generateArgon2Salt(),A=await le.argon2DeriveInWorker(b,v,N.DEFAULT_KDF_PARAMS),l.current.push(A);const w=await N.aesGcmEncryptToBase64(j,N.toEncryptionKey(A));n({step:"uploading"});const E={solanaPubkey:x,shareAAuthMethod:h,shareACiphertext:w.ciphertext,shareANonce:w.nonce,shareB:N.uint8ArrayToBase64(y)};h==="password"&&(E.shareAKdfSalt=N.uint8ArrayToBase64(v),E.shareAKdfParams=N.DEFAULT_KDF_PARAMS),h==="passkey"&&(E.prfSalt=S),await s(E),d(),n({step:"complete"})}catch(f){d(),n({step:"error",error:f instanceof Error?f.message:"Recovery failed"})}finally{c(!1)}},[s,t,r,d]),g=i.useCallback(()=>{d(),n({step:"idle"}),c(!1)},[d]);return{state:a,startRecovery:u,cancel:g,isRecovering:o}}function Lr({onComplete:s,onCancel:t,className:r="",defaultAuthMethod:a="password"}){const{state:n,startRecovery:o,cancel:c,isRecovering:l}=Pr(),[d,u]=i.useState([]),[g,m]=i.useState(!1),[h,b]=i.useState(a),[f,p]=i.useState(""),[x,j]=i.useState(""),[y,A]=i.useState(null),v=i.useCallback(L=>{u(L),m(!0)},[]),S=i.useCallback(async L=>{if(L.preventDefault(),A(null),h!=="passkey"){if(f!==x){A("Passwords do not match");return}if(h==="password"&&f.length<8){A("Password must be at least 8 characters");return}}await o(d,h,f)},[d,h,f,x,o]),w=i.useCallback(()=>{c(),u([]),m(!1),p(""),j(""),t?.()},[c,t]),E=i.useCallback(()=>{m(!1),p(""),j("")},[]),P=i.useCallback(()=>{s?.()},[s]);return n.step==="validating"||n.step==="encrypting"||n.step==="uploading"?e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("div",{className:"cedros-wallet-recovery-progress",children:[e.jsx("div",{className:"cedros-wallet-recovery-icon",children:e.jsx(Ia,{})}),e.jsxs("h3",{className:"cedros-wallet-recovery-title",children:[n.step==="validating"&&"Validating Recovery Phrase",n.step==="encrypting"&&"Encrypting Wallet",n.step==="uploading"&&"Saving to Server"]}),e.jsxs("p",{className:"cedros-wallet-recovery-description",children:[n.step==="validating"&&"Checking your recovery phrase...",n.step==="encrypting"&&"Securing your wallet with new encryption...",n.step==="uploading"&&"Uploading encrypted wallet data..."]})]})}):n.step==="complete"?e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("div",{className:"cedros-wallet-recovery-success",children:[e.jsx("div",{className:"cedros-wallet-recovery-icon",children:e.jsx(Ua,{})}),e.jsx("h3",{className:"cedros-wallet-recovery-title",children:"Wallet Recovered"}),e.jsxs("p",{className:"cedros-wallet-recovery-description",children:["Your wallet has been successfully recovered and secured with your new"," ",h==="passkey"?"passkey":"password","."]}),e.jsx("div",{className:"cedros-wallet-recovery-actions",children:e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:P,children:"Done"})})]})}):n.step==="error"?e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("div",{className:"cedros-wallet-recovery-error",children:[e.jsx("div",{className:"cedros-wallet-recovery-icon",children:e.jsx(Fa,{})}),e.jsx("h3",{className:"cedros-wallet-recovery-title",children:"Recovery Failed"}),e.jsx("p",{className:"cedros-wallet-recovery-description",children:n.error??"An error occurred during recovery. Please try again."}),e.jsx("div",{className:"cedros-wallet-recovery-actions",children:e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:w,children:"Start Over"})})]})}):g?e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("form",{className:"cedros-wallet-recovery-credential",onSubmit:S,children:[e.jsxs("div",{className:"cedros-wallet-recovery-header",children:[e.jsx("h3",{className:"cedros-wallet-recovery-title",children:"Set New Security"}),e.jsx("p",{className:"cedros-wallet-recovery-description",children:"Choose how to secure your recovered wallet."})]}),e.jsxs("div",{className:"cedros-auth-method-selector",children:[e.jsxs("label",{className:"cedros-radio-label",children:[e.jsx("input",{type:"radio",name:"authMethod",value:"password",checked:h==="password",onChange:()=>b("password"),disabled:l}),e.jsx("span",{children:"Password"})]}),e.jsxs("label",{className:"cedros-radio-label",children:[e.jsx("input",{type:"radio",name:"authMethod",value:"passkey",checked:h==="passkey",onChange:()=>b("passkey"),disabled:l}),e.jsx("span",{children:"Passkey"})]})]}),h==="password"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-password-input",children:[e.jsx("label",{htmlFor:"recovery-password",className:"cedros-label",children:"New Password"}),e.jsx("input",{id:"recovery-password",type:"password",className:"cedros-input",value:f,onChange:L=>p(L.target.value),disabled:l,minLength:8,placeholder:"Enter a strong password"})]}),e.jsxs("div",{className:"cedros-password-input",children:[e.jsx("label",{htmlFor:"recovery-password-confirm",className:"cedros-label",children:"Confirm Password"}),e.jsx("input",{id:"recovery-password-confirm",type:"password",className:"cedros-input",value:x,onChange:L=>j(L.target.value),disabled:l,"aria-invalid":y?"true":void 0,placeholder:"Confirm your password"}),y&&e.jsx("p",{className:"cedros-input-error",role:"alert",children:y})]})]}),h==="passkey"&&e.jsxs("div",{className:"cedros-passkey-info",children:[e.jsx(Ba,{}),e.jsx("p",{children:"Use your passkey (Touch ID, Face ID, or Windows Hello) to secure your wallet."})]}),e.jsxs("div",{className:"cedros-wallet-recovery-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:E,disabled:l,children:"Back"}),e.jsx("button",{type:"submit",className:"cedros-button cedros-button-primary",disabled:l||h!=="passkey"&&(f.length===0||x.length===0),children:l?"Recovering...":"Recover Wallet"})]})]})}):e.jsx("div",{className:`cedros-wallet-recovery ${r}`,children:e.jsxs("div",{className:"cedros-wallet-recovery-phrase",children:[e.jsxs("div",{className:"cedros-wallet-recovery-header",children:[e.jsx("h3",{className:"cedros-wallet-recovery-title",children:"Recover Your Wallet"}),e.jsx("p",{className:"cedros-wallet-recovery-description",children:"Enter your 12-word recovery phrase to restore your wallet."})]}),e.jsx(Ar,{onSubmit:v,onCancel:w,isSubmitting:!1})]})})}function Ia(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",className:"cedros-spinner",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-muted, #e5e7eb)",strokeWidth:"3",fill:"none"}),e.jsx("path",{d:"M24 4a20 20 0 0 1 20 20",stroke:"var(--cedros-primary, #6366f1)",strokeWidth:"3",strokeLinecap:"round",fill:"none"})]})}function Ua(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-success, #22c55e)",strokeWidth:"2",fill:"var(--cedros-success-light, #dcfce7)"}),e.jsx("path",{d:"M16 24l6 6 10-10",stroke:"var(--cedros-success, #22c55e)",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function Fa(){return e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"var(--cedros-destructive, #ef4444)",strokeWidth:"2",fill:"var(--cedros-destructive-light, #fee2e2)"}),e.jsx("path",{d:"M24 16v10M24 30v2",stroke:"var(--cedros-destructive, #ef4444)",strokeWidth:"3",strokeLinecap:"round"})]})}function Ba(){return e.jsxs("svg",{className:"cedros-passkey-icon",width:"48",height:"48",viewBox:"0 0 48 48",fill:"none","aria-hidden":"true",children:[e.jsx("rect",{x:"8",y:"16",width:"32",height:"24",rx:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("circle",{cx:"24",cy:"28",r:"4",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M24 32v4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}function Mr({address:s,label:t="Wallet Address",showCopy:r=!0,showExplorerLink:a=!0,allowReveal:n=!0,className:o=""}){const c=N.useCedrosLoginOptional(),[l,d]=i.useState(!1),[u,g]=i.useState(null),[m,h]=i.useState(!1),b=i.useRef(null),f=c?.config.solana?.network??"mainnet-beta",p=i.useMemo(()=>{const A=`https://explorer.solana.com/address/${s}`;return f==="mainnet-beta"?A:`${A}?cluster=${encodeURIComponent(f)}`},[s,f]),x=n&&s.length>18,j=i.useMemo(()=>!x||m?s:`${s.slice(0,8)}...${s.slice(-8)}`,[s,x,m]),y=i.useCallback(async()=>{try{g(null),await navigator.clipboard.writeText(s),d(!0),b.current!==null&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{d(!1),b.current=null},2e3)}catch(A){d(!1),g(A instanceof Error?A.message:"Copy failed")}},[s]);return i.useEffect(()=>()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)},[]),e.jsxs("div",{className:`cedros-wallet-address-row ${o}`,children:[e.jsxs("div",{className:"cedros-wallet-address-row-header",children:[e.jsx("span",{className:"cedros-wallet-status-pubkey-label",children:t}),e.jsxs("div",{className:"cedros-wallet-address-row-actions",children:[x&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-sm cedros-button-ghost",onClick:()=>h(A=>!A),"aria-label":m?"Hide full wallet address":"Show full wallet address",children:m?e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[e.jsx("path",{d:"M3 3l18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M10.7 10.7a3 3 0 0 0 4.24 4.24",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M9.88 5.09A10.94 10.94 0 0 1 12 5c5 0 9.27 3.11 11 7-0.55 1.23-1.32 2.33-2.27 3.25",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M6.61 6.61C4.4 7.9 2.74 9.8 1 12c1.73 3.89 6 7 11 7 1.14 0 2.25-0.16 3.3-0.46",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}):e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[e.jsx("path",{d:"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})}),a&&e.jsx("a",{className:"cedros-button cedros-button-sm cedros-button-ghost",href:p,target:"_blank",rel:"noreferrer",children:"Explorer"}),r&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-sm cedros-button-outline",onClick:y,"aria-label":"Copy wallet address",children:l?"Copied":"Copy"})]})]}),e.jsx("code",{className:"cedros-wallet-status-pubkey-value",title:s,children:j}),u&&e.jsx("p",{className:"cedros-input-hint",role:"status",children:u})]})}function Dr({status:s,publicKey:t,onLock:r,onEnroll:a,onUnlock:n,onRecover:o,showActions:c=!0,compact:l=!1,className:d=""}){const u=s!==void 0,g=N.useWallet(),m=u?s:g.status,h=u?t??null:g.solanaPubkey,b=u?null:g.error,f=u?()=>{}:g.refresh,p=u?()=>{}:g.clearError,x=Oa(m,b);return l?e.jsxs("div",{className:`cedros-wallet-status cedros-wallet-status-compact ${d}`,children:[e.jsx("span",{className:`cedros-wallet-status-dot cedros-wallet-status-${x.color}`,title:x.label}),e.jsx("span",{className:"cedros-wallet-status-label",children:x.label}),h&&e.jsx("span",{className:"cedros-wallet-status-pubkey",title:h,children:qa(h)})]}):e.jsxs("div",{className:`cedros-wallet-status ${d}`,children:[e.jsxs("div",{className:"cedros-wallet-status-header",children:[e.jsx("div",{className:`cedros-wallet-status-icon cedros-wallet-status-icon-${x.color}`,children:e.jsx(Wa,{status:m})}),e.jsxs("div",{className:"cedros-wallet-status-info",children:[e.jsx("h4",{className:"cedros-wallet-status-title",children:x.title}),e.jsx("p",{className:"cedros-wallet-status-description",children:x.description})]})]}),h&&e.jsx("div",{className:"cedros-wallet-status-pubkey-full",children:e.jsx(Mr,{address:h})}),b&&e.jsxs("div",{className:"cedros-wallet-status-error-box",role:"alert",children:[e.jsx("p",{children:b}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-sm cedros-button-secondary",onClick:p,children:"Dismiss"})]}),c&&e.jsxs("div",{className:"cedros-wallet-status-actions",children:[m==="not_enrolled"&&a&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary cedros-button-sm",onClick:a,children:"Create Wallet"}),m==="enrolled_locked"&&n&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary cedros-button-sm",onClick:n,children:"Unlock Wallet"}),(m==="not_enrolled"||m==="error")&&o&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:o,children:"Recover Wallet"}),m==="error"&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:f,children:"Retry"})]})]})}function Oa(s,t){switch(s){case"loading":return{label:"Loading",title:"Checking Wallet",description:"Verifying wallet status...",color:"loading"};case"not_enrolled":return{label:"Not Set Up",title:"No Wallet",description:"Create a wallet to start using Solana.",color:"muted"};case"enrolled_locked":return{label:"Locked",title:"Wallet Locked",description:"Unlock your wallet to sign transactions.",color:"warning"};case"enrolled_unlocked":case"unlocked":return{label:"Ready",title:"Wallet Ready",description:"Your wallet is unlocked and ready to use.",color:"success"};case"error":default:return{label:"Error",title:"Wallet Error",description:t??"An error occurred with your wallet.",color:"error"}}}function qa(s){return s.length<=12?s:`${s.slice(0,4)}...${s.slice(-4)}`}function Wa({status:s}){switch(s){case"loading":return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",className:"cedros-spinner",children:[e.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),e.jsx("path",{d:"M12 3a9 9 0 0 1 9 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]});case"not_enrolled":return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M8 12h8M12 8v8"})]});case"enrolled_locked":return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),e.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]});case"enrolled_unlocked":case"unlocked":return e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"M20 6L9 17l-5-5"})});case"error":return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),e.jsx("path",{d:"M12 9v4M12 17h.01"})]});default:return null}}function $a({className:s="",showActions:t=!0}){const r=N.useWallet(),[a,n]=i.useState("status"),o=i.useMemo(()=>{switch(a){case"enroll":return{title:"Create Wallet",description:"Set up your embedded wallet."};case"unlock":return{title:"Unlock Wallet",description:"Unlock to sign transactions."};case"recover_intro":case"recover":return{title:"Recover Wallet",description:"Restore access using your recovery phrase."};case"status":default:return null}},[a]),c=i.useCallback(()=>n("status"),[]),l=i.useCallback(async()=>{n("status"),await r.refresh()},[r]),d=i.useCallback(async()=>{n("status"),await r.refresh()},[r]),u=i.useCallback(async()=>{n("status"),await r.refresh()},[r]);return e.jsxs("div",{className:`cedros-wallet-manager ${s}`,children:[a!=="status"&&o&&e.jsxs("div",{className:"cedros-wallet-manager-header",children:[e.jsxs("div",{className:"cedros-wallet-manager-header-text",children:[e.jsx("h3",{className:"cedros-wallet-manager-title",children:o.title}),e.jsx("p",{className:"cedros-wallet-manager-subtitle",children:o.description})]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-sm cedros-button-ghost",onClick:c,children:"Back"})]}),a==="status"&&e.jsx(Dr,{onEnroll:()=>n("enroll"),onUnlock:()=>n("unlock"),onRecover:()=>n("recover_intro"),showActions:t}),a==="enroll"&&e.jsx(Sr,{onComplete:()=>{l()},onCancel:c}),a==="unlock"&&e.jsx(Tr,{onUnlock:()=>{d()},onCancel:c}),a==="recover_intro"&&e.jsx("div",{className:"cedros-wallet-manager-intro",children:e.jsxs("div",{className:"cedros-wallet-manager-intro-card",children:[e.jsx("h4",{className:"cedros-wallet-manager-intro-title",children:"Before you start"}),e.jsxs("ul",{className:"cedros-wallet-manager-intro-list",children:[e.jsx("li",{children:"You’ll need your 12-word recovery phrase."}),e.jsx("li",{children:"You’ll set a new password or passkey for this wallet."}),e.jsx("li",{children:"If you’re on a shared device, avoid copying the phrase into other apps."})]}),e.jsxs("div",{className:"cedros-wallet-manager-intro-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:()=>n("recover"),children:"Start recovery"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:c,children:"Cancel"})]})]})}),a==="recover"&&e.jsx(Lr,{onComplete:()=>{u()},onCancel:c})]})}class za{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async getSettings(){try{return await this.client.get("/admin/settings")}catch(t){throw N.handleApiError(t,"Failed to fetch system settings")}}async updateSettings(t){try{return await this.client.patch("/admin/settings",{settings:t})}catch(r){throw N.handleApiError(r,"Failed to update system settings")}}}function Re(){const{config:s,authState:t,_internal:r}=N.useCedrosLogin(),[a,n]=i.useState({}),[o,c]=i.useState(!1),[l,d]=i.useState(!1),[u,g]=i.useState(null),m=i.useRef(0),h=i.useMemo(()=>new za(s.serverUrl,s.requestTimeout,s.retryAttempts,r?.getAccessToken),[s.serverUrl,s.requestTimeout,s.retryAttempts,r]),b=i.useRef(h);b.current=h;const f=i.useCallback(async()=>{if(t!=="authenticated"){n({});return}c(!0),g(null);const j=++m.current;try{const y=await b.current.getSettings();if(j!==m.current)return;n(y.settings)}catch(y){if(j!==m.current)return;g(y instanceof Error?y:new Error("Failed to fetch settings"))}finally{j===m.current&&c(!1)}},[t]),p=i.useCallback(async j=>{if(t!=="authenticated")throw new Error("Not authenticated");d(!0),g(null);try{await b.current.updateSettings(j),await f()}catch(y){const A=y instanceof Error?y:new Error("Failed to update settings");throw g(A),A}finally{d(!1)}},[t,f]),x=i.useCallback(j=>{for(const y of Object.values(a)){const A=y.find(v=>v.key===j);if(A)return A.value}},[a]);return{settings:a,isLoading:o,isUpdating:l,error:u,fetchSettings:f,updateSettings:p,getValue:x}}function Va(s){const t=Math.floor(s/86400),r=Math.floor(s%86400/3600),a=Math.floor(s%3600/60),n=s%60;return{days:t,hours:r,minutes:a,seconds:n}}function Ha(s){const{days:t,hours:r,minutes:a}=Va(s),n=[];return t>0&&n.push(`${t}d`),r>0&&n.push(`${r}h`),a>0&&n.push(`${a}m`),n.length===0&&n.push(`${s}s`),n.join(" ")}const Qa={auth_email_enabled:{key:"auth_email_enabled",label:"Enable Email Authentication",description:"Allow users to sign up and log in with email/password.",inputType:"boolean"},auth_email_require_verification:{key:"auth_email_require_verification",label:"Require Email Verification",description:"Users must verify their email address before they can log in.",inputType:"boolean"},auth_email_block_disposable:{key:"auth_email_block_disposable",label:"Block Disposable Emails",description:"Reject registrations from known disposable email providers.",inputType:"boolean"},auth_google_enabled:{key:"auth_google_enabled",label:"Enable Google Sign-In",description:"Allow users to authenticate with their Google account.",inputType:"boolean"},auth_google_client_id:{key:"auth_google_client_id",label:"Google Client ID",description:"OAuth 2.0 client ID from Google Cloud Console.",inputType:"text"},auth_google_client_secret:{key:"auth_google_client_secret",label:"Google Client Secret",description:"OAuth 2.0 client secret from Google Cloud Console.",inputType:"secret"},auth_apple_enabled:{key:"auth_apple_enabled",label:"Enable Sign in with Apple",description:"Allow users to authenticate with their Apple ID.",inputType:"boolean"},auth_apple_client_id:{key:"auth_apple_client_id",label:"Apple Services ID",description:"The Services ID configured in your Apple Developer account.",inputType:"text"},auth_apple_team_id:{key:"auth_apple_team_id",label:"Apple Team ID",description:"Your Apple Developer Team ID.",inputType:"text"},auth_apple_key_id:{key:"auth_apple_key_id",label:"Apple Key ID",description:"The Key ID for your Sign in with Apple private key.",inputType:"text"},auth_apple_private_key:{key:"auth_apple_private_key",label:"Apple Private Key",description:"The private key file contents (PEM format) for Sign in with Apple.",inputType:"secret",multiline:!0},auth_solana_enabled:{key:"auth_solana_enabled",label:"Enable Solana Wallet Auth",description:"Allow users to authenticate by signing with their Solana wallet.",inputType:"boolean"},auth_solana_challenge_expiry:{key:"auth_solana_challenge_expiry",label:"Challenge Expiry",description:"How long a wallet signature challenge is valid.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"10 minutes",value:"600"}]},auth_webauthn_enabled:{key:"auth_webauthn_enabled",label:"Enable WebAuthn/Passkeys",description:"Allow passwordless authentication with FIDO2/WebAuthn credentials.",inputType:"boolean"},auth_webauthn_rp_id:{key:"auth_webauthn_rp_id",label:"Relying Party ID",description:"Usually your domain (e.g., example.com). Passkeys are bound to this.",inputType:"text"},auth_webauthn_rp_name:{key:"auth_webauthn_rp_name",label:"Relying Party Name",description:"Display name shown to users during passkey registration.",inputType:"text"},auth_webauthn_rp_origin:{key:"auth_webauthn_rp_origin",label:"Allowed Origins",description:"Comma-separated origins allowed for WebAuthn (e.g., https://example.com).",inputType:"text"},feature_privacy_cash:{key:"feature_privacy_cash",label:"Privacy Cash",description:"Enable Privacy Cash deposits and timed withdrawals.",inputType:"boolean"},feature_wallet_signing:{key:"feature_wallet_signing",label:"Embedded Wallet Signing",description:"Enable the embedded wallet for transaction signing.",inputType:"boolean"},feature_sso:{key:"feature_sso",label:"Enterprise SSO",description:"Enable SAML/OIDC single sign-on for enterprise customers.",inputType:"boolean"},feature_organizations:{key:"feature_organizations",label:"Organizations",description:"Enable multi-user organizations with role-based access.",inputType:"boolean"},feature_mfa:{key:"feature_mfa",label:"Two-Factor Authentication",description:"Allow users to enable TOTP-based two-factor authentication.",inputType:"boolean"},feature_instant_link:{key:"feature_instant_link",label:"Instant Link Login",description:"Allow passwordless login via magic link sent to email.",inputType:"boolean"},security_cors_origins:{key:"security_cors_origins",label:"CORS Origins",description:"Allowed origins for cross-origin requests (comma-separated). Empty = same origin only.",inputType:"text"},security_cookie_domain:{key:"security_cookie_domain",label:"Cookie Domain",description:"Domain for auth cookies. Empty uses the request origin.",inputType:"text"},security_cookie_secure:{key:"security_cookie_secure",label:"Secure Cookies",description:"Require HTTPS for cookies. Disable only for local development.",inputType:"boolean"},security_cookie_same_site:{key:"security_cookie_same_site",label:"Cookie SameSite",description:'SameSite policy for cookies. Use "none" only if needed for cross-site embeds.',inputType:"select",presets:[{label:"Strict",value:"strict"},{label:"Lax (Recommended)",value:"lax"},{label:"None (cross-site)",value:"none"}]},security_session_timeout:{key:"security_session_timeout",label:"Session Timeout",description:"How long sessions remain valid before requiring re-authentication.",inputType:"duration",min:300,presets:[{label:"1 hour",value:"3600"},{label:"24 hours",value:"86400"},{label:"7 days",value:"604800"},{label:"30 days",value:"2592000"}]},security_jwt_issuer:{key:"security_jwt_issuer",label:"JWT Issuer",description:"Issuer claim for JWTs. Empty uses the server URL.",inputType:"text"},security_jwt_audience:{key:"security_jwt_audience",label:"JWT Audience",description:"Audience claim for JWTs. Empty uses default.",inputType:"text"},email_smtp_host:{key:"email_smtp_host",label:"SMTP Host",description:"SMTP server hostname (e.g., smtp.sendgrid.net).",inputType:"text"},email_smtp_port:{key:"email_smtp_port",label:"SMTP Port",description:"SMTP server port. Common: 587 (TLS), 465 (SSL), 25 (unencrypted).",inputType:"select",presets:[{label:"587 (TLS)",value:"587"},{label:"465 (SSL)",value:"465"},{label:"25 (Plain)",value:"25"}]},email_smtp_user:{key:"email_smtp_user",label:"SMTP Username",description:"Username for SMTP authentication.",inputType:"text"},email_smtp_password:{key:"email_smtp_password",label:"SMTP Password",description:"Password or API key for SMTP authentication.",inputType:"secret"},email_smtp_tls:{key:"email_smtp_tls",label:"Use TLS",description:"Enable TLS encryption for SMTP connections.",inputType:"boolean"},email_from_address:{key:"email_from_address",label:"From Address",description:"Default sender email address (e.g., noreply@example.com).",inputType:"text"},email_from_name:{key:"email_from_name",label:"From Name",description:'Default sender display name (e.g., "My App").',inputType:"text"},webhook_enabled:{key:"webhook_enabled",label:"Enable Webhooks",description:"Send HTTP notifications for auth events (signup, login, etc.).",inputType:"boolean"},webhook_url:{key:"webhook_url",label:"Webhook URL",description:"Endpoint to receive webhook POST requests.",inputType:"text"},webhook_secret:{key:"webhook_secret",label:"Webhook Secret",description:"Secret used to sign webhook payloads (HMAC-SHA256).",inputType:"secret"},webhook_timeout:{key:"webhook_timeout",label:"Timeout",description:"Maximum time to wait for webhook response.",inputType:"duration",min:5,presets:[{label:"10 seconds",value:"10"},{label:"30 seconds",value:"30"},{label:"60 seconds",value:"60"}]},webhook_retries:{key:"webhook_retries",label:"Max Retries",description:"Number of retry attempts for failed webhooks.",inputType:"select",presets:[{label:"0 (No retries)",value:"0"},{label:"3 (Recommended)",value:"3"},{label:"5",value:"5"}]},server_frontend_url:{key:"server_frontend_url",label:"Frontend URL",description:"URL of your frontend app (for redirects and email links).",inputType:"text"},server_base_path:{key:"server_base_path",label:"Base Path",description:"Base path for auth endpoints (e.g., /auth).",inputType:"text"},server_trust_proxy:{key:"server_trust_proxy",label:"Trust Proxy",description:"Trust X-Forwarded-For headers. Enable if behind a reverse proxy.",inputType:"boolean"},privacy_period_secs:{key:"privacy_period_secs",label:"Privacy Period",description:"How long deposits are held before withdrawal to provide timing privacy. Longer periods provide better privacy but delay user access to funds.",inputType:"duration",min:0,presets:[{label:"Disabled",value:"0"},{label:"1 hour",value:"3600"},{label:"6 hours",value:"21600"},{label:"24 hours",value:"86400"},{label:"7 days",value:"604800"},{label:"14 days",value:"1209600"},{label:"30 days",value:"2592000"}],warningThreshold:{below:3600,message:"Very short privacy periods may not provide adequate timing protection."}},withdrawal_poll_interval_secs:{key:"withdrawal_poll_interval_secs",label:"Worker Poll Interval",description:"How often the withdrawal worker checks for deposits ready to process. Lower values process faster but increase server load.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"},{label:"1 hour",value:"3600"},{label:"6 hours",value:"21600"}],warningThreshold:{below:60,message:"Polling more than once per minute may cause excessive load."}},withdrawal_batch_size:{key:"withdrawal_batch_size",label:"Batch Size",description:"Maximum number of withdrawals to process in a single batch. Higher values improve throughput but may cause timeouts.",inputType:"select",min:1,max:100,presets:[{label:"1 (Sequential)",value:"1"},{label:"5",value:"5"},{label:"10 (Recommended)",value:"10"},{label:"25",value:"25"},{label:"50",value:"50"},{label:"100 (Max)",value:"100"}]},withdrawal_timeout_secs:{key:"withdrawal_timeout_secs",label:"Transaction Timeout",description:"How long to wait for a withdrawal transaction to confirm before considering it failed.",inputType:"duration",min:30,presets:[{label:"30 seconds",value:"30"},{label:"1 minute",value:"60"},{label:"2 minutes",value:"120"},{label:"5 minutes",value:"300"}],warningThreshold:{below:30,message:"Very short timeouts may cause premature failure on slow networks."}},withdrawal_max_retries:{key:"withdrawal_max_retries",label:"Max Retries",description:"Number of times to retry a failed withdrawal before marking it as permanently failed.",inputType:"select",min:0,max:10,presets:[{label:"0 (No retries)",value:"0"},{label:"1",value:"1"},{label:"3 (Recommended)",value:"3"},{label:"5",value:"5"},{label:"10",value:"10"}]},withdrawal_percentage:{key:"withdrawal_percentage",label:"Withdrawal Percentage",description:"Percentage of ready funds to withdraw each cycle. Lower values spread withdrawals over time for better privacy.",inputType:"percentage",min:1,max:100,step:5,presets:[{label:"25%",value:"25"},{label:"50%",value:"50"},{label:"75%",value:"75"},{label:"100% (All at once)",value:"100"}],warningThreshold:{above:75,message:"High percentages may reduce timing privacy by processing most withdrawals together."}},partial_withdrawal_count:{key:"partial_withdrawal_count",label:"Partial Withdrawals",description:"Maximum partial withdrawals per batch. Partial withdrawals add noise to timing analysis. Set to 0 to disable.",inputType:"select",min:0,presets:[{label:"Disabled",value:"0"},{label:"1",value:"1"},{label:"3",value:"3"},{label:"5",value:"5"},{label:"10",value:"10"}]},partial_withdrawal_min_lamports:{key:"partial_withdrawal_min_lamports",label:"Min Balance for Partial",description:"Minimum account balance (in lamports) required before partial withdrawals are considered. 1 SOL = 1,000,000,000 lamports.",inputType:"select",min:0,presets:[{label:"0.1 SOL",value:"100000000"},{label:"0.5 SOL",value:"500000000"},{label:"1 SOL",value:"1000000000"},{label:"5 SOL",value:"5000000000"},{label:"10 SOL",value:"10000000000"}]},rate_limit_auth:{key:"rate_limit_auth",label:"Auth Request Limit",description:"Maximum authentication attempts (login, register, password reset) per IP per window. Protects against brute force attacks.",inputType:"select",min:1,unit:"requests",presets:[{label:"5 (Strict)",value:"5"},{label:"10 (Recommended)",value:"10"},{label:"20",value:"20"},{label:"50 (Permissive)",value:"50"}],warningThreshold:{above:20,message:"High auth limits may allow brute force attempts."}},rate_limit_general:{key:"rate_limit_general",label:"General Request Limit",description:"Maximum general API requests per IP per window. Affects all non-auth endpoints.",inputType:"select",min:1,unit:"requests",presets:[{label:"30",value:"30"},{label:"60 (Recommended)",value:"60"},{label:"120",value:"120"},{label:"300",value:"300"}]},rate_limit_credit:{key:"rate_limit_credit",label:"Credit Request Limit",description:"Maximum credit/balance check requests per IP per window. Higher for apps that poll balance frequently.",inputType:"select",min:1,unit:"requests",presets:[{label:"10",value:"10"},{label:"30 (Recommended)",value:"30"},{label:"60",value:"60"},{label:"120",value:"120"}]},rate_limit_window:{key:"rate_limit_window",label:"Rate Limit Window",description:'Time window for rate limiting. All limits above are "per window". Shorter windows are stricter.',inputType:"duration",min:1,presets:[{label:"30 seconds",value:"30"},{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"}]},deposit_quick_action_tokens:{key:"deposit_quick_action_tokens",label:"Quick Action Tokens",description:"Comma-separated token symbols shown as quick action buttons. First token is the default.",inputType:"tokenSymbolList"},deposit_custom_tokens:{key:"deposit_custom_tokens",label:"Custom Dropdown Tokens",description:'Comma-separated token symbols shown in the "Custom" dropdown. Leave empty to show all.',inputType:"tokenSymbolList"},deposit_custom_tokens_json:{key:"deposit_custom_tokens_json",label:"Custom Token Definitions",description:"Add tokens beyond the built-in list. Define symbol, mint address, decimals, and logo URL.",inputType:"tokenList"}},Ka={"auth.apple":{label:"Apple Sign-In",description:"Configure Sign in with Apple OAuth integration.",icon:""},"auth.email":{label:"Email Authentication",description:"Configure email/password authentication settings.",icon:""},"auth.google":{label:"Google Sign-In",description:"Configure Google OAuth integration.",icon:""},"auth.solana":{label:"Solana Wallet Auth",description:"Configure Solana wallet signature authentication.",icon:""},"auth.webauthn":{label:"WebAuthn / Passkeys",description:"Configure FIDO2/WebAuthn passwordless authentication.",icon:""},deposit:{label:"Deposit Settings",description:"Configure token lists and deposit flow display options.",icon:""},email:{label:"Email / SMTP",description:"Configure outbound email delivery for verification, password reset, and notifications.",icon:""},features:{label:"Feature Flags",description:"Enable or disable major platform features.",icon:""},privacy:{label:"Privacy Settings",description:"Control the privacy period for deposits. Longer periods provide better timing privacy but delay fund availability.",icon:""},rate_limit:{label:"Rate Limiting",description:"Protect the system from abuse by limiting request rates. Balance security with user experience.",icon:""},security:{label:"Security",description:"Configure CORS, cookies, sessions, and JWT settings.",icon:""},server:{label:"Server",description:"Server infrastructure settings. Some may be overridden by environment variables.",icon:""},webhook:{label:"Webhooks",description:"Configure HTTP webhook notifications for auth events.",icon:""},withdrawal:{label:"Withdrawal Worker",description:"Configure how the automated withdrawal processor handles pending withdrawals. These settings affect throughput and privacy.",icon:""}};function Ga({showDescriptions:s=!0,className:t="",onSave:r}){const{settings:a,isLoading:n,isUpdating:o,error:c,fetchSettings:l,updateSettings:d}=Re(),[u,g]=i.useState({}),[m,h]=i.useState(null),[b,f]=i.useState(!1);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{if(b){const S=setTimeout(()=>f(!1),3e3);return()=>clearTimeout(S)}},[b]);const p=i.useCallback((S,w)=>{g(E=>({...E,[S]:w})),h(null),f(!1)},[]),x=i.useCallback(async()=>{const S=Object.entries(u).map(([w,E])=>({key:w,value:E}));if(S.length!==0)try{await d(S),g({}),h(null),f(!0),r?.()}catch(w){h(w instanceof Error?w.message:"Failed to save settings")}},[u,d,r]),j=i.useCallback(()=>{g({}),h(null),f(!1)},[]),y=Object.keys(u).length>0,A=Object.keys(u).length;if(n&&Object.keys(a).length===0)return e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${t}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]});if(c)return e.jsx("div",{className:`cedros-system-settings ${t}`,children:e.jsx(N.ErrorMessage,{error:c.message})});const v=Object.keys(a).sort();return v.length===0?e.jsx("div",{className:`cedros-system-settings cedros-system-settings-empty ${t}`,children:e.jsx("p",{children:"No system settings found."})}):e.jsxs("div",{className:`cedros-system-settings ${t}`,children:[m&&e.jsx(N.ErrorMessage,{error:m}),b&&e.jsx("div",{className:"cedros-settings-success",children:"Settings saved successfully."}),v.map(S=>e.jsx(Ya,{category:S,settings:a[S],edits:u,showDescription:s,onChange:p},S)),e.jsxs("div",{className:"cedros-system-settings-actions",children:[y&&e.jsxs("span",{className:"cedros-settings-change-count",children:[A," unsaved change",A!==1?"s":""]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-secondary",onClick:j,disabled:!y||o,children:"Reset"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary",onClick:x,disabled:!y||o,children:o?e.jsx(N.LoadingSpinner,{size:"sm"}):"Save Changes"})]})]})}function Ya({category:s,settings:t,edits:r,showDescription:a,onChange:n}){const o=Ka[s]||{label:s,description:"",icon:"⚙️"};return e.jsxs("section",{className:"cedros-settings-section",children:[e.jsxs("div",{className:"cedros-settings-section-header",children:[e.jsx("span",{className:"cedros-settings-section-icon",children:o.icon}),e.jsxs("div",{children:[e.jsx("h3",{className:"cedros-settings-section-title",children:o.label}),a&&o.description&&e.jsx("p",{className:"cedros-settings-section-description",children:o.description})]})]}),e.jsx("div",{className:"cedros-settings-grid",children:t.map(c=>e.jsx(Ja,{setting:c,editValue:r[c.key],onChange:n},c.key))})]})}function Ja({setting:s,editValue:t,onChange:r}){const a=Qa[s.key],n=t??s.value,o=t!==void 0&&t!==s.value,c=i.useMemo(()=>{if(!a?.warningThreshold)return null;const l=parseInt(n,10);if(isNaN(l))return null;const{above:d,below:u,message:g}=a.warningThreshold;return d!==void 0&&l>d||u!==void 0&&l<u?g:null},[n,a?.warningThreshold]);return a?e.jsxs("div",{className:`cedros-setting-row ${o?"cedros-setting-row-changed":""} ${c?"cedros-setting-row-warning":""}`,children:[e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:a.label}),e.jsx("span",{className:"cedros-setting-description",children:a.description})]}),e.jsxs("div",{className:"cedros-setting-control",children:[a.inputType==="duration"&&e.jsx(Xa,{value:n,onChange:l=>r(s.key,l),presets:a.presets,min:a.min}),a.inputType==="percentage"&&e.jsx(Za,{value:n,onChange:l=>r(s.key,l),min:a.min??1,max:a.max??100,step:a.step??5,presets:a.presets}),a.inputType==="select"&&e.jsx(eo,{value:n,onChange:l=>r(s.key,l),presets:a.presets??[],unit:a.unit}),a.inputType==="number"&&e.jsx(so,{value:n,onChange:l=>r(s.key,l),min:a.min,max:a.max,unit:a.unit}),a.inputType==="tokenList"&&e.jsx(no,{value:n,onChange:l=>r(s.key,l)}),a.inputType==="text"&&e.jsx("input",{type:"text",value:n,onChange:l=>r(s.key,l.target.value),className:"cedros-setting-input",placeholder:a.label}),a.inputType==="boolean"&&e.jsx(to,{value:n,onChange:l=>r(s.key,l)}),a.inputType==="secret"&&e.jsx(ro,{value:n,onChange:l=>r(s.key,l),multiline:a.multiline}),a.inputType==="tokenSymbolList"&&e.jsx(ao,{value:n,onChange:l=>r(s.key,l)}),c&&e.jsx("div",{className:"cedros-setting-warning",children:c})]})]}):e.jsxs("div",{className:`cedros-setting-row ${o?"cedros-setting-row-changed":""}`,children:[e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:s.key}),s.description&&e.jsx("span",{className:"cedros-setting-description",children:s.description})]}),e.jsx("div",{className:"cedros-setting-input-wrapper",children:e.jsx("input",{type:"text",value:n,onChange:l=>r(s.key,l.target.value),className:"cedros-setting-input"})})]})}function Xa({value:s,onChange:t,presets:r,min:a=0}){const n=parseInt(s,10)||0,o=Ha(n),c=i.useCallback(d=>{d.target.value&&t(d.target.value)},[t]),l=i.useCallback(d=>{const u=Math.max(a,parseInt(d.target.value,10)||0);t(String(u))},[t,a]);return e.jsxs("div",{className:"cedros-duration-input",children:[r&&r.length>0&&e.jsxs("select",{value:r.find(d=>d.value===s)?.value??"",onChange:c,className:"cedros-setting-select",children:[e.jsx("option",{value:"",children:"Custom..."}),r.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))]}),e.jsxs("div",{className:"cedros-duration-custom",children:[e.jsx("input",{type:"number",value:n,onChange:l,min:a,className:"cedros-setting-input cedros-setting-input-sm"}),e.jsx("span",{className:"cedros-setting-unit",children:"seconds"}),e.jsxs("span",{className:"cedros-duration-display",children:["= ",o]})]})]})}function Za({value:s,onChange:t,min:r,max:a,step:n,presets:o}){const c=parseInt(s,10)||r,l=i.useCallback(u=>{t(u.target.value)},[t]),d=i.useCallback(u=>{t(u)},[t]);return e.jsxs("div",{className:"cedros-percentage-input",children:[e.jsxs("div",{className:"cedros-percentage-slider-row",children:[e.jsx("input",{type:"range",value:c,onChange:l,min:r,max:a,step:n,className:"cedros-percentage-slider"}),e.jsxs("span",{className:"cedros-percentage-value",children:[c,"%"]})]}),o&&o.length>0&&e.jsx("div",{className:"cedros-preset-buttons",children:o.map(u=>e.jsx("button",{type:"button",className:`cedros-preset-button ${u.value===s?"cedros-preset-button-active":""}`,onClick:()=>d(u.value),children:u.label},u.value))})]})}function eo({value:s,onChange:t,presets:r,unit:a}){const n=!r.some(l=>l.value===s),o=i.useCallback(l=>{l.target.value!=="__custom__"&&t(l.target.value)},[t]),c=i.useCallback(l=>{t(l.target.value)},[t]);return e.jsxs("div",{className:"cedros-select-input",children:[e.jsxs("select",{value:n?"__custom__":s,onChange:o,className:"cedros-setting-select",children:[r.map(l=>e.jsx("option",{value:l.value,children:l.label},l.value)),e.jsx("option",{value:"__custom__",children:"Custom..."})]}),n&&e.jsxs("div",{className:"cedros-select-custom",children:[e.jsx("input",{type:"number",value:s,onChange:c,className:"cedros-setting-input cedros-setting-input-sm"}),a&&e.jsx("span",{className:"cedros-setting-unit",children:a})]})]})}function so({value:s,onChange:t,min:r,max:a,unit:n}){const o=i.useCallback(c=>{t(c.target.value)},[t]);return e.jsxs("div",{className:"cedros-number-input",children:[e.jsx("input",{type:"number",value:s,onChange:o,min:r,max:a,className:"cedros-setting-input"}),n&&e.jsx("span",{className:"cedros-setting-unit",children:n})]})}function to({value:s,onChange:t}){const r=s==="true",a=i.useCallback(()=>{t(r?"false":"true")},[r,t]);return e.jsxs("button",{type:"button",role:"switch","aria-checked":r,className:`cedros-toggle ${r?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:a,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:r?"Enabled":"Disabled"})]})}function ro({value:s,onChange:t,multiline:r}){const[a,n]=i.useState(!1),[o,c]=i.useState(!1),l=s&&s.length>0,d=i.useCallback(()=>{n(!0),c(!0)},[]),u=i.useCallback(()=>{n(!1),c(!1)},[]),g=i.useCallback(m=>{t(m.target.value)},[t]);return!a&&l?e.jsxs("div",{className:"cedros-secret-input cedros-secret-input-masked",children:[e.jsx("span",{className:"cedros-secret-masked",children:"•".repeat(Math.min(s.length,20))}),e.jsx("button",{type:"button",className:"cedros-secret-edit-btn",onClick:d,children:"Edit"})]}):e.jsxs("div",{className:"cedros-secret-input",children:[r?e.jsx("textarea",{value:s,onChange:g,className:"cedros-setting-input cedros-setting-textarea",placeholder:"Enter secret value...",rows:4}):e.jsx("input",{type:o?"text":"password",value:s,onChange:g,className:"cedros-setting-input",placeholder:"Enter secret value..."}),e.jsxs("div",{className:"cedros-secret-actions",children:[!r&&e.jsx("button",{type:"button",className:"cedros-secret-toggle-btn",onClick:()=>c(!o),children:o?"Hide":"Show"}),a&&e.jsx("button",{type:"button",className:"cedros-secret-done-btn",onClick:u,children:"Done"})]})]})}const Rr=["SOL","USDC","USDT","EURC","USD1","PYUSD","USDH","CASH","BONK","ORE"];function no({value:s,onChange:t}){const r=i.useMemo(()=>{try{return JSON.parse(s||"[]")}catch{return[]}},[s]),a=i.useCallback(l=>{t(JSON.stringify(l))},[t]),n=i.useCallback(()=>{a([...r,{symbol:"",mint:"",decimals:6}])},[r,a]),o=i.useCallback((l,d,u)=>{const g=[...r];g[l]={...g[l],[d]:u},a(g)},[r,a]),c=i.useCallback(l=>{a(r.filter((d,u)=>u!==l))},[r,a]);return e.jsxs("div",{className:"cedros-token-list-input",children:[e.jsxs("div",{className:"cedros-token-presets",children:[e.jsx("span",{className:"cedros-token-presets-label",children:"Built-in tokens:"}),e.jsx("div",{className:"cedros-token-presets-list",children:Rr.map(l=>e.jsx("span",{className:"cedros-token-preset-chip",children:l},l))})]}),r.length===0&&e.jsx("p",{className:"cedros-token-list-empty",children:"No custom tokens added. Use the built-in tokens above or add your own."}),r.map((l,d)=>e.jsxs("div",{className:"cedros-token-row",children:[e.jsxs("div",{className:"cedros-token-row-fields",children:[e.jsx("input",{type:"text",placeholder:"Symbol",value:l.symbol,onChange:u=>o(d,"symbol",u.target.value.toUpperCase()),className:"cedros-setting-input cedros-token-input-symbol",maxLength:10}),e.jsx("input",{type:"text",placeholder:"Mint address",value:l.mint,onChange:u=>o(d,"mint",u.target.value),className:"cedros-setting-input cedros-token-input-mint"}),e.jsx("input",{type:"number",placeholder:"Decimals",value:l.decimals,onChange:u=>o(d,"decimals",parseInt(u.target.value,10)||0),className:"cedros-setting-input cedros-token-input-decimals",min:0,max:18}),e.jsx("input",{type:"text",placeholder:"Logo URL (optional)",value:l.logoUrl||"",onChange:u=>o(d,"logoUrl",u.target.value||void 0),className:"cedros-setting-input cedros-token-input-logo"})]}),e.jsx("button",{type:"button",className:"cedros-token-remove-btn",onClick:()=>c(d),title:"Remove token",children:"×"})]},d)),e.jsx("button",{type:"button",className:"cedros-token-add-btn",onClick:n,children:"+ Add Token"})]})}function ao({value:s,onChange:t}){const r=i.useMemo(()=>s.split(",").map(o=>o.trim()).filter(Boolean),[s]),a=i.useCallback(o=>{if(!o||r.includes(o))return;const c=[...r,o].join(", ");t(c)},[r,t]),n=i.useCallback(o=>{const c=r.filter(l=>l!==o).join(", ");t(c)},[r,t]);return e.jsxs("div",{className:"cedros-token-symbol-list-input",children:[e.jsxs("div",{className:"cedros-token-presets",children:[e.jsx("span",{className:"cedros-token-presets-label",children:"Click to add:"}),e.jsx("div",{className:"cedros-token-presets-list",children:Rr.map(o=>{const c=r.includes(o);return e.jsxs("button",{type:"button",className:`cedros-token-preset-chip ${c?"cedros-token-preset-chip-selected":""}`,onClick:()=>c?n(o):a(o),title:c?`Remove ${o}`:`Add ${o}`,children:[o,c&&e.jsx("span",{className:"cedros-token-chip-check",children:"✓"})]},o)})})]}),e.jsx("input",{type:"text",value:s,onChange:o=>t(o.target.value),className:"cedros-setting-input",placeholder:"USDC, SOL, BONK..."})]})}class oo{client;constructor(t,r,a){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a})}async getStatus(){try{return await this.client.get("/setup/status")}catch(t){throw N.handleApiError(t,"Failed to check setup status")}}async createFirstAdmin(t){try{return await this.client.post("/setup/admin",t)}catch(r){throw N.handleApiError(r,"Failed to create admin account")}}}function Ks(){const{config:s}=N.useCedrosLogin(),[t,r]=i.useState(null),[a,n]=i.useState(!1),[o,c]=i.useState(!1),[l,d]=i.useState(null),u=i.useRef(0),g=i.useMemo(()=>new oo(s.serverUrl,s.requestTimeout,s.retryAttempts),[s.serverUrl,s.requestTimeout,s.retryAttempts]),m=i.useRef(g);m.current=g;const h=i.useCallback(async()=>{n(!0),d(null);const f=++u.current;try{const p=await m.current.getStatus();if(f!==u.current)return;r(p)}catch(p){if(f!==u.current)return;d(p instanceof Error?p:new Error("Failed to check setup status"))}finally{f===u.current&&n(!1)}},[]),b=i.useCallback(async f=>{c(!0),d(null);try{const p=await m.current.createFirstAdmin(f);return await h(),p}catch(p){const x=p instanceof Error?p:new Error("Failed to create admin");throw d(x),x}finally{c(!1)}},[h]);return{status:t,isLoading:a,isCreating:o,error:l,checkStatus:h,createAdmin:b}}const io=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,ht=8;function lo(s){const t={};return s.email?io.test(s.email)||(t.email="Invalid email format"):t.email="Email is required",s.password?s.password.length<ht&&(t.password=`Password must be at least ${ht} characters`):t.password="Password is required",s.confirmPassword?s.password!==s.confirmPassword&&(t.confirmPassword="Passwords do not match"):t.confirmPassword="Please confirm your password",t}function Ir({onComplete:s,className:t=""}){const{status:r,isLoading:a,isCreating:n,error:o,checkStatus:c,createAdmin:l}=Ks(),[d,u]=i.useState({email:"",password:"",confirmPassword:"",name:"",orgName:""}),[g,m]=i.useState({}),[h,b]=i.useState(!1);i.useEffect(()=>{c()},[c]);const f=i.useCallback(x=>j=>{u(y=>({...y,[x]:j.target.value})),m(y=>({...y,[x]:void 0}))},[]),p=i.useCallback(async x=>{x.preventDefault();const j=lo(d);if(Object.keys(j).length>0){m(j);return}try{await l({email:d.email,password:d.password,name:d.name||void 0,orgName:d.orgName||void 0}),b(!0),s?.()}catch{}},[d,l,s]);return a?e.jsx("div",{className:`cedros-setup ${t}`,children:e.jsxs("div",{className:"cedros-setup__loading",children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{className:"cedros-setup__loading-text",children:"Checking setup status..."})]})}):r&&!r.needsSetup?e.jsx("div",{className:`cedros-setup ${t}`,children:e.jsxs("div",{className:"cedros-setup__complete",children:[e.jsx("div",{className:"cedros-setup__icon cedros-setup__icon--success",children:e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),e.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}),e.jsx("h2",{className:"cedros-setup__title",children:"Setup Complete"}),e.jsx("p",{className:"cedros-setup__text",children:"An admin account already exists. You can now log in."})]})}):h?e.jsx("div",{className:`cedros-setup ${t}`,children:e.jsxs("div",{className:"cedros-setup__complete",children:[e.jsx("div",{className:"cedros-setup__icon cedros-setup__icon--success",children:e.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),e.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}),e.jsx("h2",{className:"cedros-setup__title",children:"Admin Account Created"}),e.jsx("p",{className:"cedros-setup__text",children:"Your admin account has been created successfully. You can now log in with your credentials."})]})}):e.jsx("div",{className:`cedros-setup ${t}`,children:e.jsxs("div",{className:"cedros-setup__container",children:[e.jsxs("div",{className:"cedros-setup__header",children:[e.jsx("div",{className:"cedros-setup__logo",children:e.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),e.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]})}),e.jsx("h1",{className:"cedros-setup__title",children:"Welcome to Cedros"}),e.jsx("p",{className:"cedros-setup__subtitle",children:"Let's set up your admin account to get started."})]}),e.jsxs("form",{className:"cedros-setup__form",onSubmit:p,children:[o&&e.jsx(N.ErrorMessage,{error:o.message}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsxs("label",{htmlFor:"setup-email",className:"cedros-setup__label",children:["Email Address ",e.jsx("span",{className:"cedros-setup__required",children:"*"})]}),e.jsx("input",{id:"setup-email",type:"email",className:`cedros-setup__input ${g.email?"cedros-setup__input--error":""}`,value:d.email,onChange:f("email"),placeholder:"admin@example.com",autoComplete:"email",autoFocus:!0,disabled:n}),g.email&&e.jsx("span",{className:"cedros-setup__error",children:g.email})]}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsx("label",{htmlFor:"setup-name",className:"cedros-setup__label",children:"Display Name"}),e.jsx("input",{id:"setup-name",type:"text",className:"cedros-setup__input",value:d.name,onChange:f("name"),placeholder:"Admin",autoComplete:"name",disabled:n})]}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsx("label",{htmlFor:"setup-org-name",className:"cedros-setup__label",children:"Organization Name"}),e.jsx("input",{id:"setup-org-name",type:"text",className:"cedros-setup__input",value:d.orgName,onChange:f("orgName"),placeholder:"My Organization",disabled:n})]}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsxs("label",{htmlFor:"setup-password",className:"cedros-setup__label",children:["Password ",e.jsx("span",{className:"cedros-setup__required",children:"*"})]}),e.jsx("input",{id:"setup-password",type:"password",className:`cedros-setup__input ${g.password?"cedros-setup__input--error":""}`,value:d.password,onChange:f("password"),placeholder:"At least 8 characters",autoComplete:"new-password",disabled:n}),g.password&&e.jsx("span",{className:"cedros-setup__error",children:g.password})]}),e.jsxs("div",{className:"cedros-setup__field",children:[e.jsxs("label",{htmlFor:"setup-confirm-password",className:"cedros-setup__label",children:["Confirm Password ",e.jsx("span",{className:"cedros-setup__required",children:"*"})]}),e.jsx("input",{id:"setup-confirm-password",type:"password",className:`cedros-setup__input ${g.confirmPassword?"cedros-setup__input--error":""}`,value:d.confirmPassword,onChange:f("confirmPassword"),placeholder:"Confirm your password",autoComplete:"new-password",disabled:n}),g.confirmPassword&&e.jsx("span",{className:"cedros-setup__error",children:g.confirmPassword})]}),e.jsx("button",{type:"submit",className:"cedros-setup__button",disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Creating Account..."})]}):"Create Admin Account"})]}),e.jsxs("div",{className:"cedros-setup__footer",children:[e.jsx("p",{className:"cedros-setup__note",children:"This will be the first administrator account for your installation."}),r?.serverVersion&&e.jsxs("p",{className:"cedros-setup__version",children:["Server version: ",r.serverVersion]})]})]})})}const co=800,uo=2e3;function Ee(){const{settings:s,isLoading:t,error:r,fetchSettings:a,updateSettings:n}=Re(),[o,c]=i.useState({}),[l,d]=i.useState("idle"),[u,g]=i.useState(null),m=i.useRef(null),h=i.useRef(null),b=i.useRef({});i.useEffect(()=>()=>{m.current&&clearTimeout(m.current),h.current&&clearTimeout(h.current)},[]);const f=i.useCallback(async()=>{const j={...b.current};if(Object.keys(j).length===0){d("idle");return}d("saving"),g(null);const y=Object.entries(j).map(([A,v])=>({key:A,value:v}));try{await n(y),c(A=>{const v={...A};for(const S of Object.keys(j))delete v[S];return v});for(const A of Object.keys(j))delete b.current[A];d("saved"),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{d("idle")},uo)}catch(A){d("error"),g(A instanceof Error?A.message:"Failed to save")}},[n]),p=i.useCallback((j,y)=>{c(A=>({...A,[j]:y})),b.current[j]=y,g(null),d("pending"),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{f()},co)},[f]),x=i.useCallback(j=>{if(o[j]!==void 0)return o[j];for(const y of Object.values(s)){const A=y.find(v=>v.key===j);if(A)return A.value}return""},[o,s]);return{settings:s,edits:o,isLoading:t,autosaveStatus:l,autosaveError:u,error:r,fetchSettings:a,handleChange:p,getEffectiveValue:x}}function ho(s){const t=Math.floor(s/86400),r=Math.floor(s%86400/3600),a=Math.floor(s%3600/60),n=s%60;return{days:t,hours:r,minutes:a,seconds:n}}function mo(s){const{days:t,hours:r,minutes:a}=ho(s),n=[];return t>0&&n.push(`${t}d`),r>0&&n.push(`${r}h`),a>0&&n.push(`${a}m`),n.length===0&&n.push(`${s}s`),n.join(" ")}const po={auth_email_enabled:{key:"auth_email_enabled",label:"Enable Email Authentication",description:"Allow users to sign up and log in with email/password.",inputType:"boolean"},auth_email_require_verification:{key:"auth_email_require_verification",label:"Require Email Verification",description:"Users must verify their email address before they can log in.",inputType:"boolean"},auth_email_block_disposable:{key:"auth_email_block_disposable",label:"Block Disposable Emails",description:"Reject registrations from known disposable email providers.",inputType:"boolean"},auth_google_enabled:{key:"auth_google_enabled",label:"Enable Google Sign-In",description:"Allow users to authenticate with their Google account.",inputType:"boolean"},auth_google_client_id:{key:"auth_google_client_id",label:"Google Client ID",description:"OAuth 2.0 client ID from Google Cloud Console.",inputType:"text"},auth_google_client_secret:{key:"auth_google_client_secret",label:"Google Client Secret",description:"OAuth 2.0 client secret from Google Cloud Console.",inputType:"secret"},auth_apple_enabled:{key:"auth_apple_enabled",label:"Enable Sign in with Apple",description:"Allow users to authenticate with their Apple ID.",inputType:"boolean"},auth_apple_client_id:{key:"auth_apple_client_id",label:"Apple Services ID",description:"The Services ID configured in your Apple Developer account.",inputType:"text"},auth_apple_team_id:{key:"auth_apple_team_id",label:"Apple Team ID",description:"Your Apple Developer Team ID.",inputType:"text"},auth_apple_key_id:{key:"auth_apple_key_id",label:"Apple Key ID",description:"The Key ID for your Sign in with Apple private key.",inputType:"text"},auth_apple_private_key:{key:"auth_apple_private_key",label:"Apple Private Key",description:"The private key file contents (PEM format) for Sign in with Apple.",inputType:"secret",multiline:!0},auth_solana_enabled:{key:"auth_solana_enabled",label:"Enable Solana Wallet Auth",description:"Allow users to authenticate by signing with their Solana wallet.",inputType:"boolean"},auth_solana_challenge_expiry:{key:"auth_solana_challenge_expiry",label:"Challenge Expiry",description:"How long a wallet signature challenge is valid.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"10 minutes",value:"600"}]},auth_webauthn_enabled:{key:"auth_webauthn_enabled",label:"Enable WebAuthn/Passkeys",description:"Allow passwordless authentication with FIDO2/WebAuthn credentials.",inputType:"boolean"},auth_webauthn_rp_id:{key:"auth_webauthn_rp_id",label:"Relying Party ID",description:"Usually your domain (e.g., example.com). Passkeys are bound to this.",inputType:"text"},auth_webauthn_rp_name:{key:"auth_webauthn_rp_name",label:"Relying Party Name",description:"Display name shown to users during passkey registration.",inputType:"text"},auth_webauthn_rp_origin:{key:"auth_webauthn_rp_origin",label:"Allowed Origins",description:"Comma-separated origins allowed for WebAuthn (e.g., https://example.com).",inputType:"text"},auth_instantlink_enabled:{key:"auth_instantlink_enabled",label:"Enable Instant Link",description:"Allow passwordless login via magic link sent to email.",inputType:"boolean"},auth_instantlink_expiry:{key:"auth_instantlink_expiry",label:"Link Expiry",description:"How long the magic link remains valid.",inputType:"duration",min:60,presets:[{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"},{label:"30 minutes",value:"1800"},{label:"1 hour",value:"3600"}]},auth_instantlink_rate_limit:{key:"auth_instantlink_rate_limit",label:"Rate Limit",description:"Maximum instant link requests per email per hour.",inputType:"select",presets:[{label:"3 per hour",value:"3"},{label:"5 per hour",value:"5"},{label:"10 per hour",value:"10"}]},feature_organizations:{key:"feature_organizations",label:"Organizations",description:"Enable multi-user organizations with role-based access.",inputType:"boolean"},feature_sso:{key:"feature_sso",label:"Enterprise SSO",description:"Enable SAML/OIDC single sign-on for enterprise customers.",inputType:"boolean"},feature_mfa:{key:"feature_mfa",label:"Two-Factor Authentication",description:"Allow users to enable TOTP-based two-factor authentication.",inputType:"boolean"},feature_wallet_signing:{key:"feature_wallet_signing",label:"Enable Embedded Wallet",description:"Enable the embedded wallet for transaction signing.",inputType:"boolean"},wallet_recovery_mode:{key:"wallet_recovery_mode",label:"Recovery Mode",description:"How users can recover their wallet if they lose access.",inputType:"select",presets:[{label:"Share C Only (Recommended)",value:"share_c_only"},{label:"Full Seed Phrase",value:"full_seed"},{label:"No Recovery",value:"none"}]},feature_credits:{key:"feature_credits",label:"Credit System",description:"Enable the deposits and credits system. Users can deposit tokens to receive platform credits.",inputType:"boolean"},security_cors_origins:{key:"security_cors_origins",label:"CORS Origins",description:"Allowed origins for cross-origin requests (comma-separated). Empty = same origin only.",inputType:"text"},security_cookie_domain:{key:"security_cookie_domain",label:"Cookie Domain",description:"Domain for auth cookies. Empty uses the request origin.",inputType:"text"},security_cookie_secure:{key:"security_cookie_secure",label:"Secure Cookies",description:"Require HTTPS for cookies. Disable only for local development.",inputType:"boolean"},security_cookie_same_site:{key:"security_cookie_same_site",label:"Cookie SameSite",description:'SameSite policy for cookies. Use "none" only if needed for cross-site embeds.',inputType:"select",presets:[{label:"Strict",value:"strict"},{label:"Lax (Recommended)",value:"lax"},{label:"None (cross-site)",value:"none"}]},security_session_timeout:{key:"security_session_timeout",label:"Session Timeout",description:"How long sessions remain valid before requiring re-authentication.",inputType:"duration",min:300,presets:[{label:"1 hour",value:"3600"},{label:"24 hours",value:"86400"},{label:"7 days",value:"604800"},{label:"30 days",value:"2592000"}]},security_jwt_issuer:{key:"security_jwt_issuer",label:"JWT Issuer",description:"Issuer claim for JWTs. Empty uses the server URL.",inputType:"text"},security_jwt_audience:{key:"security_jwt_audience",label:"JWT Audience",description:"Audience claim for JWTs. Empty uses default.",inputType:"text"},email_provider:{key:"email_provider",label:"Email Provider",description:"Select your email service provider for automatic configuration.",inputType:"select",presets:[{label:"Mailgun",value:"mailgun"},{label:"SendGrid",value:"sendgrid"},{label:"Postmark",value:"postmark"},{label:"AWS SES",value:"ses"},{label:"Resend",value:"resend"},{label:"Custom SMTP",value:"custom"}]},email_smtp_host:{key:"email_smtp_host",label:"SMTP Host",description:"SMTP server hostname (e.g., smtp.sendgrid.net).",inputType:"text"},email_smtp_port:{key:"email_smtp_port",label:"SMTP Port",description:"SMTP server port. Common: 587 (TLS), 465 (SSL), 25 (unencrypted).",inputType:"select",presets:[{label:"587 (TLS)",value:"587"},{label:"465 (SSL)",value:"465"},{label:"25 (Plain)",value:"25"}]},email_smtp_user:{key:"email_smtp_user",label:"SMTP Username",description:"Username for SMTP authentication.",inputType:"text"},email_smtp_password:{key:"email_smtp_password",label:"API Key",description:"API key or password for your email provider.",inputType:"secret"},email_smtp_tls:{key:"email_smtp_tls",label:"Use TLS",description:"Enable TLS encryption for SMTP connections.",inputType:"boolean"},email_from_address:{key:"email_from_address",label:"From Address",description:"Default sender email address (e.g., noreply@example.com).",inputType:"text"},email_from_name:{key:"email_from_name",label:"From Name",description:'Default sender display name (e.g., "My App").',inputType:"text"},webhook_enabled:{key:"webhook_enabled",label:"Enable Webhooks",description:"Send notifications to a Discord or Slack webhook URL.",inputType:"boolean"},webhook_url:{key:"webhook_url",label:"Webhook URL",description:"Discord or Slack webhook URL to receive notifications.",inputType:"text",placeholder:"https://discord.com/api/webhooks/..."},webhook_notify_registrations:{key:"webhook_notify_registrations",label:"New Registrations",description:"Notify when a new user registers.",inputType:"boolean"},webhook_notify_signins:{key:"webhook_notify_signins",label:"Sign-Ins",description:"Notify when a user signs in.",inputType:"boolean"},webhook_notify_deposits:{key:"webhook_notify_deposits",label:"Deposits",description:"Notify when a user makes a deposit.",inputType:"boolean"},server_frontend_url:{key:"server_frontend_url",label:"Frontend URL",description:"URL of your frontend app (for redirects and email links).",inputType:"text"},server_base_path:{key:"server_base_path",label:"Base Path",description:"Base path for auth endpoints (e.g., /auth).",inputType:"text"},server_trust_proxy:{key:"server_trust_proxy",label:"Trust Proxy",description:"Trust X-Forwarded-For headers. Enable if behind a reverse proxy.",inputType:"boolean"},server_cedros_pay_api_key:{key:"server_cedros_pay_api_key",label:"Cedros Pay API Key",description:"API key for Cedros Pay to authenticate with this server. Copy this into your Cedros Pay settings.",inputType:"secret"},jupiter_api_key:{key:"jupiter_api_key",label:"Jupiter API Key",description:'API key for Jupiter Ultra API (gasless swaps). Get a free key at <a href="https://portal.jup.ag" target="_blank" rel="noopener">portal.jup.ag</a>.',inputType:"secret"},server_metrics_api_key:{key:"server_metrics_api_key",label:"Metrics API Key",description:"API key for Prometheus/Grafana to scrape the /metrics endpoint. Use with Authorization: Bearer header.",inputType:"secret"},server_log_level:{key:"server_log_level",label:"Log Level",description:"Minimum severity level for log output. Lower levels are more verbose.",inputType:"select",presets:[{label:"Trace (most verbose)",value:"trace"},{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error (least verbose)",value:"error"}]},server_log_format:{key:"server_log_format",label:"Log Format",description:"Output format for log messages.",inputType:"select",presets:[{label:"JSON (structured)",value:"json"},{label:"Pretty (human-readable)",value:"pretty"}]},server_environment:{key:"server_environment",label:"Environment",description:"Deployment environment. Affects default behaviors and log verbosity.",inputType:"select",presets:[{label:"Development",value:"development"},{label:"Staging",value:"staging"},{label:"Production",value:"production"}]},privacy_period_secs:{key:"privacy_period_secs",label:"Privacy Period",description:"How long deposits are held before withdrawal to provide timing privacy. Longer periods provide better privacy but delay user access to funds.",inputType:"duration",min:0,presets:[{label:"Disabled",value:"0"},{label:"1 hour",value:"3600"},{label:"6 hours",value:"21600"},{label:"24 hours",value:"86400"},{label:"7 days",value:"604800"},{label:"14 days",value:"1209600"},{label:"30 days",value:"2592000"}],warningThreshold:{below:3600,message:"Very short privacy periods may not provide adequate timing protection."}},treasury_wallet_address:{key:"treasury_wallet_address",label:"Treasury Wallet Address",description:"Solana wallet address where funds are sent. Used for privacy cash withdrawals, micro payment batches, and direct payments.",inputType:"text",placeholder:"e.g., 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"},withdrawal_poll_interval_secs:{key:"withdrawal_poll_interval_secs",label:"Worker Poll Interval",description:"How often the withdrawal worker checks for deposits ready to process. Lower values process faster but increase server load.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"},{label:"1 hour",value:"3600"},{label:"6 hours",value:"21600"}],warningThreshold:{below:60,message:"Polling more than once per minute may cause excessive load."}},withdrawal_batch_size:{key:"withdrawal_batch_size",label:"Batch Size",description:"Maximum number of withdrawals to process in a single batch. Higher values improve throughput but may cause timeouts.",inputType:"select",min:1,max:100,presets:[{label:"1 (Sequential)",value:"1"},{label:"5",value:"5"},{label:"10 (Recommended)",value:"10"},{label:"25",value:"25"},{label:"50",value:"50"},{label:"100 (Max)",value:"100"}]},withdrawal_timeout_secs:{key:"withdrawal_timeout_secs",label:"Transaction Timeout",description:"How long to wait for a withdrawal transaction to confirm before considering it failed.",inputType:"duration",min:30,presets:[{label:"30 seconds",value:"30"},{label:"1 minute",value:"60"},{label:"2 minutes",value:"120"},{label:"5 minutes",value:"300"}],warningThreshold:{below:30,message:"Very short timeouts may cause premature failure on slow networks."}},withdrawal_max_retries:{key:"withdrawal_max_retries",label:"Max Retries",description:"Number of times to retry a failed withdrawal before marking it as permanently failed.",inputType:"select",min:0,max:10,presets:[{label:"0 (No retries)",value:"0"},{label:"1",value:"1"},{label:"3 (Recommended)",value:"3"},{label:"5",value:"5"},{label:"10",value:"10"}]},withdrawal_percentage:{key:"withdrawal_percentage",label:"Withdrawal Percentage",description:"Percentage of ready funds to withdraw each cycle. Lower values spread withdrawals over time for better privacy.",inputType:"percentage",min:1,max:100,step:5,presets:[{label:"25%",value:"25"},{label:"50%",value:"50"},{label:"75%",value:"75"},{label:"100% (All at once)",value:"100"}],warningThreshold:{above:75,message:"High percentages may reduce timing privacy by processing most withdrawals together."}},partial_withdrawal_count:{key:"partial_withdrawal_count",label:"Partial Withdrawals",description:"Maximum partial withdrawals per batch. Partial withdrawals add noise to timing analysis. Set to 0 to disable.",inputType:"select",min:0,presets:[{label:"Disabled",value:"0"},{label:"1",value:"1"},{label:"3",value:"3"},{label:"5",value:"5"},{label:"10",value:"10"}]},partial_withdrawal_min_lamports:{key:"partial_withdrawal_min_lamports",label:"Min Balance for Partial",description:"Minimum account balance (in lamports) required before partial withdrawals are considered. 1 SOL = 1,000,000,000 lamports.",inputType:"select",min:0,presets:[{label:"0.1 SOL",value:"100000000"},{label:"0.5 SOL",value:"500000000"},{label:"1 SOL",value:"1000000000"},{label:"5 SOL",value:"5000000000"},{label:"10 SOL",value:"10000000000"}]},rate_limit_auth:{key:"rate_limit_auth",label:"Auth Request Limit",description:"Maximum authentication attempts (login, register, password reset) per IP per window. Protects against brute force attacks.",inputType:"select",min:1,unit:"requests",presets:[{label:"5 (Strict)",value:"5"},{label:"10 (Recommended)",value:"10"},{label:"20",value:"20"},{label:"50 (Permissive)",value:"50"}],warningThreshold:{above:20,message:"High auth limits may allow brute force attempts."}},rate_limit_general:{key:"rate_limit_general",label:"General Request Limit",description:"Maximum general API requests per IP per window. Affects all non-auth endpoints.",inputType:"select",min:1,unit:"requests",presets:[{label:"30",value:"30"},{label:"60 (Recommended)",value:"60"},{label:"120",value:"120"},{label:"300",value:"300"}]},rate_limit_credit:{key:"rate_limit_credit",label:"Credit Request Limit",description:"Maximum credit/balance check requests per IP per window. Higher for apps that poll balance frequently.",inputType:"select",min:1,unit:"requests",presets:[{label:"10",value:"10"},{label:"30 (Recommended)",value:"30"},{label:"60",value:"60"},{label:"120",value:"120"}]},rate_limit_window:{key:"rate_limit_window",label:"Rate Limit Window",description:'Time window for rate limiting. All limits above are "per window". Shorter windows are stricter.',inputType:"duration",min:1,presets:[{label:"30 seconds",value:"30"},{label:"1 minute",value:"60"},{label:"5 minutes",value:"300"},{label:"15 minutes",value:"900"}]},solana_rpc_url:{key:"solana_rpc_url",label:"Solana RPC URL",description:'Get a fast RPC endpoint from <a href="https://helius.dev" target="_blank" rel="noopener">Helius</a> or <a href="https://quicknode.com" target="_blank" rel="noopener">QuickNode</a>.',inputType:"text",placeholder:"https://api.mainnet-beta.solana.com"},solana_network:{key:"solana_network",label:"Solana Network",description:"The Solana network to use for deposits and withdrawals.",inputType:"select",presets:[{label:"Mainnet",value:"mainnet-beta"},{label:"Devnet",value:"devnet"}]},deposit_privacy_enabled:{key:"deposit_privacy_enabled",label:"Enable Private Deposits",description:"When enabled, deposits are held for a privacy period before withdrawal. Provides timing privacy but delays fund availability.",inputType:"boolean"},deposit_company_token:{key:"deposit_company_token",label:"Platform Token",description:"The token that represents platform credits. Deposits are converted to this token. Common choices: USDC, SOL.",inputType:"select",presets:[{label:"USDC",value:"USDC"},{label:"USDT",value:"USDT"},{label:"SOL",value:"SOL"},{label:"EURC",value:"EURC"}]},deposit_micro_enabled:{key:"deposit_micro_enabled",label:"SOL Micro Payments",description:"Allow small SOL deposits (under $10) that are batched together for efficiency.",inputType:"boolean"},deposit_gasless_swap_enabled:{key:"deposit_gasless_swap_enabled",label:"Gasless Swap Payments",description:"Allow deposits via Jupiter swaps.",inputType:"boolean"},deposit_min_usd:{key:"deposit_min_usd",label:"Minimum Deposit",description:"Minimum deposit amount in USD equivalent.",inputType:"select",unit:"USD",presets:[{label:"$1",value:"1"},{label:"$5",value:"5"},{label:"$10",value:"10"},{label:"$25",value:"25"}]},deposit_max_usd:{key:"deposit_max_usd",label:"Maximum Deposit",description:"Maximum deposit amount per transaction in USD equivalent. Set to 0 for unlimited.",inputType:"select",unit:"USD",presets:[{label:"Unlimited",value:"0"},{label:"$1,000",value:"1000"},{label:"$10,000",value:"10000"},{label:"$100,000",value:"100000"}]},deposit_show_explainer:{key:"deposit_show_explainer",label:"Show Explainer Screen",description:"Show the introductory explainer screen at the start of the deposit flow.",inputType:"boolean"},deposit_quick_action_tokens:{key:"deposit_quick_action_tokens",label:"Quick Action Tokens",description:"Comma-separated token symbols shown as quick action buttons. First token is the default.",inputType:"tokenSymbolList"},deposit_custom_tokens:{key:"deposit_custom_tokens",label:"Custom Dropdown Tokens",description:'Comma-separated token symbols shown in the "Custom" dropdown. Leave empty to show all.',inputType:"tokenSymbolList"},deposit_custom_tokens_json:{key:"deposit_custom_tokens_json",label:"Custom Token Definitions",description:"Add tokens beyond the built-in list. Define symbol, mint address, decimals, and logo URL.",inputType:"tokenList"},deposit_fee_policy:{key:"deposit_fee_policy",label:"Fee Policy",description:"Who pays deposit fees: company absorbs all, or user pays swap/privacy/all fees.",inputType:"select",presets:[{label:"Company Pays All",value:"company_pays_all"},{label:"User Pays Swap Fees",value:"user_pays_swap"},{label:"User Pays Privacy Fees",value:"user_pays_privacy"},{label:"User Pays All Fees",value:"user_pays_all"}]},privacy_fee_fixed_lamports:{key:"privacy_fee_fixed_lamports",label:"Privacy Fixed Fee",description:"Fixed fee for Privacy Cash deposits in lamports. 1 SOL = 1,000,000,000 lamports.",inputType:"select",unit:"lamports",presets:[{label:"0 SOL",value:"0"},{label:"0.001 SOL",value:"1000000"},{label:"0.005 SOL",value:"5000000"},{label:"0.006 SOL (Default)",value:"6000000"},{label:"0.01 SOL",value:"10000000"}]},privacy_fee_percent_bps:{key:"privacy_fee_percent_bps",label:"Privacy Percentage Fee",description:"Percentage fee for Privacy Cash deposits in basis points. 100 bps = 1%.",inputType:"select",unit:"bps",presets:[{label:"0%",value:"0"},{label:"0.25%",value:"25"},{label:"0.35% (Default)",value:"35"},{label:"0.5%",value:"50"},{label:"1%",value:"100"}]},swap_fee_fixed_lamports:{key:"swap_fee_fixed_lamports",label:"Swap Fixed Fee",description:"Fixed fee for Jupiter swaps in lamports. Covers transaction costs.",inputType:"select",unit:"lamports",presets:[{label:"0 SOL",value:"0"},{label:"0.001 SOL (Default)",value:"1000000"},{label:"0.002 SOL",value:"2000000"},{label:"0.005 SOL",value:"5000000"}]},swap_fee_percent_bps:{key:"swap_fee_percent_bps",label:"Swap Percentage Fee",description:"Percentage fee for Jupiter swaps in basis points. 100 bps = 1%.",inputType:"select",unit:"bps",presets:[{label:"0%",value:"0"},{label:"0.1% (Default)",value:"10"},{label:"0.25%",value:"25"},{label:"0.5%",value:"50"}]},company_fee_fixed_lamports:{key:"company_fee_fixed_lamports",label:"Company Fixed Fee",description:"Additional fixed processing fee in lamports. Set to 0 to disable.",inputType:"select",unit:"lamports",presets:[{label:"Disabled",value:"0"},{label:"0.001 SOL",value:"1000000"},{label:"0.005 SOL",value:"5000000"},{label:"0.01 SOL",value:"10000000"}]},company_fee_percent_bps:{key:"company_fee_percent_bps",label:"Company Percentage Fee",description:"Additional percentage processing fee in basis points. 100 bps = 1%.",inputType:"select",unit:"bps",presets:[{label:"Disabled",value:"0"},{label:"0.1%",value:"10"},{label:"0.25%",value:"25"},{label:"0.5%",value:"50"},{label:"1%",value:"100"}]},micro_batch_threshold_usd:{key:"micro_batch_threshold_usd",label:"Batch Threshold",description:"Minimum accumulated USD value before triggering a batch swap. Jupiter requires ~$10 minimum.",inputType:"select",unit:"USD",presets:[{label:"$10 (Minimum)",value:"10"},{label:"$25",value:"25"},{label:"$50",value:"50"},{label:"$100",value:"100"}]},micro_batch_poll_secs:{key:"micro_batch_poll_secs",label:"Batch Poll Interval",description:"How often to check for batchable micro deposits. Lower values process faster but increase load.",inputType:"duration",min:60,presets:[{label:"1 minute",value:"60"},{label:"5 minutes (Default)",value:"300"},{label:"15 minutes",value:"900"},{label:"1 hour",value:"3600"}]},private_deposit_min_lamports:{key:"private_deposit_min_lamports",label:"Min Private Deposit",description:"Minimum amount for Privacy Cash deposits in lamports. Smaller deposits use micro batching.",inputType:"select",unit:"lamports",presets:[{label:"0.1 SOL",value:"100000000"},{label:"0.25 SOL (Default)",value:"250000000"},{label:"0.5 SOL",value:"500000000"},{label:"1 SOL",value:"1000000000"}]},withdrawal_min_lamports:{key:"withdrawal_min_lamports",label:"Min Withdrawal Amount",description:"Minimum amount to withdraw in lamports. Deposits below this remain pending. Fees are ~0.006 SOL + 0.35% + Jupiter.",inputType:"select",unit:"lamports",presets:[{label:"0.5 SOL",value:"500000000"},{label:"1 SOL (Default)",value:"1000000000"},{label:"2 SOL",value:"2000000000"},{label:"5 SOL",value:"5000000000"}],warningThreshold:{below:5e8,message:"Very small withdrawals may lose significant value to fees."}}},Ur=["SOL","USDC","USDT","EURC","USD1","PYUSD","USDH","CASH","BONK","ORE"];function be({settings:s,edits:t,onChange:r,externalWarnings:a}){return e.jsx("div",{className:"cedros-settings-grid",children:s.map(n=>e.jsx(fo,{setting:n,editValue:t[n.key],onChange:r,externalWarning:a?.[n.key]},n.key))})}function fo({setting:s,editValue:t,onChange:r,externalWarning:a}){const n=po[s.key],o=t??s.value,c=t!==void 0&&t!==s.value,l=n?.inputType==="boolean",d=i.useMemo(()=>{if(a)return a;if(!n?.warningThreshold)return null;const u=parseInt(o,10);if(isNaN(u))return null;const{above:g,below:m,message:h}=n.warningThreshold;return g!==void 0&&u>g||m!==void 0&&u<m?h:null},[o,n?.warningThreshold,a]);return n?e.jsx("div",{className:`cedros-setting-row ${c?"cedros-setting-row-changed":""} ${d?"cedros-setting-row-warning":""} ${l?"cedros-setting-row-toggle":""}`,children:l?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-setting-control cedros-setting-control-toggle",children:[e.jsx(mt,{meta:n,value:o,onChange:u=>r(s.key,u)}),d&&e.jsx("div",{className:"cedros-setting-warning",children:d})]}),e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:n.label}),e.jsx("span",{className:"cedros-setting-description",dangerouslySetInnerHTML:{__html:n.description}})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:n.label}),e.jsx("span",{className:"cedros-setting-description",dangerouslySetInnerHTML:{__html:n.description}})]}),e.jsxs("div",{className:"cedros-setting-control",children:[e.jsx(mt,{meta:n,value:o,onChange:u=>r(s.key,u)}),d&&e.jsx("div",{className:"cedros-setting-warning",children:d})]})]})}):e.jsxs("div",{className:`cedros-setting-row ${c?"cedros-setting-row-changed":""}`,children:[e.jsxs("div",{className:"cedros-setting-label",children:[e.jsx("span",{className:"cedros-setting-name",children:s.key}),s.description&&e.jsx("span",{className:"cedros-setting-description",children:s.description})]}),e.jsx("div",{className:"cedros-setting-input-wrapper",children:e.jsx("input",{type:"text",value:o,onChange:u=>r(s.key,u.target.value),className:"cedros-setting-input"})})]})}function mt({meta:s,value:t,onChange:r}){switch(s.inputType){case"duration":return e.jsx(go,{value:t,onChange:r,presets:s.presets,min:s.min});case"percentage":return e.jsx(bo,{value:t,onChange:r,min:s.min??1,max:s.max??100,step:s.step??5,presets:s.presets});case"select":return e.jsx(yo,{value:t,onChange:r,presets:s.presets??[],unit:s.unit});case"number":return e.jsx(wo,{value:t,onChange:r,min:s.min,max:s.max,unit:s.unit});case"tokenList":return e.jsx(jo,{value:t,onChange:r});case"text":return e.jsx("input",{type:"text",value:t,onChange:a=>r(a.target.value),className:"cedros-setting-input",placeholder:s.label});case"boolean":return e.jsx(xo,{value:t,onChange:r});case"secret":return e.jsx(vo,{value:t,onChange:r,multiline:s.multiline});case"tokenSymbolList":return e.jsx(Ao,{value:t,onChange:r});default:return e.jsx("input",{type:"text",value:t,onChange:a=>r(a.target.value),className:"cedros-setting-input"})}}function go({value:s,onChange:t,presets:r,min:a=0}){const n=parseInt(s,10)||0,o=mo(n),c=i.useCallback(d=>{d.target.value&&t(d.target.value)},[t]),l=i.useCallback(d=>{const u=Math.max(a,parseInt(d.target.value,10)||0);t(String(u))},[t,a]);return e.jsxs("div",{className:"cedros-duration-input",children:[r&&r.length>0&&e.jsxs("select",{value:r.find(d=>d.value===s)?.value??"",onChange:c,className:"cedros-setting-select",children:[e.jsx("option",{value:"",children:"Custom..."}),r.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))]}),e.jsxs("div",{className:"cedros-duration-custom",children:[e.jsx("input",{type:"number",value:n,onChange:l,min:a,className:"cedros-setting-input cedros-setting-input-sm"}),e.jsx("span",{className:"cedros-setting-unit",children:"seconds"}),e.jsxs("span",{className:"cedros-duration-display",children:["= ",o]})]})]})}function bo({value:s,onChange:t,min:r,max:a,step:n,presets:o}){const c=parseInt(s,10)||r,l=i.useCallback(u=>{t(u.target.value)},[t]),d=i.useCallback(u=>{t(u)},[t]);return e.jsxs("div",{className:"cedros-percentage-input",children:[e.jsxs("div",{className:"cedros-percentage-slider-row",children:[e.jsx("input",{type:"range",value:c,onChange:l,min:r,max:a,step:n,className:"cedros-percentage-slider"}),e.jsxs("span",{className:"cedros-percentage-value",children:[c,"%"]})]}),o&&o.length>0&&e.jsx("div",{className:"cedros-preset-buttons",children:o.map(u=>e.jsx("button",{type:"button",className:`cedros-preset-button ${u.value===s?"cedros-preset-button-active":""}`,onClick:()=>d(u.value),children:u.label},u.value))})]})}function yo({value:s,onChange:t,presets:r,unit:a}){const n=!r.some(l=>l.value===s),o=i.useCallback(l=>{l.target.value!=="__custom__"&&t(l.target.value)},[t]),c=i.useCallback(l=>{t(l.target.value)},[t]);return e.jsxs("div",{className:"cedros-select-input",children:[e.jsxs("select",{value:n?"__custom__":s,onChange:o,className:"cedros-setting-select",children:[r.map(l=>e.jsx("option",{value:l.value,children:l.label},l.value)),e.jsx("option",{value:"__custom__",children:"Custom..."})]}),n&&e.jsxs("div",{className:"cedros-select-custom",children:[e.jsx("input",{type:"number",value:s,onChange:c,className:"cedros-setting-input cedros-setting-input-sm"}),a&&e.jsx("span",{className:"cedros-setting-unit",children:a})]})]})}function wo({value:s,onChange:t,min:r,max:a,unit:n}){const o=i.useCallback(c=>{t(c.target.value)},[t]);return e.jsxs("div",{className:"cedros-number-input",children:[e.jsx("input",{type:"number",value:s,onChange:o,min:r,max:a,className:"cedros-setting-input"}),n&&e.jsx("span",{className:"cedros-setting-unit",children:n})]})}function xo({value:s,onChange:t}){const r=s==="true",a=i.useCallback(()=>{t(r?"false":"true")},[r,t]);return e.jsxs("button",{type:"button",role:"switch","aria-checked":r,className:`cedros-toggle ${r?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:a,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:r?"Enabled":"Disabled"})]})}function vo({value:s,onChange:t,multiline:r}){const[a,n]=i.useState(!1),[o,c]=i.useState(!1),l=s&&s.length>0,d=i.useCallback(()=>{n(!0),c(!0)},[]),u=i.useCallback(()=>{n(!1),c(!1)},[]),g=i.useCallback(m=>{t(m.target.value)},[t]);return!a&&l?e.jsxs("div",{className:"cedros-secret-input cedros-secret-input-masked",children:[e.jsx("span",{className:"cedros-secret-masked",children:"•".repeat(Math.min(s.length,20))}),e.jsx("button",{type:"button",className:"cedros-secret-edit-btn",onClick:d,children:"Edit"})]}):e.jsxs("div",{className:"cedros-secret-input",children:[r?e.jsx("textarea",{value:s,onChange:g,className:"cedros-setting-input cedros-setting-textarea",placeholder:"Enter secret value...",rows:4}):e.jsx("input",{type:o?"text":"password",value:s,onChange:g,className:"cedros-setting-input",placeholder:"Enter secret value..."}),e.jsxs("div",{className:"cedros-secret-actions",children:[!r&&e.jsx("button",{type:"button",className:"cedros-secret-toggle-btn",onClick:()=>c(!o),children:o?"Hide":"Show"}),a&&e.jsx("button",{type:"button",className:"cedros-secret-done-btn",onClick:u,children:"Done"})]})]})}function jo({value:s,onChange:t}){const r=i.useMemo(()=>{try{return JSON.parse(s||"[]")}catch{return[]}},[s]),a=i.useCallback(l=>{t(JSON.stringify(l))},[t]),n=i.useCallback(()=>{a([...r,{symbol:"",mint:"",decimals:6}])},[r,a]),o=i.useCallback((l,d,u)=>{const g=[...r];g[l]={...g[l],[d]:u},a(g)},[r,a]),c=i.useCallback(l=>{a(r.filter((d,u)=>u!==l))},[r,a]);return e.jsxs("div",{className:"cedros-token-list-input",children:[e.jsxs("div",{className:"cedros-token-presets",children:[e.jsx("span",{className:"cedros-token-presets-label",children:"Built-in tokens:"}),e.jsx("div",{className:"cedros-token-presets-list",children:Ur.map(l=>e.jsx("span",{className:"cedros-token-preset-chip",children:l},l))})]}),r.length===0&&e.jsx("p",{className:"cedros-token-list-empty",children:"No custom tokens added. Use the built-in tokens above or add your own."}),r.map((l,d)=>e.jsxs("div",{className:"cedros-token-row",children:[e.jsxs("div",{className:"cedros-token-row-fields",children:[e.jsx("input",{type:"text",placeholder:"Symbol",value:l.symbol,onChange:u=>o(d,"symbol",u.target.value.toUpperCase()),className:"cedros-setting-input cedros-token-input-symbol",maxLength:10}),e.jsx("input",{type:"text",placeholder:"Mint address",value:l.mint,onChange:u=>o(d,"mint",u.target.value),className:"cedros-setting-input cedros-token-input-mint"}),e.jsx("input",{type:"number",placeholder:"Decimals",value:l.decimals,onChange:u=>o(d,"decimals",parseInt(u.target.value,10)||0),className:"cedros-setting-input cedros-token-input-decimals",min:0,max:18}),e.jsx("input",{type:"text",placeholder:"Logo URL (optional)",value:l.logoUrl||"",onChange:u=>o(d,"logoUrl",u.target.value||void 0),className:"cedros-setting-input cedros-token-input-logo"})]}),e.jsx("button",{type:"button",className:"cedros-token-remove-btn",onClick:()=>c(d),title:"Remove token",children:"×"})]},d)),e.jsx("button",{type:"button",className:"cedros-token-add-btn",onClick:n,children:"+ Add Token"})]})}function Ao({value:s,onChange:t}){const r=i.useMemo(()=>s.split(",").map(o=>o.trim()).filter(Boolean),[s]),a=i.useCallback(o=>{if(!o||r.includes(o))return;const c=[...r,o].join(", ");t(c)},[r,t]),n=i.useCallback(o=>{const c=r.filter(l=>l!==o).join(", ");t(c)},[r,t]);return e.jsxs("div",{className:"cedros-token-symbol-list-input",children:[e.jsxs("div",{className:"cedros-token-presets",children:[e.jsx("span",{className:"cedros-token-presets-label",children:"Click to add:"}),e.jsx("div",{className:"cedros-token-presets-list",children:Ur.map(o=>{const c=r.includes(o);return e.jsxs("button",{type:"button",className:`cedros-token-preset-chip ${c?"cedros-token-preset-chip-selected":""}`,onClick:()=>c?n(o):a(o),title:c?`Remove ${o}`:`Add ${o}`,children:[o,c&&e.jsx("span",{className:"cedros-token-chip-check",children:"✓"})]},o)})})]}),e.jsx("input",{type:"text",value:s,onChange:o=>t(o.target.value),className:"cedros-setting-input",placeholder:"USDC, SOL, BONK..."})]})}function Te({status:s,error:t}){return s==="idle"?null:e.jsxs("div",{className:`cedros-autosave-status cedros-autosave-status--${s}`,children:[s==="pending"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-autosave-dot"}),e.jsx("span",{children:"Unsaved changes"})]}),s==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-autosave-spinner"}),e.jsx("span",{children:"Saving..."})]}),s==="saved"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-autosave-check",children:"✓"}),e.jsx("span",{children:"Saved"})]}),s==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"cedros-autosave-error-icon",children:"!"}),e.jsx("span",{children:t||"Save failed"})]})]})}function ns({title:s,description:t,categories:r,className:a=""}){const{settings:n,edits:o,isLoading:c,autosaveStatus:l,autosaveError:d,error:u,fetchSettings:g,handleChange:m}=Ee();i.useEffect(()=>{g()},[g]);const h=r.filter(b=>n[b]?.length>0);return c&&Object.keys(n).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${a}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):u?e.jsx("div",{className:`cedros-system-settings ${a}`,children:e.jsx(N.ErrorMessage,{error:u.message})}):e.jsxs("div",{className:`cedros-system-settings ${a}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:s}),e.jsx("p",{className:"cedros-settings-page-description",children:t})]}),e.jsx(Te,{status:l,error:d})]}),h.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsx("p",{children:"No settings found for this section."})}):h.map(b=>e.jsx(be,{settings:n[b],edits:o,onChange:m},b))]})}function ko(){const{config:s,_internal:t}=N.useCedrosLogin(),r=s.serverUrl,a=i.useRef(t?.getAccessToken??(()=>null));a.current=t?.getAccessToken??(()=>null);const[n,o]=i.useState([]),[c,l]=i.useState(0),[d,u]=i.useState(!1),[g,m]=i.useState(null),h=i.useCallback(()=>{const y=a.current();return{"Content-Type":"application/json",...y?{Authorization:`Bearer ${y}`}:{}}},[]),b=i.useCallback(async(y,A=50,v=0)=>{u(!0),m(null);try{const S=new URLSearchParams;y&&S.set("org_id",y),S.set("limit",String(A)),S.set("offset",String(v));const w=await fetch(`${r}/admin/sso-providers?${S}`,{headers:h()});if(!w.ok){const P=await w.json().catch(()=>({}));throw new Error(P.error||`Failed to fetch SSO providers: ${w.status}`)}const E=await w.json();return o(E.providers),l(E.total),E}catch(S){const w=S instanceof Error?S:new Error(String(S));throw m(w),w}finally{u(!1)}},[r,h]),f=i.useCallback(async y=>{u(!0),m(null);try{const A=await fetch(`${r}/admin/sso-providers`,{method:"POST",headers:h(),body:JSON.stringify(y)});if(!A.ok){const S=await A.json().catch(()=>({}));throw new Error(S.error||`Failed to create SSO provider: ${A.status}`)}const v=await A.json();return o(S=>[...S,v]),l(S=>S+1),v}catch(A){const v=A instanceof Error?A:new Error(String(A));throw m(v),v}finally{u(!1)}},[r,h]),p=i.useCallback(async(y,A)=>{u(!0),m(null);try{const v=await fetch(`${r}/admin/sso-providers/${y}`,{method:"PUT",headers:h(),body:JSON.stringify(A)});if(!v.ok){const w=await v.json().catch(()=>({}));throw new Error(w.error||`Failed to update SSO provider: ${v.status}`)}const S=await v.json();return o(w=>w.map(E=>E.id===y?S:E)),S}catch(v){const S=v instanceof Error?v:new Error(String(v));throw m(S),S}finally{u(!1)}},[r,h]),x=i.useCallback(async y=>{u(!0),m(null);try{const A=await fetch(`${r}/admin/sso-providers/${y}`,{method:"DELETE",headers:h()});if(!A.ok){const v=await A.json().catch(()=>({}));throw new Error(v.error||`Failed to delete SSO provider: ${A.status}`)}o(v=>v.filter(S=>S.id!==y)),l(v=>v-1)}catch(A){const v=A instanceof Error?A:new Error(String(A));throw m(v),v}finally{u(!1)}},[r,h]),j=i.useCallback(async(y,A)=>p(y,{enabled:A}),[p]);return{providers:n,total:c,isLoading:d,error:g,fetchProviders:b,createProvider:f,updateProvider:p,deleteProvider:x,toggleProvider:j}}class Fr{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async listOrgs(){try{return(await this.client.get("/orgs")).orgs.map(r=>({...r,membership:{orgId:r.id,role:r.role}}))}catch(t){throw N.handleApiError(t,"Failed to list organizations")}}async getOrg(t){try{return await this.client.get(`/orgs/${t}`)}catch(r){throw N.handleApiError(r,"Failed to get organization")}}async createOrg(t){try{return await this.client.post("/orgs",t)}catch(r){throw N.handleApiError(r,"Failed to create organization")}}async updateOrg(t,r){try{return await this.client.patch(`/orgs/${t}`,r)}catch(a){throw N.handleApiError(a,"Failed to update organization")}}async deleteOrg(t){try{await this.client.delete(`/orgs/${t}`)}catch(r){throw N.handleApiError(r,"Failed to delete organization")}}async authorize(t){try{return await this.client.post("/authorize",t)}catch(r){throw N.handleApiError(r,"Failed to check authorization")}}async getPermissions(t){try{return await this.client.post("/permissions",{orgId:t})}catch(r){throw N.handleApiError(r,"Failed to get permissions")}}}const gs="cedros_active_org";function No(s){try{return localStorage.getItem(s)}catch{return null}}function pt(s,t){try{localStorage.setItem(s,t)}catch{}}function as(){const{config:s,user:t,authState:r,_internal:a}=N.useCedrosLogin(),n=typeof window<"u"&&!!window.localStorage,[o,c]=i.useState([]),[l,d]=i.useState(null),[u,g]=i.useState([]),[m,h]=i.useState(null),[b,f]=i.useState(!1),[p,x]=i.useState(null),j=i.useMemo(()=>new Fr(s.serverUrl,s.requestTimeout,s.retryAttempts,a?.getAccessToken),[s.serverUrl,s.requestTimeout,s.retryAttempts,a]),y=i.useRef(j);i.useEffect(()=>{y.current=j},[j]);const A=i.useCallback(async T=>{try{const C=await y.current.getPermissions(T);g(C.permissions),h(C.role)}catch{g([]),h(null)}},[]),v=i.useCallback(async()=>{if(r!=="authenticated"||!t){c([]),d(null),g([]),h(null);return}f(!0),x(null);try{const T=await y.current.listOrgs();c(T);const C=n?No(gs):null;let k=T.find(_=>_.id===C);!k&&T.length>0&&(k=T.find(_=>_.isPersonal)||T[0]),k?(d(k),n&&pt(gs,k.id),await A(k.id)):(d(null),g([]),h(null))}catch(T){x(T)}finally{f(!1)}},[r,t,A,n]),S=i.useCallback(async T=>{const C=o.find(k=>k.id===T);if(!C){x({code:"UNKNOWN_ERROR",message:"Organization not found"});return}d(C),n&&pt(gs,T),await A(T)},[o,A,n]),w=i.useCallback(async T=>{f(!0),x(null);try{const C=await y.current.createOrg(T);return await v(),C}catch(C){throw x(C),C}finally{f(!1)}},[v]),E=i.useCallback(async(T,C)=>{f(!0),x(null);try{const k=await y.current.updateOrg(T,C);return await v(),k}catch(k){throw x(k),k}finally{f(!1)}},[v]),P=i.useCallback(async T=>{f(!0),x(null);try{await y.current.deleteOrg(T),await v()}catch(C){throw x(C),C}finally{f(!1)}},[v]),L=i.useCallback(T=>u.includes(T),[u]);return{orgs:o,activeOrg:l,permissions:u,role:m,isLoading:b,error:p,fetchOrgs:v,switchOrg:S,createOrg:w,updateOrg:E,deleteOrg:P,hasPermission:L}}function So({className:s}){const{providers:t,isLoading:r,error:a,fetchProviders:n,createProvider:o,updateProvider:c,deleteProvider:l,toggleProvider:d}=ko(),{activeOrg:u}=as(),[g,m]=i.useState("list"),[h,b]=i.useState(null),[f,p]=i.useState(null);i.useEffect(()=>{n(u?.id)},[n,u?.id]);const x=()=>{b(null),p(null),m("add")},j=w=>{b(w),p(null),m("edit")},y=()=>{m("list"),b(null),p(null)},A=async w=>{if(confirm(`Delete SSO provider "${w.name}"? This cannot be undone.`))try{await l(w.id)}catch{}},v=async w=>{try{await d(w.id,!w.enabled)}catch{}},S=async w=>{p(null);try{g==="add"?await o(w):h&&await c(h.id,w),m("list"),b(null)}catch(E){p(E instanceof Error?E.message:"Failed to save provider")}};return r&&t.length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading SSO providers..."})]}):g==="add"||g==="edit"?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(_o,{provider:h,orgId:u?.id,error:f,isLoading:r,onSave:S,onCancel:y})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"SSO Providers"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure OIDC identity providers for enterprise single sign-on."})]}),e.jsx("button",{type:"button",className:"cedros-btn cedros-btn-primary",onClick:x,children:"Add Provider"})]}),a&&e.jsx(N.ErrorMessage,{error:a.message}),t.length===0?e.jsxs("div",{className:"cedros-system-settings-empty",children:[e.jsx("p",{children:"No SSO providers configured."}),e.jsx("p",{className:"cedros-text-muted",children:"Add an OIDC provider like Okta, Azure AD, or Auth0 to enable enterprise SSO."})]}):e.jsx("div",{className:"cedros-sso-provider-list",children:t.map(w=>e.jsx(Co,{provider:w,onEdit:()=>j(w),onDelete:()=>A(w),onToggle:()=>v(w)},w.id))})]})}function Co({provider:s,onEdit:t,onDelete:r,onToggle:a}){return e.jsxs("div",{className:`cedros-sso-provider-card ${s.enabled?"":"cedros-sso-provider-card--disabled"}`,children:[e.jsxs("div",{className:"cedros-sso-provider-card-header",children:[e.jsxs("div",{className:"cedros-sso-provider-card-info",children:[e.jsx("h3",{className:"cedros-sso-provider-card-name",children:s.name}),e.jsx("p",{className:"cedros-sso-provider-card-issuer",children:s.issuerUrl})]}),e.jsxs("button",{type:"button",role:"switch","aria-checked":s.enabled,className:`cedros-toggle ${s.enabled?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:a,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:s.enabled?"Enabled":"Disabled"})]})]}),e.jsxs("div",{className:"cedros-sso-provider-card-details",children:[e.jsxs("div",{className:"cedros-sso-provider-card-detail",children:[e.jsx("span",{className:"cedros-sso-provider-card-detail-label",children:"Client ID"}),e.jsx("code",{className:"cedros-sso-provider-card-detail-value",children:s.clientId})]}),s.emailDomain&&e.jsxs("div",{className:"cedros-sso-provider-card-detail",children:[e.jsx("span",{className:"cedros-sso-provider-card-detail-label",children:"Email Domain"}),e.jsxs("span",{className:"cedros-sso-provider-card-detail-value",children:["@",s.emailDomain]})]}),e.jsxs("div",{className:"cedros-sso-provider-card-detail",children:[e.jsx("span",{className:"cedros-sso-provider-card-detail-label",children:"Registration"}),e.jsx("span",{className:"cedros-sso-provider-card-detail-value",children:s.allowRegistration?"Allowed":"Existing users only"})]})]}),e.jsxs("div",{className:"cedros-sso-provider-card-actions",children:[e.jsx("button",{type:"button",className:"cedros-btn cedros-btn-ghost",onClick:t,children:"Edit"}),e.jsx("button",{type:"button",className:"cedros-btn cedros-btn-ghost cedros-btn-danger",onClick:r,children:"Delete"})]})]})}function _o({provider:s,orgId:t,error:r,isLoading:a,onSave:n,onCancel:o}){const c=!!s,[l,d]=i.useState(s?.name??""),[u,g]=i.useState(s?.issuerUrl??""),[m,h]=i.useState(s?.clientId??""),[b,f]=i.useState(""),[p,x]=i.useState(s?.emailDomain??""),[j,y]=i.useState(s?.allowRegistration??!0),[A,v]=i.useState(s?.enabled??!0),S=i.useCallback(w=>{if(w.preventDefault(),c){const E={name:l,issuerUrl:u,clientId:m,emailDomain:p||null,allowRegistration:j,enabled:A};b&&(E.clientSecret=b),n(E)}else{if(!t)return;n({orgId:t,name:l,issuerUrl:u,clientId:m,clientSecret:b,emailDomain:p||null,allowRegistration:j,enabled:A})}},[c,t,l,u,m,b,p,j,A,n]);return e.jsxs("form",{className:"cedros-sso-provider-form",onSubmit:S,children:[e.jsx("div",{className:"cedros-settings-page-header",children:e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:c?"Edit SSO Provider":"Add SSO Provider"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure an OIDC identity provider for enterprise single sign-on."})]})}),r&&e.jsx(N.ErrorMessage,{error:r}),e.jsxs("div",{className:"cedros-form-section",children:[e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{className:"cedros-form-label",htmlFor:"sso-name",children:"Provider Name"}),e.jsx("input",{id:"sso-name",type:"text",className:"cedros-form-input",value:l,onChange:w=>d(w.target.value),placeholder:"e.g., Okta, Azure AD",required:!0})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{className:"cedros-form-label",htmlFor:"sso-issuer",children:"Issuer URL"}),e.jsx("input",{id:"sso-issuer",type:"url",className:"cedros-form-input",value:u,onChange:w=>g(w.target.value),placeholder:"https://your-org.okta.com",required:!0}),e.jsx("p",{className:"cedros-form-hint",children:"The OIDC issuer URL. Must support discovery at /.well-known/openid-configuration"})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{className:"cedros-form-label",htmlFor:"sso-client-id",children:"Client ID"}),e.jsx("input",{id:"sso-client-id",type:"text",className:"cedros-form-input",value:m,onChange:w=>h(w.target.value),placeholder:"OAuth client ID",required:!0})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsxs("label",{className:"cedros-form-label",htmlFor:"sso-client-secret",children:["Client Secret ",c&&e.jsx("span",{className:"cedros-form-hint-inline",children:"(leave blank to keep current)"})]}),e.jsx("input",{id:"sso-client-secret",type:"password",className:"cedros-form-input",value:b,onChange:w=>f(w.target.value),placeholder:c?"••••••••":"OAuth client secret",required:!c})]}),e.jsxs("div",{className:"cedros-form-group",children:[e.jsx("label",{className:"cedros-form-label",htmlFor:"sso-email-domain",children:"Email Domain (optional)"}),e.jsx("input",{id:"sso-email-domain",type:"text",className:"cedros-form-input",value:p,onChange:w=>x(w.target.value),placeholder:"company.com"}),e.jsx("p",{className:"cedros-form-hint",children:"Restrict to users with emails from this domain"})]}),e.jsx("div",{className:"cedros-form-group",children:e.jsxs("label",{className:"cedros-form-checkbox",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:w=>y(w.target.checked)}),e.jsx("span",{children:"Allow new user registration via SSO"})]})}),e.jsx("div",{className:"cedros-form-group",children:e.jsxs("label",{className:"cedros-form-checkbox",children:[e.jsx("input",{type:"checkbox",checked:A,onChange:w=>v(w.target.checked)}),e.jsx("span",{children:"Enable this provider"})]})})]}),e.jsxs("div",{className:"cedros-form-actions",children:[e.jsx("button",{type:"button",className:"cedros-btn cedros-btn-ghost",onClick:o,disabled:a,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-btn cedros-btn-primary",disabled:a,children:a?"Saving...":c?"Save Changes":"Add Provider"})]})]})}const ft=[{id:"email",label:"Email",categories:["auth.email"]},{id:"google",label:"Google",categories:["auth.google"]},{id:"apple",label:"Apple",categories:["auth.apple"]},{id:"solana",label:"Solana",categories:["auth.solana"]},{id:"passkeys",label:"Passkeys",categories:["auth.webauthn"]},{id:"instantlink",label:"Instant Link",categories:["auth.instantlink"]},{id:"sso",label:"SSO Providers",categories:[],isCustom:!0}];function Br({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d}=Ee(),[u,g]=i.useState("email");i.useEffect(()=>{l()},[l]);const m=ft.find(f=>f.id===u),h=i.useMemo(()=>{if(!m)return[];const f=[];for(const p of m.categories){const x=t[p]??[];f.push(...x)}return f},[t,m]),b=i.useMemo(()=>m?.keys?h.filter(f=>m.keys.includes(f.key)).sort((f,p)=>m.keys.indexOf(f.key)-m.keys.indexOf(p.key)):h,[h,m]);return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Authentication"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure authentication providers and methods for user sign-in."})]}),e.jsx(Te,{status:n,error:o})]}),e.jsx("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:ft.map(f=>e.jsx("button",{type:"button",className:`cedros-admin-tab ${u===f.id?"cedros-admin-tab-active":""}`,onClick:()=>g(f.id),"aria-selected":u===f.id,role:"tab",children:f.label},f.id))}),e.jsx("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:m?.isCustom?e.jsx(So,{}):b.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsxs("p",{children:["No settings found for ",m?.label??"this provider","."]})}):e.jsx(be,{settings:b,edits:r,onChange:d})})]})}const bs=["wallet_recovery_mode"];function Or({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d,getEffectiveValue:u}=Ee();i.useEffect(()=>{l()},[l]);const m=(t.features??[]).filter(f=>bs.includes(f.key)).sort((f,p)=>bs.indexOf(f.key)-bs.indexOf(p.key)),h=u("feature_wallet_signing")==="true",b=()=>{d("feature_wallet_signing",h?"false":"true")};return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Embedded Wallet"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure the embedded wallet for transaction signing."})]}),e.jsxs("div",{className:"cedros-settings-page-header-actions",children:[e.jsxs("button",{type:"button",role:"switch","aria-checked":h,className:`cedros-toggle ${h?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:b,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:h?"Enabled":"Disabled"})]}),e.jsx(Te,{status:n,error:o})]})]}),e.jsx("div",{className:"cedros-admin-tab-content",children:m.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsx("p",{children:"No additional settings available."})}):e.jsx(be,{settings:m,edits:r,onChange:d})})]})}const Eo=["security","rate_limit"];function To({className:s}){return e.jsx(ns,{title:"Security",description:"Configure CORS, cookies, sessions, JWT, and rate limiting settings.",categories:Eo,className:s})}const Po=["email"];function Lo({className:s}){return e.jsx(ns,{title:"Email & SMTP",description:"Configure outbound email delivery for verification, password reset, and notifications.",categories:Po,className:s})}const Mo=["webhook"];function Do({className:s}){return e.jsx(ns,{title:"Webhooks",description:"Configure HTTP webhook notifications for authentication events.",categories:Mo,className:s})}const gt=[{id:"email",label:"Email",category:"email"},{id:"webhooks",label:"Webhooks",category:"webhook"}],Ro={mailgun:"smtp.mailgun.org",sendgrid:"smtp.sendgrid.net",postmark:"smtp.postmarkapp.com",ses:"email-smtp.us-east-1.amazonaws.com",resend:"smtp.resend.com"},Io=["email_provider","email_smtp_password","email_from_address","email_from_name"],Uo=["email_provider","email_smtp_host","email_smtp_port","email_smtp_user","email_smtp_password","email_smtp_tls","email_from_address","email_from_name"];function Fo({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d,getEffectiveValue:u}=Ee(),[g,m]=i.useState("email");i.useEffect(()=>{l()},[l]);const h=gt.find(y=>y.id===g),b=h?.category??"",p=(u("email_provider")||"custom")==="custom",x=i.useMemo(()=>{const y=t[b]??[];if(g!=="email")return y;const A=p?Uo:Io;return y.filter(v=>A.includes(v.key)).sort((v,S)=>A.indexOf(v.key)-A.indexOf(S.key))},[t,b,g,p]),j=(y,A)=>{if(d(y,A),y==="email_provider"&&A!=="custom"){const v=Ro[A];v&&(d("email_smtp_host",v),d("email_smtp_port","587"),d("email_smtp_tls","true"))}};return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Auth Messages"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure email delivery and webhook notifications."})]}),e.jsx(Te,{status:n,error:o})]}),e.jsx("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:gt.map(y=>e.jsx("button",{type:"button",className:`cedros-admin-tab ${g===y.id?"cedros-admin-tab-active":""}`,onClick:()=>m(y.id),"aria-selected":g===y.id,role:"tab",children:y.label},y.id))}),e.jsx("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:x.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsxs("p",{children:["No settings found for ",h?.label??"this section","."]})}):e.jsx(be,{settings:x,edits:r,onChange:g==="email"?j:d})})]})}const bt=[{id:"deposits",label:"Deposits",categories:["deposit.general"],includeKeys:["deposit_company_token","deposit_max_usd","deposit_min_usd","deposit_micro_enabled","deposit_gasless_swap_enabled","solana_rpc_url","jupiter_api_key"]},{id:"tokens",label:"Component",categories:["deposit"],includeKeys:["deposit_show_explainer","deposit_quick_action_tokens","deposit_custom_tokens","deposit_custom_tokens_json"]},{id:"fees",label:"Fees",categories:["deposit"],includeKeys:["deposit_fee_policy","privacy_fee_fixed_lamports","privacy_fee_percent_bps","swap_fee_fixed_lamports","swap_fee_percent_bps","company_fee_fixed_lamports","company_fee_percent_bps","private_deposit_min_lamports"]},{id:"privacy",label:"Privacy",categories:["deposit.general","privacy","withdrawal"],includeKeys:["deposit_privacy_enabled","privacy_period_secs","withdrawal_percentage","withdrawal_min_lamports","partial_withdrawal_count","partial_withdrawal_min_lamports"],sections:[{title:"Privacy Pool Worker",description:"Background worker for processing withdrawals from the privacy cash pool.",keys:["withdrawal_poll_interval_secs","withdrawal_batch_size"]}]},{id:"treasury",label:"Treasury",categories:["withdrawal","deposit"],includeKeys:["treasury_wallet_address"],sections:[{title:"Micropayment Batch Worker",description:"Background worker for batching small SOL deposits together.",keys:["micro_batch_threshold_usd","micro_batch_poll_secs"]}]}];function qr({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d,getEffectiveValue:u}=Ee(),[g,m]=i.useState("deposits");i.useEffect(()=>{l()},[l]);const h=bt.find(v=>v.id===g),b=i.useMemo(()=>{if(!h)return[];const v=[];for(const S of h.categories){const w=t[S]??[];v.push(...w)}return v},[t,h]),f=u("deposit_fee_policy")||"company_pays_all",p=i.useMemo(()=>{if(!h)return[];let v=b;if(h.includeKeys&&h.includeKeys.length>0?(v=v.filter(S=>h.includeKeys.includes(S.key)),v.sort((S,w)=>h.includeKeys.indexOf(S.key)-h.includeKeys.indexOf(w.key))):h.excludeKeys&&h.excludeKeys.length>0&&(v=v.filter(S=>!h.excludeKeys.includes(S.key))),h.id==="deposits"&&(parseFloat(u("deposit_min_usd"))||0)>10&&(v=v.filter(w=>w.key!=="deposit_micro_enabled")),h.id==="fees"){const S=["privacy_fee_fixed_lamports","privacy_fee_percent_bps","private_deposit_min_lamports"],w=["swap_fee_fixed_lamports","swap_fee_percent_bps"],E=["company_fee_fixed_lamports","company_fee_percent_bps"];v=v.filter(P=>P.key==="deposit_fee_policy"?!0:f==="company_pays_all"?!1:S.includes(P.key)?f==="user_pays_privacy"||f==="user_pays_all":w.includes(P.key)?f==="user_pays_swap"||f==="user_pays_all":E.includes(P.key)?f==="user_pays_all":!0)}return v},[b,h,u,f]),x=i.useCallback(v=>b.filter(S=>v.includes(S.key)).sort((S,w)=>v.indexOf(S.key)-v.indexOf(w.key)),[b]),j=i.useMemo(()=>{if(h?.id!=="deposits")return;const v={},S=parseFloat(u("deposit_min_usd"))||0,w=u("deposit_micro_enabled");return(w==="false"||w==="0"||w==="")&&S<10&&(v.deposit_min_usd="SOL micro payments must be enabled for minimum deposits under $10."),Object.keys(v).length>0?v:void 0},[h?.id,u]),y=u("feature_credits")==="true",A=()=>{d("feature_credits",y?"false":"true")};return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Credit System"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Configure credit deposits, timed withdrawals, and privacy period settings."})]}),e.jsxs("div",{className:"cedros-settings-page-header-actions",children:[e.jsxs("button",{type:"button",role:"switch","aria-checked":y,className:`cedros-toggle ${y?"cedros-toggle-on":"cedros-toggle-off"}`,onClick:A,children:[e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})}),e.jsx("span",{className:"cedros-toggle-label",children:y?"Enabled":"Disabled"})]}),e.jsx(Te,{status:n,error:o})]})]}),e.jsx("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:bt.map(v=>e.jsx("button",{type:"button",className:`cedros-admin-tab ${g===v.id?"cedros-admin-tab-active":""}`,onClick:()=>m(v.id),"aria-selected":g===v.id,role:"tab",children:v.label},v.id))}),e.jsx("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:p.length===0&&!h?.sections?.length?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsxs("p",{children:["No settings found for ",h?.label??"this section","."]})}):e.jsxs(e.Fragment,{children:[p.length>0&&e.jsx(be,{settings:p,edits:r,onChange:d,externalWarnings:j}),h?.sections?.map(v=>{const S=x(v.keys);return S.length===0?null:e.jsxs("div",{className:"cedros-settings-subsection",children:[e.jsxs("div",{className:"cedros-settings-subsection-header",children:[e.jsx("h4",{className:"cedros-settings-subsection-title",children:v.title}),v.description&&e.jsx("p",{className:"cedros-settings-subsection-description",children:v.description})]}),e.jsx(be,{settings:S,edits:r,onChange:d})]},v.title)})]})})]})}const yt=[{id:"general",label:"Integrations",keys:["server_cedros_pay_api_key"]},{id:"logging",label:"Logging",keys:["server_log_level"]},{id:"metrics",label:"Metrics",keys:["server_metrics_api_key"]},{id:"security",label:"Security",categories:["security","features"],keys:["feature_mfa","security_cors_origins","security_session_timeout"]}];function Wr({className:s}){const{settings:t,edits:r,isLoading:a,autosaveStatus:n,autosaveError:o,error:c,fetchSettings:l,handleChange:d}=Ee(),[u,g]=i.useState("general");i.useEffect(()=>{l()},[l]);const m=yt.find(b=>b.id===u),h=i.useMemo(()=>{if(!m)return[];const b=m.categories??["server"],f=[];for(const p of b){const x=t[p]??[];f.push(...x)}return f.filter(p=>m.keys.includes(p.key)).sort((p,x)=>m.keys.indexOf(p.key)-m.keys.indexOf(x.key))},[t,m]);return a&&Object.keys(t).length===0?e.jsxs("div",{className:`cedros-system-settings cedros-system-settings-loading ${s??""}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading settings..."})]}):c?e.jsx("div",{className:`cedros-system-settings ${s??""}`,children:e.jsx(N.ErrorMessage,{error:c.message})}):e.jsxs("div",{className:`cedros-system-settings ${s??""}`,children:[e.jsxs("div",{className:"cedros-settings-page-header",children:[e.jsxs("div",{className:"cedros-settings-page-header-content",children:[e.jsx("h2",{className:"cedros-settings-page-title",children:"Auth Server"}),e.jsx("p",{className:"cedros-settings-page-description",children:"Server infrastructure settings. Some may be overridden by environment variables."})]}),e.jsx(Te,{status:n,error:o})]}),e.jsx("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:yt.map(b=>e.jsx("button",{type:"button",className:`cedros-admin-tab ${u===b.id?"cedros-admin-tab-active":""}`,onClick:()=>g(b.id),"aria-selected":u===b.id,role:"tab",children:b.label},b.id))}),e.jsx("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:h.length===0?e.jsx("div",{className:"cedros-system-settings-empty",children:e.jsxs("p",{children:["No settings found for ",m?.label??"this section","."]})}):e.jsx(be,{settings:h,edits:r,onChange:d})})]})}class Bo{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async listMembers(t,r=50,a=0){try{const n=await this.client.get(`/orgs/${t}/members?limit=${r}&offset=${a}`);return{members:n.members.map(o=>({id:o.id,userId:o.userId,orgId:t,role:o.role,joinedAt:o.joinedAt,user:{id:o.userId,email:o.email,name:o.name}})),total:n.total}}catch(n){throw N.handleApiError(n,"Failed to list members")}}async updateMemberRole(t,r,a){try{return await this.client.patch(`/orgs/${t}/members/${r}`,a)}catch(n){throw N.handleApiError(n,"Failed to update member role")}}async removeMember(t,r){try{await this.client.delete(`/orgs/${t}/members/${r}`)}catch(a){throw N.handleApiError(a,"Failed to remove member")}}}function $r(s){const{config:t,authState:r,_internal:a}=N.useCedrosLogin(),[n,o]=i.useState([]),[c,l]=i.useState(0),[d,u]=i.useState(!1),[g,m]=i.useState(null),h=i.useRef(void 0),b=i.useRef(0),f=i.useMemo(()=>new Bo(t.serverUrl,t.requestTimeout,t.retryAttempts,a?.getAccessToken),[t.serverUrl,t.requestTimeout,t.retryAttempts,a]),p=i.useRef(f);p.current=f;const x=i.useCallback(async A=>{if(!s||r!=="authenticated"){o([]),l(0);return}u(!0),m(null);const v=++b.current;try{const{limit:S=50,offset:w=0}=A??{},E=await p.current.listMembers(s,S,w);if(v!==b.current)return;o(E.members),l(E.total)}catch(S){if(v!==b.current)return;m(S)}finally{v===b.current&&u(!1)}},[s,r]);i.useEffect(()=>{if(r!=="authenticated"){h.current=void 0;return}s!==h.current&&(h.current=s,x())},[s,r,x]);const j=i.useCallback(async(A,v)=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.updateMemberRole(s,A,{role:v}),await x()}catch(S){throw m(S),S}finally{u(!1)}},[s,x]),y=i.useCallback(async A=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.removeMember(s,A),await x()}catch(v){throw m(v),v}finally{u(!1)}},[s,x]);return{members:n,total:c,isLoading:d,error:g,fetchMembers:x,updateMemberRole:j,removeMember:y}}class Oo{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async listInvites(t,r=50,a=0){try{const n=await this.client.get(`/orgs/${t}/invites?limit=${r}&offset=${a}`);return{invites:n.invites.map(o=>({id:o.id,orgId:o.orgId,email:o.email,role:o.role,invitedBy:o.invitedBy,createdAt:o.createdAt,expiresAt:o.expiresAt})),total:n.total}}catch(n){throw N.handleApiError(n,"Failed to list invites")}}async createInvite(t,r){try{return await this.client.post(`/orgs/${t}/invites`,r)}catch(a){throw N.handleApiError(a,"Failed to create invite")}}async cancelInvite(t,r){try{await this.client.delete(`/orgs/${t}/invites/${r}`)}catch(a){throw N.handleApiError(a,"Failed to cancel invite")}}async resendInvite(t,r){try{await this.client.post(`/orgs/${t}/invites/${r}/resend`,{})}catch(a){throw N.handleApiError(a,"Failed to resend invite")}}async acceptInvite(t){try{return await this.client.post("/invites/accept",t)}catch(r){throw N.handleApiError(r,"Failed to accept invite")}}}function zr(s){const{config:t,authState:r,_internal:a}=N.useCedrosLogin(),[n,o]=i.useState([]),[c,l]=i.useState(0),[d,u]=i.useState(!1),[g,m]=i.useState(null),h=i.useRef(void 0),b=i.useRef(0),f=i.useMemo(()=>new Oo(t.serverUrl,t.requestTimeout,t.retryAttempts,a?.getAccessToken),[t.serverUrl,t.requestTimeout,t.retryAttempts,a]),p=i.useRef(f);p.current=f;const x=i.useCallback(async S=>{if(!s||r!=="authenticated"){o([]),l(0);return}u(!0),m(null);const w=++b.current;try{const{limit:E=50,offset:P=0}=S??{},L=await p.current.listInvites(s,E,P);if(w!==b.current)return;o(L.invites),l(L.total)}catch(E){if(w!==b.current)return;m(E)}finally{w===b.current&&u(!1)}},[s,r]);i.useEffect(()=>{if(r!=="authenticated"){h.current=void 0;return}s!==h.current&&(h.current=s,x())},[s,r,x]);const j=i.useCallback(async(S,w="member")=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.createInvite(s,{email:S,role:w}),await x()}catch(E){throw m(E),E}finally{u(!1)}},[s,x]),y=i.useCallback(async S=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.cancelInvite(s,S),await x()}catch(w){throw m(w),w}finally{u(!1)}},[s,x]),A=i.useCallback(async S=>{if(!s)throw new Error("No organization selected");u(!0),m(null);try{await p.current.resendInvite(s,S)}catch(w){throw m(w),w}finally{u(!1)}},[s]),v=i.useCallback(async S=>{u(!0),m(null);try{return await p.current.acceptInvite({token:S})}catch(w){throw m(w),w}finally{u(!1)}},[]);return{invites:n,total:c,isLoading:d,error:g,fetchInvites:x,createInvite:j,cancelInvite:y,resendInvite:A,acceptInvite:v}}const qo={organizations:!1,sso:!1,mfa:!1,walletSigning:!1,credits:!1,cedrosPay:!1};function Gs(){const{settings:s,isLoading:t,error:r,fetchSettings:a,getValue:n}=Re(),[o,c]=i.useState(!1);i.useEffect(()=>{o||(a(),c(!0))},[a,o]);const l=i.useCallback(m=>m===void 0?!1:m==="true"||m==="1",[]),d=i.useMemo(()=>Object.keys(s).length===0?qo:{organizations:l(n("feature_organizations")),sso:l(n("feature_sso")),mfa:l(n("feature_mfa")),walletSigning:l(n("feature_wallet_signing")),credits:l(n("feature_credits")),cedrosPay:l(n("feature_cedros_pay"))},[s,n,l]),u=i.useCallback(async()=>{await a()},[a]),g=i.useCallback(m=>d[m],[d]);return{features:d,isLoading:t,error:r,refetch:u,isEnabled:g}}class Wo{client;constructor(t,r,a,n){this.client=new N.ApiClient({baseUrl:t,timeoutMs:r,retryAttempts:a,getAccessToken:n})}async listUsers(t){try{const r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));const a=r.toString(),n=`/admin/users${a?`?${a}`:""}`;return await this.client.get(n)}catch(r){throw N.handleApiError(r,"Failed to list users")}}async getUser(t){try{return await this.client.get(`/admin/users/${t}`)}catch(r){throw N.handleApiError(r,"Failed to get user")}}async setSystemAdmin(t,r){try{await this.client.patch(`/admin/users/${t}/system-admin`,{isAdmin:r})}catch(a){throw N.handleApiError(a,"Failed to update system admin status")}}async updateUser(t,r){try{return await this.client.patch(`/admin/users/${t}`,r)}catch(a){throw N.handleApiError(a,"Failed to update user")}}async deleteUser(t){try{await this.client.delete(`/admin/users/${t}`)}catch(r){throw N.handleApiError(r,"Failed to delete user")}}async forcePasswordReset(t){try{await this.client.post(`/admin/users/${t}/force-password-reset`,{})}catch(r){throw N.handleApiError(r,"Failed to send password reset email")}}async adjustCredits(t,r){try{await this.client.post(`/admin/users/${t}/credits`,r)}catch(a){throw N.handleApiError(a,"Failed to adjust credits")}}async getUserDeposits(t,r){try{const a=new URLSearchParams;r?.limit&&a.set("limit",String(r.limit)),r?.offset&&a.set("offset",String(r.offset));const n=a.toString(),o=`/admin/users/${t}/deposits${n?`?${n}`:""}`;return await this.client.get(o)}catch(a){throw N.handleApiError(a,"Failed to get user deposits")}}async getUserCredits(t,r){try{const a=new URLSearchParams;r?.limit&&a.set("limit",String(r.limit)),r?.offset&&a.set("offset",String(r.offset));const n=a.toString(),o=`/admin/users/${t}/credits${n?`?${n}`:""}`;return await this.client.get(o)}catch(a){throw N.handleApiError(a,"Failed to get user credits")}}async getUserWithdrawalHistory(t,r){try{const a=new URLSearchParams;r?.limit&&a.set("limit",String(r.limit)),r?.offset&&a.set("offset",String(r.offset));const n=a.toString(),o=`/admin/users/${t}/withdrawal-history${n?`?${n}`:""}`;return await this.client.get(o)}catch(a){throw N.handleApiError(a,"Failed to get user withdrawal history")}}async getUserChats(t,r){try{const a=new URLSearchParams;r?.limit&&a.set("limit",String(r.limit)),r?.offset&&a.set("offset",String(r.offset));const n=a.toString(),o=`/admin/users/${t}/chats${n?`?${n}`:""}`;return await this.client.get(o)}catch(a){throw N.handleApiError(a,"Failed to get user chat history")}}async getStats(){try{return await this.client.get("/admin/users/stats")}catch(t){throw N.handleApiError(t,"Failed to get user stats")}}}function os(){const{config:s,_internal:t}=N.useCedrosLogin(),[r,a]=i.useState([]),[n,o]=i.useState(0),[c,l]=i.useState(!1),[d,u]=i.useState(null),[g,m]=i.useState({}),h=i.useMemo(()=>new Wo(s.serverUrl,s.requestTimeout,s.retryAttempts,t?.getAccessToken),[s.serverUrl,s.requestTimeout,s.retryAttempts,t]),b=i.useCallback(async C=>{l(!0),u(null),m(C||{});try{const k=await h.listUsers(C);return a(k.users),o(k.total),k}catch(k){const _=k instanceof Error?k:new Error("Failed to list users");throw u(_),_}finally{l(!1)}},[h]),f=i.useCallback(async C=>{l(!0),u(null);try{return await h.getUser(C)}catch(k){const _=k instanceof Error?k:new Error("Failed to get user");throw u(_),_}finally{l(!1)}},[h]),p=i.useCallback(async(C,k)=>{l(!0),u(null);try{await h.setSystemAdmin(C,k),a(_=>_.map(M=>M.id===C?{...M,isSystemAdmin:k}:M))}catch(_){const M=_ instanceof Error?_:new Error("Failed to update admin status");throw u(M),M}finally{l(!1)}},[h]),x=i.useCallback(async(C,k)=>{l(!0),u(null);try{const _=await h.updateUser(C,k);return a(M=>M.map(D=>D.id===C?_:D)),_}catch(_){const M=_ instanceof Error?_:new Error("Failed to update user");throw u(M),M}finally{l(!1)}},[h]),j=i.useCallback(async C=>{l(!0),u(null);try{await h.deleteUser(C),a(k=>k.filter(_=>_.id!==C)),o(k=>k-1)}catch(k){const _=k instanceof Error?k:new Error("Failed to delete user");throw u(_),_}finally{l(!1)}},[h]),y=i.useCallback(async C=>{l(!0),u(null);try{await h.forcePasswordReset(C)}catch(k){const _=k instanceof Error?k:new Error("Failed to send password reset");throw u(_),_}finally{l(!1)}},[h]),A=i.useCallback(async(C,k,_)=>{l(!0),u(null);try{await h.adjustCredits(C,{amount:k,reason:_})}catch(M){const D=M instanceof Error?M:new Error("Failed to adjust credits");throw u(D),D}finally{l(!1)}},[h]),v=i.useCallback(async(C,k)=>{l(!0),u(null);try{return await h.getUserDeposits(C,k)}catch(_){const M=_ instanceof Error?_:new Error("Failed to get user deposits");throw u(M),M}finally{l(!1)}},[h]),S=i.useCallback(async(C,k)=>{l(!0),u(null);try{return await h.getUserCredits(C,k)}catch(_){const M=_ instanceof Error?_:new Error("Failed to get user credits");throw u(M),M}finally{l(!1)}},[h]),w=i.useCallback(async(C,k)=>{l(!0),u(null);try{return await h.getUserWithdrawalHistory(C,k)}catch(_){const M=_ instanceof Error?_:new Error("Failed to get user withdrawal history");throw u(M),M}finally{l(!1)}},[h]),E=i.useCallback(async(C,k)=>{l(!0),u(null);try{return await h.getUserChats(C,k)}catch(_){const M=_ instanceof Error?_:new Error("Failed to get user chat history");throw u(M),M}finally{l(!1)}},[h]),P=i.useCallback(async()=>{l(!0),u(null);try{return await h.getStats()}catch(C){const k=C instanceof Error?C:new Error("Failed to get user stats");throw u(k),k}finally{l(!1)}},[h]),L=i.useCallback(async()=>{await b(g)},[b,g]),T=i.useCallback(()=>{u(null)},[]);return{users:r,total:n,isLoading:c,error:d,listUsers:b,getUser:f,setSystemAdmin:p,updateUser:x,deleteUser:j,forcePasswordReset:y,adjustCredits:A,getUserDeposits:v,getUserCredits:S,getUserWithdrawalHistory:w,getUserChats:E,getStats:P,refresh:L,clearError:T}}const $o=["users","team","deposits","withdrawals","settings-wallet","settings-auth","settings-messaging","settings-credits","settings-server"],zo=["pay-products","pay-subscriptions","pay-transactions","pay-coupons","pay-refunds","pay-storefront","pay-ai","pay-payment","pay-messaging","pay-settings"],Ae={users:"Users",team:"Team",deposits:"Deposits",withdrawals:"Withdrawals","settings-wallet":"Wallet Settings","settings-auth":"Auth Settings","settings-messaging":"Messages Settings","settings-credits":"Credits Settings","settings-server":"Server Settings","pay-products":"Products","pay-subscriptions":"Subscriptions","pay-transactions":"Transactions","pay-coupons":"Coupons","pay-refunds":"Refunds","pay-storefront":"Storefront","pay-ai":"Store AI","pay-payment":"Payment Options","pay-messaging":"Store Messages","pay-settings":"Store Server"},$e={admin:{users:!0,team:!0,deposits:!0,withdrawals:!0,"settings-wallet":!0,"settings-auth":!0,"settings-messaging":!0,"settings-credits":!0,"settings-server":!0,"pay-products":!0,"pay-subscriptions":!0,"pay-transactions":!0,"pay-coupons":!0,"pay-refunds":!0,"pay-storefront":!0,"pay-ai":!0,"pay-payment":!0,"pay-messaging":!0,"pay-settings":!0},member:{users:!1,team:!0,deposits:!1,withdrawals:!1,"settings-wallet":!1,"settings-auth":!1,"settings-messaging":!1,"settings-credits":!1,"settings-server":!1,"pay-products":!1,"pay-subscriptions":!1,"pay-transactions":!1,"pay-coupons":!1,"pay-refunds":!1,"pay-storefront":!1,"pay-ai":!1,"pay-payment":!1,"pay-messaging":!1,"pay-settings":!1}};function Vr(){const{config:s,authState:t,_internal:r}=N.useCedrosLogin(),{activeOrg:a,role:n}=as(),[o,c]=i.useState($e),[l,d]=i.useState(!1),[u,g]=i.useState(!1),[m,h]=i.useState(null),b=i.useRef(0),f=i.useMemo(()=>new N.ApiClient({baseUrl:s.serverUrl,timeoutMs:s.requestTimeout,retryAttempts:s.retryAttempts,getAccessToken:r?.getAccessToken}),[s.serverUrl,s.requestTimeout,s.retryAttempts,r]),p=i.useRef(f);p.current=f;const x=i.useCallback(async()=>{if(t!=="authenticated"||!a){c($e);return}d(!0),h(null);const A=++b.current;try{const v=await p.current.get("/admin/dashboard-permissions");if(A!==b.current)return;c(v.permissions)}catch(v){if(A!==b.current)return;if(v instanceof Error&&v.message.includes("404"))c($e);else{const S=v instanceof Error?v.message:"Failed to fetch permissions";h({code:"NETWORK_ERROR",message:S}),c($e)}}finally{A===b.current&&d(!1)}},[t,a]),j=i.useCallback(async A=>{if(t!=="authenticated"||!a)throw new Error("Not authenticated");if(n!=="owner")throw new Error("Only owners can modify dashboard permissions");g(!0),h(null);try{await p.current.request({method:"PUT",path:"/admin/dashboard-permissions",body:A}),c(A)}catch(v){const S=v instanceof Error?v.message:"Failed to update permissions";throw h({code:"NETWORK_ERROR",message:S}),new Error(S)}finally{g(!1)}},[t,a,n]),y=i.useCallback(A=>!a||!n||n==="owner"?!0:o[n]?.[A]??!1,[a,n,o]);return i.useEffect(()=>{a?.id&&x()},[a?.id,x]),{permissions:o,canAccess:y,updatePermissions:j,isLoading:l,isUpdating:u,error:m,fetchPermissions:x}}function ye(){const s=N.useCedrosLoginOptional(),[t,r]=i.useState(!1),[a,n]=i.useState(null),o=i.useMemo(()=>s?new N.ApiClient({baseUrl:s.config.serverUrl,timeoutMs:s.config.requestTimeout,retryAttempts:s.config.retryAttempts,getAccessToken:s._internal?.getAccessToken}):null,[s]),c=i.useCallback(()=>{n(null)},[]),l=i.useCallback(async p=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{const x=new URLSearchParams;p?.status&&x.set("status",p.status),p?.limit!==void 0&&x.set("limit",String(p.limit)),p?.offset!==void 0&&x.set("offset",String(p.offset));const j=x.toString(),y=j?`/admin/deposits?${j}`:"/admin/deposits";return await o.get(y)}catch(x){const j=N.handleApiError(x,"Failed to list deposits");throw n(j.message),j}finally{r(!1)}},[o]),d=i.useCallback(async()=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.get("/admin/deposits/stats")}catch(p){const x=N.handleApiError(p,"Failed to get deposit stats");throw n(x.message),x}finally{r(!1)}},[o]),u=i.useCallback(async p=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{const x=new URLSearchParams;p?.limit!==void 0&&x.set("limit",String(p.limit)),p?.offset!==void 0&&x.set("offset",String(p.offset));const j=x.toString(),y=j?`/admin/deposits/in-privacy-period?${j}`:"/admin/deposits/in-privacy-period";return await o.get(y)}catch(x){const j=N.handleApiError(x,"Failed to list deposits in privacy period");throw n(j.message),j}finally{r(!1)}},[o]),g=i.useCallback(async p=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{const x=new URLSearchParams;p?.limit!==void 0&&x.set("limit",String(p.limit)),p?.offset!==void 0&&x.set("offset",String(p.offset));const j=x.toString(),y=j?`/admin/withdrawals/pending?${j}`:"/admin/withdrawals/pending";return await o.get(y)}catch(x){const j=N.handleApiError(x,"Failed to list pending withdrawals");throw n(j.message),j}finally{r(!1)}},[o]),m=i.useCallback(async(p,x)=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.post(`/admin/withdrawals/${p}/process`,x??{})}catch(j){const y=N.handleApiError(j,"Failed to process withdrawal");throw n(y.message),y}finally{r(!1)}},[o]),h=i.useCallback(async()=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.post("/admin/withdrawals/process-all",{})}catch(p){const x=N.handleApiError(p,"Failed to process withdrawals");throw n(x.message),x}finally{r(!1)}},[o]),b=i.useCallback(async()=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.get("/admin/privacy/status")}catch(p){const x=N.handleApiError(p,"Failed to get privacy status");throw n(x.message),x}finally{r(!1)}},[o]),f=i.useCallback(async()=>{if(!o)throw new Error("useAdminDeposits must be used within a CedrosLoginProvider");r(!0),n(null);try{return await o.get("/admin/credits/stats")}catch(p){const x=N.handleApiError(p,"Failed to get credit stats");throw n(x.message),x}finally{r(!1)}},[o]);return{listDeposits:l,getStats:d,listInPrivacyPeriod:u,listPendingWithdrawals:g,processWithdrawal:m,processAllWithdrawals:h,getPrivacyStatus:b,getCreditStats:f,isLoading:t,error:a,clearError:c}}const wt={loading:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:e.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),e.jsx("path",{d:"M21 3v5h-5"}),e.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),e.jsx("path",{d:"M8 16H3v5"})]})};function Ce({stats:s,isLoading:t=!1,onRefresh:r}){return e.jsxs("div",{className:"cedros-admin__stats-bar",children:[e.jsx("div",{className:"cedros-admin__stats-bar-grid",children:s.map((a,n)=>e.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[e.jsx("span",{className:"cedros-admin__stats-bar-label",children:a.label}),e.jsx("span",{className:`cedros-admin__stats-bar-value ${a.variant?`cedros-admin__stats-bar-value--${a.variant}`:""}`,children:t?e.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):a.value}),a.description&&e.jsx("span",{className:"cedros-admin__stats-bar-desc",children:a.description})]},n))}),r&&e.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:r,disabled:t,title:"Refresh stats",children:t?wt.loading:wt.refresh})]})}function Hr({refreshInterval:s=0,className:t="",onLoad:r}){const{getStats:a,isLoading:n,error:o,clearError:c}=ye(),[l,d]=i.useState(null),[u,g]=i.useState(null),m=i.useCallback(async()=>{try{const b=await a();d(b),r?.(b),g(null)}catch(b){const f=b&&typeof b=="object"&&"message"in b?String(b.message):"Failed to load stats";g(f)}},[a,r]);i.useEffect(()=>{m()},[m]),i.useEffect(()=>{if(s<=0)return;const b=setInterval(m,s);return()=>clearInterval(b)},[s,m]);const h=u||o;return h?e.jsxs("div",{className:`cedros-admin-stats cedros-admin-stats-error ${t}`,children:[e.jsx("p",{className:"cedros-admin-error",children:h}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{c(),g(null),m()},children:"Retry"})]}):n&&!l?e.jsxs("div",{className:`cedros-admin-stats cedros-admin-stats-loading ${t}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading statistics..."})]}):l?e.jsx("div",{className:`cedros-admin-stats ${t}`,children:e.jsx(Ce,{stats:[{label:"Total Deposits",value:l.totalDeposits},{label:"Private Deposits",value:l.inPrivacyPeriodCount??0},{label:"Standard Deposits",value:l.readyForWithdrawalCount??0},{label:"Microdeposits",value:l.nativeSolDepositCount??0}],isLoading:n,onRefresh:m})}):null}function Qr({refreshInterval:s=0,className:t="",onLoad:r}){const{getStats:a,isLoading:n,error:o,clearError:c}=ye(),[l,d]=i.useState(null),[u,g]=i.useState(null),m=i.useCallback(async()=>{try{const b=await a();d(b),r?.(b),g(null)}catch(b){const f=b&&typeof b=="object"&&"message"in b?String(b.message):"Failed to load stats";g(f)}},[a,r]);i.useEffect(()=>{m()},[m]),i.useEffect(()=>{if(s<=0)return;const b=setInterval(m,s);return()=>clearInterval(b)},[s,m]);const h=u||o;return h?e.jsxs("div",{className:`cedros-admin-stats ${t}`,children:[e.jsx("p",{className:"cedros-admin-error",children:h}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{c(),g(null),m()},children:"Retry"})]}):n&&!l?e.jsx("div",{className:`cedros-admin-stats ${t}`,children:e.jsx(Ce,{stats:[{label:"Total Withdrawn",value:0},{label:"Pending Withdraw",value:0},{label:"In Privacy Period",value:0},{label:"Microbatch (SOL)",value:"0.0000"}],isLoading:!0})}):l?e.jsx("div",{className:`cedros-admin-stats ${t}`,children:e.jsx(Ce,{stats:[{label:"Total Withdrawn",value:l.totalWithdrawnCount},{label:"Pending Withdraw",value:l.pendingWithdrawalCount},{label:"In Privacy Period",value:l.inPrivacyPeriodCount??0},{label:"Microbatch (SOL)",value:l.readyForWithdrawalSol?.toFixed(4)??"0.0000"}],isLoading:n,onRefresh:m})}):null}function Vo(s){return{pending:"Pending",detected:"Detected",processing:"Processing",completed:"Completed",withdrawn:"Withdrawn",partially_withdrawn:"Partially Withdrawn",expired:"Expired",failed:"Failed"}[s]||s}function Ho(s){return s==="completed"||s==="withdrawn"||s==="partially_withdrawn"?"cedros-admin-deposit-success":s==="failed"||s==="expired"?"cedros-admin-deposit-error":s==="processing"||s==="detected"?"cedros-admin-deposit-processing":"cedros-admin-deposit-pending"}function Qo(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function Ko(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function xt(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function Kr({statusFilter:s,pageSize:t=20,refreshInterval:r=0,className:a="",onLoad:n,onDepositClick:o}){const{listDeposits:c,isLoading:l,error:d,clearError:u}=ye(),[g,m]=i.useState([]),[h,b]=i.useState(0),[f,p]=i.useState(0),[x,j]=i.useState(null),[y,A]=i.useState("createdAt"),[v,S]=i.useState("desc"),w=_=>{y===_?S(v==="asc"?"desc":"asc"):(A(_),S("desc"))},E=i.useMemo(()=>[...g].sort((_,M)=>{let D,B;switch(y){case"userId":D=_.userId.toLowerCase(),B=M.userId.toLowerCase();break;case"amountLamports":D=_.amountLamports??0,B=M.amountLamports??0;break;case"status":D=_.status,B=M.status;break;case"createdAt":D=new Date(_.createdAt).getTime(),B=new Date(M.createdAt).getTime();break;case"txSignature":D=_.txSignature||"",B=M.txSignature||"";break;default:return 0}return D<B?v==="asc"?-1:1:D>B?v==="asc"?1:-1:0}),[g,y,v]),P=i.useCallback(async()=>{try{const _=await c({status:s,limit:t,offset:f});m(_.deposits),b(_.total),n?.(_),j(null)}catch(_){const M=_&&typeof _=="object"&&"message"in _?String(_.message):"Failed to load deposits";j(M)}},[s,t,f,c,n]);i.useEffect(()=>{p(0)},[s,t]),i.useEffect(()=>{P()},[P]),i.useEffect(()=>{if(r<=0)return;const _=setInterval(P,r);return()=>clearInterval(_)},[r,P]);const L=Math.ceil(h/t),T=Math.floor(f/t)+1,C=_=>{const M=(_-1)*t;p(Math.max(0,Math.min(M,Math.max(0,h-1))))},k=x||d;return k?e.jsxs("div",{className:`cedros-admin-deposit-list cedros-admin-deposit-list-error ${a}`,children:[e.jsx("p",{className:"cedros-admin-error",children:k}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{u(),j(null),P()},children:"Retry"})]}):l&&g.length===0?e.jsxs("div",{className:`cedros-admin-deposit-list cedros-admin-deposit-list-loading ${a}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading deposits..."})]}):e.jsxs("div",{className:`cedros-admin-deposit-list ${a}`,children:[e.jsxs("div",{className:"cedros-admin-deposit-list-header",children:[e.jsx("h4",{className:"cedros-admin-deposit-list-title",children:"All Deposits"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:P,disabled:l,title:"Refresh deposits","aria-label":"Refresh deposits",children:l?"...":"↻"})]}),g.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No deposits found."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-deposit-table",children:[e.jsxs("div",{className:"cedros-admin-deposit-thead",children:[e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="userId"?"cedros-admin-sort-active":""}`,onClick:()=>w("userId"),"aria-label":"Sort by user",children:["User"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="userId"?v==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="amountLamports"?"cedros-admin-sort-active":""}`,onClick:()=>w("amountLamports"),"aria-label":"Sort by amount",children:["Amount"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="amountLamports"?v==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="status"?"cedros-admin-sort-active":""}`,onClick:()=>w("status"),"aria-label":"Sort by status",children:["Status"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="status"?v==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="createdAt"?"cedros-admin-sort-active":""}`,onClick:()=>w("createdAt"),"aria-label":"Sort by created",children:["Created"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="createdAt"?v==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-deposit-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${y==="txSignature"?"cedros-admin-sort-active":""}`,onClick:()=>w("txSignature"),"aria-label":"Sort by transaction",children:["Tx"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:y==="txSignature"?v==="asc"?"↑":"↓":"↕"})]})})]}),E.map(_=>e.jsxs("div",{className:`cedros-admin-deposit-row ${Ho(_.status)}`,onClick:()=>o?.(_),onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),o?.(_))},role:o?"button":void 0,tabIndex:o?0:void 0,children:[e.jsx("div",{className:"cedros-admin-deposit-td",title:_.userId,children:xt(_.userId)}),e.jsx("div",{className:"cedros-admin-deposit-td",children:Qo(_.amountLamports)}),e.jsx("div",{className:"cedros-admin-deposit-td",children:e.jsx("span",{className:"cedros-admin-status-badge",children:Vo(_.status)})}),e.jsx("div",{className:"cedros-admin-deposit-td",children:Ko(_.createdAt)}),e.jsx("div",{className:"cedros-admin-deposit-td",title:_.txSignature||void 0,children:_.txSignature?xt(_.txSignature):"—"})]},_.id))]}),L>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>C(T-1),disabled:T<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",T," of ",L," (",h," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>C(T+1),disabled:T>=L,children:"Next"})]})]})]})}function vt(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function jt(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function At(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function Go(s){const t=new Date(s),a=new Date().getTime()-t.getTime(),n=Math.floor(a/6e4),o=Math.floor(n/60),c=Math.floor(o/24);return c>0?`${c}d ago`:o>0?`${o}h ago`:n>0?`${n}m ago`:"just now"}function kt(s){return s?new Date(s)>new Date:!0}function Gr({pageSize:s=20,refreshInterval:t=0,className:r="",onLoad:a,onItemClick:n,onWithdrawalProcessed:o,onAllProcessed:c}){const{listPendingWithdrawals:l,processWithdrawal:d,processAllWithdrawals:u,isLoading:g,error:m,clearError:h}=ye(),[b,f]=i.useState([]),[p,x]=i.useState(0),[j,y]=i.useState(0),[A,v]=i.useState(null),[S,w]=i.useState("withdrawalAvailableAt"),[E,P]=i.useState("asc"),L=R=>{S===R?P(E==="asc"?"desc":"asc"):(w(R),P(R==="withdrawalAvailableAt"?"asc":"desc"))},T=i.useMemo(()=>[...b].sort((R,F)=>{let U,q;switch(S){case"userId":U=R.userId.toLowerCase(),q=F.userId.toLowerCase();break;case"amountLamports":U=R.amountLamports??0,q=F.amountLamports??0;break;case"withdrawalAvailableAt":U=R.withdrawalAvailableAt?new Date(R.withdrawalAvailableAt).getTime():0,q=F.withdrawalAvailableAt?new Date(F.withdrawalAvailableAt).getTime():0;break;default:return 0}return U<q?E==="asc"?-1:1:U>q?E==="asc"?1:-1:0}),[b,S,E]),[C,k]=i.useState(null),[_,M]=i.useState(!1),[D,B]=i.useState(null),[Q,Y]=i.useState(null),O=i.useCallback(async()=>{try{const R=await l({limit:s,offset:j});f(R.deposits),x(R.total),a?.(R),v(null)}catch(R){const F=R&&typeof R=="object"&&"message"in R?String(R.message):"Failed to load pending withdrawals";v(F)}},[s,j,l,a]);i.useEffect(()=>{y(0)},[s]),i.useEffect(()=>{O()},[O]),i.useEffect(()=>{if(t<=0)return;const R=setInterval(O,t);return()=>clearInterval(R)},[t,O]),i.useEffect(()=>{if(!D)return;const R=setTimeout(()=>B(null),5e3);return()=>clearTimeout(R)},[D]);const $=Math.ceil(p/s),I=Math.floor(j/s)+1,H=R=>{const F=(R-1)*s;y(Math.max(0,Math.min(F,Math.max(0,p-1))))},ee=async(R,F=!1)=>{if(!F&&kt(R.withdrawalAvailableAt)){Y(R);return}k(R.id),B(null);try{const U=await d(R.id,{force:F});U.success?(B({type:"success",message:`Withdrawal processed: ${U.txSignature?.slice(0,12)}...`}),o?.(U),await O()):B({type:"error",message:U.error||"Failed to process withdrawal"})}catch(U){B({type:"error",message:U instanceof Error?U.message:"Failed to process withdrawal"})}finally{k(null),Y(null)}},Z=async()=>{if(b.length!==0){M(!0),B(null);try{const R=await u();R.totalSucceeded>0?B({type:"success",message:`Processed ${R.totalSucceeded}/${R.totalProcessed} withdrawals`}):R.totalFailed>0&&B({type:"error",message:`Failed to process ${R.totalFailed} withdrawals`}),c?.(R),await O()}catch(R){B({type:"error",message:R instanceof Error?R.message:"Failed to process withdrawals"})}finally{M(!1)}}},K=A||m;return K?e.jsxs("div",{className:`cedros-admin-withdrawal-queue cedros-admin-withdrawal-queue-error ${r}`,children:[e.jsx("p",{className:"cedros-admin-error",children:K}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{h(),v(null),O()},children:"Retry"})]}):g&&b.length===0&&!C&&!_?e.jsxs("div",{className:`cedros-admin-withdrawal-queue cedros-admin-withdrawal-queue-loading ${r}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading withdrawal queue..."})]}):e.jsxs("div",{className:`cedros-admin-withdrawal-queue ${r}`,children:[Q&&e.jsx("div",{className:"cedros-admin-modal-overlay",onClick:()=>Y(null),onKeyDown:R=>R.key==="Escape"&&Y(null),role:"dialog","aria-modal":"true","aria-labelledby":"early-withdrawal-title",children:e.jsxs("div",{className:"cedros-admin-modal cedros-admin-modal-warning",onClick:R=>R.stopPropagation(),onKeyDown:()=>{},role:"document",children:[e.jsx("h3",{id:"early-withdrawal-title",className:"cedros-admin-modal-title",children:"Early Withdrawal Warning"}),e.jsxs("div",{className:"cedros-admin-modal-content",children:[e.jsx("p",{className:"cedros-admin-modal-warning-text",children:e.jsx("strong",{children:"This deposit is still within its privacy period."})}),e.jsx("p",{children:"Processing this withdrawal early may compromise user privacy. The privacy period exists to provide plausible deniability for deposits."}),e.jsxs("p",{className:"cedros-admin-modal-details",children:["User: ",At(Q.userId),e.jsx("br",{}),"Amount: ",vt(Q.amountLamports),e.jsx("br",{}),"Available at:"," ",Q.withdrawalAvailableAt?jt(Q.withdrawalAvailableAt):"—"]}),e.jsx("p",{children:"Are you sure you want to process this withdrawal early?"})]}),e.jsxs("div",{className:"cedros-admin-modal-actions",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>Y(null),children:"Cancel"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-danger",onClick:()=>ee(Q,!0),disabled:C===Q.id,children:C===Q.id?"Processing...":"Process Early"})]})]})}),D&&e.jsx("div",{className:`cedros-admin-result cedros-admin-result-${D.type}`,role:"status","aria-live":"polite",children:D.message}),e.jsxs("div",{className:"cedros-admin-withdrawal-queue-header",children:[e.jsx("h4",{className:"cedros-admin-withdrawal-queue-title",children:"Pending Withdrawals"}),e.jsxs("div",{className:"cedros-admin-withdrawal-queue-actions",children:[e.jsxs("span",{className:"cedros-admin-queue-count",children:[p," pending"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:O,disabled:g||_,title:"Refresh queue","aria-label":"Refresh queue",children:g&&!_?"...":"↻"}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-primary cedros-button-sm",onClick:Z,disabled:g||_||b.length===0,title:"Process all ready withdrawals",children:_?"Processing...":"Process All"})]})]}),b.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No pending withdrawals."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-withdrawal-table",children:[e.jsxs("div",{className:"cedros-admin-withdrawal-thead",children:[e.jsx("div",{className:"cedros-admin-withdrawal-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${S==="userId"?"cedros-admin-sort-active":""}`,onClick:()=>L("userId"),"aria-label":"Sort by user",children:["User"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:S==="userId"?E==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-withdrawal-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${S==="amountLamports"?"cedros-admin-sort-active":""}`,onClick:()=>L("amountLamports"),"aria-label":"Sort by amount",children:["Amount"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:S==="amountLamports"?E==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-withdrawal-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${S==="withdrawalAvailableAt"?"cedros-admin-sort-active":""}`,onClick:()=>L("withdrawalAvailableAt"),"aria-label":"Sort by ready since",children:["Ready Since"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:S==="withdrawalAvailableAt"?E==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-withdrawal-th",children:"Waiting"}),e.jsx("div",{className:"cedros-admin-withdrawal-th cedros-admin-withdrawal-th-action",children:"Action"})]}),T.map(R=>{const F=kt(R.withdrawalAvailableAt),U=C===R.id;return e.jsxs("div",{className:`cedros-admin-withdrawal-row ${F?"cedros-admin-withdrawal-row-early":""}`,onClick:()=>n?.(R),onKeyDown:q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),n?.(R))},role:n?"button":void 0,tabIndex:n?0:void 0,children:[e.jsx("div",{className:"cedros-admin-withdrawal-td",title:R.userId,children:At(R.userId)}),e.jsx("div",{className:"cedros-admin-withdrawal-td",children:vt(R.amountLamports)}),e.jsx("div",{className:"cedros-admin-withdrawal-td",children:R.withdrawalAvailableAt?jt(R.withdrawalAvailableAt):"—"}),e.jsx("div",{className:"cedros-admin-withdrawal-td cedros-admin-withdrawal-waiting",children:R.withdrawalAvailableAt?F?"In privacy period":Go(R.withdrawalAvailableAt):"—"}),e.jsx("div",{className:"cedros-admin-withdrawal-td cedros-admin-withdrawal-td-action",children:e.jsx("button",{type:"button",className:`cedros-button cedros-button-sm ${F?"cedros-button-warning":"cedros-button-primary"}`,onClick:q=>{q.stopPropagation(),ee(R)},disabled:U||_,title:F?"Early withdrawal (requires confirmation)":"Process this withdrawal",children:U?"...":F?"Early":"Process"})})]},R.id)})]}),$>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>H(I-1),disabled:I<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",I," of ",$," (",p," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>H(I+1),disabled:I>=$,children:"Next"})]})]})]})}function Yo(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function Jo(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Xo(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function Zo(s){const t=new Date(s),r=new Date,a=t.getTime()-r.getTime();if(a<=0)return"Ready";const n=Math.floor(a/6e4),o=Math.floor(n/60),c=Math.floor(o/24);if(c>0){const l=o%24;return l>0?`${c}d ${l}h`:`${c}d`}if(o>0){const l=n%60;return l>0?`${o}h ${l}m`:`${o}h`}return`${n}m`}function Yr({pageSize:s=20,refreshInterval:t=0,className:r="",onLoad:a,onItemClick:n}){const{listInPrivacyPeriod:o,isLoading:c,error:l,clearError:d}=ye(),[u,g]=i.useState([]),[m,h]=i.useState(0),[b,f]=i.useState(0),[p,x]=i.useState(null),j=i.useCallback(async()=>{try{const w=await o({limit:s,offset:b});g(w.deposits),h(w.total),a?.(w),x(null)}catch(w){const E=w&&typeof w=="object"&&"message"in w?String(w.message):"Failed to load deposits";x(E)}},[s,b,o,a]);i.useEffect(()=>{f(0)},[s]),i.useEffect(()=>{j()},[j]),i.useEffect(()=>{if(t<=0)return;const w=setInterval(j,t);return()=>clearInterval(w)},[t,j]);const y=Math.ceil(m/s),A=Math.floor(b/s)+1,v=w=>{const E=(w-1)*s;f(Math.max(0,Math.min(E,Math.max(0,m-1))))},S=p||l;return S?e.jsxs("div",{className:`cedros-admin-privacy-deposits cedros-admin-privacy-deposits-error ${r}`,children:[e.jsx("p",{className:"cedros-admin-error",children:S}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{d(),x(null),j()},children:"Retry"})]}):c&&u.length===0?e.jsxs("div",{className:`cedros-admin-privacy-deposits cedros-admin-privacy-deposits-loading ${r}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading deposits..."})]}):e.jsxs("div",{className:`cedros-admin-privacy-deposits ${r}`,children:[e.jsxs("div",{className:"cedros-admin-privacy-deposits-header",children:[e.jsx("h4",{className:"cedros-admin-privacy-deposits-title",children:"In Privacy Period"}),e.jsxs("div",{className:"cedros-admin-privacy-deposits-actions",children:[e.jsxs("span",{className:"cedros-admin-queue-count",children:[m," deposit",m!==1?"s":""]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:j,disabled:c,title:"Refresh list","aria-label":"Refresh list",children:c?"...":"↻"})]})]}),u.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No deposits in privacy period."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-privacy-table",children:[e.jsxs("div",{className:"cedros-admin-privacy-thead",children:[e.jsx("div",{className:"cedros-admin-privacy-th",children:e.jsxs("button",{type:"button",className:"cedros-admin-sort-button","aria-label":"Sort by user",children:["User ",e.jsx("span",{className:"cedros-admin-sort-icon",children:"↕"})]})}),e.jsx("div",{className:"cedros-admin-privacy-th",children:e.jsxs("button",{type:"button",className:"cedros-admin-sort-button","aria-label":"Sort by amount",children:["Amount ",e.jsx("span",{className:"cedros-admin-sort-icon",children:"↕"})]})}),e.jsx("div",{className:"cedros-admin-privacy-th",children:e.jsxs("button",{type:"button",className:"cedros-admin-sort-button","aria-label":"Sort by deposited",children:["Deposited ",e.jsx("span",{className:"cedros-admin-sort-icon",children:"↕"})]})}),e.jsx("div",{className:"cedros-admin-privacy-th",children:e.jsxs("button",{type:"button",className:"cedros-admin-sort-button","aria-label":"Sort by ready in",children:["Ready In ",e.jsx("span",{className:"cedros-admin-sort-icon",children:"↕"})]})})]}),u.map(w=>e.jsxs("div",{className:"cedros-admin-privacy-row",onClick:()=>n?.(w),onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),n?.(w))},role:n?"button":void 0,tabIndex:n?0:void 0,children:[e.jsx("div",{className:"cedros-admin-privacy-td",title:w.userId,children:Xo(w.userId)}),e.jsx("div",{className:"cedros-admin-privacy-td",children:Yo(w.amountLamports)}),e.jsx("div",{className:"cedros-admin-privacy-td",children:w.completedAt?Jo(w.completedAt):"—"}),e.jsx("div",{className:"cedros-admin-privacy-td cedros-admin-privacy-remaining",children:w.withdrawalAvailableAt?Zo(w.withdrawalAvailableAt):"—"})]},w.id))]}),y>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>v(A-1),disabled:A<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",A," of ",y," (",m," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>v(A+1),disabled:A>=y,children:"Next"})]})]})]})}function ei(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function si(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ti(s){return s.length<=16?s:`${s.slice(0,8)}...${s.slice(-6)}`}function ri(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function Jr({pageSize:s=20,refreshInterval:t=0,className:r="",onLoad:a,onItemClick:n}){const{listDeposits:o,isLoading:c,error:l,clearError:d}=ye(),[u,g]=i.useState([]),[m,h]=i.useState(0),[b,f]=i.useState(0),[p,x]=i.useState(null),[j,y]=i.useState("completedAt"),[A,v]=i.useState("desc"),S=k=>{j===k?v(A==="asc"?"desc":"asc"):(y(k),v("desc"))},w=i.useMemo(()=>[...u].sort((k,_)=>{let M,D;switch(j){case"userId":M=k.userId.toLowerCase(),D=_.userId.toLowerCase();break;case"amountLamports":M=k.amountLamports??0,D=_.amountLamports??0;break;case"completedAt":M=k.completedAt?new Date(k.completedAt).getTime():0,D=_.completedAt?new Date(_.completedAt).getTime():0;break;case"withdrawalTxSignature":M=k.withdrawalTxSignature||"",D=_.withdrawalTxSignature||"";break;default:return 0}return M<D?A==="asc"?-1:1:M>D?A==="asc"?1:-1:0}),[u,j,A]),E=i.useCallback(async()=>{try{const k=await o({status:"withdrawn",limit:s,offset:b});g(k.deposits),h(k.total),a?.(k),x(null)}catch(k){const _=k&&typeof k=="object"&&"message"in k?String(k.message):"Failed to load withdrawal history";x(_)}},[s,b,o,a]);i.useEffect(()=>{f(0)},[s]),i.useEffect(()=>{E()},[E]),i.useEffect(()=>{if(t<=0)return;const k=setInterval(E,t);return()=>clearInterval(k)},[t,E]);const P=Math.ceil(m/s),L=Math.floor(b/s)+1,T=k=>{const _=(k-1)*s;f(Math.max(0,Math.min(_,Math.max(0,m-1))))},C=p||l;return C?e.jsxs("div",{className:`cedros-admin-withdrawal-history cedros-admin-withdrawal-history-error ${r}`,children:[e.jsx("p",{className:"cedros-admin-error",children:C}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{d(),x(null),E()},children:"Retry"})]}):c&&u.length===0?e.jsxs("div",{className:`cedros-admin-withdrawal-history cedros-admin-withdrawal-history-loading ${r}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading withdrawal history..."})]}):e.jsxs("div",{className:`cedros-admin-withdrawal-history ${r}`,children:[e.jsxs("div",{className:"cedros-admin-withdrawal-history-header",children:[e.jsx("h4",{className:"cedros-admin-withdrawal-history-title",children:"Withdrawal History"}),e.jsxs("div",{className:"cedros-admin-withdrawal-history-actions",children:[e.jsxs("span",{className:"cedros-admin-queue-count",children:[m," withdrawal",m!==1?"s":""]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:E,disabled:c,title:"Refresh list","aria-label":"Refresh list",children:c?"...":"↻"})]})]}),u.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No withdrawals processed yet."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-history-table",children:[e.jsxs("div",{className:"cedros-admin-history-thead",children:[e.jsx("div",{className:"cedros-admin-history-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${j==="userId"?"cedros-admin-sort-active":""}`,onClick:()=>S("userId"),"aria-label":"Sort by user",children:["User"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:j==="userId"?A==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-history-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${j==="amountLamports"?"cedros-admin-sort-active":""}`,onClick:()=>S("amountLamports"),"aria-label":"Sort by amount",children:["Amount"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:j==="amountLamports"?A==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-history-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${j==="completedAt"?"cedros-admin-sort-active":""}`,onClick:()=>S("completedAt"),"aria-label":"Sort by processed",children:["Processed"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:j==="completedAt"?A==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-history-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${j==="withdrawalTxSignature"?"cedros-admin-sort-active":""}`,onClick:()=>S("withdrawalTxSignature"),"aria-label":"Sort by transaction",children:["Transaction"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:j==="withdrawalTxSignature"?A==="asc"?"↑":"↓":"↕"})]})})]}),w.map(k=>e.jsxs("div",{className:"cedros-admin-history-row",onClick:()=>n?.(k),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),n?.(k))},role:n?"button":void 0,tabIndex:n?0:void 0,children:[e.jsx("div",{className:"cedros-admin-history-td",title:k.userId,children:ri(k.userId)}),e.jsx("div",{className:"cedros-admin-history-td",children:ei(k.amountLamports)}),e.jsx("div",{className:"cedros-admin-history-td",children:k.completedAt?si(k.completedAt):"—"}),e.jsx("div",{className:"cedros-admin-history-td",children:k.withdrawalTxSignature?e.jsx("a",{href:`https://orbmarkets.io/tx/${k.withdrawalTxSignature}`,target:"_blank",rel:"noopener noreferrer",className:"cedros-admin-tx-link",onClick:_=>_.stopPropagation(),title:k.withdrawalTxSignature,children:ti(k.withdrawalTxSignature)}):"—"})]},k.id))]}),P>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>T(L-1),disabled:L<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",L," of ",P," (",m," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>T(L+1),disabled:L>=P,children:"Next"})]})]})]})}function Nt(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ni(s){return s.length<=12?s:`${s.slice(0,6)}...${s.slice(-4)}`}function ai(s){return s==null?"-":(s/1e9).toFixed(4)}function Xr({pageSize:s=20,refreshInterval:t=0,currentUserId:r,className:a="",onLoad:n,onUserClick:o}){const{users:c,total:l,isLoading:d,error:u,listUsers:g,clearError:m}=os(),[h,b]=i.useState(0),[f,p]=i.useState(null),[x,j]=i.useState("createdAt"),[y,A]=i.useState("desc"),v=T=>{x===T?A(y==="asc"?"desc":"asc"):(j(T),A("desc"))},S=i.useMemo(()=>[...c].sort((T,C)=>{let k,_;switch(x){case"name":k=(T.name||T.email||"").toLowerCase(),_=(C.name||C.email||"").toLowerCase();break;case"createdAt":k=new Date(T.createdAt).getTime(),_=new Date(C.createdAt).getTime();break;case"lastLoginAt":k=T.lastLoginAt?new Date(T.lastLoginAt).getTime():0,_=C.lastLoginAt?new Date(C.lastLoginAt).getTime():0;break;case"balanceLamports":k=T.balanceLamports??0,_=C.balanceLamports??0;break;default:return 0}return k<_?y==="asc"?-1:1:k>_?y==="asc"?1:-1:0}),[c,x,y]),w=i.useCallback(async()=>{try{const T=await g({limit:s,offset:h});n?.(T),p(null)}catch(T){p(T instanceof Error?T.message:"Failed to load users")}},[s,h,g,n]);i.useEffect(()=>{b(0)},[s]),i.useEffect(()=>{w()},[w]),i.useEffect(()=>{if(t<=0)return;const T=setInterval(w,t);return()=>clearInterval(T)},[t,w]);const E=Math.ceil(l/s),P=Math.floor(h/s)+1,L=T=>{const C=(T-1)*s;b(Math.max(0,Math.min(C,Math.max(0,l-1))))};return f||u?e.jsxs("div",{className:`cedros-admin-user-list cedros-admin-user-list-error ${a}`,children:[e.jsx("p",{className:"cedros-admin-error",children:f||u?.message}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{m(),p(null),w()},children:"Retry"})]}):d&&c.length===0?e.jsxs("div",{className:`cedros-admin-user-list cedros-admin-user-list-loading ${a}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading users..."})]}):e.jsxs("div",{className:`cedros-admin-user-list ${a}`,children:[e.jsxs("div",{className:"cedros-admin-user-list-header",children:[e.jsx("h4",{className:"cedros-admin-user-list-title",children:"All Users"}),e.jsxs("div",{className:"cedros-admin-user-list-actions",children:[e.jsxs("span",{className:"cedros-admin-queue-count",children:[l," user",l!==1?"s":""]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-icon-button",onClick:w,disabled:d,title:"Refresh list","aria-label":"Refresh list",children:d?"...":"↻"})]})]}),c.length===0?e.jsx("div",{className:"cedros-admin-empty",children:e.jsx("p",{className:"cedros-admin-empty-message",children:"No users found."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-user-table",children:[e.jsxs("div",{className:"cedros-admin-user-thead",children:[e.jsx("div",{className:"cedros-admin-user-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${x==="name"?"cedros-admin-sort-active":""}`,onClick:()=>v("name"),"aria-label":"Sort by user",children:["User"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:x==="name"?y==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-user-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${x==="createdAt"?"cedros-admin-sort-active":""}`,onClick:()=>v("createdAt"),"aria-label":"Sort by registered date",children:["Registered"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:x==="createdAt"?y==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-user-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${x==="lastLoginAt"?"cedros-admin-sort-active":""}`,onClick:()=>v("lastLoginAt"),"aria-label":"Sort by last login",children:["Last Login"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:x==="lastLoginAt"?y==="asc"?"↑":"↓":"↕"})]})}),e.jsx("div",{className:"cedros-admin-user-th",children:e.jsxs("button",{type:"button",className:`cedros-admin-sort-button ${x==="balanceLamports"?"cedros-admin-sort-active":""}`,onClick:()=>v("balanceLamports"),"aria-label":"Sort by balance",children:["Balance"," ",e.jsx("span",{className:"cedros-admin-sort-icon",children:x==="balanceLamports"?y==="asc"?"↑":"↓":"↕"})]})})]}),S.map(T=>{const C=T.id===r;return e.jsxs("div",{className:`cedros-admin-user-row ${C?"cedros-admin-user-row-current":""}`,onClick:()=>o?.(T),onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),o?.(T))},role:o?"button":void 0,tabIndex:o?0:void 0,children:[e.jsxs("div",{className:"cedros-admin-user-td cedros-admin-user-info",children:[e.jsx("div",{className:"cedros-admin-user-avatar",children:T.picture?e.jsx("img",{src:T.picture,alt:T.name||T.email||"User",className:"cedros-admin-user-avatar-img",referrerPolicy:"no-referrer"}):e.jsx("span",{className:"cedros-admin-user-avatar-placeholder",children:(T.name?.[0]||T.email?.[0]||"?").toUpperCase()})}),e.jsxs("div",{className:"cedros-admin-user-details",children:[e.jsxs("span",{className:"cedros-admin-user-name",children:[T.name||"Unknown",C&&e.jsx("span",{className:"cedros-admin-user-you",children:"(you)"})]}),e.jsx("span",{className:"cedros-admin-user-email",title:T.email,children:T.email||ni(T.id)})]})]}),e.jsx("div",{className:"cedros-admin-user-td",children:Nt(T.createdAt)}),e.jsx("div",{className:"cedros-admin-user-td",children:T.lastLoginAt?Nt(T.lastLoginAt):"-"}),e.jsx("div",{className:"cedros-admin-user-td",children:ai(T.balanceLamports)})]},T.id)})]}),E>1&&e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>L(P-1),disabled:P<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",P," of ",E," (",l," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>L(P+1),disabled:P>=E,children:"Next"})]})]})]})}function St(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Ys(s){return new Date(s).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function oi(s){return s==null?"—":`${(s/1e9).toFixed(4)} SOL`}function He(s){return s==null?"—":(s/1e9).toFixed(4)}function ii(s){return{DEPOSIT:"Deposit",SPEND:"Spend",ADJUSTMENT:"Adjustment",REFUND:"Refund"}[s.toUpperCase()]||s}function li(s,t){return t?{deposit:"Credit deposit",purchase:"Purchase",api_call:"API usage",subscription:"Subscription",refund:"Refund",bonus:"Bonus credit",promo:"Promotional credit",correction:"Balance correction"}[t.toLowerCase()]||t:{DEPOSIT:"Credit added",SPEND:"Credit used",ADJUSTMENT:"Manual adjustment",REFUND:"Credit refunded"}[s.toUpperCase()]||"—"}function Zr({userId:s,onBack:t,currentUserId:r,onEditUser:a,onAdjustCredits:n,cedrosPayEnabled:o=!1,className:c=""}){const{isLoading:l,getUser:d,getUserDeposits:u,getUserCredits:g,getUserChats:m,deleteUser:h,forcePasswordReset:b,clearError:f}=os(),[p,x]=i.useState(null),[j,y]=i.useState(null),[A,v]=i.useState(null),[S,w]=i.useState(null),[E,P]=i.useState("deposits"),[L,T]=i.useState(null),[C,k]=i.useState(null),[_,M]=i.useState(null),[D,B]=i.useState(null),[Q,Y]=i.useState(!1),[O,$]=i.useState(0),[I,H]=i.useState(0),[ee,Z]=i.useState(0),K=10,R=i.useCallback(async()=>{try{const z=await d(s);x(z),T(null)}catch(z){T(z instanceof Error?z.message:"Failed to load user")}},[s,d]),F=i.useCallback(async()=>{try{const he=await u(s,{limit:K,offset:O});v(he),M(null)}catch(z){M(z instanceof Error?z.message:"Failed to load deposits")}},[s,u,O]),U=i.useCallback(async()=>{try{const he=await g(s,{limit:K,offset:I});y(he),k(null)}catch(z){k(z instanceof Error?z.message:"Failed to load credits")}},[s,g,I]),q=i.useCallback(async()=>{if(o)try{const he=await m(s,{limit:K,offset:ee});w(he),B(null)}catch(z){B(z instanceof Error?z.message:"Failed to load chat history")}},[s,m,ee,o]);i.useEffect(()=>{R(),F(),U(),o&&q()},[R,F,U,q,o]);const re=async()=>{if(!p)return;if(p.id===r){alert("You cannot delete your own account");return}if(p.isSystemAdmin){alert("Cannot delete a system admin. Remove admin status first.");return}if(window.confirm(`Are you sure you want to delete ${p.name||p.email||"this user"}? This action cannot be undone.`)){Y(!0);try{await h(p.id),t()}catch{}finally{Y(!1)}}},de=async()=>{if(!p?.email){alert("User has no email address");return}if(window.confirm(`Send a password reset email to ${p.email}?`)){Y(!0);try{await b(p.id),alert("Password reset email sent")}catch{}finally{Y(!1)}}},Ie=A?Math.ceil(A.total/K):0,Pe=Math.floor(O/K)+1,fe=j?Math.ceil(j.totalTransactions/K):0,cs=Math.floor(I/K)+1,Le=z=>{$((z-1)*K)},ve=z=>{H((z-1)*K)},Ue=S?Math.ceil(S.total/K):0,ds=Math.floor(ee/K)+1,us=z=>{Z((z-1)*K)};if(L)return e.jsxs("div",{className:`cedros-admin-user-detail cedros-admin-user-detail-error ${c}`,children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:t,children:"Back"}),e.jsx("p",{className:"cedros-admin-error",children:L}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline",onClick:()=>{f(),T(null),R()},children:"Retry"})]});if(l&&!p)return e.jsxs("div",{className:`cedros-admin-user-detail cedros-admin-user-detail-loading ${c}`,children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{className:"cedros-admin-loading-text",children:"Loading user..."})]});if(!p)return e.jsxs("div",{className:`cedros-admin-user-detail ${c}`,children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:t,children:"Back"}),e.jsx("p",{className:"cedros-admin-empty-message",children:"User not found."})]});const ge=p.id===r;return e.jsxs("div",{className:`cedros-admin-user-detail ${c}`,children:[e.jsxs("div",{className:"cedros-admin-user-detail-header",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-back-btn",onClick:t,children:"Back to Users"}),e.jsxs("div",{className:"cedros-admin-user-detail-actions",children:[a&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>a(p),disabled:Q,children:"Edit"}),p.email&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:de,disabled:Q,children:"Reset Password"}),n&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>n(p),disabled:Q,children:"Adjust Credits"}),!ge&&!p.isSystemAdmin&&e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm cedros-admin-btn-danger",onClick:re,disabled:Q,children:"Delete"})]})]}),e.jsxs("div",{className:"cedros-admin-user-detail-info",children:[e.jsx("div",{className:"cedros-admin-user-detail-avatar",children:p.picture?e.jsx("img",{src:p.picture,alt:p.name||p.email||"User",className:"cedros-admin-user-detail-avatar-img",referrerPolicy:"no-referrer"}):e.jsx("span",{className:"cedros-admin-user-detail-avatar-placeholder",children:(p.name?.[0]||p.email?.[0]||"?").toUpperCase()})}),e.jsxs("div",{className:"cedros-admin-user-detail-meta",children:[e.jsxs("h2",{className:"cedros-admin-user-detail-name",children:[p.name||"Unknown",ge&&e.jsx("span",{className:"cedros-admin-user-you",children:"(you)"})]}),e.jsxs("p",{className:"cedros-admin-user-detail-email",children:[p.email||"No email",p.emailVerified&&e.jsx("span",{className:"cedros-admin-verified-badge",title:"Email verified",children:"Verified"})]}),p.isSystemAdmin&&e.jsx("div",{className:"cedros-admin-user-detail-badges",children:e.jsx("span",{className:"cedros-admin-admin-badge cedros-admin-admin-badge-yes",children:"System Admin"})}),e.jsxs("div",{className:"cedros-admin-user-detail-methods",children:[e.jsx("span",{className:"cedros-admin-user-detail-methods-label",children:"Auth Methods:"}),p.authMethods.length>0?p.authMethods.map(z=>e.jsx("span",{className:`cedros-admin-auth-badge cedros-admin-auth-badge-${z}`,children:z},z)):e.jsx("span",{className:"cedros-admin-auth-badge cedros-admin-auth-badge-none",children:"none"})]}),e.jsxs("p",{className:"cedros-admin-user-detail-dates",children:["Registered: ",St(p.createdAt)," | Updated: ",St(p.updatedAt)]})]})]}),C?e.jsxs("div",{className:"cedros-admin-stats-error",children:[e.jsx("p",{className:"cedros-admin-error-inline",children:C}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>{k(null),U()},children:"Retry"})]}):j?e.jsxs("div",{className:"cedros-admin-user-detail-stats",children:[e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Credit Balance"}),e.jsx("span",{className:"cedros-admin-stat-value",children:He(j.stats.currentBalanceLamports)})]}),e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Total Credited"}),e.jsx("span",{className:"cedros-admin-stat-value",children:He(j.stats.totalDepositedLamports)})]}),e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Total Spent"}),e.jsx("span",{className:"cedros-admin-stat-value",children:He(j.stats.totalSpentLamports)})]}),e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Deposits"}),e.jsx("span",{className:"cedros-admin-stat-value",children:j.stats.depositCount})]}),e.jsxs("div",{className:"cedros-admin-stat-card",children:[e.jsx("span",{className:"cedros-admin-stat-label",children:"Transactions"}),e.jsx("span",{className:"cedros-admin-stat-value",children:j.stats.spendCount})]})]}):e.jsxs("div",{className:"cedros-admin-stats-loading",children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{children:"Loading credit stats..."})]}),e.jsxs("div",{className:"cedros-admin-user-detail-tabs",children:[e.jsxs("button",{type:"button",className:`cedros-admin-tab ${E==="deposits"?"cedros-admin-tab-active":""}`,onClick:()=>P("deposits"),children:["Deposits (",A?.total??0,")"]}),e.jsxs("button",{type:"button",className:`cedros-admin-tab ${E==="transactions"?"cedros-admin-tab-active":""}`,onClick:()=>P("transactions"),children:["Credits (",j?.totalTransactions??0,")"]}),o&&e.jsxs("button",{type:"button",className:`cedros-admin-tab ${E==="chats"?"cedros-admin-tab-active":""}`,onClick:()=>P("chats"),children:["Chats (",S?.total??0,")"]})]}),e.jsxs("div",{className:"cedros-admin-user-detail-content",children:[E==="deposits"&&e.jsx(ci,{deposits:A?.deposits??[],total:A?.total??0,currentPage:Pe,totalPages:Ie,onPageChange:Le,isLoading:l,error:_,onRetry:()=>{M(null),F()}}),E==="transactions"&&e.jsx(di,{transactions:j?.transactions??[],total:j?.totalTransactions??0,currentPage:cs,totalPages:fe,onPageChange:ve,error:C,onRetry:()=>{k(null),U()},isLoading:l}),E==="chats"&&o&&e.jsx(ui,{sessions:S?.sessions??[],total:S?.total??0,currentPage:ds,totalPages:Ue,onPageChange:us,error:D,onRetry:()=>{B(null),q()},isLoading:l})]})]})}function ci({deposits:s,total:t,currentPage:r,totalPages:a,onPageChange:n,isLoading:o,error:c,onRetry:l}){return c?e.jsxs("div",{className:"cedros-admin-tab-error",children:[e.jsx("p",{className:"cedros-admin-error-inline",children:c}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:l,children:"Retry"})]}):o&&s.length===0?e.jsxs("div",{className:"cedros-admin-tab-loading",children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{children:"Loading deposits..."})]}):t===0?e.jsx("div",{className:"cedros-admin-empty-message",children:"No deposits found."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-list-table",children:[e.jsxs("div",{className:"cedros-admin-list-thead",children:[e.jsx("div",{className:"cedros-admin-list-th",children:"Date"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Amount"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Status"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Transaction"})]}),s.map(d=>e.jsxs("div",{className:"cedros-admin-list-row",children:[e.jsx("div",{className:"cedros-admin-list-td",children:Ys(d.createdAt)}),e.jsx("div",{className:"cedros-admin-list-td",children:oi(d.amountLamports)}),e.jsx("div",{className:"cedros-admin-list-td",children:e.jsx("span",{className:`cedros-admin-status-badge cedros-admin-status-${d.status}`,children:d.status})}),e.jsx("div",{className:"cedros-admin-list-td cedros-admin-list-td-actions",children:d.txSignature?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"cedros-admin-list-td-mono",title:d.txSignature,children:[d.txSignature.slice(0,8),"..."]}),e.jsx("a",{href:`https://orbmarkets.io/tx/${d.txSignature}`,target:"_blank",rel:"noopener noreferrer",className:"cedros-admin-icon-link",title:"View on Orbmarkets","aria-label":"View transaction on Orbmarkets",children:"↗"})]}):e.jsx("span",{className:"cedros-admin-list-td-muted",children:"—"})})]},d.id))]}),a>1&&e.jsx(Js,{currentPage:r,totalPages:a,total:t,onPageChange:n})]})}function di({transactions:s,total:t,currentPage:r,totalPages:a,onPageChange:n,isLoading:o,error:c,onRetry:l}){return c?e.jsxs("div",{className:"cedros-admin-tab-error",children:[e.jsx("p",{className:"cedros-admin-error-inline",children:c}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:l,children:"Retry"})]}):o&&s.length===0?e.jsxs("div",{className:"cedros-admin-tab-loading",children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{children:"Loading transactions..."})]}):t===0?e.jsx("div",{className:"cedros-admin-empty-message",children:"No credit transactions found."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-list-table",children:[e.jsxs("div",{className:"cedros-admin-list-thead",children:[e.jsx("div",{className:"cedros-admin-list-th",children:"Date"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Type"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Description"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Amount"})]}),s.map(d=>e.jsxs("div",{className:"cedros-admin-list-row",children:[e.jsx("div",{className:"cedros-admin-list-td",children:Ys(d.createdAt)}),e.jsx("div",{className:"cedros-admin-list-td",children:e.jsx("span",{className:`cedros-admin-tx-type cedros-admin-tx-type-${d.txType.toLowerCase()}`,children:ii(d.txType)})}),e.jsx("div",{className:"cedros-admin-list-td",children:li(d.txType,d.referenceType)}),e.jsxs("div",{className:`cedros-admin-list-td ${d.amountLamports>=0?"cedros-admin-amount-positive":"cedros-admin-amount-negative"}`,children:[d.amountLamports>=0?"+":"",He(d.amountLamports)]})]},d.id))]}),a>1&&e.jsx(Js,{currentPage:r,totalPages:a,total:t,onPageChange:n})]})}function ui({sessions:s,total:t,currentPage:r,totalPages:a,onPageChange:n,isLoading:o,error:c,onRetry:l}){return c?e.jsxs("div",{className:"cedros-admin-tab-error",children:[e.jsx("p",{className:"cedros-admin-error-inline",children:c}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:l,children:"Retry"})]}):o&&s.length===0?e.jsxs("div",{className:"cedros-admin-tab-loading",children:[e.jsx("span",{className:"cedros-admin-loading-indicator"}),e.jsx("span",{children:"Loading chat history..."})]}):t===0?e.jsx("div",{className:"cedros-admin-empty-message",children:"No chat sessions found."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin-list-table",children:[e.jsxs("div",{className:"cedros-admin-list-thead",children:[e.jsx("div",{className:"cedros-admin-list-th",children:"Date"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Session"}),e.jsx("div",{className:"cedros-admin-list-th",children:"Messages"})]}),s.map(d=>e.jsxs("div",{className:"cedros-admin-list-row",children:[e.jsx("div",{className:"cedros-admin-list-td",children:Ys(d.createdAt)}),e.jsx("div",{className:"cedros-admin-list-td",children:d.title||`Chat ${d.id.slice(0,8)}...`}),e.jsx("div",{className:"cedros-admin-list-td",children:d.messageCount})]},d.id))]}),a>1&&e.jsx(Js,{currentPage:r,totalPages:a,total:t,onPageChange:n})]})}function Js({currentPage:s,totalPages:t,total:r,onPageChange:a}){return e.jsxs("div",{className:"cedros-admin-pagination",children:[e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>a(s-1),disabled:s<=1,children:"Previous"}),e.jsxs("span",{className:"cedros-admin-page-info",children:["Page ",s," of ",t," (",r," total)"]}),e.jsx("button",{type:"button",className:"cedros-button cedros-button-outline cedros-button-sm",onClick:()=>a(s+1),disabled:s>=t,children:"Next"})]})}function ze({checked:s,onChange:t,disabled:r,label:a}){return e.jsx("button",{type:"button",role:"switch","aria-checked":s,"aria-label":a,disabled:r,className:`cedros-toggle cedros-toggle-sm ${s?"cedros-toggle-on":"cedros-toggle-off"} ${r?"cedros-toggle-disabled":""}`,onClick:()=>!r&&t(!s),children:e.jsx("span",{className:"cedros-toggle-track",children:e.jsx("span",{className:"cedros-toggle-thumb"})})})}function en({userRole:s}){const{permissions:t,updatePermissions:r,isLoading:a,isUpdating:n,error:o}=Vr(),{features:c,isLoading:l}=Gs(),d=i.useRef(null),u=i.useRef(null),g=s==="owner",m=c.cedrosPay,h=i.useCallback(f=>{u.current=f,d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{u.current&&(r(u.current).catch(()=>{}),u.current=null)},500)},[r]);i.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const b=i.useCallback((f,p,x)=>{const j={...t,[f]:{...t[f],[p]:x}};h(j)},[t,h]);return a||l?e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx("div",{className:"cedros-dashboard__loading",children:"Loading permissions..."})}):g?e.jsxs("div",{className:"cedros-dashboard__section cedros-permissions-section",children:[e.jsxs("div",{className:"cedros-permissions-header",children:[e.jsx("p",{className:"cedros-permissions-description",children:"Configure which dashboard sections each role can access. Owners always have full access."}),o&&e.jsx("div",{className:"cedros-permissions-error",children:o.message}),n&&e.jsx("span",{className:"cedros-permissions-saving",children:"Saving..."})]}),e.jsx("div",{className:"cedros-permissions-matrix",children:e.jsx("table",{className:"cedros-permissions-table",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"cedros-permissions-group-header",children:[e.jsx("th",{className:"cedros-permissions-section-header",children:"Cedros Login"}),e.jsx("th",{className:"cedros-permissions-role-header",children:"Admin"}),e.jsx("th",{className:"cedros-permissions-role-header",children:"Member"})]}),$o.map(f=>e.jsxs("tr",{className:"cedros-permissions-row",children:[e.jsx("td",{className:"cedros-permissions-section-label",children:Ae[f]}),e.jsx("td",{className:"cedros-permissions-toggle-cell",children:e.jsx(ze,{checked:t.admin[f]??!1,onChange:p=>b("admin",f,p),disabled:n,label:`Admin access to ${Ae[f]}`})}),e.jsx("td",{className:"cedros-permissions-toggle-cell",children:e.jsx(ze,{checked:t.member[f]??!1,onChange:p=>b("member",f,p),disabled:n,label:`Member access to ${Ae[f]}`})})]},f)),m&&e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"cedros-permissions-group-header",children:[e.jsx("th",{className:"cedros-permissions-section-header",children:"Cedros Pay"}),e.jsx("th",{className:"cedros-permissions-role-header",children:"Admin"}),e.jsx("th",{className:"cedros-permissions-role-header",children:"Member"})]}),zo.map(f=>e.jsxs("tr",{className:"cedros-permissions-row",children:[e.jsx("td",{className:"cedros-permissions-section-label",children:Ae[f]}),e.jsx("td",{className:"cedros-permissions-toggle-cell",children:e.jsx(ze,{checked:t.admin[f]??!1,onChange:p=>b("admin",f,p),disabled:n,label:`Admin access to ${Ae[f]}`})}),e.jsx("td",{className:"cedros-permissions-toggle-cell",children:e.jsx(ze,{checked:t.member[f]??!1,onChange:p=>b("member",f,p),disabled:n,label:`Member access to ${Ae[f]}`})})]},f))]})]})})})]}):e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx("div",{className:"cedros-dashboard__empty",children:"Only organization owners can configure dashboard permissions."})})}function Xs({name:s,email:t,picture:r,onSettings:a,onLogout:n,className:o=""}){const[c,l]=i.useState(!1),d=i.useRef(null);i.useEffect(()=>{function b(f){d.current&&!d.current.contains(f.target)&&l(!1)}if(c)return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[c]),i.useEffect(()=>{function b(f){f.key==="Escape"&&l(!1)}if(c)return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[c]);const u=i.useCallback(()=>{l(!1),a?.()},[a]),g=i.useCallback(()=>{l(!1),n?.()},[n]),m=s||"User",h=(s?.[0]||t?.[0]||"?").toUpperCase();return e.jsxs("div",{className:`cedros-profile-dropdown ${o}`,ref:d,children:[e.jsxs("button",{type:"button",className:"cedros-profile-dropdown__trigger",onClick:()=>l(!c),"aria-expanded":c,"aria-haspopup":"menu",children:[e.jsx("div",{className:"cedros-profile-dropdown__avatar",children:r?e.jsx("img",{src:r,alt:m,className:"cedros-profile-dropdown__avatar-img",referrerPolicy:"no-referrer"}):e.jsx("span",{className:"cedros-profile-dropdown__avatar-placeholder",children:h})}),e.jsxs("div",{className:"cedros-profile-dropdown__info",children:[e.jsx("span",{className:"cedros-profile-dropdown__name",children:m}),t&&e.jsx("span",{className:"cedros-profile-dropdown__email",children:t})]}),e.jsx("svg",{className:`cedros-profile-dropdown__chevron ${c?"cedros-profile-dropdown__chevron--open":""}`,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"m6 9 6 6 6-6"})})]}),c&&e.jsxs("div",{className:"cedros-profile-dropdown__menu",role:"menu",children:[a&&e.jsxs("button",{type:"button",className:"cedros-profile-dropdown__item",onClick:u,role:"menuitem",children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),"Settings"]}),n&&e.jsxs("button",{type:"button",className:"cedros-profile-dropdown__item cedros-profile-dropdown__item--danger",onClick:g,role:"menuitem",children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),e.jsx("polyline",{points:"16 17 21 12 16 7"}),e.jsx("line",{x1:"21",x2:"9",y1:"12",y2:"12"})]}),"Log out"]})]})]})}const ie={users:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),members:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),deposits:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"}),e.jsx("path",{d:"M12 18V6"})]}),withdrawals:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2"}),e.jsx("path",{d:"M9 22v-4h6v4"}),e.jsx("path",{d:"M8 6h.01"}),e.jsx("path",{d:"M16 6h.01"}),e.jsx("path",{d:"M12 6h.01"}),e.jsx("path",{d:"M12 10h.01"}),e.jsx("path",{d:"M12 14h.01"}),e.jsx("path",{d:"M16 10h.01"}),e.jsx("path",{d:"M16 14h.01"}),e.jsx("path",{d:"M8 10h.01"}),e.jsx("path",{d:"M8 14h.01"})]}),wallet:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),e.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),key:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})}),mail:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),e.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),coins:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"8",cy:"8",r:"6"}),e.jsx("path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18"}),e.jsx("path",{d:"M7 6h1v4"}),e.jsx("path",{d:"m16.71 13.88.7.71-2.82 2.82"})]}),server:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),e.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),e.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),e.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]})},hi=[{id:"users",label:"Users",icon:ie.users},{id:"team",label:"Team",icon:ie.members},{id:"deposits",label:"Deposits",icon:ie.deposits,requiredFeature:"credits"},{id:"withdrawals",label:"Withdrawals",icon:ie.withdrawals,requiredFeature:"credits"},{id:"settings-auth",label:"Authentication",icon:ie.key,group:"Configuration"},{id:"settings-messaging",label:"Auth Messages",icon:ie.mail,group:"Configuration"},{id:"settings-wallet",label:"User Wallets",icon:ie.wallet,group:"Configuration"},{id:"settings-credits",label:"Credit System",icon:ie.coins,group:"Configuration",requiredFeature:"credits"},{id:"settings-server",label:"Auth Server",icon:ie.server,group:"Configuration"}];function mi({title:s="Dashboard",sections:t=["users","team","deposits","withdrawals","settings-wallet","settings-auth","settings-messaging","settings-credits","settings-server"],defaultSection:r="users",refreshInterval:a=0,pageSize:n=20,onSectionChange:o,onSettingsClick:c,onLogoutClick:l,className:d=""}){const[u,g]=i.useState(r),[m,h]=i.useState(!0),{user:b,logout:f}=N.useCedrosLogin(),{activeOrg:p,role:x,isLoading:j,fetchOrgs:y,hasPermission:A}=as(),{status:v,isLoading:S,checkStatus:w}=Ks(),{features:E,isLoading:P}=Gs(),{canAccess:L}=Vr(),T=i.useCallback(D=>{g(D),o?.(D)},[o]),C=hi.filter(D=>!(!t.includes(D.id)||D.requiredFeature&&!E[D.requiredFeature]||!L(D.id))),k=C.find(D=>D.id===u),_=!k&&!P;return i.useEffect(()=>{y(),w()},[y,w]),i.useEffect(()=>{_&&C.length>0&&g("users")},[_,C.length]),!S&&v?.needsSetup?e.jsx("div",{className:`cedros-admin cedros-dashboard cedros-dashboard--setup ${d}`,children:e.jsx(Ir,{onComplete:()=>w()})}):(j||S||P)&&!p?e.jsxs("div",{className:`cedros-admin cedros-dashboard cedros-dashboard--loading ${d}`,children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{className:"cedros-dashboard__loading-text",children:"Loading..."})]}):u==="team"&&!p?e.jsx("div",{className:`cedros-admin cedros-dashboard ${d}`,children:e.jsx(N.ErrorMessage,{error:"No organization selected. Please select an organization first."})}):e.jsxs("div",{className:`cedros-admin cedros-dashboard ${d}`,children:[e.jsxs("aside",{className:"cedros-dashboard__sidebar",children:[e.jsx("div",{className:"cedros-dashboard__sidebar-header",children:e.jsxs("div",{className:"cedros-dashboard__logo",children:[ie.wallet,e.jsx("span",{className:"cedros-dashboard__logo-text",children:s})]})}),e.jsxs("nav",{className:"cedros-dashboard__nav",children:[e.jsxs("div",{className:"cedros-dashboard__nav-group",children:[e.jsx("span",{className:"cedros-dashboard__nav-label",children:"Menu"}),C.filter(D=>!D.group).map(D=>e.jsxs("button",{type:"button",className:`cedros-dashboard__nav-item ${u===D.id?"cedros-dashboard__nav-item--active":""}`,onClick:()=>T(D.id),"aria-current":u===D.id?"page":void 0,children:[e.jsx("span",{className:"cedros-dashboard__nav-icon",children:D.icon}),e.jsx("span",{className:"cedros-dashboard__nav-text",children:D.label})]},D.id))]}),C.some(D=>D.group==="Configuration")&&e.jsxs("div",{className:"cedros-dashboard__nav-group",children:[e.jsxs("button",{type:"button",className:"cedros-dashboard__nav-label cedros-dashboard__nav-label--collapsible",onClick:()=>h(!m),"aria-expanded":m,children:[e.jsx("span",{children:"Configuration"}),e.jsx("span",{className:`cedros-dashboard__nav-chevron ${m?"cedros-dashboard__nav-chevron--expanded":""}`,children:ie.chevronRight})]}),m&&C.filter(D=>D.group==="Configuration").map(D=>e.jsxs("button",{type:"button",className:`cedros-dashboard__nav-item ${u===D.id?"cedros-dashboard__nav-item--active":""}`,onClick:()=>T(D.id),"aria-current":u===D.id?"page":void 0,children:[e.jsx("span",{className:"cedros-dashboard__nav-icon",children:D.icon}),e.jsx("span",{className:"cedros-dashboard__nav-text",children:D.label})]},D.id))]})]}),b&&e.jsx("div",{className:"cedros-dashboard__sidebar-footer",children:e.jsx(Xs,{name:b.name,email:b.email,picture:b.picture,onSettings:c,onLogout:l??f})})]}),e.jsxs("main",{className:"cedros-dashboard__main",children:[e.jsx("header",{className:"cedros-dashboard__header",children:e.jsxs("div",{className:"cedros-dashboard__breadcrumb",children:[e.jsx("span",{className:"cedros-dashboard__breadcrumb-root",children:s}),e.jsx("span",{className:"cedros-dashboard__breadcrumb-sep",children:ie.chevronRight}),e.jsx("span",{className:"cedros-dashboard__breadcrumb-current",children:k?.label})]})}),e.jsxs("div",{className:"cedros-dashboard__content",children:[u==="users"&&e.jsx(pi,{pageSize:n,currentUserId:b?.id}),u==="team"&&p&&e.jsx(fi,{orgId:p.id,currentUserId:b?.id,hasPermission:A,role:x}),u==="deposits"&&e.jsx(gi,{pageSize:n,refreshInterval:a}),u==="withdrawals"&&e.jsx(bi,{pageSize:n,refreshInterval:a}),u==="settings-auth"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Br,{})}),u==="settings-wallet"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Or,{})}),u==="settings-messaging"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Fo,{})}),u==="settings-credits"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(qr,{})}),u==="settings-server"&&e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Wr,{})})]})]})]})}function pi({pageSize:s,currentUserId:t}){const[r,a]=i.useState(null),[n,o]=i.useState(null),[c,l]=i.useState(!1),[d,u]=i.useState(null),{getStats:g}=os(),{fetchSettings:m,getValue:h}=Re(),[b,f]=i.useState(!1);i.useEffect(()=>{b||(m(),f(!0))},[m,b]);const p=i.useCallback(y=>{const A=h(y);return A===void 0?!1:A==="true"||A==="1"},[h]),x=i.useCallback(async()=>{l(!0),u(null);try{const y=await g();o(y)}catch(y){u(y instanceof Error?y.message:"Failed to load user stats")}finally{l(!1)}},[g]);i.useEffect(()=>{x()},[x]);const j=i.useMemo(()=>{const y=[{label:"Total Users",value:n?.total??"—"}],A=p("auth_email_enabled"),v=p("auth_google_enabled"),S=p("auth_apple_enabled"),w=p("auth_solana_enabled"),E=p("auth_webauthn_enabled"),P=p("feature_sso");return A&&y.push({label:"Email Users",value:n?.authMethodCounts.email??0}),v&&y.push({label:"Google Users",value:n?.authMethodCounts.google??0}),S&&y.push({label:"Apple Users",value:n?.authMethodCounts.apple??0}),w&&y.push({label:"Solana Users",value:n?.authMethodCounts.solana??0}),E&&y.push({label:"Passkey Users",value:n?.authMethodCounts.webauthn??0}),P&&y.push({label:"SSO Provider Users",value:n?.authMethodCounts.sso??0}),y},[n,p]);return r?e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(Zr,{userId:r.id,currentUserId:t,onBack:()=>a(null)})}):e.jsxs("div",{className:"cedros-dashboard__section",children:[e.jsx(Ce,{stats:j,isLoading:c,onRefresh:x}),d&&e.jsx("p",{className:"cedros-admin-error-inline",children:d}),e.jsx(Xr,{pageSize:s,currentUserId:t,onUserClick:y=>a(y)})]})}function fi({orgId:s,currentUserId:t,hasPermission:r,role:a}){const[n,o]=i.useState("members"),{members:c,isLoading:l,error:d,fetchMembers:u,updateMemberRole:g,removeMember:m}=$r(s),{invites:h,isLoading:b,error:f,fetchInvites:p,createInvite:x,cancelInvite:j,resendInvite:y}=zr(s);i.useEffect(()=>{u(),p()},[u,p]);const A=r("invite:create"),v=r("invite:cancel"),S=h.length,w=c.reduce((T,C)=>(T[C.role]=(T[C.role]??0)+1,T),{}),E=w.owner??0,P=w.admin??0,L=w.member??0;return e.jsxs("div",{className:"cedros-dashboard__team",children:[e.jsx(Ce,{stats:[{label:"Owners",value:E},{label:"Admins",value:P},{label:"Members",value:L},{label:"Pending Invites",value:S}]}),e.jsxs("div",{className:"cedros-admin-tabs cedros-admin-tabs--line",children:[e.jsx("button",{type:"button",className:`cedros-admin-tab ${n==="members"?"cedros-admin-tab-active":""}`,onClick:()=>o("members"),"aria-selected":n==="members",role:"tab",children:"Members"}),e.jsxs("button",{type:"button",className:`cedros-admin-tab ${n==="invites"?"cedros-admin-tab-active":""}`,onClick:()=>o("invites"),"aria-selected":n==="invites",role:"tab",children:["Pending Invites",S>0&&` (${S})`]}),a==="owner"&&e.jsx("button",{type:"button",className:`cedros-admin-tab ${n==="permissions"?"cedros-admin-tab-active":""}`,onClick:()=>o("permissions"),"aria-selected":n==="permissions",role:"tab",children:"Permissions"})]}),e.jsxs("div",{className:"cedros-admin-tab-content",role:"tabpanel",children:[n==="members"&&e.jsx(yr,{members:c,currentUserId:t,isLoading:l,error:d?.message,canManage:r("member:remove"),canChangeRoles:r("member:role_change"),onUpdateRole:g,onRemove:m}),n==="invites"&&e.jsxs("div",{className:"cedros-dashboard__invites",children:[A&&e.jsxs("div",{className:"cedros-dashboard__section",children:[e.jsx("div",{className:"cedros-dashboard__section-header",children:e.jsx("h3",{className:"cedros-dashboard__section-title",children:"Send Invitation"})}),e.jsx(wr,{onSubmit:x,isLoading:b,error:f?.message})]}),e.jsx("div",{className:"cedros-dashboard__section",children:e.jsx(xr,{invites:h,isLoading:b,error:f?.message,canManage:v||A,onCancel:v?j:void 0,onResend:A?y:void 0})})]}),n==="permissions"&&a==="owner"&&e.jsx(en,{userRole:a})]})]})}function gi({pageSize:s,refreshInterval:t}){const[r,a]=i.useState("");return e.jsxs("div",{className:"cedros-dashboard__deposits",children:[e.jsx(Hr,{refreshInterval:t}),e.jsxs("div",{className:"cedros-dashboard__deposits-list",children:[e.jsx("div",{className:"cedros-dashboard__toolbar",children:e.jsxs("div",{className:"cedros-dashboard__filter",children:[e.jsx("label",{className:"cedros-dashboard__filter-label",htmlFor:"status-filter",children:"Status"}),e.jsxs("select",{id:"status-filter",className:"cedros-dashboard__select",value:r,onChange:n=>a(n.target.value),children:[e.jsx("option",{value:"",children:"All statuses"}),e.jsx("option",{value:"pending",children:"Pending"}),e.jsx("option",{value:"detected",children:"Detected"}),e.jsx("option",{value:"processing",children:"Processing"}),e.jsx("option",{value:"completed",children:"Completed"}),e.jsx("option",{value:"withdrawn",children:"Withdrawn"}),e.jsx("option",{value:"expired",children:"Expired"}),e.jsx("option",{value:"failed",children:"Failed"})]})]})}),e.jsx(Kr,{statusFilter:r||void 0,pageSize:s,refreshInterval:t})]})]})}function bi({pageSize:s,refreshInterval:t}){return e.jsxs("div",{className:"cedros-dashboard__withdrawals",children:[e.jsx(Qr,{refreshInterval:t}),e.jsx("p",{className:"cedros-dashboard__text-muted",children:"Track deposits through the withdrawal pipeline: privacy period, ready for processing, and completed."}),e.jsxs("div",{className:"cedros-dashboard__pipeline",children:[e.jsx(Yr,{pageSize:s,refreshInterval:t}),e.jsx(Gr,{pageSize:s,refreshInterval:t}),e.jsx(Jr,{pageSize:s,refreshInterval:t})]})]})}class yi{plugins=new Map;listeners=new Set;register(t){this.plugins.has(t.id)&&console.warn(`Plugin ${t.id} already registered, replacing...`),this.plugins.set(t.id,t),t.onRegister?.(this),this.notify()}unregister(t){const r=this.plugins.get(t);r&&(r.onUnregister?.(),this.plugins.delete(t),this.notify())}get(t){return this.plugins.get(t)}getAll(){return Array.from(this.plugins.values())}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){const t=this.getAll();this.listeners.forEach(r=>r(t))}}const sn=i.createContext(null);function wi(){const s=i.useContext(sn);if(!s)throw new Error("useAdminShell must be used within AdminShell");return s}function xi(s){const t=new Map;for(const r of s)for(const a of r.groups??[])t.has(a.label)||t.set(a.label,a.order);return t}function vi({title:s="Admin",plugins:t=[],hostContext:r,defaultSection:a,pageSize:n=20,refreshInterval:o=0,onSectionChange:c,logo:l,sidebarFooter:d,onSettingsClick:u,onLogoutClick:g,className:m=""}){const[h]=i.useState(()=>{const C=new yi;return t.forEach(k=>C.register(k)),C}),[b,f]=i.useState(()=>h.getAll());i.useEffect(()=>h.subscribe(f),[h]);const p=i.useMemo(()=>b.flatMap(C=>C.sections.filter(k=>!(k.requiredPermission&&!C.checkPermission(k.requiredPermission,r)||r.dashboardPermissions&&!r.dashboardPermissions.canAccess(k.id))).map(k=>({...k,qualifiedId:`${C.id}:${k.id}`,pluginId:C.id,cssNamespace:C.cssNamespace}))),[b,r]),[x,j]=i.useState(()=>a??p[0]?.qualifiedId??null),[y,A]=i.useState(new Set),v=i.useCallback(C=>{A(k=>{const _=new Set(k);return _.has(C)?_.delete(C):_.add(C),_})},[]);i.useEffect(()=>{x&&!p.find(C=>C.qualifiedId===x)&&j(p[0]?.qualifiedId??null)},[p,x]);const S=i.useCallback(C=>{j(C),c?.(C)},[c]),w=i.useCallback(C=>{const k=h.get(C);return k?k.createPluginContext(r):null},[h,r]),E=i.useMemo(()=>{const C=xi(b),k=new Map;return p.forEach(M=>{const D=M.group??"Menu",B=k.get(D)??[];k.set(D,[...B,M])}),Array.from(k.entries()).sort(([M],[D])=>{const B=C.get(M)??99,Q=C.get(D)??99;return B-Q})},[p,b]),P=i.useMemo(()=>{if(!x)return null;const[C,k]=x.split(":"),_=h.get(C);if(!_)return null;const M=_.components[k];if(!M)return null;const D=_.createPluginContext(r);return{Component:M,pluginContext:D,plugin:_}},[x,h,r]),L=i.useMemo(()=>({registry:h,hostContext:r,activeSection:x,setActiveSection:S,getPluginContext:w}),[h,r,x,S,w]),T=i.useMemo(()=>{const C=r.cedrosLogin;if(!C)return null;const k=C.user?{authMethods:[],emailVerified:!1,createdAt:"",updatedAt:"",...C.user}:null;return{config:{serverUrl:C.serverUrl},user:k,authState:C.user?"authenticated":"unauthenticated",error:null,logout:async()=>{},refreshUser:async()=>{},isModalOpen:!1,openModal:()=>{},closeModal:()=>{},_internal:{handleLoginSuccess:()=>{},getAccessToken:C.getAccessToken}}},[r.cedrosLogin]);return e.jsx(sn.Provider,{value:L,children:e.jsx(N.CedrosLoginContext.Provider,{value:T,children:e.jsxs("div",{className:`cedros-admin cedros-admin-shell ${m||""}`,children:[e.jsxs("aside",{className:"cedros-admin-shell__sidebar",children:[e.jsx("div",{className:"cedros-admin-shell__sidebar-header",children:l??e.jsx("div",{className:"cedros-admin-shell__logo",children:e.jsx("span",{className:"cedros-admin-shell__logo-text",children:s})})}),e.jsx("nav",{className:"cedros-admin-shell__nav",children:E.map(([C,k])=>{const _=C==="Configuration",M=y.has(C);return e.jsxs("div",{className:"cedros-admin-shell__nav-group",children:[_?e.jsxs("button",{type:"button",className:"cedros-admin-shell__nav-label cedros-admin-shell__nav-label--collapsible",onClick:()=>v(C),"aria-expanded":!M,children:[e.jsx("span",{children:C}),e.jsx("span",{className:`cedros-admin-shell__nav-chevron ${M?"":"cedros-admin-shell__nav-chevron--expanded"}`,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"m9 18 6-6-6-6"})})})]}):e.jsx("span",{className:"cedros-admin-shell__nav-label",children:C}),(!_||!M)&&k.sort((D,B)=>(D.order??0)-(B.order??0)).map(D=>e.jsxs("button",{type:"button",className:`cedros-admin-shell__nav-item ${x===D.qualifiedId?"cedros-admin-shell__nav-item--active":""}`,onClick:()=>S(D.qualifiedId),"aria-current":x===D.qualifiedId?"page":void 0,children:[e.jsx("span",{className:"cedros-admin-shell__nav-icon",children:D.icon}),e.jsx("span",{className:"cedros-admin-shell__nav-text",children:D.label}),D.badge&&e.jsx("span",{className:"cedros-admin-shell__nav-badge",children:D.badge})]},D.qualifiedId))]},C)})}),(r.cedrosLogin?.user||d)&&e.jsxs("div",{className:"cedros-admin-shell__sidebar-footer",children:[r.cedrosLogin?.user&&e.jsx(Xs,{name:r.cedrosLogin.user.name,email:r.cedrosLogin.user.email,picture:r.cedrosLogin.user.picture,onSettings:u,onLogout:g}),d]})]}),e.jsx("main",{className:"cedros-admin-shell__main",children:P?e.jsx(i.Suspense,{fallback:e.jsx(ji,{}),children:e.jsx("div",{className:"cedros-admin-shell__section","data-plugin-namespace":P.plugin.cssNamespace,children:e.jsx(P.Component,{pluginContext:P.pluginContext,pageSize:n,refreshInterval:o})})}):e.jsx("div",{className:"cedros-admin-shell__empty",children:p.length===0?"No plugins loaded":"Select a section from the sidebar"})})]})})})}function ji(){return e.jsxs("div",{className:"cedros-admin-shell__loading",children:[e.jsx(N.LoadingSpinner,{}),e.jsx("span",{children:"Loading..."})]})}const te={width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},ce={users:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),members:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),invites:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),e.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),deposits:e.jsxs("svg",{...te,children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"}),e.jsx("path",{d:"M12 18V6"})]}),withdrawals:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2"}),e.jsx("path",{d:"M9 22v-4h6v4"}),e.jsx("path",{d:"M8 6h.01"}),e.jsx("path",{d:"M16 6h.01"}),e.jsx("path",{d:"M12 6h.01"}),e.jsx("path",{d:"M12 10h.01"}),e.jsx("path",{d:"M12 14h.01"}),e.jsx("path",{d:"M16 10h.01"}),e.jsx("path",{d:"M16 14h.01"}),e.jsx("path",{d:"M8 10h.01"}),e.jsx("path",{d:"M8 14h.01"})]}),settings:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),e.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:e.jsx("svg",{...te,children:e.jsx("path",{d:"m9 18 6-6-6-6"})}),key:e.jsx("svg",{...te,children:e.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})}),toggles:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"20",height:"12",x:"2",y:"6",rx:"6"}),e.jsx("circle",{cx:"8",cy:"12",r:"2"})]}),shield:e.jsx("svg",{...te,children:e.jsx("path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"})}),mail:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),e.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),webhook:e.jsxs("svg",{...te,children:[e.jsx("path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2"}),e.jsx("path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06"}),e.jsx("path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8"})]}),coins:e.jsxs("svg",{...te,children:[e.jsx("circle",{cx:"8",cy:"8",r:"6"}),e.jsx("path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18"}),e.jsx("path",{d:"M7 6h1v4"}),e.jsx("path",{d:"m16.71 13.88.7.71-2.82 2.82"})]}),server:e.jsxs("svg",{...te,children:[e.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),e.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),e.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),e.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]})},Ai=i.lazy(()=>Promise.resolve().then(()=>require("./UsersSection-DDfHW_ao.cjs"))),ki=i.lazy(()=>Promise.resolve().then(()=>require("./TeamSection-W9SC2Keh.cjs"))),Ni=i.lazy(()=>Promise.resolve().then(()=>require("./DepositsSection-DEh9Oy0V.cjs"))),Si=i.lazy(()=>Promise.resolve().then(()=>require("./WithdrawalsSection-MFj2muP6.cjs"))),Ci=i.lazy(()=>Promise.resolve().then(()=>require("./AuthenticationSettings-BxpBLsUX.cjs"))),_i=i.lazy(()=>Promise.resolve().then(()=>require("./EmbeddedWalletSettings-NZfbc5K8.cjs"))),Ei=i.lazy(()=>Promise.resolve().then(()=>require("./EmailSettings-CGocWYc0.cjs"))),Ti=i.lazy(()=>Promise.resolve().then(()=>require("./WebhookSettings-9dcnVNH_.cjs"))),Pi=i.lazy(()=>Promise.resolve().then(()=>require("./CreditSystemSettings-BuBKDfKL.cjs"))),Li=i.lazy(()=>Promise.resolve().then(()=>require("./ServerSettings-Bkr_xuDx.cjs"))),Mi={"login:users:read":["admin","owner"],"login:users:write":["admin","owner"],"login:members:read":["member:read","admin","owner"],"login:members:write":["member:remove","member:role_change"],"login:invites:read":["invite:read","admin","owner"],"login:invites:write":["invite:create","invite:cancel"],"login:deposits:read":["admin","owner"],"login:deposits:write":["admin","owner"],"login:settings:read":["admin","owner"],"login:settings:write":["admin","owner"]},Di=[{id:"users",label:"Users",icon:ce.users,group:"Users",order:0,requiredPermission:"login:users:read"},{id:"team",label:"Team",icon:ce.members,group:"Users",order:1,requiredPermission:"login:members:read"},{id:"deposits",label:"Deposits",icon:ce.deposits,group:"Users",order:2,requiredPermission:"login:deposits:read"},{id:"withdrawals",label:"Withdrawals",icon:ce.withdrawals,group:"Users",order:3,requiredPermission:"login:deposits:read"},{id:"settings-auth",label:"Authentication",icon:ce.key,group:"Configuration",order:0,requiredPermission:"login:settings:read"},{id:"settings-email",label:"Email & SMTP",icon:ce.mail,group:"Configuration",order:1,requiredPermission:"login:settings:read"},{id:"settings-webhooks",label:"Webhooks",icon:ce.webhook,group:"Configuration",order:2,requiredPermission:"login:settings:read"},{id:"settings-wallet",label:"User Wallets",icon:ce.wallet,group:"Configuration",order:3,requiredPermission:"login:settings:read"},{id:"settings-credits",label:"Credit System",icon:ce.coins,group:"Configuration",order:4,requiredPermission:"login:settings:read"},{id:"settings-server",label:"Auth Server",icon:ce.server,group:"Configuration",order:5,requiredPermission:"login:settings:read"}],Ri={id:"cedros-login",name:"Cedros Login",version:"1.0.0",sections:Di,groups:[{id:"users",label:"Users",order:0},{id:"configuration",label:"Configuration",order:2}],components:{users:Ai,team:ki,deposits:Ni,withdrawals:Si,"settings-auth":Ci,"settings-wallet":_i,"settings-email":Ei,"settings-webhooks":Ti,"settings-credits":Pi,"settings-server":Li},createPluginContext(s){const t=s.cedrosLogin;if(!t)throw new Error("cedros-login plugin requires cedrosLogin in hostContext");return{serverUrl:t.serverUrl,userId:t.user?.id,getAccessToken:t.getAccessToken,hasPermission:r=>this.checkPermission(r,s),orgId:s.org?.orgId,pluginData:{user:t.user,orgRole:s.org?.role}}},checkPermission(s,t){const r=t.org;if(!r)return!!t.cedrosLogin?.user;const a=Mi[s];return a?a.some(n=>r.permissions.includes(n)||n===r.role||n==="admin"&&["admin","owner"].includes(r.role)||n==="owner"&&r.role==="owner"):!1},cssNamespace:"cedros-dashboard"};var ke={},ys,Ct;function Ii(){return Ct||(Ct=1,ys=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ys}var ws={},pe={},_t;function we(){if(_t)return pe;_t=1;let s;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return pe.getSymbolSize=function(a){if(!a)throw new Error('"version" cannot be null or undefined');if(a<1||a>40)throw new Error('"version" should be in range from 1 to 40');return a*4+17},pe.getSymbolTotalCodewords=function(a){return t[a]},pe.getBCHDigit=function(r){let a=0;for(;r!==0;)a++,r>>>=1;return a},pe.setToSJISFunction=function(a){if(typeof a!="function")throw new Error('"toSJISFunc" is not a valid function.');s=a},pe.isKanjiModeEnabled=function(){return typeof s<"u"},pe.toSJIS=function(a){return s(a)},pe}var xs={},Et;function Zs(){return Et||(Et=1,(function(s){s.L={bit:1},s.M={bit:0},s.Q={bit:3},s.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return s.L;case"m":case"medium":return s.M;case"q":case"quartile":return s.Q;case"h":case"high":return s.H;default:throw new Error("Unknown EC Level: "+r)}}s.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},s.from=function(a,n){if(s.isValid(a))return a;try{return t(a)}catch{return n}}})(xs)),xs}var vs,Tt;function Ui(){if(Tt)return vs;Tt=1;function s(){this.buffer=[],this.length=0}return s.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let a=0;a<r;a++)this.putBit((t>>>r-a-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},vs=s,vs}var js,Pt;function Fi(){if(Pt)return js;Pt=1;function s(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return s.prototype.set=function(t,r,a,n){const o=t*this.size+r;this.data[o]=a,n&&(this.reservedBit[o]=!0)},s.prototype.get=function(t,r){return this.data[t*this.size+r]},s.prototype.xor=function(t,r,a){this.data[t*this.size+r]^=a},s.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},js=s,js}var As={},Lt;function Bi(){return Lt||(Lt=1,(function(s){const t=we().getSymbolSize;s.getRowColCoords=function(a){if(a===1)return[];const n=Math.floor(a/7)+2,o=t(a),c=o===145?26:Math.ceil((o-13)/(2*n-2))*2,l=[o-7];for(let d=1;d<n-1;d++)l[d]=l[d-1]-c;return l.push(6),l.reverse()},s.getPositions=function(a){const n=[],o=s.getRowColCoords(a),c=o.length;for(let l=0;l<c;l++)for(let d=0;d<c;d++)l===0&&d===0||l===0&&d===c-1||l===c-1&&d===0||n.push([o[l],o[d]]);return n}})(As)),As}var ks={},Mt;function Oi(){if(Mt)return ks;Mt=1;const s=we().getSymbolSize,t=7;return ks.getPositions=function(a){const n=s(a);return[[0,0],[n-t,0],[0,n-t]]},ks}var Ns={},Dt;function qi(){return Dt||(Dt=1,(function(s){s.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};s.isValid=function(n){return n!=null&&n!==""&&!isNaN(n)&&n>=0&&n<=7},s.from=function(n){return s.isValid(n)?parseInt(n,10):void 0},s.getPenaltyN1=function(n){const o=n.size;let c=0,l=0,d=0,u=null,g=null;for(let m=0;m<o;m++){l=d=0,u=g=null;for(let h=0;h<o;h++){let b=n.get(m,h);b===u?l++:(l>=5&&(c+=t.N1+(l-5)),u=b,l=1),b=n.get(h,m),b===g?d++:(d>=5&&(c+=t.N1+(d-5)),g=b,d=1)}l>=5&&(c+=t.N1+(l-5)),d>=5&&(c+=t.N1+(d-5))}return c},s.getPenaltyN2=function(n){const o=n.size;let c=0;for(let l=0;l<o-1;l++)for(let d=0;d<o-1;d++){const u=n.get(l,d)+n.get(l,d+1)+n.get(l+1,d)+n.get(l+1,d+1);(u===4||u===0)&&c++}return c*t.N2},s.getPenaltyN3=function(n){const o=n.size;let c=0,l=0,d=0;for(let u=0;u<o;u++){l=d=0;for(let g=0;g<o;g++)l=l<<1&2047|n.get(u,g),g>=10&&(l===1488||l===93)&&c++,d=d<<1&2047|n.get(g,u),g>=10&&(d===1488||d===93)&&c++}return c*t.N3},s.getPenaltyN4=function(n){let o=0;const c=n.data.length;for(let d=0;d<c;d++)o+=n.data[d];return Math.abs(Math.ceil(o*100/c/5)-10)*t.N4};function r(a,n,o){switch(a){case s.Patterns.PATTERN000:return(n+o)%2===0;case s.Patterns.PATTERN001:return n%2===0;case s.Patterns.PATTERN010:return o%3===0;case s.Patterns.PATTERN011:return(n+o)%3===0;case s.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(o/3))%2===0;case s.Patterns.PATTERN101:return n*o%2+n*o%3===0;case s.Patterns.PATTERN110:return(n*o%2+n*o%3)%2===0;case s.Patterns.PATTERN111:return(n*o%3+(n+o)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}s.applyMask=function(n,o){const c=o.size;for(let l=0;l<c;l++)for(let d=0;d<c;d++)o.isReserved(d,l)||o.xor(d,l,r(n,d,l))},s.getBestMask=function(n,o){const c=Object.keys(s.Patterns).length;let l=0,d=1/0;for(let u=0;u<c;u++){o(u),s.applyMask(u,n);const g=s.getPenaltyN1(n)+s.getPenaltyN2(n)+s.getPenaltyN3(n)+s.getPenaltyN4(n);s.applyMask(u,n),g<d&&(d=g,l=u)}return l}})(Ns)),Ns}var Ve={},Rt;function tn(){if(Rt)return Ve;Rt=1;const s=Zs(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Ve.getBlocksCount=function(n,o){switch(o){case s.L:return t[(n-1)*4+0];case s.M:return t[(n-1)*4+1];case s.Q:return t[(n-1)*4+2];case s.H:return t[(n-1)*4+3];default:return}},Ve.getTotalCodewordsCount=function(n,o){switch(o){case s.L:return r[(n-1)*4+0];case s.M:return r[(n-1)*4+1];case s.Q:return r[(n-1)*4+2];case s.H:return r[(n-1)*4+3];default:return}},Ve}var Ss={},De={},It;function Wi(){if(It)return De;It=1;const s=new Uint8Array(512),t=new Uint8Array(256);return(function(){let a=1;for(let n=0;n<255;n++)s[n]=a,t[a]=n,a<<=1,a&256&&(a^=285);for(let n=255;n<512;n++)s[n]=s[n-255]})(),De.log=function(a){if(a<1)throw new Error("log("+a+")");return t[a]},De.exp=function(a){return s[a]},De.mul=function(a,n){return a===0||n===0?0:s[t[a]+t[n]]},De}var Ut;function $i(){return Ut||(Ut=1,(function(s){const t=Wi();s.mul=function(a,n){const o=new Uint8Array(a.length+n.length-1);for(let c=0;c<a.length;c++)for(let l=0;l<n.length;l++)o[c+l]^=t.mul(a[c],n[l]);return o},s.mod=function(a,n){let o=new Uint8Array(a);for(;o.length-n.length>=0;){const c=o[0];for(let d=0;d<n.length;d++)o[d]^=t.mul(n[d],c);let l=0;for(;l<o.length&&o[l]===0;)l++;o=o.slice(l)}return o},s.generateECPolynomial=function(a){let n=new Uint8Array([1]);for(let o=0;o<a;o++)n=s.mul(n,new Uint8Array([1,t.exp(o)]));return n}})(Ss)),Ss}var Cs,Ft;function zi(){if(Ft)return Cs;Ft=1;const s=$i();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(a){this.degree=a,this.genPoly=s.generateECPolynomial(this.degree)},t.prototype.encode=function(a){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(a.length+this.degree);n.set(a);const o=s.mod(n,this.genPoly),c=this.degree-o.length;if(c>0){const l=new Uint8Array(this.degree);return l.set(o,c),l}return o},Cs=t,Cs}var _s={},Es={},Ts={},Bt;function rn(){return Bt||(Bt=1,Ts.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Ts}var ue={},Ot;function nn(){if(Ot)return ue;Ot=1;const s="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const a="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
2050
2050
|
]))+`;ue.KANJI=new RegExp(r,"g"),ue.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ue.BYTE=new RegExp(a,"g"),ue.NUMERIC=new RegExp(s,"g"),ue.ALPHANUMERIC=new RegExp(t,"g");const n=new RegExp("^"+r+"$"),o=new RegExp("^"+s+"$"),c=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ue.testKanji=function(d){return n.test(d)},ue.testNumeric=function(d){return o.test(d)},ue.testAlphanumeric=function(d){return c.test(d)},ue}var qt;function xe(){return qt||(qt=1,(function(s){const t=rn(),r=nn();s.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},s.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},s.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},s.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},s.MIXED={bit:-1},s.getCharCountIndicator=function(o,c){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!t.isValid(c))throw new Error("Invalid version: "+c);return c>=1&&c<10?o.ccBits[0]:c<27?o.ccBits[1]:o.ccBits[2]},s.getBestModeForData=function(o){return r.testNumeric(o)?s.NUMERIC:r.testAlphanumeric(o)?s.ALPHANUMERIC:r.testKanji(o)?s.KANJI:s.BYTE},s.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},s.isValid=function(o){return o&&o.bit&&o.ccBits};function a(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return s.NUMERIC;case"alphanumeric":return s.ALPHANUMERIC;case"kanji":return s.KANJI;case"byte":return s.BYTE;default:throw new Error("Unknown mode: "+n)}}s.from=function(o,c){if(s.isValid(o))return o;try{return a(o)}catch{return c}}})(Es)),Es}var Wt;function Vi(){return Wt||(Wt=1,(function(s){const t=we(),r=tn(),a=Zs(),n=xe(),o=rn(),c=7973,l=t.getBCHDigit(c);function d(h,b,f){for(let p=1;p<=40;p++)if(b<=s.getCapacity(p,f,h))return p}function u(h,b){return n.getCharCountIndicator(h,b)+4}function g(h,b){let f=0;return h.forEach(function(p){const x=u(p.mode,b);f+=x+p.getBitsLength()}),f}function m(h,b){for(let f=1;f<=40;f++)if(g(h,f)<=s.getCapacity(f,b,n.MIXED))return f}s.from=function(b,f){return o.isValid(b)?parseInt(b,10):f},s.getCapacity=function(b,f,p){if(!o.isValid(b))throw new Error("Invalid QR Code version");typeof p>"u"&&(p=n.BYTE);const x=t.getSymbolTotalCodewords(b),j=r.getTotalCodewordsCount(b,f),y=(x-j)*8;if(p===n.MIXED)return y;const A=y-u(p,b);switch(p){case n.NUMERIC:return Math.floor(A/10*3);case n.ALPHANUMERIC:return Math.floor(A/11*2);case n.KANJI:return Math.floor(A/13);case n.BYTE:default:return Math.floor(A/8)}},s.getBestVersionForData=function(b,f){let p;const x=a.from(f,a.M);if(Array.isArray(b)){if(b.length>1)return m(b,x);if(b.length===0)return 1;p=b[0]}else p=b;return d(p.mode,p.getLength(),x)},s.getEncodedBits=function(b){if(!o.isValid(b)||b<7)throw new Error("Invalid QR Code version");let f=b<<12;for(;t.getBCHDigit(f)-l>=0;)f^=c<<t.getBCHDigit(f)-l;return b<<12|f}})(_s)),_s}var Ps={},$t;function Hi(){if($t)return Ps;$t=1;const s=we(),t=1335,r=21522,a=s.getBCHDigit(t);return Ps.getEncodedBits=function(o,c){const l=o.bit<<3|c;let d=l<<10;for(;s.getBCHDigit(d)-a>=0;)d^=t<<s.getBCHDigit(d)-a;return(l<<10|d)^r},Ps}var Ls={},Ms,zt;function Qi(){if(zt)return Ms;zt=1;const s=xe();function t(r){this.mode=s.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(a){return 10*Math.floor(a/3)+(a%3?a%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(a){let n,o,c;for(n=0;n+3<=this.data.length;n+=3)o=this.data.substr(n,3),c=parseInt(o,10),a.put(c,10);const l=this.data.length-n;l>0&&(o=this.data.substr(n),c=parseInt(o,10),a.put(c,l*3+1))},Ms=t,Ms}var Ds,Vt;function Ki(){if(Vt)return Ds;Vt=1;const s=xe(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(a){this.mode=s.ALPHANUMERIC,this.data=a}return r.getBitsLength=function(n){return 11*Math.floor(n/2)+6*(n%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o+2<=this.data.length;o+=2){let c=t.indexOf(this.data[o])*45;c+=t.indexOf(this.data[o+1]),n.put(c,11)}this.data.length%2&&n.put(t.indexOf(this.data[o]),6)},Ds=r,Ds}var Rs,Ht;function Gi(){if(Ht)return Rs;Ht=1;const s=xe();function t(r){this.mode=s.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(a){return a*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let a=0,n=this.data.length;a<n;a++)r.put(this.data[a],8)},Rs=t,Rs}var Is,Qt;function Yi(){if(Qt)return Is;Qt=1;const s=xe(),t=we();function r(a){this.mode=s.KANJI,this.data=a}return r.getBitsLength=function(n){return n*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(a){let n;for(n=0;n<this.data.length;n++){let o=t.toSJIS(this.data[n]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[n]+`
|
|
2051
2051
|
Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),a.put(o,13)}},Is=r,Is}var Us={exports:{}},Kt;function Ji(){return Kt||(Kt=1,(function(s){var t={single_source_shortest_paths:function(r,a,n){var o={},c={};c[a]=0;var l=t.PriorityQueue.make();l.push(a,0);for(var d,u,g,m,h,b,f,p,x;!l.empty();){d=l.pop(),u=d.value,m=d.cost,h=r[u]||{};for(g in h)h.hasOwnProperty(g)&&(b=h[g],f=m+b,p=c[g],x=typeof c[g]>"u",(x||p>f)&&(c[g]=f,l.push(g,f),o[g]=u))}if(typeof n<"u"&&typeof c[n]>"u"){var j=["Could not find a path from ",a," to ",n,"."].join("");throw new Error(j)}return o},extract_shortest_path_from_predecessor_list:function(r,a){for(var n=[],o=a;o;)n.push(o),r[o],o=r[o];return n.reverse(),n},find_path:function(r,a,n){var o=t.single_source_shortest_paths(r,a,n);return t.extract_shortest_path_from_predecessor_list(o,n)},PriorityQueue:{make:function(r){var a=t.PriorityQueue,n={},o;r=r||{};for(o in a)a.hasOwnProperty(o)&&(n[o]=a[o]);return n.queue=[],n.sorter=r.sorter||a.default_sorter,n},default_sorter:function(r,a){return r.cost-a.cost},push:function(r,a){var n={value:r,cost:a};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};s.exports=t})(Us)),Us.exports}var Gt;function Xi(){return Gt||(Gt=1,(function(s){const t=xe(),r=Qi(),a=Ki(),n=Gi(),o=Yi(),c=nn(),l=we(),d=Ji();function u(j){return unescape(encodeURIComponent(j)).length}function g(j,y,A){const v=[];let S;for(;(S=j.exec(A))!==null;)v.push({data:S[0],index:S.index,mode:y,length:S[0].length});return v}function m(j){const y=g(c.NUMERIC,t.NUMERIC,j),A=g(c.ALPHANUMERIC,t.ALPHANUMERIC,j);let v,S;return l.isKanjiModeEnabled()?(v=g(c.BYTE,t.BYTE,j),S=g(c.KANJI,t.KANJI,j)):(v=g(c.BYTE_KANJI,t.BYTE,j),S=[]),y.concat(A,v,S).sort(function(E,P){return E.index-P.index}).map(function(E){return{data:E.data,mode:E.mode,length:E.length}})}function h(j,y){switch(y){case t.NUMERIC:return r.getBitsLength(j);case t.ALPHANUMERIC:return a.getBitsLength(j);case t.KANJI:return o.getBitsLength(j);case t.BYTE:return n.getBitsLength(j)}}function b(j){return j.reduce(function(y,A){const v=y.length-1>=0?y[y.length-1]:null;return v&&v.mode===A.mode?(y[y.length-1].data+=A.data,y):(y.push(A),y)},[])}function f(j){const y=[];for(let A=0;A<j.length;A++){const v=j[A];switch(v.mode){case t.NUMERIC:y.push([v,{data:v.data,mode:t.ALPHANUMERIC,length:v.length},{data:v.data,mode:t.BYTE,length:v.length}]);break;case t.ALPHANUMERIC:y.push([v,{data:v.data,mode:t.BYTE,length:v.length}]);break;case t.KANJI:y.push([v,{data:v.data,mode:t.BYTE,length:u(v.data)}]);break;case t.BYTE:y.push([{data:v.data,mode:t.BYTE,length:u(v.data)}])}}return y}function p(j,y){const A={},v={start:{}};let S=["start"];for(let w=0;w<j.length;w++){const E=j[w],P=[];for(let L=0;L<E.length;L++){const T=E[L],C=""+w+L;P.push(C),A[C]={node:T,lastCount:0},v[C]={};for(let k=0;k<S.length;k++){const _=S[k];A[_]&&A[_].node.mode===T.mode?(v[_][C]=h(A[_].lastCount+T.length,T.mode)-h(A[_].lastCount,T.mode),A[_].lastCount+=T.length):(A[_]&&(A[_].lastCount=T.length),v[_][C]=h(T.length,T.mode)+4+t.getCharCountIndicator(T.mode,y))}}S=P}for(let w=0;w<S.length;w++)v[S[w]].end=0;return{map:v,table:A}}function x(j,y){let A;const v=t.getBestModeForData(j);if(A=t.from(y,v),A!==t.BYTE&&A.bit<v.bit)throw new Error('"'+j+'" cannot be encoded with mode '+t.toString(A)+`.
|
|
2052
2052
|
Suggested mode is: `+t.toString(v));switch(A===t.KANJI&&!l.isKanjiModeEnabled()&&(A=t.BYTE),A){case t.NUMERIC:return new r(j);case t.ALPHANUMERIC:return new a(j);case t.KANJI:return new o(j);case t.BYTE:return new n(j)}}s.fromArray=function(y){return y.reduce(function(A,v){return typeof v=="string"?A.push(x(v,null)):v.data&&A.push(x(v.data,v.mode)),A},[])},s.fromString=function(y,A){const v=m(y,l.isKanjiModeEnabled()),S=f(v),w=p(S,A),E=d.find_path(w.map,"start","end"),P=[];for(let L=1;L<E.length-1;L++)P.push(w.table[E[L]].node);return s.fromArray(b(P))},s.rawSplit=function(y){return s.fromArray(m(y,l.isKanjiModeEnabled()))}})(Ls)),Ls}var Yt;function Zi(){if(Yt)return ws;Yt=1;const s=we(),t=Zs(),r=Ui(),a=Fi(),n=Bi(),o=Oi(),c=qi(),l=tn(),d=zi(),u=Vi(),g=Hi(),m=xe(),h=Xi();function b(w,E){const P=w.size,L=o.getPositions(E);for(let T=0;T<L.length;T++){const C=L[T][0],k=L[T][1];for(let _=-1;_<=7;_++)if(!(C+_<=-1||P<=C+_))for(let M=-1;M<=7;M++)k+M<=-1||P<=k+M||(_>=0&&_<=6&&(M===0||M===6)||M>=0&&M<=6&&(_===0||_===6)||_>=2&&_<=4&&M>=2&&M<=4?w.set(C+_,k+M,!0,!0):w.set(C+_,k+M,!1,!0))}}function f(w){const E=w.size;for(let P=8;P<E-8;P++){const L=P%2===0;w.set(P,6,L,!0),w.set(6,P,L,!0)}}function p(w,E){const P=n.getPositions(E);for(let L=0;L<P.length;L++){const T=P[L][0],C=P[L][1];for(let k=-2;k<=2;k++)for(let _=-2;_<=2;_++)k===-2||k===2||_===-2||_===2||k===0&&_===0?w.set(T+k,C+_,!0,!0):w.set(T+k,C+_,!1,!0)}}function x(w,E){const P=w.size,L=u.getEncodedBits(E);let T,C,k;for(let _=0;_<18;_++)T=Math.floor(_/3),C=_%3+P-8-3,k=(L>>_&1)===1,w.set(T,C,k,!0),w.set(C,T,k,!0)}function j(w,E,P){const L=w.size,T=g.getEncodedBits(E,P);let C,k;for(C=0;C<15;C++)k=(T>>C&1)===1,C<6?w.set(C,8,k,!0):C<8?w.set(C+1,8,k,!0):w.set(L-15+C,8,k,!0),C<8?w.set(8,L-C-1,k,!0):C<9?w.set(8,15-C-1+1,k,!0):w.set(8,15-C-1,k,!0);w.set(L-8,8,1,!0)}function y(w,E){const P=w.size;let L=-1,T=P-1,C=7,k=0;for(let _=P-1;_>0;_-=2)for(_===6&&_--;;){for(let M=0;M<2;M++)if(!w.isReserved(T,_-M)){let D=!1;k<E.length&&(D=(E[k]>>>C&1)===1),w.set(T,_-M,D),C--,C===-1&&(k++,C=7)}if(T+=L,T<0||P<=T){T-=L,L=-L;break}}}function A(w,E,P){const L=new r;P.forEach(function(M){L.put(M.mode.bit,4),L.put(M.getLength(),m.getCharCountIndicator(M.mode,w)),M.write(L)});const T=s.getSymbolTotalCodewords(w),C=l.getTotalCodewordsCount(w,E),k=(T-C)*8;for(L.getLengthInBits()+4<=k&&L.put(0,4);L.getLengthInBits()%8!==0;)L.putBit(0);const _=(k-L.getLengthInBits())/8;for(let M=0;M<_;M++)L.put(M%2?17:236,8);return v(L,w,E)}function v(w,E,P){const L=s.getSymbolTotalCodewords(E),T=l.getTotalCodewordsCount(E,P),C=L-T,k=l.getBlocksCount(E,P),_=L%k,M=k-_,D=Math.floor(L/k),B=Math.floor(C/k),Q=B+1,Y=D-B,O=new d(Y);let $=0;const I=new Array(k),H=new Array(k);let ee=0;const Z=new Uint8Array(w.buffer);for(let q=0;q<k;q++){const re=q<M?B:Q;I[q]=Z.slice($,$+re),H[q]=O.encode(I[q]),$+=re,ee=Math.max(ee,re)}const K=new Uint8Array(L);let R=0,F,U;for(F=0;F<ee;F++)for(U=0;U<k;U++)F<I[U].length&&(K[R++]=I[U][F]);for(F=0;F<Y;F++)for(U=0;U<k;U++)K[R++]=H[U][F];return K}function S(w,E,P,L){let T;if(Array.isArray(w))T=h.fromArray(w);else if(typeof w=="string"){let D=E;if(!D){const B=h.rawSplit(w);D=u.getBestVersionForData(B,P)}T=h.fromString(w,D||40)}else throw new Error("Invalid data");const C=u.getBestVersionForData(T,P);if(!C)throw new Error("The amount of data is too big to be stored in a QR Code");if(!E)E=C;else if(E<C)throw new Error(`
|