@cedros/pay-react 1.1.17 → 1.1.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AISettingsSection-BrXUD4l_.js → AISettingsSection-C-thWh51.js} +1 -1
- package/dist/{AISettingsSection--jn-BNmd.mjs → AISettingsSection-CD9IRyR1.mjs} +2 -2
- package/dist/{AutosaveIndicator-BQkm3cn8.js → AutosaveIndicator-DxemlKnX.js} +1 -1
- package/dist/{AutosaveIndicator-B3T328jH.mjs → AutosaveIndicator-G2CRN8hH.mjs} +1 -1
- package/dist/{CryptoButton-Dhxnk9d7.mjs → CryptoButton-BdOtL7w-.mjs} +1 -1
- package/dist/{CryptoButton-B4-oJ8lF.js → CryptoButton-N8kRfNDO.js} +1 -1
- package/dist/{FAQSection-BB1wJRsR.mjs → FAQSection-CyYK9OAN.mjs} +1 -1
- package/dist/{FAQSection-aoAz35MV.js → FAQSection-_pm1ekTe.js} +1 -1
- package/dist/{MessagingSection-DId-WJdU.js → MessagingSection-BHzf1Mhu.js} +1 -1
- package/dist/{MessagingSection-BG9O62ko.mjs → MessagingSection-DO2yPTvs.mjs} +2 -2
- package/dist/{PaymentSettingsSection-c13RAUxn.mjs → PaymentSettingsSection--Aqlne1F.mjs} +1 -1
- package/dist/{PaymentSettingsSection-D92IO4xJ.js → PaymentSettingsSection-DpENgoca.js} +1 -1
- package/dist/{SettingsSection-htem-WL3.mjs → SettingsSection-CGKKGXWz.mjs} +1 -1
- package/dist/{SettingsSection-DUxjXl2G.js → SettingsSection-DNoODw7i.js} +1 -1
- package/dist/{SingleCategorySettings-BIEs6s6Z.mjs → SingleCategorySettings-8DCtLcow.mjs} +22 -22
- package/dist/{SingleCategorySettings-CQ-osdzb.js → SingleCategorySettings-NLBYxM0O.js} +2 -2
- package/dist/{StorefrontSection-DcSoDx-k.js → StorefrontSection-BEOMtSAg.js} +1 -1
- package/dist/{StorefrontSection-CKTQt255.mjs → StorefrontSection-Mzr1H51w.mjs} +2 -2
- package/dist/{SubscriptionsSection-C0hYf7Hr.js → SubscriptionsSection-4b29i-41.js} +1 -1
- package/dist/{SubscriptionsSection-CONwHhT4.mjs → SubscriptionsSection-Dy1e15fe.mjs} +1 -1
- package/dist/components/admin/SingleCategorySettings.d.ts.map +1 -1
- package/dist/crypto-only.js +1 -1
- package/dist/crypto-only.mjs +3 -3
- package/dist/{index-2N_CMVAv.js → index-B-0trqeD.js} +1 -1
- package/dist/{index-C1hbnxn0.mjs → index-bbSf3B7-.mjs} +24 -24
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{sections-D2GMJuKq.js → sections-CKwGmrzV.js} +1 -1
- package/dist/{sections-DICaHGhz.mjs → sections-DpEdFL1B.mjs} +1 -1
- package/dist/stripe-only.js +1 -1
- package/dist/stripe-only.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var jp=Object.create;var Ei=Object.defineProperty;var Sp=Object.getOwnPropertyDescriptor;var Cp=Object.getOwnPropertyNames;var Np=Object.getPrototypeOf,Ep=Object.prototype.hasOwnProperty;var Ap=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Cp(t))!Ep.call(e,o)&&o!==n&&Ei(e,o,{get:()=>t[o],enumerable:!(r=Sp(t,o))||r.enumerable});return e};var Pp=(e,t,n)=>(n=e!=null?jp(Np(e)):{},Ap(t||!e||!e.__esModule?Ei(n,"default",{value:e,enumerable:!0}):n,e));const oe=require("./CedrosContext-C26DlvLF.js"),s=require("react/jsx-runtime"),b=require("react"),Ip=require("@solana/wallet-adapter-react");require("@solana/web3.js");const Ai=require("./index-WcOlBYZJ.js"),Tp=require("@cedros/login-react"),fa=require("react-dom");function nl(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const p=nl(b),Ps=nl(fa);function Rp(e){return!e||!e.coupon_codes?[]:e.coupon_codes.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Op(e,t=", "){return e.join(t)}function Mp(e,t){return e<=0?0:(e-t)/e*100}function Lp(e,t){if(!t||t.length===0)return e;let n=e,r=0;for(const o of t)if(o.discountType==="percentage"){const a=1-o.discountValue/100;n=n*a}else o.discountType==="fixed"&&(r+=o.discountValue);return n=n-r,n<0&&(n=0),Math.ceil(n*100)/100}function rl(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return 1;const n=Math.floor(t);return n>0?n:1}function us(e){return e.map(t=>({resource:t.resource,quantity:rl(t.quantity),variantId:t.variantId,metadata:t.metadata}))}function Mr(e){return e.reduce((t,n)=>t+rl(n.quantity),0)}function Dp(e){return!!(e&&e.length>0&&(e.length>1||e.length===1&&(e[0].quantity??1)>1))}const Un=new Map,Uo=new Map,bn=new Map,fs=1e3,sl=200,pa=2e3;function $p(e){const t=bn.get(e);return t?Date.now()<t?!0:(bn.delete(e),!1):!1}function zp(e,t=sl){const n=Date.now()+t;if(bn.set(e,n),bn.size>fs){const r=Array.from(bn.keys()).slice(0,bn.size-fs);for(const o of r)bn.delete(o)}}function Fp(e,t=pa){const n=Un.get(e);if(!n)return!1;const o=Date.now()-n;return o<t?(oe.getLogger().debug(`[Deduplication] Duplicate request blocked: ${e} (${o}ms ago)`),!0):!1}function Bp(e){if(Un.set(e,Date.now()),Un.size>fs){const t=Array.from(Un.keys()).slice(0,Un.size-fs);for(const n of t)Un.delete(n)}}function Up(e){return Uo.get(e)||null}function Vp(e,t){Uo.set(e,t);const n=()=>{Uo.delete(e),Bp(e)};return t.then(n,n),t}async function Wp(e,t,n={}){const{windowMs:r=pa,throwOnDuplicate:o=!0}=n,a=Up(e);if(a)return oe.getLogger().debug(`[Deduplication] Reusing in-flight request: ${e}`),a;if(Fp(e,r)){if(o)throw new Error(`Duplicate request blocked: ${e}`);oe.getLogger().warn(`[Deduplication] Duplicate request blocked but not throwing: ${e}`);return}const i=t();return Vp(e,i)}function Qn(e,t,n={}){const{cooldownMs:r=sl,deduplicationWindowMs:o=pa}=n;return async()=>{if($p(e)){oe.getLogger().debug(`[Deduplication] Button in cooldown: ${e}`);return}zp(e,r);try{await Wp(e,async()=>{const a=t();a instanceof Promise&&await a},{windowMs:o,throwOnDuplicate:!1})}catch(a){if(a instanceof Error&&a.message.includes("Duplicate request"))return;throw a}}}function ol(e){return{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:e,opacity:.6,padding:"0.25rem",lineHeight:1}}const dn={PAYMENT_START:"cedros:payment:start",WALLET_CONNECT:"cedros:wallet:connect",WALLET_CONNECTED:"cedros:wallet:connected",WALLET_ERROR:"cedros:wallet:error",PAYMENT_PROCESSING:"cedros:payment:processing",PAYMENT_SUCCESS:"cedros:payment:success",PAYMENT_ERROR:"cedros:payment:error"};function An(e,t){if(typeof window>"u")return;const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!1});window.dispatchEvent(n)}function Kn(e,t,n){An(dn.PAYMENT_START,{timestamp:Date.now(),method:e,resource:t,itemCount:n})}function qp(e){An(dn.WALLET_CONNECT,{timestamp:Date.now(),wallet:e})}function Hp(e,t){An(dn.WALLET_CONNECTED,{timestamp:Date.now(),wallet:e,publicKey:t})}function Zp(e,t){An(dn.WALLET_ERROR,{timestamp:Date.now(),wallet:t,error:e})}function Jn(e,t,n){An(dn.PAYMENT_PROCESSING,{timestamp:Date.now(),method:e,resource:t,itemCount:n})}function Xn(e,t,n,r){An(dn.PAYMENT_SUCCESS,{timestamp:Date.now(),method:e,transactionId:t,resource:n,itemCount:r})}function Bt(e,t,n,r){An(dn.PAYMENT_ERROR,{timestamp:Date.now(),method:e,error:t,resource:n,itemCount:r})}function Gp(e){return e instanceof oe.PaymentError&&e.canRetry()}function Yp(e){return e instanceof oe.PaymentError?e.getUserMessage():e instanceof Error?e.message:String(e)}function Qp(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 Kp(e){try{const t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e}}function al(e={}){const{solanaCluster:t="mainnet-beta",solanaEndpoint:n,customRpcProviders:r=[],allowUnsafeScripts:o=!1,additionalScriptSrc:a=[],additionalConnectSrc:i=[],additionalFrameSrc:c=[],includeStripe:l=!0,includeSolana:d=!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 f=["'self'"];o&&f.push("'unsafe-inline'","'unsafe-eval'"),l&&f.push("https://js.stripe.com"),f.push(...a);const u=["'self'"];if(l&&u.push("https://api.stripe.com","https://*.stripe.com"),d){const h=Qp(t);if(u.push(h),n){const v=Kp(n);u.includes(v)||u.push(v)}r.forEach(v=>{u.includes(v)||u.push(v)})}u.push(...i);const m=["'self'"];return l&&m.push("https://js.stripe.com","https://checkout.stripe.com"),m.push(...c),{scriptSrc:f,connectSrc:u,frameSrc:m}}function il(e,t="header"){const{scriptSrc:n,connectSrc:r,frameSrc:o}=e;switch(t){case"header":case"meta":case"nextjs":case"nginx":{const a=[];return n.length>0&&a.push(`script-src ${n.join(" ")}`),r.length>0&&a.push(`connect-src ${r.join(" ")}`),o.length>0&&a.push(`frame-src ${o.join(" ")}`),a.join("; ")}case"helmet":{const a={};return n.length>0&&(a.scriptSrc=n),r.length>0&&(a.connectSrc=r),o.length>0&&(a.frameSrc=o),a}case"directives":return{scriptSrc:n,connectSrc:r,frameSrc:o};default:throw new Error(`Unknown CSP format: ${t}`)}}function Jp(e={},t="header"){const n=al(e);return il(n,t)}const Xp={HELIUS:"https://*.helius-rpc.com",QUICKNODE:"https://*.quicknode.pro",ALCHEMY:"https://*.alchemy.com",ANKR:"https://rpc.ankr.com",TRITON:"https://*.rpcpool.com"},em={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:()=>({includeStripe:!0,includeSolana:!1})};function br(e){return new Date(e).toLocaleString()}function Is(){const{stripeManager:e}=oe.useCedrosContext(),[t,n]=b.useState({status:"idle",error:null,transactionId:null}),r=b.useRef(!1),o=b.useCallback(async(c,l,d,f,u,m)=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n({status:"loading",error:null,transactionId:null});const h={resource:c,successUrl:l,cancelUrl:d,metadata:f,customerEmail:u,couponCode:m};try{const v=await e.processPayment(h);return n({status:v.success?"success":"error",error:v.success?null:v.error||"Payment failed",transactionId:v.success&&v.transactionId||null}),v}catch(v){const x=v instanceof Error?v.message:"Payment failed";return n({status:"error",error:x,transactionId:null}),{success:!1,error:x}}finally{r.current=!1}},[e]),a=b.useCallback(async(c,l,d,f,u,m,h,v,x,g,y,k,_)=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n({status:"loading",error:null,transactionId:null});const w=us(c);try{const j=await e.processCartCheckout({items:w,successUrl:l,cancelUrl:d,metadata:f,customerEmail:u,customerName:h,customerPhone:v,shippingAddress:x,billingAddress:g,couponCode:m,tipAmount:y,shippingMethodId:k,paymentMethodId:_});return n({status:j.success?"success":"error",error:j.success?null:j.error||"Cart checkout failed",transactionId:j.success&&j.transactionId||null}),j}catch(j){const P=j instanceof Error?j.message:"Cart checkout failed";return n({status:"error",error:P,transactionId:null}),{success:!1,error:P}}finally{r.current=!1}},[e]),i=b.useCallback(()=>{n({status:"idle",error:null,transactionId:null}),r.current=!1},[]);return{...t,processPayment:o,processCartCheckout:a,reset:i}}function Lr(e,t){return b.useMemo(()=>{const n=Dp(t),r=e||(t?.length===1?t[0].resource:"");return{isCartMode:n,effectiveResource:r}},[e,t])}const tm=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((o,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},xo=new Map;let Vr=null;async function Pi(e){if(xo.has(e))return xo.get(e);try{const t=await tm(Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),`./translations/${e}.json`,3),n=t.default||t;return xo.set(e,n),n}catch{return null}}async function nm(){if(Vr)return Vr;const e=Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),t=[];for(const n in e){const r=n.match(/\.\/translations\/([a-z]{2,3}(?:-[A-Z]{2})?)\.json$/);r&&t.push(r[1])}return Vr=t.length>0?t:["en"],Vr}function cl(){return typeof navigator>"u"?"en":(navigator.language||navigator.userLanguage||"en").split("-")[0].toLowerCase()}async function ll(e){let t=await Pi(e);if(t||(t=await Pi("en"),t))return t;throw new Error("Critical: No translation files found, not even en.json")}function dl(e){return(t,n)=>{const r=t.split(".");let o=e;for(const a of r)if(o&&typeof o=="object"&&a in o)o=o[a];else return t;return typeof o!="string"?t:n?Object.entries(n).reduce((a,[i,c])=>a.replace(new RegExp(`\\{${i}\\}`,"g"),c),o):o}}function rm(e,t,n=!0){const r=t.errors[e];if(!r){const o=oe.getUserFriendlyError(e);return n&&o.action?`${o.message} ${o.action}`:o.message}return n&&r.action?`${r.message} ${r.action}`:r.message}function Pn(e){const[t,n]=b.useState(null),[r,o]=b.useState(!0),a=b.useMemo(()=>e||cl(),[e]);return b.useEffect(()=>{let c=!1;return(async()=>{o(!0);try{const d=await ll(a);c||(n(d),o(!1))}catch(d){console.error("[CedrosPay] Failed to load translations:",d),c||o(!1)}})(),()=>{c=!0}},[a]),{t:b.useMemo(()=>t?dl(t):c=>({"ui.purchase":"Purchase","ui.pay_with_card":"Pay with Card","ui.pay_with_crypto":"Pay with USDC","ui.pay_with_usdc":"Pay with USDC","ui.card":"Card","ui.usdc_solana":"USDC (Solana)","ui.crypto":"Crypto","ui.processing":"Processing...","ui.loading":"Loading...","ui.connect_wallet":"Connect Wallet","ui.connecting":"Connecting..."})[c]||c,[t]),locale:a,isLoading:r,translations:t}}function sm(e,t=!0){const{translations:n}=Pn();if(!n){const o=oe.getUserFriendlyError(e);return t&&o.action?`${o.message} ${o.action}`:o.message}const r=n.errors[e];if(!r){const o=oe.getUserFriendlyError(e);return t&&o.action?`${o.message} ${o.action}`:o.message}return t&&r.action?`${r.message} ${r.action}`:r.message}function ma({resource:e,items:t,successUrl:n,cancelUrl:r,metadata:o,customerEmail:a,couponCode:i,label:c,disabled:l=!1,onAttempt:d,onSuccess:f,onError:u,className:m=""}){const{status:h,error:v,transactionId:x,processPayment:g,processCartCheckout:y}=Is(),k=oe.useCedrosTheme(),{isCartMode:_,effectiveResource:w}=Lr(e,t),{t:j,translations:P}=Pn(),T=c||j("ui.pay_with_card"),N=k.unstyled?m:`${k.className} cedros-theme__stripe-button ${m}`.trim(),A=v&&typeof v!="string"?v?.code??null:null,I=v?typeof v=="string"?v:(S=>{if(!S||!P)return"";const C=P.errors[S];return C?C.action?`${C.message} ${C.action}`:C.message:""})(A):null,M=b.useCallback(async()=>{oe.getLogger().debug("[StripeButton] executePayment with couponCode:",i);const S=_&&t?Mr(t):void 0;if(Kn("stripe",w,S),d&&d("stripe"),!_&&!w){const W="Invalid payment configuration: missing resource or items";oe.getLogger().error("[StripeButton]",W),Bt("stripe",W,w,S),u&&u(W);return}let C;Jn("stripe",w,S),_&&t?(oe.getLogger().debug("[StripeButton] Processing cart checkout with coupon:",i),C=await y(t,n,r,o,a,i)):w&&(oe.getLogger().debug("[StripeButton] Processing single payment with coupon:",i),C=await g(w,n,r,o,a,i)),C&&C.success&&C.transactionId?(Xn("stripe",C.transactionId,w,S),f&&f(C.transactionId)):C&&!C.success&&C.error&&(Bt("stripe",C.error,w,S),u&&u(C.error))},[i,_,w,t,n,r,o,a,y,g,d,f,u]),z=b.useMemo(()=>_&&t?`stripe-cart-${t.map(S=>S.resource).join("-")}`:`stripe-${w||"unknown"}`,[_,t,w]),D=b.useMemo(()=>Qn(z,M),[z,M]),V=h==="loading",L=l||V;return s.jsxs("div",{className:N,style:k.unstyled?{}:k.style,children:[s.jsx("button",{onClick:D,disabled:L,className:k.unstyled?m:"cedros-theme__button cedros-theme__stripe",type:"button",children:V?j("ui.processing"):T}),I&&s.jsx("div",{className:k.unstyled?"":"cedros-theme__error",children:I}),x&&s.jsx("div",{className:k.unstyled?"":"cedros-theme__success",children:j("ui.payment_successful")})]})}function ul(){const{creditsManager:e}=oe.useCedrosContext(),[t,n]=b.useState({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),r=b.useRef(!1),o=b.useCallback(async(d,f)=>{n(u=>({...u,status:"loading",error:null}));try{const u=await e.requestQuote(d,f);return n(m=>({...m,status:"idle",requirement:u})),u}catch(u){const m=u instanceof Error?u.message:"Failed to fetch credits quote";return n(h=>({...h,status:"error",error:m})),null}},[e]),a=b.useCallback(async(d,f)=>{n(u=>({...u,status:"loading",error:null}));try{const u=us(d),m=await e.requestCartQuote(u,f);return n(h=>({...h,status:"idle"})),m}catch(u){const m=u instanceof Error?u.message:"Failed to fetch cart credits quote";return n(h=>({...h,status:"error",error:m})),null}},[e]),i=b.useCallback(async(d,f,u,m)=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=await e.processPayment(d,f,u,m);return n({status:h.success?"success":"error",error:h.success?null:h.error||"Credits payment failed",transactionId:h.success&&h.transactionId||null,requirement:null,holdId:null}),h}catch(h){const v=h instanceof Error?h.message:"Credits payment failed";return n({status:"error",error:v,transactionId:null,requirement:null,holdId:null}),{success:!1,error:v}}finally{r.current=!1}},[e]),c=b.useCallback(async(d,f,u,m)=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});let h=null;try{const v=us(d),x=await e.requestCartQuote(v,u);if(!x)return n({status:"error",error:"Credits payment not available for this cart",transactionId:null,requirement:null,holdId:null}),{success:!1,error:"Credits payment not available"};h=(await e.createCartHold({cartId:x.cartId,authToken:f})).holdId,n(k=>({...k,holdId:h}));const y=await e.authorizeCartPayment({cartId:x.cartId,holdId:h,authToken:f,metadata:m});if(!y.success&&h)try{await e.releaseHold(h,f)}catch(k){oe.getLogger().warn("[useCreditsPayment] Hold release failed, will expire server-side",{holdId:h,error:k instanceof Error?k.message:String(k)})}return n({status:y.success?"success":"error",error:y.success?null:y.error||"Cart credits payment failed",transactionId:y.success&&y.transactionId||null,requirement:null,holdId:null}),{success:y.success,transactionId:y.transactionId,error:y.error}}catch(v){const x=v instanceof Error?v.message:"Cart credits payment failed";if(h)try{await e.releaseHold(h,f)}catch(g){oe.getLogger().warn("[useCreditsPayment] Hold release failed, will expire server-side",{holdId:h,error:g instanceof Error?g.message:String(g)})}return n({status:"error",error:x,transactionId:null,requirement:null,holdId:null}),{success:!1,error:x}}finally{r.current=!1}},[e]),l=b.useCallback(()=>{n({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),r.current=!1},[]);return{...t,fetchQuote:o,fetchCartQuote:a,processPayment:i,processCartPayment:c,reset:l}}function ha({resource:e,items:t,authToken:n,metadata:r,couponCode:o,label:a,disabled:i=!1,onAttempt:c,onSuccess:l,onError:d,className:f=""}){const{status:u,error:m,transactionId:h,processPayment:v,processCartPayment:x}=ul(),g=oe.useCedrosTheme(),{isCartMode:y,effectiveResource:k}=Lr(e,t),{t:_,translations:w}=Pn(),j=a||_("ui.pay_with_credits")||"Pay with Credits",P=g.unstyled?f:`${g.className} cedros-theme__credits-button ${f}`.trim(),T=m&&typeof m!="string"?m?.code??null:null,A=m?typeof m=="string"?m:(V=>{if(!V||!w)return"";const L=w.errors[V];return L?L.action?`${L.message} ${L.action}`:L.message:""})(T):null,R=b.useCallback(async()=>{oe.getLogger().debug("[CreditsButton] executePayment");const V=y&&t?Mr(t):void 0;if(Kn("credits",k,V),c&&c("credits"),!n){const S="Authentication required: please log in to pay with credits";oe.getLogger().error("[CreditsButton]",S),Bt("credits",S,k,V),d&&d(S);return}if(!y&&!k){const S="Invalid payment configuration: missing resource";oe.getLogger().error("[CreditsButton]",S),Bt("credits",S,k,V),d&&d(S);return}let L;Jn("credits",k,V),y&&t?(oe.getLogger().debug("[CreditsButton] Processing cart checkout"),L=await x(t,n,o,r)):k&&(oe.getLogger().debug("[CreditsButton] Processing single payment"),L=await v(k,n,o,r)),L&&L.success&&L.transactionId?(Xn("credits",L.transactionId,k,V),l&&l(L.transactionId)):L&&!L.success&&L.error&&(Bt("credits",L.error,k,V),d&&d(L.error))},[n,y,k,t,o,r,v,x,c,l,d]),I=b.useMemo(()=>y&&t?`credits-cart-${t.map(V=>V.resource).join("-")}`:`credits-${k||"unknown"}`,[y,t,k]),M=b.useMemo(()=>Qn(I,R),[I,R]),z=u==="loading",D=i||z;return s.jsxs("div",{className:P,style:g.unstyled?{}:g.style,children:[s.jsx("button",{onClick:M,disabled:D,className:g.unstyled?f:"cedros-theme__button cedros-theme__credits",type:"button",children:z?_("ui.processing"):j}),A&&s.jsx("div",{className:g.unstyled?"":"cedros-theme__error",children:A}),h&&s.jsx("div",{className:g.unstyled?"":"cedros-theme__success",children:_("ui.payment_successful")})]})}const om=b.lazy(()=>Promise.resolve().then(()=>require("./CryptoButton-B4-oJ8lF.js")).then(e=>e.CryptoButton$1).then(e=>({default:e.CryptoButton}))),fl=({isOpen:e,onClose:t,resource:n,items:r,cardLabel:o="Card",cryptoLabel:a="USDC (Solana)",creditsLabel:i="Pay with Credits",showCard:c=!0,showCrypto:l=!0,showCredits:d=!1,onPaymentAttempt:f,onPaymentSuccess:u,onPaymentError:m,onStripeSuccess:h,onCryptoSuccess:v,onCreditsSuccess:x,onStripeError:g,onCryptoError:y,onCreditsError:k,customerEmail:_,successUrl:w,cancelUrl:j,metadata:P,couponCode:T,authToken:N,testPageUrl:A,hideMessages:R=!1})=>{const{tokens:I}=oe.useCedrosTheme();return b.useEffect(()=>{const M=z=>{z.key==="Escape"&&e&&t()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e,t]),b.useEffect(()=>{if(e){const M=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${M}px`,document.body.style.width="100%",document.body.style.overflowY="scroll",()=>{const z=document.body.style.top?Math.abs(parseInt(document.body.style.top.replace("px",""),10)):0;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflowY="",window.scrollTo(0,z)}}},[e]),e?s.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:I.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:t,children:s.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:I.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 ${I.modalBorder}`},onClick:M=>M.stopPropagation(),children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[s.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:I.surfaceText},children:"Choose Payment Method"}),s.jsx("button",{type:"button",onClick:t,style:ol(I.surfaceText),"aria-label":"Close modal",children:"×"})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[c&&s.jsx(ma,{resource:n,items:r,label:o,onAttempt:f,onSuccess:h||u,onError:g||m,customerEmail:_,successUrl:w,cancelUrl:j,metadata:P,couponCode:T}),l&&s.jsx(b.Suspense,{fallback:null,children:s.jsx(om,{resource:n,items:r,label:a,onAttempt:f,onSuccess:v||u,onError:y||m,testPageUrl:A,hideMessages:R,metadata:P,couponCode:T})}),d&&s.jsx(ha,{resource:n,items:r,label:i,authToken:N,onAttempt:f?()=>f("credits"):void 0,onSuccess:x||u,onError:k||m,metadata:P,couponCode:T})]})]})}):null},pl=({resource:e,items:t,label:n,cardLabel:r,cryptoLabel:o,creditsLabel:a,showCard:i=!0,showCrypto:c=!0,showCredits:l=!1,onPaymentAttempt:d,onPaymentSuccess:f,onPaymentError:u,onStripeSuccess:m,onCryptoSuccess:h,onCreditsSuccess:v,onStripeError:x,onCryptoError:g,onCreditsError:y,customerEmail:k,successUrl:_,cancelUrl:w,metadata:j,couponCode:P,authToken:T,autoDetectWallets:N=!0,testPageUrl:A,hideMessages:R=!1,renderModal:I})=>{const M=oe.useCedrosTheme(),[z,D]=b.useState(!1),{status:V,processPayment:L,processCartCheckout:S}=Is(),{isCartMode:C,effectiveResource:W}=Lr(e,t),{t:Z}=Pn(),Q=n||Z("ui.purchase"),de=r||Z("ui.card"),q=o||Z("ui.usdc_solana"),K=a||Z("ui.pay_with_credits")||"Pay with Credits",Y=b.useCallback(async()=>{if(N&&i){const{detectSolanaWallets:U}=await Promise.resolve().then(()=>require("./walletDetection-bNmV5ItZ.js"));if(!U()){const se=C?void 0:W,le=C&&t?Mr(t):void 0;Kn("stripe",se,le),d&&d("stripe"),Jn("stripe",se,le);let ue;C&&t?ue=await S(t,_,w,j,k,P):W&&(ue=await L(W,_,w,j,k,P)),ue&&ue.success&&ue.transactionId?(Xn("stripe",ue.transactionId,se,le),m?m(ue.transactionId):f&&f(ue.transactionId)):ue&&!ue.success&&ue.error&&(Bt("stripe",ue.error,se,le),x?x(ue.error):u&&u(ue.error));return}}D(!0)},[N,i,C,t,W,S,L,_,w,j,k,P,f,u,m,x,d]),me=b.useMemo(()=>C&&t?`purchase-cart-${t.map(U=>U.resource).join("-")}`:`purchase-${W||"unknown"}`,[C,t,W]),$=b.useMemo(()=>Qn(me,Y),[me,Y]),G=V==="loading",pe={isOpen:z,onClose:()=>D(!1),resource:C?void 0:W,items:C?t:void 0,cardLabel:de,cryptoLabel:q,creditsLabel:K,showCard:i,showCrypto:c,showCredits:l,onPaymentAttempt:d,onPaymentSuccess:U=>{D(!1),f?.(U)},onPaymentError:U=>{D(!1),u?.(U)},onStripeSuccess:U=>{D(!1),m?.(U)},onCryptoSuccess:U=>{D(!1),h?.(U)},onCreditsSuccess:U=>{D(!1),v?.(U)},onStripeError:U=>{D(!1),x?.(U)},onCryptoError:U=>{D(!1),g?.(U)},onCreditsError:U=>{D(!1),y?.(U)},customerEmail:k,successUrl:_,cancelUrl:w,metadata:j,couponCode:P,authToken:T,testPageUrl:A,hideMessages:R};return s.jsxs("div",{className:M.unstyled?"":M.className,style:M.unstyled?{}:M.style,children:[s.jsx("button",{onClick:$,disabled:G,className:M.unstyled?"":"cedros-theme__button cedros-theme__stripe",style:{width:"100%",cursor:G?"not-allowed":"pointer",opacity:G?.6:1},type:"button",children:G?Z("ui.processing"):Q}),I?I(pe):s.jsx(fl,{...pe})]})},am={"mainnet-beta":"https://api.mainnet-beta.solana.com",devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com"};function im(){const[e,t]=b.useState(null);return b.useEffect(()=>{let n=!1;return import("@solana/wallet-adapter-react").then(r=>{n||t(r)}),()=>{n=!0}},[]),e}function cm({endpoint:e,wallets:t,children:n}){const r=im();if(!r)return s.jsx(s.Fragment,{children:n});const{ConnectionProvider:o,WalletProvider:a}=r;return s.jsx(o,{endpoint:e,children:s.jsx(a,{wallets:t,autoConnect:!1,children:n})})}const lm=b.lazy(()=>Promise.resolve().then(()=>require("./CryptoButton-B4-oJ8lF.js")).then(e=>e.CryptoButton$1).then(e=>({default:e.CryptoButton})));function dm(e){const{resource:t,items:n,checkout:r={},display:o={},callbacks:a={},advanced:i={}}=e,{config:c,walletPool:l}=oe.useCedrosContext(),d=oe.useCedrosTheme(),{isCartMode:f}=Lr(t,n),u=o.showCrypto??!0,m=b.useMemo(()=>({marginTop:"0.5rem",fontSize:"0.875rem",color:d.tokens.surfaceText,opacity:.7,textAlign:"center"}),[d.tokens.surfaceText]),h=b.useMemo(()=>u?i.wallets&&i.wallets.length>0?i.wallets:l.getAdapters():[],[i.wallets,l,u]),v=b.useMemo(()=>n?Mr(n):0,[n]),{onPaymentSuccess:x,onPaymentError:g,onPaymentAttempt:y}=a,k=b.useCallback(S=>x?.({transactionId:S,method:"stripe"}),[x]),_=b.useCallback(S=>x?.({transactionId:S,method:"crypto"}),[x]),w=b.useCallback(S=>g?.({message:S,method:"stripe"}),[g]),j=b.useCallback(S=>g?.({message:S,method:"crypto"}),[g]),P=b.useCallback(S=>x?.({transactionId:S,method:"credits"}),[x]),T=b.useCallback(S=>g?.({message:S,method:"credits"}),[g]),N=b.useCallback(()=>y?.("credits"),[y]),A=u?c.solanaEndpoint??am[c.solanaCluster]:"";if(!t&&(!n||n.length===0))return oe.getLogger().error('CedrosPay: Must provide either "resource" or "items" prop'),s.jsx("div",{className:o.className,style:{color:d.tokens.errorText},children:"Configuration error: No resource or items provided"});const R=o.showCard??!0,I=o.showCredits??!1,M=o.showPurchaseButton??!1,z=o.layout??"vertical",D=o.hideMessages??!1,V=i.autoDetectWallets??!0,L=s.jsx("div",{className:d.unstyled?o.className:`cedros-theme__pay ${o.className||""}`,children:s.jsxs("div",{className:d.unstyled?"":`cedros-theme__pay-content cedros-theme__pay-content--${z}`,children:[M?s.jsx(pl,{resource:f?void 0:t||n?.[0]?.resource,items:f?n:void 0,label:o.purchaseLabel,cardLabel:o.cardLabel,cryptoLabel:o.cryptoLabel,showCard:R,showCrypto:u,onPaymentAttempt:a.onPaymentAttempt,onPaymentSuccess:k,onPaymentError:w,onStripeSuccess:k,onCryptoSuccess:_,onStripeError:w,onCryptoError:j,customerEmail:r.customerEmail,successUrl:r.successUrl,cancelUrl:r.cancelUrl,metadata:r.metadata,couponCode:r.couponCode,autoDetectWallets:V,testPageUrl:i.testPageUrl,hideMessages:D,renderModal:o.renderModal}):s.jsxs(s.Fragment,{children:[R&&s.jsx(ma,{resource:f?void 0:t||n?.[0]?.resource,items:f?n:void 0,customerEmail:r.customerEmail,successUrl:r.successUrl,cancelUrl:r.cancelUrl,metadata:r.metadata,couponCode:r.couponCode,label:o.cardLabel,onAttempt:a.onPaymentAttempt,onSuccess:k,onError:w}),u&&s.jsx(b.Suspense,{fallback:null,children:s.jsx(lm,{resource:f?void 0:t||n?.[0]?.resource,items:f?n:void 0,metadata:r.metadata,couponCode:r.couponCode,label:o.cryptoLabel,onAttempt:a.onPaymentAttempt,onSuccess:_,onError:j,testPageUrl:i.testPageUrl,hideMessages:D})}),I&&s.jsx(ha,{resource:f?void 0:t||n?.[0]?.resource,items:f?n:void 0,authToken:r.authToken,metadata:r.metadata,couponCode:r.couponCode,label:o.creditsLabel,onAttempt:N,onSuccess:P,onError:T})]}),f&&n&&n.length>1&&!D&&s.jsxs("div",{style:m,children:["Checking out ",v," items"]})]})});return s.jsx("div",{className:d.unstyled?o.className:d.className,style:d.unstyled?{}:d.style,children:s.jsx(cm,{endpoint:A||"https://api.devnet.solana.com",wallets:h,children:L})})}const J={products:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),s.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),s.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),s.jsx("path",{d:"M3 3v5h5"}),s.jsx("path",{d:"M12 7v5l4 2"})]}),settings:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:s.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:s.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),s.jsx("path",{d:"M21 3v5h-5"}),s.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),s.jsx("path",{d:"M8 16H3v5"})]}),check:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.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:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),s.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"}),s.jsx("path",{d:"M12 3v6"})]}),arrowUp:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"m5 12 7-7 7 7"}),s.jsx("path",{d:"M12 19V5"})]}),arrowDown:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"m5 12 7 7 7-7"}),s.jsx("path",{d:"M12 5v14"})]}),delete:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),s.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:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("path",{d:"M12 17h.01"})]}),chat:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),s.jsx("path",{d:"M2 12h20"})]}),ai:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),s.jsx("path",{d:"M10 10v.5"}),s.jsx("path",{d:"M14 10v.5"}),s.jsx("path",{d:"M12 14v2"}),s.jsx("path",{d:"M8 18h8"}),s.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),s.jsx("path",{d:"M6 12v6"}),s.jsx("path",{d:"M18 12v6"})]}),notifications:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),s.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),s.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"}),s.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"}),s.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),s.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),s.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),s.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),s.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),s.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),s.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),s.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),s.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),s.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.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"}),s.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),s.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),s.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),s.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),s.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),s.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),s.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function Dr({message:e,onRetry:t}){return e?s.jsxs("div",{className:"cedros-admin__error-banner",children:[s.jsx("span",{children:e}),t&&s.jsxs("button",{type:"button",className:"cedros-admin__error-banner-retry",onClick:t,children:[J.refresh," Retry"]})]}):null}function $r({stats:e,isLoading:t=!1,onRefresh:n}){return s.jsxs("div",{className:"cedros-admin__stats-bar",children:[s.jsx("div",{className:"cedros-admin__stats-bar-grid",children:e.map((r,o)=>s.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[s.jsx("span",{className:"cedros-admin__stats-bar-label",children:r.label}),s.jsx("span",{className:`cedros-admin__stats-bar-value ${r.variant?`cedros-admin__stats-bar-value--${r.variant}`:""}`,children:t?s.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):r.value}),r.description&&s.jsx("span",{className:"cedros-admin__stats-bar-desc",children:r.description})]},o))}),n&&s.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:n,disabled:t,title:"Refresh stats",children:t?J.loading:J.refresh})]})}function um({serverUrl:e,productId:t,apiKey:n,authManager:r}){const[o,a]=b.useState(null),[i,c]=b.useState(!1),[l,d]=b.useState(!1),[f,u]=b.useState(null),m=b.useCallback(async()=>{if(t){c(!0),u(null);try{let x;if(r?.isAuthenticated())x=await r.fetchWithAuth(`/admin/products/${t}/variations`);else{const g={"Content-Type":"application/json"};n&&(g["X-API-Key"]=n);const y=await fetch(`${e}/admin/products/${t}/variations`,{headers:g});if(!y.ok)throw new Error(`Failed to fetch variations: ${y.status}`);x=await y.json()}x.variationConfig||(x.variationConfig={variationTypes:[]}),x.variants||(x.variants=[]),a(x)}catch(x){const g=x instanceof Error?x.message:"Failed to fetch variations";u(g),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,n,r]),h=b.useCallback(async x=>{if(!t)return null;d(!0),u(null);try{let g;if(r?.isAuthenticated())g=await r.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(x)});else{const y={"Content-Type":"application/json"};n&&(y["X-API-Key"]=n);const k=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:y,body:JSON.stringify(x)});if(!k.ok)throw new Error(`Failed to save variations: ${k.status}`);g=await k.json()}return a({productId:t,variationConfig:g.variationConfig,variants:g.variants}),{variantsCreated:g.variantsCreated}}catch(g){const y=g instanceof Error?g.message:"Failed to save variations";return u(y),null}finally{d(!1)}},[e,t,n,r]),v=b.useCallback(async x=>{if(!t||x.length===0)return!1;d(!0),u(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/products/${t}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:x})});else{const g={"Content-Type":"application/json"};n&&(g["X-API-Key"]=n);const y=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:g,body:JSON.stringify({updates:x})});if(!y.ok)throw new Error(`Failed to update inventory: ${y.status}`)}if(o){const g=new Map(x.map(y=>[y.variantId,y]));a({...o,variants:o.variants.map(y=>{const k=g.get(y.id);return k?{...y,inventoryQuantity:k.inventoryQuantity,inventoryStatus:k.inventoryStatus??y.inventoryStatus}:y})})}return!0}catch(g){const y=g instanceof Error?g.message:"Failed to update inventory";return u(y),!1}finally{d(!1)}},[e,t,n,r,o]);return{data:o,isLoading:i,error:f,fetch:m,save:h,bulkUpdateInventory:v,isSaving:l}}function Ii(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function fm({value:e,onChange:t,maxTypes:n=5,maxValuesPerType:r=20,disabled:o=!1}){const[a,i]=b.useState(null),[c,l]=b.useState(""),[d,f]=b.useState({}),u=e.variationTypes,m=b.useCallback(()=>{if(!c.trim()||u.length>=n)return;const _={id:Ii(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,_]}),l(""),i(_.id)},[c,u,n,t]),h=b.useCallback(_=>{t({variationTypes:u.filter(w=>w.id!==_).map((w,j)=>({...w,displayOrder:j}))}),a===_&&i(null)},[u,t,a]),v=b.useCallback((_,w)=>{t({variationTypes:u.map(j=>j.id===_?{...j,name:w}:j)})},[u,t]),x=b.useCallback((_,w)=>{const j=u.findIndex(N=>N.id===_);if(j===-1||w==="up"&&j===0||w==="down"&&j===u.length-1)return;const P=[...u],T=w==="up"?j-1:j+1;[P[j],P[T]]=[P[T],P[j]],t({variationTypes:P.map((N,A)=>({...N,displayOrder:A}))})},[u,t]),g=b.useCallback(_=>{const w=(d[_]||"").trim();if(!w)return;const j=u.find(T=>T.id===_);if(!j||j.values.length>=r)return;const P={id:Ii(),label:w};t({variationTypes:u.map(T=>T.id===_?{...T,values:[...T.values,P]}:T)}),f(T=>({...T,[_]:""}))},[u,d,r,t]),y=b.useCallback((_,w)=>{t({variationTypes:u.map(j=>j.id===_?{...j,values:j.values.filter(P=>P.id!==w)}:j)})},[u,t]),k=b.useCallback((_,w,j)=>{t({variationTypes:u.map(P=>P.id===_?{...P,values:P.values.map(T=>T.id===w?{...T,label:j}:T)}:P)})},[u,t]);return s.jsxs("div",{className:"cedros-admin__variation-editor",children:[s.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[s.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),s.jsxs("span",{style:{fontSize:12,opacity:.7},children:[u.length,"/",n," types"]})]}),u.length===0?s.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):s.jsx("div",{className:"cedros-admin__variation-type-list",children:u.map((_,w)=>s.jsxs("div",{className:"cedros-admin__variation-type-item",children:[s.jsxs("div",{className:"cedros-admin__variation-type-header",children:[s.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>x(_.id,"up"),disabled:o||w===0,title:"Move up",children:J.arrowUp}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>x(_.id,"down"),disabled:o||w===u.length-1,title:"Move down",children:J.arrowDown})]}),s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:_.name,onChange:j=>v(_.id,j.target.value),disabled:o,placeholder:"Type name"}),s.jsxs("span",{className:"cedros-admin__variation-value-count",children:[_.values.length," values"]}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===_.id?null:_.id),children:a===_.id?"Collapse":"Edit values"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>h(_.id),disabled:o,title:"Remove type",children:J.delete})]}),a===_.id&&s.jsxs("div",{className:"cedros-admin__variation-values",children:[s.jsxs("div",{className:"cedros-admin__variation-values-header",children:[s.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',_.name,'"']}),s.jsxs("span",{style:{fontSize:11,opacity:.7},children:[_.values.length,"/",r]})]}),_.values.length===0?s.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):s.jsx("div",{className:"cedros-admin__variation-value-list",children:_.values.map(j=>s.jsxs("div",{className:"cedros-admin__variation-value-item",children:[s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:j.label,onChange:P=>k(_.id,j.id,P.target.value),disabled:o}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>y(_.id,j.id),disabled:o,title:"Remove value",children:J.close})]},j.id))}),_.values.length<r&&s.jsxs("div",{className:"cedros-admin__variation-add-value",children:[s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:d[_.id]||"",onChange:j=>f(P=>({...P,[_.id]:j.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),g(_.id))}}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>g(_.id),disabled:o||!d[_.id]?.trim(),children:"Add"})]})]})]},_.id))}),u.length<n&&s.jsxs("div",{className:"cedros-admin__variation-add-type",children:[s.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:_=>l(_.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),m())}}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:m,disabled:o||!c.trim(),children:"Add Type"})]})]})}function ml({value:e,onChange:t,options:n,placeholder:r="Filter",disabled:o}){const[a,i]=b.useState(!1),c=b.useRef(null),d=n.find(f=>f.value===e)?.label||r;return b.useEffect(()=>{const f=u=>{c.current&&!c.current.contains(u.target)&&i(!1)};if(a)return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[a]),b.useEffect(()=>{const f=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[a]),s.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[s.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[s.jsx("span",{children:d}),s.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:J.chevronDown})]}),a&&s.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:n.map(f=>s.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${f.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{f.disabled||(t(f.value),i(!1))},role:"option","aria-selected":f.value===e,disabled:f.disabled,children:[f.label,f.value===e&&s.jsx("span",{className:"cedros-admin__dropdown-check",children:J.check})]},f.value))})]})}function At({value:e,onChange:t,options:n,label:r,description:o,disabled:a,className:i,style:c}){const[l,d]=b.useState(!1),f=b.useRef(null),m=n.find(h=>h.value===e)?.label||"Select...";return b.useEffect(()=>{const h=v=>{f.current&&!f.current.contains(v.target)&&d(!1)};if(l)return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[l]),b.useEffect(()=>{const h=v=>{v.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[l]),s.jsxs("div",{className:`cedros-admin__field ${i||""}`,style:c,children:[s.jsx("label",{className:"cedros-admin__field-label",children:r}),s.jsxs("div",{className:"cedros-admin__dropdown cedros-admin__dropdown--form",ref:f,children:[s.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:[s.jsx("span",{children:m}),s.jsx("span",{className:`cedros-admin__dropdown-chevron ${l?"cedros-admin__dropdown-chevron--open":""}`,children:J.chevronDown})]}),l&&s.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:n.map(h=>s.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&&s.jsx("span",{className:"cedros-admin__dropdown-check",children:J.check})]},h.value))})]}),o&&s.jsx("p",{className:"cedros-admin__field-description",children:o})]})}function Ti(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function pm(e){if(e.length===0)return[];const t=[...e].sort((r,o)=>r.displayOrder-o.displayOrder),n=(r,o)=>{if(r>=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[r],i=[];for(const c of a.values)i.push(...n(r+1,{valueIds:[...o.valueIds,c.id],options:{...o.options,[a.name]:c.label}}));return i};return n(0,{valueIds:[],options:{}})}function mm(e){return e.optionValueIds?.length?[...e.optionValueIds].sort().join("|"):Object.entries(e.options).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${t}:${n}`).join("|")}function hm({variationConfig:e,variants:t,onChange:n,defaultPrice:r=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=b.useMemo(()=>pm(e.variationTypes),[e.variationTypes]),l=b.useMemo(()=>{const x=new Map;for(const g of t)x.set(mm(g),g);return x},[t]),{existingRows:d,possibleRows:f}=b.useMemo(()=>{const x=[],g=[];for(const y of c){const k=l.get(y.key);k?x.push({combo:y,variant:k}):g.push(y)}return{existingRows:x,possibleRows:g}},[c,l]),u=b.useCallback((x,g)=>{n(t.map(y=>y.id===x?{...y,...g}:y))},[t,n]),m=b.useCallback(x=>{n(t.filter(g=>g.id!==x))},[t,n]),h=b.useCallback(x=>{if(t.length>=a)return;const g={id:Ti(),title:x.title,options:x.options,optionValueIds:x.optionValueIds,price:r,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};n([...t,g])},[t,n,a,r]),v=b.useCallback(()=>{const x=a-t.length,y=f.slice(0,x).map(k=>({id:Ti(),title:k.title,options:k.options,optionValueIds:k.optionValueIds,price:r,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));n([...t,...y])},[t,n,f,a,r]);return e.variationTypes.length===0?s.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):c.length===0?s.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):s.jsxs("div",{className:"cedros-admin__variant-grid",children:[s.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[s.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),s.jsxs("span",{style:{fontSize:12,opacity:.7},children:[t.length,"/",a," variants (",c.length," ","possible)"]})]}),f.length>0&&t.length<a&&s.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[s.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:v,disabled:i,children:["Generate All (",Math.min(f.length,a-t.length),")"]}),s.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Variant"}),s.jsx("th",{style:{width:100},children:"Price"}),s.jsx("th",{style:{width:80},children:"Qty"}),s.jsx("th",{style:{width:100},children:"SKU"}),s.jsx("th",{style:{width:100},children:"Status"}),s.jsx("th",{style:{width:80},children:"Actions"})]})}),s.jsxs("tbody",{children:[d.map(({combo:x,variant:g})=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{fontWeight:600},children:x.title}),s.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(x.options).map(([y,k])=>`${y}: ${k}`).join(", ")})]})}),s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[s.jsx("span",{children:o}),s.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:g.price??"",onChange:y=>u(g.id,{price:y.target.value===""?void 0:parseFloat(y.target.value)||0}),disabled:i,min:"0",step:"0.01",style:{width:70}})]})}),s.jsx("td",{children:s.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:g.inventoryQuantity??"",onChange:y=>u(g.id,{inventoryQuantity:y.target.value===""?void 0:parseInt(y.target.value)||0}),disabled:i,min:"0",style:{width:60}})}),s.jsx("td",{children:s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:g.sku??"",onChange:y=>u(g.id,{sku:y.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),s.jsx("td",{children:s.jsx(ml,{value:g.inventoryStatus??"in_stock",onChange:y=>u(g.id,{inventoryStatus:y}),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})}),s.jsx("td",{children:s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>m(g.id),disabled:i,title:"Remove variant",children:J.trash})})]},g.id)),f.length>0&&t.length<a&&s.jsxs(s.Fragment,{children:[s.jsx("tr",{className:"cedros-admin__variant-separator",children:s.jsx("td",{colSpan:6,children:s.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",f.length,")"]})})}),f.slice(0,10).map(x=>s.jsxs("tr",{className:"cedros-admin__variant-possible",children:[s.jsx("td",{children:s.jsx("span",{style:{opacity:.6},children:x.title})}),s.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),s.jsx("td",{children:s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>h(x),disabled:i,title:"Create variant",children:J.plus})})]},x.key)),f.length>10&&s.jsx("tr",{className:"cedros-admin__variant-more",children:s.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",f.length-10," more combinations"]})})]})]})]})})]})}function gm({serverUrl:e,productId:t,productTitle:n,defaultPrice:r=0,currencySymbol:o="$",apiKey:a,authManager:i,onClose:c}){const{data:l,isLoading:d,error:f,fetch:u,save:m,isSaving:h}=um({serverUrl:e,productId:t,apiKey:a,authManager:i}),[v,x]=b.useState({variationTypes:[]}),[g,y]=b.useState([]),[k,_]=b.useState(!1),[w,j]=b.useState(!1);b.useEffect(()=>{u()},[u]),b.useEffect(()=>{l&&(x(l.variationConfig),y(l.variants),_(!1))},[l]);const P=b.useCallback(A=>{x(A),_(!0),j(!1)},[]),T=b.useCallback(A=>{y(A),_(!0),j(!1)},[]),N=b.useCallback(async()=>{const A=new Set((l?.variants??[]).map(D=>D.id)),R=g.filter(D=>!A.has(D.id)),I=g.filter(D=>A.has(D.id)),M=(l?.variants??[]).filter(D=>!g.some(V=>V.id===D.id)).map(D=>D.id);await m({variationConfig:v,createVariants:R.map(D=>({optionValueIds:D.optionValueIds??[],inventoryQuantity:D.inventoryQuantity,sku:D.sku,price:D.price})),updateVariants:I.map(D=>({id:D.id,inventoryQuantity:D.inventoryQuantity,sku:D.sku,price:D.price,inventoryStatus:D.inventoryStatus})),deleteVariantIds:M.length>0?M:void 0})&&(_(!1),j(!0),setTimeout(()=>j(!1),3e3))},[v,g,l?.variants,m]);return d?s.jsxs("div",{className:"cedros-admin__variations-editor",children:[s.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:n?`Variations: ${n}`:"Product Variations"}),c&&s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:J.close})]}),s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading variations..."]})]}):s.jsxs("div",{className:"cedros-admin__variations-editor",children:[s.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:n?`Variations: ${n}`:"Product Variations"}),s.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[w&&s.jsxs("span",{className:"cedros-admin__success-text",children:[J.check," Saved"]}),k&&s.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:N,disabled:h||!k,children:h?"Saving...":"Save Changes"}),c&&s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:J.close})]})]}),f&&s.jsx("div",{className:"cedros-admin__error-banner",children:f}),s.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[s.jsx("div",{className:"cedros-admin__variations-editor-section",children:s.jsx(fm,{value:v,onChange:P,disabled:h})}),v.variationTypes.length>0&&s.jsx("div",{className:"cedros-admin__variations-editor-section",children:s.jsx(hm,{variationConfig:v,variants:g,onChange:T,defaultPrice:r,currencySymbol:o,disabled:h})})]})]})}function hl({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=b.useState([]),[i,c]=b.useState(!0),[l,d]=b.useState(!1),[f,u]=b.useState(!1),[m,h]=b.useState(null),[v,x]=b.useState(null),[g,y]=b.useState(null),[k,_]=b.useState(null),[w,j]=b.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:""}),P=S=>{const C=S.tagsCsv.split(",").map(Y=>Y.trim()).filter(Boolean),W=S.categoryIdsCsv.split(",").map(Y=>Y.trim()).filter(Boolean),Z={email:S.checkoutEmail,name:S.checkoutName,phone:S.checkoutPhone,shippingAddress:S.checkoutShippingAddress,billingAddress:S.checkoutBillingAddress},Q=S.fulfillmentType==="shipping"?"physical":"digital",de={title:S.title,slug:S.slug||S.id,shipping_profile:Q,inventory_status:S.inventoryStatus,checkout_requirements:JSON.stringify(Z),fulfillment_type:S.fulfillmentType};S.imageUrl&&(de.image_url=S.imageUrl);const q=S.compareAtUsd?Math.round(Number(S.compareAtUsd)*100):0;q&&(de.compare_at_amount_cents=String(q)),C.length&&(de.tags=JSON.stringify(C)),W.length&&(de.category_ids=JSON.stringify(W)),S.fulfillmentNotes&&(de.fulfillment_notes=S.fulfillmentNotes);const K=S.shippingCountriesCsv.split(",").map(Y=>Y.trim().toUpperCase()).filter(Boolean);return K.length&&(de.shippingCountries=K.join(","),de.shipping_countries=K.join(",")),de},T=S=>S.metadata?.title||S.description||S.id,N=S=>S.metadata?.image_url,A=b.useCallback(async()=>{try{_(null);let S;if(r?.isAuthenticated())S=await r.fetchWithAuth(`/admin/products?limit=${n}`);else{const C={"Content-Type":"application/json"};t&&(C["X-API-Key"]=t);const W=await fetch(`${e}/admin/products?limit=${n}`,{headers:C});if(!W.ok)throw new Error(`Failed to fetch products: ${W.status}`);S=await W.json()}a(S.products||[])}catch{a([]),_("Failed to load products")}finally{c(!1)}},[e,t,n,r]);b.useEffect(()=>{A()},[A]);const R=async S=>{if(S.preventDefault(),!(!w.id||!w.description)){if(h(null),w.fulfillmentType==="shipping"&&w.checkoutShippingAddress&&!w.shippingCountriesCsv.split(",").map(W=>W.trim()).filter(Boolean).length){h("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:C}=w,W=w.inventoryQuantity===""?void 0:Number.isFinite(Number(w.inventoryQuantity))?Number(w.inventoryQuantity):void 0,Z=Number(w.priceUsd)||0,Q=Math.round(Z*100),de=Math.round(Z*1e6),q={id:w.id,description:w.description,fiatAmountCents:Q,fiatCurrency:w.fiatCurrency,cryptoAtomicAmount:de,cryptoToken:w.cryptoToken,...W!==void 0?{inventoryQuantity:W}:{},metadata:{...C?{product_type:C}:{},...P(w)}};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(q)});else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const Y=await fetch(`${e}/admin/products`,{method:"POST",headers:K,body:JSON.stringify(q)});if(!Y.ok)throw new Error(`Failed to create product: ${Y.status}`)}j({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),A()}catch(C){h(C instanceof Error?C.message:"Failed to create product")}finally{u(!1)}}},I=S=>`$${(S/100).toFixed(2)}`,M=S=>{switch(S){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},z=b.useMemo(()=>{const S=o.filter(W=>W.active).length,C=o.reduce((W,Z)=>{const Q=Z.variations?.length??0;return W+(Q>0?Q:1)},0);return{activeCount:S,totalSkus:C}},[o]),D=S=>{y(C=>!C||C.key!==S?{key:S,direction:"asc"}:{key:S,direction:C.direction==="asc"?"desc":"asc"})},V=S=>!g||g.key!==S?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:J.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:g.direction==="asc"?J.chevronUp:J.chevronDown}),L=b.useMemo(()=>{if(!g)return o;const S=g.direction==="asc"?1:-1,C=W=>{switch(g.key){case"product":return T(W);case"type":return M(W.metadata?.product_type);case"price":return W.fiatAmountCents??0;case"status":return W.active?1:0;case"id":default:return W.id}};return[...o].sort((W,Z)=>{const Q=C(W),de=C(Z);return typeof Q=="number"&&typeof de=="number"?(Q-de)*S:String(Q).localeCompare(String(de),void 0,{sensitivity:"base"})*S})},[o,g]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(Dr,{message:k,onRetry:A}),s.jsx($r,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:z.activeCount,variant:z.activeCount>0?"success":"muted"},{label:"Total SKUs",value:z.totalSkus}],isLoading:i}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),s.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{h(null),d(!l)},children:[l?J.close:J.plus,l?"Cancel":"Add Product"]})]}),l&&s.jsxs("form",{onSubmit:R,className:"cedros-admin__add-form",children:[m&&s.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:m}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.id,onChange:S=>j(C=>({...C,id:S.target.value})),placeholder:"e.g., premium-article",required:!0})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.title,onChange:S=>j(C=>({...C,title:S.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.slug,onChange:S=>j(C=>({...C,slug:S.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),s.jsx("input",{type:"url",className:"cedros-admin__input",value:w.imageUrl,onChange:S=>j(C=>({...C,imageUrl:S.target.value})),placeholder:"https://..."})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.description,onChange:S=>j(C=>({...C,description:S.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:w.productType,onChange:S=>j(C=>({...C,productType:S})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"}],label:"Product Type"}),s.jsx(At,{value:w.fulfillmentType,onChange:S=>{const C=S;j(W=>({...W,fulfillmentType:C,checkoutShippingAddress:C==="shipping"?W.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),w.fulfillmentType==="shipping"&&s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:w.inventoryStatus,onChange:S=>j(C=>({...C,inventoryStatus:S})),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"}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:w.inventoryQuantity,onChange:S=>j(C=>({...C,inventoryQuantity:S.target.value===""?"":parseInt(S.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:w.compareAtUsd===""?"":w.compareAtUsd,onChange:S=>j(C=>({...C,compareAtUsd:S.target.value===""?"":parseFloat(S.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:w.priceUsd===""?"":w.priceUsd,onChange:S=>j(C=>({...C,priceUsd:S.target.value===""?"":parseFloat(S.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.tagsCsv,onChange:S=>j(C=>({...C,tagsCsv:S.target.value})),placeholder:"e.g., core, new, gift"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.categoryIdsCsv,onChange:S=>j(C=>({...C,categoryIdsCsv:S.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:w.checkoutEmail,onChange:S=>j(C=>({...C,checkoutEmail:S})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),s.jsx(At,{value:w.checkoutName,onChange:S=>j(C=>({...C,checkoutName:S})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),s.jsx(At,{value:w.checkoutPhone,onChange:S=>j(C=>({...C,checkoutPhone:S})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[w.fulfillmentType==="shipping"&&s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:w.checkoutShippingAddress,onChange:S=>j(C=>({...C,checkoutShippingAddress:S.target.checked}))}),"Collect shipping address"]})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:w.checkoutBillingAddress,onChange:S=>j(C=>({...C,checkoutBillingAddress:S.target.checked}))}),"Collect billing address"]})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.fulfillmentNotes,onChange:S=>j(C=>({...C,fulfillmentNotes:S.target.value})),placeholder:w.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),w.fulfillmentType==="shipping"&&w.checkoutShippingAddress&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.shippingCountriesCsv,onChange:S=>j(C=>({...C,shippingCountriesCsv:S.target.value})),placeholder:"e.g., US,CA"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),s.jsx("div",{className:"cedros-admin__form-actions",children:s.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:f,children:f?"Creating...":"Create Product"})})]}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading products..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":g?.key==="id"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("id"),children:["ID",V("id")]})}),s.jsx("th",{"aria-sort":g?.key==="product"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("product"),children:["Product",V("product")]})}),s.jsx("th",{"aria-sort":g?.key==="type"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("type"),children:["Type",V("type")]})}),s.jsx("th",{"aria-sort":g?.key==="price"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("price"),children:["Price",V("price")]})}),s.jsx("th",{"aria-sort":g?.key==="status"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("status"),children:["Status",V("status")]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:L.map(S=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:S.id})}),s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[N(S)?s.jsx("img",{src:N(S),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):s.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),s.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{fontWeight:600},children:T(S)}),s.jsx("span",{style:{opacity:.8},children:S.description})]})]})}),s.jsx("td",{children:M(S.metadata?.product_type)}),s.jsx("td",{children:I(S.fiatAmountCents)}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge ${S.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:S.active?"Active":"Inactive"})}),s.jsx("td",{children:s.jsx("div",{style:{display:"flex",gap:"0.25rem"},children:s.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>x(S),children:"Variations"})})})]},S.id))})]})}),v&&s.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>x(null),children:s.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:S=>S.stopPropagation(),children:s.jsx(gm,{serverUrl:e,productId:v.id,productTitle:T(v),defaultPrice:v.fiatAmountCents/100,apiKey:t,authManager:r,onClose:()=>x(null)})})})]})}function gl({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=b.useState([]),[i,c]=b.useState(null),[l,d]=b.useState(!0),[f,u]=b.useState(!0),[m,h]=b.useState(null),[v,x]=b.useState(""),[g,y]=b.useState(null),k=b.useCallback(async()=>{u(!0);try{h(null);let N;if(r?.isAuthenticated())N=await r.fetchWithAuth("/admin/stats");else{const A={"Content-Type":"application/json"};t&&(A["X-API-Key"]=t);const R=await fetch(`${e}/admin/stats`,{headers:A});if(!R.ok)throw new Error(`Failed to fetch stats: ${R.status}`);N=await R.json()}c(N)}catch{c(null),h("Failed to load payment stats")}finally{u(!1)}},[e,t,r]);b.useEffect(()=>{k()},[k]);const _=b.useCallback(async()=>{try{h(null);let N;const A=new URLSearchParams({limit:n.toString()});v&&A.set("method",v);const R=`/admin/transactions?${A}`;if(r?.isAuthenticated())N=await r.fetchWithAuth(R);else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const M=await fetch(`${e}${R}`,{headers:I});if(!M.ok)throw new Error(`Failed to fetch transactions: ${M.status}`);N=await M.json()}a(N.transactions||[])}catch{a([]),h("Failed to load transactions")}finally{d(!1)}},[e,t,n,v,r]);b.useEffect(()=>{_()},[_]);const w=(N,A="USD")=>new Intl.NumberFormat("en-US",{style:"currency",currency:A}).format(N),j=N=>{y(A=>!A||A.key!==N?{key:N,direction:"asc"}:{key:N,direction:A.direction==="asc"?"desc":"asc"})},P=N=>!g||g.key!==N?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:J.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:g.direction==="asc"?J.chevronUp:J.chevronDown}),T=b.useMemo(()=>{if(!g)return o;const N=g.direction==="asc"?1:-1,A=R=>{switch(g.key){case"resource":return R.resourceId;case"method":return R.method;case"amount":return R.amount;case"status":return R.status;case"date":return new Date(R.paidAt).getTime();case"id":default:return R.id}};return[...o].sort((R,I)=>{const M=A(R),z=A(I);return typeof M=="number"&&typeof z=="number"?(M-z)*N:String(M).localeCompare(String(z),void 0,{sensitivity:"base"})*N})},[o,g]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(Dr,{message:m,onRetry:()=>{k(),_()}}),s.jsx($r,{stats:[{label:"Revenue",value:w(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:w(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:w(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:w(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:f,onRefresh:k}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),s.jsx(ml,{value:v,onChange:x,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading transactions..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":g?.key==="id"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("id"),children:["ID",P("id")]})}),s.jsx("th",{"aria-sort":g?.key==="resource"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("resource"),children:["Resource",P("resource")]})}),s.jsx("th",{"aria-sort":g?.key==="method"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("method"),children:["Method",P("method")]})}),s.jsx("th",{"aria-sort":g?.key==="amount"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("amount"),children:["Amount",P("amount")]})}),s.jsx("th",{"aria-sort":g?.key==="status"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("status"),children:["Status",P("status")]})}),s.jsx("th",{"aria-sort":g?.key==="date"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("date"),children:["Date",P("date")]})})]})}),s.jsx("tbody",{children:T.map(N=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:N.id})}),s.jsx("td",{children:N.resourceId}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${N.method}`,children:N.method})}),s.jsxs("td",{children:["$",N.amount.toFixed(2)," ",N.currency.toUpperCase()]}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${N.status}`,children:N.status})}),s.jsx("td",{children:br(N.paidAt)})]},N.id))})]})})]})}function xl({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=b.useState([]),[i,c]=b.useState(!0),[l,d]=b.useState(!1),[f,u]=b.useState(!1),[m,h]=b.useState(null),[v,x]=b.useState(null),[g,y]=b.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}),k=b.useCallback(async()=>{try{x(null);let A;const R=`/admin/coupons?limit=${n}`;if(r?.isAuthenticated())A=await r.fetchWithAuth(R);else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const M=await fetch(`${e}${R}`,{headers:I});if(!M.ok)throw new Error(`Failed to fetch coupons: ${M.status}`);A=await M.json()}a(A.coupons||[])}catch(A){oe.getLogger().error("[CouponsSection] Failed to fetch coupons:",A,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),x("Failed to load coupons")}finally{c(!1)}},[e,t,n,r]);b.useEffect(()=>{k()},[k]);const _=async A=>{if(A.preventDefault(),!(!g.code||g.discountValue<=0)){u(!0);try{const R=g.minimumAmountUsd?Math.round(Number(g.minimumAmountUsd)*100):void 0,I=g.productIdsCsv.split(",").map(D=>D.trim()).filter(Boolean),M=g.categoryIdsCsv.split(",").map(D=>D.trim()).filter(Boolean),z={code:g.code,discountType:g.discountType,discountValue:g.discountValue,usageLimit:g.usageLimit,active:!0,usageCount:0,scope:g.scope,...I.length?{productIds:I}:{},...M.length?{categoryIds:M}:{},...g.paymentMethod!=="any"?{paymentMethod:g.paymentMethod}:{},...g.autoApply?{autoApply:!0}:{},...g.appliesAt!=="both"?{appliesAt:g.appliesAt}:{},...g.startsAt?{startsAt:g.startsAt}:{},...g.expiresAt?{expiresAt:g.expiresAt}:{},...R?{minimumAmountCents:R}:{},...g.usageLimitPerCustomer?{usageLimitPerCustomer:g.usageLimitPerCustomer}:{},...g.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(z)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const V=await fetch(`${e}/admin/coupons`,{method:"POST",headers:D,body:JSON.stringify(z)});if(!V.ok)throw new Error(`Failed to create coupon: ${V.status}`)}y({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),k()}catch(R){oe.getLogger().error("[CouponsSection] Failed to add coupon:",R,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),x("Failed to create coupon")}finally{u(!1)}}},w=o.filter(A=>A.active).length,j=o.reduce((A,R)=>A+(R.usageCount??0),0),P=A=>{h(R=>!R||R.key!==A?{key:A,direction:"asc"}:{key:A,direction:R.direction==="asc"?"desc":"asc"})},T=A=>!m||m.key!==A?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:J.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:m.direction==="asc"?J.chevronUp:J.chevronDown}),N=b.useMemo(()=>{if(!m)return o;const A=m.direction==="asc"?1:-1,R=I=>{switch(m.key){case"discount":return I.discountValue??0;case"usage":return I.usageCount??0;case"status":return I.active?1:0;case"code":default:return I.code}};return[...o].sort((I,M)=>{const z=R(I),D=R(M);return typeof z=="number"&&typeof D=="number"?(z-D)*A:String(z).localeCompare(String(D),void 0,{sensitivity:"base"})*A})},[o,m]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(Dr,{message:v,onRetry:k}),s.jsx($r,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:w,variant:w>0?"success":"muted"},{label:"Redemptions",value:j}],isLoading:i}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),s.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?J.close:J.plus,l?"Cancel":"Add Coupon"]})]}),l&&s.jsxs("form",{onSubmit:_,className:"cedros-admin__add-form",children:[s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:g.code,onChange:A=>y(R=>({...R,code:A.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),s.jsx(At,{value:g.discountType,onChange:A=>y(R=>({...R,discountType:A})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",g.discountType==="percentage"?"(%)":"($)"]}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:g.discountValue||"",onChange:A=>y(R=>({...R,discountValue:parseFloat(A.target.value)||0})),placeholder:g.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:g.discountType==="percentage"?"1":"0.01",required:!0})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:g.usageLimit||"",onChange:A=>y(R=>({...R,usageLimit:A.target.value?parseInt(A.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),s.jsx("input",{type:"date",className:"cedros-admin__input",value:g.expiresAt,onChange:A=>y(R=>({...R,expiresAt:A.target.value}))})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:g.scope,onChange:A=>y(R=>({...R,scope:A})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),s.jsx(At,{value:g.paymentMethod,onChange:A=>y(R=>({...R,paymentMethod:A})),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"}),s.jsx(At,{value:g.appliesAt,onChange:A=>y(R=>({...R,appliesAt:A})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),g.scope==="specific_products"&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:g.productIdsCsv,onChange:A=>y(R=>({...R,productIdsCsv:A.target.value})),placeholder:"e.g., prod_123, prod_456"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),s.jsx("input",{type:"date",className:"cedros-admin__input",value:g.startsAt,onChange:A=>y(R=>({...R,startsAt:A.target.value}))})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:g.autoApply,onChange:A=>y(R=>({...R,autoApply:A.target.checked}))}),"Automatically apply when conditions met"]})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:g.minimumAmountUsd===""?"":g.minimumAmountUsd,onChange:A=>y(R=>({...R,minimumAmountUsd:A.target.value===""?"":parseFloat(A.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:g.usageLimitPerCustomer||"",onChange:A=>y(R=>({...R,usageLimitPerCustomer:A.target.value?parseInt(A.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:g.firstPurchaseOnly,onChange:A=>y(R=>({...R,firstPurchaseOnly:A.target.checked}))}),"New customers only"]})]})]}),g.scope==="specific_categories"&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:g.categoryIdsCsv,onChange:A=>y(R=>({...R,categoryIdsCsv:A.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),s.jsx("div",{className:"cedros-admin__form-actions",children:s.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:f,children:f?"Creating...":"Create Coupon"})})]}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading coupons..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":m?.key==="code"?m?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("code"),children:["Code",T("code")]})}),s.jsx("th",{"aria-sort":m?.key==="discount"?m?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("discount"),children:["Discount",T("discount")]})}),s.jsx("th",{"aria-sort":m?.key==="usage"?m?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("usage"),children:["Usage",T("usage")]})}),s.jsx("th",{"aria-sort":m?.key==="status"?m?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("status"),children:["Status",T("status")]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:N.map(A=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:A.code})}),s.jsx("td",{children:A.discountType==="percentage"?`${A.discountValue}%`:`$${A.discountValue.toFixed(2)}`}),s.jsxs("td",{children:[A.usageCount,A.usageLimit?` / ${A.usageLimit}`:""]}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge ${A.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:A.active?"Active":"Inactive"})}),s.jsx("td",{children:s.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},A.code))})]})})]})}function vl({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=b.useState([]),[i,c]=b.useState(!0),[l,d]=b.useState(null),[f,u]=b.useState([]),[m,h]=b.useState(!0),[v,x]=b.useState(null),[g,y]=b.useState(null),[k,_]=b.useState([]),[w,j]=b.useState(!0),[P,T]=b.useState(null),[N,A]=b.useState(null),[R,I]=b.useState(null),[M,z]=b.useState(""),[D,V]=b.useState(null),L=b.useCallback(async()=>{try{let O;const X=`/admin/refunds?limit=${n}`;if(r?.isAuthenticated())O=await r.fetchWithAuth(X);else{const ae={"Content-Type":"application/json"};t&&(ae["X-API-Key"]=t);const be=await fetch(`${e}${X}`,{headers:ae});if(!be.ok)throw new Error(`Failed to fetch x402 refunds: ${be.status}`);O=await be.json()}a(O.refunds||[])}catch(O){oe.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),V("Failed to load x402 refunds")}finally{c(!1)}},[e,t,n,r]);b.useEffect(()=>{L()},[L]);const S=b.useCallback(async()=>{try{let O;const X=`/admin/credits/refund-requests?status=pending&limit=${n}&offset=0`;if(r?.isAuthenticated())O=await r.fetchWithAuth(X);else{const be={"Content-Type":"application/json"};t&&(be["X-API-Key"]=t);const we=await fetch(`${e}${X}`,{headers:be});if(!we.ok)throw new Error(`Failed to fetch credits refund requests: ${we.status}`);O=await we.json()}const ae=Array.isArray(O)?O:"refundRequests"in O?O.refundRequests:O.requests||[];u(ae)}catch(O){oe.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([]),V("Failed to load credits refunds")}finally{h(!1)}},[e,t,n,r]);b.useEffect(()=>{S()},[S]);const C=async O=>{x(O.id);try{const X=`/admin/credits/refund-requests/${O.id}/process`,ae=JSON.stringify({amountLamports:O.amountLamports,reason:O.reason});if(r?.isAuthenticated())await r.fetchWithAuth(X,{method:"POST",body:ae});else{const be={"Content-Type":"application/json"};t&&(be["X-API-Key"]=t);const we=await fetch(`${e}${X}`,{method:"POST",headers:be,body:ae});if(!we.ok)throw new Error(`Failed to process credits refund: ${we.status}`)}await S()}catch(X){oe.getLogger().error("[RefundsSection] Failed to process credits refund:",X,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:O.id}),V("Failed to process credits refund")}finally{x(null)}},W=O=>{z(O.reason??""),I(O)},Z=()=>{I(null),z("")},Q=async()=>{if(!R)return;const O=R,X=M;Z(),x(O.id);try{const ae=`/admin/credits/refund-requests/${O.id}/reject`,be=JSON.stringify({reason:X});if(r?.isAuthenticated())await r.fetchWithAuth(ae,{method:"POST",body:be});else{const we={"Content-Type":"application/json"};t&&(we["X-API-Key"]=t);const Re=await fetch(`${e}${ae}`,{method:"POST",headers:we,body:be});if(!Re.ok)throw new Error(`Failed to reject credits refund: ${Re.status}`)}await S()}catch(ae){oe.getLogger().error("[RefundsSection] Failed to reject credits refund:",ae,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:O.id}),V("Failed to reject credits refund")}finally{x(null)}},de=b.useCallback(async()=>{try{let O;const X=`/admin/stripe/refunds?limit=${n}`;if(r?.isAuthenticated())O=await r.fetchWithAuth(X);else{const ae={"Content-Type":"application/json"};t&&(ae["X-API-Key"]=t);const be=await fetch(`${e}${X}`,{headers:ae});if(!be.ok)throw new Error(`Failed to fetch Stripe refunds: ${be.status}`);O=await be.json()}_(O.refunds||[])}catch(O){oe.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),_([]),V("Failed to load Stripe refunds")}finally{j(!1)}},[e,t,n,r]);b.useEffect(()=>{de()},[de]);const q=async O=>{T(O);try{const X=`/admin/stripe/refunds/${O}/process`;if(r?.isAuthenticated())await r.fetchWithAuth(X,{method:"POST"});else{const ae={"Content-Type":"application/json"};t&&(ae["X-API-Key"]=t);const be=await fetch(`${e}${X}`,{method:"POST",headers:ae});if(!be.ok)throw new Error(`Failed to process refund: ${be.status}`)}await de()}catch(X){oe.getLogger().error("[RefundsSection] Failed to process Stripe refund:",X,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:O}),V("Failed to process Stripe refund")}finally{T(null)}},K=(O,X)=>new Intl.NumberFormat("en-US",{style:"currency",currency:X}).format(O/100),Y=O=>O?O.replace(/_/g," ").replace(/\b\w/g,X=>X.toUpperCase()):"—",me=O=>{switch(O){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},$=(O,X)=>X?X.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(O/1e6)} (USD credits)`:`${O.toLocaleString()} ${X.toUpperCase()} (atomic)`:`${O.toLocaleString()} (atomic)`,G=O=>{switch(O){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},pe=O=>O.stripeRefundId??"—",U=O=>O.chargeId??"—",se=k.filter(O=>O.status==="pending"||O.status==="requires_action").length,le=f.filter(O=>O.status==="pending").length,ue=o.filter(O=>O.status==="pending").length,Te=se+le+ue,We=k.filter(O=>O.status==="succeeded").reduce((O,X)=>O+X.amount,0),Ye=f.filter(O=>O.status==="processed").reduce((O,X)=>O+X.amountLamports,0),qe=o.filter(O=>O.status==="completed").reduce((O,X)=>O+X.amount,0),_t=We/100+Ye/1e6+qe,Qe=O=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(O),tn=w||m||i,xt=O=>{A(X=>!X||X.key!==O?{key:O,direction:"asc"}:{key:O,direction:X.direction==="asc"?"desc":"asc"})},Se=O=>{y(X=>!X||X.key!==O?{key:O,direction:"asc"}:{key:O,direction:X.direction==="asc"?"desc":"asc"})},Xe=O=>{d(X=>!X||X.key!==O?{key:O,direction:"asc"}:{key:O,direction:X.direction==="asc"?"desc":"asc"})},ke=(O,X)=>!O||!X?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:J.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:X==="asc"?J.chevronUp:J.chevronDown}),Gt=b.useMemo(()=>{if(!N)return k;const O=N.direction==="asc"?1:-1,X=ae=>{switch(N.key){case"stripe":return ae.stripeRefundId??"";case"charge":return ae.chargeId??"";case"amount":return ae.amount??0;case"reason":return ae.reason??"";case"status":return ae.status??"";case"date":return new Date(ae.createdAt).getTime();case"id":default:return ae.id}};return[...k].sort((ae,be)=>{const we=X(ae),Re=X(be);return typeof we=="number"&&typeof Re=="number"?(we-Re)*O:String(we).localeCompare(String(Re),void 0,{sensitivity:"base"})*O})},[k,N]),ft=b.useMemo(()=>{if(!g)return f;const O=g.direction==="asc"?1:-1,X=ae=>{switch(g.key){case"original":return ae.originalTransactionId??"";case"user":return ae.userId??"";case"amount":return ae.amountLamports??0;case"reason":return ae.reason??"";case"status":return ae.status??"";case"date":return new Date(ae.createdAt).getTime();case"id":default:return ae.id}};return[...f].sort((ae,be)=>{const we=X(ae),Re=X(be);return typeof we=="number"&&typeof Re=="number"?(we-Re)*O:String(we).localeCompare(String(Re),void 0,{sensitivity:"base"})*O})},[f,g]),it=b.useMemo(()=>{if(!l)return o;const O=l.direction==="asc"?1:-1,X=ae=>{switch(l.key){case"transaction":return ae.transactionId??"";case"amount":return ae.amount??0;case"reason":return ae.reason??"";case"status":return ae.status??"";case"date":return new Date(ae.createdAt).getTime();case"id":default:return ae.id}};return[...o].sort((ae,be)=>{const we=X(ae),Re=X(be);return typeof we=="number"&&typeof Re=="number"?(we-Re)*O:String(we).localeCompare(String(Re),void 0,{sensitivity:"base"})*O})},[o,l]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(Dr,{message:D,onRetry:()=>{L(),S(),de()}}),s.jsx($r,{stats:[{label:"Pending",value:Te,variant:Te>0?"warning":"muted"},{label:"Card Pending",value:se,description:"Stripe"},{label:"Credits Pending",value:le},{label:"Crypto Pending",value:ue,description:"x402"},{label:"Total Refunded",value:Qe(_t),variant:"success"}],isLoading:tn}),s.jsx("div",{className:"cedros-admin__section-header",children:s.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),w?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading Stripe refunds..."]}):k.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":N?.key==="id"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("id"),children:["Request ID",ke(N?.key==="id",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="stripe"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("stripe"),children:["Stripe Refund ID",ke(N?.key==="stripe",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="charge"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("charge"),children:["Charge",ke(N?.key==="charge",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="amount"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("amount"),children:["Amount",ke(N?.key==="amount",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="reason"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("reason"),children:["Reason",ke(N?.key==="reason",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="status"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("status"),children:["Status",ke(N?.key==="status",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="date"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("date"),children:["Date",ke(N?.key==="date",N?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:Gt.map(O=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:O.id})}),s.jsx("td",{children:s.jsx("code",{children:pe(O)})}),s.jsx("td",{children:s.jsx("code",{children:U(O)})}),s.jsx("td",{children:K(O.amount,O.currency)}),s.jsx("td",{children:Y(O.reason)}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${G(O.status)}`,children:O.status})}),s.jsx("td",{children:br(O.createdAt)}),s.jsx("td",{children:(O.status==="pending"||O.status==="requires_action")&&s.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>q(O.id),disabled:P===O.id,children:P===O.id?"Processing...":"Process"})})]},O.id))})]})}),s.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:s.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),m?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading credits refunds..."]}):f.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":g?.key==="id"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("id"),children:["Request ID",ke(g?.key==="id",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="original"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("original"),children:["Original Tx",ke(g?.key==="original",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="user"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("user"),children:["User",ke(g?.key==="user",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="amount"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("amount"),children:["Amount",ke(g?.key==="amount",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="reason"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("reason"),children:["Reason",ke(g?.key==="reason",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="status"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("status"),children:["Status",ke(g?.key==="status",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="date"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("date"),children:["Date",ke(g?.key==="date",g?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:ft.map(O=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:O.id})}),s.jsx("td",{children:s.jsx("code",{children:O.originalTransactionId})}),s.jsx("td",{children:s.jsx("code",{children:O.userId??"—"})}),s.jsx("td",{children:$(O.amountLamports,O.currency)}),s.jsx("td",{children:O.reason??"—"}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${me(O.status)}`,children:O.status})}),s.jsx("td",{children:br(O.createdAt)}),s.jsx("td",{children:O.status==="pending"?s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>C(O),disabled:v===O.id,children:v===O.id?"Processing...":"Process"}),s.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>W(O),disabled:v===O.id,children:"Reject"})]}):null})]},O.id))})]})}),s.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:s.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading x402 refunds..."]}):o.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("id"),children:["ID",ke(l?.key==="id",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="transaction"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("transaction"),children:["Transaction",ke(l?.key==="transaction",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="amount"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("amount"),children:["Amount",ke(l?.key==="amount",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="reason"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("reason"),children:["Reason",ke(l?.key==="reason",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="status"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("status"),children:["Status",ke(l?.key==="status",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="date"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("date"),children:["Date",ke(l?.key==="date",l?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:it.map(O=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:O.id})}),s.jsx("td",{children:s.jsx("code",{children:O.transactionId})}),s.jsxs("td",{children:["$",O.amount.toFixed(2)]}),s.jsx("td",{children:O.reason||"—"}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${O.status}`,children:O.status})}),s.jsx("td",{children:br(O.createdAt)}),s.jsx("td",{})]},O.id))})]})}),R&&s.jsx("div",{className:"cedros-admin__modal-overlay",onClick:Z,children:s.jsxs("div",{className:"cedros-admin__modal",onClick:O=>O.stopPropagation(),children:[s.jsxs("div",{className:"cedros-admin__modal-header",children:[s.jsx("h3",{className:"cedros-admin__modal-title",children:"Reject Refund Request"}),s.jsx("button",{type:"button",className:"cedros-admin__modal-close",onClick:Z,"aria-label":"Close",children:J.close})]}),s.jsxs("div",{className:"cedros-admin__modal-body",children:[s.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",s.jsx("code",{children:R.id})," for ",$(R.amountLamports,R.currency),"."]}),s.jsxs("label",{className:"cedros-admin__form-field",children:[s.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),s.jsx("textarea",{className:"cedros-admin__input",value:M,onChange:O=>z(O.target.value),placeholder:"Enter rejection reason...",rows:3,style:{resize:"vertical"}})]})]}),s.jsxs("div",{className:"cedros-admin__modal-footer",children:[s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--outline",onClick:Z,children:"Cancel"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:Q,children:"Reject Refund"})]})]})})]})}const xm=b.lazy(()=>Promise.resolve().then(()=>require("./SettingsSection-DUxjXl2G.js")).then(e=>({default:e.SettingsSection})));function yl(e){return s.jsx(b.Suspense,{fallback:null,children:s.jsx(xm,{...e})})}class bl{serverUrl;walletSigner=null;jwtToken=null;isAdminUser=!1;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdminUser?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,oe.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,n){this.jwtToken=t,this.isAdminUser=n??!1,oe.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t,isAdmin:this.isAdminUser})}async createAuthHeaders(t){const n=this.getAuthMethod();if(n==="wallet")return this.createWalletAuthHeaders(t);if(n==="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 n=await this.fetchNonce(t),r=new TextEncoder().encode(n.nonce_id),o=await this.walletSigner.signMessage(r),a=Ai.bs58.encode(this.walletSigner.publicKey.toBytes()),i=Ai.bs58.encode(o);return{"X-Signer":a,"X-Message":n.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 n=`${this.serverUrl}/paywall/v1/nonce`;oe.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const r=await oe.fetchWithTimeout(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!r.ok){const o=await r.text();throw new Error(`Failed to fetch nonce: ${r.status} ${o}`)}return await r.json()}async fetchWithAuth(t,n={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,n.method||"GET"),a=await this.createAuthHeaders(o),i=(n.method||"GET").toUpperCase(),c={...i!=="GET"&&i!=="HEAD"?{"Content-Type":"application/json"}:{},...n.headers||{},...a},l=await oe.fetchWithTimeout(`${this.serverUrl}${t}`,{...n,headers:c});if(!l.ok){let d=`Admin API error ${l.status}`;try{const f=await l.json();f&&typeof f.error=="string"?d=f.error:f&&typeof f.message=="string"&&(d=f.message)}catch{}throw new Error(d)}return await l.json()}getPurposeFromPath(t,n){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?.[n])return o[n];if(t.startsWith("/admin/products/")){if(n==="PUT")return"admin_products_update";if(n==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(n==="PUT")return"admin_coupons_update";if(n==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(n==="GET")return"admin_config_get";if(n==="PUT")return"admin_config_update";if(n==="PATCH")return"admin_config_patch"}return`admin_${n.toLowerCase()}`}}function vm({serverUrl:e,cedrosLoginToken:t,isAdmin:n=!1}){const r=Ip.useWallet(),o=b.useMemo(()=>{const u=new bl(e);return u.setCedrosLoginAuth(t??null,n),u},[e,t,n]);b.useEffect(()=>{r.publicKey&&r.signMessage?o.setWalletSigner({publicKey:r.publicKey,signMessage:r.signMessage}):o.setWalletSigner(null)},[o,r.publicKey,r.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(r.publicKey&&r.signMessage),l=!!t,d=b.useMemo(()=>{if(!r.publicKey)return null;const u=r.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[r.publicKey]),f=b.useCallback((u,m)=>o.fetchWithAuth(u,m),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:f}}const ym=b.lazy(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-C0hYf7Hr.js")).then(e=>({default:e.SubscriptionsSection}))),bm=b.lazy(()=>Promise.resolve().then(()=>require("./StorefrontSection-DcSoDx-k.js")).then(e=>({default:e.StorefrontSection}))),wm=b.lazy(()=>Promise.resolve().then(()=>require("./AISettingsSection-BrXUD4l_.js")).then(e=>({default:e.AISettingsSection}))),_m=b.lazy(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-D92IO4xJ.js")).then(e=>({default:e.PaymentSettingsSection}))),km=b.lazy(()=>Promise.resolve().then(()=>require("./MessagingSection-DId-WJdU.js")).then(e=>({default:e.MessagingSection}))),jm=b.lazy(()=>Promise.resolve().then(()=>require("./FAQSection-aoAz35MV.js")).then(e=>({default:e.FAQSection}))),wl=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:J.transactions},{id:"products",label:"Products",icon:J.products},{id:"subscriptions",label:"Subscriptions",icon:J.calendarRepeat},{id:"coupons",label:"Coupons",icon:J.coupons},{id:"refunds",label:"Refunds",icon:J.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:J.storefront},{id:"ai-settings",label:"Store AI",icon:J.brain},{id:"faqs",label:"Knowledge Base",icon:J.faq},{id:"payment-settings",label:"Payment Options",icon:J.creditCard},{id:"messaging",label:"Store Messages",icon:J.mail},{id:"settings",label:"Store Server",icon:J.server}]}],Sm=wl.flatMap(e=>e.sections);function Cm(){const[e,t]=b.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return b.useEffect(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)"),r=o=>t(o.matches?"dark":"light");return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}function Nm(e,t,n){return e!=="system"?e:t||n}function Em({serverUrl:e,apiKey:t,title:n="Cedros Pay",sections:r=["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:f=!1,theme:u="system"}){const[m,h]=b.useState(o),[v]=b.useState(!1),[x,g]=b.useState(new Set),y=b.useCallback(I=>{g(M=>{const z=new Set(M);return z.has(I)?z.delete(I):z.add(I),z})},[]),k=oe.useCedrosThemeOptional(),_=Cm(),j=Nm(u,k?.mode??null,_)==="dark"?"cedros-admin--dark":"",{authManager:P,isAuthenticated:T}=vm({serverUrl:e,cedrosLoginToken:d,isAdmin:f}),N=b.useCallback(I=>{h(I),c?.(I)},[c]),R=Sm.filter(I=>r.includes(I.id)).find(I=>I.id===m);return v?s.jsxs("div",{className:`cedros-admin cedros-admin--loading ${j} ${l}`,children:[J.loading,s.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):T?s.jsxs("div",{className:`cedros-admin ${j} ${l}`,children:[s.jsxs("aside",{className:"cedros-admin__sidebar",children:[s.jsx("div",{className:"cedros-admin__sidebar-header",children:s.jsxs("div",{className:"cedros-admin__logo",children:[J.wallet,s.jsx("span",{className:"cedros-admin__logo-text",children:n})]})}),s.jsx("nav",{className:"cedros-admin__nav",children:wl.map(I=>{const M=I.sections.filter(D=>r.includes(D.id));if(M.length===0)return null;const z=I.collapsible&&x.has(I.label);return s.jsxs("div",{className:"cedros-admin__nav-group",children:[I.collapsible?s.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>y(I.label),"aria-expanded":!z,children:[I.label,s.jsx("span",{className:`cedros-admin__nav-label-icon ${z?"":"cedros-admin__nav-label-icon--expanded"}`,children:J.chevronRight})]}):s.jsx("span",{className:"cedros-admin__nav-label",children:I.label}),!z&&M.map(D=>s.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${m===D.id?"cedros-admin__nav-item--active":""}`,onClick:()=>N(D.id),"aria-current":m===D.id?"page":void 0,children:[s.jsx("span",{className:"cedros-admin__nav-icon",children:D.icon}),s.jsx("span",{className:"cedros-admin__nav-text",children:D.label})]},D.id))]},I.label)})})]}),s.jsxs("main",{className:"cedros-admin__main",children:[s.jsx("header",{className:"cedros-admin__header",children:s.jsxs("div",{className:"cedros-admin__breadcrumb",children:[s.jsx("span",{className:"cedros-admin__breadcrumb-root",children:n}),s.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:J.chevronRight}),s.jsx("span",{className:"cedros-admin__breadcrumb-current",children:R?.label})]})}),s.jsxs("div",{className:"cedros-admin__content",children:[m==="products"&&s.jsx(hl,{serverUrl:e,apiKey:t,pageSize:i,authManager:P}),m==="subscriptions"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(ym,{serverUrl:e,apiKey:t,authManager:P})}),m==="transactions"&&s.jsx(gl,{serverUrl:e,apiKey:t,pageSize:i,authManager:P}),m==="coupons"&&s.jsx(xl,{serverUrl:e,apiKey:t,pageSize:i,authManager:P}),m==="refunds"&&s.jsx(vl,{serverUrl:e,apiKey:t,pageSize:i,authManager:P}),m==="storefront"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(bm,{serverUrl:e,apiKey:t,authManager:P})}),m==="ai-settings"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(wm,{serverUrl:e,apiKey:t,authManager:P})}),m==="faqs"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(jm,{serverUrl:e,apiKey:t,pageSize:i,authManager:P})}),m==="payment-settings"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(_m,{serverUrl:e,apiKey:t,authManager:P})}),m==="messaging"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(km,{serverUrl:e,apiKey:t,authManager:P})}),m==="settings"&&s.jsx(yl,{serverUrl:e,apiKey:t,authManager:P})]})]})]}):s.jsx("div",{className:`cedros-admin cedros-admin--unauthenticated ${j} ${l}`,children:s.jsx("p",{className:"cedros-admin__auth-prompt",children:"Please connect a wallet or sign in as admin to access the dashboard."})})}function Ts(e){const t=b.lazy(e),n=r=>b.createElement(b.Suspense,{fallback:null},b.createElement(t,r));return n.displayName="LazyAdminSection",n}Ts(()=>Promise.resolve().then(()=>require("./SettingsSection-DUxjXl2G.js")).then(e=>({default:e.SettingsSection})));Ts(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-C0hYf7Hr.js")).then(e=>({default:e.SubscriptionsSection})));Ts(()=>Promise.resolve().then(()=>require("./StorefrontSection-DcSoDx-k.js")).then(e=>({default:e.StorefrontSection})));Ts(()=>Promise.resolve().then(()=>require("./FAQSection-aoAz35MV.js")).then(e=>({default:e.FAQSection})));const kt=e=>b.lazy(async()=>{const r=(await e()).default;return{default:({pluginContext:a})=>{const c=Tp.useCedrosLogin()?._internal?.getAccessToken()??a.getAccessToken(),l=b.useMemo(()=>{const f=new bl(a.serverUrl);return f.setCedrosLoginAuth(c??null),f},[a.serverUrl,c]),d={serverUrl:a.serverUrl,authManager:l};return s.jsx(r,{...d})}}}),Am={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:J.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:J.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:J.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:J.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:J.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:J.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:J.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:J.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:J.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:J.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:J.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:kt(()=>Promise.resolve().then(()=>require("./sections-D2GMJuKq.js")).then(e=>({default:e.ProductsSection}))),subscriptions:kt(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-C0hYf7Hr.js")).then(e=>({default:e.SubscriptionsSection}))),transactions:kt(()=>Promise.resolve().then(()=>require("./sections-D2GMJuKq.js")).then(e=>({default:e.TransactionsSection}))),coupons:kt(()=>Promise.resolve().then(()=>require("./sections-D2GMJuKq.js")).then(e=>({default:e.CouponsSection}))),refunds:kt(()=>Promise.resolve().then(()=>require("./sections-D2GMJuKq.js")).then(e=>({default:e.RefundsSection}))),storefront:kt(()=>Promise.resolve().then(()=>require("./StorefrontSection-DcSoDx-k.js")).then(e=>({default:e.StorefrontSection}))),"ai-settings":kt(()=>Promise.resolve().then(()=>require("./AISettingsSection-BrXUD4l_.js")).then(e=>({default:e.AISettingsSection}))),faqs:kt(()=>Promise.resolve().then(()=>require("./FAQSection-aoAz35MV.js")).then(e=>({default:e.FAQSection}))),"payment-settings":kt(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-D92IO4xJ.js")).then(e=>({default:e.PaymentSettingsSection}))),messaging:kt(()=>Promise.resolve().then(()=>require("./MessagingSection-DId-WJdU.js")).then(e=>({default:e.MessagingSection}))),settings:kt(()=>Promise.resolve().then(()=>require("./SettingsSection-DUxjXl2G.js")).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,n=e.cedrosLogin;return{serverUrl:t?.serverUrl||n?.serverUrl||"",userId:n?.user?.id,getAccessToken:()=>n?.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 Pm({product:e,paymentMethod:t,showOriginalPrice:n=!1,className:r="",style:o={}}){const a=t==="stripe",i=a?e.fiatAmount:e.cryptoAmount,c=a?e.effectiveFiatAmount:e.effectiveCryptoAmount,l=a?e.fiatCurrency.toUpperCase():e.cryptoToken,d=a?e.hasStripeCoupon:e.hasCryptoCoupon,f=a?e.stripeDiscountPercent:e.cryptoDiscountPercent;return s.jsxs("div",{className:r,style:o,children:[n&&d&&s.jsxs("span",{style:{textDecoration:"line-through",opacity:.6,marginRight:"0.5rem",fontSize:"0.875em"},children:[i.toFixed(2)," ",l]}),s.jsxs("span",{style:{fontWeight:600},children:[c.toFixed(2)," ",l]}),d&&f>0&&s.jsxs("span",{style:{marginLeft:"0.5rem",padding:"0.125rem 0.375rem",backgroundColor:"#10b981",color:"white",borderRadius:"0.25rem",fontSize:"0.75em",fontWeight:600},children:[f,"% OFF"]})]})}function Im({product:e,paymentMethod:t,className:n="",style:r={}}){const o=t==="stripe",a=o?e.hasStripeCoupon:e.hasCryptoCoupon,i=o?e.stripeDiscountPercent:e.cryptoDiscountPercent,c=o?e.stripeCouponCode:e.cryptoCouponCode;if(!a||i===0)return null;const l=o?`${i}% off with card!`:`${i}% off with crypto!`;return s.jsxs("div",{className:n,style:{display:"inline-flex",alignItems:"center",padding:"0.5rem 0.75rem",backgroundColor:o?"#6366f1":"#10b981",color:"white",borderRadius:"0.375rem",fontSize:"0.875rem",fontWeight:600,...r},children:[l,c&&s.jsxs("span",{style:{marginLeft:"0.5rem",opacity:.8,fontSize:"0.75em",fontWeight:400},children:["(",c,")"]})]})}function _l(){const{subscriptionManager:e}=oe.useCedrosContext(),[t,n]=b.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),r=b.useRef(!1),o=b.useCallback(async l=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n(d=>({...d,status:"loading",error:null}));try{const d=await e.processSubscription(l);return n(f=>({...f,status:d.success?"success":"error",error:d.success?null:d.error||"Subscription failed",sessionId:d.success&&d.transactionId||null})),d}catch(d){const f=oe.formatError(d,"Subscription failed");return n(u=>({...u,status:"error",error:f})),{success:!1,error:f}}finally{r.current=!1}},[e]),a=b.useCallback(async l=>{n(d=>({...d,status:"checking",error:null}));try{const d=await e.checkSubscriptionStatus(l);return n(f=>({...f,status:d.active?"success":"idle",subscriptionStatus:d.status,expiresAt:d.expiresAt||d.currentPeriodEnd||null})),d}catch(d){const f=d instanceof Error?d.message:"Failed to check subscription status";throw n(u=>({...u,status:"error",error:f})),d}},[e]),i=b.useCallback(async(l,d,f)=>{n(u=>({...u,status:"loading",error:null}));try{const u=await e.requestSubscriptionQuote(l,d,f);return n(m=>({...m,status:"idle"})),u}catch(u){const m=u instanceof Error?u.message:"Failed to get subscription quote";throw n(h=>({...h,status:"error",error:m})),u}},[e]),c=b.useCallback(()=>{n({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:o,checkStatus:a,requestQuote:i,reset:c}}function Tm({resource:e,interval:t,intervalDays:n,trialDays:r,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:f=!1,onAttempt:u,onSuccess:m,onError:h,className:v=""}){const{status:x,error:g,sessionId:y,processSubscription:k}=_l(),_=oe.useCedrosTheme(),{t:w,translations:j}=Pn(),P=d||w("ui.subscribe"),T=_.unstyled?v:`${_.className} cedros-theme__stripe-button ${v}`.trim(),N=g&&typeof g!="string"?g?.code??null:null,R=g?typeof g=="string"?g:(L=>{if(!L||!j)return"";const S=j.errors[L];return S?S.action?`${S.message} ${S.action}`:S.message:""})(N):null,I=b.useCallback(async()=>{oe.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:n,trialDays:r,couponCode:l}),Kn("stripe",e),u&&u("stripe"),Jn("stripe",e);const L=await k({resource:e,interval:t,intervalDays:n,trialDays:r,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});L.success&&L.transactionId?(Xn("stripe",L.transactionId,e),m&&m(L.transactionId)):!L.success&&L.error&&(Bt("stripe",L.error,e),h&&h(L.error))},[e,t,n,r,c,i,l,o,a,k,u,m,h]),M=b.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),z=b.useMemo(()=>Qn(M,I),[M,I]),D=x==="loading",V=f||D;return s.jsxs("div",{className:T,style:_.unstyled?{}:_.style,children:[s.jsx("button",{onClick:z,disabled:V,className:_.unstyled?v:"cedros-theme__button cedros-theme__stripe",type:"button",children:D?w("ui.processing"):P}),R&&s.jsx("div",{className:_.unstyled?"":"cedros-theme__error",children:R}),y&&s.jsx("div",{className:_.unstyled?"":"cedros-theme__success",children:w("ui.redirecting_to_checkout")})]})}function kl(){const{subscriptionManager:e,creditsManager:t}=oe.useCedrosContext(),[n,r]=b.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=b.useRef(!1),a=b.useCallback(async(d,f)=>{r(u=>({...u,status:"checking",error:null}));try{const u=await e.checkSubscriptionStatus({resource:d,userId:f});return r(m=>({...m,status:u.active?"success":"idle",subscriptionStatus:u.status,expiresAt:u.expiresAt||u.currentPeriodEnd||null})),u}catch(u){const m=oe.formatError(u,"Failed to check subscription status");return r(h=>({...h,status:"error",error:m})),null}},[e]),i=b.useCallback(async(d,f,u)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await t.requestQuote(d,u?.couponCode);return r(h=>({...h,status:"idle",creditsRequirement:m})),m}catch(m){const h=oe.formatError(m,"Failed to get subscription quote");return r(v=>({...v,status:"error",error:h})),null}},[t]),c=b.useCallback(async(d,f,u,m)=>{if(o.current)return{success:!1,error:"Payment already in progress"};if(!u){const h="Authentication required for credits payment";return r(v=>({...v,status:"error",error:h})),{success:!1,error:h}}o.current=!0,r(h=>({...h,status:"loading",error:null}));try{const h=await t.processPayment(d,u,m?.couponCode,{interval:f,...m?.intervalDays&&{intervalDays:String(m.intervalDays)}});return h.success?r({status:"success",error:null,sessionId:h.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):r(v=>({...v,status:"error",error:h.error||"Credits subscription payment failed"})),h}catch(h){const v=oe.formatError(h,"Credits subscription payment failed");return r(x=>({...x,status:"error",error:v})),{success:!1,error:v}}finally{o.current=!1}},[t]),l=b.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...n,checkStatus:a,requestQuote:i,processPayment:c,reset:l}}function Rm({resource:e,interval:t,intervalDays:n,authToken:r,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:f,className:u="",hideMessages:m=!1,autoCheckStatus:h=!1}){const{status:v,error:x,subscriptionStatus:g,expiresAt:y,checkStatus:k,processPayment:_}=kl(),w=oe.useCedrosTheme(),{t:j,translations:P}=Pn(),T=b.useRef(k);b.useEffect(()=>{T.current=k},[k]),b.useEffect(()=>{h&&o&&(oe.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),T.current(e,o))},[h,o,e]);const N=i||j("ui.subscribe_with_credits")||"Subscribe with Credits",A=x&&typeof x!="string"?x?.code??null:null,I=x?typeof x=="string"?x:(Z=>{if(!Z||!P)return"";const Q=P.errors[Z];return Q?Q.action?`${Q.message} ${Q.action}`:Q.message:""})(A):null,M=b.useCallback(async()=>{if(oe.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:n,hasAuthToken:!!r}),Kn("credits",e),l&&l("credits"),!r){const Q="Authentication required: please log in to subscribe with credits";oe.getLogger().error("[CreditsSubscribeButton]",Q),Bt("credits",Q,e),f&&f(Q);return}Jn("credits",e);const Z=await _(e,t,r,{couponCode:a,intervalDays:n});Z.success&&Z.transactionId?(Xn("credits",Z.transactionId,e),d&&d(Z.transactionId)):!Z.success&&Z.error&&(Bt("credits",Z.error,e),f&&f(Z.error))},[e,t,n,r,a,_,l,d,f]),z=b.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),D=b.useMemo(()=>Qn(z,M,{cooldownMs:200,deduplicationWindowMs:0}),[z,M]),V=v==="loading"||v==="checking",L=g==="active"||g==="trialing",S=c||V||L;let C=N;if(V)C=j("ui.processing");else if(L&&y){const Z=new Date(y).toLocaleDateString();C=`${j("ui.subscribed_until")} ${Z}`}else L&&(C=j("ui.subscribed"));const W=w.unstyled?u:`${w.className} cedros-theme__credits-button ${u}`.trim();return s.jsxs("div",{className:W,style:w.unstyled?{}:w.style,children:[s.jsx("button",{onClick:D,disabled:S,className:w.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:C}),!m&&I&&s.jsx("div",{className:w.unstyled?"":"cedros-theme__error",children:I}),!m&&L&&s.jsx("div",{className:w.unstyled?"":"cedros-theme__success",children:j("ui.subscription_active")})]})}function jl(){const{subscriptionChangeManager:e}=oe.useCedrosContext(),[t,n]=b.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),r=b.useRef(t);r.current=t;const o=b.useCallback(async(u,m)=>{n(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,m);return n(v=>({...v,status:"success",subscription:h,userId:m})),h}catch(h){const v=h instanceof Error?h.message:"Failed to load subscription";return n(x=>({...x,status:"error",error:v})),null}},[e]),a=b.useCallback(async(u,m,h,v)=>{n(x=>({...x,status:"loading",error:null}));try{const x={currentResource:u,newResource:m,userId:h,newInterval:v},g=await e.previewChange(x);return n(y=>({...y,status:"idle",changePreview:g})),g}catch(x){const g=x instanceof Error?x.message:"Failed to preview change";return n(y=>({...y,status:"error",error:g})),null}},[e]),i=b.useCallback(async u=>{const{subscription:m,userId:h}=r.current;if(!m||!h)return n(v=>({...v,status:"error",error:"No subscription loaded"})),null;n(v=>({...v,status:"loading",error:null}));try{const v={currentResource:m.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},x=await e.changeSubscription(v);return x.success?n(g=>({...g,status:"success",subscription:g.subscription?{...g.subscription,resource:x.newResource,interval:x.newInterval,status:x.status}:null,changePreview:null})):n(g=>({...g,status:"error",error:x.error||"Failed to change subscription"})),x}catch(v){const x=v instanceof Error?v.message:"Failed to change subscription";return n(g=>({...g,status:"error",error:x})),null}},[e]),c=b.useCallback(async u=>{const{subscription:m,userId:h}=r.current;if(!m||!h)return n(v=>({...v,status:"error",error:"No subscription loaded"})),null;n(v=>({...v,status:"loading",error:null}));try{const v={resource:m.resource,userId:h,immediate:u},x=await e.cancel(v);if(x.success){const g=u?"canceled":m.status;n(y=>({...y,status:"success",subscription:y.subscription?{...y.subscription,status:g,cancelAtPeriodEnd:!u}:null}))}else n(g=>({...g,status:"error",error:x.error||"Failed to cancel subscription"}));return x}catch(v){const x=v instanceof Error?v.message:"Failed to cancel subscription";return n(g=>({...g,status:"error",error:x})),null}},[e]),l=b.useCallback(async(u,m)=>{n(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:m});try{if(new URL(h.url).protocol!=="https:")throw new Error("Billing portal URL must use HTTPS")}catch{throw new Error("Invalid billing portal URL")}return window.location.href=h.url,h}catch(h){const v=h instanceof Error?h.message:"Failed to open billing portal";return n(x=>({...x,status:"error",error:v})),null}},[e]),d=b.useCallback(()=>{n(u=>({...u,changePreview:null}))},[]),f=b.useCallback(()=>{n({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:f}}const Om={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"},Mm={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 Lm(e){const t=e?Mm:Om;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 wn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function Sl(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function Dm(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 $m({preview:e,onConfirm:t,onCancel:n,isLoading:r,styles:o}){const a=e.immediateAmount<0;return s.jsxs("div",{className:"cedros-proration-preview",style:o.prorationPreview,children:[s.jsx("h4",{style:o.previewTitle,children:"Change Preview"}),s.jsxs("div",{style:o.previewDetails,children:[s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"Current plan:"}),s.jsxs("span",{children:[wn(e.currentPlanPrice,e.currency),"/period"]})]}),s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"New plan:"}),s.jsxs("span",{children:[wn(e.newPlanPrice,e.currency),"/period"]})]}),s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"Days remaining:"}),s.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"Unused credit:"}),s.jsxs("span",{children:["-",wn(e.prorationDetails.unusedCredit,e.currency)]})]}),s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"New plan cost:"}),s.jsx("span",{children:wn(e.prorationDetails.newPlanCost,e.currency)})]})]}),s.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[s.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),s.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:wn(Math.abs(e.immediateAmount),e.currency)})]}),s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"Effective date:"}),s.jsx("span",{children:Sl(e.effectiveDate)})]})]}),s.jsxs("div",{style:o.previewActions,children:[s.jsx("button",{onClick:n,style:o.cancelButton,disabled:r,children:"Cancel"}),s.jsx("button",{onClick:t,style:o.confirmButton,disabled:r,children:r?"Processing...":"Confirm Change"})]})]})}function zm({resource:e,userId:t,availablePlans:n=[],onSubscriptionChanged:r,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=oe.useCedrosTheme(),f=b.useMemo(()=>Lm(d==="dark"),[d]),{subscription:u,changePreview:m,status:h,error:v,loadSubscription:x,previewChange:g,changeSubscription:y,cancelSubscription:k,openBillingPortal:_,clearPreview:w}=jl();b.useEffect(()=>{x(e,t)},[e,t,x]);const j=b.useRef(null),P=b.useCallback(async(I,M)=>{j.current={resource:I,interval:M},await g(e,I,t,M)},[e,t,g]),T=b.useCallback(async()=>{if(!m)return;const I=j.current;(await y({newResource:I?.resource||e,newInterval:I?.interval,immediate:!0}))?.success&&I&&I.interval&&(r?.(I.resource,I.interval),j.current=null)},[m,e,y,r]),N=b.useCallback(async I=>{(await k(I))?.success&&o?.()},[k,o]),A=b.useCallback(()=>{_(t,a)},[t,a,_]),R=h==="loading";return s.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...f.container,...l},children:[v&&s.jsx("div",{className:"cedros-subscription-error",style:f.error,children:v}),R&&!u&&s.jsx("div",{className:"cedros-subscription-loading",style:f.loading,children:"Loading subscription..."}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"cedros-subscription-details",style:f.details,children:[s.jsx("h3",{style:f.title,children:"Current Subscription"}),s.jsxs("div",{style:f.detailRow,children:[s.jsx("span",{style:f.label,children:"Plan:"}),s.jsx("span",{style:f.value,children:u.resource})]}),s.jsxs("div",{style:f.detailRow,children:[s.jsx("span",{style:f.label,children:"Status:"}),s.jsx("span",{style:{...f.statusBadge,backgroundColor:Dm(u.status)},children:u.status})]}),s.jsxs("div",{style:f.detailRow,children:[s.jsx("span",{style:f.label,children:"Price:"}),s.jsxs("span",{style:f.value,children:[wn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),s.jsxs("div",{style:f.detailRow,children:[s.jsx("span",{style:f.label,children:"Current period ends:"}),s.jsx("span",{style:f.value,children:Sl(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&s.jsx("div",{style:f.cancelNotice,children:"Subscription will cancel at end of current period"})]}),m&&s.jsx($m,{preview:m,onConfirm:T,onCancel:w,isLoading:R,styles:f}),n.length>0&&!m&&s.jsxs("div",{className:"cedros-available-plans",style:f.plansSection,children:[s.jsx("h4",{style:f.plansTitle,children:"Available Plans"}),s.jsx("div",{style:f.plansList,children:n.map(I=>{const M=I.resource===u.resource;return s.jsxs("div",{style:{...f.planCard,...M?f.currentPlan:{}},children:[s.jsx("div",{style:f.planName,children:I.name}),s.jsxs("div",{style:f.planPrice,children:[wn(I.price,I.currency),"/",I.interval]}),I.description&&s.jsx("div",{style:f.planDescription,children:I.description}),M?s.jsx("span",{style:f.currentBadge,children:"Current Plan"}):s.jsx("button",{onClick:()=>P(I.resource,I.interval),style:f.changePlanButton,disabled:R,children:I.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},I.resource)})})]}),s.jsxs("div",{className:"cedros-subscription-actions",style:f.actions,children:[i&&u.paymentMethod==="stripe"&&s.jsx("button",{onClick:A,style:f.portalButton,disabled:R,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&s.jsx("button",{onClick:()=>N(!1),style:f.cancelSubscriptionButton,disabled:R,children:"Cancel Subscription"})]})]})]})}function Fm(){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 Bm(){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 Um(){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 Vm(){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 Wm(){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 qm(){const e=[Fm(),Bm(),Um(),Vm(),Wm()],t=e.some(a=>a.severity==="error"&&!a.passed),n=e.some(a=>a.severity==="warning"&&!a.passed);let r,o;return t?(r="vulnerable",o="Security issues detected. Review errors and apply recommendations."):n?(r="warnings",o="Minor security warnings detected. Consider applying recommendations."):(r="secure",o="All security checks passed."),{checks:e,overallStatus:r,summary:o}}function Hm(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 n=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${n} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const Zm={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"},ga=b.createContext(null);function Pe(){const e=b.useContext(ga);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function xa(){return b.useContext(ga)}function Gm({config:e,children:t}){const n=b.useMemo(()=>({config:e}),[e]);return s.jsx(ga.Provider,{value:n,children:t})}function jt(e){return new Promise(t=>setTimeout(t,e))}const Cl=[{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."}],ps=[{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"}];function Ym(e,t){let n=e;if(t.category&&t.category!=="all"){const l=Cl.find(d=>d.slug===t.category||d.id===t.category);l&&(n=n.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();n=n.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const r=t.filters??{},o=r.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));n=n.filter(d=>d.tags?.some(f=>l.has(f)))}const a=typeof r.priceMin=="number"?r.priceMin:void 0,i=typeof r.priceMax=="number"?r.priceMax:void 0;return typeof a=="number"&&(n=n.filter(l=>l.price>=a)),typeof i=="number"&&(n=n.filter(l=>l.price<=i)),(typeof r.inStock=="boolean"?r.inStock:void 0)===!0&&(n=n.filter(l=>l.inventoryStatus!=="out_of_stock")),n}function Qm(e,t){if(!t||t==="featured")return e;const n=[...e];return t==="price_asc"&&n.sort((r,o)=>r.price-o.price),t==="price_desc"&&n.sort((r,o)=>o.price-r.price),n}function Km(e,t,n){const r=(t-1)*n;return{items:e.slice(r,r+n),page:t,pageSize:n,total:e.length,hasNextPage:r+n<e.length}}function Jm(e){const t=new Date().toISOString(),n=e.cart.map(o=>{const a=ps.find(i=>i.id===o.resource||i.slug===o.resource)??ps[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),r=n.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:r,currency:e.options.currency,items:n,receiptUrl:e.options.successUrl}}function Xm(){let e=[];const t={};return{async listProducts(n){await jt(150);const r=n.page??1,o=n.pageSize??24,a=Ym(ps,n),i=Qm(a,n.sort);return Km(i,r,o)},async getProductBySlug(n){return await jt(100),ps.find(r=>r.slug===n)??null},async listCategories(){return await jt(80),Cl},async getOrderHistory(){return await jt(120),e},async getCart({customerId:n}){return await jt(80),t[n]??{items:[]}},async mergeCart({customerId:n,cart:r}){await jt(120);const o=t[n]??{items:[]},a=new Map,i=l=>{const d=`${l.productId}::${l.variantId??""}`,f=a.get(d);f?a.set(d,{...f,qty:f.qty+l.qty}):a.set(d,l)};for(const l of o.items)i(l);for(const l of r.items)i(l);const c={items:Array.from(a.values()),promoCode:r.promoCode??o.promoCode};return t[n]=c,c},async updateCart({customerId:n,cart:r}){await jt(60),t[n]=r},async createCheckoutSession(n){await jt(250);const r=Jm(n);if(e=[r,...e].slice(0,25),n.options.successUrl){const o=new URL(n.options.successUrl,"http://localhost");return o.searchParams.set("demoOrderId",r.id),{kind:"redirect",url:o.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:r.id}}},async listSubscriptionTiers(){return await jt(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 jt(80),{isActive:!1}},async createSubscriptionCheckoutSession(n){return await jt(200),n.successUrl?{kind:"redirect",url:n.successUrl}:{kind:"custom",data:n}}}}const Ri=50,eh=4,th=5,nh=1e4,rh={maxRetries:2,initialDelayMs:100,backoffFactor:2,maxDelayMs:500,jitter:!1};function Nl(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function sh(e){return e?e.toUpperCase():"USD"}function oh(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function ah(e){if(e&&(e==="physical"||e==="digital"))return e}function ih(e){const t=[];if(Array.isArray(e))for(const n of e)typeof n=="string"&&t.push(n);else if(typeof e=="string"){const n=e.trim();if(n.startsWith("["))try{const r=JSON.parse(n);if(Array.isArray(r))for(const o of r)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(n=>n.split(",")).map(n=>n.trim().toUpperCase()).filter(Boolean)}function Dn(e){const t=sh(e.fiatCurrency),n=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],r=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=ih(a);return{id:e.id,slug:e.slug??e.id,title:e.title??Nl(e.id),description:e.description??"",images:n,price:r/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:oh(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:ah(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function os(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],n=e.total??e.count;return{products:t,total:n}}async function Ct(e,t,n,r={}){const{body:o,headers:a,method:i="GET",retryableRead:c=!1,timeoutMs:l=nh}=r,d={};n&&(d["X-API-Key"]=n),a&&Object.assign(d,a);const f=async()=>{const u=await oe.fetchWithTimeout(`${e}${t}`,{body:o,headers:d,method:i},l);if(!u.ok){const m=await u.text().catch(()=>""),h=new Error(`Request failed (${u.status}): ${m}`);throw h.status=u.status,h}return u.json()};return c?oe.retryWithBackoff(f,{...rh,name:`paywall-read-${i.toLowerCase()}`}):f()}async function ch(e,t,n,r){const o=await Ct(e,`/paywall/v1/products?limit=${n}&offset=${r}`,t,{retryableRead:!0});return os(o)}async function Oi(e,t,n,r){const{maxPages:o,pageSize:a}=n;for(let i=0;i<o;i+=1){const c=i*a,{products:l,total:d}=await ch(e,t,a,c);if(l.length===0||r(l))return;const f=typeof d=="number"&&c+l.length>=d,u=l.length<a;if(f||u)return}}function lh(e){const t=async d=>{const f=d.page??1,u=d.pageSize??24,m=u,h=(f-1)*u,v=new URLSearchParams;v.set("limit",String(m)),v.set("offset",String(h)),d.search&&v.set("search",d.search),d.category&&v.set("category",d.category),d.sort&&v.set("sort",d.sort),d.filters?.inStock&&v.set("in_stock","true"),d.filters?.minPrice!=null&&v.set("min_price",String(d.filters.minPrice)),d.filters?.maxPrice!=null&&v.set("max_price",String(d.filters.maxPrice));const x=d.filters?.tags,g=Array.isArray(x)?x:typeof x=="string"?[x]:[];g.length&&v.set("tags",g.join(","));const y=await Ct(e.serverUrl,`/paywall/v1/products?${v.toString()}`,e.apiKey,{retryableRead:!0}),{products:k,total:_}=os(y);return{items:k.map(Dn),page:f,pageSize:u,total:_,hasNextPage:typeof _=="number"?h+m<_:k.length===m}},n=async d=>{try{const f=await Ct(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(d)}`,e.apiKey,{retryableRead:!0});return Dn(f)}catch(f){const u=f?.status;if(u!==404&&u!==405)throw f;try{const m=await Ct(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(d)}`,e.apiKey,{retryableRead:!0});return Dn(m)}catch(m){const h=m?.status;if(h!==404&&h!==405)throw m;let v;return await Oi(e.serverUrl,e.apiKey,{maxPages:eh,pageSize:Ri},x=>(v=x.find(g=>g.slug===d||g.id===d),!!v)),v?Dn(v):null}}};return{listProducts:t,getProductBySlug:n,getProductsByIds:async d=>{const f=Array.from(new Set(d.filter(Boolean)));if(f.length===0)return new Map;const u=new Map;try{const v=new URLSearchParams;v.set("ids",f.join(",")),v.set("limit",String(f.length)),v.set("offset","0");const x=await Ct(e.serverUrl,`/paywall/v1/products?${v.toString()}`,e.apiKey,{retryableRead:!0}),{products:g}=os(x);for(const y of g){const k=Dn(y);u.set(k.id,k),k.slug&&k.slug!==k.id&&u.set(k.slug,k)}}catch{}const m=f.filter(v=>!u.has(v));if(m.length===0)return u;let h=m;try{const v=new Set(h);if(await Oi(e.serverUrl,e.apiKey,{maxPages:th,pageSize:Ri},x=>{for(const g of x){const y=Dn(g);!v.has(y.id)&&!(y.slug&&v.has(y.slug))||(u.set(y.id,y),y.slug&&y.slug!==y.id&&u.set(y.slug,y),v.delete(y.id),y.slug&&v.delete(y.slug))}return v.size===0}),h=Array.from(v),h.length===0)return u}catch{}for(const v of h)try{const x=await n(v);x&&(u.set(x.id,x),x.slug&&x.slug!==x.id&&u.set(x.slug,x))}catch{}return u},listCategories:async()=>{const d=await Ct(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey,{retryableRead:!0}),{products:f}=os(d),u=new Set;for(const m of f)for(const h of m.categoryIds??[])u.add(h);return Array.from(u).map(m=>({id:m,slug:m,name:Nl(m)}))},getOrderHistory:async()=>[],createCheckoutSession:async d=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await Ct(e.serverUrl,"/admin/config/shop",e.apiKey,{retryableRead:!0})).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[d,f,u]=await Promise.allSettled([Ct(e.serverUrl,"/admin/config/stripe",e.apiKey,{retryableRead:!0}),Ct(e.serverUrl,"/admin/config/x402",e.apiKey,{retryableRead:!0}),Ct(e.serverUrl,"/admin/config/cedros_login",e.apiKey,{retryableRead:!0})]),m=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=f.status==="fulfilled"?!!f.value?.config?.enabled:!1,v=u.status==="fulfilled"?!!u.value?.config?.enabled:!1;return{card:m,crypto:h,credits:v}}catch{return null}},getAIRelatedProducts:async d=>Ct(e.serverUrl,"/admin/ai/related-products",e.apiKey,{method:"POST",body:JSON.stringify(d),headers:{"Content-Type":"application/json"},retryableRead:!1})}}function dh(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function vn(e){return`${e.productId}::${e.variantId??""}`}const uh={items:[]};function fh(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const n=Math.max(1,Math.floor(t.qty??1)),r=vn(t.item);return e.items.find(a=>vn(a)===r)?{...e,items:e.items.map(a=>vn(a)===r?{...a,qty:a.qty+n}:a)}:{...e,items:[...e.items,{...t.item,qty:n}]}}case"cart/remove":{const n=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(r=>vn(r)!==n)}}case"cart/setQty":{const n=Math.max(0,Math.floor(t.qty)),r=`${t.productId}::${t.variantId??""}`;return n===0?{...e,items:e.items.filter(o=>vn(o)!==r)}:{...e,items:e.items.map(o=>vn(o)===r?{...o,qty:n}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const n=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(r=>vn(r)===n?{...r,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:r)}}default:return dh(t)}}function ph(e){return e.reduce((t,n)=>t+n.qty,0)}function mh(e){return e.reduce((t,n)=>t+n.qty*n.unitPrice,0)}function Mi(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function hh(e,t){try{const n=e.getItem(t);return n?JSON.parse(n):null}catch{return null}}function gh(e,t,n){try{return e.setItem(t,JSON.stringify(n)),!0}catch(r){return console.warn(`[cedros] Failed to write "${t}" to storage`,r),!1}}const El=b.createContext(null);function Rt(){const e=b.useContext(El);if(!e)throw new Error("useCart must be used within CartProvider");return e}function Li(e){return!!e&&typeof e=="object"&&typeof e.productId=="string"&&e.productId.length>0&&typeof e.qty=="number"&&e.qty>0&&typeof e.unitPrice=="number"&&typeof e.currency=="string"&&typeof e.titleSnapshot=="string"}function xh({children:e}){const{config:t}=Pe(),n=t.cart?.storageKey??"cedros_shop_cart_v1",r=t.customer?.id,o=t.customer?.isSignedIn??!!r,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=b.useReducer(fh,uh),d=b.useRef(c);d.current=c;const[f,u]=b.useState(!1),m=b.useRef(!1),h=b.useRef(null),v=b.useRef(null);b.useEffect(()=>{const k=Mi();if(!k)return;const _=hh(k,n);if(_&&Array.isArray(_.items)){const w=_.items.filter(Li);l({type:"cart/hydrate",state:{items:w,promoCode:typeof _.promoCode=="string"?_.promoCode:void 0}})}u(!0)},[n]),b.useEffect(()=>{if(!f)return;const k=Mi();k&&gh(k,n,c)},[c,n,f]),b.useEffect(()=>{if(!f||!o||!r||!t.adapter.mergeCart&&!t.adapter.getCart||(v.current!==r&&(m.current=!1,h.current=null,v.current=r),m.current))return;let k=!1;return(async()=>{try{const _=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:r,cart:d.current}):await t.adapter.getCart({customerId:r});if(k)return;if(_&&Array.isArray(_.items)){m.current=!0;const w={..._,items:_.items.filter(Li)};l({type:"cart/hydrate",state:w}),h.current=JSON.stringify(w)}}catch{k||(m.current=!1)}})(),()=>{k=!0}},[t.adapter,r,f,o]),b.useEffect(()=>{if(!f||!o||!r||!t.adapter.updateCart||!m.current||typeof window>"u")return;const k=JSON.stringify(c);if(h.current===k)return;const _=window.setTimeout(()=>{t.adapter.updateCart({customerId:r,cart:c}).then(()=>{h.current=k}).catch(w=>{console.warn("[CedrosPay] Cart server sync failed:",w instanceof Error?w.message:w)})},a);return()=>window.clearTimeout(_)},[t.adapter,r,f,o,c,a]);const x=b.useCallback((k,_)=>{const w=c.items.find(j=>j.productId===k&&j.variantId===_);if(w)return{holdId:w.holdId,expiresAt:w.holdExpiresAt}},[c.items]),g=b.useCallback((k,_,w)=>{l({type:"cart/updateHold",productId:k,variantId:_,holdExpiresAt:w})},[]),y=b.useMemo(()=>{const k=ph(c.items),_=mh(c.items);return{items:c.items,promoCode:c.promoCode,count:k,subtotal:_,addItem:(w,j)=>l({type:"cart/add",item:w,qty:j}),removeItem:(w,j)=>l({type:"cart/remove",productId:w,variantId:j}),setQty:(w,j,P)=>l({type:"cart/setQty",productId:w,variantId:j,qty:P}),clear:()=>l({type:"cart/clear"}),setPromoCode:w=>l({type:"cart/setPromoCode",promoCode:w}),holdsSupported:i,getItemHold:x,updateItemHold:g}},[c.items,c.promoCode,i,x,g]);return s.jsx(El.Provider,{value:y,children:e})}function B(e,t,n){function r(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,f=Object.keys(d);for(let u=0;u<f.length;u++){const m=f[u];m in c||(c[m]=d[m].bind(c))}}const o=n?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=n?.Parent?new a:this;r(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const f of d._zod.deferred)f();return d}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Wn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Al extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Pl={};function kn(e){return Pl}function Il(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function Vo(e,t){return typeof t=="bigint"?t.toString():t}function va(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ya(e){return e==null}function ba(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function vh(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=n>o?n:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const Di=Symbol("evaluating");function _e(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Di)return r===void 0&&(r=Di,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function In(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function un(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function $i(e){return JSON.stringify(e)}function yh(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Tl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ms(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const bh=va(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function jr(e){if(ms(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(ms(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Rl(e){return jr(e)?{...e}:Array.isArray(e)?[...e]:e}const wh=new Set(["string","number","symbol"]);function Zn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function ce(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 _h(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const kh={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 jh(e,t){const n=e._zod.def,r=n.checks;if(r&&r.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 n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=n.shape[c])}return In(this,"shape",i),i},checks:[]});return fn(e,a)}function Sh(e,t){const n=e._zod.def,r=n.checks;if(r&&r.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 n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return In(this,"shape",i),i},checks:[]});return fn(e,a)}function Ch(e,t){if(!jr(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.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 In(this,"shape",a),a}});return fn(e,o)}function Nh(e,t){if(!jr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=un(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return In(this,"shape",r),r}});return fn(e,n)}function Eh(e,t){const n=un(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return In(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return fn(e,n)}function Ah(e,t,n){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(n)for(const d in n){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);n[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 In(this,"shape",l),l},checks:[]});return fn(t,i)}function Ph(e,t,n){const r=un(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(n)for(const i in n){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);n[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 In(this,"shape",a),a}});return fn(t,r)}function Vn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Ol(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Wr(e){return typeof e=="string"?e:e?.message}function jn(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=Wr(e.inst?._zod.def?.error?.(e))??Wr(t?.error?.(e))??Wr(n.customError?.(e))??Wr(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function wa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Sr(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const Ml=(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,Vo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ll=B("$ZodError",Ml),Dl=B("$ZodError",Ml,{Parent:Error});function Ih(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Th(e,t=n=>n.message){const n={_errors:[]},r=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>r({issues:i}));else if(a.code==="invalid_key")r({issues:a.issues});else if(a.code==="invalid_element")r({issues:a.issues});else if(a.path.length===0)n._errors.push(t(a));else{let i=n,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 r(e),n}const _a=e=>(t,n,r,o)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new Wn;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>jn(l,a,kn())));throw Tl(c,o?.callee),c}return i.value},ka=e=>async(t,n,r,o)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,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,kn())));throw Tl(c,o?.callee),c}return i.value},Rs=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new Wn;return a.issues.length?{success:!1,error:new(e??Ll)(a.issues.map(i=>jn(i,o,kn())))}:{success:!0,data:a.value}},Rh=Rs(Dl),Os=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>jn(i,o,kn())))}:{success:!0,data:a.value}},Oh=Os(Dl),Mh=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _a(e)(t,n,o)},Lh=e=>(t,n,r)=>_a(e)(t,n,r),Dh=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ka(e)(t,n,o)},$h=e=>async(t,n,r)=>ka(e)(t,n,r),zh=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Rs(e)(t,n,o)},Fh=e=>(t,n,r)=>Rs(e)(t,n,r),Bh=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Os(e)(t,n,o)},Uh=e=>async(t,n,r)=>Os(e)(t,n,r),Vh=/^[cC][^\s-]{8,}$/,Wh=/^[0-9a-z]+$/,qh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Hh=/^[0-9a-vA-V]{20}$/,Zh=/^[A-Za-z0-9]{27}$/,Gh=/^[a-zA-Z0-9_-]{21}$/,Yh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Qh=/^([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})$/,zi=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)$/,Kh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Jh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Xh(){return new RegExp(Jh,"u")}const eg=/^(?:(?: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])$/,tg=/^(([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}|:))$/,ng=/^((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])$/,rg=/^(([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])$/,sg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$l=/^[A-Za-z0-9_-]*$/,og=/^\+[1-9]\d{6,14}$/,zl="(?:(?:\\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])))",ag=new RegExp(`^${zl}$`);function Fl(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 ig(e){return new RegExp(`^${Fl(e)}$`)}function cg(e){const t=Fl({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${zl}T(?:${r})$`)}const lg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},dg=/^-?\d+$/,ug=/^-?\d+(?:\.\d+)?$/,fg=/^[^A-Z]*$/,pg=/^[^a-z]*$/,ut=B("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Bl={number:"number",bigint:"bigint",object:"date"},Ul=B("$ZodCheckLessThan",(e,t)=>{ut.init(e,t);const n=Bl[typeof t.value];e._zod.onattach.push(r=>{const o=r._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=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Vl=B("$ZodCheckGreaterThan",(e,t)=>{ut.init(e,t);const n=Bl[typeof t.value];e._zod.onattach.push(r=>{const o=r._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=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),mg=B("$ZodCheckMultipleOf",(e,t)=>{ut.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):vh(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),hg=B("$ZodCheckNumberFormat",(e,t)=>{ut.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,a]=kh[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,n&&(c.pattern=dg)}),e._zod.check=i=>{const c=i.value;if(n){if(!Number.isInteger(c)){i.issues.push({expected:r,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:r,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:r,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})}}),gg=B("$ZodCheckMaxLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ya(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const i=wa(o);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),xg=B("$ZodCheckMinLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ya(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const i=wa(o);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),vg=B("$ZodCheckLengthEquals",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ya(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,a=o.length;if(a===t.length)return;const i=wa(o),c=a>t.length;r.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Ms=B("$ZodCheckStringFormat",(e,t)=>{var n,r;ut.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?(n=e._zod).check??(n.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})}):(r=e._zod).check??(r.check=()=>{})}),yg=B("$ZodCheckRegex",(e,t)=>{Ms.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),bg=B("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=fg),Ms.init(e,t)}),wg=B("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=pg),Ms.init(e,t)}),_g=B("$ZodCheckIncludes",(e,t)=>{ut.init(e,t);const n=Zn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),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})}}),kg=B("$ZodCheckStartsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`^${Zn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),jg=B("$ZodCheckEndsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`.*${Zn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Sg=B("$ZodCheckOverwrite",(e,t)=>{ut.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Cg{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 r=t.split(`
|
|
1
|
+
"use strict";var jp=Object.create;var Ei=Object.defineProperty;var Sp=Object.getOwnPropertyDescriptor;var Cp=Object.getOwnPropertyNames;var Np=Object.getPrototypeOf,Ep=Object.prototype.hasOwnProperty;var Ap=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Cp(t))!Ep.call(e,o)&&o!==n&&Ei(e,o,{get:()=>t[o],enumerable:!(r=Sp(t,o))||r.enumerable});return e};var Pp=(e,t,n)=>(n=e!=null?jp(Np(e)):{},Ap(t||!e||!e.__esModule?Ei(n,"default",{value:e,enumerable:!0}):n,e));const oe=require("./CedrosContext-C26DlvLF.js"),s=require("react/jsx-runtime"),b=require("react"),Ip=require("@solana/wallet-adapter-react");require("@solana/web3.js");const Ai=require("./index-WcOlBYZJ.js"),Tp=require("@cedros/login-react"),fa=require("react-dom");function nl(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const p=nl(b),Ps=nl(fa);function Rp(e){return!e||!e.coupon_codes?[]:e.coupon_codes.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Op(e,t=", "){return e.join(t)}function Mp(e,t){return e<=0?0:(e-t)/e*100}function Lp(e,t){if(!t||t.length===0)return e;let n=e,r=0;for(const o of t)if(o.discountType==="percentage"){const a=1-o.discountValue/100;n=n*a}else o.discountType==="fixed"&&(r+=o.discountValue);return n=n-r,n<0&&(n=0),Math.ceil(n*100)/100}function rl(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return 1;const n=Math.floor(t);return n>0?n:1}function us(e){return e.map(t=>({resource:t.resource,quantity:rl(t.quantity),variantId:t.variantId,metadata:t.metadata}))}function Mr(e){return e.reduce((t,n)=>t+rl(n.quantity),0)}function Dp(e){return!!(e&&e.length>0&&(e.length>1||e.length===1&&(e[0].quantity??1)>1))}const Un=new Map,Uo=new Map,bn=new Map,fs=1e3,sl=200,pa=2e3;function $p(e){const t=bn.get(e);return t?Date.now()<t?!0:(bn.delete(e),!1):!1}function zp(e,t=sl){const n=Date.now()+t;if(bn.set(e,n),bn.size>fs){const r=Array.from(bn.keys()).slice(0,bn.size-fs);for(const o of r)bn.delete(o)}}function Fp(e,t=pa){const n=Un.get(e);if(!n)return!1;const o=Date.now()-n;return o<t?(oe.getLogger().debug(`[Deduplication] Duplicate request blocked: ${e} (${o}ms ago)`),!0):!1}function Bp(e){if(Un.set(e,Date.now()),Un.size>fs){const t=Array.from(Un.keys()).slice(0,Un.size-fs);for(const n of t)Un.delete(n)}}function Up(e){return Uo.get(e)||null}function Vp(e,t){Uo.set(e,t);const n=()=>{Uo.delete(e),Bp(e)};return t.then(n,n),t}async function Wp(e,t,n={}){const{windowMs:r=pa,throwOnDuplicate:o=!0}=n,a=Up(e);if(a)return oe.getLogger().debug(`[Deduplication] Reusing in-flight request: ${e}`),a;if(Fp(e,r)){if(o)throw new Error(`Duplicate request blocked: ${e}`);oe.getLogger().warn(`[Deduplication] Duplicate request blocked but not throwing: ${e}`);return}const i=t();return Vp(e,i)}function Qn(e,t,n={}){const{cooldownMs:r=sl,deduplicationWindowMs:o=pa}=n;return async()=>{if($p(e)){oe.getLogger().debug(`[Deduplication] Button in cooldown: ${e}`);return}zp(e,r);try{await Wp(e,async()=>{const a=t();a instanceof Promise&&await a},{windowMs:o,throwOnDuplicate:!1})}catch(a){if(a instanceof Error&&a.message.includes("Duplicate request"))return;throw a}}}function ol(e){return{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:e,opacity:.6,padding:"0.25rem",lineHeight:1}}const dn={PAYMENT_START:"cedros:payment:start",WALLET_CONNECT:"cedros:wallet:connect",WALLET_CONNECTED:"cedros:wallet:connected",WALLET_ERROR:"cedros:wallet:error",PAYMENT_PROCESSING:"cedros:payment:processing",PAYMENT_SUCCESS:"cedros:payment:success",PAYMENT_ERROR:"cedros:payment:error"};function An(e,t){if(typeof window>"u")return;const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!1});window.dispatchEvent(n)}function Kn(e,t,n){An(dn.PAYMENT_START,{timestamp:Date.now(),method:e,resource:t,itemCount:n})}function qp(e){An(dn.WALLET_CONNECT,{timestamp:Date.now(),wallet:e})}function Hp(e,t){An(dn.WALLET_CONNECTED,{timestamp:Date.now(),wallet:e,publicKey:t})}function Zp(e,t){An(dn.WALLET_ERROR,{timestamp:Date.now(),wallet:t,error:e})}function Jn(e,t,n){An(dn.PAYMENT_PROCESSING,{timestamp:Date.now(),method:e,resource:t,itemCount:n})}function Xn(e,t,n,r){An(dn.PAYMENT_SUCCESS,{timestamp:Date.now(),method:e,transactionId:t,resource:n,itemCount:r})}function Bt(e,t,n,r){An(dn.PAYMENT_ERROR,{timestamp:Date.now(),method:e,error:t,resource:n,itemCount:r})}function Gp(e){return e instanceof oe.PaymentError&&e.canRetry()}function Yp(e){return e instanceof oe.PaymentError?e.getUserMessage():e instanceof Error?e.message:String(e)}function Qp(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 Kp(e){try{const t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e}}function al(e={}){const{solanaCluster:t="mainnet-beta",solanaEndpoint:n,customRpcProviders:r=[],allowUnsafeScripts:o=!1,additionalScriptSrc:a=[],additionalConnectSrc:i=[],additionalFrameSrc:c=[],includeStripe:l=!0,includeSolana:d=!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 f=["'self'"];o&&f.push("'unsafe-inline'","'unsafe-eval'"),l&&f.push("https://js.stripe.com"),f.push(...a);const u=["'self'"];if(l&&u.push("https://api.stripe.com","https://*.stripe.com"),d){const h=Qp(t);if(u.push(h),n){const v=Kp(n);u.includes(v)||u.push(v)}r.forEach(v=>{u.includes(v)||u.push(v)})}u.push(...i);const m=["'self'"];return l&&m.push("https://js.stripe.com","https://checkout.stripe.com"),m.push(...c),{scriptSrc:f,connectSrc:u,frameSrc:m}}function il(e,t="header"){const{scriptSrc:n,connectSrc:r,frameSrc:o}=e;switch(t){case"header":case"meta":case"nextjs":case"nginx":{const a=[];return n.length>0&&a.push(`script-src ${n.join(" ")}`),r.length>0&&a.push(`connect-src ${r.join(" ")}`),o.length>0&&a.push(`frame-src ${o.join(" ")}`),a.join("; ")}case"helmet":{const a={};return n.length>0&&(a.scriptSrc=n),r.length>0&&(a.connectSrc=r),o.length>0&&(a.frameSrc=o),a}case"directives":return{scriptSrc:n,connectSrc:r,frameSrc:o};default:throw new Error(`Unknown CSP format: ${t}`)}}function Jp(e={},t="header"){const n=al(e);return il(n,t)}const Xp={HELIUS:"https://*.helius-rpc.com",QUICKNODE:"https://*.quicknode.pro",ALCHEMY:"https://*.alchemy.com",ANKR:"https://rpc.ankr.com",TRITON:"https://*.rpcpool.com"},em={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:()=>({includeStripe:!0,includeSolana:!1})};function br(e){return new Date(e).toLocaleString()}function Is(){const{stripeManager:e}=oe.useCedrosContext(),[t,n]=b.useState({status:"idle",error:null,transactionId:null}),r=b.useRef(!1),o=b.useCallback(async(c,l,d,f,u,m)=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n({status:"loading",error:null,transactionId:null});const h={resource:c,successUrl:l,cancelUrl:d,metadata:f,customerEmail:u,couponCode:m};try{const v=await e.processPayment(h);return n({status:v.success?"success":"error",error:v.success?null:v.error||"Payment failed",transactionId:v.success&&v.transactionId||null}),v}catch(v){const x=v instanceof Error?v.message:"Payment failed";return n({status:"error",error:x,transactionId:null}),{success:!1,error:x}}finally{r.current=!1}},[e]),a=b.useCallback(async(c,l,d,f,u,m,h,v,x,g,y,k,_)=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n({status:"loading",error:null,transactionId:null});const w=us(c);try{const j=await e.processCartCheckout({items:w,successUrl:l,cancelUrl:d,metadata:f,customerEmail:u,customerName:h,customerPhone:v,shippingAddress:x,billingAddress:g,couponCode:m,tipAmount:y,shippingMethodId:k,paymentMethodId:_});return n({status:j.success?"success":"error",error:j.success?null:j.error||"Cart checkout failed",transactionId:j.success&&j.transactionId||null}),j}catch(j){const P=j instanceof Error?j.message:"Cart checkout failed";return n({status:"error",error:P,transactionId:null}),{success:!1,error:P}}finally{r.current=!1}},[e]),i=b.useCallback(()=>{n({status:"idle",error:null,transactionId:null}),r.current=!1},[]);return{...t,processPayment:o,processCartCheckout:a,reset:i}}function Lr(e,t){return b.useMemo(()=>{const n=Dp(t),r=e||(t?.length===1?t[0].resource:"");return{isCartMode:n,effectiveResource:r}},[e,t])}const tm=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((o,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},xo=new Map;let Vr=null;async function Pi(e){if(xo.has(e))return xo.get(e);try{const t=await tm(Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),`./translations/${e}.json`,3),n=t.default||t;return xo.set(e,n),n}catch{return null}}async function nm(){if(Vr)return Vr;const e=Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),t=[];for(const n in e){const r=n.match(/\.\/translations\/([a-z]{2,3}(?:-[A-Z]{2})?)\.json$/);r&&t.push(r[1])}return Vr=t.length>0?t:["en"],Vr}function cl(){return typeof navigator>"u"?"en":(navigator.language||navigator.userLanguage||"en").split("-")[0].toLowerCase()}async function ll(e){let t=await Pi(e);if(t||(t=await Pi("en"),t))return t;throw new Error("Critical: No translation files found, not even en.json")}function dl(e){return(t,n)=>{const r=t.split(".");let o=e;for(const a of r)if(o&&typeof o=="object"&&a in o)o=o[a];else return t;return typeof o!="string"?t:n?Object.entries(n).reduce((a,[i,c])=>a.replace(new RegExp(`\\{${i}\\}`,"g"),c),o):o}}function rm(e,t,n=!0){const r=t.errors[e];if(!r){const o=oe.getUserFriendlyError(e);return n&&o.action?`${o.message} ${o.action}`:o.message}return n&&r.action?`${r.message} ${r.action}`:r.message}function Pn(e){const[t,n]=b.useState(null),[r,o]=b.useState(!0),a=b.useMemo(()=>e||cl(),[e]);return b.useEffect(()=>{let c=!1;return(async()=>{o(!0);try{const d=await ll(a);c||(n(d),o(!1))}catch(d){console.error("[CedrosPay] Failed to load translations:",d),c||o(!1)}})(),()=>{c=!0}},[a]),{t:b.useMemo(()=>t?dl(t):c=>({"ui.purchase":"Purchase","ui.pay_with_card":"Pay with Card","ui.pay_with_crypto":"Pay with USDC","ui.pay_with_usdc":"Pay with USDC","ui.card":"Card","ui.usdc_solana":"USDC (Solana)","ui.crypto":"Crypto","ui.processing":"Processing...","ui.loading":"Loading...","ui.connect_wallet":"Connect Wallet","ui.connecting":"Connecting..."})[c]||c,[t]),locale:a,isLoading:r,translations:t}}function sm(e,t=!0){const{translations:n}=Pn();if(!n){const o=oe.getUserFriendlyError(e);return t&&o.action?`${o.message} ${o.action}`:o.message}const r=n.errors[e];if(!r){const o=oe.getUserFriendlyError(e);return t&&o.action?`${o.message} ${o.action}`:o.message}return t&&r.action?`${r.message} ${r.action}`:r.message}function ma({resource:e,items:t,successUrl:n,cancelUrl:r,metadata:o,customerEmail:a,couponCode:i,label:c,disabled:l=!1,onAttempt:d,onSuccess:f,onError:u,className:m=""}){const{status:h,error:v,transactionId:x,processPayment:g,processCartCheckout:y}=Is(),k=oe.useCedrosTheme(),{isCartMode:_,effectiveResource:w}=Lr(e,t),{t:j,translations:P}=Pn(),T=c||j("ui.pay_with_card"),N=k.unstyled?m:`${k.className} cedros-theme__stripe-button ${m}`.trim(),A=v&&typeof v!="string"?v?.code??null:null,I=v?typeof v=="string"?v:(S=>{if(!S||!P)return"";const C=P.errors[S];return C?C.action?`${C.message} ${C.action}`:C.message:""})(A):null,M=b.useCallback(async()=>{oe.getLogger().debug("[StripeButton] executePayment with couponCode:",i);const S=_&&t?Mr(t):void 0;if(Kn("stripe",w,S),d&&d("stripe"),!_&&!w){const W="Invalid payment configuration: missing resource or items";oe.getLogger().error("[StripeButton]",W),Bt("stripe",W,w,S),u&&u(W);return}let C;Jn("stripe",w,S),_&&t?(oe.getLogger().debug("[StripeButton] Processing cart checkout with coupon:",i),C=await y(t,n,r,o,a,i)):w&&(oe.getLogger().debug("[StripeButton] Processing single payment with coupon:",i),C=await g(w,n,r,o,a,i)),C&&C.success&&C.transactionId?(Xn("stripe",C.transactionId,w,S),f&&f(C.transactionId)):C&&!C.success&&C.error&&(Bt("stripe",C.error,w,S),u&&u(C.error))},[i,_,w,t,n,r,o,a,y,g,d,f,u]),z=b.useMemo(()=>_&&t?`stripe-cart-${t.map(S=>S.resource).join("-")}`:`stripe-${w||"unknown"}`,[_,t,w]),D=b.useMemo(()=>Qn(z,M),[z,M]),V=h==="loading",L=l||V;return s.jsxs("div",{className:N,style:k.unstyled?{}:k.style,children:[s.jsx("button",{onClick:D,disabled:L,className:k.unstyled?m:"cedros-theme__button cedros-theme__stripe",type:"button",children:V?j("ui.processing"):T}),I&&s.jsx("div",{className:k.unstyled?"":"cedros-theme__error",children:I}),x&&s.jsx("div",{className:k.unstyled?"":"cedros-theme__success",children:j("ui.payment_successful")})]})}function ul(){const{creditsManager:e}=oe.useCedrosContext(),[t,n]=b.useState({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),r=b.useRef(!1),o=b.useCallback(async(d,f)=>{n(u=>({...u,status:"loading",error:null}));try{const u=await e.requestQuote(d,f);return n(m=>({...m,status:"idle",requirement:u})),u}catch(u){const m=u instanceof Error?u.message:"Failed to fetch credits quote";return n(h=>({...h,status:"error",error:m})),null}},[e]),a=b.useCallback(async(d,f)=>{n(u=>({...u,status:"loading",error:null}));try{const u=us(d),m=await e.requestCartQuote(u,f);return n(h=>({...h,status:"idle"})),m}catch(u){const m=u instanceof Error?u.message:"Failed to fetch cart credits quote";return n(h=>({...h,status:"error",error:m})),null}},[e]),i=b.useCallback(async(d,f,u,m)=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=await e.processPayment(d,f,u,m);return n({status:h.success?"success":"error",error:h.success?null:h.error||"Credits payment failed",transactionId:h.success&&h.transactionId||null,requirement:null,holdId:null}),h}catch(h){const v=h instanceof Error?h.message:"Credits payment failed";return n({status:"error",error:v,transactionId:null,requirement:null,holdId:null}),{success:!1,error:v}}finally{r.current=!1}},[e]),c=b.useCallback(async(d,f,u,m)=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});let h=null;try{const v=us(d),x=await e.requestCartQuote(v,u);if(!x)return n({status:"error",error:"Credits payment not available for this cart",transactionId:null,requirement:null,holdId:null}),{success:!1,error:"Credits payment not available"};h=(await e.createCartHold({cartId:x.cartId,authToken:f})).holdId,n(k=>({...k,holdId:h}));const y=await e.authorizeCartPayment({cartId:x.cartId,holdId:h,authToken:f,metadata:m});if(!y.success&&h)try{await e.releaseHold(h,f)}catch(k){oe.getLogger().warn("[useCreditsPayment] Hold release failed, will expire server-side",{holdId:h,error:k instanceof Error?k.message:String(k)})}return n({status:y.success?"success":"error",error:y.success?null:y.error||"Cart credits payment failed",transactionId:y.success&&y.transactionId||null,requirement:null,holdId:null}),{success:y.success,transactionId:y.transactionId,error:y.error}}catch(v){const x=v instanceof Error?v.message:"Cart credits payment failed";if(h)try{await e.releaseHold(h,f)}catch(g){oe.getLogger().warn("[useCreditsPayment] Hold release failed, will expire server-side",{holdId:h,error:g instanceof Error?g.message:String(g)})}return n({status:"error",error:x,transactionId:null,requirement:null,holdId:null}),{success:!1,error:x}}finally{r.current=!1}},[e]),l=b.useCallback(()=>{n({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),r.current=!1},[]);return{...t,fetchQuote:o,fetchCartQuote:a,processPayment:i,processCartPayment:c,reset:l}}function ha({resource:e,items:t,authToken:n,metadata:r,couponCode:o,label:a,disabled:i=!1,onAttempt:c,onSuccess:l,onError:d,className:f=""}){const{status:u,error:m,transactionId:h,processPayment:v,processCartPayment:x}=ul(),g=oe.useCedrosTheme(),{isCartMode:y,effectiveResource:k}=Lr(e,t),{t:_,translations:w}=Pn(),j=a||_("ui.pay_with_credits")||"Pay with Credits",P=g.unstyled?f:`${g.className} cedros-theme__credits-button ${f}`.trim(),T=m&&typeof m!="string"?m?.code??null:null,A=m?typeof m=="string"?m:(V=>{if(!V||!w)return"";const L=w.errors[V];return L?L.action?`${L.message} ${L.action}`:L.message:""})(T):null,R=b.useCallback(async()=>{oe.getLogger().debug("[CreditsButton] executePayment");const V=y&&t?Mr(t):void 0;if(Kn("credits",k,V),c&&c("credits"),!n){const S="Authentication required: please log in to pay with credits";oe.getLogger().error("[CreditsButton]",S),Bt("credits",S,k,V),d&&d(S);return}if(!y&&!k){const S="Invalid payment configuration: missing resource";oe.getLogger().error("[CreditsButton]",S),Bt("credits",S,k,V),d&&d(S);return}let L;Jn("credits",k,V),y&&t?(oe.getLogger().debug("[CreditsButton] Processing cart checkout"),L=await x(t,n,o,r)):k&&(oe.getLogger().debug("[CreditsButton] Processing single payment"),L=await v(k,n,o,r)),L&&L.success&&L.transactionId?(Xn("credits",L.transactionId,k,V),l&&l(L.transactionId)):L&&!L.success&&L.error&&(Bt("credits",L.error,k,V),d&&d(L.error))},[n,y,k,t,o,r,v,x,c,l,d]),I=b.useMemo(()=>y&&t?`credits-cart-${t.map(V=>V.resource).join("-")}`:`credits-${k||"unknown"}`,[y,t,k]),M=b.useMemo(()=>Qn(I,R),[I,R]),z=u==="loading",D=i||z;return s.jsxs("div",{className:P,style:g.unstyled?{}:g.style,children:[s.jsx("button",{onClick:M,disabled:D,className:g.unstyled?f:"cedros-theme__button cedros-theme__credits",type:"button",children:z?_("ui.processing"):j}),A&&s.jsx("div",{className:g.unstyled?"":"cedros-theme__error",children:A}),h&&s.jsx("div",{className:g.unstyled?"":"cedros-theme__success",children:_("ui.payment_successful")})]})}const om=b.lazy(()=>Promise.resolve().then(()=>require("./CryptoButton-N8kRfNDO.js")).then(e=>e.CryptoButton$1).then(e=>({default:e.CryptoButton}))),fl=({isOpen:e,onClose:t,resource:n,items:r,cardLabel:o="Card",cryptoLabel:a="USDC (Solana)",creditsLabel:i="Pay with Credits",showCard:c=!0,showCrypto:l=!0,showCredits:d=!1,onPaymentAttempt:f,onPaymentSuccess:u,onPaymentError:m,onStripeSuccess:h,onCryptoSuccess:v,onCreditsSuccess:x,onStripeError:g,onCryptoError:y,onCreditsError:k,customerEmail:_,successUrl:w,cancelUrl:j,metadata:P,couponCode:T,authToken:N,testPageUrl:A,hideMessages:R=!1})=>{const{tokens:I}=oe.useCedrosTheme();return b.useEffect(()=>{const M=z=>{z.key==="Escape"&&e&&t()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e,t]),b.useEffect(()=>{if(e){const M=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${M}px`,document.body.style.width="100%",document.body.style.overflowY="scroll",()=>{const z=document.body.style.top?Math.abs(parseInt(document.body.style.top.replace("px",""),10)):0;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflowY="",window.scrollTo(0,z)}}},[e]),e?s.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:I.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:t,children:s.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:I.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 ${I.modalBorder}`},onClick:M=>M.stopPropagation(),children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[s.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:I.surfaceText},children:"Choose Payment Method"}),s.jsx("button",{type:"button",onClick:t,style:ol(I.surfaceText),"aria-label":"Close modal",children:"×"})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[c&&s.jsx(ma,{resource:n,items:r,label:o,onAttempt:f,onSuccess:h||u,onError:g||m,customerEmail:_,successUrl:w,cancelUrl:j,metadata:P,couponCode:T}),l&&s.jsx(b.Suspense,{fallback:null,children:s.jsx(om,{resource:n,items:r,label:a,onAttempt:f,onSuccess:v||u,onError:y||m,testPageUrl:A,hideMessages:R,metadata:P,couponCode:T})}),d&&s.jsx(ha,{resource:n,items:r,label:i,authToken:N,onAttempt:f?()=>f("credits"):void 0,onSuccess:x||u,onError:k||m,metadata:P,couponCode:T})]})]})}):null},pl=({resource:e,items:t,label:n,cardLabel:r,cryptoLabel:o,creditsLabel:a,showCard:i=!0,showCrypto:c=!0,showCredits:l=!1,onPaymentAttempt:d,onPaymentSuccess:f,onPaymentError:u,onStripeSuccess:m,onCryptoSuccess:h,onCreditsSuccess:v,onStripeError:x,onCryptoError:g,onCreditsError:y,customerEmail:k,successUrl:_,cancelUrl:w,metadata:j,couponCode:P,authToken:T,autoDetectWallets:N=!0,testPageUrl:A,hideMessages:R=!1,renderModal:I})=>{const M=oe.useCedrosTheme(),[z,D]=b.useState(!1),{status:V,processPayment:L,processCartCheckout:S}=Is(),{isCartMode:C,effectiveResource:W}=Lr(e,t),{t:Z}=Pn(),Q=n||Z("ui.purchase"),de=r||Z("ui.card"),q=o||Z("ui.usdc_solana"),K=a||Z("ui.pay_with_credits")||"Pay with Credits",Y=b.useCallback(async()=>{if(N&&i){const{detectSolanaWallets:U}=await Promise.resolve().then(()=>require("./walletDetection-bNmV5ItZ.js"));if(!U()){const se=C?void 0:W,le=C&&t?Mr(t):void 0;Kn("stripe",se,le),d&&d("stripe"),Jn("stripe",se,le);let ue;C&&t?ue=await S(t,_,w,j,k,P):W&&(ue=await L(W,_,w,j,k,P)),ue&&ue.success&&ue.transactionId?(Xn("stripe",ue.transactionId,se,le),m?m(ue.transactionId):f&&f(ue.transactionId)):ue&&!ue.success&&ue.error&&(Bt("stripe",ue.error,se,le),x?x(ue.error):u&&u(ue.error));return}}D(!0)},[N,i,C,t,W,S,L,_,w,j,k,P,f,u,m,x,d]),me=b.useMemo(()=>C&&t?`purchase-cart-${t.map(U=>U.resource).join("-")}`:`purchase-${W||"unknown"}`,[C,t,W]),$=b.useMemo(()=>Qn(me,Y),[me,Y]),G=V==="loading",pe={isOpen:z,onClose:()=>D(!1),resource:C?void 0:W,items:C?t:void 0,cardLabel:de,cryptoLabel:q,creditsLabel:K,showCard:i,showCrypto:c,showCredits:l,onPaymentAttempt:d,onPaymentSuccess:U=>{D(!1),f?.(U)},onPaymentError:U=>{D(!1),u?.(U)},onStripeSuccess:U=>{D(!1),m?.(U)},onCryptoSuccess:U=>{D(!1),h?.(U)},onCreditsSuccess:U=>{D(!1),v?.(U)},onStripeError:U=>{D(!1),x?.(U)},onCryptoError:U=>{D(!1),g?.(U)},onCreditsError:U=>{D(!1),y?.(U)},customerEmail:k,successUrl:_,cancelUrl:w,metadata:j,couponCode:P,authToken:T,testPageUrl:A,hideMessages:R};return s.jsxs("div",{className:M.unstyled?"":M.className,style:M.unstyled?{}:M.style,children:[s.jsx("button",{onClick:$,disabled:G,className:M.unstyled?"":"cedros-theme__button cedros-theme__stripe",style:{width:"100%",cursor:G?"not-allowed":"pointer",opacity:G?.6:1},type:"button",children:G?Z("ui.processing"):Q}),I?I(pe):s.jsx(fl,{...pe})]})},am={"mainnet-beta":"https://api.mainnet-beta.solana.com",devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com"};function im(){const[e,t]=b.useState(null);return b.useEffect(()=>{let n=!1;return import("@solana/wallet-adapter-react").then(r=>{n||t(r)}),()=>{n=!0}},[]),e}function cm({endpoint:e,wallets:t,children:n}){const r=im();if(!r)return s.jsx(s.Fragment,{children:n});const{ConnectionProvider:o,WalletProvider:a}=r;return s.jsx(o,{endpoint:e,children:s.jsx(a,{wallets:t,autoConnect:!1,children:n})})}const lm=b.lazy(()=>Promise.resolve().then(()=>require("./CryptoButton-N8kRfNDO.js")).then(e=>e.CryptoButton$1).then(e=>({default:e.CryptoButton})));function dm(e){const{resource:t,items:n,checkout:r={},display:o={},callbacks:a={},advanced:i={}}=e,{config:c,walletPool:l}=oe.useCedrosContext(),d=oe.useCedrosTheme(),{isCartMode:f}=Lr(t,n),u=o.showCrypto??!0,m=b.useMemo(()=>({marginTop:"0.5rem",fontSize:"0.875rem",color:d.tokens.surfaceText,opacity:.7,textAlign:"center"}),[d.tokens.surfaceText]),h=b.useMemo(()=>u?i.wallets&&i.wallets.length>0?i.wallets:l.getAdapters():[],[i.wallets,l,u]),v=b.useMemo(()=>n?Mr(n):0,[n]),{onPaymentSuccess:x,onPaymentError:g,onPaymentAttempt:y}=a,k=b.useCallback(S=>x?.({transactionId:S,method:"stripe"}),[x]),_=b.useCallback(S=>x?.({transactionId:S,method:"crypto"}),[x]),w=b.useCallback(S=>g?.({message:S,method:"stripe"}),[g]),j=b.useCallback(S=>g?.({message:S,method:"crypto"}),[g]),P=b.useCallback(S=>x?.({transactionId:S,method:"credits"}),[x]),T=b.useCallback(S=>g?.({message:S,method:"credits"}),[g]),N=b.useCallback(()=>y?.("credits"),[y]),A=u?c.solanaEndpoint??am[c.solanaCluster]:"";if(!t&&(!n||n.length===0))return oe.getLogger().error('CedrosPay: Must provide either "resource" or "items" prop'),s.jsx("div",{className:o.className,style:{color:d.tokens.errorText},children:"Configuration error: No resource or items provided"});const R=o.showCard??!0,I=o.showCredits??!1,M=o.showPurchaseButton??!1,z=o.layout??"vertical",D=o.hideMessages??!1,V=i.autoDetectWallets??!0,L=s.jsx("div",{className:d.unstyled?o.className:`cedros-theme__pay ${o.className||""}`,children:s.jsxs("div",{className:d.unstyled?"":`cedros-theme__pay-content cedros-theme__pay-content--${z}`,children:[M?s.jsx(pl,{resource:f?void 0:t||n?.[0]?.resource,items:f?n:void 0,label:o.purchaseLabel,cardLabel:o.cardLabel,cryptoLabel:o.cryptoLabel,showCard:R,showCrypto:u,onPaymentAttempt:a.onPaymentAttempt,onPaymentSuccess:k,onPaymentError:w,onStripeSuccess:k,onCryptoSuccess:_,onStripeError:w,onCryptoError:j,customerEmail:r.customerEmail,successUrl:r.successUrl,cancelUrl:r.cancelUrl,metadata:r.metadata,couponCode:r.couponCode,autoDetectWallets:V,testPageUrl:i.testPageUrl,hideMessages:D,renderModal:o.renderModal}):s.jsxs(s.Fragment,{children:[R&&s.jsx(ma,{resource:f?void 0:t||n?.[0]?.resource,items:f?n:void 0,customerEmail:r.customerEmail,successUrl:r.successUrl,cancelUrl:r.cancelUrl,metadata:r.metadata,couponCode:r.couponCode,label:o.cardLabel,onAttempt:a.onPaymentAttempt,onSuccess:k,onError:w}),u&&s.jsx(b.Suspense,{fallback:null,children:s.jsx(lm,{resource:f?void 0:t||n?.[0]?.resource,items:f?n:void 0,metadata:r.metadata,couponCode:r.couponCode,label:o.cryptoLabel,onAttempt:a.onPaymentAttempt,onSuccess:_,onError:j,testPageUrl:i.testPageUrl,hideMessages:D})}),I&&s.jsx(ha,{resource:f?void 0:t||n?.[0]?.resource,items:f?n:void 0,authToken:r.authToken,metadata:r.metadata,couponCode:r.couponCode,label:o.creditsLabel,onAttempt:N,onSuccess:P,onError:T})]}),f&&n&&n.length>1&&!D&&s.jsxs("div",{style:m,children:["Checking out ",v," items"]})]})});return s.jsx("div",{className:d.unstyled?o.className:d.className,style:d.unstyled?{}:d.style,children:s.jsx(cm,{endpoint:A||"https://api.devnet.solana.com",wallets:h,children:L})})}const J={products:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),s.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),s.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),s.jsx("path",{d:"M3 3v5h5"}),s.jsx("path",{d:"M12 7v5l4 2"})]}),settings:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:s.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:s.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),s.jsx("path",{d:"M21 3v5h-5"}),s.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),s.jsx("path",{d:"M8 16H3v5"})]}),check:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.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:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),s.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"}),s.jsx("path",{d:"M12 3v6"})]}),arrowUp:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"m5 12 7-7 7 7"}),s.jsx("path",{d:"M12 19V5"})]}),arrowDown:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"m5 12 7 7 7-7"}),s.jsx("path",{d:"M12 5v14"})]}),delete:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),s.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:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("path",{d:"M12 17h.01"})]}),chat:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),s.jsx("path",{d:"M2 12h20"})]}),ai:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),s.jsx("path",{d:"M10 10v.5"}),s.jsx("path",{d:"M14 10v.5"}),s.jsx("path",{d:"M12 14v2"}),s.jsx("path",{d:"M8 18h8"}),s.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),s.jsx("path",{d:"M6 12v6"}),s.jsx("path",{d:"M18 12v6"})]}),notifications:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),s.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),s.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"}),s.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"}),s.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),s.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),s.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),s.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),s.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),s.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),s.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),s.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),s.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),s.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.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"}),s.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"}),s.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),s.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),s.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),s.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),s.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),s.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),s.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function Dr({message:e,onRetry:t}){return e?s.jsxs("div",{className:"cedros-admin__error-banner",children:[s.jsx("span",{children:e}),t&&s.jsxs("button",{type:"button",className:"cedros-admin__error-banner-retry",onClick:t,children:[J.refresh," Retry"]})]}):null}function $r({stats:e,isLoading:t=!1,onRefresh:n}){return s.jsxs("div",{className:"cedros-admin__stats-bar",children:[s.jsx("div",{className:"cedros-admin__stats-bar-grid",children:e.map((r,o)=>s.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[s.jsx("span",{className:"cedros-admin__stats-bar-label",children:r.label}),s.jsx("span",{className:`cedros-admin__stats-bar-value ${r.variant?`cedros-admin__stats-bar-value--${r.variant}`:""}`,children:t?s.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):r.value}),r.description&&s.jsx("span",{className:"cedros-admin__stats-bar-desc",children:r.description})]},o))}),n&&s.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:n,disabled:t,title:"Refresh stats",children:t?J.loading:J.refresh})]})}function um({serverUrl:e,productId:t,apiKey:n,authManager:r}){const[o,a]=b.useState(null),[i,c]=b.useState(!1),[l,d]=b.useState(!1),[f,u]=b.useState(null),m=b.useCallback(async()=>{if(t){c(!0),u(null);try{let x;if(r?.isAuthenticated())x=await r.fetchWithAuth(`/admin/products/${t}/variations`);else{const g={"Content-Type":"application/json"};n&&(g["X-API-Key"]=n);const y=await fetch(`${e}/admin/products/${t}/variations`,{headers:g});if(!y.ok)throw new Error(`Failed to fetch variations: ${y.status}`);x=await y.json()}x.variationConfig||(x.variationConfig={variationTypes:[]}),x.variants||(x.variants=[]),a(x)}catch(x){const g=x instanceof Error?x.message:"Failed to fetch variations";u(g),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,n,r]),h=b.useCallback(async x=>{if(!t)return null;d(!0),u(null);try{let g;if(r?.isAuthenticated())g=await r.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(x)});else{const y={"Content-Type":"application/json"};n&&(y["X-API-Key"]=n);const k=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:y,body:JSON.stringify(x)});if(!k.ok)throw new Error(`Failed to save variations: ${k.status}`);g=await k.json()}return a({productId:t,variationConfig:g.variationConfig,variants:g.variants}),{variantsCreated:g.variantsCreated}}catch(g){const y=g instanceof Error?g.message:"Failed to save variations";return u(y),null}finally{d(!1)}},[e,t,n,r]),v=b.useCallback(async x=>{if(!t||x.length===0)return!1;d(!0),u(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/products/${t}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:x})});else{const g={"Content-Type":"application/json"};n&&(g["X-API-Key"]=n);const y=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:g,body:JSON.stringify({updates:x})});if(!y.ok)throw new Error(`Failed to update inventory: ${y.status}`)}if(o){const g=new Map(x.map(y=>[y.variantId,y]));a({...o,variants:o.variants.map(y=>{const k=g.get(y.id);return k?{...y,inventoryQuantity:k.inventoryQuantity,inventoryStatus:k.inventoryStatus??y.inventoryStatus}:y})})}return!0}catch(g){const y=g instanceof Error?g.message:"Failed to update inventory";return u(y),!1}finally{d(!1)}},[e,t,n,r,o]);return{data:o,isLoading:i,error:f,fetch:m,save:h,bulkUpdateInventory:v,isSaving:l}}function Ii(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function fm({value:e,onChange:t,maxTypes:n=5,maxValuesPerType:r=20,disabled:o=!1}){const[a,i]=b.useState(null),[c,l]=b.useState(""),[d,f]=b.useState({}),u=e.variationTypes,m=b.useCallback(()=>{if(!c.trim()||u.length>=n)return;const _={id:Ii(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,_]}),l(""),i(_.id)},[c,u,n,t]),h=b.useCallback(_=>{t({variationTypes:u.filter(w=>w.id!==_).map((w,j)=>({...w,displayOrder:j}))}),a===_&&i(null)},[u,t,a]),v=b.useCallback((_,w)=>{t({variationTypes:u.map(j=>j.id===_?{...j,name:w}:j)})},[u,t]),x=b.useCallback((_,w)=>{const j=u.findIndex(N=>N.id===_);if(j===-1||w==="up"&&j===0||w==="down"&&j===u.length-1)return;const P=[...u],T=w==="up"?j-1:j+1;[P[j],P[T]]=[P[T],P[j]],t({variationTypes:P.map((N,A)=>({...N,displayOrder:A}))})},[u,t]),g=b.useCallback(_=>{const w=(d[_]||"").trim();if(!w)return;const j=u.find(T=>T.id===_);if(!j||j.values.length>=r)return;const P={id:Ii(),label:w};t({variationTypes:u.map(T=>T.id===_?{...T,values:[...T.values,P]}:T)}),f(T=>({...T,[_]:""}))},[u,d,r,t]),y=b.useCallback((_,w)=>{t({variationTypes:u.map(j=>j.id===_?{...j,values:j.values.filter(P=>P.id!==w)}:j)})},[u,t]),k=b.useCallback((_,w,j)=>{t({variationTypes:u.map(P=>P.id===_?{...P,values:P.values.map(T=>T.id===w?{...T,label:j}:T)}:P)})},[u,t]);return s.jsxs("div",{className:"cedros-admin__variation-editor",children:[s.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[s.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),s.jsxs("span",{style:{fontSize:12,opacity:.7},children:[u.length,"/",n," types"]})]}),u.length===0?s.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):s.jsx("div",{className:"cedros-admin__variation-type-list",children:u.map((_,w)=>s.jsxs("div",{className:"cedros-admin__variation-type-item",children:[s.jsxs("div",{className:"cedros-admin__variation-type-header",children:[s.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>x(_.id,"up"),disabled:o||w===0,title:"Move up",children:J.arrowUp}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>x(_.id,"down"),disabled:o||w===u.length-1,title:"Move down",children:J.arrowDown})]}),s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:_.name,onChange:j=>v(_.id,j.target.value),disabled:o,placeholder:"Type name"}),s.jsxs("span",{className:"cedros-admin__variation-value-count",children:[_.values.length," values"]}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===_.id?null:_.id),children:a===_.id?"Collapse":"Edit values"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>h(_.id),disabled:o,title:"Remove type",children:J.delete})]}),a===_.id&&s.jsxs("div",{className:"cedros-admin__variation-values",children:[s.jsxs("div",{className:"cedros-admin__variation-values-header",children:[s.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',_.name,'"']}),s.jsxs("span",{style:{fontSize:11,opacity:.7},children:[_.values.length,"/",r]})]}),_.values.length===0?s.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):s.jsx("div",{className:"cedros-admin__variation-value-list",children:_.values.map(j=>s.jsxs("div",{className:"cedros-admin__variation-value-item",children:[s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:j.label,onChange:P=>k(_.id,j.id,P.target.value),disabled:o}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>y(_.id,j.id),disabled:o,title:"Remove value",children:J.close})]},j.id))}),_.values.length<r&&s.jsxs("div",{className:"cedros-admin__variation-add-value",children:[s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:d[_.id]||"",onChange:j=>f(P=>({...P,[_.id]:j.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),g(_.id))}}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>g(_.id),disabled:o||!d[_.id]?.trim(),children:"Add"})]})]})]},_.id))}),u.length<n&&s.jsxs("div",{className:"cedros-admin__variation-add-type",children:[s.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:_=>l(_.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),m())}}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:m,disabled:o||!c.trim(),children:"Add Type"})]})]})}function ml({value:e,onChange:t,options:n,placeholder:r="Filter",disabled:o}){const[a,i]=b.useState(!1),c=b.useRef(null),d=n.find(f=>f.value===e)?.label||r;return b.useEffect(()=>{const f=u=>{c.current&&!c.current.contains(u.target)&&i(!1)};if(a)return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[a]),b.useEffect(()=>{const f=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[a]),s.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[s.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[s.jsx("span",{children:d}),s.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:J.chevronDown})]}),a&&s.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:n.map(f=>s.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${f.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{f.disabled||(t(f.value),i(!1))},role:"option","aria-selected":f.value===e,disabled:f.disabled,children:[f.label,f.value===e&&s.jsx("span",{className:"cedros-admin__dropdown-check",children:J.check})]},f.value))})]})}function At({value:e,onChange:t,options:n,label:r,description:o,disabled:a,className:i,style:c}){const[l,d]=b.useState(!1),f=b.useRef(null),m=n.find(h=>h.value===e)?.label||"Select...";return b.useEffect(()=>{const h=v=>{f.current&&!f.current.contains(v.target)&&d(!1)};if(l)return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[l]),b.useEffect(()=>{const h=v=>{v.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[l]),s.jsxs("div",{className:`cedros-admin__field ${i||""}`,style:c,children:[s.jsx("label",{className:"cedros-admin__field-label",children:r}),s.jsxs("div",{className:"cedros-admin__dropdown cedros-admin__dropdown--form",ref:f,children:[s.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:[s.jsx("span",{children:m}),s.jsx("span",{className:`cedros-admin__dropdown-chevron ${l?"cedros-admin__dropdown-chevron--open":""}`,children:J.chevronDown})]}),l&&s.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:n.map(h=>s.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&&s.jsx("span",{className:"cedros-admin__dropdown-check",children:J.check})]},h.value))})]}),o&&s.jsx("p",{className:"cedros-admin__field-description",children:o})]})}function Ti(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function pm(e){if(e.length===0)return[];const t=[...e].sort((r,o)=>r.displayOrder-o.displayOrder),n=(r,o)=>{if(r>=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[r],i=[];for(const c of a.values)i.push(...n(r+1,{valueIds:[...o.valueIds,c.id],options:{...o.options,[a.name]:c.label}}));return i};return n(0,{valueIds:[],options:{}})}function mm(e){return e.optionValueIds?.length?[...e.optionValueIds].sort().join("|"):Object.entries(e.options).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${t}:${n}`).join("|")}function hm({variationConfig:e,variants:t,onChange:n,defaultPrice:r=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=b.useMemo(()=>pm(e.variationTypes),[e.variationTypes]),l=b.useMemo(()=>{const x=new Map;for(const g of t)x.set(mm(g),g);return x},[t]),{existingRows:d,possibleRows:f}=b.useMemo(()=>{const x=[],g=[];for(const y of c){const k=l.get(y.key);k?x.push({combo:y,variant:k}):g.push(y)}return{existingRows:x,possibleRows:g}},[c,l]),u=b.useCallback((x,g)=>{n(t.map(y=>y.id===x?{...y,...g}:y))},[t,n]),m=b.useCallback(x=>{n(t.filter(g=>g.id!==x))},[t,n]),h=b.useCallback(x=>{if(t.length>=a)return;const g={id:Ti(),title:x.title,options:x.options,optionValueIds:x.optionValueIds,price:r,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};n([...t,g])},[t,n,a,r]),v=b.useCallback(()=>{const x=a-t.length,y=f.slice(0,x).map(k=>({id:Ti(),title:k.title,options:k.options,optionValueIds:k.optionValueIds,price:r,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));n([...t,...y])},[t,n,f,a,r]);return e.variationTypes.length===0?s.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):c.length===0?s.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):s.jsxs("div",{className:"cedros-admin__variant-grid",children:[s.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[s.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),s.jsxs("span",{style:{fontSize:12,opacity:.7},children:[t.length,"/",a," variants (",c.length," ","possible)"]})]}),f.length>0&&t.length<a&&s.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[s.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:v,disabled:i,children:["Generate All (",Math.min(f.length,a-t.length),")"]}),s.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Variant"}),s.jsx("th",{style:{width:100},children:"Price"}),s.jsx("th",{style:{width:80},children:"Qty"}),s.jsx("th",{style:{width:100},children:"SKU"}),s.jsx("th",{style:{width:100},children:"Status"}),s.jsx("th",{style:{width:80},children:"Actions"})]})}),s.jsxs("tbody",{children:[d.map(({combo:x,variant:g})=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{fontWeight:600},children:x.title}),s.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(x.options).map(([y,k])=>`${y}: ${k}`).join(", ")})]})}),s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[s.jsx("span",{children:o}),s.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:g.price??"",onChange:y=>u(g.id,{price:y.target.value===""?void 0:parseFloat(y.target.value)||0}),disabled:i,min:"0",step:"0.01",style:{width:70}})]})}),s.jsx("td",{children:s.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:g.inventoryQuantity??"",onChange:y=>u(g.id,{inventoryQuantity:y.target.value===""?void 0:parseInt(y.target.value)||0}),disabled:i,min:"0",style:{width:60}})}),s.jsx("td",{children:s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:g.sku??"",onChange:y=>u(g.id,{sku:y.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),s.jsx("td",{children:s.jsx(ml,{value:g.inventoryStatus??"in_stock",onChange:y=>u(g.id,{inventoryStatus:y}),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})}),s.jsx("td",{children:s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>m(g.id),disabled:i,title:"Remove variant",children:J.trash})})]},g.id)),f.length>0&&t.length<a&&s.jsxs(s.Fragment,{children:[s.jsx("tr",{className:"cedros-admin__variant-separator",children:s.jsx("td",{colSpan:6,children:s.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",f.length,")"]})})}),f.slice(0,10).map(x=>s.jsxs("tr",{className:"cedros-admin__variant-possible",children:[s.jsx("td",{children:s.jsx("span",{style:{opacity:.6},children:x.title})}),s.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),s.jsx("td",{children:s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>h(x),disabled:i,title:"Create variant",children:J.plus})})]},x.key)),f.length>10&&s.jsx("tr",{className:"cedros-admin__variant-more",children:s.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",f.length-10," more combinations"]})})]})]})]})})]})}function gm({serverUrl:e,productId:t,productTitle:n,defaultPrice:r=0,currencySymbol:o="$",apiKey:a,authManager:i,onClose:c}){const{data:l,isLoading:d,error:f,fetch:u,save:m,isSaving:h}=um({serverUrl:e,productId:t,apiKey:a,authManager:i}),[v,x]=b.useState({variationTypes:[]}),[g,y]=b.useState([]),[k,_]=b.useState(!1),[w,j]=b.useState(!1);b.useEffect(()=>{u()},[u]),b.useEffect(()=>{l&&(x(l.variationConfig),y(l.variants),_(!1))},[l]);const P=b.useCallback(A=>{x(A),_(!0),j(!1)},[]),T=b.useCallback(A=>{y(A),_(!0),j(!1)},[]),N=b.useCallback(async()=>{const A=new Set((l?.variants??[]).map(D=>D.id)),R=g.filter(D=>!A.has(D.id)),I=g.filter(D=>A.has(D.id)),M=(l?.variants??[]).filter(D=>!g.some(V=>V.id===D.id)).map(D=>D.id);await m({variationConfig:v,createVariants:R.map(D=>({optionValueIds:D.optionValueIds??[],inventoryQuantity:D.inventoryQuantity,sku:D.sku,price:D.price})),updateVariants:I.map(D=>({id:D.id,inventoryQuantity:D.inventoryQuantity,sku:D.sku,price:D.price,inventoryStatus:D.inventoryStatus})),deleteVariantIds:M.length>0?M:void 0})&&(_(!1),j(!0),setTimeout(()=>j(!1),3e3))},[v,g,l?.variants,m]);return d?s.jsxs("div",{className:"cedros-admin__variations-editor",children:[s.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:n?`Variations: ${n}`:"Product Variations"}),c&&s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:J.close})]}),s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading variations..."]})]}):s.jsxs("div",{className:"cedros-admin__variations-editor",children:[s.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:n?`Variations: ${n}`:"Product Variations"}),s.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[w&&s.jsxs("span",{className:"cedros-admin__success-text",children:[J.check," Saved"]}),k&&s.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:N,disabled:h||!k,children:h?"Saving...":"Save Changes"}),c&&s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:J.close})]})]}),f&&s.jsx("div",{className:"cedros-admin__error-banner",children:f}),s.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[s.jsx("div",{className:"cedros-admin__variations-editor-section",children:s.jsx(fm,{value:v,onChange:P,disabled:h})}),v.variationTypes.length>0&&s.jsx("div",{className:"cedros-admin__variations-editor-section",children:s.jsx(hm,{variationConfig:v,variants:g,onChange:T,defaultPrice:r,currencySymbol:o,disabled:h})})]})]})}function hl({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=b.useState([]),[i,c]=b.useState(!0),[l,d]=b.useState(!1),[f,u]=b.useState(!1),[m,h]=b.useState(null),[v,x]=b.useState(null),[g,y]=b.useState(null),[k,_]=b.useState(null),[w,j]=b.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:""}),P=S=>{const C=S.tagsCsv.split(",").map(Y=>Y.trim()).filter(Boolean),W=S.categoryIdsCsv.split(",").map(Y=>Y.trim()).filter(Boolean),Z={email:S.checkoutEmail,name:S.checkoutName,phone:S.checkoutPhone,shippingAddress:S.checkoutShippingAddress,billingAddress:S.checkoutBillingAddress},Q=S.fulfillmentType==="shipping"?"physical":"digital",de={title:S.title,slug:S.slug||S.id,shipping_profile:Q,inventory_status:S.inventoryStatus,checkout_requirements:JSON.stringify(Z),fulfillment_type:S.fulfillmentType};S.imageUrl&&(de.image_url=S.imageUrl);const q=S.compareAtUsd?Math.round(Number(S.compareAtUsd)*100):0;q&&(de.compare_at_amount_cents=String(q)),C.length&&(de.tags=JSON.stringify(C)),W.length&&(de.category_ids=JSON.stringify(W)),S.fulfillmentNotes&&(de.fulfillment_notes=S.fulfillmentNotes);const K=S.shippingCountriesCsv.split(",").map(Y=>Y.trim().toUpperCase()).filter(Boolean);return K.length&&(de.shippingCountries=K.join(","),de.shipping_countries=K.join(",")),de},T=S=>S.metadata?.title||S.description||S.id,N=S=>S.metadata?.image_url,A=b.useCallback(async()=>{try{_(null);let S;if(r?.isAuthenticated())S=await r.fetchWithAuth(`/admin/products?limit=${n}`);else{const C={"Content-Type":"application/json"};t&&(C["X-API-Key"]=t);const W=await fetch(`${e}/admin/products?limit=${n}`,{headers:C});if(!W.ok)throw new Error(`Failed to fetch products: ${W.status}`);S=await W.json()}a(S.products||[])}catch{a([]),_("Failed to load products")}finally{c(!1)}},[e,t,n,r]);b.useEffect(()=>{A()},[A]);const R=async S=>{if(S.preventDefault(),!(!w.id||!w.description)){if(h(null),w.fulfillmentType==="shipping"&&w.checkoutShippingAddress&&!w.shippingCountriesCsv.split(",").map(W=>W.trim()).filter(Boolean).length){h("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:C}=w,W=w.inventoryQuantity===""?void 0:Number.isFinite(Number(w.inventoryQuantity))?Number(w.inventoryQuantity):void 0,Z=Number(w.priceUsd)||0,Q=Math.round(Z*100),de=Math.round(Z*1e6),q={id:w.id,description:w.description,fiatAmountCents:Q,fiatCurrency:w.fiatCurrency,cryptoAtomicAmount:de,cryptoToken:w.cryptoToken,...W!==void 0?{inventoryQuantity:W}:{},metadata:{...C?{product_type:C}:{},...P(w)}};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(q)});else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const Y=await fetch(`${e}/admin/products`,{method:"POST",headers:K,body:JSON.stringify(q)});if(!Y.ok)throw new Error(`Failed to create product: ${Y.status}`)}j({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),A()}catch(C){h(C instanceof Error?C.message:"Failed to create product")}finally{u(!1)}}},I=S=>`$${(S/100).toFixed(2)}`,M=S=>{switch(S){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},z=b.useMemo(()=>{const S=o.filter(W=>W.active).length,C=o.reduce((W,Z)=>{const Q=Z.variations?.length??0;return W+(Q>0?Q:1)},0);return{activeCount:S,totalSkus:C}},[o]),D=S=>{y(C=>!C||C.key!==S?{key:S,direction:"asc"}:{key:S,direction:C.direction==="asc"?"desc":"asc"})},V=S=>!g||g.key!==S?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:J.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:g.direction==="asc"?J.chevronUp:J.chevronDown}),L=b.useMemo(()=>{if(!g)return o;const S=g.direction==="asc"?1:-1,C=W=>{switch(g.key){case"product":return T(W);case"type":return M(W.metadata?.product_type);case"price":return W.fiatAmountCents??0;case"status":return W.active?1:0;case"id":default:return W.id}};return[...o].sort((W,Z)=>{const Q=C(W),de=C(Z);return typeof Q=="number"&&typeof de=="number"?(Q-de)*S:String(Q).localeCompare(String(de),void 0,{sensitivity:"base"})*S})},[o,g]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(Dr,{message:k,onRetry:A}),s.jsx($r,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:z.activeCount,variant:z.activeCount>0?"success":"muted"},{label:"Total SKUs",value:z.totalSkus}],isLoading:i}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),s.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{h(null),d(!l)},children:[l?J.close:J.plus,l?"Cancel":"Add Product"]})]}),l&&s.jsxs("form",{onSubmit:R,className:"cedros-admin__add-form",children:[m&&s.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:m}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.id,onChange:S=>j(C=>({...C,id:S.target.value})),placeholder:"e.g., premium-article",required:!0})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.title,onChange:S=>j(C=>({...C,title:S.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.slug,onChange:S=>j(C=>({...C,slug:S.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),s.jsx("input",{type:"url",className:"cedros-admin__input",value:w.imageUrl,onChange:S=>j(C=>({...C,imageUrl:S.target.value})),placeholder:"https://..."})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.description,onChange:S=>j(C=>({...C,description:S.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:w.productType,onChange:S=>j(C=>({...C,productType:S})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"}],label:"Product Type"}),s.jsx(At,{value:w.fulfillmentType,onChange:S=>{const C=S;j(W=>({...W,fulfillmentType:C,checkoutShippingAddress:C==="shipping"?W.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),w.fulfillmentType==="shipping"&&s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:w.inventoryStatus,onChange:S=>j(C=>({...C,inventoryStatus:S})),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"}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:w.inventoryQuantity,onChange:S=>j(C=>({...C,inventoryQuantity:S.target.value===""?"":parseInt(S.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:w.compareAtUsd===""?"":w.compareAtUsd,onChange:S=>j(C=>({...C,compareAtUsd:S.target.value===""?"":parseFloat(S.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:w.priceUsd===""?"":w.priceUsd,onChange:S=>j(C=>({...C,priceUsd:S.target.value===""?"":parseFloat(S.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.tagsCsv,onChange:S=>j(C=>({...C,tagsCsv:S.target.value})),placeholder:"e.g., core, new, gift"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.categoryIdsCsv,onChange:S=>j(C=>({...C,categoryIdsCsv:S.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:w.checkoutEmail,onChange:S=>j(C=>({...C,checkoutEmail:S})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),s.jsx(At,{value:w.checkoutName,onChange:S=>j(C=>({...C,checkoutName:S})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),s.jsx(At,{value:w.checkoutPhone,onChange:S=>j(C=>({...C,checkoutPhone:S})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[w.fulfillmentType==="shipping"&&s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:w.checkoutShippingAddress,onChange:S=>j(C=>({...C,checkoutShippingAddress:S.target.checked}))}),"Collect shipping address"]})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:w.checkoutBillingAddress,onChange:S=>j(C=>({...C,checkoutBillingAddress:S.target.checked}))}),"Collect billing address"]})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.fulfillmentNotes,onChange:S=>j(C=>({...C,fulfillmentNotes:S.target.value})),placeholder:w.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),w.fulfillmentType==="shipping"&&w.checkoutShippingAddress&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:w.shippingCountriesCsv,onChange:S=>j(C=>({...C,shippingCountriesCsv:S.target.value})),placeholder:"e.g., US,CA"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),s.jsx("div",{className:"cedros-admin__form-actions",children:s.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:f,children:f?"Creating...":"Create Product"})})]}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading products..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":g?.key==="id"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("id"),children:["ID",V("id")]})}),s.jsx("th",{"aria-sort":g?.key==="product"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("product"),children:["Product",V("product")]})}),s.jsx("th",{"aria-sort":g?.key==="type"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("type"),children:["Type",V("type")]})}),s.jsx("th",{"aria-sort":g?.key==="price"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("price"),children:["Price",V("price")]})}),s.jsx("th",{"aria-sort":g?.key==="status"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("status"),children:["Status",V("status")]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:L.map(S=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:S.id})}),s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[N(S)?s.jsx("img",{src:N(S),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):s.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),s.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{fontWeight:600},children:T(S)}),s.jsx("span",{style:{opacity:.8},children:S.description})]})]})}),s.jsx("td",{children:M(S.metadata?.product_type)}),s.jsx("td",{children:I(S.fiatAmountCents)}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge ${S.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:S.active?"Active":"Inactive"})}),s.jsx("td",{children:s.jsx("div",{style:{display:"flex",gap:"0.25rem"},children:s.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>x(S),children:"Variations"})})})]},S.id))})]})}),v&&s.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>x(null),children:s.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:S=>S.stopPropagation(),children:s.jsx(gm,{serverUrl:e,productId:v.id,productTitle:T(v),defaultPrice:v.fiatAmountCents/100,apiKey:t,authManager:r,onClose:()=>x(null)})})})]})}function gl({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=b.useState([]),[i,c]=b.useState(null),[l,d]=b.useState(!0),[f,u]=b.useState(!0),[m,h]=b.useState(null),[v,x]=b.useState(""),[g,y]=b.useState(null),k=b.useCallback(async()=>{u(!0);try{h(null);let N;if(r?.isAuthenticated())N=await r.fetchWithAuth("/admin/stats");else{const A={"Content-Type":"application/json"};t&&(A["X-API-Key"]=t);const R=await fetch(`${e}/admin/stats`,{headers:A});if(!R.ok)throw new Error(`Failed to fetch stats: ${R.status}`);N=await R.json()}c(N)}catch{c(null),h("Failed to load payment stats")}finally{u(!1)}},[e,t,r]);b.useEffect(()=>{k()},[k]);const _=b.useCallback(async()=>{try{h(null);let N;const A=new URLSearchParams({limit:n.toString()});v&&A.set("method",v);const R=`/admin/transactions?${A}`;if(r?.isAuthenticated())N=await r.fetchWithAuth(R);else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const M=await fetch(`${e}${R}`,{headers:I});if(!M.ok)throw new Error(`Failed to fetch transactions: ${M.status}`);N=await M.json()}a(N.transactions||[])}catch{a([]),h("Failed to load transactions")}finally{d(!1)}},[e,t,n,v,r]);b.useEffect(()=>{_()},[_]);const w=(N,A="USD")=>new Intl.NumberFormat("en-US",{style:"currency",currency:A}).format(N),j=N=>{y(A=>!A||A.key!==N?{key:N,direction:"asc"}:{key:N,direction:A.direction==="asc"?"desc":"asc"})},P=N=>!g||g.key!==N?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:J.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:g.direction==="asc"?J.chevronUp:J.chevronDown}),T=b.useMemo(()=>{if(!g)return o;const N=g.direction==="asc"?1:-1,A=R=>{switch(g.key){case"resource":return R.resourceId;case"method":return R.method;case"amount":return R.amount;case"status":return R.status;case"date":return new Date(R.paidAt).getTime();case"id":default:return R.id}};return[...o].sort((R,I)=>{const M=A(R),z=A(I);return typeof M=="number"&&typeof z=="number"?(M-z)*N:String(M).localeCompare(String(z),void 0,{sensitivity:"base"})*N})},[o,g]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(Dr,{message:m,onRetry:()=>{k(),_()}}),s.jsx($r,{stats:[{label:"Revenue",value:w(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:w(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:w(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:w(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:f,onRefresh:k}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),s.jsx(ml,{value:v,onChange:x,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading transactions..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":g?.key==="id"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("id"),children:["ID",P("id")]})}),s.jsx("th",{"aria-sort":g?.key==="resource"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("resource"),children:["Resource",P("resource")]})}),s.jsx("th",{"aria-sort":g?.key==="method"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("method"),children:["Method",P("method")]})}),s.jsx("th",{"aria-sort":g?.key==="amount"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("amount"),children:["Amount",P("amount")]})}),s.jsx("th",{"aria-sort":g?.key==="status"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("status"),children:["Status",P("status")]})}),s.jsx("th",{"aria-sort":g?.key==="date"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("date"),children:["Date",P("date")]})})]})}),s.jsx("tbody",{children:T.map(N=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:N.id})}),s.jsx("td",{children:N.resourceId}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${N.method}`,children:N.method})}),s.jsxs("td",{children:["$",N.amount.toFixed(2)," ",N.currency.toUpperCase()]}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${N.status}`,children:N.status})}),s.jsx("td",{children:br(N.paidAt)})]},N.id))})]})})]})}function xl({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=b.useState([]),[i,c]=b.useState(!0),[l,d]=b.useState(!1),[f,u]=b.useState(!1),[m,h]=b.useState(null),[v,x]=b.useState(null),[g,y]=b.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}),k=b.useCallback(async()=>{try{x(null);let A;const R=`/admin/coupons?limit=${n}`;if(r?.isAuthenticated())A=await r.fetchWithAuth(R);else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const M=await fetch(`${e}${R}`,{headers:I});if(!M.ok)throw new Error(`Failed to fetch coupons: ${M.status}`);A=await M.json()}a(A.coupons||[])}catch(A){oe.getLogger().error("[CouponsSection] Failed to fetch coupons:",A,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),x("Failed to load coupons")}finally{c(!1)}},[e,t,n,r]);b.useEffect(()=>{k()},[k]);const _=async A=>{if(A.preventDefault(),!(!g.code||g.discountValue<=0)){u(!0);try{const R=g.minimumAmountUsd?Math.round(Number(g.minimumAmountUsd)*100):void 0,I=g.productIdsCsv.split(",").map(D=>D.trim()).filter(Boolean),M=g.categoryIdsCsv.split(",").map(D=>D.trim()).filter(Boolean),z={code:g.code,discountType:g.discountType,discountValue:g.discountValue,usageLimit:g.usageLimit,active:!0,usageCount:0,scope:g.scope,...I.length?{productIds:I}:{},...M.length?{categoryIds:M}:{},...g.paymentMethod!=="any"?{paymentMethod:g.paymentMethod}:{},...g.autoApply?{autoApply:!0}:{},...g.appliesAt!=="both"?{appliesAt:g.appliesAt}:{},...g.startsAt?{startsAt:g.startsAt}:{},...g.expiresAt?{expiresAt:g.expiresAt}:{},...R?{minimumAmountCents:R}:{},...g.usageLimitPerCustomer?{usageLimitPerCustomer:g.usageLimitPerCustomer}:{},...g.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(z)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const V=await fetch(`${e}/admin/coupons`,{method:"POST",headers:D,body:JSON.stringify(z)});if(!V.ok)throw new Error(`Failed to create coupon: ${V.status}`)}y({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),k()}catch(R){oe.getLogger().error("[CouponsSection] Failed to add coupon:",R,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),x("Failed to create coupon")}finally{u(!1)}}},w=o.filter(A=>A.active).length,j=o.reduce((A,R)=>A+(R.usageCount??0),0),P=A=>{h(R=>!R||R.key!==A?{key:A,direction:"asc"}:{key:A,direction:R.direction==="asc"?"desc":"asc"})},T=A=>!m||m.key!==A?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:J.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:m.direction==="asc"?J.chevronUp:J.chevronDown}),N=b.useMemo(()=>{if(!m)return o;const A=m.direction==="asc"?1:-1,R=I=>{switch(m.key){case"discount":return I.discountValue??0;case"usage":return I.usageCount??0;case"status":return I.active?1:0;case"code":default:return I.code}};return[...o].sort((I,M)=>{const z=R(I),D=R(M);return typeof z=="number"&&typeof D=="number"?(z-D)*A:String(z).localeCompare(String(D),void 0,{sensitivity:"base"})*A})},[o,m]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(Dr,{message:v,onRetry:k}),s.jsx($r,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:w,variant:w>0?"success":"muted"},{label:"Redemptions",value:j}],isLoading:i}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),s.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?J.close:J.plus,l?"Cancel":"Add Coupon"]})]}),l&&s.jsxs("form",{onSubmit:_,className:"cedros-admin__add-form",children:[s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:g.code,onChange:A=>y(R=>({...R,code:A.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),s.jsx(At,{value:g.discountType,onChange:A=>y(R=>({...R,discountType:A})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",g.discountType==="percentage"?"(%)":"($)"]}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:g.discountValue||"",onChange:A=>y(R=>({...R,discountValue:parseFloat(A.target.value)||0})),placeholder:g.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:g.discountType==="percentage"?"1":"0.01",required:!0})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:g.usageLimit||"",onChange:A=>y(R=>({...R,usageLimit:A.target.value?parseInt(A.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),s.jsx("input",{type:"date",className:"cedros-admin__input",value:g.expiresAt,onChange:A=>y(R=>({...R,expiresAt:A.target.value}))})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:g.scope,onChange:A=>y(R=>({...R,scope:A})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),s.jsx(At,{value:g.paymentMethod,onChange:A=>y(R=>({...R,paymentMethod:A})),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"}),s.jsx(At,{value:g.appliesAt,onChange:A=>y(R=>({...R,appliesAt:A})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),g.scope==="specific_products"&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:g.productIdsCsv,onChange:A=>y(R=>({...R,productIdsCsv:A.target.value})),placeholder:"e.g., prod_123, prod_456"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),s.jsx("input",{type:"date",className:"cedros-admin__input",value:g.startsAt,onChange:A=>y(R=>({...R,startsAt:A.target.value}))})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:g.autoApply,onChange:A=>y(R=>({...R,autoApply:A.target.checked}))}),"Automatically apply when conditions met"]})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:g.minimumAmountUsd===""?"":g.minimumAmountUsd,onChange:A=>y(R=>({...R,minimumAmountUsd:A.target.value===""?"":parseFloat(A.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:g.usageLimitPerCustomer||"",onChange:A=>y(R=>({...R,usageLimitPerCustomer:A.target.value?parseInt(A.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:g.firstPurchaseOnly,onChange:A=>y(R=>({...R,firstPurchaseOnly:A.target.checked}))}),"New customers only"]})]})]}),g.scope==="specific_categories"&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:g.categoryIdsCsv,onChange:A=>y(R=>({...R,categoryIdsCsv:A.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),s.jsx("div",{className:"cedros-admin__form-actions",children:s.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:f,children:f?"Creating...":"Create Coupon"})})]}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading coupons..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":m?.key==="code"?m?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("code"),children:["Code",T("code")]})}),s.jsx("th",{"aria-sort":m?.key==="discount"?m?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("discount"),children:["Discount",T("discount")]})}),s.jsx("th",{"aria-sort":m?.key==="usage"?m?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("usage"),children:["Usage",T("usage")]})}),s.jsx("th",{"aria-sort":m?.key==="status"?m?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>P("status"),children:["Status",T("status")]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:N.map(A=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:A.code})}),s.jsx("td",{children:A.discountType==="percentage"?`${A.discountValue}%`:`$${A.discountValue.toFixed(2)}`}),s.jsxs("td",{children:[A.usageCount,A.usageLimit?` / ${A.usageLimit}`:""]}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge ${A.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:A.active?"Active":"Inactive"})}),s.jsx("td",{children:s.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},A.code))})]})})]})}function vl({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=b.useState([]),[i,c]=b.useState(!0),[l,d]=b.useState(null),[f,u]=b.useState([]),[m,h]=b.useState(!0),[v,x]=b.useState(null),[g,y]=b.useState(null),[k,_]=b.useState([]),[w,j]=b.useState(!0),[P,T]=b.useState(null),[N,A]=b.useState(null),[R,I]=b.useState(null),[M,z]=b.useState(""),[D,V]=b.useState(null),L=b.useCallback(async()=>{try{let O;const X=`/admin/refunds?limit=${n}`;if(r?.isAuthenticated())O=await r.fetchWithAuth(X);else{const ae={"Content-Type":"application/json"};t&&(ae["X-API-Key"]=t);const be=await fetch(`${e}${X}`,{headers:ae});if(!be.ok)throw new Error(`Failed to fetch x402 refunds: ${be.status}`);O=await be.json()}a(O.refunds||[])}catch(O){oe.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),V("Failed to load x402 refunds")}finally{c(!1)}},[e,t,n,r]);b.useEffect(()=>{L()},[L]);const S=b.useCallback(async()=>{try{let O;const X=`/admin/credits/refund-requests?status=pending&limit=${n}&offset=0`;if(r?.isAuthenticated())O=await r.fetchWithAuth(X);else{const be={"Content-Type":"application/json"};t&&(be["X-API-Key"]=t);const we=await fetch(`${e}${X}`,{headers:be});if(!we.ok)throw new Error(`Failed to fetch credits refund requests: ${we.status}`);O=await we.json()}const ae=Array.isArray(O)?O:"refundRequests"in O?O.refundRequests:O.requests||[];u(ae)}catch(O){oe.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([]),V("Failed to load credits refunds")}finally{h(!1)}},[e,t,n,r]);b.useEffect(()=>{S()},[S]);const C=async O=>{x(O.id);try{const X=`/admin/credits/refund-requests/${O.id}/process`,ae=JSON.stringify({amountLamports:O.amountLamports,reason:O.reason});if(r?.isAuthenticated())await r.fetchWithAuth(X,{method:"POST",body:ae});else{const be={"Content-Type":"application/json"};t&&(be["X-API-Key"]=t);const we=await fetch(`${e}${X}`,{method:"POST",headers:be,body:ae});if(!we.ok)throw new Error(`Failed to process credits refund: ${we.status}`)}await S()}catch(X){oe.getLogger().error("[RefundsSection] Failed to process credits refund:",X,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:O.id}),V("Failed to process credits refund")}finally{x(null)}},W=O=>{z(O.reason??""),I(O)},Z=()=>{I(null),z("")},Q=async()=>{if(!R)return;const O=R,X=M;Z(),x(O.id);try{const ae=`/admin/credits/refund-requests/${O.id}/reject`,be=JSON.stringify({reason:X});if(r?.isAuthenticated())await r.fetchWithAuth(ae,{method:"POST",body:be});else{const we={"Content-Type":"application/json"};t&&(we["X-API-Key"]=t);const Re=await fetch(`${e}${ae}`,{method:"POST",headers:we,body:be});if(!Re.ok)throw new Error(`Failed to reject credits refund: ${Re.status}`)}await S()}catch(ae){oe.getLogger().error("[RefundsSection] Failed to reject credits refund:",ae,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:O.id}),V("Failed to reject credits refund")}finally{x(null)}},de=b.useCallback(async()=>{try{let O;const X=`/admin/stripe/refunds?limit=${n}`;if(r?.isAuthenticated())O=await r.fetchWithAuth(X);else{const ae={"Content-Type":"application/json"};t&&(ae["X-API-Key"]=t);const be=await fetch(`${e}${X}`,{headers:ae});if(!be.ok)throw new Error(`Failed to fetch Stripe refunds: ${be.status}`);O=await be.json()}_(O.refunds||[])}catch(O){oe.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),_([]),V("Failed to load Stripe refunds")}finally{j(!1)}},[e,t,n,r]);b.useEffect(()=>{de()},[de]);const q=async O=>{T(O);try{const X=`/admin/stripe/refunds/${O}/process`;if(r?.isAuthenticated())await r.fetchWithAuth(X,{method:"POST"});else{const ae={"Content-Type":"application/json"};t&&(ae["X-API-Key"]=t);const be=await fetch(`${e}${X}`,{method:"POST",headers:ae});if(!be.ok)throw new Error(`Failed to process refund: ${be.status}`)}await de()}catch(X){oe.getLogger().error("[RefundsSection] Failed to process Stripe refund:",X,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:O}),V("Failed to process Stripe refund")}finally{T(null)}},K=(O,X)=>new Intl.NumberFormat("en-US",{style:"currency",currency:X}).format(O/100),Y=O=>O?O.replace(/_/g," ").replace(/\b\w/g,X=>X.toUpperCase()):"—",me=O=>{switch(O){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},$=(O,X)=>X?X.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(O/1e6)} (USD credits)`:`${O.toLocaleString()} ${X.toUpperCase()} (atomic)`:`${O.toLocaleString()} (atomic)`,G=O=>{switch(O){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},pe=O=>O.stripeRefundId??"—",U=O=>O.chargeId??"—",se=k.filter(O=>O.status==="pending"||O.status==="requires_action").length,le=f.filter(O=>O.status==="pending").length,ue=o.filter(O=>O.status==="pending").length,Te=se+le+ue,We=k.filter(O=>O.status==="succeeded").reduce((O,X)=>O+X.amount,0),Ye=f.filter(O=>O.status==="processed").reduce((O,X)=>O+X.amountLamports,0),qe=o.filter(O=>O.status==="completed").reduce((O,X)=>O+X.amount,0),_t=We/100+Ye/1e6+qe,Qe=O=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(O),tn=w||m||i,xt=O=>{A(X=>!X||X.key!==O?{key:O,direction:"asc"}:{key:O,direction:X.direction==="asc"?"desc":"asc"})},Se=O=>{y(X=>!X||X.key!==O?{key:O,direction:"asc"}:{key:O,direction:X.direction==="asc"?"desc":"asc"})},Xe=O=>{d(X=>!X||X.key!==O?{key:O,direction:"asc"}:{key:O,direction:X.direction==="asc"?"desc":"asc"})},ke=(O,X)=>!O||!X?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:J.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:X==="asc"?J.chevronUp:J.chevronDown}),Gt=b.useMemo(()=>{if(!N)return k;const O=N.direction==="asc"?1:-1,X=ae=>{switch(N.key){case"stripe":return ae.stripeRefundId??"";case"charge":return ae.chargeId??"";case"amount":return ae.amount??0;case"reason":return ae.reason??"";case"status":return ae.status??"";case"date":return new Date(ae.createdAt).getTime();case"id":default:return ae.id}};return[...k].sort((ae,be)=>{const we=X(ae),Re=X(be);return typeof we=="number"&&typeof Re=="number"?(we-Re)*O:String(we).localeCompare(String(Re),void 0,{sensitivity:"base"})*O})},[k,N]),ft=b.useMemo(()=>{if(!g)return f;const O=g.direction==="asc"?1:-1,X=ae=>{switch(g.key){case"original":return ae.originalTransactionId??"";case"user":return ae.userId??"";case"amount":return ae.amountLamports??0;case"reason":return ae.reason??"";case"status":return ae.status??"";case"date":return new Date(ae.createdAt).getTime();case"id":default:return ae.id}};return[...f].sort((ae,be)=>{const we=X(ae),Re=X(be);return typeof we=="number"&&typeof Re=="number"?(we-Re)*O:String(we).localeCompare(String(Re),void 0,{sensitivity:"base"})*O})},[f,g]),it=b.useMemo(()=>{if(!l)return o;const O=l.direction==="asc"?1:-1,X=ae=>{switch(l.key){case"transaction":return ae.transactionId??"";case"amount":return ae.amount??0;case"reason":return ae.reason??"";case"status":return ae.status??"";case"date":return new Date(ae.createdAt).getTime();case"id":default:return ae.id}};return[...o].sort((ae,be)=>{const we=X(ae),Re=X(be);return typeof we=="number"&&typeof Re=="number"?(we-Re)*O:String(we).localeCompare(String(Re),void 0,{sensitivity:"base"})*O})},[o,l]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(Dr,{message:D,onRetry:()=>{L(),S(),de()}}),s.jsx($r,{stats:[{label:"Pending",value:Te,variant:Te>0?"warning":"muted"},{label:"Card Pending",value:se,description:"Stripe"},{label:"Credits Pending",value:le},{label:"Crypto Pending",value:ue,description:"x402"},{label:"Total Refunded",value:Qe(_t),variant:"success"}],isLoading:tn}),s.jsx("div",{className:"cedros-admin__section-header",children:s.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),w?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading Stripe refunds..."]}):k.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":N?.key==="id"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("id"),children:["Request ID",ke(N?.key==="id",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="stripe"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("stripe"),children:["Stripe Refund ID",ke(N?.key==="stripe",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="charge"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("charge"),children:["Charge",ke(N?.key==="charge",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="amount"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("amount"),children:["Amount",ke(N?.key==="amount",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="reason"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("reason"),children:["Reason",ke(N?.key==="reason",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="status"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("status"),children:["Status",ke(N?.key==="status",N?.direction)]})}),s.jsx("th",{"aria-sort":N?.key==="date"?N?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("date"),children:["Date",ke(N?.key==="date",N?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:Gt.map(O=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:O.id})}),s.jsx("td",{children:s.jsx("code",{children:pe(O)})}),s.jsx("td",{children:s.jsx("code",{children:U(O)})}),s.jsx("td",{children:K(O.amount,O.currency)}),s.jsx("td",{children:Y(O.reason)}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${G(O.status)}`,children:O.status})}),s.jsx("td",{children:br(O.createdAt)}),s.jsx("td",{children:(O.status==="pending"||O.status==="requires_action")&&s.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>q(O.id),disabled:P===O.id,children:P===O.id?"Processing...":"Process"})})]},O.id))})]})}),s.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:s.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),m?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading credits refunds..."]}):f.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":g?.key==="id"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("id"),children:["Request ID",ke(g?.key==="id",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="original"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("original"),children:["Original Tx",ke(g?.key==="original",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="user"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("user"),children:["User",ke(g?.key==="user",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="amount"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("amount"),children:["Amount",ke(g?.key==="amount",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="reason"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("reason"),children:["Reason",ke(g?.key==="reason",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="status"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("status"),children:["Status",ke(g?.key==="status",g?.direction)]})}),s.jsx("th",{"aria-sort":g?.key==="date"?g?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Se("date"),children:["Date",ke(g?.key==="date",g?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:ft.map(O=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:O.id})}),s.jsx("td",{children:s.jsx("code",{children:O.originalTransactionId})}),s.jsx("td",{children:s.jsx("code",{children:O.userId??"—"})}),s.jsx("td",{children:$(O.amountLamports,O.currency)}),s.jsx("td",{children:O.reason??"—"}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${me(O.status)}`,children:O.status})}),s.jsx("td",{children:br(O.createdAt)}),s.jsx("td",{children:O.status==="pending"?s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>C(O),disabled:v===O.id,children:v===O.id?"Processing...":"Process"}),s.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>W(O),disabled:v===O.id,children:"Reject"})]}):null})]},O.id))})]})}),s.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:s.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[J.loading," Loading x402 refunds..."]}):o.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("id"),children:["ID",ke(l?.key==="id",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="transaction"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("transaction"),children:["Transaction",ke(l?.key==="transaction",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="amount"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("amount"),children:["Amount",ke(l?.key==="amount",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="reason"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("reason"),children:["Reason",ke(l?.key==="reason",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="status"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("status"),children:["Status",ke(l?.key==="status",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="date"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("date"),children:["Date",ke(l?.key==="date",l?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:it.map(O=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:O.id})}),s.jsx("td",{children:s.jsx("code",{children:O.transactionId})}),s.jsxs("td",{children:["$",O.amount.toFixed(2)]}),s.jsx("td",{children:O.reason||"—"}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${O.status}`,children:O.status})}),s.jsx("td",{children:br(O.createdAt)}),s.jsx("td",{})]},O.id))})]})}),R&&s.jsx("div",{className:"cedros-admin__modal-overlay",onClick:Z,children:s.jsxs("div",{className:"cedros-admin__modal",onClick:O=>O.stopPropagation(),children:[s.jsxs("div",{className:"cedros-admin__modal-header",children:[s.jsx("h3",{className:"cedros-admin__modal-title",children:"Reject Refund Request"}),s.jsx("button",{type:"button",className:"cedros-admin__modal-close",onClick:Z,"aria-label":"Close",children:J.close})]}),s.jsxs("div",{className:"cedros-admin__modal-body",children:[s.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",s.jsx("code",{children:R.id})," for ",$(R.amountLamports,R.currency),"."]}),s.jsxs("label",{className:"cedros-admin__form-field",children:[s.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),s.jsx("textarea",{className:"cedros-admin__input",value:M,onChange:O=>z(O.target.value),placeholder:"Enter rejection reason...",rows:3,style:{resize:"vertical"}})]})]}),s.jsxs("div",{className:"cedros-admin__modal-footer",children:[s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--outline",onClick:Z,children:"Cancel"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:Q,children:"Reject Refund"})]})]})})]})}const xm=b.lazy(()=>Promise.resolve().then(()=>require("./SettingsSection-DNoODw7i.js")).then(e=>({default:e.SettingsSection})));function yl(e){return s.jsx(b.Suspense,{fallback:null,children:s.jsx(xm,{...e})})}class bl{serverUrl;walletSigner=null;jwtToken=null;isAdminUser=!1;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdminUser?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,oe.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,n){this.jwtToken=t,this.isAdminUser=n??!1,oe.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t,isAdmin:this.isAdminUser})}async createAuthHeaders(t){const n=this.getAuthMethod();if(n==="wallet")return this.createWalletAuthHeaders(t);if(n==="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 n=await this.fetchNonce(t),r=new TextEncoder().encode(n.nonce_id),o=await this.walletSigner.signMessage(r),a=Ai.bs58.encode(this.walletSigner.publicKey.toBytes()),i=Ai.bs58.encode(o);return{"X-Signer":a,"X-Message":n.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 n=`${this.serverUrl}/paywall/v1/nonce`;oe.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const r=await oe.fetchWithTimeout(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!r.ok){const o=await r.text();throw new Error(`Failed to fetch nonce: ${r.status} ${o}`)}return await r.json()}async fetchWithAuth(t,n={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,n.method||"GET"),a=await this.createAuthHeaders(o),i=(n.method||"GET").toUpperCase(),c={...i!=="GET"&&i!=="HEAD"?{"Content-Type":"application/json"}:{},...n.headers||{},...a},l=await oe.fetchWithTimeout(`${this.serverUrl}${t}`,{...n,headers:c});if(!l.ok){let d=`Admin API error ${l.status}`;try{const f=await l.json();f&&typeof f.error=="string"?d=f.error:f&&typeof f.message=="string"&&(d=f.message)}catch{}throw new Error(d)}return await l.json()}getPurposeFromPath(t,n){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?.[n])return o[n];if(t.startsWith("/admin/products/")){if(n==="PUT")return"admin_products_update";if(n==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(n==="PUT")return"admin_coupons_update";if(n==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(n==="GET")return"admin_config_get";if(n==="PUT")return"admin_config_update";if(n==="PATCH")return"admin_config_patch"}return`admin_${n.toLowerCase()}`}}function vm({serverUrl:e,cedrosLoginToken:t,isAdmin:n=!1}){const r=Ip.useWallet(),o=b.useMemo(()=>{const u=new bl(e);return u.setCedrosLoginAuth(t??null,n),u},[e,t,n]);b.useEffect(()=>{r.publicKey&&r.signMessage?o.setWalletSigner({publicKey:r.publicKey,signMessage:r.signMessage}):o.setWalletSigner(null)},[o,r.publicKey,r.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(r.publicKey&&r.signMessage),l=!!t,d=b.useMemo(()=>{if(!r.publicKey)return null;const u=r.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[r.publicKey]),f=b.useCallback((u,m)=>o.fetchWithAuth(u,m),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:f}}const ym=b.lazy(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-4b29i-41.js")).then(e=>({default:e.SubscriptionsSection}))),bm=b.lazy(()=>Promise.resolve().then(()=>require("./StorefrontSection-BEOMtSAg.js")).then(e=>({default:e.StorefrontSection}))),wm=b.lazy(()=>Promise.resolve().then(()=>require("./AISettingsSection-C-thWh51.js")).then(e=>({default:e.AISettingsSection}))),_m=b.lazy(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-DpENgoca.js")).then(e=>({default:e.PaymentSettingsSection}))),km=b.lazy(()=>Promise.resolve().then(()=>require("./MessagingSection-BHzf1Mhu.js")).then(e=>({default:e.MessagingSection}))),jm=b.lazy(()=>Promise.resolve().then(()=>require("./FAQSection-_pm1ekTe.js")).then(e=>({default:e.FAQSection}))),wl=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:J.transactions},{id:"products",label:"Products",icon:J.products},{id:"subscriptions",label:"Subscriptions",icon:J.calendarRepeat},{id:"coupons",label:"Coupons",icon:J.coupons},{id:"refunds",label:"Refunds",icon:J.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:J.storefront},{id:"ai-settings",label:"Store AI",icon:J.brain},{id:"faqs",label:"Knowledge Base",icon:J.faq},{id:"payment-settings",label:"Payment Options",icon:J.creditCard},{id:"messaging",label:"Store Messages",icon:J.mail},{id:"settings",label:"Store Server",icon:J.server}]}],Sm=wl.flatMap(e=>e.sections);function Cm(){const[e,t]=b.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return b.useEffect(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)"),r=o=>t(o.matches?"dark":"light");return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}function Nm(e,t,n){return e!=="system"?e:t||n}function Em({serverUrl:e,apiKey:t,title:n="Cedros Pay",sections:r=["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:f=!1,theme:u="system"}){const[m,h]=b.useState(o),[v]=b.useState(!1),[x,g]=b.useState(new Set),y=b.useCallback(I=>{g(M=>{const z=new Set(M);return z.has(I)?z.delete(I):z.add(I),z})},[]),k=oe.useCedrosThemeOptional(),_=Cm(),j=Nm(u,k?.mode??null,_)==="dark"?"cedros-admin--dark":"",{authManager:P,isAuthenticated:T}=vm({serverUrl:e,cedrosLoginToken:d,isAdmin:f}),N=b.useCallback(I=>{h(I),c?.(I)},[c]),R=Sm.filter(I=>r.includes(I.id)).find(I=>I.id===m);return v?s.jsxs("div",{className:`cedros-admin cedros-admin--loading ${j} ${l}`,children:[J.loading,s.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):T?s.jsxs("div",{className:`cedros-admin ${j} ${l}`,children:[s.jsxs("aside",{className:"cedros-admin__sidebar",children:[s.jsx("div",{className:"cedros-admin__sidebar-header",children:s.jsxs("div",{className:"cedros-admin__logo",children:[J.wallet,s.jsx("span",{className:"cedros-admin__logo-text",children:n})]})}),s.jsx("nav",{className:"cedros-admin__nav",children:wl.map(I=>{const M=I.sections.filter(D=>r.includes(D.id));if(M.length===0)return null;const z=I.collapsible&&x.has(I.label);return s.jsxs("div",{className:"cedros-admin__nav-group",children:[I.collapsible?s.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>y(I.label),"aria-expanded":!z,children:[I.label,s.jsx("span",{className:`cedros-admin__nav-label-icon ${z?"":"cedros-admin__nav-label-icon--expanded"}`,children:J.chevronRight})]}):s.jsx("span",{className:"cedros-admin__nav-label",children:I.label}),!z&&M.map(D=>s.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${m===D.id?"cedros-admin__nav-item--active":""}`,onClick:()=>N(D.id),"aria-current":m===D.id?"page":void 0,children:[s.jsx("span",{className:"cedros-admin__nav-icon",children:D.icon}),s.jsx("span",{className:"cedros-admin__nav-text",children:D.label})]},D.id))]},I.label)})})]}),s.jsxs("main",{className:"cedros-admin__main",children:[s.jsx("header",{className:"cedros-admin__header",children:s.jsxs("div",{className:"cedros-admin__breadcrumb",children:[s.jsx("span",{className:"cedros-admin__breadcrumb-root",children:n}),s.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:J.chevronRight}),s.jsx("span",{className:"cedros-admin__breadcrumb-current",children:R?.label})]})}),s.jsxs("div",{className:"cedros-admin__content",children:[m==="products"&&s.jsx(hl,{serverUrl:e,apiKey:t,pageSize:i,authManager:P}),m==="subscriptions"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(ym,{serverUrl:e,apiKey:t,authManager:P})}),m==="transactions"&&s.jsx(gl,{serverUrl:e,apiKey:t,pageSize:i,authManager:P}),m==="coupons"&&s.jsx(xl,{serverUrl:e,apiKey:t,pageSize:i,authManager:P}),m==="refunds"&&s.jsx(vl,{serverUrl:e,apiKey:t,pageSize:i,authManager:P}),m==="storefront"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(bm,{serverUrl:e,apiKey:t,authManager:P})}),m==="ai-settings"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(wm,{serverUrl:e,apiKey:t,authManager:P})}),m==="faqs"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(jm,{serverUrl:e,apiKey:t,pageSize:i,authManager:P})}),m==="payment-settings"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(_m,{serverUrl:e,apiKey:t,authManager:P})}),m==="messaging"&&s.jsx(b.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(km,{serverUrl:e,apiKey:t,authManager:P})}),m==="settings"&&s.jsx(yl,{serverUrl:e,apiKey:t,authManager:P})]})]})]}):s.jsx("div",{className:`cedros-admin cedros-admin--unauthenticated ${j} ${l}`,children:s.jsx("p",{className:"cedros-admin__auth-prompt",children:"Please connect a wallet or sign in as admin to access the dashboard."})})}function Ts(e){const t=b.lazy(e),n=r=>b.createElement(b.Suspense,{fallback:null},b.createElement(t,r));return n.displayName="LazyAdminSection",n}Ts(()=>Promise.resolve().then(()=>require("./SettingsSection-DNoODw7i.js")).then(e=>({default:e.SettingsSection})));Ts(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-4b29i-41.js")).then(e=>({default:e.SubscriptionsSection})));Ts(()=>Promise.resolve().then(()=>require("./StorefrontSection-BEOMtSAg.js")).then(e=>({default:e.StorefrontSection})));Ts(()=>Promise.resolve().then(()=>require("./FAQSection-_pm1ekTe.js")).then(e=>({default:e.FAQSection})));const kt=e=>b.lazy(async()=>{const r=(await e()).default;return{default:({pluginContext:a})=>{const c=Tp.useCedrosLogin()?._internal?.getAccessToken()??a.getAccessToken(),l=b.useMemo(()=>{const f=new bl(a.serverUrl);return f.setCedrosLoginAuth(c??null),f},[a.serverUrl,c]),d={serverUrl:a.serverUrl,authManager:l};return s.jsx(r,{...d})}}}),Am={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:J.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:J.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:J.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:J.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:J.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:J.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:J.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:J.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:J.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:J.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:J.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:kt(()=>Promise.resolve().then(()=>require("./sections-CKwGmrzV.js")).then(e=>({default:e.ProductsSection}))),subscriptions:kt(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-4b29i-41.js")).then(e=>({default:e.SubscriptionsSection}))),transactions:kt(()=>Promise.resolve().then(()=>require("./sections-CKwGmrzV.js")).then(e=>({default:e.TransactionsSection}))),coupons:kt(()=>Promise.resolve().then(()=>require("./sections-CKwGmrzV.js")).then(e=>({default:e.CouponsSection}))),refunds:kt(()=>Promise.resolve().then(()=>require("./sections-CKwGmrzV.js")).then(e=>({default:e.RefundsSection}))),storefront:kt(()=>Promise.resolve().then(()=>require("./StorefrontSection-BEOMtSAg.js")).then(e=>({default:e.StorefrontSection}))),"ai-settings":kt(()=>Promise.resolve().then(()=>require("./AISettingsSection-C-thWh51.js")).then(e=>({default:e.AISettingsSection}))),faqs:kt(()=>Promise.resolve().then(()=>require("./FAQSection-_pm1ekTe.js")).then(e=>({default:e.FAQSection}))),"payment-settings":kt(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-DpENgoca.js")).then(e=>({default:e.PaymentSettingsSection}))),messaging:kt(()=>Promise.resolve().then(()=>require("./MessagingSection-BHzf1Mhu.js")).then(e=>({default:e.MessagingSection}))),settings:kt(()=>Promise.resolve().then(()=>require("./SettingsSection-DNoODw7i.js")).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,n=e.cedrosLogin;return{serverUrl:t?.serverUrl||n?.serverUrl||"",userId:n?.user?.id,getAccessToken:()=>n?.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 Pm({product:e,paymentMethod:t,showOriginalPrice:n=!1,className:r="",style:o={}}){const a=t==="stripe",i=a?e.fiatAmount:e.cryptoAmount,c=a?e.effectiveFiatAmount:e.effectiveCryptoAmount,l=a?e.fiatCurrency.toUpperCase():e.cryptoToken,d=a?e.hasStripeCoupon:e.hasCryptoCoupon,f=a?e.stripeDiscountPercent:e.cryptoDiscountPercent;return s.jsxs("div",{className:r,style:o,children:[n&&d&&s.jsxs("span",{style:{textDecoration:"line-through",opacity:.6,marginRight:"0.5rem",fontSize:"0.875em"},children:[i.toFixed(2)," ",l]}),s.jsxs("span",{style:{fontWeight:600},children:[c.toFixed(2)," ",l]}),d&&f>0&&s.jsxs("span",{style:{marginLeft:"0.5rem",padding:"0.125rem 0.375rem",backgroundColor:"#10b981",color:"white",borderRadius:"0.25rem",fontSize:"0.75em",fontWeight:600},children:[f,"% OFF"]})]})}function Im({product:e,paymentMethod:t,className:n="",style:r={}}){const o=t==="stripe",a=o?e.hasStripeCoupon:e.hasCryptoCoupon,i=o?e.stripeDiscountPercent:e.cryptoDiscountPercent,c=o?e.stripeCouponCode:e.cryptoCouponCode;if(!a||i===0)return null;const l=o?`${i}% off with card!`:`${i}% off with crypto!`;return s.jsxs("div",{className:n,style:{display:"inline-flex",alignItems:"center",padding:"0.5rem 0.75rem",backgroundColor:o?"#6366f1":"#10b981",color:"white",borderRadius:"0.375rem",fontSize:"0.875rem",fontWeight:600,...r},children:[l,c&&s.jsxs("span",{style:{marginLeft:"0.5rem",opacity:.8,fontSize:"0.75em",fontWeight:400},children:["(",c,")"]})]})}function _l(){const{subscriptionManager:e}=oe.useCedrosContext(),[t,n]=b.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),r=b.useRef(!1),o=b.useCallback(async l=>{if(r.current)return{success:!1,error:"Payment already in progress"};r.current=!0,n(d=>({...d,status:"loading",error:null}));try{const d=await e.processSubscription(l);return n(f=>({...f,status:d.success?"success":"error",error:d.success?null:d.error||"Subscription failed",sessionId:d.success&&d.transactionId||null})),d}catch(d){const f=oe.formatError(d,"Subscription failed");return n(u=>({...u,status:"error",error:f})),{success:!1,error:f}}finally{r.current=!1}},[e]),a=b.useCallback(async l=>{n(d=>({...d,status:"checking",error:null}));try{const d=await e.checkSubscriptionStatus(l);return n(f=>({...f,status:d.active?"success":"idle",subscriptionStatus:d.status,expiresAt:d.expiresAt||d.currentPeriodEnd||null})),d}catch(d){const f=d instanceof Error?d.message:"Failed to check subscription status";throw n(u=>({...u,status:"error",error:f})),d}},[e]),i=b.useCallback(async(l,d,f)=>{n(u=>({...u,status:"loading",error:null}));try{const u=await e.requestSubscriptionQuote(l,d,f);return n(m=>({...m,status:"idle"})),u}catch(u){const m=u instanceof Error?u.message:"Failed to get subscription quote";throw n(h=>({...h,status:"error",error:m})),u}},[e]),c=b.useCallback(()=>{n({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:o,checkStatus:a,requestQuote:i,reset:c}}function Tm({resource:e,interval:t,intervalDays:n,trialDays:r,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:f=!1,onAttempt:u,onSuccess:m,onError:h,className:v=""}){const{status:x,error:g,sessionId:y,processSubscription:k}=_l(),_=oe.useCedrosTheme(),{t:w,translations:j}=Pn(),P=d||w("ui.subscribe"),T=_.unstyled?v:`${_.className} cedros-theme__stripe-button ${v}`.trim(),N=g&&typeof g!="string"?g?.code??null:null,R=g?typeof g=="string"?g:(L=>{if(!L||!j)return"";const S=j.errors[L];return S?S.action?`${S.message} ${S.action}`:S.message:""})(N):null,I=b.useCallback(async()=>{oe.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:n,trialDays:r,couponCode:l}),Kn("stripe",e),u&&u("stripe"),Jn("stripe",e);const L=await k({resource:e,interval:t,intervalDays:n,trialDays:r,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});L.success&&L.transactionId?(Xn("stripe",L.transactionId,e),m&&m(L.transactionId)):!L.success&&L.error&&(Bt("stripe",L.error,e),h&&h(L.error))},[e,t,n,r,c,i,l,o,a,k,u,m,h]),M=b.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),z=b.useMemo(()=>Qn(M,I),[M,I]),D=x==="loading",V=f||D;return s.jsxs("div",{className:T,style:_.unstyled?{}:_.style,children:[s.jsx("button",{onClick:z,disabled:V,className:_.unstyled?v:"cedros-theme__button cedros-theme__stripe",type:"button",children:D?w("ui.processing"):P}),R&&s.jsx("div",{className:_.unstyled?"":"cedros-theme__error",children:R}),y&&s.jsx("div",{className:_.unstyled?"":"cedros-theme__success",children:w("ui.redirecting_to_checkout")})]})}function kl(){const{subscriptionManager:e,creditsManager:t}=oe.useCedrosContext(),[n,r]=b.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=b.useRef(!1),a=b.useCallback(async(d,f)=>{r(u=>({...u,status:"checking",error:null}));try{const u=await e.checkSubscriptionStatus({resource:d,userId:f});return r(m=>({...m,status:u.active?"success":"idle",subscriptionStatus:u.status,expiresAt:u.expiresAt||u.currentPeriodEnd||null})),u}catch(u){const m=oe.formatError(u,"Failed to check subscription status");return r(h=>({...h,status:"error",error:m})),null}},[e]),i=b.useCallback(async(d,f,u)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await t.requestQuote(d,u?.couponCode);return r(h=>({...h,status:"idle",creditsRequirement:m})),m}catch(m){const h=oe.formatError(m,"Failed to get subscription quote");return r(v=>({...v,status:"error",error:h})),null}},[t]),c=b.useCallback(async(d,f,u,m)=>{if(o.current)return{success:!1,error:"Payment already in progress"};if(!u){const h="Authentication required for credits payment";return r(v=>({...v,status:"error",error:h})),{success:!1,error:h}}o.current=!0,r(h=>({...h,status:"loading",error:null}));try{const h=await t.processPayment(d,u,m?.couponCode,{interval:f,...m?.intervalDays&&{intervalDays:String(m.intervalDays)}});return h.success?r({status:"success",error:null,sessionId:h.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):r(v=>({...v,status:"error",error:h.error||"Credits subscription payment failed"})),h}catch(h){const v=oe.formatError(h,"Credits subscription payment failed");return r(x=>({...x,status:"error",error:v})),{success:!1,error:v}}finally{o.current=!1}},[t]),l=b.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...n,checkStatus:a,requestQuote:i,processPayment:c,reset:l}}function Rm({resource:e,interval:t,intervalDays:n,authToken:r,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:f,className:u="",hideMessages:m=!1,autoCheckStatus:h=!1}){const{status:v,error:x,subscriptionStatus:g,expiresAt:y,checkStatus:k,processPayment:_}=kl(),w=oe.useCedrosTheme(),{t:j,translations:P}=Pn(),T=b.useRef(k);b.useEffect(()=>{T.current=k},[k]),b.useEffect(()=>{h&&o&&(oe.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),T.current(e,o))},[h,o,e]);const N=i||j("ui.subscribe_with_credits")||"Subscribe with Credits",A=x&&typeof x!="string"?x?.code??null:null,I=x?typeof x=="string"?x:(Z=>{if(!Z||!P)return"";const Q=P.errors[Z];return Q?Q.action?`${Q.message} ${Q.action}`:Q.message:""})(A):null,M=b.useCallback(async()=>{if(oe.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:n,hasAuthToken:!!r}),Kn("credits",e),l&&l("credits"),!r){const Q="Authentication required: please log in to subscribe with credits";oe.getLogger().error("[CreditsSubscribeButton]",Q),Bt("credits",Q,e),f&&f(Q);return}Jn("credits",e);const Z=await _(e,t,r,{couponCode:a,intervalDays:n});Z.success&&Z.transactionId?(Xn("credits",Z.transactionId,e),d&&d(Z.transactionId)):!Z.success&&Z.error&&(Bt("credits",Z.error,e),f&&f(Z.error))},[e,t,n,r,a,_,l,d,f]),z=b.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),D=b.useMemo(()=>Qn(z,M,{cooldownMs:200,deduplicationWindowMs:0}),[z,M]),V=v==="loading"||v==="checking",L=g==="active"||g==="trialing",S=c||V||L;let C=N;if(V)C=j("ui.processing");else if(L&&y){const Z=new Date(y).toLocaleDateString();C=`${j("ui.subscribed_until")} ${Z}`}else L&&(C=j("ui.subscribed"));const W=w.unstyled?u:`${w.className} cedros-theme__credits-button ${u}`.trim();return s.jsxs("div",{className:W,style:w.unstyled?{}:w.style,children:[s.jsx("button",{onClick:D,disabled:S,className:w.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:C}),!m&&I&&s.jsx("div",{className:w.unstyled?"":"cedros-theme__error",children:I}),!m&&L&&s.jsx("div",{className:w.unstyled?"":"cedros-theme__success",children:j("ui.subscription_active")})]})}function jl(){const{subscriptionChangeManager:e}=oe.useCedrosContext(),[t,n]=b.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),r=b.useRef(t);r.current=t;const o=b.useCallback(async(u,m)=>{n(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,m);return n(v=>({...v,status:"success",subscription:h,userId:m})),h}catch(h){const v=h instanceof Error?h.message:"Failed to load subscription";return n(x=>({...x,status:"error",error:v})),null}},[e]),a=b.useCallback(async(u,m,h,v)=>{n(x=>({...x,status:"loading",error:null}));try{const x={currentResource:u,newResource:m,userId:h,newInterval:v},g=await e.previewChange(x);return n(y=>({...y,status:"idle",changePreview:g})),g}catch(x){const g=x instanceof Error?x.message:"Failed to preview change";return n(y=>({...y,status:"error",error:g})),null}},[e]),i=b.useCallback(async u=>{const{subscription:m,userId:h}=r.current;if(!m||!h)return n(v=>({...v,status:"error",error:"No subscription loaded"})),null;n(v=>({...v,status:"loading",error:null}));try{const v={currentResource:m.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},x=await e.changeSubscription(v);return x.success?n(g=>({...g,status:"success",subscription:g.subscription?{...g.subscription,resource:x.newResource,interval:x.newInterval,status:x.status}:null,changePreview:null})):n(g=>({...g,status:"error",error:x.error||"Failed to change subscription"})),x}catch(v){const x=v instanceof Error?v.message:"Failed to change subscription";return n(g=>({...g,status:"error",error:x})),null}},[e]),c=b.useCallback(async u=>{const{subscription:m,userId:h}=r.current;if(!m||!h)return n(v=>({...v,status:"error",error:"No subscription loaded"})),null;n(v=>({...v,status:"loading",error:null}));try{const v={resource:m.resource,userId:h,immediate:u},x=await e.cancel(v);if(x.success){const g=u?"canceled":m.status;n(y=>({...y,status:"success",subscription:y.subscription?{...y.subscription,status:g,cancelAtPeriodEnd:!u}:null}))}else n(g=>({...g,status:"error",error:x.error||"Failed to cancel subscription"}));return x}catch(v){const x=v instanceof Error?v.message:"Failed to cancel subscription";return n(g=>({...g,status:"error",error:x})),null}},[e]),l=b.useCallback(async(u,m)=>{n(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:m});try{if(new URL(h.url).protocol!=="https:")throw new Error("Billing portal URL must use HTTPS")}catch{throw new Error("Invalid billing portal URL")}return window.location.href=h.url,h}catch(h){const v=h instanceof Error?h.message:"Failed to open billing portal";return n(x=>({...x,status:"error",error:v})),null}},[e]),d=b.useCallback(()=>{n(u=>({...u,changePreview:null}))},[]),f=b.useCallback(()=>{n({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:f}}const Om={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"},Mm={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 Lm(e){const t=e?Mm:Om;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 wn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function Sl(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function Dm(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 $m({preview:e,onConfirm:t,onCancel:n,isLoading:r,styles:o}){const a=e.immediateAmount<0;return s.jsxs("div",{className:"cedros-proration-preview",style:o.prorationPreview,children:[s.jsx("h4",{style:o.previewTitle,children:"Change Preview"}),s.jsxs("div",{style:o.previewDetails,children:[s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"Current plan:"}),s.jsxs("span",{children:[wn(e.currentPlanPrice,e.currency),"/period"]})]}),s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"New plan:"}),s.jsxs("span",{children:[wn(e.newPlanPrice,e.currency),"/period"]})]}),s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"Days remaining:"}),s.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"Unused credit:"}),s.jsxs("span",{children:["-",wn(e.prorationDetails.unusedCredit,e.currency)]})]}),s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"New plan cost:"}),s.jsx("span",{children:wn(e.prorationDetails.newPlanCost,e.currency)})]})]}),s.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[s.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),s.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:wn(Math.abs(e.immediateAmount),e.currency)})]}),s.jsxs("div",{style:o.previewRow,children:[s.jsx("span",{children:"Effective date:"}),s.jsx("span",{children:Sl(e.effectiveDate)})]})]}),s.jsxs("div",{style:o.previewActions,children:[s.jsx("button",{onClick:n,style:o.cancelButton,disabled:r,children:"Cancel"}),s.jsx("button",{onClick:t,style:o.confirmButton,disabled:r,children:r?"Processing...":"Confirm Change"})]})]})}function zm({resource:e,userId:t,availablePlans:n=[],onSubscriptionChanged:r,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=oe.useCedrosTheme(),f=b.useMemo(()=>Lm(d==="dark"),[d]),{subscription:u,changePreview:m,status:h,error:v,loadSubscription:x,previewChange:g,changeSubscription:y,cancelSubscription:k,openBillingPortal:_,clearPreview:w}=jl();b.useEffect(()=>{x(e,t)},[e,t,x]);const j=b.useRef(null),P=b.useCallback(async(I,M)=>{j.current={resource:I,interval:M},await g(e,I,t,M)},[e,t,g]),T=b.useCallback(async()=>{if(!m)return;const I=j.current;(await y({newResource:I?.resource||e,newInterval:I?.interval,immediate:!0}))?.success&&I&&I.interval&&(r?.(I.resource,I.interval),j.current=null)},[m,e,y,r]),N=b.useCallback(async I=>{(await k(I))?.success&&o?.()},[k,o]),A=b.useCallback(()=>{_(t,a)},[t,a,_]),R=h==="loading";return s.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...f.container,...l},children:[v&&s.jsx("div",{className:"cedros-subscription-error",style:f.error,children:v}),R&&!u&&s.jsx("div",{className:"cedros-subscription-loading",style:f.loading,children:"Loading subscription..."}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"cedros-subscription-details",style:f.details,children:[s.jsx("h3",{style:f.title,children:"Current Subscription"}),s.jsxs("div",{style:f.detailRow,children:[s.jsx("span",{style:f.label,children:"Plan:"}),s.jsx("span",{style:f.value,children:u.resource})]}),s.jsxs("div",{style:f.detailRow,children:[s.jsx("span",{style:f.label,children:"Status:"}),s.jsx("span",{style:{...f.statusBadge,backgroundColor:Dm(u.status)},children:u.status})]}),s.jsxs("div",{style:f.detailRow,children:[s.jsx("span",{style:f.label,children:"Price:"}),s.jsxs("span",{style:f.value,children:[wn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),s.jsxs("div",{style:f.detailRow,children:[s.jsx("span",{style:f.label,children:"Current period ends:"}),s.jsx("span",{style:f.value,children:Sl(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&s.jsx("div",{style:f.cancelNotice,children:"Subscription will cancel at end of current period"})]}),m&&s.jsx($m,{preview:m,onConfirm:T,onCancel:w,isLoading:R,styles:f}),n.length>0&&!m&&s.jsxs("div",{className:"cedros-available-plans",style:f.plansSection,children:[s.jsx("h4",{style:f.plansTitle,children:"Available Plans"}),s.jsx("div",{style:f.plansList,children:n.map(I=>{const M=I.resource===u.resource;return s.jsxs("div",{style:{...f.planCard,...M?f.currentPlan:{}},children:[s.jsx("div",{style:f.planName,children:I.name}),s.jsxs("div",{style:f.planPrice,children:[wn(I.price,I.currency),"/",I.interval]}),I.description&&s.jsx("div",{style:f.planDescription,children:I.description}),M?s.jsx("span",{style:f.currentBadge,children:"Current Plan"}):s.jsx("button",{onClick:()=>P(I.resource,I.interval),style:f.changePlanButton,disabled:R,children:I.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},I.resource)})})]}),s.jsxs("div",{className:"cedros-subscription-actions",style:f.actions,children:[i&&u.paymentMethod==="stripe"&&s.jsx("button",{onClick:A,style:f.portalButton,disabled:R,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&s.jsx("button",{onClick:()=>N(!1),style:f.cancelSubscriptionButton,disabled:R,children:"Cancel Subscription"})]})]})]})}function Fm(){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 Bm(){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 Um(){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 Vm(){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 Wm(){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 qm(){const e=[Fm(),Bm(),Um(),Vm(),Wm()],t=e.some(a=>a.severity==="error"&&!a.passed),n=e.some(a=>a.severity==="warning"&&!a.passed);let r,o;return t?(r="vulnerable",o="Security issues detected. Review errors and apply recommendations."):n?(r="warnings",o="Minor security warnings detected. Consider applying recommendations."):(r="secure",o="All security checks passed."),{checks:e,overallStatus:r,summary:o}}function Hm(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 n=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${n} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const Zm={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"},ga=b.createContext(null);function Pe(){const e=b.useContext(ga);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function xa(){return b.useContext(ga)}function Gm({config:e,children:t}){const n=b.useMemo(()=>({config:e}),[e]);return s.jsx(ga.Provider,{value:n,children:t})}function jt(e){return new Promise(t=>setTimeout(t,e))}const Cl=[{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."}],ps=[{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"}];function Ym(e,t){let n=e;if(t.category&&t.category!=="all"){const l=Cl.find(d=>d.slug===t.category||d.id===t.category);l&&(n=n.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();n=n.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const r=t.filters??{},o=r.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));n=n.filter(d=>d.tags?.some(f=>l.has(f)))}const a=typeof r.priceMin=="number"?r.priceMin:void 0,i=typeof r.priceMax=="number"?r.priceMax:void 0;return typeof a=="number"&&(n=n.filter(l=>l.price>=a)),typeof i=="number"&&(n=n.filter(l=>l.price<=i)),(typeof r.inStock=="boolean"?r.inStock:void 0)===!0&&(n=n.filter(l=>l.inventoryStatus!=="out_of_stock")),n}function Qm(e,t){if(!t||t==="featured")return e;const n=[...e];return t==="price_asc"&&n.sort((r,o)=>r.price-o.price),t==="price_desc"&&n.sort((r,o)=>o.price-r.price),n}function Km(e,t,n){const r=(t-1)*n;return{items:e.slice(r,r+n),page:t,pageSize:n,total:e.length,hasNextPage:r+n<e.length}}function Jm(e){const t=new Date().toISOString(),n=e.cart.map(o=>{const a=ps.find(i=>i.id===o.resource||i.slug===o.resource)??ps[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),r=n.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:r,currency:e.options.currency,items:n,receiptUrl:e.options.successUrl}}function Xm(){let e=[];const t={};return{async listProducts(n){await jt(150);const r=n.page??1,o=n.pageSize??24,a=Ym(ps,n),i=Qm(a,n.sort);return Km(i,r,o)},async getProductBySlug(n){return await jt(100),ps.find(r=>r.slug===n)??null},async listCategories(){return await jt(80),Cl},async getOrderHistory(){return await jt(120),e},async getCart({customerId:n}){return await jt(80),t[n]??{items:[]}},async mergeCart({customerId:n,cart:r}){await jt(120);const o=t[n]??{items:[]},a=new Map,i=l=>{const d=`${l.productId}::${l.variantId??""}`,f=a.get(d);f?a.set(d,{...f,qty:f.qty+l.qty}):a.set(d,l)};for(const l of o.items)i(l);for(const l of r.items)i(l);const c={items:Array.from(a.values()),promoCode:r.promoCode??o.promoCode};return t[n]=c,c},async updateCart({customerId:n,cart:r}){await jt(60),t[n]=r},async createCheckoutSession(n){await jt(250);const r=Jm(n);if(e=[r,...e].slice(0,25),n.options.successUrl){const o=new URL(n.options.successUrl,"http://localhost");return o.searchParams.set("demoOrderId",r.id),{kind:"redirect",url:o.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:r.id}}},async listSubscriptionTiers(){return await jt(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 jt(80),{isActive:!1}},async createSubscriptionCheckoutSession(n){return await jt(200),n.successUrl?{kind:"redirect",url:n.successUrl}:{kind:"custom",data:n}}}}const Ri=50,eh=4,th=5,nh=1e4,rh={maxRetries:2,initialDelayMs:100,backoffFactor:2,maxDelayMs:500,jitter:!1};function Nl(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function sh(e){return e?e.toUpperCase():"USD"}function oh(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function ah(e){if(e&&(e==="physical"||e==="digital"))return e}function ih(e){const t=[];if(Array.isArray(e))for(const n of e)typeof n=="string"&&t.push(n);else if(typeof e=="string"){const n=e.trim();if(n.startsWith("["))try{const r=JSON.parse(n);if(Array.isArray(r))for(const o of r)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(n=>n.split(",")).map(n=>n.trim().toUpperCase()).filter(Boolean)}function Dn(e){const t=sh(e.fiatCurrency),n=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],r=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=ih(a);return{id:e.id,slug:e.slug??e.id,title:e.title??Nl(e.id),description:e.description??"",images:n,price:r/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:oh(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:ah(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function os(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],n=e.total??e.count;return{products:t,total:n}}async function Ct(e,t,n,r={}){const{body:o,headers:a,method:i="GET",retryableRead:c=!1,timeoutMs:l=nh}=r,d={};n&&(d["X-API-Key"]=n),a&&Object.assign(d,a);const f=async()=>{const u=await oe.fetchWithTimeout(`${e}${t}`,{body:o,headers:d,method:i},l);if(!u.ok){const m=await u.text().catch(()=>""),h=new Error(`Request failed (${u.status}): ${m}`);throw h.status=u.status,h}return u.json()};return c?oe.retryWithBackoff(f,{...rh,name:`paywall-read-${i.toLowerCase()}`}):f()}async function ch(e,t,n,r){const o=await Ct(e,`/paywall/v1/products?limit=${n}&offset=${r}`,t,{retryableRead:!0});return os(o)}async function Oi(e,t,n,r){const{maxPages:o,pageSize:a}=n;for(let i=0;i<o;i+=1){const c=i*a,{products:l,total:d}=await ch(e,t,a,c);if(l.length===0||r(l))return;const f=typeof d=="number"&&c+l.length>=d,u=l.length<a;if(f||u)return}}function lh(e){const t=async d=>{const f=d.page??1,u=d.pageSize??24,m=u,h=(f-1)*u,v=new URLSearchParams;v.set("limit",String(m)),v.set("offset",String(h)),d.search&&v.set("search",d.search),d.category&&v.set("category",d.category),d.sort&&v.set("sort",d.sort),d.filters?.inStock&&v.set("in_stock","true"),d.filters?.minPrice!=null&&v.set("min_price",String(d.filters.minPrice)),d.filters?.maxPrice!=null&&v.set("max_price",String(d.filters.maxPrice));const x=d.filters?.tags,g=Array.isArray(x)?x:typeof x=="string"?[x]:[];g.length&&v.set("tags",g.join(","));const y=await Ct(e.serverUrl,`/paywall/v1/products?${v.toString()}`,e.apiKey,{retryableRead:!0}),{products:k,total:_}=os(y);return{items:k.map(Dn),page:f,pageSize:u,total:_,hasNextPage:typeof _=="number"?h+m<_:k.length===m}},n=async d=>{try{const f=await Ct(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(d)}`,e.apiKey,{retryableRead:!0});return Dn(f)}catch(f){const u=f?.status;if(u!==404&&u!==405)throw f;try{const m=await Ct(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(d)}`,e.apiKey,{retryableRead:!0});return Dn(m)}catch(m){const h=m?.status;if(h!==404&&h!==405)throw m;let v;return await Oi(e.serverUrl,e.apiKey,{maxPages:eh,pageSize:Ri},x=>(v=x.find(g=>g.slug===d||g.id===d),!!v)),v?Dn(v):null}}};return{listProducts:t,getProductBySlug:n,getProductsByIds:async d=>{const f=Array.from(new Set(d.filter(Boolean)));if(f.length===0)return new Map;const u=new Map;try{const v=new URLSearchParams;v.set("ids",f.join(",")),v.set("limit",String(f.length)),v.set("offset","0");const x=await Ct(e.serverUrl,`/paywall/v1/products?${v.toString()}`,e.apiKey,{retryableRead:!0}),{products:g}=os(x);for(const y of g){const k=Dn(y);u.set(k.id,k),k.slug&&k.slug!==k.id&&u.set(k.slug,k)}}catch{}const m=f.filter(v=>!u.has(v));if(m.length===0)return u;let h=m;try{const v=new Set(h);if(await Oi(e.serverUrl,e.apiKey,{maxPages:th,pageSize:Ri},x=>{for(const g of x){const y=Dn(g);!v.has(y.id)&&!(y.slug&&v.has(y.slug))||(u.set(y.id,y),y.slug&&y.slug!==y.id&&u.set(y.slug,y),v.delete(y.id),y.slug&&v.delete(y.slug))}return v.size===0}),h=Array.from(v),h.length===0)return u}catch{}for(const v of h)try{const x=await n(v);x&&(u.set(x.id,x),x.slug&&x.slug!==x.id&&u.set(x.slug,x))}catch{}return u},listCategories:async()=>{const d=await Ct(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey,{retryableRead:!0}),{products:f}=os(d),u=new Set;for(const m of f)for(const h of m.categoryIds??[])u.add(h);return Array.from(u).map(m=>({id:m,slug:m,name:Nl(m)}))},getOrderHistory:async()=>[],createCheckoutSession:async d=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await Ct(e.serverUrl,"/admin/config/shop",e.apiKey,{retryableRead:!0})).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[d,f,u]=await Promise.allSettled([Ct(e.serverUrl,"/admin/config/stripe",e.apiKey,{retryableRead:!0}),Ct(e.serverUrl,"/admin/config/x402",e.apiKey,{retryableRead:!0}),Ct(e.serverUrl,"/admin/config/cedros_login",e.apiKey,{retryableRead:!0})]),m=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=f.status==="fulfilled"?!!f.value?.config?.enabled:!1,v=u.status==="fulfilled"?!!u.value?.config?.enabled:!1;return{card:m,crypto:h,credits:v}}catch{return null}},getAIRelatedProducts:async d=>Ct(e.serverUrl,"/admin/ai/related-products",e.apiKey,{method:"POST",body:JSON.stringify(d),headers:{"Content-Type":"application/json"},retryableRead:!1})}}function dh(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function vn(e){return`${e.productId}::${e.variantId??""}`}const uh={items:[]};function fh(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const n=Math.max(1,Math.floor(t.qty??1)),r=vn(t.item);return e.items.find(a=>vn(a)===r)?{...e,items:e.items.map(a=>vn(a)===r?{...a,qty:a.qty+n}:a)}:{...e,items:[...e.items,{...t.item,qty:n}]}}case"cart/remove":{const n=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(r=>vn(r)!==n)}}case"cart/setQty":{const n=Math.max(0,Math.floor(t.qty)),r=`${t.productId}::${t.variantId??""}`;return n===0?{...e,items:e.items.filter(o=>vn(o)!==r)}:{...e,items:e.items.map(o=>vn(o)===r?{...o,qty:n}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const n=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(r=>vn(r)===n?{...r,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:r)}}default:return dh(t)}}function ph(e){return e.reduce((t,n)=>t+n.qty,0)}function mh(e){return e.reduce((t,n)=>t+n.qty*n.unitPrice,0)}function Mi(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function hh(e,t){try{const n=e.getItem(t);return n?JSON.parse(n):null}catch{return null}}function gh(e,t,n){try{return e.setItem(t,JSON.stringify(n)),!0}catch(r){return console.warn(`[cedros] Failed to write "${t}" to storage`,r),!1}}const El=b.createContext(null);function Rt(){const e=b.useContext(El);if(!e)throw new Error("useCart must be used within CartProvider");return e}function Li(e){return!!e&&typeof e=="object"&&typeof e.productId=="string"&&e.productId.length>0&&typeof e.qty=="number"&&e.qty>0&&typeof e.unitPrice=="number"&&typeof e.currency=="string"&&typeof e.titleSnapshot=="string"}function xh({children:e}){const{config:t}=Pe(),n=t.cart?.storageKey??"cedros_shop_cart_v1",r=t.customer?.id,o=t.customer?.isSignedIn??!!r,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=b.useReducer(fh,uh),d=b.useRef(c);d.current=c;const[f,u]=b.useState(!1),m=b.useRef(!1),h=b.useRef(null),v=b.useRef(null);b.useEffect(()=>{const k=Mi();if(!k)return;const _=hh(k,n);if(_&&Array.isArray(_.items)){const w=_.items.filter(Li);l({type:"cart/hydrate",state:{items:w,promoCode:typeof _.promoCode=="string"?_.promoCode:void 0}})}u(!0)},[n]),b.useEffect(()=>{if(!f)return;const k=Mi();k&&gh(k,n,c)},[c,n,f]),b.useEffect(()=>{if(!f||!o||!r||!t.adapter.mergeCart&&!t.adapter.getCart||(v.current!==r&&(m.current=!1,h.current=null,v.current=r),m.current))return;let k=!1;return(async()=>{try{const _=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:r,cart:d.current}):await t.adapter.getCart({customerId:r});if(k)return;if(_&&Array.isArray(_.items)){m.current=!0;const w={..._,items:_.items.filter(Li)};l({type:"cart/hydrate",state:w}),h.current=JSON.stringify(w)}}catch{k||(m.current=!1)}})(),()=>{k=!0}},[t.adapter,r,f,o]),b.useEffect(()=>{if(!f||!o||!r||!t.adapter.updateCart||!m.current||typeof window>"u")return;const k=JSON.stringify(c);if(h.current===k)return;const _=window.setTimeout(()=>{t.adapter.updateCart({customerId:r,cart:c}).then(()=>{h.current=k}).catch(w=>{console.warn("[CedrosPay] Cart server sync failed:",w instanceof Error?w.message:w)})},a);return()=>window.clearTimeout(_)},[t.adapter,r,f,o,c,a]);const x=b.useCallback((k,_)=>{const w=c.items.find(j=>j.productId===k&&j.variantId===_);if(w)return{holdId:w.holdId,expiresAt:w.holdExpiresAt}},[c.items]),g=b.useCallback((k,_,w)=>{l({type:"cart/updateHold",productId:k,variantId:_,holdExpiresAt:w})},[]),y=b.useMemo(()=>{const k=ph(c.items),_=mh(c.items);return{items:c.items,promoCode:c.promoCode,count:k,subtotal:_,addItem:(w,j)=>l({type:"cart/add",item:w,qty:j}),removeItem:(w,j)=>l({type:"cart/remove",productId:w,variantId:j}),setQty:(w,j,P)=>l({type:"cart/setQty",productId:w,variantId:j,qty:P}),clear:()=>l({type:"cart/clear"}),setPromoCode:w=>l({type:"cart/setPromoCode",promoCode:w}),holdsSupported:i,getItemHold:x,updateItemHold:g}},[c.items,c.promoCode,i,x,g]);return s.jsx(El.Provider,{value:y,children:e})}function B(e,t,n){function r(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,f=Object.keys(d);for(let u=0;u<f.length;u++){const m=f[u];m in c||(c[m]=d[m].bind(c))}}const o=n?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=n?.Parent?new a:this;r(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const f of d._zod.deferred)f();return d}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Wn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Al extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Pl={};function kn(e){return Pl}function Il(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function Vo(e,t){return typeof t=="bigint"?t.toString():t}function va(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ya(e){return e==null}function ba(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function vh(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=n>o?n:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const Di=Symbol("evaluating");function _e(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Di)return r===void 0&&(r=Di,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function In(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function un(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function $i(e){return JSON.stringify(e)}function yh(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Tl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ms(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const bh=va(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function jr(e){if(ms(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(ms(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Rl(e){return jr(e)?{...e}:Array.isArray(e)?[...e]:e}const wh=new Set(["string","number","symbol"]);function Zn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function ce(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 _h(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const kh={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 jh(e,t){const n=e._zod.def,r=n.checks;if(r&&r.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 n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=n.shape[c])}return In(this,"shape",i),i},checks:[]});return fn(e,a)}function Sh(e,t){const n=e._zod.def,r=n.checks;if(r&&r.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 n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return In(this,"shape",i),i},checks:[]});return fn(e,a)}function Ch(e,t){if(!jr(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.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 In(this,"shape",a),a}});return fn(e,o)}function Nh(e,t){if(!jr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=un(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return In(this,"shape",r),r}});return fn(e,n)}function Eh(e,t){const n=un(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return In(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return fn(e,n)}function Ah(e,t,n){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(n)for(const d in n){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);n[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 In(this,"shape",l),l},checks:[]});return fn(t,i)}function Ph(e,t,n){const r=un(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(n)for(const i in n){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);n[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 In(this,"shape",a),a}});return fn(t,r)}function Vn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Ol(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Wr(e){return typeof e=="string"?e:e?.message}function jn(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=Wr(e.inst?._zod.def?.error?.(e))??Wr(t?.error?.(e))??Wr(n.customError?.(e))??Wr(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function wa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Sr(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const Ml=(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,Vo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ll=B("$ZodError",Ml),Dl=B("$ZodError",Ml,{Parent:Error});function Ih(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Th(e,t=n=>n.message){const n={_errors:[]},r=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>r({issues:i}));else if(a.code==="invalid_key")r({issues:a.issues});else if(a.code==="invalid_element")r({issues:a.issues});else if(a.path.length===0)n._errors.push(t(a));else{let i=n,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 r(e),n}const _a=e=>(t,n,r,o)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new Wn;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>jn(l,a,kn())));throw Tl(c,o?.callee),c}return i.value},ka=e=>async(t,n,r,o)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,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,kn())));throw Tl(c,o?.callee),c}return i.value},Rs=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new Wn;return a.issues.length?{success:!1,error:new(e??Ll)(a.issues.map(i=>jn(i,o,kn())))}:{success:!0,data:a.value}},Rh=Rs(Dl),Os=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>jn(i,o,kn())))}:{success:!0,data:a.value}},Oh=Os(Dl),Mh=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _a(e)(t,n,o)},Lh=e=>(t,n,r)=>_a(e)(t,n,r),Dh=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ka(e)(t,n,o)},$h=e=>async(t,n,r)=>ka(e)(t,n,r),zh=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Rs(e)(t,n,o)},Fh=e=>(t,n,r)=>Rs(e)(t,n,r),Bh=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Os(e)(t,n,o)},Uh=e=>async(t,n,r)=>Os(e)(t,n,r),Vh=/^[cC][^\s-]{8,}$/,Wh=/^[0-9a-z]+$/,qh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Hh=/^[0-9a-vA-V]{20}$/,Zh=/^[A-Za-z0-9]{27}$/,Gh=/^[a-zA-Z0-9_-]{21}$/,Yh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Qh=/^([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})$/,zi=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)$/,Kh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Jh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Xh(){return new RegExp(Jh,"u")}const eg=/^(?:(?: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])$/,tg=/^(([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}|:))$/,ng=/^((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])$/,rg=/^(([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])$/,sg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$l=/^[A-Za-z0-9_-]*$/,og=/^\+[1-9]\d{6,14}$/,zl="(?:(?:\\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])))",ag=new RegExp(`^${zl}$`);function Fl(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 ig(e){return new RegExp(`^${Fl(e)}$`)}function cg(e){const t=Fl({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${zl}T(?:${r})$`)}const lg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},dg=/^-?\d+$/,ug=/^-?\d+(?:\.\d+)?$/,fg=/^[^A-Z]*$/,pg=/^[^a-z]*$/,ut=B("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Bl={number:"number",bigint:"bigint",object:"date"},Ul=B("$ZodCheckLessThan",(e,t)=>{ut.init(e,t);const n=Bl[typeof t.value];e._zod.onattach.push(r=>{const o=r._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=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Vl=B("$ZodCheckGreaterThan",(e,t)=>{ut.init(e,t);const n=Bl[typeof t.value];e._zod.onattach.push(r=>{const o=r._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=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),mg=B("$ZodCheckMultipleOf",(e,t)=>{ut.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):vh(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),hg=B("$ZodCheckNumberFormat",(e,t)=>{ut.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,a]=kh[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,n&&(c.pattern=dg)}),e._zod.check=i=>{const c=i.value;if(n){if(!Number.isInteger(c)){i.issues.push({expected:r,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:r,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:r,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})}}),gg=B("$ZodCheckMaxLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ya(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const i=wa(o);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),xg=B("$ZodCheckMinLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ya(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const i=wa(o);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),vg=B("$ZodCheckLengthEquals",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ya(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,a=o.length;if(a===t.length)return;const i=wa(o),c=a>t.length;r.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Ms=B("$ZodCheckStringFormat",(e,t)=>{var n,r;ut.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?(n=e._zod).check??(n.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})}):(r=e._zod).check??(r.check=()=>{})}),yg=B("$ZodCheckRegex",(e,t)=>{Ms.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),bg=B("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=fg),Ms.init(e,t)}),wg=B("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=pg),Ms.init(e,t)}),_g=B("$ZodCheckIncludes",(e,t)=>{ut.init(e,t);const n=Zn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),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})}}),kg=B("$ZodCheckStartsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`^${Zn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),jg=B("$ZodCheckEndsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`.*${Zn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Sg=B("$ZodCheckOverwrite",(e,t)=>{ut.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Cg{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 r=t.split(`
|
|
2
2
|
`).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),a=r.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,n=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...n,o.join(`
|
|
3
3
|
`))}}const Ng={major:4,minor:3,patch:6},Me=B("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ng;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const a of o._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(i,c,l)=>{let d=Vn(i),f;for(const u of c){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(d)continue;const m=i.issues.length,h=u._zod.check(i);if(h instanceof Promise&&l?.async===!1)throw new Wn;if(f||h instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await h,i.issues.length!==m&&(d||(d=Vn(i,m)))});else{if(i.issues.length===m)continue;d||(d=Vn(i,m))}}return f?f.then(()=>i):i},a=(i,c,l)=>{if(Vn(i))return i.aborted=!0,i;const d=o(c,r,l);if(d instanceof Promise){if(l.async===!1)throw new Wn;return d.then(f=>e._zod.parse(f,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(f=>a(f,i,c)):a(d,i,c)}const l=e._zod.parse(i,c);if(l instanceof Promise){if(c.async===!1)throw new Wn;return l.then(d=>o(d,r,c))}return o(l,r,c)}}_e(e,"~standard",()=>({validate:o=>{try{const a=Rh(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return Oh(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),ja=B("$ZodString",(e,t)=>{Me.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??lg(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ee=B("$ZodStringFormat",(e,t)=>{Ms.init(e,t),ja.init(e,t)}),Eg=B("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Qh),Ee.init(e,t)}),Ag=B("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=zi(r))}else t.pattern??(t.pattern=zi());Ee.init(e,t)}),Pg=B("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Kh),Ee.init(e,t)}),Ig=B("$ZodURL",(e,t)=>{Ee.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.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)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Tg=B("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Xh()),Ee.init(e,t)}),Rg=B("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Gh),Ee.init(e,t)}),Og=B("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Vh),Ee.init(e,t)}),Mg=B("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Wh),Ee.init(e,t)}),Lg=B("$ZodULID",(e,t)=>{t.pattern??(t.pattern=qh),Ee.init(e,t)}),Dg=B("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Hh),Ee.init(e,t)}),$g=B("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Zh),Ee.init(e,t)}),zg=B("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=cg(t)),Ee.init(e,t)}),Fg=B("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ag),Ee.init(e,t)}),Bg=B("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=ig(t)),Ee.init(e,t)}),Ug=B("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Yh),Ee.init(e,t)}),Vg=B("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=eg),Ee.init(e,t),e._zod.bag.format="ipv4"}),Wg=B("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=tg),Ee.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),qg=B("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ng),Ee.init(e,t)}),Hg=B("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=rg),Ee.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[o,a]=r;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{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Wl(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Zg=B("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=sg),Ee.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Wl(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Gg(e){if(!$l.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Wl(n)}const Yg=B("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=$l),Ee.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{Gg(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Qg=B("$ZodE164",(e,t)=>{t.pattern??(t.pattern=og),Ee.init(e,t)});function Kg(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const Jg=B("$ZodJWT",(e,t)=>{Ee.init(e,t),e._zod.check=n=>{Kg(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),ql=B("$ZodNumber",(e,t)=>{Me.init(e,t),e._zod.pattern=e._zod.bag.pattern??ug,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const a=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...a?{received:a}:{}}),n}}),Xg=B("$ZodNumberFormat",(e,t)=>{hg.init(e,t),ql.init(e,t)}),ex=B("$ZodUnknown",(e,t)=>{Me.init(e,t),e._zod.parse=n=>n}),tx=B("$ZodNever",(e,t)=>{Me.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Fi(e,t,n){e.issues.length&&t.issues.push(...Ol(n,e.issues)),t.value[n]=e.value}const nx=B("$ZodArray",(e,t)=>{Me.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.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:[]},r);l instanceof Promise?a.push(l.then(d=>Fi(d,n,i))):Fi(l,n,i)}return a.length?Promise.all(a).then(()=>n):n}});function hs(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...Ol(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function Hl(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_h(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Zl(e,t,n,r,o,a){const i=[],c=o.keySet,l=o.catchall._zod,d=l.def.type,f=l.optout==="optional";for(const u in t){if(c.has(u))continue;if(d==="never"){i.push(u);continue}const m=l.run({value:t[u],issues:[]},r);m instanceof Promise?e.push(m.then(h=>hs(h,n,u,t,f))):hs(m,n,u,t,f)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const rx=B("$ZodObject",(e,t)=>{if(Me.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 r=va(()=>Hl(t));_e(e._zod,"propValues",()=>{const c=t.shape,l={};for(const d in c){const f=c[d]._zod;if(f.values){l[d]??(l[d]=new Set);for(const u of f.values)l[d].add(u)}}return l});const o=ms,a=t.catchall;let i;e._zod.parse=(c,l)=>{i??(i=r.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 f=[],u=i.shape;for(const m of i.keys){const h=u[m],v=h._zod.optout==="optional",x=h._zod.run({value:d[m],issues:[]},l);x instanceof Promise?f.push(x.then(g=>hs(g,c,m,d,v))):hs(x,c,m,d,v)}return a?Zl(f,d,c,l,r.value,e):f.length?Promise.all(f).then(()=>c):c}}),sx=B("$ZodObjectJIT",(e,t)=>{rx.init(e,t);const n=e._zod.parse,r=va(()=>Hl(t)),o=m=>{const h=new Cg(["shape","payload","ctx"]),v=r.value,x=_=>{const w=$i(_);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};h.write("const input = payload.value;");const g=Object.create(null);let y=0;for(const _ of v.keys)g[_]=`key_${y++}`;h.write("const newResult = {};");for(const _ of v.keys){const w=g[_],j=$i(_),T=m[_]?._zod?.optout==="optional";h.write(`const ${w} = ${x(_)};`),T?h.write(`
|
|
4
4
|
if (${w}.issues.length) {
|