@cedros/pay-react 1.1.5 → 1.1.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.
Files changed (57) hide show
  1. package/dist/CedrosContext-C2v_s8cc.js +6 -0
  2. package/dist/CedrosContext-D7nh5-Zh.mjs +2100 -0
  3. package/dist/WalletManager-B5KLZK2D.js +1 -0
  4. package/dist/WalletManager-oEjZhaFk.mjs +219 -0
  5. package/dist/components/CedrosPay.d.ts.map +1 -1
  6. package/dist/components/admin/AISettingsSection.d.ts.map +1 -1
  7. package/dist/components/admin/CouponsSection.d.ts.map +1 -1
  8. package/dist/components/admin/ErrorBanner.d.ts +11 -0
  9. package/dist/components/admin/ErrorBanner.d.ts.map +1 -0
  10. package/dist/components/admin/FAQSection.d.ts.map +1 -1
  11. package/dist/components/admin/MessagingSection.d.ts.map +1 -1
  12. package/dist/components/admin/OverviewSection.d.ts.map +1 -1
  13. package/dist/components/admin/ProductsSection.d.ts.map +1 -1
  14. package/dist/components/admin/RefundsSection.d.ts.map +1 -1
  15. package/dist/components/admin/SingleCategorySettings.d.ts.map +1 -1
  16. package/dist/components/admin/StorefrontSection.d.ts.map +1 -1
  17. package/dist/components/admin/SubscriptionsSection.d.ts.map +1 -1
  18. package/dist/components/admin/TransactionsSection.d.ts.map +1 -1
  19. package/dist/context/CedrosContext.d.ts +9 -3
  20. package/dist/context/CedrosContext.d.ts.map +1 -1
  21. package/dist/crypto-only.d.ts +9 -19
  22. package/dist/crypto-only.d.ts.map +1 -1
  23. package/dist/crypto-only.js +1 -1
  24. package/dist/crypto-only.mjs +766 -32
  25. package/dist/index-BFt38o8Q.mjs +88 -0
  26. package/dist/index-S3b2N8tp.js +136 -0
  27. package/dist/index-WcOlBYZJ.js +1 -0
  28. package/dist/{index-Bzp2srIS.mjs → index-iIxY1o71.mjs} +10413 -9402
  29. package/dist/index.d.ts +1 -7
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +1 -1
  32. package/dist/index.mjs +68 -75
  33. package/dist/managers/ManagerCache.d.ts +2 -2
  34. package/dist/managers/ManagerCache.d.ts.map +1 -1
  35. package/dist/pay-react.css +1 -1
  36. package/dist/{sections-D6R2jRAp.js → sections-bhZyRM7o.js} +1 -1
  37. package/dist/{sections-cz9ughWO.mjs → sections-otLBNrzu.mjs} +2 -2
  38. package/dist/solanaCheck-BS3QTE63.js +6 -0
  39. package/dist/solanaCheck-IlYsbXDd.mjs +27 -0
  40. package/dist/stripe-only.d.ts +4 -21
  41. package/dist/stripe-only.d.ts.map +1 -1
  42. package/dist/stripe-only.js +1 -1
  43. package/dist/stripe-only.mjs +71 -29
  44. package/dist/testing/index.js +1 -1
  45. package/dist/testing/index.mjs +1 -1
  46. package/dist/types/componentOptions.d.ts +15 -2
  47. package/dist/types/componentOptions.d.ts.map +1 -1
  48. package/dist/utils/index.d.ts +0 -1
  49. package/dist/utils/index.d.ts.map +1 -1
  50. package/dist/walletPool-BR6etEiq.mjs +67 -0
  51. package/dist/walletPool-BZyAG4YS.js +1 -0
  52. package/package.json +6 -1
  53. package/dist/CedrosContext-DUT3cLZg.mjs +0 -2474
  54. package/dist/CedrosContext-efFL4kQz.js +0 -11
  55. package/dist/index-CFzfjC82.js +0 -136
  56. package/dist/styles-C4-_hbgr.js +0 -1
  57. package/dist/styles-QcAsIVWl.mjs +0 -1909
@@ -1,136 +0,0 @@
1
- "use strict";const n=require("react/jsx-runtime"),w=require("react"),Hn=require("@solana/wallet-adapter-react"),fe=require("./styles-C4-_hbgr.js"),oe=require("./CedrosContext-efFL4kQz.js"),Gc=require("@solana/web3.js"),wi=require("@solana/wallet-adapter-base"),hp=require("@solana/wallet-adapter-react-ui");require("@solana/wallet-adapter-wallets");const oa=require("react-dom");function Qc(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const g=Qc(w),ys=Qc(oa);function gp(e){switch(e){case"mainnet-beta":return"https://api.mainnet-beta.solana.com";case"devnet":return"https://api.devnet.solana.com";case"testnet":return"https://api.testnet.solana.com";default:return"https://api.mainnet-beta.solana.com"}}function xp(e){try{const t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e}}function Yc(e={}){const{solanaCluster:t="mainnet-beta",solanaEndpoint:r,customRpcProviders:s=[],allowUnsafeScripts:o=!1,additionalScriptSrc:a=[],additionalConnectSrc:i=[],additionalFrameSrc:c=[],includeStripe:l=!0}=e;o&&console.warn("[CedrosPay] SECURITY WARNING: allowUnsafeScripts is enabled. This adds 'unsafe-inline' and 'unsafe-eval' to script-src, which significantly weakens CSP protection against XSS attacks. Only use this in development or if absolutely required by your framework.");const d=["'self'"];o&&d.push("'unsafe-inline'","'unsafe-eval'"),l&&d.push("https://js.stripe.com"),d.push(...a);const m=["'self'"];l&&m.push("https://api.stripe.com","https://*.stripe.com");const u=gp(t);if(m.push(u),r){const h=xp(r);m.includes(h)||m.push(h)}s.forEach(h=>{m.includes(h)||m.push(h)}),m.push(...i);const f=["'self'"];return l&&f.push("https://js.stripe.com","https://checkout.stripe.com"),f.push(...c),{scriptSrc:d,connectSrc:m,frameSrc:f}}function Kc(e,t="header"){const{scriptSrc:r,connectSrc:s,frameSrc:o}=e;switch(t){case"header":case"meta":case"nextjs":case"nginx":{const a=[];return r.length>0&&a.push(`script-src ${r.join(" ")}`),s.length>0&&a.push(`connect-src ${s.join(" ")}`),o.length>0&&a.push(`frame-src ${o.join(" ")}`),a.join("; ")}case"helmet":{const a={};return r.length>0&&(a.scriptSrc=r),s.length>0&&(a.connectSrc=s),o.length>0&&(a.frameSrc=o),a}case"directives":return{scriptSrc:r,connectSrc:s,frameSrc:o};default:throw new Error(`Unknown CSP format: ${t}`)}}function yp(e={},t="header"){const r=Yc(e);return Kc(r,t)}const bp={HELIUS:"https://*.helius-rpc.com",QUICKNODE:"https://*.quicknode.pro",ALCHEMY:"https://*.alchemy.com",ANKR:"https://rpc.ankr.com",TRITON:"https://*.rpcpool.com"},vp={MAINNET_CUSTOM_RPC:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),MAINNET_NEXTJS:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),DEVNET:()=>({solanaCluster:"devnet",allowUnsafeScripts:!1}),CRYPTO_ONLY:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,includeStripe:!1}),STRIPE_ONLY:()=>({solanaCluster:"mainnet-beta",includeStripe:!0,customRpcProviders:[]})};function fr(e){return new Date(e).toLocaleString()}const Jc=({resource:e,items:t,label:r,cardLabel:s,cryptoLabel:o,creditsLabel:a,showCard:i=!0,showCrypto:c=!0,showCredits:l=!1,onPaymentAttempt:d,onPaymentSuccess:m,onPaymentError:u,onStripeSuccess:f,onCryptoSuccess:h,onCreditsSuccess:x,onStripeError:p,onCryptoError:y,onCreditsError:j,customerEmail:b,successUrl:v,cancelUrl:_,metadata:C,couponCode:E,authToken:S,autoDetectWallets:N=!0,testPageUrl:U,hideMessages:k=!1,renderModal:A})=>{const P=oe.useCedrosTheme(),[D,z]=w.useState(!1),{status:L,processPayment:O,processCartCheckout:M}=fe.useStripeCheckout(),{isCartMode:R,effectiveResource:W}=fe.usePaymentMode(e,t),{t:T}=fe.useTranslation(),V=r||T("ui.purchase"),ee=s||T("ui.card"),B=o||T("ui.usdc_solana"),Y=a||T("ui.pay_with_credits")||"Pay with Credits",J=w.useCallback(async()=>{if(N&&i){const{detectSolanaWallets:q}=await Promise.resolve().then(()=>Sk);if(!q()){const te=R?void 0:W,ce=R&&t?fe.getCartItemCount(t):void 0;fe.emitPaymentStart("stripe",te,ce),d&&d("stripe"),fe.emitPaymentProcessing("stripe",te,ce);let pe;R&&t?pe=await M(t,v,_,C,b,E):W&&(pe=await O(W,v,_,C,b,E)),pe&&pe.success&&pe.transactionId?(fe.emitPaymentSuccess("stripe",pe.transactionId,te,ce),f?f(pe.transactionId):m&&m(pe.transactionId)):pe&&!pe.success&&pe.error&&(fe.emitPaymentError("stripe",pe.error,te,ce),p?p(pe.error):u&&u(pe.error));return}}z(!0)},[N,i,R,t,W,M,O,v,_,C,b,E,m,u,f,p,d]),ge=w.useMemo(()=>R&&t?`purchase-cart-${t.map(q=>q.resource).join("-")}`:`purchase-${W||"unknown"}`,[R,t,W]),F=w.useMemo(()=>fe.createDedupedClickHandler(ge,J),[ge,J]),K=L==="loading",me={isOpen:D,onClose:()=>z(!1),resource:R?void 0:W,items:R?t:void 0,cardLabel:ee,cryptoLabel:B,creditsLabel:Y,showCard:i,showCrypto:c,showCredits:l,onPaymentAttempt:d,onPaymentSuccess:q=>{z(!1),m?.(q)},onPaymentError:q=>{z(!1),u?.(q)},onStripeSuccess:q=>{z(!1),f?.(q)},onCryptoSuccess:q=>{z(!1),h?.(q)},onCreditsSuccess:q=>{z(!1),x?.(q)},onStripeError:q=>{z(!1),p?.(q)},onCryptoError:q=>{z(!1),y?.(q)},onCreditsError:q=>{z(!1),j?.(q)},customerEmail:b,successUrl:v,cancelUrl:_,metadata:C,couponCode:E,authToken:S,testPageUrl:U,hideMessages:k};return n.jsxs("div",{className:P.unstyled?"":P.className,style:P.unstyled?{}:P.style,children:[n.jsx("button",{onClick:F,disabled:K,className:P.unstyled?"":"cedros-theme__button cedros-theme__stripe",style:{width:"100%",cursor:K?"not-allowed":"pointer",opacity:K?.6:1},type:"button",children:K?T("ui.processing"):V}),A?A(me):n.jsx(fe.PaymentModal,{...me})]})};function wp(e){const{resource:t,items:r,checkout:s={},display:o={},callbacks:a={},advanced:i={}}=e,{config:c,walletPool:l}=oe.useCedrosContext(),d=oe.useCedrosTheme(),{isCartMode:m}=fe.usePaymentMode(t,r),u=w.useMemo(()=>({marginTop:"0.5rem",fontSize:"0.875rem",color:d.tokens.surfaceText,opacity:.7,textAlign:"center"}),[d.tokens.surfaceText]),f=w.useMemo(()=>i.wallets&&i.wallets.length>0?i.wallets:l.getAdapters(),[i.wallets,l]),h=w.useMemo(()=>r?fe.getCartItemCount(r):0,[r]),x=w.useMemo(()=>a.onPaymentSuccess?D=>a.onPaymentSuccess({transactionId:D,method:"stripe"}):void 0,[a.onPaymentSuccess]),p=w.useMemo(()=>a.onPaymentSuccess?D=>a.onPaymentSuccess({transactionId:D,method:"crypto"}):void 0,[a.onPaymentSuccess]),y=w.useMemo(()=>a.onPaymentError?D=>a.onPaymentError({message:D,method:"stripe"}):void 0,[a.onPaymentError]),j=w.useMemo(()=>a.onPaymentError?D=>a.onPaymentError({message:D,method:"crypto"}):void 0,[a.onPaymentError]),b=w.useMemo(()=>a.onPaymentSuccess?D=>a.onPaymentSuccess({transactionId:D,method:"credits"}):void 0,[a.onPaymentSuccess]),v=w.useMemo(()=>a.onPaymentError?D=>a.onPaymentError({message:D,method:"credits"}):void 0,[a.onPaymentError]),_=w.useMemo(()=>a.onPaymentAttempt?()=>a.onPaymentAttempt("credits"):void 0,[a.onPaymentAttempt]),C=c.solanaEndpoint??Gc.clusterApiUrl(c.solanaCluster);if(!t&&(!r||r.length===0))return oe.getLogger().error('CedrosPay: Must provide either "resource" or "items" prop'),n.jsx("div",{className:o.className,style:{color:d.tokens.errorText},children:"Configuration error: No resource or items provided"});const E=o.showCard??!0,S=o.showCrypto??!0,N=o.showCredits??!1,U=o.showPurchaseButton??!1,k=o.layout??"vertical",A=o.hideMessages??!1,P=i.autoDetectWallets??!0;return n.jsx("div",{className:d.unstyled?o.className:d.className,style:d.unstyled?{}:d.style,children:n.jsx(Hn.ConnectionProvider,{endpoint:C,children:n.jsx(Hn.WalletProvider,{wallets:f,autoConnect:!1,children:n.jsx("div",{className:d.unstyled?o.className:`cedros-theme__pay ${o.className||""}`,children:n.jsxs("div",{className:d.unstyled?"":`cedros-theme__pay-content cedros-theme__pay-content--${k}`,children:[U?n.jsx(Jc,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,label:o.purchaseLabel,cardLabel:o.cardLabel,cryptoLabel:o.cryptoLabel,showCard:E,showCrypto:S,onPaymentAttempt:a.onPaymentAttempt,onPaymentSuccess:x,onPaymentError:y,onStripeSuccess:x,onCryptoSuccess:p,onStripeError:y,onCryptoError:j,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,autoDetectWallets:P,testPageUrl:i.testPageUrl,hideMessages:A,renderModal:o.renderModal}):n.jsxs(n.Fragment,{children:[E&&n.jsx(fe.StripeButton,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,label:o.cardLabel,onAttempt:a.onPaymentAttempt,onSuccess:x,onError:y}),S&&n.jsx(fe.CryptoButton,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,metadata:s.metadata,couponCode:s.couponCode,label:o.cryptoLabel,onAttempt:a.onPaymentAttempt,onSuccess:p,onError:j,testPageUrl:i.testPageUrl,hideMessages:A}),N&&n.jsx(fe.CreditsButton,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,authToken:s.authToken,metadata:s.metadata,couponCode:s.couponCode,label:o.creditsLabel,onAttempt:_,onSuccess:b,onError:v})]}),m&&r&&r.length>1&&!A&&n.jsxs("div",{style:u,children:["Checking out ",h," items"]})]})})})})})}const G={products:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),n.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),n.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),n.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),n.jsx("path",{d:"M3 3v5h5"}),n.jsx("path",{d:"M12 7v5l4 2"})]}),settings:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.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"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.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"}),n.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:n.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:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"}),n.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),n.jsx("path",{d:"M8 16H3v5"})]}),check:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})}),plus:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),n.jsx("path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9"}),n.jsx("path",{d:"M12 3v6"})]}),arrowUp:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7-7 7 7"}),n.jsx("path",{d:"M12 19V5"})]}),arrowDown:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7 7 7-7"}),n.jsx("path",{d:"M12 5v14"})]}),delete:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),n.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),faq:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),n.jsx("path",{d:"M12 17h.01"})]}),chat:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),n.jsx("path",{d:"M2 12h20"})]}),ai:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),n.jsx("path",{d:"M10 10v.5"}),n.jsx("path",{d:"M14 10v.5"}),n.jsx("path",{d:"M12 14v2"}),n.jsx("path",{d:"M8 18h8"}),n.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),n.jsx("path",{d:"M6 12v6"}),n.jsx("path",{d:"M18 12v6"})]}),notifications:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),n.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),n.jsx("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),n.jsx("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),n.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),n.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),n.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),n.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),n.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),n.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),n.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),n.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),n.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),n.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),n.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),n.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),n.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),n.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),n.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),n.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),n.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function Gn({stats:e,isLoading:t=!1,onRefresh:r}){return n.jsxs("div",{className:"cedros-admin__stats-bar",children:[n.jsx("div",{className:"cedros-admin__stats-bar-grid",children:e.map((s,o)=>n.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[n.jsx("span",{className:"cedros-admin__stats-bar-label",children:s.label}),n.jsx("span",{className:`cedros-admin__stats-bar-value ${s.variant?`cedros-admin__stats-bar-value--${s.variant}`:""}`,children:t?n.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):s.value}),s.description&&n.jsx("span",{className:"cedros-admin__stats-bar-desc",children:s.description})]},o))}),r&&n.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:r,disabled:t,title:"Refresh stats",children:t?G.loading:G.refresh})]})}function _p({serverUrl:e,productId:t,apiKey:r,authManager:s}){const[o,a]=w.useState(null),[i,c]=w.useState(!1),[l,d]=w.useState(!1),[m,u]=w.useState(null),f=w.useCallback(async()=>{if(t){c(!0),u(null);try{let p;if(s?.isAuthenticated())p=await s.fetchWithAuth(`/admin/products/${t}/variations`);else{const y={"Content-Type":"application/json"};r&&(y["X-API-Key"]=r);const j=await fetch(`${e}/admin/products/${t}/variations`,{headers:y});if(!j.ok)throw new Error(`Failed to fetch variations: ${j.status}`);p=await j.json()}p.variationConfig||(p.variationConfig={variationTypes:[]}),p.variants||(p.variants=[]),a(p)}catch(p){const y=p instanceof Error?p.message:"Failed to fetch variations";u(y),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,r,s]),h=w.useCallback(async p=>{if(!t)return null;d(!0),u(null);try{let y;if(s?.isAuthenticated())y=await s.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(p)});else{const j={"Content-Type":"application/json"};r&&(j["X-API-Key"]=r);const b=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:j,body:JSON.stringify(p)});if(!b.ok)throw new Error(`Failed to save variations: ${b.status}`);y=await b.json()}return a({productId:t,variationConfig:y.variationConfig,variants:y.variants}),{variantsCreated:y.variantsCreated}}catch(y){const j=y instanceof Error?y.message:"Failed to save variations";return u(j),null}finally{d(!1)}},[e,t,r,s]),x=w.useCallback(async p=>{if(!t||p.length===0)return!1;d(!0),u(null);try{if(s?.isAuthenticated())await s.fetchWithAuth(`/admin/products/${t}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:p})});else{const y={"Content-Type":"application/json"};r&&(y["X-API-Key"]=r);const j=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:y,body:JSON.stringify({updates:p})});if(!j.ok)throw new Error(`Failed to update inventory: ${j.status}`)}if(o){const y=new Map(p.map(j=>[j.variantId,j]));a({...o,variants:o.variants.map(j=>{const b=y.get(j.id);return b?{...j,inventoryQuantity:b.inventoryQuantity,inventoryStatus:b.inventoryStatus??j.inventoryStatus}:j})})}return!0}catch(y){const j=y instanceof Error?y.message:"Failed to update inventory";return u(j),!1}finally{d(!1)}},[e,t,r,s,o]);return{data:o,isLoading:i,error:m,fetch:f,save:h,bulkUpdateInventory:x,isSaving:l}}function _i(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function jp({value:e,onChange:t,maxTypes:r=5,maxValuesPerType:s=20,disabled:o=!1}){const[a,i]=w.useState(null),[c,l]=w.useState(""),[d,m]=w.useState({}),u=e.variationTypes,f=w.useCallback(()=>{if(!c.trim()||u.length>=r)return;const v={id:_i(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,v]}),l(""),i(v.id)},[c,u,r,t]),h=w.useCallback(v=>{t({variationTypes:u.filter(_=>_.id!==v).map((_,C)=>({..._,displayOrder:C}))}),a===v&&i(null)},[u,t,a]),x=w.useCallback((v,_)=>{t({variationTypes:u.map(C=>C.id===v?{...C,name:_}:C)})},[u,t]),p=w.useCallback((v,_)=>{const C=u.findIndex(N=>N.id===v);if(C===-1||_==="up"&&C===0||_==="down"&&C===u.length-1)return;const E=[...u],S=_==="up"?C-1:C+1;[E[C],E[S]]=[E[S],E[C]],t({variationTypes:E.map((N,U)=>({...N,displayOrder:U}))})},[u,t]),y=w.useCallback(v=>{const _=(d[v]||"").trim();if(!_)return;const C=u.find(S=>S.id===v);if(!C||C.values.length>=s)return;const E={id:_i(),label:_};t({variationTypes:u.map(S=>S.id===v?{...S,values:[...S.values,E]}:S)}),m(S=>({...S,[v]:""}))},[u,d,s,t]),j=w.useCallback((v,_)=>{t({variationTypes:u.map(C=>C.id===v?{...C,values:C.values.filter(E=>E.id!==_)}:C)})},[u,t]),b=w.useCallback((v,_,C)=>{t({variationTypes:u.map(E=>E.id===v?{...E,values:E.values.map(S=>S.id===_?{...S,label:C}:S)}:E)})},[u,t]);return n.jsxs("div",{className:"cedros-admin__variation-editor",children:[n.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[u.length,"/",r," types"]})]}),u.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):n.jsx("div",{className:"cedros-admin__variation-type-list",children:u.map((v,_)=>n.jsxs("div",{className:"cedros-admin__variation-type-item",children:[n.jsxs("div",{className:"cedros-admin__variation-type-header",children:[n.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>p(v.id,"up"),disabled:o||_===0,title:"Move up",children:G.arrowUp}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>p(v.id,"down"),disabled:o||_===u.length-1,title:"Move down",children:G.arrowDown})]}),n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:v.name,onChange:C=>x(v.id,C.target.value),disabled:o,placeholder:"Type name"}),n.jsxs("span",{className:"cedros-admin__variation-value-count",children:[v.values.length," values"]}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===v.id?null:v.id),children:a===v.id?"Collapse":"Edit values"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>h(v.id),disabled:o,title:"Remove type",children:G.delete})]}),a===v.id&&n.jsxs("div",{className:"cedros-admin__variation-values",children:[n.jsxs("div",{className:"cedros-admin__variation-values-header",children:[n.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',v.name,'"']}),n.jsxs("span",{style:{fontSize:11,opacity:.7},children:[v.values.length,"/",s]})]}),v.values.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):n.jsx("div",{className:"cedros-admin__variation-value-list",children:v.values.map(C=>n.jsxs("div",{className:"cedros-admin__variation-value-item",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:C.label,onChange:E=>b(v.id,C.id,E.target.value),disabled:o}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>j(v.id,C.id),disabled:o,title:"Remove value",children:G.close})]},C.id))}),v.values.length<s&&n.jsxs("div",{className:"cedros-admin__variation-add-value",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:d[v.id]||"",onChange:C=>m(E=>({...E,[v.id]:C.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),y(v.id))}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>y(v.id),disabled:o||!d[v.id]?.trim(),children:"Add"})]})]})]},v.id))}),u.length<r&&n.jsxs("div",{className:"cedros-admin__variation-add-type",children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:v=>l(v.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:v=>{v.key==="Enter"&&(v.preventDefault(),f())}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:f,disabled:o||!c.trim(),children:"Add Type"})]})]})}function Xc({value:e,onChange:t,options:r,placeholder:s="Filter",disabled:o}){const[a,i]=w.useState(!1),c=w.useRef(null),d=r.find(m=>m.value===e)?.label||s;return w.useEffect(()=>{const m=u=>{c.current&&!c.current.contains(u.target)&&i(!1)};if(a)return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[a]),w.useEffect(()=>{const m=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[a]),n.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[n.jsx("span",{children:d}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:G.chevronDown})]}),a&&n.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:r.map(m=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${m.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{m.disabled||(t(m.value),i(!1))},role:"option","aria-selected":m.value===e,disabled:m.disabled,children:[m.label,m.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:G.check})]},m.value))})]})}function lt({value:e,onChange:t,options:r,label:s,description:o,disabled:a,className:i,style:c}){const[l,d]=w.useState(!1),m=w.useRef(null),f=r.find(h=>h.value===e)?.label||"Select...";return w.useEffect(()=>{const h=x=>{m.current&&!m.current.contains(x.target)&&d(!1)};if(l)return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[l]),w.useEffect(()=>{const h=x=>{x.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[l]),n.jsxs("div",{className:`cedros-admin__field ${i||""}`,style:c,children:[n.jsx("label",{className:"cedros-admin__field-label",children:s}),n.jsxs("div",{className:"cedros-admin__dropdown cedros-admin__dropdown--form",ref:m,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger cedros-admin__dropdown-trigger--form",onClick:()=>!a&&d(!l),"aria-expanded":l,"aria-haspopup":"listbox",disabled:a,children:[n.jsx("span",{children:f}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${l?"cedros-admin__dropdown-chevron--open":""}`,children:G.chevronDown})]}),l&&n.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:r.map(h=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${h.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{h.disabled||(t(h.value),d(!1))},role:"option","aria-selected":h.value===e,disabled:h.disabled,children:[h.label,h.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:G.check})]},h.value))})]}),o&&n.jsx("p",{className:"cedros-admin__field-description",children:o})]})}function ji(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Sp(e){if(e.length===0)return[];const t=[...e].sort((s,o)=>s.displayOrder-o.displayOrder),r=(s,o)=>{if(s>=t.length){const c=o.valueIds.sort().join("|"),l=Object.values(o.options).join(" / ");return[{key:c,title:l,optionValueIds:[...o.valueIds],options:{...o.options}}]}const a=t[s],i=[];for(const c of a.values)i.push(...r(s+1,{valueIds:[...o.valueIds,c.id],options:{...o.options,[a.name]:c.label}}));return i};return r(0,{valueIds:[],options:{}})}function kp(e){return e.optionValueIds?.length?[...e.optionValueIds].sort().join("|"):Object.entries(e.options).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${t}:${r}`).join("|")}function Cp({variationConfig:e,variants:t,onChange:r,defaultPrice:s=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=w.useMemo(()=>Sp(e.variationTypes),[e.variationTypes]),l=w.useMemo(()=>{const p=new Map;for(const y of t)p.set(kp(y),y);return p},[t]),{existingRows:d,possibleRows:m}=w.useMemo(()=>{const p=[],y=[];for(const j of c){const b=l.get(j.key);b?p.push({combo:j,variant:b}):y.push(j)}return{existingRows:p,possibleRows:y}},[c,l]),u=w.useCallback((p,y)=>{r(t.map(j=>j.id===p?{...j,...y}:j))},[t,r]),f=w.useCallback(p=>{r(t.filter(y=>y.id!==p))},[t,r]),h=w.useCallback(p=>{if(t.length>=a)return;const y={id:ji(),title:p.title,options:p.options,optionValueIds:p.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};r([...t,y])},[t,r,a,s]),x=w.useCallback(()=>{const p=a-t.length,j=m.slice(0,p).map(b=>({id:ji(),title:b.title,options:b.options,optionValueIds:b.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));r([...t,...j])},[t,r,m,a,s]);return e.variationTypes.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):c.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):n.jsxs("div",{className:"cedros-admin__variant-grid",children:[n.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[t.length,"/",a," variants (",c.length," ","possible)"]})]}),m.length>0&&t.length<a&&n.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[n.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:x,disabled:i,children:["Generate All (",Math.min(m.length,a-t.length),")"]}),n.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{children:"Variant"}),n.jsx("th",{style:{width:100},children:"Price"}),n.jsx("th",{style:{width:80},children:"Qty"}),n.jsx("th",{style:{width:100},children:"SKU"}),n.jsx("th",{style:{width:100},children:"Status"}),n.jsx("th",{style:{width:80},children:"Actions"})]})}),n.jsxs("tbody",{children:[d.map(({combo:p,variant:y})=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:p.title}),n.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(p.options).map(([j,b])=>`${j}: ${b}`).join(", ")})]})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx("span",{children:o}),n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:y.price??"",onChange:j=>u(y.id,{price:j.target.value===""?void 0:parseFloat(j.target.value)||0}),disabled:i,min:"0",step:"0.01",style:{width:70}})]})}),n.jsx("td",{children:n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:y.inventoryQuantity??"",onChange:j=>u(y.id,{inventoryQuantity:j.target.value===""?void 0:parseInt(j.target.value)||0}),disabled:i,min:"0",style:{width:60}})}),n.jsx("td",{children:n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:y.sku??"",onChange:j=>u(y.id,{sku:j.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),n.jsx("td",{children:n.jsx(Xc,{value:y.inventoryStatus??"in_stock",onChange:j=>u(y.id,{inventoryStatus:j}),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],disabled:i})}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>f(y.id),disabled:i,title:"Remove variant",children:G.trash})})]},y.id)),m.length>0&&t.length<a&&n.jsxs(n.Fragment,{children:[n.jsx("tr",{className:"cedros-admin__variant-separator",children:n.jsx("td",{colSpan:6,children:n.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",m.length,")"]})})}),m.slice(0,10).map(p=>n.jsxs("tr",{className:"cedros-admin__variant-possible",children:[n.jsx("td",{children:n.jsx("span",{style:{opacity:.6},children:p.title})}),n.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>h(p),disabled:i,title:"Create variant",children:G.plus})})]},p.key)),m.length>10&&n.jsx("tr",{className:"cedros-admin__variant-more",children:n.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",m.length-10," more combinations"]})})]})]})]})})]})}function Np({serverUrl:e,productId:t,productTitle:r,defaultPrice:s=0,currencySymbol:o="$",apiKey:a,authManager:i,onClose:c}){const{data:l,isLoading:d,error:m,fetch:u,save:f,isSaving:h}=_p({serverUrl:e,productId:t,apiKey:a,authManager:i}),[x,p]=w.useState({variationTypes:[]}),[y,j]=w.useState([]),[b,v]=w.useState(!1),[_,C]=w.useState(!1);w.useEffect(()=>{u()},[u]),w.useEffect(()=>{l&&(p(l.variationConfig),j(l.variants),v(!1))},[l]);const E=w.useCallback(U=>{p(U),v(!0),C(!1)},[]),S=w.useCallback(U=>{j(U),v(!0),C(!1)},[]),N=w.useCallback(async()=>{const U=new Set((l?.variants??[]).map(z=>z.id)),k=y.filter(z=>!U.has(z.id)),A=y.filter(z=>U.has(z.id)),P=(l?.variants??[]).filter(z=>!y.some(L=>L.id===z.id)).map(z=>z.id);await f({variationConfig:x,createVariants:k.map(z=>({optionValueIds:z.optionValueIds??[],inventoryQuantity:z.inventoryQuantity,sku:z.sku,price:z.price})),updateVariants:A.map(z=>({id:z.id,inventoryQuantity:z.inventoryQuantity,sku:z.sku,price:z.price,inventoryStatus:z.inventoryStatus})),deleteVariantIds:P.length>0?P:void 0})&&(v(!1),C(!0),setTimeout(()=>C(!1),3e3))},[x,y,l?.variants,f]);return d?n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:G.close})]}),n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading variations..."]})]}):n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),n.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[_&&n.jsxs("span",{className:"cedros-admin__success-text",children:[G.check," Saved"]}),b&&n.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:N,disabled:h||!b,children:h?"Saving...":"Save Changes"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:G.close})]})]}),m&&n.jsx("div",{className:"cedros-admin__error-banner",children:m}),n.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(jp,{value:x,onChange:E,disabled:h})}),x.variationTypes.length>0&&n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(Cp,{variationConfig:x,variants:y,onChange:S,defaultPrice:s,currencySymbol:o,disabled:h})})]})]})}function el({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=w.useState([]),[i,c]=w.useState(!0),[l,d]=w.useState(!1),[m,u]=w.useState(!1),[f,h]=w.useState(null),[x,p]=w.useState(null),[y,j]=w.useState(null),[b,v]=w.useState({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),_=L=>{const O=L.tagsCsv.split(",").map(B=>B.trim()).filter(Boolean),M=L.categoryIdsCsv.split(",").map(B=>B.trim()).filter(Boolean),R={email:L.checkoutEmail,name:L.checkoutName,phone:L.checkoutPhone,shippingAddress:L.checkoutShippingAddress,billingAddress:L.checkoutBillingAddress},W=L.fulfillmentType==="shipping"?"physical":"digital",T={title:L.title,slug:L.slug||L.id,shipping_profile:W,inventory_status:L.inventoryStatus,checkout_requirements:JSON.stringify(R),fulfillment_type:L.fulfillmentType};L.imageUrl&&(T.image_url=L.imageUrl);const V=L.compareAtUsd?Math.round(Number(L.compareAtUsd)*100):0;V&&(T.compare_at_amount_cents=String(V)),O.length&&(T.tags=JSON.stringify(O)),M.length&&(T.category_ids=JSON.stringify(M)),L.fulfillmentNotes&&(T.fulfillment_notes=L.fulfillmentNotes);const ee=L.shippingCountriesCsv.split(",").map(B=>B.trim().toUpperCase()).filter(Boolean);return ee.length&&(T.shippingCountries=ee.join(","),T.shipping_countries=ee.join(",")),T},C=L=>L.metadata?.title||L.description||L.id,E=L=>L.metadata?.image_url,S=w.useCallback(async()=>{try{let L;if(s?.isAuthenticated())L=await s.fetchWithAuth(`/admin/products?limit=${r}`);else{const O={"Content-Type":"application/json"};t&&(O["X-API-Key"]=t);const M=await fetch(`${e}/admin/products?limit=${r}`,{headers:O});if(!M.ok)throw new Error(`Failed to fetch products: ${M.status}`);L=await M.json()}a(L.products||[])}catch{a([{id:"premium-article",description:"Premium Article Access",fiatAmountCents:500,fiatCurrency:"usd",cryptoAtomicAmount:5e6,cryptoToken:"USDC",active:!0},{id:"video-course",description:"Video Course Bundle",fiatAmountCents:2999,fiatCurrency:"usd",cryptoAtomicAmount:2999e4,cryptoToken:"USDC",active:!0},{id:"api-credits",description:"API Credits Pack",fiatAmountCents:1e3,fiatCurrency:"usd",cryptoAtomicAmount:1e7,cryptoToken:"USDC",active:!0}])}finally{c(!1)}},[e,t,r,s]);w.useEffect(()=>{S()},[S]);const N=async L=>{if(L.preventDefault(),!(!b.id||!b.description)){if(h(null),b.fulfillmentType==="shipping"&&b.checkoutShippingAddress&&!b.shippingCountriesCsv.split(",").map(M=>M.trim()).filter(Boolean).length){h("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:O}=b,M=b.inventoryQuantity===""?void 0:Number.isFinite(Number(b.inventoryQuantity))?Number(b.inventoryQuantity):void 0,R=Number(b.priceUsd)||0,W=Math.round(R*100),T=Math.round(R*1e6),V={id:b.id,description:b.description,fiatAmountCents:W,fiatCurrency:b.fiatCurrency,cryptoAtomicAmount:T,cryptoToken:b.cryptoToken,...M!==void 0?{inventoryQuantity:M}:{},metadata:{...O?{product_type:O}:{},..._(b)}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(V)});else{const ee={"Content-Type":"application/json"};t&&(ee["X-API-Key"]=t);const B=await fetch(`${e}/admin/products`,{method:"POST",headers:ee,body:JSON.stringify(V)});if(!B.ok)throw new Error(`Failed to create product: ${B.status}`)}v({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),d(!1),S()}catch{const M=Number(b.priceUsd)||0;a(R=>[...R,{id:b.id,title:b.title||void 0,slug:b.slug||void 0,imageUrl:b.imageUrl||void 0,description:b.description,fiatAmountCents:Math.round(M*100),fiatCurrency:b.fiatCurrency,cryptoAtomicAmount:Math.round(M*1e6),cryptoToken:b.cryptoToken,inventoryQuantity:b.inventoryQuantity===""?void 0:Number.isFinite(Number(b.inventoryQuantity))?Number(b.inventoryQuantity):void 0,active:!0,metadata:{...b.productType?{product_type:b.productType}:{},..._(b)}}]),v({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),d(!1)}finally{u(!1)}}},U=L=>`$${(L/100).toFixed(2)}`,k=L=>{switch(L){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},A=w.useMemo(()=>{const L=o.filter(M=>M.active).length,O=o.reduce((M,R)=>{const W=R.variations?.length??0;return M+(W>0?W:1)},0);return{activeCount:L,totalSkus:O}},[o]),P=L=>{j(O=>!O||O.key!==L?{key:L,direction:"asc"}:{key:L,direction:O.direction==="asc"?"desc":"asc"})},D=L=>!y||y.key!==L?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:G.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:y.direction==="asc"?G.chevronUp:G.chevronDown}),z=w.useMemo(()=>{if(!y)return o;const L=y.direction==="asc"?1:-1,O=M=>{switch(y.key){case"product":return C(M);case"type":return k(M.metadata?.product_type);case"price":return M.fiatAmountCents??0;case"status":return M.active?1:0;case"id":default:return M.id}};return[...o].sort((M,R)=>{const W=O(M),T=O(R);return typeof W=="number"&&typeof T=="number"?(W-T)*L:String(W).localeCompare(String(T),void 0,{sensitivity:"base"})*L})},[o,y]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Gn,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:A.activeCount,variant:A.activeCount>0?"success":"muted"},{label:"Total SKUs",value:A.totalSkus}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{h(null),d(!l)},children:[l?G.close:G.plus,l?"Cancel":"Add Product"]})]}),l&&n.jsxs("form",{onSubmit:N,className:"cedros-admin__add-form",children:[f&&n.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:f}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.id,onChange:L=>v(O=>({...O,id:L.target.value})),placeholder:"e.g., premium-article",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.title,onChange:L=>v(O=>({...O,title:L.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.slug,onChange:L=>v(O=>({...O,slug:L.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:b.imageUrl,onChange:L=>v(O=>({...O,imageUrl:L.target.value})),placeholder:"https://..."})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.description,onChange:L=>v(O=>({...O,description:L.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(lt,{value:b.productType,onChange:L=>v(O=>({...O,productType:L})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"}],label:"Product Type"}),n.jsx(lt,{value:b.fulfillmentType,onChange:L=>{const O=L;v(M=>({...M,fulfillmentType:O,checkoutShippingAddress:O==="shipping"?M.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),b.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(lt,{value:b.inventoryStatus,onChange:L=>v(O=>({...O,inventoryStatus:L})),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],label:"Inventory status"}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:b.inventoryQuantity,onChange:L=>v(O=>({...O,inventoryQuantity:L.target.value===""?"":parseInt(L.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:b.compareAtUsd===""?"":b.compareAtUsd,onChange:L=>v(O=>({...O,compareAtUsd:L.target.value===""?"":parseFloat(L.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:b.priceUsd===""?"":b.priceUsd,onChange:L=>v(O=>({...O,priceUsd:L.target.value===""?"":parseFloat(L.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.tagsCsv,onChange:L=>v(O=>({...O,tagsCsv:L.target.value})),placeholder:"e.g., core, new, gift"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.categoryIdsCsv,onChange:L=>v(O=>({...O,categoryIdsCsv:L.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(lt,{value:b.checkoutEmail,onChange:L=>v(O=>({...O,checkoutEmail:L})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),n.jsx(lt,{value:b.checkoutName,onChange:L=>v(O=>({...O,checkoutName:L})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),n.jsx(lt,{value:b.checkoutPhone,onChange:L=>v(O=>({...O,checkoutPhone:L})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[b.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:b.checkoutShippingAddress,onChange:L=>v(O=>({...O,checkoutShippingAddress:L.target.checked}))}),"Collect shipping address"]})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:b.checkoutBillingAddress,onChange:L=>v(O=>({...O,checkoutBillingAddress:L.target.checked}))}),"Collect billing address"]})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.fulfillmentNotes,onChange:L=>v(O=>({...O,fulfillmentNotes:L.target.value})),placeholder:b.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),b.fulfillmentType==="shipping"&&b.checkoutShippingAddress&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.shippingCountriesCsv,onChange:L=>v(O=>({...O,shippingCountriesCsv:L.target.value})),placeholder:"e.g., US,CA"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Product"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading products..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":y?.key==="id"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("id"),children:["ID",D("id")]})}),n.jsx("th",{"aria-sort":y?.key==="product"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("product"),children:["Product",D("product")]})}),n.jsx("th",{"aria-sort":y?.key==="type"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("type"),children:["Type",D("type")]})}),n.jsx("th",{"aria-sort":y?.key==="price"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("price"),children:["Price",D("price")]})}),n.jsx("th",{"aria-sort":y?.key==="status"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("status"),children:["Status",D("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:z.map(L=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:L.id})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[E(L)?n.jsx("img",{src:E(L),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):n.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:C(L)}),n.jsx("span",{style:{opacity:.8},children:L.description})]})]})}),n.jsx("td",{children:k(L.metadata?.product_type)}),n.jsx("td",{children:U(L.fiatAmountCents)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${L.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:L.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>p(L),children:"Variations"})]})})]},L.id))})]})}),x&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>p(null),children:n.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:L=>L.stopPropagation(),children:n.jsx(Np,{serverUrl:e,productId:x.id,productTitle:C(x),defaultPrice:x.fiatAmountCents/100,apiKey:t,authManager:s,onClose:()=>p(null)})})})]})}function tl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=w.useState([]),[i,c]=w.useState(null),[l,d]=w.useState(!0),[m,u]=w.useState(!0),[f,h]=w.useState(""),[x,p]=w.useState(null),y=w.useCallback(async()=>{u(!0);try{let C;if(s?.isAuthenticated())C=await s.fetchWithAuth("/admin/stats");else{const E={"Content-Type":"application/json"};t&&(E["X-API-Key"]=t);const S=await fetch(`${e}/admin/stats`,{headers:E});if(!S.ok)throw new Error(`Failed to fetch stats: ${S.status}`);C=await S.json()}c(C)}catch{c({totalRevenue:12450,totalTransactions:342,activeProducts:8,pendingRefunds:3,revenueByMethod:{stripe:8200,x402:3150,credits:1100},transactionsByMethod:{stripe:210,x402:98,credits:34}})}finally{u(!1)}},[e,t,s]);w.useEffect(()=>{y()},[y]),w.useEffect(()=>{(async()=>{try{let E;const S=new URLSearchParams({limit:r.toString()});f&&S.set("method",f);const N=`/admin/transactions?${S}`;if(s?.isAuthenticated())E=await s.fetchWithAuth(N);else{const U={"Content-Type":"application/json"};t&&(U["X-API-Key"]=t);const k=await fetch(`${e}${N}`,{headers:U});if(!k.ok)throw new Error(`Failed to fetch transactions: ${k.status}`);E=await k.json()}a(E.transactions||[])}catch{a([{id:"txn_1",resourceId:"premium-article",method:"stripe",amount:5,currency:"usd",status:"completed",paidAt:new Date().toISOString()},{id:"txn_2",resourceId:"video-course",method:"x402",amount:29.99,currency:"usdc",status:"completed",paidAt:new Date(Date.now()-36e5).toISOString()},{id:"txn_3",resourceId:"api-credits",method:"credits",amount:10,currency:"credits",status:"completed",paidAt:new Date(Date.now()-72e5).toISOString()}])}finally{d(!1)}})()},[e,t,r,f,s]);const j=C=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(C),b=C=>{p(E=>!E||E.key!==C?{key:C,direction:"asc"}:{key:C,direction:E.direction==="asc"?"desc":"asc"})},v=C=>!x||x.key!==C?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:G.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:x.direction==="asc"?G.chevronUp:G.chevronDown}),_=w.useMemo(()=>{if(!x)return o;const C=x.direction==="asc"?1:-1,E=S=>{switch(x.key){case"resource":return S.resourceId;case"method":return S.method;case"amount":return S.amount;case"status":return S.status;case"date":return new Date(S.paidAt).getTime();case"id":default:return S.id}};return[...o].sort((S,N)=>{const U=E(S),k=E(N);return typeof U=="number"&&typeof k=="number"?(U-k)*C:String(U).localeCompare(String(k),void 0,{sensitivity:"base"})*C})},[o,x]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Gn,{stats:[{label:"Revenue",value:j(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:j(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:j(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:j(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:m,onRefresh:y}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),n.jsx(Xc,{value:f,onChange:h,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading transactions..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":x?.key==="id"?x?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>b("id"),children:["ID",v("id")]})}),n.jsx("th",{"aria-sort":x?.key==="resource"?x?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>b("resource"),children:["Resource",v("resource")]})}),n.jsx("th",{"aria-sort":x?.key==="method"?x?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>b("method"),children:["Method",v("method")]})}),n.jsx("th",{"aria-sort":x?.key==="amount"?x?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>b("amount"),children:["Amount",v("amount")]})}),n.jsx("th",{"aria-sort":x?.key==="status"?x?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>b("status"),children:["Status",v("status")]})}),n.jsx("th",{"aria-sort":x?.key==="date"?x?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>b("date"),children:["Date",v("date")]})})]})}),n.jsx("tbody",{children:_.map(C=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:C.id})}),n.jsx("td",{children:C.resourceId}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.method}`,children:C.method})}),n.jsxs("td",{children:["$",C.amount.toFixed(2)," ",C.currency.toUpperCase()]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.status}`,children:C.status})}),n.jsx("td",{children:fr(C.paidAt)})]},C.id))})]})})]})}function nl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=w.useState([]),[i,c]=w.useState(!0),[l,d]=w.useState(!1),[m,u]=w.useState(!1),[f,h]=w.useState(null),[x,p]=w.useState({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),y=w.useCallback(async()=>{try{let S;const N=`/admin/coupons?limit=${r}`;if(s?.isAuthenticated())S=await s.fetchWithAuth(N);else{const U={"Content-Type":"application/json"};t&&(U["X-API-Key"]=t);const k=await fetch(`${e}${N}`,{headers:U});if(!k.ok)throw new Error(`Failed to fetch coupons: ${k.status}`);S=await k.json()}a(S.coupons||[])}catch(S){oe.getLogger().error("[CouponsSection] Failed to fetch coupons:",S,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([{code:"SAVE20",discountType:"percentage",discountValue:20,active:!0,usageLimit:100,usageCount:42},{code:"LAUNCH10",discountType:"fixed",discountValue:10,currency:"usd",active:!0,usageCount:15},{code:"EXPIRED50",discountType:"percentage",discountValue:50,active:!1,usageCount:100,expiresAt:"2024-12-31"}])}finally{c(!1)}},[e,t,r,s]);w.useEffect(()=>{y()},[y]);const j=async S=>{if(S.preventDefault(),!(!x.code||x.discountValue<=0)){u(!0);try{const N=x.minimumAmountUsd?Math.round(Number(x.minimumAmountUsd)*100):void 0,U=x.productIdsCsv.split(",").map(P=>P.trim()).filter(Boolean),k=x.categoryIdsCsv.split(",").map(P=>P.trim()).filter(Boolean),A={code:x.code,discountType:x.discountType,discountValue:x.discountValue,usageLimit:x.usageLimit,active:!0,usageCount:0,scope:x.scope,...U.length?{productIds:U}:{},...k.length?{categoryIds:k}:{},...x.paymentMethod!=="any"?{paymentMethod:x.paymentMethod}:{},...x.autoApply?{autoApply:!0}:{},...x.appliesAt!=="both"?{appliesAt:x.appliesAt}:{},...x.startsAt?{startsAt:x.startsAt}:{},...x.expiresAt?{expiresAt:x.expiresAt}:{},...N?{minimumAmountCents:N}:{},...x.usageLimitPerCustomer?{usageLimitPerCustomer:x.usageLimitPerCustomer}:{},...x.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(A)});else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const D=await fetch(`${e}/admin/coupons`,{method:"POST",headers:P,body:JSON.stringify(A)});if(!D.ok)throw new Error(`Failed to create coupon: ${D.status}`)}p({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),d(!1),y()}catch(N){oe.getLogger().error("[CouponsSection] Failed to add coupon:",N,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t});const U=x.minimumAmountUsd?Math.round(Number(x.minimumAmountUsd)*100):void 0,k=x.productIdsCsv.split(",").map(P=>P.trim()).filter(Boolean),A=x.categoryIdsCsv.split(",").map(P=>P.trim()).filter(Boolean);a(P=>[...P,{code:x.code,discountType:x.discountType,discountValue:x.discountValue,usageLimit:x.usageLimit,active:!0,usageCount:0,scope:x.scope,productIds:k.length?k:void 0,categoryIds:A.length?A:void 0,paymentMethod:x.paymentMethod!=="any"?x.paymentMethod:void 0,autoApply:x.autoApply||void 0,appliesAt:x.appliesAt!=="both"?x.appliesAt:void 0,startsAt:x.startsAt||void 0,expiresAt:x.expiresAt||void 0,minimumAmountCents:U,usageLimitPerCustomer:x.usageLimitPerCustomer,firstPurchaseOnly:x.firstPurchaseOnly||void 0}]),p({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),d(!1)}finally{u(!1)}}},b=o.filter(S=>S.active).length,v=o.reduce((S,N)=>S+(N.usageCount??0),0),_=S=>{h(N=>!N||N.key!==S?{key:S,direction:"asc"}:{key:S,direction:N.direction==="asc"?"desc":"asc"})},C=S=>!f||f.key!==S?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:G.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:f.direction==="asc"?G.chevronUp:G.chevronDown}),E=w.useMemo(()=>{if(!f)return o;const S=f.direction==="asc"?1:-1,N=U=>{switch(f.key){case"discount":return U.discountValue??0;case"usage":return U.usageCount??0;case"status":return U.active?1:0;case"code":default:return U.code}};return[...o].sort((U,k)=>{const A=N(U),P=N(k);return typeof A=="number"&&typeof P=="number"?(A-P)*S:String(A).localeCompare(String(P),void 0,{sensitivity:"base"})*S})},[o,f]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Gn,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:b,variant:b>0?"success":"muted"},{label:"Redemptions",value:v}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?G.close:G.plus,l?"Cancel":"Add Coupon"]})]}),l&&n.jsxs("form",{onSubmit:j,className:"cedros-admin__add-form",children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:x.code,onChange:S=>p(N=>({...N,code:S.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),n.jsx(lt,{value:x.discountType,onChange:S=>p(N=>({...N,discountType:S})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",x.discountType==="percentage"?"(%)":"($)"]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:x.discountValue||"",onChange:S=>p(N=>({...N,discountValue:parseFloat(S.target.value)||0})),placeholder:x.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:x.discountType==="percentage"?"1":"0.01",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:x.usageLimit||"",onChange:S=>p(N=>({...N,usageLimit:S.target.value?parseInt(S.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:x.expiresAt,onChange:S=>p(N=>({...N,expiresAt:S.target.value}))})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(lt,{value:x.scope,onChange:S=>p(N=>({...N,scope:S})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),n.jsx(lt,{value:x.paymentMethod,onChange:S=>p(N=>({...N,paymentMethod:S})),options:[{value:"any",label:"Any Payment Method"},{value:"stripe",label:"Stripe (Card) Only"},{value:"x402",label:"Crypto (x402) Only"},{value:"credits",label:"Credits Only"}],label:"Payment Method"}),n.jsx(lt,{value:x.appliesAt,onChange:S=>p(N=>({...N,appliesAt:S})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),x.scope==="specific_products"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:x.productIdsCsv,onChange:S=>p(N=>({...N,productIdsCsv:S.target.value})),placeholder:"e.g., prod_123, prod_456"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:x.startsAt,onChange:S=>p(N=>({...N,startsAt:S.target.value}))})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:x.autoApply,onChange:S=>p(N=>({...N,autoApply:S.target.checked}))}),"Automatically apply when conditions met"]})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:x.minimumAmountUsd===""?"":x.minimumAmountUsd,onChange:S=>p(N=>({...N,minimumAmountUsd:S.target.value===""?"":parseFloat(S.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:x.usageLimitPerCustomer||"",onChange:S=>p(N=>({...N,usageLimitPerCustomer:S.target.value?parseInt(S.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:x.firstPurchaseOnly,onChange:S=>p(N=>({...N,firstPurchaseOnly:S.target.checked}))}),"New customers only"]})]})]}),x.scope==="specific_categories"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:x.categoryIdsCsv,onChange:S=>p(N=>({...N,categoryIdsCsv:S.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Coupon"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading coupons..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="code"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>_("code"),children:["Code",C("code")]})}),n.jsx("th",{"aria-sort":f?.key==="discount"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>_("discount"),children:["Discount",C("discount")]})}),n.jsx("th",{"aria-sort":f?.key==="usage"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>_("usage"),children:["Usage",C("usage")]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>_("status"),children:["Status",C("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:E.map(S=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:S.code})}),n.jsx("td",{children:S.discountType==="percentage"?`${S.discountValue}%`:`$${S.discountValue.toFixed(2)}`}),n.jsxs("td",{children:[S.usageCount,S.usageLimit?` / ${S.usageLimit}`:""]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${S.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:S.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},S.code))})]})})]})}function rl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=w.useState([]),[i,c]=w.useState(!0),[l,d]=w.useState(null),[m,u]=w.useState([]),[f,h]=w.useState(!0),[x,p]=w.useState(null),[y,j]=w.useState(null),[b,v]=w.useState([]),[_,C]=w.useState(!0),[E,S]=w.useState(null),[N,U]=w.useState(null),[k,A]=w.useState(null),[P,D]=w.useState("");w.useEffect(()=>{(async()=>{try{let X;const ne=`/admin/refunds?limit=${r}`;if(s?.isAuthenticated())X=await s.fetchWithAuth(ne);else{const xe={"Content-Type":"application/json"};t&&(xe["X-API-Key"]=t);const we=await fetch(`${e}${ne}`,{headers:xe});if(!we.ok)throw new Error(`Failed to fetch x402 refunds: ${we.status}`);X=await we.json()}a(X.refunds||[])}catch(X){oe.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",X,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([{id:"ref_1",transactionId:"txn_42",amount:29.99,currency:"usd",status:"pending",reason:"Customer request",createdAt:new Date().toISOString()},{id:"ref_2",transactionId:"txn_38",amount:5,currency:"usd",status:"completed",createdAt:new Date(Date.now()-864e5).toISOString()}])}finally{c(!1)}})()},[e,t,r,s]);const z=w.useCallback(async()=>{try{let $;const X=`/admin/credits/refund-requests?status=pending&limit=${r}&offset=0`;if(s?.isAuthenticated())$=await s.fetchWithAuth(X);else{const xe={"Content-Type":"application/json"};t&&(xe["X-API-Key"]=t);const we=await fetch(`${e}${X}`,{headers:xe});if(!we.ok)throw new Error(`Failed to fetch credits refund requests: ${we.status}`);$=await we.json()}const ne=Array.isArray($)?$:"refundRequests"in $?$.refundRequests:$.requests||[];u(ne)}catch($){oe.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",$,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([{id:"crr_demo1",originalTransactionId:"ctx_demo1",userId:"user_demo1",amountLamports:25e5,currency:"USD",status:"pending",reason:"Requested by customer",createdAt:new Date().toISOString()}])}finally{h(!1)}},[e,t,r,s]);w.useEffect(()=>{z()},[z]);const L=async $=>{p($.id);try{const X=`/admin/credits/refund-requests/${$.id}/process`,ne=JSON.stringify({amountLamports:$.amountLamports,reason:$.reason});if(s?.isAuthenticated())await s.fetchWithAuth(X,{method:"POST",body:ne});else{const xe={"Content-Type":"application/json"};t&&(xe["X-API-Key"]=t);const we=await fetch(`${e}${X}`,{method:"POST",headers:xe,body:ne});if(!we.ok)throw new Error(`Failed to process credits refund: ${we.status}`)}await z()}catch(X){oe.getLogger().error("[RefundsSection] Failed to process credits refund:",X,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:$.id}),u(ne=>ne.map(xe=>xe.id===$.id?{...xe,status:"processed"}:xe))}finally{p(null)}},O=$=>{D($.reason??""),A($)},M=()=>{A(null),D("")},R=async()=>{if(!k)return;const $=k,X=P;M(),p($.id);try{const ne=`/admin/credits/refund-requests/${$.id}/reject`,xe=JSON.stringify({reason:X});if(s?.isAuthenticated())await s.fetchWithAuth(ne,{method:"POST",body:xe});else{const we={"Content-Type":"application/json"};t&&(we["X-API-Key"]=t);const Te=await fetch(`${e}${ne}`,{method:"POST",headers:we,body:xe});if(!Te.ok)throw new Error(`Failed to reject credits refund: ${Te.status}`)}await z()}catch(ne){oe.getLogger().error("[RefundsSection] Failed to reject credits refund:",ne,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:$.id}),u(xe=>xe.map(we=>we.id===$.id?{...we,status:"rejected",rejectedAt:new Date().toISOString(),rejectedReason:X||null}:we))}finally{p(null)}},W=w.useCallback(async()=>{try{let $;const X=`/admin/stripe/refunds?limit=${r}`;if(s?.isAuthenticated())$=await s.fetchWithAuth(X);else{const ne={"Content-Type":"application/json"};t&&(ne["X-API-Key"]=t);const xe=await fetch(`${e}${X}`,{headers:ne});if(!xe.ok)throw new Error(`Failed to fetch Stripe refunds: ${xe.status}`);$=await xe.json()}v($.refunds||[])}catch($){oe.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",$,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),v([{id:"rr_demo1",stripeRefundId:"re_demo1",chargeId:"ch_demo1",paymentIntentId:"pi_demo1",amount:4999,currency:"usd",status:"succeeded",reason:"requested_by_customer",createdAt:new Date().toISOString()},{id:"rr_demo2",stripeRefundId:null,chargeId:null,paymentIntentId:"pi_demo2",amount:1500,currency:"usd",status:"pending",reason:"duplicate",createdAt:new Date(Date.now()-36e5).toISOString()}])}finally{C(!1)}},[e,t,r,s]);w.useEffect(()=>{W()},[W]);const T=async $=>{S($);try{const X=`/admin/stripe/refunds/${$}/process`;if(s?.isAuthenticated())await s.fetchWithAuth(X,{method:"POST"});else{const ne={"Content-Type":"application/json"};t&&(ne["X-API-Key"]=t);const xe=await fetch(`${e}${X}`,{method:"POST",headers:ne});if(!xe.ok)throw new Error(`Failed to process refund: ${xe.status}`)}await W()}catch(X){oe.getLogger().error("[RefundsSection] Failed to process Stripe refund:",X,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:$}),v(ne=>ne.map(xe=>xe.id===$?{...xe,stripeRefundId:xe.stripeRefundId??"re_demo_processed",status:"succeeded"}:xe))}finally{S(null)}},V=($,X)=>new Intl.NumberFormat("en-US",{style:"currency",currency:X}).format($/100),ee=$=>$?$.replace(/_/g," ").replace(/\b\w/g,X=>X.toUpperCase()):"—",B=$=>{switch($){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},Y=($,X)=>X?X.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format($/1e6)} (USD credits)`:`${$.toLocaleString()} ${X.toUpperCase()} (atomic)`:`${$.toLocaleString()} (atomic)`,J=$=>{switch($){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},ge=$=>$.stripeRefundId??"—",F=$=>$.chargeId??"—",K=b.filter($=>$.status==="pending"||$.status==="requires_action").length,me=m.filter($=>$.status==="pending").length,q=o.filter($=>$.status==="pending").length,te=K+me+q,ce=b.filter($=>$.status==="succeeded").reduce(($,X)=>$+X.amount,0),pe=m.filter($=>$.status==="processed").reduce(($,X)=>$+X.amountLamports,0),Oe=o.filter($=>$.status==="completed").reduce(($,X)=>$+X.amount,0),Ge=ce/100+pe/1e6+Oe,Qe=$=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format($),$e=_||f||i,Ye=$=>{U(X=>!X||X.key!==$?{key:$,direction:"asc"}:{key:$,direction:X.direction==="asc"?"desc":"asc"})},Ne=$=>{j(X=>!X||X.key!==$?{key:$,direction:"asc"}:{key:$,direction:X.direction==="asc"?"desc":"asc"})},st=$=>{d(X=>!X||X.key!==$?{key:$,direction:"asc"}:{key:$,direction:X.direction==="asc"?"desc":"asc"})},Ae=($,X)=>!$||!X?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:G.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:X==="asc"?G.chevronUp:G.chevronDown}),Fe=w.useMemo(()=>{if(!N)return b;const $=N.direction==="asc"?1:-1,X=ne=>{switch(N.key){case"stripe":return ne.stripeRefundId??"";case"charge":return ne.chargeId??"";case"amount":return ne.amount??0;case"reason":return ne.reason??"";case"status":return ne.status??"";case"date":return new Date(ne.createdAt).getTime();case"id":default:return ne.id}};return[...b].sort((ne,xe)=>{const we=X(ne),Te=X(xe);return typeof we=="number"&&typeof Te=="number"?(we-Te)*$:String(we).localeCompare(String(Te),void 0,{sensitivity:"base"})*$})},[b,N]),de=w.useMemo(()=>{if(!y)return m;const $=y.direction==="asc"?1:-1,X=ne=>{switch(y.key){case"original":return ne.originalTransactionId??"";case"user":return ne.userId??"";case"amount":return ne.amountLamports??0;case"reason":return ne.reason??"";case"status":return ne.status??"";case"date":return new Date(ne.createdAt).getTime();case"id":default:return ne.id}};return[...m].sort((ne,xe)=>{const we=X(ne),Te=X(xe);return typeof we=="number"&&typeof Te=="number"?(we-Te)*$:String(we).localeCompare(String(Te),void 0,{sensitivity:"base"})*$})},[m,y]),ke=w.useMemo(()=>{if(!l)return o;const $=l.direction==="asc"?1:-1,X=ne=>{switch(l.key){case"transaction":return ne.transactionId??"";case"amount":return ne.amount??0;case"reason":return ne.reason??"";case"status":return ne.status??"";case"date":return new Date(ne.createdAt).getTime();case"id":default:return ne.id}};return[...o].sort((ne,xe)=>{const we=X(ne),Te=X(xe);return typeof we=="number"&&typeof Te=="number"?(we-Te)*$:String(we).localeCompare(String(Te),void 0,{sensitivity:"base"})*$})},[o,l]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Gn,{stats:[{label:"Pending",value:te,variant:te>0?"warning":"muted"},{label:"Card Pending",value:K,description:"Stripe"},{label:"Credits Pending",value:me},{label:"Crypto Pending",value:q,description:"x402"},{label:"Total Refunded",value:Qe(Ge),variant:"success"}],isLoading:$e}),n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),_?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading Stripe refunds..."]}):b.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":N?.key==="id"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ye("id"),children:["Request ID",Ae(N?.key==="id",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="stripe"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ye("stripe"),children:["Stripe Refund ID",Ae(N?.key==="stripe",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="charge"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ye("charge"),children:["Charge",Ae(N?.key==="charge",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="amount"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ye("amount"),children:["Amount",Ae(N?.key==="amount",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="reason"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ye("reason"),children:["Reason",Ae(N?.key==="reason",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="status"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ye("status"),children:["Status",Ae(N?.key==="status",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="date"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ye("date"),children:["Date",Ae(N?.key==="date",N?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:Fe.map($=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:$.id})}),n.jsx("td",{children:n.jsx("code",{children:ge($)})}),n.jsx("td",{children:n.jsx("code",{children:F($)})}),n.jsx("td",{children:V($.amount,$.currency)}),n.jsx("td",{children:ee($.reason)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${J($.status)}`,children:$.status})}),n.jsx("td",{children:fr($.createdAt)}),n.jsx("td",{children:($.status==="pending"||$.status==="requires_action")&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>T($.id),disabled:E===$.id,children:E===$.id?"Processing...":"Process"})})]},$.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),f?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading credits refunds..."]}):m.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":y?.key==="id"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ne("id"),children:["Request ID",Ae(y?.key==="id",y?.direction)]})}),n.jsx("th",{"aria-sort":y?.key==="original"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ne("original"),children:["Original Tx",Ae(y?.key==="original",y?.direction)]})}),n.jsx("th",{"aria-sort":y?.key==="user"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ne("user"),children:["User",Ae(y?.key==="user",y?.direction)]})}),n.jsx("th",{"aria-sort":y?.key==="amount"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ne("amount"),children:["Amount",Ae(y?.key==="amount",y?.direction)]})}),n.jsx("th",{"aria-sort":y?.key==="reason"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ne("reason"),children:["Reason",Ae(y?.key==="reason",y?.direction)]})}),n.jsx("th",{"aria-sort":y?.key==="status"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ne("status"),children:["Status",Ae(y?.key==="status",y?.direction)]})}),n.jsx("th",{"aria-sort":y?.key==="date"?y?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Ne("date"),children:["Date",Ae(y?.key==="date",y?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:de.map($=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:$.id})}),n.jsx("td",{children:n.jsx("code",{children:$.originalTransactionId})}),n.jsx("td",{children:n.jsx("code",{children:$.userId??"—"})}),n.jsx("td",{children:Y($.amountLamports,$.currency)}),n.jsx("td",{children:$.reason??"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${B($.status)}`,children:$.status})}),n.jsx("td",{children:fr($.createdAt)}),n.jsx("td",{children:$.status==="pending"?n.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>L($),disabled:x===$.id,children:x===$.id?"Processing...":"Process"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>O($),disabled:x===$.id,children:"Reject"})]}):null})]},$.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading x402 refunds..."]}):o.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>st("id"),children:["ID",Ae(l?.key==="id",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="transaction"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>st("transaction"),children:["Transaction",Ae(l?.key==="transaction",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="amount"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>st("amount"),children:["Amount",Ae(l?.key==="amount",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="reason"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>st("reason"),children:["Reason",Ae(l?.key==="reason",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="status"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>st("status"),children:["Status",Ae(l?.key==="status",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="date"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>st("date"),children:["Date",Ae(l?.key==="date",l?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:ke.map($=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:$.id})}),n.jsx("td",{children:n.jsx("code",{children:$.transactionId})}),n.jsxs("td",{children:["$",$.amount.toFixed(2)]}),n.jsx("td",{children:$.reason||"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${$.status}`,children:$.status})}),n.jsx("td",{children:fr($.createdAt)}),n.jsx("td",{children:$.status==="pending"&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",children:"Process"})})]},$.id))})]})}),k&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:M,children:n.jsxs("div",{className:"cedros-admin__modal",onClick:$=>$.stopPropagation(),children:[n.jsxs("div",{className:"cedros-admin__modal-header",children:[n.jsx("h3",{className:"cedros-admin__modal-title",children:"Reject Refund Request"}),n.jsx("button",{type:"button",className:"cedros-admin__modal-close",onClick:M,"aria-label":"Close",children:G.close})]}),n.jsxs("div",{className:"cedros-admin__modal-body",children:[n.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",n.jsx("code",{children:k.id})," for ",Y(k.amountLamports,k.currency),"."]}),n.jsxs("label",{className:"cedros-admin__form-field",children:[n.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),n.jsx("textarea",{className:"cedros-admin__input",value:P,onChange:$=>D($.target.value),placeholder:"Enter rejection reason...",rows:3,style:{resize:"vertical"}})]})]}),n.jsxs("div",{className:"cedros-admin__modal-footer",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--outline",onClick:M,children:"Cancel"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:R,children:"Reject Refund"})]})]})})]})}async function Ap(e){const t=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=await e.sign(t);return{"X-Signer":e.signerPublicKey,"X-Message":t,"X-Signature":r,"Content-Type":"application/json"}}class Pp{constructor(t,r,s){this.serverUrl=t,this.auth=r,this.authManager=s}async fetch(t,r={}){if(this.authManager?.isAuthenticated())return this.authManager.fetchWithAuth(t,r);const s={"Content-Type":"application/json",...r.headers||{}};if(this.auth){const a=await Ap(this.auth);Object.assign(s,a)}const o=await fetch(`${this.serverUrl}${t}`,{...r,headers:s});if(!o.ok){const a=await o.text();throw new Error(`API error ${o.status}: ${a}`)}return o.json()}async listCategories(t=100){return this.fetch(`/admin/config?limit=${t}`)}async getConfig(t,r=!0){return this.fetch(`/admin/config/${t}?redact_secrets=${r}`)}async updateConfig(t,r,s){await this.fetch(`/admin/config/${t}`,{method:"PUT",body:JSON.stringify({config:r,description:s})})}async patchConfig(t,r,s){await this.fetch(`/admin/config/${t}`,{method:"PATCH",body:JSON.stringify({updates:r,description:s})})}async batchUpdate(t){await this.fetch("/admin/config/batch",{method:"POST",body:JSON.stringify({updates:t})})}async validateConfig(t,r){return this.fetch("/admin/config/validate",{method:"POST",body:JSON.stringify({category:t,config:r})})}async getHistory(t,r=50){const s=new URLSearchParams({limit:r.toString()});return t&&s.set("category",t),this.fetch(`/admin/config/history?${s}`)}}const aa={server:{label:"Server",secrets:[],icon:"🖥️",fields:{admin_metrics_api_key:{hidden:!0},cors_allowed_origins:{hidden:!0}}},security:{label:"Security",description:"Configure CORS, rate limiting, and other security settings",secrets:[],icon:"🔒",fields:{cors_allowed_origins:{description:'List of allowed origins for CORS requests. Use ["*"] to allow all origins (not recommended for production).'}}},metrics:{label:"Metrics",description:"Configure metrics collection and API access",secrets:["admin_metrics_api_key"],icon:"📊",fields:{admin_metrics_api_key:{description:"API key for accessing the admin metrics endpoint. Keep this secret."}}},logging:{label:"Logging",secrets:[],icon:"📝",fields:{level:{type:"dropdown",options:["trace","debug","info","warn","error"]},format:{hidden:!0},environment:{hidden:!0}}},stripe:{label:"Stripe",secrets:["secret_key","webhook_secret"],icon:"💳",fields:{enabled:{hidden:!0},mode:{type:"dropdown",options:["test","live"]},success_url:{hidden:!0},cancel_url:{hidden:!0}}},x402:{label:"X402 (Crypto)",secrets:["server_wallets"],icon:"⚡",fields:{enabled:{hidden:!0},payment_address:{type:"solana_address",description:"The Solana wallet address where payments are received. This is where customer funds are sent."},token_mint:{type:"token_mint",description:"The SPL token used for payments. Most commonly USDC."},token_decimals:{type:"number",description:"Number of decimal places for the token (e.g., USDC has 6 decimals).",hidden:!0},custom_token_symbol:{description:'Display symbol for your custom token (e.g., "MYTOKEN").',hidden:!0},custom_token_icon:{description:"URL to your token's icon image.",hidden:!0},rpc_url:{description:"Custom Solana RPC endpoint. Leave empty to use the default public RPC."},gasless_enabled:{type:"toggle",description:"When enabled, your server pays transaction fees so customers don't need SOL."},server_wallets:{type:"secret_array",description:"Server keypair(s) used to sign and pay for transactions. Required for gasless payments.",showWhen:"gasless_enabled"},network:{hidden:!0}}},paywall:{label:"Paywall",secrets:[],icon:"🚪",fields:{product_cache_ttl:{type:"number",unit:"seconds"}}},coupons:{label:"Coupons",secrets:[],icon:"🎟️",fields:{cache_ttl:{type:"number",unit:"seconds"}}},subscriptions:{label:"Subscriptions",secrets:[],icon:"🔄",fields:{grace_period_hours:{type:"number",unit:"hours"}}},callbacks:{label:"Callbacks",secrets:["hmac_secret"],icon:"🔔"},email:{label:"Email",description:"Email receipts for customers after purchase",secrets:["smtp_password"],icon:"📧",fields:{enabled:{hidden:!0},provider:{type:"dropdown",options:["sendgrid","mailgun","postmark","ses","resend","custom"],description:"Email service provider."},smtp_host:{description:"SMTP server hostname.",showWhen:"provider"},smtp_port:{type:"number",description:"SMTP server port (typically 587 for TLS).",showWhen:"provider"},smtp_user:{description:"SMTP authentication username or API key name.",showWhen:"provider"},smtp_password:{description:"SMTP password or API key.",showWhen:"provider"},from_address:{description:"Sender email address (e.g., orders@yourstore.com)."},from_name:{description:'Sender display name (e.g., "Your Store").'}}},webhook:{label:"Webhook",description:"HTTP notifications when purchases occur",secrets:["secret"],icon:"🔔",fields:{enabled:{hidden:!0},url:{description:"URL to receive POST notifications (e.g., https://api.yoursite.com/webhooks/orders)."},secret:{description:"Shared secret for HMAC-SHA256 signature verification."},retry_attempts:{type:"number",description:"Number of retry attempts on failure (default: 3)."}}},messaging:{label:"Messaging",description:"Email and webhook notifications for purchases",secrets:["smtp_password","webhook_secret"],icon:"📬",fields:{email_enabled:{type:"boolean",description:"Send order confirmation emails to customers."},smtp_host:{description:"SMTP server hostname.",showWhen:"email_enabled"},smtp_port:{type:"number",description:"SMTP server port (typically 587 for TLS).",showWhen:"email_enabled"},smtp_username:{description:"SMTP authentication username or API key.",showWhen:"email_enabled"},smtp_password:{description:"SMTP password or API key.",showWhen:"email_enabled"},from_email:{description:"Sender email address (e.g., orders@yourstore.com).",showWhen:"email_enabled"},from_name:{description:'Sender display name (e.g., "Your Store").',showWhen:"email_enabled"},webhook_enabled:{type:"boolean",description:"Send webhook notifications when purchases complete."},webhook_url:{description:"URL to receive POST notifications.",showWhen:"webhook_enabled"},webhook_secret:{description:"Shared secret for HMAC-SHA256 signature verification.",showWhen:"webhook_enabled"},webhook_timeout:{type:"number",description:"Request timeout in seconds (default: 30).",showWhen:"webhook_enabled"}}},monitoring:{label:"Monitoring",secrets:[],icon:"📊",fields:{check_interval:{type:"number",unit:"seconds"},low_balance_threshold:{type:"number",unit:"SOL"}}},rate_limit:{label:"Rate Limiting",secrets:[],icon:"⏱️"},circuit_breaker:{label:"Circuit Breaker",secrets:[],icon:"🔌"},admin:{label:"Admin Keys",secrets:[],icon:"👤"},api_keys:{label:"API Keys",secrets:[],icon:"🔐"},cedros_login:{label:"Cedros Login",secrets:["api_key"],icon:"🔑",fields:{enabled:{hidden:!0},credits_enabled:{hidden:!0},base_url:{hidden:!0},timeout:{hidden:!0}}},storefront:{label:"Storefront",description:"Product pages & display settings",secrets:[],icon:"🏪",fields:{"relatedProducts.mode":{type:"dropdown",options:["most_recent","by_category","manual","ai"]},"relatedProducts.maxItems":{type:"number"}}}};function sl(e,t){return aa[e]?.secrets.includes(t)??!1}const vt="[REDACTED]";function ia({data:e,onSave:t,debounceMs:r=1500,savedDurationMs:s=2e3,enabled:o=!0,skipInitial:a=!0}){const[i,c]=w.useState("idle"),[l,d]=w.useState(null),m=w.useRef(!0),u=w.useRef(null),f=w.useRef(null),h=w.useRef(e);h.current=e;const x=w.useCallback(async()=>{c("saving"),d(null);try{await t(h.current),c("saved"),f.current=setTimeout(()=>{c("idle")},s)}catch(j){c("error"),d(j instanceof Error?j.message:"Save failed")}},[t,s]),p=w.useCallback(async()=>{u.current&&(clearTimeout(u.current),u.current=null),await x()},[x]),y=w.useCallback(()=>{c("idle"),d(null)},[]);return w.useEffect(()=>{if(o){if(a&&m.current){m.current=!1;return}return u.current&&clearTimeout(u.current),f.current&&clearTimeout(f.current),c("pending"),u.current=setTimeout(()=>{x()},r),()=>{u.current&&clearTimeout(u.current)}}},[e,o,a,r,x]),w.useEffect(()=>()=>{u.current&&clearTimeout(u.current),f.current&&clearTimeout(f.current)},[]),{status:i,error:l,saveNow:p,reset:y}}function Tp(e){if(!e||e.trim()==="")return{valid:!0};try{return new Gc.PublicKey(e.trim()),{valid:!0}}catch{return{valid:!1,error:"Invalid Solana address"}}}function Si(e,t,r){const s=sl(e,t),o=t.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase()),i=aa[e]?.fields?.[t],c={isSecret:s,label:o,description:i?.description,hidden:i?.hidden,showWhen:i?.showWhen};return i?.type==="dropdown"&&i.options?{...c,type:"dropdown",options:i.options}:i?.type==="token_mint"?{...c,type:"token_mint"}:i?.type==="toggle"?{...c,type:"toggle"}:i?.type==="secret_array"?{...c,type:"secret_array",isSecret:!0}:i?.type==="solana_address"?{...c,type:"solana_address"}:i?.type==="number"?{...c,type:"number",unit:i.unit}:typeof r=="boolean"?{...c,type:"boolean"}:typeof r=="number"?{...c,type:"number",unit:i?.unit}:Array.isArray(r)?{...c,type:"array"}:typeof r=="object"&&r!==null?{...c,type:"object"}:{...c,type:"string"}}function Ep({category:e,config:t,originalConfig:r,isLoading:s=!1,onSave:o}){const[a,i]=w.useState(t),[c,l]=w.useState(new Set);w.useEffect(()=>{i(t)},[t]);const d=w.useMemo(()=>{const b={...a};for(const v of Object.keys(b))if(sl(e,v)){const _=r[v],C=b[v];(C===vt||C===_)&&(b[v]=vt)}return b},[a,r,e]),{status:m,error:u}=ia({data:d,onSave:o,debounceMs:1500}),f=w.useCallback((b,v)=>{i(_=>({..._,[b]:v}))},[]),h=w.useCallback(b=>{l(v=>{const _=new Set(v);return _.has(b)?_.delete(b):_.add(b),_})},[]),x=b=>b?n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:b}):null,p=(b,v)=>{const _=Si(e,b,r[b]??v);if(_.type==="dropdown"&&_.options)return n.jsx(lt,{value:v,onChange:S=>f(b,S),options:_.options.map(S=>({value:S,label:S})),label:_.label,description:_.description,disabled:s});if(_.type==="token_mint")return n.jsx(Ip,{label:_.label,value:v,onChange:S=>f(b,S),decimals:a.token_decimals??6,onDecimalsChange:S=>f("token_decimals",S),disabled:s,description:_.description,customSymbol:a.custom_token_symbol||"",customIcon:a.custom_token_icon||"",onCustomSymbolChange:S=>f("custom_token_symbol",S),onCustomIconChange:S=>f("custom_token_icon",S)});if(_.type==="toggle")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("button",{type:"button",role:"switch","aria-checked":v,onClick:()=>f(b,!v),disabled:s,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:v?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:s?"not-allowed":"pointer",position:"relative",transition:"background-color 0.2s",opacity:s?.5:1,flexShrink:0},children:n.jsx("span",{style:{position:"absolute",top:2,left:v?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})}),n.jsx("span",{className:"cedros-admin__field-label",style:{marginBottom:0},children:_.label})]}),x(_.description)]});if(_.type==="solana_address"){const S=v||"",N=Tp(S);return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:_.label}),n.jsxs("div",{style:{position:"relative"},children:[n.jsx("input",{type:"text",className:`cedros-admin__input ${N.valid?"":"cedros-admin__input--error"}`,value:S,onChange:U=>f(b,U.target.value),disabled:s,placeholder:"e.g. 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",style:{width:"100%",fontFamily:"monospace",fontSize:"0.875rem",borderColor:N.valid?void 0:"var(--cedros-admin-error, #dc2626)",paddingRight:S&&N.valid?"2rem":void 0}}),S&&N.valid&&n.jsx("span",{style:{position:"absolute",right:10,top:"50%",transform:"translateY(-50%)",color:"var(--cedros-admin-success, #16a34a)",fontSize:"1rem"},title:"Valid Solana address",children:"✓"})]}),!N.valid&&n.jsx("span",{style:{color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.75rem",marginTop:"0.25rem",display:"block"},children:N.error}),x(_.description)]})}if(_.type==="boolean")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__checkbox",children:[n.jsx("input",{type:"checkbox",checked:v,onChange:S=>f(b,S.target.checked),disabled:s}),_.label]}),x(_.description)]});if(_.type==="number")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[_.label,_.unit&&n.jsxs("span",{className:"cedros-admin__field-unit",children:[" (",_.unit,")"]})]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v,onChange:S=>f(b,parseFloat(S.target.value)||0),disabled:s}),x(_.description)]});if(_.type==="secret_array")return n.jsx(Rp,{label:_.label,value:v,onChange:S=>f(b,S),disabled:s,description:_.description});if(_.type==="array"){const S=v;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:_.label}),n.jsx("textarea",{className:"cedros-admin__textarea",value:S.join(`
2
- `),onChange:N=>f(b,N.target.value.split(`
3
- `).filter(Boolean)),placeholder:"One item per line",rows:3,disabled:s}),x(_.description)]})}if(_.type==="object")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:_.label}),n.jsx("textarea",{className:"cedros-admin__textarea cedros-admin__textarea--mono",value:JSON.stringify(v,null,2),onChange:S=>{try{f(b,JSON.parse(S.target.value))}catch{}},rows:5,disabled:s}),x(_.description)]});const C=c.has(b),E=_.isSecret&&!C&&v===vt?vt:v;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[_.label,_.isSecret&&n.jsx("span",{className:"cedros-admin__field-secret",children:" (secret)"})]}),n.jsxs("div",{className:"cedros-admin__input-group",children:[n.jsx("input",{type:_.isSecret&&!C?"password":"text",className:"cedros-admin__input",value:E,onChange:S=>f(b,S.target.value),disabled:s,placeholder:_.isSecret?"••••••••":""}),_.isSecret&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>h(b),style:{padding:"0.5rem",minWidth:"auto"},title:C?"Hide":"Show",children:C?G.eyeOff:G.eye})]}),x(_.description)]})},y=Object.keys(a),j=b=>{const v=Si(e,b,r[b]??a[b]);if(v.hidden||v.showWhen&&!a[v.showWhen])return!1;if(b==="token_decimals"){const _=a.token_mint;if(_&&oe.STABLECOIN_METADATA[_])return!1}return!0};return n.jsxs("div",{className:"cedros-admin__config-editor",children:[n.jsx("div",{className:"cedros-admin__config-fields",children:y.filter(j).map(b=>n.jsx("div",{className:"cedros-admin__config-field",children:p(b,a[b])},b))}),n.jsx("div",{className:"cedros-admin__config-actions",children:n.jsx("div",{className:"cedros-admin__autosave-status",children:n.jsx(Op,{status:m,error:u})})})]})}function Ip({label:e,value:t,onChange:r,decimals:s,onDecimalsChange:o,disabled:a=!1,description:i,customSymbol:c="",customIcon:l="",onCustomSymbolChange:d,onCustomIconChange:m}){const[u,f]=w.useState(!1),h=Object.entries(oe.STABLECOIN_METADATA),p=!!oe.STABLECOIN_METADATA[t],j=u||!!t&&!p,b=v=>{if(v==="custom")f(!0),p&&r("");else{f(!1),r(v);const _=oe.STABLECOIN_METADATA[v];_&&o&&o(_.decimals),d&&d(""),m&&m("")}};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:e}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem"},children:[h.map(([v,_])=>n.jsxs("button",{type:"button",onClick:()=>b(v),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:t===v?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:t===v?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:t===v?600:400},children:[n.jsx("img",{src:_.icon,alt:_.symbol,style:{width:20,height:20,borderRadius:"50%"},onError:C=>{C.target.style.display="none"}}),n.jsx("span",{children:_.symbol})]},v)),n.jsxs("button",{type:"button",onClick:()=>b("custom"),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:j?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:j?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:j?600:400},children:[n.jsx("span",{style:{fontSize:"1rem"},children:"+"}),n.jsx("span",{children:"Custom"})]})]}),j&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"1rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:[n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Mint Address"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:t,onChange:v=>r(v.target.value),placeholder:"e.g., EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",disabled:a,style:{fontFamily:"monospace",fontSize:"0.875rem"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Symbol"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:v=>d?.(v.target.value),placeholder:"e.g., MYTOKEN",disabled:a,style:{textTransform:"uppercase"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Icon URL"}),n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:l,onChange:v=>m?.(v.target.value),placeholder:"https://example.com/token-logo.png",disabled:a,style:{flex:1}}),l&&n.jsx("img",{src:l,alt:"Token icon preview",style:{width:32,height:32,borderRadius:"50%",border:"1px solid var(--cedros-admin-border, #e5e7eb)",objectFit:"cover"},onError:v=>{v.target.style.display="none"}})]}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Shown to customers during checkout"})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Decimals"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:s??6,onChange:v=>o?.(parseInt(v.target.value,10)||0),min:0,max:18,disabled:a,style:{width:"100px"}}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Most SPL tokens use 6 decimals (like USDC)"})]})]}),t&&p&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",fontFamily:"monospace",wordBreak:"break-all"},children:t}),i&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:i})]})]})}function Rp({label:e,value:t,onChange:r,disabled:s=!1,description:o}){const[a,i]=w.useState(new Set),[c,l]=w.useState(null),[d,m]=w.useState(""),u=Array.isArray(t)?t:[],f=v=>{i(_=>{const C=new Set(_);return C.has(v)?C.delete(v):C.add(v),C})},h=()=>{r([...u,""]),l(u.length),m("")},x=(v,_)=>{const C=[...u];C[v]=_,r(C)},p=v=>{const _=u.filter((C,E)=>E!==v);r(_),i(C=>{const E=new Set;return C.forEach(S=>{S<v?E.add(S):S>v&&E.add(S-1)}),E})},y=v=>{l(v),m(u[v]||"")},j=()=>{c!==null&&(x(c,d),l(null),m(""))},b=()=>{c!==null&&u[c]===""&&p(c),l(null),m("")};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",style:{marginBottom:0},children:e}),n.jsxs("button",{type:"button",onClick:h,disabled:s,style:{display:"flex",alignItems:"center",gap:"0.25rem",padding:"0.25rem 0.5rem",fontSize:"0.75rem",border:"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.375rem",background:"var(--cedros-admin-bg, #fff)",cursor:s?"not-allowed":"pointer",opacity:s?.5:1},children:[G.plus,"Add"]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u.length===0&&n.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"0.875rem",border:"1px dashed var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem"},children:'No items. Click "Add" to create one.'}),u.map((v,_)=>{const C=a.has(_),E=c===_,S=v===vt;return n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.375rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:E?n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:d,onChange:N=>m(N.target.value),placeholder:"Enter wallet keypair...",autoFocus:!0,style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem"},onKeyDown:N=>{N.key==="Enter"&&j(),N.key==="Escape"&&b()}}),n.jsx("button",{type:"button",onClick:j,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-success, #22c55e)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Save",children:G.check}),n.jsx("button",{type:"button",onClick:b,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-text-muted, #64748b)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Cancel",children:G.close})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C&&!S?v:S?"[REDACTED]":"••••••••••••••••••••"}),n.jsx("button",{type:"button",onClick:()=>f(_),disabled:s||S,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s||S?"not-allowed":"pointer",opacity:s||S?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:C?"Hide":"Show",children:C?G.eyeOff:G.eye}),n.jsx("button",{type:"button",onClick:()=>y(_),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:"Edit",children:G.settings}),n.jsx("button",{type:"button",onClick:()=>p(_),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-error, #ef4444)"},title:"Delete",children:G.trash})]})},_)})]}),o&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.5rem"},children:o})]})}function Op({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${e}`,style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx(n.Fragment,{children:n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"})}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx(n.Fragment,{children:n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})})]})}function ol({serverUrl:e,apiKey:t,authManager:r,category:s,title:o,description:a,enabledField:i="enabled",showEnabledToggle:c=!1}){const l=w.useMemo(()=>new Pp(e,void 0,r),[e,r]),[d,m]=w.useState(null),[u,f]=w.useState([]),[h,x]=w.useState(!1),[p,y]=w.useState(!0),[j,b]=w.useState(null),[v,_]=w.useState(null),[C,E]=w.useState(!1),S=aa[s]||{label:s,icon:"⚙️"},N=o||S.label,U=a||S.description,k=w.useCallback(()=>({stripe:{secret_key:vt,webhook_secret:vt,publishable_key:"pk_test_xxx",success_url:"https://example.com/success",cancel_url:"https://example.com/cancel",mode:"test",enabled:!0},x402:{enabled:!1,payment_address:"",token_mint:"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",token_decimals:6,network:"mainnet-beta",rpc_url:"",gasless_enabled:!1,server_wallets:vt},server:{address:":8080",read_timeout:"15s",write_timeout:"15s",cors_allowed_origins:["http://localhost:3000"],admin_metrics_api_key:vt},logging:{level:"info",format:"json",environment:"production"},metrics:{admin_metrics_api_key:vt},security:{cors_allowed_origins:["http://localhost:3000"]},cedros_login:{enabled:!1,credits_enabled:!1,base_url:"",api_key:vt,timeout:30},email:{enabled:!1,provider:"",smtp_host:"",smtp_port:587,smtp_user:"",smtp_password:vt,from_address:"",from_name:""},webhook:{enabled:!1,url:"",secret:vt,retry_attempts:3}})[s]||{},[s]),A=w.useCallback(async()=>{y(!0),b(null);try{const W=await l.getConfig(s,!0);m(W)}catch{m({category:s,config:k(),updatedAt:new Date().toISOString(),secretsRedacted:!0})}finally{y(!1)}},[l,s,k]);w.useEffect(()=>{A()},[A]);const P=w.useCallback(async()=>{try{const W=await l.getHistory(s,20);f(W.history)}catch{f([{id:"1",configKey:`${s}.updated`,action:"UPDATE",changedAt:new Date().toISOString(),changedBy:"admin"}])}},[l,s]);w.useEffect(()=>{h&&P()},[h,P]);const D=w.useCallback(async W=>{await l.updateConfig(s,W,"Updated via admin dashboard"),await A()},[l,s,A]),z=w.useCallback(async W=>l.validateConfig(s,W),[l,s]),[L,O]=w.useState(!1),M=w.useCallback(async()=>{if(!d||L)return;const T=!!!d.config[i],V={...d.config,[i]:T};O(!0),m({...d,config:V});try{await l.updateConfig(s,V,`${T?"Enabled":"Disabled"} via admin dashboard`)}catch(ee){console.warn("Failed to save enabled state to server (demo mode?):",ee)}finally{O(!1)}},[d,l,s,i,L]),R=!!d?.config[i];return p&&!d?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading ",N," settings..."]})}):j?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__error",children:["Failed to load settings: ",j]})}):n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{children:[n.jsxs("h3",{className:"cedros-admin__section-title",children:[n.jsx("span",{style:{marginRight:"0.5rem"},children:S.icon}),N]}),U&&n.jsx("p",{className:"cedros-admin__text-muted",style:{marginTop:"0.25rem"},children:U})]}),c&&d&&i in d.config&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("span",{style:{fontSize:"0.875rem",color:R?"var(--cedros-admin-text, #171717)":"var(--cedros-admin-muted, #737373)"},children:R?"Enabled":"Disabled"}),n.jsx("button",{type:"button",role:"switch","aria-checked":R,onClick:M,disabled:L,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:R?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:L?"wait":"pointer",position:"relative",transition:"background-color 0.2s",flexShrink:0,opacity:L?.6:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:R?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})]})]}),d&&n.jsxs("div",{className:"cedros-admin__settings-editor",style:{marginTop:"1rem",opacity:c&&!R?.6:1,pointerEvents:c&&!R?"none":"auto"},children:[c&&!R&&n.jsx("div",{style:{padding:"0.75rem 1rem",marginBottom:"1rem",backgroundColor:"var(--cedros-admin-warning-bg, #fef3c7)",border:"1px solid var(--cedros-admin-warning-border, #f59e0b)",borderRadius:"0.375rem",fontSize:"0.875rem",color:"var(--cedros-admin-warning-text, #92400e)",pointerEvents:"auto"},children:"This payment method is disabled. Enable it using the toggle above to accept payments."}),n.jsx(Ep,{category:d.category,config:d.config,originalConfig:d.config,onSave:D,onValidate:z,onCancel:()=>A()})]}),h&&n.jsxs("div",{className:"cedros-admin__settings-history",style:{marginTop:"1.5rem"},children:[n.jsx("h4",{style:{marginBottom:"0.75rem",fontWeight:600},children:"Change History"}),u.length===0?n.jsx("p",{className:"cedros-admin__text-muted",children:"No history entries found."}):n.jsx("div",{className:"cedros-admin__settings-timeline",children:u.map(W=>n.jsxs("div",{className:"cedros-admin__settings-timeline-item",children:[n.jsx("div",{className:"cedros-admin__settings-timeline-dot"}),n.jsxs("div",{className:"cedros-admin__settings-timeline-content",children:[n.jsxs("div",{className:"cedros-admin__settings-timeline-header",children:[n.jsx("code",{children:W.configKey}),n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${W.action.toLowerCase()}`,children:W.action})]}),n.jsxs("div",{className:"cedros-admin__settings-timeline-meta",children:[fr(W.changedAt)," by ",W.changedBy]})]})]},W.id))})]}),v&&n.jsx("div",{style:{marginTop:"1rem",padding:"0.75rem 1rem",borderRadius:"0.375rem",backgroundColor:v.valid?"var(--cedros-admin-success-bg, #dcfce7)":"var(--cedros-admin-error-bg, #fef2f2)",border:`1px solid ${v.valid?"var(--cedros-admin-success-border, #86efac)":"var(--cedros-admin-error-border, #fecaca)"}`},children:n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:600,color:v.valid?"var(--cedros-admin-success, #16a34a)":"var(--cedros-admin-error, #dc2626)",marginBottom:v.errors.length>0||v.warnings.length>0?"0.5rem":0},children:v.valid?"✓ Configuration is valid":"✗ Validation failed"}),v.errors.length>0&&n.jsx("ul",{style:{margin:0,paddingLeft:"1.25rem",color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.875rem"},children:v.errors.map((W,T)=>n.jsx("li",{children:W},T))}),v.warnings.length>0&&n.jsx("ul",{style:{margin:v.errors.length>0?"0.5rem 0 0":0,paddingLeft:"1.25rem",color:"var(--cedros-admin-warning, #ca8a04)",fontSize:"0.875rem"},children:v.warnings.map((W,T)=>n.jsx("li",{children:W},T))})]}),n.jsx("button",{type:"button",onClick:()=>_(null),style:{background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"1.25rem",lineHeight:1},title:"Dismiss",children:"×"})]})}),n.jsxs("div",{style:{marginTop:"1.5rem",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:()=>x(!h),children:h?"Hide History":"History"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",disabled:C||!d,onClick:async()=>{if(d){E(!0),_(null);try{const W=await z(d.config);_(W)}catch(W){_({valid:!1,errors:[W instanceof Error?W.message:"Validation failed"],warnings:[]})}finally{E(!1)}}},children:C?"Validating...":"Validate"})]})]})}const ki=[{id:"logging",label:"Logging",category:"logging",description:"Configure log levels, format, and environment settings."},{id:"metrics",label:"Metrics",category:"metrics",description:"Configure metrics collection and API access for monitoring."},{id:"security",label:"Security",category:"security",description:"Configure CORS, rate limiting, and other security settings."}];function ca({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("logging"),a=ki.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__server-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Server"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure logging, metrics, and security settings."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:ki.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(ol,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description},a.category)})]})}const Mp=Object.freeze(Object.defineProperty({__proto__:null,SettingsSection:ca},Symbol.toStringTag,{value:"Module"})),Se={enabled:!1,plans:[],pageTitle:"Choose Your Plan",pageSubtitle:"Select the plan that best fits your needs.",annualSavingsBadge:"2 months free",popularBadgeText:"Best Deal",footerNotice:""},Dp={title:"New Plan",description:"",priceMonthlyUsd:0,priceAnnualUsd:0,features:[],featureHighlight:"",buttonText:"Purchase",isPopular:!1,isActive:!0,sortOrder:0};function Lp(){return`plan_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function al({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState(Se),[a,i]=w.useState(!0),[c,l]=w.useState(null),[d,m]=w.useState("plans"),[u,f]=w.useState("idle"),[h,x]=w.useState({enabled:Se.enabled,pageTitle:Se.pageTitle,pageSubtitle:Se.pageSubtitle,annualSavingsBadge:Se.annualSavingsBadge,popularBadgeText:Se.popularBadgeText,footerNotice:Se.footerNotice}),[p,y]=w.useState(h),[j,b]=w.useState(""),v=w.useCallback(async()=>{try{let T;const V="/admin/subscriptions/settings";if(r?.isAuthenticated())T=await r.fetchWithAuth(V);else{const ee={"Content-Type":"application/json"};t&&(ee["X-API-Key"]=t);const B=await fetch(`${e}${V}`,{headers:ee});if(!B.ok)throw new Error(`Failed to fetch settings: ${B.status}`);T=await B.json()}o({...Se,...T}),x({enabled:T.enabled??Se.enabled,pageTitle:T.pageTitle??Se.pageTitle,pageSubtitle:T.pageSubtitle??Se.pageSubtitle,annualSavingsBadge:T.annualSavingsBadge??Se.annualSavingsBadge,popularBadgeText:T.popularBadgeText??Se.popularBadgeText,footerNotice:T.footerNotice??Se.footerNotice}),y({enabled:T.enabled??Se.enabled,pageTitle:T.pageTitle??Se.pageTitle,pageSubtitle:T.pageSubtitle??Se.pageSubtitle,annualSavingsBadge:T.annualSavingsBadge??Se.annualSavingsBadge,popularBadgeText:T.popularBadgeText??Se.popularBadgeText,footerNotice:T.footerNotice??Se.footerNotice}),b(JSON.stringify(T.plans??[]))}catch{const T={...Se,enabled:!0,plans:[{id:"plan_starter",title:"Starter",description:"For individuals",priceMonthlyUsd:9,priceAnnualUsd:90,features:["100 requests/month","Email support"],isActive:!0,sortOrder:0,activeSubscribers:142},{id:"plan_pro",title:"Pro",description:"For professionals",priceMonthlyUsd:29,priceAnnualUsd:290,features:["Unlimited requests","Priority support","API access"],isPopular:!0,isActive:!0,sortOrder:1,activeSubscribers:89},{id:"plan_enterprise",title:"Enterprise",description:"For teams",priceMonthlyUsd:99,priceAnnualUsd:990,features:["Everything in Pro","SSO","Dedicated support"],isActive:!0,sortOrder:2,activeSubscribers:23}]};o(T),x({enabled:T.enabled,pageTitle:T.pageTitle??Se.pageTitle,pageSubtitle:T.pageSubtitle??Se.pageSubtitle,annualSavingsBadge:T.annualSavingsBadge??Se.annualSavingsBadge,popularBadgeText:T.popularBadgeText??Se.popularBadgeText,footerNotice:T.footerNotice??Se.footerNotice}),y({enabled:T.enabled,pageTitle:T.pageTitle??Se.pageTitle,pageSubtitle:T.pageSubtitle??Se.pageSubtitle,annualSavingsBadge:T.annualSavingsBadge??Se.annualSavingsBadge,popularBadgeText:T.popularBadgeText??Se.popularBadgeText,footerNotice:T.footerNotice??Se.footerNotice}),b(JSON.stringify(T.plans))}finally{i(!1)}},[e,t,r]);w.useEffect(()=>{v()},[v]);const _=w.useCallback(async T=>{try{const V="/admin/subscriptions/settings",ee=JSON.stringify(T);if(r?.isAuthenticated())await r.fetchWithAuth(V,{method:"PUT",body:ee});else{const B={"Content-Type":"application/json"};t&&(B["X-API-Key"]=t);const Y=await fetch(`${e}${V}`,{method:"PUT",headers:B,body:ee});if(!Y.ok)throw new Error(`Failed to save settings: ${Y.status}`)}return!0}catch{return!0}},[r,t,e]),C=w.useMemo(()=>p.enabled!==h.enabled||p.pageTitle!==h.pageTitle||p.pageSubtitle!==h.pageSubtitle||p.annualSavingsBadge!==h.annualSavingsBadge||p.popularBadgeText!==h.popularBadgeText||p.footerNotice!==h.footerNotice,[h,p]),E=w.useMemo(()=>JSON.stringify(s.plans),[s.plans]),S=w.useMemo(()=>j!==E,[E,j]),N=w.useCallback(async()=>{const T={...s,enabled:h.enabled,pageTitle:h.pageTitle,pageSubtitle:h.pageSubtitle,annualSavingsBadge:h.annualSavingsBadge,popularBadgeText:h.popularBadgeText,footerNotice:h.footerNotice};f("saving");const V=await _(T);o(T),V&&(y({enabled:T.enabled,pageTitle:T.pageTitle,pageSubtitle:T.pageSubtitle,annualSavingsBadge:T.annualSavingsBadge,popularBadgeText:T.popularBadgeText,footerNotice:T.footerNotice}),b(JSON.stringify(T.plans))),f(V?"saved":"error"),setTimeout(()=>f("idle"),1500)},[h,_,s]);w.useEffect(()=>{if(d!=="page"||a||!C)return;const T=setTimeout(N,600);return()=>clearTimeout(T)},[d,C,a,N]),w.useEffect(()=>{if(d!=="plans"||a||!S)return;const T=setTimeout(N,800);return()=>clearTimeout(T)},[d,S,a,N]);const U=()=>{const T={...Dp,id:Lp(),sortOrder:s.plans.length};o(V=>({...V,plans:[...V.plans,T]})),l(T.id)},k=(T,V)=>{o(ee=>({...ee,plans:ee.plans.map(B=>B.id===T?{...B,...V}:B)}))},A=T=>{confirm("Delete this plan? This cannot be undone.")&&(o(V=>({...V,plans:V.plans.filter(ee=>ee.id!==T)})),c===T&&l(null))},P=(T,V)=>{const ee=s.plans.findIndex(J=>J.id===T);if(ee===-1||V==="up"&&ee===0||V==="down"&&ee===s.plans.length-1)return;const B=[...s.plans],Y=V==="up"?ee-1:ee+1;[B[ee],B[Y]]=[B[Y],B[ee]],o(J=>({...J,plans:B}))},D=T=>{k(T,{features:[...s.plans.find(V=>V.id===T)?.features||[],""]})},z=(T,V,ee)=>{const B=s.plans.find(J=>J.id===T);if(!B)return;const Y=[...B.features];Y[V]=ee,k(T,{features:Y})},L=(T,V)=>{const ee=s.plans.find(Y=>Y.id===T);if(!ee)return;const B=ee.features.filter((Y,J)=>J!==V);k(T,{features:B})};if(a)return n.jsx("div",{className:"cedros-admin__page",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading subscription settings..."]})});const O=s.plans.filter(T=>T.isActive).length,M=s.plans.reduce((T,V)=>T+(V.activeSubscribers??0),0),R=h.enabled,W=s.plans.filter(T=>T.isActive).map(T=>({label:T.title,value:T.activeSubscribers??0,description:"subscribers"}));return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Gn,{stats:[{label:"Status",value:R?"Enabled":"Disabled",variant:R?"success":"muted"},{label:"Active Plans",value:O,variant:O>0?"success":"muted"},{label:"Total Subscribers",value:M,variant:M>0?"success":"muted"},...W],isLoading:a}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Subscription Settings"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[d==="plans"&&n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:U,disabled:!R,children:[G.plus,"Add Plan"]}),n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${u}`,children:[u==="saving"&&"Saving...",u==="saved"&&"Saved",u==="error"&&"Error"]})]})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="plans"?"cedros-admin__tab--active":""}`,onClick:()=>m("plans"),children:"Plans"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="page"?"cedros-admin__tab--active":""}`,onClick:()=>m("page"),children:"Page Settings"})]}),d==="page"&&n.jsxs("div",{children:[n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Subscriptions"}),n.jsxs("label",{className:"cedros-admin__toggle",children:[n.jsx("input",{type:"checkbox",className:"cedros-admin__toggle-input",checked:h.enabled,onChange:T=>x(V=>({...V,enabled:T.target.checked}))}),n.jsx("span",{className:"cedros-admin__toggle-track",children:n.jsx("span",{className:"cedros-admin__toggle-thumb"})}),n.jsx("span",{className:"cedros-admin__toggle-label",children:"Enable Subscriptions"})]})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:h.pageTitle||"",onChange:T=>x(V=>({...V,pageTitle:T.target.value})),placeholder:"Choose Your Plan"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Subtitle"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:h.pageSubtitle||"",onChange:T=>x(V=>({...V,pageSubtitle:T.target.value})),placeholder:"Select the plan that best fits your needs."})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Savings Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:h.annualSavingsBadge||"",onChange:T=>x(V=>({...V,annualSavingsBadge:T.target.value})),placeholder:"2 months free"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Popular Plan Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:h.popularBadgeText||"",onChange:T=>x(V=>({...V,popularBadgeText:T.target.value})),placeholder:"Best Deal"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Footer Notice (optional)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:h.footerNotice||"",onChange:T=>x(V=>({...V,footerNotice:T.target.value})),placeholder:"For information regarding invoices, taxes..."})]})})]}),d==="plans"&&n.jsxs("div",{children:[!R&&n.jsx("div",{style:{padding:"1.5rem",textAlign:"center",opacity:.6},children:"Subscriptions are disabled. Enable them to configure plans."}),s.plans.length===0?n.jsx("div",{style:{padding:"2rem",textAlign:"center",opacity:.6,border:"1px dashed currentColor",borderRadius:8},children:'No plans configured. Click "Add Plan" to create your first subscription tier.'}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:s.plans.map((T,V)=>{const ee=c===T.id;return n.jsxs("div",{style:{border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:8,overflow:"hidden",background:T.isPopular?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"1rem",padding:"0.75rem 1rem",cursor:"pointer"},onClick:()=>l(ee?null:T.id),children:[n.jsx("span",{style:{opacity:.5},children:ee?G.chevronDown:G.chevronRight}),n.jsxs("div",{style:{flex:1},children:[n.jsx("span",{style:{fontWeight:600},children:T.title||"Untitled Plan"}),T.isPopular&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:11,padding:"2px 6px",borderRadius:4,background:"var(--cedros-admin-primary, #171717)",color:"#fff"},children:"Popular"}),!T.isActive&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:11,padding:"2px 6px",borderRadius:4,background:"#9ca3af",color:"#fff"},children:"Inactive"})]}),n.jsxs("span",{style:{opacity:.6,fontSize:14},children:["$",T.priceMonthlyUsd,"/mo · $",T.priceAnnualUsd,"/yr"]}),n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},onClick:B=>B.stopPropagation(),children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>P(T.id,"up"),disabled:V===0,title:"Move up",style:{padding:"4px 8px"},children:G.chevronUp}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>P(T.id,"down"),disabled:V===s.plans.length-1,title:"Move down",style:{padding:"4px 8px"},children:G.chevronDown}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>A(T.id),title:"Delete plan",style:{padding:"4px 8px",color:"#dc2626"},children:G.trash})]})]}),ee&&n.jsxs("div",{style:{padding:"1rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Plan Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:T.title,onChange:B=>k(T.id,{title:B.target.value}),placeholder:"e.g., Starter"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Button Text"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:T.buttonText||"",onChange:B=>k(T.id,{buttonText:B.target.value}),placeholder:"Purchase"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:T.description,onChange:B=>k(T.id,{description:B.target.value}),placeholder:"For entry-level developers managing lightweight workloads"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Monthly Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:T.priceMonthlyUsd||"",onChange:B=>k(T.id,{priceMonthlyUsd:parseFloat(B.target.value)||0}),placeholder:"10",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:T.priceAnnualUsd||"",onChange:B=>k(T.id,{priceAnnualUsd:parseFloat(B.target.value)||0}),placeholder:"100",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Feature Highlight"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:T.featureHighlight||"",onChange:B=>k(T.id,{featureHighlight:B.target.value}),placeholder:"100 prompts every 5 hours"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Bold text shown above feature list"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:T.isPopular||!1,onChange:B=>k(T.id,{isPopular:B.target.checked})}),"Mark as Popular (featured styling)"]})}),n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:T.isActive,onChange:B=>k(T.id,{isActive:B.target.checked})}),"Active (available for purchase)"]})})]}),n.jsxs("div",{className:"cedros-admin__form-row",style:{marginTop:"0.5rem"},children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:T.inventoryQuantity!=null,onChange:B=>k(T.id,{inventoryQuantity:B.target.checked?100:null})}),"Limit quantity available"]})}),T.inventoryQuantity!=null&&n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Total Available"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:T.inventoryQuantity??"",onChange:B=>k(T.id,{inventoryQuantity:parseInt(B.target.value)||0}),min:"0",style:{width:100}}),T.inventorySold!=null&&T.inventorySold>0&&n.jsxs("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:[T.inventorySold," sold · ",Math.max(0,T.inventoryQuantity-T.inventorySold)," remaining"]})]})]}),n.jsxs("div",{style:{marginTop:"1rem"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[n.jsxs("label",{className:"cedros-admin__field-label",style:{margin:0},children:["Feature List (",T.features.length,")"]}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>D(T.id),style:{fontSize:12,padding:"4px 8px"},children:"+ Add Feature"})]}),T.features.length===0?n.jsx("div",{style:{padding:"1rem",textAlign:"center",opacity:.5,fontSize:13,border:"1px dashed currentColor",borderRadius:6},children:'No features. Click "Add Feature" to add bullet points.'}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:T.features.map((B,Y)=>n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsxs("span",{style:{opacity:.4,fontSize:12},children:[Y+1,"."]}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:B,onChange:J=>z(T.id,Y,J.target.value),placeholder:"e.g., Powered by MiniMax M2.1",style:{flex:1}}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>L(T.id,Y),style:{padding:"4px 8px",color:"#dc2626"},title:"Remove feature",children:G.trash})]},Y))})]})]})]},T.id)})})]})]})]})}const $p=Object.freeze(Object.defineProperty({__proto__:null,SubscriptionsSection:al},Symbol.toStringTag,{value:"Module"})),ro={relatedProducts:{mode:"most_recent",maxItems:4,layout:{layout:"large",imageCrop:"center"}},catalog:{filters:{tags:!0,priceRange:!0,inStock:!0},sort:{featured:!0,priceAsc:!0,priceDesc:!0}},checkout:{promoCodes:!0},shopLayout:{layout:"large",imageCrop:"center"},categoryLayout:{layout:"large",imageCrop:"center"},sections:{showDescription:!0,showSpecs:!0,showShipping:!0,showRelatedProducts:!0},inventory:{preCheckoutVerification:!0,holdsEnabled:!1,holdDurationMinutes:15},shopPage:{title:"Shop",description:""}},zp=[{value:"most_recent",label:"Most Recent",description:"Show the most recently added products (excluding current product)."},{value:"by_category",label:"By Category",description:"Show products from the same category as the current product."},{value:"manual",label:"Manual Selection",description:"Specify related products per-product using relatedProductIds in metadata."},{value:"ai",label:"AI Recommendations",description:"Let AI analyze products and suggest the best matches. Requires AI to be configured in AI Settings."}],so=[{value:"large",label:"Large",description:"Portrait cards (4:5) with full product info, description, and tags."},{value:"square",label:"Square",description:"Square cards (1:1) showing title and price only."},{value:"compact",label:"Compact",description:"Compact cards (3:4) with smaller text to fit more products."}],oo=[{value:"center",label:"Center"},{value:"top",label:"Top"},{value:"bottom",label:"Bottom"},{value:"left",label:"Left"},{value:"right",label:"Right"}],Fp=[{id:"shop-page",label:"Shop Page"},{id:"catalog",label:"Catalog"},{id:"layouts",label:"Layouts"},{id:"product-pages",label:"Product Pages"},{id:"checkout",label:"Checkout"}];function il({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("shop-page"),[a,i]=w.useState(ro),[c,l]=w.useState(!0),[d,m]=w.useState(!0),u=w.useCallback(async()=>{try{let k;const A="/admin/config/storefront";if(r?.isAuthenticated())k=await r.fetchWithAuth(A);else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const D=await fetch(`${e}${A}`,{headers:P});if(!D.ok)throw new Error(`Failed to fetch settings: ${D.status}`);k=await D.json()}i({...ro,...k.config})}catch{i(ro)}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);w.useEffect(()=>{u()},[u]);const f=w.useCallback(async k=>{const A="/admin/config/storefront",P=JSON.stringify({config:k});try{if(r?.isAuthenticated())await r.fetchWithAuth(A,{method:"PUT",body:P});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}${A}`,{method:"PUT",headers:D,body:P});if(!z.ok)throw new Error(`Failed to save settings: ${z.status}`)}}catch{}},[e,t,r]),{status:h,error:x}=ia({data:a,onSave:f,debounceMs:1500,enabled:!d}),p=k=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,mode:k}}))},y=k=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,maxItems:k}}))},j=(k,A)=>{i(P=>({...P,relatedProducts:{...P.relatedProducts,layout:{...P.relatedProducts.layout,[k]:A}}}))},b=(k,A)=>{i(P=>({...P,catalog:{...P.catalog,filters:{...P.catalog.filters,[k]:A}}}))},v=(k,A)=>{const P=a.catalog.sort,D=Object.values(P).filter(Boolean).length;!A&&D<=1||i(z=>({...z,catalog:{...z.catalog,sort:{...z.catalog.sort,[k]:A}}}))},_=(k,A)=>{i(P=>({...P,checkout:{...P.checkout,[k]:A}}))},C=(k,A)=>{i(P=>({...P,shopLayout:{...P.shopLayout,[k]:A}}))},E=(k,A)=>{i(P=>({...P,categoryLayout:{...P.categoryLayout,[k]:A}}))},S=(k,A)=>{i(P=>({...P,sections:{...P.sections,[k]:A}}))},N=(k,A)=>{i(P=>({...P,inventory:{...P.inventory,[k]:A}}))},U=(k,A)=>{i(P=>({...P,shopPage:{...P.shopPage,[k]:A}}))};return c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading storefront settings..."]})}):n.jsxs("div",{className:"cedros-admin__storefront-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Storefront"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure catalog filters, product layouts, and checkout settings."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[Fp.map(k=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===k.id?"cedros-admin__tab--active":""}`,onClick:()=>o(k.id),children:k.label},k.id)),n.jsx("div",{style:{flex:1}}),n.jsx(Bp,{status:h,error:x})]}),s==="shop-page"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Shop Page Content"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Customize the title and description shown on your shop page."}),n.jsxs("div",{className:"cedros-admin__field",style:{marginBottom:"1.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.shopPage.title,onChange:k=>U("title",k.target.value),placeholder:"Shop"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"The main heading displayed on your shop page."})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Description"}),n.jsx("textarea",{className:"cedros-admin__textarea",value:a.shopPage.description,onChange:k=>U("description",k.target.value),placeholder:"Browse our collection of products...",rows:3,style:{resize:"vertical"}}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"A short description or subtitle shown below the title. Leave empty to hide."})]})]}),s==="catalog"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Catalog Filters"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which filters appear in the shop and category page sidebars."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.filters.tags,onChange:k=>b("tags",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Tags"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter products by tags (multi-select checkboxes)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.filters.priceRange,onChange:k=>b("priceRange",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price Range"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter by minimum and maximum price"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.filters.inStock,onChange:k=>b("inStock",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"In Stock"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show only products that are in stock"})]})]})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Sort Options"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sort options appear in the shop and category pages. At least one must be enabled."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.sort.featured,onChange:k=>v("featured",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Featured"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Default sort order (as returned by backend)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.sort.priceAsc,onChange:k=>v("priceAsc",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: Low to High"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price ascending"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.sort.priceDesc,onChange:k=>v("priceDesc",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: High to Low"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price descending"})]})]})]})]})]}),s==="layouts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Product Layouts"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Configure product card layouts for shop and category pages."}),n.jsxs("div",{style:{marginBottom:"2rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Shop Page"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:so.map(k=>{const A=a.shopLayout.layout===k.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"shopLayout",value:k.value,checked:A,onChange:()=>C("layout",k.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:k.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:k.description})]})]},k.value)})}),n.jsx(lt,{value:a.shopLayout.imageCrop,onChange:k=>C("imageCrop",k),options:oo,label:"Image Crop",style:{maxWidth:180}})]}),n.jsxs("div",{style:{paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Category Pages"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:so.map(k=>{const A=a.categoryLayout.layout===k.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"categoryLayout",value:k.value,checked:A,onChange:()=>E("layout",k.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:k.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:k.description})]})]},k.value)})}),n.jsx(lt,{value:a.categoryLayout.imageCrop,onChange:k=>E("imageCrop",k),options:oo,label:"Image Crop",style:{maxWidth:180}})]})]}),s==="product-pages"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Related Products"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure how related products are displayed on product detail pages."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"1.5rem"},children:zp.map(k=>{const A=a.relatedProducts.mode===k.value,P=k.badge==="Coming Soon";return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"1rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:8,cursor:P?"not-allowed":"pointer",opacity:P?.6:1,background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedProductsMode",value:k.value,checked:A,onChange:()=>!P&&p(k.value),disabled:P,style:{marginTop:2}}),n.jsxs("div",{style:{flex:1},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("span",{style:{fontWeight:600},children:k.label}),k.badge&&n.jsx("span",{style:{fontSize:11,padding:"2px 6px",borderRadius:4,background:"#6366f1",color:"#fff"},children:k.badge})]}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:13,opacity:.75},children:k.description})]})]},k.value)})}),a.relatedProducts.mode==="manual"&&n.jsxs("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #f5f5f5)",borderRadius:8,border:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("strong",{style:{fontSize:14},children:"How to set related products:"}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.8},children:["When editing a product, add a ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"relatedProductIds"})," field to its metadata containing a comma-separated list of product IDs."]}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.6},children:["Example: ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"prod_123,prod_456,prod_789"})]})]}),n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Max Related Products"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.relatedProducts.maxItems,onChange:k=>y(Math.max(1,Math.min(12,parseInt(k.target.value)||4))),min:1,max:12}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How many related products to show (1-12)"})]}),n.jsxs("div",{style:{marginTop:"1.5rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Display Layout"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:so.map(k=>{const A=a.relatedProducts.layout.layout===k.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedLayout",value:k.value,checked:A,onChange:()=>j("layout",k.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:k.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:k.description})]})]},k.value)})}),n.jsx(lt,{value:a.relatedProducts.layout.imageCrop,onChange:k=>j("imageCrop",k),options:oo,label:"Image Crop",style:{maxWidth:180}})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Page Sections"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sections appear on product detail pages."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showDescription,onChange:k=>S("showDescription",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Description"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Expandable description accordion"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showSpecs,onChange:k=>S("showSpecs",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Specifications"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product attributes and details"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showShipping,onChange:k=>S("showShipping",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Shipping & Returns"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Shipping and return policy information"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showRelatedProducts,onChange:k=>S("showRelatedProducts",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Related Products"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product recommendations section"})]})]})]})]})]}),s==="checkout"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Checkout Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure checkout and cart page features."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.checkout.promoCodes,onChange:k=>_("promoCodes",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Promo Codes"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show promo/coupon code input on cart and checkout pages"})]})]})})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Inventory Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure inventory verification and reservation behavior."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.inventory.preCheckoutVerification,onChange:k=>N("preCheckoutVerification",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Pre-Checkout Verification"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Verify inventory availability before processing payment"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.inventory.holdsEnabled,onChange:k=>N("holdsEnabled",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Inventory Holds"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Reserve inventory when items are added to cart"})]})]})]}),a.inventory.holdsEnabled&&n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200,marginTop:"1rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Hold Duration (minutes)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.inventory.holdDurationMinutes,onChange:k=>N("holdDurationMinutes",Math.max(5,Math.min(60,parseInt(k.target.value)||15))),min:5,max:60}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How long to reserve inventory in carts (5-60 minutes)"})]})]})]})]})}function Bp({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function bt({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:()=>t(!e),style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const Up=Object.freeze(Object.defineProperty({__proto__:null,StorefrontSection:il},Symbol.toStringTag,{value:"Module"})),ao=[{id:"not_set",label:"Not Set",provider:null},{id:"gemini-2.5-flash",label:"Gemini 2.5 Flash",provider:"gemini"},{id:"gemini-2.5-pro",label:"Gemini 2.5 Pro",provider:"gemini"},{id:"openai-4o",label:"OpenAI 4o",provider:"openai"},{id:"openai-5.1",label:"OpenAI 5.1",provider:"openai"},{id:"openai-5.2",label:"OpenAI 5.2",provider:"openai"}],Oo=[{task:"site_chat",label:"Site Chat",description:"The conversational model that crafts responses to customer messages",defaultPrompt:`You are a friendly and helpful shopping assistant for our store. Your role is to:
4
-
5
- - Help customers find products that match their needs
6
- - Answer questions about products, shipping, returns, and store policies
7
- - Provide personalized recommendations based on customer preferences
8
- - Use the Product Searcher tool when customers are looking for specific items
9
-
10
- Guidelines:
11
- - Be warm, conversational, and concise
12
- - Stay focused on helping with shopping-related questions
13
- - If you don't know something specific about a product, say so honestly
14
- - Never make up product details, prices, or availability
15
- - For complex issues (order problems, refunds), direct customers to contact support`},{task:"product_searcher",label:"Product Searcher",description:"Tool used by Site Chat to find products based on customer queries",defaultPrompt:`You are a product search assistant. Given a customer's query, extract relevant search parameters to find matching products.
16
-
17
- Extract the following when present:
18
- - Keywords: Main search terms
19
- - Category: Product category or type
20
- - Price range: Min/max price if mentioned
21
- - Attributes: Color, size, material, brand, or other specifications
22
- - Sort preference: Price, popularity, newest, etc.
23
-
24
- Return structured search parameters. Be liberal in interpretation - if a customer says "something for my mom's birthday under $50" extract: keywords=gift, price_max=50, occasion=birthday.
25
-
26
- Do not make assumptions about specific products. Focus only on extracting search intent.`},{task:"related_product_finder",label:"Related Product Finder",description:"AI-powered recommendations for related products on product pages",defaultPrompt:`You are a product recommendation engine. Given a product, suggest related items that customers might also be interested in.
27
-
28
- Consider these recommendation types:
29
- - Complementary items: Products that go well together (e.g., phone case for a phone)
30
- - Similar alternatives: Products in the same category with different features or price points
31
- - Frequently bought together: Items commonly purchased as a set
32
- - Upsells: Premium versions or upgrades
33
-
34
- Guidelines:
35
- - Prioritize relevance over variety
36
- - Consider the product's category, price range, and use case
37
- - Return product IDs or search criteria for related items
38
- - Aim for 4-8 recommendations with a mix of types`},{task:"product_detail_assistant",label:"Product Detail Assistant",description:"Admin tool to generate product descriptions, suggest tags, and fill out product details",defaultPrompt:`You are a product copywriting assistant helping store administrators create compelling product listings.
39
-
40
- You can help with:
41
- - Writing engaging product descriptions that highlight key features and benefits
42
- - Suggesting relevant tags and categories for better discoverability
43
- - Creating SEO-friendly titles and meta descriptions
44
- - Generating bullet points for key features
45
- - Writing size guides or care instructions when applicable
46
-
47
- Guidelines:
48
- - Match the store's brand voice (ask if unclear)
49
- - Focus on benefits, not just features
50
- - Use sensory language when appropriate
51
- - Keep descriptions scannable with short paragraphs
52
- - Avoid superlatives and unverifiable claims
53
- - Include relevant keywords naturally for SEO`}],Wp=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],Ci={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:Oo.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function cl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("api-keys"),[a,i]=w.useState(Ci),[c,l]=w.useState(!0),[d,m]=w.useState(!1),[u,f]=w.useState(null),[h,x]=w.useState(!1),p=w.useRef(null),[y,j]=w.useState({gemini:"",openai:""}),[b,v]=w.useState({gemini:!1,openai:!1});w.useEffect(()=>{async function k(){try{let A;if(r?.isAuthenticated())A=await r.fetchWithAuth("/admin/config/ai");else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const D=await fetch(`${e}/admin/config/ai`,{headers:P});if(!D.ok)throw new Error(`Failed to fetch: ${D.status}`);A=await D.json()}A.settings&&i(A.settings)}catch{i(Ci)}finally{l(!1)}}k()},[e,t,r]);const _=w.useCallback(async k=>{const A=y[k];if(A.trim()){m(!0),f(null);try{const P={provider:k,apiKey:A};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(P)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:D,body:JSON.stringify(P)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(D=>({...D,apiKeys:D.apiKeys.map(z=>z.provider===k?{...z,isConfigured:!0,maskedKey:`${A.slice(0,4)}...${A.slice(-4)}`,updatedAt:new Date().toISOString()}:z)})),j(D=>({...D,[k]:""})),x(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3)}catch(P){f(P instanceof Error?P.message:"Failed to save API key")}finally{m(!1)}}},[y,e,t,r]),C=w.useCallback(async k=>{if(confirm(`Are you sure you want to delete the ${k==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),f(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${k}`,{method:"DELETE"});else{const A={"Content-Type":"application/json"};t&&(A["X-API-Key"]=t);const P=await fetch(`${e}/admin/config/ai/api-key/${k}`,{method:"DELETE",headers:A});if(!P.ok)throw new Error(`Failed to delete: ${P.status}`)}i(A=>({...A,apiKeys:A.apiKeys.map(P=>P.provider===k?{provider:k,isConfigured:!1}:P)}))}catch(A){f(A instanceof Error?A.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),E=w.useCallback(async(k,A)=>{m(!0),f(null);try{const P={task:k,model:A};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(P)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:D,body:JSON.stringify(P)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(z=>z.task===k?{...z,assignedModel:A}:z)})),x(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3)}catch(P){f(P instanceof Error?P.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),S=w.useCallback(k=>{if(k==="not_set")return!0;const A=ao.find(D=>D.id===k);return A?.provider?a.apiKeys.find(D=>D.provider===A.provider)?.isConfigured??!1:!0},[a.apiKeys]),N=w.useMemo(()=>ao.map(k=>{const A=S(k.id);return{value:k.id,label:A?k.label:`${k.label} (API key required)`,disabled:!A}}),[S]),U=w.useCallback(async(k,A)=>{m(!0),f(null);try{const P={task:k,systemPrompt:A};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(P)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:D,body:JSON.stringify(P)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(z=>z.task===k?{...z,systemPrompt:A}:z)})),x(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3)}catch(P){f(P instanceof Error?P.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),h&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[G.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:Wp.map(k=>{const A=a.apiKeys.find(D=>D.provider===k.id),P=A?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:k.label}),P&&A?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",A.maskedKey,A.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(A.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${P?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:P?"Configured":"Not Set"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:b[k.id]?"text":"password",className:"cedros-admin__input",placeholder:P?"Enter new key to replace":k.placeholder,value:y[k.id],onChange:D=>j(z=>({...z,[k.id]:D.target.value})),onBlur:()=>{y[k.id].trim()&&_(k.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>v(D=>({...D,[k.id]:!D[k.id]})),title:b[k.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:b[k.id]?G.eyeOff:G.eye}),P&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(k.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:G.trash})]})})]},k.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(k=>{const A=Oo.find(D=>D.task===k.task),P=ao.find(D=>D.id===k.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:A?.label??k.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:A?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(lt,{value:k.assignedModel,onChange:D=>E(k.task,D),options:N,label:"",disabled:d,style:{flex:1,maxWidth:280}}),P&&P.provider&&n.jsx("span",{className:`cedros-admin__badge ${S(P.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:S(P.id)?"Ready":"Missing API Key"})]})]},k.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(k=>{const A=Oo.find(P=>P.task===k.task);return n.jsx(Vp,{task:k.task,label:A?.label??k.task,description:A?.description??"",initialPrompt:k.systemPrompt??"",onSave:U},k.task)})})]})]})}function Vp({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=w.useState(s),[c,l]=w.useState("idle"),d=w.useRef(null),m=w.useRef(null),u=w.useRef(!0);return w.useEffect(()=>{if(u.current){u.current=!1;return}return d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),l("pending"),d.current=setTimeout(async()=>{l("saving");try{await o(e,a),l("saved"),m.current=setTimeout(()=>l("idle"),2e3)}catch{l("error")}},1500),()=>{d.current&&clearTimeout(d.current)}},[a,e,o]),w.useEffect(()=>()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current)},[]),n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:t}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:r})]}),n.jsx(Hp,{status:c})]}),n.jsx("textarea",{className:"cedros-admin__input",value:a,onChange:f=>i(f.target.value),placeholder:"Enter system prompt...",rows:4,style:{width:"100%",resize:"vertical",fontFamily:"inherit",minHeight:100}})]})}function Hp({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const qp=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:cl},Symbol.toStringTag,{value:"Module"}));function Dn({href:e,children:t}){return n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:t})}const Ni=[{id:"stripe",label:"Stripe",category:"stripe",description:n.jsxs(n.Fragment,{children:["Configure your Stripe integration for card payments. Get your API keys from the"," ",n.jsx(Dn,{href:"https://dashboard.stripe.com/apikeys",children:"Stripe Dashboard"}),"."]})},{id:"crypto",label:"Crypto",category:"x402",description:n.jsxs(n.Fragment,{children:["Configure Solana wallet and token settings for crypto payments. Get a fast RPC endpoint from"," ",n.jsx(Dn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(Dn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(Dn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(Dn,{href:"https://solflare.com",children:"Solflare"})," wallet."]})},{id:"credits",label:"Credits",category:"cedros_login",description:n.jsxs(n.Fragment,{children:["Configure Cedros Login integration for credits payments. See the"," ",n.jsx(Dn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function ll({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("stripe"),a=Ni.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__payment-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Payment Options"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure payment methods including Stripe, crypto, and credits."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:Ni.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(ol,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description,showEnabledToggle:!0},a.category)})]})}const Zp=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:ll},Symbol.toStringTag,{value:"Module"})),io={email_enabled:!1,smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function dl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("messages"),[a,i]=w.useState(io),[c,l]=w.useState(!0),[d,m]=w.useState(!0),[u,f]=w.useState(new Set),h=w.useCallback(async()=>{try{let b;const v="/admin/config/messaging";if(r?.isAuthenticated())b=await r.fetchWithAuth(v);else{const _={"Content-Type":"application/json"};t&&(_["X-API-Key"]=t);const C=await fetch(`${e}${v}`,{headers:_});if(!C.ok)throw new Error(`Failed to fetch: ${C.status}`);b=await C.json()}i({...io,...b.config})}catch{i(io)}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);w.useEffect(()=>{h()},[h]);const x=w.useCallback(async b=>{const v="/admin/config/messaging",_={...b};u.has("smtp_password")||delete _.smtp_password,u.has("webhook_secret")||delete _.webhook_secret;const C=JSON.stringify({config:_});try{if(r?.isAuthenticated())await r.fetchWithAuth(v,{method:"PUT",body:C});else{const E={"Content-Type":"application/json"};t&&(E["X-API-Key"]=t);const S=await fetch(`${e}${v}`,{method:"PUT",headers:E,body:C});if(!S.ok)throw new Error(`Failed to save: ${S.status}`)}}catch{}},[e,t,r,u]),{status:p,error:y}=ia({data:a,onSave:x,debounceMs:1500,enabled:!d}),j=(b,v)=>{(b==="smtp_password"||b==="webhook_secret")&&f(_=>new Set(_).add(b)),i(_=>({..._,[b]:v}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[G.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(Gp,{status:p,error:y})]}),n.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[s==="messages"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(Ai,{checked:a.email_enabled,onChange:()=>j("email_enabled",!a.email_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(Ai,{checked:a.webhook_enabled,onChange:()=>j("webhook_enabled",!a.webhook_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),s==="email"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure your email provider for sending customer notifications."}),!a.email_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:b=>j("smtp_host",b.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:b=>j("smtp_port",parseInt(b.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:b=>j("smtp_username",b.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:u.has("smtp_password")?a.smtp_password:"",onChange:b=>j("smtp_password",b.target.value),placeholder:a.smtp_password?"••••••••":"Enter password",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),n.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:b=>j("from_email",b.target.value),placeholder:"orders@yourstore.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:b=>j("from_name",b.target.value),placeholder:"Your Store",disabled:!a.email_enabled})]})]})]}),s==="webhooks"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:b=>j("webhook_url",b.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:u.has("webhook_secret")?a.webhook_secret:"",onChange:b=>j("webhook_secret",b.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:b=>j("webhook_timeout",parseInt(b.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function Gp({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function Ai({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:t,style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const Qp=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:dl},Symbol.toStringTag,{value:"Module"}));function Mo(e){return!e||typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function ul({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=w.useState([]),[i,c]=w.useState(!0),[l,d]=w.useState(!1),[m,u]=w.useState(null),[f,h]=w.useState(!1),[x,p]=w.useState(""),[y,j]=w.useState("all"),[b,v]=w.useState(null),[_,C]=w.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),E=w.useCallback(async()=>{c(!0);try{let M;const R=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())M=await s.fetchWithAuth(R);else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const T=await fetch(`${e}${R}`,{headers:W});if(!T.ok)throw new Error(`Failed to fetch FAQs: ${T.status}`);M=await T.json()}a(M.faqs||[])}catch{a([{id:"faq_1",question:"What is your return policy?",answer:"We accept returns within 30 days of purchase. Items must be unused and in original packaging.",keywords:["returns","refund","policy"],active:!0,useInChat:!0,displayOnPage:!0,createdAt:"2026-01-15T10:00:00Z"},{id:"faq_2",question:"How long does shipping take?",answer:"Standard shipping takes 5-7 business days. Express shipping is available for 2-3 day delivery.",keywords:["shipping","delivery","time"],active:!0,useInChat:!0,displayOnPage:!0,createdAt:"2026-01-16T10:00:00Z"},{id:"faq_3",question:"Do you ship internationally?",answer:"Yes, we ship to most countries. International shipping typically takes 10-14 business days.",keywords:["international","shipping","global"],active:!1,useInChat:!0,displayOnPage:!1,createdAt:"2026-01-17T10:00:00Z"}])}finally{c(!1)}},[e,t,r,s]);w.useEffect(()=>{E()},[E]);const S=async M=>{if(M.preventDefault(),!(!_.question.trim()||!_.answer.trim())){h(!0);try{const R=_.keywordsCsv.split(",").map(T=>T.trim().toLowerCase()).filter(Boolean),W={question:_.question.trim(),answer:_.answer.trim(),keywords:R,active:_.active,useInChat:_.useInChat,displayOnPage:_.displayOnPage};if(m){const T=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(T,{method:"PUT",body:JSON.stringify(W)});else{const V={"Content-Type":"application/json"};t&&(V["X-API-Key"]=t);const ee=await fetch(`${e}${T}`,{method:"PUT",headers:V,body:JSON.stringify(W)});if(!ee.ok)throw new Error(`Failed to update FAQ: ${ee.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(W)});else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const V=await fetch(`${e}/admin/faqs`,{method:"POST",headers:T,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to create FAQ: ${V.status}`)}k(),E()}catch{a(m?R=>R.map(W=>W.id===m.id?{...W,question:_.question.trim(),answer:_.answer.trim(),keywords:Mo(_.keywordsCsv).map(T=>T.toLowerCase()),active:_.active,useInChat:_.useInChat,displayOnPage:_.displayOnPage,updatedAt:new Date().toISOString()}:W):R=>[...R,{id:`faq_${Date.now()}`,question:_.question.trim(),answer:_.answer.trim(),keywords:Mo(_.keywordsCsv).map(W=>W.toLowerCase()),active:_.active,useInChat:_.useInChat,displayOnPage:_.displayOnPage,createdAt:new Date().toISOString()}]),k()}finally{h(!1)}}},N=async M=>{try{const R=`/admin/faqs/${M}`;if(s?.isAuthenticated())await s.fetchWithAuth(R,{method:"DELETE"});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const T=await fetch(`${e}${R}`,{method:"DELETE",headers:W});if(!T.ok)throw new Error(`Failed to delete FAQ: ${T.status}`)}E()}catch{a(R=>R.filter(W=>W.id!==M))}v(null)},U=async M=>{try{const R=`/admin/faqs/${M.id}`,W={...M,active:!M.active};if(s?.isAuthenticated())await s.fetchWithAuth(R,{method:"PUT",body:JSON.stringify(W)});else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const V=await fetch(`${e}${R}`,{method:"PUT",headers:T,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to update FAQ: ${V.status}`)}E()}catch{a(R=>R.map(W=>W.id===M.id?{...W,active:!W.active}:W))}},k=()=>{C({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},A=M=>{C({question:M.question,answer:M.answer,keywordsCsv:M.keywords.join(", "),active:M.active,useInChat:M.useInChat??!0,displayOnPage:M.displayOnPage??!0}),u(M),d(!0)},P=o.length,D=o.filter(M=>M.active).length,z=o.filter(M=>M.active&&M.useInChat).length,L=o.filter(M=>M.active&&M.displayOnPage).length,O=w.useMemo(()=>o.filter(M=>{if(y==="active"&&!M.active||y==="inactive"&&M.active)return!1;if(x){const R=x.toLowerCase();return M.question.toLowerCase().includes(R)||M.answer.toLowerCase().includes(R)||M.keywords.some(W=>W.includes(R))}return!0}),[o,y,x]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(Gn,{stats:[{label:"Total FAQs",value:P},{label:"Active",value:D,variant:"success"},{label:"In Chat",value:z},{label:"On Page",value:L}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__btn cedros-admin__btn--primary",onClick:()=>{k(),d(!0)},children:[G.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:x,onChange:M=>p(M.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:y,onChange:M=>j(M.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:S,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__btn--icon",onClick:k,children:G.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:_.question,onChange:M=>C(R=>({...R,question:M.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),n.jsx("textarea",{value:_.answer,onChange:M=>C(R=>({...R,answer:M.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),n.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),n.jsx("input",{type:"text",value:_.keywordsCsv,onChange:M=>C(R=>({...R,keywordsCsv:M.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),n.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:_.active,onChange:M=>C(R=>({...R,active:M.target.checked}))}),n.jsx("span",{children:"Active"})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),n.jsxs("div",{className:"cedros-admin__checkbox-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:_.useInChat,onChange:M=>C(R=>({...R,useInChat:M.target.checked}))}),n.jsx("span",{children:"Use in AI Chat"})]}),n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:_.displayOnPage,onChange:M=>C(R=>({...R,displayOnPage:M.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__btn",onClick:k,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__btn cedros-admin__btn--primary",disabled:f||!_.question.trim()||!_.answer.trim(),children:f?G.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading,n.jsx("span",{children:"Loading FAQs..."})]}):O.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:x||y!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:O.map(M=>n.jsxs("div",{className:`cedros-admin__faq-item ${M.active?"":"cedros-admin__faq-item--inactive"}`,children:[n.jsxs("div",{className:"cedros-admin__faq-content",children:[n.jsxs("div",{className:"cedros-admin__faq-question",children:[n.jsx("span",{className:`cedros-admin__status-dot ${M.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),M.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:M.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[M.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:M.keywords.map(R=>n.jsx("span",{className:"cedros-admin__tag",children:R},R))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[M.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[G.chat," Chat"]}),M.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[G.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>U(M),title:M.active?"Deactivate":"Activate",children:M.active?G.eyeOff:G.eye}),n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>A(M),title:"Edit",children:G.edit}),n.jsx("button",{className:"cedros-admin__btn--icon cedros-admin__btn--danger",onClick:()=>v(M.id),title:"Delete",children:G.trash})]}),b===M.id&&n.jsx("div",{className:"cedros-admin__confirm-overlay",children:n.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[n.jsx("p",{children:"Delete this FAQ?"}),n.jsxs("div",{className:"cedros-admin__confirm-actions",children:[n.jsx("button",{className:"cedros-admin__btn",onClick:()=>v(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__btn cedros-admin__btn--danger",onClick:()=>N(M.id),children:"Delete"})]})]})})]},M.id))})]})]})}const Yp=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:ul},Symbol.toStringTag,{value:"Module"}));class Kp{serverUrl;walletSigner=null;jwtToken=null;isAdmin=!1;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdmin?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,oe.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,this.isAdmin=r,oe.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t,isAdmin:r})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=oe.bs58.encode(this.walletSigner.publicKey.toBytes()),i=oe.bs58.encode(o);return{"X-Signer":a,"X-Message":r.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const r=`${this.serverUrl}/paywall/v1/nonce`;oe.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await oe.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!s.ok){const o=await s.text();throw new Error(`Failed to fetch nonce: ${s.status} ${o}`)}return await s.json()}async fetchWithAuth(t,r={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,r.method||"GET"),a=await this.createAuthHeaders(o),i={"Content-Type":"application/json",...r.headers||{},...a},c=await oe.fetchWithTimeout(`${this.serverUrl}${t}`,{...r,headers:i});if(!c.ok){const l=await c.text();throw new Error(`Admin API error ${c.status}: ${l}`)}return await c.json()}getPurposeFromPath(t,r){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[r])return o[r];if(t.startsWith("/admin/products/")){if(r==="PUT")return"admin_products_update";if(r==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(r==="PUT")return"admin_coupons_update";if(r==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(r==="GET")return"admin_config_get";if(r==="PUT")return"admin_config_update";if(r==="PATCH")return"admin_config_patch"}return`admin_${r.toLowerCase()}`}}function Jp({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=Hn.useWallet(),o=w.useMemo(()=>new Kp(e),[e]);w.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]),w.useEffect(()=>{o.setCedrosLoginAuth(t??null,r)},[o,t,r]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!(t&&r),d=w.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=w.useCallback((u,f)=>o.fetchWithAuth(u,f),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const ml=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:G.transactions},{id:"products",label:"Products",icon:G.products},{id:"subscriptions",label:"Subscriptions",icon:G.calendarRepeat},{id:"coupons",label:"Coupons",icon:G.coupons},{id:"refunds",label:"Refunds",icon:G.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:G.storefront},{id:"ai-settings",label:"Store AI",icon:G.brain},{id:"faqs",label:"Knowledge Base",icon:G.faq},{id:"payment-settings",label:"Payment Options",icon:G.creditCard},{id:"messaging",label:"Store Messages",icon:G.mail},{id:"settings",label:"Store Server",icon:G.server}]}],Xp=ml.flatMap(e=>e.sections);function ef(){const[e,t]=w.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return w.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=o=>t(o.matches?"dark":"light");return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[]),e}function tf(e,t,r){return e!=="system"?e:t||r}function nf({serverUrl:e,apiKey:t,title:r="Cedros Pay",sections:s=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:m=!1,theme:u="system"}){const[f,h]=w.useState(o),[x,p]=w.useState(!0),[y,j]=w.useState(new Set),b=w.useCallback(A=>{j(P=>{const D=new Set(P);return D.has(A)?D.delete(A):D.add(A),D})},[]),v=oe.useCedrosThemeOptional(),_=ef(),E=tf(u,v?.mode??null,_)==="dark"?"cedros-admin--dark":"",{authManager:S}=Jp({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),N=w.useCallback(A=>{h(A),c?.(A)},[c]),k=Xp.filter(A=>s.includes(A.id)).find(A=>A.id===f);return w.useEffect(()=>{const A=setTimeout(()=>p(!1),500);return()=>clearTimeout(A)},[]),x?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${E} ${l}`,children:[G.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${E} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[G.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:ml.map(A=>{const P=A.sections.filter(z=>s.includes(z.id));if(P.length===0)return null;const D=A.collapsible&&y.has(A.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[A.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>b(A.label),"aria-expanded":!D,children:[A.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${D?"":"cedros-admin__nav-label-icon--expanded"}`,children:G.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:A.label}),!D&&P.map(z=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${f===z.id?"cedros-admin__nav-item--active":""}`,onClick:()=>N(z.id),"aria-current":f===z.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:z.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:z.label})]},z.id))]},A.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:G.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:k?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[f==="products"&&n.jsx(el,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="subscriptions"&&n.jsx(al,{serverUrl:e,apiKey:t,authManager:S}),f==="transactions"&&n.jsx(tl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="coupons"&&n.jsx(nl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="refunds"&&n.jsx(rl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="storefront"&&n.jsx(il,{serverUrl:e,apiKey:t,authManager:S}),f==="ai-settings"&&n.jsx(cl,{serverUrl:e,apiKey:t,authManager:S}),f==="faqs"&&n.jsx(ul,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="payment-settings"&&n.jsx(ll,{serverUrl:e,apiKey:t,authManager:S}),f==="messaging"&&n.jsx(dl,{serverUrl:e,apiKey:t,authManager:S}),f==="settings"&&n.jsx(ca,{serverUrl:e,apiKey:t,authManager:S})]})]})]})}const Nt=e=>w.lazy(async()=>{const s=(await e()).default;return{default:({pluginContext:a})=>{const i={serverUrl:a.serverUrl};return n.jsx(s,{...i})}}}),rf={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:G.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:G.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:G.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:G.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:G.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:G.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:G.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:G.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:G.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:G.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:G.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:Nt(()=>Promise.resolve().then(()=>require("./sections-D6R2jRAp.js")).then(e=>({default:e.ProductsSection}))),subscriptions:Nt(()=>Promise.resolve().then(()=>$p).then(e=>({default:e.SubscriptionsSection}))),transactions:Nt(()=>Promise.resolve().then(()=>require("./sections-D6R2jRAp.js")).then(e=>({default:e.TransactionsSection}))),coupons:Nt(()=>Promise.resolve().then(()=>require("./sections-D6R2jRAp.js")).then(e=>({default:e.CouponsSection}))),refunds:Nt(()=>Promise.resolve().then(()=>require("./sections-D6R2jRAp.js")).then(e=>({default:e.RefundsSection}))),storefront:Nt(()=>Promise.resolve().then(()=>Up).then(e=>({default:e.StorefrontSection}))),"ai-settings":Nt(()=>Promise.resolve().then(()=>qp).then(e=>({default:e.AISettingsSection}))),faqs:Nt(()=>Promise.resolve().then(()=>Yp).then(e=>({default:e.FAQSection}))),"payment-settings":Nt(()=>Promise.resolve().then(()=>Zp).then(e=>({default:e.PaymentSettingsSection}))),messaging:Nt(()=>Promise.resolve().then(()=>Qp).then(e=>({default:e.MessagingSection}))),settings:Nt(()=>Promise.resolve().then(()=>Mp).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,r=e.cedrosLogin;return{serverUrl:t?.serverUrl||r?.serverUrl||"",userId:r?.user?.id,getAccessToken:()=>r?.getAccessToken?.()||t?.jwtToken||null,hasPermission:o=>this.checkPermission(o,e),orgId:e.org?.orgId,pluginData:{walletAddress:t?.walletAddress}}},checkPermission(e,t){return t.org?.permissions?t.org.permissions.includes(e):!!(t.cedrosLogin?.user||t.cedrosPay?.jwtToken||t.cedrosPay?.walletAddress)},cssNamespace:"cedros-dashboard"};function pl(){const{subscriptionManager:e}=oe.useCedrosContext(),[t,r]=w.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=w.useCallback(async c=>{r(d=>({...d,status:"loading",error:null}));const l=await e.processSubscription(c);return r(d=>({...d,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l},[e]),o=w.useCallback(async c=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(c);return r(d=>({...d,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const d=l instanceof Error?l.message:"Failed to check subscription status";throw r(m=>({...m,status:"error",error:d})),l}},[e]),a=w.useCallback(async(c,l,d)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await e.requestSubscriptionQuote(c,l,d);return r(u=>({...u,status:"idle"})),m}catch(m){const u=m instanceof Error?m.message:"Failed to get subscription quote";throw r(f=>({...f,status:"error",error:u})),m}},[e]),i=w.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:s,checkStatus:o,requestQuote:a,reset:i}}function sf({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:m=!1,onAttempt:u,onSuccess:f,onError:h,className:x=""}){const{status:p,error:y,sessionId:j,processSubscription:b}=pl(),v=oe.useCedrosTheme(),{t:_,translations:C}=fe.useTranslation(),E=d||_("ui.subscribe"),S=v.unstyled?x:`${v.className} cedros-theme__stripe-button ${x}`.trim(),N=y&&typeof y!="string"?y?.code??null:null,k=y?typeof y=="string"?y:(O=>{if(!O||!C)return"";const M=C.errors[O];return M?M.action?`${M.message} ${M.action}`:M.message:""})(N):null,A=w.useCallback(async()=>{oe.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),fe.emitPaymentStart("stripe",e),u&&u("stripe"),fe.emitPaymentProcessing("stripe",e);const O=await b({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});O.success&&O.transactionId?(fe.emitPaymentSuccess("stripe",O.transactionId,e),f&&f(O.transactionId)):!O.success&&O.error&&(fe.emitPaymentError("stripe",O.error,e),h&&h(O.error))},[e,t,r,s,c,i,l,o,a,b,u,f,h]),P=w.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),D=w.useMemo(()=>fe.createDedupedClickHandler(P,A),[P,A]),z=p==="loading",L=m||z;return n.jsxs("div",{className:S,style:v.unstyled?{}:v.style,children:[n.jsx("button",{onClick:D,disabled:L,className:v.unstyled?x:"cedros-theme__button cedros-theme__stripe",type:"button",children:z?_("ui.processing"):E}),k&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__error",children:k}),j&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__success",children:_("ui.redirecting_to_checkout")})]})}function fl(){const{subscriptionManager:e,x402Manager:t,walletManager:r}=oe.useCedrosContext(),{publicKey:s,signTransaction:o}=Hn.useWallet(),[a,i]=w.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),[c,l]=w.useState(null),d=w.useCallback(()=>{if(!s){const x="Wallet not connected";return i(p=>({...p,status:"error",error:x})),{valid:!1,error:x}}if(!o){const x="Wallet does not support signing";return i(p=>({...p,status:"error",error:x})),{valid:!1,error:x}}return{valid:!0}},[s,o]),m=w.useCallback(async x=>{if(!s)return i(p=>({...p,status:"error",error:"Wallet not connected"})),null;i(p=>({...p,status:"checking",error:null}));try{const p=await e.checkSubscriptionStatus({resource:x,userId:s.toString()});return i(y=>({...y,status:p.active?"success":"idle",subscriptionStatus:p.status,expiresAt:p.expiresAt||p.currentPeriodEnd||null})),p}catch(p){const y=oe.formatError(p,"Failed to check subscription status");return i(j=>({...j,status:"error",error:y})),null}},[s,e]),u=w.useCallback(async(x,p,y)=>{i(j=>({...j,status:"loading",error:null}));try{const j=await e.requestSubscriptionQuote(x,p,y);return l(j),i(b=>({...b,status:"idle"})),j}catch(j){const b=oe.formatError(j,"Failed to get subscription quote");return i(v=>({...v,status:"error",error:b})),null}},[e]),f=w.useCallback(async(x,p,y)=>{const j=d();if(!j.valid)return{success:!1,error:j.error};i(b=>({...b,status:"loading",error:null}));try{const b=await e.requestSubscriptionQuote(x,p,y);l(b);const v=b.requirement;if(!t.validateRequirement(v))throw new Error("Invalid subscription quote received from server");const _=!!v.extra?.feePayer;let C;if(_){const{transaction:E,blockhash:S}=await t.buildGaslessTransaction({resourceId:x,userWallet:s.toString(),feePayer:v.extra.feePayer,couponCode:y?.couponCode}),N=r.deserializeTransaction(E),U=await r.partiallySignTransaction({transaction:N,signTransaction:o,blockhash:S});C=await t.submitGaslessTransaction({resource:x,partialTx:U,couponCode:y?.couponCode,resourceType:"regular",requirement:v})}else{const E=await r.buildTransaction({requirement:v,payerPublicKey:s}),S=await r.signTransaction({transaction:E,signTransaction:o}),N=r.buildPaymentPayload({requirement:v,signedTx:S,payerPublicKey:s});C=await t.submitPayment({resource:x,payload:N,couponCode:y?.couponCode,resourceType:"regular"})}if(C.success){const E=await e.checkSubscriptionStatus({resource:x,userId:s.toString()});i({status:"success",error:null,sessionId:C.transactionId||null,subscriptionStatus:E.status,expiresAt:E.expiresAt||E.currentPeriodEnd||null})}else i(E=>({...E,status:"error",error:C.error||"Subscription payment failed"}));return C}catch(b){const v=oe.formatError(b,"Subscription payment failed");return i(_=>({..._,status:"error",error:v})),{success:!1,error:v}}},[d,e,t,r,s,o]),h=w.useCallback(()=>{i({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),l(null)},[]);return{...a,quote:c,checkStatus:m,requestQuote:u,processPayment:f,reset:h}}function of({resource:e,interval:t,intervalDays:r,couponCode:s,label:o,disabled:a=!1,onAttempt:i,onSuccess:c,onError:l,className:d="",testPageUrl:m,hideMessages:u=!1,autoCheckStatus:f=!0}){const{connected:h,connecting:x,connect:p,disconnect:y,select:j,wallets:b,wallet:v,publicKey:_}=Hn.useWallet(),{status:C,error:E,subscriptionStatus:S,expiresAt:N,checkStatus:U,processPayment:k}=fl(),A=oe.useCedrosTheme(),{solanaError:P}=oe.useCedrosContext(),{t:D,translations:z}=fe.useTranslation(),L=o||D("ui.subscribe_with_crypto"),O=w.useRef(k),M=w.useRef(U);w.useEffect(()=>{O.current=k,M.current=U},[k,U]);const R=E&&typeof E!="string"?E?.code??null:null,W=P&&typeof P!="string"?P?.code??null:null,T=de=>{if(!de||!z)return"";const ke=z.errors[de];return ke?ke.action?`${ke.message} ${ke.action}`:ke.message:""},V=E?typeof E=="string"?E:T(R):null,ee=P?typeof P=="string"?P:T(W):null,B=w.useMemo(()=>b.map(de=>`${de.adapter.name}-${de.readyState}`).join(","),[b]),Y=w.useMemo(()=>b.filter(({readyState:de})=>de===wi.WalletReadyState.Installed||de===wi.WalletReadyState.Loadable),[B]);w.useEffect(()=>{f&&h&&_&&(oe.getLogger().debug("[CryptoSubscribeButton] Auto-checking subscription status"),M.current(e))},[f,h,_,e]),w.useEffect(()=>{C==="success"&&S==="active"&&(fe.emitPaymentSuccess("crypto","subscription-active",e),c&&c("subscription-active"))},[C,S,e,c]),w.useEffect(()=>{C==="error"&&E&&(fe.emitPaymentError("crypto",E,e),l&&l(E))},[C,E,e,l]);const J=typeof window<"u"&&window.top!==window.self,[ge,F]=w.useState(!1),[K,me]=w.useState(!1),[q,te]=w.useState(!1),ce=P;w.useEffect(()=>{let de=!1;return de||(async()=>{if(K&&v&&!h&&!x){oe.getLogger().debug("[CryptoSubscribeButton] Wallet detected, attempting auto-connect:",v.adapter.name),me(!1),fe.emitWalletConnect(v.adapter.name);try{await p(),de||oe.getLogger().debug("[CryptoSubscribeButton] Auto-connect successful")}catch($){if(!de){oe.getLogger().error("[CryptoSubscribeButton] Auto-connect failed:",$);const X=$ instanceof Error?$.message:"Failed to connect wallet";fe.emitWalletError(X,v.adapter.name),te(!1)}}}})(),()=>{de=!0}},[v,K,h,x,p]),w.useEffect(()=>{h&&q&&_&&v&&(fe.emitWalletConnected(v.adapter.name,_.toString()),oe.getLogger().debug("[CryptoSubscribeButton] Processing pending subscription payment"),te(!1),F(!1),fe.emitPaymentProcessing("crypto",e),O.current(e,t,{couponCode:s,intervalDays:r}))},[h,q,_,v,e,t,s,r]);const pe=w.useCallback(async()=>{if(oe.getLogger().debug("[CryptoSubscribeButton] executeSubscriptionFlow called",{connected:h,wallet:v?.adapter.name,resource:e,interval:t}),fe.emitPaymentStart("crypto",e),i&&i("crypto"),ce){oe.getLogger().error("[CryptoSubscribeButton] Solana dependencies missing:",ce),fe.emitPaymentError("crypto",ce,e),l&&l(ce);return}if(J){const de=m||window.location.href;try{if(new URL(de,window.location.origin).origin!==window.location.origin)throw oe.getLogger().error("[CryptoSubscribeButton] Blocked attempt to open external URL:",de),new Error("Cannot open external URLs from embedded context");window.open(de,"_blank","noopener,noreferrer")}catch(ke){throw oe.getLogger().error("[CryptoSubscribeButton] URL validation failed:",ke),ke}return}if(h)fe.emitPaymentProcessing("crypto",e),await k(e,t,{couponCode:s,intervalDays:r});else{te(!0);try{if(v)oe.getLogger().debug("[CryptoSubscribeButton] Wallet already selected, connecting:",v.adapter.name),fe.emitWalletConnect(v.adapter.name),await p();else{if(oe.getLogger().debug("[CryptoSubscribeButton] No wallet selected, showing selector"),Y.length===0){te(!1);const de="No wallets available";throw fe.emitWalletError(de),new Error(de)}F(!0)}}catch(de){te(!1);const ke=de instanceof Error?de.message:"Failed to connect wallet";oe.getLogger().error("[CryptoSubscribeButton] Connection error:",ke),fe.emitWalletError(ke,v?.adapter.name)}}},[h,v,e,t,s,r,J,m,Y,p,k,ce,i,l]),Oe=w.useMemo(()=>`crypto-subscribe-${e}-${t}`,[e,t]),Ge=w.useMemo(()=>fe.createDedupedClickHandler(Oe,pe,{cooldownMs:200,deduplicationWindowMs:0}),[Oe,pe]),Qe=C==="loading"||C==="checking",$e=S==="active"||S==="trialing",Ye=a||Qe||x||!!ce||$e;let Ne=L;if(Qe)Ne=D("ui.processing");else if($e&&N){const de=new Date(N).toLocaleDateString();Ne=`${D("ui.subscribed_until")} ${de}`}else $e&&(Ne=D("ui.subscribed"));const st=w.useCallback(async()=>{try{me(!1),h&&await y(),j(null),F(!0)}catch(de){oe.getLogger().error("Failed to change wallet:",de)}},[h,y,j]),Ae=w.useCallback(de=>{oe.getLogger().debug("[CryptoSubscribeButton] Wallet clicked:",de),F(!1),j(de),me(!0)},[j]),Fe=w.useCallback(async()=>{try{if(await y(),te(!1),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(de){de instanceof Error&&de.name==="QuotaExceededError"?oe.getLogger().warn("localStorage quota exceeded when removing wallet preference"):oe.getLogger().error("Failed to clear wallet preference from localStorage:",de)}}catch(de){oe.getLogger().error("Failed to disconnect wallet:",de)}},[y]);return n.jsxs("div",{className:A.unstyled?d:`${A.className} cedros-theme__crypto-button ${d||""}`,style:A.unstyled?{}:A.style,children:[n.jsx("button",{onClick:Ge,disabled:Ye,className:A.unstyled?d:"cedros-theme__button cedros-theme__crypto",type:"button",children:Ne}),ge&&!u&&n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:A.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>F(!1),children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:A.tokens.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${A.tokens.modalBorder}`},onClick:de=>de.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:A.tokens.surfaceText},children:D("wallet.select_wallet")}),n.jsx("button",{onClick:()=>F(!1),style:fe.getModalCloseButtonStyles(A.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:Y.map(de=>n.jsxs("button",{onClick:()=>Ae(de.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:A.tokens.surfaceBackground,border:`1px solid ${A.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:A.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:ke=>{ke.currentTarget.style.backgroundColor=A.tokens.modalBackground,ke.currentTarget.style.borderColor=A.tokens.surfaceText,ke.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:ke=>{ke.currentTarget.style.backgroundColor=A.tokens.surfaceBackground,ke.currentTarget.style.borderColor=A.tokens.surfaceBorder,ke.currentTarget.style.transform="translateY(0)"},type:"button",children:[n.jsx(hp.WalletIcon,{wallet:de,style:{width:"24px",height:"24px"}}),n.jsx("span",{style:{fontWeight:500},children:de.adapter.name})]},de.adapter.name))})]})}),h&&!u&&!ge&&n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:A.tokens.surfaceText,opacity:.7},children:[n.jsx("button",{onClick:st,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:D("wallet.change")}),n.jsx("button",{onClick:Fe,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:D("ui.disconnect")})]}),!u&&ee&&n.jsx("div",{className:A.unstyled?"":"cedros-theme__error",children:ee}),!u&&V&&n.jsx("div",{className:A.unstyled?"":"cedros-theme__error",children:V}),!u&&$e&&n.jsx("div",{className:A.unstyled?"":"cedros-theme__success",children:D("ui.subscription_active")})]})}function hl(){const{subscriptionManager:e,creditsManager:t}=oe.useCedrosContext(),[r,s]=w.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=w.useCallback(async(l,d)=>{s(m=>({...m,status:"checking",error:null}));try{const m=await e.checkSubscriptionStatus({resource:l,userId:d});return s(u=>({...u,status:m.active?"success":"idle",subscriptionStatus:m.status,expiresAt:m.expiresAt||m.currentPeriodEnd||null})),m}catch(m){const u=oe.formatError(m,"Failed to check subscription status");return s(f=>({...f,status:"error",error:u})),null}},[e]),a=w.useCallback(async(l,d,m)=>{s(u=>({...u,status:"loading",error:null}));try{const u=await t.requestQuote(l,m?.couponCode);return s(f=>({...f,status:"idle",creditsRequirement:u})),u}catch(u){const f=oe.formatError(u,"Failed to get subscription quote");return s(h=>({...h,status:"error",error:f})),null}},[t]),i=w.useCallback(async(l,d,m,u)=>{if(!m){const f="Authentication required for credits payment";return s(h=>({...h,status:"error",error:f})),{success:!1,error:f}}s(f=>({...f,status:"loading",error:null}));try{const f=await t.processPayment(l,m,u?.couponCode,{interval:d,...u?.intervalDays&&{intervalDays:String(u.intervalDays)}});return f.success?s({status:"success",error:null,sessionId:f.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(h=>({...h,status:"error",error:f.error||"Credits subscription payment failed"})),f}catch(f){const h=oe.formatError(f,"Credits subscription payment failed");return s(x=>({...x,status:"error",error:h})),{success:!1,error:h}}},[t]),c=w.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:o,requestQuote:a,processPayment:i,reset:c}}function af({resource:e,interval:t,intervalDays:r,authToken:s,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:m,className:u="",hideMessages:f=!1,autoCheckStatus:h=!1}){const{status:x,error:p,subscriptionStatus:y,expiresAt:j,checkStatus:b,processPayment:v}=hl(),_=oe.useCedrosTheme(),{t:C,translations:E}=fe.useTranslation(),S=w.useRef(b);w.useEffect(()=>{S.current=b},[b]),w.useEffect(()=>{h&&o&&(oe.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),S.current(e,o))},[h,o,e]);const N=i||C("ui.subscribe_with_credits")||"Subscribe with Credits",U=p&&typeof p!="string"?p?.code??null:null,A=p?typeof p=="string"?p:(T=>{if(!T||!E)return"";const V=E.errors[T];return V?V.action?`${V.message} ${V.action}`:V.message:""})(U):null,P=w.useCallback(async()=>{if(oe.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),fe.emitPaymentStart("credits",e),l&&l("credits"),!s){const V="Authentication required: please log in to subscribe with credits";oe.getLogger().error("[CreditsSubscribeButton]",V),fe.emitPaymentError("credits",V,e),m&&m(V);return}fe.emitPaymentProcessing("credits",e);const T=await v(e,t,s,{couponCode:a,intervalDays:r});T.success&&T.transactionId?(fe.emitPaymentSuccess("credits",T.transactionId,e),d&&d(T.transactionId)):!T.success&&T.error&&(fe.emitPaymentError("credits",T.error,e),m&&m(T.error))},[e,t,r,s,a,v,l,d,m]),D=w.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),z=w.useMemo(()=>fe.createDedupedClickHandler(D,P,{cooldownMs:200,deduplicationWindowMs:0}),[D,P]),L=x==="loading"||x==="checking",O=y==="active"||y==="trialing",M=c||L||O;let R=N;if(L)R=C("ui.processing");else if(O&&j){const T=new Date(j).toLocaleDateString();R=`${C("ui.subscribed_until")} ${T}`}else O&&(R=C("ui.subscribed"));const W=_.unstyled?u:`${_.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:W,style:_.unstyled?{}:_.style,children:[n.jsx("button",{onClick:z,disabled:M,className:_.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:R}),!f&&A&&n.jsx("div",{className:_.unstyled?"":"cedros-theme__error",children:A}),!f&&O&&n.jsx("div",{className:_.unstyled?"":"cedros-theme__success",children:C("ui.subscription_active")})]})}function gl(){const{subscriptionChangeManager:e}=oe.useCedrosContext(),[t,r]=w.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=w.useRef(t);s.current=t;const o=w.useCallback(async(u,f)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,f);return r(x=>({...x,status:"success",subscription:h,userId:f})),h}catch(h){const x=h instanceof Error?h.message:"Failed to load subscription";return r(p=>({...p,status:"error",error:x})),null}},[e]),a=w.useCallback(async(u,f,h,x)=>{r(p=>({...p,status:"loading",error:null}));try{const p={currentResource:u,newResource:f,userId:h,newInterval:x},y=await e.previewChange(p);return r(j=>({...j,status:"idle",changePreview:y})),y}catch(p){const y=p instanceof Error?p.message:"Failed to preview change";return r(j=>({...j,status:"error",error:y})),null}},[e]),i=w.useCallback(async u=>{const{subscription:f,userId:h}=s.current;if(!f||!h)return r(x=>({...x,status:"error",error:"No subscription loaded"})),null;r(x=>({...x,status:"loading",error:null}));try{const x={currentResource:f.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},p=await e.changeSubscription(x);return p.success?r(y=>({...y,status:"success",subscription:y.subscription?{...y.subscription,resource:p.newResource,interval:p.newInterval,status:p.status}:null,changePreview:null})):r(y=>({...y,status:"error",error:p.error||"Failed to change subscription"})),p}catch(x){const p=x instanceof Error?x.message:"Failed to change subscription";return r(y=>({...y,status:"error",error:p})),null}},[e]),c=w.useCallback(async u=>{const{subscription:f,userId:h}=s.current;if(!f||!h)return r(x=>({...x,status:"error",error:"No subscription loaded"})),null;r(x=>({...x,status:"loading",error:null}));try{const x={resource:f.resource,userId:h,immediate:u},p=await e.cancel(x);if(p.success){const y=u?"canceled":f.status;r(j=>({...j,status:"success",subscription:j.subscription?{...j.subscription,status:y,cancelAtPeriodEnd:!u}:null}))}else r(y=>({...y,status:"error",error:p.error||"Failed to cancel subscription"}));return p}catch(x){const p=x instanceof Error?x.message:"Failed to cancel subscription";return r(y=>({...y,status:"error",error:p})),null}},[e]),l=w.useCallback(async(u,f)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:f});return window.location.href=h.url,h}catch(h){const x=h instanceof Error?h.message:"Failed to open billing portal";return r(p=>({...p,status:"error",error:x})),null}},[e]),d=w.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=w.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:o,previewChange:a,changeSubscription:i,cancelSubscription:c,openBillingPortal:l,clearPreview:d,reset:m}}const cf={bg:"#fff",bgMuted:"#f9fafb",bgHighlight:"#eff6ff",text:"#111827",textMuted:"#6b7280",textFaint:"#9ca3af",border:"#e5e7eb",borderLight:"#f3f4f6",primary:"#3b82f6",error:"#ef4444",errorBg:"#fef2f2",errorBorder:"#fecaca",warningBg:"#fef3c7",warningBorder:"#fcd34d",warningText:"#92400e",buttonBg:"#f3f4f6",buttonBorder:"#d1d5db",buttonText:"#374151"},lf={bg:"#1e293b",bgMuted:"#334155",bgHighlight:"rgba(59, 130, 246, 0.15)",text:"#f1f5f9",textMuted:"#94a3b8",textFaint:"#64748b",border:"#475569",borderLight:"#334155",primary:"#3b82f6",error:"#ef4444",errorBg:"rgba(239, 68, 68, 0.15)",errorBorder:"rgba(239, 68, 68, 0.3)",warningBg:"rgba(245, 158, 11, 0.15)",warningBorder:"rgba(245, 158, 11, 0.3)",warningText:"#fbbf24",buttonBg:"#334155",buttonBorder:"#475569",buttonText:"#e2e8f0"};function df(e){const t=e?lf:cf;return{container:{padding:"24px",backgroundColor:t.bg,borderRadius:"8px",border:`1px solid ${t.border}`,fontFamily:"system-ui, -apple-system, sans-serif",color:t.text},error:{padding:"12px 16px",backgroundColor:t.errorBg,border:`1px solid ${t.errorBorder}`,borderRadius:"6px",color:t.error,marginBottom:"16px"},loading:{padding:"24px",textAlign:"center",color:t.textMuted},details:{marginBottom:"24px"},title:{margin:"0 0 16px 0",fontSize:"18px",fontWeight:600,color:t.text},detailRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 0",borderBottom:`1px solid ${t.borderLight}`},label:{color:t.textMuted,fontSize:"14px"},value:{color:t.text,fontSize:"14px",fontWeight:500},statusBadge:{padding:"4px 8px",borderRadius:"4px",color:"#fff",fontSize:"12px",fontWeight:500,textTransform:"capitalize"},cancelNotice:{marginTop:"12px",padding:"8px 12px",backgroundColor:t.warningBg,border:`1px solid ${t.warningBorder}`,borderRadius:"6px",color:t.warningText,fontSize:"13px"},prorationPreview:{padding:"16px",backgroundColor:t.bgMuted,borderRadius:"8px",marginBottom:"24px"},previewTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},previewDetails:{marginBottom:"16px"},previewRow:{display:"flex",justifyContent:"space-between",padding:"6px 0",fontSize:"14px",color:t.textMuted},previewTotal:{borderTop:`1px solid ${t.border}`,marginTop:"8px",paddingTop:"12px",fontWeight:600,color:t.text},previewActions:{display:"flex",gap:"12px",justifyContent:"flex-end"},cancelButton:{padding:"8px 16px",backgroundColor:t.bg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px"},confirmButton:{padding:"8px 16px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},plansSection:{marginBottom:"24px"},plansTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},plansList:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"16px"},planCard:{padding:"16px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"8px",textAlign:"center"},currentPlan:{borderColor:t.primary,backgroundColor:t.bgHighlight},planName:{fontSize:"16px",fontWeight:600,color:t.text,marginBottom:"4px"},planPrice:{fontSize:"14px",color:t.textMuted,marginBottom:"8px"},planDescription:{fontSize:"12px",color:t.textFaint,marginBottom:"12px"},currentBadge:{display:"inline-block",padding:"4px 8px",backgroundColor:t.primary,color:"#fff",borderRadius:"4px",fontSize:"12px",fontWeight:500},changePlanButton:{padding:"8px 16px",backgroundColor:t.buttonBg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px",width:"100%"},actions:{display:"flex",gap:"12px",justifyContent:"flex-end",paddingTop:"16px",borderTop:`1px solid ${t.border}`},portalButton:{padding:"10px 20px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},cancelSubscriptionButton:{padding:"10px 20px",backgroundColor:t.bg,border:`1px solid ${t.error}`,borderRadius:"6px",color:t.error,cursor:"pointer",fontSize:"14px"}}}function vn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function xl(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function uf(e){switch(e){case"active":return"#22c55e";case"trialing":return"#3b82f6";case"past_due":return"#f59e0b";case"canceled":case"expired":return"#ef4444";default:return"#6b7280"}}function mf({preview:e,onConfirm:t,onCancel:r,isLoading:s,styles:o}){const a=e.immediateAmount<0;return n.jsxs("div",{className:"cedros-proration-preview",style:o.prorationPreview,children:[n.jsx("h4",{style:o.previewTitle,children:"Change Preview"}),n.jsxs("div",{style:o.previewDetails,children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Current plan:"}),n.jsxs("span",{children:[vn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[vn(e.newPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Days remaining:"}),n.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Unused credit:"}),n.jsxs("span",{children:["-",vn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:vn(e.prorationDetails.newPlanCost,e.currency)})]})]}),n.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[n.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),n.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:vn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:xl(e.effectiveDate)})]})]}),n.jsxs("div",{style:o.previewActions,children:[n.jsx("button",{onClick:r,style:o.cancelButton,disabled:s,children:"Cancel"}),n.jsx("button",{onClick:t,style:o.confirmButton,disabled:s,children:s?"Processing...":"Confirm Change"})]})]})}function pf({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=oe.useCedrosTheme(),m=w.useMemo(()=>df(d==="dark"),[d]),{subscription:u,changePreview:f,status:h,error:x,loadSubscription:p,previewChange:y,changeSubscription:j,cancelSubscription:b,openBillingPortal:v,clearPreview:_}=gl();w.useEffect(()=>{p(e,t)},[e,t,p]);const C=w.useCallback(async(k,A)=>{await y(e,k,t,A)},[e,t,y]),E=w.useCallback(async()=>{if(!f)return;const k=r.find(P=>P.price===f.newPlanPrice&&P.currency===f.currency);(await j({newResource:k?.resource||e,newInterval:k?.interval,immediate:!0}))?.success&&k&&s?.(k.resource,k.interval)},[f,r,e,j,s]),S=w.useCallback(async k=>{(await b(k))?.success&&o?.()},[b,o]),N=w.useCallback(()=>{v(t,a)},[t,a,v]),U=h==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[x&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:x}),U&&!u&&n.jsx("div",{className:"cedros-subscription-loading",style:m.loading,children:"Loading subscription..."}),u&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"cedros-subscription-details",style:m.details,children:[n.jsx("h3",{style:m.title,children:"Current Subscription"}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Plan:"}),n.jsx("span",{style:m.value,children:u.resource})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Status:"}),n.jsx("span",{style:{...m.statusBadge,backgroundColor:uf(u.status)},children:u.status})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Price:"}),n.jsxs("span",{style:m.value,children:[vn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Current period ends:"}),n.jsx("span",{style:m.value,children:xl(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),f&&n.jsx(mf,{preview:f,onConfirm:E,onCancel:_,isLoading:U,styles:m}),r.length>0&&!f&&n.jsxs("div",{className:"cedros-available-plans",style:m.plansSection,children:[n.jsx("h4",{style:m.plansTitle,children:"Available Plans"}),n.jsx("div",{style:m.plansList,children:r.map(k=>{const A=k.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...A?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:k.name}),n.jsxs("div",{style:m.planPrice,children:[vn(k.price,k.currency),"/",k.interval]}),k.description&&n.jsx("div",{style:m.planDescription,children:k.description}),A?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>C(k.resource,k.interval),style:m.changePlanButton,disabled:U,children:k.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},k.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:N,style:m.portalButton,disabled:U,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>S(!1),style:m.cancelSubscriptionButton,disabled:U,children:"Cancel Subscription"})]})]})]})}function ff(){const{x402Manager:e,walletManager:t}=oe.useCedrosContext(),{publicKey:r,signTransaction:s}=Hn.useWallet(),[o,a]=w.useState({status:"idle",error:null,transactionId:null}),[i,c]=w.useState(null),[l,d]=w.useState(null),m=w.useCallback(async x=>{try{a(y=>({...y,status:"loading"}));const p=await e.requestQuote({resource:x});if(!e.validateRequirement(p))throw new Error("Invalid refund requirement received from server");return c(p),a(y=>({...y,status:"idle"})),p}catch(p){const y=oe.formatError(p,"Failed to fetch refund requirement");throw a({status:"error",error:y,transactionId:null}),p}},[e]),u=w.useCallback(async(x,p)=>{if(!r||!s)throw new Error("Wallet not connected");try{a({status:"loading",error:null,transactionId:null});const y=await e.requestQuote({resource:x,couponCode:p});if(!e.validateRequirement(y))throw new Error("Invalid refund requirement received");c(y);const j=await t.buildTransaction({requirement:y,payerPublicKey:r}),b=await t.signTransaction({transaction:j,signTransaction:s}),v=t.buildPaymentPayload({requirement:y,signedTx:b,payerPublicKey:r}),_=await e.submitPayment({resource:x,payload:v,couponCode:p,metadata:void 0,resourceType:"refund"});return _.settlement&&d(_.settlement),a({status:"success",error:null,transactionId:_.transactionId||b.signature}),_}catch(y){const j=oe.formatError(y,"Refund payment failed");throw a({status:"error",error:j,transactionId:null}),y}},[r,s,e,t]),f=w.useCallback(async x=>{if(!r||!s)throw new Error("Wallet not connected");try{a({status:"loading",error:null,transactionId:null});const p=await e.requestQuote({resource:x});if(!e.validateRequirement(p))throw new Error("Invalid refund requirement received");c(p);const{transaction:y}=await e.buildGaslessTransaction({resourceId:x,userWallet:r.toString(),feePayer:p.extra.feePayer}),j=t.deserializeTransaction(y),b=await t.partiallySignTransaction({transaction:j,signTransaction:s}),v=await e.submitGaslessTransaction({resource:x,partialTx:b,couponCode:void 0,metadata:void 0,resourceType:"refund",requirement:p});return v.settlement&&d(v.settlement),a({status:"success",error:null,transactionId:v.transactionId||"gasless-refund-tx"}),v}catch(p){const y=oe.formatError(p,"Gasless refund payment failed");throw a({status:"error",error:y,transactionId:null}),p}},[r,s,e,t]),h=w.useCallback(()=>{a({status:"idle",error:null,transactionId:null}),c(null),d(null)},[]);return{state:o,requirement:i,settlement:l,fetchRefundQuote:m,processRefund:u,processGaslessRefund:f,reset:h}}function hf(){if(typeof window>"u")return{passed:!0,severity:"info",message:"HTTPS check skipped (SSR environment)"};const e=window.location.protocol==="https:",t=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";return e||t?{passed:!0,severity:"info",message:"HTTPS enforced"}:{passed:!1,severity:"error",message:"Page not served over HTTPS",recommendation:"Enable HTTPS for all payment pages. Stripe.js requires HTTPS in production."}}function gf(){return typeof document>"u"?{passed:!0,severity:"info",message:"CSP check skipped (SSR environment)"}:document.querySelector('meta[http-equiv="Content-Security-Policy"]')?{passed:!0,severity:"info",message:"Content Security Policy detected"}:{passed:!1,severity:"warning",message:"No Content Security Policy detected",recommendation:"Configure CSP headers to protect against XSS and CDN compromise. Use generateCSP() helper from @cedros/pay-react."}}function xf(){return process.env.NODE_ENV==="development"||typeof window<"u"&&window.location.hostname==="localhost"?{passed:!0,severity:"info",message:"Running in development mode (some security checks relaxed)"}:{passed:!0,severity:"info",message:"Running in production mode"}}function yf(){return{passed:!0,severity:"info",message:"Stripe.js loaded via @stripe/stripe-js package (CSP recommended, not SRI)",recommendation:"Ensure CSP script-src includes https://js.stripe.com"}}function bf(){return typeof window>"u"?{passed:!0,severity:"info",message:"Mixed content check skipped (SSR environment)"}:window.location.protocol==="https:"?{passed:!0,severity:"info",message:"Mixed content protection active (HTTPS page)"}:{passed:!0,severity:"info",message:"Mixed content check skipped (HTTP page)"}}function vf(){const e=[hf(),gf(),xf(),yf(),bf()],t=e.some(a=>a.severity==="error"&&!a.passed),r=e.some(a=>a.severity==="warning"&&!a.passed);let s,o;return t?(s="vulnerable",o="Security issues detected. Review errors and apply recommendations."):r?(s="warnings",o="Minor security warnings detected. Consider applying recommendations."):(s="secure",o="All security checks passed."),{checks:e,overallStatus:s,summary:o}}function wf(e){process.env.NODE_ENV!=="production"&&(console.group("🔒 Cedros Pay Security Report"),console.log(`Status: ${e.overallStatus.toUpperCase()}`),console.log(`Summary: ${e.summary}`),console.log(""),e.checks.forEach(t=>{const r=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${r} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const _f={CSP:"Use generateCSP() from @cedros/pay-react to generate Content Security Policy headers",HTTPS:"Always serve payment pages over HTTPS in production",PACKAGE_UPDATES:"Keep @stripe/stripe-js and @cedros/pay-react updated for security patches",AUDIT:"Run npm audit regularly to check for known vulnerabilities",MONITORING:"Monitor Stripe security advisories and apply updates promptly",NO_SRI:"Do NOT use SRI hashes for Stripe.js - use CSP instead"},la=w.createContext(null);function De(){const e=w.useContext(la);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function da(){return w.useContext(la)}function jf({config:e,children:t}){return n.jsx(la.Provider,{value:{config:e},children:t})}function At(e){return new Promise(t=>setTimeout(t,e))}const yl=[{id:"cat_all",slug:"all",name:"All Products",description:"Everything in the catalog."},{id:"cat_apparel",slug:"apparel",name:"Apparel",description:"Soft goods and daily wear."},{id:"cat_accessories",slug:"accessories",name:"Accessories",description:"Carry, attach, decorate."}],ts=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];let co=[];const Rr={};function Sf(e,t){let r=e;if(t.category&&t.category!=="all"){const l=yl.find(d=>d.slug===t.category||d.id===t.category);l&&(r=r.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();r=r.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const s=t.filters??{},o=s.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));r=r.filter(d=>d.tags?.some(m=>l.has(m)))}const a=typeof s.priceMin=="number"?s.priceMin:void 0,i=typeof s.priceMax=="number"?s.priceMax:void 0;return typeof a=="number"&&(r=r.filter(l=>l.price>=a)),typeof i=="number"&&(r=r.filter(l=>l.price<=i)),(typeof s.inStock=="boolean"?s.inStock:void 0)===!0&&(r=r.filter(l=>l.inventoryStatus!=="out_of_stock")),r}function kf(e,t){if(!t||t==="featured")return e;const r=[...e];return t==="price_asc"&&r.sort((s,o)=>s.price-o.price),t==="price_desc"&&r.sort((s,o)=>o.price-s.price),r}function Cf(e,t,r){const s=(t-1)*r;return{items:e.slice(s,s+r),page:t,pageSize:r,total:e.length,hasNextPage:s+r<e.length}}function Nf(e){const t=new Date().toISOString(),r=e.cart.map(o=>{const a=ts.find(i=>i.id===o.resource||i.slug===o.resource)??ts[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),s=r.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:s,currency:e.options.currency,items:r,receiptUrl:e.options.successUrl}}function Af(){return{async listProducts(e){await At(150);const t=e.page??1,r=e.pageSize??24,s=Sf(ts,e),o=kf(s,e.sort);return Cf(o,t,r)},async getProductBySlug(e){return await At(100),ts.find(t=>t.slug===e)??null},async listCategories(){return await At(80),yl},async getOrderHistory(){return await At(120),co},async getCart({customerId:e}){return await At(80),Rr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await At(120);const r=Rr[e]??{items:[]},s=new Map,o=i=>{const c=`${i.productId}::${i.variantId??""}`,l=s.get(c);l?s.set(c,{...l,qty:l.qty+i.qty}):s.set(c,i)};for(const i of r.items)o(i);for(const i of t.items)o(i);const a={items:Array.from(s.values()),promoCode:t.promoCode??r.promoCode};return Rr[e]=a,a},async updateCart({customerId:e,cart:t}){await At(60),Rr[e]=t},async createCheckoutSession(e){await At(250);const t=Nf(e);if(co=[t,...co].slice(0,25),e.options.successUrl){const r=new URL(e.options.successUrl,"http://localhost");return r.searchParams.set("demoOrderId",t.id),{kind:"redirect",url:r.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:t.id}}},async listSubscriptionTiers(){return await At(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await At(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await At(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function bl(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Pf(e){return e?e.toUpperCase():"USD"}function Tf(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function Ef(e){if(e&&(e==="physical"||e==="digital"))return e}function If(e){const t=[];if(Array.isArray(e))for(const r of e)typeof r=="string"&&t.push(r);else if(typeof e=="string"){const r=e.trim();if(r.startsWith("["))try{const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(r=>r.split(",")).map(r=>r.trim().toUpperCase()).filter(Boolean)}function Or(e){const t=Pf(e.fiatCurrency),r=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],s=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=If(a);return{id:e.id,slug:e.slug??e.id,title:e.title??bl(e.id),description:e.description??"",images:r,price:s/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:Tf(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:Ef(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function lo(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],r=e.total??e.count;return{products:t,total:r}}async function Xt(e,t,r){const s={};r&&(s["X-API-Key"]=r);const o=await fetch(`${e}${t}`,{headers:s});if(!o.ok){const a=await o.text().catch(()=>""),i=new Error(`Request failed (${o.status}): ${a}`);throw i.status=o.status,i}return o.json()}function Rf(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,f=(d-1)*m,h=new URLSearchParams;h.set("limit",String(u)),h.set("offset",String(f)),l.search&&h.set("search",l.search),l.category&&h.set("category",l.category),l.sort&&h.set("sort",l.sort),l.filters?.inStock&&h.set("in_stock","true"),l.filters?.minPrice!=null&&h.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&h.set("max_price",String(l.filters.maxPrice));const x=l.filters?.tags,p=Array.isArray(x)?x:typeof x=="string"?[x]:[];p.length&&h.set("tags",p.join(","));const y=await Xt(e.serverUrl,`/paywall/v1/products?${h.toString()}`,e.apiKey),{products:j,total:b}=lo(y);return{items:j.map(Or),page:d,pageSize:m,total:b,hasNextPage:typeof b=="number"?f+u<b:j.length===u}},getProductBySlug:async l=>{try{const d=await Xt(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(l)}`,e.apiKey);return Or(d)}catch(d){const m=d?.status;if(m!==404&&m!==405)throw d;try{const u=await Xt(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(l)}`,e.apiKey);return Or(u)}catch(u){const f=u?.status;if(f!==404&&f!==405)throw u;const h=await Xt(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:x}=lo(h),p=x.find(y=>y.slug===l||y.id===l);return p?Or(p):null}}},listCategories:async()=>{const l=await Xt(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=lo(l),m=new Set;for(const u of d)for(const f of u.categoryIds??[])m.add(f);return Array.from(m).map(u=>({id:u,slug:u,name:bl(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await Xt(e.serverUrl,"/admin/config/storefront",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([Xt(e.serverUrl,"/admin/config/stripe",e.apiKey),Xt(e.serverUrl,"/admin/config/x402",e.apiKey),Xt(e.serverUrl,"/admin/config/cedros_login",e.apiKey)]),u=l.status==="fulfilled"?!!l.value?.config?.enabled:!1,f=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:f,credits:h}}catch{return null}},getAIRelatedProducts:async l=>{const d={"Content-Type":"application/json"};e.apiKey&&(d["X-API-Key"]=e.apiKey);const m=await fetch(`${e.serverUrl}/admin/ai/related-products`,{method:"POST",headers:d,body:JSON.stringify(l)});if(!m.ok){const u=await m.text().catch(()=>"");throw new Error(`AI related products request failed (${m.status}): ${u}`)}return m.json()}}}function Of(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function yn(e){return`${e.productId}::${e.variantId??""}`}const Mf={items:[]};function Df(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const r=Math.max(1,Math.floor(t.qty??1)),s=yn(t.item);return e.items.find(a=>yn(a)===s)?{...e,items:e.items.map(a=>yn(a)===s?{...a,qty:a.qty+r}:a)}:{...e,items:[...e.items,{...t.item,qty:r}]}}case"cart/remove":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(s=>yn(s)!==r)}}case"cart/setQty":{const r=Math.max(0,Math.floor(t.qty)),s=`${t.productId}::${t.variantId??""}`;return r===0?{...e,items:e.items.filter(o=>yn(o)!==s)}:{...e,items:e.items.map(o=>yn(o)===s?{...o,qty:r}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(s=>yn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return Of(t)}}function Lf(e){return e.reduce((t,r)=>t+r.qty,0)}function $f(e){return e.reduce((t,r)=>t+r.qty*r.unitPrice,0)}function Pi(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function zf(e,t){try{const r=e.getItem(t);return r?JSON.parse(r):null}catch{return null}}function Ff(e,t,r){try{e.setItem(t,JSON.stringify(r))}catch{}}const vl=w.createContext(null);function Mt(){const e=w.useContext(vl);if(!e)throw new Error("useCart must be used within CartProvider");return e}function Bf({children:e}){const{config:t}=De(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=w.useReducer(Df,Mf),[d,m]=w.useState(!1),u=w.useRef(!1),f=w.useRef(null);w.useEffect(()=>{const y=Pi();if(!y)return;const j=zf(y,r);j&&Array.isArray(j.items)&&l({type:"cart/hydrate",state:j}),m(!0)},[r]),w.useEffect(()=>{const y=Pi();y&&Ff(y,r,c)},[c,r]),w.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const y=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});y&&Array.isArray(y.items)&&(l({type:"cart/hydrate",state:y}),f.current=JSON.stringify(y))}catch{}})()))},[t.adapter,s,d,o,c]),w.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const y=JSON.stringify(c);if(f.current===y)return;const j=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{f.current=y}).catch(()=>{})},a);return()=>window.clearTimeout(j)},[t.adapter,s,d,o,c,a]);const h=w.useCallback((y,j)=>{const b=c.items.find(v=>v.productId===y&&v.variantId===j);if(b)return{holdId:b.holdId,expiresAt:b.holdExpiresAt}},[c.items]),x=w.useCallback((y,j,b)=>{l({type:"cart/updateHold",productId:y,variantId:j,holdExpiresAt:b})},[]),p=w.useMemo(()=>{const y=Lf(c.items),j=$f(c.items);return{items:c.items,promoCode:c.promoCode,count:y,subtotal:j,addItem:(b,v)=>l({type:"cart/add",item:b,qty:v}),removeItem:(b,v)=>l({type:"cart/remove",productId:b,variantId:v}),setQty:(b,v,_)=>l({type:"cart/setQty",productId:b,variantId:v,qty:_}),clear:()=>l({type:"cart/clear"}),setPromoCode:b=>l({type:"cart/setPromoCode",promoCode:b}),holdsSupported:i,getItemHold:h,updateItemHold:x}},[c.items,c.promoCode,i,h,x]);return n.jsx(vl.Provider,{value:p,children:e})}function Z(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const f=m[u];f in c||(c[f]=d[f].bind(c))}}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=r?.Parent?new a:this;s(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Un extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class wl extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const _l={};function _n(e){return _l}function jl(e){const t=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,o])=>t.indexOf(+s)===-1).map(([s,o])=>o)}function Do(e,t){return typeof t=="bigint"?t.toString():t}function ua(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ma(e){return e==null}function pa(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Uf(e,t){const r=(e.toString().split(".")[1]||"").length,s=t.toString();let o=(s.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(s)){const l=s.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=r>o?r:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const Ti=Symbol("evaluating");function Ce(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==Ti)return s===void 0&&(s=Ti,s=r()),s},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function An(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function un(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}function Ei(e){return JSON.stringify(e)}function Wf(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Sl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Vf=ua(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function yr(e){if(ns(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(ns(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function kl(e){return yr(e)?{...e}:Array.isArray(e)?[...e]:e}const Hf=new Set(["string","number","symbol"]);function bs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function ue(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function qf(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Zf={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Gf(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=un(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return An(this,"shape",i),i},checks:[]});return mn(e,a)}function Qf(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=un(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return An(this,"shape",i),i},checks:[]});return mn(e,a)}function Yf(e,t){if(!yr(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=un(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return An(this,"shape",a),a}});return mn(e,o)}function Kf(e,t){if(!yr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=un(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return An(this,"shape",s),s}});return mn(e,r)}function Jf(e,t){const r=un(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return An(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return mn(e,r)}function Xf(e,t,r){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=un(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(r)for(const d in r){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return An(this,"shape",l),l},checks:[]});return mn(t,i)}function eh(e,t,r){const s=un(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(r)for(const i in r){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return An(this,"shape",a),a}});return mn(t,s)}function Bn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Cl(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Mr(e){return typeof e=="string"?e:e?.message}function jn(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Mr(e.inst?._zod.def?.error?.(e))??Mr(t?.error?.(e))??Mr(r.customError?.(e))??Mr(r.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function fa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function br(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const Nl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Do,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Al=Z("$ZodError",Nl),Pl=Z("$ZodError",Nl,{Parent:Error});function th(e,t=r=>r.message){const r={},s=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):s.push(t(o));return{formErrors:s,fieldErrors:r}}function nh(e,t=r=>r.message){const r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)r._errors.push(t(a));else{let i=r,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(t(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(e),r}const ha=e=>(t,r,s,o)=>{const a=s?Object.assign(s,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Un;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>jn(l,a,_n())));throw Sl(c,o?.callee),c}return i.value},ga=e=>async(t,r,s,o)=>{const a=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>jn(l,a,_n())));throw Sl(c,o?.callee),c}return i.value},vs=e=>(t,r,s)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Un;return a.issues.length?{success:!1,error:new(e??Al)(a.issues.map(i=>jn(i,o,_n())))}:{success:!0,data:a.value}},rh=vs(Pl),ws=e=>async(t,r,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>jn(i,o,_n())))}:{success:!0,data:a.value}},sh=ws(Pl),oh=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return ha(e)(t,r,o)},ah=e=>(t,r,s)=>ha(e)(t,r,s),ih=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return ga(e)(t,r,o)},ch=e=>async(t,r,s)=>ga(e)(t,r,s),lh=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return vs(e)(t,r,o)},dh=e=>(t,r,s)=>vs(e)(t,r,s),uh=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return ws(e)(t,r,o)},mh=e=>async(t,r,s)=>ws(e)(t,r,s),ph=/^[cC][^\s-]{8,}$/,fh=/^[0-9a-z]+$/,hh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gh=/^[0-9a-vA-V]{20}$/,xh=/^[A-Za-z0-9]{27}$/,yh=/^[a-zA-Z0-9_-]{21}$/,bh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,vh=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ii=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,wh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_h="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jh(){return new RegExp(_h,"u")}const Sh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,kh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ch=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Nh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ah=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tl=/^[A-Za-z0-9_-]*$/,Ph=/^\+[1-9]\d{6,14}$/,El="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Th=new RegExp(`^${El}$`);function Il(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Eh(e){return new RegExp(`^${Il(e)}$`)}function Ih(e){const t=Il({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${El}T(?:${s})$`)}const Rh=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Oh=/^-?\d+$/,Mh=/^-?\d+(?:\.\d+)?$/,Dh=/^[^A-Z]*$/,Lh=/^[^a-z]*$/,gt=Z("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Rl={number:"number",bigint:"bigint",object:"date"},Ol=Z("$ZodCheckLessThan",(e,t)=>{gt.init(e,t);const r=Rl[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ml=Z("$ZodCheckGreaterThan",(e,t)=>{gt.init(e,t);const r=Rl[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$h=Z("$ZodCheckMultipleOf",(e,t)=>{gt.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Uf(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),zh=Z("$ZodCheckNumberFormat",(e,t)=>{gt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=Zf[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,r&&(c.pattern=Oh)}),e._zod.check=i=>{const c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>a&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Fh=Z("$ZodCheckMaxLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!ma(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const o=s.value;if(o.length<=t.maximum)return;const i=fa(o);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Bh=Z("$ZodCheckMinLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!ma(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const o=s.value;if(o.length>=t.minimum)return;const i=fa(o);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Uh=Z("$ZodCheckLengthEquals",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!ma(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=s=>{const o=s.value,a=o.length;if(a===t.length)return;const i=fa(o),c=a>t.length;s.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),_s=Z("$ZodCheckStringFormat",(e,t)=>{var r,s;gt.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),Wh=Z("$ZodCheckRegex",(e,t)=>{_s.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Vh=Z("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Dh),_s.init(e,t)}),Hh=Z("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Lh),_s.init(e,t)}),qh=Z("$ZodCheckIncludes",(e,t)=>{gt.init(e,t);const r=bs(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(s)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Zh=Z("$ZodCheckStartsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`^${bs(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),Gh=Z("$ZodCheckEndsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`.*${bs(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),Qh=Z("$ZodCheckOverwrite",(e,t)=>{gt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Yh{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
54
- `).filter(i=>i),o=Math.min(...s.map(i=>i.length-i.trimStart().length)),a=s.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...r,o.join(`
55
- `))}}const Kh={major:4,minor:3,patch:6},qe=Z("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Kh;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const o of s)for(const a of o._zod.onattach)a(e);if(s.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(i,c,l)=>{let d=Bn(i),m;for(const u of c){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(d)continue;const f=i.issues.length,h=u._zod.check(i);if(h instanceof Promise&&l?.async===!1)throw new Un;if(m||h instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await h,i.issues.length!==f&&(d||(d=Bn(i,f)))});else{if(i.issues.length===f)continue;d||(d=Bn(i,f))}}return m?m.then(()=>i):i},a=(i,c,l)=>{if(Bn(i))return i.aborted=!0,i;const d=o(c,s,l);if(d instanceof Promise){if(l.async===!1)throw new Un;return d.then(m=>e._zod.parse(m,l))}return e._zod.parse(d,l)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const d=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(m=>a(m,i,c)):a(d,i,c)}const l=e._zod.parse(i,c);if(l instanceof Promise){if(c.async===!1)throw new Un;return l.then(d=>o(d,s,c))}return o(l,s,c)}}Ce(e,"~standard",()=>({validate:o=>{try{const a=rh(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return sh(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),xa=Z("$ZodString",(e,t)=>{qe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Rh(e._zod.bag),e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Re=Z("$ZodStringFormat",(e,t)=>{_s.init(e,t),xa.init(e,t)}),Jh=Z("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=vh),Re.init(e,t)}),Xh=Z("$ZodUUID",(e,t)=>{if(t.version){const s={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(s===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ii(s))}else t.pattern??(t.pattern=Ii());Re.init(e,t)}),eg=Z("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=wh),Re.init(e,t)}),tg=Z("$ZodURL",(e,t)=>{Re.init(e,t),e._zod.check=r=>{try{const s=r.value.trim(),o=new URL(s);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ng=Z("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=jh()),Re.init(e,t)}),rg=Z("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=yh),Re.init(e,t)}),sg=Z("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ph),Re.init(e,t)}),og=Z("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=fh),Re.init(e,t)}),ag=Z("$ZodULID",(e,t)=>{t.pattern??(t.pattern=hh),Re.init(e,t)}),ig=Z("$ZodXID",(e,t)=>{t.pattern??(t.pattern=gh),Re.init(e,t)}),cg=Z("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=xh),Re.init(e,t)}),lg=Z("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Ih(t)),Re.init(e,t)}),dg=Z("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Th),Re.init(e,t)}),ug=Z("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Eh(t)),Re.init(e,t)}),mg=Z("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=bh),Re.init(e,t)}),pg=Z("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Sh),Re.init(e,t),e._zod.bag.format="ipv4"}),fg=Z("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=kh),Re.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),hg=Z("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ch),Re.init(e,t)}),gg=Z("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Nh),Re.init(e,t),e._zod.check=r=>{const s=r.value.split("/");try{if(s.length!==2)throw new Error;const[o,a]=s;if(!a)throw new Error;const i=Number(a);if(`${i}`!==a)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Dl(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const xg=Z("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ah),Re.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Dl(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function yg(e){if(!Tl.test(e))return!1;const t=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Dl(r)}const bg=Z("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Tl),Re.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{yg(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),vg=Z("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ph),Re.init(e,t)});function wg(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[s]=r;if(!s)return!1;const o=JSON.parse(atob(s));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const _g=Z("$ZodJWT",(e,t)=>{Re.init(e,t),e._zod.check=r=>{wg(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Ll=Z("$ZodNumber",(e,t)=>{qe.init(e,t),e._zod.pattern=e._zod.bag.pattern??Mh,e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const a=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...a?{received:a}:{}}),r}}),jg=Z("$ZodNumberFormat",(e,t)=>{zh.init(e,t),Ll.init(e,t)}),Sg=Z("$ZodUnknown",(e,t)=>{qe.init(e,t),e._zod.parse=r=>r}),kg=Z("$ZodNever",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Ri(e,t,r){e.issues.length&&t.issues.push(...Cl(r,e.issues)),t.value[r]=e.value}const Cg=Z("$ZodArray",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const a=[];for(let i=0;i<o.length;i++){const c=o[i],l=t.element._zod.run({value:c,issues:[]},s);l instanceof Promise?a.push(l.then(d=>Ri(d,r,i))):Ri(l,r,i)}return a.length?Promise.all(a).then(()=>r):r}});function rs(e,t,r,s,o){if(e.issues.length){if(o&&!(r in s))return;t.issues.push(...Cl(r,e.issues))}e.value===void 0?r in s&&(t.value[r]=void 0):t.value[r]=e.value}function $l(e){const t=Object.keys(e.shape);for(const s of t)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${s}": expected a Zod schema`);const r=qf(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function zl(e,t,r,s,o,a){const i=[],c=o.keySet,l=o.catchall._zod,d=l.def.type,m=l.optout==="optional";for(const u in t){if(c.has(u))continue;if(d==="never"){i.push(u);continue}const f=l.run({value:t[u],issues:[]},s);f instanceof Promise?e.push(f.then(h=>rs(h,r,u,t,m))):rs(f,r,u,t,m)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:a}),e.length?Promise.all(e).then(()=>r):r}const Ng=Z("$ZodObject",(e,t)=>{if(qe.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}const s=ua(()=>$l(t));Ce(e._zod,"propValues",()=>{const c=t.shape,l={};for(const d in c){const m=c[d]._zod;if(m.values){l[d]??(l[d]=new Set);for(const u of m.values)l[d].add(u)}}return l});const o=ns,a=t.catchall;let i;e._zod.parse=(c,l)=>{i??(i=s.value);const d=c.value;if(!o(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const m=[],u=i.shape;for(const f of i.keys){const h=u[f],x=h._zod.optout==="optional",p=h._zod.run({value:d[f],issues:[]},l);p instanceof Promise?m.push(p.then(y=>rs(y,c,f,d,x))):rs(p,c,f,d,x)}return a?zl(m,d,c,l,s.value,e):m.length?Promise.all(m).then(()=>c):c}}),Ag=Z("$ZodObjectJIT",(e,t)=>{Ng.init(e,t);const r=e._zod.parse,s=ua(()=>$l(t)),o=f=>{const h=new Yh(["shape","payload","ctx"]),x=s.value,p=v=>{const _=Ei(v);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};h.write("const input = payload.value;");const y=Object.create(null);let j=0;for(const v of x.keys)y[v]=`key_${j++}`;h.write("const newResult = {};");for(const v of x.keys){const _=y[v],C=Ei(v),S=f[v]?._zod?.optout==="optional";h.write(`const ${_} = ${p(v)};`),S?h.write(`
56
- if (${_}.issues.length) {
57
- if (${C} in input) {
58
- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
59
- ...iss,
60
- path: iss.path ? [${C}, ...iss.path] : [${C}]
61
- })));
62
- }
63
- }
64
-
65
- if (${_}.value === undefined) {
66
- if (${C} in input) {
67
- newResult[${C}] = undefined;
68
- }
69
- } else {
70
- newResult[${C}] = ${_}.value;
71
- }
72
-
73
- `):h.write(`
74
- if (${_}.issues.length) {
75
- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
76
- ...iss,
77
- path: iss.path ? [${C}, ...iss.path] : [${C}]
78
- })));
79
- }
80
-
81
- if (${_}.value === undefined) {
82
- if (${C} in input) {
83
- newResult[${C}] = undefined;
84
- }
85
- } else {
86
- newResult[${C}] = ${_}.value;
87
- }
88
-
89
- `)}h.write("payload.value = newResult;"),h.write("return payload;");const b=h.compile();return(v,_)=>b(f,v,_)};let a;const i=ns,c=!_l.jitless,d=c&&Vf.value,m=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=s.value);const x=f.value;return i(x)?c&&d&&h?.async===!1&&h.jitless!==!0?(a||(a=o(t.shape)),f=a(f,h),m?zl([],x,f,h,u,e):f):r(f,h):(f.issues.push({expected:"object",code:"invalid_type",input:x,inst:e}),f)}});function Oi(e,t,r,s){for(const a of e)if(a.issues.length===0)return t.value=a.value,t;const o=e.filter(a=>!Bn(a));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(a=>a.issues.map(i=>jn(i,s,_n())))}),t)}const Pg=Z("$ZodUnion",(e,t)=>{qe.init(e,t),Ce(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Ce(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Ce(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Ce(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${o.map(a=>pa(a.source)).join("|")})$`)}});const r=t.options.length===1,s=t.options[0]._zod.run;e._zod.parse=(o,a)=>{if(r)return s(o,a);let i=!1;const c=[];for(const l of t.options){const d=l._zod.run({value:o.value,issues:[]},a);if(d instanceof Promise)c.push(d),i=!0;else{if(d.issues.length===0)return d;c.push(d)}}return i?Promise.all(c).then(l=>Oi(l,o,e,a)):Oi(c,o,e,a)}}),Tg=Z("$ZodIntersection",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>{const o=r.value,a=t.left._zod.run({value:o,issues:[]},s),i=t.right._zod.run({value:o,issues:[]},s);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([l,d])=>Mi(r,l,d)):Mi(r,a,i)}});function Lo(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(yr(e)&&yr(t)){const r=Object.keys(t),s=Object.keys(e).filter(a=>r.indexOf(a)!==-1),o={...e,...t};for(const a of s){const i=Lo(e[a],t[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};o[a]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let s=0;s<e.length;s++){const o=e[s],a=t[s],i=Lo(o,a);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Mi(e,t,r){const s=new Map;let o;for(const c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(const l of c.keys)s.has(l)||s.set(l,{}),s.get(l).l=!0}else e.issues.push(c);for(const c of r.issues)if(c.code==="unrecognized_keys")for(const l of c.keys)s.has(l)||s.set(l,{}),s.get(l).r=!0;else e.issues.push(c);const a=[...s].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length&&o&&e.issues.push({...o,keys:a}),Bn(e))return e;const i=Lo(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const Eg=Z("$ZodEnum",(e,t)=>{qe.init(e,t);const r=jl(t.entries),s=new Set(r);e._zod.values=s,e._zod.pattern=new RegExp(`^(${r.filter(o=>Hf.has(typeof o)).map(o=>typeof o=="string"?bs(o):o.toString()).join("|")})$`),e._zod.parse=(o,a)=>{const i=o.value;return s.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Ig=Z("$ZodTransform",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new wl(e.constructor.name);const o=t.transform(r.value,r);if(s.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Un;return r.value=o,r}});function Di(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Fl=Z("$ZodOptional",(e,t)=>{qe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pa(r.source)})?$`):void 0}),e._zod.parse=(r,s)=>{if(t.innerType._zod.optin==="optional"){const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>Di(a,r.value)):Di(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,s)}}),Rg=Z("$ZodExactOptional",(e,t)=>{Fl.init(e,t),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,s)=>t.innerType._zod.run(r,s)}),Og=Z("$ZodNullable",(e,t)=>{qe.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pa(r.source)}|null)$`):void 0}),Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,s)=>r.value===null?r:t.innerType._zod.run(r,s)}),Mg=Z("$ZodDefault",(e,t)=>{qe.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>Li(a,t)):Li(o,t)}});function Li(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Dg=Z("$ZodPrefault",(e,t)=>{qe.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>(s.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,s))}),Lg=Z("$ZodNonOptional",(e,t)=>{qe.init(e,t),Ce(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(s=>s!==void 0)):void 0}),e._zod.parse=(r,s)=>{const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>$i(a,e)):$i(o,e)}});function $i(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const $g=Z("$ZodCatch",(e,t)=>{qe.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(i=>jn(i,s,_n()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>jn(a,s,_n()))},input:r.value}),r.issues=[]),r)}}),zg=Z("$ZodPipe",(e,t)=>{qe.init(e,t),Ce(e._zod,"values",()=>t.in._zod.values),Ce(e._zod,"optin",()=>t.in._zod.optin),Ce(e._zod,"optout",()=>t.out._zod.optout),Ce(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,s)=>{if(s.direction==="backward"){const a=t.out._zod.run(r,s);return a instanceof Promise?a.then(i=>Dr(i,t.in,s)):Dr(a,t.in,s)}const o=t.in._zod.run(r,s);return o instanceof Promise?o.then(a=>Dr(a,t.out,s)):Dr(o,t.out,s)}});function Dr(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const Fg=Z("$ZodReadonly",(e,t)=>{qe.init(e,t),Ce(e._zod,"propValues",()=>t.innerType._zod.propValues),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"optin",()=>t.innerType?._zod?.optin),Ce(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(zi):zi(o)}});function zi(e){return e.value=Object.freeze(e.value),e}const Bg=Z("$ZodCustom",(e,t)=>{gt.init(e,t),qe.init(e,t),e._zod.parse=(r,s)=>r,e._zod.check=r=>{const s=r.value,o=t.fn(s);if(o instanceof Promise)return o.then(a=>Fi(a,r,s,e));Fi(o,r,s,e)}});function Fi(e,t,r,s){if(!e){const o={code:"custom",input:r,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(o.params=s._zod.def.params),t.issues.push(br(o))}}var Bi;class Ug{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){const s=r[0];return this._map.set(t,s),s&&typeof s=="object"&&"id"in s&&this._idmap.set(s.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const s={...this.get(r)??{}};delete s.id;const o={...s,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Wg(){return new Ug}(Bi=globalThis).__zod_globalRegistry??(Bi.__zod_globalRegistry=Wg());const mr=globalThis.__zod_globalRegistry;function Vg(e,t){return new e({type:"string",...ue(t)})}function Hg(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ue(t)})}function Ui(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ue(t)})}function qg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ue(t)})}function Zg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ue(t)})}function Gg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ue(t)})}function Qg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ue(t)})}function Yg(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ue(t)})}function Kg(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ue(t)})}function Jg(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ue(t)})}function Xg(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ue(t)})}function ex(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ue(t)})}function tx(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ue(t)})}function nx(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ue(t)})}function rx(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ue(t)})}function sx(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ue(t)})}function ox(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ue(t)})}function ax(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ue(t)})}function ix(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ue(t)})}function cx(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ue(t)})}function lx(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ue(t)})}function dx(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ue(t)})}function ux(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ue(t)})}function mx(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ue(t)})}function px(e,t){return new e({type:"string",format:"date",check:"string_format",...ue(t)})}function fx(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ue(t)})}function hx(e,t){return new e({type:"string",format:"duration",check:"string_format",...ue(t)})}function gx(e,t){return new e({type:"number",checks:[],...ue(t)})}function xx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ue(t)})}function yx(e){return new e({type:"unknown"})}function bx(e,t){return new e({type:"never",...ue(t)})}function Wi(e,t){return new Ol({check:"less_than",...ue(t),value:e,inclusive:!1})}function uo(e,t){return new Ol({check:"less_than",...ue(t),value:e,inclusive:!0})}function Vi(e,t){return new Ml({check:"greater_than",...ue(t),value:e,inclusive:!1})}function mo(e,t){return new Ml({check:"greater_than",...ue(t),value:e,inclusive:!0})}function Hi(e,t){return new $h({check:"multiple_of",...ue(t),value:e})}function Bl(e,t){return new Fh({check:"max_length",...ue(t),maximum:e})}function ss(e,t){return new Bh({check:"min_length",...ue(t),minimum:e})}function Ul(e,t){return new Uh({check:"length_equals",...ue(t),length:e})}function vx(e,t){return new Wh({check:"string_format",format:"regex",...ue(t),pattern:e})}function wx(e){return new Vh({check:"string_format",format:"lowercase",...ue(e)})}function _x(e){return new Hh({check:"string_format",format:"uppercase",...ue(e)})}function jx(e,t){return new qh({check:"string_format",format:"includes",...ue(t),includes:e})}function Sx(e,t){return new Zh({check:"string_format",format:"starts_with",...ue(t),prefix:e})}function kx(e,t){return new Gh({check:"string_format",format:"ends_with",...ue(t),suffix:e})}function Qn(e){return new Qh({check:"overwrite",tx:e})}function Cx(e){return Qn(t=>t.normalize(e))}function Nx(){return Qn(e=>e.trim())}function Ax(){return Qn(e=>e.toLowerCase())}function Px(){return Qn(e=>e.toUpperCase())}function Tx(){return Qn(e=>Wf(e))}function Ex(e,t,r){return new e({type:"array",element:t,...ue(r)})}function Ix(e,t,r){return new e({type:"custom",check:"custom",fn:t,...ue(r)})}function Rx(e){const t=Ox(r=>(r.addIssue=s=>{if(typeof s=="string")r.issues.push(br(s,r.value,t._zod.def));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(br(o))}},e(r.value,r)));return t}function Ox(e,t){const r=new gt({check:"custom",...ue(t)});return r._zod.check=e,r}function Wl(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??mr,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function et(e,t,r={path:[],schemaPath:[]}){var s;const o=e._zod.def,a=t.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);const c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{const m={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,m);else{const f=i.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,f,m)}const u=e._zod.parent;u&&(i.ref||(i.ref=u),et(u,t,m),t.seen.get(u).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),t.io==="input"&&it(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&i.schema._prefault&&((s=i.schema).default??(s.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Vl(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const i of e.seen.entries()){const c=e.metadataRegistry.get(i[0])?.id;if(c){const l=s.get(c);if(l&&l!==i[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(c,i[0])}}const o=i=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const u=e.external.registry.get(i[0])?.id,f=e.external.uri??(x=>x);if(u)return{ref:f(u)};const h=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=h,{defId:h,ref:`${f("__shared")}#/${c}/${h}`}}if(i[1]===r)return{ref:"#"};const d=`#/${c}/`,m=i[1].schema.id??`__schema${e.counter++}`;return{defId:m,ref:d+m}},a=i=>{if(i[1].schema.$ref)return;const c=i[1],{ref:l,defId:d}=o(i);c.def={...c.schema},d&&(c.defId=d);const m=c.schema;for(const u in m)delete m[u];m.$ref=l};if(e.cycles==="throw")for(const i of e.seen.entries()){const c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
90
-
91
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const c=i[1];if(t===i[0]){a(i);continue}if(e.external){const d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){a(i);continue}}if(e.metadataRegistry.get(i[0])?.id){a(i);continue}if(c.cycle){a(i);continue}if(c.count>1&&e.reused==="ref"){a(i);continue}}}function Hl(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i=>{const c=e.seen.get(i);if(c.ref===null)return;const l=c.def??c.schema,d={...l},m=c.ref;if(c.ref=null,m){s(m);const f=e.seen.get(m),h=f.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(h)):Object.assign(l,h),Object.assign(l,d),i._zod.parent===m)for(const p in l)p==="$ref"||p==="allOf"||p in d||delete l[p];if(h.$ref&&f.def)for(const p in l)p==="$ref"||p==="allOf"||p in f.def&&JSON.stringify(l[p])===JSON.stringify(f.def[p])&&delete l[p]}const u=i._zod.parent;if(u&&u!==m){s(u);const f=e.seen.get(u);if(f?.schema.$ref&&(l.$ref=f.schema.$ref,f.def))for(const h in l)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(l[h])===JSON.stringify(f.def[h])&&delete l[h]}e.override({zodSchema:i,jsonSchema:l,path:c.path??[]})};for(const i of[...e.seen.entries()].reverse())s(i[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(i)}Object.assign(o,r.def??r.schema);const a=e.external?.defs??{};for(const i of e.seen.entries()){const c=i[1];c.def&&c.defId&&(a[c.defId]=c.def)}e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?o.$defs=a:o.definitions=a);try{const i=JSON.parse(JSON.stringify(o));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:os(t,"input",e.processors),output:os(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function it(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return it(s.element,r);if(s.type==="set")return it(s.valueType,r);if(s.type==="lazy")return it(s.getter(),r);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return it(s.innerType,r);if(s.type==="intersection")return it(s.left,r)||it(s.right,r);if(s.type==="record"||s.type==="map")return it(s.keyType,r)||it(s.valueType,r);if(s.type==="pipe")return it(s.in,r)||it(s.out,r);if(s.type==="object"){for(const o in s.shape)if(it(s.shape[o],r))return!0;return!1}if(s.type==="union"){for(const o of s.options)if(it(o,r))return!0;return!1}if(s.type==="tuple"){for(const o of s.items)if(it(o,r))return!0;return!!(s.rest&&it(s.rest,r))}return!1}const Mx=(e,t={})=>r=>{const s=Wl({...r,processors:t});return et(e,s),Vl(s,e),Hl(s,e)},os=(e,t,r={})=>s=>{const{libraryOptions:o,target:a}=s??{},i=Wl({...o??{},target:a,io:t,processors:r});return et(e,i),Vl(i,e),Hl(i,e)},Dx={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Lx=(e,t,r,s)=>{const o=r;o.type="string";const{minimum:a,maximum:i,format:c,patterns:l,contentEncoding:d}=e._zod.bag;if(typeof a=="number"&&(o.minLength=a),typeof i=="number"&&(o.maxLength=i),c&&(o.format=Dx[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),d&&(o.contentEncoding=d),l&&l.size>0){const m=[...l];m.length===1?o.pattern=m[0].source:m.length>1&&(o.allOf=[...m.map(u=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:u.source}))])}},$x=(e,t,r,s)=>{const o=r,{minimum:a,maximum:i,format:c,multipleOf:l,exclusiveMaximum:d,exclusiveMinimum:m}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number",typeof m=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=m,o.exclusiveMinimum=!0):o.exclusiveMinimum=m),typeof a=="number"&&(o.minimum=a,typeof m=="number"&&t.target!=="draft-04"&&(m>=a?delete o.minimum:delete o.exclusiveMinimum)),typeof d=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=d,o.exclusiveMaximum=!0):o.exclusiveMaximum=d),typeof i=="number"&&(o.maximum=i,typeof d=="number"&&t.target!=="draft-04"&&(d<=i?delete o.maximum:delete o.exclusiveMaximum)),typeof l=="number"&&(o.multipleOf=l)},zx=(e,t,r,s)=>{r.not={}},Fx=(e,t,r,s)=>{},Bx=(e,t,r,s)=>{const o=e._zod.def,a=jl(o.entries);a.every(i=>typeof i=="number")&&(r.type="number"),a.every(i=>typeof i=="string")&&(r.type="string"),r.enum=a},Ux=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Wx=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Vx=(e,t,r,s)=>{const o=r,a=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=et(a.element,t,{...s,path:[...s.path,"items"]})},Hx=(e,t,r,s)=>{const o=r,a=e._zod.def;o.type="object",o.properties={};const i=a.shape;for(const d in i)o.properties[d]=et(i[d],t,{...s,path:[...s.path,"properties",d]});const c=new Set(Object.keys(i)),l=new Set([...c].filter(d=>{const m=a.shape[d]._zod;return t.io==="input"?m.optin===void 0:m.optout===void 0}));l.size>0&&(o.required=Array.from(l)),a.catchall?._zod.def.type==="never"?o.additionalProperties=!1:a.catchall?a.catchall&&(o.additionalProperties=et(a.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},qx=(e,t,r,s)=>{const o=e._zod.def,a=o.inclusive===!1,i=o.options.map((c,l)=>et(c,t,{...s,path:[...s.path,a?"oneOf":"anyOf",l]}));a?r.oneOf=i:r.anyOf=i},Zx=(e,t,r,s)=>{const o=e._zod.def,a=et(o.left,t,{...s,path:[...s.path,"allOf",0]}),i=et(o.right,t,{...s,path:[...s.path,"allOf",1]}),c=d=>"allOf"in d&&Object.keys(d).length===1,l=[...c(a)?a.allOf:[a],...c(i)?i.allOf:[i]];r.allOf=l},Gx=(e,t,r,s)=>{const o=e._zod.def,a=et(o.innerType,t,s),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]},Qx=(e,t,r,s)=>{const o=e._zod.def;et(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},Yx=(e,t,r,s)=>{const o=e._zod.def;et(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Kx=(e,t,r,s)=>{const o=e._zod.def;et(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Jx=(e,t,r,s)=>{const o=e._zod.def;et(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Xx=(e,t,r,s)=>{const o=e._zod.def,a=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;et(a,t,s);const i=t.seen.get(e);i.ref=a},ey=(e,t,r,s)=>{const o=e._zod.def;et(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.readOnly=!0},ql=(e,t,r,s)=>{const o=e._zod.def;et(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},ty=Z("ZodISODateTime",(e,t)=>{lg.init(e,t),Le.init(e,t)});function ny(e){return mx(ty,e)}const ry=Z("ZodISODate",(e,t)=>{dg.init(e,t),Le.init(e,t)});function sy(e){return px(ry,e)}const oy=Z("ZodISOTime",(e,t)=>{ug.init(e,t),Le.init(e,t)});function ay(e){return fx(oy,e)}const iy=Z("ZodISODuration",(e,t)=>{mg.init(e,t),Le.init(e,t)});function cy(e){return hx(iy,e)}const ly=(e,t)=>{Al.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>nh(e,r)},flatten:{value:r=>th(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Do,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Do,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ct=Z("ZodError",ly,{Parent:Error}),dy=ha(Ct),uy=ga(Ct),my=vs(Ct),py=ws(Ct),fy=oh(Ct),hy=ah(Ct),gy=ih(Ct),xy=ch(Ct),yy=lh(Ct),by=dh(Ct),vy=uh(Ct),wy=mh(Ct),Ze=Z("ZodType",(e,t)=>(qe.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:os(e,"input"),output:os(e,"output")}}),e.toJSONSchema=Mx(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(un(t,{checks:[...t.checks??[],...r.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0}),e.with=e.check,e.clone=(r,s)=>mn(e,r,s),e.brand=()=>e,e.register=((r,s)=>(r.add(e,s),e)),e.parse=(r,s)=>dy(e,r,s,{callee:e.parse}),e.safeParse=(r,s)=>my(e,r,s),e.parseAsync=async(r,s)=>uy(e,r,s,{callee:e.parseAsync}),e.safeParseAsync=async(r,s)=>py(e,r,s),e.spa=e.safeParseAsync,e.encode=(r,s)=>fy(e,r,s),e.decode=(r,s)=>hy(e,r,s),e.encodeAsync=async(r,s)=>gy(e,r,s),e.decodeAsync=async(r,s)=>xy(e,r,s),e.safeEncode=(r,s)=>yy(e,r,s),e.safeDecode=(r,s)=>by(e,r,s),e.safeEncodeAsync=async(r,s)=>vy(e,r,s),e.safeDecodeAsync=async(r,s)=>wy(e,r,s),e.refine=(r,s)=>e.check(hb(r,s)),e.superRefine=r=>e.check(gb(r)),e.overwrite=r=>e.check(Qn(r)),e.optional=()=>Qi(e),e.exactOptional=()=>nb(e),e.nullable=()=>Yi(e),e.nullish=()=>Qi(Yi(e)),e.nonoptional=r=>cb(e,r),e.array=()=>qy(e),e.or=r=>Qy([e,r]),e.and=r=>Ky(e,r),e.transform=r=>Ki(e,eb(r)),e.default=r=>ob(e,r),e.prefault=r=>ib(e,r),e.catch=r=>db(e,r),e.pipe=r=>Ki(e,r),e.readonly=()=>pb(e),e.describe=r=>{const s=e.clone();return mr.add(s,{description:r}),s},Object.defineProperty(e,"description",{get(){return mr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return mr.get(e);const s=e.clone();return mr.add(s,r[0]),s},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),Zl=Z("_ZodString",(e,t)=>{xa.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Lx(e,s,o);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...s)=>e.check(vx(...s)),e.includes=(...s)=>e.check(jx(...s)),e.startsWith=(...s)=>e.check(Sx(...s)),e.endsWith=(...s)=>e.check(kx(...s)),e.min=(...s)=>e.check(ss(...s)),e.max=(...s)=>e.check(Bl(...s)),e.length=(...s)=>e.check(Ul(...s)),e.nonempty=(...s)=>e.check(ss(1,...s)),e.lowercase=s=>e.check(wx(s)),e.uppercase=s=>e.check(_x(s)),e.trim=()=>e.check(Nx()),e.normalize=(...s)=>e.check(Cx(...s)),e.toLowerCase=()=>e.check(Ax()),e.toUpperCase=()=>e.check(Px()),e.slugify=()=>e.check(Tx())}),_y=Z("ZodString",(e,t)=>{xa.init(e,t),Zl.init(e,t),e.email=r=>e.check(Hg(jy,r)),e.url=r=>e.check(Yg(Sy,r)),e.jwt=r=>e.check(ux(zy,r)),e.emoji=r=>e.check(Kg(ky,r)),e.guid=r=>e.check(Ui(qi,r)),e.uuid=r=>e.check(qg(Lr,r)),e.uuidv4=r=>e.check(Zg(Lr,r)),e.uuidv6=r=>e.check(Gg(Lr,r)),e.uuidv7=r=>e.check(Qg(Lr,r)),e.nanoid=r=>e.check(Jg(Cy,r)),e.guid=r=>e.check(Ui(qi,r)),e.cuid=r=>e.check(Xg(Ny,r)),e.cuid2=r=>e.check(ex(Ay,r)),e.ulid=r=>e.check(tx(Py,r)),e.base64=r=>e.check(cx(Dy,r)),e.base64url=r=>e.check(lx(Ly,r)),e.xid=r=>e.check(nx(Ty,r)),e.ksuid=r=>e.check(rx(Ey,r)),e.ipv4=r=>e.check(sx(Iy,r)),e.ipv6=r=>e.check(ox(Ry,r)),e.cidrv4=r=>e.check(ax(Oy,r)),e.cidrv6=r=>e.check(ix(My,r)),e.e164=r=>e.check(dx($y,r)),e.datetime=r=>e.check(ny(r)),e.date=r=>e.check(sy(r)),e.time=r=>e.check(ay(r)),e.duration=r=>e.check(cy(r))});function ct(e){return Vg(_y,e)}const Le=Z("ZodStringFormat",(e,t)=>{Re.init(e,t),Zl.init(e,t)}),jy=Z("ZodEmail",(e,t)=>{eg.init(e,t),Le.init(e,t)}),qi=Z("ZodGUID",(e,t)=>{Jh.init(e,t),Le.init(e,t)}),Lr=Z("ZodUUID",(e,t)=>{Xh.init(e,t),Le.init(e,t)}),Sy=Z("ZodURL",(e,t)=>{tg.init(e,t),Le.init(e,t)}),ky=Z("ZodEmoji",(e,t)=>{ng.init(e,t),Le.init(e,t)}),Cy=Z("ZodNanoID",(e,t)=>{rg.init(e,t),Le.init(e,t)}),Ny=Z("ZodCUID",(e,t)=>{sg.init(e,t),Le.init(e,t)}),Ay=Z("ZodCUID2",(e,t)=>{og.init(e,t),Le.init(e,t)}),Py=Z("ZodULID",(e,t)=>{ag.init(e,t),Le.init(e,t)}),Ty=Z("ZodXID",(e,t)=>{ig.init(e,t),Le.init(e,t)}),Ey=Z("ZodKSUID",(e,t)=>{cg.init(e,t),Le.init(e,t)}),Iy=Z("ZodIPv4",(e,t)=>{pg.init(e,t),Le.init(e,t)}),Ry=Z("ZodIPv6",(e,t)=>{fg.init(e,t),Le.init(e,t)}),Oy=Z("ZodCIDRv4",(e,t)=>{hg.init(e,t),Le.init(e,t)}),My=Z("ZodCIDRv6",(e,t)=>{gg.init(e,t),Le.init(e,t)}),Dy=Z("ZodBase64",(e,t)=>{xg.init(e,t),Le.init(e,t)}),Ly=Z("ZodBase64URL",(e,t)=>{bg.init(e,t),Le.init(e,t)}),$y=Z("ZodE164",(e,t)=>{vg.init(e,t),Le.init(e,t)}),zy=Z("ZodJWT",(e,t)=>{_g.init(e,t),Le.init(e,t)}),Gl=Z("ZodNumber",(e,t)=>{Ll.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(s,o,a)=>$x(e,s,o),e.gt=(s,o)=>e.check(Vi(s,o)),e.gte=(s,o)=>e.check(mo(s,o)),e.min=(s,o)=>e.check(mo(s,o)),e.lt=(s,o)=>e.check(Wi(s,o)),e.lte=(s,o)=>e.check(uo(s,o)),e.max=(s,o)=>e.check(uo(s,o)),e.int=s=>e.check(Zi(s)),e.safe=s=>e.check(Zi(s)),e.positive=s=>e.check(Vi(0,s)),e.nonnegative=s=>e.check(mo(0,s)),e.negative=s=>e.check(Wi(0,s)),e.nonpositive=s=>e.check(uo(0,s)),e.multipleOf=(s,o)=>e.check(Hi(s,o)),e.step=(s,o)=>e.check(Hi(s,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Fy(e){return gx(Gl,e)}const By=Z("ZodNumberFormat",(e,t)=>{jg.init(e,t),Gl.init(e,t)});function Zi(e){return xx(By,e)}const Uy=Z("ZodUnknown",(e,t)=>{Sg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Fx()});function Gi(){return yx(Uy)}const Wy=Z("ZodNever",(e,t)=>{kg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>zx(e,r,s)});function Vy(e){return bx(Wy,e)}const Hy=Z("ZodArray",(e,t)=>{Cg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Vx(e,r,s,o),e.element=t.element,e.min=(r,s)=>e.check(ss(r,s)),e.nonempty=r=>e.check(ss(1,r)),e.max=(r,s)=>e.check(Bl(r,s)),e.length=(r,s)=>e.check(Ul(r,s)),e.unwrap=()=>e.element});function qy(e,t){return Ex(Hy,e,t)}const Zy=Z("ZodObject",(e,t)=>{Ag.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Hx(e,r,s,o),Ce(e,"shape",()=>t.shape),e.keyof=()=>Jy(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Gi()}),e.loose=()=>e.clone({...e._zod.def,catchall:Gi()}),e.strict=()=>e.clone({...e._zod.def,catchall:Vy()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Yf(e,r),e.safeExtend=r=>Kf(e,r),e.merge=r=>Jf(e,r),e.pick=r=>Gf(e,r),e.omit=r=>Qf(e,r),e.partial=(...r)=>Xf(Yl,e,r[0]),e.required=(...r)=>eh(Kl,e,r[0])});function Ql(e,t){const r={type:"object",shape:e??{},...ue(t)};return new Zy(r)}const Gy=Z("ZodUnion",(e,t)=>{Pg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>qx(e,r,s,o),e.options=t.options});function Qy(e,t){return new Gy({type:"union",options:e,...ue(t)})}const Yy=Z("ZodIntersection",(e,t)=>{Tg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Zx(e,r,s,o)});function Ky(e,t){return new Yy({type:"intersection",left:e,right:t})}const $o=Z("ZodEnum",(e,t)=>{Eg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Bx(e,s,o),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(s,o)=>{const a={};for(const i of s)if(r.has(i))a[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new $o({...t,checks:[],...ue(o),entries:a})},e.exclude=(s,o)=>{const a={...t.entries};for(const i of s)if(r.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new $o({...t,checks:[],...ue(o),entries:a})}});function Jy(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new $o({type:"enum",entries:r,...ue(t)})}const Xy=Z("ZodTransform",(e,t)=>{Ig.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Wx(e,r),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new wl(e.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(br(a,r.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(br(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(a=>(r.value=a,r)):(r.value=o,r)}});function eb(e){return new Xy({type:"transform",transform:e})}const Yl=Z("ZodOptional",(e,t)=>{Fl.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ql(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Qi(e){return new Yl({type:"optional",innerType:e})}const tb=Z("ZodExactOptional",(e,t)=>{Rg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ql(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function nb(e){return new tb({type:"optional",innerType:e})}const rb=Z("ZodNullable",(e,t)=>{Og.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Gx(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Yi(e){return new rb({type:"nullable",innerType:e})}const sb=Z("ZodDefault",(e,t)=>{Mg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Yx(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ob(e,t){return new sb({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():kl(t)}})}const ab=Z("ZodPrefault",(e,t)=>{Dg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Kx(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function ib(e,t){return new ab({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():kl(t)}})}const Kl=Z("ZodNonOptional",(e,t)=>{Lg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Qx(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function cb(e,t){return new Kl({type:"nonoptional",innerType:e,...ue(t)})}const lb=Z("ZodCatch",(e,t)=>{$g.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Jx(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function db(e,t){return new lb({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const ub=Z("ZodPipe",(e,t)=>{zg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Xx(e,r,s,o),e.in=t.in,e.out=t.out});function Ki(e,t){return new ub({type:"pipe",in:e,out:t})}const mb=Z("ZodReadonly",(e,t)=>{Fg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ey(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function pb(e){return new mb({type:"readonly",innerType:e})}const fb=Z("ZodCustom",(e,t)=>{Bg.init(e,t),Ze.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Ux(e,r)});function hb(e,t={}){return Ix(fb,e,t)}function gb(e){return Rx(e)}const $r=Ql({line1:ct().min(1,"Address line 1 is required"),line2:ct().optional(),city:ct().min(1,"City is required"),state:ct().optional(),postalCode:ct().min(1,"Postal code is required"),country:ct().min(2,"Country is required")});function xb(e){return Ql({email:e.requireEmail?ct().email("Valid email required"):ct().email("Valid email required").optional(),name:e.requireName?ct().min(1,"Name is required"):ct().optional(),phone:e.requirePhone?ct().min(6,"Phone is required"):ct().optional(),notes:ct().max(500).optional(),shippingAddress:e.requireShippingAddress?$r:$r.optional(),billingAddress:e.requireBillingAddress?$r:$r.optional(),discountCode:ct().optional(),tipAmount:Fy().min(0).optional(),shippingMethodId:ct().optional()})}const Ji={none:0,optional:1,required:2};function po(e,t){return Ji[e]>=Ji[t]?e:t}function yb(e){if(!e)return null;try{const t=JSON.parse(e);return!t||typeof t!="object"?null:t}catch{return null}}function Yr(e,t){let r=!1,s=!1;const o=new Set;let a=t.requireEmail?"required":"none",i=t.defaultMode==="none"?"none":"optional",c=t.defaultMode==="full"?"optional":"none",l=t.allowShipping&&(t.defaultMode==="shipping"||t.defaultMode==="full"),d=t.defaultMode==="full";for(const u of e){u.metadata?.shippingProfile==="digital"?r=!0:s=!0;const h=yb(u.metadata?.checkoutRequirements);h&&(h.email&&(a=po(a,h.email)),h.name&&(i=po(i,h.name)),h.phone&&(c=po(c,h.phone)),typeof h.shippingAddress=="boolean"&&(l=l||h.shippingAddress),typeof h.billingAddress=="boolean"&&(d=d||h.billingAddress));const x=u.metadata?.fulfillmentNotes;x&&o.add(x)}const m=r&&!s;return m&&(l=!1),{email:a,name:i,phone:c,shippingAddress:l,billingAddress:d,fulfillmentNotes:Array.from(o).join(" "),isDigitalOnly:m,hasPhysical:s}}const Jl=w.createContext(null);function Xl(){const{config:e}=De(),t=Mt(),r=w.useMemo(()=>({line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"}),[]),s=w.useMemo(()=>{const b=Yr(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});return xb({requireEmail:b.email==="required",requireName:b.name==="required",requirePhone:b.phone==="required",requireShippingAddress:b.shippingAddress,requireBillingAddress:b.billingAddress})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail]),[o,a]=w.useState(()=>({email:e.checkout.requireEmail??!0?"":void 0,name:"",phone:"",notes:"",shippingAddress:e.checkout.mode==="shipping"||e.checkout.mode==="full"?r:void 0,billingAddress:e.checkout.mode==="full"?r:void 0,discountCode:"",tipAmount:0,shippingMethodId:""}));w.useEffect(()=>{const b=Yr(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});a(v=>{const _={...v};return b.email==="required"&&!_.email&&(_.email=""),b.shippingAddress&&!_.shippingAddress&&(_.shippingAddress=r),b.billingAddress&&!_.billingAddress&&(_.billingAddress=r),b.shippingAddress||(_.shippingAddress=void 0),b.billingAddress||(_.billingAddress=void 0),_})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail,r]);const[i,c]=w.useState({}),[l,d]=w.useState("idle"),[m,u]=w.useState(null),[f,h]=w.useState(null),x=w.useCallback(()=>{c({}),d("idle"),u(null),h(null)},[]),p=w.useCallback((b,v)=>{a(_=>({..._,[b]:v}))},[]),y=w.useCallback(()=>{d("validating"),u(null);const b=s.safeParse(o);if(b.success)return c({}),d("idle"),{ok:!0,values:b.data};const v={};for(const _ of b.error.issues)v[_.path.join(".")]=_.message;return c(v),d("error"),u("Please fix the highlighted fields."),{ok:!1}},[s,o]),j=w.useCallback(async b=>{const v=y();if(!v.ok)return{ok:!1};d("creating_session"),u(null),h(null);const _=t.items.map(N=>({resource:N.paymentResource??N.productId,quantity:N.qty,variantId:N.variantId})),C=Yr(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1}),E=new Set;if(C.shippingAddress)for(const N of t.items){const U=N.metadata?.shippingCountries;if(U)for(const k of U.split(",")){const A=k.trim().toUpperCase();A&&E.add(A)}}const S={...E.size?{shippingCountries:Array.from(E).join(","),shipping_countries:Array.from(E).join(",")}:{}};try{const N=await e.adapter.createCheckoutSession({cart:_,customer:{email:v.values.email||void 0,name:v.values.name||void 0,phone:v.values.phone||void 0,notes:v.values.notes||void 0,shippingAddress:v.values.shippingAddress,billingAddress:v.values.billingAddress},options:{currency:e.currency,successUrl:e.checkout.successUrl,cancelUrl:e.checkout.cancelUrl,allowPromoCodes:e.checkout.allowPromoCodes,metadata:Object.keys(S).length?S:void 0,discountCode:(e.checkout.allowPromoCodes?v.values.discountCode||t.promoCode:void 0)||void 0,tipAmount:e.checkout.allowTipping&&v.values.tipAmount||void 0,shippingMethodId:e.checkout.allowShipping&&v.values.shippingMethodId||void 0,paymentMethodId:b?.paymentMethodId}});return N.kind==="redirect"?(h(N),d("redirecting"),typeof window<"u"&&window.location.assign(N.url),{ok:!0,session:N}):(h(N),d("success"),{ok:!0,session:N})}catch(N){return d("error"),u(N instanceof Error?N.message:"Checkout failed"),{ok:!1}}},[t.items,t.promoCode,e.adapter,e.checkout,e.currency,y]);return{values:o,setValues:a,setField:p,fieldErrors:i,status:l,error:m,session:f,reset:x,validate:y,createCheckoutSession:j}}function ed({children:e}){const t=Xl();return n.jsx(Jl.Provider,{value:t,children:e})}function js(){const e=w.useContext(Jl);if(!e)throw new Error("useCheckout must be used within CheckoutProvider");return e}function bb(){return Xl()}function ya(){const{config:e}=De(),[t,r]=g.useState([]),[s,o]=g.useState(!0),[a,i]=g.useState(null);return g.useEffect(()=>{let c=!1;return o(!0),i(null),e.adapter.listCategories().then(l=>{c||r(l)}).catch(l=>{c||i(l instanceof Error?l.message:"Failed to load categories")}).finally(()=>{c||o(!1)}),()=>{c=!0}},[e.adapter]),{categories:t,isLoading:s,error:a}}function Ss(e){const{config:t}=De(),[r,s]=g.useState(null),[o,a]=g.useState(!0),[i,c]=g.useState(null),l=JSON.stringify(e.filters??{});return g.useEffect(()=>{let d=!1;return a(!0),c(null),t.adapter.listProducts(e).then(m=>{d||s(m)}).catch(m=>{d||c(m instanceof Error?m.message:"Failed to load products")}).finally(()=>{d||a(!1)}),()=>{d=!0}},[t.adapter,e.category,e.search,e.sort,e.page,e.pageSize,l]),{data:r,isLoading:o,error:i}}function td(e){const{config:t}=De(),[r,s]=g.useState(null),[o,a]=g.useState(!0),[i,c]=g.useState(null);return g.useEffect(()=>{let l=!1;return a(!0),c(null),t.adapter.getProductBySlug(e).then(d=>{l||s(d)}).catch(d=>{l||c(d instanceof Error?d.message:"Failed to load product")}).finally(()=>{l||a(!1)}),()=>{l=!0}},[t.adapter,e]),{product:r,isLoading:o,error:i}}function nd(){const{config:e}=De(),[t,r]=g.useState([]),[s,o]=g.useState(!0),[a,i]=g.useState(null);return g.useEffect(()=>{let c=!1;return o(!0),i(null),e.adapter.getOrderHistory().then(l=>{c||r(l)}).catch(l=>{c||i(l instanceof Error?l.message:"Failed to load orders")}).finally(()=>{c||o(!1)}),()=>{c=!0}},[e.adapter]),{orders:t,isLoading:s,error:a}}function rd(){const{config:e}=De(),[t,r]=g.useState([]),[s,o]=g.useState(null),[a,i]=g.useState(!0),[c,l]=g.useState(null);return g.useEffect(()=>{let d=!1;async function m(){i(!0),l(null);try{const[u,f]=await Promise.all([e.adapter.listSubscriptionTiers?.()??Promise.resolve([]),e.adapter.getSubscriptionStatus?.()??Promise.resolve(null)]);if(d)return;r(u),o(f)}catch(u){if(d)return;l(u instanceof Error?u.message:"Failed to load subscriptions")}finally{d||i(!1)}}return m(),()=>{d=!0}},[e.adapter]),{tiers:t,status:s,isLoading:a,error:c}}function sd({enabled:e,customer:t}){const{config:r}=De(),[s,o]=g.useState([]),[a,i]=g.useState(!1),[c,l]=g.useState(null),d=JSON.stringify(t.shippingAddress??{});return g.useEffect(()=>{let m=!1;if(!e||!r.adapter.getShippingMethods){o([]);return}return i(!0),l(null),r.adapter.getShippingMethods({currency:r.currency,customer:t}).then(u=>{m||o(u)}).catch(u=>{m||l(u instanceof Error?u.message:"Failed to load shipping methods")}).finally(()=>{m||i(!1)}),()=>{m=!0}},[r.adapter,r.currency,e,t.email,t.name,d]),{methods:s,isLoading:a,error:c}}function or(e,...t){for(const r of t){const s=e[r];if(s)return s}}function ba(e){const t=or(e,"error","error_message","message");if(t)return{kind:"error",message:t};const r=or(e,"canceled","cancelled","cancel","canceled_at");if(r&&r!=="0"&&r!=="false")return{kind:"cancel"};const s=or(e,"orderId","order_id","demoOrderId"),o=or(e,"session_id","checkout_session_id");if(s||o)return{kind:"success",orderId:s??o};const a=(or(e,"status","checkout")??"").toLowerCase();return a==="success"?{kind:"success",orderId:s}:a==="cancel"||a==="canceled"?{kind:"cancel"}:a==="error"?{kind:"error"}:{kind:"idle"}}function vb(e){const t={};return e.forEach((r,s)=>{t[s]=r}),t}function va(){const{config:e}=De(),[t,r]=g.useState({kind:"idle"});return g.useEffect(()=>{if(typeof window>"u")return;const s=new URLSearchParams(window.location.search),o=vb(s);(async()=>{try{const a=e.adapter.resolveCheckoutReturn?await e.adapter.resolveCheckoutReturn({query:o}):ba(o);if(a.kind==="success"&&a.orderId&&e.adapter.getOrderById){const i=await e.adapter.getOrderById(a.orderId);if(i){r({kind:"success",orderId:a.orderId,order:i});return}}r(a)}catch(a){r({kind:"error",message:a instanceof Error?a.message:"Failed to resolve checkout"})}})()},[e.adapter]),t}function zo(e){if(!e)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function wb(e){const t=e.get("tags"),r=t?t.split(",").map(c=>c.trim()).filter(Boolean):void 0,s=zo(e.get("min")),o=zo(e.get("max")),a=e.get("inStock"),i=a==="1"?!0:a==="0"?!1:void 0;return{tags:r&&r.length?r:void 0,priceMin:s,priceMax:o,inStock:i}}function _b(e,t){t.tags?.length?e.set("tags",t.tags.join(",")):e.delete("tags"),typeof t.priceMin=="number"?e.set("min",String(t.priceMin)):e.delete("min"),typeof t.priceMax=="number"?e.set("max",String(t.priceMax)):e.delete("max"),typeof t.inStock=="boolean"?e.set("inStock",t.inStock?"1":"0"):e.delete("inStock")}function wa({includeCategory:e}){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),r=t.get("q")??"",s=t.get("sort")??"featured",o=zo(t.get("page"))??1,a=wb(t),i=e?t.get("cat")??void 0:void 0;return{search:r,sort:s,page:Math.max(1,Math.floor(o)),category:i,filters:a}}function _a(e,{includeCategory:t}){const r=JSON.stringify(e.filters.tags??[]);g.useEffect(()=>{if(typeof window>"u")return;const s=window.setTimeout(()=>{const o=new URL(window.location.href),a=o.searchParams;e.search.trim()?a.set("q",e.search.trim()):a.delete("q"),e.sort&&e.sort!=="featured"?a.set("sort",e.sort):a.delete("sort"),e.page&&e.page!==1?a.set("page",String(e.page)):a.delete("page"),t&&(e.category?a.set("cat",e.category):a.delete("cat")),_b(a,e.filters);const i=`${o.pathname}?${a.toString()}${o.hash}`,c=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==c&&window.history.replaceState({},"",i)},250);return()=>window.clearTimeout(s)},[t,e.category,e.page,e.search,e.sort,r,e.filters.priceMin,e.filters.priceMax,e.filters.inStock])}function Xi(e,t){return`${e}::${t??""}`}function jb(e,t){if(t&&e.variants?.length){const r=e.variants.find(s=>s.id===t);if(r)return{qty:r.inventoryQuantity,status:r.inventoryStatus}}return{qty:e.inventoryQuantity,status:e.inventoryStatus}}function Sb(e,t){const r={productId:e.productId,variantId:e.variantId,isOutOfStock:!1,exceedsAvailable:!1,isLowStock:!1};if(!t)return{...r,isOutOfStock:!0,message:"This product is no longer available"};const{qty:s,status:o}=jb(t,e.variantId);return r.availableQty=s,r.status=o,o==="out_of_stock"||typeof s=="number"&&s<=0?{...r,isOutOfStock:!0,message:"Out of stock"}:typeof s=="number"&&e.qty>s?{...r,exceedsAvailable:!0,message:s===0?"Out of stock":`Only ${s} available (you have ${e.qty} in cart)`}:o==="low"||typeof s=="number"&&s>0&&s<=5?{...r,isLowStock:!0,message:typeof s=="number"?`Only ${s} left`:"Low stock"}:r}function ja({items:e,refreshInterval:t=3e4,skip:r=!1}){const{config:s}=De(),[o,a]=g.useState(new Map),[i,c]=g.useState(!1),[l,d]=g.useState(null),m=g.useMemo(()=>{const x=new Set;for(const p of e)x.add(p.productId);return Array.from(x)},[e]),u=g.useCallback(async()=>{if(r||m.length===0){a(new Map);return}c(!0),d(null);try{const x=await Promise.all(m.map(async j=>{try{return await s.adapter.getProductBySlug(j)}catch{return null}})),p=new Map;for(const j of x)j&&(p.set(j.id,j),j.slug&&j.slug!==j.id&&p.set(j.slug,j));const y=new Map;for(const j of e){const b=Xi(j.productId,j.variantId),v=p.get(j.productId)??null;y.set(b,Sb(j,v))}a(y)}catch(x){d(x instanceof Error?x.message:"Failed to check inventory")}finally{c(!1)}},[s.adapter,e,m,r]);g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(r||t<=0||m.length===0)return;const x=setInterval(u,t);return()=>clearInterval(x)},[u,m.length,t,r]);const f=g.useCallback((x,p)=>o.get(Xi(x,p)),[o]),h=g.useMemo(()=>{for(const x of o.values())if(x.isOutOfStock||x.exceedsAvailable)return!0;return!1},[o]);return{inventory:o,isLoading:i,error:l,refresh:u,getItemInventory:f,hasIssues:h}}function kb(e,t){if(t&&e.variants?.length){const r=e.variants.find(s=>s.id===t);if(r)return{qty:r.inventoryQuantity,status:r.inventoryStatus}}return{qty:e.inventoryQuantity,status:e.inventoryStatus}}function Cb(e,t,r){if(!t)return e.titleSnapshot??"Unknown Product";const s=t.title??e.titleSnapshot??"Product";if(r&&t.variants?.length){const o=t.variants.find(a=>a.id===r);if(o?.title)return`${s} - ${o.title}`}return s}function Nb(e,t){const r=Cb(e,t,e.variantId);if(!t)return{productId:e.productId,variantId:e.variantId,title:r,requestedQty:e.qty,availableQty:0,type:"product_unavailable",message:"This product is no longer available"};const{qty:s,status:o}=kb(t,e.variantId);return o==="out_of_stock"||typeof s=="number"&&s<=0?{productId:e.productId,variantId:e.variantId,title:r,requestedQty:e.qty,availableQty:0,type:"out_of_stock",message:"This item is out of stock"}:typeof s=="number"&&e.qty>s?{productId:e.productId,variantId:e.variantId,title:r,requestedQty:e.qty,availableQty:s,type:"insufficient_stock",message:s===0?"This item is out of stock":`Only ${s} available`}:null}function od({items:e}){const{config:t}=De(),[r,s]=g.useState(null),[o,a]=g.useState(!1),[i,c]=g.useState(null),l=g.useMemo(()=>{const u=new Set;for(const f of e)u.add(f.productId);return Array.from(u)},[e]),d=g.useCallback(async()=>{if(e.length===0){const u={ok:!0,issues:[],verifiedAt:new Date};return s(u),u}a(!0),c(null);try{const u=await Promise.all(l.map(async p=>{try{return await t.adapter.getProductBySlug(p)}catch{return null}})),f=new Map;for(const p of u)p&&(f.set(p.id,p),p.slug&&p.slug!==p.id&&f.set(p.slug,p));const h=[];for(const p of e){const y=f.get(p.productId)??null,j=Nb(p,y);j&&h.push(j)}const x={ok:h.length===0,issues:h,verifiedAt:new Date};return s(x),a(!1),x}catch(u){const f=u instanceof Error?u.message:"Failed to verify inventory";c(f),a(!1);const h={ok:!1,issues:[],verifiedAt:new Date};return s(h),h}},[t.adapter,e,l]),m=g.useCallback(()=>{s(null),c(null)},[]);return{result:r,isVerifying:o,error:i,verify:d,reset:m}}function Ab({items:e,onExpiry:t,enabled:r=!0}){const[s,o]=g.useState([]),[a,i]=g.useState([]),c=g.useRef(new Set),l=g.useMemo(()=>r?e.filter(d=>d.holdId&&d.holdExpiresAt):[],[e,r]);return g.useEffect(()=>{if(!r||l.length===0){o([]),i([]);return}const d=()=>{const u=Date.now(),f=120*1e3,h=[],x=[];for(const p of l){if(!p.holdExpiresAt)continue;const y=new Date(p.holdExpiresAt),j=y.getTime()-u,b=`${p.productId}::${p.variantId??""}`;j<=0?(h.push({productId:p.productId,variantId:p.variantId}),c.current.has(b)||(c.current.add(b),t?.({productId:p.productId,variantId:p.variantId,title:p.titleSnapshot,expiredAt:y}))):j<=f&&x.push({productId:p.productId,variantId:p.variantId,expiresAt:y,remainingMs:j})}o(h),i(x)};d();const m=setInterval(d,1e4);return()=>clearInterval(m)},[r,l,t]),g.useEffect(()=>{const d=new Set(l.map(m=>`${m.productId}::${m.variantId??""}`));for(const m of c.current)d.has(m)||c.current.delete(m)},[l]),{expiringItems:a,expiredItems:s}}const Pe={relatedProducts:{mode:"most_recent",maxItems:4,layout:{layout:"large",imageCrop:"center"}},catalog:{filters:{tags:!0,priceRange:!0,inStock:!0},sort:{featured:!0,priceAsc:!0,priceDesc:!0}},checkout:{promoCodes:!0},shopLayout:{layout:"large",imageCrop:"center"},categoryLayout:{layout:"large",imageCrop:"center"},sections:{showDescription:!0,showSpecs:!0,showShipping:!0,showRelatedProducts:!0},inventory:{preCheckoutVerification:!0,holdsEnabled:!1,holdDurationMinutes:15},shopPage:{title:"Shop",description:""}};function Pb(e){return{relatedProducts:{mode:e.relatedProducts?.mode||Pe.relatedProducts.mode,maxItems:e.relatedProducts?.maxItems||Pe.relatedProducts.maxItems,layout:{layout:e.relatedProducts?.layout?.layout??Pe.relatedProducts.layout.layout,imageCrop:e.relatedProducts?.layout?.imageCrop??Pe.relatedProducts.layout.imageCrop}},catalog:{filters:{tags:e.catalog?.filters?.tags??Pe.catalog.filters.tags,priceRange:e.catalog?.filters?.priceRange??Pe.catalog.filters.priceRange,inStock:e.catalog?.filters?.inStock??Pe.catalog.filters.inStock},sort:{featured:e.catalog?.sort?.featured??Pe.catalog.sort.featured,priceAsc:e.catalog?.sort?.priceAsc??Pe.catalog.sort.priceAsc,priceDesc:e.catalog?.sort?.priceDesc??Pe.catalog.sort.priceDesc}},checkout:{promoCodes:e.checkout?.promoCodes??Pe.checkout.promoCodes},shopLayout:{layout:e.shopLayout?.layout??Pe.shopLayout.layout,imageCrop:e.shopLayout?.imageCrop??Pe.shopLayout.imageCrop},categoryLayout:{layout:e.categoryLayout?.layout??Pe.categoryLayout.layout,imageCrop:e.categoryLayout?.imageCrop??Pe.categoryLayout.imageCrop},sections:{showDescription:e.sections?.showDescription??Pe.sections.showDescription,showSpecs:e.sections?.showSpecs??Pe.sections.showSpecs,showShipping:e.sections?.showShipping??Pe.sections.showShipping,showRelatedProducts:e.sections?.showRelatedProducts??Pe.sections.showRelatedProducts},inventory:{preCheckoutVerification:e.inventory?.preCheckoutVerification??Pe.inventory.preCheckoutVerification,holdsEnabled:e.inventory?.holdsEnabled??Pe.inventory.holdsEnabled,holdDurationMinutes:e.inventory?.holdDurationMinutes??Pe.inventory.holdDurationMinutes},shopPage:{title:e.shopPage?.title??Pe.shopPage.title,description:e.shopPage?.description??Pe.shopPage.description}}}function Yn(e={}){const r=da()?.config?.adapter,[s,o]=w.useState(Pe),[a,i]=w.useState(!!r?.getStorefrontSettings);return w.useEffect(()=>{if(!r?.getStorefrontSettings){i(!1);return}let c=!1;async function l(){try{const d=await r.getStorefrontSettings();!c&&d&&o(Pb(d))}catch{}finally{c||i(!1)}}return l(),()=>{c=!0}},[r]),{settings:s,isLoading:a}}const Tb={card:!0,crypto:!0,credits:!1};function ad(){const t=da()?.config?.adapter,[r,s]=w.useState(Tb),[o,a]=w.useState(!!t?.getPaymentMethodsConfig);return w.useEffect(()=>{if(!t?.getPaymentMethodsConfig){a(!1);return}let i=!1;async function c(){try{const l=await t.getPaymentMethodsConfig();!i&&l&&s(l)}catch{}finally{i||a(!1)}}return c(),()=>{i=!0}},[t]),{config:r,isLoading:o}}const ec=new Map;function Eb(e){return e.productId?`id:${e.productId}`:e.name?`name:${e.name}`:""}function id(e={}){const{productId:t,product:r,enabled:s=!0}=e,a=da()?.config?.adapter,[i,c]=w.useState(null),[l,d]=w.useState(null),[m,u]=w.useState(!1),[f,h]=w.useState(null),x=w.useRef(0),p=w.useCallback(async()=>{const y=t?{productId:t}:r?{name:r.name,description:r.description,tags:r.tags,categoryIds:r.categoryIds}:{};if(!y.productId&&!y.name)return;if(!a?.getAIRelatedProducts){h("AI recommendations not available");return}const j=Eb(y),b=ec.get(j);if(b){c(b.relatedProductIds),d(b.reasoning),h(null);return}const v=++x.current;u(!0),h(null);try{const _=await a.getAIRelatedProducts(y);v===x.current&&(c(_.relatedProductIds),d(_.reasoning),h(null),j&&ec.set(j,_))}catch(_){if(v===x.current){const C=_ instanceof Error?_.message:"Failed to get AI recommendations";h(C),c(null),d(null)}}finally{v===x.current&&u(!1)}},[a,t,r]);return w.useEffect(()=>{s&&(!t&&!r?.name||p())},[s,t,r?.name,p]),{relatedProductIds:i,reasoning:l,isLoading:m,error:f,refetch:p}}function Me(e,t){if(!e)throw new Error(t)}function Pt(e){return typeof e=="string"&&e.trim().length>0}async function Ib(e,t={}){const r=t.pageSize??10,s=await e.listCategories();Me(Array.isArray(s),"listCategories() must return an array");for(const i of s)Me(Pt(i.id),"Category.id is required"),Me(Pt(i.slug),"Category.slug is required"),Me(Pt(i.name),"Category.name is required");const o=await e.listProducts({page:1,pageSize:r});if(Me(o&&Array.isArray(o.items),"listProducts() must return { items: Product[] }"),Me(typeof o.page=="number","listProducts().page must be a number"),Me(typeof o.pageSize=="number","listProducts().pageSize must be a number"),o.items.length>0){const i=o.items[0];Me(Pt(i.id),"Product.id is required"),Me(Pt(i.slug),"Product.slug is required"),Me(Pt(i.title),"Product.title is required"),Me(typeof i.description=="string","Product.description must be a string"),Me(Array.isArray(i.images),"Product.images must be an array"),Me(typeof i.price=="number","Product.price must be a number"),Me(Pt(i.currency),"Product.currency is required"),Me(Array.isArray(i.tags),"Product.tags must be an array"),Me(Array.isArray(i.categoryIds),"Product.categoryIds must be an array");const c=await e.getProductBySlug(i.slug);Me(c===null||Pt(c.id),"getProductBySlug() must return Product or null")}const a=await e.getOrderHistory();Me(Array.isArray(a),"getOrderHistory() must return an array");for(const i of a)Me(Pt(i.id),"Order.id is required"),Me(Pt(i.createdAt),"Order.createdAt is required"),Me(typeof i.total=="number","Order.total must be a number"),Me(Pt(i.currency),"Order.currency is required"),Me(Array.isArray(i.items),"Order.items must be an array")}function tc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Kn(...e){return t=>{let r=!1;const s=e.map(o=>{const a=tc(o,t);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let o=0;o<s.length;o++){const a=s[o];typeof a=="function"?a():tc(e[o],null)}}}}function Ie(...e){return g.useCallback(Kn(...e),e)}var Rb=Symbol.for("react.lazy"),as=g[" use ".trim().toString()];function Ob(e){return typeof e=="object"&&e!==null&&"then"in e}function cd(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Rb&&"_payload"in e&&Ob(e._payload)}function ld(e){const t=Db(e),r=g.forwardRef((s,o)=>{let{children:a,...i}=s;cd(a)&&typeof as=="function"&&(a=as(a._payload));const c=g.Children.toArray(a),l=c.find($b);if(l){const d=l.props.children,m=c.map(u=>u===l?g.Children.count(d)>1?g.Children.only(null):g.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:g.isValidElement(d)?g.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}var Mb=ld("Slot");function Db(e){const t=g.forwardRef((r,s)=>{let{children:o,...a}=r;if(cd(o)&&typeof as=="function"&&(o=as(o._payload)),g.isValidElement(o)){const i=Fb(o),c=zb(a,o.props);return o.type!==g.Fragment&&(c.ref=s?Kn(s,i):i),g.cloneElement(o,c)}return g.Children.count(o)>1?g.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Lb=Symbol("radix.slottable");function $b(e){return g.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Lb}function zb(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function Fb(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function dd(e){var t,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(r=dd(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function ud(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=dd(e))&&(s&&(s+=" "),s+=t);return s}const nc=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,rc=ud,Sa=(e,t)=>r=>{var s;if(t?.variants==null)return rc(e,r?.class,r?.className);const{variants:o,defaultVariants:a}=t,i=Object.keys(o).map(d=>{const m=r?.[d],u=a?.[d];if(m===null)return null;const f=nc(m)||nc(u);return o[d][f]}),c=r&&Object.entries(r).reduce((d,m)=>{let[u,f]=m;return f===void 0||(d[u]=f),d},{}),l=t==null||(s=t.compoundVariants)===null||s===void 0?void 0:s.reduce((d,m)=>{let{class:u,className:f,...h}=m;return Object.entries(h).every(x=>{let[p,y]=x;return Array.isArray(y)?y.includes({...a,...c}[p]):{...a,...c}[p]===y})?[...d,u,f]:d},[]);return rc(e,i,l,r?.class,r?.className)},Bb=(e,t)=>{const r=new Array(e.length+t.length);for(let s=0;s<e.length;s++)r[s]=e[s];for(let s=0;s<t.length;s++)r[e.length+s]=t[s];return r},Ub=(e,t)=>({classGroupId:e,validator:t}),md=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),is="-",sc=[],Wb="arbitrary..",Vb=e=>{const t=qb(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return Hb(i);const c=i.split(is),l=c[0]===""&&c.length>1?1:0;return pd(c,l,t)},getConflictingClassGroupIds:(i,c)=>{if(c){const l=s[i],d=r[i];return l?d?Bb(d,l):l:d||sc}return r[i]||sc}}},pd=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],a=r.nextPart.get(o);if(a){const d=pd(e,t+1,a);if(d)return d}const i=r.validators;if(i===null)return;const c=t===0?e.join(is):e.slice(t).join(is),l=i.length;for(let d=0;d<l;d++){const m=i[d];if(m.validator(c))return m.classGroupId}},Hb=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),s=t.slice(0,r);return s?Wb+s:void 0})(),qb=e=>{const{theme:t,classGroups:r}=e;return Zb(r,t)},Zb=(e,t)=>{const r=md();for(const s in e){const o=e[s];ka(o,r,s,t)}return r},ka=(e,t,r,s)=>{const o=e.length;for(let a=0;a<o;a++){const i=e[a];Gb(i,t,r,s)}},Gb=(e,t,r,s)=>{if(typeof e=="string"){Qb(e,t,r);return}if(typeof e=="function"){Yb(e,t,r,s);return}Kb(e,t,r,s)},Qb=(e,t,r)=>{const s=e===""?t:fd(t,e);s.classGroupId=r},Yb=(e,t,r,s)=>{if(Jb(e)){ka(e(s),t,r,s);return}t.validators===null&&(t.validators=[]),t.validators.push(Ub(r,e))},Kb=(e,t,r,s)=>{const o=Object.entries(e),a=o.length;for(let i=0;i<a;i++){const[c,l]=o[i];ka(l,fd(t,c),r,s)}},fd=(e,t)=>{let r=e;const s=t.split(is),o=s.length;for(let a=0;a<o;a++){const i=s[a];let c=r.nextPart.get(i);c||(c=md(),r.nextPart.set(i,c)),r=c}return r},Jb=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Xb=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),s=Object.create(null);const o=(a,i)=>{r[a]=i,t++,t>e&&(t=0,s=r,r=Object.create(null))};return{get(a){let i=r[a];if(i!==void 0)return i;if((i=s[a])!==void 0)return o(a,i),i},set(a,i){a in r?r[a]=i:o(a,i)}}},Fo="!",oc=":",ev=[],ac=(e,t,r,s,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),tv=e=>{const{prefix:t,experimentalParseClassName:r}=e;let s=o=>{const a=[];let i=0,c=0,l=0,d;const m=o.length;for(let p=0;p<m;p++){const y=o[p];if(i===0&&c===0){if(y===oc){a.push(o.slice(l,p)),l=p+1;continue}if(y==="/"){d=p;continue}}y==="["?i++:y==="]"?i--:y==="("?c++:y===")"&&c--}const u=a.length===0?o:o.slice(l);let f=u,h=!1;u.endsWith(Fo)?(f=u.slice(0,-1),h=!0):u.startsWith(Fo)&&(f=u.slice(1),h=!0);const x=d&&d>l?d-l:void 0;return ac(a,h,f,x)};if(t){const o=t+oc,a=s;s=i=>i.startsWith(o)?a(i.slice(o.length)):ac(ev,!1,i,void 0,!0)}if(r){const o=s;s=a=>r({className:a,parseClassName:o})}return s},nv=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,s)=>{t.set(r,1e6+s)}),r=>{const s=[];let o=[];for(let a=0;a<r.length;a++){const i=r[a],c=i[0]==="[",l=t.has(i);c||l?(o.length>0&&(o.sort(),s.push(...o),o=[]),s.push(i)):o.push(i)}return o.length>0&&(o.sort(),s.push(...o)),s}},rv=e=>({cache:Xb(e.cacheSize),parseClassName:tv(e),sortModifiers:nv(e),...Vb(e)}),sv=/\s+/,ov=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:a}=t,i=[],c=e.trim().split(sv);let l="";for(let d=c.length-1;d>=0;d-=1){const m=c[d],{isExternal:u,modifiers:f,hasImportantModifier:h,baseClassName:x,maybePostfixModifierPosition:p}=r(m);if(u){l=m+(l.length>0?" "+l:l);continue}let y=!!p,j=s(y?x.substring(0,p):x);if(!j){if(!y){l=m+(l.length>0?" "+l:l);continue}if(j=s(x),!j){l=m+(l.length>0?" "+l:l);continue}y=!1}const b=f.length===0?"":f.length===1?f[0]:a(f).join(":"),v=h?b+Fo:b,_=v+j;if(i.indexOf(_)>-1)continue;i.push(_);const C=o(j,y);for(let E=0;E<C.length;++E){const S=C[E];i.push(v+S)}l=m+(l.length>0?" "+l:l)}return l},av=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=hd(r))&&(o&&(o+=" "),o+=s);return o},hd=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=hd(e[s]))&&(r&&(r+=" "),r+=t);return r},iv=(e,...t)=>{let r,s,o,a;const i=l=>{const d=t.reduce((m,u)=>u(m),e());return r=rv(d),s=r.cache.get,o=r.cache.set,a=c,c(l)},c=l=>{const d=s(l);if(d)return d;const m=ov(l,r);return o(l,m),m};return a=i,(...l)=>a(av(...l))},cv=[],Ke=e=>{const t=r=>r[e]||cv;return t.isThemeGetter=!0,t},gd=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,xd=/^\((?:(\w[\w-]*):)?(.+)\)$/i,lv=/^\d+\/\d+$/,dv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,uv=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,mv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,pv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,fv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ln=e=>lv.test(e),ye=e=>!!e&&!Number.isNaN(Number(e)),sn=e=>!!e&&Number.isInteger(Number(e)),fo=e=>e.endsWith("%")&&ye(e.slice(0,-1)),en=e=>dv.test(e),hv=()=>!0,gv=e=>uv.test(e)&&!mv.test(e),yd=()=>!1,xv=e=>pv.test(e),yv=e=>fv.test(e),bv=e=>!re(e)&&!se(e),vv=e=>Jn(e,wd,yd),re=e=>gd.test(e),bn=e=>Jn(e,_d,gv),ho=e=>Jn(e,kv,ye),ic=e=>Jn(e,bd,yd),wv=e=>Jn(e,vd,yv),zr=e=>Jn(e,jd,xv),se=e=>xd.test(e),ar=e=>Xn(e,_d),_v=e=>Xn(e,Cv),cc=e=>Xn(e,bd),jv=e=>Xn(e,wd),Sv=e=>Xn(e,vd),Fr=e=>Xn(e,jd,!0),Jn=(e,t,r)=>{const s=gd.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},Xn=(e,t,r=!1)=>{const s=xd.exec(e);return s?s[1]?t(s[1]):r:!1},bd=e=>e==="position"||e==="percentage",vd=e=>e==="image"||e==="url",wd=e=>e==="length"||e==="size"||e==="bg-size",_d=e=>e==="length",kv=e=>e==="number",Cv=e=>e==="family-name",jd=e=>e==="shadow",Nv=()=>{const e=Ke("color"),t=Ke("font"),r=Ke("text"),s=Ke("font-weight"),o=Ke("tracking"),a=Ke("leading"),i=Ke("breakpoint"),c=Ke("container"),l=Ke("spacing"),d=Ke("radius"),m=Ke("shadow"),u=Ke("inset-shadow"),f=Ke("text-shadow"),h=Ke("drop-shadow"),x=Ke("blur"),p=Ke("perspective"),y=Ke("aspect"),j=Ke("ease"),b=Ke("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],_=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],C=()=>[..._(),se,re],E=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],N=()=>[se,re,l],U=()=>[Ln,"full","auto",...N()],k=()=>[sn,"none","subgrid",se,re],A=()=>["auto",{span:["full",sn,se,re]},sn,se,re],P=()=>[sn,"auto",se,re],D=()=>["auto","min","max","fr",se,re],z=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],L=()=>["start","end","center","stretch","center-safe","end-safe"],O=()=>["auto",...N()],M=()=>[Ln,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...N()],R=()=>[e,se,re],W=()=>[..._(),cc,ic,{position:[se,re]}],T=()=>["no-repeat",{repeat:["","x","y","space","round"]}],V=()=>["auto","cover","contain",jv,vv,{size:[se,re]}],ee=()=>[fo,ar,bn],B=()=>["","none","full",d,se,re],Y=()=>["",ye,ar,bn],J=()=>["solid","dashed","dotted","double"],ge=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],F=()=>[ye,fo,cc,ic],K=()=>["","none",x,se,re],me=()=>["none",ye,se,re],q=()=>["none",ye,se,re],te=()=>[ye,se,re],ce=()=>[Ln,"full",...N()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[en],breakpoint:[en],color:[hv],container:[en],"drop-shadow":[en],ease:["in","out","in-out"],font:[bv],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[en],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[en],shadow:[en],spacing:["px",ye],text:[en],"text-shadow":[en],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ln,re,se,y]}],container:["container"],columns:[{columns:[ye,re,se,c]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:C()}],overflow:[{overflow:E()}],"overflow-x":[{"overflow-x":E()}],"overflow-y":[{"overflow-y":E()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{start:U()}],end:[{end:U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[sn,"auto",se,re]}],basis:[{basis:[Ln,"full","auto",c,...N()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ye,Ln,"auto","initial","none",re]}],grow:[{grow:["",ye,se,re]}],shrink:[{shrink:["",ye,se,re]}],order:[{order:[sn,"first","last","none",se,re]}],"grid-cols":[{"grid-cols":k()}],"col-start-end":[{col:A()}],"col-start":[{"col-start":P()}],"col-end":[{"col-end":P()}],"grid-rows":[{"grid-rows":k()}],"row-start-end":[{row:A()}],"row-start":[{"row-start":P()}],"row-end":[{"row-end":P()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":D()}],"auto-rows":[{"auto-rows":D()}],gap:[{gap:N()}],"gap-x":[{"gap-x":N()}],"gap-y":[{"gap-y":N()}],"justify-content":[{justify:[...z(),"normal"]}],"justify-items":[{"justify-items":[...L(),"normal"]}],"justify-self":[{"justify-self":["auto",...L()]}],"align-content":[{content:["normal",...z()]}],"align-items":[{items:[...L(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...L(),{baseline:["","last"]}]}],"place-content":[{"place-content":z()}],"place-items":[{"place-items":[...L(),"baseline"]}],"place-self":[{"place-self":["auto",...L()]}],p:[{p:N()}],px:[{px:N()}],py:[{py:N()}],ps:[{ps:N()}],pe:[{pe:N()}],pt:[{pt:N()}],pr:[{pr:N()}],pb:[{pb:N()}],pl:[{pl:N()}],m:[{m:O()}],mx:[{mx:O()}],my:[{my:O()}],ms:[{ms:O()}],me:[{me:O()}],mt:[{mt:O()}],mr:[{mr:O()}],mb:[{mb:O()}],ml:[{ml:O()}],"space-x":[{"space-x":N()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":N()}],"space-y-reverse":["space-y-reverse"],size:[{size:M()}],w:[{w:[c,"screen",...M()]}],"min-w":[{"min-w":[c,"screen","none",...M()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[i]},...M()]}],h:[{h:["screen","lh",...M()]}],"min-h":[{"min-h":["screen","lh","none",...M()]}],"max-h":[{"max-h":["screen","lh",...M()]}],"font-size":[{text:["base",r,ar,bn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,se,ho]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",fo,re]}],"font-family":[{font:[_v,re,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,se,re]}],"line-clamp":[{"line-clamp":[ye,"none",se,ho]}],leading:[{leading:[a,...N()]}],"list-image":[{"list-image":["none",se,re]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",se,re]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:R()}],"text-color":[{text:R()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[ye,"from-font","auto",se,bn]}],"text-decoration-color":[{decoration:R()}],"underline-offset":[{"underline-offset":[ye,"auto",se,re]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:N()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",se,re]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",se,re]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:W()}],"bg-repeat":[{bg:T()}],"bg-size":[{bg:V()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},sn,se,re],radial:["",se,re],conic:[sn,se,re]},Sv,wv]}],"bg-color":[{bg:R()}],"gradient-from-pos":[{from:ee()}],"gradient-via-pos":[{via:ee()}],"gradient-to-pos":[{to:ee()}],"gradient-from":[{from:R()}],"gradient-via":[{via:R()}],"gradient-to":[{to:R()}],rounded:[{rounded:B()}],"rounded-s":[{"rounded-s":B()}],"rounded-e":[{"rounded-e":B()}],"rounded-t":[{"rounded-t":B()}],"rounded-r":[{"rounded-r":B()}],"rounded-b":[{"rounded-b":B()}],"rounded-l":[{"rounded-l":B()}],"rounded-ss":[{"rounded-ss":B()}],"rounded-se":[{"rounded-se":B()}],"rounded-ee":[{"rounded-ee":B()}],"rounded-es":[{"rounded-es":B()}],"rounded-tl":[{"rounded-tl":B()}],"rounded-tr":[{"rounded-tr":B()}],"rounded-br":[{"rounded-br":B()}],"rounded-bl":[{"rounded-bl":B()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:R()}],"border-color-x":[{"border-x":R()}],"border-color-y":[{"border-y":R()}],"border-color-s":[{"border-s":R()}],"border-color-e":[{"border-e":R()}],"border-color-t":[{"border-t":R()}],"border-color-r":[{"border-r":R()}],"border-color-b":[{"border-b":R()}],"border-color-l":[{"border-l":R()}],"divide-color":[{divide:R()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ye,se,re]}],"outline-w":[{outline:["",ye,ar,bn]}],"outline-color":[{outline:R()}],shadow:[{shadow:["","none",m,Fr,zr]}],"shadow-color":[{shadow:R()}],"inset-shadow":[{"inset-shadow":["none",u,Fr,zr]}],"inset-shadow-color":[{"inset-shadow":R()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:R()}],"ring-offset-w":[{"ring-offset":[ye,bn]}],"ring-offset-color":[{"ring-offset":R()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":R()}],"text-shadow":[{"text-shadow":["none",f,Fr,zr]}],"text-shadow-color":[{"text-shadow":R()}],opacity:[{opacity:[ye,se,re]}],"mix-blend":[{"mix-blend":[...ge(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ge()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":F()}],"mask-image-linear-to-pos":[{"mask-linear-to":F()}],"mask-image-linear-from-color":[{"mask-linear-from":R()}],"mask-image-linear-to-color":[{"mask-linear-to":R()}],"mask-image-t-from-pos":[{"mask-t-from":F()}],"mask-image-t-to-pos":[{"mask-t-to":F()}],"mask-image-t-from-color":[{"mask-t-from":R()}],"mask-image-t-to-color":[{"mask-t-to":R()}],"mask-image-r-from-pos":[{"mask-r-from":F()}],"mask-image-r-to-pos":[{"mask-r-to":F()}],"mask-image-r-from-color":[{"mask-r-from":R()}],"mask-image-r-to-color":[{"mask-r-to":R()}],"mask-image-b-from-pos":[{"mask-b-from":F()}],"mask-image-b-to-pos":[{"mask-b-to":F()}],"mask-image-b-from-color":[{"mask-b-from":R()}],"mask-image-b-to-color":[{"mask-b-to":R()}],"mask-image-l-from-pos":[{"mask-l-from":F()}],"mask-image-l-to-pos":[{"mask-l-to":F()}],"mask-image-l-from-color":[{"mask-l-from":R()}],"mask-image-l-to-color":[{"mask-l-to":R()}],"mask-image-x-from-pos":[{"mask-x-from":F()}],"mask-image-x-to-pos":[{"mask-x-to":F()}],"mask-image-x-from-color":[{"mask-x-from":R()}],"mask-image-x-to-color":[{"mask-x-to":R()}],"mask-image-y-from-pos":[{"mask-y-from":F()}],"mask-image-y-to-pos":[{"mask-y-to":F()}],"mask-image-y-from-color":[{"mask-y-from":R()}],"mask-image-y-to-color":[{"mask-y-to":R()}],"mask-image-radial":[{"mask-radial":[se,re]}],"mask-image-radial-from-pos":[{"mask-radial-from":F()}],"mask-image-radial-to-pos":[{"mask-radial-to":F()}],"mask-image-radial-from-color":[{"mask-radial-from":R()}],"mask-image-radial-to-color":[{"mask-radial-to":R()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":_()}],"mask-image-conic-pos":[{"mask-conic":[ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":F()}],"mask-image-conic-to-pos":[{"mask-conic-to":F()}],"mask-image-conic-from-color":[{"mask-conic-from":R()}],"mask-image-conic-to-color":[{"mask-conic-to":R()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:W()}],"mask-repeat":[{mask:T()}],"mask-size":[{mask:V()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",se,re]}],filter:[{filter:["","none",se,re]}],blur:[{blur:K()}],brightness:[{brightness:[ye,se,re]}],contrast:[{contrast:[ye,se,re]}],"drop-shadow":[{"drop-shadow":["","none",h,Fr,zr]}],"drop-shadow-color":[{"drop-shadow":R()}],grayscale:[{grayscale:["",ye,se,re]}],"hue-rotate":[{"hue-rotate":[ye,se,re]}],invert:[{invert:["",ye,se,re]}],saturate:[{saturate:[ye,se,re]}],sepia:[{sepia:["",ye,se,re]}],"backdrop-filter":[{"backdrop-filter":["","none",se,re]}],"backdrop-blur":[{"backdrop-blur":K()}],"backdrop-brightness":[{"backdrop-brightness":[ye,se,re]}],"backdrop-contrast":[{"backdrop-contrast":[ye,se,re]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ye,se,re]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ye,se,re]}],"backdrop-invert":[{"backdrop-invert":["",ye,se,re]}],"backdrop-opacity":[{"backdrop-opacity":[ye,se,re]}],"backdrop-saturate":[{"backdrop-saturate":[ye,se,re]}],"backdrop-sepia":[{"backdrop-sepia":["",ye,se,re]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":N()}],"border-spacing-x":[{"border-spacing-x":N()}],"border-spacing-y":[{"border-spacing-y":N()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",se,re]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ye,"initial",se,re]}],ease:[{ease:["linear","initial",j,se,re]}],delay:[{delay:[ye,se,re]}],animate:[{animate:["none",b,se,re]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,se,re]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:me()}],"rotate-x":[{"rotate-x":me()}],"rotate-y":[{"rotate-y":me()}],"rotate-z":[{"rotate-z":me()}],scale:[{scale:q()}],"scale-x":[{"scale-x":q()}],"scale-y":[{"scale-y":q()}],"scale-z":[{"scale-z":q()}],"scale-3d":["scale-3d"],skew:[{skew:te()}],"skew-x":[{"skew-x":te()}],"skew-y":[{"skew-y":te()}],transform:[{transform:[se,re,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ce()}],"translate-x":[{"translate-x":ce()}],"translate-y":[{"translate-y":ce()}],"translate-z":[{"translate-z":ce()}],"translate-none":["translate-none"],accent:[{accent:R()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:R()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",se,re]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":N()}],"scroll-mx":[{"scroll-mx":N()}],"scroll-my":[{"scroll-my":N()}],"scroll-ms":[{"scroll-ms":N()}],"scroll-me":[{"scroll-me":N()}],"scroll-mt":[{"scroll-mt":N()}],"scroll-mr":[{"scroll-mr":N()}],"scroll-mb":[{"scroll-mb":N()}],"scroll-ml":[{"scroll-ml":N()}],"scroll-p":[{"scroll-p":N()}],"scroll-px":[{"scroll-px":N()}],"scroll-py":[{"scroll-py":N()}],"scroll-ps":[{"scroll-ps":N()}],"scroll-pe":[{"scroll-pe":N()}],"scroll-pt":[{"scroll-pt":N()}],"scroll-pr":[{"scroll-pr":N()}],"scroll-pb":[{"scroll-pb":N()}],"scroll-pl":[{"scroll-pl":N()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",se,re]}],fill:[{fill:["none",...R()]}],"stroke-w":[{stroke:[ye,ar,bn,ho]}],stroke:[{stroke:["none",...R()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Av=iv(Nv);function H(...e){return Av(ud(e))}const Pv=Sa("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-neutral-50/20",{variants:{variant:{default:"bg-neutral-900 text-neutral-50 hover:bg-neutral-900/90 dark:bg-neutral-50 dark:text-neutral-900 dark:hover:bg-neutral-50/90",secondary:"bg-neutral-100 text-neutral-900 hover:bg-neutral-100/80 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800/80",outline:"border border-neutral-200 bg-transparent text-neutral-900 hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800",ghost:"bg-transparent text-neutral-900 hover:bg-neutral-100 dark:text-neutral-50 dark:hover:bg-neutral-800",destructive:"bg-red-600 text-neutral-50 hover:bg-red-600/90 dark:bg-red-500 dark:hover:bg-red-500/90",link:"bg-transparent text-neutral-900 underline-offset-4 hover:underline dark:text-neutral-50"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-6",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ie=g.forwardRef(({className:e,variant:t,size:r,asChild:s,...o},a)=>{const i=s?Mb:"button";return n.jsx(i,{className:H(Pv({variant:t,size:r}),e),ref:a,...o})});ie.displayName="Button";const Tv=Sa("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors",{variants:{variant:{default:"border-transparent bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900",secondary:"border-transparent bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",outline:"border-neutral-200 text-neutral-900 dark:border-neutral-800 dark:text-neutral-50"}},defaultVariants:{variant:"secondary"}});function wn({className:e,variant:t,...r}){return n.jsx("div",{className:H(Tv({variant:t}),e),...r})}const It=g.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("rounded-xl border border-neutral-200 bg-white text-neutral-950 shadow-sm dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",e),...t}));It.displayName="Card";const vr=g.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex flex-col space-y-1.5 p-6",e),...t}));vr.displayName="CardHeader";const wr=g.forwardRef(({className:e,...t},r)=>n.jsx("h3",{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));wr.displayName="CardTitle";const Sd=g.forwardRef(({className:e,...t},r)=>n.jsx("p",{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));Sd.displayName="CardDescription";const qt=g.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("p-6 pt-0",e),...t}));qt.displayName="CardContent";const kd=g.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex items-center p-6 pt-0",e),...t}));kd.displayName="CardFooter";const He=g.forwardRef(({className:e,...t},r)=>n.jsx("input",{ref:r,className:H("flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-50/20",e),...t}));He.displayName="Input";const dt=g.forwardRef(({className:e,...t},r)=>n.jsx("label",{ref:r,className:H("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",e),...t}));dt.displayName="Label";var Ev=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Iv=Ev.reduce((e,t)=>{const r=ld(`Primitive.${t}`),s=g.forwardRef((o,a)=>{const{asChild:i,...c}=o,l=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(l,{...c,ref:a})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{}),Rv="Separator",lc="horizontal",Ov=["horizontal","vertical"],Cd=g.forwardRef((e,t)=>{const{decorative:r,orientation:s=lc,...o}=e,a=Mv(s)?s:lc,c=r?{role:"none"}:{"aria-orientation":a==="vertical"?a:void 0,role:"separator"};return n.jsx(Iv.div,{"data-orientation":a,...c,...o,ref:t})});Cd.displayName=Rv;function Mv(e){return Ov.includes(e)}var Nd=Cd;const St=g.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...s},o)=>n.jsx(Nd,{ref:o,decorative:r,orientation:t,className:H("shrink-0 bg-neutral-200 dark:bg-neutral-800",t==="horizontal"?"h-px w-full":"h-full w-px",e),...s}));St.displayName=Nd.displayName;function ze({className:e,...t}){return n.jsx("div",{className:H("animate-pulse rounded-md bg-neutral-100 dark:bg-neutral-800",e),...t})}function dc(e,[t,r]){return Math.min(r,Math.max(t,e))}function je(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e?.(o),r===!1||!o.defaultPrevented)return t?.(o)}}function Dv(e,t){const r=g.createContext(t),s=a=>{const{children:i,...c}=a,l=g.useMemo(()=>c,Object.values(c));return n.jsx(r.Provider,{value:l,children:i})};s.displayName=e+"Provider";function o(a){const i=g.useContext(r);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${a}\` must be used within \`${e}\``)}return[s,o]}function pn(e,t=[]){let r=[];function s(a,i){const c=g.createContext(i),l=r.length;r=[...r,i];const d=u=>{const{scope:f,children:h,...x}=u,p=f?.[e]?.[l]||c,y=g.useMemo(()=>x,Object.values(x));return n.jsx(p.Provider,{value:y,children:h})};d.displayName=a+"Provider";function m(u,f){const h=f?.[e]?.[l]||c,x=g.useContext(h);if(x)return x;if(i!==void 0)return i;throw new Error(`\`${u}\` must be used within \`${a}\``)}return[d,m]}const o=()=>{const a=r.map(i=>g.createContext(i));return function(c){const l=c?.[e]||a;return g.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return o.scopeName=e,[s,Lv(o,...t)]}function Lv(...e){const t=e[0];if(e.length===1)return t;const r=()=>{const s=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(a){const i=s.reduce((c,{useScope:l,scopeName:d})=>{const u=l(a)[`__scope${d}`];return{...c,...u}},{});return g.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return r.scopeName=t.scopeName,r}function uc(e){const t=$v(e),r=g.forwardRef((s,o)=>{const{children:a,...i}=s,c=g.Children.toArray(a),l=c.find(Fv);if(l){const d=l.props.children,m=c.map(u=>u===l?g.Children.count(d)>1?g.Children.only(null):g.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:g.isValidElement(d)?g.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function $v(e){const t=g.forwardRef((r,s)=>{const{children:o,...a}=r;if(g.isValidElement(o)){const i=Uv(o),c=Bv(a,o.props);return o.type!==g.Fragment&&(c.ref=s?Kn(s,i):i),g.cloneElement(o,c)}return g.Children.count(o)>1?g.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var zv=Symbol("radix.slottable");function Fv(e){return g.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===zv}function Bv(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function Uv(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function Ca(e){const t=e+"CollectionProvider",[r,s]=pn(t),[o,a]=r(t,{collectionRef:{current:null},itemMap:new Map}),i=p=>{const{scope:y,children:j}=p,b=w.useRef(null),v=w.useRef(new Map).current;return n.jsx(o,{scope:y,itemMap:v,collectionRef:b,children:j})};i.displayName=t;const c=e+"CollectionSlot",l=uc(c),d=w.forwardRef((p,y)=>{const{scope:j,children:b}=p,v=a(c,j),_=Ie(y,v.collectionRef);return n.jsx(l,{ref:_,children:b})});d.displayName=c;const m=e+"CollectionItemSlot",u="data-radix-collection-item",f=uc(m),h=w.forwardRef((p,y)=>{const{scope:j,children:b,...v}=p,_=w.useRef(null),C=Ie(y,_),E=a(m,j);return w.useEffect(()=>(E.itemMap.set(_,{ref:_,...v}),()=>void E.itemMap.delete(_))),n.jsx(f,{[u]:"",ref:C,children:b})});h.displayName=m;function x(p){const y=a(e+"CollectionConsumer",p);return w.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const v=Array.from(b.querySelectorAll(`[${u}]`));return Array.from(y.itemMap.values()).sort((E,S)=>v.indexOf(E.ref.current)-v.indexOf(S.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:d,ItemSlot:h},x,s]}var Wv=g.createContext(void 0);function ks(e){const t=g.useContext(Wv);return e||t||"ltr"}function Vv(e){const t=Hv(e),r=g.forwardRef((s,o)=>{const{children:a,...i}=s,c=g.Children.toArray(a),l=c.find(Zv);if(l){const d=l.props.children,m=c.map(u=>u===l?g.Children.count(d)>1?g.Children.only(null):g.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:g.isValidElement(d)?g.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function Hv(e){const t=g.forwardRef((r,s)=>{const{children:o,...a}=r;if(g.isValidElement(o)){const i=Qv(o),c=Gv(a,o.props);return o.type!==g.Fragment&&(c.ref=s?Kn(s,i):i),g.cloneElement(o,c)}return g.Children.count(o)>1?g.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var qv=Symbol("radix.slottable");function Zv(e){return g.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===qv}function Gv(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function Qv(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Yv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ve=Yv.reduce((e,t)=>{const r=Vv(`Primitive.${t}`),s=g.forwardRef((o,a)=>{const{asChild:i,...c}=o,l=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(l,{...c,ref:a})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{});function Kv(e,t){e&&ys.flushSync(()=>e.dispatchEvent(t))}function an(e){const t=g.useRef(e);return g.useEffect(()=>{t.current=e}),g.useMemo(()=>(...r)=>t.current?.(...r),[])}function Jv(e,t=globalThis?.document){const r=an(e);g.useEffect(()=>{const s=o=>{o.key==="Escape"&&r(o)};return t.addEventListener("keydown",s,{capture:!0}),()=>t.removeEventListener("keydown",s,{capture:!0})},[r,t])}var Xv="DismissableLayer",Bo="dismissableLayer.update",e0="dismissableLayer.pointerDownOutside",t0="dismissableLayer.focusOutside",mc,Ad=g.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Na=g.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:i,onDismiss:c,...l}=e,d=g.useContext(Ad),[m,u]=g.useState(null),f=m?.ownerDocument??globalThis?.document,[,h]=g.useState({}),x=Ie(t,S=>u(S)),p=Array.from(d.layers),[y]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),j=p.indexOf(y),b=m?p.indexOf(m):-1,v=d.layersWithOutsidePointerEventsDisabled.size>0,_=b>=j,C=s0(S=>{const N=S.target,U=[...d.branches].some(k=>k.contains(N));!_||U||(o?.(S),i?.(S),S.defaultPrevented||c?.())},f),E=o0(S=>{const N=S.target;[...d.branches].some(k=>k.contains(N))||(a?.(S),i?.(S),S.defaultPrevented||c?.())},f);return Jv(S=>{b===d.layers.size-1&&(s?.(S),!S.defaultPrevented&&c&&(S.preventDefault(),c()))},f),g.useEffect(()=>{if(m)return r&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(mc=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(m)),d.layers.add(m),pc(),()=>{r&&d.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=mc)}},[m,f,r,d]),g.useEffect(()=>()=>{m&&(d.layers.delete(m),d.layersWithOutsidePointerEventsDisabled.delete(m),pc())},[m,d]),g.useEffect(()=>{const S=()=>h({});return document.addEventListener(Bo,S),()=>document.removeEventListener(Bo,S)},[]),n.jsx(ve.div,{...l,ref:x,style:{pointerEvents:v?_?"auto":"none":void 0,...e.style},onFocusCapture:je(e.onFocusCapture,E.onFocusCapture),onBlurCapture:je(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:je(e.onPointerDownCapture,C.onPointerDownCapture)})});Na.displayName=Xv;var n0="DismissableLayerBranch",r0=g.forwardRef((e,t)=>{const r=g.useContext(Ad),s=g.useRef(null),o=Ie(t,s);return g.useEffect(()=>{const a=s.current;if(a)return r.branches.add(a),()=>{r.branches.delete(a)}},[r.branches]),n.jsx(ve.div,{...e,ref:o})});r0.displayName=n0;function s0(e,t=globalThis?.document){const r=an(e),s=g.useRef(!1),o=g.useRef(()=>{});return g.useEffect(()=>{const a=c=>{if(c.target&&!s.current){let l=function(){Pd(e0,r,d,{discrete:!0})};const d={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);s.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",a)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",a),t.removeEventListener("click",o.current)}},[t,r]),{onPointerDownCapture:()=>s.current=!0}}function o0(e,t=globalThis?.document){const r=an(e),s=g.useRef(!1);return g.useEffect(()=>{const o=a=>{a.target&&!s.current&&Pd(t0,r,{originalEvent:a},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,r]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function pc(){const e=new CustomEvent(Bo);document.dispatchEvent(e)}function Pd(e,t,r,{discrete:s}){const o=r.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&o.addEventListener(e,t,{once:!0}),s?Kv(o,a):o.dispatchEvent(a)}var go=0;function Td(){g.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??fc()),document.body.insertAdjacentElement("beforeend",e[1]??fc()),go++,()=>{go===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),go--}},[])}function fc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var xo="focusScope.autoFocusOnMount",yo="focusScope.autoFocusOnUnmount",hc={bubbles:!1,cancelable:!0},a0="FocusScope",Aa=g.forwardRef((e,t)=>{const{loop:r=!1,trapped:s=!1,onMountAutoFocus:o,onUnmountAutoFocus:a,...i}=e,[c,l]=g.useState(null),d=an(o),m=an(a),u=g.useRef(null),f=Ie(t,p=>l(p)),h=g.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;g.useEffect(()=>{if(s){let p=function(v){if(h.paused||!c)return;const _=v.target;c.contains(_)?u.current=_:on(u.current,{select:!0})},y=function(v){if(h.paused||!c)return;const _=v.relatedTarget;_!==null&&(c.contains(_)||on(u.current,{select:!0}))},j=function(v){if(document.activeElement===document.body)for(const C of v)C.removedNodes.length>0&&on(c)};document.addEventListener("focusin",p),document.addEventListener("focusout",y);const b=new MutationObserver(j);return c&&b.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",y),b.disconnect()}}},[s,c,h.paused]),g.useEffect(()=>{if(c){xc.add(h);const p=document.activeElement;if(!c.contains(p)){const j=new CustomEvent(xo,hc);c.addEventListener(xo,d),c.dispatchEvent(j),j.defaultPrevented||(i0(m0(Ed(c)),{select:!0}),document.activeElement===p&&on(c))}return()=>{c.removeEventListener(xo,d),setTimeout(()=>{const j=new CustomEvent(yo,hc);c.addEventListener(yo,m),c.dispatchEvent(j),j.defaultPrevented||on(p??document.body,{select:!0}),c.removeEventListener(yo,m),xc.remove(h)},0)}}},[c,d,m,h]);const x=g.useCallback(p=>{if(!r&&!s||h.paused)return;const y=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,j=document.activeElement;if(y&&j){const b=p.currentTarget,[v,_]=c0(b);v&&_?!p.shiftKey&&j===_?(p.preventDefault(),r&&on(v,{select:!0})):p.shiftKey&&j===v&&(p.preventDefault(),r&&on(_,{select:!0})):j===b&&p.preventDefault()}},[r,s,h.paused]);return n.jsx(ve.div,{tabIndex:-1,...i,ref:f,onKeyDown:x})});Aa.displayName=a0;function i0(e,{select:t=!1}={}){const r=document.activeElement;for(const s of e)if(on(s,{select:t}),document.activeElement!==r)return}function c0(e){const t=Ed(e),r=gc(t,e),s=gc(t.reverse(),e);return[r,s]}function Ed(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const o=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||o?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function gc(e,t){for(const r of e)if(!l0(r,{upTo:t}))return r}function l0(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function d0(e){return e instanceof HTMLInputElement&&"select"in e}function on(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&d0(e)&&t&&e.select()}}var xc=u0();function u0(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=yc(e,t),e.unshift(t)},remove(t){e=yc(e,t),e[0]?.resume()}}}function yc(e,t){const r=[...e],s=r.indexOf(t);return s!==-1&&r.splice(s,1),r}function m0(e){return e.filter(t=>t.tagName!=="A")}var tt=globalThis?.document?g.useLayoutEffect:()=>{},p0=g[" useId ".trim().toString()]||(()=>{}),f0=0;function Wt(e){const[t,r]=g.useState(p0());return tt(()=>{r(s=>s??String(f0++))},[e]),t?`radix-${t}`:""}const h0=["top","right","bottom","left"],cn=Math.min,wt=Math.max,cs=Math.round,Br=Math.floor,Vt=e=>({x:e,y:e}),g0={left:"right",right:"left",bottom:"top",top:"bottom"},x0={start:"end",end:"start"};function Uo(e,t,r){return wt(e,cn(t,r))}function tn(e,t){return typeof e=="function"?e(t):e}function nn(e){return e.split("-")[0]}function er(e){return e.split("-")[1]}function Pa(e){return e==="x"?"y":"x"}function Ta(e){return e==="y"?"height":"width"}const y0=new Set(["top","bottom"]);function Ut(e){return y0.has(nn(e))?"y":"x"}function Ea(e){return Pa(Ut(e))}function b0(e,t,r){r===void 0&&(r=!1);const s=er(e),o=Ea(e),a=Ta(o);let i=o==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(i=ls(i)),[i,ls(i)]}function v0(e){const t=ls(e);return[Wo(e),t,Wo(t)]}function Wo(e){return e.replace(/start|end/g,t=>x0[t])}const bc=["left","right"],vc=["right","left"],w0=["top","bottom"],_0=["bottom","top"];function j0(e,t,r){switch(e){case"top":case"bottom":return r?t?vc:bc:t?bc:vc;case"left":case"right":return t?w0:_0;default:return[]}}function S0(e,t,r,s){const o=er(e);let a=j0(nn(e),r==="start",s);return o&&(a=a.map(i=>i+"-"+o),t&&(a=a.concat(a.map(Wo)))),a}function ls(e){return e.replace(/left|right|bottom|top/g,t=>g0[t])}function k0(e){return{top:0,right:0,bottom:0,left:0,...e}}function Id(e){return typeof e!="number"?k0(e):{top:e,right:e,bottom:e,left:e}}function ds(e){const{x:t,y:r,width:s,height:o}=e;return{width:s,height:o,top:r,left:t,right:t+s,bottom:r+o,x:t,y:r}}function wc(e,t,r){let{reference:s,floating:o}=e;const a=Ut(t),i=Ea(t),c=Ta(i),l=nn(t),d=a==="y",m=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,f=s[c]/2-o[c]/2;let h;switch(l){case"top":h={x:m,y:s.y-o.height};break;case"bottom":h={x:m,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(er(t)){case"start":h[i]-=f*(r&&d?-1:1);break;case"end":h[i]+=f*(r&&d?-1:1);break}return h}const C0=async(e,t,r)=>{const{placement:s="bottom",strategy:o="absolute",middleware:a=[],platform:i}=r,c=a.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let d=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:u}=wc(d,s,l),f=s,h={},x=0;for(let p=0;p<c.length;p++){const{name:y,fn:j}=c[p],{x:b,y:v,data:_,reset:C}=await j({x:m,y:u,initialPlacement:s,placement:f,strategy:o,middlewareData:h,rects:d,platform:i,elements:{reference:e,floating:t}});m=b??m,u=v??u,h={...h,[y]:{...h[y],..._}},C&&x<=50&&(x++,typeof C=="object"&&(C.placement&&(f=C.placement),C.rects&&(d=C.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:m,y:u}=wc(d,f,l)),p=-1)}return{x:m,y:u,placement:f,strategy:o,middlewareData:h}};async function _r(e,t){var r;t===void 0&&(t={});const{x:s,y:o,platform:a,rects:i,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:m="viewport",elementContext:u="floating",altBoundary:f=!1,padding:h=0}=tn(t,e),x=Id(h),y=c[f?u==="floating"?"reference":"floating":u],j=ds(await a.getClippingRect({element:(r=await(a.isElement==null?void 0:a.isElement(y)))==null||r?y:y.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(c.floating)),boundary:d,rootBoundary:m,strategy:l})),b=u==="floating"?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,v=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),_=await(a.isElement==null?void 0:a.isElement(v))?await(a.getScale==null?void 0:a.getScale(v))||{x:1,y:1}:{x:1,y:1},C=ds(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:b,offsetParent:v,strategy:l}):b);return{top:(j.top-C.top+x.top)/_.y,bottom:(C.bottom-j.bottom+x.bottom)/_.y,left:(j.left-C.left+x.left)/_.x,right:(C.right-j.right+x.right)/_.x}}const N0=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:s,placement:o,rects:a,platform:i,elements:c,middlewareData:l}=t,{element:d,padding:m=0}=tn(e,t)||{};if(d==null)return{};const u=Id(m),f={x:r,y:s},h=Ea(o),x=Ta(h),p=await i.getDimensions(d),y=h==="y",j=y?"top":"left",b=y?"bottom":"right",v=y?"clientHeight":"clientWidth",_=a.reference[x]+a.reference[h]-f[h]-a.floating[x],C=f[h]-a.reference[h],E=await(i.getOffsetParent==null?void 0:i.getOffsetParent(d));let S=E?E[v]:0;(!S||!await(i.isElement==null?void 0:i.isElement(E)))&&(S=c.floating[v]||a.floating[x]);const N=_/2-C/2,U=S/2-p[x]/2-1,k=cn(u[j],U),A=cn(u[b],U),P=k,D=S-p[x]-A,z=S/2-p[x]/2+N,L=Uo(P,z,D),O=!l.arrow&&er(o)!=null&&z!==L&&a.reference[x]/2-(z<P?k:A)-p[x]/2<0,M=O?z<P?z-P:z-D:0;return{[h]:f[h]+M,data:{[h]:L,centerOffset:z-L-M,...O&&{alignmentOffset:M}},reset:O}}}),A0=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var r,s;const{placement:o,middlewareData:a,rects:i,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:m=!0,crossAxis:u=!0,fallbackPlacements:f,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:x="none",flipAlignment:p=!0,...y}=tn(e,t);if((r=a.arrow)!=null&&r.alignmentOffset)return{};const j=nn(o),b=Ut(c),v=nn(c)===c,_=await(l.isRTL==null?void 0:l.isRTL(d.floating)),C=f||(v||!p?[ls(c)]:v0(c)),E=x!=="none";!f&&E&&C.push(...S0(c,p,x,_));const S=[c,...C],N=await _r(t,y),U=[];let k=((s=a.flip)==null?void 0:s.overflows)||[];if(m&&U.push(N[j]),u){const z=b0(o,i,_);U.push(N[z[0]],N[z[1]])}if(k=[...k,{placement:o,overflows:U}],!U.every(z=>z<=0)){var A,P;const z=(((A=a.flip)==null?void 0:A.index)||0)+1,L=S[z];if(L&&(!(u==="alignment"?b!==Ut(L):!1)||k.every(R=>Ut(R.placement)===b?R.overflows[0]>0:!0)))return{data:{index:z,overflows:k},reset:{placement:L}};let O=(P=k.filter(M=>M.overflows[0]<=0).sort((M,R)=>M.overflows[1]-R.overflows[1])[0])==null?void 0:P.placement;if(!O)switch(h){case"bestFit":{var D;const M=(D=k.filter(R=>{if(E){const W=Ut(R.placement);return W===b||W==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(W=>W>0).reduce((W,T)=>W+T,0)]).sort((R,W)=>R[1]-W[1])[0])==null?void 0:D[0];M&&(O=M);break}case"initialPlacement":O=c;break}if(o!==O)return{reset:{placement:O}}}return{}}}};function _c(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function jc(e){return h0.some(t=>e[t]>=0)}const P0=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:s="referenceHidden",...o}=tn(e,t);switch(s){case"referenceHidden":{const a=await _r(t,{...o,elementContext:"reference"}),i=_c(a,r.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:jc(i)}}}case"escaped":{const a=await _r(t,{...o,altBoundary:!0}),i=_c(a,r.floating);return{data:{escapedOffsets:i,escaped:jc(i)}}}default:return{}}}}},Rd=new Set(["left","top"]);async function T0(e,t){const{placement:r,platform:s,elements:o}=e,a=await(s.isRTL==null?void 0:s.isRTL(o.floating)),i=nn(r),c=er(r),l=Ut(r)==="y",d=Rd.has(i)?-1:1,m=a&&l?-1:1,u=tn(t,e);let{mainAxis:f,crossAxis:h,alignmentAxis:x}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return c&&typeof x=="number"&&(h=c==="end"?x*-1:x),l?{x:h*m,y:f*d}:{x:f*d,y:h*m}}const E0=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var r,s;const{x:o,y:a,placement:i,middlewareData:c}=t,l=await T0(t,e);return i===((r=c.offset)==null?void 0:r.placement)&&(s=c.arrow)!=null&&s.alignmentOffset?{}:{x:o+l.x,y:a+l.y,data:{...l,placement:i}}}}},I0=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:s,placement:o}=t,{mainAxis:a=!0,crossAxis:i=!1,limiter:c={fn:y=>{let{x:j,y:b}=y;return{x:j,y:b}}},...l}=tn(e,t),d={x:r,y:s},m=await _r(t,l),u=Ut(nn(o)),f=Pa(u);let h=d[f],x=d[u];if(a){const y=f==="y"?"top":"left",j=f==="y"?"bottom":"right",b=h+m[y],v=h-m[j];h=Uo(b,h,v)}if(i){const y=u==="y"?"top":"left",j=u==="y"?"bottom":"right",b=x+m[y],v=x-m[j];x=Uo(b,x,v)}const p=c.fn({...t,[f]:h,[u]:x});return{...p,data:{x:p.x-r,y:p.y-s,enabled:{[f]:a,[u]:i}}}}}},R0=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:r,y:s,placement:o,rects:a,middlewareData:i}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=tn(e,t),m={x:r,y:s},u=Ut(o),f=Pa(u);let h=m[f],x=m[u];const p=tn(c,t),y=typeof p=="number"?{mainAxis:p,crossAxis:0}:{mainAxis:0,crossAxis:0,...p};if(l){const v=f==="y"?"height":"width",_=a.reference[f]-a.floating[v]+y.mainAxis,C=a.reference[f]+a.reference[v]-y.mainAxis;h<_?h=_:h>C&&(h=C)}if(d){var j,b;const v=f==="y"?"width":"height",_=Rd.has(nn(o)),C=a.reference[u]-a.floating[v]+(_&&((j=i.offset)==null?void 0:j[u])||0)+(_?0:y.crossAxis),E=a.reference[u]+a.reference[v]+(_?0:((b=i.offset)==null?void 0:b[u])||0)-(_?y.crossAxis:0);x<C?x=C:x>E&&(x=E)}return{[f]:h,[u]:x}}}},O0=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var r,s;const{placement:o,rects:a,platform:i,elements:c}=t,{apply:l=()=>{},...d}=tn(e,t),m=await _r(t,d),u=nn(o),f=er(o),h=Ut(o)==="y",{width:x,height:p}=a.floating;let y,j;u==="top"||u==="bottom"?(y=u,j=f===(await(i.isRTL==null?void 0:i.isRTL(c.floating))?"start":"end")?"left":"right"):(j=u,y=f==="end"?"top":"bottom");const b=p-m.top-m.bottom,v=x-m.left-m.right,_=cn(p-m[y],b),C=cn(x-m[j],v),E=!t.middlewareData.shift;let S=_,N=C;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(N=v),(s=t.middlewareData.shift)!=null&&s.enabled.y&&(S=b),E&&!f){const k=wt(m.left,0),A=wt(m.right,0),P=wt(m.top,0),D=wt(m.bottom,0);h?N=x-2*(k!==0||A!==0?k+A:wt(m.left,m.right)):S=p-2*(P!==0||D!==0?P+D:wt(m.top,m.bottom))}await l({...t,availableWidth:N,availableHeight:S});const U=await i.getDimensions(c.floating);return x!==U.width||p!==U.height?{reset:{rects:!0}}:{}}}};function Cs(){return typeof window<"u"}function tr(e){return Od(e)?(e.nodeName||"").toLowerCase():"#document"}function _t(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Gt(e){var t;return(t=(Od(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Od(e){return Cs()?e instanceof Node||e instanceof _t(e).Node:!1}function Rt(e){return Cs()?e instanceof Element||e instanceof _t(e).Element:!1}function Zt(e){return Cs()?e instanceof HTMLElement||e instanceof _t(e).HTMLElement:!1}function Sc(e){return!Cs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof _t(e).ShadowRoot}const M0=new Set(["inline","contents"]);function Pr(e){const{overflow:t,overflowX:r,overflowY:s,display:o}=Ot(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+r)&&!M0.has(o)}const D0=new Set(["table","td","th"]);function L0(e){return D0.has(tr(e))}const $0=[":popover-open",":modal"];function Ns(e){return $0.some(t=>{try{return e.matches(t)}catch{return!1}})}const z0=["transform","translate","scale","rotate","perspective"],F0=["transform","translate","scale","rotate","perspective","filter"],B0=["paint","layout","strict","content"];function Ia(e){const t=Ra(),r=Rt(e)?Ot(e):e;return z0.some(s=>r[s]?r[s]!=="none":!1)||(r.containerType?r.containerType!=="normal":!1)||!t&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!t&&(r.filter?r.filter!=="none":!1)||F0.some(s=>(r.willChange||"").includes(s))||B0.some(s=>(r.contain||"").includes(s))}function U0(e){let t=ln(e);for(;Zt(t)&&!qn(t);){if(Ia(t))return t;if(Ns(t))return null;t=ln(t)}return null}function Ra(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const W0=new Set(["html","body","#document"]);function qn(e){return W0.has(tr(e))}function Ot(e){return _t(e).getComputedStyle(e)}function As(e){return Rt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ln(e){if(tr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Sc(e)&&e.host||Gt(e);return Sc(t)?t.host:t}function Md(e){const t=ln(e);return qn(t)?e.ownerDocument?e.ownerDocument.body:e.body:Zt(t)&&Pr(t)?t:Md(t)}function jr(e,t,r){var s;t===void 0&&(t=[]),r===void 0&&(r=!0);const o=Md(e),a=o===((s=e.ownerDocument)==null?void 0:s.body),i=_t(o);if(a){const c=Vo(i);return t.concat(i,i.visualViewport||[],Pr(o)?o:[],c&&r?jr(c):[])}return t.concat(o,jr(o,[],r))}function Vo(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Dd(e){const t=Ot(e);let r=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Zt(e),a=o?e.offsetWidth:r,i=o?e.offsetHeight:s,c=cs(r)!==a||cs(s)!==i;return c&&(r=a,s=i),{width:r,height:s,$:c}}function Oa(e){return Rt(e)?e:e.contextElement}function Wn(e){const t=Oa(e);if(!Zt(t))return Vt(1);const r=t.getBoundingClientRect(),{width:s,height:o,$:a}=Dd(t);let i=(a?cs(r.width):r.width)/s,c=(a?cs(r.height):r.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!c||!Number.isFinite(c))&&(c=1),{x:i,y:c}}const V0=Vt(0);function Ld(e){const t=_t(e);return!Ra()||!t.visualViewport?V0:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function H0(e,t,r){return t===void 0&&(t=!1),!r||t&&r!==_t(e)?!1:t}function Sn(e,t,r,s){t===void 0&&(t=!1),r===void 0&&(r=!1);const o=e.getBoundingClientRect(),a=Oa(e);let i=Vt(1);t&&(s?Rt(s)&&(i=Wn(s)):i=Wn(e));const c=H0(a,r,s)?Ld(a):Vt(0);let l=(o.left+c.x)/i.x,d=(o.top+c.y)/i.y,m=o.width/i.x,u=o.height/i.y;if(a){const f=_t(a),h=s&&Rt(s)?_t(s):s;let x=f,p=Vo(x);for(;p&&s&&h!==x;){const y=Wn(p),j=p.getBoundingClientRect(),b=Ot(p),v=j.left+(p.clientLeft+parseFloat(b.paddingLeft))*y.x,_=j.top+(p.clientTop+parseFloat(b.paddingTop))*y.y;l*=y.x,d*=y.y,m*=y.x,u*=y.y,l+=v,d+=_,x=_t(p),p=Vo(x)}}return ds({width:m,height:u,x:l,y:d})}function Ps(e,t){const r=As(e).scrollLeft;return t?t.left+r:Sn(Gt(e)).left+r}function $d(e,t){const r=e.getBoundingClientRect(),s=r.left+t.scrollLeft-Ps(e,r),o=r.top+t.scrollTop;return{x:s,y:o}}function q0(e){let{elements:t,rect:r,offsetParent:s,strategy:o}=e;const a=o==="fixed",i=Gt(s),c=t?Ns(t.floating):!1;if(s===i||c&&a)return r;let l={scrollLeft:0,scrollTop:0},d=Vt(1);const m=Vt(0),u=Zt(s);if((u||!u&&!a)&&((tr(s)!=="body"||Pr(i))&&(l=As(s)),Zt(s))){const h=Sn(s);d=Wn(s),m.x=h.x+s.clientLeft,m.y=h.y+s.clientTop}const f=i&&!u&&!a?$d(i,l):Vt(0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-l.scrollLeft*d.x+m.x+f.x,y:r.y*d.y-l.scrollTop*d.y+m.y+f.y}}function Z0(e){return Array.from(e.getClientRects())}function G0(e){const t=Gt(e),r=As(e),s=e.ownerDocument.body,o=wt(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),a=wt(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-r.scrollLeft+Ps(e);const c=-r.scrollTop;return Ot(s).direction==="rtl"&&(i+=wt(t.clientWidth,s.clientWidth)-o),{width:o,height:a,x:i,y:c}}const kc=25;function Q0(e,t){const r=_t(e),s=Gt(e),o=r.visualViewport;let a=s.clientWidth,i=s.clientHeight,c=0,l=0;if(o){a=o.width,i=o.height;const m=Ra();(!m||m&&t==="fixed")&&(c=o.offsetLeft,l=o.offsetTop)}const d=Ps(s);if(d<=0){const m=s.ownerDocument,u=m.body,f=getComputedStyle(u),h=m.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,x=Math.abs(s.clientWidth-u.clientWidth-h);x<=kc&&(a-=x)}else d<=kc&&(a+=d);return{width:a,height:i,x:c,y:l}}const Y0=new Set(["absolute","fixed"]);function K0(e,t){const r=Sn(e,!0,t==="fixed"),s=r.top+e.clientTop,o=r.left+e.clientLeft,a=Zt(e)?Wn(e):Vt(1),i=e.clientWidth*a.x,c=e.clientHeight*a.y,l=o*a.x,d=s*a.y;return{width:i,height:c,x:l,y:d}}function Cc(e,t,r){let s;if(t==="viewport")s=Q0(e,r);else if(t==="document")s=G0(Gt(e));else if(Rt(t))s=K0(t,r);else{const o=Ld(e);s={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ds(s)}function zd(e,t){const r=ln(e);return r===t||!Rt(r)||qn(r)?!1:Ot(r).position==="fixed"||zd(r,t)}function J0(e,t){const r=t.get(e);if(r)return r;let s=jr(e,[],!1).filter(c=>Rt(c)&&tr(c)!=="body"),o=null;const a=Ot(e).position==="fixed";let i=a?ln(e):e;for(;Rt(i)&&!qn(i);){const c=Ot(i),l=Ia(i);!l&&c.position==="fixed"&&(o=null),(a?!l&&!o:!l&&c.position==="static"&&!!o&&Y0.has(o.position)||Pr(i)&&!l&&zd(e,i))?s=s.filter(m=>m!==i):o=c,i=ln(i)}return t.set(e,s),s}function X0(e){let{element:t,boundary:r,rootBoundary:s,strategy:o}=e;const i=[...r==="clippingAncestors"?Ns(t)?[]:J0(t,this._c):[].concat(r),s],c=i[0],l=i.reduce((d,m)=>{const u=Cc(t,m,o);return d.top=wt(u.top,d.top),d.right=cn(u.right,d.right),d.bottom=cn(u.bottom,d.bottom),d.left=wt(u.left,d.left),d},Cc(t,c,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function ew(e){const{width:t,height:r}=Dd(e);return{width:t,height:r}}function tw(e,t,r){const s=Zt(t),o=Gt(t),a=r==="fixed",i=Sn(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=Vt(0);function d(){l.x=Ps(o)}if(s||!s&&!a)if((tr(t)!=="body"||Pr(o))&&(c=As(t)),s){const h=Sn(t,!0,a,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&d();a&&!s&&o&&d();const m=o&&!s&&!a?$d(o,c):Vt(0),u=i.left+c.scrollLeft-l.x-m.x,f=i.top+c.scrollTop-l.y-m.y;return{x:u,y:f,width:i.width,height:i.height}}function bo(e){return Ot(e).position==="static"}function Nc(e,t){if(!Zt(e)||Ot(e).position==="fixed")return null;if(t)return t(e);let r=e.offsetParent;return Gt(e)===r&&(r=r.ownerDocument.body),r}function Fd(e,t){const r=_t(e);if(Ns(e))return r;if(!Zt(e)){let o=ln(e);for(;o&&!qn(o);){if(Rt(o)&&!bo(o))return o;o=ln(o)}return r}let s=Nc(e,t);for(;s&&L0(s)&&bo(s);)s=Nc(s,t);return s&&qn(s)&&bo(s)&&!Ia(s)?r:s||U0(e)||r}const nw=async function(e){const t=this.getOffsetParent||Fd,r=this.getDimensions,s=await r(e.floating);return{reference:tw(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function rw(e){return Ot(e).direction==="rtl"}const sw={convertOffsetParentRelativeRectToViewportRelativeRect:q0,getDocumentElement:Gt,getClippingRect:X0,getOffsetParent:Fd,getElementRects:nw,getClientRects:Z0,getDimensions:ew,getScale:Wn,isElement:Rt,isRTL:rw};function Bd(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ow(e,t){let r=null,s;const o=Gt(e);function a(){var c;clearTimeout(s),(c=r)==null||c.disconnect(),r=null}function i(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:m,top:u,width:f,height:h}=d;if(c||t(),!f||!h)return;const x=Br(u),p=Br(o.clientWidth-(m+f)),y=Br(o.clientHeight-(u+h)),j=Br(m),v={rootMargin:-x+"px "+-p+"px "+-y+"px "+-j+"px",threshold:wt(0,cn(1,l))||1};let _=!0;function C(E){const S=E[0].intersectionRatio;if(S!==l){if(!_)return i();S?i(!1,S):s=setTimeout(()=>{i(!1,1e-7)},1e3)}S===1&&!Bd(d,e.getBoundingClientRect())&&i(),_=!1}try{r=new IntersectionObserver(C,{...v,root:o.ownerDocument})}catch{r=new IntersectionObserver(C,v)}r.observe(e)}return i(!0),a}function aw(e,t,r,s){s===void 0&&(s={});const{ancestorScroll:o=!0,ancestorResize:a=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=s,d=Oa(e),m=o||a?[...d?jr(d):[],...jr(t)]:[];m.forEach(j=>{o&&j.addEventListener("scroll",r,{passive:!0}),a&&j.addEventListener("resize",r)});const u=d&&c?ow(d,r):null;let f=-1,h=null;i&&(h=new ResizeObserver(j=>{let[b]=j;b&&b.target===d&&h&&(h.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var v;(v=h)==null||v.observe(t)})),r()}),d&&!l&&h.observe(d),h.observe(t));let x,p=l?Sn(e):null;l&&y();function y(){const j=Sn(e);p&&!Bd(p,j)&&r(),p=j,x=requestAnimationFrame(y)}return r(),()=>{var j;m.forEach(b=>{o&&b.removeEventListener("scroll",r),a&&b.removeEventListener("resize",r)}),u?.(),(j=h)==null||j.disconnect(),h=null,l&&cancelAnimationFrame(x)}}const iw=E0,cw=I0,lw=A0,dw=O0,uw=P0,Ac=N0,mw=R0,pw=(e,t,r)=>{const s=new Map,o={platform:sw,...r},a={...o.platform,_c:s};return C0(e,t,{...o,platform:a})};var fw=typeof document<"u",hw=function(){},Kr=fw?w.useLayoutEffect:hw;function us(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let r,s,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(s=r;s--!==0;)if(!us(e[s],t[s]))return!1;return!0}if(o=Object.keys(e),r=o.length,r!==Object.keys(t).length)return!1;for(s=r;s--!==0;)if(!{}.hasOwnProperty.call(t,o[s]))return!1;for(s=r;s--!==0;){const a=o[s];if(!(a==="_owner"&&e.$$typeof)&&!us(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function Ud(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Pc(e,t){const r=Ud(e);return Math.round(t*r)/r}function vo(e){const t=g.useRef(e);return Kr(()=>{t.current=e}),t}function gw(e){e===void 0&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:s=[],platform:o,elements:{reference:a,floating:i}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[m,u]=g.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,h]=g.useState(s);us(f,s)||h(s);const[x,p]=g.useState(null),[y,j]=g.useState(null),b=g.useCallback(R=>{R!==E.current&&(E.current=R,p(R))},[]),v=g.useCallback(R=>{R!==S.current&&(S.current=R,j(R))},[]),_=a||x,C=i||y,E=g.useRef(null),S=g.useRef(null),N=g.useRef(m),U=l!=null,k=vo(l),A=vo(o),P=vo(d),D=g.useCallback(()=>{if(!E.current||!S.current)return;const R={placement:t,strategy:r,middleware:f};A.current&&(R.platform=A.current),pw(E.current,S.current,R).then(W=>{const T={...W,isPositioned:P.current!==!1};z.current&&!us(N.current,T)&&(N.current=T,ys.flushSync(()=>{u(T)}))})},[f,t,r,A,P]);Kr(()=>{d===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,u(R=>({...R,isPositioned:!1})))},[d]);const z=g.useRef(!1);Kr(()=>(z.current=!0,()=>{z.current=!1}),[]),Kr(()=>{if(_&&(E.current=_),C&&(S.current=C),_&&C){if(k.current)return k.current(_,C,D);D()}},[_,C,D,k,U]);const L=g.useMemo(()=>({reference:E,floating:S,setReference:b,setFloating:v}),[b,v]),O=g.useMemo(()=>({reference:_,floating:C}),[_,C]),M=g.useMemo(()=>{const R={position:r,left:0,top:0};if(!O.floating)return R;const W=Pc(O.floating,m.x),T=Pc(O.floating,m.y);return c?{...R,transform:"translate("+W+"px, "+T+"px)",...Ud(O.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:W,top:T}},[r,c,O.floating,m.x,m.y]);return g.useMemo(()=>({...m,update:D,refs:L,elements:O,floatingStyles:M}),[m,D,L,O,M])}const xw=e=>{function t(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:e,fn(r){const{element:s,padding:o}=typeof e=="function"?e(r):e;return s&&t(s)?s.current!=null?Ac({element:s.current,padding:o}).fn(r):{}:s?Ac({element:s,padding:o}).fn(r):{}}}},yw=(e,t)=>({...iw(e),options:[e,t]}),bw=(e,t)=>({...cw(e),options:[e,t]}),vw=(e,t)=>({...mw(e),options:[e,t]}),ww=(e,t)=>({...lw(e),options:[e,t]}),_w=(e,t)=>({...dw(e),options:[e,t]}),jw=(e,t)=>({...uw(e),options:[e,t]}),Sw=(e,t)=>({...xw(e),options:[e,t]});var kw="Arrow",Wd=g.forwardRef((e,t)=>{const{children:r,width:s=10,height:o=5,...a}=e;return n.jsx(ve.svg,{...a,ref:t,width:s,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:n.jsx("polygon",{points:"0,0 30,0 15,10"})})});Wd.displayName=kw;var Cw=Wd;function Nw(e){const[t,r]=g.useState(void 0);return tt(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const s=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const a=o[0];let i,c;if("borderBoxSize"in a){const l=a.borderBoxSize,d=Array.isArray(l)?l[0]:l;i=d.inlineSize,c=d.blockSize}else i=e.offsetWidth,c=e.offsetHeight;r({width:i,height:c})});return s.observe(e,{box:"border-box"}),()=>s.unobserve(e)}else r(void 0)},[e]),t}var Ma="Popper",[Vd,Hd]=pn(Ma),[Aw,qd]=Vd(Ma),Zd=e=>{const{__scopePopper:t,children:r}=e,[s,o]=g.useState(null);return n.jsx(Aw,{scope:t,anchor:s,onAnchorChange:o,children:r})};Zd.displayName=Ma;var Gd="PopperAnchor",Qd=g.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:s,...o}=e,a=qd(Gd,r),i=g.useRef(null),c=Ie(t,i),l=g.useRef(null);return g.useEffect(()=>{const d=l.current;l.current=s?.current||i.current,d!==l.current&&a.onAnchorChange(l.current)}),s?null:n.jsx(ve.div,{...o,ref:c})});Qd.displayName=Gd;var Da="PopperContent",[Pw,Tw]=Vd(Da),Yd=g.forwardRef((e,t)=>{const{__scopePopper:r,side:s="bottom",sideOffset:o=0,align:a="center",alignOffset:i=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:m=0,sticky:u="partial",hideWhenDetached:f=!1,updatePositionStrategy:h="optimized",onPlaced:x,...p}=e,y=qd(Da,r),[j,b]=g.useState(null),v=Ie(t,F=>b(F)),[_,C]=g.useState(null),E=Nw(_),S=E?.width??0,N=E?.height??0,U=s+(a!=="center"?"-"+a:""),k=typeof m=="number"?m:{top:0,right:0,bottom:0,left:0,...m},A=Array.isArray(d)?d:[d],P=A.length>0,D={padding:k,boundary:A.filter(Iw),altBoundary:P},{refs:z,floatingStyles:L,placement:O,isPositioned:M,middlewareData:R}=gw({strategy:"fixed",placement:U,whileElementsMounted:(...F)=>aw(...F,{animationFrame:h==="always"}),elements:{reference:y.anchor},middleware:[yw({mainAxis:o+N,alignmentAxis:i}),l&&bw({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?vw():void 0,...D}),l&&ww({...D}),_w({...D,apply:({elements:F,rects:K,availableWidth:me,availableHeight:q})=>{const{width:te,height:ce}=K.reference,pe=F.floating.style;pe.setProperty("--radix-popper-available-width",`${me}px`),pe.setProperty("--radix-popper-available-height",`${q}px`),pe.setProperty("--radix-popper-anchor-width",`${te}px`),pe.setProperty("--radix-popper-anchor-height",`${ce}px`)}}),_&&Sw({element:_,padding:c}),Rw({arrowWidth:S,arrowHeight:N}),f&&jw({strategy:"referenceHidden",...D})]}),[W,T]=Xd(O),V=an(x);tt(()=>{M&&V?.()},[M,V]);const ee=R.arrow?.x,B=R.arrow?.y,Y=R.arrow?.centerOffset!==0,[J,ge]=g.useState();return tt(()=>{j&&ge(window.getComputedStyle(j).zIndex)},[j]),n.jsx("div",{ref:z.setFloating,"data-radix-popper-content-wrapper":"",style:{...L,transform:M?L.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:J,"--radix-popper-transform-origin":[R.transformOrigin?.x,R.transformOrigin?.y].join(" "),...R.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:n.jsx(Pw,{scope:r,placedSide:W,onArrowChange:C,arrowX:ee,arrowY:B,shouldHideArrow:Y,children:n.jsx(ve.div,{"data-side":W,"data-align":T,...p,ref:v,style:{...p.style,animation:M?void 0:"none"}})})})});Yd.displayName=Da;var Kd="PopperArrow",Ew={top:"bottom",right:"left",bottom:"top",left:"right"},Jd=g.forwardRef(function(t,r){const{__scopePopper:s,...o}=t,a=Tw(Kd,s),i=Ew[a.placedSide];return n.jsx("span",{ref:a.onArrowChange,style:{position:"absolute",left:a.arrowX,top:a.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[a.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[a.placedSide],visibility:a.shouldHideArrow?"hidden":void 0},children:n.jsx(Cw,{...o,ref:r,style:{...o.style,display:"block"}})})});Jd.displayName=Kd;function Iw(e){return e!==null}var Rw=e=>({name:"transformOrigin",options:e,fn(t){const{placement:r,rects:s,middlewareData:o}=t,i=o.arrow?.centerOffset!==0,c=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[d,m]=Xd(r),u={start:"0%",center:"50%",end:"100%"}[m],f=(o.arrow?.x??0)+c/2,h=(o.arrow?.y??0)+l/2;let x="",p="";return d==="bottom"?(x=i?u:`${f}px`,p=`${-l}px`):d==="top"?(x=i?u:`${f}px`,p=`${s.floating.height+l}px`):d==="right"?(x=`${-l}px`,p=i?u:`${h}px`):d==="left"&&(x=`${s.floating.width+l}px`,p=i?u:`${h}px`),{data:{x,y:p}}}});function Xd(e){const[t,r="center"]=e.split("-");return[t,r]}var Ow=Zd,Mw=Qd,Dw=Yd,Lw=Jd,$w="Portal",La=g.forwardRef((e,t)=>{const{container:r,...s}=e,[o,a]=g.useState(!1);tt(()=>a(!0),[]);const i=r||o&&globalThis?.document?.body;return i?oa.createPortal(n.jsx(ve.div,{...s,ref:t}),i):null});La.displayName=$w;function zw(e){const t=Fw(e),r=g.forwardRef((s,o)=>{const{children:a,...i}=s,c=g.Children.toArray(a),l=c.find(Uw);if(l){const d=l.props.children,m=c.map(u=>u===l?g.Children.count(d)>1?g.Children.only(null):g.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:g.isValidElement(d)?g.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function Fw(e){const t=g.forwardRef((r,s)=>{const{children:o,...a}=r;if(g.isValidElement(o)){const i=Vw(o),c=Ww(a,o.props);return o.type!==g.Fragment&&(c.ref=s?Kn(s,i):i),g.cloneElement(o,c)}return g.Children.count(o)>1?g.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Bw=Symbol("radix.slottable");function Uw(e){return g.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Bw}function Ww(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function Vw(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Hw=g[" useInsertionEffect ".trim().toString()]||tt;function dn({prop:e,defaultProp:t,onChange:r=()=>{},caller:s}){const[o,a,i]=qw({defaultProp:t,onChange:r}),c=e!==void 0,l=c?e:o;{const m=g.useRef(e!==void 0);g.useEffect(()=>{const u=m.current;u!==c&&console.warn(`${s} is changing from ${u?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=c},[c,s])}const d=g.useCallback(m=>{if(c){const u=Zw(m)?m(e):m;u!==e&&i.current?.(u)}else a(m)},[c,e,a,i]);return[l,d]}function qw({defaultProp:e,onChange:t}){const[r,s]=g.useState(e),o=g.useRef(r),a=g.useRef(t);return Hw(()=>{a.current=t},[t]),g.useEffect(()=>{o.current!==r&&(a.current?.(r),o.current=r)},[r,o]),[r,s,a]}function Zw(e){return typeof e=="function"}function Gw(e){const t=g.useRef({value:e,previous:e});return g.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var eu=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Qw="VisuallyHidden",Yw=g.forwardRef((e,t)=>n.jsx(ve.span,{...e,ref:t,style:{...eu,...e.style}}));Yw.displayName=Qw;var Kw=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},$n=new WeakMap,Ur=new WeakMap,Wr={},wo=0,tu=function(e){return e&&(e.host||tu(e.parentNode))},Jw=function(e,t){return t.map(function(r){if(e.contains(r))return r;var s=tu(r);return s&&e.contains(s)?s:(console.error("aria-hidden",r,"in not contained inside",e,". Doing nothing"),null)}).filter(function(r){return!!r})},Xw=function(e,t,r,s){var o=Jw(t,Array.isArray(e)?e:[e]);Wr[r]||(Wr[r]=new WeakMap);var a=Wr[r],i=[],c=new Set,l=new Set(o),d=function(u){!u||c.has(u)||(c.add(u),d(u.parentNode))};o.forEach(d);var m=function(u){!u||l.has(u)||Array.prototype.forEach.call(u.children,function(f){if(c.has(f))m(f);else try{var h=f.getAttribute(s),x=h!==null&&h!=="false",p=($n.get(f)||0)+1,y=(a.get(f)||0)+1;$n.set(f,p),a.set(f,y),i.push(f),p===1&&x&&Ur.set(f,!0),y===1&&f.setAttribute(r,"true"),x||f.setAttribute(s,"true")}catch(j){console.error("aria-hidden: cannot operate on ",f,j)}})};return m(t),c.clear(),wo++,function(){i.forEach(function(u){var f=$n.get(u)-1,h=a.get(u)-1;$n.set(u,f),a.set(u,h),f||(Ur.has(u)||u.removeAttribute(s),Ur.delete(u)),h||u.removeAttribute(r)}),wo--,wo||($n=new WeakMap,$n=new WeakMap,Ur=new WeakMap,Wr={})}},nu=function(e,t,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(e)?e:[e]),o=Kw(e);return o?(s.push.apply(s,Array.from(o.querySelectorAll("[aria-live], script"))),Xw(s,o,r,"aria-hidden")):function(){return null}},Bt=function(){return Bt=Object.assign||function(t){for(var r,s=1,o=arguments.length;s<o;s++){r=arguments[s];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])}return t},Bt.apply(this,arguments)};function ru(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,s=Object.getOwnPropertySymbols(e);o<s.length;o++)t.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(e,s[o])&&(r[s[o]]=e[s[o]]);return r}function e_(e,t,r){if(r||arguments.length===2)for(var s=0,o=t.length,a;s<o;s++)(a||!(s in t))&&(a||(a=Array.prototype.slice.call(t,0,s)),a[s]=t[s]);return e.concat(a||Array.prototype.slice.call(t))}var Jr="right-scroll-bar-position",Xr="width-before-scroll-bar",t_="with-scroll-bars-hidden",n_="--removed-body-scroll-bar-size";function _o(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function r_(e,t){var r=w.useState(function(){return{value:e,callback:t,facade:{get current(){return r.value},set current(s){var o=r.value;o!==s&&(r.value=s,r.callback(s,o))}}}})[0];return r.callback=t,r.facade}var s_=typeof window<"u"?g.useLayoutEffect:g.useEffect,Tc=new WeakMap;function o_(e,t){var r=r_(null,function(s){return e.forEach(function(o){return _o(o,s)})});return s_(function(){var s=Tc.get(r);if(s){var o=new Set(s),a=new Set(e),i=r.current;o.forEach(function(c){a.has(c)||_o(c,null)}),a.forEach(function(c){o.has(c)||_o(c,i)})}Tc.set(r,e)},[e]),r}function a_(e){return e}function i_(e,t){t===void 0&&(t=a_);var r=[],s=!1,o={read:function(){if(s)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(a){var i=t(a,s);return r.push(i),function(){r=r.filter(function(c){return c!==i})}},assignSyncMedium:function(a){for(s=!0;r.length;){var i=r;r=[],i.forEach(a)}r={push:function(c){return a(c)},filter:function(){return r}}},assignMedium:function(a){s=!0;var i=[];if(r.length){var c=r;r=[],c.forEach(a),i=r}var l=function(){var m=i;i=[],m.forEach(a)},d=function(){return Promise.resolve().then(l)};d(),r={push:function(m){i.push(m),d()},filter:function(m){return i=i.filter(m),r}}}};return o}function c_(e){e===void 0&&(e={});var t=i_(null);return t.options=Bt({async:!0,ssr:!1},e),t}var su=function(e){var t=e.sideCar,r=ru(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var s=t.read();if(!s)throw new Error("Sidecar medium not found");return g.createElement(s,Bt({},r))};su.isSideCarExport=!0;function l_(e,t){return e.useMedium(t),su}var ou=c_(),jo=function(){},Ts=g.forwardRef(function(e,t){var r=g.useRef(null),s=g.useState({onScrollCapture:jo,onWheelCapture:jo,onTouchMoveCapture:jo}),o=s[0],a=s[1],i=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,m=e.enabled,u=e.shards,f=e.sideCar,h=e.noRelative,x=e.noIsolation,p=e.inert,y=e.allowPinchZoom,j=e.as,b=j===void 0?"div":j,v=e.gapMode,_=ru(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=f,E=o_([r,t]),S=Bt(Bt({},_),o);return g.createElement(g.Fragment,null,m&&g.createElement(C,{sideCar:ou,removeScrollBar:d,shards:u,noRelative:h,noIsolation:x,inert:p,setCallbacks:a,allowPinchZoom:!!y,lockRef:r,gapMode:v}),i?g.cloneElement(g.Children.only(c),Bt(Bt({},S),{ref:E})):g.createElement(b,Bt({},S,{className:l,ref:E}),c))});Ts.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Ts.classNames={fullWidth:Xr,zeroRight:Jr};var d_=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function u_(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=d_();return t&&e.setAttribute("nonce",t),e}function m_(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function p_(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var f_=function(){var e=0,t=null;return{add:function(r){e==0&&(t=u_())&&(m_(t,r),p_(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},h_=function(){var e=f_();return function(t,r){g.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])}},au=function(){var e=h_(),t=function(r){var s=r.styles,o=r.dynamic;return e(s,o),null};return t},g_={left:0,top:0,right:0,gap:0},So=function(e){return parseInt(e||"",10)||0},x_=function(e){var t=window.getComputedStyle(document.body),r=t[e==="padding"?"paddingLeft":"marginLeft"],s=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[So(r),So(s),So(o)]},y_=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return g_;var t=x_(e),r=document.documentElement.clientWidth,s=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,s-r+t[2]-t[0])}},b_=au(),Vn="data-scroll-locked",v_=function(e,t,r,s){var o=e.left,a=e.top,i=e.right,c=e.gap;return r===void 0&&(r="margin"),`
92
- .`.concat(t_,` {
93
- overflow: hidden `).concat(s,`;
94
- padding-right: `).concat(c,"px ").concat(s,`;
95
- }
96
- body[`).concat(Vn,`] {
97
- overflow: hidden `).concat(s,`;
98
- overscroll-behavior: contain;
99
- `).concat([t&&"position: relative ".concat(s,";"),r==="margin"&&`
100
- padding-left: `.concat(o,`px;
101
- padding-top: `).concat(a,`px;
102
- padding-right: `).concat(i,`px;
103
- margin-left:0;
104
- margin-top:0;
105
- margin-right: `).concat(c,"px ").concat(s,`;
106
- `),r==="padding"&&"padding-right: ".concat(c,"px ").concat(s,";")].filter(Boolean).join(""),`
107
- }
108
-
109
- .`).concat(Jr,` {
110
- right: `).concat(c,"px ").concat(s,`;
111
- }
112
-
113
- .`).concat(Xr,` {
114
- margin-right: `).concat(c,"px ").concat(s,`;
115
- }
116
-
117
- .`).concat(Jr," .").concat(Jr,` {
118
- right: 0 `).concat(s,`;
119
- }
120
-
121
- .`).concat(Xr," .").concat(Xr,` {
122
- margin-right: 0 `).concat(s,`;
123
- }
124
-
125
- body[`).concat(Vn,`] {
126
- `).concat(n_,": ").concat(c,`px;
127
- }
128
- `)},Ec=function(){var e=parseInt(document.body.getAttribute(Vn)||"0",10);return isFinite(e)?e:0},w_=function(){g.useEffect(function(){return document.body.setAttribute(Vn,(Ec()+1).toString()),function(){var e=Ec()-1;e<=0?document.body.removeAttribute(Vn):document.body.setAttribute(Vn,e.toString())}},[])},__=function(e){var t=e.noRelative,r=e.noImportant,s=e.gapMode,o=s===void 0?"margin":s;w_();var a=g.useMemo(function(){return y_(o)},[o]);return g.createElement(b_,{styles:v_(a,!t,o,r?"":"!important")})},Ho=!1;if(typeof window<"u")try{var Vr=Object.defineProperty({},"passive",{get:function(){return Ho=!0,!0}});window.addEventListener("test",Vr,Vr),window.removeEventListener("test",Vr,Vr)}catch{Ho=!1}var zn=Ho?{passive:!1}:!1,j_=function(e){return e.tagName==="TEXTAREA"},iu=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!j_(e)&&r[t]==="visible")},S_=function(e){return iu(e,"overflowY")},k_=function(e){return iu(e,"overflowX")},Ic=function(e,t){var r=t.ownerDocument,s=t;do{typeof ShadowRoot<"u"&&s instanceof ShadowRoot&&(s=s.host);var o=cu(e,s);if(o){var a=lu(e,s),i=a[1],c=a[2];if(i>c)return!0}s=s.parentNode}while(s&&s!==r.body);return!1},C_=function(e){var t=e.scrollTop,r=e.scrollHeight,s=e.clientHeight;return[t,r,s]},N_=function(e){var t=e.scrollLeft,r=e.scrollWidth,s=e.clientWidth;return[t,r,s]},cu=function(e,t){return e==="v"?S_(t):k_(t)},lu=function(e,t){return e==="v"?C_(t):N_(t)},A_=function(e,t){return e==="h"&&t==="rtl"?-1:1},P_=function(e,t,r,s,o){var a=A_(e,window.getComputedStyle(t).direction),i=a*s,c=r.target,l=t.contains(c),d=!1,m=i>0,u=0,f=0;do{if(!c)break;var h=lu(e,c),x=h[0],p=h[1],y=h[2],j=p-y-a*x;(x||j)&&cu(e,c)&&(u+=j,f+=x);var b=c.parentNode;c=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!l&&c!==document.body||l&&(t.contains(c)||t===c));return(m&&Math.abs(u)<1||!m&&Math.abs(f)<1)&&(d=!0),d},Hr=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Rc=function(e){return[e.deltaX,e.deltaY]},Oc=function(e){return e&&"current"in e?e.current:e},T_=function(e,t){return e[0]===t[0]&&e[1]===t[1]},E_=function(e){return`
129
- .block-interactivity-`.concat(e,` {pointer-events: none;}
130
- .allow-interactivity-`).concat(e,` {pointer-events: all;}
131
- `)},I_=0,Fn=[];function R_(e){var t=g.useRef([]),r=g.useRef([0,0]),s=g.useRef(),o=g.useState(I_++)[0],a=g.useState(au)[0],i=g.useRef(e);g.useEffect(function(){i.current=e},[e]),g.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var p=e_([e.lockRef.current],(e.shards||[]).map(Oc),!0).filter(Boolean);return p.forEach(function(y){return y.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),p.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var c=g.useCallback(function(p,y){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var j=Hr(p),b=r.current,v="deltaX"in p?p.deltaX:b[0]-j[0],_="deltaY"in p?p.deltaY:b[1]-j[1],C,E=p.target,S=Math.abs(v)>Math.abs(_)?"h":"v";if("touches"in p&&S==="h"&&E.type==="range")return!1;var N=window.getSelection(),U=N&&N.anchorNode,k=U?U===E||U.contains(E):!1;if(k)return!1;var A=Ic(S,E);if(!A)return!0;if(A?C=S:(C=S==="v"?"h":"v",A=Ic(S,E)),!A)return!1;if(!s.current&&"changedTouches"in p&&(v||_)&&(s.current=C),!C)return!0;var P=s.current||C;return P_(P,y,p,P==="h"?v:_)},[]),l=g.useCallback(function(p){var y=p;if(!(!Fn.length||Fn[Fn.length-1]!==a)){var j="deltaY"in y?Rc(y):Hr(y),b=t.current.filter(function(C){return C.name===y.type&&(C.target===y.target||y.target===C.shadowParent)&&T_(C.delta,j)})[0];if(b&&b.should){y.cancelable&&y.preventDefault();return}if(!b){var v=(i.current.shards||[]).map(Oc).filter(Boolean).filter(function(C){return C.contains(y.target)}),_=v.length>0?c(y,v[0]):!i.current.noIsolation;_&&y.cancelable&&y.preventDefault()}}},[]),d=g.useCallback(function(p,y,j,b){var v={name:p,delta:y,target:j,should:b,shadowParent:O_(j)};t.current.push(v),setTimeout(function(){t.current=t.current.filter(function(_){return _!==v})},1)},[]),m=g.useCallback(function(p){r.current=Hr(p),s.current=void 0},[]),u=g.useCallback(function(p){d(p.type,Rc(p),p.target,c(p,e.lockRef.current))},[]),f=g.useCallback(function(p){d(p.type,Hr(p),p.target,c(p,e.lockRef.current))},[]);g.useEffect(function(){return Fn.push(a),e.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:f}),document.addEventListener("wheel",l,zn),document.addEventListener("touchmove",l,zn),document.addEventListener("touchstart",m,zn),function(){Fn=Fn.filter(function(p){return p!==a}),document.removeEventListener("wheel",l,zn),document.removeEventListener("touchmove",l,zn),document.removeEventListener("touchstart",m,zn)}},[]);var h=e.removeScrollBar,x=e.inert;return g.createElement(g.Fragment,null,x?g.createElement(a,{styles:E_(o)}):null,h?g.createElement(__,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function O_(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const M_=l_(ou,R_);var $a=g.forwardRef(function(e,t){return g.createElement(Ts,Bt({},e,{ref:t,sideCar:M_}))});$a.classNames=Ts.classNames;var D_=[" ","Enter","ArrowUp","ArrowDown"],L_=[" ","Enter"],kn="Select",[Es,Is,$_]=Ca(kn),[nr]=pn(kn,[$_,Hd]),Rs=Hd(),[z_,fn]=nr(kn),[F_,B_]=nr(kn),du=e=>{const{__scopeSelect:t,children:r,open:s,defaultOpen:o,onOpenChange:a,value:i,defaultValue:c,onValueChange:l,dir:d,name:m,autoComplete:u,disabled:f,required:h,form:x}=e,p=Rs(t),[y,j]=g.useState(null),[b,v]=g.useState(null),[_,C]=g.useState(!1),E=ks(d),[S,N]=dn({prop:s,defaultProp:o??!1,onChange:a,caller:kn}),[U,k]=dn({prop:i,defaultProp:c,onChange:l,caller:kn}),A=g.useRef(null),P=y?x||!!y.closest("form"):!0,[D,z]=g.useState(new Set),L=Array.from(D).map(O=>O.props.value).join(";");return n.jsx(Ow,{...p,children:n.jsxs(z_,{required:h,scope:t,trigger:y,onTriggerChange:j,valueNode:b,onValueNodeChange:v,valueNodeHasChildren:_,onValueNodeHasChildrenChange:C,contentId:Wt(),value:U,onValueChange:k,open:S,onOpenChange:N,dir:E,triggerPointerDownPosRef:A,disabled:f,children:[n.jsx(Es.Provider,{scope:t,children:n.jsx(F_,{scope:e.__scopeSelect,onNativeOptionAdd:g.useCallback(O=>{z(M=>new Set(M).add(O))},[]),onNativeOptionRemove:g.useCallback(O=>{z(M=>{const R=new Set(M);return R.delete(O),R})},[]),children:r})}),P?n.jsxs(Tu,{"aria-hidden":!0,required:h,tabIndex:-1,name:m,autoComplete:u,value:U,onChange:O=>k(O.target.value),disabled:f,form:x,children:[U===void 0?n.jsx("option",{value:""}):null,Array.from(D)]},L):null]})})};du.displayName=kn;var uu="SelectTrigger",mu=g.forwardRef((e,t)=>{const{__scopeSelect:r,disabled:s=!1,...o}=e,a=Rs(r),i=fn(uu,r),c=i.disabled||s,l=Ie(t,i.onTriggerChange),d=Is(r),m=g.useRef("touch"),[u,f,h]=Iu(p=>{const y=d().filter(v=>!v.disabled),j=y.find(v=>v.value===i.value),b=Ru(y,p,j);b!==void 0&&i.onValueChange(b.value)}),x=p=>{c||(i.onOpenChange(!0),h()),p&&(i.triggerPointerDownPosRef.current={x:Math.round(p.pageX),y:Math.round(p.pageY)})};return n.jsx(Mw,{asChild:!0,...a,children:n.jsx(ve.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":Eu(i.value)?"":void 0,...o,ref:l,onClick:je(o.onClick,p=>{p.currentTarget.focus(),m.current!=="mouse"&&x(p)}),onPointerDown:je(o.onPointerDown,p=>{m.current=p.pointerType;const y=p.target;y.hasPointerCapture(p.pointerId)&&y.releasePointerCapture(p.pointerId),p.button===0&&p.ctrlKey===!1&&p.pointerType==="mouse"&&(x(p),p.preventDefault())}),onKeyDown:je(o.onKeyDown,p=>{const y=u.current!=="";!(p.ctrlKey||p.altKey||p.metaKey)&&p.key.length===1&&f(p.key),!(y&&p.key===" ")&&D_.includes(p.key)&&(x(),p.preventDefault())})})})});mu.displayName=uu;var pu="SelectValue",fu=g.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,children:a,placeholder:i="",...c}=e,l=fn(pu,r),{onValueNodeHasChildrenChange:d}=l,m=a!==void 0,u=Ie(t,l.onValueNodeChange);return tt(()=>{d(m)},[d,m]),n.jsx(ve.span,{...c,ref:u,style:{pointerEvents:"none"},children:Eu(l.value)?n.jsx(n.Fragment,{children:i}):a})});fu.displayName=pu;var U_="SelectIcon",hu=g.forwardRef((e,t)=>{const{__scopeSelect:r,children:s,...o}=e;return n.jsx(ve.span,{"aria-hidden":!0,...o,ref:t,children:s||"▼"})});hu.displayName=U_;var W_="SelectPortal",gu=e=>n.jsx(La,{asChild:!0,...e});gu.displayName=W_;var Cn="SelectContent",xu=g.forwardRef((e,t)=>{const r=fn(Cn,e.__scopeSelect),[s,o]=g.useState();if(tt(()=>{o(new DocumentFragment)},[]),!r.open){const a=s;return a?ys.createPortal(n.jsx(yu,{scope:e.__scopeSelect,children:n.jsx(Es.Slot,{scope:e.__scopeSelect,children:n.jsx("div",{children:e.children})})}),a):null}return n.jsx(bu,{...e,ref:t})});xu.displayName=Cn;var Tt=10,[yu,hn]=nr(Cn),V_="SelectContentImpl",H_=zw("SelectContent.RemoveScroll"),bu=g.forwardRef((e,t)=>{const{__scopeSelect:r,position:s="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:a,onPointerDownOutside:i,side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:f,collisionPadding:h,sticky:x,hideWhenDetached:p,avoidCollisions:y,...j}=e,b=fn(Cn,r),[v,_]=g.useState(null),[C,E]=g.useState(null),S=Ie(t,F=>_(F)),[N,U]=g.useState(null),[k,A]=g.useState(null),P=Is(r),[D,z]=g.useState(!1),L=g.useRef(!1);g.useEffect(()=>{if(v)return nu(v)},[v]),Td();const O=g.useCallback(F=>{const[K,...me]=P().map(ce=>ce.ref.current),[q]=me.slice(-1),te=document.activeElement;for(const ce of F)if(ce===te||(ce?.scrollIntoView({block:"nearest"}),ce===K&&C&&(C.scrollTop=0),ce===q&&C&&(C.scrollTop=C.scrollHeight),ce?.focus(),document.activeElement!==te))return},[P,C]),M=g.useCallback(()=>O([N,v]),[O,N,v]);g.useEffect(()=>{D&&M()},[D,M]);const{onOpenChange:R,triggerPointerDownPosRef:W}=b;g.useEffect(()=>{if(v){let F={x:0,y:0};const K=q=>{F={x:Math.abs(Math.round(q.pageX)-(W.current?.x??0)),y:Math.abs(Math.round(q.pageY)-(W.current?.y??0))}},me=q=>{F.x<=10&&F.y<=10?q.preventDefault():v.contains(q.target)||R(!1),document.removeEventListener("pointermove",K),W.current=null};return W.current!==null&&(document.addEventListener("pointermove",K),document.addEventListener("pointerup",me,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",K),document.removeEventListener("pointerup",me,{capture:!0})}}},[v,R,W]),g.useEffect(()=>{const F=()=>R(!1);return window.addEventListener("blur",F),window.addEventListener("resize",F),()=>{window.removeEventListener("blur",F),window.removeEventListener("resize",F)}},[R]);const[T,V]=Iu(F=>{const K=P().filter(te=>!te.disabled),me=K.find(te=>te.ref.current===document.activeElement),q=Ru(K,F,me);q&&setTimeout(()=>q.ref.current.focus())}),ee=g.useCallback((F,K,me)=>{const q=!L.current&&!me;(b.value!==void 0&&b.value===K||q)&&(U(F),q&&(L.current=!0))},[b.value]),B=g.useCallback(()=>v?.focus(),[v]),Y=g.useCallback((F,K,me)=>{const q=!L.current&&!me;(b.value!==void 0&&b.value===K||q)&&A(F)},[b.value]),J=s==="popper"?qo:vu,ge=J===qo?{side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:f,collisionPadding:h,sticky:x,hideWhenDetached:p,avoidCollisions:y}:{};return n.jsx(yu,{scope:r,content:v,viewport:C,onViewportChange:E,itemRefCallback:ee,selectedItem:N,onItemLeave:B,itemTextRefCallback:Y,focusSelectedItem:M,selectedItemText:k,position:s,isPositioned:D,searchRef:T,children:n.jsx($a,{as:H_,allowPinchZoom:!0,children:n.jsx(Aa,{asChild:!0,trapped:b.open,onMountAutoFocus:F=>{F.preventDefault()},onUnmountAutoFocus:je(o,F=>{b.trigger?.focus({preventScroll:!0}),F.preventDefault()}),children:n.jsx(Na,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:F=>F.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:n.jsx(J,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:F=>F.preventDefault(),...j,...ge,onPlaced:()=>z(!0),ref:S,style:{display:"flex",flexDirection:"column",outline:"none",...j.style},onKeyDown:je(j.onKeyDown,F=>{const K=F.ctrlKey||F.altKey||F.metaKey;if(F.key==="Tab"&&F.preventDefault(),!K&&F.key.length===1&&V(F.key),["ArrowUp","ArrowDown","Home","End"].includes(F.key)){let q=P().filter(te=>!te.disabled).map(te=>te.ref.current);if(["ArrowUp","End"].includes(F.key)&&(q=q.slice().reverse()),["ArrowUp","ArrowDown"].includes(F.key)){const te=F.target,ce=q.indexOf(te);q=q.slice(ce+1)}setTimeout(()=>O(q)),F.preventDefault()}})})})})})})});bu.displayName=V_;var q_="SelectItemAlignedPosition",vu=g.forwardRef((e,t)=>{const{__scopeSelect:r,onPlaced:s,...o}=e,a=fn(Cn,r),i=hn(Cn,r),[c,l]=g.useState(null),[d,m]=g.useState(null),u=Ie(t,S=>m(S)),f=Is(r),h=g.useRef(!1),x=g.useRef(!0),{viewport:p,selectedItem:y,selectedItemText:j,focusSelectedItem:b}=i,v=g.useCallback(()=>{if(a.trigger&&a.valueNode&&c&&d&&p&&y&&j){const S=a.trigger.getBoundingClientRect(),N=d.getBoundingClientRect(),U=a.valueNode.getBoundingClientRect(),k=j.getBoundingClientRect();if(a.dir!=="rtl"){const te=k.left-N.left,ce=U.left-te,pe=S.left-ce,Oe=S.width+pe,Ge=Math.max(Oe,N.width),Qe=window.innerWidth-Tt,$e=dc(ce,[Tt,Math.max(Tt,Qe-Ge)]);c.style.minWidth=Oe+"px",c.style.left=$e+"px"}else{const te=N.right-k.right,ce=window.innerWidth-U.right-te,pe=window.innerWidth-S.right-ce,Oe=S.width+pe,Ge=Math.max(Oe,N.width),Qe=window.innerWidth-Tt,$e=dc(ce,[Tt,Math.max(Tt,Qe-Ge)]);c.style.minWidth=Oe+"px",c.style.right=$e+"px"}const A=f(),P=window.innerHeight-Tt*2,D=p.scrollHeight,z=window.getComputedStyle(d),L=parseInt(z.borderTopWidth,10),O=parseInt(z.paddingTop,10),M=parseInt(z.borderBottomWidth,10),R=parseInt(z.paddingBottom,10),W=L+O+D+R+M,T=Math.min(y.offsetHeight*5,W),V=window.getComputedStyle(p),ee=parseInt(V.paddingTop,10),B=parseInt(V.paddingBottom,10),Y=S.top+S.height/2-Tt,J=P-Y,ge=y.offsetHeight/2,F=y.offsetTop+ge,K=L+O+F,me=W-K;if(K<=Y){const te=A.length>0&&y===A[A.length-1].ref.current;c.style.bottom="0px";const ce=d.clientHeight-p.offsetTop-p.offsetHeight,pe=Math.max(J,ge+(te?B:0)+ce+M),Oe=K+pe;c.style.height=Oe+"px"}else{const te=A.length>0&&y===A[0].ref.current;c.style.top="0px";const pe=Math.max(Y,L+p.offsetTop+(te?ee:0)+ge)+me;c.style.height=pe+"px",p.scrollTop=K-Y+p.offsetTop}c.style.margin=`${Tt}px 0`,c.style.minHeight=T+"px",c.style.maxHeight=P+"px",s?.(),requestAnimationFrame(()=>h.current=!0)}},[f,a.trigger,a.valueNode,c,d,p,y,j,a.dir,s]);tt(()=>v(),[v]);const[_,C]=g.useState();tt(()=>{d&&C(window.getComputedStyle(d).zIndex)},[d]);const E=g.useCallback(S=>{S&&x.current===!0&&(v(),b?.(),x.current=!1)},[v,b]);return n.jsx(G_,{scope:r,contentWrapper:c,shouldExpandOnScrollRef:h,onScrollButtonChange:E,children:n.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:_},children:n.jsx(ve.div,{...o,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});vu.displayName=q_;var Z_="SelectPopperPosition",qo=g.forwardRef((e,t)=>{const{__scopeSelect:r,align:s="start",collisionPadding:o=Tt,...a}=e,i=Rs(r);return n.jsx(Dw,{...i,...a,ref:t,align:s,collisionPadding:o,style:{boxSizing:"border-box",...a.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});qo.displayName=Z_;var[G_,za]=nr(Cn,{}),Zo="SelectViewport",wu=g.forwardRef((e,t)=>{const{__scopeSelect:r,nonce:s,...o}=e,a=hn(Zo,r),i=za(Zo,r),c=Ie(t,a.onViewportChange),l=g.useRef(0);return n.jsxs(n.Fragment,{children:[n.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),n.jsx(Es.Slot,{scope:r,children:n.jsx(ve.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:je(o.onScroll,d=>{const m=d.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:f}=i;if(f?.current&&u){const h=Math.abs(l.current-m.scrollTop);if(h>0){const x=window.innerHeight-Tt*2,p=parseFloat(u.style.minHeight),y=parseFloat(u.style.height),j=Math.max(p,y);if(j<x){const b=j+h,v=Math.min(x,b),_=b-v;u.style.height=v+"px",u.style.bottom==="0px"&&(m.scrollTop=_>0?_:0,u.style.justifyContent="flex-end")}}}l.current=m.scrollTop})})})]})});wu.displayName=Zo;var _u="SelectGroup",[Q_,Y_]=nr(_u),ju=g.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Wt();return n.jsx(Q_,{scope:r,id:o,children:n.jsx(ve.div,{role:"group","aria-labelledby":o,...s,ref:t})})});ju.displayName=_u;var Su="SelectLabel",K_=g.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Y_(Su,r);return n.jsx(ve.div,{id:o.id,...s,ref:t})});K_.displayName=Su;var ms="SelectItem",[J_,ku]=nr(ms),Cu=g.forwardRef((e,t)=>{const{__scopeSelect:r,value:s,disabled:o=!1,textValue:a,...i}=e,c=fn(ms,r),l=hn(ms,r),d=c.value===s,[m,u]=g.useState(a??""),[f,h]=g.useState(!1),x=Ie(t,b=>l.itemRefCallback?.(b,s,o)),p=Wt(),y=g.useRef("touch"),j=()=>{o||(c.onValueChange(s),c.onOpenChange(!1))};if(s==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return n.jsx(J_,{scope:r,value:s,disabled:o,textId:p,isSelected:d,onItemTextChange:g.useCallback(b=>{u(v=>v||(b?.textContent??"").trim())},[]),children:n.jsx(Es.ItemSlot,{scope:r,value:s,disabled:o,textValue:m,children:n.jsx(ve.div,{role:"option","aria-labelledby":p,"data-highlighted":f?"":void 0,"aria-selected":d&&f,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:x,onFocus:je(i.onFocus,()=>h(!0)),onBlur:je(i.onBlur,()=>h(!1)),onClick:je(i.onClick,()=>{y.current!=="mouse"&&j()}),onPointerUp:je(i.onPointerUp,()=>{y.current==="mouse"&&j()}),onPointerDown:je(i.onPointerDown,b=>{y.current=b.pointerType}),onPointerMove:je(i.onPointerMove,b=>{y.current=b.pointerType,o?l.onItemLeave?.():y.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:je(i.onPointerLeave,b=>{b.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:je(i.onKeyDown,b=>{l.searchRef?.current!==""&&b.key===" "||(L_.includes(b.key)&&j(),b.key===" "&&b.preventDefault())})})})})});Cu.displayName=ms;var pr="SelectItemText",Nu=g.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,...a}=e,i=fn(pr,r),c=hn(pr,r),l=ku(pr,r),d=B_(pr,r),[m,u]=g.useState(null),f=Ie(t,j=>u(j),l.onItemTextChange,j=>c.itemTextRefCallback?.(j,l.value,l.disabled)),h=m?.textContent,x=g.useMemo(()=>n.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:p,onNativeOptionRemove:y}=d;return tt(()=>(p(x),()=>y(x)),[p,y,x]),n.jsxs(n.Fragment,{children:[n.jsx(ve.span,{id:l.textId,...a,ref:f}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?ys.createPortal(a.children,i.valueNode):null]})});Nu.displayName=pr;var Au="SelectItemIndicator",X_=g.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return ku(Au,r).isSelected?n.jsx(ve.span,{"aria-hidden":!0,...s,ref:t}):null});X_.displayName=Au;var Go="SelectScrollUpButton",ej=g.forwardRef((e,t)=>{const r=hn(Go,e.__scopeSelect),s=za(Go,e.__scopeSelect),[o,a]=g.useState(!1),i=Ie(t,s.onScrollButtonChange);return tt(()=>{if(r.viewport&&r.isPositioned){let c=function(){const d=l.scrollTop>0;a(d)};const l=r.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),o?n.jsx(Pu,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});ej.displayName=Go;var Qo="SelectScrollDownButton",tj=g.forwardRef((e,t)=>{const r=hn(Qo,e.__scopeSelect),s=za(Qo,e.__scopeSelect),[o,a]=g.useState(!1),i=Ie(t,s.onScrollButtonChange);return tt(()=>{if(r.viewport&&r.isPositioned){let c=function(){const d=l.scrollHeight-l.clientHeight,m=Math.ceil(l.scrollTop)<d;a(m)};const l=r.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),o?n.jsx(Pu,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});tj.displayName=Qo;var Pu=g.forwardRef((e,t)=>{const{__scopeSelect:r,onAutoScroll:s,...o}=e,a=hn("SelectScrollButton",r),i=g.useRef(null),c=Is(r),l=g.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return g.useEffect(()=>()=>l(),[l]),tt(()=>{c().find(m=>m.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),n.jsx(ve.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:je(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(s,50))}),onPointerMove:je(o.onPointerMove,()=>{a.onItemLeave?.(),i.current===null&&(i.current=window.setInterval(s,50))}),onPointerLeave:je(o.onPointerLeave,()=>{l()})})}),nj="SelectSeparator",rj=g.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return n.jsx(ve.div,{"aria-hidden":!0,...s,ref:t})});rj.displayName=nj;var Yo="SelectArrow",sj=g.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Rs(r),a=fn(Yo,r),i=hn(Yo,r);return a.open&&i.position==="popper"?n.jsx(Lw,{...o,...s,ref:t}):null});sj.displayName=Yo;var oj="SelectBubbleInput",Tu=g.forwardRef(({__scopeSelect:e,value:t,...r},s)=>{const o=g.useRef(null),a=Ie(s,o),i=Gw(t);return g.useEffect(()=>{const c=o.current;if(!c)return;const l=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&m){const u=new Event("change",{bubbles:!0});m.call(c,t),c.dispatchEvent(u)}},[i,t]),n.jsx(ve.select,{...r,style:{...eu,...r.style},ref:a,defaultValue:t})});Tu.displayName=oj;function Eu(e){return e===""||e===void 0}function Iu(e){const t=an(e),r=g.useRef(""),s=g.useRef(0),o=g.useCallback(i=>{const c=r.current+i;t(c),(function l(d){r.current=d,window.clearTimeout(s.current),d!==""&&(s.current=window.setTimeout(()=>l(""),1e3))})(c)},[t]),a=g.useCallback(()=>{r.current="",window.clearTimeout(s.current)},[]);return g.useEffect(()=>()=>window.clearTimeout(s.current),[]),[r,o,a]}function Ru(e,t,r){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,a=r?e.indexOf(r):-1;let i=aj(e,Math.max(a,0));o.length===1&&(i=i.filter(d=>d!==r));const l=i.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==r?l:void 0}function aj(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var ij=du,Ou=mu,cj=fu,lj=hu,dj=gu,Mu=xu,uj=wu,mj=ju,Du=Cu,pj=Nu;const ps=ij,fj=mj,fs=cj,Sr=g.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(Ou,{ref:s,className:H("flex h-10 w-full items-center justify-between rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:focus-visible:ring-neutral-50/20",e),...r,children:[t,n.jsx(lj,{className:"ml-2 text-neutral-500 dark:text-neutral-400",children:"▾"})]}));Sr.displayName=Ou.displayName;const kr=g.forwardRef(({className:e,children:t,position:r="popper",...s},o)=>n.jsx(dj,{children:n.jsx(Mu,{ref:o,position:r,className:H("z-50 min-w-[8rem] overflow-hidden rounded-md border border-neutral-200 bg-white text-neutral-950 shadow-md dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",e),...s,children:n.jsx(uj,{className:H("p-1",r==="popper"?"w-full":void 0),children:t})})}));kr.displayName=Mu.displayName;const Cr=g.forwardRef(({className:e,children:t,...r},s)=>n.jsx(Du,{ref:s,className:H("relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-neutral-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-neutral-800",e),...r,children:n.jsx(pj,{children:t})}));Cr.displayName=Du.displayName;function hj(e,t){return g.useReducer((r,s)=>t[r][s]??r,e)}var rr=e=>{const{present:t,children:r}=e,s=gj(t),o=typeof r=="function"?r({present:s.isPresent}):g.Children.only(r),a=Ie(s.ref,xj(o));return typeof r=="function"||s.isPresent?g.cloneElement(o,{ref:a}):null};rr.displayName="Presence";function gj(e){const[t,r]=g.useState(),s=g.useRef(null),o=g.useRef(e),a=g.useRef("none"),i=e?"mounted":"unmounted",[c,l]=hj(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return g.useEffect(()=>{const d=qr(s.current);a.current=c==="mounted"?d:"none"},[c]),tt(()=>{const d=s.current,m=o.current;if(m!==e){const f=a.current,h=qr(d);e?l("MOUNT"):h==="none"||d?.display==="none"?l("UNMOUNT"):l(m&&f!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),tt(()=>{if(t){let d;const m=t.ownerDocument.defaultView??window,u=h=>{const p=qr(s.current).includes(CSS.escape(h.animationName));if(h.target===t&&p&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",d=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},f=h=>{h.target===t&&(a.current=qr(s.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{m.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:g.useCallback(d=>{s.current=d?getComputedStyle(d):null,r(d)},[])}}function qr(e){return e?.animationName||"none"}function xj(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function yj(e){const t=bj(e),r=g.forwardRef((s,o)=>{const{children:a,...i}=s,c=g.Children.toArray(a),l=c.find(wj);if(l){const d=l.props.children,m=c.map(u=>u===l?g.Children.count(d)>1?g.Children.only(null):g.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:g.isValidElement(d)?g.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function bj(e){const t=g.forwardRef((r,s)=>{const{children:o,...a}=r;if(g.isValidElement(o)){const i=jj(o),c=_j(a,o.props);return o.type!==g.Fragment&&(c.ref=s?Kn(s,i):i),g.cloneElement(o,c)}return g.Children.count(o)>1?g.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var vj=Symbol("radix.slottable");function wj(e){return g.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===vj}function _j(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function jj(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Os="Dialog",[Lu]=pn(Os),[Sj,Dt]=Lu(Os),$u=e=>{const{__scopeDialog:t,children:r,open:s,defaultOpen:o,onOpenChange:a,modal:i=!0}=e,c=g.useRef(null),l=g.useRef(null),[d,m]=dn({prop:s,defaultProp:o??!1,onChange:a,caller:Os});return n.jsx(Sj,{scope:t,triggerRef:c,contentRef:l,contentId:Wt(),titleId:Wt(),descriptionId:Wt(),open:d,onOpenChange:m,onOpenToggle:g.useCallback(()=>m(u=>!u),[m]),modal:i,children:r})};$u.displayName=Os;var zu="DialogTrigger",Fu=g.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(zu,r),a=Ie(t,o.triggerRef);return n.jsx(ve.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ua(o.open),...s,ref:a,onClick:je(e.onClick,o.onOpenToggle)})});Fu.displayName=zu;var Fa="DialogPortal",[kj,Bu]=Lu(Fa,{forceMount:void 0}),Uu=e=>{const{__scopeDialog:t,forceMount:r,children:s,container:o}=e,a=Dt(Fa,t);return n.jsx(kj,{scope:t,forceMount:r,children:g.Children.map(s,i=>n.jsx(rr,{present:r||a.open,children:n.jsx(La,{asChild:!0,container:o,children:i})}))})};Uu.displayName=Fa;var hs="DialogOverlay",Wu=g.forwardRef((e,t)=>{const r=Bu(hs,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Dt(hs,e.__scopeDialog);return a.modal?n.jsx(rr,{present:s||a.open,children:n.jsx(Nj,{...o,ref:t})}):null});Wu.displayName=hs;var Cj=yj("DialogOverlay.RemoveScroll"),Nj=g.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(hs,r);return n.jsx($a,{as:Cj,allowPinchZoom:!0,shards:[o.contentRef],children:n.jsx(ve.div,{"data-state":Ua(o.open),...s,ref:t,style:{pointerEvents:"auto",...s.style}})})}),Nn="DialogContent",Vu=g.forwardRef((e,t)=>{const r=Bu(Nn,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Dt(Nn,e.__scopeDialog);return n.jsx(rr,{present:s||a.open,children:a.modal?n.jsx(Aj,{...o,ref:t}):n.jsx(Pj,{...o,ref:t})})});Vu.displayName=Nn;var Aj=g.forwardRef((e,t)=>{const r=Dt(Nn,e.__scopeDialog),s=g.useRef(null),o=Ie(t,r.contentRef,s);return g.useEffect(()=>{const a=s.current;if(a)return nu(a)},[]),n.jsx(Hu,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:je(e.onCloseAutoFocus,a=>{a.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:je(e.onPointerDownOutside,a=>{const i=a.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&a.preventDefault()}),onFocusOutside:je(e.onFocusOutside,a=>a.preventDefault())})}),Pj=g.forwardRef((e,t)=>{const r=Dt(Nn,e.__scopeDialog),s=g.useRef(!1),o=g.useRef(!1);return n.jsx(Hu,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(s.current||r.triggerRef.current?.focus(),a.preventDefault()),s.current=!1,o.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(s.current=!0,a.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=a.target;r.triggerRef.current?.contains(i)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&o.current&&a.preventDefault()}})}),Hu=g.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,...i}=e,c=Dt(Nn,r),l=g.useRef(null),d=Ie(t,l);return Td(),n.jsxs(n.Fragment,{children:[n.jsx(Aa,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:o,onUnmountAutoFocus:a,children:n.jsx(Na,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":Ua(c.open),...i,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),n.jsxs(n.Fragment,{children:[n.jsx(Tj,{titleId:c.titleId}),n.jsx(Ij,{contentRef:l,descriptionId:c.descriptionId})]})]})}),Ba="DialogTitle",qu=g.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(Ba,r);return n.jsx(ve.h2,{id:o.titleId,...s,ref:t})});qu.displayName=Ba;var Zu="DialogDescription",Gu=g.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(Zu,r);return n.jsx(ve.p,{id:o.descriptionId,...s,ref:t})});Gu.displayName=Zu;var Qu="DialogClose",Yu=g.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(Qu,r);return n.jsx(ve.button,{type:"button",...s,ref:t,onClick:je(e.onClick,()=>o.onOpenChange(!1))})});Yu.displayName=Qu;function Ua(e){return e?"open":"closed"}var Ku="DialogTitleWarning",[Yk,Ju]=Dv(Ku,{contentName:Nn,titleName:Ba,docsSlug:"dialog"}),Tj=({titleId:e})=>{const t=Ju(Ku),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
132
-
133
- If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
134
-
135
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return g.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},Ej="DialogDescriptionWarning",Ij=({contentRef:e,descriptionId:t})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Ju(Ej).contentName}}.`;return g.useEffect(()=>{const o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(s))},[s,e,t]),null},Xu=$u,em=Fu,tm=Uu,Ms=Wu,Ds=Vu,Ls=qu,$s=Gu,nm=Yu;const Wa=Xu,Rj=em,rm=tm,Oj=nm,Va=g.forwardRef(({className:e,...t},r)=>n.jsx(Ms,{ref:r,className:H("fixed inset-0 z-50 bg-neutral-950/40 backdrop-blur-sm transition-opacity data-[state=closed]:opacity-0 data-[state=open]:opacity-100",e),...t}));Va.displayName=Ms.displayName;const zs=g.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(rm,{children:[n.jsx(Va,{}),n.jsx(Ds,{ref:s,className:H("fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border border-neutral-200 bg-white p-6 shadow-lg outline-none transition data-[state=closed]:opacity-0 data-[state=closed]:scale-95 data-[state=open]:opacity-100 data-[state=open]:scale-100 dark:border-neutral-800 dark:bg-neutral-950","rounded-2xl",e),...r,children:t})]}));zs.displayName=Ds.displayName;const Ha=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-center sm:text-left",e),...t}),sm=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t}),Fs=g.forwardRef(({className:e,...t},r)=>n.jsx(Ls,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));Fs.displayName=Ls.displayName;const qa=g.forwardRef(({className:e,...t},r)=>n.jsx($s,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));qa.displayName=$s.displayName;const Bs=Xu,Us=em,om=nm,am=tm,Za=g.forwardRef(({className:e,...t},r)=>n.jsx(Ms,{ref:r,className:H("fixed inset-0 z-50 bg-neutral-950/40 backdrop-blur-sm transition-opacity data-[state=closed]:opacity-0 data-[state=open]:opacity-100",e),...t}));Za.displayName=Ms.displayName;const Mj=Sa("fixed z-50 gap-4 bg-white p-6 shadow-lg outline-none transition duration-200 ease-out dark:bg-neutral-950",{variants:{side:{top:"inset-x-0 top-0 border-b border-neutral-200 data-[state=closed]:-translate-y-full data-[state=open]:translate-y-0 dark:border-neutral-800",bottom:"inset-x-0 bottom-0 border-t border-neutral-200 data-[state=closed]:translate-y-full data-[state=open]:translate-y-0 dark:border-neutral-800",left:"inset-y-0 left-0 h-full w-3/4 border-r border-neutral-200 data-[state=closed]:-translate-x-full data-[state=open]:translate-x-0 sm:max-w-sm dark:border-neutral-800",right:"inset-y-0 right-0 h-full w-3/4 border-l border-neutral-200 data-[state=closed]:translate-x-full data-[state=open]:translate-x-0 sm:max-w-sm dark:border-neutral-800",popup:"bottom-4 right-4 w-[420px] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-2rem)] overflow-hidden rounded-2xl border border-neutral-200 p-4 data-[state=closed]:translate-y-2 data-[state=open]:translate-y-0 data-[state=closed]:opacity-0 data-[state=open]:opacity-100 data-[state=closed]:scale-95 data-[state=open]:scale-100 dark:border-neutral-800"}},defaultVariants:{side:"right"}}),Tr=g.forwardRef(({side:e="right",className:t,children:r,overlayClassName:s,...o},a)=>n.jsxs(am,{children:[n.jsx(Za,{className:s}),n.jsx(Ds,{ref:a,className:H(Mj({side:e}),t),...o,children:r})]}));Tr.displayName=Ds.displayName;const Ws=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-left",e),...t}),Vs=g.forwardRef(({className:e,...t},r)=>n.jsx(Ls,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));Vs.displayName=Ls.displayName;const im=g.forwardRef(({className:e,...t},r)=>n.jsx($s,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));im.displayName=$s.displayName;var Hs="Collapsible",[Dj,cm]=pn(Hs),[Lj,Ga]=Dj(Hs),lm=g.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:s,defaultOpen:o,disabled:a,onOpenChange:i,...c}=e,[l,d]=dn({prop:s,defaultProp:o??!1,onChange:i,caller:Hs});return n.jsx(Lj,{scope:r,disabled:a,contentId:Wt(),open:l,onOpenToggle:g.useCallback(()=>d(m=>!m),[d]),children:n.jsx(ve.div,{"data-state":Ya(l),"data-disabled":a?"":void 0,...c,ref:t})})});lm.displayName=Hs;var dm="CollapsibleTrigger",um=g.forwardRef((e,t)=>{const{__scopeCollapsible:r,...s}=e,o=Ga(dm,r);return n.jsx(ve.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":Ya(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...s,ref:t,onClick:je(e.onClick,o.onOpenToggle)})});um.displayName=dm;var Qa="CollapsibleContent",mm=g.forwardRef((e,t)=>{const{forceMount:r,...s}=e,o=Ga(Qa,e.__scopeCollapsible);return n.jsx(rr,{present:r||o.open,children:({present:a})=>n.jsx($j,{...s,ref:t,present:a})})});mm.displayName=Qa;var $j=g.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:s,children:o,...a}=e,i=Ga(Qa,r),[c,l]=g.useState(s),d=g.useRef(null),m=Ie(t,d),u=g.useRef(0),f=u.current,h=g.useRef(0),x=h.current,p=i.open||c,y=g.useRef(p),j=g.useRef(void 0);return g.useEffect(()=>{const b=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(b)},[]),tt(()=>{const b=d.current;if(b){j.current=j.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const v=b.getBoundingClientRect();u.current=v.height,h.current=v.width,y.current||(b.style.transitionDuration=j.current.transitionDuration,b.style.animationName=j.current.animationName),l(s)}},[i.open,s]),n.jsx(ve.div,{"data-state":Ya(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!p,...a,ref:m,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":x?`${x}px`:void 0,...e.style},children:p&&o})});function Ya(e){return e?"open":"closed"}var zj=lm,Fj=um,Bj=mm,Lt="Accordion",Uj=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[Ka,Wj,Vj]=Ca(Lt),[qs]=pn(Lt,[Vj,cm]),Ja=cm(),pm=w.forwardRef((e,t)=>{const{type:r,...s}=e,o=s,a=s;return n.jsx(Ka.Provider,{scope:e.__scopeAccordion,children:r==="multiple"?n.jsx(Gj,{...a,ref:t}):n.jsx(Zj,{...o,ref:t})})});pm.displayName=Lt;var[fm,Hj]=qs(Lt),[hm,qj]=qs(Lt,{collapsible:!1}),Zj=w.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},collapsible:a=!1,...i}=e,[c,l]=dn({prop:r,defaultProp:s??"",onChange:o,caller:Lt});return n.jsx(fm,{scope:e.__scopeAccordion,value:w.useMemo(()=>c?[c]:[],[c]),onItemOpen:l,onItemClose:w.useCallback(()=>a&&l(""),[a,l]),children:n.jsx(hm,{scope:e.__scopeAccordion,collapsible:a,children:n.jsx(gm,{...i,ref:t})})})}),Gj=w.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},...a}=e,[i,c]=dn({prop:r,defaultProp:s??[],onChange:o,caller:Lt}),l=w.useCallback(m=>c((u=[])=>[...u,m]),[c]),d=w.useCallback(m=>c((u=[])=>u.filter(f=>f!==m)),[c]);return n.jsx(fm,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:d,children:n.jsx(hm,{scope:e.__scopeAccordion,collapsible:!0,children:n.jsx(gm,{...a,ref:t})})})}),[Qj,Zs]=qs(Lt),gm=w.forwardRef((e,t)=>{const{__scopeAccordion:r,disabled:s,dir:o,orientation:a="vertical",...i}=e,c=w.useRef(null),l=Ie(c,t),d=Wj(r),u=ks(o)==="ltr",f=je(e.onKeyDown,h=>{if(!Uj.includes(h.key))return;const x=h.target,p=d().filter(N=>!N.ref.current?.disabled),y=p.findIndex(N=>N.ref.current===x),j=p.length;if(y===-1)return;h.preventDefault();let b=y;const v=0,_=j-1,C=()=>{b=y+1,b>_&&(b=v)},E=()=>{b=y-1,b<v&&(b=_)};switch(h.key){case"Home":b=v;break;case"End":b=_;break;case"ArrowRight":a==="horizontal"&&(u?C():E());break;case"ArrowDown":a==="vertical"&&C();break;case"ArrowLeft":a==="horizontal"&&(u?E():C());break;case"ArrowUp":a==="vertical"&&E();break}const S=b%j;p[S].ref.current?.focus()});return n.jsx(Qj,{scope:r,disabled:s,direction:o,orientation:a,children:n.jsx(Ka.Slot,{scope:r,children:n.jsx(ve.div,{...i,"data-orientation":a,ref:l,onKeyDown:s?void 0:f})})})}),gs="AccordionItem",[Yj,Xa]=qs(gs),xm=w.forwardRef((e,t)=>{const{__scopeAccordion:r,value:s,...o}=e,a=Zs(gs,r),i=Hj(gs,r),c=Ja(r),l=Wt(),d=s&&i.value.includes(s)||!1,m=a.disabled||e.disabled;return n.jsx(Yj,{scope:r,open:d,disabled:m,triggerId:l,children:n.jsx(zj,{"data-orientation":a.orientation,"data-state":jm(d),...c,...o,ref:t,disabled:m,open:d,onOpenChange:u=>{u?i.onItemOpen(s):i.onItemClose(s)}})})});xm.displayName=gs;var ym="AccordionHeader",bm=w.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=Zs(Lt,r),a=Xa(ym,r);return n.jsx(ve.h3,{"data-orientation":o.orientation,"data-state":jm(a.open),"data-disabled":a.disabled?"":void 0,...s,ref:t})});bm.displayName=ym;var Ko="AccordionTrigger",vm=w.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=Zs(Lt,r),a=Xa(Ko,r),i=qj(Ko,r),c=Ja(r);return n.jsx(Ka.ItemSlot,{scope:r,children:n.jsx(Fj,{"aria-disabled":a.open&&!i.collapsible||void 0,"data-orientation":o.orientation,id:a.triggerId,...c,...s,ref:t})})});vm.displayName=Ko;var wm="AccordionContent",_m=w.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=Zs(Lt,r),a=Xa(wm,r),i=Ja(r);return n.jsx(Bj,{role:"region","aria-labelledby":a.triggerId,"data-orientation":o.orientation,...i,...s,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});_m.displayName=wm;function jm(e){return e?"open":"closed"}var Kj=pm,Sm=xm,Jj=bm,km=vm,Cm=_m;const Nm=Kj,hr=g.forwardRef(({className:e,...t},r)=>n.jsx(Sm,{ref:r,className:H("border-b border-neutral-200 dark:border-neutral-800",e),...t}));hr.displayName=Sm.displayName;const gr=g.forwardRef(({className:e,children:t,...r},s)=>n.jsx(Jj,{className:"flex",children:n.jsxs(km,{ref:s,className:H("flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline",e),...r,children:[t,n.jsx("span",{className:"ml-3 text-neutral-500 dark:text-neutral-400","aria-hidden":!0,children:"▾"})]})}));gr.displayName=km.displayName;const xr=g.forwardRef(({className:e,children:t,...r},s)=>n.jsx(Cm,{ref:s,className:H("overflow-hidden text-sm",e),...r,children:n.jsx("div",{className:"pb-4 pt-0",children:t})}));xr.displayName=Cm.displayName;var ko="rovingFocusGroup.onEntryFocus",Xj={bubbles:!1,cancelable:!0},Er="RovingFocusGroup",[Jo,Am,eS]=Ca(Er),[tS,Pm]=pn(Er,[eS]),[nS,rS]=tS(Er),Tm=g.forwardRef((e,t)=>n.jsx(Jo.Provider,{scope:e.__scopeRovingFocusGroup,children:n.jsx(Jo.Slot,{scope:e.__scopeRovingFocusGroup,children:n.jsx(sS,{...e,ref:t})})}));Tm.displayName=Er;var sS=g.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,orientation:s,loop:o=!1,dir:a,currentTabStopId:i,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:m=!1,...u}=e,f=g.useRef(null),h=Ie(t,f),x=ks(a),[p,y]=dn({prop:i,defaultProp:c??null,onChange:l,caller:Er}),[j,b]=g.useState(!1),v=an(d),_=Am(r),C=g.useRef(!1),[E,S]=g.useState(0);return g.useEffect(()=>{const N=f.current;if(N)return N.addEventListener(ko,v),()=>N.removeEventListener(ko,v)},[v]),n.jsx(nS,{scope:r,orientation:s,dir:x,loop:o,currentTabStopId:p,onItemFocus:g.useCallback(N=>y(N),[y]),onItemShiftTab:g.useCallback(()=>b(!0),[]),onFocusableItemAdd:g.useCallback(()=>S(N=>N+1),[]),onFocusableItemRemove:g.useCallback(()=>S(N=>N-1),[]),children:n.jsx(ve.div,{tabIndex:j||E===0?-1:0,"data-orientation":s,...u,ref:h,style:{outline:"none",...e.style},onMouseDown:je(e.onMouseDown,()=>{C.current=!0}),onFocus:je(e.onFocus,N=>{const U=!C.current;if(N.target===N.currentTarget&&U&&!j){const k=new CustomEvent(ko,Xj);if(N.currentTarget.dispatchEvent(k),!k.defaultPrevented){const A=_().filter(O=>O.focusable),P=A.find(O=>O.active),D=A.find(O=>O.id===p),L=[P,D,...A].filter(Boolean).map(O=>O.ref.current);Rm(L,m)}}C.current=!1}),onBlur:je(e.onBlur,()=>b(!1))})})}),Em="RovingFocusGroupItem",Im=g.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,focusable:s=!0,active:o=!1,tabStopId:a,children:i,...c}=e,l=Wt(),d=a||l,m=rS(Em,r),u=m.currentTabStopId===d,f=Am(r),{onFocusableItemAdd:h,onFocusableItemRemove:x,currentTabStopId:p}=m;return g.useEffect(()=>{if(s)return h(),()=>x()},[s,h,x]),n.jsx(Jo.ItemSlot,{scope:r,id:d,focusable:s,active:o,children:n.jsx(ve.span,{tabIndex:u?0:-1,"data-orientation":m.orientation,...c,ref:t,onMouseDown:je(e.onMouseDown,y=>{s?m.onItemFocus(d):y.preventDefault()}),onFocus:je(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:je(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){m.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const j=iS(y,m.orientation,m.dir);if(j!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let v=f().filter(_=>_.focusable).map(_=>_.ref.current);if(j==="last")v.reverse();else if(j==="prev"||j==="next"){j==="prev"&&v.reverse();const _=v.indexOf(y.currentTarget);v=m.loop?cS(v,_+1):v.slice(_+1)}setTimeout(()=>Rm(v))}}),children:typeof i=="function"?i({isCurrentTabStop:u,hasTabStop:p!=null}):i})})});Im.displayName=Em;var oS={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function aS(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function iS(e,t,r){const s=aS(e.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(s))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(s)))return oS[s]}function Rm(e,t=!1){const r=document.activeElement;for(const s of e)if(s===r||(s.focus({preventScroll:t}),document.activeElement!==r))return}function cS(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var lS=Tm,dS=Im,Gs="Tabs",[uS]=pn(Gs,[Pm]),Om=Pm(),[mS,ei]=uS(Gs),Mm=g.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,onValueChange:o,defaultValue:a,orientation:i="horizontal",dir:c,activationMode:l="automatic",...d}=e,m=ks(c),[u,f]=dn({prop:s,onChange:o,defaultProp:a??"",caller:Gs});return n.jsx(mS,{scope:r,baseId:Wt(),value:u,onValueChange:f,orientation:i,dir:m,activationMode:l,children:n.jsx(ve.div,{dir:m,"data-orientation":i,...d,ref:t})})});Mm.displayName=Gs;var Dm="TabsList",Lm=g.forwardRef((e,t)=>{const{__scopeTabs:r,loop:s=!0,...o}=e,a=ei(Dm,r),i=Om(r);return n.jsx(lS,{asChild:!0,...i,orientation:a.orientation,dir:a.dir,loop:s,children:n.jsx(ve.div,{role:"tablist","aria-orientation":a.orientation,...o,ref:t})})});Lm.displayName=Dm;var $m="TabsTrigger",zm=g.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,disabled:o=!1,...a}=e,i=ei($m,r),c=Om(r),l=Um(i.baseId,s),d=Wm(i.baseId,s),m=s===i.value;return n.jsx(dS,{asChild:!0,...c,focusable:!o,active:m,children:n.jsx(ve.button,{type:"button",role:"tab","aria-selected":m,"aria-controls":d,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:l,...a,ref:t,onMouseDown:je(e.onMouseDown,u=>{!o&&u.button===0&&u.ctrlKey===!1?i.onValueChange(s):u.preventDefault()}),onKeyDown:je(e.onKeyDown,u=>{[" ","Enter"].includes(u.key)&&i.onValueChange(s)}),onFocus:je(e.onFocus,()=>{const u=i.activationMode!=="manual";!m&&!o&&u&&i.onValueChange(s)})})})});zm.displayName=$m;var Fm="TabsContent",Bm=g.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,forceMount:o,children:a,...i}=e,c=ei(Fm,r),l=Um(c.baseId,s),d=Wm(c.baseId,s),m=s===c.value,u=g.useRef(m);return g.useEffect(()=>{const f=requestAnimationFrame(()=>u.current=!1);return()=>cancelAnimationFrame(f)},[]),n.jsx(rr,{present:o||m,children:({present:f})=>n.jsx(ve.div,{"data-state":m?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!f,id:d,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:u.current?"0s":void 0},children:f&&a})})});Bm.displayName=Fm;function Um(e,t){return`${e}-trigger-${t}`}function Wm(e,t){return`${e}-content-${t}`}var pS=Mm,Vm=Lm,Hm=zm,qm=Bm;const ti=pS,Qs=g.forwardRef(({className:e,...t},r)=>n.jsx(Vm,{ref:r,className:H("inline-flex h-10 items-center justify-center rounded-md bg-neutral-100 p-1 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400",e),...t}));Qs.displayName=Vm.displayName;const Nr=g.forwardRef(({className:e,...t},r)=>n.jsx(Hm,{ref:r,className:H("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-neutral-950 data-[state=active]:shadow-sm dark:ring-offset-neutral-950 dark:focus-visible:ring-neutral-50/20 dark:data-[state=active]:bg-neutral-950 dark:data-[state=active]:text-neutral-50",e),...t}));Nr.displayName=Hm.displayName;const Zm=g.forwardRef(({className:e,...t},r)=>n.jsx(qm,{ref:r,className:H("mt-2 ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 dark:ring-offset-neutral-950 dark:focus-visible:ring-neutral-50/20",e),...t}));Zm.displayName=qm.displayName;function Zn({title:e,description:t,actionLabel:r,onAction:s,className:o}){return n.jsx("div",{className:H("flex flex-col items-center justify-center rounded-xl border border-neutral-200 bg-white p-10 text-center dark:border-neutral-800 dark:bg-neutral-950",o),children:n.jsxs("div",{className:"max-w-sm",children:[n.jsx("h3",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:e}),t?n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}):null,r&&s?n.jsx("div",{className:"mt-5",children:n.jsx(ie,{type:"button",onClick:s,variant:"secondary",children:r})}):null]})})}function Ht({title:e,description:t,onRetry:r,className:s}){return n.jsxs("div",{className:H("rounded-xl border border-neutral-200 bg-white p-6 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h3",{className:"text-sm font-semibold",children:e??"Something went wrong"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}),r?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"Try again"})}):null]})}class fS extends g.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error):n.jsx(Ht,{description:this.state.error.message}):this.props.children}}function hS(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}const gS=e=>{switch(e){case"success":return bS;case"info":return wS;case"warning":return vS;case"error":return _S;default:return null}},xS=Array(12).fill(0),yS=({visible:e,className:t})=>w.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},w.createElement("div",{className:"sonner-spinner"},xS.map((r,s)=>w.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),bS=w.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},w.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),vS=w.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},w.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),wS=w.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},w.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),_S=w.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},w.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),jS=w.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},w.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),w.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),SS=()=>{const[e,t]=w.useState(document.hidden);return w.useEffect(()=>{const r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),e};let Xo=1;class kS{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const r=this.subscribers.indexOf(t);this.subscribers.splice(r,1)}),this.publish=t=>{this.subscribers.forEach(r=>r(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var r;const{message:s,...o}=t,a=typeof t?.id=="number"||((r=t.id)==null?void 0:r.length)>0?t.id:Xo++,i=this.toasts.find(l=>l.id===a),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(a)&&this.dismissedToasts.delete(a),i?this.toasts=this.toasts.map(l=>l.id===a?(this.publish({...l,...t,id:a,title:s}),{...l,...t,id:a,dismissible:c,title:s}):l):this.addToast({title:s,...o,dismissible:c,id:a}),a},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(r=>r({id:t,dismiss:!0})))):this.toasts.forEach(r=>{this.subscribers.forEach(s=>s({id:r.id,dismiss:!0}))}),t),this.message=(t,r)=>this.create({...r,message:t}),this.error=(t,r)=>this.create({...r,message:t,type:"error"}),this.success=(t,r)=>this.create({...r,type:"success",message:t}),this.info=(t,r)=>this.create({...r,type:"info",message:t}),this.warning=(t,r)=>this.create({...r,type:"warning",message:t}),this.loading=(t,r)=>this.create({...r,type:"loading",message:t}),this.promise=(t,r)=>{if(!r)return;let s;r.loading!==void 0&&(s=this.create({...r,promise:t,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));const o=Promise.resolve(t instanceof Function?t():t);let a=s!==void 0,i;const c=o.then(async d=>{if(i=["resolve",d],w.isValidElement(d))a=!1,this.create({id:s,type:"default",message:d});else if(NS(d)&&!d.ok){a=!1;const u=typeof r.error=="function"?await r.error(`HTTP error! status: ${d.status}`):r.error,f=typeof r.description=="function"?await r.description(`HTTP error! status: ${d.status}`):r.description,x=typeof u=="object"&&!w.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:f,...x})}else if(d instanceof Error){a=!1;const u=typeof r.error=="function"?await r.error(d):r.error,f=typeof r.description=="function"?await r.description(d):r.description,x=typeof u=="object"&&!w.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:f,...x})}else if(r.success!==void 0){a=!1;const u=typeof r.success=="function"?await r.success(d):r.success,f=typeof r.description=="function"?await r.description(d):r.description,x=typeof u=="object"&&!w.isValidElement(u)?u:{message:u};this.create({id:s,type:"success",description:f,...x})}}).catch(async d=>{if(i=["reject",d],r.error!==void 0){a=!1;const m=typeof r.error=="function"?await r.error(d):r.error,u=typeof r.description=="function"?await r.description(d):r.description,h=typeof m=="object"&&!w.isValidElement(m)?m:{message:m};this.create({id:s,type:"error",description:u,...h})}}).finally(()=>{a&&(this.dismiss(s),s=void 0),r.finally==null||r.finally.call(r)}),l=()=>new Promise((d,m)=>c.then(()=>i[0]==="reject"?m(i[1]):d(i[1])).catch(m));return typeof s!="string"&&typeof s!="number"?{unwrap:l}:Object.assign(s,{unwrap:l})},this.custom=(t,r)=>{const s=r?.id||Xo++;return this.create({jsx:t(s),id:s,...r}),s},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ht=new kS,CS=(e,t)=>{const r=t?.id||Xo++;return ht.addToast({title:e,...t,id:r}),r},NS=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",AS=CS,PS=()=>ht.toasts,TS=()=>ht.getActiveToasts(),ES=Object.assign(AS,{success:ht.success,info:ht.info,warning:ht.warning,error:ht.error,custom:ht.custom,message:ht.message,promise:ht.promise,dismiss:ht.dismiss,loading:ht.loading},{getHistory:PS,getToasts:TS});hS("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Zr(e){return e.label!==void 0}const IS=3,RS="24px",OS="16px",Mc=4e3,MS=356,DS=14,LS=45,$S=200;function zt(...e){return e.filter(Boolean).join(" ")}function zS(e){const[t,r]=e.split("-"),s=[];return t&&s.push(t),r&&s.push(r),s}const FS=e=>{var t,r,s,o,a,i,c,l,d;const{invert:m,toast:u,unstyled:f,interacting:h,setHeights:x,visibleToasts:p,heights:y,index:j,toasts:b,expanded:v,removeToast:_,defaultRichColors:C,closeButton:E,style:S,cancelButtonStyle:N,actionButtonStyle:U,className:k="",descriptionClassName:A="",duration:P,position:D,gap:z,expandByDefault:L,classNames:O,icons:M,closeButtonAriaLabel:R="Close toast"}=e,[W,T]=w.useState(null),[V,ee]=w.useState(null),[B,Y]=w.useState(!1),[J,ge]=w.useState(!1),[F,K]=w.useState(!1),[me,q]=w.useState(!1),[te,ce]=w.useState(!1),[pe,Oe]=w.useState(0),[Ge,Qe]=w.useState(0),$e=w.useRef(u.duration||P||Mc),Ye=w.useRef(null),Ne=w.useRef(null),st=j===0,Ae=j+1<=p,Fe=u.type,de=u.dismissible!==!1,ke=u.className||"",$=u.descriptionClassName||"",X=w.useMemo(()=>y.findIndex(he=>he.toastId===u.id)||0,[y,u.id]),ne=w.useMemo(()=>{var he;return(he=u.closeButton)!=null?he:E},[u.closeButton,E]),xe=w.useMemo(()=>u.duration||P||Mc,[u.duration,P]),we=w.useRef(0),Te=w.useRef(0),Pn=w.useRef(0),Qt=w.useRef(null),[Tn,En]=D.split("-"),jt=w.useMemo(()=>y.reduce((he,Be,_e)=>_e>=X?he:he+Be.height,0),[y,X]),Yt=SS(),sr=u.invert||m,gn=Fe==="loading";Te.current=w.useMemo(()=>X*z+jt,[X,jt]),w.useEffect(()=>{$e.current=xe},[xe]),w.useEffect(()=>{Y(!0)},[]),w.useEffect(()=>{const he=Ne.current;if(he){const Be=he.getBoundingClientRect().height;return Qe(Be),x(_e=>[{toastId:u.id,height:Be,position:u.position},..._e]),()=>x(_e=>_e.filter(Ue=>Ue.toastId!==u.id))}},[x,u.id]),w.useLayoutEffect(()=>{if(!B)return;const he=Ne.current,Be=he.style.height;he.style.height="auto";const _e=he.getBoundingClientRect().height;he.style.height=Be,Qe(_e),x(Ue=>Ue.find(We=>We.toastId===u.id)?Ue.map(We=>We.toastId===u.id?{...We,height:_e}:We):[{toastId:u.id,height:_e,position:u.position},...Ue])},[B,u.title,u.description,x,u.id,u.jsx,u.action,u.cancel]);const $t=w.useCallback(()=>{ge(!0),Oe(Te.current),x(he=>he.filter(Be=>Be.toastId!==u.id)),setTimeout(()=>{_(u)},$S)},[u,_,x,Te]);w.useEffect(()=>{if(u.promise&&Fe==="loading"||u.duration===1/0||u.type==="loading")return;let he;return v||h||Yt?(()=>{if(Pn.current<we.current){const Ue=new Date().getTime()-we.current;$e.current=$e.current-Ue}Pn.current=new Date().getTime()})():(()=>{$e.current!==1/0&&(we.current=new Date().getTime(),he=setTimeout(()=>{u.onAutoClose==null||u.onAutoClose.call(u,u),$t()},$e.current))})(),()=>clearTimeout(he)},[v,h,u,Fe,Yt,$t]),w.useEffect(()=>{u.delete&&($t(),u.onDismiss==null||u.onDismiss.call(u,u))},[$t,u.delete]);function In(){var he;if(M?.loading){var Be;return w.createElement("div",{className:zt(O?.loader,u==null||(Be=u.classNames)==null?void 0:Be.loader,"sonner-loader"),"data-visible":Fe==="loading"},M.loading)}return w.createElement(yS,{className:zt(O?.loader,u==null||(he=u.classNames)==null?void 0:he.loader),visible:Fe==="loading"})}const Rn=u.icon||M?.[Fe]||gS(Fe);var Ir,rn;return w.createElement("li",{tabIndex:0,ref:Ne,className:zt(k,ke,O?.toast,u==null||(t=u.classNames)==null?void 0:t.toast,O?.default,O?.[Fe],u==null||(r=u.classNames)==null?void 0:r[Fe]),"data-sonner-toast":"","data-rich-colors":(Ir=u.richColors)!=null?Ir:C,"data-styled":!(u.jsx||u.unstyled||f),"data-mounted":B,"data-promise":!!u.promise,"data-swiped":te,"data-removed":J,"data-visible":Ae,"data-y-position":Tn,"data-x-position":En,"data-index":j,"data-front":st,"data-swiping":F,"data-dismissible":de,"data-type":Fe,"data-invert":sr,"data-swipe-out":me,"data-swipe-direction":V,"data-expanded":!!(v||L&&B),"data-testid":u.testId,style:{"--index":j,"--toasts-before":j,"--z-index":b.length-j,"--offset":`${J?pe:Te.current}px`,"--initial-height":L?"auto":`${Ge}px`,...S,...u.style},onDragEnd:()=>{K(!1),T(null),Qt.current=null},onPointerDown:he=>{he.button!==2&&(gn||!de||(Ye.current=new Date,Oe(Te.current),he.target.setPointerCapture(he.pointerId),he.target.tagName!=="BUTTON"&&(K(!0),Qt.current={x:he.clientX,y:he.clientY})))},onPointerUp:()=>{var he,Be,_e;if(me||!de)return;Qt.current=null;const Ue=Number(((he=Ne.current)==null?void 0:he.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),On=Number(((Be=Ne.current)==null?void 0:Be.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),We=new Date().getTime()-((_e=Ye.current)==null?void 0:_e.getTime()),nt=W==="x"?Ue:On,xn=Math.abs(nt)/We;if(Math.abs(nt)>=LS||xn>.11){Oe(Te.current),u.onDismiss==null||u.onDismiss.call(u,u),ee(W==="x"?Ue>0?"right":"left":On>0?"down":"up"),$t(),q(!0);return}else{var pt,xt;(pt=Ne.current)==null||pt.style.setProperty("--swipe-amount-x","0px"),(xt=Ne.current)==null||xt.style.setProperty("--swipe-amount-y","0px")}ce(!1),K(!1),T(null)},onPointerMove:he=>{var Be,_e,Ue;if(!Qt.current||!de||((Be=window.getSelection())==null?void 0:Be.toString().length)>0)return;const We=he.clientY-Qt.current.y,nt=he.clientX-Qt.current.x;var xn;const pt=(xn=e.swipeDirections)!=null?xn:zS(D);!W&&(Math.abs(nt)>1||Math.abs(We)>1)&&T(Math.abs(nt)>Math.abs(We)?"x":"y");let xt={x:0,y:0};const yt=ot=>1/(1.5+Math.abs(ot)/20);if(W==="y"){if(pt.includes("top")||pt.includes("bottom"))if(pt.includes("top")&&We<0||pt.includes("bottom")&&We>0)xt.y=We;else{const ot=We*yt(We);xt.y=Math.abs(ot)<Math.abs(We)?ot:We}}else if(W==="x"&&(pt.includes("left")||pt.includes("right")))if(pt.includes("left")&&nt<0||pt.includes("right")&&nt>0)xt.x=nt;else{const ot=nt*yt(nt);xt.x=Math.abs(ot)<Math.abs(nt)?ot:nt}(Math.abs(xt.x)>0||Math.abs(xt.y)>0)&&ce(!0),(_e=Ne.current)==null||_e.style.setProperty("--swipe-amount-x",`${xt.x}px`),(Ue=Ne.current)==null||Ue.style.setProperty("--swipe-amount-y",`${xt.y}px`)}},ne&&!u.jsx&&Fe!=="loading"?w.createElement("button",{"aria-label":R,"data-disabled":gn,"data-close-button":!0,onClick:gn||!de?()=>{}:()=>{$t(),u.onDismiss==null||u.onDismiss.call(u,u)},className:zt(O?.closeButton,u==null||(s=u.classNames)==null?void 0:s.closeButton)},(rn=M?.close)!=null?rn:jS):null,(Fe||u.icon||u.promise)&&u.icon!==null&&(M?.[Fe]!==null||u.icon)?w.createElement("div",{"data-icon":"",className:zt(O?.icon,u==null||(o=u.classNames)==null?void 0:o.icon)},u.promise||u.type==="loading"&&!u.icon?u.icon||In():null,u.type!=="loading"?Rn:null):null,w.createElement("div",{"data-content":"",className:zt(O?.content,u==null||(a=u.classNames)==null?void 0:a.content)},w.createElement("div",{"data-title":"",className:zt(O?.title,u==null||(i=u.classNames)==null?void 0:i.title)},u.jsx?u.jsx:typeof u.title=="function"?u.title():u.title),u.description?w.createElement("div",{"data-description":"",className:zt(A,$,O?.description,u==null||(c=u.classNames)==null?void 0:c.description)},typeof u.description=="function"?u.description():u.description):null),w.isValidElement(u.cancel)?u.cancel:u.cancel&&Zr(u.cancel)?w.createElement("button",{"data-button":!0,"data-cancel":!0,style:u.cancelButtonStyle||N,onClick:he=>{Zr(u.cancel)&&de&&(u.cancel.onClick==null||u.cancel.onClick.call(u.cancel,he),$t())},className:zt(O?.cancelButton,u==null||(l=u.classNames)==null?void 0:l.cancelButton)},u.cancel.label):null,w.isValidElement(u.action)?u.action:u.action&&Zr(u.action)?w.createElement("button",{"data-button":!0,"data-action":!0,style:u.actionButtonStyle||U,onClick:he=>{Zr(u.action)&&(u.action.onClick==null||u.action.onClick.call(u.action,he),!he.defaultPrevented&&$t())},className:zt(O?.actionButton,u==null||(d=u.classNames)==null?void 0:d.actionButton)},u.action.label):null)};function Dc(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function BS(e,t){const r={};return[e,t].forEach((s,o)=>{const a=o===1,i=a?"--mobile-offset":"--offset",c=a?OS:RS;function l(d){["top","right","bottom","left"].forEach(m=>{r[`${i}-${m}`]=typeof d=="number"?`${d}px`:d})}typeof s=="number"||typeof s=="string"?l(s):typeof s=="object"?["top","right","bottom","left"].forEach(d=>{s[d]===void 0?r[`${i}-${d}`]=c:r[`${i}-${d}`]=typeof s[d]=="number"?`${s[d]}px`:s[d]}):l(c)}),r}const US=w.forwardRef(function(t,r){const{id:s,invert:o,position:a="bottom-right",hotkey:i=["altKey","KeyT"],expand:c,closeButton:l,className:d,offset:m,mobileOffset:u,theme:f="light",richColors:h,duration:x,style:p,visibleToasts:y=IS,toastOptions:j,dir:b=Dc(),gap:v=DS,icons:_,containerAriaLabel:C="Notifications"}=t,[E,S]=w.useState([]),N=w.useMemo(()=>s?E.filter(B=>B.toasterId===s):E.filter(B=>!B.toasterId),[E,s]),U=w.useMemo(()=>Array.from(new Set([a].concat(N.filter(B=>B.position).map(B=>B.position)))),[N,a]),[k,A]=w.useState([]),[P,D]=w.useState(!1),[z,L]=w.useState(!1),[O,M]=w.useState(f!=="system"?f:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),R=w.useRef(null),W=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),T=w.useRef(null),V=w.useRef(!1),ee=w.useCallback(B=>{S(Y=>{var J;return(J=Y.find(ge=>ge.id===B.id))!=null&&J.delete||ht.dismiss(B.id),Y.filter(({id:ge})=>ge!==B.id)})},[]);return w.useEffect(()=>ht.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{S(Y=>Y.map(J=>J.id===B.id?{...J,delete:!0}:J))});return}setTimeout(()=>{oa.flushSync(()=>{S(Y=>{const J=Y.findIndex(ge=>ge.id===B.id);return J!==-1?[...Y.slice(0,J),{...Y[J],...B},...Y.slice(J+1)]:[B,...Y]})})})}),[E]),w.useEffect(()=>{if(f!=="system"){M(f);return}if(f==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?M("dark"):M("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:Y})=>{M(Y?"dark":"light")})}catch{B.addListener(({matches:J})=>{try{M(J?"dark":"light")}catch(ge){console.error(ge)}})}},[f]),w.useEffect(()=>{E.length<=1&&D(!1)},[E]),w.useEffect(()=>{const B=Y=>{var J;if(i.every(K=>Y[K]||Y.code===K)){var F;D(!0),(F=R.current)==null||F.focus()}Y.code==="Escape"&&(document.activeElement===R.current||(J=R.current)!=null&&J.contains(document.activeElement))&&D(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[i]),w.useEffect(()=>{if(R.current)return()=>{T.current&&(T.current.focus({preventScroll:!0}),T.current=null,V.current=!1)}},[R.current]),w.createElement("section",{ref:r,"aria-label":`${C} ${W}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,Y)=>{var J;const[ge,F]=B.split("-");return N.length?w.createElement("ol",{key:B,dir:b==="auto"?Dc():b,tabIndex:-1,ref:R,className:d,"data-sonner-toaster":!0,"data-sonner-theme":O,"data-y-position":ge,"data-x-position":F,style:{"--front-toast-height":`${((J=k[0])==null?void 0:J.height)||0}px`,"--width":`${MS}px`,"--gap":`${v}px`,...p,...BS(m,u)},onBlur:K=>{V.current&&!K.currentTarget.contains(K.relatedTarget)&&(V.current=!1,T.current&&(T.current.focus({preventScroll:!0}),T.current=null))},onFocus:K=>{K.target instanceof HTMLElement&&K.target.dataset.dismissible==="false"||V.current||(V.current=!0,T.current=K.relatedTarget)},onMouseEnter:()=>D(!0),onMouseMove:()=>D(!0),onMouseLeave:()=>{z||D(!1)},onDragEnd:()=>D(!1),onPointerDown:K=>{K.target instanceof HTMLElement&&K.target.dataset.dismissible==="false"||L(!0)},onPointerUp:()=>L(!1)},N.filter(K=>!K.position&&Y===0||K.position===B).map((K,me)=>{var q,te;return w.createElement(FS,{key:K.id,icons:_,index:me,toast:K,defaultRichColors:h,duration:(q=j?.duration)!=null?q:x,className:j?.className,descriptionClassName:j?.descriptionClassName,invert:o,visibleToasts:y,closeButton:(te=j?.closeButton)!=null?te:l,interacting:z,position:B,style:j?.style,unstyled:j?.unstyled,classNames:j?.classNames,cancelButtonStyle:j?.cancelButtonStyle,actionButtonStyle:j?.actionButtonStyle,closeButtonAriaLabel:j?.closeButtonAriaLabel,removeToast:ee,toasts:N.filter(ce=>ce.position==K.position),heights:k.filter(ce=>ce.position==K.position),setHeights:A,expandByDefault:c,gap:v,expanded:P,swipeDirections:t.swipeDirections})})):null}))}),ni=g.createContext(null);function WS(){const e=g.useContext(ni);if(!e)throw new Error("useToast must be used within ToastProvider");return e}function Ys(){return g.useContext(ni)}function VS({children:e}){const t=g.useCallback(r=>{const s=r.title??"",o=r.description;ES(s||o||"Notification",{description:s?o:void 0,duration:r.durationMs??5e3,action:r.actionLabel&&r.onAction?{label:r.actionLabel,onClick:()=>r.onAction?.()}:void 0})},[]);return n.jsxs(ni.Provider,{value:{toast:t},children:[e,n.jsx(US,{position:"top-center",closeButton:!0,expand:!0,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:pointer-events-auto group-[.toaster]:w-full group-[.toaster]:rounded-xl group-[.toaster]:border group-[.toaster]:border-neutral-200 group-[.toaster]:bg-white group-[.toaster]:p-4 group-[.toaster]:shadow-lg dark:group-[.toaster]:border-neutral-800 dark:group-[.toaster]:bg-neutral-950",title:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",description:"text-sm text-neutral-600 dark:text-neutral-400",actionButton:"h-8 rounded-md border border-neutral-200 bg-white px-3 text-xs font-medium text-neutral-900 shadow-sm hover:bg-neutral-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:hover:bg-neutral-900",cancelButton:"h-8 rounded-md bg-neutral-100 px-3 text-xs font-medium text-neutral-900 hover:bg-neutral-200 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-700",closeButton:"rounded-md text-neutral-600 opacity-0 transition-opacity hover:bg-neutral-100 hover:text-neutral-900 group-hover:opacity-100 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-neutral-50"}}})]})}const{entries:Gm,setPrototypeOf:Lc,isFrozen:HS,getPrototypeOf:qS,getOwnPropertyDescriptor:ZS}=Object;let{freeze:ut,seal:kt,create:ea}=Object,{apply:ta,construct:na}=typeof Reflect<"u"&&Reflect;ut||(ut=function(t){return t});kt||(kt=function(t){return t});ta||(ta=function(t,r){for(var s=arguments.length,o=new Array(s>2?s-2:0),a=2;a<s;a++)o[a-2]=arguments[a];return t.apply(r,o)});na||(na=function(t){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return new t(...s)});const Gr=mt(Array.prototype.forEach),GS=mt(Array.prototype.lastIndexOf),$c=mt(Array.prototype.pop),ir=mt(Array.prototype.push),QS=mt(Array.prototype.splice),es=mt(String.prototype.toLowerCase),Co=mt(String.prototype.toString),No=mt(String.prototype.match),cr=mt(String.prototype.replace),YS=mt(String.prototype.indexOf),KS=mt(String.prototype.trim),Et=mt(Object.prototype.hasOwnProperty),at=mt(RegExp.prototype.test),lr=JS(TypeError);function mt(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return ta(e,t,s)}}function JS(e){return function(){for(var t=arguments.length,r=new Array(t),s=0;s<t;s++)r[s]=arguments[s];return na(e,r)}}function be(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:es;Lc&&Lc(e,null);let s=t.length;for(;s--;){let o=t[s];if(typeof o=="string"){const a=r(o);a!==o&&(HS(t)||(t[s]=a),o=a)}e[o]=!0}return e}function XS(e){for(let t=0;t<e.length;t++)Et(e,t)||(e[t]=null);return e}function Ft(e){const t=ea(null);for(const[r,s]of Gm(e))Et(e,r)&&(Array.isArray(s)?t[r]=XS(s):s&&typeof s=="object"&&s.constructor===Object?t[r]=Ft(s):t[r]=s);return t}function dr(e,t){for(;e!==null;){const s=ZS(e,t);if(s){if(s.get)return mt(s.get);if(typeof s.value=="function")return mt(s.value)}e=qS(e)}function r(){return null}return r}const zc=ut(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ao=ut(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Po=ut(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),ek=ut(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),To=ut(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),tk=ut(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Fc=ut(["#text"]),Bc=ut(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Eo=ut(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Uc=ut(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Qr=ut(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),nk=kt(/\{\{[\w\W]*|[\w\W]*\}\}/gm),rk=kt(/<%[\w\W]*|[\w\W]*%>/gm),sk=kt(/\$\{[\w\W]*/gm),ok=kt(/^data-[\-\w.\u00B7-\uFFFF]+$/),ak=kt(/^aria-[\-\w]+$/),Qm=kt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ik=kt(/^(?:\w+script|data):/i),ck=kt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ym=kt(/^html$/i),lk=kt(/^[a-z][.\w]*(-[.\w]+)+$/i);var Wc=Object.freeze({__proto__:null,ARIA_ATTR:ak,ATTR_WHITESPACE:ck,CUSTOM_ELEMENT:lk,DATA_ATTR:ok,DOCTYPE_NAME:Ym,ERB_EXPR:rk,IS_ALLOWED_URI:Qm,IS_SCRIPT_OR_DATA:ik,MUSTACHE_EXPR:nk,TMPLIT_EXPR:sk});const ur={element:1,text:3,progressingInstruction:7,comment:8,document:9},dk=function(){return typeof window>"u"?null:window},uk=function(t,r){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(s=r.getAttribute(o));const a="dompurify"+(s?"#"+s:"");try{return t.createPolicy(a,{createHTML(i){return i},createScriptURL(i){return i}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},Vc=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Km(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dk();const t=le=>Km(le);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==ur.document||!e.Element)return t.isSupported=!1,t;let{document:r}=e;const s=r,o=s.currentScript,{DocumentFragment:a,HTMLTemplateElement:i,Node:c,Element:l,NodeFilter:d,NamedNodeMap:m=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:f,trustedTypes:h}=e,x=l.prototype,p=dr(x,"cloneNode"),y=dr(x,"remove"),j=dr(x,"nextSibling"),b=dr(x,"childNodes"),v=dr(x,"parentNode");if(typeof i=="function"){const le=r.createElement("template");le.content&&le.content.ownerDocument&&(r=le.content.ownerDocument)}let _,C="";const{implementation:E,createNodeIterator:S,createDocumentFragment:N,getElementsByTagName:U}=r,{importNode:k}=s;let A=Vc();t.isSupported=typeof Gm=="function"&&typeof v=="function"&&E&&E.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:P,ERB_EXPR:D,TMPLIT_EXPR:z,DATA_ATTR:L,ARIA_ATTR:O,IS_SCRIPT_OR_DATA:M,ATTR_WHITESPACE:R,CUSTOM_ELEMENT:W}=Wc;let{IS_ALLOWED_URI:T}=Wc,V=null;const ee=be({},[...zc,...Ao,...Po,...To,...Fc]);let B=null;const Y=be({},[...Bc,...Eo,...Uc,...Qr]);let J=Object.seal(ea(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ge=null,F=null;const K=Object.seal(ea(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let me=!0,q=!0,te=!1,ce=!0,pe=!1,Oe=!0,Ge=!1,Qe=!1,$e=!1,Ye=!1,Ne=!1,st=!1,Ae=!0,Fe=!1;const de="user-content-";let ke=!0,$=!1,X={},ne=null;const xe=be({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let we=null;const Te=be({},["audio","video","img","source","image","track"]);let Pn=null;const Qt=be({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Tn="http://www.w3.org/1998/Math/MathML",En="http://www.w3.org/2000/svg",jt="http://www.w3.org/1999/xhtml";let Yt=jt,sr=!1,gn=null;const $t=be({},[Tn,En,jt],Co);let In=be({},["mi","mo","mn","ms","mtext"]),Rn=be({},["annotation-xml"]);const Ir=be({},["title","style","font","a","script"]);let rn=null;const he=["application/xhtml+xml","text/html"],Be="text/html";let _e=null,Ue=null;const On=r.createElement("form"),We=function(I){return I instanceof RegExp||I instanceof Function},nt=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ue&&Ue===I)){if((!I||typeof I!="object")&&(I={}),I=Ft(I),rn=he.indexOf(I.PARSER_MEDIA_TYPE)===-1?Be:I.PARSER_MEDIA_TYPE,_e=rn==="application/xhtml+xml"?Co:es,V=Et(I,"ALLOWED_TAGS")?be({},I.ALLOWED_TAGS,_e):ee,B=Et(I,"ALLOWED_ATTR")?be({},I.ALLOWED_ATTR,_e):Y,gn=Et(I,"ALLOWED_NAMESPACES")?be({},I.ALLOWED_NAMESPACES,Co):$t,Pn=Et(I,"ADD_URI_SAFE_ATTR")?be(Ft(Qt),I.ADD_URI_SAFE_ATTR,_e):Qt,we=Et(I,"ADD_DATA_URI_TAGS")?be(Ft(Te),I.ADD_DATA_URI_TAGS,_e):Te,ne=Et(I,"FORBID_CONTENTS")?be({},I.FORBID_CONTENTS,_e):xe,ge=Et(I,"FORBID_TAGS")?be({},I.FORBID_TAGS,_e):Ft({}),F=Et(I,"FORBID_ATTR")?be({},I.FORBID_ATTR,_e):Ft({}),X=Et(I,"USE_PROFILES")?I.USE_PROFILES:!1,me=I.ALLOW_ARIA_ATTR!==!1,q=I.ALLOW_DATA_ATTR!==!1,te=I.ALLOW_UNKNOWN_PROTOCOLS||!1,ce=I.ALLOW_SELF_CLOSE_IN_ATTR!==!1,pe=I.SAFE_FOR_TEMPLATES||!1,Oe=I.SAFE_FOR_XML!==!1,Ge=I.WHOLE_DOCUMENT||!1,Ye=I.RETURN_DOM||!1,Ne=I.RETURN_DOM_FRAGMENT||!1,st=I.RETURN_TRUSTED_TYPE||!1,$e=I.FORCE_BODY||!1,Ae=I.SANITIZE_DOM!==!1,Fe=I.SANITIZE_NAMED_PROPS||!1,ke=I.KEEP_CONTENT!==!1,$=I.IN_PLACE||!1,T=I.ALLOWED_URI_REGEXP||Qm,Yt=I.NAMESPACE||jt,In=I.MATHML_TEXT_INTEGRATION_POINTS||In,Rn=I.HTML_INTEGRATION_POINTS||Rn,J=I.CUSTOM_ELEMENT_HANDLING||{},I.CUSTOM_ELEMENT_HANDLING&&We(I.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(J.tagNameCheck=I.CUSTOM_ELEMENT_HANDLING.tagNameCheck),I.CUSTOM_ELEMENT_HANDLING&&We(I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(J.attributeNameCheck=I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),I.CUSTOM_ELEMENT_HANDLING&&typeof I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(J.allowCustomizedBuiltInElements=I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),pe&&(q=!1),Ne&&(Ye=!0),X&&(V=be({},Fc),B=[],X.html===!0&&(be(V,zc),be(B,Bc)),X.svg===!0&&(be(V,Ao),be(B,Eo),be(B,Qr)),X.svgFilters===!0&&(be(V,Po),be(B,Eo),be(B,Qr)),X.mathMl===!0&&(be(V,To),be(B,Uc),be(B,Qr))),I.ADD_TAGS&&(typeof I.ADD_TAGS=="function"?K.tagCheck=I.ADD_TAGS:(V===ee&&(V=Ft(V)),be(V,I.ADD_TAGS,_e))),I.ADD_ATTR&&(typeof I.ADD_ATTR=="function"?K.attributeCheck=I.ADD_ATTR:(B===Y&&(B=Ft(B)),be(B,I.ADD_ATTR,_e))),I.ADD_URI_SAFE_ATTR&&be(Pn,I.ADD_URI_SAFE_ATTR,_e),I.FORBID_CONTENTS&&(ne===xe&&(ne=Ft(ne)),be(ne,I.FORBID_CONTENTS,_e)),I.ADD_FORBID_CONTENTS&&(ne===xe&&(ne=Ft(ne)),be(ne,I.ADD_FORBID_CONTENTS,_e)),ke&&(V["#text"]=!0),Ge&&be(V,["html","head","body"]),V.table&&(be(V,["tbody"]),delete ge.tbody),I.TRUSTED_TYPES_POLICY){if(typeof I.TRUSTED_TYPES_POLICY.createHTML!="function")throw lr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof I.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw lr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');_=I.TRUSTED_TYPES_POLICY,C=_.createHTML("")}else _===void 0&&(_=uk(h,o)),_!==null&&typeof C=="string"&&(C=_.createHTML(""));ut&&ut(I),Ue=I}},xn=be({},[...Ao,...Po,...ek]),pt=be({},[...To,...tk]),xt=function(I){let Q=v(I);(!Q||!Q.tagName)&&(Q={namespaceURI:Yt,tagName:"template"});const ae=es(I.tagName),Ee=es(Q.tagName);return gn[I.namespaceURI]?I.namespaceURI===En?Q.namespaceURI===jt?ae==="svg":Q.namespaceURI===Tn?ae==="svg"&&(Ee==="annotation-xml"||In[Ee]):!!xn[ae]:I.namespaceURI===Tn?Q.namespaceURI===jt?ae==="math":Q.namespaceURI===En?ae==="math"&&Rn[Ee]:!!pt[ae]:I.namespaceURI===jt?Q.namespaceURI===En&&!Rn[Ee]||Q.namespaceURI===Tn&&!In[Ee]?!1:!pt[ae]&&(Ir[ae]||!xn[ae]):!!(rn==="application/xhtml+xml"&&gn[I.namespaceURI]):!1},yt=function(I){ir(t.removed,{element:I});try{v(I).removeChild(I)}catch{y(I)}},ot=function(I,Q){try{ir(t.removed,{attribute:Q.getAttributeNode(I),from:Q})}catch{ir(t.removed,{attribute:null,from:Q})}if(Q.removeAttribute(I),I==="is")if(Ye||Ne)try{yt(Q)}catch{}else try{Q.setAttribute(I,"")}catch{}},eo=function(I){let Q=null,ae=null;if($e)I="<remove></remove>"+I;else{const Ve=No(I,/^[\r\n\t ]+/);ae=Ve&&Ve[0]}rn==="application/xhtml+xml"&&Yt===jt&&(I='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+I+"</body></html>");const Ee=_?_.createHTML(I):I;if(Yt===jt)try{Q=new f().parseFromString(Ee,rn)}catch{}if(!Q||!Q.documentElement){Q=E.createDocument(Yt,"template",null);try{Q.documentElement.innerHTML=sr?C:Ee}catch{}}const rt=Q.body||Q.documentElement;return I&&ae&&rt.insertBefore(r.createTextNode(ae),rt.childNodes[0]||null),Yt===jt?U.call(Q,Ge?"html":"body")[0]:Ge?Q.documentElement:rt},pi=function(I){return S.call(I.ownerDocument||I,I,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},to=function(I){return I instanceof u&&(typeof I.nodeName!="string"||typeof I.textContent!="string"||typeof I.removeChild!="function"||!(I.attributes instanceof m)||typeof I.removeAttribute!="function"||typeof I.setAttribute!="function"||typeof I.namespaceURI!="string"||typeof I.insertBefore!="function"||typeof I.hasChildNodes!="function")},fi=function(I){return typeof c=="function"&&I instanceof c};function Kt(le,I,Q){Gr(le,ae=>{ae.call(t,I,Q,Ue)})}const hi=function(I){let Q=null;if(Kt(A.beforeSanitizeElements,I,null),to(I))return yt(I),!0;const ae=_e(I.nodeName);if(Kt(A.uponSanitizeElement,I,{tagName:ae,allowedTags:V}),Oe&&I.hasChildNodes()&&!fi(I.firstElementChild)&&at(/<[/\w!]/g,I.innerHTML)&&at(/<[/\w!]/g,I.textContent)||I.nodeType===ur.progressingInstruction||Oe&&I.nodeType===ur.comment&&at(/<[/\w]/g,I.data))return yt(I),!0;if(!(K.tagCheck instanceof Function&&K.tagCheck(ae))&&(!V[ae]||ge[ae])){if(!ge[ae]&&xi(ae)&&(J.tagNameCheck instanceof RegExp&&at(J.tagNameCheck,ae)||J.tagNameCheck instanceof Function&&J.tagNameCheck(ae)))return!1;if(ke&&!ne[ae]){const Ee=v(I)||I.parentNode,rt=b(I)||I.childNodes;if(rt&&Ee){const Ve=rt.length;for(let ft=Ve-1;ft>=0;--ft){const Jt=p(rt[ft],!0);Jt.__removalCount=(I.__removalCount||0)+1,Ee.insertBefore(Jt,j(I))}}}return yt(I),!0}return I instanceof l&&!xt(I)||(ae==="noscript"||ae==="noembed"||ae==="noframes")&&at(/<\/no(script|embed|frames)/i,I.innerHTML)?(yt(I),!0):(pe&&I.nodeType===ur.text&&(Q=I.textContent,Gr([P,D,z],Ee=>{Q=cr(Q,Ee," ")}),I.textContent!==Q&&(ir(t.removed,{element:I.cloneNode()}),I.textContent=Q)),Kt(A.afterSanitizeElements,I,null),!1)},gi=function(I,Q,ae){if(Ae&&(Q==="id"||Q==="name")&&(ae in r||ae in On))return!1;if(!(q&&!F[Q]&&at(L,Q))){if(!(me&&at(O,Q))){if(!(K.attributeCheck instanceof Function&&K.attributeCheck(Q,I))){if(!B[Q]||F[Q]){if(!(xi(I)&&(J.tagNameCheck instanceof RegExp&&at(J.tagNameCheck,I)||J.tagNameCheck instanceof Function&&J.tagNameCheck(I))&&(J.attributeNameCheck instanceof RegExp&&at(J.attributeNameCheck,Q)||J.attributeNameCheck instanceof Function&&J.attributeNameCheck(Q,I))||Q==="is"&&J.allowCustomizedBuiltInElements&&(J.tagNameCheck instanceof RegExp&&at(J.tagNameCheck,ae)||J.tagNameCheck instanceof Function&&J.tagNameCheck(ae))))return!1}else if(!Pn[Q]){if(!at(T,cr(ae,R,""))){if(!((Q==="src"||Q==="xlink:href"||Q==="href")&&I!=="script"&&YS(ae,"data:")===0&&we[I])){if(!(te&&!at(M,cr(ae,R,"")))){if(ae)return!1}}}}}}}return!0},xi=function(I){return I!=="annotation-xml"&&No(I,W)},yi=function(I){Kt(A.beforeSanitizeAttributes,I,null);const{attributes:Q}=I;if(!Q||to(I))return;const ae={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:B,forceKeepAttr:void 0};let Ee=Q.length;for(;Ee--;){const rt=Q[Ee],{name:Ve,namespaceURI:ft,value:Jt}=rt,Mn=_e(Ve),no=Jt;let Xe=Ve==="value"?no:KS(no);if(ae.attrName=Mn,ae.attrValue=Xe,ae.keepAttr=!0,ae.forceKeepAttr=void 0,Kt(A.uponSanitizeAttribute,I,ae),Xe=ae.attrValue,Fe&&(Mn==="id"||Mn==="name")&&(ot(Ve,I),Xe=de+Xe),Oe&&at(/((--!?|])>)|<\/(style|title|textarea)/i,Xe)){ot(Ve,I);continue}if(Mn==="attributename"&&No(Xe,"href")){ot(Ve,I);continue}if(ae.forceKeepAttr)continue;if(!ae.keepAttr){ot(Ve,I);continue}if(!ce&&at(/\/>/i,Xe)){ot(Ve,I);continue}pe&&Gr([P,D,z],vi=>{Xe=cr(Xe,vi," ")});const bi=_e(I.nodeName);if(!gi(bi,Mn,Xe)){ot(Ve,I);continue}if(_&&typeof h=="object"&&typeof h.getAttributeType=="function"&&!ft)switch(h.getAttributeType(bi,Mn)){case"TrustedHTML":{Xe=_.createHTML(Xe);break}case"TrustedScriptURL":{Xe=_.createScriptURL(Xe);break}}if(Xe!==no)try{ft?I.setAttributeNS(ft,Ve,Xe):I.setAttribute(Ve,Xe),to(I)?yt(I):$c(t.removed)}catch{ot(Ve,I)}}Kt(A.afterSanitizeAttributes,I,null)},fp=function le(I){let Q=null;const ae=pi(I);for(Kt(A.beforeSanitizeShadowDOM,I,null);Q=ae.nextNode();)Kt(A.uponSanitizeShadowNode,Q,null),hi(Q),yi(Q),Q.content instanceof a&&le(Q.content);Kt(A.afterSanitizeShadowDOM,I,null)};return t.sanitize=function(le){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Q=null,ae=null,Ee=null,rt=null;if(sr=!le,sr&&(le="<!-->"),typeof le!="string"&&!fi(le))if(typeof le.toString=="function"){if(le=le.toString(),typeof le!="string")throw lr("dirty is not a string, aborting")}else throw lr("toString is not a function");if(!t.isSupported)return le;if(Qe||nt(I),t.removed=[],typeof le=="string"&&($=!1),$){if(le.nodeName){const Jt=_e(le.nodeName);if(!V[Jt]||ge[Jt])throw lr("root node is forbidden and cannot be sanitized in-place")}}else if(le instanceof c)Q=eo("<!---->"),ae=Q.ownerDocument.importNode(le,!0),ae.nodeType===ur.element&&ae.nodeName==="BODY"||ae.nodeName==="HTML"?Q=ae:Q.appendChild(ae);else{if(!Ye&&!pe&&!Ge&&le.indexOf("<")===-1)return _&&st?_.createHTML(le):le;if(Q=eo(le),!Q)return Ye?null:st?C:""}Q&&$e&&yt(Q.firstChild);const Ve=pi($?le:Q);for(;Ee=Ve.nextNode();)hi(Ee),yi(Ee),Ee.content instanceof a&&fp(Ee.content);if($)return le;if(Ye){if(Ne)for(rt=N.call(Q.ownerDocument);Q.firstChild;)rt.appendChild(Q.firstChild);else rt=Q;return(B.shadowroot||B.shadowrootmode)&&(rt=k.call(s,rt,!0)),rt}let ft=Ge?Q.outerHTML:Q.innerHTML;return Ge&&V["!doctype"]&&Q.ownerDocument&&Q.ownerDocument.doctype&&Q.ownerDocument.doctype.name&&at(Ym,Q.ownerDocument.doctype.name)&&(ft="<!DOCTYPE "+Q.ownerDocument.doctype.name+`>
136
- `+ft),pe&&Gr([P,D,z],Jt=>{ft=cr(ft,Jt," ")}),_&&st?_.createHTML(ft):ft},t.setConfig=function(){let le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};nt(le),Qe=!0},t.clearConfig=function(){Ue=null,Qe=!1},t.isValidAttribute=function(le,I,Q){Ue||nt({});const ae=_e(le),Ee=_e(I);return gi(ae,Ee,Q)},t.addHook=function(le,I){typeof I=="function"&&ir(A[le],I)},t.removeHook=function(le,I){if(I!==void 0){const Q=GS(A[le],I);return Q===-1?void 0:QS(A[le],Q,1)[0]}return $c(A[le])},t.removeHooks=function(le){A[le]=[]},t.removeAllHooks=function(){A=Vc()},t}var mk=Km();function Jm({faq:e,className:t,expanded:r,defaultExpanded:s=!1,onExpandedChange:o,showKeywords:a=!1,dangerouslySetAnswerHTML:i=!1}){const[c,l]=g.useState(s),d=r!==void 0,m=d?r:c,u=()=>{const f=!m;d||l(f),o?.(f)};return n.jsxs("div",{className:H("border border-neutral-200 rounded-lg overflow-hidden dark:border-neutral-800",t),children:[n.jsxs("button",{type:"button",onClick:u,className:H("w-full flex items-center justify-between px-4 py-3 text-left","bg-neutral-50 hover:bg-neutral-100 dark:bg-neutral-900 dark:hover:bg-neutral-800","transition-colors duration-150"),"aria-expanded":m,children:[n.jsx("span",{className:"font-medium text-neutral-900 dark:text-neutral-100 pr-4",children:e.question}),n.jsx("svg",{className:H("w-5 h-5 text-neutral-500 transition-transform duration-200 flex-shrink-0",m&&"rotate-180"),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),m&&n.jsxs("div",{className:"px-4 py-3 bg-white dark:bg-neutral-950",children:[i?n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 prose prose-sm dark:prose-invert max-w-none",dangerouslySetInnerHTML:{__html:mk.sanitize(e.answer,{ALLOWED_TAGS:["b","i","em","strong","a","p","br","ul","ol","li"],ALLOWED_ATTR:["href","target","rel"]})}}):n.jsx("p",{className:"text-sm text-neutral-600 dark:text-neutral-400 whitespace-pre-wrap",children:e.answer}),a&&e.keywords&&e.keywords.length>0&&n.jsx("div",{className:"mt-3 flex flex-wrap gap-1",children:e.keywords.map(f=>n.jsx("span",{className:"px-2 py-0.5 text-xs bg-neutral-100 text-neutral-600 rounded dark:bg-neutral-800 dark:text-neutral-400",children:f},f))})]})]})}function pk({faqs:e,className:t,accordion:r=!1,showKeywords:s=!1,dangerouslySetAnswerHTML:o=!1,emptyMessage:a="No FAQs available."}){const[i,c]=g.useState(null),l=e.filter(d=>d.active!==!1);return l.length===0?n.jsx("div",{className:H("text-center py-8 text-neutral-500 dark:text-neutral-400",t),children:a}):n.jsx("div",{className:H("space-y-2",t),children:l.map(d=>n.jsx(Jm,{faq:d,showKeywords:s,dangerouslySetAnswerHTML:o,expanded:r?i===d.id:void 0,onExpandedChange:r?m=>c(m?d.id:null):void 0},d.id))})}function Je({amount:e,currency:t}){return new Intl.NumberFormat(void 0,{style:"currency",currency:t}).format(e)}function Ks({amount:e,currency:t,compareAt:r,className:s,size:o="default"}){const a=typeof r=="number"&&r>e;return n.jsxs("div",{className:H("flex items-baseline gap-2 tabular-nums",s),children:[n.jsx("span",{className:H("font-semibold",o==="sm"?"text-sm":"text-base"),children:Je({amount:e,currency:t})}),a?n.jsx("span",{className:H("text-neutral-500 line-through dark:text-neutral-400",o==="sm"?"text-xs":"text-sm"),children:Je({amount:r,currency:t})}):null]})}const fk={large:"aspect-[4/5]",square:"aspect-square",compact:"aspect-[3/4]"},hk={center:"object-center",top:"object-top",bottom:"object-bottom",left:"object-left",right:"object-right"};function Xm({product:e,href:t,onAddToCart:r,onQuickView:s,className:o,layout:a="large",imageCrop:i="center"}){const c=e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0,l=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:null;return n.jsxs(It,{className:H("group flex h-full flex-col overflow-hidden rounded-2xl",o),children:[n.jsxs("div",{className:"relative",children:[n.jsx("a",{href:t,className:"block","aria-label":`View ${e.title}`,children:n.jsx("div",{className:H("overflow-hidden bg-neutral-100 dark:bg-neutral-900",fk[a]),children:n.jsx("img",{src:e.images[0]?.url,alt:e.images[0]?.alt??e.title,className:H("h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]",hk[i]),loading:"lazy"})})}),a!=="compact"&&e.tags?.length?n.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 flex gap-1 p-3",children:e.tags.slice(0,2).map(d=>n.jsx(wn,{className:"pointer-events-none bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:d},d))}):null,c?n.jsx("div",{className:"pointer-events-none absolute left-3 top-3",children:n.jsx(wn,{variant:"secondary",className:"bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:"Out of stock"})}):l!=null&&l>0&&l<=5?n.jsx("div",{className:"pointer-events-none absolute left-3 top-3",children:n.jsxs(wn,{variant:"secondary",className:"bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:["Only ",l," left"]})}):null,s?n.jsx("div",{className:"absolute right-3 top-3 opacity-0 transition-opacity group-hover:opacity-100",children:n.jsx(ie,{type:"button",size:"sm",variant:"secondary",className:"h-9",onClick:()=>s(e),children:"Quick view"})}):null]}),n.jsxs("div",{className:H("flex flex-1 flex-col",a==="compact"?"p-3":"p-4"),children:[n.jsx("div",{className:"flex items-start justify-between gap-3",children:n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:H("line-clamp-1 font-medium text-neutral-950 dark:text-neutral-50",a==="compact"?"text-xs":"text-sm"),children:e.title}),n.jsx("div",{className:"mt-1",children:n.jsx(Ks,{amount:e.price,currency:e.currency,compareAt:e.compareAtPrice,size:a==="compact"?"sm":"default"})})]})}),a==="large"&&n.jsx("p",{className:"mt-2 line-clamp-2 min-h-8 text-xs leading-4 text-neutral-600 dark:text-neutral-400",children:e.description}),n.jsx("div",{className:H("mt-auto",a==="compact"?"pt-3":"pt-4"),children:n.jsx(ie,{type:"button",className:"w-full",size:a==="compact"?"sm":"default",onClick:()=>r?.(e,null),disabled:c,children:c?"Out of stock":"Add to cart"})})]})]})}function Js({products:e,columns:t,onAddToCart:r,onQuickView:s,getProductHref:o,className:a,layout:i,imageCrop:c}){const l=t?.base??2,d=t?.md??3,m=t?.lg??3,u={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4"},f={1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4"},h={1:"lg:grid-cols-1",2:"lg:grid-cols-2",3:"lg:grid-cols-3",4:"lg:grid-cols-4"},x=H("grid gap-4",u[Math.min(4,Math.max(1,l))],f[Math.min(4,Math.max(1,d))],h[Math.min(4,Math.max(1,m))]);return n.jsx("div",{className:H(x,a),children:e.map(p=>n.jsx(Xm,{product:p,href:o?o(p):void 0,onAddToCart:r,onQuickView:s,layout:i,imageCrop:c},p.id))})}function ri({images:e,className:t}){const[r,s]=g.useState(0),o=e[r];return e.length===0?n.jsx("div",{className:H("aspect-square w-full rounded-xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",t)}):n.jsxs("div",{className:H("space-y-3",t),children:[n.jsx("div",{className:"aspect-square overflow-hidden rounded-2xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:n.jsx("img",{src:o?.url,alt:o?.alt??"",className:"h-full w-full object-cover",loading:"eager"})}),e.length>1?n.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:e.map((a,i)=>{const c=i===r;return n.jsx("button",{type:"button",className:H("h-16 w-16 shrink-0 overflow-hidden rounded-lg border",c?"border-neutral-900 dark:border-neutral-50":"border-neutral-200 dark:border-neutral-800"),onClick:()=>s(i),"aria-label":`View image ${i+1}`,children:n.jsx("img",{src:a.url,alt:a.alt??"",className:"h-full w-full object-cover",loading:"lazy"})},a.url)})}):null]})}function gk(e){const t=new Set;for(const r of e)for(const s of Object.keys(r.options))t.add(s);return Array.from(t)}function xk(e,t){const r=new Set;for(const s of e){const o=s.options[t];o&&r.add(o)}return Array.from(r)}function Hc(e,t){return e.find(r=>Object.entries(t).every(([s,o])=>r.options[s]===o))??null}function ep(e){return e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0}function yk(e){return e.inventoryStatus==="low"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity>0&&e.inventoryQuantity<=5}function bk(e){const t=ep(e),r=!t&&yk(e),s=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0;return{isOutOfStock:t,isLow:r,quantity:s}}function vk(e,t,r,s){const o={...t,[r]:s},a=e.filter(i=>Object.entries(o).every(([c,l])=>i.options[c]===l));return a.length===0?!1:a.some(i=>!ep(i))}function si({product:e,value:t,onChange:r,className:s,showInventory:o=!0,disableOutOfStock:a=!1}){const i=g.useMemo(()=>e.variants??[],[e.variants]),c=g.useMemo(()=>gk(i),[i]),l=g.useMemo(()=>Hc(i,t.selectedOptions),[i,t.selectedOptions]),d=g.useMemo(()=>l?bk(l):null,[l]);return i.length===0||c.length===0?null:n.jsxs("div",{className:H("space-y-4",s),children:[c.map(m=>{const u=xk(i,m),f=t.selectedOptions[m];return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-baseline justify-between",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-950 dark:text-neutral-50",children:m}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:f||"Select"})]}),n.jsx("div",{className:"flex flex-wrap gap-2",children:u.map(h=>{const x=h===f,p=vk(i,t.selectedOptions,m,h),y=a&&!p;return n.jsxs(ie,{type:"button",size:"sm",variant:x?"default":"outline",onClick:()=>{const j={...t.selectedOptions,[m]:h},b=Hc(i,j);r({selectedOptions:j,variant:b})},"aria-pressed":x,disabled:y,className:H(!p&&!y&&"opacity-50 line-through"),children:[h,!p&&!y&&n.jsx("span",{className:"ml-1 text-[10px] opacity-70",children:"(Out)"})]},h)})})]},m)}),o&&l&&d&&n.jsx("div",{className:"pt-2",children:d.isOutOfStock?n.jsx("div",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:"Out of stock"}):d.isLow&&d.quantity!==void 0?n.jsxs("div",{className:"text-sm text-amber-600 dark:text-amber-400",children:["Only ",n.jsx("span",{className:"font-semibold",children:d.quantity})," left"]}):null})]})}function oi({qty:e,onChange:t,min:r=1,max:s,className:o}){const a=Number.isFinite(e)?Math.max(r,Math.floor(e)):r,i=a>r,c=typeof s=="number"?a<s:!0;return n.jsxs("div",{className:H("flex items-center gap-2",o),children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(Math.max(r,a-1)),disabled:!i,"aria-label":"Decrease quantity",children:"-"}),n.jsx(He,{inputMode:"numeric",pattern:"[0-9]*",value:String(a),onChange:l=>{const d=Math.floor(Number(l.target.value));if(!Number.isFinite(d))return;const m=Math.max(r,typeof s=="number"?Math.min(s,d):d);t(m)},className:"h-10 w-16 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(a+1),disabled:!c,"aria-label":"Increase quantity",children:"+"})]})}function ai({product:e,open:t,onOpenChange:r,productHref:s,onAddToCart:o,className:a}){const[i,c]=g.useState(1),[l,d]=g.useState({selectedOptions:{},variant:null});if(g.useEffect(()=>{if(e)if(c(1),e.variants?.length){const f=e.variants[0];d({selectedOptions:{...f.options},variant:f})}else d({selectedOptions:{},variant:null})},[e?.id]),!e)return null;const m=l.variant?.price??e.price,u=l.variant?.compareAtPrice??e.compareAtPrice;return n.jsx(Wa,{open:t,onOpenChange:r,children:n.jsxs(zs,{className:H("max-w-3xl",a),children:[n.jsx(Ha,{children:n.jsxs(Fs,{className:"flex items-center justify-between gap-3",children:[n.jsx("span",{className:"truncate",children:e.title}),s?n.jsx("a",{href:s(e.slug),className:"text-sm font-normal text-neutral-700 hover:underline dark:text-neutral-300",children:"View details"}):null]})}),n.jsxs("div",{className:"grid gap-8 md:grid-cols-2",children:[n.jsx(ri,{images:e.images}),n.jsxs("div",{className:"space-y-5",children:[n.jsxs("div",{children:[n.jsx(Ks,{amount:m,currency:e.currency,compareAt:u}),n.jsx("p",{className:"mt-3 text-sm text-neutral-600 dark:text-neutral-400",children:e.description})]}),n.jsx(si,{product:e,value:{selectedOptions:l.selectedOptions,variantId:l.variant?.id},onChange:f=>d(f)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(oi,{qty:i,onChange:c}),n.jsx(ie,{type:"button",className:"flex-1",onClick:()=>{o(e,l.variant,i),r(!1)},children:"Add to cart"})]}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:e.inventoryStatus==="out_of_stock"?"Out of stock":"In stock"})]})]})]})})}function ra({categories:e,activeSlug:t,onSelect:r,className:s}){return n.jsx("nav",{className:H("space-y-1",s),"aria-label":"Categories",children:e.map(o=>{const a=t===o.slug;return n.jsxs("button",{type:"button",className:H("flex w-full items-center justify-between rounded-md px-3 py-2 text-sm transition-colors",a?"bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900":"text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"),onClick:()=>r?.(o),"aria-current":a?"page":void 0,children:[n.jsx("span",{className:"truncate",children:o.name}),n.jsx("span",{className:"text-xs opacity-70",children:"›"})]},o.id)})})}function ii({items:e,className:t}){return n.jsx("nav",{className:H("flex items-center gap-2 text-xs text-neutral-600 dark:text-neutral-400",t),"aria-label":"Breadcrumb",children:e.map((r,s)=>n.jsxs("span",{className:"flex items-center gap-2",children:[r.href?n.jsx("a",{href:r.href,className:"hover:underline",children:r.label}):n.jsx("span",{className:"text-neutral-900 dark:text-neutral-50",children:r.label}),s<e.length-1?n.jsx("span",{"aria-hidden":!0,children:"·"}):null]},`${r.label}-${s}`))})}function ci({value:e,onChange:t,placeholder:r="Search products…",className:s}){return n.jsxs("div",{className:H("relative",s),children:[n.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-3 flex items-center text-neutral-500 dark:text-neutral-400","aria-hidden":!0,children:"⌕"}),n.jsx(He,{value:e,onChange:o=>t(o.target.value),placeholder:r,className:"pl-9","aria-label":"Search"})]})}function xs({facets:e,value:t,onChange:r,onClear:s,className:o,enabledFilters:a}){const i=e.tags??[],c=new Set(t.tags??[]),l=a?.tags??!0,d=a?.priceRange??!0,m=a?.inStock??!0;return l||d||m?n.jsxs("div",{className:H("space-y-4",o),children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Filters"}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-8 px-2 text-xs",onClick:s,children:"Clear"})]}),n.jsx(St,{}),l&&i.length?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Tags"}),n.jsx("div",{className:"space-y-2",children:i.map(f=>n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:c.has(f),onChange:h=>{const x=new Set(c);h.target.checked?x.add(f):x.delete(f),r({...t,tags:Array.from(x)})}}),f]},f))})]}):null,d&&e.price?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Price"}),n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-1",children:[n.jsx(dt,{className:"text-xs",htmlFor:"price-min",children:"Min"}),n.jsx(He,{id:"price-min",inputMode:"decimal",placeholder:String(e.price.min),value:t.priceMin??"",onChange:f=>{const h=Number(f.target.value);r({...t,priceMin:Number.isFinite(h)&&f.target.value!==""?h:void 0})}})]}),n.jsxs("div",{className:"grid gap-1",children:[n.jsx(dt,{className:"text-xs",htmlFor:"price-max",children:"Max"}),n.jsx(He,{id:"price-max",inputMode:"decimal",placeholder:String(e.price.max),value:t.priceMax??"",onChange:f=>{const h=Number(f.target.value);r({...t,priceMax:Number.isFinite(h)&&f.target.value!==""?h:void 0})}})]})]})]}):null,m?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Availability"}),n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:t.inStock??!1,onChange:f=>r({...t,inStock:f.target.checked})}),"In stock"]})]}):null]}):null}function qc(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}function wk(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("path",{d:"M3 6h18"}),n.jsx("path",{d:"M8 6V4h8v2"}),n.jsx("path",{d:"M6 6l1 16h10l1-16"}),n.jsx("path",{d:"M10 11v6"}),n.jsx("path",{d:"M14 11v6"})]})}function li({item:e,onRemove:t,onSetQty:r,variant:s="table",className:o,inventory:a}){const i=e.unitPrice*e.qty,[c,l]=g.useState(!1),d=g.useMemo(()=>{if(a?.availableQty)return a.availableQty},[a?.availableQty]),m=!a?.isOutOfStock&&(d===void 0||e.qty<d),u=g.useMemo(()=>a?a.isOutOfStock?{type:"error",message:a.message||"Out of stock"}:a.exceedsAvailable?{type:"warning",message:a.message||"Quantity exceeds available stock"}:a.isLowStock?{type:"info",message:a.message||"Low stock"}:null:null,[a]);return g.useEffect(()=>{c&&e.qty!==1&&l(!1)},[c,e.qty]),s==="compact"?n.jsxs("div",{className:H("flex items-start gap-3",o),children:[n.jsx("div",{className:"h-12 w-12 shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:e.imageSnapshot?n.jsx("img",{src:e.imageSnapshot,alt:e.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"truncate text-sm font-medium text-neutral-950 dark:text-neutral-50",children:e.titleSnapshot}),n.jsx("div",{className:"mt-0.5 text-xs tabular-nums text-neutral-600 dark:text-neutral-400",children:Je({amount:i,currency:e.currency})}),u&&n.jsxs("div",{className:H("mt-1 flex items-center gap-1 text-[11px]",u.type==="error"&&"text-red-600 dark:text-red-400",u.type==="warning"&&"text-amber-600 dark:text-amber-400",u.type==="info"&&"text-blue-600 dark:text-blue-400"),children:[n.jsx(qc,{className:"h-3 w-3 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsx("div",{className:"flex h-12 w-[140px] shrink-0 items-center justify-end",children:c?n.jsxs("div",{className:"flex w-full flex-col items-center justify-center gap-2",children:[n.jsx("div",{className:"text-center text-[11px] font-medium leading-none text-neutral-600 dark:text-neutral-400",children:"Remove item?"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",variant:"outline",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:()=>l(!1),children:"Cancel"}),n.jsx(ie,{type:"button",variant:"destructive",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:t,children:"Confirm"})]})]}):n.jsxs("div",{className:"flex items-center justify-end gap-1.5 whitespace-nowrap",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":e.qty===1?"Remove item":"Decrease quantity",onClick:()=>{if(e.qty===1){l(!0);return}r(e.qty-1)},children:e.qty===1?n.jsx(wk,{className:"h-4 w-4"}):"-"}),n.jsx(He,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:f=>{const h=Math.floor(Number(f.target.value));if(!Number.isFinite(h))return;const x=Math.max(1,d?Math.min(d,h):h);r(x)},className:"h-8 w-11 px-2 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]})})]})})]}):n.jsxs("div",{className:H("grid grid-cols-[64px_1fr] items-start gap-x-4 gap-y-3 sm:grid-cols-[64px_1fr_176px_120px]",o),children:[n.jsx("div",{className:"h-16 w-16 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:e.imageSnapshot?n.jsx("img",{src:e.imageSnapshot,alt:e.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsxs("div",{className:"col-start-2 row-start-1 min-w-0",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsx("div",{className:"truncate text-sm font-medium text-neutral-950 dark:text-neutral-50",children:e.titleSnapshot}),n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50 sm:hidden",children:Je({amount:i,currency:e.currency})})]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[Je({amount:e.unitPrice,currency:e.currency})," each"]}),u&&n.jsxs("div",{className:H("mt-1.5 flex items-center gap-1 text-xs",u.type==="error"&&"text-red-600 dark:text-red-400",u.type==="warning"&&"text-amber-600 dark:text-amber-400",u.type==="info"&&"text-blue-600 dark:text-blue-400"),children:[n.jsx(qc,{className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsxs("div",{className:"col-span-2 col-start-1 row-start-2 flex items-center justify-between gap-3 sm:col-span-1 sm:col-start-3 sm:row-start-1 sm:justify-center",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Decrease quantity",onClick:()=>r(Math.max(1,e.qty-1)),children:"-"}),n.jsx(He,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:f=>{const h=Math.floor(Number(f.target.value));if(!Number.isFinite(h))return;const x=Math.max(1,d?Math.min(d,h):h);r(x)},className:"h-9 w-14 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-9 px-2 text-xs text-red-600 dark:text-red-400 sm:hidden",onClick:t,children:"Remove"})]}),n.jsxs("div",{className:"hidden sm:col-start-4 sm:row-start-1 sm:flex sm:flex-col sm:items-center sm:text-center",children:[n.jsx("div",{className:"text-sm font-semibold tabular-nums text-neutral-950 dark:text-neutral-50",children:Je({amount:i,currency:e.currency})}),n.jsx(ie,{type:"button",variant:"ghost",className:"mt-1 h-8 px-2 text-xs text-red-600 dark:text-red-400",onClick:t,children:"Remove"})]})]})}function di({currency:e,subtotal:t,itemCount:r,onCheckout:s,isCheckoutDisabled:o,checkoutDisabledReason:a,onRemoveUnavailable:i,className:c}){return n.jsxs("div",{className:H("space-y-4",c),children:[n.jsx(St,{}),n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsxs("div",{className:"flex items-center gap-2 text-neutral-600 dark:text-neutral-400",children:[n.jsx("span",{children:"Subtotal"}),typeof r=="number"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-neutral-300 dark:text-neutral-700",children:"·"}),n.jsxs("span",{className:"tabular-nums",children:[r," item",r===1?"":"s"]})]}):null]}),n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:Je({amount:t,currency:e})})]}),n.jsx(ie,{type:"button",onClick:s,disabled:o,className:"w-full",children:"Checkout"}),o&&a&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-center text-xs text-amber-600 dark:text-amber-400",children:a}),i&&n.jsx("button",{type:"button",onClick:i,className:"mx-auto block text-xs text-neutral-500 underline underline-offset-2 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-300",children:"Remove unavailable items"})]})]})}function tp({onCheckout:e,className:t}){const{config:r}=De(),s=Mt(),{getItemInventory:o,hasIssues:a}=ja({items:s.items,refreshInterval:3e4,skip:s.items.length===0}),i=()=>{for(const c of s.items){const l=o(c.productId,c.variantId);(l?.isOutOfStock||l?.exceedsAvailable)&&s.removeItem(c.productId,c.variantId)}};return s.items.length===0?n.jsx(Zn,{title:"Cart is empty",description:"Add items from the catalog to check out.",className:t}):n.jsxs("div",{className:H("flex h-full flex-col rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-800 dark:bg-neutral-950",t),children:[n.jsx("div",{className:"-mr-4 min-h-0 flex-1 overflow-y-auto overflow-x-hidden pr-4",children:n.jsx("div",{className:"divide-y divide-neutral-200 dark:divide-neutral-800",children:s.items.map(c=>n.jsx("div",{className:"py-3",children:n.jsx(li,{variant:"compact",item:c,onRemove:()=>s.removeItem(c.productId,c.variantId),onSetQty:l=>s.setQty(c.productId,c.variantId,l),inventory:o(c.productId,c.variantId)})},`${c.productId}::${c.variantId??""}`))})}),n.jsx("div",{className:"mt-4 space-y-4",children:n.jsx(di,{currency:r.currency,subtotal:s.subtotal,itemCount:s.count,onCheckout:e,isCheckoutDisabled:s.items.length===0||a,checkoutDisabledReason:a?"Some items have inventory issues":void 0,onRemoveUnavailable:a?i:void 0})})]})}const np=g.forwardRef(({className:e,...t},r)=>n.jsx("textarea",{ref:r,className:H("flex min-h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm transition-colors placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-50/20",e),...t}));np.displayName="Textarea";function _k(){const[e,t]=g.useState(!1);return g.useEffect(()=>{const r=window.matchMedia?.("(prefers-reduced-motion: reduce)");if(!r)return;const s=()=>t(r.matches);return s(),r.addEventListener?.("change",s),()=>r.removeEventListener?.("change",s)},[]),e}function Zc({children:e,className:t}){const r=g.useRef(null),s=_k();return g.useEffect(()=>{const o=r.current;!o||s||o.animate([{opacity:0,transform:"translateY(6px)"},{opacity:1,transform:"translateY(0px)"}],{duration:180,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)",fill:"both"})},[s]),n.jsx("div",{ref:r,className:t,children:e})}function Io(){return`${Date.now()}_${Math.random().toString(16).slice(2)}`}function jk({className:e}){const[t,r]=g.useState(""),[s,o]=g.useState(!1),[a,i]=g.useState(()=>[{id:Io(),role:"agent",text:"Hi! How can we help today? We can recommend products or answer support questions.",createdAt:Date.now()}]),[c,l]=g.useState("…");g.useEffect(()=>{if(!s)return;const h=[".","..","..."];let x=0;const p=window.setInterval(()=>{x=(x+1)%h.length,l(h[x])},450);return()=>window.clearInterval(p)},[s]);const d=g.useRef(null),m=g.useRef(null);g.useEffect(()=>{const h=d.current;h&&(h.scrollTop=h.scrollHeight)},[a.length]);const u=g.useCallback(()=>{const h=m.current;if(!h)return;const x=120;h.style.height="0px";const p=Math.min(x,Math.max(40,h.scrollHeight));h.style.height=`${p}px`,h.style.overflowY=h.scrollHeight>x?"auto":"hidden"},[]);g.useEffect(()=>{u()},[t,u]);const f=g.useCallback(()=>{const h=t.trim();h&&(i(x=>[...x,{id:Io(),role:"user",text:h,createdAt:Date.now()}]),r(""),o(!0),window.setTimeout(()=>{i(x=>[...x,{id:Io(),role:"agent",text:"Got it. Want recommendations, sizing help, or help with an order?",createdAt:Date.now()}]),o(!1)},450))},[t]);return n.jsxs("div",{className:H("flex h-full min-h-0 flex-col",e),children:[n.jsxs("div",{ref:d,className:"min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain rounded-2xl border border-neutral-200 bg-white p-4 dark:border-neutral-800 dark:bg-neutral-950",children:[a.map(h=>n.jsx(Zc,{className:H("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsx("div",{className:H("max-w-[85%] rounded-2xl px-3 py-2 text-sm leading-5",h.role==="user"?"bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900":"bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50"),children:n.jsx("span",{className:"whitespace-pre-wrap break-words",children:h.text})})},h.id)),s?n.jsx(Zc,{className:"flex justify-start",children:n.jsx("div",{className:"max-w-[85%] rounded-2xl bg-neutral-100 px-3 py-2 text-sm leading-5 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",children:c})}):null]}),n.jsxs("div",{className:"mt-3 flex shrink-0 items-end gap-2",children:[n.jsx(np,{ref:m,rows:1,value:t,onChange:h=>r(h.target.value),placeholder:"Type a message…",className:"max-h-[120px] resize-none",onKeyDown:h=>{h.key==="Enter"&&(h.shiftKey||(h.preventDefault(),f()))}}),n.jsx(ie,{type:"button",onClick:f,disabled:!t.trim(),className:"h-10 shrink-0",children:"Send"})]})]})}function Ar({trigger:e,side:t="right",open:r,onOpenChange:s,onCheckout:o,preferredTab:a,className:i}){const[c,l]=g.useState(a??"cart");return g.useEffect(()=>{r&&l(a??"cart")},[r,a]),n.jsxs(Bs,{modal:!1,open:r,onOpenChange:s,children:[e?n.jsx(Us,{asChild:!0,children:e}):null,n.jsxs(Tr,{side:t,overlayClassName:t==="popup"?"pointer-events-none bg-transparent backdrop-blur-none":"pointer-events-none bg-neutral-950/40 backdrop-blur-none",className:H(t==="bottom"?"h-[85vh] rounded-t-2xl":void 0,t==="popup"?"shadow-xl":"w-full sm:max-w-md",t==="popup"?"h-[min(640px,calc(100vh-2rem))]":void 0,t==="popup"?void 0:"p-4","flex flex-col overflow-hidden",i),children:[n.jsx(Ws,{className:"space-y-0",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx(ti,{value:c,onValueChange:d=>l(d),children:n.jsxs(Qs,{className:"h-9",children:[n.jsx(Nr,{value:"cart",className:"text-sm",children:"Cart"}),n.jsx(Nr,{value:"chat",className:"text-sm",children:"Chat"})]})}),n.jsx(om,{asChild:!0,children:n.jsx(ie,{type:"button",size:"icon",variant:"ghost",className:"h-9 w-9 rounded-full text-lg leading-none","aria-label":"Close cart",children:"X"})})]})}),n.jsx("div",{className:"mt-3 min-h-0 flex-1 overflow-hidden",children:c==="chat"?n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Get help finding a product or ask us any questions. We’re both your shopping assistant and support chat."}),n.jsx("div",{className:"mt-3 min-h-0 flex-1",children:n.jsx(jk,{className:"h-full"})})]}):n.jsx(tp,{onCheckout:()=>{o(),s?.(!1)},className:"h-full border-0 bg-transparent p-0 shadow-none"})})]})]})}function ui({value:e,onApply:t,className:r}){const[s,o]=g.useState(e??"");return g.useEffect(()=>{o(e??"")},[e]),n.jsxs("div",{className:H("space-y-2",r),children:[n.jsx("div",{className:"text-sm font-medium text-neutral-950 dark:text-neutral-50",children:"Promo code"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(He,{value:s,onChange:a=>o(a.target.value),placeholder:"SAVE10","aria-label":"Promo code"}),n.jsx(ie,{type:"button",variant:"outline",onClick:()=>t(s.trim()||void 0),children:"Apply"})]})]})}function rp({onCheckout:e,showPromoCode:t,className:r}){const{config:s}=De(),o=Mt(),{getItemInventory:a,hasIssues:i}=ja({items:o.items,refreshInterval:3e4,skip:o.items.length===0}),c=()=>{for(const l of o.items){const d=a(l.productId,l.variantId);(d?.isOutOfStock||d?.exceedsAvailable)&&o.removeItem(l.productId,l.variantId)}};return o.items.length===0?n.jsx(Zn,{title:"Your cart is empty",description:"Add a few products and come back here when you're ready to check out.",className:r}):n.jsxs("div",{className:H("grid items-start gap-6 lg:grid-cols-[1fr_360px]",r),children:[n.jsxs("div",{className:"self-start rounded-2xl border border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsxs("div",{className:"hidden grid-cols-[64px_1fr_176px_120px] gap-x-4 px-5 py-3 text-xs font-medium text-neutral-500 dark:text-neutral-400 sm:grid",children:[n.jsx("div",{}),n.jsx("div",{children:"Item"}),n.jsx("div",{className:"text-center",children:"Qty"}),n.jsx("div",{className:"text-center",children:"Total"})]}),n.jsx("div",{className:"divide-y divide-neutral-200 dark:divide-neutral-800",children:o.items.map(l=>n.jsx("div",{className:"px-4 py-4 sm:px-5",children:n.jsx(li,{item:l,onRemove:()=>o.removeItem(l.productId,l.variantId),onSetQty:d=>o.setQty(l.productId,l.variantId,d),inventory:a(l.productId,l.variantId)})},`${l.productId}::${l.variantId??""}`))})]}),n.jsx("div",{className:"lg:sticky lg:top-24 self-start",children:n.jsxs("div",{className:"rounded-2xl border border-neutral-200 bg-white p-5 shadow-sm dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Summary"}),n.jsx(St,{className:"my-4"}),n.jsxs("div",{className:"space-y-4",children:[t?n.jsx(ui,{value:o.promoCode,onApply:o.setPromoCode}):null,n.jsx(di,{currency:s.currency,subtotal:o.subtotal,onCheckout:e,isCheckoutDisabled:o.items.length===0||i,checkoutDisabledReason:i?"Some items have inventory issues":void 0,onRemoveUnavailable:i?c:void 0})]})]})})]})}function sp({left:e,right:t,className:r}){return n.jsxs("div",{className:H("grid items-start gap-8 lg:grid-cols-[1fr_420px]",r),children:[n.jsx("div",{children:e}),n.jsx("div",{children:t})]})}function sa({title:e,value:t,onChange:r,errors:s,className:o}){return n.jsxs("section",{className:H("space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",o),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:e}),n.jsxs("div",{className:"grid gap-3",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:`${e}-line1`,children:"Address line 1"}),n.jsx(He,{id:`${e}-line1`,value:t.line1,onChange:a=>r({...t,line1:a.target.value}),"aria-invalid":!!s?.line1}),s?.line1?n.jsx("div",{className:"text-xs text-red-600",children:s.line1}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:`${e}-line2`,children:"Address line 2"}),n.jsx(He,{id:`${e}-line2`,value:t.line2??"",onChange:a=>r({...t,line2:a.target.value})})]}),n.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:`${e}-city`,children:"City"}),n.jsx(He,{id:`${e}-city`,value:t.city,onChange:a=>r({...t,city:a.target.value}),"aria-invalid":!!s?.city}),s?.city?n.jsx("div",{className:"text-xs text-red-600",children:s.city}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:`${e}-state`,children:"State"}),n.jsx(He,{id:`${e}-state`,value:t.state??"",onChange:a=>r({...t,state:a.target.value})})]})]}),n.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:`${e}-postal`,children:"Postal code"}),n.jsx(He,{id:`${e}-postal`,value:t.postalCode,onChange:a=>r({...t,postalCode:a.target.value}),"aria-invalid":!!s?.postalCode}),s?.postalCode?n.jsx("div",{className:"text-xs text-red-600",children:s.postalCode}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:`${e}-country`,children:"Country"}),n.jsx(He,{id:`${e}-country`,value:t.country,onChange:a=>r({...t,country:a.target.value}),"aria-invalid":!!s?.country}),s?.country?n.jsx("div",{className:"text-xs text-red-600",children:s.country}):null]})]})]})]})}function op({methods:e,value:t,onChange:r,currency:s,className:o}){return e.length===0?null:n.jsxs("section",{className:H("space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",o),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Shipping method"}),n.jsx("div",{className:"space-y-2",children:e.map(a=>{const i=a.id===t;return n.jsxs(ie,{type:"button",variant:i?"default":"outline",className:"h-auto w-full justify-between px-4 py-3",onClick:()=>r(a.id),"aria-pressed":i,children:[n.jsxs("div",{className:"text-left",children:[n.jsx("div",{className:"text-sm font-medium",children:a.label}),a.detail?n.jsx("div",{className:"text-xs opacity-80",children:a.detail}):null]}),n.jsx("div",{className:"text-sm font-semibold",children:Je({amount:a.price,currency:a.currency||s})})]},a.id)})})]})}function Ro({message:e}){return e?n.jsx("div",{className:"text-xs text-red-600",children:e}):null}function ap({className:e}){const{config:t}=De(),r=js(),s=Mt(),o=t.checkout.mode,a=g.useMemo(()=>Yr(s.items,{requireEmail:t.checkout.requireEmail??!0,defaultMode:o,allowShipping:t.checkout.allowShipping??!1}),[s.items,t.checkout.allowShipping,t.checkout.requireEmail,o]),i=(t.checkout.allowShipping??!1)&&a.shippingAddress&&(o==="shipping"||o==="full"),c=a.email!=="none"||a.name!=="none"||a.phone!=="none",l={line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"},d=r.values.shippingAddress??l,m=r.values.billingAddress??l,u=sd({enabled:!!t.adapter.getShippingMethods&&i,customer:{email:r.values.email||void 0,name:r.values.name||void 0,shippingAddress:d}});return n.jsxs("form",{className:H("space-y-6",e),onSubmit:f=>f.preventDefault(),children:[a.isDigitalOnly?n.jsx(It,{className:"rounded-2xl",children:n.jsxs(qt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Digital delivery"}),n.jsx("div",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:a.fulfillmentNotes||"This is a digital product and will be available from your account after purchase."})]})}):null,a.hasPhysical&&!(t.checkout.allowShipping??!1)?n.jsx(It,{className:"rounded-2xl border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/30",children:n.jsxs(qt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-red-900 dark:text-red-200",children:"Shipping required"}),n.jsx("div",{className:"mt-1 text-sm text-red-800/90 dark:text-red-200/80",children:"Your cart contains shippable items, but shipping is disabled for this checkout."})]})}):null,c?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Contact"}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:a.email==="required"||a.name==="required"||a.phone==="required"?"Required":"Optional"})]}),n.jsxs("div",{className:"grid gap-3",children:[a.email!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:"checkout-email",children:"Email"}),n.jsx(He,{id:"checkout-email",value:r.values.email??"",onChange:f=>r.setField("email",f.target.value),placeholder:"you@company.com","aria-invalid":!!r.fieldErrors.email,required:a.email==="required"}),n.jsx(Ro,{message:r.fieldErrors.email})]}):null,a.name!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:"checkout-name",children:"Name"}),n.jsx(He,{id:"checkout-name",value:r.values.name??"",onChange:f=>r.setField("name",f.target.value),placeholder:"Full name","aria-invalid":!!r.fieldErrors.name,required:a.name==="required"}),n.jsx(Ro,{message:r.fieldErrors.name})]}):null,a.phone!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:"checkout-phone",children:"Phone"}),n.jsx(He,{id:"checkout-phone",value:r.values.phone??"",onChange:f=>r.setField("phone",f.target.value),placeholder:"Phone number","aria-invalid":!!r.fieldErrors.phone,required:a.phone==="required"}),n.jsx(Ro,{message:r.fieldErrors.phone})]}):null]})]}):null,i?n.jsx(sa,{title:"Shipping address",value:d,onChange:f=>r.setField("shippingAddress",f),errors:{line1:r.fieldErrors["shippingAddress.line1"],city:r.fieldErrors["shippingAddress.city"],postalCode:r.fieldErrors["shippingAddress.postalCode"],country:r.fieldErrors["shippingAddress.country"]}}):null,i&&u.methods.length?n.jsx(op,{methods:u.methods,value:r.values.shippingMethodId,onChange:f=>r.setField("shippingMethodId",f),currency:t.currency}):null,o==="full"?n.jsx(sa,{title:"Billing address",value:m,onChange:f=>r.setField("billingAddress",f)}):null,t.checkout.allowTipping?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Tip"}),n.jsxs("div",{className:"grid gap-2",children:[n.jsxs(dt,{htmlFor:"checkout-tip",children:["Tip amount (",t.currency,")"]}),n.jsx(He,{id:"checkout-tip",inputMode:"decimal",value:String(r.values.tipAmount??0),onChange:f=>r.setField("tipAmount",Number(f.target.value)||0)})]})]}):null,o==="full"?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Notes"}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(dt,{htmlFor:"checkout-notes",children:"Order notes (optional)"}),n.jsx(He,{id:"checkout-notes",value:r.values.notes??"",onChange:f=>r.setField("notes",f.target.value),placeholder:"Delivery instructions, gift note…"})]})]}):null]})}function ip(){if(typeof window>"u")return!1;const e=window,t=["phantom","solflare","backpack","glow","slope","sollet","coin98","clover","mathWallet","ledger","torus","walletconnect"];for(const r of t){const s=e[r];if(s&&typeof s=="object"&&"solana"in s&&s.solana)return!0}return!!e.solana}const Sk=Object.freeze(Object.defineProperty({__proto__:null,detectSolanaWallets:ip},Symbol.toStringTag,{value:"Module"}));function kk(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}function Ck(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("path",{d:"M3 6h18"}),n.jsx("path",{d:"M8 6V4h8v2"}),n.jsx("path",{d:"M6 6l1 16h10l1-16"})]})}function cp({open:e,onOpenChange:t,issues:r,onRemoveItem:s,onUpdateQuantity:o,onGoToCart:a,className:i}){const c=r.some(l=>l.type==="out_of_stock"||l.type==="product_unavailable");return n.jsx(Wa,{open:e,onOpenChange:t,children:n.jsxs(zs,{className:H("sm:max-w-lg",i),children:[n.jsxs(Ha,{children:[n.jsxs(Fs,{className:"flex items-center gap-2",children:[n.jsx(kk,{className:"h-5 w-5 text-amber-500"}),"Inventory Update"]}),n.jsx(qa,{children:c?"Some items in your cart are no longer available.":"Some items in your cart have limited availability."})]}),n.jsx("div",{className:"my-4 divide-y divide-neutral-200 dark:divide-neutral-800",children:r.map(l=>n.jsx(Nk,{issue:l,onRemove:()=>s(l.productId,l.variantId),onUpdateQty:d=>o(l.productId,l.variantId,d)},`${l.productId}::${l.variantId??""}`))}),n.jsxs(sm,{className:"flex-col gap-2 sm:flex-row",children:[a?n.jsx(ie,{type:"button",variant:"outline",onClick:()=>{t(!1),a()},children:"Go to Cart"}):null,n.jsx(ie,{type:"button",onClick:()=>t(!1),children:"Continue"})]})]})})}function Nk({issue:e,onRemove:t,onUpdateQty:r}){const s=e.type==="out_of_stock"||e.type==="product_unavailable";return n.jsxs("div",{className:"flex items-start gap-3 py-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-900 dark:text-neutral-100",children:e.title}),n.jsx("div",{className:H("mt-0.5 text-sm",s?"text-red-600 dark:text-red-400":"text-amber-600 dark:text-amber-400"),children:e.message}),e.type==="insufficient_stock"&&e.availableQty>0?n.jsxs("div",{className:"mt-1 text-xs text-neutral-500 dark:text-neutral-400",children:["You requested ",e.requestedQty,", but only ",e.availableQty," available"]}):null]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.type==="insufficient_stock"&&e.availableQty>0?n.jsxs(ie,{type:"button",size:"sm",variant:"outline",onClick:()=>r(e.availableQty),children:["Update to ",e.availableQty]}):null,n.jsxs(ie,{type:"button",size:"sm",variant:"ghost",className:"text-red-600 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-950/30 dark:hover:text-red-300",onClick:t,children:[n.jsx(Ck,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Remove"})]})]})]})}function lp({className:e,ctaLabel:t,renderEmbedded:r,embeddedFallback:s,renderCustom:o,customFallback:a}){const{config:i}=De(),c=Mt(),l=js(),{config:d,isLoading:m}=ad(),[u,f]=g.useState(!1);g.useEffect(()=>{f(ip())},[]);const h=od({items:c.items}),[x,p]=g.useState(!1),y=g.useMemo(()=>i.checkout.paymentMethods&&i.checkout.paymentMethods.length?i.checkout.paymentMethods:[{id:"card",label:"Card",ctaLabel:"Pay now"}],[i.checkout.paymentMethods]),j=g.useMemo(()=>y.filter(D=>!(D.id==="card"&&!d.card||D.id==="crypto"&&!d.crypto||D.id==="credits"&&!d.credits||D.id==="crypto"&&!u)),[u,y,d]),[b,v]=g.useState((j[0]??y[0]).id);g.useEffect(()=>{j.length&&(j.some(P=>P.id===b)||v(j[0].id))},[b,j]),g.useEffect(()=>{l.reset()},[b]);const _=j.find(P=>P.id===b)??y.find(P=>P.id===b)??y[0],C=_.description??(b==="crypto"?"Pay using a connected wallet.":void 0),E=b==="crypto"&&!u,S=m||l.status==="validating"||l.status==="creating_session"||l.status==="redirecting"||h.isVerifying,N=t??_.ctaLabel??(i.checkout.mode==="none"?"Continue to payment":"Pay now"),U=g.useCallback(async P=>{const D=await h.verify();if(!D.ok&&D.issues.length>0){p(!0);return}l.createCheckoutSession({paymentMethodId:P})},[l,h]),k=l.session?.kind==="embedded"?l.session:null,A=l.session?.kind==="custom"?l.session:null;return n.jsxs("div",{className:H("space-y-3",e),children:[j.length>1?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs font-medium text-neutral-600 dark:text-neutral-400",children:"Payment method"}),n.jsx(ti,{value:b,onValueChange:v,children:n.jsx(Qs,{className:"w-full",children:j.map(P=>n.jsx(Nr,{value:P.id,className:"flex-1",disabled:S,children:P.label},P.id))})})]}):null,l.error?n.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-900/40 dark:bg-red-950/30 dark:text-red-200",children:l.error}):null,A?n.jsx("div",{className:"space-y-3",children:o?o(A):a??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Checkout session created. Provide `renderCustom` to render a custom payment UI."})}):k?n.jsx("div",{className:"space-y-3",children:r?r(k):s??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Embedded checkout session created. Provide `renderEmbedded` to render your payment UI."})}):n.jsx(ie,{type:"button",className:"w-full",disabled:c.items.length===0||S||E,onClick:()=>{U(b)},children:h.isVerifying?"Checking availability…":S?"Processing…":N}),!k&&!A?n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:E?"Install a browser wallet to enable crypto payments.":C??"You will be redirected to complete your payment."}):null,n.jsx(cp,{open:x,onOpenChange:P=>{p(P),P||h.reset()},issues:h.result?.issues??[],onRemoveItem:(P,D)=>{c.removeItem(P,D)},onUpdateQuantity:(P,D,z)=>{c.setQty(P,D,z)}})]})}function dp({className:e}){const{config:t}=De(),r=Mt(),s=js(),{settings:o}=Yn(),a=(t.checkout.allowPromoCodes??!1)&&o.checkout.promoCodes;return n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",e),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order review"}),n.jsx(St,{className:"my-3"}),n.jsx("div",{className:"space-y-3",children:r.items.map(i=>n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[n.jsx("div",{className:"h-10 w-10 shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:i.imageSnapshot?n.jsx("img",{src:i.imageSnapshot,alt:i.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"line-clamp-1 text-sm text-neutral-950 dark:text-neutral-50",children:i.titleSnapshot}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Qty ",i.qty]})]})]}),n.jsx("div",{className:"text-sm font-semibold tabular-nums text-neutral-950 dark:text-neutral-50",children:Je({amount:i.unitPrice*i.qty,currency:i.currency})})]},`${i.productId}::${i.variantId??""}`))}),n.jsx(St,{className:"my-3"}),a?n.jsx(ui,{value:s.values.discountCode??r.promoCode,onApply:i=>{s.setField("discountCode",i??""),r.setPromoCode(i)}}):null,a?n.jsx(St,{className:"my-3"}):null,n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("span",{className:"text-neutral-600 dark:text-neutral-400",children:"Subtotal"}),n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:Je({amount:r.subtotal,currency:t.currency})})]})]})}function Xs({result:e,onContinueShopping:t,onViewOrders:r,className:s}){return e.kind==="idle"?null:e.kind==="success"?n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-600 dark:text-neutral-400",children:"Receipt"}),n.jsx("h2",{className:"mt-2 text-2xl font-semibold",children:"Payment successful"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"Thanks for your purchase. You’ll receive a confirmation email shortly."}),e.order?n.jsxs("div",{className:"mt-5 rounded-xl border border-neutral-200 bg-neutral-50 p-4 dark:border-neutral-800 dark:bg-neutral-900/40",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:["Order ",e.order.id]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[new Date(e.order.createdAt).toLocaleString()," · ",e.order.status]})]}),n.jsx("div",{className:"text-sm font-semibold",children:Je({amount:e.order.total,currency:e.order.currency})})]}),n.jsxs("div",{className:"mt-3 space-y-2",children:[e.order.items.slice(0,4).map((o,a)=>n.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[n.jsx("div",{className:"min-w-0 truncate",children:o.title}),n.jsxs("div",{className:"shrink-0 text-neutral-600 dark:text-neutral-400",children:["Qty ",o.qty]})]},`${o.title}-${a}`)),e.order.items.length>4?n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["+",e.order.items.length-4," more item(s)"]}):null]}),n.jsxs("div",{className:"mt-3 flex gap-3 text-sm",children:[e.order.receiptUrl?n.jsx("a",{href:e.order.receiptUrl,className:"hover:underline",children:"Receipt"}):null,e.order.invoiceUrl?n.jsx("a",{href:e.order.invoiceUrl,className:"hover:underline",children:"Invoice"}):null]})]}):e.orderId?n.jsxs("p",{className:"mt-4 text-xs text-neutral-500 dark:text-neutral-400",children:["Session/Order ID: ",n.jsx("span",{className:"font-mono",children:e.orderId})]}):null,n.jsxs("div",{className:"mt-6 flex flex-col gap-2 sm:flex-row",children:[t?n.jsx(ie,{type:"button",onClick:t,children:"Continue shopping"}):null,r?n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"View orders"}):null]})]}):e.kind==="cancel"?n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Checkout cancelled"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"No charges were made. You can continue shopping and try again."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]}):n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Payment failed"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:e.message??"Something went wrong while processing your payment."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]})}function Ak({onContinueShopping:e,onViewOrders:t,className:r,receiptClassName:s}){const o=va();return o.kind==="idle"?n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",r),children:n.jsx("div",{className:"text-center text-neutral-600 dark:text-neutral-400",children:"Loading order details..."})}):n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",r),children:n.jsx(Xs,{result:o,onContinueShopping:e,onViewOrders:t,className:H("w-full max-w-lg",s)})})}function Pk({onContinueShopping:e,className:t,receiptClassName:r}){const s={kind:"cancel"};return n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",t),children:n.jsx(Xs,{result:s,onContinueShopping:e,className:H("w-full max-w-lg",r)})})}function Tk(e){switch(e){case"created":return"secondary";case"paid":return"default";case"processing":return"secondary";case"fulfilled":return"outline";case"shipped":return"default";case"delivered":return"outline";case"cancelled":return"outline";case"refunded":return"outline";default:return"secondary"}}function up({order:e,onView:t,className:r}){const s=`${e.items.length} item${e.items.length===1?"":"s"}`,o=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),a=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(It,{className:H("group overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm transition-shadow hover:shadow-md dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsx(qt,{className:"p-5",children:n.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-x-4 gap-y-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsx("div",{className:"mt-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:o})]}),n.jsx("div",{className:"flex items-start justify-end",children:n.jsx(wn,{variant:Tk(e.status),className:"capitalize",children:a})}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:s}),n.jsx("div",{className:"text-right text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Je({amount:e.total,currency:e.currency})}),n.jsxs("div",{className:"col-span-2 mt-3 flex items-center justify-between gap-3 border-t border-neutral-200/70 pt-3 dark:border-neutral-800",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:()=>t(e),children:"Details"}):null]})]})})})}function mp({orders:e,onView:t,className:r}){return n.jsx("div",{className:H("grid gap-4",r),children:e.map(s=>n.jsx(up,{order:s,onView:t},s.id))})}function Ek(e){switch(e){case"paid":return"default";case"processing":return"secondary";case"fulfilled":return"outline";case"cancelled":return"outline";case"refunded":return"outline";default:return"secondary"}}function pp({order:e,onBack:t,className:r}){const s=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),o=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(It,{className:H("overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsxs(qt,{className:"p-6",children:[n.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-neutral-600 dark:text-neutral-400",children:[n.jsx("span",{children:s}),n.jsx("span",{className:"text-neutral-300 dark:text-neutral-700",children:"·"}),n.jsx("span",{children:o})]})]}),n.jsxs("div",{className:"flex items-center gap-2 sm:justify-end",children:[n.jsx(wn,{variant:Ek(e.status),className:"capitalize",children:o}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:t,children:"Back"}):null]})]}),n.jsx(St,{className:"my-5"}),n.jsx("div",{className:"space-y-3",children:e.items.map((a,i)=>n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"truncate text-sm text-neutral-950 dark:text-neutral-50",children:a.title}),n.jsxs("div",{className:"mt-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:["Qty ",a.qty]})]}),n.jsx("div",{className:"text-right text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Je({amount:a.unitPrice*a.qty,currency:a.currency})})]},`${a.title}-${i}`))}),n.jsx(St,{className:"my-5"}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Total"}),n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Je({amount:e.total,currency:e.currency})})]}),e.receiptUrl||e.invoiceUrl?n.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-2",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}):null]})})}function mi(e){const t={};e.shippingProfile&&(t.shippingProfile=e.shippingProfile),e.checkoutRequirements&&(t.checkoutRequirements=JSON.stringify(e.checkoutRequirements)),e.fulfillment?.type&&(t.fulfillmentType=e.fulfillment.type),e.fulfillment?.notes&&(t.fulfillmentNotes=e.fulfillment.notes);const r=e.attributes?.shippingCountries;return typeof r=="string"&&r.trim()&&(t.shippingCountries=r),Object.keys(t).length?t:void 0}function Ik(e){return n.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:n.jsx("path",{d:"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"})})}const Rk={shop:"/shop",category:e=>`/shop/${e}`,product:e=>`/product/${e}`,cart:"/cart",checkout:"/checkout",orders:"/account/orders",subscribe:"/subscribe"};function Ok(e){const t=new Set;let r=Number.POSITIVE_INFINITY,s=0;for(const i of e){for(const c of i.tags??[])t.add(c);r=Math.min(r,i.price),s=Math.max(s,i.price)}const o=Array.from(t).slice(0,12),a=Number.isFinite(r)?{min:r,max:s}:void 0;return{tags:o,price:a}}function Mk({className:e,routes:t,initialCategorySlug:r}){const{config:s}=De(),o=Mt(),a=Ys(),i={...Rk,...t},[c,l]=g.useState("cart"),[d,m]=g.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(min-width: 1024px)")?.matches??!1);g.useEffect(()=>{if(typeof window>"u")return;const F=window.matchMedia?.("(min-width: 1024px)");if(!F)return;const K=()=>m(F.matches);return K(),F.addEventListener?.("change",K),()=>F.removeEventListener?.("change",K)},[]);const{categories:u,isLoading:f,error:h}=ya(),x=g.useMemo(()=>wa({includeCategory:!0}),[]),[p,y]=g.useState(x?.search??""),[j,b]=g.useState(r??x?.category),[v,_]=g.useState(x?.page??1),[C,E]=g.useState(x?.sort??"featured"),[S,N]=g.useState(x?.filters??{}),{data:U,isLoading:k,error:A}=Ss({category:j,search:p.trim()||void 0,filters:S,sort:C,page:v,pageSize:24}),P=g.useMemo(()=>Ok(U?.items??[]),[U?.items]),{settings:D}=Yn(),z=D.catalog.filters,L=D.catalog.sort,O=g.useMemo(()=>{const F=[];return L.featured&&F.push({value:"featured",label:"Featured"}),L.priceAsc&&F.push({value:"price_asc",label:"Price: Low to High"}),L.priceDesc&&F.push({value:"price_desc",label:"Price: High to Low"}),F.length===0&&F.push({value:"featured",label:"Featured"}),F},[L]);g.useEffect(()=>{O.some(F=>F.value===C)||E(O[0].value)},[O,C]),_a({search:p,sort:C,page:v,category:j,filters:S},{includeCategory:!0});const[M,R]=g.useState(!1),[W,T]=g.useState(!1),[V,ee]=g.useState(null),[B,Y]=g.useState(!1),J=F=>{b(F.slug),_(1),R(!1)},ge=g.useCallback((F,K,me)=>{o.addItem({productId:F.id,variantId:K?.id,unitPrice:F.price,currency:F.currency,titleSnapshot:K?`${F.title} — ${K.title}`:F.title,imageSnapshot:F.images[0]?.url,paymentResource:F.id,metadata:mi(F)},me),a?.toast({title:"Added to cart",description:F.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(i.cart):(l("cart"),T(!0)))}})},[o,i.cart,a]);return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:i.shop,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(ci,{value:p,onChange:y})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(Bs,{open:M,onOpenChange:R,children:[n.jsx(Us,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Tr,{side:"left",children:[n.jsx(Ws,{children:n.jsx(Vs,{children:"Browse"})}),n.jsxs("div",{className:"mt-4",children:[h?n.jsx(Ht,{description:h}):null,f?n.jsxs("div",{className:"space-y-2",children:[n.jsx(ze,{className:"h-9"}),n.jsx(ze,{className:"h-9"}),n.jsx(ze,{className:"h-9"})]}):n.jsxs("div",{className:"space-y-6",children:[n.jsx(ra,{categories:u,activeSlug:j,onSelect:J}),n.jsx(xs,{facets:P,value:S,onChange:F=>{N(F),_(1)},onClear:()=>{N({}),_(1)},enabledFilters:z}),O.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(ps,{value:C,onValueChange:F=>{E(F),_(1)},children:[n.jsx(Sr,{"aria-label":"Sort",children:n.jsx(fs,{placeholder:"Sort"})}),n.jsx(kr,{children:O.map(F=>n.jsx(Cr,{value:F.value,children:F.label},F.value))})]})]})]})]})]})]}),n.jsx(Ar,{open:!d&&W,onOpenChange:T,side:"bottom",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx(Ar,{open:d&&W,onOpenChange:T,side:"popup",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(i.checkout)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",W?"lg:hidden":void 0),onClick:()=>{l("chat"),T(!0)},"aria-label":"Open chat",children:[n.jsx(Ik,{className:"h-4 w-4"}),"Chat"]}),n.jsxs("main",{className:"mx-auto grid max-w-7xl items-start gap-6 px-4 py-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:n.jsxs(It,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:[n.jsx(vr,{className:"pb-4",children:n.jsx(wr,{className:"text-base",children:"Browse"})}),n.jsxs(qt,{className:"flex-1 space-y-6 overflow-y-auto pr-2",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Categories"}),h?n.jsx(Ht,{className:"mt-3",description:h}):null,f?n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx(ze,{className:"h-9"}),n.jsx(ze,{className:"h-9"}),n.jsx(ze,{className:"h-9"})]}):n.jsx("div",{className:"mt-3",children:n.jsx(ra,{categories:u,activeSlug:j,onSelect:J})})]}),O.length>1&&n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsx("div",{className:"mt-2",children:n.jsxs(ps,{value:C,onValueChange:F=>{E(F),_(1)},children:[n.jsx(Sr,{"aria-label":"Sort",children:n.jsx(fs,{placeholder:"Sort"})}),n.jsx(kr,{children:O.map(F=>n.jsx(Cr,{value:F.value,children:F.label},F.value))})]})})]}),n.jsx(xs,{facets:P,value:S,onChange:F=>{N(F),_(1)},onClear:()=>{N({}),_(1)},enabledFilters:z})]})]})})}),n.jsxs("section",{children:[n.jsx("div",{className:"flex items-end justify-between gap-3",children:n.jsxs("div",{children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:D.shopPage.title||"Shop"}),D.shopPage.description&&n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:D.shopPage.description})]})}),A?n.jsx(Ht,{className:"mt-6",description:A}):null,k?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((F,K)=>n.jsx(ze,{className:"aspect-[4/5] rounded-2xl"},K))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(Js,{products:U?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:F=>i.product(F.slug),onAddToCart:F=>ge(F,null,1),onQuickView:F=>{ee(F),Y(!0)},layout:D.shopLayout.layout,imageCrop:D.shopLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:v<=1,onClick:()=>_(F=>Math.max(1,F-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",v]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!U?.hasNextPage,onClick:()=>_(F=>F+1),children:"Next"})]})]})]})]}),n.jsx(ai,{product:V,open:B,onOpenChange:Y,productHref:F=>i.product(F),onAddToCart:(F,K,me)=>ge(F,K,me)})]})}function Dk(e){return n.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:n.jsx("path",{d:"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"})})}function Lk({categorySlug:e,className:t,routes:r}){const{config:s}=De(),o=Mt(),a=Ys(),{categories:i}=ya(),[c,l]=g.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(min-width: 1024px)")?.matches??!1);g.useEffect(()=>{if(typeof window>"u")return;const q=window.matchMedia?.("(min-width: 1024px)");if(!q)return;const te=()=>l(q.matches);return te(),q.addEventListener?.("change",te),()=>q.removeEventListener?.("change",te)},[]);const[d,m]=g.useState(!1),[u,f]=g.useState(!1),[h,x]=g.useState("cart"),p=g.useMemo(()=>wa({includeCategory:!1}),[]),[y,j]=g.useState(p?.search??""),[b,v]=g.useState(p?.page??1),[_,C]=g.useState(p?.sort??"featured"),[E,S]=g.useState(p?.filters??{}),[N,U]=g.useState(null),[k,A]=g.useState(!1),P=i.find(q=>q.slug===e)??null,{data:D,isLoading:z,error:L}=Ss({category:e,search:y.trim()||void 0,filters:E,sort:_,page:b,pageSize:24}),O=r?.product??(q=>`/product/${q}`),M=r?.shop??"/shop",R=r?.cart??"/cart",W=r?.checkout??"/checkout",T=g.useMemo(()=>{const q=D?.items??[],te=new Set;let ce=Number.POSITIVE_INFINITY,pe=0;for(const Qe of q){for(const $e of Qe.tags??[])te.add($e);ce=Math.min(ce,Qe.price),pe=Math.max(pe,Qe.price)}const Oe=Array.from(te).slice(0,12),Ge=Number.isFinite(ce)?{min:ce,max:pe}:void 0;return{tags:Oe,price:Ge}},[D?.items]),{settings:V}=Yn(),ee=V.catalog.filters,B=V.catalog.sort,Y=g.useMemo(()=>{const q=[];return B.featured&&q.push({value:"featured",label:"Featured"}),B.priceAsc&&q.push({value:"price_asc",label:"Price: Low to High"}),B.priceDesc&&q.push({value:"price_desc",label:"Price: High to Low"}),q.length===0&&q.push({value:"featured",label:"Featured"}),q},[B]);g.useEffect(()=>{Y.some(q=>q.value===_)||C(Y[0].value)},[Y,_]),_a({search:y,sort:_,page:b,filters:E},{includeCategory:!1});const J=g.useCallback((q,te,ce)=>{o.addItem({productId:q.id,variantId:te?.id,unitPrice:q.price,currency:q.currency,titleSnapshot:te?`${q.title} — ${te.title}`:q.title,imageSnapshot:q.images[0]?.url,paymentResource:q.id,metadata:mi(q)},ce),a?.toast({title:"Added to cart",description:q.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(R):(x("cart"),f(!0)))}})},[o,R,a]),ge=q=>{S(q),v(1)},F=()=>{S({}),v(1)},K=q=>{C(q),v(1)},me=n.jsx(It,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:n.jsxs(qt,{className:"flex-1 space-y-5 overflow-y-auto pr-2 pt-6",children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-neutral-500 dark:text-neutral-400",children:"Category"}),n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2 text-xs",children:n.jsx("a",{href:M,children:"All categories"})})]}),n.jsx("div",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:P?.name??e}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:P?.description??"Browse products in this category."})]}),Y.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(ps,{value:_,onValueChange:K,children:[n.jsx(Sr,{"aria-label":"Sort",children:n.jsx(fs,{placeholder:"Sort"})}),n.jsx(kr,{children:Y.map(q=>n.jsx(Cr,{value:q.value,children:q.label},q.value))})]})]}),n.jsx(St,{}),n.jsx(xs,{facets:T,value:E,onChange:ge,onClear:F,enabledFilters:ee})]})});return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:M,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(ci,{value:y,onChange:j})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(Bs,{open:d,onOpenChange:m,children:[n.jsx(Us,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Tr,{side:"left",children:[n.jsx(Ws,{children:n.jsx(Vs,{children:"Filters"})}),n.jsx("div",{className:"mt-4",children:me})]})]}),n.jsx(Ar,{open:!c&&u,onOpenChange:f,side:"bottom",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(W)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>x("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx(Ar,{open:c&&u,onOpenChange:f,side:"popup",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(W)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>x("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(W)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",u?"lg:hidden":void 0),onClick:()=>{x("chat"),f(!0)},"aria-label":"Open chat",children:[n.jsx(Dk,{className:"h-4 w-4"}),"Chat"]}),n.jsxs("main",{className:"mx-auto max-w-7xl px-4 py-8",children:[n.jsx(ii,{items:[{label:"Shop",href:M},{label:P?.name??e}]}),n.jsxs("div",{className:"mt-6",children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:P?.name??"Category"}),n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:P?.description??"Browse products in this category."})]}),L?n.jsx(Ht,{className:"mt-6",description:L}):null,n.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:me})}),n.jsx("div",{children:z?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((q,te)=>n.jsx(ze,{className:"aspect-[4/5] rounded-2xl"},te))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(Js,{products:D?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:q=>O(q.slug),onAddToCart:q=>J(q,null,1),onQuickView:q=>{U(q),A(!0)},layout:V.categoryLayout.layout,imageCrop:V.categoryLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:b<=1,onClick:()=>v(q=>Math.max(1,q-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",b]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!D?.hasNextPage,onClick:()=>v(q=>q+1),children:"Next"})]})]})})]}),n.jsx(ai,{product:N,open:k,onOpenChange:A,productHref:q=>O(q),onAddToCart:(q,te,ce)=>J(q,te,ce)})]})]})}function $k({slug:e,className:t,routes:r}){const s=Mt(),o=Ys(),{product:a,isLoading:i,error:c}=td(e),[l,d]=g.useState(1),[m,u]=g.useState({selectedOptions:{},variant:null});g.useEffect(()=>{if(!a||!a.variants?.length)return;const P=a.variants[0];u({selectedOptions:{...P.options},variant:P})},[a?.id]);const{settings:f}=Yn(),{mode:h,maxItems:x}=f.relatedProducts,p=id({productId:a?.id,enabled:h==="ai"&&!!a?.id}),y=g.useMemo(()=>h==="by_category"&&a?.categoryIds?.length?{category:a.categoryIds[0],page:1,pageSize:x+1}:{page:1,pageSize:x+4},[h,x,a?.categoryIds]),j=Ss(y),b=g.useMemo(()=>{const D=(j.data?.items??[]).filter(z=>z.slug!==e);if(h==="manual"&&a){const z=a.attributes?.relatedProductIds||a.attributes?.related_product_ids;if(z){const L=Mo(String(z));if(L.length>0){const O=new Map(D.map(R=>[R.id,R]));return L.map(R=>O.get(R)).filter(R=>!!R).slice(0,x)}}}if(h==="ai"&&p.relatedProductIds&&p.relatedProductIds.length>0){const z=new Map(D.map(O=>[O.id,O])),L=p.relatedProductIds.map(O=>z.get(O)).filter(O=>!!O);if(L.length>0)return L.slice(0,x)}return D.slice(0,x)},[j.data?.items,e,h,x,a,p.relatedProductIds]),v=r?.shop??"/shop",_=r?.checkout??"/checkout",C=r?.cart??"/cart",E=r?.product??(P=>`/product/${P}`);if(i)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsxs("div",{className:"mx-auto max-w-6xl",children:[n.jsx(ze,{className:"h-5 w-40"}),n.jsxs("div",{className:"mt-6 grid gap-8 lg:grid-cols-2",children:[n.jsx(ze,{className:"aspect-square rounded-2xl"}),n.jsxs("div",{className:"space-y-4",children:[n.jsx(ze,{className:"h-8 w-2/3"}),n.jsx(ze,{className:"h-6 w-32"}),n.jsx(ze,{className:"h-20"}),n.jsx(ze,{className:"h-11"})]})]})]})});if(c)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsx("div",{className:"mx-auto max-w-6xl",children:n.jsx(Ht,{description:c})})});if(!a)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsx("div",{className:"mx-auto max-w-6xl",children:n.jsx(Ht,{description:"Product not found."})})});const S=m.variant?.price??a.price,N=m.variant?.compareAtPrice??a.compareAtPrice,U=a.inventoryStatus==="out_of_stock"||typeof a.inventoryQuantity=="number"&&a.inventoryQuantity<=0,k=()=>{U||(s.addItem({productId:a.id,variantId:m.variant?.id,unitPrice:S,currency:a.currency,titleSnapshot:m.variant?`${a.title} — ${m.variant.title}`:a.title,imageSnapshot:a.images[0]?.url,paymentResource:a.id,metadata:mi(a)},l),o?.toast({title:"Added to cart",description:a.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&window.location.assign(C)}}))},A=()=>{U||(k(),typeof window<"u"&&window.location.assign(_))};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-8",children:[n.jsx(ii,{items:[{label:"Shop",href:v},{label:a.title}]}),n.jsxs("div",{className:"mt-6 grid gap-10 lg:grid-cols-2",children:[n.jsx(ri,{images:a.images}),n.jsxs("div",{className:"space-y-6",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:a.title}),n.jsx("div",{className:"mt-3",children:n.jsx(Ks,{amount:S,currency:a.currency,compareAt:N})}),U?n.jsx("div",{className:"mt-2 text-sm font-medium text-red-700 dark:text-red-300",children:"Out of stock"}):typeof a.inventoryQuantity=="number"&&a.inventoryQuantity>0&&a.inventoryQuantity<=5?n.jsxs("div",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:["Only ",n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:a.inventoryQuantity})," left"]}):null,n.jsx("p",{className:"mt-4 text-sm text-neutral-600 dark:text-neutral-400",children:a.description})]}),n.jsx(si,{product:a,value:{selectedOptions:m.selectedOptions,variantId:m.variant?.id},onChange:P=>u(P)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(oi,{qty:l,onChange:d}),n.jsx(ie,{type:"button",onClick:k,className:"flex-1",disabled:U,children:U?"Out of stock":"Add to cart"}),n.jsx(ie,{type:"button",variant:"outline",onClick:A,disabled:U,children:"Buy now"})]}),(f.sections.showDescription||f.sections.showSpecs||f.sections.showShipping)&&n.jsxs(Nm,{type:"single",collapsible:!0,defaultValue:f.sections.showDescription?"desc":void 0,children:[f.sections.showDescription&&n.jsxs(hr,{value:"desc",children:[n.jsx(gr,{children:"Description"}),n.jsx(xr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.description})})]}),f.sections.showSpecs&&n.jsxs(hr,{value:"specs",children:[n.jsx(gr,{children:"Specs"}),n.jsx(xr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.attributes?n.jsx("div",{className:"space-y-1",children:Object.entries(a.attributes).map(([P,D])=>n.jsxs("div",{children:[n.jsxs("span",{className:"font-medium text-neutral-950 dark:text-neutral-50",children:[P,":"]})," ",String(D)]},P))}):"No specs provided."})})]}),f.sections.showShipping&&n.jsxs(hr,{value:"ship",children:[n.jsx(gr,{children:"Shipping & returns"}),n.jsx(xr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Ships in 2–3 business days. Easy returns within 30 days."})})]})]})]})]}),f.sections.showRelatedProducts&&b.length?n.jsxs("section",{className:"mt-12",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Related products"}),n.jsx("div",{className:"mt-4",children:n.jsx(Js,{products:b,columns:{base:2,md:4,lg:4},layout:f.relatedProducts.layout.layout,imageCrop:f.relatedProducts.layout.imageCrop,getProductHref:P=>E(P.slug),onAddToCart:P=>s.addItem({productId:P.id,unitPrice:P.price,currency:P.currency,titleSnapshot:P.title,imageSnapshot:P.images[0]?.url,paymentResource:P.id},1)})})]}):null]})})}function zk({className:e,checkoutHref:t}){const{config:r}=De(),{settings:s}=Yn(),o=t??"/checkout",a=r.checkout.allowPromoCodes&&s.checkout.promoCodes;return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-10",children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Cart"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"Review items, adjust quantities, then check out."}),n.jsx("div",{className:"mt-8",children:n.jsx(rp,{onCheckout:()=>{typeof window<"u"&&window.location.assign(o)},showPromoCode:a})})]})})}function Fk({className:e,routes:t}){const{config:r}=De(),s=Mt(),o=va(),a=r.customer?.isSignedIn??!!r.customer?.id,c=!(r.checkout.requireAccount?!1:r.checkout.guestCheckout??!0)&&!a;g.useEffect(()=>{o.kind==="success"&&s.clear()},[o.kind]);const l=t?.shop??"/shop",d=t?.orders??"/account/orders",m=t?.login;return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-10",children:[n.jsx(Xs,{result:o,onContinueShopping:()=>{typeof window<"u"&&window.location.assign(l)},onViewOrders:()=>{typeof window<"u"&&window.location.assign(d)}}),o.kind==="idle"?n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Checkout"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:r.checkout.mode==="none"?"Confirm and pay.":"Enter details, then complete payment."})]}),n.jsx("div",{className:"mt-8",children:n.jsx(ed,{children:c?n.jsxs(It,{className:"rounded-2xl",children:[n.jsx(vr,{className:"pb-4",children:n.jsx(wr,{className:"text-base",children:"Sign in required"})}),n.jsxs(qt,{children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"This store requires an account to complete checkout."}),m?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",onClick:()=>{typeof window<"u"&&window.location.assign(m)},children:"Sign in"})}):null]})]}):n.jsx(sp,{left:n.jsxs("div",{className:"space-y-6",children:[n.jsx(ap,{}),n.jsxs(It,{className:"rounded-2xl",children:[n.jsx(vr,{className:"pb-4",children:n.jsx(wr,{className:"text-base",children:"Payment"})}),n.jsxs(qt,{children:[n.jsx(St,{className:"mb-4"}),n.jsx(lp,{})]})]})]}),right:n.jsx("div",{className:"lg:sticky lg:top-24",children:n.jsx(dp,{})})})})})]}):null]})})}function Bk({className:e,isSignedIn:t=!0,onLogin:r}){const{orders:s,isLoading:o,error:a}=nd(),[i,c]=g.useState(null);return t?n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-5xl px-4 py-10 sm:py-12",children:[n.jsxs("header",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Orders"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"View past purchases and receipts."})]}),!o&&!a&&!i&&s.length>0?n.jsxs("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:[s.length," order",s.length===1?"":"s"]}):null]}),a?n.jsx(Ht,{className:"mt-8",description:a}):null,o?n.jsxs("div",{className:"mt-8 grid gap-4",children:[n.jsx(ze,{className:"h-32 rounded-2xl"}),n.jsx(ze,{className:"h-32 rounded-2xl"}),n.jsx(ze,{className:"h-32 rounded-2xl"})]}):s.length===0?n.jsx("div",{className:"mt-8",children:n.jsx(Zn,{title:"No orders yet",description:"When you purchase something, it will show up here."})}):i?n.jsx("div",{className:"mt-8",children:n.jsx(pp,{order:i,onBack:()=>c(null)})}):n.jsx("div",{className:"mt-8",children:n.jsx(mp,{orders:s,onView:c})})]})}):n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-10 dark:bg-neutral-950",e),children:n.jsx("div",{className:"mx-auto max-w-4xl",children:n.jsx(Zn,{title:"Sign in to view your orders",description:"Your purchase history will appear here once you're logged in.",actionLabel:r?"Sign in":void 0,onAction:r})})})}function Uk({className:e}){return n.jsxs("svg",{className:e,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"6 9 6 2 18 2 18 9"}),n.jsx("path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"}),n.jsx("rect",{x:"6",y:"14",width:"12",height:"8"})]})}function Wk({className:e}){return n.jsx("svg",{className:e,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})})}function Vk(e){switch(e){case"x402":return"Crypto (x402)";case"credits":return"Credits";case"stripe":return"Card";default:return"Payment"}}function Hk({order:e,source:t,purchaseId:r,customerEmail:s,customerName:o,className:a,onBack:i}){const{config:c}=De(),l=t??e.source,d=r??e.purchaseId,m=s??e.customerEmail,u=o??e.customerName,f=c.brand?.name??"Store",h=c.brand?.logoUrl,x=()=>{typeof window<"u"&&window.print()},p=new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"}),y=new Date(e.createdAt).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return n.jsxs("div",{className:H("min-h-screen bg-neutral-100 dark:bg-neutral-900 print:bg-white print:dark:bg-white",a),children:[n.jsx("div",{className:"border-b border-neutral-200 bg-white px-4 py-3 dark:border-neutral-800 dark:bg-neutral-950 print:hidden",children:n.jsxs("div",{className:"mx-auto flex max-w-2xl items-center justify-between",children:[i?n.jsxs(ie,{type:"button",variant:"ghost",size:"sm",onClick:i,children:[n.jsx(Wk,{className:"mr-1"})," Back"]}):n.jsx("div",{}),n.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:x,children:[n.jsx(Uk,{className:"mr-2"})," Print Receipt"]})]})}),n.jsx("div",{className:"mx-auto max-w-2xl px-4 py-8 print:max-w-none print:px-0 print:py-0",children:n.jsxs("div",{className:"rounded-xl border border-neutral-200 bg-white p-8 shadow-sm dark:border-neutral-800 dark:bg-neutral-950 print:border-0 print:shadow-none print:dark:bg-white print:dark:text-neutral-950",children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-neutral-200 pb-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[h?n.jsx("img",{src:h,alt:f,className:"h-10 w-10 rounded-lg object-contain"}):null,n.jsx("div",{className:"text-xl font-semibold",children:f})]}),n.jsxs("div",{className:"text-right",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Receipt"}),n.jsx("div",{className:"mt-1 font-mono text-sm",children:e.id})]})]}),n.jsxs("div",{className:"mt-6 grid grid-cols-2 gap-4 text-sm sm:grid-cols-3",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Date"}),n.jsx("div",{className:"mt-1 font-medium",children:p}),n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:y})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Payment Method"}),n.jsx("div",{className:"mt-1 font-medium",children:Vk(l)})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Status"}),n.jsx("div",{className:"mt-1",children:n.jsx(wn,{variant:"outline",className:"capitalize print:border-neutral-300",children:e.status})})]})]}),(u||m)&&n.jsxs("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Customer"}),u&&n.jsx("div",{className:"mt-1 font-medium",children:u}),m&&n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:m})]}),n.jsx("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-neutral-200 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("th",{className:"pb-3 text-left font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Item"}),n.jsx("th",{className:"pb-3 text-center font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Qty"}),n.jsx("th",{className:"pb-3 text-right font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Price"})]})}),n.jsx("tbody",{children:e.items.map((j,b)=>n.jsxs("tr",{className:"border-b border-neutral-100 dark:border-neutral-800/50 print:dark:border-neutral-100",children:[n.jsx("td",{className:"py-3",children:n.jsx("div",{className:"font-medium",children:j.title})}),n.jsx("td",{className:"py-3 text-center text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:j.qty}),n.jsx("td",{className:"py-3 text-right",children:Je({amount:j.unitPrice*j.qty,currency:j.currency})})]},`${j.title}-${b}`))})]})}),n.jsxs("div",{className:"mt-4 flex flex-col items-end gap-2 text-sm",children:[n.jsxs("div",{className:"flex w-48 justify-between",children:[n.jsx("span",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Subtotal"}),n.jsx("span",{children:Je({amount:e.total,currency:e.currency})})]}),n.jsxs("div",{className:"flex w-48 justify-between border-t border-neutral-200 pt-2 text-base font-semibold dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("span",{children:"Total"}),n.jsx("span",{children:Je({amount:e.total,currency:e.currency})})]})]}),d&&n.jsxs("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Transaction ID"}),n.jsx("div",{className:"mt-1 break-all font-mono text-xs",children:d})]}),n.jsxs("div",{className:"mt-8 border-t border-neutral-200 pt-6 text-center text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400 print:dark:border-neutral-200 print:dark:text-neutral-500",children:[n.jsx("p",{children:"Thank you for your purchase!"}),n.jsx("p",{className:"mt-1",children:"If you have any questions, please contact support."})]})]})})]})}function qk({className:e}){return n.jsx("svg",{className:H("h-4 w-4 flex-shrink-0",e),viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})}function Zk({className:e,title:t="Choose Your Plan",subtitle:r="Select the plan that best fits your needs.",annualSavingsBadge:s="2 months free",popularBadgeText:o="Best Deal",footerNotice:a}){const{config:i}=De(),{tiers:c,status:l,isLoading:d,error:m}=rd(),[u,f]=g.useState("monthly"),h=!!i.adapter.createSubscriptionCheckoutSession,x=async p=>{if(!i.adapter.createSubscriptionCheckoutSession)return;const y=await i.adapter.createSubscriptionCheckoutSession({tierId:p,interval:u,successUrl:i.checkout.successUrl,cancelUrl:i.checkout.cancelUrl});y.kind==="redirect"&&typeof window<"u"&&window.location.assign(y.url)};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-16",children:[n.jsxs("div",{className:"text-center",children:[n.jsx("h1",{className:"text-5xl font-bold tracking-tight",children:t}),n.jsx("p",{className:"mt-4 text-base text-neutral-600 dark:text-neutral-400",children:r})]}),n.jsx("div",{className:"mt-10 flex justify-center",children:n.jsxs("div",{className:"inline-flex items-center rounded-full bg-neutral-200/60 p-1 dark:bg-neutral-800/60",children:[n.jsxs("button",{type:"button",onClick:()=>f("annual"),className:H("relative flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-all",u==="annual"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:["Yearly",s&&n.jsx("span",{className:H("rounded-full px-2 py-0.5 text-xs font-medium",u==="annual"?"bg-white/20 text-white dark:bg-neutral-900/20 dark:text-neutral-900":"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900"),children:s})]}),n.jsx("button",{type:"button",onClick:()=>f("monthly"),className:H("rounded-full px-4 py-2 text-sm font-medium transition-all",u==="monthly"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:"Monthly"})]})}),m?n.jsx(Ht,{className:"mt-10",description:m}):null,d?n.jsxs("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[n.jsx(ze,{className:"h-[480px] rounded-2xl"}),n.jsx(ze,{className:"h-[480px] rounded-2xl"}),n.jsx(ze,{className:"h-[480px] rounded-2xl"})]}):c.length===0?n.jsx("div",{className:"mt-12",children:n.jsx(Zn,{title:"No plans available",description:"Subscription plans will appear here once configured."})}):n.jsx("div",{className:"mt-12 grid gap-6 md:grid-cols-3 items-start",children:c.map(p=>{const y=l?.isActive&&l.currentTierId===p.id,j=u==="annual"&&p.priceAnnual?p.priceAnnual:p.priceMonthly,b=p.isPopular,v=p.inventoryQuantity!=null,_=v?Math.max(0,(p.inventoryQuantity??0)-(p.inventorySold??0)):null,C=v&&_===0,E=v&&_!=null&&_>0&&_<=5,[S,...N]=p.features;return n.jsxs("div",{className:H("relative flex flex-col rounded-2xl border p-6 transition-shadow",b?"border-neutral-900 bg-neutral-900 text-white shadow-xl dark:border-white dark:bg-white dark:text-neutral-900":"border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-900"),children:[b&&o&&n.jsx("div",{className:"absolute -top-3 right-4",children:n.jsx("span",{className:"rounded-full bg-neutral-100 px-3 py-1 text-xs font-semibold text-neutral-900 shadow-sm dark:bg-neutral-800 dark:text-white",children:o})}),n.jsxs("div",{className:"mb-6",children:[n.jsx("h3",{className:"text-xl font-bold",children:p.title}),p.description&&n.jsx("p",{className:H("mt-2 text-sm leading-relaxed",b?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:p.description})]}),n.jsxs("div",{className:"mb-6",children:[n.jsx("div",{className:"text-5xl font-bold tracking-tight",children:Je({amount:j,currency:p.currency||i.currency})}),n.jsxs("div",{className:H("mt-2 text-sm",b?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:["Per ",u==="annual"?"year":"month",", billed ",u==="annual"?"annually":"monthly"]})]}),v&&n.jsx("div",{className:H("mb-3 text-xs font-medium",C?"text-red-600 dark:text-red-400":E?b?"text-amber-300 dark:text-amber-600":"text-amber-600 dark:text-amber-400":b?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:C?"Sold out":`${_} remaining`}),n.jsx(ie,{type:"button",className:H("mb-6 w-full rounded-full py-3 font-medium",b?"bg-white text-neutral-900 hover:bg-neutral-100 dark:bg-neutral-900 dark:text-white dark:hover:bg-neutral-800":""),variant:b?"default":"outline",disabled:y||!h||C,onClick:()=>void x(p.id),children:C?"Sold Out":y?"Current Plan":"Purchase"}),S&&n.jsx("div",{className:H("mb-4 text-sm font-semibold",b?"":"text-neutral-900 dark:text-white"),children:S}),N.length>0&&n.jsx("ul",{className:"space-y-3",children:N.map((U,k)=>n.jsxs("li",{className:"flex items-start gap-3",children:[n.jsx(qk,{className:H("mt-0.5",b?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400")}),n.jsx("span",{className:H("text-sm leading-relaxed",b?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:U})]},k))})]},p.id)})}),a&&n.jsx("div",{className:"mt-12 text-center",children:n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400 leading-relaxed max-w-2xl mx-auto",children:a})})]})})}function Gk(e){const{processCartCheckout:t}=fe.useStripeCheckout();return g.useMemo(()=>({...e,async createCheckoutSession(r){const s=await t(r.cart,r.options.successUrl,r.options.cancelUrl,r.options.metadata,r.customer.email,r.options.discountCode);if(!s.success)throw new Error(s.error||"Checkout failed");return{kind:"redirect",url:r.options.successUrl??"/"}},async resolveCheckoutReturn({query:r}){return ba(r)}}),[e,t])}const Qk=Object.freeze(Object.defineProperty({__proto__:null,Accordion:Nm,AccordionContent:xr,AccordionItem:hr,AccordionTrigger:gr,AddressForm:sa,Badge:wn,Breadcrumbs:ii,Button:ie,Card:It,CardContent:qt,CardDescription:Sd,CardFooter:kd,CardHeader:vr,CardTitle:wr,CartLineItem:li,CartPageContent:rp,CartPanel:tp,CartProvider:Bf,CartSidebar:Ar,CartSummary:di,CartTemplate:zk,CategoryNav:ra,CategoryTemplate:Lk,CedrosShopProvider:jf,CheckoutCancelPage:Pk,CheckoutForm:ap,CheckoutLayout:sp,CheckoutProvider:ed,CheckoutReceipt:Xs,CheckoutSuccessPage:Ak,CheckoutTemplate:Fk,Dialog:Wa,DialogClose:Oj,DialogContent:zs,DialogDescription:qa,DialogFooter:sm,DialogHeader:Ha,DialogOverlay:Va,DialogPortal:rm,DialogTitle:Fs,DialogTrigger:Rj,EmptyState:Zn,ErrorBoundary:fS,ErrorState:Ht,FAQItem:Jm,FAQList:pk,FilterPanel:xs,Input:He,InventoryVerificationDialog:cp,Label:dt,OrderCard:up,OrderDetails:pp,OrderList:mp,OrderReview:dp,PaymentStep:lp,Price:Ks,ProductCard:Xm,ProductGallery:ri,ProductGrid:Js,ProductTemplate:$k,PromoCodeInput:ui,PurchaseHistoryTemplate:Bk,QuantitySelector:oi,QuickViewDialog:ai,ReceiptTemplate:Hk,SearchInput:ci,Select:ps,SelectContent:kr,SelectGroup:fj,SelectItem:Cr,SelectTrigger:Sr,SelectValue:fs,Separator:St,Sheet:Bs,SheetClose:om,SheetContent:Tr,SheetDescription:im,SheetHeader:Ws,SheetOverlay:Za,SheetPortal:am,SheetTitle:Vs,SheetTrigger:Us,ShippingMethodSelector:op,ShopTemplate:Mk,Skeleton:ze,SubscriptionTemplate:Zk,Tabs:ti,TabsContent:Zm,TabsList:Qs,TabsTrigger:Nr,ToastProvider:VS,VariantSelector:si,createMockCommerceAdapter:Af,createPaywallCommerceAdapter:Rf,parseCheckoutReturn:ba,readCatalogUrlState:wa,useAIRelatedProducts:id,useCart:Mt,useCartInventory:ja,useCatalogUrlSync:_a,useCategories:ya,useCedrosPayCheckoutAdapter:Gk,useCedrosShop:De,useCheckout:js,useCheckoutResultFromUrl:va,useHoldExpiry:Ab,useInventoryVerification:od,useOptionalToast:Ys,useOrders:nd,usePaymentMethodsConfig:ad,useProduct:td,useProducts:Ss,useShippingMethods:sd,useStandaloneCheckout:bb,useStorefrontSettings:Yn,useSubscriptionData:rd,useToast:WS,validateCommerceAdapterContract:Ib},Symbol.toStringTag,{value:"Module"}));exports.CSP_PRESETS=vp;exports.CedrosPay=wp;exports.CedrosPayAdminDashboard=nf;exports.CouponsSection=nl;exports.CreditsSubscribeButton=af;exports.CryptoSubscribeButton=of;exports.ProductsSection=el;exports.PurchaseButton=Jc;exports.RPC_PROVIDERS=bp;exports.RefundsSection=rl;exports.SECURITY_RECOMMENDATIONS=_f;exports.SettingsSection=ca;exports.SubscribeButton=sf;exports.SubscriptionManagementPanel=pf;exports.TransactionsSection=tl;exports.cedrosPayPlugin=rf;exports.formatCSP=Kc;exports.generateCSP=yp;exports.generateCSPDirectives=Yc;exports.index=Qk;exports.logSecurityReport=wf;exports.useCreditsSubscription=hl;exports.useCryptoSubscription=fl;exports.useRefundVerification=ff;exports.useSubscription=pl;exports.useSubscriptionManagement=gl;exports.validateSecurity=vf;