@cedros/pay-react 1.1.14 → 1.1.15
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/components/admin/StorefrontSection.d.ts.map +1 -1
- package/dist/components/admin/configApi.d.ts.map +1 -1
- package/dist/crypto-only.js +1 -1
- package/dist/crypto-only.mjs +2 -2
- package/dist/{index-CdyuXqXT.mjs → index-BjxGupjw.mjs} +699 -656
- package/dist/{index-FGF9nfl8.js → index-DW6XWuRP.js} +17 -17
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/pay-react.css +1 -1
- package/dist/{sections-BF5Zky5V.js → sections-DG4Ws13b.js} +1 -1
- package/dist/{sections-Dsma4UNK.mjs → sections-Dl8qjlql.mjs} +1 -1
- package/dist/stripe-only.js +1 -1
- package/dist/stripe-only.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var Xp=Object.create;var qi=Object.defineProperty;var Jp=Object.getOwnPropertyDescriptor;var ef=Object.getOwnPropertyNames;var tf=Object.getPrototypeOf,nf=Object.prototype.hasOwnProperty;var rf=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ef(t))!nf.call(e,o)&&o!==r&&qi(e,o,{get:()=>t[o],enumerable:!(s=Jp(t,o))||s.enumerable});return e};var sf=(e,t,r)=>(r=e!=null?Xp(tf(e)):{},rf(t||!e||!e.__esModule?qi(r,"default",{value:e,enumerable:!0}):r,e));const n=require("react/jsx-runtime"),y=require("react"),J=require("./CedrosContext-C2v_s8cc.js"),ja=require("@solana/wallet-adapter-react"),Hi=require("@solana/wallet-adapter-base"),of=require("@solana/wallet-adapter-react-ui"),af=require("@solana/web3.js"),cf=require("@cedros/login-react"),Zi=require("./index-WcOlBYZJ.js"),ka=require("react-dom");function wl(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const x=wl(y),Is=wl(ka);function lf(e){return!e||!e.coupon_codes?[]:e.coupon_codes.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function df(e,t=", "){return e.join(t)}function uf(e,t){return e<=0?0:(e-t)/e*100}function mf(e,t){if(!t||t.length===0)return e;let r=e,s=0;for(const o of t)if(o.discountType==="percentage"){const a=1-o.discountValue/100;r=r*a}else o.discountType==="fixed"&&(s+=o.discountValue);return r=r-s,r<0&&(r=0),Math.ceil(r*100)/100}function _l(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return 1;const r=Math.floor(t);return r>0?r:1}function ps(e){return e.map(t=>({resource:t.resource,quantity:_l(t.quantity),variantId:t.variantId,metadata:t.metadata}))}function dn(e){return e.reduce((t,r)=>t+_l(r.quantity),0)}function pf(e){return!!(e&&e.length>0&&(e.length>1||e.length===1&&(e[0].quantity??1)>1))}const ff={invalid_payment_proof:{message:"Payment verification failed",action:"Please try your payment again. If this continues, contact support.",technicalHint:"Invalid payment proof format"},invalid_signature:{message:"Transaction signature is invalid",action:"Please approve the transaction in your wallet and try again.",technicalHint:"Transaction signature verification failed"},invalid_transaction:{message:"Transaction format is invalid",action:"Please try your payment again. If this continues, try updating your wallet app.",technicalHint:"Malformed transaction structure"},transaction_not_found:{message:"Transaction not found on the blockchain",action:"Your transaction may still be processing. Please wait a moment and check your wallet, or try again.",technicalHint:"Transaction signature not found on-chain"},transaction_not_confirmed:{message:"Transaction is still processing",action:"Please wait a moment for the blockchain to confirm your transaction, then try again.",technicalHint:"Transaction not yet confirmed"},transaction_failed:{message:"Transaction failed on the blockchain",action:"Check your wallet for details. You may need to adjust your transaction settings or add more SOL for fees.",technicalHint:"On-chain transaction failure"},transaction_expired:{message:"Transaction took too long to process",action:"Please try your payment again. Consider increasing transaction priority if your wallet supports it.",technicalHint:"Transaction blockhash expired"},invalid_recipient:{message:"Payment was sent to the wrong address",action:"Please try again and ensure you approve the correct transaction in your wallet.",technicalHint:"Recipient address mismatch"},invalid_sender:{message:"Payment sender wallet is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Sender address validation failed"},unauthorized_refund_issuer:{message:"You are not authorized to issue refunds",action:"Only authorized accounts can process refunds. Please contact support if you believe this is an error.",technicalHint:"Refund issuer not in authorized list"},amount_below_minimum:{message:"Payment amount is too low",action:"Please check the required amount and try again.",technicalHint:"Amount below minimum threshold"},amount_mismatch:{message:"Payment amount does not match the quote",action:"The price may have changed. Please refresh and try your payment again.",technicalHint:"Amount does not match quote"},insufficient_funds_sol:{message:"Not enough SOL for transaction fees",action:"Add at least 0.001 SOL to your wallet to cover network fees, then try again.",technicalHint:"Insufficient SOL balance for fees"},insufficient_funds_token:{message:"Insufficient balance in your wallet",action:"Add more funds to your wallet and try again.",technicalHint:"Insufficient token balance"},invalid_token_mint:{message:"Incorrect payment token",action:"Please pay with the correct token as shown in the payment details.",technicalHint:"Token mint address mismatch"},not_spl_transfer:{message:"Transaction is not a valid token transfer",action:"Please ensure you are sending the correct token type from your wallet.",technicalHint:"Transaction is not an SPL token transfer"},missing_token_account:{message:"Token account not found",action:"Your wallet may need to create a token account first. Try again or use a different wallet.",technicalHint:"Associated token account does not exist"},invalid_token_program:{message:"Invalid token program",action:"Please try your payment again. If this continues, try using a different wallet.",technicalHint:"Token program ID mismatch"},missing_memo:{message:"Payment memo is required but was not included",action:"Please try your payment again and ensure transaction details are approved in your wallet.",technicalHint:"Required memo instruction missing"},invalid_memo:{message:"Payment memo format is invalid",action:"Please try your payment again.",technicalHint:"Memo does not match expected format"},payment_already_used:{message:"This payment has already been processed",action:"Check your transaction history. If you need to make another payment, please start a new transaction.",technicalHint:"Payment signature already recorded"},signature_reused:{message:"Transaction signature has already been used",action:"Please create a new payment transaction.",technicalHint:"Duplicate signature detected"},quote_expired:{message:"Payment quote has expired",action:"Prices are updated frequently. Please refresh and try your payment again.",technicalHint:"Quote timestamp expired"},missing_field:{message:"Required information is missing",action:"Please check all required fields and try again.",technicalHint:"Required field not provided"},invalid_field:{message:"Some information is invalid",action:"Please check your input and try again.",technicalHint:"Field validation failed"},invalid_amount:{message:"Payment amount is invalid",action:"Please check the amount and try again.",technicalHint:"Amount validation failed"},invalid_wallet:{message:"Wallet address is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Wallet address validation failed"},invalid_resource:{message:"Invalid item selection",action:"Please refresh the page and try again.",technicalHint:"Resource ID validation failed"},invalid_coupon:{message:"Invalid coupon code",action:"Please check the coupon code and try again.",technicalHint:"Coupon code format invalid"},invalid_cart_item:{message:"One or more cart items are invalid",action:"Please review your cart and try again.",technicalHint:"Cart item validation failed"},empty_cart:{message:"Your cart is empty",action:"Please add items to your cart before checking out.",technicalHint:"Cart contains no items"},resource_not_found:{message:"Item not found",action:"This item may no longer be available. Please refresh and try again.",technicalHint:"Resource not found in database"},cart_not_found:{message:"Shopping cart not found",action:"Your cart may have expired. Please start a new order.",technicalHint:"Cart ID not found"},refund_not_found:{message:"Refund not found",action:"Please check your refund reference number or contact support.",technicalHint:"Refund ID not found"},product_not_found:{message:"Product not available",action:"This product may no longer be available. Please browse our current selection.",technicalHint:"Product ID not found"},coupon_not_found:{message:"Coupon code not found",action:"Please check the coupon code or remove it to continue.",technicalHint:"Coupon code not in database"},session_not_found:{message:"Payment session expired",action:"Please start a new payment.",technicalHint:"Session ID not found or expired"},cart_already_paid:{message:"This order has already been paid",action:"Check your order history. If you need to make another purchase, please start a new order.",technicalHint:"Cart marked as paid"},refund_already_processed:{message:"This refund has already been processed",action:"Check your transaction history or contact support for details.",technicalHint:"Refund already completed"},coupon_expired:{message:"Coupon has expired",action:"Please remove the coupon code or use a different code.",technicalHint:"Coupon expiration date passed"},coupon_usage_limit_reached:{message:"Coupon usage limit reached",action:"This coupon has been fully redeemed. Please try a different code.",technicalHint:"Coupon max uses exceeded"},coupon_not_applicable:{message:"Coupon cannot be applied to this purchase",action:"Please check the coupon terms or remove it to continue.",technicalHint:"Coupon conditions not met"},coupon_wrong_payment_method:{message:"Coupon not valid for this payment method",action:"Try a different payment method or remove the coupon code.",technicalHint:"Coupon restricted to specific payment methods"},stripe_error:{message:"Card payment service temporarily unavailable",action:"Please try again in a moment, or use cryptocurrency payment instead.",technicalHint:"Stripe API error"},rpc_error:{message:"Blockchain network temporarily unavailable",action:"Please try again in a moment, or use card payment instead.",technicalHint:"Solana RPC error"},network_error:{message:"Network connection issue",action:"Please check your internet connection and try again.",technicalHint:"Network request failed"},internal_error:{message:"Something went wrong on our end",action:"Please try again. If this continues, contact support.",technicalHint:"Internal server error"},database_error:{message:"Service temporarily unavailable",action:"Please try again in a moment.",technicalHint:"Database operation failed"},config_error:{message:"Service configuration error",action:"Please contact support for assistance.",technicalHint:"Server misconfiguration"}};function fs(e){return ff[e]||{message:"An unexpected error occurred",action:"Please try again or contact support if this continues.",technicalHint:`Unknown error code: ${e}`}}const jl=new Map,Yo=new Map,Ko=new Map,kl=200,Sa=2e3;function hf(e){const t=Ko.get(e);return t?Date.now()<t?!0:(Ko.delete(e),!1):!1}function gf(e,t=kl){const r=Date.now()+t;Ko.set(e,r)}function xf(e,t=Sa){const r=jl.get(e);if(!r)return!1;const o=Date.now()-r;return o<t?(J.getLogger().debug(`[Deduplication] Duplicate request blocked: ${e} (${o}ms ago)`),!0):!1}function yf(e){jl.set(e,Date.now())}function vf(e){return Yo.get(e)||null}function bf(e,t){Yo.set(e,t);const r=()=>{Yo.delete(e),yf(e)};return t.then(r,r),t}async function wf(e,t,r={}){const{windowMs:s=Sa,throwOnDuplicate:o=!0}=r,a=vf(e);if(a)return J.getLogger().debug(`[Deduplication] Reusing in-flight request: ${e}`),a;if(xf(e,s)){if(o)throw new Error(`Duplicate request blocked: ${e}`);return J.getLogger().warn(`[Deduplication] Duplicate request blocked but not throwing: ${e}`),Promise.reject(new Error("Duplicate request"))}const i=t();return bf(e,i)}function Mn(e,t,r={}){const{cooldownMs:s=kl,deduplicationWindowMs:o=Sa}=r;return async()=>{if(hf(e)){J.getLogger().debug(`[Deduplication] Button in cooldown: ${e}`);return}gf(e,s);try{await wf(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 Ca(e){return{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:e,opacity:.6,padding:"0.25rem",lineHeight:1}}const gn={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 Dn(e,t){if(typeof window>"u")return;const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!1});window.dispatchEvent(r)}function Ln(e,t,r){Dn(gn.PAYMENT_START,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function Xo(e){Dn(gn.WALLET_CONNECT,{timestamp:Date.now(),wallet:e})}function Sl(e,t){Dn(gn.WALLET_CONNECTED,{timestamp:Date.now(),wallet:e,publicKey:t})}function is(e,t){Dn(gn.WALLET_ERROR,{timestamp:Date.now(),wallet:t,error:e})}function un(e,t,r){Dn(gn.PAYMENT_PROCESSING,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function $n(e,t,r,s){Dn(gn.PAYMENT_SUCCESS,{timestamp:Date.now(),method:e,transactionId:t,resource:r,itemCount:s})}function kt(e,t,r,s){Dn(gn.PAYMENT_ERROR,{timestamp:Date.now(),method:e,error:t,resource:r,itemCount:s})}class ln extends Error{code;retryable;details;httpStatus;constructor(t,r,s=!1,o,a){super(r),this.name="PaymentError",this.code=t,this.retryable=s,this.details=o,this.httpStatus=a,Object.setPrototypeOf(this,ln.prototype)}canRetry(){return this.retryable}is(t){return this.code===t}isInCategory(t){return t.includes(this.code)}getUserMessage(){const t=this.getErrorInfo();return t.action?`${t.message} ${t.action}`:t.message}getShortMessage(){return this.getErrorInfo().message}getAction(){return this.getErrorInfo().action}getErrorInfo(){return fs(this.code)}static fromErrorResponse(t,r){const s=t.error.retryable??Cl.RETRYABLE.includes(t.error.code);return new ln(t.error.code,t.error.message,s,t.error.details,r)}static fromUnknown(t){return t instanceof ln?t:t instanceof Error?new ln("internal_error",t.message,!1):new ln("internal_error",String(t),!1)}}const Cl={INSUFFICIENT_FUNDS:["insufficient_funds_sol","insufficient_funds_token"],TRANSACTION_PENDING:["transaction_not_confirmed","transaction_not_found"],VALIDATION:["missing_field","invalid_field","invalid_amount","invalid_wallet","invalid_resource","invalid_cart_item","empty_cart"],COUPON:["invalid_coupon","coupon_not_found","coupon_expired","coupon_usage_limit_reached","coupon_not_applicable","coupon_wrong_payment_method"],RETRYABLE:["transaction_not_confirmed","rpc_error","network_error","stripe_error"],NOT_FOUND:["resource_not_found","cart_not_found","refund_not_found","product_not_found","coupon_not_found","session_not_found","credits_hold_not_found"],CREDITS:["insufficient_credits","credits_hold_expired","credits_hold_not_found"],SECURITY:["invalid_redirect_url","rate_limit_exceeded","nonce_already_used"]};function _f(e){return e instanceof ln&&e.canRetry()}function jf(e){return e instanceof ln?e.getUserMessage():e instanceof Error?e.message:String(e)}function kf(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 Sf(e){try{const t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e}}function Nl(e={}){const{solanaCluster:t="mainnet-beta",solanaEndpoint:r,customRpcProviders:s=[],allowUnsafeScripts:o=!1,additionalScriptSrc:a=[],additionalConnectSrc:i=[],additionalFrameSrc:c=[],includeStripe:l=!0}=e;o&&console.warn("[CedrosPay] SECURITY WARNING: allowUnsafeScripts is enabled. This adds 'unsafe-inline' and 'unsafe-eval' to script-src, which significantly weakens CSP protection against XSS attacks. Only use this in development or if absolutely required by your framework.");const d=["'self'"];o&&d.push("'unsafe-inline'","'unsafe-eval'"),l&&d.push("https://js.stripe.com"),d.push(...a);const m=["'self'"];l&&m.push("https://api.stripe.com","https://*.stripe.com");const u=kf(t);if(m.push(u),r){const h=Sf(r);m.includes(h)||m.push(h)}s.forEach(h=>{m.includes(h)||m.push(h)}),m.push(...i);const p=["'self'"];return l&&p.push("https://js.stripe.com","https://checkout.stripe.com"),p.push(...c),{scriptSrc:d,connectSrc:m,frameSrc:p}}function Pl(e,t="header"){const{scriptSrc:r,connectSrc:s,frameSrc:o}=e;switch(t){case"header":case"meta":case"nextjs":case"nginx":{const a=[];return r.length>0&&a.push(`script-src ${r.join(" ")}`),s.length>0&&a.push(`connect-src ${s.join(" ")}`),o.length>0&&a.push(`frame-src ${o.join(" ")}`),a.join("; ")}case"helmet":{const a={};return r.length>0&&(a.scriptSrc=r),s.length>0&&(a.connectSrc=s),o.length>0&&(a.frameSrc=o),a}case"directives":return{scriptSrc:r,connectSrc:s,frameSrc:o};default:throw new Error(`Unknown CSP format: ${t}`)}}function Cf(e={},t="header"){const r=Nl(e);return Pl(r,t)}const Nf={HELIUS:"https://*.helius-rpc.com",QUICKNODE:"https://*.quicknode.pro",ALCHEMY:"https://*.alchemy.com",ANKR:"https://rpc.ankr.com",TRITON:"https://*.rpcpool.com"},Pf={MAINNET_CUSTOM_RPC:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),MAINNET_NEXTJS:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),DEVNET:()=>({solanaCluster:"devnet",allowUnsafeScripts:!1}),CRYPTO_ONLY:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,includeStripe:!1}),STRIPE_ONLY:()=>({solanaCluster:"mainnet-beta",includeStripe:!0,customRpcProviders:[]})};function kr(e){return new Date(e).toLocaleString()}function Rs(){const{stripeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,transactionId:null}),s=y.useRef(!1),o=y.useCallback(async(c,l,d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const h={resource:c,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p};try{const _=await e.processPayment(h);return r({status:_.success?"success":"error",error:_.success?null:_.error||"Payment failed",transactionId:_.success&&_.transactionId||null}),_}catch(_){const g=_ instanceof Error?_.message:"Payment failed";return r({status:"error",error:g,transactionId:null}),{success:!1,error:g}}finally{s.current=!1}},[e]),a=y.useCallback(async(c,l,d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const h=ps(c);try{const _=await e.processCartCheckout({items:h,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p});return r({status:_.success?"success":"error",error:_.success?null:_.error||"Cart checkout failed",transactionId:_.success&&_.transactionId||null}),_}catch(_){const g=_ instanceof Error?_.message:"Cart checkout failed";return r({status:"error",error:g,transactionId:null}),{success:!1,error:g}}finally{s.current=!1}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,transactionId:null}),s.current=!1},[]);return{...t,processPayment:o,processCartCheckout:a,reset:i}}function nr(e,t){return y.useMemo(()=>{const r=pf(t),s=e||(t?.length===1?t[0].resource:"");return{isCartMode:r,effectiveResource:s}},[e,t])}const Af=(e,t,r)=>{const s=e[t];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((o,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},vo=new Map;let Wr=null;async function Gi(e){if(vo.has(e))return vo.get(e);try{const t=await Af(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),r=t.default||t;return vo.set(e,r),r}catch{return null}}async function Ef(){if(Wr)return Wr;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 r in e){const s=r.match(/\.\/translations\/([a-z]{2,3}(?:-[A-Z]{2})?)\.json$/);s&&t.push(s[1])}return Wr=t.length>0?t:["en"],Wr}function Al(){return typeof navigator>"u"?"en":(navigator.language||navigator.userLanguage||"en").split("-")[0].toLowerCase()}async function El(e){let t=await Gi(e);if(t||(t=await Gi("en"),t))return t;throw new Error("Critical: No translation files found, not even en.json")}function Tl(e){return(t,r)=>{const s=t.split(".");let o=e;for(const a of s)if(o&&typeof o=="object"&&a in o)o=o[a];else return t;return typeof o!="string"?t:r?Object.entries(r).reduce((a,[i,c])=>a.replace(new RegExp(`\\{${i}\\}`,"g"),c),o):o}}function Tf(e,t,r=!0){const s=t.errors[e];if(!s){const o=fs(e);return r&&o.action?`${o.message} ${o.action}`:o.message}return r&&s.action?`${s.message} ${s.action}`:s.message}function xn(e){const[t,r]=y.useState(null),[s,o]=y.useState(!0),a=y.useMemo(()=>e||Al(),[e]);return y.useEffect(()=>{let c=!1;return(async()=>{o(!0);try{const d=await El(a);c||(r(d),o(!1))}catch(d){console.error("[CedrosPay] Failed to load translations:",d),c||o(!1)}})(),()=>{c=!0}},[a]),{t:y.useMemo(()=>t?Tl(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:s,translations:t}}function If(e,t=!0){const{translations:r}=xn();if(!r){const o=fs(e);return t&&o.action?`${o.message} ${o.action}`:o.message}const s=r.errors[e];if(!s){const o=fs(e);return t&&o.action?`${o.message} ${o.action}`:o.message}return t&&s.action?`${s.message} ${s.action}`:s.message}function Na({resource:e,items:t,successUrl:r,cancelUrl:s,metadata:o,customerEmail:a,couponCode:i,label:c,disabled:l=!1,onAttempt:d,onSuccess:m,onError:u,className:p=""}){const{status:h,error:_,transactionId:g,processPayment:f,processCartCheckout:w}=Rs(),j=J.useCedrosTheme(),{isCartMode:b,effectiveResource:v}=nr(e,t),{t:k,translations:R}=xn(),N=c||k("ui.pay_with_card"),C=j.unstyled?p:`${j.className} cedros-theme__stripe-button ${p}`.trim(),T=_&&typeof _!="string"?_?.code??null:null,$=_?typeof _=="string"?_:(E=>{if(!E||!R)return"";const P=R.errors[E];return P?P.action?`${P.message} ${P.action}`:P.message:""})(T):null,S=y.useCallback(async()=>{J.getLogger().debug("[StripeButton] executePayment with couponCode:",i);const E=b&&t?dn(t):void 0;if(Ln("stripe",v,E),d&&d("stripe"),!b&&!v){const z="Invalid payment configuration: missing resource or items";J.getLogger().error("[StripeButton]",z),kt("stripe",z,v,E),u&&u(z);return}let P;un("stripe",v,E),b&&t?(J.getLogger().debug("[StripeButton] Processing cart checkout with coupon:",i),P=await w(t,r,s,o,a,i)):v&&(J.getLogger().debug("[StripeButton] Processing single payment with coupon:",i),P=await f(v,r,s,o,a,i)),P&&P.success&&P.transactionId?($n("stripe",P.transactionId,v,E),m&&m(P.transactionId)):P&&!P.success&&P.error&&(kt("stripe",P.error,v,E),u&&u(P.error))},[i,b,v,t,r,s,o,a,w,f,d,m,u]),A=y.useMemo(()=>b&&t?`stripe-cart-${t.map(E=>E.resource).join("-")}`:`stripe-${v||"unknown"}`,[b,t,v]),I=y.useMemo(()=>Mn(A,S),[A,S]),B=h==="loading",D=l||B;return n.jsxs("div",{className:C,style:j.unstyled?{}:j.style,children:[n.jsx("button",{onClick:I,disabled:D,className:j.unstyled?p:"cedros-theme__button cedros-theme__stripe",type:"button",children:B?k("ui.processing"):N}),$&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__error",children:$}),g&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__success",children:k("ui.payment_successful")})]})}function Il(){const{creditsManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s=y.useRef(!1),o=y.useCallback(async(d,m)=>{r(u=>({...u,status:"loading",error:null}));try{const u=await e.requestQuote(d,m);return r(p=>({...p,status:"idle",requirement:u})),u}catch(u){const p=u instanceof Error?u.message:"Failed to fetch credits quote";return r(h=>({...h,status:"error",error:p})),null}},[e]),a=y.useCallback(async(d,m)=>{r(u=>({...u,status:"loading",error:null}));try{const u=ps(d),p=await e.requestCartQuote(u,m);return r(h=>({...h,status:"idle"})),p}catch(u){const p=u instanceof Error?u.message:"Failed to fetch cart credits quote";return r(h=>({...h,status:"error",error:p})),null}},[e]),i=y.useCallback(async(d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=await e.processPayment(d,m,u,p);return r({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}finally{s.current=!1}},[e]),c=y.useCallback(async(d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=ps(d),_=await e.requestCartQuote(h,u);if(!_)return r({status:"error",error:"Credits payment not available for this cart",transactionId:null,requirement:null,holdId:null}),{success:!1,error:"Credits payment not available"};const f=(await e.createCartHold({cartId:_.cartId,authToken:m})).holdId;r(j=>({...j,holdId:f}));const w=await e.authorizeCartPayment({cartId:_.cartId,holdId:f,authToken:m,metadata:p});return r({status:w.success?"success":"error",error:w.success?null:w.error||"Cart credits payment failed",transactionId:w.success&&w.transactionId||null,requirement:null,holdId:null}),{success:w.success,transactionId:w.transactionId,error:w.error}}catch(h){const _=h instanceof Error?h.message:"Cart credits payment failed";return r({status:"error",error:_,transactionId:null,requirement:null,holdId:null}),{success:!1,error:_}}finally{s.current=!1}},[e]),l=y.useCallback(()=>{r({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s.current=!1},[]);return{...t,fetchQuote:o,fetchCartQuote:a,processPayment:i,processCartPayment:c,reset:l}}function Pa({resource:e,items:t,authToken:r,metadata:s,couponCode:o,label:a,disabled:i=!1,onAttempt:c,onSuccess:l,onError:d,className:m=""}){const{status:u,error:p,transactionId:h,processPayment:_,processCartPayment:g}=Il(),f=J.useCedrosTheme(),{isCartMode:w,effectiveResource:j}=nr(e,t),{t:b,translations:v}=xn(),k=a||b("ui.pay_with_credits")||"Pay with Credits",R=f.unstyled?m:`${f.className} cedros-theme__credits-button ${m}`.trim(),N=p&&typeof p!="string"?p?.code??null:null,T=p?typeof p=="string"?p:(B=>{if(!B||!v)return"";const D=v.errors[B];return D?D.action?`${D.message} ${D.action}`:D.message:""})(N):null,O=y.useCallback(async()=>{J.getLogger().debug("[CreditsButton] executePayment");const B=w&&t?dn(t):void 0;if(Ln("credits",j,B),c&&c("credits"),!r){const E="Authentication required: please log in to pay with credits";J.getLogger().error("[CreditsButton]",E),kt("credits",E,j,B),d&&d(E);return}if(!w&&!j){const E="Invalid payment configuration: missing resource";J.getLogger().error("[CreditsButton]",E),kt("credits",E,j,B),d&&d(E);return}let D;un("credits",j,B),w&&t?(J.getLogger().debug("[CreditsButton] Processing cart checkout"),D=await g(t,r,o,s)):j&&(J.getLogger().debug("[CreditsButton] Processing single payment"),D=await _(j,r,o,s)),D&&D.success&&D.transactionId?($n("credits",D.transactionId,j,B),l&&l(D.transactionId)):D&&!D.success&&D.error&&(kt("credits",D.error,j,B),d&&d(D.error))},[r,w,j,t,o,s,_,g,c,l,d]),$=y.useMemo(()=>w&&t?`credits-cart-${t.map(B=>B.resource).join("-")}`:`credits-${j||"unknown"}`,[w,t,j]),S=y.useMemo(()=>Mn($,O),[$,O]),A=u==="loading",I=i||A;return n.jsxs("div",{className:R,style:f.unstyled?{}:f.style,children:[n.jsx("button",{onClick:S,disabled:I,className:f.unstyled?m:"cedros-theme__button cedros-theme__credits",type:"button",children:A?b("ui.processing"):k}),T&&n.jsx("div",{className:f.unstyled?"":"cedros-theme__error",children:T}),h&&n.jsx("div",{className:f.unstyled?"":"cedros-theme__success",children:b("ui.payment_successful")})]})}function Rl(){const{x402Manager:e,walletManager:t}=J.useCedrosContext(),{publicKey:r,signTransaction:s}=ja.useWallet(),[o,a]=y.useState({status:"idle",error:null,transactionId:null}),[i,c]=y.useState(null),[l,d]=y.useState(null),m=y.useRef(!1),u=y.useCallback(()=>{if(!r){const w="Wallet not connected";return a({status:"error",error:w,transactionId:null}),{valid:!1,error:w}}if(!s){const w="Wallet does not support signing";return a({status:"error",error:w,transactionId:null}),{valid:!1,error:w}}return{valid:!0}},[r,s]),p=y.useCallback(async w=>{try{a(b=>({...b,status:"loading"}));const j=await e.requestQuote({resource:w});if(!e.validateRequirement(j))throw new Error("Invalid requirement received from server");return c(j),a(b=>({...b,status:"idle"})),j}catch(j){const b=J.formatError(j,"Failed to fetch requirement");throw a({status:"error",error:b,transactionId:null}),j}},[e]),h=y.useCallback(async(w,j,b,v,k="regular")=>{if(!!w.extra?.feePayer){console.log("⚡ [useX402Payment] GASLESS FLOW - Backend pays fees"),console.log("🔨 [useX402Payment] Requesting backend to build gasless transaction");const{transaction:N,blockhash:C}=await e.buildGaslessTransaction({resourceId:j,userWallet:r.toString(),feePayer:w.extra.feePayer,couponCode:b});console.log("📦 [useX402Payment] Deserializing transaction from backend");const T=t.deserializeTransaction(N);console.log("✍️ [useX402Payment] Requesting wallet to partially sign (transfer authority only)");const O=await t.partiallySignTransaction({transaction:T,signTransaction:s,blockhash:C});console.log("📤 [useX402Payment] Submitting partially-signed transaction to backend");const $=await e.submitGaslessTransaction({resource:j,partialTx:O,couponCode:b,metadata:v,resourceType:k,requirement:w});return $.success&&$.settlement&&d($.settlement),$}else{const N=await t.buildTransaction({requirement:w,payerPublicKey:r}),C=await t.signTransaction({transaction:N,signTransaction:s}),T=t.buildPaymentPayload({requirement:w,signedTx:C,payerPublicKey:r}),O=await e.submitPayment({resource:j,payload:T,couponCode:b,metadata:v,resourceType:k});return O.success&&O.settlement&&d(O.settlement),O}},[r,s,e,t]),_=y.useCallback(async(w,j,b)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const v=u();if(!v.valid)return{success:!1,error:v.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{console.log("🔍 [useX402Payment] Fetching fresh quote for resource:",w);const k=await e.requestQuote({resource:w,couponCode:j});console.log("✅ [useX402Payment] Got quote:",{payTo:k.payTo,amount:k.maxAmountRequired}),c(k),console.log("⚙️ [useX402Payment] Executing payment flow with fresh requirement");const R=await h(k,w,j,b,"regular");return R.success?a({status:"success",error:null,transactionId:R.transactionId||"payment-success"}):a({status:"error",error:R.error||"Payment failed",transactionId:null}),R}catch(k){const R=J.formatError(k,"Payment failed");return a({status:"error",error:R,transactionId:null}),{success:!1,error:R}}finally{m.current=!1}},[u,e,h]),g=y.useCallback(async(w,j,b)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const v=u();if(!v.valid)return{success:!1,error:v.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{const k=ps(w),R=await e.requestCartQuote({items:k,metadata:j,couponCode:b}),N=R.cartId,C=R.quote;if(!e.validateRequirement(C))throw new Error("Invalid cart quote received from server");c(C);const T=await h(C,N,b,j,"cart");return T.success?a({status:"success",error:null,transactionId:T.transactionId||"cart-payment-success"}):a({status:"error",error:T.error||"Cart payment failed",transactionId:null}),T}catch(k){const R=J.formatError(k,"Cart payment failed");return a({status:"error",error:R,transactionId:null}),{success:!1,error:R}}finally{m.current=!1}},[u,e,h]),f=y.useCallback(()=>{a({status:"idle",error:null,transactionId:null}),c(null),d(null),m.current=!1},[]);return{...o,requirement:i,settlement:l,fetchQuote:p,processPayment:_,processCartPayment:g,reset:f}}function Aa({resource:e,items:t,label:r,disabled:s=!1,onAttempt:o,onSuccess:a,onError:i,className:c="",testPageUrl:l,hideMessages:d=!1,metadata:m,couponCode:u}){const{connected:p,connecting:h,connect:_,disconnect:g,select:f,wallets:w,wallet:j,publicKey:b}=ja.useWallet(),{status:v,error:k,transactionId:R,processPayment:N,processCartPayment:C}=Rl(),T=J.useCedrosTheme(),{solanaError:O}=J.useCedrosContext(),{isCartMode:$,effectiveResource:S}=nr(e,t),{t:A,translations:I}=xn(),B=r||A("ui.pay_with_crypto"),D=k&&typeof k!="string"?k?.code??null:null,E=O&&typeof O!="string"?O?.code??null:null,P=te=>{if(!te||!I)return"";const xe=I.errors[te];return xe?xe.action?`${xe.message} ${xe.action}`:xe.message:""},z=k?typeof k=="string"?k:P(D):null,Z=O?typeof O=="string"?O:P(E):null,K=y.useRef(N),L=y.useRef(C);y.useEffect(()=>{K.current=N,L.current=C},[N,C]);const W=y.useMemo(()=>w.map(te=>`${te.adapter.name}-${te.readyState}`).join(","),[w]),Y=y.useMemo(()=>w.filter(({readyState:te})=>te===Hi.WalletReadyState.Installed||te===Hi.WalletReadyState.Loadable),[W]);y.useEffect(()=>{if(v==="success"&&R){const te=$&&t?dn(t):void 0;$n("crypto",R,S,te),a&&a(R)}},[v,R,a,$,t,S]),y.useEffect(()=>{if(v==="error"&&k){const te=$&&t?dn(t):void 0;kt("crypto",k,S,te),i&&i(k)}},[v,k,i,$,t,S]);const V=typeof window<"u"&&window.top!==window.self,[ce,F]=y.useState(!1),[ee,pe]=y.useState(!1),[q,ne]=y.useState(null),le=O;y.useEffect(()=>{let te=!1;return te||(async()=>{if(ee&&j&&!p&&!h){J.getLogger().debug("[CryptoButton] Wallet detected, attempting auto-connect:",j.adapter.name),pe(!1),Xo(j.adapter.name);try{await _(),te||J.getLogger().debug("[CryptoButton] Auto-connect successful")}catch(ge){if(!te){J.getLogger().error("[CryptoButton] Auto-connect failed:",ge);const dt=ge instanceof Error?ge.message:"Failed to connect wallet";is(dt,j.adapter.name),ne(null)}}}})(),()=>{te=!0}},[j,ee,p,h,_]),y.useEffect(()=>{if(J.getLogger().debug("[CryptoButton] Payment useEffect triggered",{connected:p,hasPendingPayment:!!q,hasPublicKey:!!b,pendingPaymentType:q?.type}),p&&q&&b&&j){Sl(j.adapter.name,b.toString()),J.getLogger().debug("[CryptoButton] All conditions met! Processing pending payment:",q);const te=q;ne(null),F(!1);const xe=te.type==="cart"&&te.items?dn(te.items):void 0;un("crypto",te.resource,xe),te.type==="cart"&&te.items?(J.getLogger().debug("[CryptoButton] Auto-processing cart payment"),L.current(te.items,te.metadata,te.couponCode)):te.type==="single"&&te.resource&&(J.getLogger().debug("[CryptoButton] Auto-processing single payment"),K.current(te.resource,te.couponCode,te.metadata))}},[p,q,b,j]);const fe=y.useCallback(async()=>{J.getLogger().debug("[CryptoButton] executePaymentFlow called",{connected:p,wallet:j?.adapter.name,couponCode:u,isCartMode:$,hasItems:!!t,effectiveResource:S});const te=$&&t?dn(t):void 0;if(Ln("crypto",S,te),o&&o("crypto"),le){J.getLogger().error("[CryptoButton] Solana dependencies missing:",le),kt("crypto",le,S,te),i&&i(le);return}if(V){const xe=l||window.location.href;try{if(new URL(xe,window.location.origin).origin!==window.location.origin)throw J.getLogger().error("[CryptoButton] Blocked attempt to open external URL:",xe),new Error("Cannot open external URLs from embedded context");window.open(xe,"_blank","noopener,noreferrer")}catch(ge){throw J.getLogger().error("[CryptoButton] URL validation failed:",ge),ge}return}if(p)un("crypto",S,te),$&&t?(J.getLogger().debug("[CryptoButton] Processing cart payment with coupon:",u),await C(t,m,u)):S&&(J.getLogger().debug("[CryptoButton] Processing single payment with coupon:",u),await N(S,u,m));else{let xe=!1;if($&&t?(J.getLogger().debug("[CryptoButton] Setting pending cart payment with coupon:",u),ne({type:"cart",items:t,metadata:m,couponCode:u}),xe=!0):S&&(J.getLogger().debug("[CryptoButton] Setting pending single payment with coupon:",u),ne({type:"single",resource:S,metadata:m,couponCode:u}),xe=!0),!xe){J.getLogger().error("[CryptoButton] No valid payment to process");return}try{if(j)J.getLogger().debug("[CryptoButton] Wallet already selected, connecting:",j.adapter.name),Xo(j.adapter.name),await _();else{if(J.getLogger().debug("[CryptoButton] No wallet selected, showing selector. Available wallets:",Y.map(ge=>ge.adapter.name)),Y.length===0){ne(null);const ge="No wallets available";throw is(ge),new Error(ge)}F(!0)}}catch(ge){ne(null);const dt=ge instanceof Error?ge.message:"Failed to connect wallet";J.getLogger().error("[CryptoButton] Connection error:",dt),is(dt,j?.adapter.name)}}},[p,j,u,$,t,S,V,l,Y,_,m,C,N,le,o,i]),Pe=y.useMemo(()=>$&&t?`crypto-cart-${t.map(te=>te.resource).join("-")}`:`crypto-${S||"unknown"}`,[$,t,S]),Ve=y.useMemo(()=>Mn(Pe,fe,{cooldownMs:200,deduplicationWindowMs:0}),[Pe,fe]),qe=v==="loading",He=s||qe||h||!!le,gt=qe?A("ui.processing"):B,Ge=y.useCallback(async()=>{try{pe(!1),p&&await g(),f(null),F(!0)}catch(te){J.getLogger().error("Failed to change wallet:",te)}},[p,g,f]),zt=y.useCallback(te=>{J.getLogger().debug("[CryptoButton] Wallet clicked:",te),F(!1),f(te),pe(!0),J.getLogger().debug("[CryptoButton] Wallet selected, useEffect will auto-connect")},[f]),lt=y.useCallback(async()=>{try{if(await g(),ne(null),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(te){te instanceof Error&&te.name==="QuotaExceededError"?J.getLogger().warn("localStorage quota exceeded when removing wallet preference"):J.getLogger().error("Failed to clear wallet preference from localStorage:",te)}}catch(te){J.getLogger().error("Failed to disconnect wallet:",te)}},[g]);return n.jsxs("div",{className:T.unstyled?c:`${T.className} cedros-theme__crypto-button ${c||""}`,style:T.unstyled?{}:T.style,children:[n.jsx("button",{onClick:Ve,disabled:He,className:T.unstyled?c:"cedros-theme__button cedros-theme__crypto",type:"button",children:gt}),ce&&!d&&n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:T.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>F(!1),children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:T.tokens.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${T.tokens.modalBorder}`},onClick:te=>te.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:T.tokens.surfaceText},children:A("wallet.select_wallet")}),n.jsx("button",{onClick:()=>F(!1),style:Ca(T.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:Y.map(te=>n.jsxs("button",{onClick:()=>zt(te.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:T.tokens.surfaceBackground,border:`1px solid ${T.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:T.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:xe=>{xe.currentTarget.style.backgroundColor=T.tokens.modalBackground,xe.currentTarget.style.borderColor=T.tokens.surfaceText,xe.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:xe=>{xe.currentTarget.style.backgroundColor=T.tokens.surfaceBackground,xe.currentTarget.style.borderColor=T.tokens.surfaceBorder,xe.currentTarget.style.transform="translateY(0)"},type:"button",children:[n.jsx(of.WalletIcon,{wallet:te,style:{width:"24px",height:"24px"}}),n.jsx("span",{style:{fontWeight:500},children:te.adapter.name})]},te.adapter.name))})]})}),p&&!d&&!ce&&n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:T.tokens.surfaceText,opacity:.7},children:[n.jsx("button",{onClick:Ge,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:"Change Wallet"}),n.jsx("button",{onClick:lt,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:A("ui.disconnect")})]}),!d&&Z&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__error",children:Z}),!d&&z&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__error",children:z}),!d&&R&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__success",children:A("ui.payment_successful")})]})}const Rf=Object.freeze(Object.defineProperty({__proto__:null,CryptoButton:Aa},Symbol.toStringTag,{value:"Module"})),Ol=({isOpen:e,onClose:t,resource:r,items:s,cardLabel:o="Card",cryptoLabel:a="USDC (Solana)",creditsLabel:i="Pay with Credits",showCard:c=!0,showCrypto:l=!0,showCredits:d=!1,onPaymentAttempt:m,onPaymentSuccess:u,onPaymentError:p,onStripeSuccess:h,onCryptoSuccess:_,onCreditsSuccess:g,onStripeError:f,onCryptoError:w,onCreditsError:j,customerEmail:b,successUrl:v,cancelUrl:k,metadata:R,couponCode:N,authToken:C,testPageUrl:T,hideMessages:O=!1})=>{const{tokens:$}=J.useCedrosTheme();return y.useEffect(()=>{const S=A=>{A.key==="Escape"&&e&&t()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[e,t]),y.useEffect(()=>{if(e){const S=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${S}px`,document.body.style.width="100%",document.body.style.overflowY="scroll",()=>{const A=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,A)}}},[e]),e?n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:$.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:t,children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:$.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 ${$.modalBorder}`},onClick:S=>S.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:$.surfaceText},children:"Choose Payment Method"}),n.jsx("button",{onClick:t,style:Ca($.surfaceText),"aria-label":"Close modal",children:"×"})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[c&&n.jsx(Na,{resource:r,items:s,label:o,onAttempt:m,onSuccess:h||u,onError:f||p,customerEmail:b,successUrl:v,cancelUrl:k,metadata:R,couponCode:N}),l&&n.jsx(Aa,{resource:r,items:s,label:a,onAttempt:m,onSuccess:_||u,onError:w||p,testPageUrl:T,hideMessages:O,metadata:R,couponCode:N}),d&&n.jsx(Pa,{resource:r,items:s,label:i,authToken:C,onAttempt:m?()=>m("credits"):void 0,onSuccess:g||u,onError:j||p,metadata:R,couponCode:N})]})]})}):null},Ml=({resource:e,items:t,label:r,cardLabel:s,cryptoLabel:o,creditsLabel:a,showCard:i=!0,showCrypto:c=!0,showCredits:l=!1,onPaymentAttempt:d,onPaymentSuccess:m,onPaymentError:u,onStripeSuccess:p,onCryptoSuccess:h,onCreditsSuccess:_,onStripeError:g,onCryptoError:f,onCreditsError:w,customerEmail:j,successUrl:b,cancelUrl:v,metadata:k,couponCode:R,authToken:N,autoDetectWallets:C=!0,testPageUrl:T,hideMessages:O=!1,renderModal:$})=>{const S=J.useCedrosTheme(),[A,I]=y.useState(!1),{status:B,processPayment:D,processCartCheckout:E}=Rs(),{isCartMode:P,effectiveResource:z}=nr(e,t),{t:Z}=xn(),K=r||Z("ui.purchase"),L=s||Z("ui.card"),W=o||Z("ui.usdc_solana"),Y=a||Z("ui.pay_with_credits")||"Pay with Credits",V=y.useCallback(async()=>{if(C&&i){const{detectSolanaWallets:q}=await Promise.resolve().then(()=>zC);if(!q()){const ne=P?void 0:z,le=P&&t?dn(t):void 0;Ln("stripe",ne,le),d&&d("stripe"),un("stripe",ne,le);let fe;P&&t?fe=await E(t,b,v,k,j,R):z&&(fe=await D(z,b,v,k,j,R)),fe&&fe.success&&fe.transactionId?($n("stripe",fe.transactionId,ne,le),p?p(fe.transactionId):m&&m(fe.transactionId)):fe&&!fe.success&&fe.error&&(kt("stripe",fe.error,ne,le),g?g(fe.error):u&&u(fe.error));return}}I(!0)},[C,i,P,t,z,E,D,b,v,k,j,R,m,u,p,g,d]),ce=y.useMemo(()=>P&&t?`purchase-cart-${t.map(q=>q.resource).join("-")}`:`purchase-${z||"unknown"}`,[P,t,z]),F=y.useMemo(()=>Mn(ce,V),[ce,V]),ee=B==="loading",pe={isOpen:A,onClose:()=>I(!1),resource:P?void 0:z,items:P?t:void 0,cardLabel:L,cryptoLabel:W,creditsLabel:Y,showCard:i,showCrypto:c,showCredits:l,onPaymentAttempt:d,onPaymentSuccess:q=>{I(!1),m?.(q)},onPaymentError:q=>{I(!1),u?.(q)},onStripeSuccess:q=>{I(!1),p?.(q)},onCryptoSuccess:q=>{I(!1),h?.(q)},onCreditsSuccess:q=>{I(!1),_?.(q)},onStripeError:q=>{I(!1),g?.(q)},onCryptoError:q=>{I(!1),f?.(q)},onCreditsError:q=>{I(!1),w?.(q)},customerEmail:j,successUrl:b,cancelUrl:v,metadata:k,couponCode:R,authToken:N,testPageUrl:T,hideMessages:O};return n.jsxs("div",{className:S.unstyled?"":S.className,style:S.unstyled?{}:S.style,children:[n.jsx("button",{onClick:F,disabled:ee,className:S.unstyled?"":"cedros-theme__button cedros-theme__stripe",style:{width:"100%",cursor:ee?"not-allowed":"pointer",opacity:ee?.6:1},type:"button",children:ee?Z("ui.processing"):K}),$?$(pe):n.jsx(Ol,{...pe})]})},Of={"mainnet-beta":"https://api.mainnet-beta.solana.com",devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com"};function Mf(){const[e,t]=y.useState(null);return y.useEffect(()=>{let r=!1;return import("@solana/wallet-adapter-react").then(s=>{r||t(s)}),()=>{r=!0}},[]),e}function Df({endpoint:e,wallets:t,children:r}){const s=Mf();if(!s)return n.jsx(n.Fragment,{children:r});const{ConnectionProvider:o,WalletProvider:a}=s;return n.jsx(o,{endpoint:e,children:n.jsx(a,{wallets:t,autoConnect:!1,children:r})})}const Lf=y.lazy(()=>Promise.resolve().then(()=>Rf).then(e=>({default:e.CryptoButton})));function $f(e){const{resource:t,items:r,checkout:s={},display:o={},callbacks:a={},advanced:i={}}=e,{config:c,walletPool:l}=J.useCedrosContext(),d=J.useCedrosTheme(),{isCartMode:m}=nr(t,r),u=o.showCrypto??!0,p=y.useMemo(()=>({marginTop:"0.5rem",fontSize:"0.875rem",color:d.tokens.surfaceText,opacity:.7,textAlign:"center"}),[d.tokens.surfaceText]),h=y.useMemo(()=>u?i.wallets&&i.wallets.length>0?i.wallets:l.getAdapters():[],[i.wallets,l,u]),_=y.useMemo(()=>r?dn(r):0,[r]),g=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"stripe"}):void 0,[a.onPaymentSuccess]),f=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"crypto"}):void 0,[a.onPaymentSuccess]),w=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"stripe"}):void 0,[a.onPaymentError]),j=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"crypto"}):void 0,[a.onPaymentError]),b=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"credits"}):void 0,[a.onPaymentSuccess]),v=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"credits"}):void 0,[a.onPaymentError]),k=y.useMemo(()=>a.onPaymentAttempt?()=>a.onPaymentAttempt("credits"):void 0,[a.onPaymentAttempt]),R=u?c.solanaEndpoint??Of[c.solanaCluster]:"";if(!t&&(!r||r.length===0))return J.getLogger().error('CedrosPay: Must provide either "resource" or "items" prop'),n.jsx("div",{className:o.className,style:{color:d.tokens.errorText},children:"Configuration error: No resource or items provided"});const N=o.showCard??!0,C=o.showCredits??!1,T=o.showPurchaseButton??!1,O=o.layout??"vertical",$=o.hideMessages??!1,S=i.autoDetectWallets??!0,A=n.jsx("div",{className:d.unstyled?o.className:`cedros-theme__pay ${o.className||""}`,children:n.jsxs("div",{className:d.unstyled?"":`cedros-theme__pay-content cedros-theme__pay-content--${O}`,children:[T?n.jsx(Ml,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,label:o.purchaseLabel,cardLabel:o.cardLabel,cryptoLabel:o.cryptoLabel,showCard:N,showCrypto:u,onPaymentAttempt:a.onPaymentAttempt,onPaymentSuccess:g,onPaymentError:w,onStripeSuccess:g,onCryptoSuccess:f,onStripeError:w,onCryptoError:j,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,autoDetectWallets:S,testPageUrl:i.testPageUrl,hideMessages:$,renderModal:o.renderModal}):n.jsxs(n.Fragment,{children:[N&&n.jsx(Na,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,label:o.cardLabel,onAttempt:a.onPaymentAttempt,onSuccess:g,onError:w}),u&&n.jsx(y.Suspense,{fallback:null,children:n.jsx(Lf,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,metadata:s.metadata,couponCode:s.couponCode,label:o.cryptoLabel,onAttempt:a.onPaymentAttempt,onSuccess:f,onError:j,testPageUrl:i.testPageUrl,hideMessages:$})}),C&&n.jsx(Pa,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,authToken:s.authToken,metadata:s.metadata,couponCode:s.couponCode,label:o.creditsLabel,onAttempt:k,onSuccess:b,onError:v})]}),m&&r&&r.length>1&&!$&&n.jsxs("div",{style:p,children:["Checking out ",_," items"]})]})});return n.jsx("div",{className:d.unstyled?o.className:d.className,style:d.unstyled?{}:d.style,children:u?n.jsx(Df,{endpoint:R,wallets:h,children:A}):A})}const Q={products:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),n.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),n.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),n.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),n.jsx("path",{d:"M3 3v5h5"}),n.jsx("path",{d:"M12 7v5l4 2"})]}),settings:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),n.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"}),n.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),n.jsx("path",{d:"M8 16H3v5"})]}),check:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})}),plus:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),n.jsx("path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9"}),n.jsx("path",{d:"M12 3v6"})]}),arrowUp:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7-7 7 7"}),n.jsx("path",{d:"M12 19V5"})]}),arrowDown:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7 7 7-7"}),n.jsx("path",{d:"M12 5v14"})]}),delete:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),n.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),faq:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),n.jsx("path",{d:"M12 17h.01"})]}),chat:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),n.jsx("path",{d:"M2 12h20"})]}),ai:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),n.jsx("path",{d:"M10 10v.5"}),n.jsx("path",{d:"M14 10v.5"}),n.jsx("path",{d:"M12 14v2"}),n.jsx("path",{d:"M8 18h8"}),n.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),n.jsx("path",{d:"M6 12v6"}),n.jsx("path",{d:"M18 12v6"})]}),notifications:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),n.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),n.jsx("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),n.jsx("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),n.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),n.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),n.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),n.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),n.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),n.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),n.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),n.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),n.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),n.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),n.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),n.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),n.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),n.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),n.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),n.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),n.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function Yt({message:e,onRetry:t}){return e?n.jsxs("div",{className:"cedros-admin__error-banner",children:[n.jsx("span",{children:e}),t&&n.jsxs("button",{type:"button",className:"cedros-admin__error-banner-retry",onClick:t,children:[Q.refresh," Retry"]})]}):null}function rr({stats:e,isLoading:t=!1,onRefresh:r}){return n.jsxs("div",{className:"cedros-admin__stats-bar",children:[n.jsx("div",{className:"cedros-admin__stats-bar-grid",children:e.map((s,o)=>n.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[n.jsx("span",{className:"cedros-admin__stats-bar-label",children:s.label}),n.jsx("span",{className:`cedros-admin__stats-bar-value ${s.variant?`cedros-admin__stats-bar-value--${s.variant}`:""}`,children:t?n.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):s.value}),s.description&&n.jsx("span",{className:"cedros-admin__stats-bar-desc",children:s.description})]},o))}),r&&n.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:r,disabled:t,title:"Refresh stats",children:t?Q.loading:Q.refresh})]})}function zf({serverUrl:e,productId:t,apiKey:r,authManager:s}){const[o,a]=y.useState(null),[i,c]=y.useState(!1),[l,d]=y.useState(!1),[m,u]=y.useState(null),p=y.useCallback(async()=>{if(t){c(!0),u(null);try{let g;if(s?.isAuthenticated())g=await s.fetchWithAuth(`/admin/products/${t}/variations`);else{const f={"Content-Type":"application/json"};r&&(f["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variations`,{headers:f});if(!w.ok)throw new Error(`Failed to fetch variations: ${w.status}`);g=await w.json()}g.variationConfig||(g.variationConfig={variationTypes:[]}),g.variants||(g.variants=[]),a(g)}catch(g){const f=g instanceof Error?g.message:"Failed to fetch variations";u(f),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,r,s]),h=y.useCallback(async g=>{if(!t)return null;d(!0),u(null);try{let f;if(s?.isAuthenticated())f=await s.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(g)});else{const w={"Content-Type":"application/json"};r&&(w["X-API-Key"]=r);const j=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:w,body:JSON.stringify(g)});if(!j.ok)throw new Error(`Failed to save variations: ${j.status}`);f=await j.json()}return a({productId:t,variationConfig:f.variationConfig,variants:f.variants}),{variantsCreated:f.variantsCreated}}catch(f){const w=f instanceof Error?f.message:"Failed to save variations";return u(w),null}finally{d(!1)}},[e,t,r,s]),_=y.useCallback(async g=>{if(!t||g.length===0)return!1;d(!0),u(null);try{if(s?.isAuthenticated())await s.fetchWithAuth(`/admin/products/${t}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:g})});else{const f={"Content-Type":"application/json"};r&&(f["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:f,body:JSON.stringify({updates:g})});if(!w.ok)throw new Error(`Failed to update inventory: ${w.status}`)}if(o){const f=new Map(g.map(w=>[w.variantId,w]));a({...o,variants:o.variants.map(w=>{const j=f.get(w.id);return j?{...w,inventoryQuantity:j.inventoryQuantity,inventoryStatus:j.inventoryStatus??w.inventoryStatus}:w})})}return!0}catch(f){const w=f instanceof Error?f.message:"Failed to update inventory";return u(w),!1}finally{d(!1)}},[e,t,r,s,o]);return{data:o,isLoading:i,error:m,fetch:p,save:h,bulkUpdateInventory:_,isSaving:l}}function Qi(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ff({value:e,onChange:t,maxTypes:r=5,maxValuesPerType:s=20,disabled:o=!1}){const[a,i]=y.useState(null),[c,l]=y.useState(""),[d,m]=y.useState({}),u=e.variationTypes,p=y.useCallback(()=>{if(!c.trim()||u.length>=r)return;const b={id:Qi(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,b]}),l(""),i(b.id)},[c,u,r,t]),h=y.useCallback(b=>{t({variationTypes:u.filter(v=>v.id!==b).map((v,k)=>({...v,displayOrder:k}))}),a===b&&i(null)},[u,t,a]),_=y.useCallback((b,v)=>{t({variationTypes:u.map(k=>k.id===b?{...k,name:v}:k)})},[u,t]),g=y.useCallback((b,v)=>{const k=u.findIndex(C=>C.id===b);if(k===-1||v==="up"&&k===0||v==="down"&&k===u.length-1)return;const R=[...u],N=v==="up"?k-1:k+1;[R[k],R[N]]=[R[N],R[k]],t({variationTypes:R.map((C,T)=>({...C,displayOrder:T}))})},[u,t]),f=y.useCallback(b=>{const v=(d[b]||"").trim();if(!v)return;const k=u.find(N=>N.id===b);if(!k||k.values.length>=s)return;const R={id:Qi(),label:v};t({variationTypes:u.map(N=>N.id===b?{...N,values:[...N.values,R]}:N)}),m(N=>({...N,[b]:""}))},[u,d,s,t]),w=y.useCallback((b,v)=>{t({variationTypes:u.map(k=>k.id===b?{...k,values:k.values.filter(R=>R.id!==v)}:k)})},[u,t]),j=y.useCallback((b,v,k)=>{t({variationTypes:u.map(R=>R.id===b?{...R,values:R.values.map(N=>N.id===v?{...N,label:k}:N)}:R)})},[u,t]);return n.jsxs("div",{className:"cedros-admin__variation-editor",children:[n.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[u.length,"/",r," types"]})]}),u.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):n.jsx("div",{className:"cedros-admin__variation-type-list",children:u.map((b,v)=>n.jsxs("div",{className:"cedros-admin__variation-type-item",children:[n.jsxs("div",{className:"cedros-admin__variation-type-header",children:[n.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(b.id,"up"),disabled:o||v===0,title:"Move up",children:Q.arrowUp}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(b.id,"down"),disabled:o||v===u.length-1,title:"Move down",children:Q.arrowDown})]}),n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:b.name,onChange:k=>_(b.id,k.target.value),disabled:o,placeholder:"Type name"}),n.jsxs("span",{className:"cedros-admin__variation-value-count",children:[b.values.length," values"]}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===b.id?null:b.id),children:a===b.id?"Collapse":"Edit values"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>h(b.id),disabled:o,title:"Remove type",children:Q.delete})]}),a===b.id&&n.jsxs("div",{className:"cedros-admin__variation-values",children:[n.jsxs("div",{className:"cedros-admin__variation-values-header",children:[n.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',b.name,'"']}),n.jsxs("span",{style:{fontSize:11,opacity:.7},children:[b.values.length,"/",s]})]}),b.values.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):n.jsx("div",{className:"cedros-admin__variation-value-list",children:b.values.map(k=>n.jsxs("div",{className:"cedros-admin__variation-value-item",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:k.label,onChange:R=>j(b.id,k.id,R.target.value),disabled:o}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>w(b.id,k.id),disabled:o,title:"Remove value",children:Q.close})]},k.id))}),b.values.length<s&&n.jsxs("div",{className:"cedros-admin__variation-add-value",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:d[b.id]||"",onChange:k=>m(R=>({...R,[b.id]:k.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),f(b.id))}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>f(b.id),disabled:o||!d[b.id]?.trim(),children:"Add"})]})]})]},b.id))}),u.length<r&&n.jsxs("div",{className:"cedros-admin__variation-add-type",children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:b=>l(b.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),p())}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:p,disabled:o||!c.trim(),children:"Add Type"})]})]})}function Dl({value:e,onChange:t,options:r,placeholder:s="Filter",disabled:o}){const[a,i]=y.useState(!1),c=y.useRef(null),d=r.find(m=>m.value===e)?.label||s;return y.useEffect(()=>{const m=u=>{c.current&&!c.current.contains(u.target)&&i(!1)};if(a)return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[a]),y.useEffect(()=>{const m=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[a]),n.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[n.jsx("span",{children:d}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:Q.chevronDown})]}),a&&n.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:r.map(m=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${m.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{m.disabled||(t(m.value),i(!1))},role:"option","aria-selected":m.value===e,disabled:m.disabled,children:[m.label,m.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:Q.check})]},m.value))})]})}function ot({value:e,onChange:t,options:r,label:s,description:o,disabled:a,className:i,style:c}){const[l,d]=y.useState(!1),m=y.useRef(null),p=r.find(h=>h.value===e)?.label||"Select...";return y.useEffect(()=>{const h=_=>{m.current&&!m.current.contains(_.target)&&d(!1)};if(l)return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[l]),y.useEffect(()=>{const h=_=>{_.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[l]),n.jsxs("div",{className:`cedros-admin__field ${i||""}`,style:c,children:[n.jsx("label",{className:"cedros-admin__field-label",children:s}),n.jsxs("div",{className:"cedros-admin__dropdown cedros-admin__dropdown--form",ref:m,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger cedros-admin__dropdown-trigger--form",onClick:()=>!a&&d(!l),"aria-expanded":l,"aria-haspopup":"listbox",disabled:a,children:[n.jsx("span",{children:p}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${l?"cedros-admin__dropdown-chevron--open":""}`,children:Q.chevronDown})]}),l&&n.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:r.map(h=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${h.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{h.disabled||(t(h.value),d(!1))},role:"option","aria-selected":h.value===e,disabled:h.disabled,children:[h.label,h.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:Q.check})]},h.value))})]}),o&&n.jsx("p",{className:"cedros-admin__field-description",children:o})]})}function Yi(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Bf(e){if(e.length===0)return[];const t=[...e].sort((s,o)=>s.displayOrder-o.displayOrder),r=(s,o)=>{if(s>=t.length){const c=o.valueIds.sort().join("|"),l=Object.values(o.options).join(" / ");return[{key:c,title:l,optionValueIds:[...o.valueIds],options:{...o.options}}]}const a=t[s],i=[];for(const c of a.values)i.push(...r(s+1,{valueIds:[...o.valueIds,c.id],options:{...o.options,[a.name]:c.label}}));return i};return r(0,{valueIds:[],options:{}})}function Uf(e){return e.optionValueIds?.length?[...e.optionValueIds].sort().join("|"):Object.entries(e.options).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${t}:${r}`).join("|")}function Wf({variationConfig:e,variants:t,onChange:r,defaultPrice:s=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=y.useMemo(()=>Bf(e.variationTypes),[e.variationTypes]),l=y.useMemo(()=>{const g=new Map;for(const f of t)g.set(Uf(f),f);return g},[t]),{existingRows:d,possibleRows:m}=y.useMemo(()=>{const g=[],f=[];for(const w of c){const j=l.get(w.key);j?g.push({combo:w,variant:j}):f.push(w)}return{existingRows:g,possibleRows:f}},[c,l]),u=y.useCallback((g,f)=>{r(t.map(w=>w.id===g?{...w,...f}:w))},[t,r]),p=y.useCallback(g=>{r(t.filter(f=>f.id!==g))},[t,r]),h=y.useCallback(g=>{if(t.length>=a)return;const f={id:Yi(),title:g.title,options:g.options,optionValueIds:g.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};r([...t,f])},[t,r,a,s]),_=y.useCallback(()=>{const g=a-t.length,w=m.slice(0,g).map(j=>({id:Yi(),title:j.title,options:j.options,optionValueIds:j.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));r([...t,...w])},[t,r,m,a,s]);return e.variationTypes.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):c.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):n.jsxs("div",{className:"cedros-admin__variant-grid",children:[n.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[t.length,"/",a," variants (",c.length," ","possible)"]})]}),m.length>0&&t.length<a&&n.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[n.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:_,disabled:i,children:["Generate All (",Math.min(m.length,a-t.length),")"]}),n.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{children:"Variant"}),n.jsx("th",{style:{width:100},children:"Price"}),n.jsx("th",{style:{width:80},children:"Qty"}),n.jsx("th",{style:{width:100},children:"SKU"}),n.jsx("th",{style:{width:100},children:"Status"}),n.jsx("th",{style:{width:80},children:"Actions"})]})}),n.jsxs("tbody",{children:[d.map(({combo:g,variant:f})=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:g.title}),n.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(g.options).map(([w,j])=>`${w}: ${j}`).join(", ")})]})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx("span",{children:o}),n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:f.price??"",onChange:w=>u(f.id,{price:w.target.value===""?void 0:parseFloat(w.target.value)||0}),disabled:i,min:"0",step:"0.01",style:{width:70}})]})}),n.jsx("td",{children:n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:f.inventoryQuantity??"",onChange:w=>u(f.id,{inventoryQuantity:w.target.value===""?void 0:parseInt(w.target.value)||0}),disabled:i,min:"0",style:{width:60}})}),n.jsx("td",{children:n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:f.sku??"",onChange:w=>u(f.id,{sku:w.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),n.jsx("td",{children:n.jsx(Dl,{value:f.inventoryStatus??"in_stock",onChange:w=>u(f.id,{inventoryStatus:w}),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],disabled:i})}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>p(f.id),disabled:i,title:"Remove variant",children:Q.trash})})]},f.id)),m.length>0&&t.length<a&&n.jsxs(n.Fragment,{children:[n.jsx("tr",{className:"cedros-admin__variant-separator",children:n.jsx("td",{colSpan:6,children:n.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",m.length,")"]})})}),m.slice(0,10).map(g=>n.jsxs("tr",{className:"cedros-admin__variant-possible",children:[n.jsx("td",{children:n.jsx("span",{style:{opacity:.6},children:g.title})}),n.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>h(g),disabled:i,title:"Create variant",children:Q.plus})})]},g.key)),m.length>10&&n.jsx("tr",{className:"cedros-admin__variant-more",children:n.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",m.length-10," more combinations"]})})]})]})]})})]})}function Vf({serverUrl:e,productId:t,productTitle:r,defaultPrice:s=0,currencySymbol:o="$",apiKey:a,authManager:i,onClose:c}){const{data:l,isLoading:d,error:m,fetch:u,save:p,isSaving:h}=zf({serverUrl:e,productId:t,apiKey:a,authManager:i}),[_,g]=y.useState({variationTypes:[]}),[f,w]=y.useState([]),[j,b]=y.useState(!1),[v,k]=y.useState(!1);y.useEffect(()=>{u()},[u]),y.useEffect(()=>{l&&(g(l.variationConfig),w(l.variants),b(!1))},[l]);const R=y.useCallback(T=>{g(T),b(!0),k(!1)},[]),N=y.useCallback(T=>{w(T),b(!0),k(!1)},[]),C=y.useCallback(async()=>{const T=new Set((l?.variants??[]).map(I=>I.id)),O=f.filter(I=>!T.has(I.id)),$=f.filter(I=>T.has(I.id)),S=(l?.variants??[]).filter(I=>!f.some(B=>B.id===I.id)).map(I=>I.id);await p({variationConfig:_,createVariants:O.map(I=>({optionValueIds:I.optionValueIds??[],inventoryQuantity:I.inventoryQuantity,sku:I.sku,price:I.price})),updateVariants:$.map(I=>({id:I.id,inventoryQuantity:I.inventoryQuantity,sku:I.sku,price:I.price,inventoryStatus:I.inventoryStatus})),deleteVariantIds:S.length>0?S:void 0})&&(b(!1),k(!0),setTimeout(()=>k(!1),3e3))},[_,f,l?.variants,p]);return d?n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading variations..."]})]}):n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),n.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[v&&n.jsxs("span",{className:"cedros-admin__success-text",children:[Q.check," Saved"]}),j&&n.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:C,disabled:h||!j,children:h?"Saving...":"Save Changes"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Q.close})]})]}),m&&n.jsx("div",{className:"cedros-admin__error-banner",children:m}),n.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(Ff,{value:_,onChange:R,disabled:h})}),_.variationTypes.length>0&&n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(Wf,{variationConfig:_,variants:f,onChange:N,defaultPrice:s,currencySymbol:o,disabled:h})})]})]})}function Ll({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(!1),[p,h]=y.useState(null),[_,g]=y.useState(null),[f,w]=y.useState(null),[j,b]=y.useState(null),[v,k]=y.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:""}),R=E=>{const P=E.tagsCsv.split(",").map(V=>V.trim()).filter(Boolean),z=E.categoryIdsCsv.split(",").map(V=>V.trim()).filter(Boolean),Z={email:E.checkoutEmail,name:E.checkoutName,phone:E.checkoutPhone,shippingAddress:E.checkoutShippingAddress,billingAddress:E.checkoutBillingAddress},K=E.fulfillmentType==="shipping"?"physical":"digital",L={title:E.title,slug:E.slug||E.id,shipping_profile:K,inventory_status:E.inventoryStatus,checkout_requirements:JSON.stringify(Z),fulfillment_type:E.fulfillmentType};E.imageUrl&&(L.image_url=E.imageUrl);const W=E.compareAtUsd?Math.round(Number(E.compareAtUsd)*100):0;W&&(L.compare_at_amount_cents=String(W)),P.length&&(L.tags=JSON.stringify(P)),z.length&&(L.category_ids=JSON.stringify(z)),E.fulfillmentNotes&&(L.fulfillment_notes=E.fulfillmentNotes);const Y=E.shippingCountriesCsv.split(",").map(V=>V.trim().toUpperCase()).filter(Boolean);return Y.length&&(L.shippingCountries=Y.join(","),L.shipping_countries=Y.join(",")),L},N=E=>E.metadata?.title||E.description||E.id,C=E=>E.metadata?.image_url,T=y.useCallback(async()=>{try{b(null);let E;if(s?.isAuthenticated())E=await s.fetchWithAuth(`/admin/products?limit=${r}`);else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const z=await fetch(`${e}/admin/products?limit=${r}`,{headers:P});if(!z.ok)throw new Error(`Failed to fetch products: ${z.status}`);E=await z.json()}a(E.products||[])}catch{a([]),b("Failed to load products")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{T()},[T]);const O=async E=>{if(E.preventDefault(),!(!v.id||!v.description)){if(h(null),v.fulfillmentType==="shipping"&&v.checkoutShippingAddress&&!v.shippingCountriesCsv.split(",").map(z=>z.trim()).filter(Boolean).length){h("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:P}=v,z=v.inventoryQuantity===""?void 0:Number.isFinite(Number(v.inventoryQuantity))?Number(v.inventoryQuantity):void 0,Z=Number(v.priceUsd)||0,K=Math.round(Z*100),L=Math.round(Z*1e6),W={id:v.id,description:v.description,fiatAmountCents:K,fiatCurrency:v.fiatCurrency,cryptoAtomicAmount:L,cryptoToken:v.cryptoToken,...z!==void 0?{inventoryQuantity:z}:{},metadata:{...P?{product_type:P}:{},...R(v)}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(W)});else{const Y={"Content-Type":"application/json"};t&&(Y["X-API-Key"]=t);const V=await fetch(`${e}/admin/products`,{method:"POST",headers:Y,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to create product: ${V.status}`)}k({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),T()}catch(P){h(P instanceof Error?P.message:"Failed to create product")}finally{u(!1)}}},$=E=>`$${(E/100).toFixed(2)}`,S=E=>{switch(E){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},A=y.useMemo(()=>{const E=o.filter(z=>z.active).length,P=o.reduce((z,Z)=>{const K=Z.variations?.length??0;return z+(K>0?K:1)},0);return{activeCount:E,totalSkus:P}},[o]),I=E=>{w(P=>!P||P.key!==E?{key:E,direction:"asc"}:{key:E,direction:P.direction==="asc"?"desc":"asc"})},B=E=>!f||f.key!==E?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:f.direction==="asc"?Q.chevronUp:Q.chevronDown}),D=y.useMemo(()=>{if(!f)return o;const E=f.direction==="asc"?1:-1,P=z=>{switch(f.key){case"product":return N(z);case"type":return S(z.metadata?.product_type);case"price":return z.fiatAmountCents??0;case"status":return z.active?1:0;case"id":default:return z.id}};return[...o].sort((z,Z)=>{const K=P(z),L=P(Z);return typeof K=="number"&&typeof L=="number"?(K-L)*E:String(K).localeCompare(String(L),void 0,{sensitivity:"base"})*E})},[o,f]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:j,onRetry:T}),n.jsx(rr,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:A.activeCount,variant:A.activeCount>0?"success":"muted"},{label:"Total SKUs",value:A.totalSkus}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{h(null),d(!l)},children:[l?Q.close:Q.plus,l?"Cancel":"Add Product"]})]}),l&&n.jsxs("form",{onSubmit:O,className:"cedros-admin__add-form",children:[p&&n.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:p}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.id,onChange:E=>k(P=>({...P,id:E.target.value})),placeholder:"e.g., premium-article",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.title,onChange:E=>k(P=>({...P,title:E.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.slug,onChange:E=>k(P=>({...P,slug:E.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:v.imageUrl,onChange:E=>k(P=>({...P,imageUrl:E.target.value})),placeholder:"https://..."})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.description,onChange:E=>k(P=>({...P,description:E.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:v.productType,onChange:E=>k(P=>({...P,productType:E})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"}],label:"Product Type"}),n.jsx(ot,{value:v.fulfillmentType,onChange:E=>{const P=E;k(z=>({...z,fulfillmentType:P,checkoutShippingAddress:P==="shipping"?z.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),v.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:v.inventoryStatus,onChange:E=>k(P=>({...P,inventoryStatus:E})),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],label:"Inventory status"}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v.inventoryQuantity,onChange:E=>k(P=>({...P,inventoryQuantity:E.target.value===""?"":parseInt(E.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v.compareAtUsd===""?"":v.compareAtUsd,onChange:E=>k(P=>({...P,compareAtUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v.priceUsd===""?"":v.priceUsd,onChange:E=>k(P=>({...P,priceUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.tagsCsv,onChange:E=>k(P=>({...P,tagsCsv:E.target.value})),placeholder:"e.g., core, new, gift"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.categoryIdsCsv,onChange:E=>k(P=>({...P,categoryIdsCsv:E.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:v.checkoutEmail,onChange:E=>k(P=>({...P,checkoutEmail:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),n.jsx(ot,{value:v.checkoutName,onChange:E=>k(P=>({...P,checkoutName:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),n.jsx(ot,{value:v.checkoutPhone,onChange:E=>k(P=>({...P,checkoutPhone:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[v.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:v.checkoutShippingAddress,onChange:E=>k(P=>({...P,checkoutShippingAddress:E.target.checked}))}),"Collect shipping address"]})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:v.checkoutBillingAddress,onChange:E=>k(P=>({...P,checkoutBillingAddress:E.target.checked}))}),"Collect billing address"]})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.fulfillmentNotes,onChange:E=>k(P=>({...P,fulfillmentNotes:E.target.value})),placeholder:v.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),v.fulfillmentType==="shipping"&&v.checkoutShippingAddress&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.shippingCountriesCsv,onChange:E=>k(P=>({...P,shippingCountriesCsv:E.target.value})),placeholder:"e.g., US,CA"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Product"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading products..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("id"),children:["ID",B("id")]})}),n.jsx("th",{"aria-sort":f?.key==="product"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("product"),children:["Product",B("product")]})}),n.jsx("th",{"aria-sort":f?.key==="type"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("type"),children:["Type",B("type")]})}),n.jsx("th",{"aria-sort":f?.key==="price"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("price"),children:["Price",B("price")]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("status"),children:["Status",B("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:D.map(E=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:E.id})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[C(E)?n.jsx("img",{src:C(E),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):n.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:N(E)}),n.jsx("span",{style:{opacity:.8},children:E.description})]})]})}),n.jsx("td",{children:S(E.metadata?.product_type)}),n.jsx("td",{children:$(E.fiatAmountCents)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${E.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:E.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>g(E),children:"Variations"})]})})]},E.id))})]})}),_&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>g(null),children:n.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:E=>E.stopPropagation(),children:n.jsx(Vf,{serverUrl:e,productId:_.id,productTitle:N(_),defaultPrice:_.fiatAmountCents/100,apiKey:t,authManager:s,onClose:()=>g(null)})})})]})}function $l({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(null),[l,d]=y.useState(!0),[m,u]=y.useState(!0),[p,h]=y.useState(null),[_,g]=y.useState(""),[f,w]=y.useState(null),j=y.useCallback(async()=>{u(!0);try{h(null);let C;if(s?.isAuthenticated())C=await s.fetchWithAuth("/admin/stats");else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const O=await fetch(`${e}/admin/stats`,{headers:T});if(!O.ok)throw new Error(`Failed to fetch stats: ${O.status}`);C=await O.json()}c(C)}catch{c(null),h("Failed to load payment stats")}finally{u(!1)}},[e,t,s]);y.useEffect(()=>{j()},[j]);const b=y.useCallback(async()=>{try{h(null);let C;const T=new URLSearchParams({limit:r.toString()});_&&T.set("method",_);const O=`/admin/transactions?${T}`;if(s?.isAuthenticated())C=await s.fetchWithAuth(O);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const S=await fetch(`${e}${O}`,{headers:$});if(!S.ok)throw new Error(`Failed to fetch transactions: ${S.status}`);C=await S.json()}a(C.transactions||[])}catch{a([]),h("Failed to load transactions")}finally{d(!1)}},[e,t,r,_,s]);y.useEffect(()=>{b()},[b]);const v=C=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(C),k=C=>{w(T=>!T||T.key!==C?{key:C,direction:"asc"}:{key:C,direction:T.direction==="asc"?"desc":"asc"})},R=C=>!f||f.key!==C?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:f.direction==="asc"?Q.chevronUp:Q.chevronDown}),N=y.useMemo(()=>{if(!f)return o;const C=f.direction==="asc"?1:-1,T=O=>{switch(f.key){case"resource":return O.resourceId;case"method":return O.method;case"amount":return O.amount;case"status":return O.status;case"date":return new Date(O.paidAt).getTime();case"id":default:return O.id}};return[...o].sort((O,$)=>{const S=T(O),A=T($);return typeof S=="number"&&typeof A=="number"?(S-A)*C:String(S).localeCompare(String(A),void 0,{sensitivity:"base"})*C})},[o,f]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:p,onRetry:()=>{j(),b()}}),n.jsx(rr,{stats:[{label:"Revenue",value:v(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:v(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:v(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:v(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:m,onRefresh:j}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),n.jsx(Dl,{value:_,onChange:g,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading transactions..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("id"),children:["ID",R("id")]})}),n.jsx("th",{"aria-sort":f?.key==="resource"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("resource"),children:["Resource",R("resource")]})}),n.jsx("th",{"aria-sort":f?.key==="method"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("method"),children:["Method",R("method")]})}),n.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("amount"),children:["Amount",R("amount")]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("status"),children:["Status",R("status")]})}),n.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("date"),children:["Date",R("date")]})})]})}),n.jsx("tbody",{children:N.map(C=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:C.id})}),n.jsx("td",{children:C.resourceId}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.method}`,children:C.method})}),n.jsxs("td",{children:["$",C.amount.toFixed(2)," ",C.currency.toUpperCase()]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.status}`,children:C.status})}),n.jsx("td",{children:kr(C.paidAt)})]},C.id))})]})})]})}function zl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(!1),[p,h]=y.useState(null),[_,g]=y.useState(null),[f,w]=y.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}),j=y.useCallback(async()=>{try{g(null);let T;const O=`/admin/coupons?limit=${r}`;if(s?.isAuthenticated())T=await s.fetchWithAuth(O);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const S=await fetch(`${e}${O}`,{headers:$});if(!S.ok)throw new Error(`Failed to fetch coupons: ${S.status}`);T=await S.json()}a(T.coupons||[])}catch(T){J.getLogger().error("[CouponsSection] Failed to fetch coupons:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),g("Failed to load coupons")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{j()},[j]);const b=async T=>{if(T.preventDefault(),!(!f.code||f.discountValue<=0)){u(!0);try{const O=f.minimumAmountUsd?Math.round(Number(f.minimumAmountUsd)*100):void 0,$=f.productIdsCsv.split(",").map(I=>I.trim()).filter(Boolean),S=f.categoryIdsCsv.split(",").map(I=>I.trim()).filter(Boolean),A={code:f.code,discountType:f.discountType,discountValue:f.discountValue,usageLimit:f.usageLimit,active:!0,usageCount:0,scope:f.scope,...$.length?{productIds:$}:{},...S.length?{categoryIds:S}:{},...f.paymentMethod!=="any"?{paymentMethod:f.paymentMethod}:{},...f.autoApply?{autoApply:!0}:{},...f.appliesAt!=="both"?{appliesAt:f.appliesAt}:{},...f.startsAt?{startsAt:f.startsAt}:{},...f.expiresAt?{expiresAt:f.expiresAt}:{},...O?{minimumAmountCents:O}:{},...f.usageLimitPerCustomer?{usageLimitPerCustomer:f.usageLimitPerCustomer}:{},...f.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(A)});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/coupons`,{method:"POST",headers:I,body:JSON.stringify(A)});if(!B.ok)throw new Error(`Failed to create coupon: ${B.status}`)}w({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),j()}catch(O){J.getLogger().error("[CouponsSection] Failed to add coupon:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),g("Failed to create coupon")}finally{u(!1)}}},v=o.filter(T=>T.active).length,k=o.reduce((T,O)=>T+(O.usageCount??0),0),R=T=>{h(O=>!O||O.key!==T?{key:T,direction:"asc"}:{key:T,direction:O.direction==="asc"?"desc":"asc"})},N=T=>!p||p.key!==T?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:p.direction==="asc"?Q.chevronUp:Q.chevronDown}),C=y.useMemo(()=>{if(!p)return o;const T=p.direction==="asc"?1:-1,O=$=>{switch(p.key){case"discount":return $.discountValue??0;case"usage":return $.usageCount??0;case"status":return $.active?1:0;case"code":default:return $.code}};return[...o].sort(($,S)=>{const A=O($),I=O(S);return typeof A=="number"&&typeof I=="number"?(A-I)*T:String(A).localeCompare(String(I),void 0,{sensitivity:"base"})*T})},[o,p]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:_,onRetry:j}),n.jsx(rr,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:v,variant:v>0?"success":"muted"},{label:"Redemptions",value:k}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?Q.close:Q.plus,l?"Cancel":"Add Coupon"]})]}),l&&n.jsxs("form",{onSubmit:b,className:"cedros-admin__add-form",children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.code,onChange:T=>w(O=>({...O,code:T.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),n.jsx(ot,{value:f.discountType,onChange:T=>w(O=>({...O,discountType:T})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",f.discountType==="percentage"?"(%)":"($)"]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.discountValue||"",onChange:T=>w(O=>({...O,discountValue:parseFloat(T.target.value)||0})),placeholder:f.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:f.discountType==="percentage"?"1":"0.01",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.usageLimit||"",onChange:T=>w(O=>({...O,usageLimit:T.target.value?parseInt(T.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:f.expiresAt,onChange:T=>w(O=>({...O,expiresAt:T.target.value}))})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:f.scope,onChange:T=>w(O=>({...O,scope:T})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),n.jsx(ot,{value:f.paymentMethod,onChange:T=>w(O=>({...O,paymentMethod:T})),options:[{value:"any",label:"Any Payment Method"},{value:"stripe",label:"Stripe (Card) Only"},{value:"x402",label:"Crypto (x402) Only"},{value:"credits",label:"Credits Only"}],label:"Payment Method"}),n.jsx(ot,{value:f.appliesAt,onChange:T=>w(O=>({...O,appliesAt:T})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),f.scope==="specific_products"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.productIdsCsv,onChange:T=>w(O=>({...O,productIdsCsv:T.target.value})),placeholder:"e.g., prod_123, prod_456"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:f.startsAt,onChange:T=>w(O=>({...O,startsAt:T.target.value}))})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:f.autoApply,onChange:T=>w(O=>({...O,autoApply:T.target.checked}))}),"Automatically apply when conditions met"]})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.minimumAmountUsd===""?"":f.minimumAmountUsd,onChange:T=>w(O=>({...O,minimumAmountUsd:T.target.value===""?"":parseFloat(T.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.usageLimitPerCustomer||"",onChange:T=>w(O=>({...O,usageLimitPerCustomer:T.target.value?parseInt(T.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:f.firstPurchaseOnly,onChange:T=>w(O=>({...O,firstPurchaseOnly:T.target.checked}))}),"New customers only"]})]})]}),f.scope==="specific_categories"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.categoryIdsCsv,onChange:T=>w(O=>({...O,categoryIdsCsv:T.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Coupon"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading coupons..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":p?.key==="code"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("code"),children:["Code",N("code")]})}),n.jsx("th",{"aria-sort":p?.key==="discount"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("discount"),children:["Discount",N("discount")]})}),n.jsx("th",{"aria-sort":p?.key==="usage"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("usage"),children:["Usage",N("usage")]})}),n.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("status"),children:["Status",N("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:C.map(T=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:T.code})}),n.jsx("td",{children:T.discountType==="percentage"?`${T.discountValue}%`:`$${T.discountValue.toFixed(2)}`}),n.jsxs("td",{children:[T.usageCount,T.usageLimit?` / ${T.usageLimit}`:""]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${T.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:T.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},T.code))})]})})]})}function Fl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(null),[m,u]=y.useState([]),[p,h]=y.useState(!0),[_,g]=y.useState(null),[f,w]=y.useState(null),[j,b]=y.useState([]),[v,k]=y.useState(!0),[R,N]=y.useState(null),[C,T]=y.useState(null),[O,$]=y.useState(null),[S,A]=y.useState(""),[I,B]=y.useState(null),D=y.useCallback(async()=>{try{let U;const re=`/admin/refunds?limit=${r}`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{headers:de});if(!ke.ok)throw new Error(`Failed to fetch x402 refunds: ${ke.status}`);U=await ke.json()}a(U.refunds||[])}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),B("Failed to load x402 refunds")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{D()},[D]);const E=y.useCallback(async()=>{try{let U;const re=`/admin/credits/refund-requests?status=pending&limit=${r}&offset=0`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const ke={"Content-Type":"application/json"};t&&(ke["X-API-Key"]=t);const Se=await fetch(`${e}${re}`,{headers:ke});if(!Se.ok)throw new Error(`Failed to fetch credits refund requests: ${Se.status}`);U=await Se.json()}const de=Array.isArray(U)?U:"refundRequests"in U?U.refundRequests:U.requests||[];u(de)}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([]),B("Failed to load credits refunds")}finally{h(!1)}},[e,t,r,s]);y.useEffect(()=>{E()},[E]);const P=async U=>{g(U.id);try{const re=`/admin/credits/refund-requests/${U.id}/process`,de=JSON.stringify({amountLamports:U.amountLamports,reason:U.reason});if(s?.isAuthenticated())await s.fetchWithAuth(re,{method:"POST",body:de});else{const ke={"Content-Type":"application/json"};t&&(ke["X-API-Key"]=t);const Se=await fetch(`${e}${re}`,{method:"POST",headers:ke,body:de});if(!Se.ok)throw new Error(`Failed to process credits refund: ${Se.status}`)}await E()}catch(re){J.getLogger().error("[RefundsSection] Failed to process credits refund:",re,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:U.id}),B("Failed to process credits refund")}finally{g(null)}},z=U=>{A(U.reason??""),$(U)},Z=()=>{$(null),A("")},K=async()=>{if(!O)return;const U=O,re=S;Z(),g(U.id);try{const de=`/admin/credits/refund-requests/${U.id}/reject`,ke=JSON.stringify({reason:re});if(s?.isAuthenticated())await s.fetchWithAuth(de,{method:"POST",body:ke});else{const Se={"Content-Type":"application/json"};t&&(Se["X-API-Key"]=t);const Me=await fetch(`${e}${de}`,{method:"POST",headers:Se,body:ke});if(!Me.ok)throw new Error(`Failed to reject credits refund: ${Me.status}`)}await E()}catch(de){J.getLogger().error("[RefundsSection] Failed to reject credits refund:",de,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:U.id}),B("Failed to reject credits refund")}finally{g(null)}},L=y.useCallback(async()=>{try{let U;const re=`/admin/stripe/refunds?limit=${r}`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{headers:de});if(!ke.ok)throw new Error(`Failed to fetch Stripe refunds: ${ke.status}`);U=await ke.json()}b(U.refunds||[])}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),b([]),B("Failed to load Stripe refunds")}finally{k(!1)}},[e,t,r,s]);y.useEffect(()=>{L()},[L]);const W=async U=>{N(U);try{const re=`/admin/stripe/refunds/${U}/process`;if(s?.isAuthenticated())await s.fetchWithAuth(re,{method:"POST"});else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{method:"POST",headers:de});if(!ke.ok)throw new Error(`Failed to process refund: ${ke.status}`)}await L()}catch(re){J.getLogger().error("[RefundsSection] Failed to process Stripe refund:",re,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:U}),B("Failed to process Stripe refund")}finally{N(null)}},Y=(U,re)=>new Intl.NumberFormat("en-US",{style:"currency",currency:re}).format(U/100),V=U=>U?U.replace(/_/g," ").replace(/\b\w/g,re=>re.toUpperCase()):"—",ce=U=>{switch(U){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},F=(U,re)=>re?re.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(U/1e6)} (USD credits)`:`${U.toLocaleString()} ${re.toUpperCase()} (atomic)`:`${U.toLocaleString()} (atomic)`,ee=U=>{switch(U){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},pe=U=>U.stripeRefundId??"—",q=U=>U.chargeId??"—",ne=j.filter(U=>U.status==="pending"||U.status==="requires_action").length,le=m.filter(U=>U.status==="pending").length,fe=o.filter(U=>U.status==="pending").length,Pe=ne+le+fe,Ve=j.filter(U=>U.status==="succeeded").reduce((U,re)=>U+re.amount,0),qe=m.filter(U=>U.status==="processed").reduce((U,re)=>U+re.amountLamports,0),He=o.filter(U=>U.status==="completed").reduce((U,re)=>U+re.amount,0),gt=Ve/100+qe/1e6+He,Ge=U=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(U),zt=v||p||i,lt=U=>{T(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},te=U=>{w(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},xe=U=>{d(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},ge=(U,re)=>!U||!re?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:re==="asc"?Q.chevronUp:Q.chevronDown}),dt=y.useMemo(()=>{if(!C)return j;const U=C.direction==="asc"?1:-1,re=de=>{switch(C.key){case"stripe":return de.stripeRefundId??"";case"charge":return de.chargeId??"";case"amount":return de.amount??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...j].sort((de,ke)=>{const Se=re(de),Me=re(ke);return typeof Se=="number"&&typeof Me=="number"?(Se-Me)*U:String(Se).localeCompare(String(Me),void 0,{sensitivity:"base"})*U})},[j,C]),xt=y.useMemo(()=>{if(!f)return m;const U=f.direction==="asc"?1:-1,re=de=>{switch(f.key){case"original":return de.originalTransactionId??"";case"user":return de.userId??"";case"amount":return de.amountLamports??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...m].sort((de,ke)=>{const Se=re(de),Me=re(ke);return typeof Se=="number"&&typeof Me=="number"?(Se-Me)*U:String(Se).localeCompare(String(Me),void 0,{sensitivity:"base"})*U})},[m,f]),ut=y.useMemo(()=>{if(!l)return o;const U=l.direction==="asc"?1:-1,re=de=>{switch(l.key){case"transaction":return de.transactionId??"";case"amount":return de.amount??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...o].sort((de,ke)=>{const Se=re(de),Me=re(ke);return typeof Se=="number"&&typeof Me=="number"?(Se-Me)*U:String(Se).localeCompare(String(Me),void 0,{sensitivity:"base"})*U})},[o,l]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:I,onRetry:()=>{D(),E(),L()}}),n.jsx(rr,{stats:[{label:"Pending",value:Pe,variant:Pe>0?"warning":"muted"},{label:"Card Pending",value:ne,description:"Stripe"},{label:"Credits Pending",value:le},{label:"Crypto Pending",value:fe,description:"x402"},{label:"Total Refunded",value:Ge(gt),variant:"success"}],isLoading:zt}),n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),v?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading Stripe refunds..."]}):j.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":C?.key==="id"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("id"),children:["Request ID",ge(C?.key==="id",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="stripe"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("stripe"),children:["Stripe Refund ID",ge(C?.key==="stripe",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="charge"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("charge"),children:["Charge",ge(C?.key==="charge",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="amount"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("amount"),children:["Amount",ge(C?.key==="amount",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="reason"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("reason"),children:["Reason",ge(C?.key==="reason",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="status"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("status"),children:["Status",ge(C?.key==="status",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="date"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("date"),children:["Date",ge(C?.key==="date",C?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:dt.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:pe(U)})}),n.jsx("td",{children:n.jsx("code",{children:q(U)})}),n.jsx("td",{children:Y(U.amount,U.currency)}),n.jsx("td",{children:V(U.reason)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${ee(U.status)}`,children:U.status})}),n.jsx("td",{children:kr(U.createdAt)}),n.jsx("td",{children:(U.status==="pending"||U.status==="requires_action")&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>W(U.id),disabled:R===U.id,children:R===U.id?"Processing...":"Process"})})]},U.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),p?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading credits refunds..."]}):m.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("id"),children:["Request ID",ge(f?.key==="id",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="original"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("original"),children:["Original Tx",ge(f?.key==="original",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="user"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("user"),children:["User",ge(f?.key==="user",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("amount"),children:["Amount",ge(f?.key==="amount",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="reason"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("reason"),children:["Reason",ge(f?.key==="reason",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("status"),children:["Status",ge(f?.key==="status",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("date"),children:["Date",ge(f?.key==="date",f?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:xt.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:U.originalTransactionId})}),n.jsx("td",{children:n.jsx("code",{children:U.userId??"—"})}),n.jsx("td",{children:F(U.amountLamports,U.currency)}),n.jsx("td",{children:U.reason??"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${ce(U.status)}`,children:U.status})}),n.jsx("td",{children:kr(U.createdAt)}),n.jsx("td",{children:U.status==="pending"?n.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>P(U),disabled:_===U.id,children:_===U.id?"Processing...":"Process"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>z(U),disabled:_===U.id,children:"Reject"})]}):null})]},U.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading x402 refunds..."]}):o.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("id"),children:["ID",ge(l?.key==="id",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="transaction"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("transaction"),children:["Transaction",ge(l?.key==="transaction",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="amount"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("amount"),children:["Amount",ge(l?.key==="amount",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="reason"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("reason"),children:["Reason",ge(l?.key==="reason",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="status"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("status"),children:["Status",ge(l?.key==="status",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="date"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("date"),children:["Date",ge(l?.key==="date",l?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:ut.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:U.transactionId})}),n.jsxs("td",{children:["$",U.amount.toFixed(2)]}),n.jsx("td",{children:U.reason||"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${U.status}`,children:U.status})}),n.jsx("td",{children:kr(U.createdAt)}),n.jsx("td",{children:U.status==="pending"&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",children:"Process"})})]},U.id))})]})}),O&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:Z,children:n.jsxs("div",{className:"cedros-admin__modal",onClick:U=>U.stopPropagation(),children:[n.jsxs("div",{className:"cedros-admin__modal-header",children:[n.jsx("h3",{className:"cedros-admin__modal-title",children:"Reject Refund Request"}),n.jsx("button",{type:"button",className:"cedros-admin__modal-close",onClick:Z,"aria-label":"Close",children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__modal-body",children:[n.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",n.jsx("code",{children:O.id})," for ",F(O.amountLamports,O.currency),"."]}),n.jsxs("label",{className:"cedros-admin__form-field",children:[n.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),n.jsx("textarea",{className:"cedros-admin__input",value:S,onChange:U=>A(U.target.value),placeholder:"Enter rejection reason...",rows:3,style:{resize:"vertical"}})]})]}),n.jsxs("div",{className:"cedros-admin__modal-footer",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--outline",onClick:Z,children:"Cancel"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:K,children:"Reject Refund"})]})]})})]})}async function qf(e){const t=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=await e.sign(t);return{"X-Signer":e.signerPublicKey,"X-Message":t,"X-Signature":r,"Content-Type":"application/json"}}class Hf{constructor(t,r,s){this.serverUrl=t,this.auth=r,this.authManager=s}async fetch(t,r={}){if(this.authManager?.isAuthenticated())return this.authManager.fetchWithAuth(t,r);const s={"Content-Type":"application/json",...r.headers||{}};if(this.auth){const a=await qf(this.auth);Object.assign(s,a)}const o=await fetch(`${this.serverUrl}${t}`,{...r,headers:s});if(!o.ok){const a=await o.text();throw new Error(`API error ${o.status}: ${a}`)}return o.json()}async listCategories(t=100){return this.fetch(`/admin/config?limit=${t}`)}async getConfig(t,r=!0){return this.fetch(`/admin/config/${t}?redact_secrets=${r}`)}async updateConfig(t,r,s){await this.fetch(`/admin/config/${t}`,{method:"PUT",body:JSON.stringify({config:r,description:s})})}async patchConfig(t,r,s){await this.fetch(`/admin/config/${t}`,{method:"PATCH",body:JSON.stringify({updates:r,description:s})})}async batchUpdate(t){await this.fetch("/admin/config/batch",{method:"POST",body:JSON.stringify({updates:t})})}async validateConfig(t,r){return this.fetch("/admin/config/validate",{method:"POST",body:JSON.stringify({category:t,config:r})})}async getHistory(t,r=50){const s=new URLSearchParams({limit:r.toString()});return t&&s.set("category",t),this.fetch(`/admin/config/history?${s}`)}}const Ea={server:{label:"Server",secrets:[],icon:"🖥️",fields:{admin_metrics_api_key:{hidden:!0},cors_allowed_origins:{hidden:!0}}},security:{label:"Security",description:"Configure CORS, rate limiting, and other security settings",secrets:[],icon:"🔒",fields:{cors_allowed_origins:{description:'List of allowed origins for CORS requests. Use ["*"] to allow all origins (not recommended for production).'}}},metrics:{label:"Metrics",description:"Configure metrics collection and API access",secrets:["admin_metrics_api_key"],icon:"📊",fields:{admin_metrics_api_key:{description:"API key for accessing the admin metrics endpoint. Keep this secret."}}},logging:{label:"Logging",secrets:[],icon:"📝",fields:{level:{type:"dropdown",options:["trace","debug","info","warn","error"]},format:{hidden:!0},environment:{hidden:!0}}},stripe:{label:"Stripe",secrets:["secret_key","webhook_secret"],icon:"💳",fields:{enabled:{hidden:!0},mode:{type:"dropdown",options:["test","live"]},success_url:{hidden:!0},cancel_url:{hidden:!0}}},x402:{label:"X402 (Crypto)",secrets:["server_wallets"],icon:"⚡",fields:{enabled:{hidden:!0},payment_address:{type:"solana_address",description:"The Solana wallet address where payments are received. This is where customer funds are sent."},token_mint:{type:"token_mint",description:"The SPL token used for payments. Most commonly USDC."},token_decimals:{type:"number",description:"Number of decimal places for the token (e.g., USDC has 6 decimals).",hidden:!0},custom_token_symbol:{description:'Display symbol for your custom token (e.g., "MYTOKEN").',hidden:!0},custom_token_icon:{description:"URL to your token's icon image.",hidden:!0},rpc_url:{description:"Custom Solana RPC endpoint. Leave empty to use the default public RPC."},gasless_enabled:{type:"toggle",description:"When enabled, your server pays transaction fees so customers don't need SOL."},server_wallets:{type:"secret_array",description:"Server keypair(s) used to sign and pay for transactions. Required for gasless payments.",showWhen:"gasless_enabled"},network:{hidden:!0}}},paywall:{label:"Paywall",secrets:[],icon:"🚪",fields:{product_cache_ttl:{type:"number",unit:"seconds"}}},coupons:{label:"Coupons",secrets:[],icon:"🎟️",fields:{cache_ttl:{type:"number",unit:"seconds"}}},subscriptions:{label:"Subscriptions",secrets:[],icon:"🔄",fields:{grace_period_hours:{type:"number",unit:"hours"}}},callbacks:{label:"Callbacks",secrets:["hmac_secret"],icon:"🔔"},email:{label:"Email",description:"Email receipts for customers after purchase",secrets:["smtp_password"],icon:"📧",fields:{enabled:{hidden:!0},provider:{type:"dropdown",options:["sendgrid","mailgun","postmark","ses","resend","custom"],description:"Email service provider."},smtp_host:{description:"SMTP server hostname.",showWhen:"provider"},smtp_port:{type:"number",description:"SMTP server port (typically 587 for TLS).",showWhen:"provider"},smtp_user:{description:"SMTP authentication username or API key name.",showWhen:"provider"},smtp_password:{description:"SMTP password or API key.",showWhen:"provider"},from_address:{description:"Sender email address (e.g., orders@yourstore.com)."},from_name:{description:'Sender display name (e.g., "Your Store").'}}},webhook:{label:"Webhook",description:"HTTP notifications when purchases occur",secrets:["secret"],icon:"🔔",fields:{enabled:{hidden:!0},url:{description:"URL to receive POST notifications (e.g., https://api.yoursite.com/webhooks/orders)."},secret:{description:"Shared secret for HMAC-SHA256 signature verification."},retry_attempts:{type:"number",description:"Number of retry attempts on failure (default: 3)."}}},messaging:{label:"Messaging",description:"Email and webhook notifications for purchases",secrets:["smtp_password","webhook_secret"],icon:"📬",fields:{email_enabled:{type:"boolean",description:"Send order confirmation emails to customers."},smtp_host:{description:"SMTP server hostname.",showWhen:"email_enabled"},smtp_port:{type:"number",description:"SMTP server port (typically 587 for TLS).",showWhen:"email_enabled"},smtp_username:{description:"SMTP authentication username or API key.",showWhen:"email_enabled"},smtp_password:{description:"SMTP password or API key.",showWhen:"email_enabled"},from_email:{description:"Sender email address (e.g., orders@yourstore.com).",showWhen:"email_enabled"},from_name:{description:'Sender display name (e.g., "Your Store").',showWhen:"email_enabled"},webhook_enabled:{type:"boolean",description:"Send webhook notifications when purchases complete."},webhook_url:{description:"URL to receive POST notifications.",showWhen:"webhook_enabled"},webhook_secret:{description:"Shared secret for HMAC-SHA256 signature verification.",showWhen:"webhook_enabled"},webhook_timeout:{type:"number",description:"Request timeout in seconds (default: 30).",showWhen:"webhook_enabled"}}},monitoring:{label:"Monitoring",secrets:[],icon:"📊",fields:{check_interval:{type:"number",unit:"seconds"},low_balance_threshold:{type:"number",unit:"SOL"}}},rate_limit:{label:"Rate Limiting",secrets:[],icon:"⏱️"},circuit_breaker:{label:"Circuit Breaker",secrets:[],icon:"🔌"},admin:{label:"Admin Keys",secrets:[],icon:"👤"},api_keys:{label:"API Keys",secrets:[],icon:"🔐"},cedros_login:{label:"Cedros Login",secrets:["api_key"],icon:"🔑",fields:{enabled:{hidden:!0},credits_enabled:{hidden:!0},base_url:{hidden:!0},timeout:{hidden:!0}}},storefront:{label:"Storefront",description:"Product pages & display settings",secrets:[],icon:"🏪",fields:{"relatedProducts.mode":{type:"dropdown",options:["most_recent","by_category","manual","ai"]},"relatedProducts.maxItems":{type:"number"}}}};function Bl(e,t){return Ea[e]?.secrets.includes(t)??!1}const wr="[REDACTED]";function Ta({data:e,onSave:t,debounceMs:r=1500,savedDurationMs:s=2e3,enabled:o=!0,skipInitial:a=!0}){const[i,c]=y.useState("idle"),[l,d]=y.useState(null),m=y.useRef(!0),u=y.useRef(null),p=y.useRef(null),h=y.useRef(e);h.current=e;const _=y.useCallback(async()=>{c("saving"),d(null);try{await t(h.current),c("saved"),p.current=setTimeout(()=>{c("idle")},s)}catch(w){c("error"),d(w instanceof Error?w.message:"Save failed")}},[t,s]),g=y.useCallback(async()=>{u.current&&(clearTimeout(u.current),u.current=null),await _()},[_]),f=y.useCallback(()=>{c("idle"),d(null)},[]);return y.useEffect(()=>{if(o){if(a&&m.current){m.current=!1;return}return u.current&&clearTimeout(u.current),p.current&&clearTimeout(p.current),c("pending"),u.current=setTimeout(()=>{_()},r),()=>{u.current&&clearTimeout(u.current)}}},[e,o,a,r,_]),y.useEffect(()=>()=>{u.current&&clearTimeout(u.current),p.current&&clearTimeout(p.current)},[]),{status:i,error:l,saveNow:g,reset:f}}function Zf(e){if(!e||e.trim()==="")return{valid:!0};try{return new af.PublicKey(e.trim()),{valid:!0}}catch{return{valid:!1,error:"Invalid Solana address"}}}function Ki(e,t,r){const s=Bl(e,t),o=t.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase()),i=Ea[e]?.fields?.[t],c={isSecret:s,label:o,description:i?.description,hidden:i?.hidden,showWhen:i?.showWhen};return i?.type==="dropdown"&&i.options?{...c,type:"dropdown",options:i.options}:i?.type==="token_mint"?{...c,type:"token_mint"}:i?.type==="toggle"?{...c,type:"toggle"}:i?.type==="secret_array"?{...c,type:"secret_array",isSecret:!0}:i?.type==="solana_address"?{...c,type:"solana_address"}:i?.type==="number"?{...c,type:"number",unit:i.unit}:typeof r=="boolean"?{...c,type:"boolean"}:typeof r=="number"?{...c,type:"number",unit:i?.unit}:Array.isArray(r)?{...c,type:"array"}:typeof r=="object"&&r!==null?{...c,type:"object"}:{...c,type:"string"}}function Gf({category:e,config:t,originalConfig:r,isLoading:s=!1,onSave:o}){const[a,i]=y.useState(t),[c,l]=y.useState(new Set);y.useEffect(()=>{i(t)},[t]);const d=y.useMemo(()=>{const j={...a};for(const b of Object.keys(j))if(Bl(e,b)){const v=r[b],k=j[b];(k===wr||k===v)&&(j[b]=wr)}return j},[a,r,e]),{status:m,error:u}=Ta({data:d,onSave:o,debounceMs:1500}),p=y.useCallback((j,b)=>{i(v=>({...v,[j]:b}))},[]),h=y.useCallback(j=>{l(b=>{const v=new Set(b);return v.has(j)?v.delete(j):v.add(j),v})},[]),_=j=>j?n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:j}):null,g=(j,b)=>{const v=Ki(e,j,r[j]??b);if(v.type==="dropdown"&&v.options)return n.jsx(ot,{value:b,onChange:N=>p(j,N),options:v.options.map(N=>({value:N,label:N})),label:v.label,description:v.description,disabled:s});if(v.type==="token_mint")return n.jsx(Qf,{label:v.label,value:b,onChange:N=>p(j,N),decimals:a.token_decimals??6,onDecimalsChange:N=>p("token_decimals",N),disabled:s,description:v.description,customSymbol:a.custom_token_symbol||"",customIcon:a.custom_token_icon||"",onCustomSymbolChange:N=>p("custom_token_symbol",N),onCustomIconChange:N=>p("custom_token_icon",N)});if(v.type==="toggle")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("button",{type:"button",role:"switch","aria-checked":b,onClick:()=>p(j,!b),disabled:s,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:b?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:s?"not-allowed":"pointer",position:"relative",transition:"background-color 0.2s",opacity:s?.5:1,flexShrink:0},children:n.jsx("span",{style:{position:"absolute",top:2,left:b?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})}),n.jsx("span",{className:"cedros-admin__field-label",style:{marginBottom:0},children:v.label})]}),_(v.description)]});if(v.type==="solana_address"){const N=b||"",C=Zf(N);return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:v.label}),n.jsxs("div",{style:{position:"relative"},children:[n.jsx("input",{type:"text",className:`cedros-admin__input ${C.valid?"":"cedros-admin__input--error"}`,value:N,onChange:T=>p(j,T.target.value),disabled:s,placeholder:"e.g. 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",style:{width:"100%",fontFamily:"monospace",fontSize:"0.875rem",borderColor:C.valid?void 0:"var(--cedros-admin-error, #dc2626)",paddingRight:N&&C.valid?"2rem":void 0}}),N&&C.valid&&n.jsx("span",{style:{position:"absolute",right:10,top:"50%",transform:"translateY(-50%)",color:"var(--cedros-admin-success, #16a34a)",fontSize:"1rem"},title:"Valid Solana address",children:"✓"})]}),!C.valid&&n.jsx("span",{style:{color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.75rem",marginTop:"0.25rem",display:"block"},children:C.error}),_(v.description)]})}if(v.type==="boolean")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__checkbox",children:[n.jsx("input",{type:"checkbox",checked:b,onChange:N=>p(j,N.target.checked),disabled:s}),v.label]}),_(v.description)]});if(v.type==="number")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[v.label,v.unit&&n.jsxs("span",{className:"cedros-admin__field-unit",children:[" (",v.unit,")"]})]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:b,onChange:N=>p(j,parseFloat(N.target.value)||0),disabled:s}),_(v.description)]});if(v.type==="secret_array")return n.jsx(Yf,{label:v.label,value:b,onChange:N=>p(j,N),disabled:s,description:v.description});if(v.type==="array"){const N=b;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:v.label}),n.jsx("textarea",{className:"cedros-admin__textarea",value:N.join(`
|
|
1
|
+
"use strict";var Xp=Object.create;var qi=Object.defineProperty;var Jp=Object.getOwnPropertyDescriptor;var ef=Object.getOwnPropertyNames;var tf=Object.getPrototypeOf,nf=Object.prototype.hasOwnProperty;var rf=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ef(t))!nf.call(e,o)&&o!==r&&qi(e,o,{get:()=>t[o],enumerable:!(s=Jp(t,o))||s.enumerable});return e};var sf=(e,t,r)=>(r=e!=null?Xp(tf(e)):{},rf(t||!e||!e.__esModule?qi(r,"default",{value:e,enumerable:!0}):r,e));const n=require("react/jsx-runtime"),y=require("react"),J=require("./CedrosContext-C2v_s8cc.js"),ja=require("@solana/wallet-adapter-react"),Hi=require("@solana/wallet-adapter-base"),of=require("@solana/wallet-adapter-react-ui"),af=require("@solana/web3.js"),cf=require("@cedros/login-react"),Zi=require("./index-WcOlBYZJ.js"),ka=require("react-dom");function wl(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const x=wl(y),Is=wl(ka);function lf(e){return!e||!e.coupon_codes?[]:e.coupon_codes.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function df(e,t=", "){return e.join(t)}function uf(e,t){return e<=0?0:(e-t)/e*100}function mf(e,t){if(!t||t.length===0)return e;let r=e,s=0;for(const o of t)if(o.discountType==="percentage"){const a=1-o.discountValue/100;r=r*a}else o.discountType==="fixed"&&(s+=o.discountValue);return r=r-s,r<0&&(r=0),Math.ceil(r*100)/100}function _l(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return 1;const r=Math.floor(t);return r>0?r:1}function ps(e){return e.map(t=>({resource:t.resource,quantity:_l(t.quantity),variantId:t.variantId,metadata:t.metadata}))}function dn(e){return e.reduce((t,r)=>t+_l(r.quantity),0)}function pf(e){return!!(e&&e.length>0&&(e.length>1||e.length===1&&(e[0].quantity??1)>1))}const ff={invalid_payment_proof:{message:"Payment verification failed",action:"Please try your payment again. If this continues, contact support.",technicalHint:"Invalid payment proof format"},invalid_signature:{message:"Transaction signature is invalid",action:"Please approve the transaction in your wallet and try again.",technicalHint:"Transaction signature verification failed"},invalid_transaction:{message:"Transaction format is invalid",action:"Please try your payment again. If this continues, try updating your wallet app.",technicalHint:"Malformed transaction structure"},transaction_not_found:{message:"Transaction not found on the blockchain",action:"Your transaction may still be processing. Please wait a moment and check your wallet, or try again.",technicalHint:"Transaction signature not found on-chain"},transaction_not_confirmed:{message:"Transaction is still processing",action:"Please wait a moment for the blockchain to confirm your transaction, then try again.",technicalHint:"Transaction not yet confirmed"},transaction_failed:{message:"Transaction failed on the blockchain",action:"Check your wallet for details. You may need to adjust your transaction settings or add more SOL for fees.",technicalHint:"On-chain transaction failure"},transaction_expired:{message:"Transaction took too long to process",action:"Please try your payment again. Consider increasing transaction priority if your wallet supports it.",technicalHint:"Transaction blockhash expired"},invalid_recipient:{message:"Payment was sent to the wrong address",action:"Please try again and ensure you approve the correct transaction in your wallet.",technicalHint:"Recipient address mismatch"},invalid_sender:{message:"Payment sender wallet is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Sender address validation failed"},unauthorized_refund_issuer:{message:"You are not authorized to issue refunds",action:"Only authorized accounts can process refunds. Please contact support if you believe this is an error.",technicalHint:"Refund issuer not in authorized list"},amount_below_minimum:{message:"Payment amount is too low",action:"Please check the required amount and try again.",technicalHint:"Amount below minimum threshold"},amount_mismatch:{message:"Payment amount does not match the quote",action:"The price may have changed. Please refresh and try your payment again.",technicalHint:"Amount does not match quote"},insufficient_funds_sol:{message:"Not enough SOL for transaction fees",action:"Add at least 0.001 SOL to your wallet to cover network fees, then try again.",technicalHint:"Insufficient SOL balance for fees"},insufficient_funds_token:{message:"Insufficient balance in your wallet",action:"Add more funds to your wallet and try again.",technicalHint:"Insufficient token balance"},invalid_token_mint:{message:"Incorrect payment token",action:"Please pay with the correct token as shown in the payment details.",technicalHint:"Token mint address mismatch"},not_spl_transfer:{message:"Transaction is not a valid token transfer",action:"Please ensure you are sending the correct token type from your wallet.",technicalHint:"Transaction is not an SPL token transfer"},missing_token_account:{message:"Token account not found",action:"Your wallet may need to create a token account first. Try again or use a different wallet.",technicalHint:"Associated token account does not exist"},invalid_token_program:{message:"Invalid token program",action:"Please try your payment again. If this continues, try using a different wallet.",technicalHint:"Token program ID mismatch"},missing_memo:{message:"Payment memo is required but was not included",action:"Please try your payment again and ensure transaction details are approved in your wallet.",technicalHint:"Required memo instruction missing"},invalid_memo:{message:"Payment memo format is invalid",action:"Please try your payment again.",technicalHint:"Memo does not match expected format"},payment_already_used:{message:"This payment has already been processed",action:"Check your transaction history. If you need to make another payment, please start a new transaction.",technicalHint:"Payment signature already recorded"},signature_reused:{message:"Transaction signature has already been used",action:"Please create a new payment transaction.",technicalHint:"Duplicate signature detected"},quote_expired:{message:"Payment quote has expired",action:"Prices are updated frequently. Please refresh and try your payment again.",technicalHint:"Quote timestamp expired"},missing_field:{message:"Required information is missing",action:"Please check all required fields and try again.",technicalHint:"Required field not provided"},invalid_field:{message:"Some information is invalid",action:"Please check your input and try again.",technicalHint:"Field validation failed"},invalid_amount:{message:"Payment amount is invalid",action:"Please check the amount and try again.",technicalHint:"Amount validation failed"},invalid_wallet:{message:"Wallet address is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Wallet address validation failed"},invalid_resource:{message:"Invalid item selection",action:"Please refresh the page and try again.",technicalHint:"Resource ID validation failed"},invalid_coupon:{message:"Invalid coupon code",action:"Please check the coupon code and try again.",technicalHint:"Coupon code format invalid"},invalid_cart_item:{message:"One or more cart items are invalid",action:"Please review your cart and try again.",technicalHint:"Cart item validation failed"},empty_cart:{message:"Your cart is empty",action:"Please add items to your cart before checking out.",technicalHint:"Cart contains no items"},resource_not_found:{message:"Item not found",action:"This item may no longer be available. Please refresh and try again.",technicalHint:"Resource not found in database"},cart_not_found:{message:"Shopping cart not found",action:"Your cart may have expired. Please start a new order.",technicalHint:"Cart ID not found"},refund_not_found:{message:"Refund not found",action:"Please check your refund reference number or contact support.",technicalHint:"Refund ID not found"},product_not_found:{message:"Product not available",action:"This product may no longer be available. Please browse our current selection.",technicalHint:"Product ID not found"},coupon_not_found:{message:"Coupon code not found",action:"Please check the coupon code or remove it to continue.",technicalHint:"Coupon code not in database"},session_not_found:{message:"Payment session expired",action:"Please start a new payment.",technicalHint:"Session ID not found or expired"},cart_already_paid:{message:"This order has already been paid",action:"Check your order history. If you need to make another purchase, please start a new order.",technicalHint:"Cart marked as paid"},refund_already_processed:{message:"This refund has already been processed",action:"Check your transaction history or contact support for details.",technicalHint:"Refund already completed"},coupon_expired:{message:"Coupon has expired",action:"Please remove the coupon code or use a different code.",technicalHint:"Coupon expiration date passed"},coupon_usage_limit_reached:{message:"Coupon usage limit reached",action:"This coupon has been fully redeemed. Please try a different code.",technicalHint:"Coupon max uses exceeded"},coupon_not_applicable:{message:"Coupon cannot be applied to this purchase",action:"Please check the coupon terms or remove it to continue.",technicalHint:"Coupon conditions not met"},coupon_wrong_payment_method:{message:"Coupon not valid for this payment method",action:"Try a different payment method or remove the coupon code.",technicalHint:"Coupon restricted to specific payment methods"},stripe_error:{message:"Card payment service temporarily unavailable",action:"Please try again in a moment, or use cryptocurrency payment instead.",technicalHint:"Stripe API error"},rpc_error:{message:"Blockchain network temporarily unavailable",action:"Please try again in a moment, or use card payment instead.",technicalHint:"Solana RPC error"},network_error:{message:"Network connection issue",action:"Please check your internet connection and try again.",technicalHint:"Network request failed"},internal_error:{message:"Something went wrong on our end",action:"Please try again. If this continues, contact support.",technicalHint:"Internal server error"},database_error:{message:"Service temporarily unavailable",action:"Please try again in a moment.",technicalHint:"Database operation failed"},config_error:{message:"Service configuration error",action:"Please contact support for assistance.",technicalHint:"Server misconfiguration"}};function fs(e){return ff[e]||{message:"An unexpected error occurred",action:"Please try again or contact support if this continues.",technicalHint:`Unknown error code: ${e}`}}const jl=new Map,Yo=new Map,Ko=new Map,kl=200,Sa=2e3;function hf(e){const t=Ko.get(e);return t?Date.now()<t?!0:(Ko.delete(e),!1):!1}function gf(e,t=kl){const r=Date.now()+t;Ko.set(e,r)}function xf(e,t=Sa){const r=jl.get(e);if(!r)return!1;const o=Date.now()-r;return o<t?(J.getLogger().debug(`[Deduplication] Duplicate request blocked: ${e} (${o}ms ago)`),!0):!1}function yf(e){jl.set(e,Date.now())}function bf(e){return Yo.get(e)||null}function vf(e,t){Yo.set(e,t);const r=()=>{Yo.delete(e),yf(e)};return t.then(r,r),t}async function wf(e,t,r={}){const{windowMs:s=Sa,throwOnDuplicate:o=!0}=r,a=bf(e);if(a)return J.getLogger().debug(`[Deduplication] Reusing in-flight request: ${e}`),a;if(xf(e,s)){if(o)throw new Error(`Duplicate request blocked: ${e}`);return J.getLogger().warn(`[Deduplication] Duplicate request blocked but not throwing: ${e}`),Promise.reject(new Error("Duplicate request"))}const i=t();return vf(e,i)}function Mn(e,t,r={}){const{cooldownMs:s=kl,deduplicationWindowMs:o=Sa}=r;return async()=>{if(hf(e)){J.getLogger().debug(`[Deduplication] Button in cooldown: ${e}`);return}gf(e,s);try{await wf(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 Ca(e){return{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:e,opacity:.6,padding:"0.25rem",lineHeight:1}}const gn={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 Dn(e,t){if(typeof window>"u")return;const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!1});window.dispatchEvent(r)}function Ln(e,t,r){Dn(gn.PAYMENT_START,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function Xo(e){Dn(gn.WALLET_CONNECT,{timestamp:Date.now(),wallet:e})}function Sl(e,t){Dn(gn.WALLET_CONNECTED,{timestamp:Date.now(),wallet:e,publicKey:t})}function is(e,t){Dn(gn.WALLET_ERROR,{timestamp:Date.now(),wallet:t,error:e})}function un(e,t,r){Dn(gn.PAYMENT_PROCESSING,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function $n(e,t,r,s){Dn(gn.PAYMENT_SUCCESS,{timestamp:Date.now(),method:e,transactionId:t,resource:r,itemCount:s})}function kt(e,t,r,s){Dn(gn.PAYMENT_ERROR,{timestamp:Date.now(),method:e,error:t,resource:r,itemCount:s})}class ln extends Error{code;retryable;details;httpStatus;constructor(t,r,s=!1,o,a){super(r),this.name="PaymentError",this.code=t,this.retryable=s,this.details=o,this.httpStatus=a,Object.setPrototypeOf(this,ln.prototype)}canRetry(){return this.retryable}is(t){return this.code===t}isInCategory(t){return t.includes(this.code)}getUserMessage(){const t=this.getErrorInfo();return t.action?`${t.message} ${t.action}`:t.message}getShortMessage(){return this.getErrorInfo().message}getAction(){return this.getErrorInfo().action}getErrorInfo(){return fs(this.code)}static fromErrorResponse(t,r){const s=t.error.retryable??Cl.RETRYABLE.includes(t.error.code);return new ln(t.error.code,t.error.message,s,t.error.details,r)}static fromUnknown(t){return t instanceof ln?t:t instanceof Error?new ln("internal_error",t.message,!1):new ln("internal_error",String(t),!1)}}const Cl={INSUFFICIENT_FUNDS:["insufficient_funds_sol","insufficient_funds_token"],TRANSACTION_PENDING:["transaction_not_confirmed","transaction_not_found"],VALIDATION:["missing_field","invalid_field","invalid_amount","invalid_wallet","invalid_resource","invalid_cart_item","empty_cart"],COUPON:["invalid_coupon","coupon_not_found","coupon_expired","coupon_usage_limit_reached","coupon_not_applicable","coupon_wrong_payment_method"],RETRYABLE:["transaction_not_confirmed","rpc_error","network_error","stripe_error"],NOT_FOUND:["resource_not_found","cart_not_found","refund_not_found","product_not_found","coupon_not_found","session_not_found","credits_hold_not_found"],CREDITS:["insufficient_credits","credits_hold_expired","credits_hold_not_found"],SECURITY:["invalid_redirect_url","rate_limit_exceeded","nonce_already_used"]};function _f(e){return e instanceof ln&&e.canRetry()}function jf(e){return e instanceof ln?e.getUserMessage():e instanceof Error?e.message:String(e)}function kf(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 Sf(e){try{const t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e}}function Nl(e={}){const{solanaCluster:t="mainnet-beta",solanaEndpoint:r,customRpcProviders:s=[],allowUnsafeScripts:o=!1,additionalScriptSrc:a=[],additionalConnectSrc:i=[],additionalFrameSrc:c=[],includeStripe:l=!0}=e;o&&console.warn("[CedrosPay] SECURITY WARNING: allowUnsafeScripts is enabled. This adds 'unsafe-inline' and 'unsafe-eval' to script-src, which significantly weakens CSP protection against XSS attacks. Only use this in development or if absolutely required by your framework.");const d=["'self'"];o&&d.push("'unsafe-inline'","'unsafe-eval'"),l&&d.push("https://js.stripe.com"),d.push(...a);const m=["'self'"];l&&m.push("https://api.stripe.com","https://*.stripe.com");const u=kf(t);if(m.push(u),r){const h=Sf(r);m.includes(h)||m.push(h)}s.forEach(h=>{m.includes(h)||m.push(h)}),m.push(...i);const p=["'self'"];return l&&p.push("https://js.stripe.com","https://checkout.stripe.com"),p.push(...c),{scriptSrc:d,connectSrc:m,frameSrc:p}}function Pl(e,t="header"){const{scriptSrc:r,connectSrc:s,frameSrc:o}=e;switch(t){case"header":case"meta":case"nextjs":case"nginx":{const a=[];return r.length>0&&a.push(`script-src ${r.join(" ")}`),s.length>0&&a.push(`connect-src ${s.join(" ")}`),o.length>0&&a.push(`frame-src ${o.join(" ")}`),a.join("; ")}case"helmet":{const a={};return r.length>0&&(a.scriptSrc=r),s.length>0&&(a.connectSrc=s),o.length>0&&(a.frameSrc=o),a}case"directives":return{scriptSrc:r,connectSrc:s,frameSrc:o};default:throw new Error(`Unknown CSP format: ${t}`)}}function Cf(e={},t="header"){const r=Nl(e);return Pl(r,t)}const Nf={HELIUS:"https://*.helius-rpc.com",QUICKNODE:"https://*.quicknode.pro",ALCHEMY:"https://*.alchemy.com",ANKR:"https://rpc.ankr.com",TRITON:"https://*.rpcpool.com"},Pf={MAINNET_CUSTOM_RPC:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),MAINNET_NEXTJS:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),DEVNET:()=>({solanaCluster:"devnet",allowUnsafeScripts:!1}),CRYPTO_ONLY:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,includeStripe:!1}),STRIPE_ONLY:()=>({solanaCluster:"mainnet-beta",includeStripe:!0,customRpcProviders:[]})};function kr(e){return new Date(e).toLocaleString()}function Rs(){const{stripeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,transactionId:null}),s=y.useRef(!1),o=y.useCallback(async(c,l,d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const h={resource:c,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p};try{const _=await e.processPayment(h);return r({status:_.success?"success":"error",error:_.success?null:_.error||"Payment failed",transactionId:_.success&&_.transactionId||null}),_}catch(_){const g=_ instanceof Error?_.message:"Payment failed";return r({status:"error",error:g,transactionId:null}),{success:!1,error:g}}finally{s.current=!1}},[e]),a=y.useCallback(async(c,l,d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const h=ps(c);try{const _=await e.processCartCheckout({items:h,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p});return r({status:_.success?"success":"error",error:_.success?null:_.error||"Cart checkout failed",transactionId:_.success&&_.transactionId||null}),_}catch(_){const g=_ instanceof Error?_.message:"Cart checkout failed";return r({status:"error",error:g,transactionId:null}),{success:!1,error:g}}finally{s.current=!1}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,transactionId:null}),s.current=!1},[]);return{...t,processPayment:o,processCartCheckout:a,reset:i}}function nr(e,t){return y.useMemo(()=>{const r=pf(t),s=e||(t?.length===1?t[0].resource:"");return{isCartMode:r,effectiveResource:s}},[e,t])}const Af=(e,t,r)=>{const s=e[t];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((o,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},bo=new Map;let Wr=null;async function Gi(e){if(bo.has(e))return bo.get(e);try{const t=await Af(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),r=t.default||t;return bo.set(e,r),r}catch{return null}}async function Ef(){if(Wr)return Wr;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 r in e){const s=r.match(/\.\/translations\/([a-z]{2,3}(?:-[A-Z]{2})?)\.json$/);s&&t.push(s[1])}return Wr=t.length>0?t:["en"],Wr}function Al(){return typeof navigator>"u"?"en":(navigator.language||navigator.userLanguage||"en").split("-")[0].toLowerCase()}async function El(e){let t=await Gi(e);if(t||(t=await Gi("en"),t))return t;throw new Error("Critical: No translation files found, not even en.json")}function Tl(e){return(t,r)=>{const s=t.split(".");let o=e;for(const a of s)if(o&&typeof o=="object"&&a in o)o=o[a];else return t;return typeof o!="string"?t:r?Object.entries(r).reduce((a,[i,c])=>a.replace(new RegExp(`\\{${i}\\}`,"g"),c),o):o}}function Tf(e,t,r=!0){const s=t.errors[e];if(!s){const o=fs(e);return r&&o.action?`${o.message} ${o.action}`:o.message}return r&&s.action?`${s.message} ${s.action}`:s.message}function xn(e){const[t,r]=y.useState(null),[s,o]=y.useState(!0),a=y.useMemo(()=>e||Al(),[e]);return y.useEffect(()=>{let c=!1;return(async()=>{o(!0);try{const d=await El(a);c||(r(d),o(!1))}catch(d){console.error("[CedrosPay] Failed to load translations:",d),c||o(!1)}})(),()=>{c=!0}},[a]),{t:y.useMemo(()=>t?Tl(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:s,translations:t}}function If(e,t=!0){const{translations:r}=xn();if(!r){const o=fs(e);return t&&o.action?`${o.message} ${o.action}`:o.message}const s=r.errors[e];if(!s){const o=fs(e);return t&&o.action?`${o.message} ${o.action}`:o.message}return t&&s.action?`${s.message} ${s.action}`:s.message}function Na({resource:e,items:t,successUrl:r,cancelUrl:s,metadata:o,customerEmail:a,couponCode:i,label:c,disabled:l=!1,onAttempt:d,onSuccess:m,onError:u,className:p=""}){const{status:h,error:_,transactionId:g,processPayment:f,processCartCheckout:w}=Rs(),j=J.useCedrosTheme(),{isCartMode:v,effectiveResource:b}=nr(e,t),{t:k,translations:R}=xn(),N=c||k("ui.pay_with_card"),C=j.unstyled?p:`${j.className} cedros-theme__stripe-button ${p}`.trim(),T=_&&typeof _!="string"?_?.code??null:null,$=_?typeof _=="string"?_:(E=>{if(!E||!R)return"";const P=R.errors[E];return P?P.action?`${P.message} ${P.action}`:P.message:""})(T):null,S=y.useCallback(async()=>{J.getLogger().debug("[StripeButton] executePayment with couponCode:",i);const E=v&&t?dn(t):void 0;if(Ln("stripe",b,E),d&&d("stripe"),!v&&!b){const z="Invalid payment configuration: missing resource or items";J.getLogger().error("[StripeButton]",z),kt("stripe",z,b,E),u&&u(z);return}let P;un("stripe",b,E),v&&t?(J.getLogger().debug("[StripeButton] Processing cart checkout with coupon:",i),P=await w(t,r,s,o,a,i)):b&&(J.getLogger().debug("[StripeButton] Processing single payment with coupon:",i),P=await f(b,r,s,o,a,i)),P&&P.success&&P.transactionId?($n("stripe",P.transactionId,b,E),m&&m(P.transactionId)):P&&!P.success&&P.error&&(kt("stripe",P.error,b,E),u&&u(P.error))},[i,v,b,t,r,s,o,a,w,f,d,m,u]),A=y.useMemo(()=>v&&t?`stripe-cart-${t.map(E=>E.resource).join("-")}`:`stripe-${b||"unknown"}`,[v,t,b]),I=y.useMemo(()=>Mn(A,S),[A,S]),B=h==="loading",D=l||B;return n.jsxs("div",{className:C,style:j.unstyled?{}:j.style,children:[n.jsx("button",{onClick:I,disabled:D,className:j.unstyled?p:"cedros-theme__button cedros-theme__stripe",type:"button",children:B?k("ui.processing"):N}),$&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__error",children:$}),g&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__success",children:k("ui.payment_successful")})]})}function Il(){const{creditsManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s=y.useRef(!1),o=y.useCallback(async(d,m)=>{r(u=>({...u,status:"loading",error:null}));try{const u=await e.requestQuote(d,m);return r(p=>({...p,status:"idle",requirement:u})),u}catch(u){const p=u instanceof Error?u.message:"Failed to fetch credits quote";return r(h=>({...h,status:"error",error:p})),null}},[e]),a=y.useCallback(async(d,m)=>{r(u=>({...u,status:"loading",error:null}));try{const u=ps(d),p=await e.requestCartQuote(u,m);return r(h=>({...h,status:"idle"})),p}catch(u){const p=u instanceof Error?u.message:"Failed to fetch cart credits quote";return r(h=>({...h,status:"error",error:p})),null}},[e]),i=y.useCallback(async(d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=await e.processPayment(d,m,u,p);return r({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}finally{s.current=!1}},[e]),c=y.useCallback(async(d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=ps(d),_=await e.requestCartQuote(h,u);if(!_)return r({status:"error",error:"Credits payment not available for this cart",transactionId:null,requirement:null,holdId:null}),{success:!1,error:"Credits payment not available"};const f=(await e.createCartHold({cartId:_.cartId,authToken:m})).holdId;r(j=>({...j,holdId:f}));const w=await e.authorizeCartPayment({cartId:_.cartId,holdId:f,authToken:m,metadata:p});return r({status:w.success?"success":"error",error:w.success?null:w.error||"Cart credits payment failed",transactionId:w.success&&w.transactionId||null,requirement:null,holdId:null}),{success:w.success,transactionId:w.transactionId,error:w.error}}catch(h){const _=h instanceof Error?h.message:"Cart credits payment failed";return r({status:"error",error:_,transactionId:null,requirement:null,holdId:null}),{success:!1,error:_}}finally{s.current=!1}},[e]),l=y.useCallback(()=>{r({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s.current=!1},[]);return{...t,fetchQuote:o,fetchCartQuote:a,processPayment:i,processCartPayment:c,reset:l}}function Pa({resource:e,items:t,authToken:r,metadata:s,couponCode:o,label:a,disabled:i=!1,onAttempt:c,onSuccess:l,onError:d,className:m=""}){const{status:u,error:p,transactionId:h,processPayment:_,processCartPayment:g}=Il(),f=J.useCedrosTheme(),{isCartMode:w,effectiveResource:j}=nr(e,t),{t:v,translations:b}=xn(),k=a||v("ui.pay_with_credits")||"Pay with Credits",R=f.unstyled?m:`${f.className} cedros-theme__credits-button ${m}`.trim(),N=p&&typeof p!="string"?p?.code??null:null,T=p?typeof p=="string"?p:(B=>{if(!B||!b)return"";const D=b.errors[B];return D?D.action?`${D.message} ${D.action}`:D.message:""})(N):null,O=y.useCallback(async()=>{J.getLogger().debug("[CreditsButton] executePayment");const B=w&&t?dn(t):void 0;if(Ln("credits",j,B),c&&c("credits"),!r){const E="Authentication required: please log in to pay with credits";J.getLogger().error("[CreditsButton]",E),kt("credits",E,j,B),d&&d(E);return}if(!w&&!j){const E="Invalid payment configuration: missing resource";J.getLogger().error("[CreditsButton]",E),kt("credits",E,j,B),d&&d(E);return}let D;un("credits",j,B),w&&t?(J.getLogger().debug("[CreditsButton] Processing cart checkout"),D=await g(t,r,o,s)):j&&(J.getLogger().debug("[CreditsButton] Processing single payment"),D=await _(j,r,o,s)),D&&D.success&&D.transactionId?($n("credits",D.transactionId,j,B),l&&l(D.transactionId)):D&&!D.success&&D.error&&(kt("credits",D.error,j,B),d&&d(D.error))},[r,w,j,t,o,s,_,g,c,l,d]),$=y.useMemo(()=>w&&t?`credits-cart-${t.map(B=>B.resource).join("-")}`:`credits-${j||"unknown"}`,[w,t,j]),S=y.useMemo(()=>Mn($,O),[$,O]),A=u==="loading",I=i||A;return n.jsxs("div",{className:R,style:f.unstyled?{}:f.style,children:[n.jsx("button",{onClick:S,disabled:I,className:f.unstyled?m:"cedros-theme__button cedros-theme__credits",type:"button",children:A?v("ui.processing"):k}),T&&n.jsx("div",{className:f.unstyled?"":"cedros-theme__error",children:T}),h&&n.jsx("div",{className:f.unstyled?"":"cedros-theme__success",children:v("ui.payment_successful")})]})}function Rl(){const{x402Manager:e,walletManager:t}=J.useCedrosContext(),{publicKey:r,signTransaction:s}=ja.useWallet(),[o,a]=y.useState({status:"idle",error:null,transactionId:null}),[i,c]=y.useState(null),[l,d]=y.useState(null),m=y.useRef(!1),u=y.useCallback(()=>{if(!r){const w="Wallet not connected";return a({status:"error",error:w,transactionId:null}),{valid:!1,error:w}}if(!s){const w="Wallet does not support signing";return a({status:"error",error:w,transactionId:null}),{valid:!1,error:w}}return{valid:!0}},[r,s]),p=y.useCallback(async w=>{try{a(v=>({...v,status:"loading"}));const j=await e.requestQuote({resource:w});if(!e.validateRequirement(j))throw new Error("Invalid requirement received from server");return c(j),a(v=>({...v,status:"idle"})),j}catch(j){const v=J.formatError(j,"Failed to fetch requirement");throw a({status:"error",error:v,transactionId:null}),j}},[e]),h=y.useCallback(async(w,j,v,b,k="regular")=>{if(!!w.extra?.feePayer){console.log("⚡ [useX402Payment] GASLESS FLOW - Backend pays fees"),console.log("🔨 [useX402Payment] Requesting backend to build gasless transaction");const{transaction:N,blockhash:C}=await e.buildGaslessTransaction({resourceId:j,userWallet:r.toString(),feePayer:w.extra.feePayer,couponCode:v});console.log("📦 [useX402Payment] Deserializing transaction from backend");const T=t.deserializeTransaction(N);console.log("✍️ [useX402Payment] Requesting wallet to partially sign (transfer authority only)");const O=await t.partiallySignTransaction({transaction:T,signTransaction:s,blockhash:C});console.log("📤 [useX402Payment] Submitting partially-signed transaction to backend");const $=await e.submitGaslessTransaction({resource:j,partialTx:O,couponCode:v,metadata:b,resourceType:k,requirement:w});return $.success&&$.settlement&&d($.settlement),$}else{const N=await t.buildTransaction({requirement:w,payerPublicKey:r}),C=await t.signTransaction({transaction:N,signTransaction:s}),T=t.buildPaymentPayload({requirement:w,signedTx:C,payerPublicKey:r}),O=await e.submitPayment({resource:j,payload:T,couponCode:v,metadata:b,resourceType:k});return O.success&&O.settlement&&d(O.settlement),O}},[r,s,e,t]),_=y.useCallback(async(w,j,v)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const b=u();if(!b.valid)return{success:!1,error:b.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{console.log("🔍 [useX402Payment] Fetching fresh quote for resource:",w);const k=await e.requestQuote({resource:w,couponCode:j});console.log("✅ [useX402Payment] Got quote:",{payTo:k.payTo,amount:k.maxAmountRequired}),c(k),console.log("⚙️ [useX402Payment] Executing payment flow with fresh requirement");const R=await h(k,w,j,v,"regular");return R.success?a({status:"success",error:null,transactionId:R.transactionId||"payment-success"}):a({status:"error",error:R.error||"Payment failed",transactionId:null}),R}catch(k){const R=J.formatError(k,"Payment failed");return a({status:"error",error:R,transactionId:null}),{success:!1,error:R}}finally{m.current=!1}},[u,e,h]),g=y.useCallback(async(w,j,v)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const b=u();if(!b.valid)return{success:!1,error:b.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{const k=ps(w),R=await e.requestCartQuote({items:k,metadata:j,couponCode:v}),N=R.cartId,C=R.quote;if(!e.validateRequirement(C))throw new Error("Invalid cart quote received from server");c(C);const T=await h(C,N,v,j,"cart");return T.success?a({status:"success",error:null,transactionId:T.transactionId||"cart-payment-success"}):a({status:"error",error:T.error||"Cart payment failed",transactionId:null}),T}catch(k){const R=J.formatError(k,"Cart payment failed");return a({status:"error",error:R,transactionId:null}),{success:!1,error:R}}finally{m.current=!1}},[u,e,h]),f=y.useCallback(()=>{a({status:"idle",error:null,transactionId:null}),c(null),d(null),m.current=!1},[]);return{...o,requirement:i,settlement:l,fetchQuote:p,processPayment:_,processCartPayment:g,reset:f}}function Aa({resource:e,items:t,label:r,disabled:s=!1,onAttempt:o,onSuccess:a,onError:i,className:c="",testPageUrl:l,hideMessages:d=!1,metadata:m,couponCode:u}){const{connected:p,connecting:h,connect:_,disconnect:g,select:f,wallets:w,wallet:j,publicKey:v}=ja.useWallet(),{status:b,error:k,transactionId:R,processPayment:N,processCartPayment:C}=Rl(),T=J.useCedrosTheme(),{solanaError:O}=J.useCedrosContext(),{isCartMode:$,effectiveResource:S}=nr(e,t),{t:A,translations:I}=xn(),B=r||A("ui.pay_with_crypto"),D=k&&typeof k!="string"?k?.code??null:null,E=O&&typeof O!="string"?O?.code??null:null,P=te=>{if(!te||!I)return"";const xe=I.errors[te];return xe?xe.action?`${xe.message} ${xe.action}`:xe.message:""},z=k?typeof k=="string"?k:P(D):null,Z=O?typeof O=="string"?O:P(E):null,K=y.useRef(N),L=y.useRef(C);y.useEffect(()=>{K.current=N,L.current=C},[N,C]);const W=y.useMemo(()=>w.map(te=>`${te.adapter.name}-${te.readyState}`).join(","),[w]),Y=y.useMemo(()=>w.filter(({readyState:te})=>te===Hi.WalletReadyState.Installed||te===Hi.WalletReadyState.Loadable),[W]);y.useEffect(()=>{if(b==="success"&&R){const te=$&&t?dn(t):void 0;$n("crypto",R,S,te),a&&a(R)}},[b,R,a,$,t,S]),y.useEffect(()=>{if(b==="error"&&k){const te=$&&t?dn(t):void 0;kt("crypto",k,S,te),i&&i(k)}},[b,k,i,$,t,S]);const V=typeof window<"u"&&window.top!==window.self,[ce,F]=y.useState(!1),[ee,pe]=y.useState(!1),[q,ne]=y.useState(null),le=O;y.useEffect(()=>{let te=!1;return te||(async()=>{if(ee&&j&&!p&&!h){J.getLogger().debug("[CryptoButton] Wallet detected, attempting auto-connect:",j.adapter.name),pe(!1),Xo(j.adapter.name);try{await _(),te||J.getLogger().debug("[CryptoButton] Auto-connect successful")}catch(ge){if(!te){J.getLogger().error("[CryptoButton] Auto-connect failed:",ge);const dt=ge instanceof Error?ge.message:"Failed to connect wallet";is(dt,j.adapter.name),ne(null)}}}})(),()=>{te=!0}},[j,ee,p,h,_]),y.useEffect(()=>{if(J.getLogger().debug("[CryptoButton] Payment useEffect triggered",{connected:p,hasPendingPayment:!!q,hasPublicKey:!!v,pendingPaymentType:q?.type}),p&&q&&v&&j){Sl(j.adapter.name,v.toString()),J.getLogger().debug("[CryptoButton] All conditions met! Processing pending payment:",q);const te=q;ne(null),F(!1);const xe=te.type==="cart"&&te.items?dn(te.items):void 0;un("crypto",te.resource,xe),te.type==="cart"&&te.items?(J.getLogger().debug("[CryptoButton] Auto-processing cart payment"),L.current(te.items,te.metadata,te.couponCode)):te.type==="single"&&te.resource&&(J.getLogger().debug("[CryptoButton] Auto-processing single payment"),K.current(te.resource,te.couponCode,te.metadata))}},[p,q,v,j]);const fe=y.useCallback(async()=>{J.getLogger().debug("[CryptoButton] executePaymentFlow called",{connected:p,wallet:j?.adapter.name,couponCode:u,isCartMode:$,hasItems:!!t,effectiveResource:S});const te=$&&t?dn(t):void 0;if(Ln("crypto",S,te),o&&o("crypto"),le){J.getLogger().error("[CryptoButton] Solana dependencies missing:",le),kt("crypto",le,S,te),i&&i(le);return}if(V){const xe=l||window.location.href;try{if(new URL(xe,window.location.origin).origin!==window.location.origin)throw J.getLogger().error("[CryptoButton] Blocked attempt to open external URL:",xe),new Error("Cannot open external URLs from embedded context");window.open(xe,"_blank","noopener,noreferrer")}catch(ge){throw J.getLogger().error("[CryptoButton] URL validation failed:",ge),ge}return}if(p)un("crypto",S,te),$&&t?(J.getLogger().debug("[CryptoButton] Processing cart payment with coupon:",u),await C(t,m,u)):S&&(J.getLogger().debug("[CryptoButton] Processing single payment with coupon:",u),await N(S,u,m));else{let xe=!1;if($&&t?(J.getLogger().debug("[CryptoButton] Setting pending cart payment with coupon:",u),ne({type:"cart",items:t,metadata:m,couponCode:u}),xe=!0):S&&(J.getLogger().debug("[CryptoButton] Setting pending single payment with coupon:",u),ne({type:"single",resource:S,metadata:m,couponCode:u}),xe=!0),!xe){J.getLogger().error("[CryptoButton] No valid payment to process");return}try{if(j)J.getLogger().debug("[CryptoButton] Wallet already selected, connecting:",j.adapter.name),Xo(j.adapter.name),await _();else{if(J.getLogger().debug("[CryptoButton] No wallet selected, showing selector. Available wallets:",Y.map(ge=>ge.adapter.name)),Y.length===0){ne(null);const ge="No wallets available";throw is(ge),new Error(ge)}F(!0)}}catch(ge){ne(null);const dt=ge instanceof Error?ge.message:"Failed to connect wallet";J.getLogger().error("[CryptoButton] Connection error:",dt),is(dt,j?.adapter.name)}}},[p,j,u,$,t,S,V,l,Y,_,m,C,N,le,o,i]),Pe=y.useMemo(()=>$&&t?`crypto-cart-${t.map(te=>te.resource).join("-")}`:`crypto-${S||"unknown"}`,[$,t,S]),Ve=y.useMemo(()=>Mn(Pe,fe,{cooldownMs:200,deduplicationWindowMs:0}),[Pe,fe]),qe=b==="loading",He=s||qe||h||!!le,xt=qe?A("ui.processing"):B,Ge=y.useCallback(async()=>{try{pe(!1),p&&await g(),f(null),F(!0)}catch(te){J.getLogger().error("Failed to change wallet:",te)}},[p,g,f]),zt=y.useCallback(te=>{J.getLogger().debug("[CryptoButton] Wallet clicked:",te),F(!1),f(te),pe(!0),J.getLogger().debug("[CryptoButton] Wallet selected, useEffect will auto-connect")},[f]),lt=y.useCallback(async()=>{try{if(await g(),ne(null),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(te){te instanceof Error&&te.name==="QuotaExceededError"?J.getLogger().warn("localStorage quota exceeded when removing wallet preference"):J.getLogger().error("Failed to clear wallet preference from localStorage:",te)}}catch(te){J.getLogger().error("Failed to disconnect wallet:",te)}},[g]);return n.jsxs("div",{className:T.unstyled?c:`${T.className} cedros-theme__crypto-button ${c||""}`,style:T.unstyled?{}:T.style,children:[n.jsx("button",{onClick:Ve,disabled:He,className:T.unstyled?c:"cedros-theme__button cedros-theme__crypto",type:"button",children:xt}),ce&&!d&&n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:T.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>F(!1),children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:T.tokens.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${T.tokens.modalBorder}`},onClick:te=>te.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:T.tokens.surfaceText},children:A("wallet.select_wallet")}),n.jsx("button",{onClick:()=>F(!1),style:Ca(T.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:Y.map(te=>n.jsxs("button",{onClick:()=>zt(te.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:T.tokens.surfaceBackground,border:`1px solid ${T.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:T.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:xe=>{xe.currentTarget.style.backgroundColor=T.tokens.modalBackground,xe.currentTarget.style.borderColor=T.tokens.surfaceText,xe.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:xe=>{xe.currentTarget.style.backgroundColor=T.tokens.surfaceBackground,xe.currentTarget.style.borderColor=T.tokens.surfaceBorder,xe.currentTarget.style.transform="translateY(0)"},type:"button",children:[n.jsx(of.WalletIcon,{wallet:te,style:{width:"24px",height:"24px"}}),n.jsx("span",{style:{fontWeight:500},children:te.adapter.name})]},te.adapter.name))})]})}),p&&!d&&!ce&&n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:T.tokens.surfaceText,opacity:.7},children:[n.jsx("button",{onClick:Ge,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:"Change Wallet"}),n.jsx("button",{onClick:lt,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:A("ui.disconnect")})]}),!d&&Z&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__error",children:Z}),!d&&z&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__error",children:z}),!d&&R&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__success",children:A("ui.payment_successful")})]})}const Rf=Object.freeze(Object.defineProperty({__proto__:null,CryptoButton:Aa},Symbol.toStringTag,{value:"Module"})),Ol=({isOpen:e,onClose:t,resource:r,items:s,cardLabel:o="Card",cryptoLabel:a="USDC (Solana)",creditsLabel:i="Pay with Credits",showCard:c=!0,showCrypto:l=!0,showCredits:d=!1,onPaymentAttempt:m,onPaymentSuccess:u,onPaymentError:p,onStripeSuccess:h,onCryptoSuccess:_,onCreditsSuccess:g,onStripeError:f,onCryptoError:w,onCreditsError:j,customerEmail:v,successUrl:b,cancelUrl:k,metadata:R,couponCode:N,authToken:C,testPageUrl:T,hideMessages:O=!1})=>{const{tokens:$}=J.useCedrosTheme();return y.useEffect(()=>{const S=A=>{A.key==="Escape"&&e&&t()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[e,t]),y.useEffect(()=>{if(e){const S=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${S}px`,document.body.style.width="100%",document.body.style.overflowY="scroll",()=>{const A=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,A)}}},[e]),e?n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:$.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:t,children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:$.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 ${$.modalBorder}`},onClick:S=>S.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:$.surfaceText},children:"Choose Payment Method"}),n.jsx("button",{onClick:t,style:Ca($.surfaceText),"aria-label":"Close modal",children:"×"})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[c&&n.jsx(Na,{resource:r,items:s,label:o,onAttempt:m,onSuccess:h||u,onError:f||p,customerEmail:v,successUrl:b,cancelUrl:k,metadata:R,couponCode:N}),l&&n.jsx(Aa,{resource:r,items:s,label:a,onAttempt:m,onSuccess:_||u,onError:w||p,testPageUrl:T,hideMessages:O,metadata:R,couponCode:N}),d&&n.jsx(Pa,{resource:r,items:s,label:i,authToken:C,onAttempt:m?()=>m("credits"):void 0,onSuccess:g||u,onError:j||p,metadata:R,couponCode:N})]})]})}):null},Ml=({resource:e,items:t,label:r,cardLabel:s,cryptoLabel:o,creditsLabel:a,showCard:i=!0,showCrypto:c=!0,showCredits:l=!1,onPaymentAttempt:d,onPaymentSuccess:m,onPaymentError:u,onStripeSuccess:p,onCryptoSuccess:h,onCreditsSuccess:_,onStripeError:g,onCryptoError:f,onCreditsError:w,customerEmail:j,successUrl:v,cancelUrl:b,metadata:k,couponCode:R,authToken:N,autoDetectWallets:C=!0,testPageUrl:T,hideMessages:O=!1,renderModal:$})=>{const S=J.useCedrosTheme(),[A,I]=y.useState(!1),{status:B,processPayment:D,processCartCheckout:E}=Rs(),{isCartMode:P,effectiveResource:z}=nr(e,t),{t:Z}=xn(),K=r||Z("ui.purchase"),L=s||Z("ui.card"),W=o||Z("ui.usdc_solana"),Y=a||Z("ui.pay_with_credits")||"Pay with Credits",V=y.useCallback(async()=>{if(C&&i){const{detectSolanaWallets:q}=await Promise.resolve().then(()=>zC);if(!q()){const ne=P?void 0:z,le=P&&t?dn(t):void 0;Ln("stripe",ne,le),d&&d("stripe"),un("stripe",ne,le);let fe;P&&t?fe=await E(t,v,b,k,j,R):z&&(fe=await D(z,v,b,k,j,R)),fe&&fe.success&&fe.transactionId?($n("stripe",fe.transactionId,ne,le),p?p(fe.transactionId):m&&m(fe.transactionId)):fe&&!fe.success&&fe.error&&(kt("stripe",fe.error,ne,le),g?g(fe.error):u&&u(fe.error));return}}I(!0)},[C,i,P,t,z,E,D,v,b,k,j,R,m,u,p,g,d]),ce=y.useMemo(()=>P&&t?`purchase-cart-${t.map(q=>q.resource).join("-")}`:`purchase-${z||"unknown"}`,[P,t,z]),F=y.useMemo(()=>Mn(ce,V),[ce,V]),ee=B==="loading",pe={isOpen:A,onClose:()=>I(!1),resource:P?void 0:z,items:P?t:void 0,cardLabel:L,cryptoLabel:W,creditsLabel:Y,showCard:i,showCrypto:c,showCredits:l,onPaymentAttempt:d,onPaymentSuccess:q=>{I(!1),m?.(q)},onPaymentError:q=>{I(!1),u?.(q)},onStripeSuccess:q=>{I(!1),p?.(q)},onCryptoSuccess:q=>{I(!1),h?.(q)},onCreditsSuccess:q=>{I(!1),_?.(q)},onStripeError:q=>{I(!1),g?.(q)},onCryptoError:q=>{I(!1),f?.(q)},onCreditsError:q=>{I(!1),w?.(q)},customerEmail:j,successUrl:v,cancelUrl:b,metadata:k,couponCode:R,authToken:N,testPageUrl:T,hideMessages:O};return n.jsxs("div",{className:S.unstyled?"":S.className,style:S.unstyled?{}:S.style,children:[n.jsx("button",{onClick:F,disabled:ee,className:S.unstyled?"":"cedros-theme__button cedros-theme__stripe",style:{width:"100%",cursor:ee?"not-allowed":"pointer",opacity:ee?.6:1},type:"button",children:ee?Z("ui.processing"):K}),$?$(pe):n.jsx(Ol,{...pe})]})},Of={"mainnet-beta":"https://api.mainnet-beta.solana.com",devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com"};function Mf(){const[e,t]=y.useState(null);return y.useEffect(()=>{let r=!1;return import("@solana/wallet-adapter-react").then(s=>{r||t(s)}),()=>{r=!0}},[]),e}function Df({endpoint:e,wallets:t,children:r}){const s=Mf();if(!s)return n.jsx(n.Fragment,{children:r});const{ConnectionProvider:o,WalletProvider:a}=s;return n.jsx(o,{endpoint:e,children:n.jsx(a,{wallets:t,autoConnect:!1,children:r})})}const Lf=y.lazy(()=>Promise.resolve().then(()=>Rf).then(e=>({default:e.CryptoButton})));function $f(e){const{resource:t,items:r,checkout:s={},display:o={},callbacks:a={},advanced:i={}}=e,{config:c,walletPool:l}=J.useCedrosContext(),d=J.useCedrosTheme(),{isCartMode:m}=nr(t,r),u=o.showCrypto??!0,p=y.useMemo(()=>({marginTop:"0.5rem",fontSize:"0.875rem",color:d.tokens.surfaceText,opacity:.7,textAlign:"center"}),[d.tokens.surfaceText]),h=y.useMemo(()=>u?i.wallets&&i.wallets.length>0?i.wallets:l.getAdapters():[],[i.wallets,l,u]),_=y.useMemo(()=>r?dn(r):0,[r]),g=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"stripe"}):void 0,[a.onPaymentSuccess]),f=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"crypto"}):void 0,[a.onPaymentSuccess]),w=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"stripe"}):void 0,[a.onPaymentError]),j=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"crypto"}):void 0,[a.onPaymentError]),v=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"credits"}):void 0,[a.onPaymentSuccess]),b=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"credits"}):void 0,[a.onPaymentError]),k=y.useMemo(()=>a.onPaymentAttempt?()=>a.onPaymentAttempt("credits"):void 0,[a.onPaymentAttempt]),R=u?c.solanaEndpoint??Of[c.solanaCluster]:"";if(!t&&(!r||r.length===0))return J.getLogger().error('CedrosPay: Must provide either "resource" or "items" prop'),n.jsx("div",{className:o.className,style:{color:d.tokens.errorText},children:"Configuration error: No resource or items provided"});const N=o.showCard??!0,C=o.showCredits??!1,T=o.showPurchaseButton??!1,O=o.layout??"vertical",$=o.hideMessages??!1,S=i.autoDetectWallets??!0,A=n.jsx("div",{className:d.unstyled?o.className:`cedros-theme__pay ${o.className||""}`,children:n.jsxs("div",{className:d.unstyled?"":`cedros-theme__pay-content cedros-theme__pay-content--${O}`,children:[T?n.jsx(Ml,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,label:o.purchaseLabel,cardLabel:o.cardLabel,cryptoLabel:o.cryptoLabel,showCard:N,showCrypto:u,onPaymentAttempt:a.onPaymentAttempt,onPaymentSuccess:g,onPaymentError:w,onStripeSuccess:g,onCryptoSuccess:f,onStripeError:w,onCryptoError:j,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,autoDetectWallets:S,testPageUrl:i.testPageUrl,hideMessages:$,renderModal:o.renderModal}):n.jsxs(n.Fragment,{children:[N&&n.jsx(Na,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,label:o.cardLabel,onAttempt:a.onPaymentAttempt,onSuccess:g,onError:w}),u&&n.jsx(y.Suspense,{fallback:null,children:n.jsx(Lf,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,metadata:s.metadata,couponCode:s.couponCode,label:o.cryptoLabel,onAttempt:a.onPaymentAttempt,onSuccess:f,onError:j,testPageUrl:i.testPageUrl,hideMessages:$})}),C&&n.jsx(Pa,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,authToken:s.authToken,metadata:s.metadata,couponCode:s.couponCode,label:o.creditsLabel,onAttempt:k,onSuccess:v,onError:b})]}),m&&r&&r.length>1&&!$&&n.jsxs("div",{style:p,children:["Checking out ",_," items"]})]})});return n.jsx("div",{className:d.unstyled?o.className:d.className,style:d.unstyled?{}:d.style,children:u?n.jsx(Df,{endpoint:R,wallets:h,children:A}):A})}const Q={products:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),n.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),n.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),n.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),n.jsx("path",{d:"M3 3v5h5"}),n.jsx("path",{d:"M12 7v5l4 2"})]}),settings:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),n.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"}),n.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),n.jsx("path",{d:"M8 16H3v5"})]}),check:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})}),plus:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),n.jsx("path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9"}),n.jsx("path",{d:"M12 3v6"})]}),arrowUp:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7-7 7 7"}),n.jsx("path",{d:"M12 19V5"})]}),arrowDown:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7 7 7-7"}),n.jsx("path",{d:"M12 5v14"})]}),delete:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),n.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),faq:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),n.jsx("path",{d:"M12 17h.01"})]}),chat:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),n.jsx("path",{d:"M2 12h20"})]}),ai:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),n.jsx("path",{d:"M10 10v.5"}),n.jsx("path",{d:"M14 10v.5"}),n.jsx("path",{d:"M12 14v2"}),n.jsx("path",{d:"M8 18h8"}),n.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),n.jsx("path",{d:"M6 12v6"}),n.jsx("path",{d:"M18 12v6"})]}),notifications:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),n.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),n.jsx("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),n.jsx("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),n.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),n.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),n.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),n.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),n.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),n.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),n.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),n.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),n.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),n.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),n.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),n.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),n.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),n.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),n.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),n.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),n.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function Yt({message:e,onRetry:t}){return e?n.jsxs("div",{className:"cedros-admin__error-banner",children:[n.jsx("span",{children:e}),t&&n.jsxs("button",{type:"button",className:"cedros-admin__error-banner-retry",onClick:t,children:[Q.refresh," Retry"]})]}):null}function rr({stats:e,isLoading:t=!1,onRefresh:r}){return n.jsxs("div",{className:"cedros-admin__stats-bar",children:[n.jsx("div",{className:"cedros-admin__stats-bar-grid",children:e.map((s,o)=>n.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[n.jsx("span",{className:"cedros-admin__stats-bar-label",children:s.label}),n.jsx("span",{className:`cedros-admin__stats-bar-value ${s.variant?`cedros-admin__stats-bar-value--${s.variant}`:""}`,children:t?n.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):s.value}),s.description&&n.jsx("span",{className:"cedros-admin__stats-bar-desc",children:s.description})]},o))}),r&&n.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:r,disabled:t,title:"Refresh stats",children:t?Q.loading:Q.refresh})]})}function zf({serverUrl:e,productId:t,apiKey:r,authManager:s}){const[o,a]=y.useState(null),[i,c]=y.useState(!1),[l,d]=y.useState(!1),[m,u]=y.useState(null),p=y.useCallback(async()=>{if(t){c(!0),u(null);try{let g;if(s?.isAuthenticated())g=await s.fetchWithAuth(`/admin/products/${t}/variations`);else{const f={"Content-Type":"application/json"};r&&(f["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variations`,{headers:f});if(!w.ok)throw new Error(`Failed to fetch variations: ${w.status}`);g=await w.json()}g.variationConfig||(g.variationConfig={variationTypes:[]}),g.variants||(g.variants=[]),a(g)}catch(g){const f=g instanceof Error?g.message:"Failed to fetch variations";u(f),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,r,s]),h=y.useCallback(async g=>{if(!t)return null;d(!0),u(null);try{let f;if(s?.isAuthenticated())f=await s.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(g)});else{const w={"Content-Type":"application/json"};r&&(w["X-API-Key"]=r);const j=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:w,body:JSON.stringify(g)});if(!j.ok)throw new Error(`Failed to save variations: ${j.status}`);f=await j.json()}return a({productId:t,variationConfig:f.variationConfig,variants:f.variants}),{variantsCreated:f.variantsCreated}}catch(f){const w=f instanceof Error?f.message:"Failed to save variations";return u(w),null}finally{d(!1)}},[e,t,r,s]),_=y.useCallback(async g=>{if(!t||g.length===0)return!1;d(!0),u(null);try{if(s?.isAuthenticated())await s.fetchWithAuth(`/admin/products/${t}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:g})});else{const f={"Content-Type":"application/json"};r&&(f["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:f,body:JSON.stringify({updates:g})});if(!w.ok)throw new Error(`Failed to update inventory: ${w.status}`)}if(o){const f=new Map(g.map(w=>[w.variantId,w]));a({...o,variants:o.variants.map(w=>{const j=f.get(w.id);return j?{...w,inventoryQuantity:j.inventoryQuantity,inventoryStatus:j.inventoryStatus??w.inventoryStatus}:w})})}return!0}catch(f){const w=f instanceof Error?f.message:"Failed to update inventory";return u(w),!1}finally{d(!1)}},[e,t,r,s,o]);return{data:o,isLoading:i,error:m,fetch:p,save:h,bulkUpdateInventory:_,isSaving:l}}function Qi(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ff({value:e,onChange:t,maxTypes:r=5,maxValuesPerType:s=20,disabled:o=!1}){const[a,i]=y.useState(null),[c,l]=y.useState(""),[d,m]=y.useState({}),u=e.variationTypes,p=y.useCallback(()=>{if(!c.trim()||u.length>=r)return;const v={id:Qi(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,v]}),l(""),i(v.id)},[c,u,r,t]),h=y.useCallback(v=>{t({variationTypes:u.filter(b=>b.id!==v).map((b,k)=>({...b,displayOrder:k}))}),a===v&&i(null)},[u,t,a]),_=y.useCallback((v,b)=>{t({variationTypes:u.map(k=>k.id===v?{...k,name:b}:k)})},[u,t]),g=y.useCallback((v,b)=>{const k=u.findIndex(C=>C.id===v);if(k===-1||b==="up"&&k===0||b==="down"&&k===u.length-1)return;const R=[...u],N=b==="up"?k-1:k+1;[R[k],R[N]]=[R[N],R[k]],t({variationTypes:R.map((C,T)=>({...C,displayOrder:T}))})},[u,t]),f=y.useCallback(v=>{const b=(d[v]||"").trim();if(!b)return;const k=u.find(N=>N.id===v);if(!k||k.values.length>=s)return;const R={id:Qi(),label:b};t({variationTypes:u.map(N=>N.id===v?{...N,values:[...N.values,R]}:N)}),m(N=>({...N,[v]:""}))},[u,d,s,t]),w=y.useCallback((v,b)=>{t({variationTypes:u.map(k=>k.id===v?{...k,values:k.values.filter(R=>R.id!==b)}:k)})},[u,t]),j=y.useCallback((v,b,k)=>{t({variationTypes:u.map(R=>R.id===v?{...R,values:R.values.map(N=>N.id===b?{...N,label:k}:N)}:R)})},[u,t]);return n.jsxs("div",{className:"cedros-admin__variation-editor",children:[n.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[u.length,"/",r," types"]})]}),u.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):n.jsx("div",{className:"cedros-admin__variation-type-list",children:u.map((v,b)=>n.jsxs("div",{className:"cedros-admin__variation-type-item",children:[n.jsxs("div",{className:"cedros-admin__variation-type-header",children:[n.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(v.id,"up"),disabled:o||b===0,title:"Move up",children:Q.arrowUp}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(v.id,"down"),disabled:o||b===u.length-1,title:"Move down",children:Q.arrowDown})]}),n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:v.name,onChange:k=>_(v.id,k.target.value),disabled:o,placeholder:"Type name"}),n.jsxs("span",{className:"cedros-admin__variation-value-count",children:[v.values.length," values"]}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===v.id?null:v.id),children:a===v.id?"Collapse":"Edit values"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>h(v.id),disabled:o,title:"Remove type",children:Q.delete})]}),a===v.id&&n.jsxs("div",{className:"cedros-admin__variation-values",children:[n.jsxs("div",{className:"cedros-admin__variation-values-header",children:[n.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',v.name,'"']}),n.jsxs("span",{style:{fontSize:11,opacity:.7},children:[v.values.length,"/",s]})]}),v.values.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):n.jsx("div",{className:"cedros-admin__variation-value-list",children:v.values.map(k=>n.jsxs("div",{className:"cedros-admin__variation-value-item",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:k.label,onChange:R=>j(v.id,k.id,R.target.value),disabled:o}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>w(v.id,k.id),disabled:o,title:"Remove value",children:Q.close})]},k.id))}),v.values.length<s&&n.jsxs("div",{className:"cedros-admin__variation-add-value",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:d[v.id]||"",onChange:k=>m(R=>({...R,[v.id]:k.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),f(v.id))}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>f(v.id),disabled:o||!d[v.id]?.trim(),children:"Add"})]})]})]},v.id))}),u.length<r&&n.jsxs("div",{className:"cedros-admin__variation-add-type",children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:v=>l(v.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:v=>{v.key==="Enter"&&(v.preventDefault(),p())}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:p,disabled:o||!c.trim(),children:"Add Type"})]})]})}function Dl({value:e,onChange:t,options:r,placeholder:s="Filter",disabled:o}){const[a,i]=y.useState(!1),c=y.useRef(null),d=r.find(m=>m.value===e)?.label||s;return y.useEffect(()=>{const m=u=>{c.current&&!c.current.contains(u.target)&&i(!1)};if(a)return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[a]),y.useEffect(()=>{const m=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[a]),n.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[n.jsx("span",{children:d}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:Q.chevronDown})]}),a&&n.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:r.map(m=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${m.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{m.disabled||(t(m.value),i(!1))},role:"option","aria-selected":m.value===e,disabled:m.disabled,children:[m.label,m.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:Q.check})]},m.value))})]})}function ot({value:e,onChange:t,options:r,label:s,description:o,disabled:a,className:i,style:c}){const[l,d]=y.useState(!1),m=y.useRef(null),p=r.find(h=>h.value===e)?.label||"Select...";return y.useEffect(()=>{const h=_=>{m.current&&!m.current.contains(_.target)&&d(!1)};if(l)return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[l]),y.useEffect(()=>{const h=_=>{_.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[l]),n.jsxs("div",{className:`cedros-admin__field ${i||""}`,style:c,children:[n.jsx("label",{className:"cedros-admin__field-label",children:s}),n.jsxs("div",{className:"cedros-admin__dropdown cedros-admin__dropdown--form",ref:m,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger cedros-admin__dropdown-trigger--form",onClick:()=>!a&&d(!l),"aria-expanded":l,"aria-haspopup":"listbox",disabled:a,children:[n.jsx("span",{children:p}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${l?"cedros-admin__dropdown-chevron--open":""}`,children:Q.chevronDown})]}),l&&n.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:r.map(h=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${h.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{h.disabled||(t(h.value),d(!1))},role:"option","aria-selected":h.value===e,disabled:h.disabled,children:[h.label,h.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:Q.check})]},h.value))})]}),o&&n.jsx("p",{className:"cedros-admin__field-description",children:o})]})}function Yi(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Bf(e){if(e.length===0)return[];const t=[...e].sort((s,o)=>s.displayOrder-o.displayOrder),r=(s,o)=>{if(s>=t.length){const c=o.valueIds.sort().join("|"),l=Object.values(o.options).join(" / ");return[{key:c,title:l,optionValueIds:[...o.valueIds],options:{...o.options}}]}const a=t[s],i=[];for(const c of a.values)i.push(...r(s+1,{valueIds:[...o.valueIds,c.id],options:{...o.options,[a.name]:c.label}}));return i};return r(0,{valueIds:[],options:{}})}function Uf(e){return e.optionValueIds?.length?[...e.optionValueIds].sort().join("|"):Object.entries(e.options).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${t}:${r}`).join("|")}function Wf({variationConfig:e,variants:t,onChange:r,defaultPrice:s=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=y.useMemo(()=>Bf(e.variationTypes),[e.variationTypes]),l=y.useMemo(()=>{const g=new Map;for(const f of t)g.set(Uf(f),f);return g},[t]),{existingRows:d,possibleRows:m}=y.useMemo(()=>{const g=[],f=[];for(const w of c){const j=l.get(w.key);j?g.push({combo:w,variant:j}):f.push(w)}return{existingRows:g,possibleRows:f}},[c,l]),u=y.useCallback((g,f)=>{r(t.map(w=>w.id===g?{...w,...f}:w))},[t,r]),p=y.useCallback(g=>{r(t.filter(f=>f.id!==g))},[t,r]),h=y.useCallback(g=>{if(t.length>=a)return;const f={id:Yi(),title:g.title,options:g.options,optionValueIds:g.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};r([...t,f])},[t,r,a,s]),_=y.useCallback(()=>{const g=a-t.length,w=m.slice(0,g).map(j=>({id:Yi(),title:j.title,options:j.options,optionValueIds:j.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));r([...t,...w])},[t,r,m,a,s]);return e.variationTypes.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):c.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):n.jsxs("div",{className:"cedros-admin__variant-grid",children:[n.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[t.length,"/",a," variants (",c.length," ","possible)"]})]}),m.length>0&&t.length<a&&n.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[n.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:_,disabled:i,children:["Generate All (",Math.min(m.length,a-t.length),")"]}),n.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{children:"Variant"}),n.jsx("th",{style:{width:100},children:"Price"}),n.jsx("th",{style:{width:80},children:"Qty"}),n.jsx("th",{style:{width:100},children:"SKU"}),n.jsx("th",{style:{width:100},children:"Status"}),n.jsx("th",{style:{width:80},children:"Actions"})]})}),n.jsxs("tbody",{children:[d.map(({combo:g,variant:f})=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:g.title}),n.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(g.options).map(([w,j])=>`${w}: ${j}`).join(", ")})]})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx("span",{children:o}),n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:f.price??"",onChange:w=>u(f.id,{price:w.target.value===""?void 0:parseFloat(w.target.value)||0}),disabled:i,min:"0",step:"0.01",style:{width:70}})]})}),n.jsx("td",{children:n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:f.inventoryQuantity??"",onChange:w=>u(f.id,{inventoryQuantity:w.target.value===""?void 0:parseInt(w.target.value)||0}),disabled:i,min:"0",style:{width:60}})}),n.jsx("td",{children:n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:f.sku??"",onChange:w=>u(f.id,{sku:w.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),n.jsx("td",{children:n.jsx(Dl,{value:f.inventoryStatus??"in_stock",onChange:w=>u(f.id,{inventoryStatus:w}),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],disabled:i})}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>p(f.id),disabled:i,title:"Remove variant",children:Q.trash})})]},f.id)),m.length>0&&t.length<a&&n.jsxs(n.Fragment,{children:[n.jsx("tr",{className:"cedros-admin__variant-separator",children:n.jsx("td",{colSpan:6,children:n.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",m.length,")"]})})}),m.slice(0,10).map(g=>n.jsxs("tr",{className:"cedros-admin__variant-possible",children:[n.jsx("td",{children:n.jsx("span",{style:{opacity:.6},children:g.title})}),n.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>h(g),disabled:i,title:"Create variant",children:Q.plus})})]},g.key)),m.length>10&&n.jsx("tr",{className:"cedros-admin__variant-more",children:n.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",m.length-10," more combinations"]})})]})]})]})})]})}function Vf({serverUrl:e,productId:t,productTitle:r,defaultPrice:s=0,currencySymbol:o="$",apiKey:a,authManager:i,onClose:c}){const{data:l,isLoading:d,error:m,fetch:u,save:p,isSaving:h}=zf({serverUrl:e,productId:t,apiKey:a,authManager:i}),[_,g]=y.useState({variationTypes:[]}),[f,w]=y.useState([]),[j,v]=y.useState(!1),[b,k]=y.useState(!1);y.useEffect(()=>{u()},[u]),y.useEffect(()=>{l&&(g(l.variationConfig),w(l.variants),v(!1))},[l]);const R=y.useCallback(T=>{g(T),v(!0),k(!1)},[]),N=y.useCallback(T=>{w(T),v(!0),k(!1)},[]),C=y.useCallback(async()=>{const T=new Set((l?.variants??[]).map(I=>I.id)),O=f.filter(I=>!T.has(I.id)),$=f.filter(I=>T.has(I.id)),S=(l?.variants??[]).filter(I=>!f.some(B=>B.id===I.id)).map(I=>I.id);await p({variationConfig:_,createVariants:O.map(I=>({optionValueIds:I.optionValueIds??[],inventoryQuantity:I.inventoryQuantity,sku:I.sku,price:I.price})),updateVariants:$.map(I=>({id:I.id,inventoryQuantity:I.inventoryQuantity,sku:I.sku,price:I.price,inventoryStatus:I.inventoryStatus})),deleteVariantIds:S.length>0?S:void 0})&&(v(!1),k(!0),setTimeout(()=>k(!1),3e3))},[_,f,l?.variants,p]);return d?n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading variations..."]})]}):n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),n.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[b&&n.jsxs("span",{className:"cedros-admin__success-text",children:[Q.check," Saved"]}),j&&n.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:C,disabled:h||!j,children:h?"Saving...":"Save Changes"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Q.close})]})]}),m&&n.jsx("div",{className:"cedros-admin__error-banner",children:m}),n.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(Ff,{value:_,onChange:R,disabled:h})}),_.variationTypes.length>0&&n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(Wf,{variationConfig:_,variants:f,onChange:N,defaultPrice:s,currencySymbol:o,disabled:h})})]})]})}function Ll({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(!1),[p,h]=y.useState(null),[_,g]=y.useState(null),[f,w]=y.useState(null),[j,v]=y.useState(null),[b,k]=y.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:""}),R=E=>{const P=E.tagsCsv.split(",").map(V=>V.trim()).filter(Boolean),z=E.categoryIdsCsv.split(",").map(V=>V.trim()).filter(Boolean),Z={email:E.checkoutEmail,name:E.checkoutName,phone:E.checkoutPhone,shippingAddress:E.checkoutShippingAddress,billingAddress:E.checkoutBillingAddress},K=E.fulfillmentType==="shipping"?"physical":"digital",L={title:E.title,slug:E.slug||E.id,shipping_profile:K,inventory_status:E.inventoryStatus,checkout_requirements:JSON.stringify(Z),fulfillment_type:E.fulfillmentType};E.imageUrl&&(L.image_url=E.imageUrl);const W=E.compareAtUsd?Math.round(Number(E.compareAtUsd)*100):0;W&&(L.compare_at_amount_cents=String(W)),P.length&&(L.tags=JSON.stringify(P)),z.length&&(L.category_ids=JSON.stringify(z)),E.fulfillmentNotes&&(L.fulfillment_notes=E.fulfillmentNotes);const Y=E.shippingCountriesCsv.split(",").map(V=>V.trim().toUpperCase()).filter(Boolean);return Y.length&&(L.shippingCountries=Y.join(","),L.shipping_countries=Y.join(",")),L},N=E=>E.metadata?.title||E.description||E.id,C=E=>E.metadata?.image_url,T=y.useCallback(async()=>{try{v(null);let E;if(s?.isAuthenticated())E=await s.fetchWithAuth(`/admin/products?limit=${r}`);else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const z=await fetch(`${e}/admin/products?limit=${r}`,{headers:P});if(!z.ok)throw new Error(`Failed to fetch products: ${z.status}`);E=await z.json()}a(E.products||[])}catch{a([]),v("Failed to load products")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{T()},[T]);const O=async E=>{if(E.preventDefault(),!(!b.id||!b.description)){if(h(null),b.fulfillmentType==="shipping"&&b.checkoutShippingAddress&&!b.shippingCountriesCsv.split(",").map(z=>z.trim()).filter(Boolean).length){h("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:P}=b,z=b.inventoryQuantity===""?void 0:Number.isFinite(Number(b.inventoryQuantity))?Number(b.inventoryQuantity):void 0,Z=Number(b.priceUsd)||0,K=Math.round(Z*100),L=Math.round(Z*1e6),W={id:b.id,description:b.description,fiatAmountCents:K,fiatCurrency:b.fiatCurrency,cryptoAtomicAmount:L,cryptoToken:b.cryptoToken,...z!==void 0?{inventoryQuantity:z}:{},metadata:{...P?{product_type:P}:{},...R(b)}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(W)});else{const Y={"Content-Type":"application/json"};t&&(Y["X-API-Key"]=t);const V=await fetch(`${e}/admin/products`,{method:"POST",headers:Y,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to create product: ${V.status}`)}k({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),T()}catch(P){h(P instanceof Error?P.message:"Failed to create product")}finally{u(!1)}}},$=E=>`$${(E/100).toFixed(2)}`,S=E=>{switch(E){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},A=y.useMemo(()=>{const E=o.filter(z=>z.active).length,P=o.reduce((z,Z)=>{const K=Z.variations?.length??0;return z+(K>0?K:1)},0);return{activeCount:E,totalSkus:P}},[o]),I=E=>{w(P=>!P||P.key!==E?{key:E,direction:"asc"}:{key:E,direction:P.direction==="asc"?"desc":"asc"})},B=E=>!f||f.key!==E?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:f.direction==="asc"?Q.chevronUp:Q.chevronDown}),D=y.useMemo(()=>{if(!f)return o;const E=f.direction==="asc"?1:-1,P=z=>{switch(f.key){case"product":return N(z);case"type":return S(z.metadata?.product_type);case"price":return z.fiatAmountCents??0;case"status":return z.active?1:0;case"id":default:return z.id}};return[...o].sort((z,Z)=>{const K=P(z),L=P(Z);return typeof K=="number"&&typeof L=="number"?(K-L)*E:String(K).localeCompare(String(L),void 0,{sensitivity:"base"})*E})},[o,f]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:j,onRetry:T}),n.jsx(rr,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:A.activeCount,variant:A.activeCount>0?"success":"muted"},{label:"Total SKUs",value:A.totalSkus}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{h(null),d(!l)},children:[l?Q.close:Q.plus,l?"Cancel":"Add Product"]})]}),l&&n.jsxs("form",{onSubmit:O,className:"cedros-admin__add-form",children:[p&&n.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:p}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.id,onChange:E=>k(P=>({...P,id:E.target.value})),placeholder:"e.g., premium-article",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.title,onChange:E=>k(P=>({...P,title:E.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.slug,onChange:E=>k(P=>({...P,slug:E.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:b.imageUrl,onChange:E=>k(P=>({...P,imageUrl:E.target.value})),placeholder:"https://..."})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.description,onChange:E=>k(P=>({...P,description:E.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:b.productType,onChange:E=>k(P=>({...P,productType:E})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"}],label:"Product Type"}),n.jsx(ot,{value:b.fulfillmentType,onChange:E=>{const P=E;k(z=>({...z,fulfillmentType:P,checkoutShippingAddress:P==="shipping"?z.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),b.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:b.inventoryStatus,onChange:E=>k(P=>({...P,inventoryStatus:E})),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],label:"Inventory status"}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:b.inventoryQuantity,onChange:E=>k(P=>({...P,inventoryQuantity:E.target.value===""?"":parseInt(E.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:b.compareAtUsd===""?"":b.compareAtUsd,onChange:E=>k(P=>({...P,compareAtUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:b.priceUsd===""?"":b.priceUsd,onChange:E=>k(P=>({...P,priceUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.tagsCsv,onChange:E=>k(P=>({...P,tagsCsv:E.target.value})),placeholder:"e.g., core, new, gift"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.categoryIdsCsv,onChange:E=>k(P=>({...P,categoryIdsCsv:E.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:b.checkoutEmail,onChange:E=>k(P=>({...P,checkoutEmail:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),n.jsx(ot,{value:b.checkoutName,onChange:E=>k(P=>({...P,checkoutName:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),n.jsx(ot,{value:b.checkoutPhone,onChange:E=>k(P=>({...P,checkoutPhone:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[b.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:b.checkoutShippingAddress,onChange:E=>k(P=>({...P,checkoutShippingAddress:E.target.checked}))}),"Collect shipping address"]})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:b.checkoutBillingAddress,onChange:E=>k(P=>({...P,checkoutBillingAddress:E.target.checked}))}),"Collect billing address"]})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.fulfillmentNotes,onChange:E=>k(P=>({...P,fulfillmentNotes:E.target.value})),placeholder:b.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),b.fulfillmentType==="shipping"&&b.checkoutShippingAddress&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:b.shippingCountriesCsv,onChange:E=>k(P=>({...P,shippingCountriesCsv:E.target.value})),placeholder:"e.g., US,CA"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Product"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading products..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("id"),children:["ID",B("id")]})}),n.jsx("th",{"aria-sort":f?.key==="product"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("product"),children:["Product",B("product")]})}),n.jsx("th",{"aria-sort":f?.key==="type"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("type"),children:["Type",B("type")]})}),n.jsx("th",{"aria-sort":f?.key==="price"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("price"),children:["Price",B("price")]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("status"),children:["Status",B("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:D.map(E=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:E.id})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[C(E)?n.jsx("img",{src:C(E),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):n.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:N(E)}),n.jsx("span",{style:{opacity:.8},children:E.description})]})]})}),n.jsx("td",{children:S(E.metadata?.product_type)}),n.jsx("td",{children:$(E.fiatAmountCents)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${E.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:E.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>g(E),children:"Variations"})]})})]},E.id))})]})}),_&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>g(null),children:n.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:E=>E.stopPropagation(),children:n.jsx(Vf,{serverUrl:e,productId:_.id,productTitle:N(_),defaultPrice:_.fiatAmountCents/100,apiKey:t,authManager:s,onClose:()=>g(null)})})})]})}function $l({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(null),[l,d]=y.useState(!0),[m,u]=y.useState(!0),[p,h]=y.useState(null),[_,g]=y.useState(""),[f,w]=y.useState(null),j=y.useCallback(async()=>{u(!0);try{h(null);let C;if(s?.isAuthenticated())C=await s.fetchWithAuth("/admin/stats");else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const O=await fetch(`${e}/admin/stats`,{headers:T});if(!O.ok)throw new Error(`Failed to fetch stats: ${O.status}`);C=await O.json()}c(C)}catch{c(null),h("Failed to load payment stats")}finally{u(!1)}},[e,t,s]);y.useEffect(()=>{j()},[j]);const v=y.useCallback(async()=>{try{h(null);let C;const T=new URLSearchParams({limit:r.toString()});_&&T.set("method",_);const O=`/admin/transactions?${T}`;if(s?.isAuthenticated())C=await s.fetchWithAuth(O);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const S=await fetch(`${e}${O}`,{headers:$});if(!S.ok)throw new Error(`Failed to fetch transactions: ${S.status}`);C=await S.json()}a(C.transactions||[])}catch{a([]),h("Failed to load transactions")}finally{d(!1)}},[e,t,r,_,s]);y.useEffect(()=>{v()},[v]);const b=C=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(C),k=C=>{w(T=>!T||T.key!==C?{key:C,direction:"asc"}:{key:C,direction:T.direction==="asc"?"desc":"asc"})},R=C=>!f||f.key!==C?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:f.direction==="asc"?Q.chevronUp:Q.chevronDown}),N=y.useMemo(()=>{if(!f)return o;const C=f.direction==="asc"?1:-1,T=O=>{switch(f.key){case"resource":return O.resourceId;case"method":return O.method;case"amount":return O.amount;case"status":return O.status;case"date":return new Date(O.paidAt).getTime();case"id":default:return O.id}};return[...o].sort((O,$)=>{const S=T(O),A=T($);return typeof S=="number"&&typeof A=="number"?(S-A)*C:String(S).localeCompare(String(A),void 0,{sensitivity:"base"})*C})},[o,f]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:p,onRetry:()=>{j(),v()}}),n.jsx(rr,{stats:[{label:"Revenue",value:b(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:b(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:b(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:b(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:m,onRefresh:j}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),n.jsx(Dl,{value:_,onChange:g,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading transactions..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("id"),children:["ID",R("id")]})}),n.jsx("th",{"aria-sort":f?.key==="resource"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("resource"),children:["Resource",R("resource")]})}),n.jsx("th",{"aria-sort":f?.key==="method"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("method"),children:["Method",R("method")]})}),n.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("amount"),children:["Amount",R("amount")]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("status"),children:["Status",R("status")]})}),n.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("date"),children:["Date",R("date")]})})]})}),n.jsx("tbody",{children:N.map(C=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:C.id})}),n.jsx("td",{children:C.resourceId}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.method}`,children:C.method})}),n.jsxs("td",{children:["$",C.amount.toFixed(2)," ",C.currency.toUpperCase()]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.status}`,children:C.status})}),n.jsx("td",{children:kr(C.paidAt)})]},C.id))})]})})]})}function zl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(!1),[p,h]=y.useState(null),[_,g]=y.useState(null),[f,w]=y.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}),j=y.useCallback(async()=>{try{g(null);let T;const O=`/admin/coupons?limit=${r}`;if(s?.isAuthenticated())T=await s.fetchWithAuth(O);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const S=await fetch(`${e}${O}`,{headers:$});if(!S.ok)throw new Error(`Failed to fetch coupons: ${S.status}`);T=await S.json()}a(T.coupons||[])}catch(T){J.getLogger().error("[CouponsSection] Failed to fetch coupons:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),g("Failed to load coupons")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{j()},[j]);const v=async T=>{if(T.preventDefault(),!(!f.code||f.discountValue<=0)){u(!0);try{const O=f.minimumAmountUsd?Math.round(Number(f.minimumAmountUsd)*100):void 0,$=f.productIdsCsv.split(",").map(I=>I.trim()).filter(Boolean),S=f.categoryIdsCsv.split(",").map(I=>I.trim()).filter(Boolean),A={code:f.code,discountType:f.discountType,discountValue:f.discountValue,usageLimit:f.usageLimit,active:!0,usageCount:0,scope:f.scope,...$.length?{productIds:$}:{},...S.length?{categoryIds:S}:{},...f.paymentMethod!=="any"?{paymentMethod:f.paymentMethod}:{},...f.autoApply?{autoApply:!0}:{},...f.appliesAt!=="both"?{appliesAt:f.appliesAt}:{},...f.startsAt?{startsAt:f.startsAt}:{},...f.expiresAt?{expiresAt:f.expiresAt}:{},...O?{minimumAmountCents:O}:{},...f.usageLimitPerCustomer?{usageLimitPerCustomer:f.usageLimitPerCustomer}:{},...f.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(A)});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/coupons`,{method:"POST",headers:I,body:JSON.stringify(A)});if(!B.ok)throw new Error(`Failed to create coupon: ${B.status}`)}w({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),j()}catch(O){J.getLogger().error("[CouponsSection] Failed to add coupon:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),g("Failed to create coupon")}finally{u(!1)}}},b=o.filter(T=>T.active).length,k=o.reduce((T,O)=>T+(O.usageCount??0),0),R=T=>{h(O=>!O||O.key!==T?{key:T,direction:"asc"}:{key:T,direction:O.direction==="asc"?"desc":"asc"})},N=T=>!p||p.key!==T?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:p.direction==="asc"?Q.chevronUp:Q.chevronDown}),C=y.useMemo(()=>{if(!p)return o;const T=p.direction==="asc"?1:-1,O=$=>{switch(p.key){case"discount":return $.discountValue??0;case"usage":return $.usageCount??0;case"status":return $.active?1:0;case"code":default:return $.code}};return[...o].sort(($,S)=>{const A=O($),I=O(S);return typeof A=="number"&&typeof I=="number"?(A-I)*T:String(A).localeCompare(String(I),void 0,{sensitivity:"base"})*T})},[o,p]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:_,onRetry:j}),n.jsx(rr,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:b,variant:b>0?"success":"muted"},{label:"Redemptions",value:k}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?Q.close:Q.plus,l?"Cancel":"Add Coupon"]})]}),l&&n.jsxs("form",{onSubmit:v,className:"cedros-admin__add-form",children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.code,onChange:T=>w(O=>({...O,code:T.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),n.jsx(ot,{value:f.discountType,onChange:T=>w(O=>({...O,discountType:T})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",f.discountType==="percentage"?"(%)":"($)"]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.discountValue||"",onChange:T=>w(O=>({...O,discountValue:parseFloat(T.target.value)||0})),placeholder:f.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:f.discountType==="percentage"?"1":"0.01",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.usageLimit||"",onChange:T=>w(O=>({...O,usageLimit:T.target.value?parseInt(T.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:f.expiresAt,onChange:T=>w(O=>({...O,expiresAt:T.target.value}))})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:f.scope,onChange:T=>w(O=>({...O,scope:T})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),n.jsx(ot,{value:f.paymentMethod,onChange:T=>w(O=>({...O,paymentMethod:T})),options:[{value:"any",label:"Any Payment Method"},{value:"stripe",label:"Stripe (Card) Only"},{value:"x402",label:"Crypto (x402) Only"},{value:"credits",label:"Credits Only"}],label:"Payment Method"}),n.jsx(ot,{value:f.appliesAt,onChange:T=>w(O=>({...O,appliesAt:T})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),f.scope==="specific_products"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.productIdsCsv,onChange:T=>w(O=>({...O,productIdsCsv:T.target.value})),placeholder:"e.g., prod_123, prod_456"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:f.startsAt,onChange:T=>w(O=>({...O,startsAt:T.target.value}))})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:f.autoApply,onChange:T=>w(O=>({...O,autoApply:T.target.checked}))}),"Automatically apply when conditions met"]})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.minimumAmountUsd===""?"":f.minimumAmountUsd,onChange:T=>w(O=>({...O,minimumAmountUsd:T.target.value===""?"":parseFloat(T.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.usageLimitPerCustomer||"",onChange:T=>w(O=>({...O,usageLimitPerCustomer:T.target.value?parseInt(T.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:f.firstPurchaseOnly,onChange:T=>w(O=>({...O,firstPurchaseOnly:T.target.checked}))}),"New customers only"]})]})]}),f.scope==="specific_categories"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.categoryIdsCsv,onChange:T=>w(O=>({...O,categoryIdsCsv:T.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Coupon"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading coupons..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":p?.key==="code"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("code"),children:["Code",N("code")]})}),n.jsx("th",{"aria-sort":p?.key==="discount"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("discount"),children:["Discount",N("discount")]})}),n.jsx("th",{"aria-sort":p?.key==="usage"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("usage"),children:["Usage",N("usage")]})}),n.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("status"),children:["Status",N("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:C.map(T=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:T.code})}),n.jsx("td",{children:T.discountType==="percentage"?`${T.discountValue}%`:`$${T.discountValue.toFixed(2)}`}),n.jsxs("td",{children:[T.usageCount,T.usageLimit?` / ${T.usageLimit}`:""]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${T.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:T.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},T.code))})]})})]})}function Fl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(null),[m,u]=y.useState([]),[p,h]=y.useState(!0),[_,g]=y.useState(null),[f,w]=y.useState(null),[j,v]=y.useState([]),[b,k]=y.useState(!0),[R,N]=y.useState(null),[C,T]=y.useState(null),[O,$]=y.useState(null),[S,A]=y.useState(""),[I,B]=y.useState(null),D=y.useCallback(async()=>{try{let U;const re=`/admin/refunds?limit=${r}`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{headers:de});if(!ke.ok)throw new Error(`Failed to fetch x402 refunds: ${ke.status}`);U=await ke.json()}a(U.refunds||[])}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),B("Failed to load x402 refunds")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{D()},[D]);const E=y.useCallback(async()=>{try{let U;const re=`/admin/credits/refund-requests?status=pending&limit=${r}&offset=0`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const ke={"Content-Type":"application/json"};t&&(ke["X-API-Key"]=t);const Se=await fetch(`${e}${re}`,{headers:ke});if(!Se.ok)throw new Error(`Failed to fetch credits refund requests: ${Se.status}`);U=await Se.json()}const de=Array.isArray(U)?U:"refundRequests"in U?U.refundRequests:U.requests||[];u(de)}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([]),B("Failed to load credits refunds")}finally{h(!1)}},[e,t,r,s]);y.useEffect(()=>{E()},[E]);const P=async U=>{g(U.id);try{const re=`/admin/credits/refund-requests/${U.id}/process`,de=JSON.stringify({amountLamports:U.amountLamports,reason:U.reason});if(s?.isAuthenticated())await s.fetchWithAuth(re,{method:"POST",body:de});else{const ke={"Content-Type":"application/json"};t&&(ke["X-API-Key"]=t);const Se=await fetch(`${e}${re}`,{method:"POST",headers:ke,body:de});if(!Se.ok)throw new Error(`Failed to process credits refund: ${Se.status}`)}await E()}catch(re){J.getLogger().error("[RefundsSection] Failed to process credits refund:",re,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:U.id}),B("Failed to process credits refund")}finally{g(null)}},z=U=>{A(U.reason??""),$(U)},Z=()=>{$(null),A("")},K=async()=>{if(!O)return;const U=O,re=S;Z(),g(U.id);try{const de=`/admin/credits/refund-requests/${U.id}/reject`,ke=JSON.stringify({reason:re});if(s?.isAuthenticated())await s.fetchWithAuth(de,{method:"POST",body:ke});else{const Se={"Content-Type":"application/json"};t&&(Se["X-API-Key"]=t);const Me=await fetch(`${e}${de}`,{method:"POST",headers:Se,body:ke});if(!Me.ok)throw new Error(`Failed to reject credits refund: ${Me.status}`)}await E()}catch(de){J.getLogger().error("[RefundsSection] Failed to reject credits refund:",de,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:U.id}),B("Failed to reject credits refund")}finally{g(null)}},L=y.useCallback(async()=>{try{let U;const re=`/admin/stripe/refunds?limit=${r}`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{headers:de});if(!ke.ok)throw new Error(`Failed to fetch Stripe refunds: ${ke.status}`);U=await ke.json()}v(U.refunds||[])}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),v([]),B("Failed to load Stripe refunds")}finally{k(!1)}},[e,t,r,s]);y.useEffect(()=>{L()},[L]);const W=async U=>{N(U);try{const re=`/admin/stripe/refunds/${U}/process`;if(s?.isAuthenticated())await s.fetchWithAuth(re,{method:"POST"});else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{method:"POST",headers:de});if(!ke.ok)throw new Error(`Failed to process refund: ${ke.status}`)}await L()}catch(re){J.getLogger().error("[RefundsSection] Failed to process Stripe refund:",re,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:U}),B("Failed to process Stripe refund")}finally{N(null)}},Y=(U,re)=>new Intl.NumberFormat("en-US",{style:"currency",currency:re}).format(U/100),V=U=>U?U.replace(/_/g," ").replace(/\b\w/g,re=>re.toUpperCase()):"—",ce=U=>{switch(U){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},F=(U,re)=>re?re.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(U/1e6)} (USD credits)`:`${U.toLocaleString()} ${re.toUpperCase()} (atomic)`:`${U.toLocaleString()} (atomic)`,ee=U=>{switch(U){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},pe=U=>U.stripeRefundId??"—",q=U=>U.chargeId??"—",ne=j.filter(U=>U.status==="pending"||U.status==="requires_action").length,le=m.filter(U=>U.status==="pending").length,fe=o.filter(U=>U.status==="pending").length,Pe=ne+le+fe,Ve=j.filter(U=>U.status==="succeeded").reduce((U,re)=>U+re.amount,0),qe=m.filter(U=>U.status==="processed").reduce((U,re)=>U+re.amountLamports,0),He=o.filter(U=>U.status==="completed").reduce((U,re)=>U+re.amount,0),xt=Ve/100+qe/1e6+He,Ge=U=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(U),zt=b||p||i,lt=U=>{T(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},te=U=>{w(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},xe=U=>{d(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},ge=(U,re)=>!U||!re?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:re==="asc"?Q.chevronUp:Q.chevronDown}),dt=y.useMemo(()=>{if(!C)return j;const U=C.direction==="asc"?1:-1,re=de=>{switch(C.key){case"stripe":return de.stripeRefundId??"";case"charge":return de.chargeId??"";case"amount":return de.amount??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...j].sort((de,ke)=>{const Se=re(de),Me=re(ke);return typeof Se=="number"&&typeof Me=="number"?(Se-Me)*U:String(Se).localeCompare(String(Me),void 0,{sensitivity:"base"})*U})},[j,C]),yt=y.useMemo(()=>{if(!f)return m;const U=f.direction==="asc"?1:-1,re=de=>{switch(f.key){case"original":return de.originalTransactionId??"";case"user":return de.userId??"";case"amount":return de.amountLamports??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...m].sort((de,ke)=>{const Se=re(de),Me=re(ke);return typeof Se=="number"&&typeof Me=="number"?(Se-Me)*U:String(Se).localeCompare(String(Me),void 0,{sensitivity:"base"})*U})},[m,f]),ut=y.useMemo(()=>{if(!l)return o;const U=l.direction==="asc"?1:-1,re=de=>{switch(l.key){case"transaction":return de.transactionId??"";case"amount":return de.amount??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...o].sort((de,ke)=>{const Se=re(de),Me=re(ke);return typeof Se=="number"&&typeof Me=="number"?(Se-Me)*U:String(Se).localeCompare(String(Me),void 0,{sensitivity:"base"})*U})},[o,l]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:I,onRetry:()=>{D(),E(),L()}}),n.jsx(rr,{stats:[{label:"Pending",value:Pe,variant:Pe>0?"warning":"muted"},{label:"Card Pending",value:ne,description:"Stripe"},{label:"Credits Pending",value:le},{label:"Crypto Pending",value:fe,description:"x402"},{label:"Total Refunded",value:Ge(xt),variant:"success"}],isLoading:zt}),n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),b?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading Stripe refunds..."]}):j.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":C?.key==="id"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("id"),children:["Request ID",ge(C?.key==="id",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="stripe"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("stripe"),children:["Stripe Refund ID",ge(C?.key==="stripe",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="charge"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("charge"),children:["Charge",ge(C?.key==="charge",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="amount"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("amount"),children:["Amount",ge(C?.key==="amount",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="reason"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("reason"),children:["Reason",ge(C?.key==="reason",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="status"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("status"),children:["Status",ge(C?.key==="status",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="date"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("date"),children:["Date",ge(C?.key==="date",C?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:dt.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:pe(U)})}),n.jsx("td",{children:n.jsx("code",{children:q(U)})}),n.jsx("td",{children:Y(U.amount,U.currency)}),n.jsx("td",{children:V(U.reason)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${ee(U.status)}`,children:U.status})}),n.jsx("td",{children:kr(U.createdAt)}),n.jsx("td",{children:(U.status==="pending"||U.status==="requires_action")&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>W(U.id),disabled:R===U.id,children:R===U.id?"Processing...":"Process"})})]},U.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),p?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading credits refunds..."]}):m.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("id"),children:["Request ID",ge(f?.key==="id",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="original"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("original"),children:["Original Tx",ge(f?.key==="original",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="user"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("user"),children:["User",ge(f?.key==="user",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("amount"),children:["Amount",ge(f?.key==="amount",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="reason"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("reason"),children:["Reason",ge(f?.key==="reason",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("status"),children:["Status",ge(f?.key==="status",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("date"),children:["Date",ge(f?.key==="date",f?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:yt.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:U.originalTransactionId})}),n.jsx("td",{children:n.jsx("code",{children:U.userId??"—"})}),n.jsx("td",{children:F(U.amountLamports,U.currency)}),n.jsx("td",{children:U.reason??"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${ce(U.status)}`,children:U.status})}),n.jsx("td",{children:kr(U.createdAt)}),n.jsx("td",{children:U.status==="pending"?n.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>P(U),disabled:_===U.id,children:_===U.id?"Processing...":"Process"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>z(U),disabled:_===U.id,children:"Reject"})]}):null})]},U.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading x402 refunds..."]}):o.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("id"),children:["ID",ge(l?.key==="id",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="transaction"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("transaction"),children:["Transaction",ge(l?.key==="transaction",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="amount"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("amount"),children:["Amount",ge(l?.key==="amount",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="reason"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("reason"),children:["Reason",ge(l?.key==="reason",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="status"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("status"),children:["Status",ge(l?.key==="status",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="date"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("date"),children:["Date",ge(l?.key==="date",l?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:ut.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:U.transactionId})}),n.jsxs("td",{children:["$",U.amount.toFixed(2)]}),n.jsx("td",{children:U.reason||"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${U.status}`,children:U.status})}),n.jsx("td",{children:kr(U.createdAt)}),n.jsx("td",{children:U.status==="pending"&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",children:"Process"})})]},U.id))})]})}),O&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:Z,children:n.jsxs("div",{className:"cedros-admin__modal",onClick:U=>U.stopPropagation(),children:[n.jsxs("div",{className:"cedros-admin__modal-header",children:[n.jsx("h3",{className:"cedros-admin__modal-title",children:"Reject Refund Request"}),n.jsx("button",{type:"button",className:"cedros-admin__modal-close",onClick:Z,"aria-label":"Close",children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__modal-body",children:[n.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",n.jsx("code",{children:O.id})," for ",F(O.amountLamports,O.currency),"."]}),n.jsxs("label",{className:"cedros-admin__form-field",children:[n.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),n.jsx("textarea",{className:"cedros-admin__input",value:S,onChange:U=>A(U.target.value),placeholder:"Enter rejection reason...",rows:3,style:{resize:"vertical"}})]})]}),n.jsxs("div",{className:"cedros-admin__modal-footer",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--outline",onClick:Z,children:"Cancel"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:K,children:"Reject Refund"})]})]})})]})}async function qf(e){const t=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=await e.sign(t);return{"X-Signer":e.signerPublicKey,"X-Message":t,"X-Signature":r,"Content-Type":"application/json"}}class Hf{constructor(t,r,s){this.serverUrl=t,this.auth=r,this.authManager=s}async fetch(t,r={}){if(this.authManager?.isAuthenticated())return this.authManager.fetchWithAuth(t,r);const s={"Content-Type":"application/json",...r.headers||{}};if(this.auth){const a=await qf(this.auth);Object.assign(s,a)}const o=await fetch(`${this.serverUrl}${t}`,{...r,headers:s});if(!o.ok){const a=await o.text();throw new Error(`API error ${o.status}: ${a}`)}return o.json()}async listCategories(t=100){return this.fetch(`/admin/config?limit=${t}`)}async getConfig(t,r=!0){return this.fetch(`/admin/config/${t}?redact_secrets=${r}`)}async updateConfig(t,r,s){await this.fetch(`/admin/config/${t}`,{method:"PUT",body:JSON.stringify({config:r,description:s})})}async patchConfig(t,r,s){await this.fetch(`/admin/config/${t}`,{method:"PATCH",body:JSON.stringify({updates:r,description:s})})}async batchUpdate(t){await this.fetch("/admin/config/batch",{method:"POST",body:JSON.stringify({updates:t})})}async validateConfig(t,r){return this.fetch("/admin/config/validate",{method:"POST",body:JSON.stringify({category:t,config:r})})}async getHistory(t,r=50){const s=new URLSearchParams({limit:r.toString()});return t&&s.set("category",t),this.fetch(`/admin/config/history?${s}`)}}const Ea={server:{label:"Server",secrets:[],icon:"🖥️",fields:{admin_metrics_api_key:{hidden:!0},cors_allowed_origins:{hidden:!0}}},security:{label:"Security",description:"Configure CORS, rate limiting, and other security settings",secrets:[],icon:"🔒",fields:{cors_allowed_origins:{description:'List of allowed origins for CORS requests. Use ["*"] to allow all origins (not recommended for production).'}}},metrics:{label:"Metrics",description:"Configure metrics collection and API access",secrets:["admin_metrics_api_key"],icon:"📊",fields:{admin_metrics_api_key:{description:"API key for accessing the admin metrics endpoint. Keep this secret."}}},logging:{label:"Logging",secrets:[],icon:"📝",fields:{level:{type:"dropdown",options:["trace","debug","info","warn","error"]},format:{hidden:!0},environment:{hidden:!0}}},stripe:{label:"Stripe",secrets:["secret_key","webhook_secret"],icon:"💳",fields:{enabled:{hidden:!0},mode:{type:"dropdown",options:["test","live"]},success_url:{hidden:!0},cancel_url:{hidden:!0}}},x402:{label:"X402 (Crypto)",secrets:["server_wallets"],icon:"⚡",fields:{enabled:{hidden:!0},payment_address:{type:"solana_address",description:"The Solana wallet address where payments are received. This is where customer funds are sent."},token_mint:{type:"token_mint",description:"The SPL token used for payments. Most commonly USDC."},token_decimals:{type:"number",description:"Number of decimal places for the token (e.g., USDC has 6 decimals).",hidden:!0},custom_token_symbol:{description:'Display symbol for your custom token (e.g., "MYTOKEN").',hidden:!0},custom_token_icon:{description:"URL to your token's icon image.",hidden:!0},rpc_url:{description:"Custom Solana RPC endpoint. Leave empty to use the default public RPC."},gasless_enabled:{type:"toggle",description:"When enabled, your server pays transaction fees so customers don't need SOL."},server_wallets:{type:"secret_array",description:"Server keypair(s) used to sign and pay for transactions. Required for gasless payments.",showWhen:"gasless_enabled"},rounding_mode:{type:"dropdown",options:["nearest","up","down"],description:"How to round fractional token amounts: nearest (default), up (always round up), or down (always round down)."},network:{hidden:!0},ws_url:{hidden:!0},skip_preflight:{hidden:!0},commitment:{hidden:!0},compute_unit_limit:{hidden:!0},compute_unit_price:{hidden:!0}}},paywall:{label:"Paywall",secrets:[],icon:"🚪",fields:{product_cache_ttl:{type:"number",unit:"seconds"}}},coupons:{label:"Coupons",secrets:[],icon:"🎟️",fields:{cache_ttl:{type:"number",unit:"seconds"}}},subscriptions:{label:"Subscriptions",secrets:[],icon:"🔄",fields:{grace_period_hours:{type:"number",unit:"hours"}}},callbacks:{label:"Callbacks",secrets:["hmac_secret"],icon:"🔔"},email:{label:"Email",description:"Email receipts for customers after purchase",secrets:["smtp_password"],icon:"📧",fields:{enabled:{hidden:!0},provider:{type:"dropdown",options:["sendgrid","mailgun","postmark","ses","resend","custom"],description:"Email service provider."},smtp_host:{description:"SMTP server hostname.",showWhen:"provider"},smtp_port:{type:"number",description:"SMTP server port (typically 587 for TLS).",showWhen:"provider"},smtp_user:{description:"SMTP authentication username or API key name.",showWhen:"provider"},smtp_password:{description:"SMTP password or API key.",showWhen:"provider"},from_address:{description:"Sender email address (e.g., orders@yourstore.com)."},from_name:{description:'Sender display name (e.g., "Your Store").'}}},webhook:{label:"Webhook",description:"HTTP notifications when purchases occur",secrets:["secret"],icon:"🔔",fields:{enabled:{hidden:!0},url:{description:"URL to receive POST notifications (e.g., https://api.yoursite.com/webhooks/orders)."},secret:{description:"Shared secret for HMAC-SHA256 signature verification."},retry_attempts:{type:"number",description:"Number of retry attempts on failure (default: 3)."}}},messaging:{label:"Messaging",description:"Email and webhook notifications for purchases",secrets:["smtp_password","webhook_secret"],icon:"📬",fields:{email_enabled:{type:"boolean",description:"Send order confirmation emails to customers."},smtp_host:{description:"SMTP server hostname.",showWhen:"email_enabled"},smtp_port:{type:"number",description:"SMTP server port (typically 587 for TLS).",showWhen:"email_enabled"},smtp_username:{description:"SMTP authentication username or API key.",showWhen:"email_enabled"},smtp_password:{description:"SMTP password or API key.",showWhen:"email_enabled"},from_email:{description:"Sender email address (e.g., orders@yourstore.com).",showWhen:"email_enabled"},from_name:{description:'Sender display name (e.g., "Your Store").',showWhen:"email_enabled"},webhook_enabled:{type:"boolean",description:"Send webhook notifications when purchases complete."},webhook_url:{description:"URL to receive POST notifications.",showWhen:"webhook_enabled"},webhook_secret:{description:"Shared secret for HMAC-SHA256 signature verification.",showWhen:"webhook_enabled"},webhook_timeout:{type:"number",description:"Request timeout in seconds (default: 30).",showWhen:"webhook_enabled"}}},monitoring:{label:"Monitoring",secrets:[],icon:"📊",fields:{check_interval:{type:"number",unit:"seconds"},low_balance_threshold:{type:"number",unit:"SOL"}}},rate_limit:{label:"Rate Limiting",secrets:[],icon:"⏱️"},circuit_breaker:{label:"Circuit Breaker",secrets:[],icon:"🔌"},admin:{label:"Admin Keys",secrets:[],icon:"👤"},api_keys:{label:"API Keys",secrets:[],icon:"🔐"},cedros_login:{label:"Cedros Login",secrets:["api_key"],icon:"🔑",fields:{enabled:{hidden:!0},credits_enabled:{hidden:!0},base_url:{hidden:!0},timeout:{hidden:!0},jwt_issuer:{hidden:!0},jwt_audience:{hidden:!0}}},shop:{label:"Storefront",description:"Product pages & display settings",secrets:[],icon:"🏪",fields:{enabled:{hidden:!0},"relatedProducts.mode":{type:"dropdown",options:["most_recent","by_category","manual","ai"]},"relatedProducts.maxItems":{type:"number"}}}};function Bl(e,t){return Ea[e]?.secrets.includes(t)??!1}const wr="[REDACTED]";function Ta({data:e,onSave:t,debounceMs:r=1500,savedDurationMs:s=2e3,enabled:o=!0,skipInitial:a=!0}){const[i,c]=y.useState("idle"),[l,d]=y.useState(null),m=y.useRef(!0),u=y.useRef(null),p=y.useRef(null),h=y.useRef(e);h.current=e;const _=y.useCallback(async()=>{c("saving"),d(null);try{await t(h.current),c("saved"),p.current=setTimeout(()=>{c("idle")},s)}catch(w){c("error"),d(w instanceof Error?w.message:"Save failed")}},[t,s]),g=y.useCallback(async()=>{u.current&&(clearTimeout(u.current),u.current=null),await _()},[_]),f=y.useCallback(()=>{c("idle"),d(null)},[]);return y.useEffect(()=>{if(o){if(a&&m.current){m.current=!1;return}return u.current&&clearTimeout(u.current),p.current&&clearTimeout(p.current),c("pending"),u.current=setTimeout(()=>{_()},r),()=>{u.current&&clearTimeout(u.current)}}},[e,o,a,r,_]),y.useEffect(()=>()=>{u.current&&clearTimeout(u.current),p.current&&clearTimeout(p.current)},[]),{status:i,error:l,saveNow:g,reset:f}}function Zf(e){if(!e||e.trim()==="")return{valid:!0};try{return new af.PublicKey(e.trim()),{valid:!0}}catch{return{valid:!1,error:"Invalid Solana address"}}}function Ki(e,t,r){const s=Bl(e,t),o=t.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase()),i=Ea[e]?.fields?.[t],c={isSecret:s,label:o,description:i?.description,hidden:i?.hidden,showWhen:i?.showWhen};return i?.type==="dropdown"&&i.options?{...c,type:"dropdown",options:i.options}:i?.type==="token_mint"?{...c,type:"token_mint"}:i?.type==="toggle"?{...c,type:"toggle"}:i?.type==="secret_array"?{...c,type:"secret_array",isSecret:!0}:i?.type==="solana_address"?{...c,type:"solana_address"}:i?.type==="number"?{...c,type:"number",unit:i.unit}:typeof r=="boolean"?{...c,type:"boolean"}:typeof r=="number"?{...c,type:"number",unit:i?.unit}:Array.isArray(r)?{...c,type:"array"}:typeof r=="object"&&r!==null?{...c,type:"object"}:{...c,type:"string"}}function Gf({category:e,config:t,originalConfig:r,isLoading:s=!1,onSave:o}){const[a,i]=y.useState(t),[c,l]=y.useState(new Set);y.useEffect(()=>{i(t)},[t]);const d=y.useMemo(()=>{const j={...a};for(const v of Object.keys(j))if(Bl(e,v)){const b=r[v],k=j[v];(k===wr||k===b)&&(j[v]=wr)}return j},[a,r,e]),{status:m,error:u}=Ta({data:d,onSave:o,debounceMs:1500}),p=y.useCallback((j,v)=>{i(b=>({...b,[j]:v}))},[]),h=y.useCallback(j=>{l(v=>{const b=new Set(v);return b.has(j)?b.delete(j):b.add(j),b})},[]),_=j=>j?n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:j}):null,g=(j,v)=>{const b=Ki(e,j,r[j]??v);if(b.type==="dropdown"&&b.options)return n.jsx(ot,{value:v,onChange:N=>p(j,N),options:b.options.map(N=>({value:N,label:N})),label:b.label,description:b.description,disabled:s});if(b.type==="token_mint")return n.jsx(Qf,{label:b.label,value:v,onChange:N=>p(j,N),decimals:a.token_decimals??6,onDecimalsChange:N=>p("token_decimals",N),disabled:s,description:b.description,customSymbol:a.custom_token_symbol||"",customIcon:a.custom_token_icon||"",onCustomSymbolChange:N=>p("custom_token_symbol",N),onCustomIconChange:N=>p("custom_token_icon",N)});if(b.type==="toggle")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("button",{type:"button",role:"switch","aria-checked":v,onClick:()=>p(j,!v),disabled:s,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:v?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:s?"not-allowed":"pointer",position:"relative",transition:"background-color 0.2s",opacity:s?.5:1,flexShrink:0},children:n.jsx("span",{style:{position:"absolute",top:2,left:v?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})}),n.jsx("span",{className:"cedros-admin__field-label",style:{marginBottom:0},children:b.label})]}),_(b.description)]});if(b.type==="solana_address"){const N=v||"",C=Zf(N);return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:b.label}),n.jsxs("div",{style:{position:"relative"},children:[n.jsx("input",{type:"text",className:`cedros-admin__input ${C.valid?"":"cedros-admin__input--error"}`,value:N,onChange:T=>p(j,T.target.value),disabled:s,placeholder:"e.g. 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",style:{width:"100%",fontFamily:"monospace",fontSize:"0.875rem",borderColor:C.valid?void 0:"var(--cedros-admin-error, #dc2626)",paddingRight:N&&C.valid?"2rem":void 0}}),N&&C.valid&&n.jsx("span",{style:{position:"absolute",right:10,top:"50%",transform:"translateY(-50%)",color:"var(--cedros-admin-success, #16a34a)",fontSize:"1rem"},title:"Valid Solana address",children:"✓"})]}),!C.valid&&n.jsx("span",{style:{color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.75rem",marginTop:"0.25rem",display:"block"},children:C.error}),_(b.description)]})}if(b.type==="boolean")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__checkbox",children:[n.jsx("input",{type:"checkbox",checked:v,onChange:N=>p(j,N.target.checked),disabled:s}),b.label]}),_(b.description)]});if(b.type==="number")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[b.label,b.unit&&n.jsxs("span",{className:"cedros-admin__field-unit",children:[" (",b.unit,")"]})]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v,onChange:N=>p(j,parseFloat(N.target.value)||0),disabled:s}),_(b.description)]});if(b.type==="secret_array")return n.jsx(Yf,{label:b.label,value:v,onChange:N=>p(j,N),disabled:s,description:b.description});if(b.type==="array"){const N=v;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:b.label}),n.jsx("textarea",{className:"cedros-admin__textarea",value:N.join(`
|
|
2
2
|
`),onChange:C=>p(j,C.target.value.split(`
|
|
3
|
-
`).filter(Boolean)),placeholder:"One item per line",rows:3,disabled:s}),_(v.description)]})}if(v.type==="object")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:v.label}),n.jsx("textarea",{className:"cedros-admin__textarea cedros-admin__textarea--mono",value:JSON.stringify(b,null,2),onChange:N=>{try{p(j,JSON.parse(N.target.value))}catch{}},rows:5,disabled:s}),_(v.description)]});const k=c.has(j),R=v.isSecret&&!k&&b===wr?wr:b;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[v.label,v.isSecret&&n.jsx("span",{className:"cedros-admin__field-secret",children:" (secret)"})]}),n.jsxs("div",{className:"cedros-admin__input-group",children:[n.jsx("input",{type:v.isSecret&&!k?"password":"text",className:"cedros-admin__input",value:R,onChange:N=>p(j,N.target.value),disabled:s,placeholder:v.isSecret?"••••••••":""}),v.isSecret&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>h(j),style:{padding:"0.5rem",minWidth:"auto"},title:k?"Hide":"Show",children:k?Q.eyeOff:Q.eye})]}),_(v.description)]})},f=Object.keys(a),w=j=>{const b=Ki(e,j,r[j]??a[j]);if(b.hidden||b.showWhen&&!a[b.showWhen])return!1;if(j==="token_decimals"){const v=a.token_mint;if(v&&J.STABLECOIN_METADATA[v])return!1}return!0};return n.jsxs("div",{className:"cedros-admin__config-editor",children:[n.jsx("div",{className:"cedros-admin__config-fields",children:f.filter(w).map(j=>n.jsx("div",{className:"cedros-admin__config-field",children:g(j,a[j])},j))}),n.jsx("div",{className:"cedros-admin__config-actions",children:n.jsx("div",{className:"cedros-admin__autosave-status",children:n.jsx(Kf,{status:m,error:u})})})]})}function Qf({label:e,value:t,onChange:r,decimals:s,onDecimalsChange:o,disabled:a=!1,description:i,customSymbol:c="",customIcon:l="",onCustomSymbolChange:d,onCustomIconChange:m}){const[u,p]=y.useState(!1),h=Object.entries(J.STABLECOIN_METADATA),g=!!J.STABLECOIN_METADATA[t],w=u||!!t&&!g,j=b=>{if(b==="custom")p(!0),g&&r("");else{p(!1),r(b);const v=J.STABLECOIN_METADATA[b];v&&o&&o(v.decimals),d&&d(""),m&&m("")}};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:e}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem"},children:[h.map(([b,v])=>n.jsxs("button",{type:"button",onClick:()=>j(b),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:t===b?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:t===b?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:t===b?600:400},children:[n.jsx("img",{src:v.icon,alt:v.symbol,style:{width:20,height:20,borderRadius:"50%"},onError:k=>{k.target.style.display="none"}}),n.jsx("span",{children:v.symbol})]},b)),n.jsxs("button",{type:"button",onClick:()=>j("custom"),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:w?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:w?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:w?600:400},children:[n.jsx("span",{style:{fontSize:"1rem"},children:"+"}),n.jsx("span",{children:"Custom"})]})]}),w&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"1rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:[n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Mint Address"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:t,onChange:b=>r(b.target.value),placeholder:"e.g., EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",disabled:a,style:{fontFamily:"monospace",fontSize:"0.875rem"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Symbol"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:b=>d?.(b.target.value),placeholder:"e.g., MYTOKEN",disabled:a,style:{textTransform:"uppercase"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Icon URL"}),n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:l,onChange:b=>m?.(b.target.value),placeholder:"https://example.com/token-logo.png",disabled:a,style:{flex:1}}),l&&n.jsx("img",{src:l,alt:"Token icon preview",style:{width:32,height:32,borderRadius:"50%",border:"1px solid var(--cedros-admin-border, #e5e7eb)",objectFit:"cover"},onError:b=>{b.target.style.display="none"}})]}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Shown to customers during checkout"})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Decimals"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:s??6,onChange:b=>o?.(parseInt(b.target.value,10)||0),min:0,max:18,disabled:a,style:{width:"100px"}}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Most SPL tokens use 6 decimals (like USDC)"})]})]}),t&&g&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",fontFamily:"monospace",wordBreak:"break-all"},children:t}),i&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:i})]})]})}function Yf({label:e,value:t,onChange:r,disabled:s=!1,description:o}){const[a,i]=y.useState(new Set),[c,l]=y.useState(null),[d,m]=y.useState(""),u=Array.isArray(t)?t:[],p=b=>{i(v=>{const k=new Set(v);return k.has(b)?k.delete(b):k.add(b),k})},h=()=>{r([...u,""]),l(u.length),m("")},_=(b,v)=>{const k=[...u];k[b]=v,r(k)},g=b=>{const v=u.filter((k,R)=>R!==b);r(v),i(k=>{const R=new Set;return k.forEach(N=>{N<b?R.add(N):N>b&&R.add(N-1)}),R})},f=b=>{l(b),m(u[b]||"")},w=()=>{c!==null&&(_(c,d),l(null),m(""))},j=()=>{c!==null&&u[c]===""&&g(c),l(null),m("")};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",style:{marginBottom:0},children:e}),n.jsxs("button",{type:"button",onClick:h,disabled:s,style:{display:"flex",alignItems:"center",gap:"0.25rem",padding:"0.25rem 0.5rem",fontSize:"0.75rem",border:"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.375rem",background:"var(--cedros-admin-bg, #fff)",cursor:s?"not-allowed":"pointer",opacity:s?.5:1},children:[Q.plus,"Add"]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u.length===0&&n.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"0.875rem",border:"1px dashed var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem"},children:'No items. Click "Add" to create one.'}),u.map((b,v)=>{const k=a.has(v),R=c===v,N=b===wr;return n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.375rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:R?n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:d,onChange:C=>m(C.target.value),placeholder:"Enter wallet keypair...",autoFocus:!0,style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem"},onKeyDown:C=>{C.key==="Enter"&&w(),C.key==="Escape"&&j()}}),n.jsx("button",{type:"button",onClick:w,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-success, #22c55e)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Save",children:Q.check}),n.jsx("button",{type:"button",onClick:j,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-text-muted, #64748b)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Cancel",children:Q.close})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k&&!N?b:N?"[REDACTED]":"••••••••••••••••••••"}),n.jsx("button",{type:"button",onClick:()=>p(v),disabled:s||N,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s||N?"not-allowed":"pointer",opacity:s||N?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:k?"Hide":"Show",children:k?Q.eyeOff:Q.eye}),n.jsx("button",{type:"button",onClick:()=>f(v),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:"Edit",children:Q.settings}),n.jsx("button",{type:"button",onClick:()=>g(v),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-error, #ef4444)"},title:"Delete",children:Q.trash})]})},v)})]}),o&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.5rem"},children:o})]})}function Kf({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${e}`,style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx(n.Fragment,{children:n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"})}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx(n.Fragment,{children:n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})})]})}function Ul({serverUrl:e,apiKey:t,authManager:r,category:s,title:o,description:a,enabledField:i="enabled",showEnabledToggle:c=!1}){const l=y.useMemo(()=>new Hf(e,void 0,r),[e,r]),[d,m]=y.useState(null),[u,p]=y.useState([]),[h,_]=y.useState(!1),[g,f]=y.useState(!0),[w,j]=y.useState(null),[b,v]=y.useState(null),[k,R]=y.useState(!1),N=Ea[s]||{label:s,icon:"⚙️"},C=o||N.label,T=a||N.description,O=y.useCallback(async()=>{f(!0),j(null);try{const P=await l.getConfig(s,!0);m(P)}catch{m(null),j("Failed to load settings")}finally{f(!1)}},[l,s]);y.useEffect(()=>{O()},[O]);const $=y.useCallback(async()=>{try{const P=await l.getHistory(s,20);p(P.history)}catch{p([])}},[l,s]);y.useEffect(()=>{h&&$()},[h,$]);const S=y.useCallback(async P=>{await l.updateConfig(s,P,"Updated via admin dashboard"),await O()},[l,s,O]),A=y.useCallback(async P=>l.validateConfig(s,P),[l,s]),[I,B]=y.useState(!1),D=y.useCallback(async()=>{if(!d||I)return;const P=!!d.config[i],z=!P,Z={...d.config,[i]:z};B(!0),m({...d,config:Z});try{await l.updateConfig(s,Z,`${z?"Enabled":"Disabled"} via admin dashboard`)}catch(K){m({...d,config:{...d.config,[i]:P}}),j(K instanceof Error?K.message:"Failed to save enabled state")}finally{B(!1)}},[d,l,s,i,I]),E=!!d?.config[i];return g&&!d?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading ",C," settings..."]})}):n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx(Yt,{message:w,onRetry:O}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{children:[n.jsxs("h3",{className:"cedros-admin__section-title",children:[n.jsx("span",{style:{marginRight:"0.5rem"},children:N.icon}),C]}),T&&n.jsx("p",{className:"cedros-admin__text-muted",style:{marginTop:"0.25rem"},children:T})]}),c&&d&&i in d.config&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("span",{style:{fontSize:"0.875rem",color:E?"var(--cedros-admin-text, #171717)":"var(--cedros-admin-muted, #737373)"},children:E?"Enabled":"Disabled"}),n.jsx("button",{type:"button",role:"switch","aria-checked":E,onClick:D,disabled:I,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:E?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:I?"wait":"pointer",position:"relative",transition:"background-color 0.2s",flexShrink:0,opacity:I?.6:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:E?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})]})]}),d&&n.jsxs("div",{className:"cedros-admin__settings-editor",style:{marginTop:"1rem",opacity:c&&!E?.6:1,pointerEvents:c&&!E?"none":"auto"},children:[c&&!E&&n.jsx("div",{style:{padding:"0.75rem 1rem",marginBottom:"1rem",backgroundColor:"var(--cedros-admin-warning-bg, #fef3c7)",border:"1px solid var(--cedros-admin-warning-border, #f59e0b)",borderRadius:"0.375rem",fontSize:"0.875rem",color:"var(--cedros-admin-warning-text, #92400e)",pointerEvents:"auto"},children:"This payment method is disabled. Enable it using the toggle above to accept payments."}),n.jsx(Gf,{category:d.category,config:d.config,originalConfig:d.config,onSave:S,onValidate:A,onCancel:()=>O()})]}),h&&n.jsxs("div",{className:"cedros-admin__settings-history",style:{marginTop:"1.5rem"},children:[n.jsx("h4",{style:{marginBottom:"0.75rem",fontWeight:600},children:"Change History"}),u.length===0?n.jsx("p",{className:"cedros-admin__text-muted",children:"No history entries found."}):n.jsx("div",{className:"cedros-admin__settings-timeline",children:u.map(P=>n.jsxs("div",{className:"cedros-admin__settings-timeline-item",children:[n.jsx("div",{className:"cedros-admin__settings-timeline-dot"}),n.jsxs("div",{className:"cedros-admin__settings-timeline-content",children:[n.jsxs("div",{className:"cedros-admin__settings-timeline-header",children:[n.jsx("code",{children:P.configKey}),n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${P.action.toLowerCase()}`,children:P.action})]}),n.jsxs("div",{className:"cedros-admin__settings-timeline-meta",children:[kr(P.changedAt)," by ",P.changedBy]})]})]},P.id))})]}),b&&n.jsx("div",{style:{marginTop:"1rem",padding:"0.75rem 1rem",borderRadius:"0.375rem",backgroundColor:b.valid?"var(--cedros-admin-success-bg, #dcfce7)":"var(--cedros-admin-error-bg, #fef2f2)",border:`1px solid ${b.valid?"var(--cedros-admin-success-border, #86efac)":"var(--cedros-admin-error-border, #fecaca)"}`},children:n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:600,color:b.valid?"var(--cedros-admin-success, #16a34a)":"var(--cedros-admin-error, #dc2626)",marginBottom:b.errors.length>0||b.warnings.length>0?"0.5rem":0},children:b.valid?"✓ Configuration is valid":"✗ Validation failed"}),b.errors.length>0&&n.jsx("ul",{style:{margin:0,paddingLeft:"1.25rem",color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.875rem"},children:b.errors.map((P,z)=>n.jsx("li",{children:P},z))}),b.warnings.length>0&&n.jsx("ul",{style:{margin:b.errors.length>0?"0.5rem 0 0":0,paddingLeft:"1.25rem",color:"var(--cedros-admin-warning, #ca8a04)",fontSize:"0.875rem"},children:b.warnings.map((P,z)=>n.jsx("li",{children:P},z))})]}),n.jsx("button",{type:"button",onClick:()=>v(null),style:{background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"1.25rem",lineHeight:1},title:"Dismiss",children:"×"})]})}),n.jsxs("div",{style:{marginTop:"1.5rem",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:()=>_(!h),children:h?"Hide History":"History"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",disabled:k||!d,onClick:async()=>{if(d){R(!0),v(null);try{const P=await A(d.config);v(P)}catch(P){v({valid:!1,errors:[P instanceof Error?P.message:"Validation failed"],warnings:[]})}finally{R(!1)}}},children:k?"Validating...":"Validate"})]})]})}const Xi=[{id:"logging",label:"Logging",category:"logging",description:"Configure log levels, format, and environment settings."},{id:"metrics",label:"Metrics",category:"metrics",description:"Configure metrics collection and API access for monitoring."},{id:"security",label:"Security",category:"security",description:"Configure CORS, rate limiting, and other security settings."}];function Ia({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("logging"),a=Xi.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__server-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Server"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure logging, metrics, and security settings."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:Xi.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(Ul,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description},a.category)})]})}const Xf=Object.freeze(Object.defineProperty({__proto__:null,SettingsSection:Ia},Symbol.toStringTag,{value:"Module"})),je={enabled:!1,plans:[],pageTitle:"Choose Your Plan",pageSubtitle:"Select the plan that best fits your needs.",annualSavingsBadge:"2 months free",popularBadgeText:"Best Deal",footerNotice:""},Jf={title:"New Plan",description:"",priceMonthlyUsd:0,priceAnnualUsd:0,features:[],featureHighlight:"",buttonText:"Purchase",isPopular:!1,isActive:!0,sortOrder:0};function eh(){return`plan_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Wl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState(je),[a,i]=y.useState(!0),[c,l]=y.useState(null),[d,m]=y.useState("plans"),[u,p]=y.useState("idle"),[h,_]=y.useState(null),[g,f]=y.useState({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),[w,j]=y.useState(g),[b,v]=y.useState(""),k=y.useCallback(async()=>{try{_(null);let L;const W="/admin/subscriptions/settings";if(r?.isAuthenticated())L=await r.fetchWithAuth(W);else{const Y={"Content-Type":"application/json"};t&&(Y["X-API-Key"]=t);const V=await fetch(`${e}${W}`,{headers:Y});if(!V.ok)throw new Error(`Failed to fetch settings: ${V.status}`);L=await V.json()}o({...je,...L}),f({enabled:L.enabled??je.enabled,pageTitle:L.pageTitle??je.pageTitle,pageSubtitle:L.pageSubtitle??je.pageSubtitle,annualSavingsBadge:L.annualSavingsBadge??je.annualSavingsBadge,popularBadgeText:L.popularBadgeText??je.popularBadgeText,footerNotice:L.footerNotice??je.footerNotice}),j({enabled:L.enabled??je.enabled,pageTitle:L.pageTitle??je.pageTitle,pageSubtitle:L.pageSubtitle??je.pageSubtitle,annualSavingsBadge:L.annualSavingsBadge??je.annualSavingsBadge,popularBadgeText:L.popularBadgeText??je.popularBadgeText,footerNotice:L.footerNotice??je.footerNotice}),v(JSON.stringify(L.plans??[]))}catch{o(je),f({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),j({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),v(JSON.stringify([])),_("Failed to load subscription settings")}finally{i(!1)}},[e,t,r]);y.useEffect(()=>{k()},[k]);const R=y.useCallback(async L=>{try{_(null);const W="/admin/subscriptions/settings",Y=JSON.stringify(L);if(r?.isAuthenticated())await r.fetchWithAuth(W,{method:"PUT",body:Y});else{const V={"Content-Type":"application/json"};t&&(V["X-API-Key"]=t);const ce=await fetch(`${e}${W}`,{method:"PUT",headers:V,body:Y});if(!ce.ok)throw new Error(`Failed to save settings: ${ce.status}`)}return!0}catch{return _("Failed to save subscription settings"),!1}},[r,t,e]),N=y.useMemo(()=>w.enabled!==g.enabled||w.pageTitle!==g.pageTitle||w.pageSubtitle!==g.pageSubtitle||w.annualSavingsBadge!==g.annualSavingsBadge||w.popularBadgeText!==g.popularBadgeText||w.footerNotice!==g.footerNotice,[g,w]),C=y.useMemo(()=>JSON.stringify(s.plans),[s.plans]),T=y.useMemo(()=>b!==C,[C,b]),O=y.useCallback(async()=>{const L={...s,enabled:g.enabled,pageTitle:g.pageTitle,pageSubtitle:g.pageSubtitle,annualSavingsBadge:g.annualSavingsBadge,popularBadgeText:g.popularBadgeText,footerNotice:g.footerNotice};p("saving");const W=await R(L);o(L),W&&(j({enabled:L.enabled,pageTitle:L.pageTitle,pageSubtitle:L.pageSubtitle,annualSavingsBadge:L.annualSavingsBadge,popularBadgeText:L.popularBadgeText,footerNotice:L.footerNotice}),v(JSON.stringify(L.plans))),p(W?"saved":"error"),setTimeout(()=>p("idle"),1500)},[g,R,s]);y.useEffect(()=>{if(d!=="page"||a||!N)return;const L=setTimeout(O,600);return()=>clearTimeout(L)},[d,N,a,O]),y.useEffect(()=>{if(d!=="plans"||a||!T)return;const L=setTimeout(O,800);return()=>clearTimeout(L)},[d,T,a,O]);const $=()=>{const L={...Jf,id:eh(),sortOrder:s.plans.length};o(W=>({...W,plans:[...W.plans,L]})),l(L.id)},S=(L,W)=>{o(Y=>({...Y,plans:Y.plans.map(V=>V.id===L?{...V,...W}:V)}))},A=L=>{confirm("Delete this plan? This cannot be undone.")&&(o(W=>({...W,plans:W.plans.filter(Y=>Y.id!==L)})),c===L&&l(null))},I=(L,W)=>{const Y=s.plans.findIndex(F=>F.id===L);if(Y===-1||W==="up"&&Y===0||W==="down"&&Y===s.plans.length-1)return;const V=[...s.plans],ce=W==="up"?Y-1:Y+1;[V[Y],V[ce]]=[V[ce],V[Y]],o(F=>({...F,plans:V}))},B=L=>{S(L,{features:[...s.plans.find(W=>W.id===L)?.features||[],""]})},D=(L,W,Y)=>{const V=s.plans.find(F=>F.id===L);if(!V)return;const ce=[...V.features];ce[W]=Y,S(L,{features:ce})},E=(L,W)=>{const Y=s.plans.find(ce=>ce.id===L);if(!Y)return;const V=Y.features.filter((ce,F)=>F!==W);S(L,{features:V})};if(a)return n.jsx("div",{className:"cedros-admin__page",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading subscription settings..."]})});const P=s.plans.filter(L=>L.isActive).length,z=s.plans.reduce((L,W)=>L+(W.activeSubscribers??0),0),Z=g.enabled,K=s.plans.filter(L=>L.isActive).map(L=>({label:L.title,value:L.activeSubscribers??0,description:"subscribers"}));return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:h,onRetry:k}),n.jsx(rr,{stats:[{label:"Status",value:Z?"Enabled":"Disabled",variant:Z?"success":"muted"},{label:"Active Plans",value:P,variant:P>0?"success":"muted"},{label:"Total Subscribers",value:z,variant:z>0?"success":"muted"},...K],isLoading:a}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Subscription Settings"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[d==="plans"&&n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:$,disabled:!Z,children:[Q.plus,"Add Plan"]}),n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${u}`,children:[u==="saving"&&"Saving...",u==="saved"&&"Saved",u==="error"&&"Error"]})]})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="plans"?"cedros-admin__tab--active":""}`,onClick:()=>m("plans"),children:"Plans"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="page"?"cedros-admin__tab--active":""}`,onClick:()=>m("page"),children:"Page Settings"})]}),d==="page"&&n.jsxs("div",{children:[n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Subscriptions"}),n.jsxs("label",{className:"cedros-admin__toggle",children:[n.jsx("input",{type:"checkbox",className:"cedros-admin__toggle-input",checked:g.enabled,onChange:L=>f(W=>({...W,enabled:L.target.checked}))}),n.jsx("span",{className:"cedros-admin__toggle-track",children:n.jsx("span",{className:"cedros-admin__toggle-thumb"})}),n.jsx("span",{className:"cedros-admin__toggle-label",children:"Enable Subscriptions"})]})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.pageTitle||"",onChange:L=>f(W=>({...W,pageTitle:L.target.value})),placeholder:"Choose Your Plan"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Subtitle"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.pageSubtitle||"",onChange:L=>f(W=>({...W,pageSubtitle:L.target.value})),placeholder:"Select the plan that best fits your needs."})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Savings Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.annualSavingsBadge||"",onChange:L=>f(W=>({...W,annualSavingsBadge:L.target.value})),placeholder:"2 months free"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Popular Plan Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.popularBadgeText||"",onChange:L=>f(W=>({...W,popularBadgeText:L.target.value})),placeholder:"Best Deal"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Footer Notice (optional)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.footerNotice||"",onChange:L=>f(W=>({...W,footerNotice:L.target.value})),placeholder:"For information regarding invoices, taxes..."})]})})]}),d==="plans"&&n.jsxs("div",{children:[!Z&&n.jsx("div",{style:{padding:"1.5rem",textAlign:"center",opacity:.6},children:"Subscriptions are disabled. Enable them to configure plans."}),s.plans.length===0?n.jsx("div",{style:{padding:"2rem",textAlign:"center",opacity:.6,border:"1px dashed currentColor",borderRadius:8},children:'No plans configured. Click "Add Plan" to create your first subscription tier.'}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:s.plans.map((L,W)=>{const Y=c===L.id;return n.jsxs("div",{style:{border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:8,overflow:"hidden",background:L.isPopular?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"1rem",padding:"0.75rem 1rem",cursor:"pointer"},onClick:()=>l(Y?null:L.id),children:[n.jsx("span",{style:{opacity:.5},children:Y?Q.chevronDown:Q.chevronRight}),n.jsxs("div",{style:{flex:1},children:[n.jsx("span",{style:{fontWeight:600},children:L.title||"Untitled Plan"}),L.isPopular&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:11,padding:"2px 6px",borderRadius:4,background:"var(--cedros-admin-primary, #171717)",color:"#fff"},children:"Popular"}),!L.isActive&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:11,padding:"2px 6px",borderRadius:4,background:"#9ca3af",color:"#fff"},children:"Inactive"})]}),n.jsxs("span",{style:{opacity:.6,fontSize:14},children:["$",L.priceMonthlyUsd,"/mo · $",L.priceAnnualUsd,"/yr"]}),n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},onClick:V=>V.stopPropagation(),children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>I(L.id,"up"),disabled:W===0,title:"Move up",style:{padding:"4px 8px"},children:Q.chevronUp}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>I(L.id,"down"),disabled:W===s.plans.length-1,title:"Move down",style:{padding:"4px 8px"},children:Q.chevronDown}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>A(L.id),title:"Delete plan",style:{padding:"4px 8px",color:"#dc2626"},children:Q.trash})]})]}),Y&&n.jsxs("div",{style:{padding:"1rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Plan Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.title,onChange:V=>S(L.id,{title:V.target.value}),placeholder:"e.g., Starter"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Button Text"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.buttonText||"",onChange:V=>S(L.id,{buttonText:V.target.value}),placeholder:"Purchase"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.description,onChange:V=>S(L.id,{description:V.target.value}),placeholder:"For entry-level developers managing lightweight workloads"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Monthly Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:L.priceMonthlyUsd||"",onChange:V=>S(L.id,{priceMonthlyUsd:parseFloat(V.target.value)||0}),placeholder:"10",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:L.priceAnnualUsd||"",onChange:V=>S(L.id,{priceAnnualUsd:parseFloat(V.target.value)||0}),placeholder:"100",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Feature Highlight"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.featureHighlight||"",onChange:V=>S(L.id,{featureHighlight:V.target.value}),placeholder:"100 prompts every 5 hours"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Bold text shown above feature list"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:L.isPopular||!1,onChange:V=>S(L.id,{isPopular:V.target.checked})}),"Mark as Popular (featured styling)"]})}),n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:L.isActive,onChange:V=>S(L.id,{isActive:V.target.checked})}),"Active (available for purchase)"]})})]}),n.jsxs("div",{className:"cedros-admin__form-row",style:{marginTop:"0.5rem"},children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:L.inventoryQuantity!=null,onChange:V=>S(L.id,{inventoryQuantity:V.target.checked?100:null})}),"Limit quantity available"]})}),L.inventoryQuantity!=null&&n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Total Available"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:L.inventoryQuantity??"",onChange:V=>S(L.id,{inventoryQuantity:parseInt(V.target.value)||0}),min:"0",style:{width:100}}),L.inventorySold!=null&&L.inventorySold>0&&n.jsxs("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:[L.inventorySold," sold · ",Math.max(0,L.inventoryQuantity-L.inventorySold)," remaining"]})]})]}),n.jsxs("div",{style:{marginTop:"1rem"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[n.jsxs("label",{className:"cedros-admin__field-label",style:{margin:0},children:["Feature List (",L.features.length,")"]}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>B(L.id),style:{fontSize:12,padding:"4px 8px"},children:"+ Add Feature"})]}),L.features.length===0?n.jsx("div",{style:{padding:"1rem",textAlign:"center",opacity:.5,fontSize:13,border:"1px dashed currentColor",borderRadius:6},children:'No features. Click "Add Feature" to add bullet points.'}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:L.features.map((V,ce)=>n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsxs("span",{style:{opacity:.4,fontSize:12},children:[ce+1,"."]}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:V,onChange:F=>D(L.id,ce,F.target.value),placeholder:"e.g., Powered by MiniMax M2.1",style:{flex:1}}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>E(L.id,ce),style:{padding:"4px 8px",color:"#dc2626"},title:"Remove feature",children:Q.trash})]},ce))})]})]})]},L.id)})})]})]})]})}const th=Object.freeze(Object.defineProperty({__proto__:null,SubscriptionsSection:Wl},Symbol.toStringTag,{value:"Module"})),bo={relatedProducts:{mode:"most_recent",maxItems:4,layout:{layout:"large",imageCrop:"center"}},catalog:{filters:{tags:!0,priceRange:!0,inStock:!0},sort:{featured:!0,priceAsc:!0,priceDesc:!0}},checkout:{promoCodes:!0},shopLayout:{layout:"large",imageCrop:"center"},categoryLayout:{layout:"large",imageCrop:"center"},sections:{showDescription:!0,showSpecs:!0,showShipping:!0,showRelatedProducts:!0},inventory:{preCheckoutVerification:!0,holdsEnabled:!1,holdDurationMinutes:15},shopPage:{title:"Shop",description:""}},nh=[{value:"most_recent",label:"Most Recent",description:"Show the most recently added products (excluding current product)."},{value:"by_category",label:"By Category",description:"Show products from the same category as the current product."},{value:"manual",label:"Manual Selection",description:"Specify related products per-product using relatedProductIds in metadata."},{value:"ai",label:"AI Recommendations",description:"Let AI analyze products and suggest the best matches. Requires AI to be configured in AI Settings."}],wo=[{value:"large",label:"Large",description:"Portrait cards (4:5) with full product info, description, and tags."},{value:"square",label:"Square",description:"Square cards (1:1) showing title and price only."},{value:"compact",label:"Compact",description:"Compact cards (3:4) with smaller text to fit more products."}],_o=[{value:"center",label:"Center"},{value:"top",label:"Top"},{value:"bottom",label:"Bottom"},{value:"left",label:"Left"},{value:"right",label:"Right"}],rh=[{id:"shop-page",label:"Shop Page"},{id:"catalog",label:"Catalog"},{id:"layouts",label:"Layouts"},{id:"product-pages",label:"Product Pages"},{id:"checkout",label:"Checkout"}];function Vl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("shop-page"),[a,i]=y.useState(bo),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),h=y.useCallback(async()=>{try{p(null);let S;const A="/admin/config/shop";if(r?.isAuthenticated())S=await r.fetchWithAuth(A);else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}${A}`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch settings: ${B.status}`);S=await B.json()}i({...bo,...S.config})}catch{i(bo),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{h()},[h]);const _=y.useCallback(async S=>{const A="/admin/config/shop",I=JSON.stringify({config:S});try{if(r?.isAuthenticated())await r.fetchWithAuth(A,{method:"PUT",body:I});else{const B={"Content-Type":"application/json"};t&&(B["X-API-Key"]=t);const D=await fetch(`${e}${A}`,{method:"PUT",headers:B,body:I});if(!D.ok)throw new Error(`Failed to save settings: ${D.status}`)}}catch{throw p("Failed to save storefront settings"),new Error("Save failed")}},[e,t,r]),{status:g,error:f}=Ta({data:a,onSave:_,debounceMs:1500,enabled:!d}),w=S=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,mode:S}}))},j=S=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,maxItems:S}}))},b=(S,A)=>{i(I=>({...I,relatedProducts:{...I.relatedProducts,layout:{...I.relatedProducts.layout,[S]:A}}}))},v=(S,A)=>{i(I=>({...I,catalog:{...I.catalog,filters:{...I.catalog.filters,[S]:A}}}))},k=(S,A)=>{const I=a.catalog.sort,B=Object.values(I).filter(Boolean).length;!A&&B<=1||i(D=>({...D,catalog:{...D.catalog,sort:{...D.catalog.sort,[S]:A}}}))},R=(S,A)=>{i(I=>({...I,checkout:{...I.checkout,[S]:A}}))},N=(S,A)=>{i(I=>({...I,shopLayout:{...I.shopLayout,[S]:A}}))},C=(S,A)=>{i(I=>({...I,categoryLayout:{...I.categoryLayout,[S]:A}}))},T=(S,A)=>{i(I=>({...I,sections:{...I.sections,[S]:A}}))},O=(S,A)=>{i(I=>({...I,inventory:{...I.inventory,[S]:A}}))},$=(S,A)=>{i(I=>({...I,shopPage:{...I.shopPage,[S]:A}}))};return c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading storefront settings..."]})}):n.jsxs("div",{className:"cedros-admin__storefront-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Storefront"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure catalog filters, product layouts, and checkout settings."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[rh.map(S=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===S.id?"cedros-admin__tab--active":""}`,onClick:()=>o(S.id),children:S.label},S.id)),n.jsx("div",{style:{flex:1}}),n.jsx(sh,{status:g,error:f})]}),n.jsx(Yt,{message:u,onRetry:h}),s==="shop-page"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Shop Page Content"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Customize the title and description shown on your shop page."}),n.jsxs("div",{className:"cedros-admin__field",style:{marginBottom:"1.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.shopPage.title,onChange:S=>$("title",S.target.value),placeholder:"Shop"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"The main heading displayed on your shop page."})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Description"}),n.jsx("textarea",{className:"cedros-admin__textarea",value:a.shopPage.description,onChange:S=>$("description",S.target.value),placeholder:"Browse our collection of products...",rows:3,style:{resize:"vertical"}}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"A short description or subtitle shown below the title. Leave empty to hide."})]})]}),s==="catalog"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Catalog Filters"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which filters appear in the shop and category page sidebars."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.filters.tags,onChange:S=>v("tags",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Tags"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter products by tags (multi-select checkboxes)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.filters.priceRange,onChange:S=>v("priceRange",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price Range"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter by minimum and maximum price"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.filters.inStock,onChange:S=>v("inStock",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"In Stock"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show only products that are in stock"})]})]})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Sort Options"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sort options appear in the shop and category pages. At least one must be enabled."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.sort.featured,onChange:S=>k("featured",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Featured"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Default sort order (as returned by backend)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.sort.priceAsc,onChange:S=>k("priceAsc",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: Low to High"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price ascending"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.sort.priceDesc,onChange:S=>k("priceDesc",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: High to Low"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price descending"})]})]})]})]})]}),s==="layouts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Product Layouts"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Configure product card layouts for shop and category pages."}),n.jsxs("div",{style:{marginBottom:"2rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Shop Page"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:wo.map(S=>{const A=a.shopLayout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"shopLayout",value:S.value,checked:A,onChange:()=>N("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(ot,{value:a.shopLayout.imageCrop,onChange:S=>N("imageCrop",S),options:_o,label:"Image Crop",style:{maxWidth:180}})]}),n.jsxs("div",{style:{paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Category Pages"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:wo.map(S=>{const A=a.categoryLayout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"categoryLayout",value:S.value,checked:A,onChange:()=>C("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(ot,{value:a.categoryLayout.imageCrop,onChange:S=>C("imageCrop",S),options:_o,label:"Image Crop",style:{maxWidth:180}})]})]}),s==="product-pages"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Related Products"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure how related products are displayed on product detail pages."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"1.5rem"},children:nh.map(S=>{const A=a.relatedProducts.mode===S.value,I=S.badge==="Coming Soon";return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"1rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:8,cursor:I?"not-allowed":"pointer",opacity:I?.6:1,background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedProductsMode",value:S.value,checked:A,onChange:()=>!I&&w(S.value),disabled:I,style:{marginTop:2}}),n.jsxs("div",{style:{flex:1},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("span",{style:{fontWeight:600},children:S.label}),S.badge&&n.jsx("span",{style:{fontSize:11,padding:"2px 6px",borderRadius:4,background:"#6366f1",color:"#fff"},children:S.badge})]}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:13,opacity:.75},children:S.description})]})]},S.value)})}),a.relatedProducts.mode==="manual"&&n.jsxs("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #f5f5f5)",borderRadius:8,border:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("strong",{style:{fontSize:14},children:"How to set related products:"}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.8},children:["When editing a product, add a ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"relatedProductIds"})," field to its metadata containing a comma-separated list of product IDs."]}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.6},children:["Example: ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"prod_123,prod_456,prod_789"})]})]}),n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Max Related Products"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.relatedProducts.maxItems,onChange:S=>j(Math.max(1,Math.min(12,parseInt(S.target.value)||4))),min:1,max:12}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How many related products to show (1-12)"})]}),n.jsxs("div",{style:{marginTop:"1.5rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Display Layout"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:wo.map(S=>{const A=a.relatedProducts.layout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedLayout",value:S.value,checked:A,onChange:()=>b("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(ot,{value:a.relatedProducts.layout.imageCrop,onChange:S=>b("imageCrop",S),options:_o,label:"Image Crop",style:{maxWidth:180}})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Page Sections"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sections appear on product detail pages."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showDescription,onChange:S=>T("showDescription",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Description"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Expandable description accordion"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showSpecs,onChange:S=>T("showSpecs",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Specifications"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product attributes and details"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showShipping,onChange:S=>T("showShipping",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Shipping & Returns"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Shipping and return policy information"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showRelatedProducts,onChange:S=>T("showRelatedProducts",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Related Products"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product recommendations section"})]})]})]})]})]}),s==="checkout"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Checkout Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure checkout and cart page features."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.checkout.promoCodes,onChange:S=>R("promoCodes",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Promo Codes"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show promo/coupon code input on cart and checkout pages"})]})]})})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Inventory Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure inventory verification and reservation behavior."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.inventory.preCheckoutVerification,onChange:S=>O("preCheckoutVerification",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Pre-Checkout Verification"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Verify inventory availability before processing payment"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.inventory.holdsEnabled,onChange:S=>O("holdsEnabled",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Inventory Holds"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Reserve inventory when items are added to cart"})]})]})]}),a.inventory.holdsEnabled&&n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200,marginTop:"1rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Hold Duration (minutes)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.inventory.holdDurationMinutes,onChange:S=>O("holdDurationMinutes",Math.max(5,Math.min(60,parseInt(S.target.value)||15))),min:5,max:60}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How long to reserve inventory in carts (5-60 minutes)"})]})]})]})]})}function sh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function bt({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:()=>t(!e),style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const oh=Object.freeze(Object.defineProperty({__proto__:null,StorefrontSection:Vl},Symbol.toStringTag,{value:"Module"})),jo=[{id:"not_set",label:"Not Set",provider:null},{id:"gemini-2.5-flash",label:"Gemini 2.5 Flash",provider:"gemini"},{id:"gemini-2.5-pro",label:"Gemini 2.5 Pro",provider:"gemini"},{id:"openai-4o",label:"OpenAI 4o",provider:"openai"},{id:"openai-5.1",label:"OpenAI 5.1",provider:"openai"},{id:"openai-5.2",label:"OpenAI 5.2",provider:"openai"}],Jo=[{task:"site_chat",label:"Site Chat",description:"The conversational model that crafts responses to customer messages",defaultPrompt:`You are a friendly and helpful shopping assistant for our store. Your role is to:
|
|
3
|
+
`).filter(Boolean)),placeholder:"One item per line",rows:3,disabled:s}),_(b.description)]})}if(b.type==="object")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:b.label}),n.jsx("textarea",{className:"cedros-admin__textarea cedros-admin__textarea--mono",value:JSON.stringify(v,null,2),onChange:N=>{try{p(j,JSON.parse(N.target.value))}catch{}},rows:5,disabled:s}),_(b.description)]});const k=c.has(j),R=b.isSecret&&!k&&v===wr?wr:v;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[b.label,b.isSecret&&n.jsx("span",{className:"cedros-admin__field-secret",children:" (secret)"})]}),n.jsxs("div",{className:"cedros-admin__input-group",children:[n.jsx("input",{type:b.isSecret&&!k?"password":"text",className:"cedros-admin__input",value:R,onChange:N=>p(j,N.target.value),disabled:s,placeholder:b.isSecret?"••••••••":""}),b.isSecret&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>h(j),style:{padding:"0.5rem",minWidth:"auto"},title:k?"Hide":"Show",children:k?Q.eyeOff:Q.eye})]}),_(b.description)]})},f=Object.keys(a),w=j=>{const v=Ki(e,j,r[j]??a[j]);if(v.hidden||v.showWhen&&!a[v.showWhen])return!1;if(j==="token_decimals"){const b=a.token_mint;if(b&&J.STABLECOIN_METADATA[b])return!1}return!0};return n.jsxs("div",{className:"cedros-admin__config-editor",children:[n.jsx("div",{className:"cedros-admin__config-fields",children:f.filter(w).map(j=>n.jsx("div",{className:"cedros-admin__config-field",children:g(j,a[j])},j))}),n.jsx("div",{className:"cedros-admin__config-actions",children:n.jsx("div",{className:"cedros-admin__autosave-status",children:n.jsx(Kf,{status:m,error:u})})})]})}function Qf({label:e,value:t,onChange:r,decimals:s,onDecimalsChange:o,disabled:a=!1,description:i,customSymbol:c="",customIcon:l="",onCustomSymbolChange:d,onCustomIconChange:m}){const[u,p]=y.useState(!1),h=Object.entries(J.STABLECOIN_METADATA),g=!!J.STABLECOIN_METADATA[t],w=u||!!t&&!g,j=v=>{if(v==="custom")p(!0),g&&r("");else{p(!1),r(v);const b=J.STABLECOIN_METADATA[v];b&&o&&o(b.decimals),d&&d(""),m&&m("")}};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:e}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem"},children:[h.map(([v,b])=>n.jsxs("button",{type:"button",onClick:()=>j(v),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:t===v?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:t===v?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:t===v?600:400},children:[n.jsx("img",{src:b.icon,alt:b.symbol,style:{width:20,height:20,borderRadius:"50%"},onError:k=>{k.target.style.display="none"}}),n.jsx("span",{children:b.symbol})]},v)),n.jsxs("button",{type:"button",onClick:()=>j("custom"),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:w?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:w?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:w?600:400},children:[n.jsx("span",{style:{fontSize:"1rem"},children:"+"}),n.jsx("span",{children:"Custom"})]})]}),w&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"1rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:[n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Mint Address"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:t,onChange:v=>r(v.target.value),placeholder:"e.g., EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",disabled:a,style:{fontFamily:"monospace",fontSize:"0.875rem"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Symbol"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:v=>d?.(v.target.value),placeholder:"e.g., MYTOKEN",disabled:a,style:{textTransform:"uppercase"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Icon URL"}),n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:l,onChange:v=>m?.(v.target.value),placeholder:"https://example.com/token-logo.png",disabled:a,style:{flex:1}}),l&&n.jsx("img",{src:l,alt:"Token icon preview",style:{width:32,height:32,borderRadius:"50%",border:"1px solid var(--cedros-admin-border, #e5e7eb)",objectFit:"cover"},onError:v=>{v.target.style.display="none"}})]}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Shown to customers during checkout"})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Decimals"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:s??6,onChange:v=>o?.(parseInt(v.target.value,10)||0),min:0,max:18,disabled:a,style:{width:"100px"}}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Most SPL tokens use 6 decimals (like USDC)"})]})]}),t&&g&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",fontFamily:"monospace",wordBreak:"break-all"},children:t}),i&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:i})]})]})}function Yf({label:e,value:t,onChange:r,disabled:s=!1,description:o}){const[a,i]=y.useState(new Set),[c,l]=y.useState(null),[d,m]=y.useState(""),u=Array.isArray(t)?t:[],p=v=>{i(b=>{const k=new Set(b);return k.has(v)?k.delete(v):k.add(v),k})},h=()=>{r([...u,""]),l(u.length),m("")},_=(v,b)=>{const k=[...u];k[v]=b,r(k)},g=v=>{const b=u.filter((k,R)=>R!==v);r(b),i(k=>{const R=new Set;return k.forEach(N=>{N<v?R.add(N):N>v&&R.add(N-1)}),R})},f=v=>{l(v),m(u[v]||"")},w=()=>{c!==null&&(_(c,d),l(null),m(""))},j=()=>{c!==null&&u[c]===""&&g(c),l(null),m("")};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",style:{marginBottom:0},children:e}),n.jsxs("button",{type:"button",onClick:h,disabled:s,style:{display:"flex",alignItems:"center",gap:"0.25rem",padding:"0.25rem 0.5rem",fontSize:"0.75rem",border:"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.375rem",background:"var(--cedros-admin-bg, #fff)",cursor:s?"not-allowed":"pointer",opacity:s?.5:1},children:[Q.plus,"Add"]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u.length===0&&n.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"0.875rem",border:"1px dashed var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem"},children:'No items. Click "Add" to create one.'}),u.map((v,b)=>{const k=a.has(b),R=c===b,N=v===wr;return n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.375rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:R?n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:d,onChange:C=>m(C.target.value),placeholder:"Enter wallet keypair...",autoFocus:!0,style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem"},onKeyDown:C=>{C.key==="Enter"&&w(),C.key==="Escape"&&j()}}),n.jsx("button",{type:"button",onClick:w,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-success, #22c55e)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Save",children:Q.check}),n.jsx("button",{type:"button",onClick:j,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-text-muted, #64748b)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Cancel",children:Q.close})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k&&!N?v:N?"[REDACTED]":"••••••••••••••••••••"}),n.jsx("button",{type:"button",onClick:()=>p(b),disabled:s||N,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s||N?"not-allowed":"pointer",opacity:s||N?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:k?"Hide":"Show",children:k?Q.eyeOff:Q.eye}),n.jsx("button",{type:"button",onClick:()=>f(b),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:"Edit",children:Q.settings}),n.jsx("button",{type:"button",onClick:()=>g(b),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-error, #ef4444)"},title:"Delete",children:Q.trash})]})},b)})]}),o&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.5rem"},children:o})]})}function Kf({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${e}`,style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx(n.Fragment,{children:n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"})}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx(n.Fragment,{children:n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})})]})}function Ul({serverUrl:e,apiKey:t,authManager:r,category:s,title:o,description:a,enabledField:i="enabled",showEnabledToggle:c=!1}){const l=y.useMemo(()=>new Hf(e,void 0,r),[e,r]),[d,m]=y.useState(null),[u,p]=y.useState([]),[h,_]=y.useState(!1),[g,f]=y.useState(!0),[w,j]=y.useState(null),[v,b]=y.useState(null),[k,R]=y.useState(!1),N=Ea[s]||{label:s,icon:"⚙️"},C=o||N.label,T=a||N.description,O=y.useCallback(async()=>{f(!0),j(null);try{const P=await l.getConfig(s,!0);m(P)}catch{m(null),j("Failed to load settings")}finally{f(!1)}},[l,s]);y.useEffect(()=>{O()},[O]);const $=y.useCallback(async()=>{try{const P=await l.getHistory(s,20);p(P.history)}catch{p([])}},[l,s]);y.useEffect(()=>{h&&$()},[h,$]);const S=y.useCallback(async P=>{await l.updateConfig(s,P,"Updated via admin dashboard"),await O()},[l,s,O]),A=y.useCallback(async P=>l.validateConfig(s,P),[l,s]),[I,B]=y.useState(!1),D=y.useCallback(async()=>{if(!d||I)return;const P=!!d.config[i],z=!P,Z={...d.config,[i]:z};B(!0),m({...d,config:Z});try{await l.updateConfig(s,Z,`${z?"Enabled":"Disabled"} via admin dashboard`)}catch(K){m({...d,config:{...d.config,[i]:P}}),j(K instanceof Error?K.message:"Failed to save enabled state")}finally{B(!1)}},[d,l,s,i,I]),E=!!d?.config[i];return g&&!d?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading ",C," settings..."]})}):n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx(Yt,{message:w,onRetry:O}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{children:[n.jsxs("h3",{className:"cedros-admin__section-title",children:[n.jsx("span",{style:{marginRight:"0.5rem"},children:N.icon}),C]}),T&&n.jsx("p",{className:"cedros-admin__text-muted",style:{marginTop:"0.25rem"},children:T})]}),c&&d&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("span",{style:{fontSize:"0.875rem",color:E?"var(--cedros-admin-text, #171717)":"var(--cedros-admin-muted, #737373)"},children:E?"Enabled":"Disabled"}),n.jsx("button",{type:"button",role:"switch","aria-checked":E,onClick:D,disabled:I,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:E?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:I?"wait":"pointer",position:"relative",transition:"background-color 0.2s",flexShrink:0,opacity:I?.6:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:E?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})]})]}),d&&n.jsxs("div",{className:"cedros-admin__settings-editor",style:{marginTop:"1rem",opacity:c&&!E?.6:1,pointerEvents:c&&!E?"none":"auto"},children:[c&&!E&&n.jsx("div",{style:{padding:"0.75rem 1rem",marginBottom:"1rem",backgroundColor:"var(--cedros-admin-warning-bg, #fef3c7)",border:"1px solid var(--cedros-admin-warning-border, #f59e0b)",borderRadius:"0.375rem",fontSize:"0.875rem",color:"var(--cedros-admin-warning-text, #92400e)",pointerEvents:"auto"},children:"This payment method is disabled. Enable it using the toggle above to accept payments."}),n.jsx(Gf,{category:d.category,config:d.config,originalConfig:d.config,onSave:S,onValidate:A,onCancel:()=>O()})]}),h&&n.jsxs("div",{className:"cedros-admin__settings-history",style:{marginTop:"1.5rem"},children:[n.jsx("h4",{style:{marginBottom:"0.75rem",fontWeight:600},children:"Change History"}),u.length===0?n.jsx("p",{className:"cedros-admin__text-muted",children:"No history entries found."}):n.jsx("div",{className:"cedros-admin__settings-timeline",children:u.map(P=>n.jsxs("div",{className:"cedros-admin__settings-timeline-item",children:[n.jsx("div",{className:"cedros-admin__settings-timeline-dot"}),n.jsxs("div",{className:"cedros-admin__settings-timeline-content",children:[n.jsxs("div",{className:"cedros-admin__settings-timeline-header",children:[n.jsx("code",{children:P.configKey}),n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${P.action.toLowerCase()}`,children:P.action})]}),n.jsxs("div",{className:"cedros-admin__settings-timeline-meta",children:[kr(P.changedAt)," by ",P.changedBy]})]})]},P.id))})]}),v&&n.jsx("div",{style:{marginTop:"1rem",padding:"0.75rem 1rem",borderRadius:"0.375rem",backgroundColor:v.valid?"var(--cedros-admin-success-bg, #dcfce7)":"var(--cedros-admin-error-bg, #fef2f2)",border:`1px solid ${v.valid?"var(--cedros-admin-success-border, #86efac)":"var(--cedros-admin-error-border, #fecaca)"}`},children:n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:600,color:v.valid?"var(--cedros-admin-success, #16a34a)":"var(--cedros-admin-error, #dc2626)",marginBottom:v.errors.length>0||v.warnings.length>0?"0.5rem":0},children:v.valid?"✓ Configuration is valid":"✗ Validation failed"}),v.errors.length>0&&n.jsx("ul",{style:{margin:0,paddingLeft:"1.25rem",color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.875rem"},children:v.errors.map((P,z)=>n.jsx("li",{children:P},z))}),v.warnings.length>0&&n.jsx("ul",{style:{margin:v.errors.length>0?"0.5rem 0 0":0,paddingLeft:"1.25rem",color:"var(--cedros-admin-warning, #ca8a04)",fontSize:"0.875rem"},children:v.warnings.map((P,z)=>n.jsx("li",{children:P},z))})]}),n.jsx("button",{type:"button",onClick:()=>b(null),style:{background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"1.25rem",lineHeight:1},title:"Dismiss",children:"×"})]})}),n.jsxs("div",{style:{marginTop:"1.5rem",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:()=>_(!h),children:h?"Hide History":"History"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",disabled:k||!d,onClick:async()=>{if(d){R(!0),b(null);try{const P=await A(d.config);b(P)}catch(P){b({valid:!1,errors:[P instanceof Error?P.message:"Validation failed"],warnings:[]})}finally{R(!1)}}},children:k?"Validating...":"Validate"})]})]})}const Xi=[{id:"logging",label:"Logging",category:"logging",description:"Configure log levels, format, and environment settings."},{id:"metrics",label:"Metrics",category:"metrics",description:"Configure metrics collection and API access for monitoring."},{id:"security",label:"Security",category:"security",description:"Configure CORS, rate limiting, and other security settings."}];function Ia({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("logging"),a=Xi.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__server-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Server"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure logging, metrics, and security settings."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:Xi.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(Ul,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description},a.category)})]})}const Xf=Object.freeze(Object.defineProperty({__proto__:null,SettingsSection:Ia},Symbol.toStringTag,{value:"Module"})),je={enabled:!1,plans:[],pageTitle:"Choose Your Plan",pageSubtitle:"Select the plan that best fits your needs.",annualSavingsBadge:"2 months free",popularBadgeText:"Best Deal",footerNotice:""},Jf={title:"New Plan",description:"",priceMonthlyUsd:0,priceAnnualUsd:0,features:[],featureHighlight:"",buttonText:"Purchase",isPopular:!1,isActive:!0,sortOrder:0};function eh(){return`plan_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Wl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState(je),[a,i]=y.useState(!0),[c,l]=y.useState(null),[d,m]=y.useState("plans"),[u,p]=y.useState("idle"),[h,_]=y.useState(null),[g,f]=y.useState({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),[w,j]=y.useState(g),[v,b]=y.useState(""),k=y.useCallback(async()=>{try{_(null);let L;const W="/admin/subscriptions/settings";if(r?.isAuthenticated())L=await r.fetchWithAuth(W);else{const Y={"Content-Type":"application/json"};t&&(Y["X-API-Key"]=t);const V=await fetch(`${e}${W}`,{headers:Y});if(!V.ok)throw new Error(`Failed to fetch settings: ${V.status}`);L=await V.json()}o({...je,...L}),f({enabled:L.enabled??je.enabled,pageTitle:L.pageTitle??je.pageTitle,pageSubtitle:L.pageSubtitle??je.pageSubtitle,annualSavingsBadge:L.annualSavingsBadge??je.annualSavingsBadge,popularBadgeText:L.popularBadgeText??je.popularBadgeText,footerNotice:L.footerNotice??je.footerNotice}),j({enabled:L.enabled??je.enabled,pageTitle:L.pageTitle??je.pageTitle,pageSubtitle:L.pageSubtitle??je.pageSubtitle,annualSavingsBadge:L.annualSavingsBadge??je.annualSavingsBadge,popularBadgeText:L.popularBadgeText??je.popularBadgeText,footerNotice:L.footerNotice??je.footerNotice}),b(JSON.stringify(L.plans??[]))}catch{o(je),f({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),j({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),b(JSON.stringify([])),_("Failed to load subscription settings")}finally{i(!1)}},[e,t,r]);y.useEffect(()=>{k()},[k]);const R=y.useCallback(async L=>{try{_(null);const W="/admin/subscriptions/settings",Y=JSON.stringify(L);if(r?.isAuthenticated())await r.fetchWithAuth(W,{method:"PUT",body:Y});else{const V={"Content-Type":"application/json"};t&&(V["X-API-Key"]=t);const ce=await fetch(`${e}${W}`,{method:"PUT",headers:V,body:Y});if(!ce.ok)throw new Error(`Failed to save settings: ${ce.status}`)}return!0}catch{return _("Failed to save subscription settings"),!1}},[r,t,e]),N=y.useMemo(()=>w.enabled!==g.enabled||w.pageTitle!==g.pageTitle||w.pageSubtitle!==g.pageSubtitle||w.annualSavingsBadge!==g.annualSavingsBadge||w.popularBadgeText!==g.popularBadgeText||w.footerNotice!==g.footerNotice,[g,w]),C=y.useMemo(()=>JSON.stringify(s.plans),[s.plans]),T=y.useMemo(()=>v!==C,[C,v]),O=y.useCallback(async()=>{const L={...s,enabled:g.enabled,pageTitle:g.pageTitle,pageSubtitle:g.pageSubtitle,annualSavingsBadge:g.annualSavingsBadge,popularBadgeText:g.popularBadgeText,footerNotice:g.footerNotice};p("saving");const W=await R(L);o(L),W&&(j({enabled:L.enabled,pageTitle:L.pageTitle,pageSubtitle:L.pageSubtitle,annualSavingsBadge:L.annualSavingsBadge,popularBadgeText:L.popularBadgeText,footerNotice:L.footerNotice}),b(JSON.stringify(L.plans))),p(W?"saved":"error"),setTimeout(()=>p("idle"),1500)},[g,R,s]);y.useEffect(()=>{if(d!=="page"||a||!N)return;const L=setTimeout(O,600);return()=>clearTimeout(L)},[d,N,a,O]),y.useEffect(()=>{if(d!=="plans"||a||!T)return;const L=setTimeout(O,800);return()=>clearTimeout(L)},[d,T,a,O]);const $=()=>{const L={...Jf,id:eh(),sortOrder:s.plans.length};o(W=>({...W,plans:[...W.plans,L]})),l(L.id)},S=(L,W)=>{o(Y=>({...Y,plans:Y.plans.map(V=>V.id===L?{...V,...W}:V)}))},A=L=>{confirm("Delete this plan? This cannot be undone.")&&(o(W=>({...W,plans:W.plans.filter(Y=>Y.id!==L)})),c===L&&l(null))},I=(L,W)=>{const Y=s.plans.findIndex(F=>F.id===L);if(Y===-1||W==="up"&&Y===0||W==="down"&&Y===s.plans.length-1)return;const V=[...s.plans],ce=W==="up"?Y-1:Y+1;[V[Y],V[ce]]=[V[ce],V[Y]],o(F=>({...F,plans:V}))},B=L=>{S(L,{features:[...s.plans.find(W=>W.id===L)?.features||[],""]})},D=(L,W,Y)=>{const V=s.plans.find(F=>F.id===L);if(!V)return;const ce=[...V.features];ce[W]=Y,S(L,{features:ce})},E=(L,W)=>{const Y=s.plans.find(ce=>ce.id===L);if(!Y)return;const V=Y.features.filter((ce,F)=>F!==W);S(L,{features:V})};if(a)return n.jsx("div",{className:"cedros-admin__page",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading subscription settings..."]})});const P=s.plans.filter(L=>L.isActive).length,z=s.plans.reduce((L,W)=>L+(W.activeSubscribers??0),0),Z=g.enabled,K=s.plans.filter(L=>L.isActive).map(L=>({label:L.title,value:L.activeSubscribers??0,description:"subscribers"}));return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:h,onRetry:k}),n.jsx(rr,{stats:[{label:"Status",value:Z?"Enabled":"Disabled",variant:Z?"success":"muted"},{label:"Active Plans",value:P,variant:P>0?"success":"muted"},{label:"Total Subscribers",value:z,variant:z>0?"success":"muted"},...K],isLoading:a}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Subscription Settings"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[d==="plans"&&n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:$,disabled:!Z,children:[Q.plus,"Add Plan"]}),n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${u}`,children:[u==="saving"&&"Saving...",u==="saved"&&"Saved",u==="error"&&"Error"]})]})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="plans"?"cedros-admin__tab--active":""}`,onClick:()=>m("plans"),children:"Plans"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="page"?"cedros-admin__tab--active":""}`,onClick:()=>m("page"),children:"Page Settings"})]}),d==="page"&&n.jsxs("div",{children:[n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Subscriptions"}),n.jsxs("label",{className:"cedros-admin__toggle",children:[n.jsx("input",{type:"checkbox",className:"cedros-admin__toggle-input",checked:g.enabled,onChange:L=>f(W=>({...W,enabled:L.target.checked}))}),n.jsx("span",{className:"cedros-admin__toggle-track",children:n.jsx("span",{className:"cedros-admin__toggle-thumb"})}),n.jsx("span",{className:"cedros-admin__toggle-label",children:"Enable Subscriptions"})]})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.pageTitle||"",onChange:L=>f(W=>({...W,pageTitle:L.target.value})),placeholder:"Choose Your Plan"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Subtitle"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.pageSubtitle||"",onChange:L=>f(W=>({...W,pageSubtitle:L.target.value})),placeholder:"Select the plan that best fits your needs."})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Savings Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.annualSavingsBadge||"",onChange:L=>f(W=>({...W,annualSavingsBadge:L.target.value})),placeholder:"2 months free"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Popular Plan Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.popularBadgeText||"",onChange:L=>f(W=>({...W,popularBadgeText:L.target.value})),placeholder:"Best Deal"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Footer Notice (optional)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.footerNotice||"",onChange:L=>f(W=>({...W,footerNotice:L.target.value})),placeholder:"For information regarding invoices, taxes..."})]})})]}),d==="plans"&&n.jsxs("div",{children:[!Z&&n.jsx("div",{style:{padding:"1.5rem",textAlign:"center",opacity:.6},children:"Subscriptions are disabled. Enable them to configure plans."}),s.plans.length===0?n.jsx("div",{style:{padding:"2rem",textAlign:"center",opacity:.6,border:"1px dashed currentColor",borderRadius:8},children:'No plans configured. Click "Add Plan" to create your first subscription tier.'}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:s.plans.map((L,W)=>{const Y=c===L.id;return n.jsxs("div",{style:{border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:8,overflow:"hidden",background:L.isPopular?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"1rem",padding:"0.75rem 1rem",cursor:"pointer"},onClick:()=>l(Y?null:L.id),children:[n.jsx("span",{style:{opacity:.5},children:Y?Q.chevronDown:Q.chevronRight}),n.jsxs("div",{style:{flex:1},children:[n.jsx("span",{style:{fontWeight:600},children:L.title||"Untitled Plan"}),L.isPopular&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:11,padding:"2px 6px",borderRadius:4,background:"var(--cedros-admin-primary, #171717)",color:"#fff"},children:"Popular"}),!L.isActive&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:11,padding:"2px 6px",borderRadius:4,background:"#9ca3af",color:"#fff"},children:"Inactive"})]}),n.jsxs("span",{style:{opacity:.6,fontSize:14},children:["$",L.priceMonthlyUsd,"/mo · $",L.priceAnnualUsd,"/yr"]}),n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},onClick:V=>V.stopPropagation(),children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>I(L.id,"up"),disabled:W===0,title:"Move up",style:{padding:"4px 8px"},children:Q.chevronUp}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>I(L.id,"down"),disabled:W===s.plans.length-1,title:"Move down",style:{padding:"4px 8px"},children:Q.chevronDown}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>A(L.id),title:"Delete plan",style:{padding:"4px 8px",color:"#dc2626"},children:Q.trash})]})]}),Y&&n.jsxs("div",{style:{padding:"1rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Plan Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.title,onChange:V=>S(L.id,{title:V.target.value}),placeholder:"e.g., Starter"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Button Text"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.buttonText||"",onChange:V=>S(L.id,{buttonText:V.target.value}),placeholder:"Purchase"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.description,onChange:V=>S(L.id,{description:V.target.value}),placeholder:"For entry-level developers managing lightweight workloads"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Monthly Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:L.priceMonthlyUsd||"",onChange:V=>S(L.id,{priceMonthlyUsd:parseFloat(V.target.value)||0}),placeholder:"10",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:L.priceAnnualUsd||"",onChange:V=>S(L.id,{priceAnnualUsd:parseFloat(V.target.value)||0}),placeholder:"100",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Feature Highlight"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.featureHighlight||"",onChange:V=>S(L.id,{featureHighlight:V.target.value}),placeholder:"100 prompts every 5 hours"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Bold text shown above feature list"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:L.isPopular||!1,onChange:V=>S(L.id,{isPopular:V.target.checked})}),"Mark as Popular (featured styling)"]})}),n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:L.isActive,onChange:V=>S(L.id,{isActive:V.target.checked})}),"Active (available for purchase)"]})})]}),n.jsxs("div",{className:"cedros-admin__form-row",style:{marginTop:"0.5rem"},children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:L.inventoryQuantity!=null,onChange:V=>S(L.id,{inventoryQuantity:V.target.checked?100:null})}),"Limit quantity available"]})}),L.inventoryQuantity!=null&&n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Total Available"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:L.inventoryQuantity??"",onChange:V=>S(L.id,{inventoryQuantity:parseInt(V.target.value)||0}),min:"0",style:{width:100}}),L.inventorySold!=null&&L.inventorySold>0&&n.jsxs("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:[L.inventorySold," sold · ",Math.max(0,L.inventoryQuantity-L.inventorySold)," remaining"]})]})]}),n.jsxs("div",{style:{marginTop:"1rem"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[n.jsxs("label",{className:"cedros-admin__field-label",style:{margin:0},children:["Feature List (",L.features.length,")"]}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>B(L.id),style:{fontSize:12,padding:"4px 8px"},children:"+ Add Feature"})]}),L.features.length===0?n.jsx("div",{style:{padding:"1rem",textAlign:"center",opacity:.5,fontSize:13,border:"1px dashed currentColor",borderRadius:6},children:'No features. Click "Add Feature" to add bullet points.'}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:L.features.map((V,ce)=>n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsxs("span",{style:{opacity:.4,fontSize:12},children:[ce+1,"."]}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:V,onChange:F=>D(L.id,ce,F.target.value),placeholder:"e.g., Powered by MiniMax M2.1",style:{flex:1}}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>E(L.id,ce),style:{padding:"4px 8px",color:"#dc2626"},title:"Remove feature",children:Q.trash})]},ce))})]})]})]},L.id)})})]})]})]})}const th=Object.freeze(Object.defineProperty({__proto__:null,SubscriptionsSection:Wl},Symbol.toStringTag,{value:"Module"})),vo={enabled:!0,relatedProducts:{mode:"most_recent",maxItems:4,layout:{layout:"large",imageCrop:"center"}},catalog:{filters:{tags:!0,priceRange:!0,inStock:!0},sort:{featured:!0,priceAsc:!0,priceDesc:!0}},checkout:{promoCodes:!0},shopLayout:{layout:"large",imageCrop:"center"},categoryLayout:{layout:"large",imageCrop:"center"},sections:{showDescription:!0,showSpecs:!0,showShipping:!0,showRelatedProducts:!0},inventory:{preCheckoutVerification:!0,holdsEnabled:!1,holdDurationMinutes:15},shopPage:{title:"Shop",description:""}},nh=[{value:"most_recent",label:"Most Recent",description:"Show the most recently added products (excluding current product)."},{value:"by_category",label:"By Category",description:"Show products from the same category as the current product."},{value:"manual",label:"Manual Selection",description:"Specify related products per-product using relatedProductIds in metadata."},{value:"ai",label:"AI Recommendations",description:"Let AI analyze products and suggest the best matches. Requires AI to be configured in AI Settings."}],wo=[{value:"large",label:"Large",description:"Portrait cards (4:5) with full product info, description, and tags."},{value:"square",label:"Square",description:"Square cards (1:1) showing title and price only."},{value:"compact",label:"Compact",description:"Compact cards (3:4) with smaller text to fit more products."}],_o=[{value:"center",label:"Center"},{value:"top",label:"Top"},{value:"bottom",label:"Bottom"},{value:"left",label:"Left"},{value:"right",label:"Right"}],rh=[{id:"shop-page",label:"Shop Page"},{id:"catalog",label:"Catalog"},{id:"layouts",label:"Layouts"},{id:"product-pages",label:"Product Pages"},{id:"checkout",label:"Checkout"}];function Vl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("shop-page"),[a,i]=y.useState(vo),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),h=y.useCallback(async()=>{try{p(null);let S;const A="/admin/config/shop";if(r?.isAuthenticated())S=await r.fetchWithAuth(A);else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}${A}`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch settings: ${B.status}`);S=await B.json()}i({...vo,...S.config})}catch{i(vo),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{h()},[h]);const _=y.useCallback(async S=>{const A="/admin/config/shop",I=JSON.stringify({config:S});try{if(r?.isAuthenticated())await r.fetchWithAuth(A,{method:"PUT",body:I});else{const B={"Content-Type":"application/json"};t&&(B["X-API-Key"]=t);const D=await fetch(`${e}${A}`,{method:"PUT",headers:B,body:I});if(!D.ok)throw new Error(`Failed to save settings: ${D.status}`)}}catch{throw p("Failed to save storefront settings"),new Error("Save failed")}},[e,t,r]),{status:g,error:f}=Ta({data:a,onSave:_,debounceMs:1500,enabled:!d}),w=S=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,mode:S}}))},j=S=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,maxItems:S}}))},v=(S,A)=>{i(I=>({...I,relatedProducts:{...I.relatedProducts,layout:{...I.relatedProducts.layout,[S]:A}}}))},b=(S,A)=>{i(I=>({...I,catalog:{...I.catalog,filters:{...I.catalog.filters,[S]:A}}}))},k=(S,A)=>{const I=a.catalog.sort,B=Object.values(I).filter(Boolean).length;!A&&B<=1||i(D=>({...D,catalog:{...D.catalog,sort:{...D.catalog.sort,[S]:A}}}))},R=(S,A)=>{i(I=>({...I,checkout:{...I.checkout,[S]:A}}))},N=(S,A)=>{i(I=>({...I,shopLayout:{...I.shopLayout,[S]:A}}))},C=(S,A)=>{i(I=>({...I,categoryLayout:{...I.categoryLayout,[S]:A}}))},T=(S,A)=>{i(I=>({...I,sections:{...I.sections,[S]:A}}))},O=(S,A)=>{i(I=>({...I,inventory:{...I.inventory,[S]:A}}))},$=(S,A)=>{i(I=>({...I,shopPage:{...I.shopPage,[S]:A}}))};return c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading storefront settings..."]})}):n.jsxs("div",{className:"cedros-admin__storefront-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Storefront"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure catalog filters, product layouts, and checkout settings."})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",flexShrink:0},children:[n.jsx("span",{style:{fontSize:"0.875rem",color:a.enabled?"var(--cedros-admin-text, #171717)":"var(--cedros-admin-muted, #737373)"},children:a.enabled?"Enabled":"Disabled"}),n.jsx(ft,{checked:a.enabled,onChange:S=>i(A=>({...A,enabled:S}))})]})]}),!a.enabled&&n.jsx("div",{style:{padding:"0.75rem 1rem",marginBottom:"1rem",backgroundColor:"var(--cedros-admin-warning-bg, #fef3c7)",border:"1px solid var(--cedros-admin-warning-border, #f59e0b)",borderRadius:"0.375rem",fontSize:"0.875rem",color:"var(--cedros-admin-warning-text, #92400e)"},children:"The storefront is disabled. Enable it using the toggle above to activate your store."}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",style:{opacity:a.enabled?1:.5,pointerEvents:a.enabled?"auto":"none"},children:[rh.map(S=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===S.id?"cedros-admin__tab--active":""}`,onClick:()=>o(S.id),children:S.label},S.id)),n.jsx("div",{style:{flex:1}}),n.jsx(sh,{status:g,error:f})]}),n.jsx(Yt,{message:u,onRetry:h}),s==="shop-page"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Shop Page Content"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Customize the title and description shown on your shop page."}),n.jsxs("div",{className:"cedros-admin__field",style:{marginBottom:"1.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.shopPage.title,onChange:S=>$("title",S.target.value),placeholder:"Shop"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"The main heading displayed on your shop page."})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Description"}),n.jsx("textarea",{className:"cedros-admin__textarea",value:a.shopPage.description,onChange:S=>$("description",S.target.value),placeholder:"Browse our collection of products...",rows:3,style:{resize:"vertical"}}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"A short description or subtitle shown below the title. Leave empty to hide."})]})]}),s==="catalog"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Catalog Filters"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which filters appear in the shop and category page sidebars."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.catalog.filters.tags,onChange:S=>b("tags",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Tags"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter products by tags (multi-select checkboxes)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.catalog.filters.priceRange,onChange:S=>b("priceRange",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price Range"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter by minimum and maximum price"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.catalog.filters.inStock,onChange:S=>b("inStock",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"In Stock"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show only products that are in stock"})]})]})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Sort Options"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sort options appear in the shop and category pages. At least one must be enabled."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.catalog.sort.featured,onChange:S=>k("featured",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Featured"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Default sort order (as returned by backend)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.catalog.sort.priceAsc,onChange:S=>k("priceAsc",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: Low to High"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price ascending"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.catalog.sort.priceDesc,onChange:S=>k("priceDesc",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: High to Low"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price descending"})]})]})]})]})]}),s==="layouts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Product Layouts"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Configure product card layouts for shop and category pages."}),n.jsxs("div",{style:{marginBottom:"2rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Shop Page"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:wo.map(S=>{const A=a.shopLayout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"shopLayout",value:S.value,checked:A,onChange:()=>N("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(ot,{value:a.shopLayout.imageCrop,onChange:S=>N("imageCrop",S),options:_o,label:"Image Crop",style:{maxWidth:180}})]}),n.jsxs("div",{style:{paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Category Pages"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:wo.map(S=>{const A=a.categoryLayout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"categoryLayout",value:S.value,checked:A,onChange:()=>C("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(ot,{value:a.categoryLayout.imageCrop,onChange:S=>C("imageCrop",S),options:_o,label:"Image Crop",style:{maxWidth:180}})]})]}),s==="product-pages"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Related Products"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure how related products are displayed on product detail pages."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"1.5rem"},children:nh.map(S=>{const A=a.relatedProducts.mode===S.value,I=S.badge==="Coming Soon";return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"1rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:8,cursor:I?"not-allowed":"pointer",opacity:I?.6:1,background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedProductsMode",value:S.value,checked:A,onChange:()=>!I&&w(S.value),disabled:I,style:{marginTop:2}}),n.jsxs("div",{style:{flex:1},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("span",{style:{fontWeight:600},children:S.label}),S.badge&&n.jsx("span",{style:{fontSize:11,padding:"2px 6px",borderRadius:4,background:"#6366f1",color:"#fff"},children:S.badge})]}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:13,opacity:.75},children:S.description})]})]},S.value)})}),a.relatedProducts.mode==="manual"&&n.jsxs("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #f5f5f5)",borderRadius:8,border:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("strong",{style:{fontSize:14},children:"How to set related products:"}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.8},children:["When editing a product, add a ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"relatedProductIds"})," field to its metadata containing a comma-separated list of product IDs."]}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.6},children:["Example: ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"prod_123,prod_456,prod_789"})]})]}),n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Max Related Products"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.relatedProducts.maxItems,onChange:S=>j(Math.max(1,Math.min(12,parseInt(S.target.value)||4))),min:1,max:12}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How many related products to show (1-12)"})]}),n.jsxs("div",{style:{marginTop:"1.5rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Display Layout"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:wo.map(S=>{const A=a.relatedProducts.layout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedLayout",value:S.value,checked:A,onChange:()=>v("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(ot,{value:a.relatedProducts.layout.imageCrop,onChange:S=>v("imageCrop",S),options:_o,label:"Image Crop",style:{maxWidth:180}})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Page Sections"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sections appear on product detail pages."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.sections.showDescription,onChange:S=>T("showDescription",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Description"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Expandable description accordion"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.sections.showSpecs,onChange:S=>T("showSpecs",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Specifications"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product attributes and details"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.sections.showShipping,onChange:S=>T("showShipping",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Shipping & Returns"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Shipping and return policy information"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.sections.showRelatedProducts,onChange:S=>T("showRelatedProducts",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Related Products"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product recommendations section"})]})]})]})]})]}),s==="checkout"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Checkout Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure checkout and cart page features."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.checkout.promoCodes,onChange:S=>R("promoCodes",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Promo Codes"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show promo/coupon code input on cart and checkout pages"})]})]})})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Inventory Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure inventory verification and reservation behavior."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.inventory.preCheckoutVerification,onChange:S=>O("preCheckoutVerification",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Pre-Checkout Verification"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Verify inventory availability before processing payment"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ft,{checked:a.inventory.holdsEnabled,onChange:S=>O("holdsEnabled",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Inventory Holds"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Reserve inventory when items are added to cart"})]})]})]}),a.inventory.holdsEnabled&&n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200,marginTop:"1rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Hold Duration (minutes)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.inventory.holdDurationMinutes,onChange:S=>O("holdDurationMinutes",Math.max(5,Math.min(60,parseInt(S.target.value)||15))),min:5,max:60}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How long to reserve inventory in carts (5-60 minutes)"})]})]})]})]})}function sh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function ft({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:()=>t(!e),style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const oh=Object.freeze(Object.defineProperty({__proto__:null,StorefrontSection:Vl},Symbol.toStringTag,{value:"Module"})),jo=[{id:"not_set",label:"Disabled",provider:null},{id:"gemini-2.5-flash",label:"Gemini 2.5 Flash",provider:"gemini"},{id:"gemini-2.5-pro",label:"Gemini 2.5 Pro",provider:"gemini"},{id:"openai-4o",label:"OpenAI 4o",provider:"openai"},{id:"openai-5.1",label:"OpenAI 5.1",provider:"openai"},{id:"openai-5.2",label:"OpenAI 5.2",provider:"openai"}],Jo=[{task:"site_chat",label:"Site Chat",description:"The conversational model that crafts responses to customer messages",defaultPrompt:`You are a friendly and helpful shopping assistant for our store. Your role is to:
|
|
4
4
|
|
|
5
5
|
- Help customers find products that match their needs
|
|
6
6
|
- Answer questions about products, shipping, returns, and store policies
|
|
@@ -50,45 +50,45 @@ Guidelines:
|
|
|
50
50
|
- Use sensory language when appropriate
|
|
51
51
|
- Keep descriptions scannable with short paragraphs
|
|
52
52
|
- Avoid superlatives and unverifiable claims
|
|
53
|
-
- Include relevant keywords naturally for SEO`}],ah=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],Ji={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:Jo.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function ql({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("api-keys"),[a,i]=y.useState(Ji),[c,l]=y.useState(!0),[d,m]=y.useState(!1),[u,p]=y.useState(null),[h,_]=y.useState(!1),[g,f]=y.useState(null),w=y.useRef(null),[j,b]=y.useState({gemini:"",openai:""}),[v,k]=y.useState({gemini:!1,openai:!1}),R=y.useCallback(async()=>{try{let A;if(r?.isAuthenticated())A=await r.fetchWithAuth("/admin/config/ai");else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch: ${B.status}`);A=await B.json()}A.settings&&i(A.settings)}catch{i(Ji),f("Could not load saved AI settings. Showing defaults.")}finally{l(!1)}},[e,t,r]);y.useEffect(()=>{R()},[R]);const N=y.useCallback(async A=>{const I=j[A];if(I.trim()){m(!0),p(null);try{const B={provider:A,apiKey:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,apiKeys:D.apiKeys.map(E=>E.provider===A?{...E,isConfigured:!0,maskedKey:`${I.slice(0,4)}...${I.slice(-4)}`,updatedAt:new Date().toISOString()}:E)})),b(D=>({...D,[A]:""})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save API key")}finally{m(!1)}}},[j,e,t,r]),C=y.useCallback(async A=>{if(confirm(`Are you sure you want to delete the ${A==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),p(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${A}`,{method:"DELETE"});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai/api-key/${A}`,{method:"DELETE",headers:I});if(!B.ok)throw new Error(`Failed to delete: ${B.status}`)}i(I=>({...I,apiKeys:I.apiKeys.map(B=>B.provider===A?{provider:A,isConfigured:!1}:B)}))}catch(I){p(I instanceof Error?I.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),T=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,model:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,assignedModel:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),O=y.useCallback(A=>{if(A==="not_set")return!0;const I=jo.find(D=>D.id===A);return I?.provider?a.apiKeys.find(D=>D.provider===I.provider)?.isConfigured??!1:!0},[a.apiKeys]),$=y.useMemo(()=>jo.map(A=>{const I=O(A.id);return{value:A.id,label:I?A.label:`${A.label} (API key required)`,disabled:!I}}),[O]),S=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,systemPrompt:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,systemPrompt:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return y.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),n.jsx(Yt,{message:g,onRetry:R}),h&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[Q.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:ah.map(A=>{const I=a.apiKeys.find(D=>D.provider===A.id),B=I?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:A.label}),B&&I?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",I.maskedKey,I.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(I.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${B?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:B?"Configured":"Not Set"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:v[A.id]?"text":"password",className:"cedros-admin__input",placeholder:B?"Enter new key to replace":A.placeholder,value:j[A.id],onChange:D=>b(E=>({...E,[A.id]:D.target.value})),onBlur:()=>{j[A.id].trim()&&N(A.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>k(D=>({...D,[A.id]:!D[A.id]})),title:v[A.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:v[A.id]?Q.eyeOff:Q.eye}),B&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(A.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:Q.trash})]})})]},A.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(D=>D.task===A.task),B=jo.find(D=>D.id===A.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:I?.label??A.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:I?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ot,{value:A.assignedModel,onChange:D=>T(A.task,D),options:$,label:"",disabled:d,style:{flex:1,maxWidth:280}}),B&&B.provider&&n.jsx("span",{className:`cedros-admin__badge ${O(B.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:O(B.id)?"Ready":"Missing API Key"})]})]},A.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(B=>B.task===A.task);return n.jsx(ih,{task:A.task,label:I?.label??A.task,description:I?.description??"",initialPrompt:A.systemPrompt??"",onSave:S},A.task)})})]})]})}function ih({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=y.useState(s),[c,l]=y.useState("idle"),d=y.useRef(null),m=y.useRef(null),u=y.useRef(!0);return y.useEffect(()=>{if(u.current){u.current=!1;return}return d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),l("pending"),d.current=setTimeout(async()=>{l("saving");try{await o(e,a),l("saved"),m.current=setTimeout(()=>l("idle"),2e3)}catch{l("error")}},1500),()=>{d.current&&clearTimeout(d.current)}},[a,e,o]),y.useEffect(()=>()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current)},[]),n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:t}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:r})]}),n.jsx(ch,{status:c})]}),n.jsx("textarea",{className:"cedros-admin__input",value:a,onChange:p=>i(p.target.value),placeholder:"Enter system prompt...",rows:4,style:{width:"100%",resize:"vertical",fontFamily:"inherit",minHeight:100}})]})}function ch({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const lh=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:ql},Symbol.toStringTag,{value:"Module"}));function qn({href:e,children:t}){return n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:t})}const ec=[{id:"stripe",label:"Stripe",category:"stripe",description:n.jsxs(n.Fragment,{children:["Configure your Stripe integration for card payments. Get your API keys from the"," ",n.jsx(qn,{href:"https://dashboard.stripe.com/apikeys",children:"Stripe Dashboard"}),"."]})},{id:"crypto",label:"Crypto",category:"x402",description:n.jsxs(n.Fragment,{children:["Configure Solana wallet and token settings for crypto payments. Get a fast RPC endpoint from"," ",n.jsx(qn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(qn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(qn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(qn,{href:"https://solflare.com",children:"Solflare"})," wallet."]})},{id:"credits",label:"Credits",category:"cedros_login",description:n.jsxs(n.Fragment,{children:["Configure Cedros Login integration for credits payments. See the"," ",n.jsx(qn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function Hl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("stripe"),a=ec.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__payment-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Payment Options"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure payment methods including Stripe, crypto, and credits."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:ec.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(Ul,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description,showEnabledToggle:!0},a.category)})]})}const dh=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:Hl},Symbol.toStringTag,{value:"Module"})),ko={email_enabled:!1,smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function Zl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("messages"),[a,i]=y.useState(ko),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),[h,_]=y.useState(new Set),g=y.useCallback(async()=>{try{p(null);let v;const k="/admin/config/messaging";if(r?.isAuthenticated())v=await r.fetchWithAuth(k);else{const R={"Content-Type":"application/json"};t&&(R["X-API-Key"]=t);const N=await fetch(`${e}${k}`,{headers:R});if(!N.ok)throw new Error(`Failed to fetch: ${N.status}`);v=await N.json()}i({...ko,...v.config})}catch{i(ko),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{g()},[g]);const f=y.useCallback(async v=>{const k="/admin/config/messaging",R={...v};h.has("smtp_password")||delete R.smtp_password,h.has("webhook_secret")||delete R.webhook_secret;const N=JSON.stringify({config:R});try{if(r?.isAuthenticated())await r.fetchWithAuth(k,{method:"PUT",body:N});else{const C={"Content-Type":"application/json"};t&&(C["X-API-Key"]=t);const T=await fetch(`${e}${k}`,{method:"PUT",headers:C,body:N});if(!T.ok)throw new Error(`Failed to save: ${T.status}`)}}catch{throw p("Failed to save messaging settings"),new Error("Save failed")}},[e,t,r,h]),{status:w,error:j}=Ta({data:a,onSave:f,debounceMs:1500,enabled:!d}),b=(v,k)=>{(v==="smtp_password"||v==="webhook_secret")&&_(R=>new Set(R).add(v)),i(R=>({...R,[v]:k}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[Q.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(uh,{status:w,error:j})]}),n.jsx(Yt,{message:u,onRetry:g}),n.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[s==="messages"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.email_enabled,onChange:()=>b("email_enabled",!a.email_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.webhook_enabled,onChange:()=>b("webhook_enabled",!a.webhook_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),s==="email"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure your email provider for sending customer notifications."}),!a.email_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:v=>b("smtp_host",v.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:v=>b("smtp_port",parseInt(v.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:v=>b("smtp_username",v.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("smtp_password")?a.smtp_password:"",onChange:v=>b("smtp_password",v.target.value),placeholder:a.smtp_password?"••••••••":"Enter password",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),n.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:v=>b("from_email",v.target.value),placeholder:"orders@yourstore.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:v=>b("from_name",v.target.value),placeholder:"Your Store",disabled:!a.email_enabled})]})]})]}),s==="webhooks"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:v=>b("webhook_url",v.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("webhook_secret")?a.webhook_secret:"",onChange:v=>b("webhook_secret",v.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:v=>b("webhook_timeout",parseInt(v.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function uh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function tc({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:t,style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const mh=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:Zl},Symbol.toStringTag,{value:"Module"}));function Gl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(null),[p,h]=y.useState(!1),[_,g]=y.useState(""),[f,w]=y.useState("all"),[j,b]=y.useState(null),[v,k]=y.useState(null),[R,N]=y.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),C=y.useCallback(async()=>{c(!0);try{k(null);let z;const Z=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())z=await s.fetchWithAuth(Z);else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{headers:K});if(!L.ok)throw new Error(`Failed to fetch FAQs: ${L.status}`);z=await L.json()}a(z.faqs||[])}catch{a([]),k("Failed to load FAQs")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{C()},[C]);const T=async z=>{if(z.preventDefault(),!(!R.question.trim()||!R.answer.trim())){h(!0);try{const Z=R.keywordsCsv.split(",").map(L=>L.trim().toLowerCase()).filter(Boolean),K={question:R.question.trim(),answer:R.answer.trim(),keywords:Z,active:R.active,useInChat:R.useInChat,displayOnPage:R.displayOnPage};if(m){const L=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(L,{method:"PUT",body:JSON.stringify(K)});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const Y=await fetch(`${e}${L}`,{method:"PUT",headers:W,body:JSON.stringify(K)});if(!Y.ok)throw new Error(`Failed to update FAQ: ${Y.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}/admin/faqs`,{method:"POST",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to create FAQ: ${W.status}`)}S(),C()}catch{k(m?"Failed to update FAQ":"Failed to create FAQ")}finally{h(!1)}}},O=async z=>{try{const Z=`/admin/faqs/${z}`;if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"DELETE"});else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{method:"DELETE",headers:K});if(!L.ok)throw new Error(`Failed to delete FAQ: ${L.status}`)}C()}catch{k("Failed to delete FAQ")}b(null)},$=async z=>{try{const Z=`/admin/faqs/${z.id}`,K={...z,active:!z.active};if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"PUT",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}${Z}`,{method:"PUT",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to update FAQ: ${W.status}`)}C()}catch{k("Failed to update FAQ status")}},S=()=>{N({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},A=z=>{N({question:z.question,answer:z.answer,keywordsCsv:z.keywords.join(", "),active:z.active,useInChat:z.useInChat??!0,displayOnPage:z.displayOnPage??!0}),u(z),d(!0)},I=o.length,B=o.filter(z=>z.active).length,D=o.filter(z=>z.active&&z.useInChat).length,E=o.filter(z=>z.active&&z.displayOnPage).length,P=y.useMemo(()=>o.filter(z=>{if(f==="active"&&!z.active||f==="inactive"&&z.active)return!1;if(_){const Z=_.toLowerCase();return z.question.toLowerCase().includes(Z)||z.answer.toLowerCase().includes(Z)||z.keywords.some(K=>K.includes(Z))}return!0}),[o,f,_]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(Yt,{message:v,onRetry:C}),n.jsx(rr,{stats:[{label:"Total FAQs",value:I},{label:"Active",value:B,variant:"success"},{label:"In Chat",value:D},{label:"On Page",value:E}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__btn cedros-admin__btn--primary",onClick:()=>{S(),d(!0)},children:[Q.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:_,onChange:z=>g(z.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:f,onChange:z=>w(z.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:T,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__btn--icon",onClick:S,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:R.question,onChange:z=>N(Z=>({...Z,question:z.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),n.jsx("textarea",{value:R.answer,onChange:z=>N(Z=>({...Z,answer:z.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),n.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),n.jsx("input",{type:"text",value:R.keywordsCsv,onChange:z=>N(Z=>({...Z,keywordsCsv:z.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),n.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.active,onChange:z=>N(Z=>({...Z,active:z.target.checked}))}),n.jsx("span",{children:"Active"})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),n.jsxs("div",{className:"cedros-admin__checkbox-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.useInChat,onChange:z=>N(Z=>({...Z,useInChat:z.target.checked}))}),n.jsx("span",{children:"Use in AI Chat"})]}),n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.displayOnPage,onChange:z=>N(Z=>({...Z,displayOnPage:z.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__btn",onClick:S,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__btn cedros-admin__btn--primary",disabled:p||!R.question.trim()||!R.answer.trim(),children:p?Q.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading,n.jsx("span",{children:"Loading FAQs..."})]}):P.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:_||f!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:P.map(z=>n.jsxs("div",{className:`cedros-admin__faq-item ${z.active?"":"cedros-admin__faq-item--inactive"}`,children:[n.jsxs("div",{className:"cedros-admin__faq-content",children:[n.jsxs("div",{className:"cedros-admin__faq-question",children:[n.jsx("span",{className:`cedros-admin__status-dot ${z.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),z.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:z.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[z.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:z.keywords.map(Z=>n.jsx("span",{className:"cedros-admin__tag",children:Z},Z))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[z.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[Q.chat," Chat"]}),z.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[Q.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>$(z),title:z.active?"Deactivate":"Activate",children:z.active?Q.eyeOff:Q.eye}),n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>A(z),title:"Edit",children:Q.edit}),n.jsx("button",{className:"cedros-admin__btn--icon cedros-admin__btn--danger",onClick:()=>b(z.id),title:"Delete",children:Q.trash})]}),j===z.id&&n.jsx("div",{className:"cedros-admin__confirm-overlay",children:n.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[n.jsx("p",{children:"Delete this FAQ?"}),n.jsxs("div",{className:"cedros-admin__confirm-actions",children:[n.jsx("button",{className:"cedros-admin__btn",onClick:()=>b(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__btn cedros-admin__btn--danger",onClick:()=>O(z.id),children:"Delete"})]})]})})]},z.id))})]})]})}const ph=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:Gl},Symbol.toStringTag,{value:"Module"}));class Ql{serverUrl;walletSigner=null;jwtToken=null;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,J.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,J.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=Zi.bs58.encode(this.walletSigner.publicKey.toBytes()),i=Zi.bs58.encode(o);return{"X-Signer":a,"X-Message":r.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const r=`${this.serverUrl}/paywall/v1/nonce`;J.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await J.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!s.ok){const o=await s.text();throw new Error(`Failed to fetch nonce: ${s.status} ${o}`)}return await s.json()}async fetchWithAuth(t,r={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,r.method||"GET"),a=await this.createAuthHeaders(o),i={"Content-Type":"application/json",...r.headers||{},...a},c=await J.fetchWithTimeout(`${this.serverUrl}${t}`,{...r,headers:i});if(!c.ok){const l=await c.text();throw new Error(`Admin API error ${c.status}: ${l}`)}return await c.json()}getPurposeFromPath(t,r){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[r])return o[r];if(t.startsWith("/admin/products/")){if(r==="PUT")return"admin_products_update";if(r==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(r==="PUT")return"admin_coupons_update";if(r==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(r==="GET")return"admin_config_get";if(r==="PUT")return"admin_config_update";if(r==="PATCH")return"admin_config_patch"}return`admin_${r.toLowerCase()}`}}function fh({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=ja.useWallet(),o=y.useMemo(()=>{const u=new Ql(e);return u.setCedrosLoginAuth(t??null,r),u},[e,t,r]);y.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!t,d=y.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=y.useCallback((u,p)=>o.fetchWithAuth(u,p),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const Yl=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions},{id:"products",label:"Products",icon:Q.products},{id:"subscriptions",label:"Subscriptions",icon:Q.calendarRepeat},{id:"coupons",label:"Coupons",icon:Q.coupons},{id:"refunds",label:"Refunds",icon:Q.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:Q.storefront},{id:"ai-settings",label:"Store AI",icon:Q.brain},{id:"faqs",label:"Knowledge Base",icon:Q.faq},{id:"payment-settings",label:"Payment Options",icon:Q.creditCard},{id:"messaging",label:"Store Messages",icon:Q.mail},{id:"settings",label:"Store Server",icon:Q.server}]}],hh=Yl.flatMap(e=>e.sections);function gh(){const[e,t]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return y.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=o=>t(o.matches?"dark":"light");return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[]),e}function xh(e,t,r){return e!=="system"?e:t||r}function yh({serverUrl:e,apiKey:t,title:r="Cedros Pay",sections:s=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:m=!1,theme:u="system"}){const[p,h]=y.useState(o),[_,g]=y.useState(!0),[f,w]=y.useState(new Set),j=y.useCallback($=>{w(S=>{const A=new Set(S);return A.has($)?A.delete($):A.add($),A})},[]),b=J.useCedrosThemeOptional(),v=gh(),R=xh(u,b?.mode??null,v)==="dark"?"cedros-admin--dark":"",{authManager:N}=fh({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),C=y.useCallback($=>{h($),c?.($)},[c]),O=hh.filter($=>s.includes($.id)).find($=>$.id===p);return y.useEffect(()=>{const $=setTimeout(()=>g(!1),500);return()=>clearTimeout($)},[]),_?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${R} ${l}`,children:[Q.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${R} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[Q.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:Yl.map($=>{const S=$.sections.filter(I=>s.includes(I.id));if(S.length===0)return null;const A=$.collapsible&&f.has($.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[$.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>j($.label),"aria-expanded":!A,children:[$.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${A?"":"cedros-admin__nav-label-icon--expanded"}`,children:Q.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:$.label}),!A&&S.map(I=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${p===I.id?"cedros-admin__nav-item--active":""}`,onClick:()=>C(I.id),"aria-current":p===I.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:I.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:I.label})]},I.id))]},$.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:Q.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:O?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[p==="products"&&n.jsx(Ll,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="subscriptions"&&n.jsx(Wl,{serverUrl:e,apiKey:t,authManager:N}),p==="transactions"&&n.jsx($l,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="coupons"&&n.jsx(zl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="refunds"&&n.jsx(Fl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="storefront"&&n.jsx(Vl,{serverUrl:e,apiKey:t,authManager:N}),p==="ai-settings"&&n.jsx(ql,{serverUrl:e,apiKey:t,authManager:N}),p==="faqs"&&n.jsx(Gl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="payment-settings"&&n.jsx(Hl,{serverUrl:e,apiKey:t,authManager:N}),p==="messaging"&&n.jsx(Zl,{serverUrl:e,apiKey:t,authManager:N}),p==="settings"&&n.jsx(Ia,{serverUrl:e,apiKey:t,authManager:N})]})]})]})}const Pt=e=>y.lazy(async()=>{const s=(await e()).default;return{default:({pluginContext:a})=>{const c=cf.useCedrosLogin()?._internal?.getAccessToken()??a.getAccessToken(),l=y.useMemo(()=>{const m=new Ql(a.serverUrl);return m.setCedrosLoginAuth(c??null),m},[a.serverUrl,c]),d={serverUrl:a.serverUrl,authManager:l};return n.jsx(s,{...d})}}}),vh={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:Q.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:Q.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:Q.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:Q.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:Q.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:Q.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:Q.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:Q.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:Q.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:Q.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:Pt(()=>Promise.resolve().then(()=>require("./sections-BF5Zky5V.js")).then(e=>({default:e.ProductsSection}))),subscriptions:Pt(()=>Promise.resolve().then(()=>th).then(e=>({default:e.SubscriptionsSection}))),transactions:Pt(()=>Promise.resolve().then(()=>require("./sections-BF5Zky5V.js")).then(e=>({default:e.TransactionsSection}))),coupons:Pt(()=>Promise.resolve().then(()=>require("./sections-BF5Zky5V.js")).then(e=>({default:e.CouponsSection}))),refunds:Pt(()=>Promise.resolve().then(()=>require("./sections-BF5Zky5V.js")).then(e=>({default:e.RefundsSection}))),storefront:Pt(()=>Promise.resolve().then(()=>oh).then(e=>({default:e.StorefrontSection}))),"ai-settings":Pt(()=>Promise.resolve().then(()=>lh).then(e=>({default:e.AISettingsSection}))),faqs:Pt(()=>Promise.resolve().then(()=>ph).then(e=>({default:e.FAQSection}))),"payment-settings":Pt(()=>Promise.resolve().then(()=>dh).then(e=>({default:e.PaymentSettingsSection}))),messaging:Pt(()=>Promise.resolve().then(()=>mh).then(e=>({default:e.MessagingSection}))),settings:Pt(()=>Promise.resolve().then(()=>Xf).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,r=e.cedrosLogin;return{serverUrl:t?.serverUrl||r?.serverUrl||"",userId:r?.user?.id,getAccessToken:()=>r?.getAccessToken?.()||t?.jwtToken||null,hasPermission:o=>this.checkPermission(o,e),orgId:e.org?.orgId,pluginData:{walletAddress:t?.walletAddress}}},checkPermission(e,t){return t.org?.permissions?t.org.permissions.includes(e):!!(t.cedrosLogin?.user||t.cedrosPay?.jwtToken||t.cedrosPay?.walletAddress)},cssNamespace:"cedros-dashboard"};function bh({product:e,paymentMethod:t,showOriginalPrice:r=!1,className:s="",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,m=a?e.stripeDiscountPercent:e.cryptoDiscountPercent;return n.jsxs("div",{className:s,style:o,children:[r&&d&&n.jsxs("span",{style:{textDecoration:"line-through",opacity:.6,marginRight:"0.5rem",fontSize:"0.875em"},children:[i.toFixed(2)," ",l]}),n.jsxs("span",{style:{fontWeight:600},children:[c.toFixed(2)," ",l]}),d&&m>0&&n.jsxs("span",{style:{marginLeft:"0.5rem",padding:"0.125rem 0.375rem",backgroundColor:"#10b981",color:"white",borderRadius:"0.25rem",fontSize:"0.75em",fontWeight:600},children:[m,"% OFF"]})]})}function wh({product:e,paymentMethod:t,className:r="",style:s={}}){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 n.jsxs("div",{className:r,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,...s},children:[l,c&&n.jsxs("span",{style:{marginLeft:"0.5rem",opacity:.8,fontSize:"0.75em",fontWeight:400},children:["(",c,")"]})]})}function Kl(){const{subscriptionManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=y.useCallback(async c=>{r(d=>({...d,status:"loading",error:null}));const l=await e.processSubscription(c);return r(d=>({...d,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l},[e]),o=y.useCallback(async c=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(c);return r(d=>({...d,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const d=l instanceof Error?l.message:"Failed to check subscription status";throw r(m=>({...m,status:"error",error:d})),l}},[e]),a=y.useCallback(async(c,l,d)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await e.requestSubscriptionQuote(c,l,d);return r(u=>({...u,status:"idle"})),m}catch(m){const u=m instanceof Error?m.message:"Failed to get subscription quote";throw r(p=>({...p,status:"error",error:u})),m}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:s,checkStatus:o,requestQuote:a,reset:i}}function _h({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:m=!1,onAttempt:u,onSuccess:p,onError:h,className:_=""}){const{status:g,error:f,sessionId:w,processSubscription:j}=Kl(),b=J.useCedrosTheme(),{t:v,translations:k}=xn(),R=d||v("ui.subscribe"),N=b.unstyled?_:`${b.className} cedros-theme__stripe-button ${_}`.trim(),C=f&&typeof f!="string"?f?.code??null:null,O=f?typeof f=="string"?f:(D=>{if(!D||!k)return"";const E=k.errors[D];return E?E.action?`${E.message} ${E.action}`:E.message:""})(C):null,$=y.useCallback(async()=>{J.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),Ln("stripe",e),u&&u("stripe"),un("stripe",e);const D=await j({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});D.success&&D.transactionId?($n("stripe",D.transactionId,e),p&&p(D.transactionId)):!D.success&&D.error&&(kt("stripe",D.error,e),h&&h(D.error))},[e,t,r,s,c,i,l,o,a,j,u,p,h]),S=y.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),A=y.useMemo(()=>Mn(S,$),[S,$]),I=g==="loading",B=m||I;return n.jsxs("div",{className:N,style:b.unstyled?{}:b.style,children:[n.jsx("button",{onClick:A,disabled:B,className:b.unstyled?_:"cedros-theme__button cedros-theme__stripe",type:"button",children:I?v("ui.processing"):R}),O&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__error",children:O}),w&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__success",children:v("ui.redirecting_to_checkout")})]})}function Xl(){const{subscriptionManager:e,creditsManager:t}=J.useCedrosContext(),[r,s]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=y.useCallback(async(l,d)=>{s(m=>({...m,status:"checking",error:null}));try{const m=await e.checkSubscriptionStatus({resource:l,userId:d});return s(u=>({...u,status:m.active?"success":"idle",subscriptionStatus:m.status,expiresAt:m.expiresAt||m.currentPeriodEnd||null})),m}catch(m){const u=J.formatError(m,"Failed to check subscription status");return s(p=>({...p,status:"error",error:u})),null}},[e]),a=y.useCallback(async(l,d,m)=>{s(u=>({...u,status:"loading",error:null}));try{const u=await t.requestQuote(l,m?.couponCode);return s(p=>({...p,status:"idle",creditsRequirement:u})),u}catch(u){const p=J.formatError(u,"Failed to get subscription quote");return s(h=>({...h,status:"error",error:p})),null}},[t]),i=y.useCallback(async(l,d,m,u)=>{if(!m){const p="Authentication required for credits payment";return s(h=>({...h,status:"error",error:p})),{success:!1,error:p}}s(p=>({...p,status:"loading",error:null}));try{const p=await t.processPayment(l,m,u?.couponCode,{interval:d,...u?.intervalDays&&{intervalDays:String(u.intervalDays)}});return p.success?s({status:"success",error:null,sessionId:p.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(h=>({...h,status:"error",error:p.error||"Credits subscription payment failed"})),p}catch(p){const h=J.formatError(p,"Credits subscription payment failed");return s(_=>({..._,status:"error",error:h})),{success:!1,error:h}}},[t]),c=y.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:o,requestQuote:a,processPayment:i,reset:c}}function jh({resource:e,interval:t,intervalDays:r,authToken:s,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:m,className:u="",hideMessages:p=!1,autoCheckStatus:h=!1}){const{status:_,error:g,subscriptionStatus:f,expiresAt:w,checkStatus:j,processPayment:b}=Xl(),v=J.useCedrosTheme(),{t:k,translations:R}=xn(),N=y.useRef(j);y.useEffect(()=>{N.current=j},[j]),y.useEffect(()=>{h&&o&&(J.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),N.current(e,o))},[h,o,e]);const C=i||k("ui.subscribe_with_credits")||"Subscribe with Credits",T=g&&typeof g!="string"?g?.code??null:null,$=g?typeof g=="string"?g:(Z=>{if(!Z||!R)return"";const K=R.errors[Z];return K?K.action?`${K.message} ${K.action}`:K.message:""})(T):null,S=y.useCallback(async()=>{if(J.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),Ln("credits",e),l&&l("credits"),!s){const K="Authentication required: please log in to subscribe with credits";J.getLogger().error("[CreditsSubscribeButton]",K),kt("credits",K,e),m&&m(K);return}un("credits",e);const Z=await b(e,t,s,{couponCode:a,intervalDays:r});Z.success&&Z.transactionId?($n("credits",Z.transactionId,e),d&&d(Z.transactionId)):!Z.success&&Z.error&&(kt("credits",Z.error,e),m&&m(Z.error))},[e,t,r,s,a,b,l,d,m]),A=y.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),I=y.useMemo(()=>Mn(A,S,{cooldownMs:200,deduplicationWindowMs:0}),[A,S]),B=_==="loading"||_==="checking",D=f==="active"||f==="trialing",E=c||B||D;let P=C;if(B)P=k("ui.processing");else if(D&&w){const Z=new Date(w).toLocaleDateString();P=`${k("ui.subscribed_until")} ${Z}`}else D&&(P=k("ui.subscribed"));const z=v.unstyled?u:`${v.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:z,style:v.unstyled?{}:v.style,children:[n.jsx("button",{onClick:I,disabled:E,className:v.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:P}),!p&&$&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__error",children:$}),!p&&D&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__success",children:k("ui.subscription_active")})]})}function Jl(){const{subscriptionChangeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=y.useRef(t);s.current=t;const o=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,p);return r(_=>({..._,status:"success",subscription:h,userId:p})),h}catch(h){const _=h instanceof Error?h.message:"Failed to load subscription";return r(g=>({...g,status:"error",error:_})),null}},[e]),a=y.useCallback(async(u,p,h,_)=>{r(g=>({...g,status:"loading",error:null}));try{const g={currentResource:u,newResource:p,userId:h,newInterval:_},f=await e.previewChange(g);return r(w=>({...w,status:"idle",changePreview:f})),f}catch(g){const f=g instanceof Error?g.message:"Failed to preview change";return r(w=>({...w,status:"error",error:f})),null}},[e]),i=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={currentResource:p.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},g=await e.changeSubscription(_);return g.success?r(f=>({...f,status:"success",subscription:f.subscription?{...f.subscription,resource:g.newResource,interval:g.newInterval,status:g.status}:null,changePreview:null})):r(f=>({...f,status:"error",error:g.error||"Failed to change subscription"})),g}catch(_){const g=_ instanceof Error?_.message:"Failed to change subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),c=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={resource:p.resource,userId:h,immediate:u},g=await e.cancel(_);if(g.success){const f=u?"canceled":p.status;r(w=>({...w,status:"success",subscription:w.subscription?{...w.subscription,status:f,cancelAtPeriodEnd:!u}:null}))}else r(f=>({...f,status:"error",error:g.error||"Failed to cancel subscription"}));return g}catch(_){const g=_ instanceof Error?_.message:"Failed to cancel subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),l=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:p});return window.location.href=h.url,h}catch(h){const _=h instanceof Error?h.message:"Failed to open billing portal";return r(g=>({...g,status:"error",error:_})),null}},[e]),d=y.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=y.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:o,previewChange:a,changeSubscription:i,cancelSubscription:c,openBillingPortal:l,clearPreview:d,reset:m}}const kh={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"},Sh={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 Ch(e){const t=e?Sh:kh;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 Nn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function ed(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function Nh(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 Ph({preview:e,onConfirm:t,onCancel:r,isLoading:s,styles:o}){const a=e.immediateAmount<0;return n.jsxs("div",{className:"cedros-proration-preview",style:o.prorationPreview,children:[n.jsx("h4",{style:o.previewTitle,children:"Change Preview"}),n.jsxs("div",{style:o.previewDetails,children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Current plan:"}),n.jsxs("span",{children:[Nn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[Nn(e.newPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Days remaining:"}),n.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Unused credit:"}),n.jsxs("span",{children:["-",Nn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:Nn(e.prorationDetails.newPlanCost,e.currency)})]})]}),n.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[n.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),n.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:Nn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:ed(e.effectiveDate)})]})]}),n.jsxs("div",{style:o.previewActions,children:[n.jsx("button",{onClick:r,style:o.cancelButton,disabled:s,children:"Cancel"}),n.jsx("button",{onClick:t,style:o.confirmButton,disabled:s,children:s?"Processing...":"Confirm Change"})]})]})}function Ah({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=J.useCedrosTheme(),m=y.useMemo(()=>Ch(d==="dark"),[d]),{subscription:u,changePreview:p,status:h,error:_,loadSubscription:g,previewChange:f,changeSubscription:w,cancelSubscription:j,openBillingPortal:b,clearPreview:v}=Jl();y.useEffect(()=>{g(e,t)},[e,t,g]);const k=y.useCallback(async(O,$)=>{await f(e,O,t,$)},[e,t,f]),R=y.useCallback(async()=>{if(!p)return;const O=r.find(S=>S.price===p.newPlanPrice&&S.currency===p.currency);(await w({newResource:O?.resource||e,newInterval:O?.interval,immediate:!0}))?.success&&O&&s?.(O.resource,O.interval)},[p,r,e,w,s]),N=y.useCallback(async O=>{(await j(O))?.success&&o?.()},[j,o]),C=y.useCallback(()=>{b(t,a)},[t,a,b]),T=h==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[_&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:_}),T&&!u&&n.jsx("div",{className:"cedros-subscription-loading",style:m.loading,children:"Loading subscription..."}),u&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"cedros-subscription-details",style:m.details,children:[n.jsx("h3",{style:m.title,children:"Current Subscription"}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Plan:"}),n.jsx("span",{style:m.value,children:u.resource})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Status:"}),n.jsx("span",{style:{...m.statusBadge,backgroundColor:Nh(u.status)},children:u.status})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Price:"}),n.jsxs("span",{style:m.value,children:[Nn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Current period ends:"}),n.jsx("span",{style:m.value,children:ed(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),p&&n.jsx(Ph,{preview:p,onConfirm:R,onCancel:v,isLoading:T,styles:m}),r.length>0&&!p&&n.jsxs("div",{className:"cedros-available-plans",style:m.plansSection,children:[n.jsx("h4",{style:m.plansTitle,children:"Available Plans"}),n.jsx("div",{style:m.plansList,children:r.map(O=>{const $=O.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...$?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:O.name}),n.jsxs("div",{style:m.planPrice,children:[Nn(O.price,O.currency),"/",O.interval]}),O.description&&n.jsx("div",{style:m.planDescription,children:O.description}),$?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>k(O.resource,O.interval),style:m.changePlanButton,disabled:T,children:O.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},O.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:C,style:m.portalButton,disabled:T,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>N(!1),style:m.cancelSubscriptionButton,disabled:T,children:"Cancel Subscription"})]})]})]})}function Eh(){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 Th(){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 Ih(){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 Rh(){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 Oh(){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 Mh(){const e=[Eh(),Th(),Ih(),Rh(),Oh()],t=e.some(a=>a.severity==="error"&&!a.passed),r=e.some(a=>a.severity==="warning"&&!a.passed);let s,o;return t?(s="vulnerable",o="Security issues detected. Review errors and apply recommendations."):r?(s="warnings",o="Minor security warnings detected. Consider applying recommendations."):(s="secure",o="All security checks passed."),{checks:e,overallStatus:s,summary:o}}function Dh(e){process.env.NODE_ENV!=="production"&&(console.group("🔒 Cedros Pay Security Report"),console.log(`Status: ${e.overallStatus.toUpperCase()}`),console.log(`Summary: ${e.summary}`),console.log(""),e.checks.forEach(t=>{const r=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${r} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const Lh={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"},Ra=y.createContext(null);function Re(){const e=y.useContext(Ra);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function Oa(){return y.useContext(Ra)}function $h({config:e,children:t}){return n.jsx(Ra.Provider,{value:{config:e},children:t})}function At(e){return new Promise(t=>setTimeout(t,e))}const td=[{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."}],hs=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];let So=[];const Vr={};function zh(e,t){let r=e;if(t.category&&t.category!=="all"){const l=td.find(d=>d.slug===t.category||d.id===t.category);l&&(r=r.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();r=r.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const s=t.filters??{},o=s.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));r=r.filter(d=>d.tags?.some(m=>l.has(m)))}const a=typeof s.priceMin=="number"?s.priceMin:void 0,i=typeof s.priceMax=="number"?s.priceMax:void 0;return typeof a=="number"&&(r=r.filter(l=>l.price>=a)),typeof i=="number"&&(r=r.filter(l=>l.price<=i)),(typeof s.inStock=="boolean"?s.inStock:void 0)===!0&&(r=r.filter(l=>l.inventoryStatus!=="out_of_stock")),r}function Fh(e,t){if(!t||t==="featured")return e;const r=[...e];return t==="price_asc"&&r.sort((s,o)=>s.price-o.price),t==="price_desc"&&r.sort((s,o)=>o.price-s.price),r}function Bh(e,t,r){const s=(t-1)*r;return{items:e.slice(s,s+r),page:t,pageSize:r,total:e.length,hasNextPage:s+r<e.length}}function Uh(e){const t=new Date().toISOString(),r=e.cart.map(o=>{const a=hs.find(i=>i.id===o.resource||i.slug===o.resource)??hs[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),s=r.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:s,currency:e.options.currency,items:r,receiptUrl:e.options.successUrl}}function Wh(){return{async listProducts(e){await At(150);const t=e.page??1,r=e.pageSize??24,s=zh(hs,e),o=Fh(s,e.sort);return Bh(o,t,r)},async getProductBySlug(e){return await At(100),hs.find(t=>t.slug===e)??null},async listCategories(){return await At(80),td},async getOrderHistory(){return await At(120),So},async getCart({customerId:e}){return await At(80),Vr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await At(120);const r=Vr[e]??{items:[]},s=new Map,o=i=>{const c=`${i.productId}::${i.variantId??""}`,l=s.get(c);l?s.set(c,{...l,qty:l.qty+i.qty}):s.set(c,i)};for(const i of r.items)o(i);for(const i of t.items)o(i);const a={items:Array.from(s.values()),promoCode:t.promoCode??r.promoCode};return Vr[e]=a,a},async updateCart({customerId:e,cart:t}){await At(60),Vr[e]=t},async createCheckoutSession(e){await At(250);const t=Uh(e);if(So=[t,...So].slice(0,25),e.options.successUrl){const r=new URL(e.options.successUrl,"http://localhost");return r.searchParams.set("demoOrderId",t.id),{kind:"redirect",url:r.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:t.id}}},async listSubscriptionTiers(){return await At(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await At(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await At(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function nd(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Vh(e){return e?e.toUpperCase():"USD"}function qh(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function Hh(e){if(e&&(e==="physical"||e==="digital"))return e}function Zh(e){const t=[];if(Array.isArray(e))for(const r of e)typeof r=="string"&&t.push(r);else if(typeof e=="string"){const r=e.trim();if(r.startsWith("["))try{const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(r=>r.split(",")).map(r=>r.trim().toUpperCase()).filter(Boolean)}function qr(e){const t=Vh(e.fiatCurrency),r=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],s=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=Zh(a);return{id:e.id,slug:e.slug??e.id,title:e.title??nd(e.id),description:e.description??"",images:r,price:s/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:qh(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:Hh(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function Co(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],r=e.total??e.count;return{products:t,total:r}}async function tn(e,t,r){const s={};r&&(s["X-API-Key"]=r);const o=await fetch(`${e}${t}`,{headers:s});if(!o.ok){const a=await o.text().catch(()=>""),i=new Error(`Request failed (${o.status}): ${a}`);throw i.status=o.status,i}return o.json()}function Gh(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,p=(d-1)*m,h=new URLSearchParams;h.set("limit",String(u)),h.set("offset",String(p)),l.search&&h.set("search",l.search),l.category&&h.set("category",l.category),l.sort&&h.set("sort",l.sort),l.filters?.inStock&&h.set("in_stock","true"),l.filters?.minPrice!=null&&h.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&h.set("max_price",String(l.filters.maxPrice));const _=l.filters?.tags,g=Array.isArray(_)?_:typeof _=="string"?[_]:[];g.length&&h.set("tags",g.join(","));const f=await tn(e.serverUrl,`/paywall/v1/products?${h.toString()}`,e.apiKey),{products:w,total:j}=Co(f);return{items:w.map(qr),page:d,pageSize:m,total:j,hasNextPage:typeof j=="number"?p+u<j:w.length===u}},getProductBySlug:async l=>{try{const d=await tn(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(l)}`,e.apiKey);return qr(d)}catch(d){const m=d?.status;if(m!==404&&m!==405)throw d;try{const u=await tn(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(l)}`,e.apiKey);return qr(u)}catch(u){const p=u?.status;if(p!==404&&p!==405)throw u;const h=await tn(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:_}=Co(h),g=_.find(f=>f.slug===l||f.id===l);return g?qr(g):null}}},listCategories:async()=>{const l=await tn(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=Co(l),m=new Set;for(const u of d)for(const p of u.categoryIds??[])m.add(p);return Array.from(m).map(u=>({id:u,slug:u,name:nd(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await tn(e.serverUrl,"/admin/config/shop",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([tn(e.serverUrl,"/admin/config/stripe",e.apiKey),tn(e.serverUrl,"/admin/config/x402",e.apiKey),tn(e.serverUrl,"/admin/config/cedros_login",e.apiKey)]),u=l.status==="fulfilled"?!!l.value?.config?.enabled:!1,p=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:p,credits:h}}catch{return null}},getAIRelatedProducts:async l=>{const d={"Content-Type":"application/json"};e.apiKey&&(d["X-API-Key"]=e.apiKey);const m=await fetch(`${e.serverUrl}/admin/ai/related-products`,{method:"POST",headers:d,body:JSON.stringify(l)});if(!m.ok){const u=await m.text().catch(()=>"");throw new Error(`AI related products request failed (${m.status}): ${u}`)}return m.json()}}}function Qh(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function Sn(e){return`${e.productId}::${e.variantId??""}`}const Yh={items:[]};function Kh(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const r=Math.max(1,Math.floor(t.qty??1)),s=Sn(t.item);return e.items.find(a=>Sn(a)===s)?{...e,items:e.items.map(a=>Sn(a)===s?{...a,qty:a.qty+r}:a)}:{...e,items:[...e.items,{...t.item,qty:r}]}}case"cart/remove":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(s=>Sn(s)!==r)}}case"cart/setQty":{const r=Math.max(0,Math.floor(t.qty)),s=`${t.productId}::${t.variantId??""}`;return r===0?{...e,items:e.items.filter(o=>Sn(o)!==s)}:{...e,items:e.items.map(o=>Sn(o)===s?{...o,qty:r}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(s=>Sn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return Qh(t)}}function Xh(e){return e.reduce((t,r)=>t+r.qty,0)}function Jh(e){return e.reduce((t,r)=>t+r.qty*r.unitPrice,0)}function nc(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function eg(e,t){try{const r=e.getItem(t);return r?JSON.parse(r):null}catch{return null}}function tg(e,t,r){try{e.setItem(t,JSON.stringify(r))}catch{}}const rd=y.createContext(null);function Dt(){const e=y.useContext(rd);if(!e)throw new Error("useCart must be used within CartProvider");return e}function ng({children:e}){const{config:t}=Re(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=y.useReducer(Kh,Yh),[d,m]=y.useState(!1),u=y.useRef(!1),p=y.useRef(null);y.useEffect(()=>{const f=nc();if(!f)return;const w=eg(f,r);w&&Array.isArray(w.items)&&l({type:"cart/hydrate",state:w}),m(!0)},[r]),y.useEffect(()=>{const f=nc();f&&tg(f,r,c)},[c,r]),y.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const f=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});f&&Array.isArray(f.items)&&(l({type:"cart/hydrate",state:f}),p.current=JSON.stringify(f))}catch{}})()))},[t.adapter,s,d,o,c]),y.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const f=JSON.stringify(c);if(p.current===f)return;const w=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{p.current=f}).catch(()=>{})},a);return()=>window.clearTimeout(w)},[t.adapter,s,d,o,c,a]);const h=y.useCallback((f,w)=>{const j=c.items.find(b=>b.productId===f&&b.variantId===w);if(j)return{holdId:j.holdId,expiresAt:j.holdExpiresAt}},[c.items]),_=y.useCallback((f,w,j)=>{l({type:"cart/updateHold",productId:f,variantId:w,holdExpiresAt:j})},[]),g=y.useMemo(()=>{const f=Xh(c.items),w=Jh(c.items);return{items:c.items,promoCode:c.promoCode,count:f,subtotal:w,addItem:(j,b)=>l({type:"cart/add",item:j,qty:b}),removeItem:(j,b)=>l({type:"cart/remove",productId:j,variantId:b}),setQty:(j,b,v)=>l({type:"cart/setQty",productId:j,variantId:b,qty:v}),clear:()=>l({type:"cart/clear"}),setPromoCode:j=>l({type:"cart/setPromoCode",promoCode:j}),holdsSupported:i,getItemHold:h,updateItemHold:_}},[c.items,c.promoCode,i,h,_]);return n.jsx(rd.Provider,{value:g,children:e})}function G(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const p=m[u];p in c||(c[p]=d[p].bind(c))}}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=r?.Parent?new a:this;s(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Kn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class sd extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const od={};function An(e){return od}function ad(e){const t=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,o])=>t.indexOf(+s)===-1).map(([s,o])=>o)}function ea(e,t){return typeof t=="bigint"?t.toString():t}function Ma(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Da(e){return e==null}function La(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function rg(e,t){const r=(e.toString().split(".")[1]||"").length,s=t.toString();let o=(s.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(s)){const l=s.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=r>o?r:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const rc=Symbol("evaluating");function Ce(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==rc)return s===void 0&&(s=rc,s=r()),s},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function zn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function yn(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}function sc(e){return JSON.stringify(e)}function sg(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const id="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const og=Ma(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Pr(e){if(gs(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(gs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function cd(e){return Pr(e)?{...e}:Array.isArray(e)?[...e]:e}const ag=new Set(["string","number","symbol"]);function Os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function me(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 ig(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const cg={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 lg(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=yn(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return zn(this,"shape",i),i},checks:[]});return vn(e,a)}function dg(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=yn(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return zn(this,"shape",i),i},checks:[]});return vn(e,a)}function ug(e,t){if(!Pr(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=yn(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return zn(this,"shape",a),a}});return vn(e,o)}function mg(e,t){if(!Pr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return zn(this,"shape",s),s}});return vn(e,r)}function pg(e,t){const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return zn(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return vn(e,r)}function fg(e,t,r){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=yn(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(r)for(const d in r){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return zn(this,"shape",l),l},checks:[]});return vn(t,i)}function hg(e,t,r){const s=yn(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(r)for(const i in r){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return zn(this,"shape",a),a}});return vn(t,s)}function Yn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ld(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Hr(e){return typeof e=="string"?e:e?.message}function En(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Hr(e.inst?._zod.def?.error?.(e))??Hr(t?.error?.(e))??Hr(r.customError?.(e))??Hr(r.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function $a(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ar(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const dd=(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,ea,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ud=G("$ZodError",dd),md=G("$ZodError",dd,{Parent:Error});function gg(e,t=r=>r.message){const r={},s=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):s.push(t(o));return{formErrors:s,fieldErrors:r}}function xg(e,t=r=>r.message){const r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)r._errors.push(t(a));else{let i=r,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(t(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(e),r}const za=e=>(t,r,s,o)=>{const a=s?Object.assign(s,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Kn;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>En(l,a,An())));throw id(c,o?.callee),c}return i.value},Fa=e=>async(t,r,s,o)=>{const a=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>En(l,a,An())));throw id(c,o?.callee),c}return i.value},Ms=e=>(t,r,s)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Kn;return a.issues.length?{success:!1,error:new(e??ud)(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},yg=Ms(md),Ds=e=>async(t,r,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},vg=Ds(md),bg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return za(e)(t,r,o)},wg=e=>(t,r,s)=>za(e)(t,r,s),_g=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Fa(e)(t,r,o)},jg=e=>async(t,r,s)=>Fa(e)(t,r,s),kg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ms(e)(t,r,o)},Sg=e=>(t,r,s)=>Ms(e)(t,r,s),Cg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ds(e)(t,r,o)},Ng=e=>async(t,r,s)=>Ds(e)(t,r,s),Pg=/^[cC][^\s-]{8,}$/,Ag=/^[0-9a-z]+$/,Eg=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Tg=/^[0-9a-vA-V]{20}$/,Ig=/^[A-Za-z0-9]{27}$/,Rg=/^[a-zA-Z0-9_-]{21}$/,Og=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Mg=/^([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})$/,oc=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)$/,Dg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Lg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $g(){return new RegExp(Lg,"u")}const zg=/^(?:(?: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])$/,Fg=/^(([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}|:))$/,Bg=/^((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])$/,Ug=/^(([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])$/,Wg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,pd=/^[A-Za-z0-9_-]*$/,Vg=/^\+[1-9]\d{6,14}$/,fd="(?:(?:\\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])))",qg=new RegExp(`^${fd}$`);function hd(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 Hg(e){return new RegExp(`^${hd(e)}$`)}function Zg(e){const t=hd({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${fd}T(?:${s})$`)}const Gg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Qg=/^-?\d+$/,Yg=/^-?\d+(?:\.\d+)?$/,Kg=/^[^A-Z]*$/,Xg=/^[^a-z]*$/,ht=G("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),gd={number:"number",bigint:"bigint",object:"date"},xd=G("$ZodCheckLessThan",(e,t)=>{ht.init(e,t);const r=gd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yd=G("$ZodCheckGreaterThan",(e,t)=>{ht.init(e,t);const r=gd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Jg=G("$ZodCheckMultipleOf",(e,t)=>{ht.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):rg(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ex=G("$ZodCheckNumberFormat",(e,t)=>{ht.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=cg[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,r&&(c.pattern=Qg)}),e._zod.check=i=>{const c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>a&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),tx=G("$ZodCheckMaxLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const o=s.value;if(o.length<=t.maximum)return;const i=$a(o);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),nx=G("$ZodCheckMinLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const o=s.value;if(o.length>=t.minimum)return;const i=$a(o);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),rx=G("$ZodCheckLengthEquals",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=s=>{const o=s.value,a=o.length;if(a===t.length)return;const i=$a(o),c=a>t.length;s.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),Ls=G("$ZodCheckStringFormat",(e,t)=>{var r,s;ht.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),sx=G("$ZodCheckRegex",(e,t)=>{Ls.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ox=G("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Kg),Ls.init(e,t)}),ax=G("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Xg),Ls.init(e,t)}),ix=G("$ZodCheckIncludes",(e,t)=>{ht.init(e,t);const r=Os(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(s)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),cx=G("$ZodCheckStartsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`^${Os(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),lx=G("$ZodCheckEndsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`.*${Os(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),dx=G("$ZodCheckOverwrite",(e,t)=>{ht.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class ux{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
|
|
53
|
+
- Include relevant keywords naturally for SEO`}],ah=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],Ji={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:Jo.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function ql({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("api-keys"),[a,i]=y.useState(Ji),[c,l]=y.useState(!0),[d,m]=y.useState(!1),[u,p]=y.useState(null),[h,_]=y.useState(!1),[g,f]=y.useState(null),w=y.useRef(null),[j,v]=y.useState({gemini:"",openai:""}),[b,k]=y.useState({gemini:!1,openai:!1}),R=y.useCallback(async()=>{try{let A;if(r?.isAuthenticated())A=await r.fetchWithAuth("/admin/config/ai");else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch: ${B.status}`);A=await B.json()}A.settings&&i(A.settings)}catch{i(Ji),f("Could not load saved AI settings. Showing defaults.")}finally{l(!1)}},[e,t,r]);y.useEffect(()=>{R()},[R]);const N=y.useCallback(async A=>{const I=j[A];if(I.trim()){m(!0),p(null);try{const B={provider:A,apiKey:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,apiKeys:D.apiKeys.map(E=>E.provider===A?{...E,isConfigured:!0,maskedKey:`${I.slice(0,4)}...${I.slice(-4)}`,updatedAt:new Date().toISOString()}:E)})),v(D=>({...D,[A]:""})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save API key")}finally{m(!1)}}},[j,e,t,r]),C=y.useCallback(async A=>{if(confirm(`Are you sure you want to delete the ${A==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),p(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${A}`,{method:"DELETE"});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai/api-key/${A}`,{method:"DELETE",headers:I});if(!B.ok)throw new Error(`Failed to delete: ${B.status}`)}i(I=>({...I,apiKeys:I.apiKeys.map(B=>B.provider===A?{provider:A,isConfigured:!1}:B)}))}catch(I){p(I instanceof Error?I.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),T=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,model:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,assignedModel:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),O=y.useCallback(A=>{if(A==="not_set")return!0;const I=jo.find(D=>D.id===A);return I?.provider?a.apiKeys.find(D=>D.provider===I.provider)?.isConfigured??!1:!0},[a.apiKeys]),$=y.useMemo(()=>jo.map(A=>{const I=O(A.id);return{value:A.id,label:I?A.label:`${A.label} (API key required)`,disabled:!I}}),[O]),S=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,systemPrompt:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,systemPrompt:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return y.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),n.jsx(Yt,{message:g,onRetry:R}),h&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[Q.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:ah.map(A=>{const I=a.apiKeys.find(D=>D.provider===A.id),B=I?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:A.label}),B&&I?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",I.maskedKey,I.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(I.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${B?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:B?"Configured":"Not Set"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:b[A.id]?"text":"password",className:"cedros-admin__input",placeholder:B?"Enter new key to replace":A.placeholder,value:j[A.id],onChange:D=>v(E=>({...E,[A.id]:D.target.value})),onBlur:()=>{j[A.id].trim()&&N(A.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>k(D=>({...D,[A.id]:!D[A.id]})),title:b[A.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:b[A.id]?Q.eyeOff:Q.eye}),B&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(A.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:Q.trash})]})})]},A.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(D=>D.task===A.task),B=jo.find(D=>D.id===A.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:I?.label??A.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:I?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ot,{value:A.assignedModel,onChange:D=>T(A.task,D),options:$,label:"",disabled:d,style:{flex:1,maxWidth:280}}),B&&B.provider&&n.jsx("span",{className:`cedros-admin__badge ${O(B.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:O(B.id)?"Ready":"Missing API Key"})]})]},A.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(B=>B.task===A.task);return n.jsx(ih,{task:A.task,label:I?.label??A.task,description:I?.description??"",initialPrompt:A.systemPrompt??"",onSave:S},A.task)})})]})]})}function ih({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=y.useState(s),[c,l]=y.useState("idle"),d=y.useRef(null),m=y.useRef(null),u=y.useRef(!0);return y.useEffect(()=>{if(u.current){u.current=!1;return}return d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),l("pending"),d.current=setTimeout(async()=>{l("saving");try{await o(e,a),l("saved"),m.current=setTimeout(()=>l("idle"),2e3)}catch{l("error")}},1500),()=>{d.current&&clearTimeout(d.current)}},[a,e,o]),y.useEffect(()=>()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current)},[]),n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:t}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:r})]}),n.jsx(ch,{status:c})]}),n.jsx("textarea",{className:"cedros-admin__input",value:a,onChange:p=>i(p.target.value),placeholder:"Enter system prompt...",rows:4,style:{width:"100%",resize:"vertical",fontFamily:"inherit",minHeight:100}})]})}function ch({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const lh=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:ql},Symbol.toStringTag,{value:"Module"}));function qn({href:e,children:t}){return n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:t})}const ec=[{id:"stripe",label:"Stripe",category:"stripe",description:n.jsxs(n.Fragment,{children:["Configure your Stripe integration for card payments. Get your API keys from the"," ",n.jsx(qn,{href:"https://dashboard.stripe.com/apikeys",children:"Stripe Dashboard"}),"."]})},{id:"crypto",label:"Crypto",category:"x402",description:n.jsxs(n.Fragment,{children:["Configure Solana wallet and token settings for crypto payments. Get a fast RPC endpoint from"," ",n.jsx(qn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(qn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(qn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(qn,{href:"https://solflare.com",children:"Solflare"})," wallet."]})},{id:"credits",label:"Credits",category:"cedros_login",description:n.jsxs(n.Fragment,{children:["Configure Cedros Login integration for credits payments. See the"," ",n.jsx(qn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function Hl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("stripe"),a=ec.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__payment-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Payment Options"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure payment methods including Stripe, crypto, and credits."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:ec.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(Ul,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description,showEnabledToggle:!0},a.category)})]})}const dh=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:Hl},Symbol.toStringTag,{value:"Module"})),ko={email_enabled:!1,smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function Zl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("messages"),[a,i]=y.useState(ko),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),[h,_]=y.useState(new Set),g=y.useCallback(async()=>{try{p(null);let b;const k="/admin/config/messaging";if(r?.isAuthenticated())b=await r.fetchWithAuth(k);else{const R={"Content-Type":"application/json"};t&&(R["X-API-Key"]=t);const N=await fetch(`${e}${k}`,{headers:R});if(!N.ok)throw new Error(`Failed to fetch: ${N.status}`);b=await N.json()}i({...ko,...b.config})}catch{i(ko),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{g()},[g]);const f=y.useCallback(async b=>{const k="/admin/config/messaging",R={...b};h.has("smtp_password")||delete R.smtp_password,h.has("webhook_secret")||delete R.webhook_secret;const N=JSON.stringify({config:R});try{if(r?.isAuthenticated())await r.fetchWithAuth(k,{method:"PUT",body:N});else{const C={"Content-Type":"application/json"};t&&(C["X-API-Key"]=t);const T=await fetch(`${e}${k}`,{method:"PUT",headers:C,body:N});if(!T.ok)throw new Error(`Failed to save: ${T.status}`)}}catch{throw p("Failed to save messaging settings"),new Error("Save failed")}},[e,t,r,h]),{status:w,error:j}=Ta({data:a,onSave:f,debounceMs:1500,enabled:!d}),v=(b,k)=>{(b==="smtp_password"||b==="webhook_secret")&&_(R=>new Set(R).add(b)),i(R=>({...R,[b]:k}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[Q.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(uh,{status:w,error:j})]}),n.jsx(Yt,{message:u,onRetry:g}),n.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[s==="messages"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.email_enabled,onChange:()=>v("email_enabled",!a.email_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.webhook_enabled,onChange:()=>v("webhook_enabled",!a.webhook_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),s==="email"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure your email provider for sending customer notifications."}),!a.email_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:b=>v("smtp_host",b.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:b=>v("smtp_port",parseInt(b.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:b=>v("smtp_username",b.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("smtp_password")?a.smtp_password:"",onChange:b=>v("smtp_password",b.target.value),placeholder:a.smtp_password?"••••••••":"Enter password",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),n.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:b=>v("from_email",b.target.value),placeholder:"orders@yourstore.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:b=>v("from_name",b.target.value),placeholder:"Your Store",disabled:!a.email_enabled})]})]})]}),s==="webhooks"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:b=>v("webhook_url",b.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("webhook_secret")?a.webhook_secret:"",onChange:b=>v("webhook_secret",b.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:b=>v("webhook_timeout",parseInt(b.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function uh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function tc({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:t,style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const mh=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:Zl},Symbol.toStringTag,{value:"Module"}));function Gl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(null),[p,h]=y.useState(!1),[_,g]=y.useState(""),[f,w]=y.useState("all"),[j,v]=y.useState(null),[b,k]=y.useState(null),[R,N]=y.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),C=y.useCallback(async()=>{c(!0);try{k(null);let z;const Z=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())z=await s.fetchWithAuth(Z);else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{headers:K});if(!L.ok)throw new Error(`Failed to fetch FAQs: ${L.status}`);z=await L.json()}a(z.faqs||[])}catch{a([]),k("Failed to load FAQs")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{C()},[C]);const T=async z=>{if(z.preventDefault(),!(!R.question.trim()||!R.answer.trim())){h(!0);try{const Z=R.keywordsCsv.split(",").map(L=>L.trim().toLowerCase()).filter(Boolean),K={question:R.question.trim(),answer:R.answer.trim(),keywords:Z,active:R.active,useInChat:R.useInChat,displayOnPage:R.displayOnPage};if(m){const L=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(L,{method:"PUT",body:JSON.stringify(K)});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const Y=await fetch(`${e}${L}`,{method:"PUT",headers:W,body:JSON.stringify(K)});if(!Y.ok)throw new Error(`Failed to update FAQ: ${Y.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}/admin/faqs`,{method:"POST",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to create FAQ: ${W.status}`)}S(),C()}catch{k(m?"Failed to update FAQ":"Failed to create FAQ")}finally{h(!1)}}},O=async z=>{try{const Z=`/admin/faqs/${z}`;if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"DELETE"});else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{method:"DELETE",headers:K});if(!L.ok)throw new Error(`Failed to delete FAQ: ${L.status}`)}C()}catch{k("Failed to delete FAQ")}v(null)},$=async z=>{try{const Z=`/admin/faqs/${z.id}`,K={...z,active:!z.active};if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"PUT",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}${Z}`,{method:"PUT",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to update FAQ: ${W.status}`)}C()}catch{k("Failed to update FAQ status")}},S=()=>{N({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},A=z=>{N({question:z.question,answer:z.answer,keywordsCsv:z.keywords.join(", "),active:z.active,useInChat:z.useInChat??!0,displayOnPage:z.displayOnPage??!0}),u(z),d(!0)},I=o.length,B=o.filter(z=>z.active).length,D=o.filter(z=>z.active&&z.useInChat).length,E=o.filter(z=>z.active&&z.displayOnPage).length,P=y.useMemo(()=>o.filter(z=>{if(f==="active"&&!z.active||f==="inactive"&&z.active)return!1;if(_){const Z=_.toLowerCase();return z.question.toLowerCase().includes(Z)||z.answer.toLowerCase().includes(Z)||z.keywords.some(K=>K.includes(Z))}return!0}),[o,f,_]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(Yt,{message:b,onRetry:C}),n.jsx(rr,{stats:[{label:"Total FAQs",value:I},{label:"Active",value:B,variant:"success"},{label:"In Chat",value:D},{label:"On Page",value:E}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary",onClick:()=>{S(),d(!0)},children:[Q.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:_,onChange:z=>g(z.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:f,onChange:z=>w(z.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:T,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__button--icon",onClick:S,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:R.question,onChange:z=>N(Z=>({...Z,question:z.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),n.jsx("textarea",{value:R.answer,onChange:z=>N(Z=>({...Z,answer:z.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),n.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),n.jsx("input",{type:"text",value:R.keywordsCsv,onChange:z=>N(Z=>({...Z,keywordsCsv:z.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),n.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.active,onChange:z=>N(Z=>({...Z,active:z.target.checked}))}),n.jsx("span",{children:"Active"})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),n.jsxs("div",{className:"cedros-admin__checkbox-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.useInChat,onChange:z=>N(Z=>({...Z,useInChat:z.target.checked}))}),n.jsx("span",{children:"Use in AI Chat"})]}),n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.displayOnPage,onChange:z=>N(Z=>({...Z,displayOnPage:z.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__button",onClick:S,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:p||!R.question.trim()||!R.answer.trim(),children:p?Q.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading,n.jsx("span",{children:"Loading FAQs..."})]}):P.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:_||f!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:P.map(z=>n.jsxs("div",{className:`cedros-admin__faq-item ${z.active?"":"cedros-admin__faq-item--inactive"}`,children:[n.jsxs("div",{className:"cedros-admin__faq-content",children:[n.jsxs("div",{className:"cedros-admin__faq-question",children:[n.jsx("span",{className:`cedros-admin__status-dot ${z.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),z.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:z.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[z.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:z.keywords.map(Z=>n.jsx("span",{className:"cedros-admin__tag",children:Z},Z))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[z.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[Q.chat," Chat"]}),z.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[Q.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__button--icon",onClick:()=>$(z),title:z.active?"Deactivate":"Activate",children:z.active?Q.eyeOff:Q.eye}),n.jsx("button",{className:"cedros-admin__button--icon",onClick:()=>A(z),title:"Edit",children:Q.edit}),n.jsx("button",{className:"cedros-admin__button--icon cedros-admin__btn--danger",onClick:()=>v(z.id),title:"Delete",children:Q.trash})]}),j===z.id&&n.jsx("div",{className:"cedros-admin__confirm-overlay",children:n.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[n.jsx("p",{children:"Delete this FAQ?"}),n.jsxs("div",{className:"cedros-admin__confirm-actions",children:[n.jsx("button",{className:"cedros-admin__button",onClick:()=>v(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--danger",onClick:()=>O(z.id),children:"Delete"})]})]})})]},z.id))})]})]})}const ph=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:Gl},Symbol.toStringTag,{value:"Module"}));class Ql{serverUrl;walletSigner=null;jwtToken=null;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,J.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,J.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=Zi.bs58.encode(this.walletSigner.publicKey.toBytes()),i=Zi.bs58.encode(o);return{"X-Signer":a,"X-Message":r.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const r=`${this.serverUrl}/paywall/v1/nonce`;J.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await J.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!s.ok){const o=await s.text();throw new Error(`Failed to fetch nonce: ${s.status} ${o}`)}return await s.json()}async fetchWithAuth(t,r={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,r.method||"GET"),a=await this.createAuthHeaders(o),i={"Content-Type":"application/json",...r.headers||{},...a},c=await J.fetchWithTimeout(`${this.serverUrl}${t}`,{...r,headers:i});if(!c.ok){const l=await c.text();throw new Error(`Admin API error ${c.status}: ${l}`)}return await c.json()}getPurposeFromPath(t,r){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[r])return o[r];if(t.startsWith("/admin/products/")){if(r==="PUT")return"admin_products_update";if(r==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(r==="PUT")return"admin_coupons_update";if(r==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(r==="GET")return"admin_config_get";if(r==="PUT")return"admin_config_update";if(r==="PATCH")return"admin_config_patch"}return`admin_${r.toLowerCase()}`}}function fh({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=ja.useWallet(),o=y.useMemo(()=>{const u=new Ql(e);return u.setCedrosLoginAuth(t??null,r),u},[e,t,r]);y.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!t,d=y.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=y.useCallback((u,p)=>o.fetchWithAuth(u,p),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const Yl=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions},{id:"products",label:"Products",icon:Q.products},{id:"subscriptions",label:"Subscriptions",icon:Q.calendarRepeat},{id:"coupons",label:"Coupons",icon:Q.coupons},{id:"refunds",label:"Refunds",icon:Q.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:Q.storefront},{id:"ai-settings",label:"Store AI",icon:Q.brain},{id:"faqs",label:"Knowledge Base",icon:Q.faq},{id:"payment-settings",label:"Payment Options",icon:Q.creditCard},{id:"messaging",label:"Store Messages",icon:Q.mail},{id:"settings",label:"Store Server",icon:Q.server}]}],hh=Yl.flatMap(e=>e.sections);function gh(){const[e,t]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return y.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=o=>t(o.matches?"dark":"light");return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[]),e}function xh(e,t,r){return e!=="system"?e:t||r}function yh({serverUrl:e,apiKey:t,title:r="Cedros Pay",sections:s=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:m=!1,theme:u="system"}){const[p,h]=y.useState(o),[_,g]=y.useState(!0),[f,w]=y.useState(new Set),j=y.useCallback($=>{w(S=>{const A=new Set(S);return A.has($)?A.delete($):A.add($),A})},[]),v=J.useCedrosThemeOptional(),b=gh(),R=xh(u,v?.mode??null,b)==="dark"?"cedros-admin--dark":"",{authManager:N}=fh({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),C=y.useCallback($=>{h($),c?.($)},[c]),O=hh.filter($=>s.includes($.id)).find($=>$.id===p);return y.useEffect(()=>{const $=setTimeout(()=>g(!1),500);return()=>clearTimeout($)},[]),_?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${R} ${l}`,children:[Q.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${R} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[Q.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:Yl.map($=>{const S=$.sections.filter(I=>s.includes(I.id));if(S.length===0)return null;const A=$.collapsible&&f.has($.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[$.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>j($.label),"aria-expanded":!A,children:[$.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${A?"":"cedros-admin__nav-label-icon--expanded"}`,children:Q.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:$.label}),!A&&S.map(I=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${p===I.id?"cedros-admin__nav-item--active":""}`,onClick:()=>C(I.id),"aria-current":p===I.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:I.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:I.label})]},I.id))]},$.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:Q.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:O?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[p==="products"&&n.jsx(Ll,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="subscriptions"&&n.jsx(Wl,{serverUrl:e,apiKey:t,authManager:N}),p==="transactions"&&n.jsx($l,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="coupons"&&n.jsx(zl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="refunds"&&n.jsx(Fl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="storefront"&&n.jsx(Vl,{serverUrl:e,apiKey:t,authManager:N}),p==="ai-settings"&&n.jsx(ql,{serverUrl:e,apiKey:t,authManager:N}),p==="faqs"&&n.jsx(Gl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="payment-settings"&&n.jsx(Hl,{serverUrl:e,apiKey:t,authManager:N}),p==="messaging"&&n.jsx(Zl,{serverUrl:e,apiKey:t,authManager:N}),p==="settings"&&n.jsx(Ia,{serverUrl:e,apiKey:t,authManager:N})]})]})]})}const Pt=e=>y.lazy(async()=>{const s=(await e()).default;return{default:({pluginContext:a})=>{const c=cf.useCedrosLogin()?._internal?.getAccessToken()??a.getAccessToken(),l=y.useMemo(()=>{const m=new Ql(a.serverUrl);return m.setCedrosLoginAuth(c??null),m},[a.serverUrl,c]),d={serverUrl:a.serverUrl,authManager:l};return n.jsx(s,{...d})}}}),bh={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:Q.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:Q.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:Q.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:Q.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:Q.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:Q.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:Q.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:Q.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:Q.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:Q.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:Pt(()=>Promise.resolve().then(()=>require("./sections-DG4Ws13b.js")).then(e=>({default:e.ProductsSection}))),subscriptions:Pt(()=>Promise.resolve().then(()=>th).then(e=>({default:e.SubscriptionsSection}))),transactions:Pt(()=>Promise.resolve().then(()=>require("./sections-DG4Ws13b.js")).then(e=>({default:e.TransactionsSection}))),coupons:Pt(()=>Promise.resolve().then(()=>require("./sections-DG4Ws13b.js")).then(e=>({default:e.CouponsSection}))),refunds:Pt(()=>Promise.resolve().then(()=>require("./sections-DG4Ws13b.js")).then(e=>({default:e.RefundsSection}))),storefront:Pt(()=>Promise.resolve().then(()=>oh).then(e=>({default:e.StorefrontSection}))),"ai-settings":Pt(()=>Promise.resolve().then(()=>lh).then(e=>({default:e.AISettingsSection}))),faqs:Pt(()=>Promise.resolve().then(()=>ph).then(e=>({default:e.FAQSection}))),"payment-settings":Pt(()=>Promise.resolve().then(()=>dh).then(e=>({default:e.PaymentSettingsSection}))),messaging:Pt(()=>Promise.resolve().then(()=>mh).then(e=>({default:e.MessagingSection}))),settings:Pt(()=>Promise.resolve().then(()=>Xf).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,r=e.cedrosLogin;return{serverUrl:t?.serverUrl||r?.serverUrl||"",userId:r?.user?.id,getAccessToken:()=>r?.getAccessToken?.()||t?.jwtToken||null,hasPermission:o=>this.checkPermission(o,e),orgId:e.org?.orgId,pluginData:{walletAddress:t?.walletAddress}}},checkPermission(e,t){return t.org?.permissions?t.org.permissions.includes(e):!!(t.cedrosLogin?.user||t.cedrosPay?.jwtToken||t.cedrosPay?.walletAddress)},cssNamespace:"cedros-dashboard"};function vh({product:e,paymentMethod:t,showOriginalPrice:r=!1,className:s="",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,m=a?e.stripeDiscountPercent:e.cryptoDiscountPercent;return n.jsxs("div",{className:s,style:o,children:[r&&d&&n.jsxs("span",{style:{textDecoration:"line-through",opacity:.6,marginRight:"0.5rem",fontSize:"0.875em"},children:[i.toFixed(2)," ",l]}),n.jsxs("span",{style:{fontWeight:600},children:[c.toFixed(2)," ",l]}),d&&m>0&&n.jsxs("span",{style:{marginLeft:"0.5rem",padding:"0.125rem 0.375rem",backgroundColor:"#10b981",color:"white",borderRadius:"0.25rem",fontSize:"0.75em",fontWeight:600},children:[m,"% OFF"]})]})}function wh({product:e,paymentMethod:t,className:r="",style:s={}}){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 n.jsxs("div",{className:r,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,...s},children:[l,c&&n.jsxs("span",{style:{marginLeft:"0.5rem",opacity:.8,fontSize:"0.75em",fontWeight:400},children:["(",c,")"]})]})}function Kl(){const{subscriptionManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=y.useCallback(async c=>{r(d=>({...d,status:"loading",error:null}));const l=await e.processSubscription(c);return r(d=>({...d,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l},[e]),o=y.useCallback(async c=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(c);return r(d=>({...d,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const d=l instanceof Error?l.message:"Failed to check subscription status";throw r(m=>({...m,status:"error",error:d})),l}},[e]),a=y.useCallback(async(c,l,d)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await e.requestSubscriptionQuote(c,l,d);return r(u=>({...u,status:"idle"})),m}catch(m){const u=m instanceof Error?m.message:"Failed to get subscription quote";throw r(p=>({...p,status:"error",error:u})),m}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:s,checkStatus:o,requestQuote:a,reset:i}}function _h({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:m=!1,onAttempt:u,onSuccess:p,onError:h,className:_=""}){const{status:g,error:f,sessionId:w,processSubscription:j}=Kl(),v=J.useCedrosTheme(),{t:b,translations:k}=xn(),R=d||b("ui.subscribe"),N=v.unstyled?_:`${v.className} cedros-theme__stripe-button ${_}`.trim(),C=f&&typeof f!="string"?f?.code??null:null,O=f?typeof f=="string"?f:(D=>{if(!D||!k)return"";const E=k.errors[D];return E?E.action?`${E.message} ${E.action}`:E.message:""})(C):null,$=y.useCallback(async()=>{J.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),Ln("stripe",e),u&&u("stripe"),un("stripe",e);const D=await j({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});D.success&&D.transactionId?($n("stripe",D.transactionId,e),p&&p(D.transactionId)):!D.success&&D.error&&(kt("stripe",D.error,e),h&&h(D.error))},[e,t,r,s,c,i,l,o,a,j,u,p,h]),S=y.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),A=y.useMemo(()=>Mn(S,$),[S,$]),I=g==="loading",B=m||I;return n.jsxs("div",{className:N,style:v.unstyled?{}:v.style,children:[n.jsx("button",{onClick:A,disabled:B,className:v.unstyled?_:"cedros-theme__button cedros-theme__stripe",type:"button",children:I?b("ui.processing"):R}),O&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__error",children:O}),w&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__success",children:b("ui.redirecting_to_checkout")})]})}function Xl(){const{subscriptionManager:e,creditsManager:t}=J.useCedrosContext(),[r,s]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=y.useCallback(async(l,d)=>{s(m=>({...m,status:"checking",error:null}));try{const m=await e.checkSubscriptionStatus({resource:l,userId:d});return s(u=>({...u,status:m.active?"success":"idle",subscriptionStatus:m.status,expiresAt:m.expiresAt||m.currentPeriodEnd||null})),m}catch(m){const u=J.formatError(m,"Failed to check subscription status");return s(p=>({...p,status:"error",error:u})),null}},[e]),a=y.useCallback(async(l,d,m)=>{s(u=>({...u,status:"loading",error:null}));try{const u=await t.requestQuote(l,m?.couponCode);return s(p=>({...p,status:"idle",creditsRequirement:u})),u}catch(u){const p=J.formatError(u,"Failed to get subscription quote");return s(h=>({...h,status:"error",error:p})),null}},[t]),i=y.useCallback(async(l,d,m,u)=>{if(!m){const p="Authentication required for credits payment";return s(h=>({...h,status:"error",error:p})),{success:!1,error:p}}s(p=>({...p,status:"loading",error:null}));try{const p=await t.processPayment(l,m,u?.couponCode,{interval:d,...u?.intervalDays&&{intervalDays:String(u.intervalDays)}});return p.success?s({status:"success",error:null,sessionId:p.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(h=>({...h,status:"error",error:p.error||"Credits subscription payment failed"})),p}catch(p){const h=J.formatError(p,"Credits subscription payment failed");return s(_=>({..._,status:"error",error:h})),{success:!1,error:h}}},[t]),c=y.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:o,requestQuote:a,processPayment:i,reset:c}}function jh({resource:e,interval:t,intervalDays:r,authToken:s,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:m,className:u="",hideMessages:p=!1,autoCheckStatus:h=!1}){const{status:_,error:g,subscriptionStatus:f,expiresAt:w,checkStatus:j,processPayment:v}=Xl(),b=J.useCedrosTheme(),{t:k,translations:R}=xn(),N=y.useRef(j);y.useEffect(()=>{N.current=j},[j]),y.useEffect(()=>{h&&o&&(J.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),N.current(e,o))},[h,o,e]);const C=i||k("ui.subscribe_with_credits")||"Subscribe with Credits",T=g&&typeof g!="string"?g?.code??null:null,$=g?typeof g=="string"?g:(Z=>{if(!Z||!R)return"";const K=R.errors[Z];return K?K.action?`${K.message} ${K.action}`:K.message:""})(T):null,S=y.useCallback(async()=>{if(J.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),Ln("credits",e),l&&l("credits"),!s){const K="Authentication required: please log in to subscribe with credits";J.getLogger().error("[CreditsSubscribeButton]",K),kt("credits",K,e),m&&m(K);return}un("credits",e);const Z=await v(e,t,s,{couponCode:a,intervalDays:r});Z.success&&Z.transactionId?($n("credits",Z.transactionId,e),d&&d(Z.transactionId)):!Z.success&&Z.error&&(kt("credits",Z.error,e),m&&m(Z.error))},[e,t,r,s,a,v,l,d,m]),A=y.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),I=y.useMemo(()=>Mn(A,S,{cooldownMs:200,deduplicationWindowMs:0}),[A,S]),B=_==="loading"||_==="checking",D=f==="active"||f==="trialing",E=c||B||D;let P=C;if(B)P=k("ui.processing");else if(D&&w){const Z=new Date(w).toLocaleDateString();P=`${k("ui.subscribed_until")} ${Z}`}else D&&(P=k("ui.subscribed"));const z=b.unstyled?u:`${b.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:z,style:b.unstyled?{}:b.style,children:[n.jsx("button",{onClick:I,disabled:E,className:b.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:P}),!p&&$&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__error",children:$}),!p&&D&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__success",children:k("ui.subscription_active")})]})}function Jl(){const{subscriptionChangeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=y.useRef(t);s.current=t;const o=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,p);return r(_=>({..._,status:"success",subscription:h,userId:p})),h}catch(h){const _=h instanceof Error?h.message:"Failed to load subscription";return r(g=>({...g,status:"error",error:_})),null}},[e]),a=y.useCallback(async(u,p,h,_)=>{r(g=>({...g,status:"loading",error:null}));try{const g={currentResource:u,newResource:p,userId:h,newInterval:_},f=await e.previewChange(g);return r(w=>({...w,status:"idle",changePreview:f})),f}catch(g){const f=g instanceof Error?g.message:"Failed to preview change";return r(w=>({...w,status:"error",error:f})),null}},[e]),i=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={currentResource:p.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},g=await e.changeSubscription(_);return g.success?r(f=>({...f,status:"success",subscription:f.subscription?{...f.subscription,resource:g.newResource,interval:g.newInterval,status:g.status}:null,changePreview:null})):r(f=>({...f,status:"error",error:g.error||"Failed to change subscription"})),g}catch(_){const g=_ instanceof Error?_.message:"Failed to change subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),c=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={resource:p.resource,userId:h,immediate:u},g=await e.cancel(_);if(g.success){const f=u?"canceled":p.status;r(w=>({...w,status:"success",subscription:w.subscription?{...w.subscription,status:f,cancelAtPeriodEnd:!u}:null}))}else r(f=>({...f,status:"error",error:g.error||"Failed to cancel subscription"}));return g}catch(_){const g=_ instanceof Error?_.message:"Failed to cancel subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),l=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:p});return window.location.href=h.url,h}catch(h){const _=h instanceof Error?h.message:"Failed to open billing portal";return r(g=>({...g,status:"error",error:_})),null}},[e]),d=y.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=y.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:o,previewChange:a,changeSubscription:i,cancelSubscription:c,openBillingPortal:l,clearPreview:d,reset:m}}const kh={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"},Sh={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 Ch(e){const t=e?Sh:kh;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 Nn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function ed(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function Nh(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 Ph({preview:e,onConfirm:t,onCancel:r,isLoading:s,styles:o}){const a=e.immediateAmount<0;return n.jsxs("div",{className:"cedros-proration-preview",style:o.prorationPreview,children:[n.jsx("h4",{style:o.previewTitle,children:"Change Preview"}),n.jsxs("div",{style:o.previewDetails,children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Current plan:"}),n.jsxs("span",{children:[Nn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[Nn(e.newPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Days remaining:"}),n.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Unused credit:"}),n.jsxs("span",{children:["-",Nn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:Nn(e.prorationDetails.newPlanCost,e.currency)})]})]}),n.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[n.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),n.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:Nn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:ed(e.effectiveDate)})]})]}),n.jsxs("div",{style:o.previewActions,children:[n.jsx("button",{onClick:r,style:o.cancelButton,disabled:s,children:"Cancel"}),n.jsx("button",{onClick:t,style:o.confirmButton,disabled:s,children:s?"Processing...":"Confirm Change"})]})]})}function Ah({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=J.useCedrosTheme(),m=y.useMemo(()=>Ch(d==="dark"),[d]),{subscription:u,changePreview:p,status:h,error:_,loadSubscription:g,previewChange:f,changeSubscription:w,cancelSubscription:j,openBillingPortal:v,clearPreview:b}=Jl();y.useEffect(()=>{g(e,t)},[e,t,g]);const k=y.useCallback(async(O,$)=>{await f(e,O,t,$)},[e,t,f]),R=y.useCallback(async()=>{if(!p)return;const O=r.find(S=>S.price===p.newPlanPrice&&S.currency===p.currency);(await w({newResource:O?.resource||e,newInterval:O?.interval,immediate:!0}))?.success&&O&&s?.(O.resource,O.interval)},[p,r,e,w,s]),N=y.useCallback(async O=>{(await j(O))?.success&&o?.()},[j,o]),C=y.useCallback(()=>{v(t,a)},[t,a,v]),T=h==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[_&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:_}),T&&!u&&n.jsx("div",{className:"cedros-subscription-loading",style:m.loading,children:"Loading subscription..."}),u&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"cedros-subscription-details",style:m.details,children:[n.jsx("h3",{style:m.title,children:"Current Subscription"}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Plan:"}),n.jsx("span",{style:m.value,children:u.resource})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Status:"}),n.jsx("span",{style:{...m.statusBadge,backgroundColor:Nh(u.status)},children:u.status})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Price:"}),n.jsxs("span",{style:m.value,children:[Nn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Current period ends:"}),n.jsx("span",{style:m.value,children:ed(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),p&&n.jsx(Ph,{preview:p,onConfirm:R,onCancel:b,isLoading:T,styles:m}),r.length>0&&!p&&n.jsxs("div",{className:"cedros-available-plans",style:m.plansSection,children:[n.jsx("h4",{style:m.plansTitle,children:"Available Plans"}),n.jsx("div",{style:m.plansList,children:r.map(O=>{const $=O.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...$?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:O.name}),n.jsxs("div",{style:m.planPrice,children:[Nn(O.price,O.currency),"/",O.interval]}),O.description&&n.jsx("div",{style:m.planDescription,children:O.description}),$?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>k(O.resource,O.interval),style:m.changePlanButton,disabled:T,children:O.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},O.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:C,style:m.portalButton,disabled:T,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>N(!1),style:m.cancelSubscriptionButton,disabled:T,children:"Cancel Subscription"})]})]})]})}function Eh(){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 Th(){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 Ih(){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 Rh(){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 Oh(){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 Mh(){const e=[Eh(),Th(),Ih(),Rh(),Oh()],t=e.some(a=>a.severity==="error"&&!a.passed),r=e.some(a=>a.severity==="warning"&&!a.passed);let s,o;return t?(s="vulnerable",o="Security issues detected. Review errors and apply recommendations."):r?(s="warnings",o="Minor security warnings detected. Consider applying recommendations."):(s="secure",o="All security checks passed."),{checks:e,overallStatus:s,summary:o}}function Dh(e){process.env.NODE_ENV!=="production"&&(console.group("🔒 Cedros Pay Security Report"),console.log(`Status: ${e.overallStatus.toUpperCase()}`),console.log(`Summary: ${e.summary}`),console.log(""),e.checks.forEach(t=>{const r=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${r} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const Lh={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"},Ra=y.createContext(null);function Re(){const e=y.useContext(Ra);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function Oa(){return y.useContext(Ra)}function $h({config:e,children:t}){return n.jsx(Ra.Provider,{value:{config:e},children:t})}function At(e){return new Promise(t=>setTimeout(t,e))}const td=[{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."}],hs=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];let So=[];const Vr={};function zh(e,t){let r=e;if(t.category&&t.category!=="all"){const l=td.find(d=>d.slug===t.category||d.id===t.category);l&&(r=r.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();r=r.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const s=t.filters??{},o=s.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));r=r.filter(d=>d.tags?.some(m=>l.has(m)))}const a=typeof s.priceMin=="number"?s.priceMin:void 0,i=typeof s.priceMax=="number"?s.priceMax:void 0;return typeof a=="number"&&(r=r.filter(l=>l.price>=a)),typeof i=="number"&&(r=r.filter(l=>l.price<=i)),(typeof s.inStock=="boolean"?s.inStock:void 0)===!0&&(r=r.filter(l=>l.inventoryStatus!=="out_of_stock")),r}function Fh(e,t){if(!t||t==="featured")return e;const r=[...e];return t==="price_asc"&&r.sort((s,o)=>s.price-o.price),t==="price_desc"&&r.sort((s,o)=>o.price-s.price),r}function Bh(e,t,r){const s=(t-1)*r;return{items:e.slice(s,s+r),page:t,pageSize:r,total:e.length,hasNextPage:s+r<e.length}}function Uh(e){const t=new Date().toISOString(),r=e.cart.map(o=>{const a=hs.find(i=>i.id===o.resource||i.slug===o.resource)??hs[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),s=r.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:s,currency:e.options.currency,items:r,receiptUrl:e.options.successUrl}}function Wh(){return{async listProducts(e){await At(150);const t=e.page??1,r=e.pageSize??24,s=zh(hs,e),o=Fh(s,e.sort);return Bh(o,t,r)},async getProductBySlug(e){return await At(100),hs.find(t=>t.slug===e)??null},async listCategories(){return await At(80),td},async getOrderHistory(){return await At(120),So},async getCart({customerId:e}){return await At(80),Vr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await At(120);const r=Vr[e]??{items:[]},s=new Map,o=i=>{const c=`${i.productId}::${i.variantId??""}`,l=s.get(c);l?s.set(c,{...l,qty:l.qty+i.qty}):s.set(c,i)};for(const i of r.items)o(i);for(const i of t.items)o(i);const a={items:Array.from(s.values()),promoCode:t.promoCode??r.promoCode};return Vr[e]=a,a},async updateCart({customerId:e,cart:t}){await At(60),Vr[e]=t},async createCheckoutSession(e){await At(250);const t=Uh(e);if(So=[t,...So].slice(0,25),e.options.successUrl){const r=new URL(e.options.successUrl,"http://localhost");return r.searchParams.set("demoOrderId",t.id),{kind:"redirect",url:r.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:t.id}}},async listSubscriptionTiers(){return await At(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await At(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await At(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function nd(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Vh(e){return e?e.toUpperCase():"USD"}function qh(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function Hh(e){if(e&&(e==="physical"||e==="digital"))return e}function Zh(e){const t=[];if(Array.isArray(e))for(const r of e)typeof r=="string"&&t.push(r);else if(typeof e=="string"){const r=e.trim();if(r.startsWith("["))try{const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(r=>r.split(",")).map(r=>r.trim().toUpperCase()).filter(Boolean)}function qr(e){const t=Vh(e.fiatCurrency),r=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],s=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=Zh(a);return{id:e.id,slug:e.slug??e.id,title:e.title??nd(e.id),description:e.description??"",images:r,price:s/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:qh(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:Hh(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function Co(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],r=e.total??e.count;return{products:t,total:r}}async function tn(e,t,r){const s={};r&&(s["X-API-Key"]=r);const o=await fetch(`${e}${t}`,{headers:s});if(!o.ok){const a=await o.text().catch(()=>""),i=new Error(`Request failed (${o.status}): ${a}`);throw i.status=o.status,i}return o.json()}function Gh(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,p=(d-1)*m,h=new URLSearchParams;h.set("limit",String(u)),h.set("offset",String(p)),l.search&&h.set("search",l.search),l.category&&h.set("category",l.category),l.sort&&h.set("sort",l.sort),l.filters?.inStock&&h.set("in_stock","true"),l.filters?.minPrice!=null&&h.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&h.set("max_price",String(l.filters.maxPrice));const _=l.filters?.tags,g=Array.isArray(_)?_:typeof _=="string"?[_]:[];g.length&&h.set("tags",g.join(","));const f=await tn(e.serverUrl,`/paywall/v1/products?${h.toString()}`,e.apiKey),{products:w,total:j}=Co(f);return{items:w.map(qr),page:d,pageSize:m,total:j,hasNextPage:typeof j=="number"?p+u<j:w.length===u}},getProductBySlug:async l=>{try{const d=await tn(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(l)}`,e.apiKey);return qr(d)}catch(d){const m=d?.status;if(m!==404&&m!==405)throw d;try{const u=await tn(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(l)}`,e.apiKey);return qr(u)}catch(u){const p=u?.status;if(p!==404&&p!==405)throw u;const h=await tn(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:_}=Co(h),g=_.find(f=>f.slug===l||f.id===l);return g?qr(g):null}}},listCategories:async()=>{const l=await tn(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=Co(l),m=new Set;for(const u of d)for(const p of u.categoryIds??[])m.add(p);return Array.from(m).map(u=>({id:u,slug:u,name:nd(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await tn(e.serverUrl,"/admin/config/shop",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([tn(e.serverUrl,"/admin/config/stripe",e.apiKey),tn(e.serverUrl,"/admin/config/x402",e.apiKey),tn(e.serverUrl,"/admin/config/cedros_login",e.apiKey)]),u=l.status==="fulfilled"?!!l.value?.config?.enabled:!1,p=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:p,credits:h}}catch{return null}},getAIRelatedProducts:async l=>{const d={"Content-Type":"application/json"};e.apiKey&&(d["X-API-Key"]=e.apiKey);const m=await fetch(`${e.serverUrl}/admin/ai/related-products`,{method:"POST",headers:d,body:JSON.stringify(l)});if(!m.ok){const u=await m.text().catch(()=>"");throw new Error(`AI related products request failed (${m.status}): ${u}`)}return m.json()}}}function Qh(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function Sn(e){return`${e.productId}::${e.variantId??""}`}const Yh={items:[]};function Kh(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const r=Math.max(1,Math.floor(t.qty??1)),s=Sn(t.item);return e.items.find(a=>Sn(a)===s)?{...e,items:e.items.map(a=>Sn(a)===s?{...a,qty:a.qty+r}:a)}:{...e,items:[...e.items,{...t.item,qty:r}]}}case"cart/remove":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(s=>Sn(s)!==r)}}case"cart/setQty":{const r=Math.max(0,Math.floor(t.qty)),s=`${t.productId}::${t.variantId??""}`;return r===0?{...e,items:e.items.filter(o=>Sn(o)!==s)}:{...e,items:e.items.map(o=>Sn(o)===s?{...o,qty:r}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(s=>Sn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return Qh(t)}}function Xh(e){return e.reduce((t,r)=>t+r.qty,0)}function Jh(e){return e.reduce((t,r)=>t+r.qty*r.unitPrice,0)}function nc(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function eg(e,t){try{const r=e.getItem(t);return r?JSON.parse(r):null}catch{return null}}function tg(e,t,r){try{e.setItem(t,JSON.stringify(r))}catch{}}const rd=y.createContext(null);function Dt(){const e=y.useContext(rd);if(!e)throw new Error("useCart must be used within CartProvider");return e}function ng({children:e}){const{config:t}=Re(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=y.useReducer(Kh,Yh),[d,m]=y.useState(!1),u=y.useRef(!1),p=y.useRef(null);y.useEffect(()=>{const f=nc();if(!f)return;const w=eg(f,r);w&&Array.isArray(w.items)&&l({type:"cart/hydrate",state:w}),m(!0)},[r]),y.useEffect(()=>{const f=nc();f&&tg(f,r,c)},[c,r]),y.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const f=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});f&&Array.isArray(f.items)&&(l({type:"cart/hydrate",state:f}),p.current=JSON.stringify(f))}catch{}})()))},[t.adapter,s,d,o,c]),y.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const f=JSON.stringify(c);if(p.current===f)return;const w=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{p.current=f}).catch(()=>{})},a);return()=>window.clearTimeout(w)},[t.adapter,s,d,o,c,a]);const h=y.useCallback((f,w)=>{const j=c.items.find(v=>v.productId===f&&v.variantId===w);if(j)return{holdId:j.holdId,expiresAt:j.holdExpiresAt}},[c.items]),_=y.useCallback((f,w,j)=>{l({type:"cart/updateHold",productId:f,variantId:w,holdExpiresAt:j})},[]),g=y.useMemo(()=>{const f=Xh(c.items),w=Jh(c.items);return{items:c.items,promoCode:c.promoCode,count:f,subtotal:w,addItem:(j,v)=>l({type:"cart/add",item:j,qty:v}),removeItem:(j,v)=>l({type:"cart/remove",productId:j,variantId:v}),setQty:(j,v,b)=>l({type:"cart/setQty",productId:j,variantId:v,qty:b}),clear:()=>l({type:"cart/clear"}),setPromoCode:j=>l({type:"cart/setPromoCode",promoCode:j}),holdsSupported:i,getItemHold:h,updateItemHold:_}},[c.items,c.promoCode,i,h,_]);return n.jsx(rd.Provider,{value:g,children:e})}function G(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const p=m[u];p in c||(c[p]=d[p].bind(c))}}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=r?.Parent?new a:this;s(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Kn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class sd extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const od={};function An(e){return od}function ad(e){const t=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,o])=>t.indexOf(+s)===-1).map(([s,o])=>o)}function ea(e,t){return typeof t=="bigint"?t.toString():t}function Ma(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Da(e){return e==null}function La(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function rg(e,t){const r=(e.toString().split(".")[1]||"").length,s=t.toString();let o=(s.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(s)){const l=s.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=r>o?r:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const rc=Symbol("evaluating");function Ce(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==rc)return s===void 0&&(s=rc,s=r()),s},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function zn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function yn(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}function sc(e){return JSON.stringify(e)}function sg(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const id="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const og=Ma(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Pr(e){if(gs(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(gs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function cd(e){return Pr(e)?{...e}:Array.isArray(e)?[...e]:e}const ag=new Set(["string","number","symbol"]);function Os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function me(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 ig(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const cg={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 lg(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=yn(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return zn(this,"shape",i),i},checks:[]});return bn(e,a)}function dg(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=yn(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return zn(this,"shape",i),i},checks:[]});return bn(e,a)}function ug(e,t){if(!Pr(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=yn(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return zn(this,"shape",a),a}});return bn(e,o)}function mg(e,t){if(!Pr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return zn(this,"shape",s),s}});return bn(e,r)}function pg(e,t){const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return zn(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return bn(e,r)}function fg(e,t,r){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=yn(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(r)for(const d in r){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return zn(this,"shape",l),l},checks:[]});return bn(t,i)}function hg(e,t,r){const s=yn(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(r)for(const i in r){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return zn(this,"shape",a),a}});return bn(t,s)}function Yn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ld(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Hr(e){return typeof e=="string"?e:e?.message}function En(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Hr(e.inst?._zod.def?.error?.(e))??Hr(t?.error?.(e))??Hr(r.customError?.(e))??Hr(r.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function $a(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ar(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const dd=(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,ea,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ud=G("$ZodError",dd),md=G("$ZodError",dd,{Parent:Error});function gg(e,t=r=>r.message){const r={},s=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):s.push(t(o));return{formErrors:s,fieldErrors:r}}function xg(e,t=r=>r.message){const r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)r._errors.push(t(a));else{let i=r,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(t(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(e),r}const za=e=>(t,r,s,o)=>{const a=s?Object.assign(s,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Kn;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>En(l,a,An())));throw id(c,o?.callee),c}return i.value},Fa=e=>async(t,r,s,o)=>{const a=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>En(l,a,An())));throw id(c,o?.callee),c}return i.value},Ms=e=>(t,r,s)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Kn;return a.issues.length?{success:!1,error:new(e??ud)(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},yg=Ms(md),Ds=e=>async(t,r,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},bg=Ds(md),vg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return za(e)(t,r,o)},wg=e=>(t,r,s)=>za(e)(t,r,s),_g=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Fa(e)(t,r,o)},jg=e=>async(t,r,s)=>Fa(e)(t,r,s),kg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ms(e)(t,r,o)},Sg=e=>(t,r,s)=>Ms(e)(t,r,s),Cg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ds(e)(t,r,o)},Ng=e=>async(t,r,s)=>Ds(e)(t,r,s),Pg=/^[cC][^\s-]{8,}$/,Ag=/^[0-9a-z]+$/,Eg=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Tg=/^[0-9a-vA-V]{20}$/,Ig=/^[A-Za-z0-9]{27}$/,Rg=/^[a-zA-Z0-9_-]{21}$/,Og=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Mg=/^([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})$/,oc=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)$/,Dg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Lg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $g(){return new RegExp(Lg,"u")}const zg=/^(?:(?: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])$/,Fg=/^(([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}|:))$/,Bg=/^((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])$/,Ug=/^(([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])$/,Wg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,pd=/^[A-Za-z0-9_-]*$/,Vg=/^\+[1-9]\d{6,14}$/,fd="(?:(?:\\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])))",qg=new RegExp(`^${fd}$`);function hd(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 Hg(e){return new RegExp(`^${hd(e)}$`)}function Zg(e){const t=hd({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${fd}T(?:${s})$`)}const Gg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Qg=/^-?\d+$/,Yg=/^-?\d+(?:\.\d+)?$/,Kg=/^[^A-Z]*$/,Xg=/^[^a-z]*$/,gt=G("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),gd={number:"number",bigint:"bigint",object:"date"},xd=G("$ZodCheckLessThan",(e,t)=>{gt.init(e,t);const r=gd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yd=G("$ZodCheckGreaterThan",(e,t)=>{gt.init(e,t);const r=gd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Jg=G("$ZodCheckMultipleOf",(e,t)=>{gt.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):rg(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ex=G("$ZodCheckNumberFormat",(e,t)=>{gt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=cg[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,r&&(c.pattern=Qg)}),e._zod.check=i=>{const c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>a&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),tx=G("$ZodCheckMaxLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const o=s.value;if(o.length<=t.maximum)return;const i=$a(o);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),nx=G("$ZodCheckMinLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const o=s.value;if(o.length>=t.minimum)return;const i=$a(o);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),rx=G("$ZodCheckLengthEquals",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=s=>{const o=s.value,a=o.length;if(a===t.length)return;const i=$a(o),c=a>t.length;s.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),Ls=G("$ZodCheckStringFormat",(e,t)=>{var r,s;gt.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),sx=G("$ZodCheckRegex",(e,t)=>{Ls.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ox=G("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Kg),Ls.init(e,t)}),ax=G("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Xg),Ls.init(e,t)}),ix=G("$ZodCheckIncludes",(e,t)=>{gt.init(e,t);const r=Os(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(s)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),cx=G("$ZodCheckStartsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`^${Os(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),lx=G("$ZodCheckEndsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`.*${Os(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),dx=G("$ZodCheckOverwrite",(e,t)=>{gt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class ux{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
|
|
54
54
|
`).filter(i=>i),o=Math.min(...s.map(i=>i.length-i.trimStart().length)),a=s.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...r,o.join(`
|
|
55
|
-
`))}}const mx={major:4,minor:3,patch:6},Ue=G("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=mx;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const o of s)for(const a of o._zod.onattach)a(e);if(s.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(i,c,l)=>{let d=Yn(i),m;for(const u of c){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(d)continue;const p=i.issues.length,h=u._zod.check(i);if(h instanceof Promise&&l?.async===!1)throw new Kn;if(m||h instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await h,i.issues.length!==p&&(d||(d=Yn(i,p)))});else{if(i.issues.length===p)continue;d||(d=Yn(i,p))}}return m?m.then(()=>i):i},a=(i,c,l)=>{if(Yn(i))return i.aborted=!0,i;const d=o(c,s,l);if(d instanceof Promise){if(l.async===!1)throw new Kn;return d.then(m=>e._zod.parse(m,l))}return e._zod.parse(d,l)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const d=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(m=>a(m,i,c)):a(d,i,c)}const l=e._zod.parse(i,c);if(l instanceof Promise){if(c.async===!1)throw new Kn;return l.then(d=>o(d,s,c))}return o(l,s,c)}}Ce(e,"~standard",()=>({validate:o=>{try{const a=yg(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return
|
|
56
|
-
if (${
|
|
55
|
+
`))}}const mx={major:4,minor:3,patch:6},Ue=G("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=mx;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const o of s)for(const a of o._zod.onattach)a(e);if(s.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(i,c,l)=>{let d=Yn(i),m;for(const u of c){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(d)continue;const p=i.issues.length,h=u._zod.check(i);if(h instanceof Promise&&l?.async===!1)throw new Kn;if(m||h instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await h,i.issues.length!==p&&(d||(d=Yn(i,p)))});else{if(i.issues.length===p)continue;d||(d=Yn(i,p))}}return m?m.then(()=>i):i},a=(i,c,l)=>{if(Yn(i))return i.aborted=!0,i;const d=o(c,s,l);if(d instanceof Promise){if(l.async===!1)throw new Kn;return d.then(m=>e._zod.parse(m,l))}return e._zod.parse(d,l)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const d=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(m=>a(m,i,c)):a(d,i,c)}const l=e._zod.parse(i,c);if(l instanceof Promise){if(c.async===!1)throw new Kn;return l.then(d=>o(d,s,c))}return o(l,s,c)}}Ce(e,"~standard",()=>({validate:o=>{try{const a=yg(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return bg(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ba=G("$ZodString",(e,t)=>{Ue.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Gg(e._zod.bag),e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Te=G("$ZodStringFormat",(e,t)=>{Ls.init(e,t),Ba.init(e,t)}),px=G("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Mg),Te.init(e,t)}),fx=G("$ZodUUID",(e,t)=>{if(t.version){const s={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(s===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=oc(s))}else t.pattern??(t.pattern=oc());Te.init(e,t)}),hx=G("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Dg),Te.init(e,t)}),gx=G("$ZodURL",(e,t)=>{Te.init(e,t),e._zod.check=r=>{try{const s=r.value.trim(),o=new URL(s);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),xx=G("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=$g()),Te.init(e,t)}),yx=G("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Rg),Te.init(e,t)}),bx=G("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Pg),Te.init(e,t)}),vx=G("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ag),Te.init(e,t)}),wx=G("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Eg),Te.init(e,t)}),_x=G("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Tg),Te.init(e,t)}),jx=G("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ig),Te.init(e,t)}),kx=G("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Zg(t)),Te.init(e,t)}),Sx=G("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=qg),Te.init(e,t)}),Cx=G("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Hg(t)),Te.init(e,t)}),Nx=G("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Og),Te.init(e,t)}),Px=G("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=zg),Te.init(e,t),e._zod.bag.format="ipv4"}),Ax=G("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Fg),Te.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ex=G("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Bg),Te.init(e,t)}),Tx=G("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Ug),Te.init(e,t),e._zod.check=r=>{const s=r.value.split("/");try{if(s.length!==2)throw new Error;const[o,a]=s;if(!a)throw new Error;const i=Number(a);if(`${i}`!==a)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function bd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Ix=G("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Wg),Te.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{bd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Rx(e){if(!pd.test(e))return!1;const t=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return bd(r)}const Ox=G("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=pd),Te.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{Rx(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Mx=G("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Vg),Te.init(e,t)});function Dx(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[s]=r;if(!s)return!1;const o=JSON.parse(atob(s));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const Lx=G("$ZodJWT",(e,t)=>{Te.init(e,t),e._zod.check=r=>{Dx(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),vd=G("$ZodNumber",(e,t)=>{Ue.init(e,t),e._zod.pattern=e._zod.bag.pattern??Yg,e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const a=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...a?{received:a}:{}}),r}}),$x=G("$ZodNumberFormat",(e,t)=>{ex.init(e,t),vd.init(e,t)}),zx=G("$ZodUnknown",(e,t)=>{Ue.init(e,t),e._zod.parse=r=>r}),Fx=G("$ZodNever",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function ac(e,t,r){e.issues.length&&t.issues.push(...ld(r,e.issues)),t.value[r]=e.value}const Bx=G("$ZodArray",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const a=[];for(let i=0;i<o.length;i++){const c=o[i],l=t.element._zod.run({value:c,issues:[]},s);l instanceof Promise?a.push(l.then(d=>ac(d,r,i))):ac(l,r,i)}return a.length?Promise.all(a).then(()=>r):r}});function xs(e,t,r,s,o){if(e.issues.length){if(o&&!(r in s))return;t.issues.push(...ld(r,e.issues))}e.value===void 0?r in s&&(t.value[r]=void 0):t.value[r]=e.value}function wd(e){const t=Object.keys(e.shape);for(const s of t)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${s}": expected a Zod schema`);const r=ig(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function _d(e,t,r,s,o,a){const i=[],c=o.keySet,l=o.catchall._zod,d=l.def.type,m=l.optout==="optional";for(const u in t){if(c.has(u))continue;if(d==="never"){i.push(u);continue}const p=l.run({value:t[u],issues:[]},s);p instanceof Promise?e.push(p.then(h=>xs(h,r,u,t,m))):xs(p,r,u,t,m)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:a}),e.length?Promise.all(e).then(()=>r):r}const Ux=G("$ZodObject",(e,t)=>{if(Ue.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}const s=Ma(()=>wd(t));Ce(e._zod,"propValues",()=>{const c=t.shape,l={};for(const d in c){const m=c[d]._zod;if(m.values){l[d]??(l[d]=new Set);for(const u of m.values)l[d].add(u)}}return l});const o=gs,a=t.catchall;let i;e._zod.parse=(c,l)=>{i??(i=s.value);const d=c.value;if(!o(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const m=[],u=i.shape;for(const p of i.keys){const h=u[p],_=h._zod.optout==="optional",g=h._zod.run({value:d[p],issues:[]},l);g instanceof Promise?m.push(g.then(f=>xs(f,c,p,d,_))):xs(g,c,p,d,_)}return a?_d(m,d,c,l,s.value,e):m.length?Promise.all(m).then(()=>c):c}}),Wx=G("$ZodObjectJIT",(e,t)=>{Ux.init(e,t);const r=e._zod.parse,s=Ma(()=>wd(t)),o=p=>{const h=new ux(["shape","payload","ctx"]),_=s.value,g=v=>{const b=sc(v);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};h.write("const input = payload.value;");const f=Object.create(null);let w=0;for(const v of _.keys)f[v]=`key_${w++}`;h.write("const newResult = {};");for(const v of _.keys){const b=f[v],k=sc(v),N=p[v]?._zod?.optout==="optional";h.write(`const ${b} = ${g(v)};`),N?h.write(`
|
|
56
|
+
if (${b}.issues.length) {
|
|
57
57
|
if (${k} in input) {
|
|
58
|
-
payload.issues = payload.issues.concat(${
|
|
58
|
+
payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
|
|
59
59
|
...iss,
|
|
60
60
|
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
61
61
|
})));
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
-
if (${
|
|
65
|
+
if (${b}.value === undefined) {
|
|
66
66
|
if (${k} in input) {
|
|
67
67
|
newResult[${k}] = undefined;
|
|
68
68
|
}
|
|
69
69
|
} else {
|
|
70
|
-
newResult[${k}] = ${
|
|
70
|
+
newResult[${k}] = ${b}.value;
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
`):h.write(`
|
|
74
|
-
if (${
|
|
75
|
-
payload.issues = payload.issues.concat(${
|
|
74
|
+
if (${b}.issues.length) {
|
|
75
|
+
payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
|
|
76
76
|
...iss,
|
|
77
77
|
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
78
78
|
})));
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
-
if (${
|
|
81
|
+
if (${b}.value === undefined) {
|
|
82
82
|
if (${k} in input) {
|
|
83
83
|
newResult[${k}] = undefined;
|
|
84
84
|
}
|
|
85
85
|
} else {
|
|
86
|
-
newResult[${k}] = ${
|
|
86
|
+
newResult[${k}] = ${b}.value;
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
-
`)}h.write("payload.value = newResult;"),h.write("return payload;");const j=h.compile();return(b,v)=>j(p,b,v)};let a;const i=gs,c=!od.jitless,d=c&&og.value,m=t.catchall;let u;e._zod.parse=(p,h)=>{u??(u=s.value);const _=p.value;return i(_)?c&&d&&h?.async===!1&&h.jitless!==!0?(a||(a=o(t.shape)),p=a(p,h),m?_d([],_,p,h,u,e):p):r(p,h):(p.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),p)}});function ic(e,t,r,s){for(const a of e)if(a.issues.length===0)return t.value=a.value,t;const o=e.filter(a=>!Yn(a));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(a=>a.issues.map(i=>En(i,s,An())))}),t)}const Vx=G("$ZodUnion",(e,t)=>{Ue.init(e,t),Ce(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Ce(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Ce(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Ce(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${o.map(a=>La(a.source)).join("|")})$`)}});const r=t.options.length===1,s=t.options[0]._zod.run;e._zod.parse=(o,a)=>{if(r)return s(o,a);let i=!1;const c=[];for(const l of t.options){const d=l._zod.run({value:o.value,issues:[]},a);if(d instanceof Promise)c.push(d),i=!0;else{if(d.issues.length===0)return d;c.push(d)}}return i?Promise.all(c).then(l=>ic(l,o,e,a)):ic(c,o,e,a)}}),qx=G("$ZodIntersection",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>{const o=r.value,a=t.left._zod.run({value:o,issues:[]},s),i=t.right._zod.run({value:o,issues:[]},s);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([l,d])=>cc(r,l,d)):cc(r,a,i)}});function ta(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Pr(e)&&Pr(t)){const r=Object.keys(t),s=Object.keys(e).filter(a=>r.indexOf(a)!==-1),o={...e,...t};for(const a of s){const i=ta(e[a],t[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};o[a]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let s=0;s<e.length;s++){const o=e[s],a=t[s],i=ta(o,a);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function cc(e,t,r){const s=new Map;let o;for(const c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(const l of c.keys)s.has(l)||s.set(l,{}),s.get(l).l=!0}else e.issues.push(c);for(const c of r.issues)if(c.code==="unrecognized_keys")for(const l of c.keys)s.has(l)||s.set(l,{}),s.get(l).r=!0;else e.issues.push(c);const a=[...s].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length&&o&&e.issues.push({...o,keys:a}),Yn(e))return e;const i=ta(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const Hx=G("$ZodEnum",(e,t)=>{Ue.init(e,t);const r=ad(t.entries),s=new Set(r);e._zod.values=s,e._zod.pattern=new RegExp(`^(${r.filter(o=>ag.has(typeof o)).map(o=>typeof o=="string"?Os(o):o.toString()).join("|")})$`),e._zod.parse=(o,a)=>{const i=o.value;return s.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Zx=G("$ZodTransform",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new sd(e.constructor.name);const o=t.transform(r.value,r);if(s.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Kn;return r.value=o,r}});function lc(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const jd=G("$ZodOptional",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${La(r.source)})?$`):void 0}),e._zod.parse=(r,s)=>{if(t.innerType._zod.optin==="optional"){const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>lc(a,r.value)):lc(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,s)}}),Gx=G("$ZodExactOptional",(e,t)=>{jd.init(e,t),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,s)=>t.innerType._zod.run(r,s)}),Qx=G("$ZodNullable",(e,t)=>{Ue.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${La(r.source)}|null)$`):void 0}),Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,s)=>r.value===null?r:t.innerType._zod.run(r,s)}),Yx=G("$ZodDefault",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>dc(a,t)):dc(o,t)}});function dc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Kx=G("$ZodPrefault",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>(s.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,s))}),Xx=G("$ZodNonOptional",(e,t)=>{Ue.init(e,t),Ce(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(s=>s!==void 0)):void 0}),e._zod.parse=(r,s)=>{const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>uc(a,e)):uc(o,e)}});function uc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Jx=G("$ZodCatch",(e,t)=>{Ue.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(i=>En(i,s,An()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>En(a,s,An()))},input:r.value}),r.issues=[]),r)}}),ey=G("$ZodPipe",(e,t)=>{Ue.init(e,t),Ce(e._zod,"values",()=>t.in._zod.values),Ce(e._zod,"optin",()=>t.in._zod.optin),Ce(e._zod,"optout",()=>t.out._zod.optout),Ce(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,s)=>{if(s.direction==="backward"){const a=t.out._zod.run(r,s);return a instanceof Promise?a.then(i=>Zr(i,t.in,s)):Zr(a,t.in,s)}const o=t.in._zod.run(r,s);return o instanceof Promise?o.then(a=>Zr(a,t.out,s)):Zr(o,t.out,s)}});function Zr(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const ty=G("$ZodReadonly",(e,t)=>{Ue.init(e,t),Ce(e._zod,"propValues",()=>t.innerType._zod.propValues),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"optin",()=>t.innerType?._zod?.optin),Ce(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(mc):mc(o)}});function mc(e){return e.value=Object.freeze(e.value),e}const ny=G("$ZodCustom",(e,t)=>{ht.init(e,t),Ue.init(e,t),e._zod.parse=(r,s)=>r,e._zod.check=r=>{const s=r.value,o=t.fn(s);if(o instanceof Promise)return o.then(a=>pc(a,r,s,e));pc(o,r,s,e)}});function pc(e,t,r,s){if(!e){const o={code:"custom",input:r,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(o.params=s._zod.def.params),t.issues.push(Ar(o))}}var fc;class ry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){const s=r[0];return this._map.set(t,s),s&&typeof s=="object"&&"id"in s&&this._idmap.set(s.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const s={...this.get(r)??{}};delete s.id;const o={...s,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function sy(){return new ry}(fc=globalThis).__zod_globalRegistry??(fc.__zod_globalRegistry=sy());const _r=globalThis.__zod_globalRegistry;function oy(e,t){return new e({type:"string",...me(t)})}function ay(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...me(t)})}function hc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...me(t)})}function iy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...me(t)})}function cy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...me(t)})}function ly(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...me(t)})}function dy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...me(t)})}function uy(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...me(t)})}function my(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...me(t)})}function py(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...me(t)})}function fy(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...me(t)})}function hy(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...me(t)})}function gy(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...me(t)})}function xy(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...me(t)})}function yy(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...me(t)})}function vy(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...me(t)})}function by(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...me(t)})}function wy(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...me(t)})}function _y(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...me(t)})}function jy(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...me(t)})}function ky(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...me(t)})}function Sy(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...me(t)})}function Cy(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...me(t)})}function Ny(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...me(t)})}function Py(e,t){return new e({type:"string",format:"date",check:"string_format",...me(t)})}function Ay(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...me(t)})}function Ey(e,t){return new e({type:"string",format:"duration",check:"string_format",...me(t)})}function Ty(e,t){return new e({type:"number",checks:[],...me(t)})}function Iy(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...me(t)})}function Ry(e){return new e({type:"unknown"})}function Oy(e,t){return new e({type:"never",...me(t)})}function gc(e,t){return new xd({check:"less_than",...me(t),value:e,inclusive:!1})}function No(e,t){return new xd({check:"less_than",...me(t),value:e,inclusive:!0})}function xc(e,t){return new yd({check:"greater_than",...me(t),value:e,inclusive:!1})}function Po(e,t){return new yd({check:"greater_than",...me(t),value:e,inclusive:!0})}function yc(e,t){return new Jg({check:"multiple_of",...me(t),value:e})}function kd(e,t){return new tx({check:"max_length",...me(t),maximum:e})}function ys(e,t){return new nx({check:"min_length",...me(t),minimum:e})}function Sd(e,t){return new rx({check:"length_equals",...me(t),length:e})}function My(e,t){return new sx({check:"string_format",format:"regex",...me(t),pattern:e})}function Dy(e){return new ox({check:"string_format",format:"lowercase",...me(e)})}function Ly(e){return new ax({check:"string_format",format:"uppercase",...me(e)})}function $y(e,t){return new ix({check:"string_format",format:"includes",...me(t),includes:e})}function zy(e,t){return new cx({check:"string_format",format:"starts_with",...me(t),prefix:e})}function Fy(e,t){return new lx({check:"string_format",format:"ends_with",...me(t),suffix:e})}function sr(e){return new dx({check:"overwrite",tx:e})}function By(e){return sr(t=>t.normalize(e))}function Uy(){return sr(e=>e.trim())}function Wy(){return sr(e=>e.toLowerCase())}function Vy(){return sr(e=>e.toUpperCase())}function qy(){return sr(e=>sg(e))}function Hy(e,t,r){return new e({type:"array",element:t,...me(r)})}function Zy(e,t,r){return new e({type:"custom",check:"custom",fn:t,...me(r)})}function Gy(e){const t=Qy(r=>(r.addIssue=s=>{if(typeof s=="string")r.issues.push(Ar(s,r.value,t._zod.def));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Ar(o))}},e(r.value,r)));return t}function Qy(e,t){const r=new ht({check:"custom",...me(t)});return r._zod.check=e,r}function Cd(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??_r,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Ke(e,t,r={path:[],schemaPath:[]}){var s;const o=e._zod.def,a=t.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);const c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{const m={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,m);else{const p=i.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,p,m)}const u=e._zod.parent;u&&(i.ref||(i.ref=u),Ke(u,t,m),t.seen.get(u).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),t.io==="input"&&rt(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&i.schema._prefault&&((s=i.schema).default??(s.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Nd(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const i of e.seen.entries()){const c=e.metadataRegistry.get(i[0])?.id;if(c){const l=s.get(c);if(l&&l!==i[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(c,i[0])}}const o=i=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const u=e.external.registry.get(i[0])?.id,p=e.external.uri??(_=>_);if(u)return{ref:p(u)};const h=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=h,{defId:h,ref:`${p("__shared")}#/${c}/${h}`}}if(i[1]===r)return{ref:"#"};const d=`#/${c}/`,m=i[1].schema.id??`__schema${e.counter++}`;return{defId:m,ref:d+m}},a=i=>{if(i[1].schema.$ref)return;const c=i[1],{ref:l,defId:d}=o(i);c.def={...c.schema},d&&(c.defId=d);const m=c.schema;for(const u in m)delete m[u];m.$ref=l};if(e.cycles==="throw")for(const i of e.seen.entries()){const c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
89
|
+
`)}h.write("payload.value = newResult;"),h.write("return payload;");const j=h.compile();return(v,b)=>j(p,v,b)};let a;const i=gs,c=!od.jitless,d=c&&og.value,m=t.catchall;let u;e._zod.parse=(p,h)=>{u??(u=s.value);const _=p.value;return i(_)?c&&d&&h?.async===!1&&h.jitless!==!0?(a||(a=o(t.shape)),p=a(p,h),m?_d([],_,p,h,u,e):p):r(p,h):(p.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),p)}});function ic(e,t,r,s){for(const a of e)if(a.issues.length===0)return t.value=a.value,t;const o=e.filter(a=>!Yn(a));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(a=>a.issues.map(i=>En(i,s,An())))}),t)}const Vx=G("$ZodUnion",(e,t)=>{Ue.init(e,t),Ce(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Ce(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Ce(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Ce(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${o.map(a=>La(a.source)).join("|")})$`)}});const r=t.options.length===1,s=t.options[0]._zod.run;e._zod.parse=(o,a)=>{if(r)return s(o,a);let i=!1;const c=[];for(const l of t.options){const d=l._zod.run({value:o.value,issues:[]},a);if(d instanceof Promise)c.push(d),i=!0;else{if(d.issues.length===0)return d;c.push(d)}}return i?Promise.all(c).then(l=>ic(l,o,e,a)):ic(c,o,e,a)}}),qx=G("$ZodIntersection",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>{const o=r.value,a=t.left._zod.run({value:o,issues:[]},s),i=t.right._zod.run({value:o,issues:[]},s);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([l,d])=>cc(r,l,d)):cc(r,a,i)}});function ta(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Pr(e)&&Pr(t)){const r=Object.keys(t),s=Object.keys(e).filter(a=>r.indexOf(a)!==-1),o={...e,...t};for(const a of s){const i=ta(e[a],t[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};o[a]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let s=0;s<e.length;s++){const o=e[s],a=t[s],i=ta(o,a);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function cc(e,t,r){const s=new Map;let o;for(const c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(const l of c.keys)s.has(l)||s.set(l,{}),s.get(l).l=!0}else e.issues.push(c);for(const c of r.issues)if(c.code==="unrecognized_keys")for(const l of c.keys)s.has(l)||s.set(l,{}),s.get(l).r=!0;else e.issues.push(c);const a=[...s].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length&&o&&e.issues.push({...o,keys:a}),Yn(e))return e;const i=ta(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const Hx=G("$ZodEnum",(e,t)=>{Ue.init(e,t);const r=ad(t.entries),s=new Set(r);e._zod.values=s,e._zod.pattern=new RegExp(`^(${r.filter(o=>ag.has(typeof o)).map(o=>typeof o=="string"?Os(o):o.toString()).join("|")})$`),e._zod.parse=(o,a)=>{const i=o.value;return s.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Zx=G("$ZodTransform",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new sd(e.constructor.name);const o=t.transform(r.value,r);if(s.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Kn;return r.value=o,r}});function lc(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const jd=G("$ZodOptional",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${La(r.source)})?$`):void 0}),e._zod.parse=(r,s)=>{if(t.innerType._zod.optin==="optional"){const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>lc(a,r.value)):lc(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,s)}}),Gx=G("$ZodExactOptional",(e,t)=>{jd.init(e,t),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,s)=>t.innerType._zod.run(r,s)}),Qx=G("$ZodNullable",(e,t)=>{Ue.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${La(r.source)}|null)$`):void 0}),Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,s)=>r.value===null?r:t.innerType._zod.run(r,s)}),Yx=G("$ZodDefault",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>dc(a,t)):dc(o,t)}});function dc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Kx=G("$ZodPrefault",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>(s.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,s))}),Xx=G("$ZodNonOptional",(e,t)=>{Ue.init(e,t),Ce(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(s=>s!==void 0)):void 0}),e._zod.parse=(r,s)=>{const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>uc(a,e)):uc(o,e)}});function uc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Jx=G("$ZodCatch",(e,t)=>{Ue.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(i=>En(i,s,An()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>En(a,s,An()))},input:r.value}),r.issues=[]),r)}}),ey=G("$ZodPipe",(e,t)=>{Ue.init(e,t),Ce(e._zod,"values",()=>t.in._zod.values),Ce(e._zod,"optin",()=>t.in._zod.optin),Ce(e._zod,"optout",()=>t.out._zod.optout),Ce(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,s)=>{if(s.direction==="backward"){const a=t.out._zod.run(r,s);return a instanceof Promise?a.then(i=>Zr(i,t.in,s)):Zr(a,t.in,s)}const o=t.in._zod.run(r,s);return o instanceof Promise?o.then(a=>Zr(a,t.out,s)):Zr(o,t.out,s)}});function Zr(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const ty=G("$ZodReadonly",(e,t)=>{Ue.init(e,t),Ce(e._zod,"propValues",()=>t.innerType._zod.propValues),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"optin",()=>t.innerType?._zod?.optin),Ce(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(mc):mc(o)}});function mc(e){return e.value=Object.freeze(e.value),e}const ny=G("$ZodCustom",(e,t)=>{gt.init(e,t),Ue.init(e,t),e._zod.parse=(r,s)=>r,e._zod.check=r=>{const s=r.value,o=t.fn(s);if(o instanceof Promise)return o.then(a=>pc(a,r,s,e));pc(o,r,s,e)}});function pc(e,t,r,s){if(!e){const o={code:"custom",input:r,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(o.params=s._zod.def.params),t.issues.push(Ar(o))}}var fc;class ry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){const s=r[0];return this._map.set(t,s),s&&typeof s=="object"&&"id"in s&&this._idmap.set(s.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const s={...this.get(r)??{}};delete s.id;const o={...s,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function sy(){return new ry}(fc=globalThis).__zod_globalRegistry??(fc.__zod_globalRegistry=sy());const _r=globalThis.__zod_globalRegistry;function oy(e,t){return new e({type:"string",...me(t)})}function ay(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...me(t)})}function hc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...me(t)})}function iy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...me(t)})}function cy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...me(t)})}function ly(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...me(t)})}function dy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...me(t)})}function uy(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...me(t)})}function my(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...me(t)})}function py(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...me(t)})}function fy(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...me(t)})}function hy(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...me(t)})}function gy(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...me(t)})}function xy(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...me(t)})}function yy(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...me(t)})}function by(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...me(t)})}function vy(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...me(t)})}function wy(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...me(t)})}function _y(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...me(t)})}function jy(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...me(t)})}function ky(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...me(t)})}function Sy(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...me(t)})}function Cy(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...me(t)})}function Ny(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...me(t)})}function Py(e,t){return new e({type:"string",format:"date",check:"string_format",...me(t)})}function Ay(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...me(t)})}function Ey(e,t){return new e({type:"string",format:"duration",check:"string_format",...me(t)})}function Ty(e,t){return new e({type:"number",checks:[],...me(t)})}function Iy(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...me(t)})}function Ry(e){return new e({type:"unknown"})}function Oy(e,t){return new e({type:"never",...me(t)})}function gc(e,t){return new xd({check:"less_than",...me(t),value:e,inclusive:!1})}function No(e,t){return new xd({check:"less_than",...me(t),value:e,inclusive:!0})}function xc(e,t){return new yd({check:"greater_than",...me(t),value:e,inclusive:!1})}function Po(e,t){return new yd({check:"greater_than",...me(t),value:e,inclusive:!0})}function yc(e,t){return new Jg({check:"multiple_of",...me(t),value:e})}function kd(e,t){return new tx({check:"max_length",...me(t),maximum:e})}function ys(e,t){return new nx({check:"min_length",...me(t),minimum:e})}function Sd(e,t){return new rx({check:"length_equals",...me(t),length:e})}function My(e,t){return new sx({check:"string_format",format:"regex",...me(t),pattern:e})}function Dy(e){return new ox({check:"string_format",format:"lowercase",...me(e)})}function Ly(e){return new ax({check:"string_format",format:"uppercase",...me(e)})}function $y(e,t){return new ix({check:"string_format",format:"includes",...me(t),includes:e})}function zy(e,t){return new cx({check:"string_format",format:"starts_with",...me(t),prefix:e})}function Fy(e,t){return new lx({check:"string_format",format:"ends_with",...me(t),suffix:e})}function sr(e){return new dx({check:"overwrite",tx:e})}function By(e){return sr(t=>t.normalize(e))}function Uy(){return sr(e=>e.trim())}function Wy(){return sr(e=>e.toLowerCase())}function Vy(){return sr(e=>e.toUpperCase())}function qy(){return sr(e=>sg(e))}function Hy(e,t,r){return new e({type:"array",element:t,...me(r)})}function Zy(e,t,r){return new e({type:"custom",check:"custom",fn:t,...me(r)})}function Gy(e){const t=Qy(r=>(r.addIssue=s=>{if(typeof s=="string")r.issues.push(Ar(s,r.value,t._zod.def));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Ar(o))}},e(r.value,r)));return t}function Qy(e,t){const r=new gt({check:"custom",...me(t)});return r._zod.check=e,r}function Cd(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??_r,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Ke(e,t,r={path:[],schemaPath:[]}){var s;const o=e._zod.def,a=t.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);const c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{const m={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,m);else{const p=i.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,p,m)}const u=e._zod.parent;u&&(i.ref||(i.ref=u),Ke(u,t,m),t.seen.get(u).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),t.io==="input"&&rt(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&i.schema._prefault&&((s=i.schema).default??(s.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Nd(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const i of e.seen.entries()){const c=e.metadataRegistry.get(i[0])?.id;if(c){const l=s.get(c);if(l&&l!==i[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(c,i[0])}}const o=i=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const u=e.external.registry.get(i[0])?.id,p=e.external.uri??(_=>_);if(u)return{ref:p(u)};const h=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=h,{defId:h,ref:`${p("__shared")}#/${c}/${h}`}}if(i[1]===r)return{ref:"#"};const d=`#/${c}/`,m=i[1].schema.id??`__schema${e.counter++}`;return{defId:m,ref:d+m}},a=i=>{if(i[1].schema.$ref)return;const c=i[1],{ref:l,defId:d}=o(i);c.def={...c.schema},d&&(c.defId=d);const m=c.schema;for(const u in m)delete m[u];m.$ref=l};if(e.cycles==="throw")for(const i of e.seen.entries()){const c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
90
90
|
|
|
91
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const c=i[1];if(t===i[0]){a(i);continue}if(e.external){const d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){a(i);continue}}if(e.metadataRegistry.get(i[0])?.id){a(i);continue}if(c.cycle){a(i);continue}if(c.count>1&&e.reused==="ref"){a(i);continue}}}function Pd(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i=>{const c=e.seen.get(i);if(c.ref===null)return;const l=c.def??c.schema,d={...l},m=c.ref;if(c.ref=null,m){s(m);const p=e.seen.get(m),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(h)):Object.assign(l,h),Object.assign(l,d),i._zod.parent===m)for(const g in l)g==="$ref"||g==="allOf"||g in d||delete l[g];if(h.$ref&&p.def)for(const g in l)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(l[g])===JSON.stringify(p.def[g])&&delete l[g]}const u=i._zod.parent;if(u&&u!==m){s(u);const p=e.seen.get(u);if(p?.schema.$ref&&(l.$ref=p.schema.$ref,p.def))for(const h in l)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(l[h])===JSON.stringify(p.def[h])&&delete l[h]}e.override({zodSchema:i,jsonSchema:l,path:c.path??[]})};for(const i of[...e.seen.entries()].reverse())s(i[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(i)}Object.assign(o,r.def??r.schema);const a=e.external?.defs??{};for(const i of e.seen.entries()){const c=i[1];c.def&&c.defId&&(a[c.defId]=c.def)}e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?o.$defs=a:o.definitions=a);try{const i=JSON.parse(JSON.stringify(o));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:vs(t,"input",e.processors),output:vs(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function rt(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return rt(s.element,r);if(s.type==="set")return rt(s.valueType,r);if(s.type==="lazy")return rt(s.getter(),r);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return rt(s.innerType,r);if(s.type==="intersection")return rt(s.left,r)||rt(s.right,r);if(s.type==="record"||s.type==="map")return rt(s.keyType,r)||rt(s.valueType,r);if(s.type==="pipe")return rt(s.in,r)||rt(s.out,r);if(s.type==="object"){for(const o in s.shape)if(rt(s.shape[o],r))return!0;return!1}if(s.type==="union"){for(const o of s.options)if(rt(o,r))return!0;return!1}if(s.type==="tuple"){for(const o of s.items)if(rt(o,r))return!0;return!!(s.rest&&rt(s.rest,r))}return!1}const Yy=(e,t={})=>r=>{const s=Cd({...r,processors:t});return Ke(e,s),Nd(s,e),Pd(s,e)},vs=(e,t,r={})=>s=>{const{libraryOptions:o,target:a}=s??{},i=Cd({...o??{},target:a,io:t,processors:r});return Ke(e,i),Nd(i,e),Pd(i,e)},Ky={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Xy=(e,t,r,s)=>{const o=r;o.type="string";const{minimum:a,maximum:i,format:c,patterns:l,contentEncoding:d}=e._zod.bag;if(typeof a=="number"&&(o.minLength=a),typeof i=="number"&&(o.maxLength=i),c&&(o.format=Ky[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),d&&(o.contentEncoding=d),l&&l.size>0){const m=[...l];m.length===1?o.pattern=m[0].source:m.length>1&&(o.allOf=[...m.map(u=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:u.source}))])}},Jy=(e,t,r,s)=>{const o=r,{minimum:a,maximum:i,format:c,multipleOf:l,exclusiveMaximum:d,exclusiveMinimum:m}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number",typeof m=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=m,o.exclusiveMinimum=!0):o.exclusiveMinimum=m),typeof a=="number"&&(o.minimum=a,typeof m=="number"&&t.target!=="draft-04"&&(m>=a?delete o.minimum:delete o.exclusiveMinimum)),typeof d=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=d,o.exclusiveMaximum=!0):o.exclusiveMaximum=d),typeof i=="number"&&(o.maximum=i,typeof d=="number"&&t.target!=="draft-04"&&(d<=i?delete o.maximum:delete o.exclusiveMaximum)),typeof l=="number"&&(o.multipleOf=l)},ev=(e,t,r,s)=>{r.not={}},tv=(e,t,r,s)=>{},nv=(e,t,r,s)=>{const o=e._zod.def,a=ad(o.entries);a.every(i=>typeof i=="number")&&(r.type="number"),a.every(i=>typeof i=="string")&&(r.type="string"),r.enum=a},rv=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},sv=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},ov=(e,t,r,s)=>{const o=r,a=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=Ke(a.element,t,{...s,path:[...s.path,"items"]})},av=(e,t,r,s)=>{const o=r,a=e._zod.def;o.type="object",o.properties={};const i=a.shape;for(const d in i)o.properties[d]=Ke(i[d],t,{...s,path:[...s.path,"properties",d]});const c=new Set(Object.keys(i)),l=new Set([...c].filter(d=>{const m=a.shape[d]._zod;return t.io==="input"?m.optin===void 0:m.optout===void 0}));l.size>0&&(o.required=Array.from(l)),a.catchall?._zod.def.type==="never"?o.additionalProperties=!1:a.catchall?a.catchall&&(o.additionalProperties=Ke(a.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},iv=(e,t,r,s)=>{const o=e._zod.def,a=o.inclusive===!1,i=o.options.map((c,l)=>Ke(c,t,{...s,path:[...s.path,a?"oneOf":"anyOf",l]}));a?r.oneOf=i:r.anyOf=i},cv=(e,t,r,s)=>{const o=e._zod.def,a=Ke(o.left,t,{...s,path:[...s.path,"allOf",0]}),i=Ke(o.right,t,{...s,path:[...s.path,"allOf",1]}),c=d=>"allOf"in d&&Object.keys(d).length===1,l=[...c(a)?a.allOf:[a],...c(i)?i.allOf:[i]];r.allOf=l},lv=(e,t,r,s)=>{const o=e._zod.def,a=Ke(o.innerType,t,s),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]},dv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},uv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},mv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},pv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},fv=(e,t,r,s)=>{const o=e._zod.def,a=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;Ke(a,t,s);const i=t.seen.get(e);i.ref=a},hv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.readOnly=!0},Ad=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},gv=G("ZodISODateTime",(e,t)=>{kx.init(e,t),Oe.init(e,t)});function xv(e){return Ny(gv,e)}const yv=G("ZodISODate",(e,t)=>{Sx.init(e,t),Oe.init(e,t)});function vv(e){return Py(yv,e)}const bv=G("ZodISOTime",(e,t)=>{Cx.init(e,t),Oe.init(e,t)});function wv(e){return Ay(bv,e)}const _v=G("ZodISODuration",(e,t)=>{Nx.init(e,t),Oe.init(e,t)});function jv(e){return Ey(_v,e)}const kv=(e,t)=>{ud.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>xg(e,r)},flatten:{value:r=>gg(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,ea,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,ea,2)}},isEmpty:{get(){return e.issues.length===0}}})},Nt=G("ZodError",kv,{Parent:Error}),Sv=za(Nt),Cv=Fa(Nt),Nv=Ms(Nt),Pv=Ds(Nt),Av=bg(Nt),Ev=wg(Nt),Tv=_g(Nt),Iv=jg(Nt),Rv=kg(Nt),Ov=Sg(Nt),Mv=Cg(Nt),Dv=Ng(Nt),We=G("ZodType",(e,t)=>(Ue.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:vs(e,"input"),output:vs(e,"output")}}),e.toJSONSchema=Yy(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(yn(t,{checks:[...t.checks??[],...r.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0}),e.with=e.check,e.clone=(r,s)=>vn(e,r,s),e.brand=()=>e,e.register=((r,s)=>(r.add(e,s),e)),e.parse=(r,s)=>Sv(e,r,s,{callee:e.parse}),e.safeParse=(r,s)=>Nv(e,r,s),e.parseAsync=async(r,s)=>Cv(e,r,s,{callee:e.parseAsync}),e.safeParseAsync=async(r,s)=>Pv(e,r,s),e.spa=e.safeParseAsync,e.encode=(r,s)=>Av(e,r,s),e.decode=(r,s)=>Ev(e,r,s),e.encodeAsync=async(r,s)=>Tv(e,r,s),e.decodeAsync=async(r,s)=>Iv(e,r,s),e.safeEncode=(r,s)=>Rv(e,r,s),e.safeDecode=(r,s)=>Ov(e,r,s),e.safeEncodeAsync=async(r,s)=>Mv(e,r,s),e.safeDecodeAsync=async(r,s)=>Dv(e,r,s),e.refine=(r,s)=>e.check(Eb(r,s)),e.superRefine=r=>e.check(Tb(r)),e.overwrite=r=>e.check(sr(r)),e.optional=()=>_c(e),e.exactOptional=()=>xb(e),e.nullable=()=>jc(e),e.nullish=()=>_c(jc(e)),e.nonoptional=r=>jb(e,r),e.array=()=>ib(e),e.or=r=>db([e,r]),e.and=r=>mb(e,r),e.transform=r=>kc(e,hb(r)),e.default=r=>bb(e,r),e.prefault=r=>_b(e,r),e.catch=r=>Sb(e,r),e.pipe=r=>kc(e,r),e.readonly=()=>Pb(e),e.describe=r=>{const s=e.clone();return _r.add(s,{description:r}),s},Object.defineProperty(e,"description",{get(){return _r.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return _r.get(e);const s=e.clone();return _r.add(s,r[0]),s},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),Ed=G("_ZodString",(e,t)=>{Ba.init(e,t),We.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Xy(e,s,o);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...s)=>e.check(My(...s)),e.includes=(...s)=>e.check($y(...s)),e.startsWith=(...s)=>e.check(zy(...s)),e.endsWith=(...s)=>e.check(Fy(...s)),e.min=(...s)=>e.check(ys(...s)),e.max=(...s)=>e.check(kd(...s)),e.length=(...s)=>e.check(Sd(...s)),e.nonempty=(...s)=>e.check(ys(1,...s)),e.lowercase=s=>e.check(Dy(s)),e.uppercase=s=>e.check(Ly(s)),e.trim=()=>e.check(Uy()),e.normalize=(...s)=>e.check(By(...s)),e.toLowerCase=()=>e.check(Wy()),e.toUpperCase=()=>e.check(Vy()),e.slugify=()=>e.check(qy())}),Lv=G("ZodString",(e,t)=>{Ba.init(e,t),Ed.init(e,t),e.email=r=>e.check(ay($v,r)),e.url=r=>e.check(uy(zv,r)),e.jwt=r=>e.check(Cy(eb,r)),e.emoji=r=>e.check(my(Fv,r)),e.guid=r=>e.check(hc(vc,r)),e.uuid=r=>e.check(iy(Gr,r)),e.uuidv4=r=>e.check(cy(Gr,r)),e.uuidv6=r=>e.check(ly(Gr,r)),e.uuidv7=r=>e.check(dy(Gr,r)),e.nanoid=r=>e.check(py(Bv,r)),e.guid=r=>e.check(hc(vc,r)),e.cuid=r=>e.check(fy(Uv,r)),e.cuid2=r=>e.check(hy(Wv,r)),e.ulid=r=>e.check(gy(Vv,r)),e.base64=r=>e.check(jy(Kv,r)),e.base64url=r=>e.check(ky(Xv,r)),e.xid=r=>e.check(xy(qv,r)),e.ksuid=r=>e.check(yy(Hv,r)),e.ipv4=r=>e.check(vy(Zv,r)),e.ipv6=r=>e.check(by(Gv,r)),e.cidrv4=r=>e.check(wy(Qv,r)),e.cidrv6=r=>e.check(_y(Yv,r)),e.e164=r=>e.check(Sy(Jv,r)),e.datetime=r=>e.check(xv(r)),e.date=r=>e.check(vv(r)),e.time=r=>e.check(wv(r)),e.duration=r=>e.check(jv(r))});function st(e){return oy(Lv,e)}const Oe=G("ZodStringFormat",(e,t)=>{Te.init(e,t),Ed.init(e,t)}),$v=G("ZodEmail",(e,t)=>{hx.init(e,t),Oe.init(e,t)}),vc=G("ZodGUID",(e,t)=>{px.init(e,t),Oe.init(e,t)}),Gr=G("ZodUUID",(e,t)=>{fx.init(e,t),Oe.init(e,t)}),zv=G("ZodURL",(e,t)=>{gx.init(e,t),Oe.init(e,t)}),Fv=G("ZodEmoji",(e,t)=>{xx.init(e,t),Oe.init(e,t)}),Bv=G("ZodNanoID",(e,t)=>{yx.init(e,t),Oe.init(e,t)}),Uv=G("ZodCUID",(e,t)=>{vx.init(e,t),Oe.init(e,t)}),Wv=G("ZodCUID2",(e,t)=>{bx.init(e,t),Oe.init(e,t)}),Vv=G("ZodULID",(e,t)=>{wx.init(e,t),Oe.init(e,t)}),qv=G("ZodXID",(e,t)=>{_x.init(e,t),Oe.init(e,t)}),Hv=G("ZodKSUID",(e,t)=>{jx.init(e,t),Oe.init(e,t)}),Zv=G("ZodIPv4",(e,t)=>{Px.init(e,t),Oe.init(e,t)}),Gv=G("ZodIPv6",(e,t)=>{Ax.init(e,t),Oe.init(e,t)}),Qv=G("ZodCIDRv4",(e,t)=>{Ex.init(e,t),Oe.init(e,t)}),Yv=G("ZodCIDRv6",(e,t)=>{Tx.init(e,t),Oe.init(e,t)}),Kv=G("ZodBase64",(e,t)=>{Ix.init(e,t),Oe.init(e,t)}),Xv=G("ZodBase64URL",(e,t)=>{Ox.init(e,t),Oe.init(e,t)}),Jv=G("ZodE164",(e,t)=>{Mx.init(e,t),Oe.init(e,t)}),eb=G("ZodJWT",(e,t)=>{Lx.init(e,t),Oe.init(e,t)}),Td=G("ZodNumber",(e,t)=>{bd.init(e,t),We.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Jy(e,s,o),e.gt=(s,o)=>e.check(xc(s,o)),e.gte=(s,o)=>e.check(Po(s,o)),e.min=(s,o)=>e.check(Po(s,o)),e.lt=(s,o)=>e.check(gc(s,o)),e.lte=(s,o)=>e.check(No(s,o)),e.max=(s,o)=>e.check(No(s,o)),e.int=s=>e.check(bc(s)),e.safe=s=>e.check(bc(s)),e.positive=s=>e.check(xc(0,s)),e.nonnegative=s=>e.check(Po(0,s)),e.negative=s=>e.check(gc(0,s)),e.nonpositive=s=>e.check(No(0,s)),e.multipleOf=(s,o)=>e.check(yc(s,o)),e.step=(s,o)=>e.check(yc(s,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function tb(e){return Ty(Td,e)}const nb=G("ZodNumberFormat",(e,t)=>{$x.init(e,t),Td.init(e,t)});function bc(e){return Iy(nb,e)}const rb=G("ZodUnknown",(e,t)=>{zx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>tv()});function wc(){return Ry(rb)}const sb=G("ZodNever",(e,t)=>{Fx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ev(e,r,s)});function ob(e){return Oy(sb,e)}const ab=G("ZodArray",(e,t)=>{Bx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ov(e,r,s,o),e.element=t.element,e.min=(r,s)=>e.check(ys(r,s)),e.nonempty=r=>e.check(ys(1,r)),e.max=(r,s)=>e.check(kd(r,s)),e.length=(r,s)=>e.check(Sd(r,s)),e.unwrap=()=>e.element});function ib(e,t){return Hy(ab,e,t)}const cb=G("ZodObject",(e,t)=>{Wx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>av(e,r,s,o),Ce(e,"shape",()=>t.shape),e.keyof=()=>pb(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:wc()}),e.loose=()=>e.clone({...e._zod.def,catchall:wc()}),e.strict=()=>e.clone({...e._zod.def,catchall:ob()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>ug(e,r),e.safeExtend=r=>mg(e,r),e.merge=r=>pg(e,r),e.pick=r=>lg(e,r),e.omit=r=>dg(e,r),e.partial=(...r)=>fg(Rd,e,r[0]),e.required=(...r)=>hg(Od,e,r[0])});function Id(e,t){const r={type:"object",shape:e??{},...me(t)};return new cb(r)}const lb=G("ZodUnion",(e,t)=>{Vx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>iv(e,r,s,o),e.options=t.options});function db(e,t){return new lb({type:"union",options:e,...me(t)})}const ub=G("ZodIntersection",(e,t)=>{qx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>cv(e,r,s,o)});function mb(e,t){return new ub({type:"intersection",left:e,right:t})}const na=G("ZodEnum",(e,t)=>{Hx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(s,o,a)=>nv(e,s,o),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(s,o)=>{const a={};for(const i of s)if(r.has(i))a[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new na({...t,checks:[],...me(o),entries:a})},e.exclude=(s,o)=>{const a={...t.entries};for(const i of s)if(r.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new na({...t,checks:[],...me(o),entries:a})}});function pb(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new na({type:"enum",entries:r,...me(t)})}const fb=G("ZodTransform",(e,t)=>{Zx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>sv(e,r),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new sd(e.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(Ar(a,r.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(Ar(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(a=>(r.value=a,r)):(r.value=o,r)}});function hb(e){return new fb({type:"transform",transform:e})}const Rd=G("ZodOptional",(e,t)=>{jd.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Ad(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function _c(e){return new Rd({type:"optional",innerType:e})}const gb=G("ZodExactOptional",(e,t)=>{Gx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Ad(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function xb(e){return new gb({type:"optional",innerType:e})}const yb=G("ZodNullable",(e,t)=>{Qx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>lv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function jc(e){return new yb({type:"nullable",innerType:e})}const vb=G("ZodDefault",(e,t)=>{Yx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>uv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function bb(e,t){return new vb({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():cd(t)}})}const wb=G("ZodPrefault",(e,t)=>{Kx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>mv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function _b(e,t){return new wb({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():cd(t)}})}const Od=G("ZodNonOptional",(e,t)=>{Xx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>dv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function jb(e,t){return new Od({type:"nonoptional",innerType:e,...me(t)})}const kb=G("ZodCatch",(e,t)=>{Jx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>pv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Sb(e,t){return new kb({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Cb=G("ZodPipe",(e,t)=>{ey.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>fv(e,r,s,o),e.in=t.in,e.out=t.out});function kc(e,t){return new Cb({type:"pipe",in:e,out:t})}const Nb=G("ZodReadonly",(e,t)=>{ty.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>hv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Pb(e){return new Nb({type:"readonly",innerType:e})}const Ab=G("ZodCustom",(e,t)=>{ny.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>rv(e,r)});function Eb(e,t={}){return Zy(Ab,e,t)}function Tb(e){return Gy(e)}const Qr=Id({line1:st().min(1,"Address line 1 is required"),line2:st().optional(),city:st().min(1,"City is required"),state:st().optional(),postalCode:st().min(1,"Postal code is required"),country:st().min(2,"Country is required")});function Ib(e){return Id({email:e.requireEmail?st().email("Valid email required"):st().email("Valid email required").optional(),name:e.requireName?st().min(1,"Name is required"):st().optional(),phone:e.requirePhone?st().min(6,"Phone is required"):st().optional(),notes:st().max(500).optional(),shippingAddress:e.requireShippingAddress?Qr:Qr.optional(),billingAddress:e.requireBillingAddress?Qr:Qr.optional(),discountCode:st().optional(),tipAmount:tb().min(0).optional(),shippingMethodId:st().optional()})}const Sc={none:0,optional:1,required:2};function Ao(e,t){return Sc[e]>=Sc[t]?e:t}function Rb(e){if(!e)return null;try{const t=JSON.parse(e);return!t||typeof t!="object"?null:t}catch{return null}}function cs(e,t){let r=!1,s=!1;const o=new Set;let a=t.requireEmail?"required":"none",i=t.defaultMode==="none"?"none":"optional",c=t.defaultMode==="full"?"optional":"none",l=t.allowShipping&&(t.defaultMode==="shipping"||t.defaultMode==="full"),d=t.defaultMode==="full";for(const u of e){u.metadata?.shippingProfile==="digital"?r=!0:s=!0;const h=Rb(u.metadata?.checkoutRequirements);h&&(h.email&&(a=Ao(a,h.email)),h.name&&(i=Ao(i,h.name)),h.phone&&(c=Ao(c,h.phone)),typeof h.shippingAddress=="boolean"&&(l=l||h.shippingAddress),typeof h.billingAddress=="boolean"&&(d=d||h.billingAddress));const _=u.metadata?.fulfillmentNotes;_&&o.add(_)}const m=r&&!s;return m&&(l=!1),{email:a,name:i,phone:c,shippingAddress:l,billingAddress:d,fulfillmentNotes:Array.from(o).join(" "),isDigitalOnly:m,hasPhysical:s}}const Md=y.createContext(null);function Dd(){const{config:e}=Re(),t=Dt(),r=y.useMemo(()=>({line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"}),[]),s=y.useMemo(()=>{const j=cs(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});return Ib({requireEmail:j.email==="required",requireName:j.name==="required",requirePhone:j.phone==="required",requireShippingAddress:j.shippingAddress,requireBillingAddress:j.billingAddress})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail]),[o,a]=y.useState(()=>({email:e.checkout.requireEmail??!0?"":void 0,name:"",phone:"",notes:"",shippingAddress:e.checkout.mode==="shipping"||e.checkout.mode==="full"?r:void 0,billingAddress:e.checkout.mode==="full"?r:void 0,discountCode:"",tipAmount:0,shippingMethodId:""}));y.useEffect(()=>{const j=cs(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});a(b=>{const v={...b};return j.email==="required"&&!v.email&&(v.email=""),j.shippingAddress&&!v.shippingAddress&&(v.shippingAddress=r),j.billingAddress&&!v.billingAddress&&(v.billingAddress=r),j.shippingAddress||(v.shippingAddress=void 0),j.billingAddress||(v.billingAddress=void 0),v})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail,r]);const[i,c]=y.useState({}),[l,d]=y.useState("idle"),[m,u]=y.useState(null),[p,h]=y.useState(null),_=y.useCallback(()=>{c({}),d("idle"),u(null),h(null)},[]),g=y.useCallback((j,b)=>{a(v=>({...v,[j]:b}))},[]),f=y.useCallback(()=>{d("validating"),u(null);const j=s.safeParse(o);if(j.success)return c({}),d("idle"),{ok:!0,values:j.data};const b={};for(const v of j.error.issues)b[v.path.join(".")]=v.message;return c(b),d("error"),u("Please fix the highlighted fields."),{ok:!1}},[s,o]),w=y.useCallback(async j=>{const b=f();if(!b.ok)return{ok:!1};d("creating_session"),u(null),h(null);const v=t.items.map(C=>({resource:C.paymentResource??C.productId,quantity:C.qty,variantId:C.variantId})),k=cs(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1}),R=new Set;if(k.shippingAddress)for(const C of t.items){const T=C.metadata?.shippingCountries;if(T)for(const O of T.split(",")){const $=O.trim().toUpperCase();$&&R.add($)}}const N={...R.size?{shippingCountries:Array.from(R).join(","),shipping_countries:Array.from(R).join(",")}:{}};try{const C=await e.adapter.createCheckoutSession({cart:v,customer:{email:b.values.email||void 0,name:b.values.name||void 0,phone:b.values.phone||void 0,notes:b.values.notes||void 0,shippingAddress:b.values.shippingAddress,billingAddress:b.values.billingAddress},options:{currency:e.currency,successUrl:e.checkout.successUrl,cancelUrl:e.checkout.cancelUrl,allowPromoCodes:e.checkout.allowPromoCodes,metadata:Object.keys(N).length?N:void 0,discountCode:(e.checkout.allowPromoCodes?b.values.discountCode||t.promoCode:void 0)||void 0,tipAmount:e.checkout.allowTipping&&b.values.tipAmount||void 0,shippingMethodId:e.checkout.allowShipping&&b.values.shippingMethodId||void 0,paymentMethodId:j?.paymentMethodId}});return C.kind==="redirect"?(h(C),d("redirecting"),typeof window<"u"&&window.location.assign(C.url),{ok:!0,session:C}):(h(C),d("success"),{ok:!0,session:C})}catch(C){return d("error"),u(C instanceof Error?C.message:"Checkout failed"),{ok:!1}}},[t.items,t.promoCode,e.adapter,e.checkout,e.currency,f]);return{values:o,setValues:a,setField:g,fieldErrors:i,status:l,error:m,session:p,reset:_,validate:f,createCheckoutSession:w}}function Ld({children:e}){const t=Dd();return n.jsx(Md.Provider,{value:t,children:e})}function $s(){const e=y.useContext(Md);if(!e)throw new Error("useCheckout must be used within CheckoutProvider");return e}function Ob(){return Dd()}function Ua(){const{config:e}=Re(),[t,r]=x.useState([]),[s,o]=x.useState(!0),[a,i]=x.useState(null);return x.useEffect(()=>{let c=!1;return o(!0),i(null),e.adapter.listCategories().then(l=>{c||r(l)}).catch(l=>{c||i(l instanceof Error?l.message:"Failed to load categories")}).finally(()=>{c||o(!1)}),()=>{c=!0}},[e.adapter]),{categories:t,isLoading:s,error:a}}function zs(e){const{config:t}=Re(),[r,s]=x.useState(null),[o,a]=x.useState(!0),[i,c]=x.useState(null),l=JSON.stringify(e.filters??{});return x.useEffect(()=>{let d=!1;return a(!0),c(null),t.adapter.listProducts(e).then(m=>{d||s(m)}).catch(m=>{d||c(m instanceof Error?m.message:"Failed to load products")}).finally(()=>{d||a(!1)}),()=>{d=!0}},[t.adapter,e.category,e.search,e.sort,e.page,e.pageSize,l]),{data:r,isLoading:o,error:i}}function $d(e){const{config:t}=Re(),[r,s]=x.useState(null),[o,a]=x.useState(!0),[i,c]=x.useState(null);return x.useEffect(()=>{let l=!1;return a(!0),c(null),t.adapter.getProductBySlug(e).then(d=>{l||s(d)}).catch(d=>{l||c(d instanceof Error?d.message:"Failed to load product")}).finally(()=>{l||a(!1)}),()=>{l=!0}},[t.adapter,e]),{product:r,isLoading:o,error:i}}function zd(){const{config:e}=Re(),[t,r]=x.useState([]),[s,o]=x.useState(!0),[a,i]=x.useState(null);return x.useEffect(()=>{let c=!1;return o(!0),i(null),e.adapter.getOrderHistory().then(l=>{c||r(l)}).catch(l=>{c||i(l instanceof Error?l.message:"Failed to load orders")}).finally(()=>{c||o(!1)}),()=>{c=!0}},[e.adapter]),{orders:t,isLoading:s,error:a}}function Fd(){const{config:e}=Re(),[t,r]=x.useState([]),[s,o]=x.useState(null),[a,i]=x.useState(!0),[c,l]=x.useState(null);return x.useEffect(()=>{let d=!1;async function m(){i(!0),l(null);try{const[u,p]=await Promise.all([e.adapter.listSubscriptionTiers?.()??Promise.resolve([]),e.adapter.getSubscriptionStatus?.()??Promise.resolve(null)]);if(d)return;r(u),o(p)}catch(u){if(d)return;l(u instanceof Error?u.message:"Failed to load subscriptions")}finally{d||i(!1)}}return m(),()=>{d=!0}},[e.adapter]),{tiers:t,status:s,isLoading:a,error:c}}function Bd({enabled:e,customer:t}){const{config:r}=Re(),[s,o]=x.useState([]),[a,i]=x.useState(!1),[c,l]=x.useState(null),d=JSON.stringify(t.shippingAddress??{});return x.useEffect(()=>{let m=!1;if(!e||!r.adapter.getShippingMethods){o([]);return}return i(!0),l(null),r.adapter.getShippingMethods({currency:r.currency,customer:t}).then(u=>{m||o(u)}).catch(u=>{m||l(u instanceof Error?u.message:"Failed to load shipping methods")}).finally(()=>{m||i(!1)}),()=>{m=!0}},[r.adapter,r.currency,e,t.email,t.name,d]),{methods:s,isLoading:a,error:c}}function fr(e,...t){for(const r of t){const s=e[r];if(s)return s}}function Wa(e){const t=fr(e,"error","error_message","message");if(t)return{kind:"error",message:t};const r=fr(e,"canceled","cancelled","cancel","canceled_at");if(r&&r!=="0"&&r!=="false")return{kind:"cancel"};const s=fr(e,"orderId","order_id","demoOrderId"),o=fr(e,"session_id","checkout_session_id");if(s||o)return{kind:"success",orderId:s??o};const a=(fr(e,"status","checkout")??"").toLowerCase();return a==="success"?{kind:"success",orderId:s}:a==="cancel"||a==="canceled"?{kind:"cancel"}:a==="error"?{kind:"error"}:{kind:"idle"}}function Mb(e){const t={};return e.forEach((r,s)=>{t[s]=r}),t}function Va(){const{config:e}=Re(),[t,r]=x.useState({kind:"idle"});return x.useEffect(()=>{if(typeof window>"u")return;const s=new URLSearchParams(window.location.search),o=Mb(s);(async()=>{try{const a=e.adapter.resolveCheckoutReturn?await e.adapter.resolveCheckoutReturn({query:o}):Wa(o);if(a.kind==="success"&&a.orderId&&e.adapter.getOrderById){const i=await e.adapter.getOrderById(a.orderId);if(i){r({kind:"success",orderId:a.orderId,order:i});return}}r(a)}catch(a){r({kind:"error",message:a instanceof Error?a.message:"Failed to resolve checkout"})}})()},[e.adapter]),t}function ra(e){if(!e)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Db(e){const t=e.get("tags"),r=t?t.split(",").map(c=>c.trim()).filter(Boolean):void 0,s=ra(e.get("min")),o=ra(e.get("max")),a=e.get("inStock"),i=a==="1"?!0:a==="0"?!1:void 0;return{tags:r&&r.length?r:void 0,priceMin:s,priceMax:o,inStock:i}}function Lb(e,t){t.tags?.length?e.set("tags",t.tags.join(",")):e.delete("tags"),typeof t.priceMin=="number"?e.set("min",String(t.priceMin)):e.delete("min"),typeof t.priceMax=="number"?e.set("max",String(t.priceMax)):e.delete("max"),typeof t.inStock=="boolean"?e.set("inStock",t.inStock?"1":"0"):e.delete("inStock")}function qa({includeCategory:e}){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),r=t.get("q")??"",s=t.get("sort")??"featured",o=ra(t.get("page"))??1,a=Db(t),i=e?t.get("cat")??void 0:void 0;return{search:r,sort:s,page:Math.max(1,Math.floor(o)),category:i,filters:a}}function Ha(e,{includeCategory:t}){const r=JSON.stringify(e.filters.tags??[]);x.useEffect(()=>{if(typeof window>"u")return;const s=window.setTimeout(()=>{const o=new URL(window.location.href),a=o.searchParams;e.search.trim()?a.set("q",e.search.trim()):a.delete("q"),e.sort&&e.sort!=="featured"?a.set("sort",e.sort):a.delete("sort"),e.page&&e.page!==1?a.set("page",String(e.page)):a.delete("page"),t&&(e.category?a.set("cat",e.category):a.delete("cat")),Lb(a,e.filters);const i=`${o.pathname}?${a.toString()}${o.hash}`,c=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==c&&window.history.replaceState({},"",i)},250);return()=>window.clearTimeout(s)},[t,e.category,e.page,e.search,e.sort,r,e.filters.priceMin,e.filters.priceMax,e.filters.inStock])}function Cc(e,t){return`${e}::${t??""}`}function $b(e,t){if(t&&e.variants?.length){const r=e.variants.find(s=>s.id===t);if(r)return{qty:r.inventoryQuantity,status:r.inventoryStatus}}return{qty:e.inventoryQuantity,status:e.inventoryStatus}}function zb(e,t){const r={productId:e.productId,variantId:e.variantId,isOutOfStock:!1,exceedsAvailable:!1,isLowStock:!1};if(!t)return{...r,isOutOfStock:!0,message:"This product is no longer available"};const{qty:s,status:o}=$b(t,e.variantId);return r.availableQty=s,r.status=o,o==="out_of_stock"||typeof s=="number"&&s<=0?{...r,isOutOfStock:!0,message:"Out of stock"}:typeof s=="number"&&e.qty>s?{...r,exceedsAvailable:!0,message:s===0?"Out of stock":`Only ${s} available (you have ${e.qty} in cart)`}:o==="low"||typeof s=="number"&&s>0&&s<=5?{...r,isLowStock:!0,message:typeof s=="number"?`Only ${s} left`:"Low stock"}:r}function Za({items:e,refreshInterval:t=3e4,skip:r=!1}){const{config:s}=Re(),[o,a]=x.useState(new Map),[i,c]=x.useState(!1),[l,d]=x.useState(null),m=x.useMemo(()=>{const _=new Set;for(const g of e)_.add(g.productId);return Array.from(_)},[e]),u=x.useCallback(async()=>{if(r||m.length===0){a(new Map);return}c(!0),d(null);try{const _=await Promise.all(m.map(async w=>{try{return await s.adapter.getProductBySlug(w)}catch{return null}})),g=new Map;for(const w of _)w&&(g.set(w.id,w),w.slug&&w.slug!==w.id&&g.set(w.slug,w));const f=new Map;for(const w of e){const j=Cc(w.productId,w.variantId),b=g.get(w.productId)??null;f.set(j,zb(w,b))}a(f)}catch(_){d(_ instanceof Error?_.message:"Failed to check inventory")}finally{c(!1)}},[s.adapter,e,m,r]);x.useEffect(()=>{u()},[u]),x.useEffect(()=>{if(r||t<=0||m.length===0)return;const _=setInterval(u,t);return()=>clearInterval(_)},[u,m.length,t,r]);const p=x.useCallback((_,g)=>o.get(Cc(_,g)),[o]),h=x.useMemo(()=>{for(const _ of o.values())if(_.isOutOfStock||_.exceedsAvailable)return!0;return!1},[o]);return{inventory:o,isLoading:i,error:l,refresh:u,getItemInventory:p,hasIssues:h}}function Fb(e,t){if(t&&e.variants?.length){const r=e.variants.find(s=>s.id===t);if(r)return{qty:r.inventoryQuantity,status:r.inventoryStatus}}return{qty:e.inventoryQuantity,status:e.inventoryStatus}}function Bb(e,t,r){if(!t)return e.titleSnapshot??"Unknown Product";const s=t.title??e.titleSnapshot??"Product";if(r&&t.variants?.length){const o=t.variants.find(a=>a.id===r);if(o?.title)return`${s} - ${o.title}`}return s}function Ub(e,t){const r=Bb(e,t,e.variantId);if(!t)return{productId:e.productId,variantId:e.variantId,title:r,requestedQty:e.qty,availableQty:0,type:"product_unavailable",message:"This product is no longer available"};const{qty:s,status:o}=Fb(t,e.variantId);return o==="out_of_stock"||typeof s=="number"&&s<=0?{productId:e.productId,variantId:e.variantId,title:r,requestedQty:e.qty,availableQty:0,type:"out_of_stock",message:"This item is out of stock"}:typeof s=="number"&&e.qty>s?{productId:e.productId,variantId:e.variantId,title:r,requestedQty:e.qty,availableQty:s,type:"insufficient_stock",message:s===0?"This item is out of stock":`Only ${s} available`}:null}function Ud({items:e}){const{config:t}=Re(),[r,s]=x.useState(null),[o,a]=x.useState(!1),[i,c]=x.useState(null),l=x.useMemo(()=>{const u=new Set;for(const p of e)u.add(p.productId);return Array.from(u)},[e]),d=x.useCallback(async()=>{if(e.length===0){const u={ok:!0,issues:[],verifiedAt:new Date};return s(u),u}a(!0),c(null);try{const u=await Promise.all(l.map(async g=>{try{return await t.adapter.getProductBySlug(g)}catch{return null}})),p=new Map;for(const g of u)g&&(p.set(g.id,g),g.slug&&g.slug!==g.id&&p.set(g.slug,g));const h=[];for(const g of e){const f=p.get(g.productId)??null,w=Ub(g,f);w&&h.push(w)}const _={ok:h.length===0,issues:h,verifiedAt:new Date};return s(_),a(!1),_}catch(u){const p=u instanceof Error?u.message:"Failed to verify inventory";c(p),a(!1);const h={ok:!1,issues:[],verifiedAt:new Date};return s(h),h}},[t.adapter,e,l]),m=x.useCallback(()=>{s(null),c(null)},[]);return{result:r,isVerifying:o,error:i,verify:d,reset:m}}function Wb({items:e,onExpiry:t,enabled:r=!0}){const[s,o]=x.useState([]),[a,i]=x.useState([]),c=x.useRef(new Set),l=x.useMemo(()=>r?e.filter(d=>d.holdId&&d.holdExpiresAt):[],[e,r]);return x.useEffect(()=>{if(!r||l.length===0){o([]),i([]);return}const d=()=>{const u=Date.now(),p=120*1e3,h=[],_=[];for(const g of l){if(!g.holdExpiresAt)continue;const f=new Date(g.holdExpiresAt),w=f.getTime()-u,j=`${g.productId}::${g.variantId??""}`;w<=0?(h.push({productId:g.productId,variantId:g.variantId}),c.current.has(j)||(c.current.add(j),t?.({productId:g.productId,variantId:g.variantId,title:g.titleSnapshot,expiredAt:f}))):w<=p&&_.push({productId:g.productId,variantId:g.variantId,expiresAt:f,remainingMs:w})}o(h),i(_)};d();const m=setInterval(d,1e4);return()=>clearInterval(m)},[r,l,t]),x.useEffect(()=>{const d=new Set(l.map(m=>`${m.productId}::${m.variantId??""}`));for(const m of c.current)d.has(m)||c.current.delete(m)},[l]),{expiringItems:a,expiredItems:s}}const Ne={relatedProducts:{mode:"most_recent",maxItems:4,layout:{layout:"large",imageCrop:"center"}},catalog:{filters:{tags:!0,priceRange:!0,inStock:!0},sort:{featured:!0,priceAsc:!0,priceDesc:!0}},checkout:{promoCodes:!0},shopLayout:{layout:"large",imageCrop:"center"},categoryLayout:{layout:"large",imageCrop:"center"},sections:{showDescription:!0,showSpecs:!0,showShipping:!0,showRelatedProducts:!0},inventory:{preCheckoutVerification:!0,holdsEnabled:!1,holdDurationMinutes:15},shopPage:{title:"Shop",description:""}};function Vb(e){return{relatedProducts:{mode:e.relatedProducts?.mode||Ne.relatedProducts.mode,maxItems:e.relatedProducts?.maxItems||Ne.relatedProducts.maxItems,layout:{layout:e.relatedProducts?.layout?.layout??Ne.relatedProducts.layout.layout,imageCrop:e.relatedProducts?.layout?.imageCrop??Ne.relatedProducts.layout.imageCrop}},catalog:{filters:{tags:e.catalog?.filters?.tags??Ne.catalog.filters.tags,priceRange:e.catalog?.filters?.priceRange??Ne.catalog.filters.priceRange,inStock:e.catalog?.filters?.inStock??Ne.catalog.filters.inStock},sort:{featured:e.catalog?.sort?.featured??Ne.catalog.sort.featured,priceAsc:e.catalog?.sort?.priceAsc??Ne.catalog.sort.priceAsc,priceDesc:e.catalog?.sort?.priceDesc??Ne.catalog.sort.priceDesc}},checkout:{promoCodes:e.checkout?.promoCodes??Ne.checkout.promoCodes},shopLayout:{layout:e.shopLayout?.layout??Ne.shopLayout.layout,imageCrop:e.shopLayout?.imageCrop??Ne.shopLayout.imageCrop},categoryLayout:{layout:e.categoryLayout?.layout??Ne.categoryLayout.layout,imageCrop:e.categoryLayout?.imageCrop??Ne.categoryLayout.imageCrop},sections:{showDescription:e.sections?.showDescription??Ne.sections.showDescription,showSpecs:e.sections?.showSpecs??Ne.sections.showSpecs,showShipping:e.sections?.showShipping??Ne.sections.showShipping,showRelatedProducts:e.sections?.showRelatedProducts??Ne.sections.showRelatedProducts},inventory:{preCheckoutVerification:e.inventory?.preCheckoutVerification??Ne.inventory.preCheckoutVerification,holdsEnabled:e.inventory?.holdsEnabled??Ne.inventory.holdsEnabled,holdDurationMinutes:e.inventory?.holdDurationMinutes??Ne.inventory.holdDurationMinutes},shopPage:{title:e.shopPage?.title??Ne.shopPage.title,description:e.shopPage?.description??Ne.shopPage.description}}}function or(e={}){const r=Oa()?.config?.adapter,[s,o]=y.useState(Ne),[a,i]=y.useState(!!r?.getStorefrontSettings);return y.useEffect(()=>{if(!r?.getStorefrontSettings){i(!1);return}let c=!1;async function l(){try{const d=await r.getStorefrontSettings();!c&&d&&o(Vb(d))}catch{}finally{c||i(!1)}}return l(),()=>{c=!0}},[r]),{settings:s,isLoading:a}}const qb={card:!0,crypto:!0,credits:!1};function Wd(){const t=Oa()?.config?.adapter,[r,s]=y.useState(qb),[o,a]=y.useState(!!t?.getPaymentMethodsConfig);return y.useEffect(()=>{if(!t?.getPaymentMethodsConfig){a(!1);return}let i=!1;async function c(){try{const l=await t.getPaymentMethodsConfig();!i&&l&&s(l)}catch{}finally{i||a(!1)}}return c(),()=>{i=!0}},[t]),{config:r,isLoading:o}}const Nc=new Map;function Hb(e){return e.productId?`id:${e.productId}`:e.name?`name:${e.name}`:""}function Vd(e={}){const{productId:t,product:r,enabled:s=!0}=e,a=Oa()?.config?.adapter,[i,c]=y.useState(null),[l,d]=y.useState(null),[m,u]=y.useState(!1),[p,h]=y.useState(null),_=y.useRef(0),g=y.useCallback(async()=>{const f=t?{productId:t}:r?{name:r.name,description:r.description,tags:r.tags,categoryIds:r.categoryIds}:{};if(!f.productId&&!f.name)return;if(!a?.getAIRelatedProducts){h("AI recommendations not available");return}const w=Hb(f),j=Nc.get(w);if(j){c(j.relatedProductIds),d(j.reasoning),h(null);return}const b=++_.current;u(!0),h(null);try{const v=await a.getAIRelatedProducts(f);b===_.current&&(c(v.relatedProductIds),d(v.reasoning),h(null),w&&Nc.set(w,v))}catch(v){if(b===_.current){const k=v instanceof Error?v.message:"Failed to get AI recommendations";h(k),c(null),d(null)}}finally{b===_.current&&u(!1)}},[a,t,r]);return y.useEffect(()=>{s&&(!t&&!r?.name||g())},[s,t,r?.name,g]),{relatedProductIds:i,reasoning:l,isLoading:m,error:p,refetch:g}}function Ie(e,t){if(!e)throw new Error(t)}function Et(e){return typeof e=="string"&&e.trim().length>0}async function Zb(e,t={}){const r=t.pageSize??10,s=await e.listCategories();Ie(Array.isArray(s),"listCategories() must return an array");for(const i of s)Ie(Et(i.id),"Category.id is required"),Ie(Et(i.slug),"Category.slug is required"),Ie(Et(i.name),"Category.name is required");const o=await e.listProducts({page:1,pageSize:r});if(Ie(o&&Array.isArray(o.items),"listProducts() must return { items: Product[] }"),Ie(typeof o.page=="number","listProducts().page must be a number"),Ie(typeof o.pageSize=="number","listProducts().pageSize must be a number"),o.items.length>0){const i=o.items[0];Ie(Et(i.id),"Product.id is required"),Ie(Et(i.slug),"Product.slug is required"),Ie(Et(i.title),"Product.title is required"),Ie(typeof i.description=="string","Product.description must be a string"),Ie(Array.isArray(i.images),"Product.images must be an array"),Ie(typeof i.price=="number","Product.price must be a number"),Ie(Et(i.currency),"Product.currency is required"),Ie(Array.isArray(i.tags),"Product.tags must be an array"),Ie(Array.isArray(i.categoryIds),"Product.categoryIds must be an array");const c=await e.getProductBySlug(i.slug);Ie(c===null||Et(c.id),"getProductBySlug() must return Product or null")}const a=await e.getOrderHistory();Ie(Array.isArray(a),"getOrderHistory() must return an array");for(const i of a)Ie(Et(i.id),"Order.id is required"),Ie(Et(i.createdAt),"Order.createdAt is required"),Ie(typeof i.total=="number","Order.total must be a number"),Ie(Et(i.currency),"Order.currency is required"),Ie(Array.isArray(i.items),"Order.items must be an array")}function Pc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ar(...e){return t=>{let r=!1;const s=e.map(o=>{const a=Pc(o,t);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let o=0;o<s.length;o++){const a=s[o];typeof a=="function"?a():Pc(e[o],null)}}}}function Ee(...e){return x.useCallback(ar(...e),e)}var Gb=Symbol.for("react.lazy"),bs=x[" use ".trim().toString()];function Qb(e){return typeof e=="object"&&e!==null&&"then"in e}function qd(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Gb&&"_payload"in e&&Qb(e._payload)}function Hd(e){const t=Kb(e),r=x.forwardRef((s,o)=>{let{children:a,...i}=s;qd(a)&&typeof bs=="function"&&(a=bs(a._payload));const c=x.Children.toArray(a),l=c.find(Jb);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}var Yb=Hd("Slot");function Kb(e){const t=x.forwardRef((r,s)=>{let{children:o,...a}=r;if(qd(o)&&typeof bs=="function"&&(o=bs(o._payload)),x.isValidElement(o)){const i=t0(o),c=e0(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Xb=Symbol("radix.slottable");function Jb(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Xb}function e0(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function t0(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function Zd(e){var t,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(r=Zd(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function Gd(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=Zd(e))&&(s&&(s+=" "),s+=t);return s}const Ac=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Ec=Gd,Ga=(e,t)=>r=>{var s;if(t?.variants==null)return Ec(e,r?.class,r?.className);const{variants:o,defaultVariants:a}=t,i=Object.keys(o).map(d=>{const m=r?.[d],u=a?.[d];if(m===null)return null;const p=Ac(m)||Ac(u);return o[d][p]}),c=r&&Object.entries(r).reduce((d,m)=>{let[u,p]=m;return p===void 0||(d[u]=p),d},{}),l=t==null||(s=t.compoundVariants)===null||s===void 0?void 0:s.reduce((d,m)=>{let{class:u,className:p,...h}=m;return Object.entries(h).every(_=>{let[g,f]=_;return Array.isArray(f)?f.includes({...a,...c}[g]):{...a,...c}[g]===f})?[...d,u,p]:d},[]);return Ec(e,i,l,r?.class,r?.className)},n0=(e,t)=>{const r=new Array(e.length+t.length);for(let s=0;s<e.length;s++)r[s]=e[s];for(let s=0;s<t.length;s++)r[e.length+s]=t[s];return r},r0=(e,t)=>({classGroupId:e,validator:t}),Qd=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),ws="-",Tc=[],s0="arbitrary..",o0=e=>{const t=i0(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return a0(i);const c=i.split(ws),l=c[0]===""&&c.length>1?1:0;return Yd(c,l,t)},getConflictingClassGroupIds:(i,c)=>{if(c){const l=s[i],d=r[i];return l?d?n0(d,l):l:d||Tc}return r[i]||Tc}}},Yd=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],a=r.nextPart.get(o);if(a){const d=Yd(e,t+1,a);if(d)return d}const i=r.validators;if(i===null)return;const c=t===0?e.join(ws):e.slice(t).join(ws),l=i.length;for(let d=0;d<l;d++){const m=i[d];if(m.validator(c))return m.classGroupId}},a0=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),s=t.slice(0,r);return s?s0+s:void 0})(),i0=e=>{const{theme:t,classGroups:r}=e;return c0(r,t)},c0=(e,t)=>{const r=Qd();for(const s in e){const o=e[s];Qa(o,r,s,t)}return r},Qa=(e,t,r,s)=>{const o=e.length;for(let a=0;a<o;a++){const i=e[a];l0(i,t,r,s)}},l0=(e,t,r,s)=>{if(typeof e=="string"){d0(e,t,r);return}if(typeof e=="function"){u0(e,t,r,s);return}m0(e,t,r,s)},d0=(e,t,r)=>{const s=e===""?t:Kd(t,e);s.classGroupId=r},u0=(e,t,r,s)=>{if(p0(e)){Qa(e(s),t,r,s);return}t.validators===null&&(t.validators=[]),t.validators.push(r0(r,e))},m0=(e,t,r,s)=>{const o=Object.entries(e),a=o.length;for(let i=0;i<a;i++){const[c,l]=o[i];Qa(l,Kd(t,c),r,s)}},Kd=(e,t)=>{let r=e;const s=t.split(ws),o=s.length;for(let a=0;a<o;a++){const i=s[a];let c=r.nextPart.get(i);c||(c=Qd(),r.nextPart.set(i,c)),r=c}return r},p0=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,f0=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),s=Object.create(null);const o=(a,i)=>{r[a]=i,t++,t>e&&(t=0,s=r,r=Object.create(null))};return{get(a){let i=r[a];if(i!==void 0)return i;if((i=s[a])!==void 0)return o(a,i),i},set(a,i){a in r?r[a]=i:o(a,i)}}},sa="!",Ic=":",h0=[],Rc=(e,t,r,s,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),g0=e=>{const{prefix:t,experimentalParseClassName:r}=e;let s=o=>{const a=[];let i=0,c=0,l=0,d;const m=o.length;for(let g=0;g<m;g++){const f=o[g];if(i===0&&c===0){if(f===Ic){a.push(o.slice(l,g)),l=g+1;continue}if(f==="/"){d=g;continue}}f==="["?i++:f==="]"?i--:f==="("?c++:f===")"&&c--}const u=a.length===0?o:o.slice(l);let p=u,h=!1;u.endsWith(sa)?(p=u.slice(0,-1),h=!0):u.startsWith(sa)&&(p=u.slice(1),h=!0);const _=d&&d>l?d-l:void 0;return Rc(a,h,p,_)};if(t){const o=t+Ic,a=s;s=i=>i.startsWith(o)?a(i.slice(o.length)):Rc(h0,!1,i,void 0,!0)}if(r){const o=s;s=a=>r({className:a,parseClassName:o})}return s},x0=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,s)=>{t.set(r,1e6+s)}),r=>{const s=[];let o=[];for(let a=0;a<r.length;a++){const i=r[a],c=i[0]==="[",l=t.has(i);c||l?(o.length>0&&(o.sort(),s.push(...o),o=[]),s.push(i)):o.push(i)}return o.length>0&&(o.sort(),s.push(...o)),s}},y0=e=>({cache:f0(e.cacheSize),parseClassName:g0(e),sortModifiers:x0(e),...o0(e)}),v0=/\s+/,b0=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:a}=t,i=[],c=e.trim().split(v0);let l="";for(let d=c.length-1;d>=0;d-=1){const m=c[d],{isExternal:u,modifiers:p,hasImportantModifier:h,baseClassName:_,maybePostfixModifierPosition:g}=r(m);if(u){l=m+(l.length>0?" "+l:l);continue}let f=!!g,w=s(f?_.substring(0,g):_);if(!w){if(!f){l=m+(l.length>0?" "+l:l);continue}if(w=s(_),!w){l=m+(l.length>0?" "+l:l);continue}f=!1}const j=p.length===0?"":p.length===1?p[0]:a(p).join(":"),b=h?j+sa:j,v=b+w;if(i.indexOf(v)>-1)continue;i.push(v);const k=o(w,f);for(let R=0;R<k.length;++R){const N=k[R];i.push(b+N)}l=m+(l.length>0?" "+l:l)}return l},w0=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=Xd(r))&&(o&&(o+=" "),o+=s);return o},Xd=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=Xd(e[s]))&&(r&&(r+=" "),r+=t);return r},_0=(e,...t)=>{let r,s,o,a;const i=l=>{const d=t.reduce((m,u)=>u(m),e());return r=y0(d),s=r.cache.get,o=r.cache.set,a=c,c(l)},c=l=>{const d=s(l);if(d)return d;const m=b0(l,r);return o(l,m),m};return a=i,(...l)=>a(w0(...l))},j0=[],Ze=e=>{const t=r=>r[e]||j0;return t.isThemeGetter=!0,t},Jd=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,eu=/^\((?:(\w[\w-]*):)?(.+)\)$/i,k0=/^\d+\/\d+$/,S0=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,C0=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,N0=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,P0=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,A0=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Hn=e=>k0.test(e),ye=e=>!!e&&!Number.isNaN(Number(e)),an=e=>!!e&&Number.isInteger(Number(e)),Eo=e=>e.endsWith("%")&&ye(e.slice(0,-1)),nn=e=>S0.test(e),E0=()=>!0,T0=e=>C0.test(e)&&!N0.test(e),tu=()=>!1,I0=e=>P0.test(e),R0=e=>A0.test(e),O0=e=>!se(e)&&!oe(e),M0=e=>ir(e,su,tu),se=e=>Jd.test(e),Cn=e=>ir(e,ou,T0),To=e=>ir(e,F0,ye),Oc=e=>ir(e,nu,tu),D0=e=>ir(e,ru,R0),Yr=e=>ir(e,au,I0),oe=e=>eu.test(e),hr=e=>cr(e,ou),L0=e=>cr(e,B0),Mc=e=>cr(e,nu),$0=e=>cr(e,su),z0=e=>cr(e,ru),Kr=e=>cr(e,au,!0),ir=(e,t,r)=>{const s=Jd.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},cr=(e,t,r=!1)=>{const s=eu.exec(e);return s?s[1]?t(s[1]):r:!1},nu=e=>e==="position"||e==="percentage",ru=e=>e==="image"||e==="url",su=e=>e==="length"||e==="size"||e==="bg-size",ou=e=>e==="length",F0=e=>e==="number",B0=e=>e==="family-name",au=e=>e==="shadow",U0=()=>{const e=Ze("color"),t=Ze("font"),r=Ze("text"),s=Ze("font-weight"),o=Ze("tracking"),a=Ze("leading"),i=Ze("breakpoint"),c=Ze("container"),l=Ze("spacing"),d=Ze("radius"),m=Ze("shadow"),u=Ze("inset-shadow"),p=Ze("text-shadow"),h=Ze("drop-shadow"),_=Ze("blur"),g=Ze("perspective"),f=Ze("aspect"),w=Ze("ease"),j=Ze("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],v=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],k=()=>[...v(),oe,se],R=()=>["auto","hidden","clip","visible","scroll"],N=()=>["auto","contain","none"],C=()=>[oe,se,l],T=()=>[Hn,"full","auto",...C()],O=()=>[an,"none","subgrid",oe,se],$=()=>["auto",{span:["full",an,oe,se]},an,oe,se],S=()=>[an,"auto",oe,se],A=()=>["auto","min","max","fr",oe,se],I=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],B=()=>["start","end","center","stretch","center-safe","end-safe"],D=()=>["auto",...C()],E=()=>[Hn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...C()],P=()=>[e,oe,se],z=()=>[...v(),Mc,Oc,{position:[oe,se]}],Z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],K=()=>["auto","cover","contain",$0,M0,{size:[oe,se]}],L=()=>[Eo,hr,Cn],W=()=>["","none","full",d,oe,se],Y=()=>["",ye,hr,Cn],V=()=>["solid","dashed","dotted","double"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],F=()=>[ye,Eo,Mc,Oc],ee=()=>["","none",_,oe,se],pe=()=>["none",ye,oe,se],q=()=>["none",ye,oe,se],ne=()=>[ye,oe,se],le=()=>[Hn,"full",...C()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[nn],breakpoint:[nn],color:[E0],container:[nn],"drop-shadow":[nn],ease:["in","out","in-out"],font:[O0],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[nn],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[nn],shadow:[nn],spacing:["px",ye],text:[nn],"text-shadow":[nn],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Hn,se,oe,f]}],container:["container"],columns:[{columns:[ye,se,oe,c]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:k()}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:N()}],"overscroll-x":[{"overscroll-x":N()}],"overscroll-y":[{"overscroll-y":N()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{start:T()}],end:[{end:T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[an,"auto",oe,se]}],basis:[{basis:[Hn,"full","auto",c,...C()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ye,Hn,"auto","initial","none",se]}],grow:[{grow:["",ye,oe,se]}],shrink:[{shrink:["",ye,oe,se]}],order:[{order:[an,"first","last","none",oe,se]}],"grid-cols":[{"grid-cols":O()}],"col-start-end":[{col:$()}],"col-start":[{"col-start":S()}],"col-end":[{"col-end":S()}],"grid-rows":[{"grid-rows":O()}],"row-start-end":[{row:$()}],"row-start":[{"row-start":S()}],"row-end":[{"row-end":S()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":A()}],"auto-rows":[{"auto-rows":A()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...I(),"normal"]}],"justify-items":[{"justify-items":[...B(),"normal"]}],"justify-self":[{"justify-self":["auto",...B()]}],"align-content":[{content:["normal",...I()]}],"align-items":[{items:[...B(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...B(),{baseline:["","last"]}]}],"place-content":[{"place-content":I()}],"place-items":[{"place-items":[...B(),"baseline"]}],"place-self":[{"place-self":["auto",...B()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:D()}],mx:[{mx:D()}],my:[{my:D()}],ms:[{ms:D()}],me:[{me:D()}],mt:[{mt:D()}],mr:[{mr:D()}],mb:[{mb:D()}],ml:[{ml:D()}],"space-x":[{"space-x":C()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":C()}],"space-y-reverse":["space-y-reverse"],size:[{size:E()}],w:[{w:[c,"screen",...E()]}],"min-w":[{"min-w":[c,"screen","none",...E()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[i]},...E()]}],h:[{h:["screen","lh",...E()]}],"min-h":[{"min-h":["screen","lh","none",...E()]}],"max-h":[{"max-h":["screen","lh",...E()]}],"font-size":[{text:["base",r,hr,Cn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,oe,To]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Eo,se]}],"font-family":[{font:[L0,se,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,oe,se]}],"line-clamp":[{"line-clamp":[ye,"none",oe,To]}],leading:[{leading:[a,...C()]}],"list-image":[{"list-image":["none",oe,se]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",oe,se]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:P()}],"text-color":[{text:P()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:[ye,"from-font","auto",oe,Cn]}],"text-decoration-color":[{decoration:P()}],"underline-offset":[{"underline-offset":[ye,"auto",oe,se]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",oe,se]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",oe,se]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:Z()}],"bg-size":[{bg:K()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},an,oe,se],radial:["",oe,se],conic:[an,oe,se]},z0,D0]}],"bg-color":[{bg:P()}],"gradient-from-pos":[{from:L()}],"gradient-via-pos":[{via:L()}],"gradient-to-pos":[{to:L()}],"gradient-from":[{from:P()}],"gradient-via":[{via:P()}],"gradient-to":[{to:P()}],rounded:[{rounded:W()}],"rounded-s":[{"rounded-s":W()}],"rounded-e":[{"rounded-e":W()}],"rounded-t":[{"rounded-t":W()}],"rounded-r":[{"rounded-r":W()}],"rounded-b":[{"rounded-b":W()}],"rounded-l":[{"rounded-l":W()}],"rounded-ss":[{"rounded-ss":W()}],"rounded-se":[{"rounded-se":W()}],"rounded-ee":[{"rounded-ee":W()}],"rounded-es":[{"rounded-es":W()}],"rounded-tl":[{"rounded-tl":W()}],"rounded-tr":[{"rounded-tr":W()}],"rounded-br":[{"rounded-br":W()}],"rounded-bl":[{"rounded-bl":W()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...V(),"hidden","none"]}],"divide-style":[{divide:[...V(),"hidden","none"]}],"border-color":[{border:P()}],"border-color-x":[{"border-x":P()}],"border-color-y":[{"border-y":P()}],"border-color-s":[{"border-s":P()}],"border-color-e":[{"border-e":P()}],"border-color-t":[{"border-t":P()}],"border-color-r":[{"border-r":P()}],"border-color-b":[{"border-b":P()}],"border-color-l":[{"border-l":P()}],"divide-color":[{divide:P()}],"outline-style":[{outline:[...V(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ye,oe,se]}],"outline-w":[{outline:["",ye,hr,Cn]}],"outline-color":[{outline:P()}],shadow:[{shadow:["","none",m,Kr,Yr]}],"shadow-color":[{shadow:P()}],"inset-shadow":[{"inset-shadow":["none",u,Kr,Yr]}],"inset-shadow-color":[{"inset-shadow":P()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:P()}],"ring-offset-w":[{"ring-offset":[ye,Cn]}],"ring-offset-color":[{"ring-offset":P()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":P()}],"text-shadow":[{"text-shadow":["none",p,Kr,Yr]}],"text-shadow-color":[{"text-shadow":P()}],opacity:[{opacity:[ye,oe,se]}],"mix-blend":[{"mix-blend":[...ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":F()}],"mask-image-linear-to-pos":[{"mask-linear-to":F()}],"mask-image-linear-from-color":[{"mask-linear-from":P()}],"mask-image-linear-to-color":[{"mask-linear-to":P()}],"mask-image-t-from-pos":[{"mask-t-from":F()}],"mask-image-t-to-pos":[{"mask-t-to":F()}],"mask-image-t-from-color":[{"mask-t-from":P()}],"mask-image-t-to-color":[{"mask-t-to":P()}],"mask-image-r-from-pos":[{"mask-r-from":F()}],"mask-image-r-to-pos":[{"mask-r-to":F()}],"mask-image-r-from-color":[{"mask-r-from":P()}],"mask-image-r-to-color":[{"mask-r-to":P()}],"mask-image-b-from-pos":[{"mask-b-from":F()}],"mask-image-b-to-pos":[{"mask-b-to":F()}],"mask-image-b-from-color":[{"mask-b-from":P()}],"mask-image-b-to-color":[{"mask-b-to":P()}],"mask-image-l-from-pos":[{"mask-l-from":F()}],"mask-image-l-to-pos":[{"mask-l-to":F()}],"mask-image-l-from-color":[{"mask-l-from":P()}],"mask-image-l-to-color":[{"mask-l-to":P()}],"mask-image-x-from-pos":[{"mask-x-from":F()}],"mask-image-x-to-pos":[{"mask-x-to":F()}],"mask-image-x-from-color":[{"mask-x-from":P()}],"mask-image-x-to-color":[{"mask-x-to":P()}],"mask-image-y-from-pos":[{"mask-y-from":F()}],"mask-image-y-to-pos":[{"mask-y-to":F()}],"mask-image-y-from-color":[{"mask-y-from":P()}],"mask-image-y-to-color":[{"mask-y-to":P()}],"mask-image-radial":[{"mask-radial":[oe,se]}],"mask-image-radial-from-pos":[{"mask-radial-from":F()}],"mask-image-radial-to-pos":[{"mask-radial-to":F()}],"mask-image-radial-from-color":[{"mask-radial-from":P()}],"mask-image-radial-to-color":[{"mask-radial-to":P()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":v()}],"mask-image-conic-pos":[{"mask-conic":[ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":F()}],"mask-image-conic-to-pos":[{"mask-conic-to":F()}],"mask-image-conic-from-color":[{"mask-conic-from":P()}],"mask-image-conic-to-color":[{"mask-conic-to":P()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:Z()}],"mask-size":[{mask:K()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",oe,se]}],filter:[{filter:["","none",oe,se]}],blur:[{blur:ee()}],brightness:[{brightness:[ye,oe,se]}],contrast:[{contrast:[ye,oe,se]}],"drop-shadow":[{"drop-shadow":["","none",h,Kr,Yr]}],"drop-shadow-color":[{"drop-shadow":P()}],grayscale:[{grayscale:["",ye,oe,se]}],"hue-rotate":[{"hue-rotate":[ye,oe,se]}],invert:[{invert:["",ye,oe,se]}],saturate:[{saturate:[ye,oe,se]}],sepia:[{sepia:["",ye,oe,se]}],"backdrop-filter":[{"backdrop-filter":["","none",oe,se]}],"backdrop-blur":[{"backdrop-blur":ee()}],"backdrop-brightness":[{"backdrop-brightness":[ye,oe,se]}],"backdrop-contrast":[{"backdrop-contrast":[ye,oe,se]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ye,oe,se]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ye,oe,se]}],"backdrop-invert":[{"backdrop-invert":["",ye,oe,se]}],"backdrop-opacity":[{"backdrop-opacity":[ye,oe,se]}],"backdrop-saturate":[{"backdrop-saturate":[ye,oe,se]}],"backdrop-sepia":[{"backdrop-sepia":["",ye,oe,se]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",oe,se]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ye,"initial",oe,se]}],ease:[{ease:["linear","initial",w,oe,se]}],delay:[{delay:[ye,oe,se]}],animate:[{animate:["none",j,oe,se]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,oe,se]}],"perspective-origin":[{"perspective-origin":k()}],rotate:[{rotate:pe()}],"rotate-x":[{"rotate-x":pe()}],"rotate-y":[{"rotate-y":pe()}],"rotate-z":[{"rotate-z":pe()}],scale:[{scale:q()}],"scale-x":[{"scale-x":q()}],"scale-y":[{"scale-y":q()}],"scale-z":[{"scale-z":q()}],"scale-3d":["scale-3d"],skew:[{skew:ne()}],"skew-x":[{"skew-x":ne()}],"skew-y":[{"skew-y":ne()}],transform:[{transform:[oe,se,"","none","gpu","cpu"]}],"transform-origin":[{origin:k()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:le()}],"translate-x":[{"translate-x":le()}],"translate-y":[{"translate-y":le()}],"translate-z":[{"translate-z":le()}],"translate-none":["translate-none"],accent:[{accent:P()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:P()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",oe,se]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",oe,se]}],fill:[{fill:["none",...P()]}],"stroke-w":[{stroke:[ye,hr,Cn,To]}],stroke:[{stroke:["none",...P()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},W0=_0(U0);function H(...e){return W0(Gd(e))}const V0=Ga("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-neutral-50/20",{variants:{variant:{default:"bg-neutral-900 text-neutral-50 hover:bg-neutral-900/90 dark:bg-neutral-50 dark:text-neutral-900 dark:hover:bg-neutral-50/90",secondary:"bg-neutral-100 text-neutral-900 hover:bg-neutral-100/80 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800/80",outline:"border border-neutral-200 bg-transparent text-neutral-900 hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800",ghost:"bg-transparent text-neutral-900 hover:bg-neutral-100 dark:text-neutral-50 dark:hover:bg-neutral-800",destructive:"bg-red-600 text-neutral-50 hover:bg-red-600/90 dark:bg-red-500 dark:hover:bg-red-500/90",link:"bg-transparent text-neutral-900 underline-offset-4 hover:underline dark:text-neutral-50"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-6",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ie=x.forwardRef(({className:e,variant:t,size:r,asChild:s,...o},a)=>{const i=s?Yb:"button";return n.jsx(i,{className:H(V0({variant:t,size:r}),e),ref:a,...o})});ie.displayName="Button";const q0=Ga("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors",{variants:{variant:{default:"border-transparent bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900",secondary:"border-transparent bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",outline:"border-neutral-200 text-neutral-900 dark:border-neutral-800 dark:text-neutral-50"}},defaultVariants:{variant:"secondary"}});function Pn({className:e,variant:t,...r}){return n.jsx("div",{className:H(q0({variant:t}),e),...r})}const Rt=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("rounded-xl border border-neutral-200 bg-white text-neutral-950 shadow-sm dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",e),...t}));Rt.displayName="Card";const Er=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex flex-col space-y-1.5 p-6",e),...t}));Er.displayName="CardHeader";const Tr=x.forwardRef(({className:e,...t},r)=>n.jsx("h3",{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));Tr.displayName="CardTitle";const iu=x.forwardRef(({className:e,...t},r)=>n.jsx("p",{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));iu.displayName="CardDescription";const Gt=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("p-6 pt-0",e),...t}));Gt.displayName="CardContent";const cu=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex items-center p-6 pt-0",e),...t}));cu.displayName="CardFooter";const Be=x.forwardRef(({className:e,...t},r)=>n.jsx("input",{ref:r,className:H("flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-50/20",e),...t}));Be.displayName="Input";const at=x.forwardRef(({className:e,...t},r)=>n.jsx("label",{ref:r,className:H("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",e),...t}));at.displayName="Label";var H0=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Z0=H0.reduce((e,t)=>{const r=Hd(`Primitive.${t}`),s=x.forwardRef((o,a)=>{const{asChild:i,...c}=o,l=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(l,{...c,ref:a})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{}),G0="Separator",Dc="horizontal",Q0=["horizontal","vertical"],lu=x.forwardRef((e,t)=>{const{decorative:r,orientation:s=Dc,...o}=e,a=Y0(s)?s:Dc,c=r?{role:"none"}:{"aria-orientation":a==="vertical"?a:void 0,role:"separator"};return n.jsx(Z0.div,{"data-orientation":a,...c,...o,ref:t})});lu.displayName=G0;function Y0(e){return Q0.includes(e)}var du=lu;const St=x.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...s},o)=>n.jsx(du,{ref:o,decorative:r,orientation:t,className:H("shrink-0 bg-neutral-200 dark:bg-neutral-800",t==="horizontal"?"h-px w-full":"h-full w-px",e),...s}));St.displayName=du.displayName;function De({className:e,...t}){return n.jsx("div",{className:H("animate-pulse rounded-md bg-neutral-100 dark:bg-neutral-800",e),...t})}function Lc(e,[t,r]){return Math.min(r,Math.max(t,e))}function _e(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e?.(o),r===!1||!o.defaultPrevented)return t?.(o)}}function K0(e,t){const r=x.createContext(t),s=a=>{const{children:i,...c}=a,l=x.useMemo(()=>c,Object.values(c));return n.jsx(r.Provider,{value:l,children:i})};s.displayName=e+"Provider";function o(a){const i=x.useContext(r);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${a}\` must be used within \`${e}\``)}return[s,o]}function bn(e,t=[]){let r=[];function s(a,i){const c=x.createContext(i),l=r.length;r=[...r,i];const d=u=>{const{scope:p,children:h,..._}=u,g=p?.[e]?.[l]||c,f=x.useMemo(()=>_,Object.values(_));return n.jsx(g.Provider,{value:f,children:h})};d.displayName=a+"Provider";function m(u,p){const h=p?.[e]?.[l]||c,_=x.useContext(h);if(_)return _;if(i!==void 0)return i;throw new Error(`\`${u}\` must be used within \`${a}\``)}return[d,m]}const o=()=>{const a=r.map(i=>x.createContext(i));return function(c){const l=c?.[e]||a;return x.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return o.scopeName=e,[s,X0(o,...t)]}function X0(...e){const t=e[0];if(e.length===1)return t;const r=()=>{const s=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(a){const i=s.reduce((c,{useScope:l,scopeName:d})=>{const u=l(a)[`__scope${d}`];return{...c,...u}},{});return x.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return r.scopeName=t.scopeName,r}function $c(e){const t=J0(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(tw);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function J0(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=rw(o),c=nw(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ew=Symbol("radix.slottable");function tw(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ew}function nw(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function rw(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function Ya(e){const t=e+"CollectionProvider",[r,s]=bn(t),[o,a]=r(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:f,children:w}=g,j=y.useRef(null),b=y.useRef(new Map).current;return n.jsx(o,{scope:f,itemMap:b,collectionRef:j,children:w})};i.displayName=t;const c=e+"CollectionSlot",l=$c(c),d=y.forwardRef((g,f)=>{const{scope:w,children:j}=g,b=a(c,w),v=Ee(f,b.collectionRef);return n.jsx(l,{ref:v,children:j})});d.displayName=c;const m=e+"CollectionItemSlot",u="data-radix-collection-item",p=$c(m),h=y.forwardRef((g,f)=>{const{scope:w,children:j,...b}=g,v=y.useRef(null),k=Ee(f,v),R=a(m,w);return y.useEffect(()=>(R.itemMap.set(v,{ref:v,...b}),()=>void R.itemMap.delete(v))),n.jsx(p,{[u]:"",ref:k,children:j})});h.displayName=m;function _(g){const f=a(e+"CollectionConsumer",g);return y.useCallback(()=>{const j=f.collectionRef.current;if(!j)return[];const b=Array.from(j.querySelectorAll(`[${u}]`));return Array.from(f.itemMap.values()).sort((R,N)=>b.indexOf(R.ref.current)-b.indexOf(N.ref.current))},[f.collectionRef,f.itemMap])}return[{Provider:i,Slot:d,ItemSlot:h},_,s]}var sw=x.createContext(void 0);function Fs(e){const t=x.useContext(sw);return e||t||"ltr"}function ow(e){const t=aw(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(cw);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function aw(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=dw(o),c=lw(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var iw=Symbol("radix.slottable");function cw(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===iw}function lw(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function dw(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var uw=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],be=uw.reduce((e,t)=>{const r=ow(`Primitive.${t}`),s=x.forwardRef((o,a)=>{const{asChild:i,...c}=o,l=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(l,{...c,ref:a})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{});function mw(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function mn(e){const t=x.useRef(e);return x.useEffect(()=>{t.current=e}),x.useMemo(()=>(...r)=>t.current?.(...r),[])}function pw(e,t=globalThis?.document){const r=mn(e);x.useEffect(()=>{const s=o=>{o.key==="Escape"&&r(o)};return t.addEventListener("keydown",s,{capture:!0}),()=>t.removeEventListener("keydown",s,{capture:!0})},[r,t])}var fw="DismissableLayer",oa="dismissableLayer.update",hw="dismissableLayer.pointerDownOutside",gw="dismissableLayer.focusOutside",zc,uu=x.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ka=x.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:i,onDismiss:c,...l}=e,d=x.useContext(uu),[m,u]=x.useState(null),p=m?.ownerDocument??globalThis?.document,[,h]=x.useState({}),_=Ee(t,N=>u(N)),g=Array.from(d.layers),[f]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),w=g.indexOf(f),j=m?g.indexOf(m):-1,b=d.layersWithOutsidePointerEventsDisabled.size>0,v=j>=w,k=vw(N=>{const C=N.target,T=[...d.branches].some(O=>O.contains(C));!v||T||(o?.(N),i?.(N),N.defaultPrevented||c?.())},p),R=bw(N=>{const C=N.target;[...d.branches].some(O=>O.contains(C))||(a?.(N),i?.(N),N.defaultPrevented||c?.())},p);return pw(N=>{j===d.layers.size-1&&(s?.(N),!N.defaultPrevented&&c&&(N.preventDefault(),c()))},p),x.useEffect(()=>{if(m)return r&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(zc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(m)),d.layers.add(m),Fc(),()=>{r&&d.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=zc)}},[m,p,r,d]),x.useEffect(()=>()=>{m&&(d.layers.delete(m),d.layersWithOutsidePointerEventsDisabled.delete(m),Fc())},[m,d]),x.useEffect(()=>{const N=()=>h({});return document.addEventListener(oa,N),()=>document.removeEventListener(oa,N)},[]),n.jsx(be.div,{...l,ref:_,style:{pointerEvents:b?v?"auto":"none":void 0,...e.style},onFocusCapture:_e(e.onFocusCapture,R.onFocusCapture),onBlurCapture:_e(e.onBlurCapture,R.onBlurCapture),onPointerDownCapture:_e(e.onPointerDownCapture,k.onPointerDownCapture)})});Ka.displayName=fw;var xw="DismissableLayerBranch",yw=x.forwardRef((e,t)=>{const r=x.useContext(uu),s=x.useRef(null),o=Ee(t,s);return x.useEffect(()=>{const a=s.current;if(a)return r.branches.add(a),()=>{r.branches.delete(a)}},[r.branches]),n.jsx(be.div,{...e,ref:o})});yw.displayName=xw;function vw(e,t=globalThis?.document){const r=mn(e),s=x.useRef(!1),o=x.useRef(()=>{});return x.useEffect(()=>{const a=c=>{if(c.target&&!s.current){let l=function(){mu(hw,r,d,{discrete:!0})};const d={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);s.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",a)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",a),t.removeEventListener("click",o.current)}},[t,r]),{onPointerDownCapture:()=>s.current=!0}}function bw(e,t=globalThis?.document){const r=mn(e),s=x.useRef(!1);return x.useEffect(()=>{const o=a=>{a.target&&!s.current&&mu(gw,r,{originalEvent:a},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,r]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function Fc(){const e=new CustomEvent(oa);document.dispatchEvent(e)}function mu(e,t,r,{discrete:s}){const o=r.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&o.addEventListener(e,t,{once:!0}),s?mw(o,a):o.dispatchEvent(a)}var Io=0;function pu(){x.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Bc()),document.body.insertAdjacentElement("beforeend",e[1]??Bc()),Io++,()=>{Io===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Io--}},[])}function Bc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Ro="focusScope.autoFocusOnMount",Oo="focusScope.autoFocusOnUnmount",Uc={bubbles:!1,cancelable:!0},ww="FocusScope",Xa=x.forwardRef((e,t)=>{const{loop:r=!1,trapped:s=!1,onMountAutoFocus:o,onUnmountAutoFocus:a,...i}=e,[c,l]=x.useState(null),d=mn(o),m=mn(a),u=x.useRef(null),p=Ee(t,g=>l(g)),h=x.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;x.useEffect(()=>{if(s){let g=function(b){if(h.paused||!c)return;const v=b.target;c.contains(v)?u.current=v:cn(u.current,{select:!0})},f=function(b){if(h.paused||!c)return;const v=b.relatedTarget;v!==null&&(c.contains(v)||cn(u.current,{select:!0}))},w=function(b){if(document.activeElement===document.body)for(const k of b)k.removedNodes.length>0&&cn(c)};document.addEventListener("focusin",g),document.addEventListener("focusout",f);const j=new MutationObserver(w);return c&&j.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",f),j.disconnect()}}},[s,c,h.paused]),x.useEffect(()=>{if(c){Vc.add(h);const g=document.activeElement;if(!c.contains(g)){const w=new CustomEvent(Ro,Uc);c.addEventListener(Ro,d),c.dispatchEvent(w),w.defaultPrevented||(_w(Nw(fu(c)),{select:!0}),document.activeElement===g&&cn(c))}return()=>{c.removeEventListener(Ro,d),setTimeout(()=>{const w=new CustomEvent(Oo,Uc);c.addEventListener(Oo,m),c.dispatchEvent(w),w.defaultPrevented||cn(g??document.body,{select:!0}),c.removeEventListener(Oo,m),Vc.remove(h)},0)}}},[c,d,m,h]);const _=x.useCallback(g=>{if(!r&&!s||h.paused)return;const f=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,w=document.activeElement;if(f&&w){const j=g.currentTarget,[b,v]=jw(j);b&&v?!g.shiftKey&&w===v?(g.preventDefault(),r&&cn(b,{select:!0})):g.shiftKey&&w===b&&(g.preventDefault(),r&&cn(v,{select:!0})):w===j&&g.preventDefault()}},[r,s,h.paused]);return n.jsx(be.div,{tabIndex:-1,...i,ref:p,onKeyDown:_})});Xa.displayName=ww;function _w(e,{select:t=!1}={}){const r=document.activeElement;for(const s of e)if(cn(s,{select:t}),document.activeElement!==r)return}function jw(e){const t=fu(e),r=Wc(t,e),s=Wc(t.reverse(),e);return[r,s]}function fu(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const o=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||o?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function Wc(e,t){for(const r of e)if(!kw(r,{upTo:t}))return r}function kw(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Sw(e){return e instanceof HTMLInputElement&&"select"in e}function cn(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&Sw(e)&&t&&e.select()}}var Vc=Cw();function Cw(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=qc(e,t),e.unshift(t)},remove(t){e=qc(e,t),e[0]?.resume()}}}function qc(e,t){const r=[...e],s=r.indexOf(t);return s!==-1&&r.splice(s,1),r}function Nw(e){return e.filter(t=>t.tagName!=="A")}var Xe=globalThis?.document?x.useLayoutEffect:()=>{},Pw=x[" useId ".trim().toString()]||(()=>{}),Aw=0;function qt(e){const[t,r]=x.useState(Pw());return Xe(()=>{r(s=>s??String(Aw++))},[e]),t?`radix-${t}`:""}const Ew=["top","right","bottom","left"],pn=Math.min,wt=Math.max,_s=Math.round,Xr=Math.floor,Ht=e=>({x:e,y:e}),Tw={left:"right",right:"left",bottom:"top",top:"bottom"},Iw={start:"end",end:"start"};function aa(e,t,r){return wt(e,pn(t,r))}function rn(e,t){return typeof e=="function"?e(t):e}function sn(e){return e.split("-")[0]}function lr(e){return e.split("-")[1]}function Ja(e){return e==="x"?"y":"x"}function ei(e){return e==="y"?"height":"width"}const Rw=new Set(["top","bottom"]);function Vt(e){return Rw.has(sn(e))?"y":"x"}function ti(e){return Ja(Vt(e))}function Ow(e,t,r){r===void 0&&(r=!1);const s=lr(e),o=ti(e),a=ei(o);let i=o==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(i=js(i)),[i,js(i)]}function Mw(e){const t=js(e);return[ia(e),t,ia(t)]}function ia(e){return e.replace(/start|end/g,t=>Iw[t])}const Hc=["left","right"],Zc=["right","left"],Dw=["top","bottom"],Lw=["bottom","top"];function $w(e,t,r){switch(e){case"top":case"bottom":return r?t?Zc:Hc:t?Hc:Zc;case"left":case"right":return t?Dw:Lw;default:return[]}}function zw(e,t,r,s){const o=lr(e);let a=$w(sn(e),r==="start",s);return o&&(a=a.map(i=>i+"-"+o),t&&(a=a.concat(a.map(ia)))),a}function js(e){return e.replace(/left|right|bottom|top/g,t=>Tw[t])}function Fw(e){return{top:0,right:0,bottom:0,left:0,...e}}function hu(e){return typeof e!="number"?Fw(e):{top:e,right:e,bottom:e,left:e}}function ks(e){const{x:t,y:r,width:s,height:o}=e;return{width:s,height:o,top:r,left:t,right:t+s,bottom:r+o,x:t,y:r}}function Gc(e,t,r){let{reference:s,floating:o}=e;const a=Vt(t),i=ti(t),c=ei(i),l=sn(t),d=a==="y",m=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[c]/2-o[c]/2;let h;switch(l){case"top":h={x:m,y:s.y-o.height};break;case"bottom":h={x:m,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(lr(t)){case"start":h[i]-=p*(r&&d?-1:1);break;case"end":h[i]+=p*(r&&d?-1:1);break}return h}const Bw=async(e,t,r)=>{const{placement:s="bottom",strategy:o="absolute",middleware:a=[],platform:i}=r,c=a.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let d=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:u}=Gc(d,s,l),p=s,h={},_=0;for(let g=0;g<c.length;g++){const{name:f,fn:w}=c[g],{x:j,y:b,data:v,reset:k}=await w({x:m,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:h,rects:d,platform:i,elements:{reference:e,floating:t}});m=j??m,u=b??u,h={...h,[f]:{...h[f],...v}},k&&_<=50&&(_++,typeof k=="object"&&(k.placement&&(p=k.placement),k.rects&&(d=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:m,y:u}=Gc(d,p,l)),g=-1)}return{x:m,y:u,placement:p,strategy:o,middlewareData:h}};async function Ir(e,t){var r;t===void 0&&(t={});const{x:s,y:o,platform:a,rects:i,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:m="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=rn(t,e),_=hu(h),f=c[p?u==="floating"?"reference":"floating":u],w=ks(await a.getClippingRect({element:(r=await(a.isElement==null?void 0:a.isElement(f)))==null||r?f:f.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(c.floating)),boundary:d,rootBoundary:m,strategy:l})),j=u==="floating"?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,b=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),v=await(a.isElement==null?void 0:a.isElement(b))?await(a.getScale==null?void 0:a.getScale(b))||{x:1,y:1}:{x:1,y:1},k=ks(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:j,offsetParent:b,strategy:l}):j);return{top:(w.top-k.top+_.top)/v.y,bottom:(k.bottom-w.bottom+_.bottom)/v.y,left:(w.left-k.left+_.left)/v.x,right:(k.right-w.right+_.right)/v.x}}const Uw=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:s,placement:o,rects:a,platform:i,elements:c,middlewareData:l}=t,{element:d,padding:m=0}=rn(e,t)||{};if(d==null)return{};const u=hu(m),p={x:r,y:s},h=ti(o),_=ei(h),g=await i.getDimensions(d),f=h==="y",w=f?"top":"left",j=f?"bottom":"right",b=f?"clientHeight":"clientWidth",v=a.reference[_]+a.reference[h]-p[h]-a.floating[_],k=p[h]-a.reference[h],R=await(i.getOffsetParent==null?void 0:i.getOffsetParent(d));let N=R?R[b]:0;(!N||!await(i.isElement==null?void 0:i.isElement(R)))&&(N=c.floating[b]||a.floating[_]);const C=v/2-k/2,T=N/2-g[_]/2-1,O=pn(u[w],T),$=pn(u[j],T),S=O,A=N-g[_]-$,I=N/2-g[_]/2+C,B=aa(S,I,A),D=!l.arrow&&lr(o)!=null&&I!==B&&a.reference[_]/2-(I<S?O:$)-g[_]/2<0,E=D?I<S?I-S:I-A:0;return{[h]:p[h]+E,data:{[h]:B,centerOffset:I-B-E,...D&&{alignmentOffset:E}},reset:D}}}),Ww=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var r,s;const{placement:o,middlewareData:a,rects:i,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:m=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:_="none",flipAlignment:g=!0,...f}=rn(e,t);if((r=a.arrow)!=null&&r.alignmentOffset)return{};const w=sn(o),j=Vt(c),b=sn(c)===c,v=await(l.isRTL==null?void 0:l.isRTL(d.floating)),k=p||(b||!g?[js(c)]:Mw(c)),R=_!=="none";!p&&R&&k.push(...zw(c,g,_,v));const N=[c,...k],C=await Ir(t,f),T=[];let O=((s=a.flip)==null?void 0:s.overflows)||[];if(m&&T.push(C[w]),u){const I=Ow(o,i,v);T.push(C[I[0]],C[I[1]])}if(O=[...O,{placement:o,overflows:T}],!T.every(I=>I<=0)){var $,S;const I=((($=a.flip)==null?void 0:$.index)||0)+1,B=N[I];if(B&&(!(u==="alignment"?j!==Vt(B):!1)||O.every(P=>Vt(P.placement)===j?P.overflows[0]>0:!0)))return{data:{index:I,overflows:O},reset:{placement:B}};let D=(S=O.filter(E=>E.overflows[0]<=0).sort((E,P)=>E.overflows[1]-P.overflows[1])[0])==null?void 0:S.placement;if(!D)switch(h){case"bestFit":{var A;const E=(A=O.filter(P=>{if(R){const z=Vt(P.placement);return z===j||z==="y"}return!0}).map(P=>[P.placement,P.overflows.filter(z=>z>0).reduce((z,Z)=>z+Z,0)]).sort((P,z)=>P[1]-z[1])[0])==null?void 0:A[0];E&&(D=E);break}case"initialPlacement":D=c;break}if(o!==D)return{reset:{placement:D}}}return{}}}};function Qc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Yc(e){return Ew.some(t=>e[t]>=0)}const Vw=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:s="referenceHidden",...o}=rn(e,t);switch(s){case"referenceHidden":{const a=await Ir(t,{...o,elementContext:"reference"}),i=Qc(a,r.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Yc(i)}}}case"escaped":{const a=await Ir(t,{...o,altBoundary:!0}),i=Qc(a,r.floating);return{data:{escapedOffsets:i,escaped:Yc(i)}}}default:return{}}}}},gu=new Set(["left","top"]);async function qw(e,t){const{placement:r,platform:s,elements:o}=e,a=await(s.isRTL==null?void 0:s.isRTL(o.floating)),i=sn(r),c=lr(r),l=Vt(r)==="y",d=gu.has(i)?-1:1,m=a&&l?-1:1,u=rn(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:_}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return c&&typeof _=="number"&&(h=c==="end"?_*-1:_),l?{x:h*m,y:p*d}:{x:p*d,y:h*m}}const Hw=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var r,s;const{x:o,y:a,placement:i,middlewareData:c}=t,l=await qw(t,e);return i===((r=c.offset)==null?void 0:r.placement)&&(s=c.arrow)!=null&&s.alignmentOffset?{}:{x:o+l.x,y:a+l.y,data:{...l,placement:i}}}}},Zw=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:s,placement:o}=t,{mainAxis:a=!0,crossAxis:i=!1,limiter:c={fn:f=>{let{x:w,y:j}=f;return{x:w,y:j}}},...l}=rn(e,t),d={x:r,y:s},m=await Ir(t,l),u=Vt(sn(o)),p=Ja(u);let h=d[p],_=d[u];if(a){const f=p==="y"?"top":"left",w=p==="y"?"bottom":"right",j=h+m[f],b=h-m[w];h=aa(j,h,b)}if(i){const f=u==="y"?"top":"left",w=u==="y"?"bottom":"right",j=_+m[f],b=_-m[w];_=aa(j,_,b)}const g=c.fn({...t,[p]:h,[u]:_});return{...g,data:{x:g.x-r,y:g.y-s,enabled:{[p]:a,[u]:i}}}}}},Gw=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:r,y:s,placement:o,rects:a,middlewareData:i}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=rn(e,t),m={x:r,y:s},u=Vt(o),p=Ja(u);let h=m[p],_=m[u];const g=rn(c,t),f=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const b=p==="y"?"height":"width",v=a.reference[p]-a.floating[b]+f.mainAxis,k=a.reference[p]+a.reference[b]-f.mainAxis;h<v?h=v:h>k&&(h=k)}if(d){var w,j;const b=p==="y"?"width":"height",v=gu.has(sn(o)),k=a.reference[u]-a.floating[b]+(v&&((w=i.offset)==null?void 0:w[u])||0)+(v?0:f.crossAxis),R=a.reference[u]+a.reference[b]+(v?0:((j=i.offset)==null?void 0:j[u])||0)-(v?f.crossAxis:0);_<k?_=k:_>R&&(_=R)}return{[p]:h,[u]:_}}}},Qw=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var r,s;const{placement:o,rects:a,platform:i,elements:c}=t,{apply:l=()=>{},...d}=rn(e,t),m=await Ir(t,d),u=sn(o),p=lr(o),h=Vt(o)==="y",{width:_,height:g}=a.floating;let f,w;u==="top"||u==="bottom"?(f=u,w=p===(await(i.isRTL==null?void 0:i.isRTL(c.floating))?"start":"end")?"left":"right"):(w=u,f=p==="end"?"top":"bottom");const j=g-m.top-m.bottom,b=_-m.left-m.right,v=pn(g-m[f],j),k=pn(_-m[w],b),R=!t.middlewareData.shift;let N=v,C=k;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(C=b),(s=t.middlewareData.shift)!=null&&s.enabled.y&&(N=j),R&&!p){const O=wt(m.left,0),$=wt(m.right,0),S=wt(m.top,0),A=wt(m.bottom,0);h?C=_-2*(O!==0||$!==0?O+$:wt(m.left,m.right)):N=g-2*(S!==0||A!==0?S+A:wt(m.top,m.bottom))}await l({...t,availableWidth:C,availableHeight:N});const T=await i.getDimensions(c.floating);return _!==T.width||g!==T.height?{reset:{rects:!0}}:{}}}};function Bs(){return typeof window<"u"}function dr(e){return xu(e)?(e.nodeName||"").toLowerCase():"#document"}function _t(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Kt(e){var t;return(t=(xu(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function xu(e){return Bs()?e instanceof Node||e instanceof _t(e).Node:!1}function Ot(e){return Bs()?e instanceof Element||e instanceof _t(e).Element:!1}function Qt(e){return Bs()?e instanceof HTMLElement||e instanceof _t(e).HTMLElement:!1}function Kc(e){return!Bs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof _t(e).ShadowRoot}const Yw=new Set(["inline","contents"]);function zr(e){const{overflow:t,overflowX:r,overflowY:s,display:o}=Mt(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+r)&&!Yw.has(o)}const Kw=new Set(["table","td","th"]);function Xw(e){return Kw.has(dr(e))}const Jw=[":popover-open",":modal"];function Us(e){return Jw.some(t=>{try{return e.matches(t)}catch{return!1}})}const e_=["transform","translate","scale","rotate","perspective"],t_=["transform","translate","scale","rotate","perspective","filter"],n_=["paint","layout","strict","content"];function ni(e){const t=ri(),r=Ot(e)?Mt(e):e;return e_.some(s=>r[s]?r[s]!=="none":!1)||(r.containerType?r.containerType!=="normal":!1)||!t&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!t&&(r.filter?r.filter!=="none":!1)||t_.some(s=>(r.willChange||"").includes(s))||n_.some(s=>(r.contain||"").includes(s))}function r_(e){let t=fn(e);for(;Qt(t)&&!er(t);){if(ni(t))return t;if(Us(t))return null;t=fn(t)}return null}function ri(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const s_=new Set(["html","body","#document"]);function er(e){return s_.has(dr(e))}function Mt(e){return _t(e).getComputedStyle(e)}function Ws(e){return Ot(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function fn(e){if(dr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Kc(e)&&e.host||Kt(e);return Kc(t)?t.host:t}function yu(e){const t=fn(e);return er(t)?e.ownerDocument?e.ownerDocument.body:e.body:Qt(t)&&zr(t)?t:yu(t)}function Rr(e,t,r){var s;t===void 0&&(t=[]),r===void 0&&(r=!0);const o=yu(e),a=o===((s=e.ownerDocument)==null?void 0:s.body),i=_t(o);if(a){const c=ca(i);return t.concat(i,i.visualViewport||[],zr(o)?o:[],c&&r?Rr(c):[])}return t.concat(o,Rr(o,[],r))}function ca(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function vu(e){const t=Mt(e);let r=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Qt(e),a=o?e.offsetWidth:r,i=o?e.offsetHeight:s,c=_s(r)!==a||_s(s)!==i;return c&&(r=a,s=i),{width:r,height:s,$:c}}function si(e){return Ot(e)?e:e.contextElement}function Xn(e){const t=si(e);if(!Qt(t))return Ht(1);const r=t.getBoundingClientRect(),{width:s,height:o,$:a}=vu(t);let i=(a?_s(r.width):r.width)/s,c=(a?_s(r.height):r.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!c||!Number.isFinite(c))&&(c=1),{x:i,y:c}}const o_=Ht(0);function bu(e){const t=_t(e);return!ri()||!t.visualViewport?o_:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function a_(e,t,r){return t===void 0&&(t=!1),!r||t&&r!==_t(e)?!1:t}function Tn(e,t,r,s){t===void 0&&(t=!1),r===void 0&&(r=!1);const o=e.getBoundingClientRect(),a=si(e);let i=Ht(1);t&&(s?Ot(s)&&(i=Xn(s)):i=Xn(e));const c=a_(a,r,s)?bu(a):Ht(0);let l=(o.left+c.x)/i.x,d=(o.top+c.y)/i.y,m=o.width/i.x,u=o.height/i.y;if(a){const p=_t(a),h=s&&Ot(s)?_t(s):s;let _=p,g=ca(_);for(;g&&s&&h!==_;){const f=Xn(g),w=g.getBoundingClientRect(),j=Mt(g),b=w.left+(g.clientLeft+parseFloat(j.paddingLeft))*f.x,v=w.top+(g.clientTop+parseFloat(j.paddingTop))*f.y;l*=f.x,d*=f.y,m*=f.x,u*=f.y,l+=b,d+=v,_=_t(g),g=ca(_)}}return ks({width:m,height:u,x:l,y:d})}function Vs(e,t){const r=Ws(e).scrollLeft;return t?t.left+r:Tn(Kt(e)).left+r}function wu(e,t){const r=e.getBoundingClientRect(),s=r.left+t.scrollLeft-Vs(e,r),o=r.top+t.scrollTop;return{x:s,y:o}}function i_(e){let{elements:t,rect:r,offsetParent:s,strategy:o}=e;const a=o==="fixed",i=Kt(s),c=t?Us(t.floating):!1;if(s===i||c&&a)return r;let l={scrollLeft:0,scrollTop:0},d=Ht(1);const m=Ht(0),u=Qt(s);if((u||!u&&!a)&&((dr(s)!=="body"||zr(i))&&(l=Ws(s)),Qt(s))){const h=Tn(s);d=Xn(s),m.x=h.x+s.clientLeft,m.y=h.y+s.clientTop}const p=i&&!u&&!a?wu(i,l):Ht(0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-l.scrollLeft*d.x+m.x+p.x,y:r.y*d.y-l.scrollTop*d.y+m.y+p.y}}function c_(e){return Array.from(e.getClientRects())}function l_(e){const t=Kt(e),r=Ws(e),s=e.ownerDocument.body,o=wt(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),a=wt(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-r.scrollLeft+Vs(e);const c=-r.scrollTop;return Mt(s).direction==="rtl"&&(i+=wt(t.clientWidth,s.clientWidth)-o),{width:o,height:a,x:i,y:c}}const Xc=25;function d_(e,t){const r=_t(e),s=Kt(e),o=r.visualViewport;let a=s.clientWidth,i=s.clientHeight,c=0,l=0;if(o){a=o.width,i=o.height;const m=ri();(!m||m&&t==="fixed")&&(c=o.offsetLeft,l=o.offsetTop)}const d=Vs(s);if(d<=0){const m=s.ownerDocument,u=m.body,p=getComputedStyle(u),h=m.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,_=Math.abs(s.clientWidth-u.clientWidth-h);_<=Xc&&(a-=_)}else d<=Xc&&(a+=d);return{width:a,height:i,x:c,y:l}}const u_=new Set(["absolute","fixed"]);function m_(e,t){const r=Tn(e,!0,t==="fixed"),s=r.top+e.clientTop,o=r.left+e.clientLeft,a=Qt(e)?Xn(e):Ht(1),i=e.clientWidth*a.x,c=e.clientHeight*a.y,l=o*a.x,d=s*a.y;return{width:i,height:c,x:l,y:d}}function Jc(e,t,r){let s;if(t==="viewport")s=d_(e,r);else if(t==="document")s=l_(Kt(e));else if(Ot(t))s=m_(t,r);else{const o=bu(e);s={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ks(s)}function _u(e,t){const r=fn(e);return r===t||!Ot(r)||er(r)?!1:Mt(r).position==="fixed"||_u(r,t)}function p_(e,t){const r=t.get(e);if(r)return r;let s=Rr(e,[],!1).filter(c=>Ot(c)&&dr(c)!=="body"),o=null;const a=Mt(e).position==="fixed";let i=a?fn(e):e;for(;Ot(i)&&!er(i);){const c=Mt(i),l=ni(i);!l&&c.position==="fixed"&&(o=null),(a?!l&&!o:!l&&c.position==="static"&&!!o&&u_.has(o.position)||zr(i)&&!l&&_u(e,i))?s=s.filter(m=>m!==i):o=c,i=fn(i)}return t.set(e,s),s}function f_(e){let{element:t,boundary:r,rootBoundary:s,strategy:o}=e;const i=[...r==="clippingAncestors"?Us(t)?[]:p_(t,this._c):[].concat(r),s],c=i[0],l=i.reduce((d,m)=>{const u=Jc(t,m,o);return d.top=wt(u.top,d.top),d.right=pn(u.right,d.right),d.bottom=pn(u.bottom,d.bottom),d.left=wt(u.left,d.left),d},Jc(t,c,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function h_(e){const{width:t,height:r}=vu(e);return{width:t,height:r}}function g_(e,t,r){const s=Qt(t),o=Kt(t),a=r==="fixed",i=Tn(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=Ht(0);function d(){l.x=Vs(o)}if(s||!s&&!a)if((dr(t)!=="body"||zr(o))&&(c=Ws(t)),s){const h=Tn(t,!0,a,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&d();a&&!s&&o&&d();const m=o&&!s&&!a?wu(o,c):Ht(0),u=i.left+c.scrollLeft-l.x-m.x,p=i.top+c.scrollTop-l.y-m.y;return{x:u,y:p,width:i.width,height:i.height}}function Mo(e){return Mt(e).position==="static"}function el(e,t){if(!Qt(e)||Mt(e).position==="fixed")return null;if(t)return t(e);let r=e.offsetParent;return Kt(e)===r&&(r=r.ownerDocument.body),r}function ju(e,t){const r=_t(e);if(Us(e))return r;if(!Qt(e)){let o=fn(e);for(;o&&!er(o);){if(Ot(o)&&!Mo(o))return o;o=fn(o)}return r}let s=el(e,t);for(;s&&Xw(s)&&Mo(s);)s=el(s,t);return s&&er(s)&&Mo(s)&&!ni(s)?r:s||r_(e)||r}const x_=async function(e){const t=this.getOffsetParent||ju,r=this.getDimensions,s=await r(e.floating);return{reference:g_(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function y_(e){return Mt(e).direction==="rtl"}const v_={convertOffsetParentRelativeRectToViewportRelativeRect:i_,getDocumentElement:Kt,getClippingRect:f_,getOffsetParent:ju,getElementRects:x_,getClientRects:c_,getDimensions:h_,getScale:Xn,isElement:Ot,isRTL:y_};function ku(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function b_(e,t){let r=null,s;const o=Kt(e);function a(){var c;clearTimeout(s),(c=r)==null||c.disconnect(),r=null}function i(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:m,top:u,width:p,height:h}=d;if(c||t(),!p||!h)return;const _=Xr(u),g=Xr(o.clientWidth-(m+p)),f=Xr(o.clientHeight-(u+h)),w=Xr(m),b={rootMargin:-_+"px "+-g+"px "+-f+"px "+-w+"px",threshold:wt(0,pn(1,l))||1};let v=!0;function k(R){const N=R[0].intersectionRatio;if(N!==l){if(!v)return i();N?i(!1,N):s=setTimeout(()=>{i(!1,1e-7)},1e3)}N===1&&!ku(d,e.getBoundingClientRect())&&i(),v=!1}try{r=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{r=new IntersectionObserver(k,b)}r.observe(e)}return i(!0),a}function w_(e,t,r,s){s===void 0&&(s={});const{ancestorScroll:o=!0,ancestorResize:a=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=s,d=si(e),m=o||a?[...d?Rr(d):[],...Rr(t)]:[];m.forEach(w=>{o&&w.addEventListener("scroll",r,{passive:!0}),a&&w.addEventListener("resize",r)});const u=d&&c?b_(d,r):null;let p=-1,h=null;i&&(h=new ResizeObserver(w=>{let[j]=w;j&&j.target===d&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var b;(b=h)==null||b.observe(t)})),r()}),d&&!l&&h.observe(d),h.observe(t));let _,g=l?Tn(e):null;l&&f();function f(){const w=Tn(e);g&&!ku(g,w)&&r(),g=w,_=requestAnimationFrame(f)}return r(),()=>{var w;m.forEach(j=>{o&&j.removeEventListener("scroll",r),a&&j.removeEventListener("resize",r)}),u?.(),(w=h)==null||w.disconnect(),h=null,l&&cancelAnimationFrame(_)}}const __=Hw,j_=Zw,k_=Ww,S_=Qw,C_=Vw,tl=Uw,N_=Gw,P_=(e,t,r)=>{const s=new Map,o={platform:v_,...r},a={...o.platform,_c:s};return Bw(e,t,{...o,platform:a})};var A_=typeof document<"u",E_=function(){},ls=A_?y.useLayoutEffect:E_;function Ss(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let r,s,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(s=r;s--!==0;)if(!Ss(e[s],t[s]))return!1;return!0}if(o=Object.keys(e),r=o.length,r!==Object.keys(t).length)return!1;for(s=r;s--!==0;)if(!{}.hasOwnProperty.call(t,o[s]))return!1;for(s=r;s--!==0;){const a=o[s];if(!(a==="_owner"&&e.$$typeof)&&!Ss(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function Su(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function nl(e,t){const r=Su(e);return Math.round(t*r)/r}function Do(e){const t=x.useRef(e);return ls(()=>{t.current=e}),t}function T_(e){e===void 0&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:s=[],platform:o,elements:{reference:a,floating:i}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[m,u]=x.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=x.useState(s);Ss(p,s)||h(s);const[_,g]=x.useState(null),[f,w]=x.useState(null),j=x.useCallback(P=>{P!==R.current&&(R.current=P,g(P))},[]),b=x.useCallback(P=>{P!==N.current&&(N.current=P,w(P))},[]),v=a||_,k=i||f,R=x.useRef(null),N=x.useRef(null),C=x.useRef(m),T=l!=null,O=Do(l),$=Do(o),S=Do(d),A=x.useCallback(()=>{if(!R.current||!N.current)return;const P={placement:t,strategy:r,middleware:p};$.current&&(P.platform=$.current),P_(R.current,N.current,P).then(z=>{const Z={...z,isPositioned:S.current!==!1};I.current&&!Ss(C.current,Z)&&(C.current=Z,Is.flushSync(()=>{u(Z)}))})},[p,t,r,$,S]);ls(()=>{d===!1&&C.current.isPositioned&&(C.current.isPositioned=!1,u(P=>({...P,isPositioned:!1})))},[d]);const I=x.useRef(!1);ls(()=>(I.current=!0,()=>{I.current=!1}),[]),ls(()=>{if(v&&(R.current=v),k&&(N.current=k),v&&k){if(O.current)return O.current(v,k,A);A()}},[v,k,A,O,T]);const B=x.useMemo(()=>({reference:R,floating:N,setReference:j,setFloating:b}),[j,b]),D=x.useMemo(()=>({reference:v,floating:k}),[v,k]),E=x.useMemo(()=>{const P={position:r,left:0,top:0};if(!D.floating)return P;const z=nl(D.floating,m.x),Z=nl(D.floating,m.y);return c?{...P,transform:"translate("+z+"px, "+Z+"px)",...Su(D.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:z,top:Z}},[r,c,D.floating,m.x,m.y]);return x.useMemo(()=>({...m,update:A,refs:B,elements:D,floatingStyles:E}),[m,A,B,D,E])}const I_=e=>{function t(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:e,fn(r){const{element:s,padding:o}=typeof e=="function"?e(r):e;return s&&t(s)?s.current!=null?tl({element:s.current,padding:o}).fn(r):{}:s?tl({element:s,padding:o}).fn(r):{}}}},R_=(e,t)=>({...__(e),options:[e,t]}),O_=(e,t)=>({...j_(e),options:[e,t]}),M_=(e,t)=>({...N_(e),options:[e,t]}),D_=(e,t)=>({...k_(e),options:[e,t]}),L_=(e,t)=>({...S_(e),options:[e,t]}),$_=(e,t)=>({...C_(e),options:[e,t]}),z_=(e,t)=>({...I_(e),options:[e,t]});var F_="Arrow",Cu=x.forwardRef((e,t)=>{const{children:r,width:s=10,height:o=5,...a}=e;return n.jsx(be.svg,{...a,ref:t,width:s,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:n.jsx("polygon",{points:"0,0 30,0 15,10"})})});Cu.displayName=F_;var B_=Cu;function U_(e){const[t,r]=x.useState(void 0);return Xe(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const s=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const a=o[0];let i,c;if("borderBoxSize"in a){const l=a.borderBoxSize,d=Array.isArray(l)?l[0]:l;i=d.inlineSize,c=d.blockSize}else i=e.offsetWidth,c=e.offsetHeight;r({width:i,height:c})});return s.observe(e,{box:"border-box"}),()=>s.unobserve(e)}else r(void 0)},[e]),t}var oi="Popper",[Nu,Pu]=bn(oi),[W_,Au]=Nu(oi),Eu=e=>{const{__scopePopper:t,children:r}=e,[s,o]=x.useState(null);return n.jsx(W_,{scope:t,anchor:s,onAnchorChange:o,children:r})};Eu.displayName=oi;var Tu="PopperAnchor",Iu=x.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:s,...o}=e,a=Au(Tu,r),i=x.useRef(null),c=Ee(t,i),l=x.useRef(null);return x.useEffect(()=>{const d=l.current;l.current=s?.current||i.current,d!==l.current&&a.onAnchorChange(l.current)}),s?null:n.jsx(be.div,{...o,ref:c})});Iu.displayName=Tu;var ai="PopperContent",[V_,q_]=Nu(ai),Ru=x.forwardRef((e,t)=>{const{__scopePopper:r,side:s="bottom",sideOffset:o=0,align:a="center",alignOffset:i=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:m=0,sticky:u="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:_,...g}=e,f=Au(ai,r),[w,j]=x.useState(null),b=Ee(t,F=>j(F)),[v,k]=x.useState(null),R=U_(v),N=R?.width??0,C=R?.height??0,T=s+(a!=="center"?"-"+a:""),O=typeof m=="number"?m:{top:0,right:0,bottom:0,left:0,...m},$=Array.isArray(d)?d:[d],S=$.length>0,A={padding:O,boundary:$.filter(Z_),altBoundary:S},{refs:I,floatingStyles:B,placement:D,isPositioned:E,middlewareData:P}=T_({strategy:"fixed",placement:T,whileElementsMounted:(...F)=>w_(...F,{animationFrame:h==="always"}),elements:{reference:f.anchor},middleware:[R_({mainAxis:o+C,alignmentAxis:i}),l&&O_({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?M_():void 0,...A}),l&&D_({...A}),L_({...A,apply:({elements:F,rects:ee,availableWidth:pe,availableHeight:q})=>{const{width:ne,height:le}=ee.reference,fe=F.floating.style;fe.setProperty("--radix-popper-available-width",`${pe}px`),fe.setProperty("--radix-popper-available-height",`${q}px`),fe.setProperty("--radix-popper-anchor-width",`${ne}px`),fe.setProperty("--radix-popper-anchor-height",`${le}px`)}}),v&&z_({element:v,padding:c}),G_({arrowWidth:N,arrowHeight:C}),p&&$_({strategy:"referenceHidden",...A})]}),[z,Z]=Du(D),K=mn(_);Xe(()=>{E&&K?.()},[E,K]);const L=P.arrow?.x,W=P.arrow?.y,Y=P.arrow?.centerOffset!==0,[V,ce]=x.useState();return Xe(()=>{w&&ce(window.getComputedStyle(w).zIndex)},[w]),n.jsx("div",{ref:I.setFloating,"data-radix-popper-content-wrapper":"",style:{...B,transform:E?B.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:V,"--radix-popper-transform-origin":[P.transformOrigin?.x,P.transformOrigin?.y].join(" "),...P.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:n.jsx(V_,{scope:r,placedSide:z,onArrowChange:k,arrowX:L,arrowY:W,shouldHideArrow:Y,children:n.jsx(be.div,{"data-side":z,"data-align":Z,...g,ref:b,style:{...g.style,animation:E?void 0:"none"}})})})});Ru.displayName=ai;var Ou="PopperArrow",H_={top:"bottom",right:"left",bottom:"top",left:"right"},Mu=x.forwardRef(function(t,r){const{__scopePopper:s,...o}=t,a=q_(Ou,s),i=H_[a.placedSide];return n.jsx("span",{ref:a.onArrowChange,style:{position:"absolute",left:a.arrowX,top:a.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[a.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[a.placedSide],visibility:a.shouldHideArrow?"hidden":void 0},children:n.jsx(B_,{...o,ref:r,style:{...o.style,display:"block"}})})});Mu.displayName=Ou;function Z_(e){return e!==null}var G_=e=>({name:"transformOrigin",options:e,fn(t){const{placement:r,rects:s,middlewareData:o}=t,i=o.arrow?.centerOffset!==0,c=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[d,m]=Du(r),u={start:"0%",center:"50%",end:"100%"}[m],p=(o.arrow?.x??0)+c/2,h=(o.arrow?.y??0)+l/2;let _="",g="";return d==="bottom"?(_=i?u:`${p}px`,g=`${-l}px`):d==="top"?(_=i?u:`${p}px`,g=`${s.floating.height+l}px`):d==="right"?(_=`${-l}px`,g=i?u:`${h}px`):d==="left"&&(_=`${s.floating.width+l}px`,g=i?u:`${h}px`),{data:{x:_,y:g}}}});function Du(e){const[t,r="center"]=e.split("-");return[t,r]}var Q_=Eu,Y_=Iu,K_=Ru,X_=Mu,J_="Portal",ii=x.forwardRef((e,t)=>{const{container:r,...s}=e,[o,a]=x.useState(!1);Xe(()=>a(!0),[]);const i=r||o&&globalThis?.document?.body;return i?ka.createPortal(n.jsx(be.div,{...s,ref:t}),i):null});ii.displayName=J_;function ej(e){const t=tj(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(rj);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function tj(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=oj(o),c=sj(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var nj=Symbol("radix.slottable");function rj(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===nj}function sj(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function oj(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var aj=x[" useInsertionEffect ".trim().toString()]||Xe;function hn({prop:e,defaultProp:t,onChange:r=()=>{},caller:s}){const[o,a,i]=ij({defaultProp:t,onChange:r}),c=e!==void 0,l=c?e:o;{const m=x.useRef(e!==void 0);x.useEffect(()=>{const u=m.current;u!==c&&console.warn(`${s} is changing from ${u?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=c},[c,s])}const d=x.useCallback(m=>{if(c){const u=cj(m)?m(e):m;u!==e&&i.current?.(u)}else a(m)},[c,e,a,i]);return[l,d]}function ij({defaultProp:e,onChange:t}){const[r,s]=x.useState(e),o=x.useRef(r),a=x.useRef(t);return aj(()=>{a.current=t},[t]),x.useEffect(()=>{o.current!==r&&(a.current?.(r),o.current=r)},[r,o]),[r,s,a]}function cj(e){return typeof e=="function"}function lj(e){const t=x.useRef({value:e,previous:e});return x.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Lu=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),dj="VisuallyHidden",uj=x.forwardRef((e,t)=>n.jsx(be.span,{...e,ref:t,style:{...Lu,...e.style}}));uj.displayName=dj;var mj=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Zn=new WeakMap,Jr=new WeakMap,es={},Lo=0,$u=function(e){return e&&(e.host||$u(e.parentNode))},pj=function(e,t){return t.map(function(r){if(e.contains(r))return r;var s=$u(r);return s&&e.contains(s)?s:(console.error("aria-hidden",r,"in not contained inside",e,". Doing nothing"),null)}).filter(function(r){return!!r})},fj=function(e,t,r,s){var o=pj(t,Array.isArray(e)?e:[e]);es[r]||(es[r]=new WeakMap);var a=es[r],i=[],c=new Set,l=new Set(o),d=function(u){!u||c.has(u)||(c.add(u),d(u.parentNode))};o.forEach(d);var m=function(u){!u||l.has(u)||Array.prototype.forEach.call(u.children,function(p){if(c.has(p))m(p);else try{var h=p.getAttribute(s),_=h!==null&&h!=="false",g=(Zn.get(p)||0)+1,f=(a.get(p)||0)+1;Zn.set(p,g),a.set(p,f),i.push(p),g===1&&_&&Jr.set(p,!0),f===1&&p.setAttribute(r,"true"),_||p.setAttribute(s,"true")}catch(w){console.error("aria-hidden: cannot operate on ",p,w)}})};return m(t),c.clear(),Lo++,function(){i.forEach(function(u){var p=Zn.get(u)-1,h=a.get(u)-1;Zn.set(u,p),a.set(u,h),p||(Jr.has(u)||u.removeAttribute(s),Jr.delete(u)),h||u.removeAttribute(r)}),Lo--,Lo||(Zn=new WeakMap,Zn=new WeakMap,Jr=new WeakMap,es={})}},zu=function(e,t,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(e)?e:[e]),o=mj(e);return o?(s.push.apply(s,Array.from(o.querySelectorAll("[aria-live], script"))),fj(s,o,r,"aria-hidden")):function(){return null}},Wt=function(){return Wt=Object.assign||function(t){for(var r,s=1,o=arguments.length;s<o;s++){r=arguments[s];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])}return t},Wt.apply(this,arguments)};function Fu(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,s=Object.getOwnPropertySymbols(e);o<s.length;o++)t.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(e,s[o])&&(r[s[o]]=e[s[o]]);return r}function hj(e,t,r){if(r||arguments.length===2)for(var s=0,o=t.length,a;s<o;s++)(a||!(s in t))&&(a||(a=Array.prototype.slice.call(t,0,s)),a[s]=t[s]);return e.concat(a||Array.prototype.slice.call(t))}var ds="right-scroll-bar-position",us="width-before-scroll-bar",gj="with-scroll-bars-hidden",xj="--removed-body-scroll-bar-size";function $o(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function yj(e,t){var r=y.useState(function(){return{value:e,callback:t,facade:{get current(){return r.value},set current(s){var o=r.value;o!==s&&(r.value=s,r.callback(s,o))}}}})[0];return r.callback=t,r.facade}var vj=typeof window<"u"?x.useLayoutEffect:x.useEffect,rl=new WeakMap;function bj(e,t){var r=yj(null,function(s){return e.forEach(function(o){return $o(o,s)})});return vj(function(){var s=rl.get(r);if(s){var o=new Set(s),a=new Set(e),i=r.current;o.forEach(function(c){a.has(c)||$o(c,null)}),a.forEach(function(c){o.has(c)||$o(c,i)})}rl.set(r,e)},[e]),r}function wj(e){return e}function _j(e,t){t===void 0&&(t=wj);var r=[],s=!1,o={read:function(){if(s)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(a){var i=t(a,s);return r.push(i),function(){r=r.filter(function(c){return c!==i})}},assignSyncMedium:function(a){for(s=!0;r.length;){var i=r;r=[],i.forEach(a)}r={push:function(c){return a(c)},filter:function(){return r}}},assignMedium:function(a){s=!0;var i=[];if(r.length){var c=r;r=[],c.forEach(a),i=r}var l=function(){var m=i;i=[],m.forEach(a)},d=function(){return Promise.resolve().then(l)};d(),r={push:function(m){i.push(m),d()},filter:function(m){return i=i.filter(m),r}}}};return o}function jj(e){e===void 0&&(e={});var t=_j(null);return t.options=Wt({async:!0,ssr:!1},e),t}var Bu=function(e){var t=e.sideCar,r=Fu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var s=t.read();if(!s)throw new Error("Sidecar medium not found");return x.createElement(s,Wt({},r))};Bu.isSideCarExport=!0;function kj(e,t){return e.useMedium(t),Bu}var Uu=jj(),zo=function(){},qs=x.forwardRef(function(e,t){var r=x.useRef(null),s=x.useState({onScrollCapture:zo,onWheelCapture:zo,onTouchMoveCapture:zo}),o=s[0],a=s[1],i=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,m=e.enabled,u=e.shards,p=e.sideCar,h=e.noRelative,_=e.noIsolation,g=e.inert,f=e.allowPinchZoom,w=e.as,j=w===void 0?"div":w,b=e.gapMode,v=Fu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=p,R=bj([r,t]),N=Wt(Wt({},v),o);return x.createElement(x.Fragment,null,m&&x.createElement(k,{sideCar:Uu,removeScrollBar:d,shards:u,noRelative:h,noIsolation:_,inert:g,setCallbacks:a,allowPinchZoom:!!f,lockRef:r,gapMode:b}),i?x.cloneElement(x.Children.only(c),Wt(Wt({},N),{ref:R})):x.createElement(j,Wt({},N,{className:l,ref:R}),c))});qs.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};qs.classNames={fullWidth:us,zeroRight:ds};var Sj=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Cj(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Sj();return t&&e.setAttribute("nonce",t),e}function Nj(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Pj(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Aj=function(){var e=0,t=null;return{add:function(r){e==0&&(t=Cj())&&(Nj(t,r),Pj(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ej=function(){var e=Aj();return function(t,r){x.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])}},Wu=function(){var e=Ej(),t=function(r){var s=r.styles,o=r.dynamic;return e(s,o),null};return t},Tj={left:0,top:0,right:0,gap:0},Fo=function(e){return parseInt(e||"",10)||0},Ij=function(e){var t=window.getComputedStyle(document.body),r=t[e==="padding"?"paddingLeft":"marginLeft"],s=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Fo(r),Fo(s),Fo(o)]},Rj=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Tj;var t=Ij(e),r=document.documentElement.clientWidth,s=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,s-r+t[2]-t[0])}},Oj=Wu(),Jn="data-scroll-locked",Mj=function(e,t,r,s){var o=e.left,a=e.top,i=e.right,c=e.gap;return r===void 0&&(r="margin"),`
|
|
91
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const c=i[1];if(t===i[0]){a(i);continue}if(e.external){const d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){a(i);continue}}if(e.metadataRegistry.get(i[0])?.id){a(i);continue}if(c.cycle){a(i);continue}if(c.count>1&&e.reused==="ref"){a(i);continue}}}function Pd(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i=>{const c=e.seen.get(i);if(c.ref===null)return;const l=c.def??c.schema,d={...l},m=c.ref;if(c.ref=null,m){s(m);const p=e.seen.get(m),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(h)):Object.assign(l,h),Object.assign(l,d),i._zod.parent===m)for(const g in l)g==="$ref"||g==="allOf"||g in d||delete l[g];if(h.$ref&&p.def)for(const g in l)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(l[g])===JSON.stringify(p.def[g])&&delete l[g]}const u=i._zod.parent;if(u&&u!==m){s(u);const p=e.seen.get(u);if(p?.schema.$ref&&(l.$ref=p.schema.$ref,p.def))for(const h in l)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(l[h])===JSON.stringify(p.def[h])&&delete l[h]}e.override({zodSchema:i,jsonSchema:l,path:c.path??[]})};for(const i of[...e.seen.entries()].reverse())s(i[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(i)}Object.assign(o,r.def??r.schema);const a=e.external?.defs??{};for(const i of e.seen.entries()){const c=i[1];c.def&&c.defId&&(a[c.defId]=c.def)}e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?o.$defs=a:o.definitions=a);try{const i=JSON.parse(JSON.stringify(o));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:bs(t,"input",e.processors),output:bs(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function rt(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return rt(s.element,r);if(s.type==="set")return rt(s.valueType,r);if(s.type==="lazy")return rt(s.getter(),r);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return rt(s.innerType,r);if(s.type==="intersection")return rt(s.left,r)||rt(s.right,r);if(s.type==="record"||s.type==="map")return rt(s.keyType,r)||rt(s.valueType,r);if(s.type==="pipe")return rt(s.in,r)||rt(s.out,r);if(s.type==="object"){for(const o in s.shape)if(rt(s.shape[o],r))return!0;return!1}if(s.type==="union"){for(const o of s.options)if(rt(o,r))return!0;return!1}if(s.type==="tuple"){for(const o of s.items)if(rt(o,r))return!0;return!!(s.rest&&rt(s.rest,r))}return!1}const Yy=(e,t={})=>r=>{const s=Cd({...r,processors:t});return Ke(e,s),Nd(s,e),Pd(s,e)},bs=(e,t,r={})=>s=>{const{libraryOptions:o,target:a}=s??{},i=Cd({...o??{},target:a,io:t,processors:r});return Ke(e,i),Nd(i,e),Pd(i,e)},Ky={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Xy=(e,t,r,s)=>{const o=r;o.type="string";const{minimum:a,maximum:i,format:c,patterns:l,contentEncoding:d}=e._zod.bag;if(typeof a=="number"&&(o.minLength=a),typeof i=="number"&&(o.maxLength=i),c&&(o.format=Ky[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),d&&(o.contentEncoding=d),l&&l.size>0){const m=[...l];m.length===1?o.pattern=m[0].source:m.length>1&&(o.allOf=[...m.map(u=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:u.source}))])}},Jy=(e,t,r,s)=>{const o=r,{minimum:a,maximum:i,format:c,multipleOf:l,exclusiveMaximum:d,exclusiveMinimum:m}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number",typeof m=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=m,o.exclusiveMinimum=!0):o.exclusiveMinimum=m),typeof a=="number"&&(o.minimum=a,typeof m=="number"&&t.target!=="draft-04"&&(m>=a?delete o.minimum:delete o.exclusiveMinimum)),typeof d=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=d,o.exclusiveMaximum=!0):o.exclusiveMaximum=d),typeof i=="number"&&(o.maximum=i,typeof d=="number"&&t.target!=="draft-04"&&(d<=i?delete o.maximum:delete o.exclusiveMaximum)),typeof l=="number"&&(o.multipleOf=l)},eb=(e,t,r,s)=>{r.not={}},tb=(e,t,r,s)=>{},nb=(e,t,r,s)=>{const o=e._zod.def,a=ad(o.entries);a.every(i=>typeof i=="number")&&(r.type="number"),a.every(i=>typeof i=="string")&&(r.type="string"),r.enum=a},rb=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},sb=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},ob=(e,t,r,s)=>{const o=r,a=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=Ke(a.element,t,{...s,path:[...s.path,"items"]})},ab=(e,t,r,s)=>{const o=r,a=e._zod.def;o.type="object",o.properties={};const i=a.shape;for(const d in i)o.properties[d]=Ke(i[d],t,{...s,path:[...s.path,"properties",d]});const c=new Set(Object.keys(i)),l=new Set([...c].filter(d=>{const m=a.shape[d]._zod;return t.io==="input"?m.optin===void 0:m.optout===void 0}));l.size>0&&(o.required=Array.from(l)),a.catchall?._zod.def.type==="never"?o.additionalProperties=!1:a.catchall?a.catchall&&(o.additionalProperties=Ke(a.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},ib=(e,t,r,s)=>{const o=e._zod.def,a=o.inclusive===!1,i=o.options.map((c,l)=>Ke(c,t,{...s,path:[...s.path,a?"oneOf":"anyOf",l]}));a?r.oneOf=i:r.anyOf=i},cb=(e,t,r,s)=>{const o=e._zod.def,a=Ke(o.left,t,{...s,path:[...s.path,"allOf",0]}),i=Ke(o.right,t,{...s,path:[...s.path,"allOf",1]}),c=d=>"allOf"in d&&Object.keys(d).length===1,l=[...c(a)?a.allOf:[a],...c(i)?i.allOf:[i]];r.allOf=l},lb=(e,t,r,s)=>{const o=e._zod.def,a=Ke(o.innerType,t,s),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]},db=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},ub=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},mb=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},pb=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},fb=(e,t,r,s)=>{const o=e._zod.def,a=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;Ke(a,t,s);const i=t.seen.get(e);i.ref=a},hb=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.readOnly=!0},Ad=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},gb=G("ZodISODateTime",(e,t)=>{kx.init(e,t),Oe.init(e,t)});function xb(e){return Ny(gb,e)}const yb=G("ZodISODate",(e,t)=>{Sx.init(e,t),Oe.init(e,t)});function bb(e){return Py(yb,e)}const vb=G("ZodISOTime",(e,t)=>{Cx.init(e,t),Oe.init(e,t)});function wb(e){return Ay(vb,e)}const _b=G("ZodISODuration",(e,t)=>{Nx.init(e,t),Oe.init(e,t)});function jb(e){return Ey(_b,e)}const kb=(e,t)=>{ud.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>xg(e,r)},flatten:{value:r=>gg(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,ea,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,ea,2)}},isEmpty:{get(){return e.issues.length===0}}})},Nt=G("ZodError",kb,{Parent:Error}),Sb=za(Nt),Cb=Fa(Nt),Nb=Ms(Nt),Pb=Ds(Nt),Ab=vg(Nt),Eb=wg(Nt),Tb=_g(Nt),Ib=jg(Nt),Rb=kg(Nt),Ob=Sg(Nt),Mb=Cg(Nt),Db=Ng(Nt),We=G("ZodType",(e,t)=>(Ue.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:bs(e,"input"),output:bs(e,"output")}}),e.toJSONSchema=Yy(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(yn(t,{checks:[...t.checks??[],...r.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0}),e.with=e.check,e.clone=(r,s)=>bn(e,r,s),e.brand=()=>e,e.register=((r,s)=>(r.add(e,s),e)),e.parse=(r,s)=>Sb(e,r,s,{callee:e.parse}),e.safeParse=(r,s)=>Nb(e,r,s),e.parseAsync=async(r,s)=>Cb(e,r,s,{callee:e.parseAsync}),e.safeParseAsync=async(r,s)=>Pb(e,r,s),e.spa=e.safeParseAsync,e.encode=(r,s)=>Ab(e,r,s),e.decode=(r,s)=>Eb(e,r,s),e.encodeAsync=async(r,s)=>Tb(e,r,s),e.decodeAsync=async(r,s)=>Ib(e,r,s),e.safeEncode=(r,s)=>Rb(e,r,s),e.safeDecode=(r,s)=>Ob(e,r,s),e.safeEncodeAsync=async(r,s)=>Mb(e,r,s),e.safeDecodeAsync=async(r,s)=>Db(e,r,s),e.refine=(r,s)=>e.check(Ev(r,s)),e.superRefine=r=>e.check(Tv(r)),e.overwrite=r=>e.check(sr(r)),e.optional=()=>_c(e),e.exactOptional=()=>xv(e),e.nullable=()=>jc(e),e.nullish=()=>_c(jc(e)),e.nonoptional=r=>jv(e,r),e.array=()=>iv(e),e.or=r=>dv([e,r]),e.and=r=>mv(e,r),e.transform=r=>kc(e,hv(r)),e.default=r=>vv(e,r),e.prefault=r=>_v(e,r),e.catch=r=>Sv(e,r),e.pipe=r=>kc(e,r),e.readonly=()=>Pv(e),e.describe=r=>{const s=e.clone();return _r.add(s,{description:r}),s},Object.defineProperty(e,"description",{get(){return _r.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return _r.get(e);const s=e.clone();return _r.add(s,r[0]),s},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),Ed=G("_ZodString",(e,t)=>{Ba.init(e,t),We.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Xy(e,s,o);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...s)=>e.check(My(...s)),e.includes=(...s)=>e.check($y(...s)),e.startsWith=(...s)=>e.check(zy(...s)),e.endsWith=(...s)=>e.check(Fy(...s)),e.min=(...s)=>e.check(ys(...s)),e.max=(...s)=>e.check(kd(...s)),e.length=(...s)=>e.check(Sd(...s)),e.nonempty=(...s)=>e.check(ys(1,...s)),e.lowercase=s=>e.check(Dy(s)),e.uppercase=s=>e.check(Ly(s)),e.trim=()=>e.check(Uy()),e.normalize=(...s)=>e.check(By(...s)),e.toLowerCase=()=>e.check(Wy()),e.toUpperCase=()=>e.check(Vy()),e.slugify=()=>e.check(qy())}),Lb=G("ZodString",(e,t)=>{Ba.init(e,t),Ed.init(e,t),e.email=r=>e.check(ay($b,r)),e.url=r=>e.check(uy(zb,r)),e.jwt=r=>e.check(Cy(ev,r)),e.emoji=r=>e.check(my(Fb,r)),e.guid=r=>e.check(hc(bc,r)),e.uuid=r=>e.check(iy(Gr,r)),e.uuidv4=r=>e.check(cy(Gr,r)),e.uuidv6=r=>e.check(ly(Gr,r)),e.uuidv7=r=>e.check(dy(Gr,r)),e.nanoid=r=>e.check(py(Bb,r)),e.guid=r=>e.check(hc(bc,r)),e.cuid=r=>e.check(fy(Ub,r)),e.cuid2=r=>e.check(hy(Wb,r)),e.ulid=r=>e.check(gy(Vb,r)),e.base64=r=>e.check(jy(Kb,r)),e.base64url=r=>e.check(ky(Xb,r)),e.xid=r=>e.check(xy(qb,r)),e.ksuid=r=>e.check(yy(Hb,r)),e.ipv4=r=>e.check(by(Zb,r)),e.ipv6=r=>e.check(vy(Gb,r)),e.cidrv4=r=>e.check(wy(Qb,r)),e.cidrv6=r=>e.check(_y(Yb,r)),e.e164=r=>e.check(Sy(Jb,r)),e.datetime=r=>e.check(xb(r)),e.date=r=>e.check(bb(r)),e.time=r=>e.check(wb(r)),e.duration=r=>e.check(jb(r))});function st(e){return oy(Lb,e)}const Oe=G("ZodStringFormat",(e,t)=>{Te.init(e,t),Ed.init(e,t)}),$b=G("ZodEmail",(e,t)=>{hx.init(e,t),Oe.init(e,t)}),bc=G("ZodGUID",(e,t)=>{px.init(e,t),Oe.init(e,t)}),Gr=G("ZodUUID",(e,t)=>{fx.init(e,t),Oe.init(e,t)}),zb=G("ZodURL",(e,t)=>{gx.init(e,t),Oe.init(e,t)}),Fb=G("ZodEmoji",(e,t)=>{xx.init(e,t),Oe.init(e,t)}),Bb=G("ZodNanoID",(e,t)=>{yx.init(e,t),Oe.init(e,t)}),Ub=G("ZodCUID",(e,t)=>{bx.init(e,t),Oe.init(e,t)}),Wb=G("ZodCUID2",(e,t)=>{vx.init(e,t),Oe.init(e,t)}),Vb=G("ZodULID",(e,t)=>{wx.init(e,t),Oe.init(e,t)}),qb=G("ZodXID",(e,t)=>{_x.init(e,t),Oe.init(e,t)}),Hb=G("ZodKSUID",(e,t)=>{jx.init(e,t),Oe.init(e,t)}),Zb=G("ZodIPv4",(e,t)=>{Px.init(e,t),Oe.init(e,t)}),Gb=G("ZodIPv6",(e,t)=>{Ax.init(e,t),Oe.init(e,t)}),Qb=G("ZodCIDRv4",(e,t)=>{Ex.init(e,t),Oe.init(e,t)}),Yb=G("ZodCIDRv6",(e,t)=>{Tx.init(e,t),Oe.init(e,t)}),Kb=G("ZodBase64",(e,t)=>{Ix.init(e,t),Oe.init(e,t)}),Xb=G("ZodBase64URL",(e,t)=>{Ox.init(e,t),Oe.init(e,t)}),Jb=G("ZodE164",(e,t)=>{Mx.init(e,t),Oe.init(e,t)}),ev=G("ZodJWT",(e,t)=>{Lx.init(e,t),Oe.init(e,t)}),Td=G("ZodNumber",(e,t)=>{vd.init(e,t),We.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Jy(e,s,o),e.gt=(s,o)=>e.check(xc(s,o)),e.gte=(s,o)=>e.check(Po(s,o)),e.min=(s,o)=>e.check(Po(s,o)),e.lt=(s,o)=>e.check(gc(s,o)),e.lte=(s,o)=>e.check(No(s,o)),e.max=(s,o)=>e.check(No(s,o)),e.int=s=>e.check(vc(s)),e.safe=s=>e.check(vc(s)),e.positive=s=>e.check(xc(0,s)),e.nonnegative=s=>e.check(Po(0,s)),e.negative=s=>e.check(gc(0,s)),e.nonpositive=s=>e.check(No(0,s)),e.multipleOf=(s,o)=>e.check(yc(s,o)),e.step=(s,o)=>e.check(yc(s,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function tv(e){return Ty(Td,e)}const nv=G("ZodNumberFormat",(e,t)=>{$x.init(e,t),Td.init(e,t)});function vc(e){return Iy(nv,e)}const rv=G("ZodUnknown",(e,t)=>{zx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>tb()});function wc(){return Ry(rv)}const sv=G("ZodNever",(e,t)=>{Fx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>eb(e,r,s)});function ov(e){return Oy(sv,e)}const av=G("ZodArray",(e,t)=>{Bx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ob(e,r,s,o),e.element=t.element,e.min=(r,s)=>e.check(ys(r,s)),e.nonempty=r=>e.check(ys(1,r)),e.max=(r,s)=>e.check(kd(r,s)),e.length=(r,s)=>e.check(Sd(r,s)),e.unwrap=()=>e.element});function iv(e,t){return Hy(av,e,t)}const cv=G("ZodObject",(e,t)=>{Wx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ab(e,r,s,o),Ce(e,"shape",()=>t.shape),e.keyof=()=>pv(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:wc()}),e.loose=()=>e.clone({...e._zod.def,catchall:wc()}),e.strict=()=>e.clone({...e._zod.def,catchall:ov()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>ug(e,r),e.safeExtend=r=>mg(e,r),e.merge=r=>pg(e,r),e.pick=r=>lg(e,r),e.omit=r=>dg(e,r),e.partial=(...r)=>fg(Rd,e,r[0]),e.required=(...r)=>hg(Od,e,r[0])});function Id(e,t){const r={type:"object",shape:e??{},...me(t)};return new cv(r)}const lv=G("ZodUnion",(e,t)=>{Vx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ib(e,r,s,o),e.options=t.options});function dv(e,t){return new lv({type:"union",options:e,...me(t)})}const uv=G("ZodIntersection",(e,t)=>{qx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>cb(e,r,s,o)});function mv(e,t){return new uv({type:"intersection",left:e,right:t})}const na=G("ZodEnum",(e,t)=>{Hx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(s,o,a)=>nb(e,s,o),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(s,o)=>{const a={};for(const i of s)if(r.has(i))a[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new na({...t,checks:[],...me(o),entries:a})},e.exclude=(s,o)=>{const a={...t.entries};for(const i of s)if(r.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new na({...t,checks:[],...me(o),entries:a})}});function pv(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new na({type:"enum",entries:r,...me(t)})}const fv=G("ZodTransform",(e,t)=>{Zx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>sb(e,r),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new sd(e.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(Ar(a,r.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(Ar(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(a=>(r.value=a,r)):(r.value=o,r)}});function hv(e){return new fv({type:"transform",transform:e})}const Rd=G("ZodOptional",(e,t)=>{jd.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Ad(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function _c(e){return new Rd({type:"optional",innerType:e})}const gv=G("ZodExactOptional",(e,t)=>{Gx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Ad(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function xv(e){return new gv({type:"optional",innerType:e})}const yv=G("ZodNullable",(e,t)=>{Qx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>lb(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function jc(e){return new yv({type:"nullable",innerType:e})}const bv=G("ZodDefault",(e,t)=>{Yx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ub(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function vv(e,t){return new bv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():cd(t)}})}const wv=G("ZodPrefault",(e,t)=>{Kx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>mb(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function _v(e,t){return new wv({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():cd(t)}})}const Od=G("ZodNonOptional",(e,t)=>{Xx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>db(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function jv(e,t){return new Od({type:"nonoptional",innerType:e,...me(t)})}const kv=G("ZodCatch",(e,t)=>{Jx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>pb(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Sv(e,t){return new kv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Cv=G("ZodPipe",(e,t)=>{ey.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>fb(e,r,s,o),e.in=t.in,e.out=t.out});function kc(e,t){return new Cv({type:"pipe",in:e,out:t})}const Nv=G("ZodReadonly",(e,t)=>{ty.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>hb(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Pv(e){return new Nv({type:"readonly",innerType:e})}const Av=G("ZodCustom",(e,t)=>{ny.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>rb(e,r)});function Ev(e,t={}){return Zy(Av,e,t)}function Tv(e){return Gy(e)}const Qr=Id({line1:st().min(1,"Address line 1 is required"),line2:st().optional(),city:st().min(1,"City is required"),state:st().optional(),postalCode:st().min(1,"Postal code is required"),country:st().min(2,"Country is required")});function Iv(e){return Id({email:e.requireEmail?st().email("Valid email required"):st().email("Valid email required").optional(),name:e.requireName?st().min(1,"Name is required"):st().optional(),phone:e.requirePhone?st().min(6,"Phone is required"):st().optional(),notes:st().max(500).optional(),shippingAddress:e.requireShippingAddress?Qr:Qr.optional(),billingAddress:e.requireBillingAddress?Qr:Qr.optional(),discountCode:st().optional(),tipAmount:tv().min(0).optional(),shippingMethodId:st().optional()})}const Sc={none:0,optional:1,required:2};function Ao(e,t){return Sc[e]>=Sc[t]?e:t}function Rv(e){if(!e)return null;try{const t=JSON.parse(e);return!t||typeof t!="object"?null:t}catch{return null}}function cs(e,t){let r=!1,s=!1;const o=new Set;let a=t.requireEmail?"required":"none",i=t.defaultMode==="none"?"none":"optional",c=t.defaultMode==="full"?"optional":"none",l=t.allowShipping&&(t.defaultMode==="shipping"||t.defaultMode==="full"),d=t.defaultMode==="full";for(const u of e){u.metadata?.shippingProfile==="digital"?r=!0:s=!0;const h=Rv(u.metadata?.checkoutRequirements);h&&(h.email&&(a=Ao(a,h.email)),h.name&&(i=Ao(i,h.name)),h.phone&&(c=Ao(c,h.phone)),typeof h.shippingAddress=="boolean"&&(l=l||h.shippingAddress),typeof h.billingAddress=="boolean"&&(d=d||h.billingAddress));const _=u.metadata?.fulfillmentNotes;_&&o.add(_)}const m=r&&!s;return m&&(l=!1),{email:a,name:i,phone:c,shippingAddress:l,billingAddress:d,fulfillmentNotes:Array.from(o).join(" "),isDigitalOnly:m,hasPhysical:s}}const Md=y.createContext(null);function Dd(){const{config:e}=Re(),t=Dt(),r=y.useMemo(()=>({line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"}),[]),s=y.useMemo(()=>{const j=cs(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});return Iv({requireEmail:j.email==="required",requireName:j.name==="required",requirePhone:j.phone==="required",requireShippingAddress:j.shippingAddress,requireBillingAddress:j.billingAddress})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail]),[o,a]=y.useState(()=>({email:e.checkout.requireEmail??!0?"":void 0,name:"",phone:"",notes:"",shippingAddress:e.checkout.mode==="shipping"||e.checkout.mode==="full"?r:void 0,billingAddress:e.checkout.mode==="full"?r:void 0,discountCode:"",tipAmount:0,shippingMethodId:""}));y.useEffect(()=>{const j=cs(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});a(v=>{const b={...v};return j.email==="required"&&!b.email&&(b.email=""),j.shippingAddress&&!b.shippingAddress&&(b.shippingAddress=r),j.billingAddress&&!b.billingAddress&&(b.billingAddress=r),j.shippingAddress||(b.shippingAddress=void 0),j.billingAddress||(b.billingAddress=void 0),b})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail,r]);const[i,c]=y.useState({}),[l,d]=y.useState("idle"),[m,u]=y.useState(null),[p,h]=y.useState(null),_=y.useCallback(()=>{c({}),d("idle"),u(null),h(null)},[]),g=y.useCallback((j,v)=>{a(b=>({...b,[j]:v}))},[]),f=y.useCallback(()=>{d("validating"),u(null);const j=s.safeParse(o);if(j.success)return c({}),d("idle"),{ok:!0,values:j.data};const v={};for(const b of j.error.issues)v[b.path.join(".")]=b.message;return c(v),d("error"),u("Please fix the highlighted fields."),{ok:!1}},[s,o]),w=y.useCallback(async j=>{const v=f();if(!v.ok)return{ok:!1};d("creating_session"),u(null),h(null);const b=t.items.map(C=>({resource:C.paymentResource??C.productId,quantity:C.qty,variantId:C.variantId})),k=cs(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1}),R=new Set;if(k.shippingAddress)for(const C of t.items){const T=C.metadata?.shippingCountries;if(T)for(const O of T.split(",")){const $=O.trim().toUpperCase();$&&R.add($)}}const N={...R.size?{shippingCountries:Array.from(R).join(","),shipping_countries:Array.from(R).join(",")}:{}};try{const C=await e.adapter.createCheckoutSession({cart:b,customer:{email:v.values.email||void 0,name:v.values.name||void 0,phone:v.values.phone||void 0,notes:v.values.notes||void 0,shippingAddress:v.values.shippingAddress,billingAddress:v.values.billingAddress},options:{currency:e.currency,successUrl:e.checkout.successUrl,cancelUrl:e.checkout.cancelUrl,allowPromoCodes:e.checkout.allowPromoCodes,metadata:Object.keys(N).length?N:void 0,discountCode:(e.checkout.allowPromoCodes?v.values.discountCode||t.promoCode:void 0)||void 0,tipAmount:e.checkout.allowTipping&&v.values.tipAmount||void 0,shippingMethodId:e.checkout.allowShipping&&v.values.shippingMethodId||void 0,paymentMethodId:j?.paymentMethodId}});return C.kind==="redirect"?(h(C),d("redirecting"),typeof window<"u"&&window.location.assign(C.url),{ok:!0,session:C}):(h(C),d("success"),{ok:!0,session:C})}catch(C){return d("error"),u(C instanceof Error?C.message:"Checkout failed"),{ok:!1}}},[t.items,t.promoCode,e.adapter,e.checkout,e.currency,f]);return{values:o,setValues:a,setField:g,fieldErrors:i,status:l,error:m,session:p,reset:_,validate:f,createCheckoutSession:w}}function Ld({children:e}){const t=Dd();return n.jsx(Md.Provider,{value:t,children:e})}function $s(){const e=y.useContext(Md);if(!e)throw new Error("useCheckout must be used within CheckoutProvider");return e}function Ov(){return Dd()}function Ua(){const{config:e}=Re(),[t,r]=x.useState([]),[s,o]=x.useState(!0),[a,i]=x.useState(null);return x.useEffect(()=>{let c=!1;return o(!0),i(null),e.adapter.listCategories().then(l=>{c||r(l)}).catch(l=>{c||i(l instanceof Error?l.message:"Failed to load categories")}).finally(()=>{c||o(!1)}),()=>{c=!0}},[e.adapter]),{categories:t,isLoading:s,error:a}}function zs(e){const{config:t}=Re(),[r,s]=x.useState(null),[o,a]=x.useState(!0),[i,c]=x.useState(null),l=JSON.stringify(e.filters??{});return x.useEffect(()=>{let d=!1;return a(!0),c(null),t.adapter.listProducts(e).then(m=>{d||s(m)}).catch(m=>{d||c(m instanceof Error?m.message:"Failed to load products")}).finally(()=>{d||a(!1)}),()=>{d=!0}},[t.adapter,e.category,e.search,e.sort,e.page,e.pageSize,l]),{data:r,isLoading:o,error:i}}function $d(e){const{config:t}=Re(),[r,s]=x.useState(null),[o,a]=x.useState(!0),[i,c]=x.useState(null);return x.useEffect(()=>{let l=!1;return a(!0),c(null),t.adapter.getProductBySlug(e).then(d=>{l||s(d)}).catch(d=>{l||c(d instanceof Error?d.message:"Failed to load product")}).finally(()=>{l||a(!1)}),()=>{l=!0}},[t.adapter,e]),{product:r,isLoading:o,error:i}}function zd(){const{config:e}=Re(),[t,r]=x.useState([]),[s,o]=x.useState(!0),[a,i]=x.useState(null);return x.useEffect(()=>{let c=!1;return o(!0),i(null),e.adapter.getOrderHistory().then(l=>{c||r(l)}).catch(l=>{c||i(l instanceof Error?l.message:"Failed to load orders")}).finally(()=>{c||o(!1)}),()=>{c=!0}},[e.adapter]),{orders:t,isLoading:s,error:a}}function Fd(){const{config:e}=Re(),[t,r]=x.useState([]),[s,o]=x.useState(null),[a,i]=x.useState(!0),[c,l]=x.useState(null);return x.useEffect(()=>{let d=!1;async function m(){i(!0),l(null);try{const[u,p]=await Promise.all([e.adapter.listSubscriptionTiers?.()??Promise.resolve([]),e.adapter.getSubscriptionStatus?.()??Promise.resolve(null)]);if(d)return;r(u),o(p)}catch(u){if(d)return;l(u instanceof Error?u.message:"Failed to load subscriptions")}finally{d||i(!1)}}return m(),()=>{d=!0}},[e.adapter]),{tiers:t,status:s,isLoading:a,error:c}}function Bd({enabled:e,customer:t}){const{config:r}=Re(),[s,o]=x.useState([]),[a,i]=x.useState(!1),[c,l]=x.useState(null),d=JSON.stringify(t.shippingAddress??{});return x.useEffect(()=>{let m=!1;if(!e||!r.adapter.getShippingMethods){o([]);return}return i(!0),l(null),r.adapter.getShippingMethods({currency:r.currency,customer:t}).then(u=>{m||o(u)}).catch(u=>{m||l(u instanceof Error?u.message:"Failed to load shipping methods")}).finally(()=>{m||i(!1)}),()=>{m=!0}},[r.adapter,r.currency,e,t.email,t.name,d]),{methods:s,isLoading:a,error:c}}function fr(e,...t){for(const r of t){const s=e[r];if(s)return s}}function Wa(e){const t=fr(e,"error","error_message","message");if(t)return{kind:"error",message:t};const r=fr(e,"canceled","cancelled","cancel","canceled_at");if(r&&r!=="0"&&r!=="false")return{kind:"cancel"};const s=fr(e,"orderId","order_id","demoOrderId"),o=fr(e,"session_id","checkout_session_id");if(s||o)return{kind:"success",orderId:s??o};const a=(fr(e,"status","checkout")??"").toLowerCase();return a==="success"?{kind:"success",orderId:s}:a==="cancel"||a==="canceled"?{kind:"cancel"}:a==="error"?{kind:"error"}:{kind:"idle"}}function Mv(e){const t={};return e.forEach((r,s)=>{t[s]=r}),t}function Va(){const{config:e}=Re(),[t,r]=x.useState({kind:"idle"});return x.useEffect(()=>{if(typeof window>"u")return;const s=new URLSearchParams(window.location.search),o=Mv(s);(async()=>{try{const a=e.adapter.resolveCheckoutReturn?await e.adapter.resolveCheckoutReturn({query:o}):Wa(o);if(a.kind==="success"&&a.orderId&&e.adapter.getOrderById){const i=await e.adapter.getOrderById(a.orderId);if(i){r({kind:"success",orderId:a.orderId,order:i});return}}r(a)}catch(a){r({kind:"error",message:a instanceof Error?a.message:"Failed to resolve checkout"})}})()},[e.adapter]),t}function ra(e){if(!e)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Dv(e){const t=e.get("tags"),r=t?t.split(",").map(c=>c.trim()).filter(Boolean):void 0,s=ra(e.get("min")),o=ra(e.get("max")),a=e.get("inStock"),i=a==="1"?!0:a==="0"?!1:void 0;return{tags:r&&r.length?r:void 0,priceMin:s,priceMax:o,inStock:i}}function Lv(e,t){t.tags?.length?e.set("tags",t.tags.join(",")):e.delete("tags"),typeof t.priceMin=="number"?e.set("min",String(t.priceMin)):e.delete("min"),typeof t.priceMax=="number"?e.set("max",String(t.priceMax)):e.delete("max"),typeof t.inStock=="boolean"?e.set("inStock",t.inStock?"1":"0"):e.delete("inStock")}function qa({includeCategory:e}){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),r=t.get("q")??"",s=t.get("sort")??"featured",o=ra(t.get("page"))??1,a=Dv(t),i=e?t.get("cat")??void 0:void 0;return{search:r,sort:s,page:Math.max(1,Math.floor(o)),category:i,filters:a}}function Ha(e,{includeCategory:t}){const r=JSON.stringify(e.filters.tags??[]);x.useEffect(()=>{if(typeof window>"u")return;const s=window.setTimeout(()=>{const o=new URL(window.location.href),a=o.searchParams;e.search.trim()?a.set("q",e.search.trim()):a.delete("q"),e.sort&&e.sort!=="featured"?a.set("sort",e.sort):a.delete("sort"),e.page&&e.page!==1?a.set("page",String(e.page)):a.delete("page"),t&&(e.category?a.set("cat",e.category):a.delete("cat")),Lv(a,e.filters);const i=`${o.pathname}?${a.toString()}${o.hash}`,c=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==c&&window.history.replaceState({},"",i)},250);return()=>window.clearTimeout(s)},[t,e.category,e.page,e.search,e.sort,r,e.filters.priceMin,e.filters.priceMax,e.filters.inStock])}function Cc(e,t){return`${e}::${t??""}`}function $v(e,t){if(t&&e.variants?.length){const r=e.variants.find(s=>s.id===t);if(r)return{qty:r.inventoryQuantity,status:r.inventoryStatus}}return{qty:e.inventoryQuantity,status:e.inventoryStatus}}function zv(e,t){const r={productId:e.productId,variantId:e.variantId,isOutOfStock:!1,exceedsAvailable:!1,isLowStock:!1};if(!t)return{...r,isOutOfStock:!0,message:"This product is no longer available"};const{qty:s,status:o}=$v(t,e.variantId);return r.availableQty=s,r.status=o,o==="out_of_stock"||typeof s=="number"&&s<=0?{...r,isOutOfStock:!0,message:"Out of stock"}:typeof s=="number"&&e.qty>s?{...r,exceedsAvailable:!0,message:s===0?"Out of stock":`Only ${s} available (you have ${e.qty} in cart)`}:o==="low"||typeof s=="number"&&s>0&&s<=5?{...r,isLowStock:!0,message:typeof s=="number"?`Only ${s} left`:"Low stock"}:r}function Za({items:e,refreshInterval:t=3e4,skip:r=!1}){const{config:s}=Re(),[o,a]=x.useState(new Map),[i,c]=x.useState(!1),[l,d]=x.useState(null),m=x.useMemo(()=>{const _=new Set;for(const g of e)_.add(g.productId);return Array.from(_)},[e]),u=x.useCallback(async()=>{if(r||m.length===0){a(new Map);return}c(!0),d(null);try{const _=await Promise.all(m.map(async w=>{try{return await s.adapter.getProductBySlug(w)}catch{return null}})),g=new Map;for(const w of _)w&&(g.set(w.id,w),w.slug&&w.slug!==w.id&&g.set(w.slug,w));const f=new Map;for(const w of e){const j=Cc(w.productId,w.variantId),v=g.get(w.productId)??null;f.set(j,zv(w,v))}a(f)}catch(_){d(_ instanceof Error?_.message:"Failed to check inventory")}finally{c(!1)}},[s.adapter,e,m,r]);x.useEffect(()=>{u()},[u]),x.useEffect(()=>{if(r||t<=0||m.length===0)return;const _=setInterval(u,t);return()=>clearInterval(_)},[u,m.length,t,r]);const p=x.useCallback((_,g)=>o.get(Cc(_,g)),[o]),h=x.useMemo(()=>{for(const _ of o.values())if(_.isOutOfStock||_.exceedsAvailable)return!0;return!1},[o]);return{inventory:o,isLoading:i,error:l,refresh:u,getItemInventory:p,hasIssues:h}}function Fv(e,t){if(t&&e.variants?.length){const r=e.variants.find(s=>s.id===t);if(r)return{qty:r.inventoryQuantity,status:r.inventoryStatus}}return{qty:e.inventoryQuantity,status:e.inventoryStatus}}function Bv(e,t,r){if(!t)return e.titleSnapshot??"Unknown Product";const s=t.title??e.titleSnapshot??"Product";if(r&&t.variants?.length){const o=t.variants.find(a=>a.id===r);if(o?.title)return`${s} - ${o.title}`}return s}function Uv(e,t){const r=Bv(e,t,e.variantId);if(!t)return{productId:e.productId,variantId:e.variantId,title:r,requestedQty:e.qty,availableQty:0,type:"product_unavailable",message:"This product is no longer available"};const{qty:s,status:o}=Fv(t,e.variantId);return o==="out_of_stock"||typeof s=="number"&&s<=0?{productId:e.productId,variantId:e.variantId,title:r,requestedQty:e.qty,availableQty:0,type:"out_of_stock",message:"This item is out of stock"}:typeof s=="number"&&e.qty>s?{productId:e.productId,variantId:e.variantId,title:r,requestedQty:e.qty,availableQty:s,type:"insufficient_stock",message:s===0?"This item is out of stock":`Only ${s} available`}:null}function Ud({items:e}){const{config:t}=Re(),[r,s]=x.useState(null),[o,a]=x.useState(!1),[i,c]=x.useState(null),l=x.useMemo(()=>{const u=new Set;for(const p of e)u.add(p.productId);return Array.from(u)},[e]),d=x.useCallback(async()=>{if(e.length===0){const u={ok:!0,issues:[],verifiedAt:new Date};return s(u),u}a(!0),c(null);try{const u=await Promise.all(l.map(async g=>{try{return await t.adapter.getProductBySlug(g)}catch{return null}})),p=new Map;for(const g of u)g&&(p.set(g.id,g),g.slug&&g.slug!==g.id&&p.set(g.slug,g));const h=[];for(const g of e){const f=p.get(g.productId)??null,w=Uv(g,f);w&&h.push(w)}const _={ok:h.length===0,issues:h,verifiedAt:new Date};return s(_),a(!1),_}catch(u){const p=u instanceof Error?u.message:"Failed to verify inventory";c(p),a(!1);const h={ok:!1,issues:[],verifiedAt:new Date};return s(h),h}},[t.adapter,e,l]),m=x.useCallback(()=>{s(null),c(null)},[]);return{result:r,isVerifying:o,error:i,verify:d,reset:m}}function Wv({items:e,onExpiry:t,enabled:r=!0}){const[s,o]=x.useState([]),[a,i]=x.useState([]),c=x.useRef(new Set),l=x.useMemo(()=>r?e.filter(d=>d.holdId&&d.holdExpiresAt):[],[e,r]);return x.useEffect(()=>{if(!r||l.length===0){o([]),i([]);return}const d=()=>{const u=Date.now(),p=120*1e3,h=[],_=[];for(const g of l){if(!g.holdExpiresAt)continue;const f=new Date(g.holdExpiresAt),w=f.getTime()-u,j=`${g.productId}::${g.variantId??""}`;w<=0?(h.push({productId:g.productId,variantId:g.variantId}),c.current.has(j)||(c.current.add(j),t?.({productId:g.productId,variantId:g.variantId,title:g.titleSnapshot,expiredAt:f}))):w<=p&&_.push({productId:g.productId,variantId:g.variantId,expiresAt:f,remainingMs:w})}o(h),i(_)};d();const m=setInterval(d,1e4);return()=>clearInterval(m)},[r,l,t]),x.useEffect(()=>{const d=new Set(l.map(m=>`${m.productId}::${m.variantId??""}`));for(const m of c.current)d.has(m)||c.current.delete(m)},[l]),{expiringItems:a,expiredItems:s}}const Ne={relatedProducts:{mode:"most_recent",maxItems:4,layout:{layout:"large",imageCrop:"center"}},catalog:{filters:{tags:!0,priceRange:!0,inStock:!0},sort:{featured:!0,priceAsc:!0,priceDesc:!0}},checkout:{promoCodes:!0},shopLayout:{layout:"large",imageCrop:"center"},categoryLayout:{layout:"large",imageCrop:"center"},sections:{showDescription:!0,showSpecs:!0,showShipping:!0,showRelatedProducts:!0},inventory:{preCheckoutVerification:!0,holdsEnabled:!1,holdDurationMinutes:15},shopPage:{title:"Shop",description:""}};function Vv(e){return{relatedProducts:{mode:e.relatedProducts?.mode||Ne.relatedProducts.mode,maxItems:e.relatedProducts?.maxItems||Ne.relatedProducts.maxItems,layout:{layout:e.relatedProducts?.layout?.layout??Ne.relatedProducts.layout.layout,imageCrop:e.relatedProducts?.layout?.imageCrop??Ne.relatedProducts.layout.imageCrop}},catalog:{filters:{tags:e.catalog?.filters?.tags??Ne.catalog.filters.tags,priceRange:e.catalog?.filters?.priceRange??Ne.catalog.filters.priceRange,inStock:e.catalog?.filters?.inStock??Ne.catalog.filters.inStock},sort:{featured:e.catalog?.sort?.featured??Ne.catalog.sort.featured,priceAsc:e.catalog?.sort?.priceAsc??Ne.catalog.sort.priceAsc,priceDesc:e.catalog?.sort?.priceDesc??Ne.catalog.sort.priceDesc}},checkout:{promoCodes:e.checkout?.promoCodes??Ne.checkout.promoCodes},shopLayout:{layout:e.shopLayout?.layout??Ne.shopLayout.layout,imageCrop:e.shopLayout?.imageCrop??Ne.shopLayout.imageCrop},categoryLayout:{layout:e.categoryLayout?.layout??Ne.categoryLayout.layout,imageCrop:e.categoryLayout?.imageCrop??Ne.categoryLayout.imageCrop},sections:{showDescription:e.sections?.showDescription??Ne.sections.showDescription,showSpecs:e.sections?.showSpecs??Ne.sections.showSpecs,showShipping:e.sections?.showShipping??Ne.sections.showShipping,showRelatedProducts:e.sections?.showRelatedProducts??Ne.sections.showRelatedProducts},inventory:{preCheckoutVerification:e.inventory?.preCheckoutVerification??Ne.inventory.preCheckoutVerification,holdsEnabled:e.inventory?.holdsEnabled??Ne.inventory.holdsEnabled,holdDurationMinutes:e.inventory?.holdDurationMinutes??Ne.inventory.holdDurationMinutes},shopPage:{title:e.shopPage?.title??Ne.shopPage.title,description:e.shopPage?.description??Ne.shopPage.description}}}function or(e={}){const r=Oa()?.config?.adapter,[s,o]=y.useState(Ne),[a,i]=y.useState(!!r?.getStorefrontSettings);return y.useEffect(()=>{if(!r?.getStorefrontSettings){i(!1);return}let c=!1;async function l(){try{const d=await r.getStorefrontSettings();!c&&d&&o(Vv(d))}catch{}finally{c||i(!1)}}return l(),()=>{c=!0}},[r]),{settings:s,isLoading:a}}const qv={card:!0,crypto:!0,credits:!1};function Wd(){const t=Oa()?.config?.adapter,[r,s]=y.useState(qv),[o,a]=y.useState(!!t?.getPaymentMethodsConfig);return y.useEffect(()=>{if(!t?.getPaymentMethodsConfig){a(!1);return}let i=!1;async function c(){try{const l=await t.getPaymentMethodsConfig();!i&&l&&s(l)}catch{}finally{i||a(!1)}}return c(),()=>{i=!0}},[t]),{config:r,isLoading:o}}const Nc=new Map;function Hv(e){return e.productId?`id:${e.productId}`:e.name?`name:${e.name}`:""}function Vd(e={}){const{productId:t,product:r,enabled:s=!0}=e,a=Oa()?.config?.adapter,[i,c]=y.useState(null),[l,d]=y.useState(null),[m,u]=y.useState(!1),[p,h]=y.useState(null),_=y.useRef(0),g=y.useCallback(async()=>{const f=t?{productId:t}:r?{name:r.name,description:r.description,tags:r.tags,categoryIds:r.categoryIds}:{};if(!f.productId&&!f.name)return;if(!a?.getAIRelatedProducts){h("AI recommendations not available");return}const w=Hv(f),j=Nc.get(w);if(j){c(j.relatedProductIds),d(j.reasoning),h(null);return}const v=++_.current;u(!0),h(null);try{const b=await a.getAIRelatedProducts(f);v===_.current&&(c(b.relatedProductIds),d(b.reasoning),h(null),w&&Nc.set(w,b))}catch(b){if(v===_.current){const k=b instanceof Error?b.message:"Failed to get AI recommendations";h(k),c(null),d(null)}}finally{v===_.current&&u(!1)}},[a,t,r]);return y.useEffect(()=>{s&&(!t&&!r?.name||g())},[s,t,r?.name,g]),{relatedProductIds:i,reasoning:l,isLoading:m,error:p,refetch:g}}function Ie(e,t){if(!e)throw new Error(t)}function Et(e){return typeof e=="string"&&e.trim().length>0}async function Zv(e,t={}){const r=t.pageSize??10,s=await e.listCategories();Ie(Array.isArray(s),"listCategories() must return an array");for(const i of s)Ie(Et(i.id),"Category.id is required"),Ie(Et(i.slug),"Category.slug is required"),Ie(Et(i.name),"Category.name is required");const o=await e.listProducts({page:1,pageSize:r});if(Ie(o&&Array.isArray(o.items),"listProducts() must return { items: Product[] }"),Ie(typeof o.page=="number","listProducts().page must be a number"),Ie(typeof o.pageSize=="number","listProducts().pageSize must be a number"),o.items.length>0){const i=o.items[0];Ie(Et(i.id),"Product.id is required"),Ie(Et(i.slug),"Product.slug is required"),Ie(Et(i.title),"Product.title is required"),Ie(typeof i.description=="string","Product.description must be a string"),Ie(Array.isArray(i.images),"Product.images must be an array"),Ie(typeof i.price=="number","Product.price must be a number"),Ie(Et(i.currency),"Product.currency is required"),Ie(Array.isArray(i.tags),"Product.tags must be an array"),Ie(Array.isArray(i.categoryIds),"Product.categoryIds must be an array");const c=await e.getProductBySlug(i.slug);Ie(c===null||Et(c.id),"getProductBySlug() must return Product or null")}const a=await e.getOrderHistory();Ie(Array.isArray(a),"getOrderHistory() must return an array");for(const i of a)Ie(Et(i.id),"Order.id is required"),Ie(Et(i.createdAt),"Order.createdAt is required"),Ie(typeof i.total=="number","Order.total must be a number"),Ie(Et(i.currency),"Order.currency is required"),Ie(Array.isArray(i.items),"Order.items must be an array")}function Pc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ar(...e){return t=>{let r=!1;const s=e.map(o=>{const a=Pc(o,t);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let o=0;o<s.length;o++){const a=s[o];typeof a=="function"?a():Pc(e[o],null)}}}}function Ee(...e){return x.useCallback(ar(...e),e)}var Gv=Symbol.for("react.lazy"),vs=x[" use ".trim().toString()];function Qv(e){return typeof e=="object"&&e!==null&&"then"in e}function qd(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Gv&&"_payload"in e&&Qv(e._payload)}function Hd(e){const t=Kv(e),r=x.forwardRef((s,o)=>{let{children:a,...i}=s;qd(a)&&typeof vs=="function"&&(a=vs(a._payload));const c=x.Children.toArray(a),l=c.find(Jv);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}var Yv=Hd("Slot");function Kv(e){const t=x.forwardRef((r,s)=>{let{children:o,...a}=r;if(qd(o)&&typeof vs=="function"&&(o=vs(o._payload)),x.isValidElement(o)){const i=t0(o),c=e0(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Xv=Symbol("radix.slottable");function Jv(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Xv}function e0(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function t0(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function Zd(e){var t,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(r=Zd(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function Gd(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=Zd(e))&&(s&&(s+=" "),s+=t);return s}const Ac=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Ec=Gd,Ga=(e,t)=>r=>{var s;if(t?.variants==null)return Ec(e,r?.class,r?.className);const{variants:o,defaultVariants:a}=t,i=Object.keys(o).map(d=>{const m=r?.[d],u=a?.[d];if(m===null)return null;const p=Ac(m)||Ac(u);return o[d][p]}),c=r&&Object.entries(r).reduce((d,m)=>{let[u,p]=m;return p===void 0||(d[u]=p),d},{}),l=t==null||(s=t.compoundVariants)===null||s===void 0?void 0:s.reduce((d,m)=>{let{class:u,className:p,...h}=m;return Object.entries(h).every(_=>{let[g,f]=_;return Array.isArray(f)?f.includes({...a,...c}[g]):{...a,...c}[g]===f})?[...d,u,p]:d},[]);return Ec(e,i,l,r?.class,r?.className)},n0=(e,t)=>{const r=new Array(e.length+t.length);for(let s=0;s<e.length;s++)r[s]=e[s];for(let s=0;s<t.length;s++)r[e.length+s]=t[s];return r},r0=(e,t)=>({classGroupId:e,validator:t}),Qd=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),ws="-",Tc=[],s0="arbitrary..",o0=e=>{const t=i0(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return a0(i);const c=i.split(ws),l=c[0]===""&&c.length>1?1:0;return Yd(c,l,t)},getConflictingClassGroupIds:(i,c)=>{if(c){const l=s[i],d=r[i];return l?d?n0(d,l):l:d||Tc}return r[i]||Tc}}},Yd=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],a=r.nextPart.get(o);if(a){const d=Yd(e,t+1,a);if(d)return d}const i=r.validators;if(i===null)return;const c=t===0?e.join(ws):e.slice(t).join(ws),l=i.length;for(let d=0;d<l;d++){const m=i[d];if(m.validator(c))return m.classGroupId}},a0=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),s=t.slice(0,r);return s?s0+s:void 0})(),i0=e=>{const{theme:t,classGroups:r}=e;return c0(r,t)},c0=(e,t)=>{const r=Qd();for(const s in e){const o=e[s];Qa(o,r,s,t)}return r},Qa=(e,t,r,s)=>{const o=e.length;for(let a=0;a<o;a++){const i=e[a];l0(i,t,r,s)}},l0=(e,t,r,s)=>{if(typeof e=="string"){d0(e,t,r);return}if(typeof e=="function"){u0(e,t,r,s);return}m0(e,t,r,s)},d0=(e,t,r)=>{const s=e===""?t:Kd(t,e);s.classGroupId=r},u0=(e,t,r,s)=>{if(p0(e)){Qa(e(s),t,r,s);return}t.validators===null&&(t.validators=[]),t.validators.push(r0(r,e))},m0=(e,t,r,s)=>{const o=Object.entries(e),a=o.length;for(let i=0;i<a;i++){const[c,l]=o[i];Qa(l,Kd(t,c),r,s)}},Kd=(e,t)=>{let r=e;const s=t.split(ws),o=s.length;for(let a=0;a<o;a++){const i=s[a];let c=r.nextPart.get(i);c||(c=Qd(),r.nextPart.set(i,c)),r=c}return r},p0=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,f0=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),s=Object.create(null);const o=(a,i)=>{r[a]=i,t++,t>e&&(t=0,s=r,r=Object.create(null))};return{get(a){let i=r[a];if(i!==void 0)return i;if((i=s[a])!==void 0)return o(a,i),i},set(a,i){a in r?r[a]=i:o(a,i)}}},sa="!",Ic=":",h0=[],Rc=(e,t,r,s,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),g0=e=>{const{prefix:t,experimentalParseClassName:r}=e;let s=o=>{const a=[];let i=0,c=0,l=0,d;const m=o.length;for(let g=0;g<m;g++){const f=o[g];if(i===0&&c===0){if(f===Ic){a.push(o.slice(l,g)),l=g+1;continue}if(f==="/"){d=g;continue}}f==="["?i++:f==="]"?i--:f==="("?c++:f===")"&&c--}const u=a.length===0?o:o.slice(l);let p=u,h=!1;u.endsWith(sa)?(p=u.slice(0,-1),h=!0):u.startsWith(sa)&&(p=u.slice(1),h=!0);const _=d&&d>l?d-l:void 0;return Rc(a,h,p,_)};if(t){const o=t+Ic,a=s;s=i=>i.startsWith(o)?a(i.slice(o.length)):Rc(h0,!1,i,void 0,!0)}if(r){const o=s;s=a=>r({className:a,parseClassName:o})}return s},x0=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,s)=>{t.set(r,1e6+s)}),r=>{const s=[];let o=[];for(let a=0;a<r.length;a++){const i=r[a],c=i[0]==="[",l=t.has(i);c||l?(o.length>0&&(o.sort(),s.push(...o),o=[]),s.push(i)):o.push(i)}return o.length>0&&(o.sort(),s.push(...o)),s}},y0=e=>({cache:f0(e.cacheSize),parseClassName:g0(e),sortModifiers:x0(e),...o0(e)}),b0=/\s+/,v0=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:a}=t,i=[],c=e.trim().split(b0);let l="";for(let d=c.length-1;d>=0;d-=1){const m=c[d],{isExternal:u,modifiers:p,hasImportantModifier:h,baseClassName:_,maybePostfixModifierPosition:g}=r(m);if(u){l=m+(l.length>0?" "+l:l);continue}let f=!!g,w=s(f?_.substring(0,g):_);if(!w){if(!f){l=m+(l.length>0?" "+l:l);continue}if(w=s(_),!w){l=m+(l.length>0?" "+l:l);continue}f=!1}const j=p.length===0?"":p.length===1?p[0]:a(p).join(":"),v=h?j+sa:j,b=v+w;if(i.indexOf(b)>-1)continue;i.push(b);const k=o(w,f);for(let R=0;R<k.length;++R){const N=k[R];i.push(v+N)}l=m+(l.length>0?" "+l:l)}return l},w0=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=Xd(r))&&(o&&(o+=" "),o+=s);return o},Xd=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=Xd(e[s]))&&(r&&(r+=" "),r+=t);return r},_0=(e,...t)=>{let r,s,o,a;const i=l=>{const d=t.reduce((m,u)=>u(m),e());return r=y0(d),s=r.cache.get,o=r.cache.set,a=c,c(l)},c=l=>{const d=s(l);if(d)return d;const m=v0(l,r);return o(l,m),m};return a=i,(...l)=>a(w0(...l))},j0=[],Ze=e=>{const t=r=>r[e]||j0;return t.isThemeGetter=!0,t},Jd=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,eu=/^\((?:(\w[\w-]*):)?(.+)\)$/i,k0=/^\d+\/\d+$/,S0=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,C0=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,N0=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,P0=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,A0=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Hn=e=>k0.test(e),ye=e=>!!e&&!Number.isNaN(Number(e)),an=e=>!!e&&Number.isInteger(Number(e)),Eo=e=>e.endsWith("%")&&ye(e.slice(0,-1)),nn=e=>S0.test(e),E0=()=>!0,T0=e=>C0.test(e)&&!N0.test(e),tu=()=>!1,I0=e=>P0.test(e),R0=e=>A0.test(e),O0=e=>!se(e)&&!oe(e),M0=e=>ir(e,su,tu),se=e=>Jd.test(e),Cn=e=>ir(e,ou,T0),To=e=>ir(e,F0,ye),Oc=e=>ir(e,nu,tu),D0=e=>ir(e,ru,R0),Yr=e=>ir(e,au,I0),oe=e=>eu.test(e),hr=e=>cr(e,ou),L0=e=>cr(e,B0),Mc=e=>cr(e,nu),$0=e=>cr(e,su),z0=e=>cr(e,ru),Kr=e=>cr(e,au,!0),ir=(e,t,r)=>{const s=Jd.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},cr=(e,t,r=!1)=>{const s=eu.exec(e);return s?s[1]?t(s[1]):r:!1},nu=e=>e==="position"||e==="percentage",ru=e=>e==="image"||e==="url",su=e=>e==="length"||e==="size"||e==="bg-size",ou=e=>e==="length",F0=e=>e==="number",B0=e=>e==="family-name",au=e=>e==="shadow",U0=()=>{const e=Ze("color"),t=Ze("font"),r=Ze("text"),s=Ze("font-weight"),o=Ze("tracking"),a=Ze("leading"),i=Ze("breakpoint"),c=Ze("container"),l=Ze("spacing"),d=Ze("radius"),m=Ze("shadow"),u=Ze("inset-shadow"),p=Ze("text-shadow"),h=Ze("drop-shadow"),_=Ze("blur"),g=Ze("perspective"),f=Ze("aspect"),w=Ze("ease"),j=Ze("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],k=()=>[...b(),oe,se],R=()=>["auto","hidden","clip","visible","scroll"],N=()=>["auto","contain","none"],C=()=>[oe,se,l],T=()=>[Hn,"full","auto",...C()],O=()=>[an,"none","subgrid",oe,se],$=()=>["auto",{span:["full",an,oe,se]},an,oe,se],S=()=>[an,"auto",oe,se],A=()=>["auto","min","max","fr",oe,se],I=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],B=()=>["start","end","center","stretch","center-safe","end-safe"],D=()=>["auto",...C()],E=()=>[Hn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...C()],P=()=>[e,oe,se],z=()=>[...b(),Mc,Oc,{position:[oe,se]}],Z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],K=()=>["auto","cover","contain",$0,M0,{size:[oe,se]}],L=()=>[Eo,hr,Cn],W=()=>["","none","full",d,oe,se],Y=()=>["",ye,hr,Cn],V=()=>["solid","dashed","dotted","double"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],F=()=>[ye,Eo,Mc,Oc],ee=()=>["","none",_,oe,se],pe=()=>["none",ye,oe,se],q=()=>["none",ye,oe,se],ne=()=>[ye,oe,se],le=()=>[Hn,"full",...C()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[nn],breakpoint:[nn],color:[E0],container:[nn],"drop-shadow":[nn],ease:["in","out","in-out"],font:[O0],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[nn],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[nn],shadow:[nn],spacing:["px",ye],text:[nn],"text-shadow":[nn],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Hn,se,oe,f]}],container:["container"],columns:[{columns:[ye,se,oe,c]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:k()}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:N()}],"overscroll-x":[{"overscroll-x":N()}],"overscroll-y":[{"overscroll-y":N()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{start:T()}],end:[{end:T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[an,"auto",oe,se]}],basis:[{basis:[Hn,"full","auto",c,...C()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ye,Hn,"auto","initial","none",se]}],grow:[{grow:["",ye,oe,se]}],shrink:[{shrink:["",ye,oe,se]}],order:[{order:[an,"first","last","none",oe,se]}],"grid-cols":[{"grid-cols":O()}],"col-start-end":[{col:$()}],"col-start":[{"col-start":S()}],"col-end":[{"col-end":S()}],"grid-rows":[{"grid-rows":O()}],"row-start-end":[{row:$()}],"row-start":[{"row-start":S()}],"row-end":[{"row-end":S()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":A()}],"auto-rows":[{"auto-rows":A()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...I(),"normal"]}],"justify-items":[{"justify-items":[...B(),"normal"]}],"justify-self":[{"justify-self":["auto",...B()]}],"align-content":[{content:["normal",...I()]}],"align-items":[{items:[...B(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...B(),{baseline:["","last"]}]}],"place-content":[{"place-content":I()}],"place-items":[{"place-items":[...B(),"baseline"]}],"place-self":[{"place-self":["auto",...B()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:D()}],mx:[{mx:D()}],my:[{my:D()}],ms:[{ms:D()}],me:[{me:D()}],mt:[{mt:D()}],mr:[{mr:D()}],mb:[{mb:D()}],ml:[{ml:D()}],"space-x":[{"space-x":C()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":C()}],"space-y-reverse":["space-y-reverse"],size:[{size:E()}],w:[{w:[c,"screen",...E()]}],"min-w":[{"min-w":[c,"screen","none",...E()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[i]},...E()]}],h:[{h:["screen","lh",...E()]}],"min-h":[{"min-h":["screen","lh","none",...E()]}],"max-h":[{"max-h":["screen","lh",...E()]}],"font-size":[{text:["base",r,hr,Cn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,oe,To]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Eo,se]}],"font-family":[{font:[L0,se,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,oe,se]}],"line-clamp":[{"line-clamp":[ye,"none",oe,To]}],leading:[{leading:[a,...C()]}],"list-image":[{"list-image":["none",oe,se]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",oe,se]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:P()}],"text-color":[{text:P()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:[ye,"from-font","auto",oe,Cn]}],"text-decoration-color":[{decoration:P()}],"underline-offset":[{"underline-offset":[ye,"auto",oe,se]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",oe,se]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",oe,se]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:Z()}],"bg-size":[{bg:K()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},an,oe,se],radial:["",oe,se],conic:[an,oe,se]},z0,D0]}],"bg-color":[{bg:P()}],"gradient-from-pos":[{from:L()}],"gradient-via-pos":[{via:L()}],"gradient-to-pos":[{to:L()}],"gradient-from":[{from:P()}],"gradient-via":[{via:P()}],"gradient-to":[{to:P()}],rounded:[{rounded:W()}],"rounded-s":[{"rounded-s":W()}],"rounded-e":[{"rounded-e":W()}],"rounded-t":[{"rounded-t":W()}],"rounded-r":[{"rounded-r":W()}],"rounded-b":[{"rounded-b":W()}],"rounded-l":[{"rounded-l":W()}],"rounded-ss":[{"rounded-ss":W()}],"rounded-se":[{"rounded-se":W()}],"rounded-ee":[{"rounded-ee":W()}],"rounded-es":[{"rounded-es":W()}],"rounded-tl":[{"rounded-tl":W()}],"rounded-tr":[{"rounded-tr":W()}],"rounded-br":[{"rounded-br":W()}],"rounded-bl":[{"rounded-bl":W()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...V(),"hidden","none"]}],"divide-style":[{divide:[...V(),"hidden","none"]}],"border-color":[{border:P()}],"border-color-x":[{"border-x":P()}],"border-color-y":[{"border-y":P()}],"border-color-s":[{"border-s":P()}],"border-color-e":[{"border-e":P()}],"border-color-t":[{"border-t":P()}],"border-color-r":[{"border-r":P()}],"border-color-b":[{"border-b":P()}],"border-color-l":[{"border-l":P()}],"divide-color":[{divide:P()}],"outline-style":[{outline:[...V(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ye,oe,se]}],"outline-w":[{outline:["",ye,hr,Cn]}],"outline-color":[{outline:P()}],shadow:[{shadow:["","none",m,Kr,Yr]}],"shadow-color":[{shadow:P()}],"inset-shadow":[{"inset-shadow":["none",u,Kr,Yr]}],"inset-shadow-color":[{"inset-shadow":P()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:P()}],"ring-offset-w":[{"ring-offset":[ye,Cn]}],"ring-offset-color":[{"ring-offset":P()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":P()}],"text-shadow":[{"text-shadow":["none",p,Kr,Yr]}],"text-shadow-color":[{"text-shadow":P()}],opacity:[{opacity:[ye,oe,se]}],"mix-blend":[{"mix-blend":[...ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":F()}],"mask-image-linear-to-pos":[{"mask-linear-to":F()}],"mask-image-linear-from-color":[{"mask-linear-from":P()}],"mask-image-linear-to-color":[{"mask-linear-to":P()}],"mask-image-t-from-pos":[{"mask-t-from":F()}],"mask-image-t-to-pos":[{"mask-t-to":F()}],"mask-image-t-from-color":[{"mask-t-from":P()}],"mask-image-t-to-color":[{"mask-t-to":P()}],"mask-image-r-from-pos":[{"mask-r-from":F()}],"mask-image-r-to-pos":[{"mask-r-to":F()}],"mask-image-r-from-color":[{"mask-r-from":P()}],"mask-image-r-to-color":[{"mask-r-to":P()}],"mask-image-b-from-pos":[{"mask-b-from":F()}],"mask-image-b-to-pos":[{"mask-b-to":F()}],"mask-image-b-from-color":[{"mask-b-from":P()}],"mask-image-b-to-color":[{"mask-b-to":P()}],"mask-image-l-from-pos":[{"mask-l-from":F()}],"mask-image-l-to-pos":[{"mask-l-to":F()}],"mask-image-l-from-color":[{"mask-l-from":P()}],"mask-image-l-to-color":[{"mask-l-to":P()}],"mask-image-x-from-pos":[{"mask-x-from":F()}],"mask-image-x-to-pos":[{"mask-x-to":F()}],"mask-image-x-from-color":[{"mask-x-from":P()}],"mask-image-x-to-color":[{"mask-x-to":P()}],"mask-image-y-from-pos":[{"mask-y-from":F()}],"mask-image-y-to-pos":[{"mask-y-to":F()}],"mask-image-y-from-color":[{"mask-y-from":P()}],"mask-image-y-to-color":[{"mask-y-to":P()}],"mask-image-radial":[{"mask-radial":[oe,se]}],"mask-image-radial-from-pos":[{"mask-radial-from":F()}],"mask-image-radial-to-pos":[{"mask-radial-to":F()}],"mask-image-radial-from-color":[{"mask-radial-from":P()}],"mask-image-radial-to-color":[{"mask-radial-to":P()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":F()}],"mask-image-conic-to-pos":[{"mask-conic-to":F()}],"mask-image-conic-from-color":[{"mask-conic-from":P()}],"mask-image-conic-to-color":[{"mask-conic-to":P()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:Z()}],"mask-size":[{mask:K()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",oe,se]}],filter:[{filter:["","none",oe,se]}],blur:[{blur:ee()}],brightness:[{brightness:[ye,oe,se]}],contrast:[{contrast:[ye,oe,se]}],"drop-shadow":[{"drop-shadow":["","none",h,Kr,Yr]}],"drop-shadow-color":[{"drop-shadow":P()}],grayscale:[{grayscale:["",ye,oe,se]}],"hue-rotate":[{"hue-rotate":[ye,oe,se]}],invert:[{invert:["",ye,oe,se]}],saturate:[{saturate:[ye,oe,se]}],sepia:[{sepia:["",ye,oe,se]}],"backdrop-filter":[{"backdrop-filter":["","none",oe,se]}],"backdrop-blur":[{"backdrop-blur":ee()}],"backdrop-brightness":[{"backdrop-brightness":[ye,oe,se]}],"backdrop-contrast":[{"backdrop-contrast":[ye,oe,se]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ye,oe,se]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ye,oe,se]}],"backdrop-invert":[{"backdrop-invert":["",ye,oe,se]}],"backdrop-opacity":[{"backdrop-opacity":[ye,oe,se]}],"backdrop-saturate":[{"backdrop-saturate":[ye,oe,se]}],"backdrop-sepia":[{"backdrop-sepia":["",ye,oe,se]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",oe,se]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ye,"initial",oe,se]}],ease:[{ease:["linear","initial",w,oe,se]}],delay:[{delay:[ye,oe,se]}],animate:[{animate:["none",j,oe,se]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,oe,se]}],"perspective-origin":[{"perspective-origin":k()}],rotate:[{rotate:pe()}],"rotate-x":[{"rotate-x":pe()}],"rotate-y":[{"rotate-y":pe()}],"rotate-z":[{"rotate-z":pe()}],scale:[{scale:q()}],"scale-x":[{"scale-x":q()}],"scale-y":[{"scale-y":q()}],"scale-z":[{"scale-z":q()}],"scale-3d":["scale-3d"],skew:[{skew:ne()}],"skew-x":[{"skew-x":ne()}],"skew-y":[{"skew-y":ne()}],transform:[{transform:[oe,se,"","none","gpu","cpu"]}],"transform-origin":[{origin:k()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:le()}],"translate-x":[{"translate-x":le()}],"translate-y":[{"translate-y":le()}],"translate-z":[{"translate-z":le()}],"translate-none":["translate-none"],accent:[{accent:P()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:P()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",oe,se]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",oe,se]}],fill:[{fill:["none",...P()]}],"stroke-w":[{stroke:[ye,hr,Cn,To]}],stroke:[{stroke:["none",...P()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},W0=_0(U0);function H(...e){return W0(Gd(e))}const V0=Ga("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-neutral-50/20",{variants:{variant:{default:"bg-neutral-900 text-neutral-50 hover:bg-neutral-900/90 dark:bg-neutral-50 dark:text-neutral-900 dark:hover:bg-neutral-50/90",secondary:"bg-neutral-100 text-neutral-900 hover:bg-neutral-100/80 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800/80",outline:"border border-neutral-200 bg-transparent text-neutral-900 hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800",ghost:"bg-transparent text-neutral-900 hover:bg-neutral-100 dark:text-neutral-50 dark:hover:bg-neutral-800",destructive:"bg-red-600 text-neutral-50 hover:bg-red-600/90 dark:bg-red-500 dark:hover:bg-red-500/90",link:"bg-transparent text-neutral-900 underline-offset-4 hover:underline dark:text-neutral-50"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-6",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ie=x.forwardRef(({className:e,variant:t,size:r,asChild:s,...o},a)=>{const i=s?Yv:"button";return n.jsx(i,{className:H(V0({variant:t,size:r}),e),ref:a,...o})});ie.displayName="Button";const q0=Ga("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors",{variants:{variant:{default:"border-transparent bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900",secondary:"border-transparent bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",outline:"border-neutral-200 text-neutral-900 dark:border-neutral-800 dark:text-neutral-50"}},defaultVariants:{variant:"secondary"}});function Pn({className:e,variant:t,...r}){return n.jsx("div",{className:H(q0({variant:t}),e),...r})}const Rt=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("rounded-xl border border-neutral-200 bg-white text-neutral-950 shadow-sm dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",e),...t}));Rt.displayName="Card";const Er=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex flex-col space-y-1.5 p-6",e),...t}));Er.displayName="CardHeader";const Tr=x.forwardRef(({className:e,...t},r)=>n.jsx("h3",{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));Tr.displayName="CardTitle";const iu=x.forwardRef(({className:e,...t},r)=>n.jsx("p",{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));iu.displayName="CardDescription";const Gt=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("p-6 pt-0",e),...t}));Gt.displayName="CardContent";const cu=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex items-center p-6 pt-0",e),...t}));cu.displayName="CardFooter";const Be=x.forwardRef(({className:e,...t},r)=>n.jsx("input",{ref:r,className:H("flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-50/20",e),...t}));Be.displayName="Input";const at=x.forwardRef(({className:e,...t},r)=>n.jsx("label",{ref:r,className:H("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",e),...t}));at.displayName="Label";var H0=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Z0=H0.reduce((e,t)=>{const r=Hd(`Primitive.${t}`),s=x.forwardRef((o,a)=>{const{asChild:i,...c}=o,l=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(l,{...c,ref:a})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{}),G0="Separator",Dc="horizontal",Q0=["horizontal","vertical"],lu=x.forwardRef((e,t)=>{const{decorative:r,orientation:s=Dc,...o}=e,a=Y0(s)?s:Dc,c=r?{role:"none"}:{"aria-orientation":a==="vertical"?a:void 0,role:"separator"};return n.jsx(Z0.div,{"data-orientation":a,...c,...o,ref:t})});lu.displayName=G0;function Y0(e){return Q0.includes(e)}var du=lu;const St=x.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...s},o)=>n.jsx(du,{ref:o,decorative:r,orientation:t,className:H("shrink-0 bg-neutral-200 dark:bg-neutral-800",t==="horizontal"?"h-px w-full":"h-full w-px",e),...s}));St.displayName=du.displayName;function De({className:e,...t}){return n.jsx("div",{className:H("animate-pulse rounded-md bg-neutral-100 dark:bg-neutral-800",e),...t})}function Lc(e,[t,r]){return Math.min(r,Math.max(t,e))}function _e(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e?.(o),r===!1||!o.defaultPrevented)return t?.(o)}}function K0(e,t){const r=x.createContext(t),s=a=>{const{children:i,...c}=a,l=x.useMemo(()=>c,Object.values(c));return n.jsx(r.Provider,{value:l,children:i})};s.displayName=e+"Provider";function o(a){const i=x.useContext(r);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${a}\` must be used within \`${e}\``)}return[s,o]}function vn(e,t=[]){let r=[];function s(a,i){const c=x.createContext(i),l=r.length;r=[...r,i];const d=u=>{const{scope:p,children:h,..._}=u,g=p?.[e]?.[l]||c,f=x.useMemo(()=>_,Object.values(_));return n.jsx(g.Provider,{value:f,children:h})};d.displayName=a+"Provider";function m(u,p){const h=p?.[e]?.[l]||c,_=x.useContext(h);if(_)return _;if(i!==void 0)return i;throw new Error(`\`${u}\` must be used within \`${a}\``)}return[d,m]}const o=()=>{const a=r.map(i=>x.createContext(i));return function(c){const l=c?.[e]||a;return x.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return o.scopeName=e,[s,X0(o,...t)]}function X0(...e){const t=e[0];if(e.length===1)return t;const r=()=>{const s=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(a){const i=s.reduce((c,{useScope:l,scopeName:d})=>{const u=l(a)[`__scope${d}`];return{...c,...u}},{});return x.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return r.scopeName=t.scopeName,r}function $c(e){const t=J0(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(tw);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function J0(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=rw(o),c=nw(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ew=Symbol("radix.slottable");function tw(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ew}function nw(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function rw(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function Ya(e){const t=e+"CollectionProvider",[r,s]=vn(t),[o,a]=r(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:f,children:w}=g,j=y.useRef(null),v=y.useRef(new Map).current;return n.jsx(o,{scope:f,itemMap:v,collectionRef:j,children:w})};i.displayName=t;const c=e+"CollectionSlot",l=$c(c),d=y.forwardRef((g,f)=>{const{scope:w,children:j}=g,v=a(c,w),b=Ee(f,v.collectionRef);return n.jsx(l,{ref:b,children:j})});d.displayName=c;const m=e+"CollectionItemSlot",u="data-radix-collection-item",p=$c(m),h=y.forwardRef((g,f)=>{const{scope:w,children:j,...v}=g,b=y.useRef(null),k=Ee(f,b),R=a(m,w);return y.useEffect(()=>(R.itemMap.set(b,{ref:b,...v}),()=>void R.itemMap.delete(b))),n.jsx(p,{[u]:"",ref:k,children:j})});h.displayName=m;function _(g){const f=a(e+"CollectionConsumer",g);return y.useCallback(()=>{const j=f.collectionRef.current;if(!j)return[];const v=Array.from(j.querySelectorAll(`[${u}]`));return Array.from(f.itemMap.values()).sort((R,N)=>v.indexOf(R.ref.current)-v.indexOf(N.ref.current))},[f.collectionRef,f.itemMap])}return[{Provider:i,Slot:d,ItemSlot:h},_,s]}var sw=x.createContext(void 0);function Fs(e){const t=x.useContext(sw);return e||t||"ltr"}function ow(e){const t=aw(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(cw);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function aw(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=dw(o),c=lw(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var iw=Symbol("radix.slottable");function cw(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===iw}function lw(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function dw(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var uw=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ve=uw.reduce((e,t)=>{const r=ow(`Primitive.${t}`),s=x.forwardRef((o,a)=>{const{asChild:i,...c}=o,l=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(l,{...c,ref:a})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{});function mw(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function mn(e){const t=x.useRef(e);return x.useEffect(()=>{t.current=e}),x.useMemo(()=>(...r)=>t.current?.(...r),[])}function pw(e,t=globalThis?.document){const r=mn(e);x.useEffect(()=>{const s=o=>{o.key==="Escape"&&r(o)};return t.addEventListener("keydown",s,{capture:!0}),()=>t.removeEventListener("keydown",s,{capture:!0})},[r,t])}var fw="DismissableLayer",oa="dismissableLayer.update",hw="dismissableLayer.pointerDownOutside",gw="dismissableLayer.focusOutside",zc,uu=x.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ka=x.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:i,onDismiss:c,...l}=e,d=x.useContext(uu),[m,u]=x.useState(null),p=m?.ownerDocument??globalThis?.document,[,h]=x.useState({}),_=Ee(t,N=>u(N)),g=Array.from(d.layers),[f]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),w=g.indexOf(f),j=m?g.indexOf(m):-1,v=d.layersWithOutsidePointerEventsDisabled.size>0,b=j>=w,k=bw(N=>{const C=N.target,T=[...d.branches].some(O=>O.contains(C));!b||T||(o?.(N),i?.(N),N.defaultPrevented||c?.())},p),R=vw(N=>{const C=N.target;[...d.branches].some(O=>O.contains(C))||(a?.(N),i?.(N),N.defaultPrevented||c?.())},p);return pw(N=>{j===d.layers.size-1&&(s?.(N),!N.defaultPrevented&&c&&(N.preventDefault(),c()))},p),x.useEffect(()=>{if(m)return r&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(zc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(m)),d.layers.add(m),Fc(),()=>{r&&d.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=zc)}},[m,p,r,d]),x.useEffect(()=>()=>{m&&(d.layers.delete(m),d.layersWithOutsidePointerEventsDisabled.delete(m),Fc())},[m,d]),x.useEffect(()=>{const N=()=>h({});return document.addEventListener(oa,N),()=>document.removeEventListener(oa,N)},[]),n.jsx(ve.div,{...l,ref:_,style:{pointerEvents:v?b?"auto":"none":void 0,...e.style},onFocusCapture:_e(e.onFocusCapture,R.onFocusCapture),onBlurCapture:_e(e.onBlurCapture,R.onBlurCapture),onPointerDownCapture:_e(e.onPointerDownCapture,k.onPointerDownCapture)})});Ka.displayName=fw;var xw="DismissableLayerBranch",yw=x.forwardRef((e,t)=>{const r=x.useContext(uu),s=x.useRef(null),o=Ee(t,s);return x.useEffect(()=>{const a=s.current;if(a)return r.branches.add(a),()=>{r.branches.delete(a)}},[r.branches]),n.jsx(ve.div,{...e,ref:o})});yw.displayName=xw;function bw(e,t=globalThis?.document){const r=mn(e),s=x.useRef(!1),o=x.useRef(()=>{});return x.useEffect(()=>{const a=c=>{if(c.target&&!s.current){let l=function(){mu(hw,r,d,{discrete:!0})};const d={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);s.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",a)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",a),t.removeEventListener("click",o.current)}},[t,r]),{onPointerDownCapture:()=>s.current=!0}}function vw(e,t=globalThis?.document){const r=mn(e),s=x.useRef(!1);return x.useEffect(()=>{const o=a=>{a.target&&!s.current&&mu(gw,r,{originalEvent:a},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,r]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function Fc(){const e=new CustomEvent(oa);document.dispatchEvent(e)}function mu(e,t,r,{discrete:s}){const o=r.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&o.addEventListener(e,t,{once:!0}),s?mw(o,a):o.dispatchEvent(a)}var Io=0;function pu(){x.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Bc()),document.body.insertAdjacentElement("beforeend",e[1]??Bc()),Io++,()=>{Io===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Io--}},[])}function Bc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Ro="focusScope.autoFocusOnMount",Oo="focusScope.autoFocusOnUnmount",Uc={bubbles:!1,cancelable:!0},ww="FocusScope",Xa=x.forwardRef((e,t)=>{const{loop:r=!1,trapped:s=!1,onMountAutoFocus:o,onUnmountAutoFocus:a,...i}=e,[c,l]=x.useState(null),d=mn(o),m=mn(a),u=x.useRef(null),p=Ee(t,g=>l(g)),h=x.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;x.useEffect(()=>{if(s){let g=function(v){if(h.paused||!c)return;const b=v.target;c.contains(b)?u.current=b:cn(u.current,{select:!0})},f=function(v){if(h.paused||!c)return;const b=v.relatedTarget;b!==null&&(c.contains(b)||cn(u.current,{select:!0}))},w=function(v){if(document.activeElement===document.body)for(const k of v)k.removedNodes.length>0&&cn(c)};document.addEventListener("focusin",g),document.addEventListener("focusout",f);const j=new MutationObserver(w);return c&&j.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",f),j.disconnect()}}},[s,c,h.paused]),x.useEffect(()=>{if(c){Vc.add(h);const g=document.activeElement;if(!c.contains(g)){const w=new CustomEvent(Ro,Uc);c.addEventListener(Ro,d),c.dispatchEvent(w),w.defaultPrevented||(_w(Nw(fu(c)),{select:!0}),document.activeElement===g&&cn(c))}return()=>{c.removeEventListener(Ro,d),setTimeout(()=>{const w=new CustomEvent(Oo,Uc);c.addEventListener(Oo,m),c.dispatchEvent(w),w.defaultPrevented||cn(g??document.body,{select:!0}),c.removeEventListener(Oo,m),Vc.remove(h)},0)}}},[c,d,m,h]);const _=x.useCallback(g=>{if(!r&&!s||h.paused)return;const f=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,w=document.activeElement;if(f&&w){const j=g.currentTarget,[v,b]=jw(j);v&&b?!g.shiftKey&&w===b?(g.preventDefault(),r&&cn(v,{select:!0})):g.shiftKey&&w===v&&(g.preventDefault(),r&&cn(b,{select:!0})):w===j&&g.preventDefault()}},[r,s,h.paused]);return n.jsx(ve.div,{tabIndex:-1,...i,ref:p,onKeyDown:_})});Xa.displayName=ww;function _w(e,{select:t=!1}={}){const r=document.activeElement;for(const s of e)if(cn(s,{select:t}),document.activeElement!==r)return}function jw(e){const t=fu(e),r=Wc(t,e),s=Wc(t.reverse(),e);return[r,s]}function fu(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const o=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||o?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function Wc(e,t){for(const r of e)if(!kw(r,{upTo:t}))return r}function kw(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Sw(e){return e instanceof HTMLInputElement&&"select"in e}function cn(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&Sw(e)&&t&&e.select()}}var Vc=Cw();function Cw(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=qc(e,t),e.unshift(t)},remove(t){e=qc(e,t),e[0]?.resume()}}}function qc(e,t){const r=[...e],s=r.indexOf(t);return s!==-1&&r.splice(s,1),r}function Nw(e){return e.filter(t=>t.tagName!=="A")}var Xe=globalThis?.document?x.useLayoutEffect:()=>{},Pw=x[" useId ".trim().toString()]||(()=>{}),Aw=0;function qt(e){const[t,r]=x.useState(Pw());return Xe(()=>{r(s=>s??String(Aw++))},[e]),t?`radix-${t}`:""}const Ew=["top","right","bottom","left"],pn=Math.min,wt=Math.max,_s=Math.round,Xr=Math.floor,Ht=e=>({x:e,y:e}),Tw={left:"right",right:"left",bottom:"top",top:"bottom"},Iw={start:"end",end:"start"};function aa(e,t,r){return wt(e,pn(t,r))}function rn(e,t){return typeof e=="function"?e(t):e}function sn(e){return e.split("-")[0]}function lr(e){return e.split("-")[1]}function Ja(e){return e==="x"?"y":"x"}function ei(e){return e==="y"?"height":"width"}const Rw=new Set(["top","bottom"]);function Vt(e){return Rw.has(sn(e))?"y":"x"}function ti(e){return Ja(Vt(e))}function Ow(e,t,r){r===void 0&&(r=!1);const s=lr(e),o=ti(e),a=ei(o);let i=o==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(i=js(i)),[i,js(i)]}function Mw(e){const t=js(e);return[ia(e),t,ia(t)]}function ia(e){return e.replace(/start|end/g,t=>Iw[t])}const Hc=["left","right"],Zc=["right","left"],Dw=["top","bottom"],Lw=["bottom","top"];function $w(e,t,r){switch(e){case"top":case"bottom":return r?t?Zc:Hc:t?Hc:Zc;case"left":case"right":return t?Dw:Lw;default:return[]}}function zw(e,t,r,s){const o=lr(e);let a=$w(sn(e),r==="start",s);return o&&(a=a.map(i=>i+"-"+o),t&&(a=a.concat(a.map(ia)))),a}function js(e){return e.replace(/left|right|bottom|top/g,t=>Tw[t])}function Fw(e){return{top:0,right:0,bottom:0,left:0,...e}}function hu(e){return typeof e!="number"?Fw(e):{top:e,right:e,bottom:e,left:e}}function ks(e){const{x:t,y:r,width:s,height:o}=e;return{width:s,height:o,top:r,left:t,right:t+s,bottom:r+o,x:t,y:r}}function Gc(e,t,r){let{reference:s,floating:o}=e;const a=Vt(t),i=ti(t),c=ei(i),l=sn(t),d=a==="y",m=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[c]/2-o[c]/2;let h;switch(l){case"top":h={x:m,y:s.y-o.height};break;case"bottom":h={x:m,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(lr(t)){case"start":h[i]-=p*(r&&d?-1:1);break;case"end":h[i]+=p*(r&&d?-1:1);break}return h}const Bw=async(e,t,r)=>{const{placement:s="bottom",strategy:o="absolute",middleware:a=[],platform:i}=r,c=a.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let d=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:u}=Gc(d,s,l),p=s,h={},_=0;for(let g=0;g<c.length;g++){const{name:f,fn:w}=c[g],{x:j,y:v,data:b,reset:k}=await w({x:m,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:h,rects:d,platform:i,elements:{reference:e,floating:t}});m=j??m,u=v??u,h={...h,[f]:{...h[f],...b}},k&&_<=50&&(_++,typeof k=="object"&&(k.placement&&(p=k.placement),k.rects&&(d=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:m,y:u}=Gc(d,p,l)),g=-1)}return{x:m,y:u,placement:p,strategy:o,middlewareData:h}};async function Ir(e,t){var r;t===void 0&&(t={});const{x:s,y:o,platform:a,rects:i,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:m="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=rn(t,e),_=hu(h),f=c[p?u==="floating"?"reference":"floating":u],w=ks(await a.getClippingRect({element:(r=await(a.isElement==null?void 0:a.isElement(f)))==null||r?f:f.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(c.floating)),boundary:d,rootBoundary:m,strategy:l})),j=u==="floating"?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,v=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),b=await(a.isElement==null?void 0:a.isElement(v))?await(a.getScale==null?void 0:a.getScale(v))||{x:1,y:1}:{x:1,y:1},k=ks(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:j,offsetParent:v,strategy:l}):j);return{top:(w.top-k.top+_.top)/b.y,bottom:(k.bottom-w.bottom+_.bottom)/b.y,left:(w.left-k.left+_.left)/b.x,right:(k.right-w.right+_.right)/b.x}}const Uw=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:s,placement:o,rects:a,platform:i,elements:c,middlewareData:l}=t,{element:d,padding:m=0}=rn(e,t)||{};if(d==null)return{};const u=hu(m),p={x:r,y:s},h=ti(o),_=ei(h),g=await i.getDimensions(d),f=h==="y",w=f?"top":"left",j=f?"bottom":"right",v=f?"clientHeight":"clientWidth",b=a.reference[_]+a.reference[h]-p[h]-a.floating[_],k=p[h]-a.reference[h],R=await(i.getOffsetParent==null?void 0:i.getOffsetParent(d));let N=R?R[v]:0;(!N||!await(i.isElement==null?void 0:i.isElement(R)))&&(N=c.floating[v]||a.floating[_]);const C=b/2-k/2,T=N/2-g[_]/2-1,O=pn(u[w],T),$=pn(u[j],T),S=O,A=N-g[_]-$,I=N/2-g[_]/2+C,B=aa(S,I,A),D=!l.arrow&&lr(o)!=null&&I!==B&&a.reference[_]/2-(I<S?O:$)-g[_]/2<0,E=D?I<S?I-S:I-A:0;return{[h]:p[h]+E,data:{[h]:B,centerOffset:I-B-E,...D&&{alignmentOffset:E}},reset:D}}}),Ww=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var r,s;const{placement:o,middlewareData:a,rects:i,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:m=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:_="none",flipAlignment:g=!0,...f}=rn(e,t);if((r=a.arrow)!=null&&r.alignmentOffset)return{};const w=sn(o),j=Vt(c),v=sn(c)===c,b=await(l.isRTL==null?void 0:l.isRTL(d.floating)),k=p||(v||!g?[js(c)]:Mw(c)),R=_!=="none";!p&&R&&k.push(...zw(c,g,_,b));const N=[c,...k],C=await Ir(t,f),T=[];let O=((s=a.flip)==null?void 0:s.overflows)||[];if(m&&T.push(C[w]),u){const I=Ow(o,i,b);T.push(C[I[0]],C[I[1]])}if(O=[...O,{placement:o,overflows:T}],!T.every(I=>I<=0)){var $,S;const I=((($=a.flip)==null?void 0:$.index)||0)+1,B=N[I];if(B&&(!(u==="alignment"?j!==Vt(B):!1)||O.every(P=>Vt(P.placement)===j?P.overflows[0]>0:!0)))return{data:{index:I,overflows:O},reset:{placement:B}};let D=(S=O.filter(E=>E.overflows[0]<=0).sort((E,P)=>E.overflows[1]-P.overflows[1])[0])==null?void 0:S.placement;if(!D)switch(h){case"bestFit":{var A;const E=(A=O.filter(P=>{if(R){const z=Vt(P.placement);return z===j||z==="y"}return!0}).map(P=>[P.placement,P.overflows.filter(z=>z>0).reduce((z,Z)=>z+Z,0)]).sort((P,z)=>P[1]-z[1])[0])==null?void 0:A[0];E&&(D=E);break}case"initialPlacement":D=c;break}if(o!==D)return{reset:{placement:D}}}return{}}}};function Qc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Yc(e){return Ew.some(t=>e[t]>=0)}const Vw=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:s="referenceHidden",...o}=rn(e,t);switch(s){case"referenceHidden":{const a=await Ir(t,{...o,elementContext:"reference"}),i=Qc(a,r.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Yc(i)}}}case"escaped":{const a=await Ir(t,{...o,altBoundary:!0}),i=Qc(a,r.floating);return{data:{escapedOffsets:i,escaped:Yc(i)}}}default:return{}}}}},gu=new Set(["left","top"]);async function qw(e,t){const{placement:r,platform:s,elements:o}=e,a=await(s.isRTL==null?void 0:s.isRTL(o.floating)),i=sn(r),c=lr(r),l=Vt(r)==="y",d=gu.has(i)?-1:1,m=a&&l?-1:1,u=rn(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:_}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return c&&typeof _=="number"&&(h=c==="end"?_*-1:_),l?{x:h*m,y:p*d}:{x:p*d,y:h*m}}const Hw=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var r,s;const{x:o,y:a,placement:i,middlewareData:c}=t,l=await qw(t,e);return i===((r=c.offset)==null?void 0:r.placement)&&(s=c.arrow)!=null&&s.alignmentOffset?{}:{x:o+l.x,y:a+l.y,data:{...l,placement:i}}}}},Zw=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:s,placement:o}=t,{mainAxis:a=!0,crossAxis:i=!1,limiter:c={fn:f=>{let{x:w,y:j}=f;return{x:w,y:j}}},...l}=rn(e,t),d={x:r,y:s},m=await Ir(t,l),u=Vt(sn(o)),p=Ja(u);let h=d[p],_=d[u];if(a){const f=p==="y"?"top":"left",w=p==="y"?"bottom":"right",j=h+m[f],v=h-m[w];h=aa(j,h,v)}if(i){const f=u==="y"?"top":"left",w=u==="y"?"bottom":"right",j=_+m[f],v=_-m[w];_=aa(j,_,v)}const g=c.fn({...t,[p]:h,[u]:_});return{...g,data:{x:g.x-r,y:g.y-s,enabled:{[p]:a,[u]:i}}}}}},Gw=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:r,y:s,placement:o,rects:a,middlewareData:i}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=rn(e,t),m={x:r,y:s},u=Vt(o),p=Ja(u);let h=m[p],_=m[u];const g=rn(c,t),f=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const v=p==="y"?"height":"width",b=a.reference[p]-a.floating[v]+f.mainAxis,k=a.reference[p]+a.reference[v]-f.mainAxis;h<b?h=b:h>k&&(h=k)}if(d){var w,j;const v=p==="y"?"width":"height",b=gu.has(sn(o)),k=a.reference[u]-a.floating[v]+(b&&((w=i.offset)==null?void 0:w[u])||0)+(b?0:f.crossAxis),R=a.reference[u]+a.reference[v]+(b?0:((j=i.offset)==null?void 0:j[u])||0)-(b?f.crossAxis:0);_<k?_=k:_>R&&(_=R)}return{[p]:h,[u]:_}}}},Qw=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var r,s;const{placement:o,rects:a,platform:i,elements:c}=t,{apply:l=()=>{},...d}=rn(e,t),m=await Ir(t,d),u=sn(o),p=lr(o),h=Vt(o)==="y",{width:_,height:g}=a.floating;let f,w;u==="top"||u==="bottom"?(f=u,w=p===(await(i.isRTL==null?void 0:i.isRTL(c.floating))?"start":"end")?"left":"right"):(w=u,f=p==="end"?"top":"bottom");const j=g-m.top-m.bottom,v=_-m.left-m.right,b=pn(g-m[f],j),k=pn(_-m[w],v),R=!t.middlewareData.shift;let N=b,C=k;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(C=v),(s=t.middlewareData.shift)!=null&&s.enabled.y&&(N=j),R&&!p){const O=wt(m.left,0),$=wt(m.right,0),S=wt(m.top,0),A=wt(m.bottom,0);h?C=_-2*(O!==0||$!==0?O+$:wt(m.left,m.right)):N=g-2*(S!==0||A!==0?S+A:wt(m.top,m.bottom))}await l({...t,availableWidth:C,availableHeight:N});const T=await i.getDimensions(c.floating);return _!==T.width||g!==T.height?{reset:{rects:!0}}:{}}}};function Bs(){return typeof window<"u"}function dr(e){return xu(e)?(e.nodeName||"").toLowerCase():"#document"}function _t(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Kt(e){var t;return(t=(xu(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function xu(e){return Bs()?e instanceof Node||e instanceof _t(e).Node:!1}function Ot(e){return Bs()?e instanceof Element||e instanceof _t(e).Element:!1}function Qt(e){return Bs()?e instanceof HTMLElement||e instanceof _t(e).HTMLElement:!1}function Kc(e){return!Bs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof _t(e).ShadowRoot}const Yw=new Set(["inline","contents"]);function zr(e){const{overflow:t,overflowX:r,overflowY:s,display:o}=Mt(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+r)&&!Yw.has(o)}const Kw=new Set(["table","td","th"]);function Xw(e){return Kw.has(dr(e))}const Jw=[":popover-open",":modal"];function Us(e){return Jw.some(t=>{try{return e.matches(t)}catch{return!1}})}const e_=["transform","translate","scale","rotate","perspective"],t_=["transform","translate","scale","rotate","perspective","filter"],n_=["paint","layout","strict","content"];function ni(e){const t=ri(),r=Ot(e)?Mt(e):e;return e_.some(s=>r[s]?r[s]!=="none":!1)||(r.containerType?r.containerType!=="normal":!1)||!t&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!t&&(r.filter?r.filter!=="none":!1)||t_.some(s=>(r.willChange||"").includes(s))||n_.some(s=>(r.contain||"").includes(s))}function r_(e){let t=fn(e);for(;Qt(t)&&!er(t);){if(ni(t))return t;if(Us(t))return null;t=fn(t)}return null}function ri(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const s_=new Set(["html","body","#document"]);function er(e){return s_.has(dr(e))}function Mt(e){return _t(e).getComputedStyle(e)}function Ws(e){return Ot(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function fn(e){if(dr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Kc(e)&&e.host||Kt(e);return Kc(t)?t.host:t}function yu(e){const t=fn(e);return er(t)?e.ownerDocument?e.ownerDocument.body:e.body:Qt(t)&&zr(t)?t:yu(t)}function Rr(e,t,r){var s;t===void 0&&(t=[]),r===void 0&&(r=!0);const o=yu(e),a=o===((s=e.ownerDocument)==null?void 0:s.body),i=_t(o);if(a){const c=ca(i);return t.concat(i,i.visualViewport||[],zr(o)?o:[],c&&r?Rr(c):[])}return t.concat(o,Rr(o,[],r))}function ca(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function bu(e){const t=Mt(e);let r=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Qt(e),a=o?e.offsetWidth:r,i=o?e.offsetHeight:s,c=_s(r)!==a||_s(s)!==i;return c&&(r=a,s=i),{width:r,height:s,$:c}}function si(e){return Ot(e)?e:e.contextElement}function Xn(e){const t=si(e);if(!Qt(t))return Ht(1);const r=t.getBoundingClientRect(),{width:s,height:o,$:a}=bu(t);let i=(a?_s(r.width):r.width)/s,c=(a?_s(r.height):r.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!c||!Number.isFinite(c))&&(c=1),{x:i,y:c}}const o_=Ht(0);function vu(e){const t=_t(e);return!ri()||!t.visualViewport?o_:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function a_(e,t,r){return t===void 0&&(t=!1),!r||t&&r!==_t(e)?!1:t}function Tn(e,t,r,s){t===void 0&&(t=!1),r===void 0&&(r=!1);const o=e.getBoundingClientRect(),a=si(e);let i=Ht(1);t&&(s?Ot(s)&&(i=Xn(s)):i=Xn(e));const c=a_(a,r,s)?vu(a):Ht(0);let l=(o.left+c.x)/i.x,d=(o.top+c.y)/i.y,m=o.width/i.x,u=o.height/i.y;if(a){const p=_t(a),h=s&&Ot(s)?_t(s):s;let _=p,g=ca(_);for(;g&&s&&h!==_;){const f=Xn(g),w=g.getBoundingClientRect(),j=Mt(g),v=w.left+(g.clientLeft+parseFloat(j.paddingLeft))*f.x,b=w.top+(g.clientTop+parseFloat(j.paddingTop))*f.y;l*=f.x,d*=f.y,m*=f.x,u*=f.y,l+=v,d+=b,_=_t(g),g=ca(_)}}return ks({width:m,height:u,x:l,y:d})}function Vs(e,t){const r=Ws(e).scrollLeft;return t?t.left+r:Tn(Kt(e)).left+r}function wu(e,t){const r=e.getBoundingClientRect(),s=r.left+t.scrollLeft-Vs(e,r),o=r.top+t.scrollTop;return{x:s,y:o}}function i_(e){let{elements:t,rect:r,offsetParent:s,strategy:o}=e;const a=o==="fixed",i=Kt(s),c=t?Us(t.floating):!1;if(s===i||c&&a)return r;let l={scrollLeft:0,scrollTop:0},d=Ht(1);const m=Ht(0),u=Qt(s);if((u||!u&&!a)&&((dr(s)!=="body"||zr(i))&&(l=Ws(s)),Qt(s))){const h=Tn(s);d=Xn(s),m.x=h.x+s.clientLeft,m.y=h.y+s.clientTop}const p=i&&!u&&!a?wu(i,l):Ht(0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-l.scrollLeft*d.x+m.x+p.x,y:r.y*d.y-l.scrollTop*d.y+m.y+p.y}}function c_(e){return Array.from(e.getClientRects())}function l_(e){const t=Kt(e),r=Ws(e),s=e.ownerDocument.body,o=wt(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),a=wt(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-r.scrollLeft+Vs(e);const c=-r.scrollTop;return Mt(s).direction==="rtl"&&(i+=wt(t.clientWidth,s.clientWidth)-o),{width:o,height:a,x:i,y:c}}const Xc=25;function d_(e,t){const r=_t(e),s=Kt(e),o=r.visualViewport;let a=s.clientWidth,i=s.clientHeight,c=0,l=0;if(o){a=o.width,i=o.height;const m=ri();(!m||m&&t==="fixed")&&(c=o.offsetLeft,l=o.offsetTop)}const d=Vs(s);if(d<=0){const m=s.ownerDocument,u=m.body,p=getComputedStyle(u),h=m.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,_=Math.abs(s.clientWidth-u.clientWidth-h);_<=Xc&&(a-=_)}else d<=Xc&&(a+=d);return{width:a,height:i,x:c,y:l}}const u_=new Set(["absolute","fixed"]);function m_(e,t){const r=Tn(e,!0,t==="fixed"),s=r.top+e.clientTop,o=r.left+e.clientLeft,a=Qt(e)?Xn(e):Ht(1),i=e.clientWidth*a.x,c=e.clientHeight*a.y,l=o*a.x,d=s*a.y;return{width:i,height:c,x:l,y:d}}function Jc(e,t,r){let s;if(t==="viewport")s=d_(e,r);else if(t==="document")s=l_(Kt(e));else if(Ot(t))s=m_(t,r);else{const o=vu(e);s={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ks(s)}function _u(e,t){const r=fn(e);return r===t||!Ot(r)||er(r)?!1:Mt(r).position==="fixed"||_u(r,t)}function p_(e,t){const r=t.get(e);if(r)return r;let s=Rr(e,[],!1).filter(c=>Ot(c)&&dr(c)!=="body"),o=null;const a=Mt(e).position==="fixed";let i=a?fn(e):e;for(;Ot(i)&&!er(i);){const c=Mt(i),l=ni(i);!l&&c.position==="fixed"&&(o=null),(a?!l&&!o:!l&&c.position==="static"&&!!o&&u_.has(o.position)||zr(i)&&!l&&_u(e,i))?s=s.filter(m=>m!==i):o=c,i=fn(i)}return t.set(e,s),s}function f_(e){let{element:t,boundary:r,rootBoundary:s,strategy:o}=e;const i=[...r==="clippingAncestors"?Us(t)?[]:p_(t,this._c):[].concat(r),s],c=i[0],l=i.reduce((d,m)=>{const u=Jc(t,m,o);return d.top=wt(u.top,d.top),d.right=pn(u.right,d.right),d.bottom=pn(u.bottom,d.bottom),d.left=wt(u.left,d.left),d},Jc(t,c,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function h_(e){const{width:t,height:r}=bu(e);return{width:t,height:r}}function g_(e,t,r){const s=Qt(t),o=Kt(t),a=r==="fixed",i=Tn(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=Ht(0);function d(){l.x=Vs(o)}if(s||!s&&!a)if((dr(t)!=="body"||zr(o))&&(c=Ws(t)),s){const h=Tn(t,!0,a,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&d();a&&!s&&o&&d();const m=o&&!s&&!a?wu(o,c):Ht(0),u=i.left+c.scrollLeft-l.x-m.x,p=i.top+c.scrollTop-l.y-m.y;return{x:u,y:p,width:i.width,height:i.height}}function Mo(e){return Mt(e).position==="static"}function el(e,t){if(!Qt(e)||Mt(e).position==="fixed")return null;if(t)return t(e);let r=e.offsetParent;return Kt(e)===r&&(r=r.ownerDocument.body),r}function ju(e,t){const r=_t(e);if(Us(e))return r;if(!Qt(e)){let o=fn(e);for(;o&&!er(o);){if(Ot(o)&&!Mo(o))return o;o=fn(o)}return r}let s=el(e,t);for(;s&&Xw(s)&&Mo(s);)s=el(s,t);return s&&er(s)&&Mo(s)&&!ni(s)?r:s||r_(e)||r}const x_=async function(e){const t=this.getOffsetParent||ju,r=this.getDimensions,s=await r(e.floating);return{reference:g_(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function y_(e){return Mt(e).direction==="rtl"}const b_={convertOffsetParentRelativeRectToViewportRelativeRect:i_,getDocumentElement:Kt,getClippingRect:f_,getOffsetParent:ju,getElementRects:x_,getClientRects:c_,getDimensions:h_,getScale:Xn,isElement:Ot,isRTL:y_};function ku(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function v_(e,t){let r=null,s;const o=Kt(e);function a(){var c;clearTimeout(s),(c=r)==null||c.disconnect(),r=null}function i(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:m,top:u,width:p,height:h}=d;if(c||t(),!p||!h)return;const _=Xr(u),g=Xr(o.clientWidth-(m+p)),f=Xr(o.clientHeight-(u+h)),w=Xr(m),v={rootMargin:-_+"px "+-g+"px "+-f+"px "+-w+"px",threshold:wt(0,pn(1,l))||1};let b=!0;function k(R){const N=R[0].intersectionRatio;if(N!==l){if(!b)return i();N?i(!1,N):s=setTimeout(()=>{i(!1,1e-7)},1e3)}N===1&&!ku(d,e.getBoundingClientRect())&&i(),b=!1}try{r=new IntersectionObserver(k,{...v,root:o.ownerDocument})}catch{r=new IntersectionObserver(k,v)}r.observe(e)}return i(!0),a}function w_(e,t,r,s){s===void 0&&(s={});const{ancestorScroll:o=!0,ancestorResize:a=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=s,d=si(e),m=o||a?[...d?Rr(d):[],...Rr(t)]:[];m.forEach(w=>{o&&w.addEventListener("scroll",r,{passive:!0}),a&&w.addEventListener("resize",r)});const u=d&&c?v_(d,r):null;let p=-1,h=null;i&&(h=new ResizeObserver(w=>{let[j]=w;j&&j.target===d&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var v;(v=h)==null||v.observe(t)})),r()}),d&&!l&&h.observe(d),h.observe(t));let _,g=l?Tn(e):null;l&&f();function f(){const w=Tn(e);g&&!ku(g,w)&&r(),g=w,_=requestAnimationFrame(f)}return r(),()=>{var w;m.forEach(j=>{o&&j.removeEventListener("scroll",r),a&&j.removeEventListener("resize",r)}),u?.(),(w=h)==null||w.disconnect(),h=null,l&&cancelAnimationFrame(_)}}const __=Hw,j_=Zw,k_=Ww,S_=Qw,C_=Vw,tl=Uw,N_=Gw,P_=(e,t,r)=>{const s=new Map,o={platform:b_,...r},a={...o.platform,_c:s};return Bw(e,t,{...o,platform:a})};var A_=typeof document<"u",E_=function(){},ls=A_?y.useLayoutEffect:E_;function Ss(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let r,s,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(s=r;s--!==0;)if(!Ss(e[s],t[s]))return!1;return!0}if(o=Object.keys(e),r=o.length,r!==Object.keys(t).length)return!1;for(s=r;s--!==0;)if(!{}.hasOwnProperty.call(t,o[s]))return!1;for(s=r;s--!==0;){const a=o[s];if(!(a==="_owner"&&e.$$typeof)&&!Ss(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function Su(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function nl(e,t){const r=Su(e);return Math.round(t*r)/r}function Do(e){const t=x.useRef(e);return ls(()=>{t.current=e}),t}function T_(e){e===void 0&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:s=[],platform:o,elements:{reference:a,floating:i}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[m,u]=x.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=x.useState(s);Ss(p,s)||h(s);const[_,g]=x.useState(null),[f,w]=x.useState(null),j=x.useCallback(P=>{P!==R.current&&(R.current=P,g(P))},[]),v=x.useCallback(P=>{P!==N.current&&(N.current=P,w(P))},[]),b=a||_,k=i||f,R=x.useRef(null),N=x.useRef(null),C=x.useRef(m),T=l!=null,O=Do(l),$=Do(o),S=Do(d),A=x.useCallback(()=>{if(!R.current||!N.current)return;const P={placement:t,strategy:r,middleware:p};$.current&&(P.platform=$.current),P_(R.current,N.current,P).then(z=>{const Z={...z,isPositioned:S.current!==!1};I.current&&!Ss(C.current,Z)&&(C.current=Z,Is.flushSync(()=>{u(Z)}))})},[p,t,r,$,S]);ls(()=>{d===!1&&C.current.isPositioned&&(C.current.isPositioned=!1,u(P=>({...P,isPositioned:!1})))},[d]);const I=x.useRef(!1);ls(()=>(I.current=!0,()=>{I.current=!1}),[]),ls(()=>{if(b&&(R.current=b),k&&(N.current=k),b&&k){if(O.current)return O.current(b,k,A);A()}},[b,k,A,O,T]);const B=x.useMemo(()=>({reference:R,floating:N,setReference:j,setFloating:v}),[j,v]),D=x.useMemo(()=>({reference:b,floating:k}),[b,k]),E=x.useMemo(()=>{const P={position:r,left:0,top:0};if(!D.floating)return P;const z=nl(D.floating,m.x),Z=nl(D.floating,m.y);return c?{...P,transform:"translate("+z+"px, "+Z+"px)",...Su(D.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:z,top:Z}},[r,c,D.floating,m.x,m.y]);return x.useMemo(()=>({...m,update:A,refs:B,elements:D,floatingStyles:E}),[m,A,B,D,E])}const I_=e=>{function t(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:e,fn(r){const{element:s,padding:o}=typeof e=="function"?e(r):e;return s&&t(s)?s.current!=null?tl({element:s.current,padding:o}).fn(r):{}:s?tl({element:s,padding:o}).fn(r):{}}}},R_=(e,t)=>({...__(e),options:[e,t]}),O_=(e,t)=>({...j_(e),options:[e,t]}),M_=(e,t)=>({...N_(e),options:[e,t]}),D_=(e,t)=>({...k_(e),options:[e,t]}),L_=(e,t)=>({...S_(e),options:[e,t]}),$_=(e,t)=>({...C_(e),options:[e,t]}),z_=(e,t)=>({...I_(e),options:[e,t]});var F_="Arrow",Cu=x.forwardRef((e,t)=>{const{children:r,width:s=10,height:o=5,...a}=e;return n.jsx(ve.svg,{...a,ref:t,width:s,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:n.jsx("polygon",{points:"0,0 30,0 15,10"})})});Cu.displayName=F_;var B_=Cu;function U_(e){const[t,r]=x.useState(void 0);return Xe(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const s=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const a=o[0];let i,c;if("borderBoxSize"in a){const l=a.borderBoxSize,d=Array.isArray(l)?l[0]:l;i=d.inlineSize,c=d.blockSize}else i=e.offsetWidth,c=e.offsetHeight;r({width:i,height:c})});return s.observe(e,{box:"border-box"}),()=>s.unobserve(e)}else r(void 0)},[e]),t}var oi="Popper",[Nu,Pu]=vn(oi),[W_,Au]=Nu(oi),Eu=e=>{const{__scopePopper:t,children:r}=e,[s,o]=x.useState(null);return n.jsx(W_,{scope:t,anchor:s,onAnchorChange:o,children:r})};Eu.displayName=oi;var Tu="PopperAnchor",Iu=x.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:s,...o}=e,a=Au(Tu,r),i=x.useRef(null),c=Ee(t,i),l=x.useRef(null);return x.useEffect(()=>{const d=l.current;l.current=s?.current||i.current,d!==l.current&&a.onAnchorChange(l.current)}),s?null:n.jsx(ve.div,{...o,ref:c})});Iu.displayName=Tu;var ai="PopperContent",[V_,q_]=Nu(ai),Ru=x.forwardRef((e,t)=>{const{__scopePopper:r,side:s="bottom",sideOffset:o=0,align:a="center",alignOffset:i=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:m=0,sticky:u="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:_,...g}=e,f=Au(ai,r),[w,j]=x.useState(null),v=Ee(t,F=>j(F)),[b,k]=x.useState(null),R=U_(b),N=R?.width??0,C=R?.height??0,T=s+(a!=="center"?"-"+a:""),O=typeof m=="number"?m:{top:0,right:0,bottom:0,left:0,...m},$=Array.isArray(d)?d:[d],S=$.length>0,A={padding:O,boundary:$.filter(Z_),altBoundary:S},{refs:I,floatingStyles:B,placement:D,isPositioned:E,middlewareData:P}=T_({strategy:"fixed",placement:T,whileElementsMounted:(...F)=>w_(...F,{animationFrame:h==="always"}),elements:{reference:f.anchor},middleware:[R_({mainAxis:o+C,alignmentAxis:i}),l&&O_({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?M_():void 0,...A}),l&&D_({...A}),L_({...A,apply:({elements:F,rects:ee,availableWidth:pe,availableHeight:q})=>{const{width:ne,height:le}=ee.reference,fe=F.floating.style;fe.setProperty("--radix-popper-available-width",`${pe}px`),fe.setProperty("--radix-popper-available-height",`${q}px`),fe.setProperty("--radix-popper-anchor-width",`${ne}px`),fe.setProperty("--radix-popper-anchor-height",`${le}px`)}}),b&&z_({element:b,padding:c}),G_({arrowWidth:N,arrowHeight:C}),p&&$_({strategy:"referenceHidden",...A})]}),[z,Z]=Du(D),K=mn(_);Xe(()=>{E&&K?.()},[E,K]);const L=P.arrow?.x,W=P.arrow?.y,Y=P.arrow?.centerOffset!==0,[V,ce]=x.useState();return Xe(()=>{w&&ce(window.getComputedStyle(w).zIndex)},[w]),n.jsx("div",{ref:I.setFloating,"data-radix-popper-content-wrapper":"",style:{...B,transform:E?B.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:V,"--radix-popper-transform-origin":[P.transformOrigin?.x,P.transformOrigin?.y].join(" "),...P.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:n.jsx(V_,{scope:r,placedSide:z,onArrowChange:k,arrowX:L,arrowY:W,shouldHideArrow:Y,children:n.jsx(ve.div,{"data-side":z,"data-align":Z,...g,ref:v,style:{...g.style,animation:E?void 0:"none"}})})})});Ru.displayName=ai;var Ou="PopperArrow",H_={top:"bottom",right:"left",bottom:"top",left:"right"},Mu=x.forwardRef(function(t,r){const{__scopePopper:s,...o}=t,a=q_(Ou,s),i=H_[a.placedSide];return n.jsx("span",{ref:a.onArrowChange,style:{position:"absolute",left:a.arrowX,top:a.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[a.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[a.placedSide],visibility:a.shouldHideArrow?"hidden":void 0},children:n.jsx(B_,{...o,ref:r,style:{...o.style,display:"block"}})})});Mu.displayName=Ou;function Z_(e){return e!==null}var G_=e=>({name:"transformOrigin",options:e,fn(t){const{placement:r,rects:s,middlewareData:o}=t,i=o.arrow?.centerOffset!==0,c=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[d,m]=Du(r),u={start:"0%",center:"50%",end:"100%"}[m],p=(o.arrow?.x??0)+c/2,h=(o.arrow?.y??0)+l/2;let _="",g="";return d==="bottom"?(_=i?u:`${p}px`,g=`${-l}px`):d==="top"?(_=i?u:`${p}px`,g=`${s.floating.height+l}px`):d==="right"?(_=`${-l}px`,g=i?u:`${h}px`):d==="left"&&(_=`${s.floating.width+l}px`,g=i?u:`${h}px`),{data:{x:_,y:g}}}});function Du(e){const[t,r="center"]=e.split("-");return[t,r]}var Q_=Eu,Y_=Iu,K_=Ru,X_=Mu,J_="Portal",ii=x.forwardRef((e,t)=>{const{container:r,...s}=e,[o,a]=x.useState(!1);Xe(()=>a(!0),[]);const i=r||o&&globalThis?.document?.body;return i?ka.createPortal(n.jsx(ve.div,{...s,ref:t}),i):null});ii.displayName=J_;function ej(e){const t=tj(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(rj);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function tj(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=oj(o),c=sj(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var nj=Symbol("radix.slottable");function rj(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===nj}function sj(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function oj(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var aj=x[" useInsertionEffect ".trim().toString()]||Xe;function hn({prop:e,defaultProp:t,onChange:r=()=>{},caller:s}){const[o,a,i]=ij({defaultProp:t,onChange:r}),c=e!==void 0,l=c?e:o;{const m=x.useRef(e!==void 0);x.useEffect(()=>{const u=m.current;u!==c&&console.warn(`${s} is changing from ${u?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),m.current=c},[c,s])}const d=x.useCallback(m=>{if(c){const u=cj(m)?m(e):m;u!==e&&i.current?.(u)}else a(m)},[c,e,a,i]);return[l,d]}function ij({defaultProp:e,onChange:t}){const[r,s]=x.useState(e),o=x.useRef(r),a=x.useRef(t);return aj(()=>{a.current=t},[t]),x.useEffect(()=>{o.current!==r&&(a.current?.(r),o.current=r)},[r,o]),[r,s,a]}function cj(e){return typeof e=="function"}function lj(e){const t=x.useRef({value:e,previous:e});return x.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Lu=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),dj="VisuallyHidden",uj=x.forwardRef((e,t)=>n.jsx(ve.span,{...e,ref:t,style:{...Lu,...e.style}}));uj.displayName=dj;var mj=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Zn=new WeakMap,Jr=new WeakMap,es={},Lo=0,$u=function(e){return e&&(e.host||$u(e.parentNode))},pj=function(e,t){return t.map(function(r){if(e.contains(r))return r;var s=$u(r);return s&&e.contains(s)?s:(console.error("aria-hidden",r,"in not contained inside",e,". Doing nothing"),null)}).filter(function(r){return!!r})},fj=function(e,t,r,s){var o=pj(t,Array.isArray(e)?e:[e]);es[r]||(es[r]=new WeakMap);var a=es[r],i=[],c=new Set,l=new Set(o),d=function(u){!u||c.has(u)||(c.add(u),d(u.parentNode))};o.forEach(d);var m=function(u){!u||l.has(u)||Array.prototype.forEach.call(u.children,function(p){if(c.has(p))m(p);else try{var h=p.getAttribute(s),_=h!==null&&h!=="false",g=(Zn.get(p)||0)+1,f=(a.get(p)||0)+1;Zn.set(p,g),a.set(p,f),i.push(p),g===1&&_&&Jr.set(p,!0),f===1&&p.setAttribute(r,"true"),_||p.setAttribute(s,"true")}catch(w){console.error("aria-hidden: cannot operate on ",p,w)}})};return m(t),c.clear(),Lo++,function(){i.forEach(function(u){var p=Zn.get(u)-1,h=a.get(u)-1;Zn.set(u,p),a.set(u,h),p||(Jr.has(u)||u.removeAttribute(s),Jr.delete(u)),h||u.removeAttribute(r)}),Lo--,Lo||(Zn=new WeakMap,Zn=new WeakMap,Jr=new WeakMap,es={})}},zu=function(e,t,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(e)?e:[e]),o=mj(e);return o?(s.push.apply(s,Array.from(o.querySelectorAll("[aria-live], script"))),fj(s,o,r,"aria-hidden")):function(){return null}},Wt=function(){return Wt=Object.assign||function(t){for(var r,s=1,o=arguments.length;s<o;s++){r=arguments[s];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])}return t},Wt.apply(this,arguments)};function Fu(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,s=Object.getOwnPropertySymbols(e);o<s.length;o++)t.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(e,s[o])&&(r[s[o]]=e[s[o]]);return r}function hj(e,t,r){if(r||arguments.length===2)for(var s=0,o=t.length,a;s<o;s++)(a||!(s in t))&&(a||(a=Array.prototype.slice.call(t,0,s)),a[s]=t[s]);return e.concat(a||Array.prototype.slice.call(t))}var ds="right-scroll-bar-position",us="width-before-scroll-bar",gj="with-scroll-bars-hidden",xj="--removed-body-scroll-bar-size";function $o(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function yj(e,t){var r=y.useState(function(){return{value:e,callback:t,facade:{get current(){return r.value},set current(s){var o=r.value;o!==s&&(r.value=s,r.callback(s,o))}}}})[0];return r.callback=t,r.facade}var bj=typeof window<"u"?x.useLayoutEffect:x.useEffect,rl=new WeakMap;function vj(e,t){var r=yj(null,function(s){return e.forEach(function(o){return $o(o,s)})});return bj(function(){var s=rl.get(r);if(s){var o=new Set(s),a=new Set(e),i=r.current;o.forEach(function(c){a.has(c)||$o(c,null)}),a.forEach(function(c){o.has(c)||$o(c,i)})}rl.set(r,e)},[e]),r}function wj(e){return e}function _j(e,t){t===void 0&&(t=wj);var r=[],s=!1,o={read:function(){if(s)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(a){var i=t(a,s);return r.push(i),function(){r=r.filter(function(c){return c!==i})}},assignSyncMedium:function(a){for(s=!0;r.length;){var i=r;r=[],i.forEach(a)}r={push:function(c){return a(c)},filter:function(){return r}}},assignMedium:function(a){s=!0;var i=[];if(r.length){var c=r;r=[],c.forEach(a),i=r}var l=function(){var m=i;i=[],m.forEach(a)},d=function(){return Promise.resolve().then(l)};d(),r={push:function(m){i.push(m),d()},filter:function(m){return i=i.filter(m),r}}}};return o}function jj(e){e===void 0&&(e={});var t=_j(null);return t.options=Wt({async:!0,ssr:!1},e),t}var Bu=function(e){var t=e.sideCar,r=Fu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var s=t.read();if(!s)throw new Error("Sidecar medium not found");return x.createElement(s,Wt({},r))};Bu.isSideCarExport=!0;function kj(e,t){return e.useMedium(t),Bu}var Uu=jj(),zo=function(){},qs=x.forwardRef(function(e,t){var r=x.useRef(null),s=x.useState({onScrollCapture:zo,onWheelCapture:zo,onTouchMoveCapture:zo}),o=s[0],a=s[1],i=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,m=e.enabled,u=e.shards,p=e.sideCar,h=e.noRelative,_=e.noIsolation,g=e.inert,f=e.allowPinchZoom,w=e.as,j=w===void 0?"div":w,v=e.gapMode,b=Fu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=p,R=vj([r,t]),N=Wt(Wt({},b),o);return x.createElement(x.Fragment,null,m&&x.createElement(k,{sideCar:Uu,removeScrollBar:d,shards:u,noRelative:h,noIsolation:_,inert:g,setCallbacks:a,allowPinchZoom:!!f,lockRef:r,gapMode:v}),i?x.cloneElement(x.Children.only(c),Wt(Wt({},N),{ref:R})):x.createElement(j,Wt({},N,{className:l,ref:R}),c))});qs.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};qs.classNames={fullWidth:us,zeroRight:ds};var Sj=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Cj(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Sj();return t&&e.setAttribute("nonce",t),e}function Nj(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Pj(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Aj=function(){var e=0,t=null;return{add:function(r){e==0&&(t=Cj())&&(Nj(t,r),Pj(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ej=function(){var e=Aj();return function(t,r){x.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])}},Wu=function(){var e=Ej(),t=function(r){var s=r.styles,o=r.dynamic;return e(s,o),null};return t},Tj={left:0,top:0,right:0,gap:0},Fo=function(e){return parseInt(e||"",10)||0},Ij=function(e){var t=window.getComputedStyle(document.body),r=t[e==="padding"?"paddingLeft":"marginLeft"],s=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Fo(r),Fo(s),Fo(o)]},Rj=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Tj;var t=Ij(e),r=document.documentElement.clientWidth,s=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,s-r+t[2]-t[0])}},Oj=Wu(),Jn="data-scroll-locked",Mj=function(e,t,r,s){var o=e.left,a=e.top,i=e.right,c=e.gap;return r===void 0&&(r="margin"),`
|
|
92
92
|
.`.concat(gj,` {
|
|
93
93
|
overflow: hidden `).concat(s,`;
|
|
94
94
|
padding-right: `).concat(c,"px ").concat(s,`;
|
|
@@ -128,9 +128,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
128
128
|
`)},sl=function(){var e=parseInt(document.body.getAttribute(Jn)||"0",10);return isFinite(e)?e:0},Dj=function(){x.useEffect(function(){return document.body.setAttribute(Jn,(sl()+1).toString()),function(){var e=sl()-1;e<=0?document.body.removeAttribute(Jn):document.body.setAttribute(Jn,e.toString())}},[])},Lj=function(e){var t=e.noRelative,r=e.noImportant,s=e.gapMode,o=s===void 0?"margin":s;Dj();var a=x.useMemo(function(){return Rj(o)},[o]);return x.createElement(Oj,{styles:Mj(a,!t,o,r?"":"!important")})},la=!1;if(typeof window<"u")try{var ts=Object.defineProperty({},"passive",{get:function(){return la=!0,!0}});window.addEventListener("test",ts,ts),window.removeEventListener("test",ts,ts)}catch{la=!1}var Gn=la?{passive:!1}:!1,$j=function(e){return e.tagName==="TEXTAREA"},Vu=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!$j(e)&&r[t]==="visible")},zj=function(e){return Vu(e,"overflowY")},Fj=function(e){return Vu(e,"overflowX")},ol=function(e,t){var r=t.ownerDocument,s=t;do{typeof ShadowRoot<"u"&&s instanceof ShadowRoot&&(s=s.host);var o=qu(e,s);if(o){var a=Hu(e,s),i=a[1],c=a[2];if(i>c)return!0}s=s.parentNode}while(s&&s!==r.body);return!1},Bj=function(e){var t=e.scrollTop,r=e.scrollHeight,s=e.clientHeight;return[t,r,s]},Uj=function(e){var t=e.scrollLeft,r=e.scrollWidth,s=e.clientWidth;return[t,r,s]},qu=function(e,t){return e==="v"?zj(t):Fj(t)},Hu=function(e,t){return e==="v"?Bj(t):Uj(t)},Wj=function(e,t){return e==="h"&&t==="rtl"?-1:1},Vj=function(e,t,r,s,o){var a=Wj(e,window.getComputedStyle(t).direction),i=a*s,c=r.target,l=t.contains(c),d=!1,m=i>0,u=0,p=0;do{if(!c)break;var h=Hu(e,c),_=h[0],g=h[1],f=h[2],w=g-f-a*_;(_||w)&&qu(e,c)&&(u+=w,p+=_);var j=c.parentNode;c=j&&j.nodeType===Node.DOCUMENT_FRAGMENT_NODE?j.host:j}while(!l&&c!==document.body||l&&(t.contains(c)||t===c));return(m&&Math.abs(u)<1||!m&&Math.abs(p)<1)&&(d=!0),d},ns=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},al=function(e){return[e.deltaX,e.deltaY]},il=function(e){return e&&"current"in e?e.current:e},qj=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Hj=function(e){return`
|
|
129
129
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
130
130
|
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
131
|
-
`)},Zj=0,Qn=[];function Gj(e){var t=x.useRef([]),r=x.useRef([0,0]),s=x.useRef(),o=x.useState(Zj++)[0],a=x.useState(Wu)[0],i=x.useRef(e);x.useEffect(function(){i.current=e},[e]),x.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var g=hj([e.lockRef.current],(e.shards||[]).map(il),!0).filter(Boolean);return g.forEach(function(f){return f.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),g.forEach(function(f){return f.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var c=x.useCallback(function(g,f){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!i.current.allowPinchZoom;var w=ns(g),j=r.current,b="deltaX"in g?g.deltaX:j[0]-w[0],v="deltaY"in g?g.deltaY:j[1]-w[1],k,R=g.target,N=Math.abs(b)>Math.abs(v)?"h":"v";if("touches"in g&&N==="h"&&R.type==="range")return!1;var C=window.getSelection(),T=C&&C.anchorNode,O=T?T===R||T.contains(R):!1;if(O)return!1;var $=ol(N,R);if(!$)return!0;if($?k=N:(k=N==="v"?"h":"v",$=ol(N,R)),!$)return!1;if(!s.current&&"changedTouches"in g&&(b||v)&&(s.current=k),!k)return!0;var S=s.current||k;return Vj(S,f,g,S==="h"?b:v)},[]),l=x.useCallback(function(g){var f=g;if(!(!Qn.length||Qn[Qn.length-1]!==a)){var w="deltaY"in f?al(f):ns(f),j=t.current.filter(function(k){return k.name===f.type&&(k.target===f.target||f.target===k.shadowParent)&&qj(k.delta,w)})[0];if(j&&j.should){f.cancelable&&f.preventDefault();return}if(!j){var b=(i.current.shards||[]).map(il).filter(Boolean).filter(function(k){return k.contains(f.target)}),v=b.length>0?c(f,b[0]):!i.current.noIsolation;v&&f.cancelable&&f.preventDefault()}}},[]),d=x.useCallback(function(g,f,w,j){var b={name:g,delta:f,target:w,should:j,shadowParent:Qj(w)};t.current.push(b),setTimeout(function(){t.current=t.current.filter(function(v){return v!==b})},1)},[]),m=x.useCallback(function(g){r.current=ns(g),s.current=void 0},[]),u=x.useCallback(function(g){d(g.type,al(g),g.target,c(g,e.lockRef.current))},[]),p=x.useCallback(function(g){d(g.type,ns(g),g.target,c(g,e.lockRef.current))},[]);x.useEffect(function(){return Qn.push(a),e.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:p}),document.addEventListener("wheel",l,Gn),document.addEventListener("touchmove",l,Gn),document.addEventListener("touchstart",m,Gn),function(){Qn=Qn.filter(function(g){return g!==a}),document.removeEventListener("wheel",l,Gn),document.removeEventListener("touchmove",l,Gn),document.removeEventListener("touchstart",m,Gn)}},[]);var h=e.removeScrollBar,_=e.inert;return x.createElement(x.Fragment,null,_?x.createElement(a,{styles:Hj(o)}):null,h?x.createElement(Lj,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Qj(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Yj=kj(Uu,Gj);var ci=x.forwardRef(function(e,t){return x.createElement(qs,Wt({},e,{ref:t,sideCar:Yj}))});ci.classNames=qs.classNames;var Kj=[" ","Enter","ArrowUp","ArrowDown"],Xj=[" ","Enter"],In="Select",[Hs,Zs,Jj]=Ya(In),[ur]=bn(In,[Jj,Pu]),Gs=Pu(),[ek,wn]=ur(In),[tk,nk]=ur(In),Zu=e=>{const{__scopeSelect:t,children:r,open:s,defaultOpen:o,onOpenChange:a,value:i,defaultValue:c,onValueChange:l,dir:d,name:m,autoComplete:u,disabled:p,required:h,form:_}=e,g=Gs(t),[f,w]=x.useState(null),[j,b]=x.useState(null),[v,k]=x.useState(!1),R=Fs(d),[N,C]=hn({prop:s,defaultProp:o??!1,onChange:a,caller:In}),[T,O]=hn({prop:i,defaultProp:c,onChange:l,caller:In}),$=x.useRef(null),S=f?_||!!f.closest("form"):!0,[A,I]=x.useState(new Set),B=Array.from(A).map(D=>D.props.value).join(";");return n.jsx(Q_,{...g,children:n.jsxs(ek,{required:h,scope:t,trigger:f,onTriggerChange:w,valueNode:j,onValueNodeChange:b,valueNodeHasChildren:v,onValueNodeHasChildrenChange:k,contentId:qt(),value:T,onValueChange:O,open:N,onOpenChange:C,dir:R,triggerPointerDownPosRef:$,disabled:p,children:[n.jsx(Hs.Provider,{scope:t,children:n.jsx(tk,{scope:e.__scopeSelect,onNativeOptionAdd:x.useCallback(D=>{I(E=>new Set(E).add(D))},[]),onNativeOptionRemove:x.useCallback(D=>{I(E=>{const P=new Set(E);return P.delete(D),P})},[]),children:r})}),S?n.jsxs(pm,{"aria-hidden":!0,required:h,tabIndex:-1,name:m,autoComplete:u,value:T,onChange:D=>O(D.target.value),disabled:p,form:_,children:[T===void 0?n.jsx("option",{value:""}):null,Array.from(A)]},B):null]})})};Zu.displayName=In;var Gu="SelectTrigger",Qu=x.forwardRef((e,t)=>{const{__scopeSelect:r,disabled:s=!1,...o}=e,a=Gs(r),i=wn(Gu,r),c=i.disabled||s,l=Ee(t,i.onTriggerChange),d=Zs(r),m=x.useRef("touch"),[u,p,h]=hm(g=>{const f=d().filter(b=>!b.disabled),w=f.find(b=>b.value===i.value),j=gm(f,g,w);j!==void 0&&i.onValueChange(j.value)}),_=g=>{c||(i.onOpenChange(!0),h()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return n.jsx(Y_,{asChild:!0,...a,children:n.jsx(be.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":fm(i.value)?"":void 0,...o,ref:l,onClick:_e(o.onClick,g=>{g.currentTarget.focus(),m.current!=="mouse"&&_(g)}),onPointerDown:_e(o.onPointerDown,g=>{m.current=g.pointerType;const f=g.target;f.hasPointerCapture(g.pointerId)&&f.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(_(g),g.preventDefault())}),onKeyDown:_e(o.onKeyDown,g=>{const f=u.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&p(g.key),!(f&&g.key===" ")&&Kj.includes(g.key)&&(_(),g.preventDefault())})})})});Qu.displayName=Gu;var Yu="SelectValue",Ku=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,children:a,placeholder:i="",...c}=e,l=wn(Yu,r),{onValueNodeHasChildrenChange:d}=l,m=a!==void 0,u=Ee(t,l.onValueNodeChange);return Xe(()=>{d(m)},[d,m]),n.jsx(be.span,{...c,ref:u,style:{pointerEvents:"none"},children:fm(l.value)?n.jsx(n.Fragment,{children:i}):a})});Ku.displayName=Yu;var rk="SelectIcon",Xu=x.forwardRef((e,t)=>{const{__scopeSelect:r,children:s,...o}=e;return n.jsx(be.span,{"aria-hidden":!0,...o,ref:t,children:s||"▼"})});Xu.displayName=rk;var sk="SelectPortal",Ju=e=>n.jsx(ii,{asChild:!0,...e});Ju.displayName=sk;var Rn="SelectContent",em=x.forwardRef((e,t)=>{const r=wn(Rn,e.__scopeSelect),[s,o]=x.useState();if(Xe(()=>{o(new DocumentFragment)},[]),!r.open){const a=s;return a?Is.createPortal(n.jsx(tm,{scope:e.__scopeSelect,children:n.jsx(Hs.Slot,{scope:e.__scopeSelect,children:n.jsx("div",{children:e.children})})}),a):null}return n.jsx(nm,{...e,ref:t})});em.displayName=Rn;var Tt=10,[tm,_n]=ur(Rn),ok="SelectContentImpl",ak=ej("SelectContent.RemoveScroll"),nm=x.forwardRef((e,t)=>{const{__scopeSelect:r,position:s="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:a,onPointerDownOutside:i,side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:p,collisionPadding:h,sticky:_,hideWhenDetached:g,avoidCollisions:f,...w}=e,j=wn(Rn,r),[b,v]=x.useState(null),[k,R]=x.useState(null),N=Ee(t,F=>v(F)),[C,T]=x.useState(null),[O,$]=x.useState(null),S=Zs(r),[A,I]=x.useState(!1),B=x.useRef(!1);x.useEffect(()=>{if(b)return zu(b)},[b]),pu();const D=x.useCallback(F=>{const[ee,...pe]=S().map(le=>le.ref.current),[q]=pe.slice(-1),ne=document.activeElement;for(const le of F)if(le===ne||(le?.scrollIntoView({block:"nearest"}),le===ee&&k&&(k.scrollTop=0),le===q&&k&&(k.scrollTop=k.scrollHeight),le?.focus(),document.activeElement!==ne))return},[S,k]),E=x.useCallback(()=>D([C,b]),[D,C,b]);x.useEffect(()=>{A&&E()},[A,E]);const{onOpenChange:P,triggerPointerDownPosRef:z}=j;x.useEffect(()=>{if(b){let F={x:0,y:0};const ee=q=>{F={x:Math.abs(Math.round(q.pageX)-(z.current?.x??0)),y:Math.abs(Math.round(q.pageY)-(z.current?.y??0))}},pe=q=>{F.x<=10&&F.y<=10?q.preventDefault():b.contains(q.target)||P(!1),document.removeEventListener("pointermove",ee),z.current=null};return z.current!==null&&(document.addEventListener("pointermove",ee),document.addEventListener("pointerup",pe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ee),document.removeEventListener("pointerup",pe,{capture:!0})}}},[b,P,z]),x.useEffect(()=>{const F=()=>P(!1);return window.addEventListener("blur",F),window.addEventListener("resize",F),()=>{window.removeEventListener("blur",F),window.removeEventListener("resize",F)}},[P]);const[Z,K]=hm(F=>{const ee=S().filter(ne=>!ne.disabled),pe=ee.find(ne=>ne.ref.current===document.activeElement),q=gm(ee,F,pe);q&&setTimeout(()=>q.ref.current.focus())}),L=x.useCallback((F,ee,pe)=>{const q=!B.current&&!pe;(j.value!==void 0&&j.value===ee||q)&&(T(F),q&&(B.current=!0))},[j.value]),W=x.useCallback(()=>b?.focus(),[b]),Y=x.useCallback((F,ee,pe)=>{const q=!B.current&&!pe;(j.value!==void 0&&j.value===ee||q)&&$(F)},[j.value]),V=s==="popper"?da:rm,ce=V===da?{side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:p,collisionPadding:h,sticky:_,hideWhenDetached:g,avoidCollisions:f}:{};return n.jsx(tm,{scope:r,content:b,viewport:k,onViewportChange:R,itemRefCallback:L,selectedItem:C,onItemLeave:W,itemTextRefCallback:Y,focusSelectedItem:E,selectedItemText:O,position:s,isPositioned:A,searchRef:Z,children:n.jsx(ci,{as:ak,allowPinchZoom:!0,children:n.jsx(Xa,{asChild:!0,trapped:j.open,onMountAutoFocus:F=>{F.preventDefault()},onUnmountAutoFocus:_e(o,F=>{j.trigger?.focus({preventScroll:!0}),F.preventDefault()}),children:n.jsx(Ka,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:F=>F.preventDefault(),onDismiss:()=>j.onOpenChange(!1),children:n.jsx(V,{role:"listbox",id:j.contentId,"data-state":j.open?"open":"closed",dir:j.dir,onContextMenu:F=>F.preventDefault(),...w,...ce,onPlaced:()=>I(!0),ref:N,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:_e(w.onKeyDown,F=>{const ee=F.ctrlKey||F.altKey||F.metaKey;if(F.key==="Tab"&&F.preventDefault(),!ee&&F.key.length===1&&K(F.key),["ArrowUp","ArrowDown","Home","End"].includes(F.key)){let q=S().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);if(["ArrowUp","End"].includes(F.key)&&(q=q.slice().reverse()),["ArrowUp","ArrowDown"].includes(F.key)){const ne=F.target,le=q.indexOf(ne);q=q.slice(le+1)}setTimeout(()=>D(q)),F.preventDefault()}})})})})})})});nm.displayName=ok;var ik="SelectItemAlignedPosition",rm=x.forwardRef((e,t)=>{const{__scopeSelect:r,onPlaced:s,...o}=e,a=wn(Rn,r),i=_n(Rn,r),[c,l]=x.useState(null),[d,m]=x.useState(null),u=Ee(t,N=>m(N)),p=Zs(r),h=x.useRef(!1),_=x.useRef(!0),{viewport:g,selectedItem:f,selectedItemText:w,focusSelectedItem:j}=i,b=x.useCallback(()=>{if(a.trigger&&a.valueNode&&c&&d&&g&&f&&w){const N=a.trigger.getBoundingClientRect(),C=d.getBoundingClientRect(),T=a.valueNode.getBoundingClientRect(),O=w.getBoundingClientRect();if(a.dir!=="rtl"){const ne=O.left-C.left,le=T.left-ne,fe=N.left-le,Pe=N.width+fe,Ve=Math.max(Pe,C.width),qe=window.innerWidth-Tt,He=Lc(le,[Tt,Math.max(Tt,qe-Ve)]);c.style.minWidth=Pe+"px",c.style.left=He+"px"}else{const ne=C.right-O.right,le=window.innerWidth-T.right-ne,fe=window.innerWidth-N.right-le,Pe=N.width+fe,Ve=Math.max(Pe,C.width),qe=window.innerWidth-Tt,He=Lc(le,[Tt,Math.max(Tt,qe-Ve)]);c.style.minWidth=Pe+"px",c.style.right=He+"px"}const $=p(),S=window.innerHeight-Tt*2,A=g.scrollHeight,I=window.getComputedStyle(d),B=parseInt(I.borderTopWidth,10),D=parseInt(I.paddingTop,10),E=parseInt(I.borderBottomWidth,10),P=parseInt(I.paddingBottom,10),z=B+D+A+P+E,Z=Math.min(f.offsetHeight*5,z),K=window.getComputedStyle(g),L=parseInt(K.paddingTop,10),W=parseInt(K.paddingBottom,10),Y=N.top+N.height/2-Tt,V=S-Y,ce=f.offsetHeight/2,F=f.offsetTop+ce,ee=B+D+F,pe=z-ee;if(ee<=Y){const ne=$.length>0&&f===$[$.length-1].ref.current;c.style.bottom="0px";const le=d.clientHeight-g.offsetTop-g.offsetHeight,fe=Math.max(V,ce+(ne?W:0)+le+E),Pe=ee+fe;c.style.height=Pe+"px"}else{const ne=$.length>0&&f===$[0].ref.current;c.style.top="0px";const fe=Math.max(Y,B+g.offsetTop+(ne?L:0)+ce)+pe;c.style.height=fe+"px",g.scrollTop=ee-Y+g.offsetTop}c.style.margin=`${Tt}px 0`,c.style.minHeight=Z+"px",c.style.maxHeight=S+"px",s?.(),requestAnimationFrame(()=>h.current=!0)}},[p,a.trigger,a.valueNode,c,d,g,f,w,a.dir,s]);Xe(()=>b(),[b]);const[v,k]=x.useState();Xe(()=>{d&&k(window.getComputedStyle(d).zIndex)},[d]);const R=x.useCallback(N=>{N&&_.current===!0&&(b(),j?.(),_.current=!1)},[b,j]);return n.jsx(lk,{scope:r,contentWrapper:c,shouldExpandOnScrollRef:h,onScrollButtonChange:R,children:n.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:v},children:n.jsx(be.div,{...o,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});rm.displayName=ik;var ck="SelectPopperPosition",da=x.forwardRef((e,t)=>{const{__scopeSelect:r,align:s="start",collisionPadding:o=Tt,...a}=e,i=Gs(r);return n.jsx(K_,{...i,...a,ref:t,align:s,collisionPadding:o,style:{boxSizing:"border-box",...a.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});da.displayName=ck;var[lk,li]=ur(Rn,{}),ua="SelectViewport",sm=x.forwardRef((e,t)=>{const{__scopeSelect:r,nonce:s,...o}=e,a=_n(ua,r),i=li(ua,r),c=Ee(t,a.onViewportChange),l=x.useRef(0);return n.jsxs(n.Fragment,{children:[n.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),n.jsx(Hs.Slot,{scope:r,children:n.jsx(be.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:_e(o.onScroll,d=>{const m=d.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:p}=i;if(p?.current&&u){const h=Math.abs(l.current-m.scrollTop);if(h>0){const _=window.innerHeight-Tt*2,g=parseFloat(u.style.minHeight),f=parseFloat(u.style.height),w=Math.max(g,f);if(w<_){const j=w+h,b=Math.min(_,j),v=j-b;u.style.height=b+"px",u.style.bottom==="0px"&&(m.scrollTop=v>0?v:0,u.style.justifyContent="flex-end")}}}l.current=m.scrollTop})})})]})});sm.displayName=ua;var om="SelectGroup",[dk,uk]=ur(om),am=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=qt();return n.jsx(dk,{scope:r,id:o,children:n.jsx(be.div,{role:"group","aria-labelledby":o,...s,ref:t})})});am.displayName=om;var im="SelectLabel",mk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=uk(im,r);return n.jsx(be.div,{id:o.id,...s,ref:t})});mk.displayName=im;var Cs="SelectItem",[pk,cm]=ur(Cs),lm=x.forwardRef((e,t)=>{const{__scopeSelect:r,value:s,disabled:o=!1,textValue:a,...i}=e,c=wn(Cs,r),l=_n(Cs,r),d=c.value===s,[m,u]=x.useState(a??""),[p,h]=x.useState(!1),_=Ee(t,j=>l.itemRefCallback?.(j,s,o)),g=qt(),f=x.useRef("touch"),w=()=>{o||(c.onValueChange(s),c.onOpenChange(!1))};if(s==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return n.jsx(pk,{scope:r,value:s,disabled:o,textId:g,isSelected:d,onItemTextChange:x.useCallback(j=>{u(b=>b||(j?.textContent??"").trim())},[]),children:n.jsx(Hs.ItemSlot,{scope:r,value:s,disabled:o,textValue:m,children:n.jsx(be.div,{role:"option","aria-labelledby":g,"data-highlighted":p?"":void 0,"aria-selected":d&&p,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:_,onFocus:_e(i.onFocus,()=>h(!0)),onBlur:_e(i.onBlur,()=>h(!1)),onClick:_e(i.onClick,()=>{f.current!=="mouse"&&w()}),onPointerUp:_e(i.onPointerUp,()=>{f.current==="mouse"&&w()}),onPointerDown:_e(i.onPointerDown,j=>{f.current=j.pointerType}),onPointerMove:_e(i.onPointerMove,j=>{f.current=j.pointerType,o?l.onItemLeave?.():f.current==="mouse"&&j.currentTarget.focus({preventScroll:!0})}),onPointerLeave:_e(i.onPointerLeave,j=>{j.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:_e(i.onKeyDown,j=>{l.searchRef?.current!==""&&j.key===" "||(Xj.includes(j.key)&&w(),j.key===" "&&j.preventDefault())})})})})});lm.displayName=Cs;var jr="SelectItemText",dm=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,...a}=e,i=wn(jr,r),c=_n(jr,r),l=cm(jr,r),d=nk(jr,r),[m,u]=x.useState(null),p=Ee(t,w=>u(w),l.onItemTextChange,w=>c.itemTextRefCallback?.(w,l.value,l.disabled)),h=m?.textContent,_=x.useMemo(()=>n.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:g,onNativeOptionRemove:f}=d;return Xe(()=>(g(_),()=>f(_)),[g,f,_]),n.jsxs(n.Fragment,{children:[n.jsx(be.span,{id:l.textId,...a,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Is.createPortal(a.children,i.valueNode):null]})});dm.displayName=jr;var um="SelectItemIndicator",fk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return cm(um,r).isSelected?n.jsx(be.span,{"aria-hidden":!0,...s,ref:t}):null});fk.displayName=um;var ma="SelectScrollUpButton",hk=x.forwardRef((e,t)=>{const r=_n(ma,e.__scopeSelect),s=li(ma,e.__scopeSelect),[o,a]=x.useState(!1),i=Ee(t,s.onScrollButtonChange);return Xe(()=>{if(r.viewport&&r.isPositioned){let c=function(){const d=l.scrollTop>0;a(d)};const l=r.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),o?n.jsx(mm,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});hk.displayName=ma;var pa="SelectScrollDownButton",gk=x.forwardRef((e,t)=>{const r=_n(pa,e.__scopeSelect),s=li(pa,e.__scopeSelect),[o,a]=x.useState(!1),i=Ee(t,s.onScrollButtonChange);return Xe(()=>{if(r.viewport&&r.isPositioned){let c=function(){const d=l.scrollHeight-l.clientHeight,m=Math.ceil(l.scrollTop)<d;a(m)};const l=r.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),o?n.jsx(mm,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});gk.displayName=pa;var mm=x.forwardRef((e,t)=>{const{__scopeSelect:r,onAutoScroll:s,...o}=e,a=_n("SelectScrollButton",r),i=x.useRef(null),c=Zs(r),l=x.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return x.useEffect(()=>()=>l(),[l]),Xe(()=>{c().find(m=>m.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),n.jsx(be.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:_e(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(s,50))}),onPointerMove:_e(o.onPointerMove,()=>{a.onItemLeave?.(),i.current===null&&(i.current=window.setInterval(s,50))}),onPointerLeave:_e(o.onPointerLeave,()=>{l()})})}),xk="SelectSeparator",yk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return n.jsx(be.div,{"aria-hidden":!0,...s,ref:t})});yk.displayName=xk;var fa="SelectArrow",vk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Gs(r),a=wn(fa,r),i=_n(fa,r);return a.open&&i.position==="popper"?n.jsx(X_,{...o,...s,ref:t}):null});vk.displayName=fa;var bk="SelectBubbleInput",pm=x.forwardRef(({__scopeSelect:e,value:t,...r},s)=>{const o=x.useRef(null),a=Ee(s,o),i=lj(t);return x.useEffect(()=>{const c=o.current;if(!c)return;const l=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&m){const u=new Event("change",{bubbles:!0});m.call(c,t),c.dispatchEvent(u)}},[i,t]),n.jsx(be.select,{...r,style:{...Lu,...r.style},ref:a,defaultValue:t})});pm.displayName=bk;function fm(e){return e===""||e===void 0}function hm(e){const t=mn(e),r=x.useRef(""),s=x.useRef(0),o=x.useCallback(i=>{const c=r.current+i;t(c),(function l(d){r.current=d,window.clearTimeout(s.current),d!==""&&(s.current=window.setTimeout(()=>l(""),1e3))})(c)},[t]),a=x.useCallback(()=>{r.current="",window.clearTimeout(s.current)},[]);return x.useEffect(()=>()=>window.clearTimeout(s.current),[]),[r,o,a]}function gm(e,t,r){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,a=r?e.indexOf(r):-1;let i=wk(e,Math.max(a,0));o.length===1&&(i=i.filter(d=>d!==r));const l=i.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==r?l:void 0}function wk(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var _k=Zu,xm=Qu,jk=Ku,kk=Xu,Sk=Ju,ym=em,Ck=sm,Nk=am,vm=lm,Pk=dm;const Ns=_k,Ak=Nk,Ps=jk,Or=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(xm,{ref:s,className:H("flex h-10 w-full items-center justify-between rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:focus-visible:ring-neutral-50/20",e),...r,children:[t,n.jsx(kk,{className:"ml-2 text-neutral-500 dark:text-neutral-400",children:"▾"})]}));Or.displayName=xm.displayName;const Mr=x.forwardRef(({className:e,children:t,position:r="popper",...s},o)=>n.jsx(Sk,{children:n.jsx(ym,{ref:o,position:r,className:H("z-50 min-w-[8rem] overflow-hidden rounded-md border border-neutral-200 bg-white text-neutral-950 shadow-md dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",e),...s,children:n.jsx(Ck,{className:H("p-1",r==="popper"?"w-full":void 0),children:t})})}));Mr.displayName=ym.displayName;const Dr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(vm,{ref:s,className:H("relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-neutral-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-neutral-800",e),...r,children:n.jsx(Pk,{children:t})}));Dr.displayName=vm.displayName;function Ek(e,t){return x.useReducer((r,s)=>t[r][s]??r,e)}var mr=e=>{const{present:t,children:r}=e,s=Tk(t),o=typeof r=="function"?r({present:s.isPresent}):x.Children.only(r),a=Ee(s.ref,Ik(o));return typeof r=="function"||s.isPresent?x.cloneElement(o,{ref:a}):null};mr.displayName="Presence";function Tk(e){const[t,r]=x.useState(),s=x.useRef(null),o=x.useRef(e),a=x.useRef("none"),i=e?"mounted":"unmounted",[c,l]=Ek(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return x.useEffect(()=>{const d=rs(s.current);a.current=c==="mounted"?d:"none"},[c]),Xe(()=>{const d=s.current,m=o.current;if(m!==e){const p=a.current,h=rs(d);e?l("MOUNT"):h==="none"||d?.display==="none"?l("UNMOUNT"):l(m&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Xe(()=>{if(t){let d;const m=t.ownerDocument.defaultView??window,u=h=>{const g=rs(s.current).includes(CSS.escape(h.animationName));if(h.target===t&&g&&(l("ANIMATION_END"),!o.current)){const f=t.style.animationFillMode;t.style.animationFillMode="forwards",d=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=f)})}},p=h=>{h.target===t&&(a.current=rs(s.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{m.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:x.useCallback(d=>{s.current=d?getComputedStyle(d):null,r(d)},[])}}function rs(e){return e?.animationName||"none"}function Ik(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function Rk(e){const t=Ok(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(Dk);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function Ok(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=$k(o),c=Lk(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Mk=Symbol("radix.slottable");function Dk(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Mk}function Lk(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function $k(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Qs="Dialog",[bm]=bn(Qs),[zk,Lt]=bm(Qs),wm=e=>{const{__scopeDialog:t,children:r,open:s,defaultOpen:o,onOpenChange:a,modal:i=!0}=e,c=x.useRef(null),l=x.useRef(null),[d,m]=hn({prop:s,defaultProp:o??!1,onChange:a,caller:Qs});return n.jsx(zk,{scope:t,triggerRef:c,contentRef:l,contentId:qt(),titleId:qt(),descriptionId:qt(),open:d,onOpenChange:m,onOpenToggle:x.useCallback(()=>m(u=>!u),[m]),modal:i,children:r})};wm.displayName=Qs;var _m="DialogTrigger",jm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(_m,r),a=Ee(t,o.triggerRef);return n.jsx(be.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":mi(o.open),...s,ref:a,onClick:_e(e.onClick,o.onOpenToggle)})});jm.displayName=_m;var di="DialogPortal",[Fk,km]=bm(di,{forceMount:void 0}),Sm=e=>{const{__scopeDialog:t,forceMount:r,children:s,container:o}=e,a=Lt(di,t);return n.jsx(Fk,{scope:t,forceMount:r,children:x.Children.map(s,i=>n.jsx(mr,{present:r||a.open,children:n.jsx(ii,{asChild:!0,container:o,children:i})}))})};Sm.displayName=di;var As="DialogOverlay",Cm=x.forwardRef((e,t)=>{const r=km(As,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Lt(As,e.__scopeDialog);return a.modal?n.jsx(mr,{present:s||a.open,children:n.jsx(Uk,{...o,ref:t})}):null});Cm.displayName=As;var Bk=Rk("DialogOverlay.RemoveScroll"),Uk=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(As,r);return n.jsx(ci,{as:Bk,allowPinchZoom:!0,shards:[o.contentRef],children:n.jsx(be.div,{"data-state":mi(o.open),...s,ref:t,style:{pointerEvents:"auto",...s.style}})})}),On="DialogContent",Nm=x.forwardRef((e,t)=>{const r=km(On,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Lt(On,e.__scopeDialog);return n.jsx(mr,{present:s||a.open,children:a.modal?n.jsx(Wk,{...o,ref:t}):n.jsx(Vk,{...o,ref:t})})});Nm.displayName=On;var Wk=x.forwardRef((e,t)=>{const r=Lt(On,e.__scopeDialog),s=x.useRef(null),o=Ee(t,r.contentRef,s);return x.useEffect(()=>{const a=s.current;if(a)return zu(a)},[]),n.jsx(Pm,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:_e(e.onCloseAutoFocus,a=>{a.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:_e(e.onPointerDownOutside,a=>{const i=a.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&a.preventDefault()}),onFocusOutside:_e(e.onFocusOutside,a=>a.preventDefault())})}),Vk=x.forwardRef((e,t)=>{const r=Lt(On,e.__scopeDialog),s=x.useRef(!1),o=x.useRef(!1);return n.jsx(Pm,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(s.current||r.triggerRef.current?.focus(),a.preventDefault()),s.current=!1,o.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(s.current=!0,a.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=a.target;r.triggerRef.current?.contains(i)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&o.current&&a.preventDefault()}})}),Pm=x.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,...i}=e,c=Lt(On,r),l=x.useRef(null),d=Ee(t,l);return pu(),n.jsxs(n.Fragment,{children:[n.jsx(Xa,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:o,onUnmountAutoFocus:a,children:n.jsx(Ka,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":mi(c.open),...i,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),n.jsxs(n.Fragment,{children:[n.jsx(qk,{titleId:c.titleId}),n.jsx(Zk,{contentRef:l,descriptionId:c.descriptionId})]})]})}),ui="DialogTitle",Am=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(ui,r);return n.jsx(be.h2,{id:o.titleId,...s,ref:t})});Am.displayName=ui;var Em="DialogDescription",Tm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(Em,r);return n.jsx(be.p,{id:o.descriptionId,...s,ref:t})});Tm.displayName=Em;var Im="DialogClose",Rm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(Im,r);return n.jsx(be.button,{type:"button",...s,ref:t,onClick:_e(e.onClick,()=>o.onOpenChange(!1))})});Rm.displayName=Im;function mi(e){return e?"open":"closed"}var Om="DialogTitleWarning",[pN,Mm]=K0(Om,{contentName:On,titleName:ui,docsSlug:"dialog"}),qk=({titleId:e})=>{const t=Mm(Om),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
131
|
+
`)},Zj=0,Qn=[];function Gj(e){var t=x.useRef([]),r=x.useRef([0,0]),s=x.useRef(),o=x.useState(Zj++)[0],a=x.useState(Wu)[0],i=x.useRef(e);x.useEffect(function(){i.current=e},[e]),x.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var g=hj([e.lockRef.current],(e.shards||[]).map(il),!0).filter(Boolean);return g.forEach(function(f){return f.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),g.forEach(function(f){return f.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var c=x.useCallback(function(g,f){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!i.current.allowPinchZoom;var w=ns(g),j=r.current,v="deltaX"in g?g.deltaX:j[0]-w[0],b="deltaY"in g?g.deltaY:j[1]-w[1],k,R=g.target,N=Math.abs(v)>Math.abs(b)?"h":"v";if("touches"in g&&N==="h"&&R.type==="range")return!1;var C=window.getSelection(),T=C&&C.anchorNode,O=T?T===R||T.contains(R):!1;if(O)return!1;var $=ol(N,R);if(!$)return!0;if($?k=N:(k=N==="v"?"h":"v",$=ol(N,R)),!$)return!1;if(!s.current&&"changedTouches"in g&&(v||b)&&(s.current=k),!k)return!0;var S=s.current||k;return Vj(S,f,g,S==="h"?v:b)},[]),l=x.useCallback(function(g){var f=g;if(!(!Qn.length||Qn[Qn.length-1]!==a)){var w="deltaY"in f?al(f):ns(f),j=t.current.filter(function(k){return k.name===f.type&&(k.target===f.target||f.target===k.shadowParent)&&qj(k.delta,w)})[0];if(j&&j.should){f.cancelable&&f.preventDefault();return}if(!j){var v=(i.current.shards||[]).map(il).filter(Boolean).filter(function(k){return k.contains(f.target)}),b=v.length>0?c(f,v[0]):!i.current.noIsolation;b&&f.cancelable&&f.preventDefault()}}},[]),d=x.useCallback(function(g,f,w,j){var v={name:g,delta:f,target:w,should:j,shadowParent:Qj(w)};t.current.push(v),setTimeout(function(){t.current=t.current.filter(function(b){return b!==v})},1)},[]),m=x.useCallback(function(g){r.current=ns(g),s.current=void 0},[]),u=x.useCallback(function(g){d(g.type,al(g),g.target,c(g,e.lockRef.current))},[]),p=x.useCallback(function(g){d(g.type,ns(g),g.target,c(g,e.lockRef.current))},[]);x.useEffect(function(){return Qn.push(a),e.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:p}),document.addEventListener("wheel",l,Gn),document.addEventListener("touchmove",l,Gn),document.addEventListener("touchstart",m,Gn),function(){Qn=Qn.filter(function(g){return g!==a}),document.removeEventListener("wheel",l,Gn),document.removeEventListener("touchmove",l,Gn),document.removeEventListener("touchstart",m,Gn)}},[]);var h=e.removeScrollBar,_=e.inert;return x.createElement(x.Fragment,null,_?x.createElement(a,{styles:Hj(o)}):null,h?x.createElement(Lj,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Qj(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Yj=kj(Uu,Gj);var ci=x.forwardRef(function(e,t){return x.createElement(qs,Wt({},e,{ref:t,sideCar:Yj}))});ci.classNames=qs.classNames;var Kj=[" ","Enter","ArrowUp","ArrowDown"],Xj=[" ","Enter"],In="Select",[Hs,Zs,Jj]=Ya(In),[ur]=vn(In,[Jj,Pu]),Gs=Pu(),[ek,wn]=ur(In),[tk,nk]=ur(In),Zu=e=>{const{__scopeSelect:t,children:r,open:s,defaultOpen:o,onOpenChange:a,value:i,defaultValue:c,onValueChange:l,dir:d,name:m,autoComplete:u,disabled:p,required:h,form:_}=e,g=Gs(t),[f,w]=x.useState(null),[j,v]=x.useState(null),[b,k]=x.useState(!1),R=Fs(d),[N,C]=hn({prop:s,defaultProp:o??!1,onChange:a,caller:In}),[T,O]=hn({prop:i,defaultProp:c,onChange:l,caller:In}),$=x.useRef(null),S=f?_||!!f.closest("form"):!0,[A,I]=x.useState(new Set),B=Array.from(A).map(D=>D.props.value).join(";");return n.jsx(Q_,{...g,children:n.jsxs(ek,{required:h,scope:t,trigger:f,onTriggerChange:w,valueNode:j,onValueNodeChange:v,valueNodeHasChildren:b,onValueNodeHasChildrenChange:k,contentId:qt(),value:T,onValueChange:O,open:N,onOpenChange:C,dir:R,triggerPointerDownPosRef:$,disabled:p,children:[n.jsx(Hs.Provider,{scope:t,children:n.jsx(tk,{scope:e.__scopeSelect,onNativeOptionAdd:x.useCallback(D=>{I(E=>new Set(E).add(D))},[]),onNativeOptionRemove:x.useCallback(D=>{I(E=>{const P=new Set(E);return P.delete(D),P})},[]),children:r})}),S?n.jsxs(pm,{"aria-hidden":!0,required:h,tabIndex:-1,name:m,autoComplete:u,value:T,onChange:D=>O(D.target.value),disabled:p,form:_,children:[T===void 0?n.jsx("option",{value:""}):null,Array.from(A)]},B):null]})})};Zu.displayName=In;var Gu="SelectTrigger",Qu=x.forwardRef((e,t)=>{const{__scopeSelect:r,disabled:s=!1,...o}=e,a=Gs(r),i=wn(Gu,r),c=i.disabled||s,l=Ee(t,i.onTriggerChange),d=Zs(r),m=x.useRef("touch"),[u,p,h]=hm(g=>{const f=d().filter(v=>!v.disabled),w=f.find(v=>v.value===i.value),j=gm(f,g,w);j!==void 0&&i.onValueChange(j.value)}),_=g=>{c||(i.onOpenChange(!0),h()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return n.jsx(Y_,{asChild:!0,...a,children:n.jsx(ve.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":fm(i.value)?"":void 0,...o,ref:l,onClick:_e(o.onClick,g=>{g.currentTarget.focus(),m.current!=="mouse"&&_(g)}),onPointerDown:_e(o.onPointerDown,g=>{m.current=g.pointerType;const f=g.target;f.hasPointerCapture(g.pointerId)&&f.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(_(g),g.preventDefault())}),onKeyDown:_e(o.onKeyDown,g=>{const f=u.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&p(g.key),!(f&&g.key===" ")&&Kj.includes(g.key)&&(_(),g.preventDefault())})})})});Qu.displayName=Gu;var Yu="SelectValue",Ku=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,children:a,placeholder:i="",...c}=e,l=wn(Yu,r),{onValueNodeHasChildrenChange:d}=l,m=a!==void 0,u=Ee(t,l.onValueNodeChange);return Xe(()=>{d(m)},[d,m]),n.jsx(ve.span,{...c,ref:u,style:{pointerEvents:"none"},children:fm(l.value)?n.jsx(n.Fragment,{children:i}):a})});Ku.displayName=Yu;var rk="SelectIcon",Xu=x.forwardRef((e,t)=>{const{__scopeSelect:r,children:s,...o}=e;return n.jsx(ve.span,{"aria-hidden":!0,...o,ref:t,children:s||"▼"})});Xu.displayName=rk;var sk="SelectPortal",Ju=e=>n.jsx(ii,{asChild:!0,...e});Ju.displayName=sk;var Rn="SelectContent",em=x.forwardRef((e,t)=>{const r=wn(Rn,e.__scopeSelect),[s,o]=x.useState();if(Xe(()=>{o(new DocumentFragment)},[]),!r.open){const a=s;return a?Is.createPortal(n.jsx(tm,{scope:e.__scopeSelect,children:n.jsx(Hs.Slot,{scope:e.__scopeSelect,children:n.jsx("div",{children:e.children})})}),a):null}return n.jsx(nm,{...e,ref:t})});em.displayName=Rn;var Tt=10,[tm,_n]=ur(Rn),ok="SelectContentImpl",ak=ej("SelectContent.RemoveScroll"),nm=x.forwardRef((e,t)=>{const{__scopeSelect:r,position:s="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:a,onPointerDownOutside:i,side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:p,collisionPadding:h,sticky:_,hideWhenDetached:g,avoidCollisions:f,...w}=e,j=wn(Rn,r),[v,b]=x.useState(null),[k,R]=x.useState(null),N=Ee(t,F=>b(F)),[C,T]=x.useState(null),[O,$]=x.useState(null),S=Zs(r),[A,I]=x.useState(!1),B=x.useRef(!1);x.useEffect(()=>{if(v)return zu(v)},[v]),pu();const D=x.useCallback(F=>{const[ee,...pe]=S().map(le=>le.ref.current),[q]=pe.slice(-1),ne=document.activeElement;for(const le of F)if(le===ne||(le?.scrollIntoView({block:"nearest"}),le===ee&&k&&(k.scrollTop=0),le===q&&k&&(k.scrollTop=k.scrollHeight),le?.focus(),document.activeElement!==ne))return},[S,k]),E=x.useCallback(()=>D([C,v]),[D,C,v]);x.useEffect(()=>{A&&E()},[A,E]);const{onOpenChange:P,triggerPointerDownPosRef:z}=j;x.useEffect(()=>{if(v){let F={x:0,y:0};const ee=q=>{F={x:Math.abs(Math.round(q.pageX)-(z.current?.x??0)),y:Math.abs(Math.round(q.pageY)-(z.current?.y??0))}},pe=q=>{F.x<=10&&F.y<=10?q.preventDefault():v.contains(q.target)||P(!1),document.removeEventListener("pointermove",ee),z.current=null};return z.current!==null&&(document.addEventListener("pointermove",ee),document.addEventListener("pointerup",pe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ee),document.removeEventListener("pointerup",pe,{capture:!0})}}},[v,P,z]),x.useEffect(()=>{const F=()=>P(!1);return window.addEventListener("blur",F),window.addEventListener("resize",F),()=>{window.removeEventListener("blur",F),window.removeEventListener("resize",F)}},[P]);const[Z,K]=hm(F=>{const ee=S().filter(ne=>!ne.disabled),pe=ee.find(ne=>ne.ref.current===document.activeElement),q=gm(ee,F,pe);q&&setTimeout(()=>q.ref.current.focus())}),L=x.useCallback((F,ee,pe)=>{const q=!B.current&&!pe;(j.value!==void 0&&j.value===ee||q)&&(T(F),q&&(B.current=!0))},[j.value]),W=x.useCallback(()=>v?.focus(),[v]),Y=x.useCallback((F,ee,pe)=>{const q=!B.current&&!pe;(j.value!==void 0&&j.value===ee||q)&&$(F)},[j.value]),V=s==="popper"?da:rm,ce=V===da?{side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:p,collisionPadding:h,sticky:_,hideWhenDetached:g,avoidCollisions:f}:{};return n.jsx(tm,{scope:r,content:v,viewport:k,onViewportChange:R,itemRefCallback:L,selectedItem:C,onItemLeave:W,itemTextRefCallback:Y,focusSelectedItem:E,selectedItemText:O,position:s,isPositioned:A,searchRef:Z,children:n.jsx(ci,{as:ak,allowPinchZoom:!0,children:n.jsx(Xa,{asChild:!0,trapped:j.open,onMountAutoFocus:F=>{F.preventDefault()},onUnmountAutoFocus:_e(o,F=>{j.trigger?.focus({preventScroll:!0}),F.preventDefault()}),children:n.jsx(Ka,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:F=>F.preventDefault(),onDismiss:()=>j.onOpenChange(!1),children:n.jsx(V,{role:"listbox",id:j.contentId,"data-state":j.open?"open":"closed",dir:j.dir,onContextMenu:F=>F.preventDefault(),...w,...ce,onPlaced:()=>I(!0),ref:N,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:_e(w.onKeyDown,F=>{const ee=F.ctrlKey||F.altKey||F.metaKey;if(F.key==="Tab"&&F.preventDefault(),!ee&&F.key.length===1&&K(F.key),["ArrowUp","ArrowDown","Home","End"].includes(F.key)){let q=S().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);if(["ArrowUp","End"].includes(F.key)&&(q=q.slice().reverse()),["ArrowUp","ArrowDown"].includes(F.key)){const ne=F.target,le=q.indexOf(ne);q=q.slice(le+1)}setTimeout(()=>D(q)),F.preventDefault()}})})})})})})});nm.displayName=ok;var ik="SelectItemAlignedPosition",rm=x.forwardRef((e,t)=>{const{__scopeSelect:r,onPlaced:s,...o}=e,a=wn(Rn,r),i=_n(Rn,r),[c,l]=x.useState(null),[d,m]=x.useState(null),u=Ee(t,N=>m(N)),p=Zs(r),h=x.useRef(!1),_=x.useRef(!0),{viewport:g,selectedItem:f,selectedItemText:w,focusSelectedItem:j}=i,v=x.useCallback(()=>{if(a.trigger&&a.valueNode&&c&&d&&g&&f&&w){const N=a.trigger.getBoundingClientRect(),C=d.getBoundingClientRect(),T=a.valueNode.getBoundingClientRect(),O=w.getBoundingClientRect();if(a.dir!=="rtl"){const ne=O.left-C.left,le=T.left-ne,fe=N.left-le,Pe=N.width+fe,Ve=Math.max(Pe,C.width),qe=window.innerWidth-Tt,He=Lc(le,[Tt,Math.max(Tt,qe-Ve)]);c.style.minWidth=Pe+"px",c.style.left=He+"px"}else{const ne=C.right-O.right,le=window.innerWidth-T.right-ne,fe=window.innerWidth-N.right-le,Pe=N.width+fe,Ve=Math.max(Pe,C.width),qe=window.innerWidth-Tt,He=Lc(le,[Tt,Math.max(Tt,qe-Ve)]);c.style.minWidth=Pe+"px",c.style.right=He+"px"}const $=p(),S=window.innerHeight-Tt*2,A=g.scrollHeight,I=window.getComputedStyle(d),B=parseInt(I.borderTopWidth,10),D=parseInt(I.paddingTop,10),E=parseInt(I.borderBottomWidth,10),P=parseInt(I.paddingBottom,10),z=B+D+A+P+E,Z=Math.min(f.offsetHeight*5,z),K=window.getComputedStyle(g),L=parseInt(K.paddingTop,10),W=parseInt(K.paddingBottom,10),Y=N.top+N.height/2-Tt,V=S-Y,ce=f.offsetHeight/2,F=f.offsetTop+ce,ee=B+D+F,pe=z-ee;if(ee<=Y){const ne=$.length>0&&f===$[$.length-1].ref.current;c.style.bottom="0px";const le=d.clientHeight-g.offsetTop-g.offsetHeight,fe=Math.max(V,ce+(ne?W:0)+le+E),Pe=ee+fe;c.style.height=Pe+"px"}else{const ne=$.length>0&&f===$[0].ref.current;c.style.top="0px";const fe=Math.max(Y,B+g.offsetTop+(ne?L:0)+ce)+pe;c.style.height=fe+"px",g.scrollTop=ee-Y+g.offsetTop}c.style.margin=`${Tt}px 0`,c.style.minHeight=Z+"px",c.style.maxHeight=S+"px",s?.(),requestAnimationFrame(()=>h.current=!0)}},[p,a.trigger,a.valueNode,c,d,g,f,w,a.dir,s]);Xe(()=>v(),[v]);const[b,k]=x.useState();Xe(()=>{d&&k(window.getComputedStyle(d).zIndex)},[d]);const R=x.useCallback(N=>{N&&_.current===!0&&(v(),j?.(),_.current=!1)},[v,j]);return n.jsx(lk,{scope:r,contentWrapper:c,shouldExpandOnScrollRef:h,onScrollButtonChange:R,children:n.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:b},children:n.jsx(ve.div,{...o,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});rm.displayName=ik;var ck="SelectPopperPosition",da=x.forwardRef((e,t)=>{const{__scopeSelect:r,align:s="start",collisionPadding:o=Tt,...a}=e,i=Gs(r);return n.jsx(K_,{...i,...a,ref:t,align:s,collisionPadding:o,style:{boxSizing:"border-box",...a.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});da.displayName=ck;var[lk,li]=ur(Rn,{}),ua="SelectViewport",sm=x.forwardRef((e,t)=>{const{__scopeSelect:r,nonce:s,...o}=e,a=_n(ua,r),i=li(ua,r),c=Ee(t,a.onViewportChange),l=x.useRef(0);return n.jsxs(n.Fragment,{children:[n.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),n.jsx(Hs.Slot,{scope:r,children:n.jsx(ve.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:_e(o.onScroll,d=>{const m=d.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:p}=i;if(p?.current&&u){const h=Math.abs(l.current-m.scrollTop);if(h>0){const _=window.innerHeight-Tt*2,g=parseFloat(u.style.minHeight),f=parseFloat(u.style.height),w=Math.max(g,f);if(w<_){const j=w+h,v=Math.min(_,j),b=j-v;u.style.height=v+"px",u.style.bottom==="0px"&&(m.scrollTop=b>0?b:0,u.style.justifyContent="flex-end")}}}l.current=m.scrollTop})})})]})});sm.displayName=ua;var om="SelectGroup",[dk,uk]=ur(om),am=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=qt();return n.jsx(dk,{scope:r,id:o,children:n.jsx(ve.div,{role:"group","aria-labelledby":o,...s,ref:t})})});am.displayName=om;var im="SelectLabel",mk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=uk(im,r);return n.jsx(ve.div,{id:o.id,...s,ref:t})});mk.displayName=im;var Cs="SelectItem",[pk,cm]=ur(Cs),lm=x.forwardRef((e,t)=>{const{__scopeSelect:r,value:s,disabled:o=!1,textValue:a,...i}=e,c=wn(Cs,r),l=_n(Cs,r),d=c.value===s,[m,u]=x.useState(a??""),[p,h]=x.useState(!1),_=Ee(t,j=>l.itemRefCallback?.(j,s,o)),g=qt(),f=x.useRef("touch"),w=()=>{o||(c.onValueChange(s),c.onOpenChange(!1))};if(s==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return n.jsx(pk,{scope:r,value:s,disabled:o,textId:g,isSelected:d,onItemTextChange:x.useCallback(j=>{u(v=>v||(j?.textContent??"").trim())},[]),children:n.jsx(Hs.ItemSlot,{scope:r,value:s,disabled:o,textValue:m,children:n.jsx(ve.div,{role:"option","aria-labelledby":g,"data-highlighted":p?"":void 0,"aria-selected":d&&p,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:_,onFocus:_e(i.onFocus,()=>h(!0)),onBlur:_e(i.onBlur,()=>h(!1)),onClick:_e(i.onClick,()=>{f.current!=="mouse"&&w()}),onPointerUp:_e(i.onPointerUp,()=>{f.current==="mouse"&&w()}),onPointerDown:_e(i.onPointerDown,j=>{f.current=j.pointerType}),onPointerMove:_e(i.onPointerMove,j=>{f.current=j.pointerType,o?l.onItemLeave?.():f.current==="mouse"&&j.currentTarget.focus({preventScroll:!0})}),onPointerLeave:_e(i.onPointerLeave,j=>{j.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:_e(i.onKeyDown,j=>{l.searchRef?.current!==""&&j.key===" "||(Xj.includes(j.key)&&w(),j.key===" "&&j.preventDefault())})})})})});lm.displayName=Cs;var jr="SelectItemText",dm=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,...a}=e,i=wn(jr,r),c=_n(jr,r),l=cm(jr,r),d=nk(jr,r),[m,u]=x.useState(null),p=Ee(t,w=>u(w),l.onItemTextChange,w=>c.itemTextRefCallback?.(w,l.value,l.disabled)),h=m?.textContent,_=x.useMemo(()=>n.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:g,onNativeOptionRemove:f}=d;return Xe(()=>(g(_),()=>f(_)),[g,f,_]),n.jsxs(n.Fragment,{children:[n.jsx(ve.span,{id:l.textId,...a,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Is.createPortal(a.children,i.valueNode):null]})});dm.displayName=jr;var um="SelectItemIndicator",fk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return cm(um,r).isSelected?n.jsx(ve.span,{"aria-hidden":!0,...s,ref:t}):null});fk.displayName=um;var ma="SelectScrollUpButton",hk=x.forwardRef((e,t)=>{const r=_n(ma,e.__scopeSelect),s=li(ma,e.__scopeSelect),[o,a]=x.useState(!1),i=Ee(t,s.onScrollButtonChange);return Xe(()=>{if(r.viewport&&r.isPositioned){let c=function(){const d=l.scrollTop>0;a(d)};const l=r.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),o?n.jsx(mm,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});hk.displayName=ma;var pa="SelectScrollDownButton",gk=x.forwardRef((e,t)=>{const r=_n(pa,e.__scopeSelect),s=li(pa,e.__scopeSelect),[o,a]=x.useState(!1),i=Ee(t,s.onScrollButtonChange);return Xe(()=>{if(r.viewport&&r.isPositioned){let c=function(){const d=l.scrollHeight-l.clientHeight,m=Math.ceil(l.scrollTop)<d;a(m)};const l=r.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),o?n.jsx(mm,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});gk.displayName=pa;var mm=x.forwardRef((e,t)=>{const{__scopeSelect:r,onAutoScroll:s,...o}=e,a=_n("SelectScrollButton",r),i=x.useRef(null),c=Zs(r),l=x.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return x.useEffect(()=>()=>l(),[l]),Xe(()=>{c().find(m=>m.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),n.jsx(ve.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:_e(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(s,50))}),onPointerMove:_e(o.onPointerMove,()=>{a.onItemLeave?.(),i.current===null&&(i.current=window.setInterval(s,50))}),onPointerLeave:_e(o.onPointerLeave,()=>{l()})})}),xk="SelectSeparator",yk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return n.jsx(ve.div,{"aria-hidden":!0,...s,ref:t})});yk.displayName=xk;var fa="SelectArrow",bk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Gs(r),a=wn(fa,r),i=_n(fa,r);return a.open&&i.position==="popper"?n.jsx(X_,{...o,...s,ref:t}):null});bk.displayName=fa;var vk="SelectBubbleInput",pm=x.forwardRef(({__scopeSelect:e,value:t,...r},s)=>{const o=x.useRef(null),a=Ee(s,o),i=lj(t);return x.useEffect(()=>{const c=o.current;if(!c)return;const l=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&m){const u=new Event("change",{bubbles:!0});m.call(c,t),c.dispatchEvent(u)}},[i,t]),n.jsx(ve.select,{...r,style:{...Lu,...r.style},ref:a,defaultValue:t})});pm.displayName=vk;function fm(e){return e===""||e===void 0}function hm(e){const t=mn(e),r=x.useRef(""),s=x.useRef(0),o=x.useCallback(i=>{const c=r.current+i;t(c),(function l(d){r.current=d,window.clearTimeout(s.current),d!==""&&(s.current=window.setTimeout(()=>l(""),1e3))})(c)},[t]),a=x.useCallback(()=>{r.current="",window.clearTimeout(s.current)},[]);return x.useEffect(()=>()=>window.clearTimeout(s.current),[]),[r,o,a]}function gm(e,t,r){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,a=r?e.indexOf(r):-1;let i=wk(e,Math.max(a,0));o.length===1&&(i=i.filter(d=>d!==r));const l=i.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==r?l:void 0}function wk(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var _k=Zu,xm=Qu,jk=Ku,kk=Xu,Sk=Ju,ym=em,Ck=sm,Nk=am,bm=lm,Pk=dm;const Ns=_k,Ak=Nk,Ps=jk,Or=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(xm,{ref:s,className:H("flex h-10 w-full items-center justify-between rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:focus-visible:ring-neutral-50/20",e),...r,children:[t,n.jsx(kk,{className:"ml-2 text-neutral-500 dark:text-neutral-400",children:"▾"})]}));Or.displayName=xm.displayName;const Mr=x.forwardRef(({className:e,children:t,position:r="popper",...s},o)=>n.jsx(Sk,{children:n.jsx(ym,{ref:o,position:r,className:H("z-50 min-w-[8rem] overflow-hidden rounded-md border border-neutral-200 bg-white text-neutral-950 shadow-md dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",e),...s,children:n.jsx(Ck,{className:H("p-1",r==="popper"?"w-full":void 0),children:t})})}));Mr.displayName=ym.displayName;const Dr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(bm,{ref:s,className:H("relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-neutral-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-neutral-800",e),...r,children:n.jsx(Pk,{children:t})}));Dr.displayName=bm.displayName;function Ek(e,t){return x.useReducer((r,s)=>t[r][s]??r,e)}var mr=e=>{const{present:t,children:r}=e,s=Tk(t),o=typeof r=="function"?r({present:s.isPresent}):x.Children.only(r),a=Ee(s.ref,Ik(o));return typeof r=="function"||s.isPresent?x.cloneElement(o,{ref:a}):null};mr.displayName="Presence";function Tk(e){const[t,r]=x.useState(),s=x.useRef(null),o=x.useRef(e),a=x.useRef("none"),i=e?"mounted":"unmounted",[c,l]=Ek(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return x.useEffect(()=>{const d=rs(s.current);a.current=c==="mounted"?d:"none"},[c]),Xe(()=>{const d=s.current,m=o.current;if(m!==e){const p=a.current,h=rs(d);e?l("MOUNT"):h==="none"||d?.display==="none"?l("UNMOUNT"):l(m&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Xe(()=>{if(t){let d;const m=t.ownerDocument.defaultView??window,u=h=>{const g=rs(s.current).includes(CSS.escape(h.animationName));if(h.target===t&&g&&(l("ANIMATION_END"),!o.current)){const f=t.style.animationFillMode;t.style.animationFillMode="forwards",d=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=f)})}},p=h=>{h.target===t&&(a.current=rs(s.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{m.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:x.useCallback(d=>{s.current=d?getComputedStyle(d):null,r(d)},[])}}function rs(e){return e?.animationName||"none"}function Ik(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function Rk(e){const t=Ok(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(Dk);if(l){const d=l.props.children,m=c.map(u=>u===l?x.Children.count(d)>1?x.Children.only(null):x.isValidElement(d)?d.props.children:null:u);return n.jsx(t,{...i,ref:o,children:x.isValidElement(d)?x.cloneElement(d,void 0,m):null})}return n.jsx(t,{...i,ref:o,children:a})});return r.displayName=`${e}.Slot`,r}function Ok(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=$k(o),c=Lk(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ar(s,i):i),x.cloneElement(o,c)}return x.Children.count(o)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Mk=Symbol("radix.slottable");function Dk(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Mk}function Lk(e,t){const r={...t};for(const s in t){const o=e[s],a=t[s];/^on[A-Z]/.test(s)?o&&a?r[s]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(r[s]=o):s==="style"?r[s]={...o,...a}:s==="className"&&(r[s]=[o,a].filter(Boolean).join(" "))}return{...e,...r}}function $k(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Qs="Dialog",[vm]=vn(Qs),[zk,Lt]=vm(Qs),wm=e=>{const{__scopeDialog:t,children:r,open:s,defaultOpen:o,onOpenChange:a,modal:i=!0}=e,c=x.useRef(null),l=x.useRef(null),[d,m]=hn({prop:s,defaultProp:o??!1,onChange:a,caller:Qs});return n.jsx(zk,{scope:t,triggerRef:c,contentRef:l,contentId:qt(),titleId:qt(),descriptionId:qt(),open:d,onOpenChange:m,onOpenToggle:x.useCallback(()=>m(u=>!u),[m]),modal:i,children:r})};wm.displayName=Qs;var _m="DialogTrigger",jm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(_m,r),a=Ee(t,o.triggerRef);return n.jsx(ve.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":mi(o.open),...s,ref:a,onClick:_e(e.onClick,o.onOpenToggle)})});jm.displayName=_m;var di="DialogPortal",[Fk,km]=vm(di,{forceMount:void 0}),Sm=e=>{const{__scopeDialog:t,forceMount:r,children:s,container:o}=e,a=Lt(di,t);return n.jsx(Fk,{scope:t,forceMount:r,children:x.Children.map(s,i=>n.jsx(mr,{present:r||a.open,children:n.jsx(ii,{asChild:!0,container:o,children:i})}))})};Sm.displayName=di;var As="DialogOverlay",Cm=x.forwardRef((e,t)=>{const r=km(As,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Lt(As,e.__scopeDialog);return a.modal?n.jsx(mr,{present:s||a.open,children:n.jsx(Uk,{...o,ref:t})}):null});Cm.displayName=As;var Bk=Rk("DialogOverlay.RemoveScroll"),Uk=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(As,r);return n.jsx(ci,{as:Bk,allowPinchZoom:!0,shards:[o.contentRef],children:n.jsx(ve.div,{"data-state":mi(o.open),...s,ref:t,style:{pointerEvents:"auto",...s.style}})})}),On="DialogContent",Nm=x.forwardRef((e,t)=>{const r=km(On,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Lt(On,e.__scopeDialog);return n.jsx(mr,{present:s||a.open,children:a.modal?n.jsx(Wk,{...o,ref:t}):n.jsx(Vk,{...o,ref:t})})});Nm.displayName=On;var Wk=x.forwardRef((e,t)=>{const r=Lt(On,e.__scopeDialog),s=x.useRef(null),o=Ee(t,r.contentRef,s);return x.useEffect(()=>{const a=s.current;if(a)return zu(a)},[]),n.jsx(Pm,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:_e(e.onCloseAutoFocus,a=>{a.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:_e(e.onPointerDownOutside,a=>{const i=a.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&a.preventDefault()}),onFocusOutside:_e(e.onFocusOutside,a=>a.preventDefault())})}),Vk=x.forwardRef((e,t)=>{const r=Lt(On,e.__scopeDialog),s=x.useRef(!1),o=x.useRef(!1);return n.jsx(Pm,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(s.current||r.triggerRef.current?.focus(),a.preventDefault()),s.current=!1,o.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(s.current=!0,a.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=a.target;r.triggerRef.current?.contains(i)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&o.current&&a.preventDefault()}})}),Pm=x.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,...i}=e,c=Lt(On,r),l=x.useRef(null),d=Ee(t,l);return pu(),n.jsxs(n.Fragment,{children:[n.jsx(Xa,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:o,onUnmountAutoFocus:a,children:n.jsx(Ka,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":mi(c.open),...i,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),n.jsxs(n.Fragment,{children:[n.jsx(qk,{titleId:c.titleId}),n.jsx(Zk,{contentRef:l,descriptionId:c.descriptionId})]})]})}),ui="DialogTitle",Am=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(ui,r);return n.jsx(ve.h2,{id:o.titleId,...s,ref:t})});Am.displayName=ui;var Em="DialogDescription",Tm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(Em,r);return n.jsx(ve.p,{id:o.descriptionId,...s,ref:t})});Tm.displayName=Em;var Im="DialogClose",Rm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(Im,r);return n.jsx(ve.button,{type:"button",...s,ref:t,onClick:_e(e.onClick,()=>o.onOpenChange(!1))})});Rm.displayName=Im;function mi(e){return e?"open":"closed"}var Om="DialogTitleWarning",[pN,Mm]=K0(Om,{contentName:On,titleName:ui,docsSlug:"dialog"}),qk=({titleId:e})=>{const t=Mm(Om),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
132
132
|
|
|
133
133
|
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
134
134
|
|
|
135
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return x.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},Hk="DialogDescriptionWarning",Zk=({contentRef:e,descriptionId:t})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Mm(Hk).contentName}}.`;return x.useEffect(()=>{const o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(s))},[s,e,t]),null},Dm=wm,Lm=jm,$m=Sm,Ys=Cm,Ks=Nm,Xs=Am,Js=Tm,zm=Rm;const pi=Dm,Gk=Lm,Fm=$m,Qk=zm,fi=x.forwardRef(({className:e,...t},r)=>n.jsx(Ys,{ref:r,className:H("fixed inset-0 z-50 bg-neutral-950/40 backdrop-blur-sm transition-opacity data-[state=closed]:opacity-0 data-[state=open]:opacity-100",e),...t}));fi.displayName=Ys.displayName;const eo=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(Fm,{children:[n.jsx(fi,{}),n.jsx(Ks,{ref:s,className:H("fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border border-neutral-200 bg-white p-6 shadow-lg outline-none transition data-[state=closed]:opacity-0 data-[state=closed]:scale-95 data-[state=open]:opacity-100 data-[state=open]:scale-100 dark:border-neutral-800 dark:bg-neutral-950","rounded-2xl",e),...r,children:t})]}));eo.displayName=Ks.displayName;const hi=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-center sm:text-left",e),...t}),Bm=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t}),to=x.forwardRef(({className:e,...t},r)=>n.jsx(Xs,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));to.displayName=Xs.displayName;const gi=x.forwardRef(({className:e,...t},r)=>n.jsx(Js,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));gi.displayName=Js.displayName;const no=Dm,ro=Lm,Um=zm,Wm=$m,xi=x.forwardRef(({className:e,...t},r)=>n.jsx(Ys,{ref:r,className:H("fixed inset-0 z-50 bg-neutral-950/40 backdrop-blur-sm transition-opacity data-[state=closed]:opacity-0 data-[state=open]:opacity-100",e),...t}));xi.displayName=Ys.displayName;const Yk=Ga("fixed z-50 gap-4 bg-white p-6 shadow-lg outline-none transition duration-200 ease-out dark:bg-neutral-950",{variants:{side:{top:"inset-x-0 top-0 border-b border-neutral-200 data-[state=closed]:-translate-y-full data-[state=open]:translate-y-0 dark:border-neutral-800",bottom:"inset-x-0 bottom-0 border-t border-neutral-200 data-[state=closed]:translate-y-full data-[state=open]:translate-y-0 dark:border-neutral-800",left:"inset-y-0 left-0 h-full w-3/4 border-r border-neutral-200 data-[state=closed]:-translate-x-full data-[state=open]:translate-x-0 sm:max-w-sm dark:border-neutral-800",right:"inset-y-0 right-0 h-full w-3/4 border-l border-neutral-200 data-[state=closed]:translate-x-full data-[state=open]:translate-x-0 sm:max-w-sm dark:border-neutral-800",popup:"bottom-4 right-4 w-[420px] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-2rem)] overflow-hidden rounded-2xl border border-neutral-200 p-4 data-[state=closed]:translate-y-2 data-[state=open]:translate-y-0 data-[state=closed]:opacity-0 data-[state=open]:opacity-100 data-[state=closed]:scale-95 data-[state=open]:scale-100 dark:border-neutral-800"}},defaultVariants:{side:"right"}}),Fr=x.forwardRef(({side:e="right",className:t,children:r,overlayClassName:s,...o},a)=>n.jsxs(Wm,{children:[n.jsx(xi,{className:s}),n.jsx(Ks,{ref:a,className:H(Yk({side:e}),t),...o,children:r})]}));Fr.displayName=Ks.displayName;const so=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-left",e),...t}),oo=x.forwardRef(({className:e,...t},r)=>n.jsx(Xs,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));oo.displayName=Xs.displayName;const Vm=x.forwardRef(({className:e,...t},r)=>n.jsx(Js,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));Vm.displayName=Js.displayName;var ao="Collapsible",[Kk,qm]=bn(ao),[Xk,yi]=Kk(ao),Hm=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:s,defaultOpen:o,disabled:a,onOpenChange:i,...c}=e,[l,d]=hn({prop:s,defaultProp:o??!1,onChange:i,caller:ao});return n.jsx(Xk,{scope:r,disabled:a,contentId:qt(),open:l,onOpenToggle:x.useCallback(()=>d(m=>!m),[d]),children:n.jsx(be.div,{"data-state":bi(l),"data-disabled":a?"":void 0,...c,ref:t})})});Hm.displayName=ao;var Zm="CollapsibleTrigger",Gm=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,...s}=e,o=yi(Zm,r);return n.jsx(be.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":bi(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...s,ref:t,onClick:_e(e.onClick,o.onOpenToggle)})});Gm.displayName=Zm;var vi="CollapsibleContent",Qm=x.forwardRef((e,t)=>{const{forceMount:r,...s}=e,o=yi(vi,e.__scopeCollapsible);return n.jsx(mr,{present:r||o.open,children:({present:a})=>n.jsx(Jk,{...s,ref:t,present:a})})});Qm.displayName=vi;var Jk=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:s,children:o,...a}=e,i=yi(vi,r),[c,l]=x.useState(s),d=x.useRef(null),m=Ee(t,d),u=x.useRef(0),p=u.current,h=x.useRef(0),_=h.current,g=i.open||c,f=x.useRef(g),w=x.useRef(void 0);return x.useEffect(()=>{const j=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(j)},[]),Xe(()=>{const j=d.current;if(j){w.current=w.current||{transitionDuration:j.style.transitionDuration,animationName:j.style.animationName},j.style.transitionDuration="0s",j.style.animationName="none";const b=j.getBoundingClientRect();u.current=b.height,h.current=b.width,f.current||(j.style.transitionDuration=w.current.transitionDuration,j.style.animationName=w.current.animationName),l(s)}},[i.open,s]),n.jsx(be.div,{"data-state":bi(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...a,ref:m,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":_?`${_}px`:void 0,...e.style},children:g&&o})});function bi(e){return e?"open":"closed"}var eS=Hm,tS=Gm,nS=Qm,$t="Accordion",rS=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[wi,sS,oS]=Ya($t),[io]=bn($t,[oS,qm]),_i=qm(),Ym=y.forwardRef((e,t)=>{const{type:r,...s}=e,o=s,a=s;return n.jsx(wi.Provider,{scope:e.__scopeAccordion,children:r==="multiple"?n.jsx(lS,{...a,ref:t}):n.jsx(cS,{...o,ref:t})})});Ym.displayName=$t;var[Km,aS]=io($t),[Xm,iS]=io($t,{collapsible:!1}),cS=y.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},collapsible:a=!1,...i}=e,[c,l]=hn({prop:r,defaultProp:s??"",onChange:o,caller:$t});return n.jsx(Km,{scope:e.__scopeAccordion,value:y.useMemo(()=>c?[c]:[],[c]),onItemOpen:l,onItemClose:y.useCallback(()=>a&&l(""),[a,l]),children:n.jsx(Xm,{scope:e.__scopeAccordion,collapsible:a,children:n.jsx(Jm,{...i,ref:t})})})}),lS=y.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},...a}=e,[i,c]=hn({prop:r,defaultProp:s??[],onChange:o,caller:$t}),l=y.useCallback(m=>c((u=[])=>[...u,m]),[c]),d=y.useCallback(m=>c((u=[])=>u.filter(p=>p!==m)),[c]);return n.jsx(Km,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:d,children:n.jsx(Xm,{scope:e.__scopeAccordion,collapsible:!0,children:n.jsx(Jm,{...a,ref:t})})})}),[dS,co]=io($t),Jm=y.forwardRef((e,t)=>{const{__scopeAccordion:r,disabled:s,dir:o,orientation:a="vertical",...i}=e,c=y.useRef(null),l=Ee(c,t),d=sS(r),u=Fs(o)==="ltr",p=_e(e.onKeyDown,h=>{if(!rS.includes(h.key))return;const _=h.target,g=d().filter(C=>!C.ref.current?.disabled),f=g.findIndex(C=>C.ref.current===_),w=g.length;if(f===-1)return;h.preventDefault();let j=f;const b=0,v=w-1,k=()=>{j=f+1,j>v&&(j=b)},R=()=>{j=f-1,j<b&&(j=v)};switch(h.key){case"Home":j=b;break;case"End":j=v;break;case"ArrowRight":a==="horizontal"&&(u?k():R());break;case"ArrowDown":a==="vertical"&&k();break;case"ArrowLeft":a==="horizontal"&&(u?R():k());break;case"ArrowUp":a==="vertical"&&R();break}const N=j%w;g[N].ref.current?.focus()});return n.jsx(dS,{scope:r,disabled:s,direction:o,orientation:a,children:n.jsx(wi.Slot,{scope:r,children:n.jsx(be.div,{...i,"data-orientation":a,ref:l,onKeyDown:s?void 0:p})})})}),Es="AccordionItem",[uS,ji]=io(Es),ep=y.forwardRef((e,t)=>{const{__scopeAccordion:r,value:s,...o}=e,a=co(Es,r),i=aS(Es,r),c=_i(r),l=qt(),d=s&&i.value.includes(s)||!1,m=a.disabled||e.disabled;return n.jsx(uS,{scope:r,open:d,disabled:m,triggerId:l,children:n.jsx(eS,{"data-orientation":a.orientation,"data-state":ap(d),...c,...o,ref:t,disabled:m,open:d,onOpenChange:u=>{u?i.onItemOpen(s):i.onItemClose(s)}})})});ep.displayName=Es;var tp="AccordionHeader",np=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=co($t,r),a=ji(tp,r);return n.jsx(be.h3,{"data-orientation":o.orientation,"data-state":ap(a.open),"data-disabled":a.disabled?"":void 0,...s,ref:t})});np.displayName=tp;var ha="AccordionTrigger",rp=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=co($t,r),a=ji(ha,r),i=iS(ha,r),c=_i(r);return n.jsx(wi.ItemSlot,{scope:r,children:n.jsx(tS,{"aria-disabled":a.open&&!i.collapsible||void 0,"data-orientation":o.orientation,id:a.triggerId,...c,...s,ref:t})})});rp.displayName=ha;var sp="AccordionContent",op=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=co($t,r),a=ji(sp,r),i=_i(r);return n.jsx(nS,{role:"region","aria-labelledby":a.triggerId,"data-orientation":o.orientation,...i,...s,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});op.displayName=sp;function ap(e){return e?"open":"closed"}var mS=Ym,ip=ep,pS=np,cp=rp,lp=op;const dp=mS,Sr=x.forwardRef(({className:e,...t},r)=>n.jsx(ip,{ref:r,className:H("border-b border-neutral-200 dark:border-neutral-800",e),...t}));Sr.displayName=ip.displayName;const Cr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(pS,{className:"flex",children:n.jsxs(cp,{ref:s,className:H("flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline",e),...r,children:[t,n.jsx("span",{className:"ml-3 text-neutral-500 dark:text-neutral-400","aria-hidden":!0,children:"▾"})]})}));Cr.displayName=cp.displayName;const Nr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(lp,{ref:s,className:H("overflow-hidden text-sm",e),...r,children:n.jsx("div",{className:"pb-4 pt-0",children:t})}));Nr.displayName=lp.displayName;var Bo="rovingFocusGroup.onEntryFocus",fS={bubbles:!1,cancelable:!0},Br="RovingFocusGroup",[ga,up,hS]=Ya(Br),[gS,mp]=bn(Br,[hS]),[xS,yS]=gS(Br),pp=x.forwardRef((e,t)=>n.jsx(ga.Provider,{scope:e.__scopeRovingFocusGroup,children:n.jsx(ga.Slot,{scope:e.__scopeRovingFocusGroup,children:n.jsx(vS,{...e,ref:t})})}));pp.displayName=Br;var vS=x.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,orientation:s,loop:o=!1,dir:a,currentTabStopId:i,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:m=!1,...u}=e,p=x.useRef(null),h=Ee(t,p),_=Fs(a),[g,f]=hn({prop:i,defaultProp:c??null,onChange:l,caller:Br}),[w,j]=x.useState(!1),b=mn(d),v=up(r),k=x.useRef(!1),[R,N]=x.useState(0);return x.useEffect(()=>{const C=p.current;if(C)return C.addEventListener(Bo,b),()=>C.removeEventListener(Bo,b)},[b]),n.jsx(xS,{scope:r,orientation:s,dir:_,loop:o,currentTabStopId:g,onItemFocus:x.useCallback(C=>f(C),[f]),onItemShiftTab:x.useCallback(()=>j(!0),[]),onFocusableItemAdd:x.useCallback(()=>N(C=>C+1),[]),onFocusableItemRemove:x.useCallback(()=>N(C=>C-1),[]),children:n.jsx(be.div,{tabIndex:w||R===0?-1:0,"data-orientation":s,...u,ref:h,style:{outline:"none",...e.style},onMouseDown:_e(e.onMouseDown,()=>{k.current=!0}),onFocus:_e(e.onFocus,C=>{const T=!k.current;if(C.target===C.currentTarget&&T&&!w){const O=new CustomEvent(Bo,fS);if(C.currentTarget.dispatchEvent(O),!O.defaultPrevented){const $=v().filter(D=>D.focusable),S=$.find(D=>D.active),A=$.find(D=>D.id===g),B=[S,A,...$].filter(Boolean).map(D=>D.ref.current);gp(B,m)}}k.current=!1}),onBlur:_e(e.onBlur,()=>j(!1))})})}),fp="RovingFocusGroupItem",hp=x.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,focusable:s=!0,active:o=!1,tabStopId:a,children:i,...c}=e,l=qt(),d=a||l,m=yS(fp,r),u=m.currentTabStopId===d,p=up(r),{onFocusableItemAdd:h,onFocusableItemRemove:_,currentTabStopId:g}=m;return x.useEffect(()=>{if(s)return h(),()=>_()},[s,h,_]),n.jsx(ga.ItemSlot,{scope:r,id:d,focusable:s,active:o,children:n.jsx(be.span,{tabIndex:u?0:-1,"data-orientation":m.orientation,...c,ref:t,onMouseDown:_e(e.onMouseDown,f=>{s?m.onItemFocus(d):f.preventDefault()}),onFocus:_e(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:_e(e.onKeyDown,f=>{if(f.key==="Tab"&&f.shiftKey){m.onItemShiftTab();return}if(f.target!==f.currentTarget)return;const w=_S(f,m.orientation,m.dir);if(w!==void 0){if(f.metaKey||f.ctrlKey||f.altKey||f.shiftKey)return;f.preventDefault();let b=p().filter(v=>v.focusable).map(v=>v.ref.current);if(w==="last")b.reverse();else if(w==="prev"||w==="next"){w==="prev"&&b.reverse();const v=b.indexOf(f.currentTarget);b=m.loop?jS(b,v+1):b.slice(v+1)}setTimeout(()=>gp(b))}}),children:typeof i=="function"?i({isCurrentTabStop:u,hasTabStop:g!=null}):i})})});hp.displayName=fp;var bS={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function wS(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function _S(e,t,r){const s=wS(e.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(s))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(s)))return bS[s]}function gp(e,t=!1){const r=document.activeElement;for(const s of e)if(s===r||(s.focus({preventScroll:t}),document.activeElement!==r))return}function jS(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var kS=pp,SS=hp,lo="Tabs",[CS]=bn(lo,[mp]),xp=mp(),[NS,ki]=CS(lo),yp=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,onValueChange:o,defaultValue:a,orientation:i="horizontal",dir:c,activationMode:l="automatic",...d}=e,m=Fs(c),[u,p]=hn({prop:s,onChange:o,defaultProp:a??"",caller:lo});return n.jsx(NS,{scope:r,baseId:qt(),value:u,onValueChange:p,orientation:i,dir:m,activationMode:l,children:n.jsx(be.div,{dir:m,"data-orientation":i,...d,ref:t})})});yp.displayName=lo;var vp="TabsList",bp=x.forwardRef((e,t)=>{const{__scopeTabs:r,loop:s=!0,...o}=e,a=ki(vp,r),i=xp(r);return n.jsx(kS,{asChild:!0,...i,orientation:a.orientation,dir:a.dir,loop:s,children:n.jsx(be.div,{role:"tablist","aria-orientation":a.orientation,...o,ref:t})})});bp.displayName=vp;var wp="TabsTrigger",_p=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,disabled:o=!1,...a}=e,i=ki(wp,r),c=xp(r),l=Sp(i.baseId,s),d=Cp(i.baseId,s),m=s===i.value;return n.jsx(SS,{asChild:!0,...c,focusable:!o,active:m,children:n.jsx(be.button,{type:"button",role:"tab","aria-selected":m,"aria-controls":d,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:l,...a,ref:t,onMouseDown:_e(e.onMouseDown,u=>{!o&&u.button===0&&u.ctrlKey===!1?i.onValueChange(s):u.preventDefault()}),onKeyDown:_e(e.onKeyDown,u=>{[" ","Enter"].includes(u.key)&&i.onValueChange(s)}),onFocus:_e(e.onFocus,()=>{const u=i.activationMode!=="manual";!m&&!o&&u&&i.onValueChange(s)})})})});_p.displayName=wp;var jp="TabsContent",kp=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,forceMount:o,children:a,...i}=e,c=ki(jp,r),l=Sp(c.baseId,s),d=Cp(c.baseId,s),m=s===c.value,u=x.useRef(m);return x.useEffect(()=>{const p=requestAnimationFrame(()=>u.current=!1);return()=>cancelAnimationFrame(p)},[]),n.jsx(mr,{present:o||m,children:({present:p})=>n.jsx(be.div,{"data-state":m?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!p,id:d,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:u.current?"0s":void 0},children:p&&a})})});kp.displayName=jp;function Sp(e,t){return`${e}-trigger-${t}`}function Cp(e,t){return`${e}-content-${t}`}var PS=yp,Np=bp,Pp=_p,Ap=kp;const Si=PS,uo=x.forwardRef(({className:e,...t},r)=>n.jsx(Np,{ref:r,className:H("inline-flex h-10 items-center justify-center rounded-md bg-neutral-100 p-1 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400",e),...t}));uo.displayName=Np.displayName;const Lr=x.forwardRef(({className:e,...t},r)=>n.jsx(Pp,{ref:r,className:H("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-neutral-950 data-[state=active]:shadow-sm dark:ring-offset-neutral-950 dark:focus-visible:ring-neutral-50/20 dark:data-[state=active]:bg-neutral-950 dark:data-[state=active]:text-neutral-50",e),...t}));Lr.displayName=Pp.displayName;const Ep=x.forwardRef(({className:e,...t},r)=>n.jsx(Ap,{ref:r,className:H("mt-2 ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 dark:ring-offset-neutral-950 dark:focus-visible:ring-neutral-50/20",e),...t}));Ep.displayName=Ap.displayName;function tr({title:e,description:t,actionLabel:r,onAction:s,className:o}){return n.jsx("div",{className:H("flex flex-col items-center justify-center rounded-xl border border-neutral-200 bg-white p-10 text-center dark:border-neutral-800 dark:bg-neutral-950",o),children:n.jsxs("div",{className:"max-w-sm",children:[n.jsx("h3",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:e}),t?n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}):null,r&&s?n.jsx("div",{className:"mt-5",children:n.jsx(ie,{type:"button",onClick:s,variant:"secondary",children:r})}):null]})})}function Zt({title:e,description:t,onRetry:r,className:s}){return n.jsxs("div",{className:H("rounded-xl border border-neutral-200 bg-white p-6 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h3",{className:"text-sm font-semibold",children:e??"Something went wrong"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}),r?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"Try again"})}):null]})}class AS extends x.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error):n.jsx(Zt,{description:this.state.error.message}):this.props.children}}function ES(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}const TS=e=>{switch(e){case"success":return OS;case"info":return DS;case"warning":return MS;case"error":return LS;default:return null}},IS=Array(12).fill(0),RS=({visible:e,className:t})=>y.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},y.createElement("div",{className:"sonner-spinner"},IS.map((r,s)=>y.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),OS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),MS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),DS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),LS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),$S=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},y.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),zS=()=>{const[e,t]=y.useState(document.hidden);return y.useEffect(()=>{const r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),e};let xa=1;class FS{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const r=this.subscribers.indexOf(t);this.subscribers.splice(r,1)}),this.publish=t=>{this.subscribers.forEach(r=>r(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var r;const{message:s,...o}=t,a=typeof t?.id=="number"||((r=t.id)==null?void 0:r.length)>0?t.id:xa++,i=this.toasts.find(l=>l.id===a),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(a)&&this.dismissedToasts.delete(a),i?this.toasts=this.toasts.map(l=>l.id===a?(this.publish({...l,...t,id:a,title:s}),{...l,...t,id:a,dismissible:c,title:s}):l):this.addToast({title:s,...o,dismissible:c,id:a}),a},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(r=>r({id:t,dismiss:!0})))):this.toasts.forEach(r=>{this.subscribers.forEach(s=>s({id:r.id,dismiss:!0}))}),t),this.message=(t,r)=>this.create({...r,message:t}),this.error=(t,r)=>this.create({...r,message:t,type:"error"}),this.success=(t,r)=>this.create({...r,type:"success",message:t}),this.info=(t,r)=>this.create({...r,type:"info",message:t}),this.warning=(t,r)=>this.create({...r,type:"warning",message:t}),this.loading=(t,r)=>this.create({...r,type:"loading",message:t}),this.promise=(t,r)=>{if(!r)return;let s;r.loading!==void 0&&(s=this.create({...r,promise:t,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));const o=Promise.resolve(t instanceof Function?t():t);let a=s!==void 0,i;const c=o.then(async d=>{if(i=["resolve",d],y.isValidElement(d))a=!1,this.create({id:s,type:"default",message:d});else if(US(d)&&!d.ok){a=!1;const u=typeof r.error=="function"?await r.error(`HTTP error! status: ${d.status}`):r.error,p=typeof r.description=="function"?await r.description(`HTTP error! status: ${d.status}`):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,..._})}else if(d instanceof Error){a=!1;const u=typeof r.error=="function"?await r.error(d):r.error,p=typeof r.description=="function"?await r.description(d):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,..._})}else if(r.success!==void 0){a=!1;const u=typeof r.success=="function"?await r.success(d):r.success,p=typeof r.description=="function"?await r.description(d):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"success",description:p,..._})}}).catch(async d=>{if(i=["reject",d],r.error!==void 0){a=!1;const m=typeof r.error=="function"?await r.error(d):r.error,u=typeof r.description=="function"?await r.description(d):r.description,h=typeof m=="object"&&!y.isValidElement(m)?m:{message:m};this.create({id:s,type:"error",description:u,...h})}}).finally(()=>{a&&(this.dismiss(s),s=void 0),r.finally==null||r.finally.call(r)}),l=()=>new Promise((d,m)=>c.then(()=>i[0]==="reject"?m(i[1]):d(i[1])).catch(m));return typeof s!="string"&&typeof s!="number"?{unwrap:l}:Object.assign(s,{unwrap:l})},this.custom=(t,r)=>{const s=r?.id||xa++;return this.create({jsx:t(s),id:s,...r}),s},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ft=new FS,BS=(e,t)=>{const r=t?.id||xa++;return ft.addToast({title:e,...t,id:r}),r},US=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",WS=BS,VS=()=>ft.toasts,qS=()=>ft.getActiveToasts(),HS=Object.assign(WS,{success:ft.success,info:ft.info,warning:ft.warning,error:ft.error,custom:ft.custom,message:ft.message,promise:ft.promise,dismiss:ft.dismiss,loading:ft.loading},{getHistory:VS,getToasts:qS});ES("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function ss(e){return e.label!==void 0}const ZS=3,GS="24px",QS="16px",cl=4e3,YS=356,KS=14,XS=45,JS=200;function Bt(...e){return e.filter(Boolean).join(" ")}function eC(e){const[t,r]=e.split("-"),s=[];return t&&s.push(t),r&&s.push(r),s}const tC=e=>{var t,r,s,o,a,i,c,l,d;const{invert:m,toast:u,unstyled:p,interacting:h,setHeights:_,visibleToasts:g,heights:f,index:w,toasts:j,expanded:b,removeToast:v,defaultRichColors:k,closeButton:R,style:N,cancelButtonStyle:C,actionButtonStyle:T,className:O="",descriptionClassName:$="",duration:S,position:A,gap:I,expandByDefault:B,classNames:D,icons:E,closeButtonAriaLabel:P="Close toast"}=e,[z,Z]=y.useState(null),[K,L]=y.useState(null),[W,Y]=y.useState(!1),[V,ce]=y.useState(!1),[F,ee]=y.useState(!1),[pe,q]=y.useState(!1),[ne,le]=y.useState(!1),[fe,Pe]=y.useState(0),[Ve,qe]=y.useState(0),He=y.useRef(u.duration||S||cl),gt=y.useRef(null),Ge=y.useRef(null),zt=w===0,lt=w+1<=g,te=u.type,xe=u.dismissible!==!1,ge=u.className||"",dt=u.descriptionClassName||"",xt=y.useMemo(()=>f.findIndex(he=>he.toastId===u.id)||0,[f,u.id]),ut=y.useMemo(()=>{var he;return(he=u.closeButton)!=null?he:R},[u.closeButton,R]),U=y.useMemo(()=>u.duration||S||cl,[u.duration,S]),re=y.useRef(0),de=y.useRef(0),ke=y.useRef(0),Se=y.useRef(null),[Me,Fn]=A.split("-"),jt=y.useMemo(()=>f.reduce((he,Le,we)=>we>=xt?he:he+Le.height,0),[f,xt]),Xt=zS(),pr=u.invert||m,jn=te==="loading";de.current=y.useMemo(()=>xt*I+jt,[xt,jt]),y.useEffect(()=>{He.current=U},[U]),y.useEffect(()=>{Y(!0)},[]),y.useEffect(()=>{const he=Ge.current;if(he){const Le=he.getBoundingClientRect().height;return qe(Le),_(we=>[{toastId:u.id,height:Le,position:u.position},...we]),()=>_(we=>we.filter($e=>$e.toastId!==u.id))}},[_,u.id]),y.useLayoutEffect(()=>{if(!W)return;const he=Ge.current,Le=he.style.height;he.style.height="auto";const we=he.getBoundingClientRect().height;he.style.height=Le,qe(we),_($e=>$e.find(ze=>ze.toastId===u.id)?$e.map(ze=>ze.toastId===u.id?{...ze,height:we}:ze):[{toastId:u.id,height:we,position:u.position},...$e])},[W,u.title,u.description,_,u.id,u.jsx,u.action,u.cancel]);const Ft=y.useCallback(()=>{ce(!0),Pe(de.current),_(he=>he.filter(Le=>Le.toastId!==u.id)),setTimeout(()=>{v(u)},JS)},[u,v,_,de]);y.useEffect(()=>{if(u.promise&&te==="loading"||u.duration===1/0||u.type==="loading")return;let he;return b||h||Xt?(()=>{if(ke.current<re.current){const $e=new Date().getTime()-re.current;He.current=He.current-$e}ke.current=new Date().getTime()})():(()=>{He.current!==1/0&&(re.current=new Date().getTime(),he=setTimeout(()=>{u.onAutoClose==null||u.onAutoClose.call(u,u),Ft()},He.current))})(),()=>clearTimeout(he)},[b,h,u,te,Xt,Ft]),y.useEffect(()=>{u.delete&&(Ft(),u.onDismiss==null||u.onDismiss.call(u,u))},[Ft,u.delete]);function Bn(){var he;if(E?.loading){var Le;return y.createElement("div",{className:Bt(D?.loader,u==null||(Le=u.classNames)==null?void 0:Le.loader,"sonner-loader"),"data-visible":te==="loading"},E.loading)}return y.createElement(RS,{className:Bt(D?.loader,u==null||(he=u.classNames)==null?void 0:he.loader),visible:te==="loading"})}const Un=u.icon||E?.[te]||TS(te);var Ur,on;return y.createElement("li",{tabIndex:0,ref:Ge,className:Bt(O,ge,D?.toast,u==null||(t=u.classNames)==null?void 0:t.toast,D?.default,D?.[te],u==null||(r=u.classNames)==null?void 0:r[te]),"data-sonner-toast":"","data-rich-colors":(Ur=u.richColors)!=null?Ur:k,"data-styled":!(u.jsx||u.unstyled||p),"data-mounted":W,"data-promise":!!u.promise,"data-swiped":ne,"data-removed":V,"data-visible":lt,"data-y-position":Me,"data-x-position":Fn,"data-index":w,"data-front":zt,"data-swiping":F,"data-dismissible":xe,"data-type":te,"data-invert":pr,"data-swipe-out":pe,"data-swipe-direction":K,"data-expanded":!!(b||B&&W),"data-testid":u.testId,style:{"--index":w,"--toasts-before":w,"--z-index":j.length-w,"--offset":`${V?fe:de.current}px`,"--initial-height":B?"auto":`${Ve}px`,...N,...u.style},onDragEnd:()=>{ee(!1),Z(null),Se.current=null},onPointerDown:he=>{he.button!==2&&(jn||!xe||(gt.current=new Date,Pe(de.current),he.target.setPointerCapture(he.pointerId),he.target.tagName!=="BUTTON"&&(ee(!0),Se.current={x:he.clientX,y:he.clientY})))},onPointerUp:()=>{var he,Le,we;if(pe||!xe)return;Se.current=null;const $e=Number(((he=Ge.current)==null?void 0:he.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Wn=Number(((Le=Ge.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),ze=new Date().getTime()-((we=gt.current)==null?void 0:we.getTime()),Je=z==="x"?$e:Wn,kn=Math.abs(Je)/ze;if(Math.abs(Je)>=XS||kn>.11){Pe(de.current),u.onDismiss==null||u.onDismiss.call(u,u),L(z==="x"?$e>0?"right":"left":Wn>0?"down":"up"),Ft(),q(!0);return}else{var mt,yt;(mt=Ge.current)==null||mt.style.setProperty("--swipe-amount-x","0px"),(yt=Ge.current)==null||yt.style.setProperty("--swipe-amount-y","0px")}le(!1),ee(!1),Z(null)},onPointerMove:he=>{var Le,we,$e;if(!Se.current||!xe||((Le=window.getSelection())==null?void 0:Le.toString().length)>0)return;const ze=he.clientY-Se.current.y,Je=he.clientX-Se.current.x;var kn;const mt=(kn=e.swipeDirections)!=null?kn:eC(A);!z&&(Math.abs(Je)>1||Math.abs(ze)>1)&&Z(Math.abs(Je)>Math.abs(ze)?"x":"y");let yt={x:0,y:0};const vt=tt=>1/(1.5+Math.abs(tt)/20);if(z==="y"){if(mt.includes("top")||mt.includes("bottom"))if(mt.includes("top")&&ze<0||mt.includes("bottom")&&ze>0)yt.y=ze;else{const tt=ze*vt(ze);yt.y=Math.abs(tt)<Math.abs(ze)?tt:ze}}else if(z==="x"&&(mt.includes("left")||mt.includes("right")))if(mt.includes("left")&&Je<0||mt.includes("right")&&Je>0)yt.x=Je;else{const tt=Je*vt(Je);yt.x=Math.abs(tt)<Math.abs(Je)?tt:Je}(Math.abs(yt.x)>0||Math.abs(yt.y)>0)&&le(!0),(we=Ge.current)==null||we.style.setProperty("--swipe-amount-x",`${yt.x}px`),($e=Ge.current)==null||$e.style.setProperty("--swipe-amount-y",`${yt.y}px`)}},ut&&!u.jsx&&te!=="loading"?y.createElement("button",{"aria-label":P,"data-disabled":jn,"data-close-button":!0,onClick:jn||!xe?()=>{}:()=>{Ft(),u.onDismiss==null||u.onDismiss.call(u,u)},className:Bt(D?.closeButton,u==null||(s=u.classNames)==null?void 0:s.closeButton)},(on=E?.close)!=null?on:$S):null,(te||u.icon||u.promise)&&u.icon!==null&&(E?.[te]!==null||u.icon)?y.createElement("div",{"data-icon":"",className:Bt(D?.icon,u==null||(o=u.classNames)==null?void 0:o.icon)},u.promise||u.type==="loading"&&!u.icon?u.icon||Bn():null,u.type!=="loading"?Un:null):null,y.createElement("div",{"data-content":"",className:Bt(D?.content,u==null||(a=u.classNames)==null?void 0:a.content)},y.createElement("div",{"data-title":"",className:Bt(D?.title,u==null||(i=u.classNames)==null?void 0:i.title)},u.jsx?u.jsx:typeof u.title=="function"?u.title():u.title),u.description?y.createElement("div",{"data-description":"",className:Bt($,dt,D?.description,u==null||(c=u.classNames)==null?void 0:c.description)},typeof u.description=="function"?u.description():u.description):null),y.isValidElement(u.cancel)?u.cancel:u.cancel&&ss(u.cancel)?y.createElement("button",{"data-button":!0,"data-cancel":!0,style:u.cancelButtonStyle||C,onClick:he=>{ss(u.cancel)&&xe&&(u.cancel.onClick==null||u.cancel.onClick.call(u.cancel,he),Ft())},className:Bt(D?.cancelButton,u==null||(l=u.classNames)==null?void 0:l.cancelButton)},u.cancel.label):null,y.isValidElement(u.action)?u.action:u.action&&ss(u.action)?y.createElement("button",{"data-button":!0,"data-action":!0,style:u.actionButtonStyle||T,onClick:he=>{ss(u.action)&&(u.action.onClick==null||u.action.onClick.call(u.action,he),!he.defaultPrevented&&Ft())},className:Bt(D?.actionButton,u==null||(d=u.classNames)==null?void 0:d.actionButton)},u.action.label):null)};function ll(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function nC(e,t){const r={};return[e,t].forEach((s,o)=>{const a=o===1,i=a?"--mobile-offset":"--offset",c=a?QS:GS;function l(d){["top","right","bottom","left"].forEach(m=>{r[`${i}-${m}`]=typeof d=="number"?`${d}px`:d})}typeof s=="number"||typeof s=="string"?l(s):typeof s=="object"?["top","right","bottom","left"].forEach(d=>{s[d]===void 0?r[`${i}-${d}`]=c:r[`${i}-${d}`]=typeof s[d]=="number"?`${s[d]}px`:s[d]}):l(c)}),r}const rC=y.forwardRef(function(t,r){const{id:s,invert:o,position:a="bottom-right",hotkey:i=["altKey","KeyT"],expand:c,closeButton:l,className:d,offset:m,mobileOffset:u,theme:p="light",richColors:h,duration:_,style:g,visibleToasts:f=ZS,toastOptions:w,dir:j=ll(),gap:b=KS,icons:v,containerAriaLabel:k="Notifications"}=t,[R,N]=y.useState([]),C=y.useMemo(()=>s?R.filter(W=>W.toasterId===s):R.filter(W=>!W.toasterId),[R,s]),T=y.useMemo(()=>Array.from(new Set([a].concat(C.filter(W=>W.position).map(W=>W.position)))),[C,a]),[O,$]=y.useState([]),[S,A]=y.useState(!1),[I,B]=y.useState(!1),[D,E]=y.useState(p!=="system"?p:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),P=y.useRef(null),z=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),Z=y.useRef(null),K=y.useRef(!1),L=y.useCallback(W=>{N(Y=>{var V;return(V=Y.find(ce=>ce.id===W.id))!=null&&V.delete||ft.dismiss(W.id),Y.filter(({id:ce})=>ce!==W.id)})},[]);return y.useEffect(()=>ft.subscribe(W=>{if(W.dismiss){requestAnimationFrame(()=>{N(Y=>Y.map(V=>V.id===W.id?{...V,delete:!0}:V))});return}setTimeout(()=>{ka.flushSync(()=>{N(Y=>{const V=Y.findIndex(ce=>ce.id===W.id);return V!==-1?[...Y.slice(0,V),{...Y[V],...W},...Y.slice(V+1)]:[W,...Y]})})})}),[R]),y.useEffect(()=>{if(p!=="system"){E(p);return}if(p==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?E("dark"):E("light")),typeof window>"u")return;const W=window.matchMedia("(prefers-color-scheme: dark)");try{W.addEventListener("change",({matches:Y})=>{E(Y?"dark":"light")})}catch{W.addListener(({matches:V})=>{try{E(V?"dark":"light")}catch(ce){console.error(ce)}})}},[p]),y.useEffect(()=>{R.length<=1&&A(!1)},[R]),y.useEffect(()=>{const W=Y=>{var V;if(i.every(ee=>Y[ee]||Y.code===ee)){var F;A(!0),(F=P.current)==null||F.focus()}Y.code==="Escape"&&(document.activeElement===P.current||(V=P.current)!=null&&V.contains(document.activeElement))&&A(!1)};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[i]),y.useEffect(()=>{if(P.current)return()=>{Z.current&&(Z.current.focus({preventScroll:!0}),Z.current=null,K.current=!1)}},[P.current]),y.createElement("section",{ref:r,"aria-label":`${k} ${z}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},T.map((W,Y)=>{var V;const[ce,F]=W.split("-");return C.length?y.createElement("ol",{key:W,dir:j==="auto"?ll():j,tabIndex:-1,ref:P,className:d,"data-sonner-toaster":!0,"data-sonner-theme":D,"data-y-position":ce,"data-x-position":F,style:{"--front-toast-height":`${((V=O[0])==null?void 0:V.height)||0}px`,"--width":`${YS}px`,"--gap":`${b}px`,...g,...nC(m,u)},onBlur:ee=>{K.current&&!ee.currentTarget.contains(ee.relatedTarget)&&(K.current=!1,Z.current&&(Z.current.focus({preventScroll:!0}),Z.current=null))},onFocus:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||K.current||(K.current=!0,Z.current=ee.relatedTarget)},onMouseEnter:()=>A(!0),onMouseMove:()=>A(!0),onMouseLeave:()=>{I||A(!1)},onDragEnd:()=>A(!1),onPointerDown:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||B(!0)},onPointerUp:()=>B(!1)},C.filter(ee=>!ee.position&&Y===0||ee.position===W).map((ee,pe)=>{var q,ne;return y.createElement(tC,{key:ee.id,icons:v,index:pe,toast:ee,defaultRichColors:h,duration:(q=w?.duration)!=null?q:_,className:w?.className,descriptionClassName:w?.descriptionClassName,invert:o,visibleToasts:f,closeButton:(ne=w?.closeButton)!=null?ne:l,interacting:I,position:W,style:w?.style,unstyled:w?.unstyled,classNames:w?.classNames,cancelButtonStyle:w?.cancelButtonStyle,actionButtonStyle:w?.actionButtonStyle,closeButtonAriaLabel:w?.closeButtonAriaLabel,removeToast:L,toasts:C.filter(le=>le.position==ee.position),heights:O.filter(le=>le.position==ee.position),setHeights:$,expandByDefault:c,gap:b,expanded:S,swipeDirections:t.swipeDirections})})):null}))}),Ci=x.createContext(null);function sC(){const e=x.useContext(Ci);if(!e)throw new Error("useToast must be used within ToastProvider");return e}function mo(){return x.useContext(Ci)}function oC({children:e}){const t=x.useCallback(r=>{const s=r.title??"",o=r.description;HS(s||o||"Notification",{description:s?o:void 0,duration:r.durationMs??5e3,action:r.actionLabel&&r.onAction?{label:r.actionLabel,onClick:()=>r.onAction?.()}:void 0})},[]);return n.jsxs(Ci.Provider,{value:{toast:t},children:[e,n.jsx(rC,{position:"top-center",closeButton:!0,expand:!0,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:pointer-events-auto group-[.toaster]:w-full group-[.toaster]:rounded-xl group-[.toaster]:border group-[.toaster]:border-neutral-200 group-[.toaster]:bg-white group-[.toaster]:p-4 group-[.toaster]:shadow-lg dark:group-[.toaster]:border-neutral-800 dark:group-[.toaster]:bg-neutral-950",title:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",description:"text-sm text-neutral-600 dark:text-neutral-400",actionButton:"h-8 rounded-md border border-neutral-200 bg-white px-3 text-xs font-medium text-neutral-900 shadow-sm hover:bg-neutral-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:hover:bg-neutral-900",cancelButton:"h-8 rounded-md bg-neutral-100 px-3 text-xs font-medium text-neutral-900 hover:bg-neutral-200 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-700",closeButton:"rounded-md text-neutral-600 opacity-0 transition-opacity hover:bg-neutral-100 hover:text-neutral-900 group-hover:opacity-100 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-neutral-50"}}})]})}const{entries:Tp,setPrototypeOf:dl,isFrozen:aC,getPrototypeOf:iC,getOwnPropertyDescriptor:cC}=Object;let{freeze:it,seal:Ct,create:ya}=Object,{apply:va,construct:ba}=typeof Reflect<"u"&&Reflect;it||(it=function(t){return t});Ct||(Ct=function(t){return t});va||(va=function(t,r){for(var s=arguments.length,o=new Array(s>2?s-2:0),a=2;a<s;a++)o[a-2]=arguments[a];return t.apply(r,o)});ba||(ba=function(t){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return new t(...s)});const os=ct(Array.prototype.forEach),lC=ct(Array.prototype.lastIndexOf),ul=ct(Array.prototype.pop),gr=ct(Array.prototype.push),dC=ct(Array.prototype.splice),ms=ct(String.prototype.toLowerCase),Uo=ct(String.prototype.toString),Wo=ct(String.prototype.match),xr=ct(String.prototype.replace),uC=ct(String.prototype.indexOf),mC=ct(String.prototype.trim),It=ct(Object.prototype.hasOwnProperty),nt=ct(RegExp.prototype.test),yr=pC(TypeError);function ct(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return va(e,t,s)}}function pC(e){return function(){for(var t=arguments.length,r=new Array(t),s=0;s<t;s++)r[s]=arguments[s];return ba(e,r)}}function ve(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ms;dl&&dl(e,null);let s=t.length;for(;s--;){let o=t[s];if(typeof o=="string"){const a=r(o);a!==o&&(aC(t)||(t[s]=a),o=a)}e[o]=!0}return e}function fC(e){for(let t=0;t<e.length;t++)It(e,t)||(e[t]=null);return e}function Ut(e){const t=ya(null);for(const[r,s]of Tp(e))It(e,r)&&(Array.isArray(s)?t[r]=fC(s):s&&typeof s=="object"&&s.constructor===Object?t[r]=Ut(s):t[r]=s);return t}function vr(e,t){for(;e!==null;){const s=cC(e,t);if(s){if(s.get)return ct(s.get);if(typeof s.value=="function")return ct(s.value)}e=iC(e)}function r(){return null}return r}const ml=it(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Vo=it(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),qo=it(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),hC=it(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ho=it(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),gC=it(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),pl=it(["#text"]),fl=it(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Zo=it(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),hl=it(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),as=it(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),xC=Ct(/\{\{[\w\W]*|[\w\W]*\}\}/gm),yC=Ct(/<%[\w\W]*|[\w\W]*%>/gm),vC=Ct(/\$\{[\w\W]*/gm),bC=Ct(/^data-[\-\w.\u00B7-\uFFFF]+$/),wC=Ct(/^aria-[\-\w]+$/),Ip=Ct(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),_C=Ct(/^(?:\w+script|data):/i),jC=Ct(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Rp=Ct(/^html$/i),kC=Ct(/^[a-z][.\w]*(-[.\w]+)+$/i);var gl=Object.freeze({__proto__:null,ARIA_ATTR:wC,ATTR_WHITESPACE:jC,CUSTOM_ELEMENT:kC,DATA_ATTR:bC,DOCTYPE_NAME:Rp,ERB_EXPR:yC,IS_ALLOWED_URI:Ip,IS_SCRIPT_OR_DATA:_C,MUSTACHE_EXPR:xC,TMPLIT_EXPR:vC});const br={element:1,text:3,progressingInstruction:7,comment:8,document:9},SC=function(){return typeof window>"u"?null:window},CC=function(t,r){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(s=r.getAttribute(o));const a="dompurify"+(s?"#"+s:"");try{return t.createPolicy(a,{createHTML(i){return i},createScriptURL(i){return i}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},xl=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Op(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:SC();const t=ue=>Op(ue);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==br.document||!e.Element)return t.isSupported=!1,t;let{document:r}=e;const s=r,o=s.currentScript,{DocumentFragment:a,HTMLTemplateElement:i,Node:c,Element:l,NodeFilter:d,NamedNodeMap:m=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:p,trustedTypes:h}=e,_=l.prototype,g=vr(_,"cloneNode"),f=vr(_,"remove"),w=vr(_,"nextSibling"),j=vr(_,"childNodes"),b=vr(_,"parentNode");if(typeof i=="function"){const ue=r.createElement("template");ue.content&&ue.content.ownerDocument&&(r=ue.content.ownerDocument)}let v,k="";const{implementation:R,createNodeIterator:N,createDocumentFragment:C,getElementsByTagName:T}=r,{importNode:O}=s;let $=xl();t.isSupported=typeof Tp=="function"&&typeof b=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:S,ERB_EXPR:A,TMPLIT_EXPR:I,DATA_ATTR:B,ARIA_ATTR:D,IS_SCRIPT_OR_DATA:E,ATTR_WHITESPACE:P,CUSTOM_ELEMENT:z}=gl;let{IS_ALLOWED_URI:Z}=gl,K=null;const L=ve({},[...ml,...Vo,...qo,...Ho,...pl]);let W=null;const Y=ve({},[...fl,...Zo,...hl,...as]);let V=Object.seal(ya(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ce=null,F=null;const ee=Object.seal(ya(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let pe=!0,q=!0,ne=!1,le=!0,fe=!1,Pe=!0,Ve=!1,qe=!1,He=!1,gt=!1,Ge=!1,zt=!1,lt=!0,te=!1;const xe="user-content-";let ge=!0,dt=!1,xt={},ut=null;const U=ve({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let re=null;const de=ve({},["audio","video","img","source","image","track"]);let ke=null;const Se=ve({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Me="http://www.w3.org/1998/Math/MathML",Fn="http://www.w3.org/2000/svg",jt="http://www.w3.org/1999/xhtml";let Xt=jt,pr=!1,jn=null;const Ft=ve({},[Me,Fn,jt],Uo);let Bn=ve({},["mi","mo","mn","ms","mtext"]),Un=ve({},["annotation-xml"]);const Ur=ve({},["title","style","font","a","script"]);let on=null;const he=["application/xhtml+xml","text/html"],Le="text/html";let we=null,$e=null;const Wn=r.createElement("form"),ze=function(M){return M instanceof RegExp||M instanceof Function},Je=function(){let M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!($e&&$e===M)){if((!M||typeof M!="object")&&(M={}),M=Ut(M),on=he.indexOf(M.PARSER_MEDIA_TYPE)===-1?Le:M.PARSER_MEDIA_TYPE,we=on==="application/xhtml+xml"?Uo:ms,K=It(M,"ALLOWED_TAGS")?ve({},M.ALLOWED_TAGS,we):L,W=It(M,"ALLOWED_ATTR")?ve({},M.ALLOWED_ATTR,we):Y,jn=It(M,"ALLOWED_NAMESPACES")?ve({},M.ALLOWED_NAMESPACES,Uo):Ft,ke=It(M,"ADD_URI_SAFE_ATTR")?ve(Ut(Se),M.ADD_URI_SAFE_ATTR,we):Se,re=It(M,"ADD_DATA_URI_TAGS")?ve(Ut(de),M.ADD_DATA_URI_TAGS,we):de,ut=It(M,"FORBID_CONTENTS")?ve({},M.FORBID_CONTENTS,we):U,ce=It(M,"FORBID_TAGS")?ve({},M.FORBID_TAGS,we):Ut({}),F=It(M,"FORBID_ATTR")?ve({},M.FORBID_ATTR,we):Ut({}),xt=It(M,"USE_PROFILES")?M.USE_PROFILES:!1,pe=M.ALLOW_ARIA_ATTR!==!1,q=M.ALLOW_DATA_ATTR!==!1,ne=M.ALLOW_UNKNOWN_PROTOCOLS||!1,le=M.ALLOW_SELF_CLOSE_IN_ATTR!==!1,fe=M.SAFE_FOR_TEMPLATES||!1,Pe=M.SAFE_FOR_XML!==!1,Ve=M.WHOLE_DOCUMENT||!1,gt=M.RETURN_DOM||!1,Ge=M.RETURN_DOM_FRAGMENT||!1,zt=M.RETURN_TRUSTED_TYPE||!1,He=M.FORCE_BODY||!1,lt=M.SANITIZE_DOM!==!1,te=M.SANITIZE_NAMED_PROPS||!1,ge=M.KEEP_CONTENT!==!1,dt=M.IN_PLACE||!1,Z=M.ALLOWED_URI_REGEXP||Ip,Xt=M.NAMESPACE||jt,Bn=M.MATHML_TEXT_INTEGRATION_POINTS||Bn,Un=M.HTML_INTEGRATION_POINTS||Un,V=M.CUSTOM_ELEMENT_HANDLING||{},M.CUSTOM_ELEMENT_HANDLING&&ze(M.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(V.tagNameCheck=M.CUSTOM_ELEMENT_HANDLING.tagNameCheck),M.CUSTOM_ELEMENT_HANDLING&&ze(M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(V.attributeNameCheck=M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),M.CUSTOM_ELEMENT_HANDLING&&typeof M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(V.allowCustomizedBuiltInElements=M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),fe&&(q=!1),Ge&&(gt=!0),xt&&(K=ve({},pl),W=[],xt.html===!0&&(ve(K,ml),ve(W,fl)),xt.svg===!0&&(ve(K,Vo),ve(W,Zo),ve(W,as)),xt.svgFilters===!0&&(ve(K,qo),ve(W,Zo),ve(W,as)),xt.mathMl===!0&&(ve(K,Ho),ve(W,hl),ve(W,as))),M.ADD_TAGS&&(typeof M.ADD_TAGS=="function"?ee.tagCheck=M.ADD_TAGS:(K===L&&(K=Ut(K)),ve(K,M.ADD_TAGS,we))),M.ADD_ATTR&&(typeof M.ADD_ATTR=="function"?ee.attributeCheck=M.ADD_ATTR:(W===Y&&(W=Ut(W)),ve(W,M.ADD_ATTR,we))),M.ADD_URI_SAFE_ATTR&&ve(ke,M.ADD_URI_SAFE_ATTR,we),M.FORBID_CONTENTS&&(ut===U&&(ut=Ut(ut)),ve(ut,M.FORBID_CONTENTS,we)),M.ADD_FORBID_CONTENTS&&(ut===U&&(ut=Ut(ut)),ve(ut,M.ADD_FORBID_CONTENTS,we)),ge&&(K["#text"]=!0),Ve&&ve(K,["html","head","body"]),K.table&&(ve(K,["tbody"]),delete ce.tbody),M.TRUSTED_TYPES_POLICY){if(typeof M.TRUSTED_TYPES_POLICY.createHTML!="function")throw yr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof M.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw yr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');v=M.TRUSTED_TYPES_POLICY,k=v.createHTML("")}else v===void 0&&(v=CC(h,o)),v!==null&&typeof k=="string"&&(k=v.createHTML(""));it&&it(M),$e=M}},kn=ve({},[...Vo,...qo,...hC]),mt=ve({},[...Ho,...gC]),yt=function(M){let X=b(M);(!X||!X.tagName)&&(X={namespaceURI:Xt,tagName:"template"});const ae=ms(M.tagName),Ae=ms(X.tagName);return jn[M.namespaceURI]?M.namespaceURI===Fn?X.namespaceURI===jt?ae==="svg":X.namespaceURI===Me?ae==="svg"&&(Ae==="annotation-xml"||Bn[Ae]):!!kn[ae]:M.namespaceURI===Me?X.namespaceURI===jt?ae==="math":X.namespaceURI===Fn?ae==="math"&&Un[Ae]:!!mt[ae]:M.namespaceURI===jt?X.namespaceURI===Fn&&!Un[Ae]||X.namespaceURI===Me&&!Bn[Ae]?!1:!mt[ae]&&(Ur[ae]||!kn[ae]):!!(on==="application/xhtml+xml"&&jn[M.namespaceURI]):!1},vt=function(M){gr(t.removed,{element:M});try{b(M).removeChild(M)}catch{f(M)}},tt=function(M,X){try{gr(t.removed,{attribute:X.getAttributeNode(M),from:X})}catch{gr(t.removed,{attribute:null,from:X})}if(X.removeAttribute(M),M==="is")if(gt||Ge)try{vt(X)}catch{}else try{X.setAttribute(M,"")}catch{}},go=function(M){let X=null,ae=null;if(He)M="<remove></remove>"+M;else{const Fe=Wo(M,/^[\r\n\t ]+/);ae=Fe&&Fe[0]}on==="application/xhtml+xml"&&Xt===jt&&(M='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+M+"</body></html>");const Ae=v?v.createHTML(M):M;if(Xt===jt)try{X=new p().parseFromString(Ae,on)}catch{}if(!X||!X.documentElement){X=R.createDocument(Xt,"template",null);try{X.documentElement.innerHTML=pr?k:Ae}catch{}}const et=X.body||X.documentElement;return M&&ae&&et.insertBefore(r.createTextNode(ae),et.childNodes[0]||null),Xt===jt?T.call(X,Ve?"html":"body")[0]:Ve?X.documentElement:et},Li=function(M){return N.call(M.ownerDocument||M,M,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},xo=function(M){return M instanceof u&&(typeof M.nodeName!="string"||typeof M.textContent!="string"||typeof M.removeChild!="function"||!(M.attributes instanceof m)||typeof M.removeAttribute!="function"||typeof M.setAttribute!="function"||typeof M.namespaceURI!="string"||typeof M.insertBefore!="function"||typeof M.hasChildNodes!="function")},$i=function(M){return typeof c=="function"&&M instanceof c};function Jt(ue,M,X){os(ue,ae=>{ae.call(t,M,X,$e)})}const zi=function(M){let X=null;if(Jt($.beforeSanitizeElements,M,null),xo(M))return vt(M),!0;const ae=we(M.nodeName);if(Jt($.uponSanitizeElement,M,{tagName:ae,allowedTags:K}),Pe&&M.hasChildNodes()&&!$i(M.firstElementChild)&&nt(/<[/\w!]/g,M.innerHTML)&&nt(/<[/\w!]/g,M.textContent)||M.nodeType===br.progressingInstruction||Pe&&M.nodeType===br.comment&&nt(/<[/\w]/g,M.data))return vt(M),!0;if(!(ee.tagCheck instanceof Function&&ee.tagCheck(ae))&&(!K[ae]||ce[ae])){if(!ce[ae]&&Bi(ae)&&(V.tagNameCheck instanceof RegExp&&nt(V.tagNameCheck,ae)||V.tagNameCheck instanceof Function&&V.tagNameCheck(ae)))return!1;if(ge&&!ut[ae]){const Ae=b(M)||M.parentNode,et=j(M)||M.childNodes;if(et&&Ae){const Fe=et.length;for(let pt=Fe-1;pt>=0;--pt){const en=g(et[pt],!0);en.__removalCount=(M.__removalCount||0)+1,Ae.insertBefore(en,w(M))}}}return vt(M),!0}return M instanceof l&&!yt(M)||(ae==="noscript"||ae==="noembed"||ae==="noframes")&&nt(/<\/no(script|embed|frames)/i,M.innerHTML)?(vt(M),!0):(fe&&M.nodeType===br.text&&(X=M.textContent,os([S,A,I],Ae=>{X=xr(X,Ae," ")}),M.textContent!==X&&(gr(t.removed,{element:M.cloneNode()}),M.textContent=X)),Jt($.afterSanitizeElements,M,null),!1)},Fi=function(M,X,ae){if(lt&&(X==="id"||X==="name")&&(ae in r||ae in Wn))return!1;if(!(q&&!F[X]&&nt(B,X))){if(!(pe&&nt(D,X))){if(!(ee.attributeCheck instanceof Function&&ee.attributeCheck(X,M))){if(!W[X]||F[X]){if(!(Bi(M)&&(V.tagNameCheck instanceof RegExp&&nt(V.tagNameCheck,M)||V.tagNameCheck instanceof Function&&V.tagNameCheck(M))&&(V.attributeNameCheck instanceof RegExp&&nt(V.attributeNameCheck,X)||V.attributeNameCheck instanceof Function&&V.attributeNameCheck(X,M))||X==="is"&&V.allowCustomizedBuiltInElements&&(V.tagNameCheck instanceof RegExp&&nt(V.tagNameCheck,ae)||V.tagNameCheck instanceof Function&&V.tagNameCheck(ae))))return!1}else if(!ke[X]){if(!nt(Z,xr(ae,P,""))){if(!((X==="src"||X==="xlink:href"||X==="href")&&M!=="script"&&uC(ae,"data:")===0&&re[M])){if(!(ne&&!nt(E,xr(ae,P,"")))){if(ae)return!1}}}}}}}return!0},Bi=function(M){return M!=="annotation-xml"&&Wo(M,z)},Ui=function(M){Jt($.beforeSanitizeAttributes,M,null);const{attributes:X}=M;if(!X||xo(M))return;const ae={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:W,forceKeepAttr:void 0};let Ae=X.length;for(;Ae--;){const et=X[Ae],{name:Fe,namespaceURI:pt,value:en}=et,Vn=we(Fe),yo=en;let Ye=Fe==="value"?yo:mC(yo);if(ae.attrName=Vn,ae.attrValue=Ye,ae.keepAttr=!0,ae.forceKeepAttr=void 0,Jt($.uponSanitizeAttribute,M,ae),Ye=ae.attrValue,te&&(Vn==="id"||Vn==="name")&&(tt(Fe,M),Ye=xe+Ye),Pe&&nt(/((--!?|])>)|<\/(style|title|textarea)/i,Ye)){tt(Fe,M);continue}if(Vn==="attributename"&&Wo(Ye,"href")){tt(Fe,M);continue}if(ae.forceKeepAttr)continue;if(!ae.keepAttr){tt(Fe,M);continue}if(!le&&nt(/\/>/i,Ye)){tt(Fe,M);continue}fe&&os([S,A,I],Vi=>{Ye=xr(Ye,Vi," ")});const Wi=we(M.nodeName);if(!Fi(Wi,Vn,Ye)){tt(Fe,M);continue}if(v&&typeof h=="object"&&typeof h.getAttributeType=="function"&&!pt)switch(h.getAttributeType(Wi,Vn)){case"TrustedHTML":{Ye=v.createHTML(Ye);break}case"TrustedScriptURL":{Ye=v.createScriptURL(Ye);break}}if(Ye!==yo)try{pt?M.setAttributeNS(pt,Fe,Ye):M.setAttribute(Fe,Ye),xo(M)?vt(M):ul(t.removed)}catch{tt(Fe,M)}}Jt($.afterSanitizeAttributes,M,null)},Kp=function ue(M){let X=null;const ae=Li(M);for(Jt($.beforeSanitizeShadowDOM,M,null);X=ae.nextNode();)Jt($.uponSanitizeShadowNode,X,null),zi(X),Ui(X),X.content instanceof a&&ue(X.content);Jt($.afterSanitizeShadowDOM,M,null)};return t.sanitize=function(ue){let M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},X=null,ae=null,Ae=null,et=null;if(pr=!ue,pr&&(ue="<!-->"),typeof ue!="string"&&!$i(ue))if(typeof ue.toString=="function"){if(ue=ue.toString(),typeof ue!="string")throw yr("dirty is not a string, aborting")}else throw yr("toString is not a function");if(!t.isSupported)return ue;if(qe||Je(M),t.removed=[],typeof ue=="string"&&(dt=!1),dt){if(ue.nodeName){const en=we(ue.nodeName);if(!K[en]||ce[en])throw yr("root node is forbidden and cannot be sanitized in-place")}}else if(ue instanceof c)X=go("<!---->"),ae=X.ownerDocument.importNode(ue,!0),ae.nodeType===br.element&&ae.nodeName==="BODY"||ae.nodeName==="HTML"?X=ae:X.appendChild(ae);else{if(!gt&&!fe&&!Ve&&ue.indexOf("<")===-1)return v&&zt?v.createHTML(ue):ue;if(X=go(ue),!X)return gt?null:zt?k:""}X&&He&&vt(X.firstChild);const Fe=Li(dt?ue:X);for(;Ae=Fe.nextNode();)zi(Ae),Ui(Ae),Ae.content instanceof a&&Kp(Ae.content);if(dt)return ue;if(gt){if(Ge)for(et=C.call(X.ownerDocument);X.firstChild;)et.appendChild(X.firstChild);else et=X;return(W.shadowroot||W.shadowrootmode)&&(et=O.call(s,et,!0)),et}let pt=Ve?X.outerHTML:X.innerHTML;return Ve&&K["!doctype"]&&X.ownerDocument&&X.ownerDocument.doctype&&X.ownerDocument.doctype.name&&nt(Rp,X.ownerDocument.doctype.name)&&(pt="<!DOCTYPE "+X.ownerDocument.doctype.name+`>
|
|
136
|
-
`+pt),fe&&os([S,A,I],en=>{pt=xr(pt,en," ")}),v&&zt?v.createHTML(pt):pt},t.setConfig=function(){let ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Je(ue),qe=!0},t.clearConfig=function(){$e=null,qe=!1},t.isValidAttribute=function(ue,M,X){$e||Je({});const ae=we(ue),Ae=we(M);return Fi(ae,Ae,X)},t.addHook=function(ue,M){typeof M=="function"&&gr($[ue],M)},t.removeHook=function(ue,M){if(M!==void 0){const X=lC($[ue],M);return X===-1?void 0:dC($[ue],X,1)[0]}return ul($[ue])},t.removeHooks=function(ue){$[ue]=[]},t.removeAllHooks=function(){$=xl()},t}var NC=Op();function Mp({faq:e,className:t,expanded:r,defaultExpanded:s=!1,onExpandedChange:o,showKeywords:a=!1,dangerouslySetAnswerHTML:i=!1}){const[c,l]=x.useState(s),d=r!==void 0,m=d?r:c,u=()=>{const p=!m;d||l(p),o?.(p)};return n.jsxs("div",{className:H("border border-neutral-200 rounded-lg overflow-hidden dark:border-neutral-800",t),children:[n.jsxs("button",{type:"button",onClick:u,className:H("w-full flex items-center justify-between px-4 py-3 text-left","bg-neutral-50 hover:bg-neutral-100 dark:bg-neutral-900 dark:hover:bg-neutral-800","transition-colors duration-150"),"aria-expanded":m,children:[n.jsx("span",{className:"font-medium text-neutral-900 dark:text-neutral-100 pr-4",children:e.question}),n.jsx("svg",{className:H("w-5 h-5 text-neutral-500 transition-transform duration-200 flex-shrink-0",m&&"rotate-180"),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),m&&n.jsxs("div",{className:"px-4 py-3 bg-white dark:bg-neutral-950",children:[i?n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 prose prose-sm dark:prose-invert max-w-none",dangerouslySetInnerHTML:{__html:NC.sanitize(e.answer,{ALLOWED_TAGS:["b","i","em","strong","a","p","br","ul","ol","li"],ALLOWED_ATTR:["href","target","rel"]})}}):n.jsx("p",{className:"text-sm text-neutral-600 dark:text-neutral-400 whitespace-pre-wrap",children:e.answer}),a&&e.keywords&&e.keywords.length>0&&n.jsx("div",{className:"mt-3 flex flex-wrap gap-1",children:e.keywords.map(p=>n.jsx("span",{className:"px-2 py-0.5 text-xs bg-neutral-100 text-neutral-600 rounded dark:bg-neutral-800 dark:text-neutral-400",children:p},p))})]})]})}function PC({faqs:e,className:t,accordion:r=!1,showKeywords:s=!1,dangerouslySetAnswerHTML:o=!1,emptyMessage:a="No FAQs available."}){const[i,c]=x.useState(null),l=e.filter(d=>d.active!==!1);return l.length===0?n.jsx("div",{className:H("text-center py-8 text-neutral-500 dark:text-neutral-400",t),children:a}):n.jsx("div",{className:H("space-y-2",t),children:l.map(d=>n.jsx(Mp,{faq:d,showKeywords:s,dangerouslySetAnswerHTML:o,expanded:r?i===d.id:void 0,onExpandedChange:r?m=>c(m?d.id:null):void 0},d.id))})}function Qe({amount:e,currency:t}){return new Intl.NumberFormat(void 0,{style:"currency",currency:t}).format(e)}function po({amount:e,currency:t,compareAt:r,className:s,size:o="default"}){const a=typeof r=="number"&&r>e;return n.jsxs("div",{className:H("flex items-baseline gap-2 tabular-nums",s),children:[n.jsx("span",{className:H("font-semibold",o==="sm"?"text-sm":"text-base"),children:Qe({amount:e,currency:t})}),a?n.jsx("span",{className:H("text-neutral-500 line-through dark:text-neutral-400",o==="sm"?"text-xs":"text-sm"),children:Qe({amount:r,currency:t})}):null]})}const AC={large:"aspect-[4/5]",square:"aspect-square",compact:"aspect-[3/4]"},EC={center:"object-center",top:"object-top",bottom:"object-bottom",left:"object-left",right:"object-right"};function Dp({product:e,href:t,onAddToCart:r,onQuickView:s,className:o,layout:a="large",imageCrop:i="center"}){const c=e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0,l=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:null;return n.jsxs(Rt,{className:H("group flex h-full flex-col overflow-hidden rounded-2xl",o),children:[n.jsxs("div",{className:"relative",children:[n.jsx("a",{href:t,className:"block","aria-label":`View ${e.title}`,children:n.jsx("div",{className:H("overflow-hidden bg-neutral-100 dark:bg-neutral-900",AC[a]),children:n.jsx("img",{src:e.images[0]?.url,alt:e.images[0]?.alt??e.title,className:H("h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]",EC[i]),loading:"lazy"})})}),a!=="compact"&&e.tags?.length?n.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 flex gap-1 p-3",children:e.tags.slice(0,2).map(d=>n.jsx(Pn,{className:"pointer-events-none bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:d},d))}):null,c?n.jsx("div",{className:"pointer-events-none absolute left-3 top-3",children:n.jsx(Pn,{variant:"secondary",className:"bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:"Out of stock"})}):l!=null&&l>0&&l<=5?n.jsx("div",{className:"pointer-events-none absolute left-3 top-3",children:n.jsxs(Pn,{variant:"secondary",className:"bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:["Only ",l," left"]})}):null,s?n.jsx("div",{className:"absolute right-3 top-3 opacity-0 transition-opacity group-hover:opacity-100",children:n.jsx(ie,{type:"button",size:"sm",variant:"secondary",className:"h-9",onClick:()=>s(e),children:"Quick view"})}):null]}),n.jsxs("div",{className:H("flex flex-1 flex-col",a==="compact"?"p-3":"p-4"),children:[n.jsx("div",{className:"flex items-start justify-between gap-3",children:n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:H("line-clamp-1 font-medium text-neutral-950 dark:text-neutral-50",a==="compact"?"text-xs":"text-sm"),children:e.title}),n.jsx("div",{className:"mt-1",children:n.jsx(po,{amount:e.price,currency:e.currency,compareAt:e.compareAtPrice,size:a==="compact"?"sm":"default"})})]})}),a==="large"&&n.jsx("p",{className:"mt-2 line-clamp-2 min-h-8 text-xs leading-4 text-neutral-600 dark:text-neutral-400",children:e.description}),n.jsx("div",{className:H("mt-auto",a==="compact"?"pt-3":"pt-4"),children:n.jsx(ie,{type:"button",className:"w-full",size:a==="compact"?"sm":"default",onClick:()=>r?.(e,null),disabled:c,children:c?"Out of stock":"Add to cart"})})]})]})}function fo({products:e,columns:t,onAddToCart:r,onQuickView:s,getProductHref:o,className:a,layout:i,imageCrop:c}){const l=t?.base??2,d=t?.md??3,m=t?.lg??3,u={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4"},p={1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4"},h={1:"lg:grid-cols-1",2:"lg:grid-cols-2",3:"lg:grid-cols-3",4:"lg:grid-cols-4"},_=H("grid gap-4",u[Math.min(4,Math.max(1,l))],p[Math.min(4,Math.max(1,d))],h[Math.min(4,Math.max(1,m))]);return n.jsx("div",{className:H(_,a),children:e.map(g=>n.jsx(Dp,{product:g,href:o?o(g):void 0,onAddToCart:r,onQuickView:s,layout:i,imageCrop:c},g.id))})}function Ni({images:e,className:t}){const[r,s]=x.useState(0),o=e[r];return e.length===0?n.jsx("div",{className:H("aspect-square w-full rounded-xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",t)}):n.jsxs("div",{className:H("space-y-3",t),children:[n.jsx("div",{className:"aspect-square overflow-hidden rounded-2xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:n.jsx("img",{src:o?.url,alt:o?.alt??"",className:"h-full w-full object-cover",loading:"eager"})}),e.length>1?n.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:e.map((a,i)=>{const c=i===r;return n.jsx("button",{type:"button",className:H("h-16 w-16 shrink-0 overflow-hidden rounded-lg border",c?"border-neutral-900 dark:border-neutral-50":"border-neutral-200 dark:border-neutral-800"),onClick:()=>s(i),"aria-label":`View image ${i+1}`,children:n.jsx("img",{src:a.url,alt:a.alt??"",className:"h-full w-full object-cover",loading:"lazy"})},a.url)})}):null]})}function TC(e){const t=new Set;for(const r of e)for(const s of Object.keys(r.options))t.add(s);return Array.from(t)}function IC(e,t){const r=new Set;for(const s of e){const o=s.options[t];o&&r.add(o)}return Array.from(r)}function yl(e,t){return e.find(r=>Object.entries(t).every(([s,o])=>r.options[s]===o))??null}function Lp(e){return e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0}function RC(e){return e.inventoryStatus==="low"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity>0&&e.inventoryQuantity<=5}function OC(e){const t=Lp(e),r=!t&&RC(e),s=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0;return{isOutOfStock:t,isLow:r,quantity:s}}function MC(e,t,r,s){const o={...t,[r]:s},a=e.filter(i=>Object.entries(o).every(([c,l])=>i.options[c]===l));return a.length===0?!1:a.some(i=>!Lp(i))}function Pi({product:e,value:t,onChange:r,className:s,showInventory:o=!0,disableOutOfStock:a=!1}){const i=x.useMemo(()=>e.variants??[],[e.variants]),c=x.useMemo(()=>TC(i),[i]),l=x.useMemo(()=>yl(i,t.selectedOptions),[i,t.selectedOptions]),d=x.useMemo(()=>l?OC(l):null,[l]);return i.length===0||c.length===0?null:n.jsxs("div",{className:H("space-y-4",s),children:[c.map(m=>{const u=IC(i,m),p=t.selectedOptions[m];return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-baseline justify-between",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-950 dark:text-neutral-50",children:m}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:p||"Select"})]}),n.jsx("div",{className:"flex flex-wrap gap-2",children:u.map(h=>{const _=h===p,g=MC(i,t.selectedOptions,m,h),f=a&&!g;return n.jsxs(ie,{type:"button",size:"sm",variant:_?"default":"outline",onClick:()=>{const w={...t.selectedOptions,[m]:h},j=yl(i,w);r({selectedOptions:w,variant:j})},"aria-pressed":_,disabled:f,className:H(!g&&!f&&"opacity-50 line-through"),children:[h,!g&&!f&&n.jsx("span",{className:"ml-1 text-[10px] opacity-70",children:"(Out)"})]},h)})})]},m)}),o&&l&&d&&n.jsx("div",{className:"pt-2",children:d.isOutOfStock?n.jsx("div",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:"Out of stock"}):d.isLow&&d.quantity!==void 0?n.jsxs("div",{className:"text-sm text-amber-600 dark:text-amber-400",children:["Only ",n.jsx("span",{className:"font-semibold",children:d.quantity})," left"]}):null})]})}function Ai({qty:e,onChange:t,min:r=1,max:s,className:o}){const a=Number.isFinite(e)?Math.max(r,Math.floor(e)):r,i=a>r,c=typeof s=="number"?a<s:!0;return n.jsxs("div",{className:H("flex items-center gap-2",o),children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(Math.max(r,a-1)),disabled:!i,"aria-label":"Decrease quantity",children:"-"}),n.jsx(Be,{inputMode:"numeric",pattern:"[0-9]*",value:String(a),onChange:l=>{const d=Math.floor(Number(l.target.value));if(!Number.isFinite(d))return;const m=Math.max(r,typeof s=="number"?Math.min(s,d):d);t(m)},className:"h-10 w-16 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(a+1),disabled:!c,"aria-label":"Increase quantity",children:"+"})]})}function Ei({product:e,open:t,onOpenChange:r,productHref:s,onAddToCart:o,className:a}){const[i,c]=x.useState(1),[l,d]=x.useState({selectedOptions:{},variant:null});if(x.useEffect(()=>{if(e)if(c(1),e.variants?.length){const p=e.variants[0];d({selectedOptions:{...p.options},variant:p})}else d({selectedOptions:{},variant:null})},[e?.id]),!e)return null;const m=l.variant?.price??e.price,u=l.variant?.compareAtPrice??e.compareAtPrice;return n.jsx(pi,{open:t,onOpenChange:r,children:n.jsxs(eo,{className:H("max-w-3xl",a),children:[n.jsx(hi,{children:n.jsxs(to,{className:"flex items-center justify-between gap-3",children:[n.jsx("span",{className:"truncate",children:e.title}),s?n.jsx("a",{href:s(e.slug),className:"text-sm font-normal text-neutral-700 hover:underline dark:text-neutral-300",children:"View details"}):null]})}),n.jsxs("div",{className:"grid gap-8 md:grid-cols-2",children:[n.jsx(Ni,{images:e.images}),n.jsxs("div",{className:"space-y-5",children:[n.jsxs("div",{children:[n.jsx(po,{amount:m,currency:e.currency,compareAt:u}),n.jsx("p",{className:"mt-3 text-sm text-neutral-600 dark:text-neutral-400",children:e.description})]}),n.jsx(Pi,{product:e,value:{selectedOptions:l.selectedOptions,variantId:l.variant?.id},onChange:p=>d(p)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(Ai,{qty:i,onChange:c}),n.jsx(ie,{type:"button",className:"flex-1",onClick:()=>{o(e,l.variant,i),r(!1)},children:"Add to cart"})]}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:e.inventoryStatus==="out_of_stock"?"Out of stock":"In stock"})]})]})]})})}function wa({categories:e,activeSlug:t,onSelect:r,className:s}){return n.jsx("nav",{className:H("space-y-1",s),"aria-label":"Categories",children:e.map(o=>{const a=t===o.slug;return n.jsxs("button",{type:"button",className:H("flex w-full items-center justify-between rounded-md px-3 py-2 text-sm transition-colors",a?"bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900":"text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"),onClick:()=>r?.(o),"aria-current":a?"page":void 0,children:[n.jsx("span",{className:"truncate",children:o.name}),n.jsx("span",{className:"text-xs opacity-70",children:"›"})]},o.id)})})}function Ti({items:e,className:t}){return n.jsx("nav",{className:H("flex items-center gap-2 text-xs text-neutral-600 dark:text-neutral-400",t),"aria-label":"Breadcrumb",children:e.map((r,s)=>n.jsxs("span",{className:"flex items-center gap-2",children:[r.href?n.jsx("a",{href:r.href,className:"hover:underline",children:r.label}):n.jsx("span",{className:"text-neutral-900 dark:text-neutral-50",children:r.label}),s<e.length-1?n.jsx("span",{"aria-hidden":!0,children:"·"}):null]},`${r.label}-${s}`))})}function Ii({value:e,onChange:t,placeholder:r="Search products…",className:s}){return n.jsxs("div",{className:H("relative",s),children:[n.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-3 flex items-center text-neutral-500 dark:text-neutral-400","aria-hidden":!0,children:"⌕"}),n.jsx(Be,{value:e,onChange:o=>t(o.target.value),placeholder:r,className:"pl-9","aria-label":"Search"})]})}function Ts({facets:e,value:t,onChange:r,onClear:s,className:o,enabledFilters:a}){const i=e.tags??[],c=new Set(t.tags??[]),l=a?.tags??!0,d=a?.priceRange??!0,m=a?.inStock??!0;return l||d||m?n.jsxs("div",{className:H("space-y-4",o),children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Filters"}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-8 px-2 text-xs",onClick:s,children:"Clear"})]}),n.jsx(St,{}),l&&i.length?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Tags"}),n.jsx("div",{className:"space-y-2",children:i.map(p=>n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:c.has(p),onChange:h=>{const _=new Set(c);h.target.checked?_.add(p):_.delete(p),r({...t,tags:Array.from(_)})}}),p]},p))})]}):null,d&&e.price?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Price"}),n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-1",children:[n.jsx(at,{className:"text-xs",htmlFor:"price-min",children:"Min"}),n.jsx(Be,{id:"price-min",inputMode:"decimal",placeholder:String(e.price.min),value:t.priceMin??"",onChange:p=>{const h=Number(p.target.value);r({...t,priceMin:Number.isFinite(h)&&p.target.value!==""?h:void 0})}})]}),n.jsxs("div",{className:"grid gap-1",children:[n.jsx(at,{className:"text-xs",htmlFor:"price-max",children:"Max"}),n.jsx(Be,{id:"price-max",inputMode:"decimal",placeholder:String(e.price.max),value:t.priceMax??"",onChange:p=>{const h=Number(p.target.value);r({...t,priceMax:Number.isFinite(h)&&p.target.value!==""?h:void 0})}})]})]})]}):null,m?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Availability"}),n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:t.inStock??!1,onChange:p=>r({...t,inStock:p.target.checked})}),"In stock"]})]}):null]}):null}function vl(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}function DC(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("path",{d:"M3 6h18"}),n.jsx("path",{d:"M8 6V4h8v2"}),n.jsx("path",{d:"M6 6l1 16h10l1-16"}),n.jsx("path",{d:"M10 11v6"}),n.jsx("path",{d:"M14 11v6"})]})}function Ri({item:e,onRemove:t,onSetQty:r,variant:s="table",className:o,inventory:a}){const i=e.unitPrice*e.qty,[c,l]=x.useState(!1),d=x.useMemo(()=>{if(a?.availableQty)return a.availableQty},[a?.availableQty]),m=!a?.isOutOfStock&&(d===void 0||e.qty<d),u=x.useMemo(()=>a?a.isOutOfStock?{type:"error",message:a.message||"Out of stock"}:a.exceedsAvailable?{type:"warning",message:a.message||"Quantity exceeds available stock"}:a.isLowStock?{type:"info",message:a.message||"Low stock"}:null:null,[a]);return x.useEffect(()=>{c&&e.qty!==1&&l(!1)},[c,e.qty]),s==="compact"?n.jsxs("div",{className:H("flex items-start gap-3",o),children:[n.jsx("div",{className:"h-12 w-12 shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:e.imageSnapshot?n.jsx("img",{src:e.imageSnapshot,alt:e.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"truncate text-sm font-medium text-neutral-950 dark:text-neutral-50",children:e.titleSnapshot}),n.jsx("div",{className:"mt-0.5 text-xs tabular-nums text-neutral-600 dark:text-neutral-400",children:Qe({amount:i,currency:e.currency})}),u&&n.jsxs("div",{className:H("mt-1 flex items-center gap-1 text-[11px]",u.type==="error"&&"text-red-600 dark:text-red-400",u.type==="warning"&&"text-amber-600 dark:text-amber-400",u.type==="info"&&"text-blue-600 dark:text-blue-400"),children:[n.jsx(vl,{className:"h-3 w-3 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsx("div",{className:"flex h-12 w-[140px] shrink-0 items-center justify-end",children:c?n.jsxs("div",{className:"flex w-full flex-col items-center justify-center gap-2",children:[n.jsx("div",{className:"text-center text-[11px] font-medium leading-none text-neutral-600 dark:text-neutral-400",children:"Remove item?"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",variant:"outline",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:()=>l(!1),children:"Cancel"}),n.jsx(ie,{type:"button",variant:"destructive",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:t,children:"Confirm"})]})]}):n.jsxs("div",{className:"flex items-center justify-end gap-1.5 whitespace-nowrap",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":e.qty===1?"Remove item":"Decrease quantity",onClick:()=>{if(e.qty===1){l(!0);return}r(e.qty-1)},children:e.qty===1?n.jsx(DC,{className:"h-4 w-4"}):"-"}),n.jsx(Be,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const h=Math.floor(Number(p.target.value));if(!Number.isFinite(h))return;const _=Math.max(1,d?Math.min(d,h):h);r(_)},className:"h-8 w-11 px-2 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]})})]})})]}):n.jsxs("div",{className:H("grid grid-cols-[64px_1fr] items-start gap-x-4 gap-y-3 sm:grid-cols-[64px_1fr_176px_120px]",o),children:[n.jsx("div",{className:"h-16 w-16 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:e.imageSnapshot?n.jsx("img",{src:e.imageSnapshot,alt:e.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsxs("div",{className:"col-start-2 row-start-1 min-w-0",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsx("div",{className:"truncate text-sm font-medium text-neutral-950 dark:text-neutral-50",children:e.titleSnapshot}),n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50 sm:hidden",children:Qe({amount:i,currency:e.currency})})]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[Qe({amount:e.unitPrice,currency:e.currency})," each"]}),u&&n.jsxs("div",{className:H("mt-1.5 flex items-center gap-1 text-xs",u.type==="error"&&"text-red-600 dark:text-red-400",u.type==="warning"&&"text-amber-600 dark:text-amber-400",u.type==="info"&&"text-blue-600 dark:text-blue-400"),children:[n.jsx(vl,{className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsxs("div",{className:"col-span-2 col-start-1 row-start-2 flex items-center justify-between gap-3 sm:col-span-1 sm:col-start-3 sm:row-start-1 sm:justify-center",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Decrease quantity",onClick:()=>r(Math.max(1,e.qty-1)),children:"-"}),n.jsx(Be,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const h=Math.floor(Number(p.target.value));if(!Number.isFinite(h))return;const _=Math.max(1,d?Math.min(d,h):h);r(_)},className:"h-9 w-14 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-9 px-2 text-xs text-red-600 dark:text-red-400 sm:hidden",onClick:t,children:"Remove"})]}),n.jsxs("div",{className:"hidden sm:col-start-4 sm:row-start-1 sm:flex sm:flex-col sm:items-center sm:text-center",children:[n.jsx("div",{className:"text-sm font-semibold tabular-nums text-neutral-950 dark:text-neutral-50",children:Qe({amount:i,currency:e.currency})}),n.jsx(ie,{type:"button",variant:"ghost",className:"mt-1 h-8 px-2 text-xs text-red-600 dark:text-red-400",onClick:t,children:"Remove"})]})]})}function Oi({currency:e,subtotal:t,itemCount:r,onCheckout:s,isCheckoutDisabled:o,checkoutDisabledReason:a,onRemoveUnavailable:i,className:c}){return n.jsxs("div",{className:H("space-y-4",c),children:[n.jsx(St,{}),n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsxs("div",{className:"flex items-center gap-2 text-neutral-600 dark:text-neutral-400",children:[n.jsx("span",{children:"Subtotal"}),typeof r=="number"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-neutral-300 dark:text-neutral-700",children:"·"}),n.jsxs("span",{className:"tabular-nums",children:[r," item",r===1?"":"s"]})]}):null]}),n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:t,currency:e})})]}),n.jsx(ie,{type:"button",onClick:s,disabled:o,className:"w-full",children:"Checkout"}),o&&a&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-center text-xs text-amber-600 dark:text-amber-400",children:a}),i&&n.jsx("button",{type:"button",onClick:i,className:"mx-auto block text-xs text-neutral-500 underline underline-offset-2 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-300",children:"Remove unavailable items"})]})]})}function $p({onCheckout:e,className:t}){const{config:r}=Re(),s=Dt(),{getItemInventory:o,hasIssues:a}=Za({items:s.items,refreshInterval:3e4,skip:s.items.length===0}),i=()=>{for(const c of s.items){const l=o(c.productId,c.variantId);(l?.isOutOfStock||l?.exceedsAvailable)&&s.removeItem(c.productId,c.variantId)}};return s.items.length===0?n.jsx(tr,{title:"Cart is empty",description:"Add items from the catalog to check out.",className:t}):n.jsxs("div",{className:H("flex h-full flex-col rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-800 dark:bg-neutral-950",t),children:[n.jsx("div",{className:"-mr-4 min-h-0 flex-1 overflow-y-auto overflow-x-hidden pr-4",children:n.jsx("div",{className:"divide-y divide-neutral-200 dark:divide-neutral-800",children:s.items.map(c=>n.jsx("div",{className:"py-3",children:n.jsx(Ri,{variant:"compact",item:c,onRemove:()=>s.removeItem(c.productId,c.variantId),onSetQty:l=>s.setQty(c.productId,c.variantId,l),inventory:o(c.productId,c.variantId)})},`${c.productId}::${c.variantId??""}`))})}),n.jsx("div",{className:"mt-4 space-y-4",children:n.jsx(Oi,{currency:r.currency,subtotal:s.subtotal,itemCount:s.count,onCheckout:e,isCheckoutDisabled:s.items.length===0||a,checkoutDisabledReason:a?"Some items have inventory issues":void 0,onRemoveUnavailable:a?i:void 0})})]})}const zp=x.forwardRef(({className:e,...t},r)=>n.jsx("textarea",{ref:r,className:H("flex min-h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm transition-colors placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-50/20",e),...t}));zp.displayName="Textarea";function LC(){const[e,t]=x.useState(!1);return x.useEffect(()=>{const r=window.matchMedia?.("(prefers-reduced-motion: reduce)");if(!r)return;const s=()=>t(r.matches);return s(),r.addEventListener?.("change",s),()=>r.removeEventListener?.("change",s)},[]),e}function bl({children:e,className:t}){const r=x.useRef(null),s=LC();return x.useEffect(()=>{const o=r.current;!o||s||o.animate([{opacity:0,transform:"translateY(6px)"},{opacity:1,transform:"translateY(0px)"}],{duration:180,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)",fill:"both"})},[s]),n.jsx("div",{ref:r,className:t,children:e})}function Go(){return`${Date.now()}_${Math.random().toString(16).slice(2)}`}function $C({className:e}){const[t,r]=x.useState(""),[s,o]=x.useState(!1),[a,i]=x.useState(()=>[{id:Go(),role:"agent",text:"Hi! How can we help today? We can recommend products or answer support questions.",createdAt:Date.now()}]),[c,l]=x.useState("…");x.useEffect(()=>{if(!s)return;const h=[".","..","..."];let _=0;const g=window.setInterval(()=>{_=(_+1)%h.length,l(h[_])},450);return()=>window.clearInterval(g)},[s]);const d=x.useRef(null),m=x.useRef(null);x.useEffect(()=>{const h=d.current;h&&(h.scrollTop=h.scrollHeight)},[a.length]);const u=x.useCallback(()=>{const h=m.current;if(!h)return;const _=120;h.style.height="0px";const g=Math.min(_,Math.max(40,h.scrollHeight));h.style.height=`${g}px`,h.style.overflowY=h.scrollHeight>_?"auto":"hidden"},[]);x.useEffect(()=>{u()},[t,u]);const p=x.useCallback(()=>{const h=t.trim();h&&(i(_=>[..._,{id:Go(),role:"user",text:h,createdAt:Date.now()}]),r(""),o(!0),window.setTimeout(()=>{i(_=>[..._,{id:Go(),role:"agent",text:"Got it. Want recommendations, sizing help, or help with an order?",createdAt:Date.now()}]),o(!1)},450))},[t]);return n.jsxs("div",{className:H("flex h-full min-h-0 flex-col",e),children:[n.jsxs("div",{ref:d,className:"min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain rounded-2xl border border-neutral-200 bg-white p-4 dark:border-neutral-800 dark:bg-neutral-950",children:[a.map(h=>n.jsx(bl,{className:H("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsx("div",{className:H("max-w-[85%] rounded-2xl px-3 py-2 text-sm leading-5",h.role==="user"?"bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900":"bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50"),children:n.jsx("span",{className:"whitespace-pre-wrap break-words",children:h.text})})},h.id)),s?n.jsx(bl,{className:"flex justify-start",children:n.jsx("div",{className:"max-w-[85%] rounded-2xl bg-neutral-100 px-3 py-2 text-sm leading-5 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",children:c})}):null]}),n.jsxs("div",{className:"mt-3 flex shrink-0 items-end gap-2",children:[n.jsx(zp,{ref:m,rows:1,value:t,onChange:h=>r(h.target.value),placeholder:"Type a message…",className:"max-h-[120px] resize-none",onKeyDown:h=>{h.key==="Enter"&&(h.shiftKey||(h.preventDefault(),p()))}}),n.jsx(ie,{type:"button",onClick:p,disabled:!t.trim(),className:"h-10 shrink-0",children:"Send"})]})]})}function $r({trigger:e,side:t="right",open:r,onOpenChange:s,onCheckout:o,preferredTab:a,className:i}){const[c,l]=x.useState(a??"cart");return x.useEffect(()=>{r&&l(a??"cart")},[r,a]),n.jsxs(no,{modal:!1,open:r,onOpenChange:s,children:[e?n.jsx(ro,{asChild:!0,children:e}):null,n.jsxs(Fr,{side:t,overlayClassName:t==="popup"?"pointer-events-none bg-transparent backdrop-blur-none":"pointer-events-none bg-neutral-950/40 backdrop-blur-none",className:H(t==="bottom"?"h-[85vh] rounded-t-2xl":void 0,t==="popup"?"shadow-xl":"w-full sm:max-w-md",t==="popup"?"h-[min(640px,calc(100vh-2rem))]":void 0,t==="popup"?void 0:"p-4","flex flex-col overflow-hidden",i),children:[n.jsx(so,{className:"space-y-0",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx(Si,{value:c,onValueChange:d=>l(d),children:n.jsxs(uo,{className:"h-9",children:[n.jsx(Lr,{value:"cart",className:"text-sm",children:"Cart"}),n.jsx(Lr,{value:"chat",className:"text-sm",children:"Chat"})]})}),n.jsx(Um,{asChild:!0,children:n.jsx(ie,{type:"button",size:"icon",variant:"ghost",className:"h-9 w-9 rounded-full text-lg leading-none","aria-label":"Close cart",children:"X"})})]})}),n.jsx("div",{className:"mt-3 min-h-0 flex-1 overflow-hidden",children:c==="chat"?n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Get help finding a product or ask us any questions. We’re both your shopping assistant and support chat."}),n.jsx("div",{className:"mt-3 min-h-0 flex-1",children:n.jsx($C,{className:"h-full"})})]}):n.jsx($p,{onCheckout:()=>{o(),s?.(!1)},className:"h-full border-0 bg-transparent p-0 shadow-none"})})]})]})}function Mi({value:e,onApply:t,className:r}){const[s,o]=x.useState(e??"");return x.useEffect(()=>{o(e??"")},[e]),n.jsxs("div",{className:H("space-y-2",r),children:[n.jsx("div",{className:"text-sm font-medium text-neutral-950 dark:text-neutral-50",children:"Promo code"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Be,{value:s,onChange:a=>o(a.target.value),placeholder:"SAVE10","aria-label":"Promo code"}),n.jsx(ie,{type:"button",variant:"outline",onClick:()=>t(s.trim()||void 0),children:"Apply"})]})]})}function Fp({onCheckout:e,showPromoCode:t,className:r}){const{config:s}=Re(),o=Dt(),{getItemInventory:a,hasIssues:i}=Za({items:o.items,refreshInterval:3e4,skip:o.items.length===0}),c=()=>{for(const l of o.items){const d=a(l.productId,l.variantId);(d?.isOutOfStock||d?.exceedsAvailable)&&o.removeItem(l.productId,l.variantId)}};return o.items.length===0?n.jsx(tr,{title:"Your cart is empty",description:"Add a few products and come back here when you're ready to check out.",className:r}):n.jsxs("div",{className:H("grid items-start gap-6 lg:grid-cols-[1fr_360px]",r),children:[n.jsxs("div",{className:"self-start rounded-2xl border border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsxs("div",{className:"hidden grid-cols-[64px_1fr_176px_120px] gap-x-4 px-5 py-3 text-xs font-medium text-neutral-500 dark:text-neutral-400 sm:grid",children:[n.jsx("div",{}),n.jsx("div",{children:"Item"}),n.jsx("div",{className:"text-center",children:"Qty"}),n.jsx("div",{className:"text-center",children:"Total"})]}),n.jsx("div",{className:"divide-y divide-neutral-200 dark:divide-neutral-800",children:o.items.map(l=>n.jsx("div",{className:"px-4 py-4 sm:px-5",children:n.jsx(Ri,{item:l,onRemove:()=>o.removeItem(l.productId,l.variantId),onSetQty:d=>o.setQty(l.productId,l.variantId,d),inventory:a(l.productId,l.variantId)})},`${l.productId}::${l.variantId??""}`))})]}),n.jsx("div",{className:"lg:sticky lg:top-24 self-start",children:n.jsxs("div",{className:"rounded-2xl border border-neutral-200 bg-white p-5 shadow-sm dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Summary"}),n.jsx(St,{className:"my-4"}),n.jsxs("div",{className:"space-y-4",children:[t?n.jsx(Mi,{value:o.promoCode,onApply:o.setPromoCode}):null,n.jsx(Oi,{currency:s.currency,subtotal:o.subtotal,onCheckout:e,isCheckoutDisabled:o.items.length===0||i,checkoutDisabledReason:i?"Some items have inventory issues":void 0,onRemoveUnavailable:i?c:void 0})]})]})})]})}function Bp({left:e,right:t,className:r}){return n.jsxs("div",{className:H("grid items-start gap-8 lg:grid-cols-[1fr_420px]",r),children:[n.jsx("div",{children:e}),n.jsx("div",{children:t})]})}function _a({title:e,value:t,onChange:r,errors:s,className:o}){return n.jsxs("section",{className:H("space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",o),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:e}),n.jsxs("div",{className:"grid gap-3",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-line1`,children:"Address line 1"}),n.jsx(Be,{id:`${e}-line1`,value:t.line1,onChange:a=>r({...t,line1:a.target.value}),"aria-invalid":!!s?.line1}),s?.line1?n.jsx("div",{className:"text-xs text-red-600",children:s.line1}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-line2`,children:"Address line 2"}),n.jsx(Be,{id:`${e}-line2`,value:t.line2??"",onChange:a=>r({...t,line2:a.target.value})})]}),n.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-city`,children:"City"}),n.jsx(Be,{id:`${e}-city`,value:t.city,onChange:a=>r({...t,city:a.target.value}),"aria-invalid":!!s?.city}),s?.city?n.jsx("div",{className:"text-xs text-red-600",children:s.city}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-state`,children:"State"}),n.jsx(Be,{id:`${e}-state`,value:t.state??"",onChange:a=>r({...t,state:a.target.value})})]})]}),n.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-postal`,children:"Postal code"}),n.jsx(Be,{id:`${e}-postal`,value:t.postalCode,onChange:a=>r({...t,postalCode:a.target.value}),"aria-invalid":!!s?.postalCode}),s?.postalCode?n.jsx("div",{className:"text-xs text-red-600",children:s.postalCode}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-country`,children:"Country"}),n.jsx(Be,{id:`${e}-country`,value:t.country,onChange:a=>r({...t,country:a.target.value}),"aria-invalid":!!s?.country}),s?.country?n.jsx("div",{className:"text-xs text-red-600",children:s.country}):null]})]})]})]})}function Up({methods:e,value:t,onChange:r,currency:s,className:o}){return e.length===0?null:n.jsxs("section",{className:H("space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",o),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Shipping method"}),n.jsx("div",{className:"space-y-2",children:e.map(a=>{const i=a.id===t;return n.jsxs(ie,{type:"button",variant:i?"default":"outline",className:"h-auto w-full justify-between px-4 py-3",onClick:()=>r(a.id),"aria-pressed":i,children:[n.jsxs("div",{className:"text-left",children:[n.jsx("div",{className:"text-sm font-medium",children:a.label}),a.detail?n.jsx("div",{className:"text-xs opacity-80",children:a.detail}):null]}),n.jsx("div",{className:"text-sm font-semibold",children:Qe({amount:a.price,currency:a.currency||s})})]},a.id)})})]})}function Qo({message:e}){return e?n.jsx("div",{className:"text-xs text-red-600",children:e}):null}function Wp({className:e}){const{config:t}=Re(),r=$s(),s=Dt(),o=t.checkout.mode,a=x.useMemo(()=>cs(s.items,{requireEmail:t.checkout.requireEmail??!0,defaultMode:o,allowShipping:t.checkout.allowShipping??!1}),[s.items,t.checkout.allowShipping,t.checkout.requireEmail,o]),i=(t.checkout.allowShipping??!1)&&a.shippingAddress&&(o==="shipping"||o==="full"),c=a.email!=="none"||a.name!=="none"||a.phone!=="none",l={line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"},d=r.values.shippingAddress??l,m=r.values.billingAddress??l,u=Bd({enabled:!!t.adapter.getShippingMethods&&i,customer:{email:r.values.email||void 0,name:r.values.name||void 0,shippingAddress:d}});return n.jsxs("form",{className:H("space-y-6",e),onSubmit:p=>p.preventDefault(),children:[a.isDigitalOnly?n.jsx(Rt,{className:"rounded-2xl",children:n.jsxs(Gt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Digital delivery"}),n.jsx("div",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:a.fulfillmentNotes||"This is a digital product and will be available from your account after purchase."})]})}):null,a.hasPhysical&&!(t.checkout.allowShipping??!1)?n.jsx(Rt,{className:"rounded-2xl border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/30",children:n.jsxs(Gt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-red-900 dark:text-red-200",children:"Shipping required"}),n.jsx("div",{className:"mt-1 text-sm text-red-800/90 dark:text-red-200/80",children:"Your cart contains shippable items, but shipping is disabled for this checkout."})]})}):null,c?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Contact"}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:a.email==="required"||a.name==="required"||a.phone==="required"?"Required":"Optional"})]}),n.jsxs("div",{className:"grid gap-3",children:[a.email!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-email",children:"Email"}),n.jsx(Be,{id:"checkout-email",value:r.values.email??"",onChange:p=>r.setField("email",p.target.value),placeholder:"you@company.com","aria-invalid":!!r.fieldErrors.email,required:a.email==="required"}),n.jsx(Qo,{message:r.fieldErrors.email})]}):null,a.name!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-name",children:"Name"}),n.jsx(Be,{id:"checkout-name",value:r.values.name??"",onChange:p=>r.setField("name",p.target.value),placeholder:"Full name","aria-invalid":!!r.fieldErrors.name,required:a.name==="required"}),n.jsx(Qo,{message:r.fieldErrors.name})]}):null,a.phone!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-phone",children:"Phone"}),n.jsx(Be,{id:"checkout-phone",value:r.values.phone??"",onChange:p=>r.setField("phone",p.target.value),placeholder:"Phone number","aria-invalid":!!r.fieldErrors.phone,required:a.phone==="required"}),n.jsx(Qo,{message:r.fieldErrors.phone})]}):null]})]}):null,i?n.jsx(_a,{title:"Shipping address",value:d,onChange:p=>r.setField("shippingAddress",p),errors:{line1:r.fieldErrors["shippingAddress.line1"],city:r.fieldErrors["shippingAddress.city"],postalCode:r.fieldErrors["shippingAddress.postalCode"],country:r.fieldErrors["shippingAddress.country"]}}):null,i&&u.methods.length?n.jsx(Up,{methods:u.methods,value:r.values.shippingMethodId,onChange:p=>r.setField("shippingMethodId",p),currency:t.currency}):null,o==="full"?n.jsx(_a,{title:"Billing address",value:m,onChange:p=>r.setField("billingAddress",p)}):null,t.checkout.allowTipping?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Tip"}),n.jsxs("div",{className:"grid gap-2",children:[n.jsxs(at,{htmlFor:"checkout-tip",children:["Tip amount (",t.currency,")"]}),n.jsx(Be,{id:"checkout-tip",inputMode:"decimal",value:String(r.values.tipAmount??0),onChange:p=>r.setField("tipAmount",Number(p.target.value)||0)})]})]}):null,o==="full"?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Notes"}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-notes",children:"Order notes (optional)"}),n.jsx(Be,{id:"checkout-notes",value:r.values.notes??"",onChange:p=>r.setField("notes",p.target.value),placeholder:"Delivery instructions, gift note…"})]})]}):null]})}function Vp(){if(typeof window>"u")return!1;const e=window,t=["phantom","solflare","backpack","glow","slope","sollet","coin98","clover","mathWallet","ledger","torus","walletconnect"];for(const r of t){const s=e[r];if(s&&typeof s=="object"&&"solana"in s&&s.solana)return!0}return!!e.solana}const zC=Object.freeze(Object.defineProperty({__proto__:null,detectSolanaWallets:Vp},Symbol.toStringTag,{value:"Module"}));function FC(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}function BC(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("path",{d:"M3 6h18"}),n.jsx("path",{d:"M8 6V4h8v2"}),n.jsx("path",{d:"M6 6l1 16h10l1-16"})]})}function qp({open:e,onOpenChange:t,issues:r,onRemoveItem:s,onUpdateQuantity:o,onGoToCart:a,className:i}){const c=r.some(l=>l.type==="out_of_stock"||l.type==="product_unavailable");return n.jsx(pi,{open:e,onOpenChange:t,children:n.jsxs(eo,{className:H("sm:max-w-lg",i),children:[n.jsxs(hi,{children:[n.jsxs(to,{className:"flex items-center gap-2",children:[n.jsx(FC,{className:"h-5 w-5 text-amber-500"}),"Inventory Update"]}),n.jsx(gi,{children:c?"Some items in your cart are no longer available.":"Some items in your cart have limited availability."})]}),n.jsx("div",{className:"my-4 divide-y divide-neutral-200 dark:divide-neutral-800",children:r.map(l=>n.jsx(UC,{issue:l,onRemove:()=>s(l.productId,l.variantId),onUpdateQty:d=>o(l.productId,l.variantId,d)},`${l.productId}::${l.variantId??""}`))}),n.jsxs(Bm,{className:"flex-col gap-2 sm:flex-row",children:[a?n.jsx(ie,{type:"button",variant:"outline",onClick:()=>{t(!1),a()},children:"Go to Cart"}):null,n.jsx(ie,{type:"button",onClick:()=>t(!1),children:"Continue"})]})]})})}function UC({issue:e,onRemove:t,onUpdateQty:r}){const s=e.type==="out_of_stock"||e.type==="product_unavailable";return n.jsxs("div",{className:"flex items-start gap-3 py-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-900 dark:text-neutral-100",children:e.title}),n.jsx("div",{className:H("mt-0.5 text-sm",s?"text-red-600 dark:text-red-400":"text-amber-600 dark:text-amber-400"),children:e.message}),e.type==="insufficient_stock"&&e.availableQty>0?n.jsxs("div",{className:"mt-1 text-xs text-neutral-500 dark:text-neutral-400",children:["You requested ",e.requestedQty,", but only ",e.availableQty," available"]}):null]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.type==="insufficient_stock"&&e.availableQty>0?n.jsxs(ie,{type:"button",size:"sm",variant:"outline",onClick:()=>r(e.availableQty),children:["Update to ",e.availableQty]}):null,n.jsxs(ie,{type:"button",size:"sm",variant:"ghost",className:"text-red-600 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-950/30 dark:hover:text-red-300",onClick:t,children:[n.jsx(BC,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Remove"})]})]})]})}function Hp({className:e,ctaLabel:t,renderEmbedded:r,embeddedFallback:s,renderCustom:o,customFallback:a}){const{config:i}=Re(),c=Dt(),l=$s(),{config:d,isLoading:m}=Wd(),[u,p]=x.useState(!1);x.useEffect(()=>{p(Vp())},[]);const h=Ud({items:c.items}),[_,g]=x.useState(!1),f=x.useMemo(()=>i.checkout.paymentMethods&&i.checkout.paymentMethods.length?i.checkout.paymentMethods:[{id:"card",label:"Card",ctaLabel:"Pay now"}],[i.checkout.paymentMethods]),w=x.useMemo(()=>f.filter(A=>!(A.id==="card"&&!d.card||A.id==="crypto"&&!d.crypto||A.id==="credits"&&!d.credits||A.id==="crypto"&&!u)),[u,f,d]),[j,b]=x.useState((w[0]??f[0]).id);x.useEffect(()=>{w.length&&(w.some(S=>S.id===j)||b(w[0].id))},[j,w]),x.useEffect(()=>{l.reset()},[j]);const v=w.find(S=>S.id===j)??f.find(S=>S.id===j)??f[0],k=v.description??(j==="crypto"?"Pay using a connected wallet.":void 0),R=j==="crypto"&&!u,N=m||l.status==="validating"||l.status==="creating_session"||l.status==="redirecting"||h.isVerifying,C=t??v.ctaLabel??(i.checkout.mode==="none"?"Continue to payment":"Pay now"),T=x.useCallback(async S=>{const A=await h.verify();if(!A.ok&&A.issues.length>0){g(!0);return}l.createCheckoutSession({paymentMethodId:S})},[l,h]),O=l.session?.kind==="embedded"?l.session:null,$=l.session?.kind==="custom"?l.session:null;return n.jsxs("div",{className:H("space-y-3",e),children:[w.length>1?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs font-medium text-neutral-600 dark:text-neutral-400",children:"Payment method"}),n.jsx(Si,{value:j,onValueChange:b,children:n.jsx(uo,{className:"w-full",children:w.map(S=>n.jsx(Lr,{value:S.id,className:"flex-1",disabled:N,children:S.label},S.id))})})]}):null,l.error?n.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-900/40 dark:bg-red-950/30 dark:text-red-200",children:l.error}):null,$?n.jsx("div",{className:"space-y-3",children:o?o($):a??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Checkout session created. Provide `renderCustom` to render a custom payment UI."})}):O?n.jsx("div",{className:"space-y-3",children:r?r(O):s??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Embedded checkout session created. Provide `renderEmbedded` to render your payment UI."})}):n.jsx(ie,{type:"button",className:"w-full",disabled:c.items.length===0||N||R,onClick:()=>{T(j)},children:h.isVerifying?"Checking availability…":N?"Processing…":C}),!O&&!$?n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:R?"Install a browser wallet to enable crypto payments.":k??"You will be redirected to complete your payment."}):null,n.jsx(qp,{open:_,onOpenChange:S=>{g(S),S||h.reset()},issues:h.result?.issues??[],onRemoveItem:(S,A)=>{c.removeItem(S,A)},onUpdateQuantity:(S,A,I)=>{c.setQty(S,A,I)}})]})}function Zp({className:e}){const{config:t}=Re(),r=Dt(),s=$s(),{settings:o}=or(),a=(t.checkout.allowPromoCodes??!1)&&o.checkout.promoCodes;return n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",e),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order review"}),n.jsx(St,{className:"my-3"}),n.jsx("div",{className:"space-y-3",children:r.items.map(i=>n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[n.jsx("div",{className:"h-10 w-10 shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:i.imageSnapshot?n.jsx("img",{src:i.imageSnapshot,alt:i.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"line-clamp-1 text-sm text-neutral-950 dark:text-neutral-50",children:i.titleSnapshot}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Qty ",i.qty]})]})]}),n.jsx("div",{className:"text-sm font-semibold tabular-nums text-neutral-950 dark:text-neutral-50",children:Qe({amount:i.unitPrice*i.qty,currency:i.currency})})]},`${i.productId}::${i.variantId??""}`))}),n.jsx(St,{className:"my-3"}),a?n.jsx(Mi,{value:s.values.discountCode??r.promoCode,onApply:i=>{s.setField("discountCode",i??""),r.setPromoCode(i)}}):null,a?n.jsx(St,{className:"my-3"}):null,n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("span",{className:"text-neutral-600 dark:text-neutral-400",children:"Subtotal"}),n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:r.subtotal,currency:t.currency})})]})]})}function ho({result:e,onContinueShopping:t,onViewOrders:r,className:s}){return e.kind==="idle"?null:e.kind==="success"?n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-600 dark:text-neutral-400",children:"Receipt"}),n.jsx("h2",{className:"mt-2 text-2xl font-semibold",children:"Payment successful"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"Thanks for your purchase. You’ll receive a confirmation email shortly."}),e.order?n.jsxs("div",{className:"mt-5 rounded-xl border border-neutral-200 bg-neutral-50 p-4 dark:border-neutral-800 dark:bg-neutral-900/40",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:["Order ",e.order.id]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[new Date(e.order.createdAt).toLocaleString()," · ",e.order.status]})]}),n.jsx("div",{className:"text-sm font-semibold",children:Qe({amount:e.order.total,currency:e.order.currency})})]}),n.jsxs("div",{className:"mt-3 space-y-2",children:[e.order.items.slice(0,4).map((o,a)=>n.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[n.jsx("div",{className:"min-w-0 truncate",children:o.title}),n.jsxs("div",{className:"shrink-0 text-neutral-600 dark:text-neutral-400",children:["Qty ",o.qty]})]},`${o.title}-${a}`)),e.order.items.length>4?n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["+",e.order.items.length-4," more item(s)"]}):null]}),n.jsxs("div",{className:"mt-3 flex gap-3 text-sm",children:[e.order.receiptUrl?n.jsx("a",{href:e.order.receiptUrl,className:"hover:underline",children:"Receipt"}):null,e.order.invoiceUrl?n.jsx("a",{href:e.order.invoiceUrl,className:"hover:underline",children:"Invoice"}):null]})]}):e.orderId?n.jsxs("p",{className:"mt-4 text-xs text-neutral-500 dark:text-neutral-400",children:["Session/Order ID: ",n.jsx("span",{className:"font-mono",children:e.orderId})]}):null,n.jsxs("div",{className:"mt-6 flex flex-col gap-2 sm:flex-row",children:[t?n.jsx(ie,{type:"button",onClick:t,children:"Continue shopping"}):null,r?n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"View orders"}):null]})]}):e.kind==="cancel"?n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Checkout cancelled"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"No charges were made. You can continue shopping and try again."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]}):n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Payment failed"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:e.message??"Something went wrong while processing your payment."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]})}function WC({onContinueShopping:e,onViewOrders:t,className:r,receiptClassName:s}){const o=Va();return o.kind==="idle"?n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",r),children:n.jsx("div",{className:"text-center text-neutral-600 dark:text-neutral-400",children:"Loading order details..."})}):n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",r),children:n.jsx(ho,{result:o,onContinueShopping:e,onViewOrders:t,className:H("w-full max-w-lg",s)})})}function VC({onContinueShopping:e,className:t,receiptClassName:r}){const s={kind:"cancel"};return n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",t),children:n.jsx(ho,{result:s,onContinueShopping:e,className:H("w-full max-w-lg",r)})})}function qC(e){switch(e){case"created":return"secondary";case"paid":return"default";case"processing":return"secondary";case"fulfilled":return"outline";case"shipped":return"default";case"delivered":return"outline";case"cancelled":return"outline";case"refunded":return"outline";default:return"secondary"}}function Gp({order:e,onView:t,className:r}){const s=`${e.items.length} item${e.items.length===1?"":"s"}`,o=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),a=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(Rt,{className:H("group overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm transition-shadow hover:shadow-md dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsx(Gt,{className:"p-5",children:n.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-x-4 gap-y-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsx("div",{className:"mt-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:o})]}),n.jsx("div",{className:"flex items-start justify-end",children:n.jsx(Pn,{variant:qC(e.status),className:"capitalize",children:a})}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:s}),n.jsx("div",{className:"text-right text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:e.total,currency:e.currency})}),n.jsxs("div",{className:"col-span-2 mt-3 flex items-center justify-between gap-3 border-t border-neutral-200/70 pt-3 dark:border-neutral-800",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:()=>t(e),children:"Details"}):null]})]})})})}function Qp({orders:e,onView:t,className:r}){return n.jsx("div",{className:H("grid gap-4",r),children:e.map(s=>n.jsx(Gp,{order:s,onView:t},s.id))})}function HC(e){switch(e){case"paid":return"default";case"processing":return"secondary";case"fulfilled":return"outline";case"cancelled":return"outline";case"refunded":return"outline";default:return"secondary"}}function Yp({order:e,onBack:t,className:r}){const s=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),o=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(Rt,{className:H("overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsxs(Gt,{className:"p-6",children:[n.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-neutral-600 dark:text-neutral-400",children:[n.jsx("span",{children:s}),n.jsx("span",{className:"text-neutral-300 dark:text-neutral-700",children:"·"}),n.jsx("span",{children:o})]})]}),n.jsxs("div",{className:"flex items-center gap-2 sm:justify-end",children:[n.jsx(Pn,{variant:HC(e.status),className:"capitalize",children:o}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:t,children:"Back"}):null]})]}),n.jsx(St,{className:"my-5"}),n.jsx("div",{className:"space-y-3",children:e.items.map((a,i)=>n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"truncate text-sm text-neutral-950 dark:text-neutral-50",children:a.title}),n.jsxs("div",{className:"mt-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:["Qty ",a.qty]})]}),n.jsx("div",{className:"text-right text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:a.unitPrice*a.qty,currency:a.currency})})]},`${a.title}-${i}`))}),n.jsx(St,{className:"my-5"}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Total"}),n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:e.total,currency:e.currency})})]}),e.receiptUrl||e.invoiceUrl?n.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-2",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}):null]})})}function Di(e){const t={};e.shippingProfile&&(t.shippingProfile=e.shippingProfile),e.checkoutRequirements&&(t.checkoutRequirements=JSON.stringify(e.checkoutRequirements)),e.fulfillment?.type&&(t.fulfillmentType=e.fulfillment.type),e.fulfillment?.notes&&(t.fulfillmentNotes=e.fulfillment.notes);const r=e.attributes?.shippingCountries;return typeof r=="string"&&r.trim()&&(t.shippingCountries=r),Object.keys(t).length?t:void 0}function ZC(e){return n.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:n.jsx("path",{d:"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"})})}const GC={shop:"/shop",category:e=>`/shop/${e}`,product:e=>`/product/${e}`,cart:"/cart",checkout:"/checkout",orders:"/account/orders",subscribe:"/subscribe"};function QC(e){const t=new Set;let r=Number.POSITIVE_INFINITY,s=0;for(const i of e){for(const c of i.tags??[])t.add(c);r=Math.min(r,i.price),s=Math.max(s,i.price)}const o=Array.from(t).slice(0,12),a=Number.isFinite(r)?{min:r,max:s}:void 0;return{tags:o,price:a}}function YC({className:e,routes:t,initialCategorySlug:r}){const{config:s}=Re(),o=Dt(),a=mo(),i={...GC,...t},[c,l]=x.useState("cart"),[d,m]=x.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(min-width: 1024px)")?.matches??!1);x.useEffect(()=>{if(typeof window>"u")return;const F=window.matchMedia?.("(min-width: 1024px)");if(!F)return;const ee=()=>m(F.matches);return ee(),F.addEventListener?.("change",ee),()=>F.removeEventListener?.("change",ee)},[]);const{categories:u,isLoading:p,error:h}=Ua(),_=x.useMemo(()=>qa({includeCategory:!0}),[]),[g,f]=x.useState(_?.search??""),[w,j]=x.useState(r??_?.category),[b,v]=x.useState(_?.page??1),[k,R]=x.useState(_?.sort??"featured"),[N,C]=x.useState(_?.filters??{}),{data:T,isLoading:O,error:$}=zs({category:w,search:g.trim()||void 0,filters:N,sort:k,page:b,pageSize:24}),S=x.useMemo(()=>QC(T?.items??[]),[T?.items]),{settings:A}=or(),I=A.catalog.filters,B=A.catalog.sort,D=x.useMemo(()=>{const F=[];return B.featured&&F.push({value:"featured",label:"Featured"}),B.priceAsc&&F.push({value:"price_asc",label:"Price: Low to High"}),B.priceDesc&&F.push({value:"price_desc",label:"Price: High to Low"}),F.length===0&&F.push({value:"featured",label:"Featured"}),F},[B]);x.useEffect(()=>{D.some(F=>F.value===k)||R(D[0].value)},[D,k]),Ha({search:g,sort:k,page:b,category:w,filters:N},{includeCategory:!0});const[E,P]=x.useState(!1),[z,Z]=x.useState(!1),[K,L]=x.useState(null),[W,Y]=x.useState(!1),V=F=>{j(F.slug),v(1),P(!1)},ce=x.useCallback((F,ee,pe)=>{o.addItem({productId:F.id,variantId:ee?.id,unitPrice:F.price,currency:F.currency,titleSnapshot:ee?`${F.title} — ${ee.title}`:F.title,imageSnapshot:F.images[0]?.url,paymentResource:F.id,metadata:Di(F)},pe),a?.toast({title:"Added to cart",description:F.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(i.cart):(l("cart"),Z(!0)))}})},[o,i.cart,a]);return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:i.shop,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(Ii,{value:g,onChange:f})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(no,{open:E,onOpenChange:P,children:[n.jsx(ro,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Fr,{side:"left",children:[n.jsx(so,{children:n.jsx(oo,{children:"Browse"})}),n.jsxs("div",{className:"mt-4",children:[h?n.jsx(Zt,{description:h}):null,p?n.jsxs("div",{className:"space-y-2",children:[n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"})]}):n.jsxs("div",{className:"space-y-6",children:[n.jsx(wa,{categories:u,activeSlug:w,onSelect:V}),n.jsx(Ts,{facets:S,value:N,onChange:F=>{C(F),v(1)},onClear:()=>{C({}),v(1)},enabledFilters:I}),D.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Ns,{value:k,onValueChange:F=>{R(F),v(1)},children:[n.jsx(Or,{"aria-label":"Sort",children:n.jsx(Ps,{placeholder:"Sort"})}),n.jsx(Mr,{children:D.map(F=>n.jsx(Dr,{value:F.value,children:F.label},F.value))})]})]})]})]})]})]}),n.jsx($r,{open:!d&&z,onOpenChange:Z,side:"bottom",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx($r,{open:d&&z,onOpenChange:Z,side:"popup",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(i.checkout)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",z?"lg:hidden":void 0),onClick:()=>{l("chat"),Z(!0)},"aria-label":"Open chat",children:[n.jsx(ZC,{className:"h-4 w-4"}),"Chat"]}),n.jsxs("main",{className:"mx-auto grid max-w-7xl items-start gap-6 px-4 py-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:n.jsxs(Rt,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:[n.jsx(Er,{className:"pb-4",children:n.jsx(Tr,{className:"text-base",children:"Browse"})}),n.jsxs(Gt,{className:"flex-1 space-y-6 overflow-y-auto pr-2",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Categories"}),h?n.jsx(Zt,{className:"mt-3",description:h}):null,p?n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"})]}):n.jsx("div",{className:"mt-3",children:n.jsx(wa,{categories:u,activeSlug:w,onSelect:V})})]}),D.length>1&&n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsx("div",{className:"mt-2",children:n.jsxs(Ns,{value:k,onValueChange:F=>{R(F),v(1)},children:[n.jsx(Or,{"aria-label":"Sort",children:n.jsx(Ps,{placeholder:"Sort"})}),n.jsx(Mr,{children:D.map(F=>n.jsx(Dr,{value:F.value,children:F.label},F.value))})]})})]}),n.jsx(Ts,{facets:S,value:N,onChange:F=>{C(F),v(1)},onClear:()=>{C({}),v(1)},enabledFilters:I})]})]})})}),n.jsxs("section",{children:[n.jsx("div",{className:"flex items-end justify-between gap-3",children:n.jsxs("div",{children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:A.shopPage.title||"Shop"}),A.shopPage.description&&n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:A.shopPage.description})]})}),$?n.jsx(Zt,{className:"mt-6",description:$}):null,O?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((F,ee)=>n.jsx(De,{className:"aspect-[4/5] rounded-2xl"},ee))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(fo,{products:T?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:F=>i.product(F.slug),onAddToCart:F=>ce(F,null,1),onQuickView:F=>{L(F),Y(!0)},layout:A.shopLayout.layout,imageCrop:A.shopLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:b<=1,onClick:()=>v(F=>Math.max(1,F-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",b]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!T?.hasNextPage,onClick:()=>v(F=>F+1),children:"Next"})]})]})]})]}),n.jsx(Ei,{product:K,open:W,onOpenChange:Y,productHref:F=>i.product(F),onAddToCart:(F,ee,pe)=>ce(F,ee,pe)})]})}function KC(e){return n.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:n.jsx("path",{d:"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"})})}function XC({categorySlug:e,className:t,routes:r}){const{config:s}=Re(),o=Dt(),a=mo(),{categories:i}=Ua(),[c,l]=x.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(min-width: 1024px)")?.matches??!1);x.useEffect(()=>{if(typeof window>"u")return;const q=window.matchMedia?.("(min-width: 1024px)");if(!q)return;const ne=()=>l(q.matches);return ne(),q.addEventListener?.("change",ne),()=>q.removeEventListener?.("change",ne)},[]);const[d,m]=x.useState(!1),[u,p]=x.useState(!1),[h,_]=x.useState("cart"),g=x.useMemo(()=>qa({includeCategory:!1}),[]),[f,w]=x.useState(g?.search??""),[j,b]=x.useState(g?.page??1),[v,k]=x.useState(g?.sort??"featured"),[R,N]=x.useState(g?.filters??{}),[C,T]=x.useState(null),[O,$]=x.useState(!1),S=i.find(q=>q.slug===e)??null,{data:A,isLoading:I,error:B}=zs({category:e,search:f.trim()||void 0,filters:R,sort:v,page:j,pageSize:24}),D=r?.product??(q=>`/product/${q}`),E=r?.shop??"/shop",P=r?.cart??"/cart",z=r?.checkout??"/checkout",Z=x.useMemo(()=>{const q=A?.items??[],ne=new Set;let le=Number.POSITIVE_INFINITY,fe=0;for(const qe of q){for(const He of qe.tags??[])ne.add(He);le=Math.min(le,qe.price),fe=Math.max(fe,qe.price)}const Pe=Array.from(ne).slice(0,12),Ve=Number.isFinite(le)?{min:le,max:fe}:void 0;return{tags:Pe,price:Ve}},[A?.items]),{settings:K}=or(),L=K.catalog.filters,W=K.catalog.sort,Y=x.useMemo(()=>{const q=[];return W.featured&&q.push({value:"featured",label:"Featured"}),W.priceAsc&&q.push({value:"price_asc",label:"Price: Low to High"}),W.priceDesc&&q.push({value:"price_desc",label:"Price: High to Low"}),q.length===0&&q.push({value:"featured",label:"Featured"}),q},[W]);x.useEffect(()=>{Y.some(q=>q.value===v)||k(Y[0].value)},[Y,v]),Ha({search:f,sort:v,page:j,filters:R},{includeCategory:!1});const V=x.useCallback((q,ne,le)=>{o.addItem({productId:q.id,variantId:ne?.id,unitPrice:q.price,currency:q.currency,titleSnapshot:ne?`${q.title} — ${ne.title}`:q.title,imageSnapshot:q.images[0]?.url,paymentResource:q.id,metadata:Di(q)},le),a?.toast({title:"Added to cart",description:q.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(P):(_("cart"),p(!0)))}})},[o,P,a]),ce=q=>{N(q),b(1)},F=()=>{N({}),b(1)},ee=q=>{k(q),b(1)},pe=n.jsx(Rt,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:n.jsxs(Gt,{className:"flex-1 space-y-5 overflow-y-auto pr-2 pt-6",children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-neutral-500 dark:text-neutral-400",children:"Category"}),n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2 text-xs",children:n.jsx("a",{href:E,children:"All categories"})})]}),n.jsx("div",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:S?.name??e}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:S?.description??"Browse products in this category."})]}),Y.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Ns,{value:v,onValueChange:ee,children:[n.jsx(Or,{"aria-label":"Sort",children:n.jsx(Ps,{placeholder:"Sort"})}),n.jsx(Mr,{children:Y.map(q=>n.jsx(Dr,{value:q.value,children:q.label},q.value))})]})]}),n.jsx(St,{}),n.jsx(Ts,{facets:Z,value:R,onChange:ce,onClear:F,enabledFilters:L})]})});return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:E,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(Ii,{value:f,onChange:w})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(no,{open:d,onOpenChange:m,children:[n.jsx(ro,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Fr,{side:"left",children:[n.jsx(so,{children:n.jsx(oo,{children:"Filters"})}),n.jsx("div",{className:"mt-4",children:pe})]})]}),n.jsx($r,{open:!c&&u,onOpenChange:p,side:"bottom",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(z)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>_("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx($r,{open:c&&u,onOpenChange:p,side:"popup",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(z)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>_("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(z)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",u?"lg:hidden":void 0),onClick:()=>{_("chat"),p(!0)},"aria-label":"Open chat",children:[n.jsx(KC,{className:"h-4 w-4"}),"Chat"]}),n.jsxs("main",{className:"mx-auto max-w-7xl px-4 py-8",children:[n.jsx(Ti,{items:[{label:"Shop",href:E},{label:S?.name??e}]}),n.jsxs("div",{className:"mt-6",children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:S?.name??"Category"}),n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:S?.description??"Browse products in this category."})]}),B?n.jsx(Zt,{className:"mt-6",description:B}):null,n.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:pe})}),n.jsx("div",{children:I?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((q,ne)=>n.jsx(De,{className:"aspect-[4/5] rounded-2xl"},ne))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(fo,{products:A?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:q=>D(q.slug),onAddToCart:q=>V(q,null,1),onQuickView:q=>{T(q),$(!0)},layout:K.categoryLayout.layout,imageCrop:K.categoryLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:j<=1,onClick:()=>b(q=>Math.max(1,q-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",j]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!A?.hasNextPage,onClick:()=>b(q=>q+1),children:"Next"})]})]})})]}),n.jsx(Ei,{product:C,open:O,onOpenChange:$,productHref:q=>D(q),onAddToCart:(q,ne,le)=>V(q,ne,le)})]})]})}function JC(e){return!e||typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function eN({slug:e,className:t,routes:r}){const s=Dt(),o=mo(),{product:a,isLoading:i,error:c}=$d(e),[l,d]=x.useState(1),[m,u]=x.useState({selectedOptions:{},variant:null});x.useEffect(()=>{if(!a||!a.variants?.length)return;const S=a.variants[0];u({selectedOptions:{...S.options},variant:S})},[a?.id]);const{settings:p}=or(),{mode:h,maxItems:_}=p.relatedProducts,g=Vd({productId:a?.id,enabled:h==="ai"&&!!a?.id}),f=x.useMemo(()=>h==="by_category"&&a?.categoryIds?.length?{category:a.categoryIds[0],page:1,pageSize:_+1}:{page:1,pageSize:_+4},[h,_,a?.categoryIds]),w=zs(f),j=x.useMemo(()=>{const A=(w.data?.items??[]).filter(I=>I.slug!==e);if(h==="manual"&&a){const I=a.attributes?.relatedProductIds||a.attributes?.related_product_ids;if(I){const B=JC(String(I));if(B.length>0){const D=new Map(A.map(P=>[P.id,P]));return B.map(P=>D.get(P)).filter(P=>!!P).slice(0,_)}}}if(h==="ai"&&g.relatedProductIds&&g.relatedProductIds.length>0){const I=new Map(A.map(D=>[D.id,D])),B=g.relatedProductIds.map(D=>I.get(D)).filter(D=>!!D);if(B.length>0)return B.slice(0,_)}return A.slice(0,_)},[w.data?.items,e,h,_,a,g.relatedProductIds]),b=r?.shop??"/shop",v=r?.checkout??"/checkout",k=r?.cart??"/cart",R=r?.product??(S=>`/product/${S}`);if(i)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsxs("div",{className:"mx-auto max-w-6xl",children:[n.jsx(De,{className:"h-5 w-40"}),n.jsxs("div",{className:"mt-6 grid gap-8 lg:grid-cols-2",children:[n.jsx(De,{className:"aspect-square rounded-2xl"}),n.jsxs("div",{className:"space-y-4",children:[n.jsx(De,{className:"h-8 w-2/3"}),n.jsx(De,{className:"h-6 w-32"}),n.jsx(De,{className:"h-20"}),n.jsx(De,{className:"h-11"})]})]})]})});if(c)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsx("div",{className:"mx-auto max-w-6xl",children:n.jsx(Zt,{description:c})})});if(!a)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsx("div",{className:"mx-auto max-w-6xl",children:n.jsx(Zt,{description:"Product not found."})})});const N=m.variant?.price??a.price,C=m.variant?.compareAtPrice??a.compareAtPrice,T=a.inventoryStatus==="out_of_stock"||typeof a.inventoryQuantity=="number"&&a.inventoryQuantity<=0,O=()=>{T||(s.addItem({productId:a.id,variantId:m.variant?.id,unitPrice:N,currency:a.currency,titleSnapshot:m.variant?`${a.title} — ${m.variant.title}`:a.title,imageSnapshot:a.images[0]?.url,paymentResource:a.id,metadata:Di(a)},l),o?.toast({title:"Added to cart",description:a.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&window.location.assign(k)}}))},$=()=>{T||(O(),typeof window<"u"&&window.location.assign(v))};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-8",children:[n.jsx(Ti,{items:[{label:"Shop",href:b},{label:a.title}]}),n.jsxs("div",{className:"mt-6 grid gap-10 lg:grid-cols-2",children:[n.jsx(Ni,{images:a.images}),n.jsxs("div",{className:"space-y-6",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:a.title}),n.jsx("div",{className:"mt-3",children:n.jsx(po,{amount:N,currency:a.currency,compareAt:C})}),T?n.jsx("div",{className:"mt-2 text-sm font-medium text-red-700 dark:text-red-300",children:"Out of stock"}):typeof a.inventoryQuantity=="number"&&a.inventoryQuantity>0&&a.inventoryQuantity<=5?n.jsxs("div",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:["Only ",n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:a.inventoryQuantity})," left"]}):null,n.jsx("p",{className:"mt-4 text-sm text-neutral-600 dark:text-neutral-400",children:a.description})]}),n.jsx(Pi,{product:a,value:{selectedOptions:m.selectedOptions,variantId:m.variant?.id},onChange:S=>u(S)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(Ai,{qty:l,onChange:d}),n.jsx(ie,{type:"button",onClick:O,className:"flex-1",disabled:T,children:T?"Out of stock":"Add to cart"}),n.jsx(ie,{type:"button",variant:"outline",onClick:$,disabled:T,children:"Buy now"})]}),(p.sections.showDescription||p.sections.showSpecs||p.sections.showShipping)&&n.jsxs(dp,{type:"single",collapsible:!0,defaultValue:p.sections.showDescription?"desc":void 0,children:[p.sections.showDescription&&n.jsxs(Sr,{value:"desc",children:[n.jsx(Cr,{children:"Description"}),n.jsx(Nr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.description})})]}),p.sections.showSpecs&&n.jsxs(Sr,{value:"specs",children:[n.jsx(Cr,{children:"Specs"}),n.jsx(Nr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.attributes?n.jsx("div",{className:"space-y-1",children:Object.entries(a.attributes).map(([S,A])=>n.jsxs("div",{children:[n.jsxs("span",{className:"font-medium text-neutral-950 dark:text-neutral-50",children:[S,":"]})," ",String(A)]},S))}):"No specs provided."})})]}),p.sections.showShipping&&n.jsxs(Sr,{value:"ship",children:[n.jsx(Cr,{children:"Shipping & returns"}),n.jsx(Nr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Ships in 2–3 business days. Easy returns within 30 days."})})]})]})]})]}),p.sections.showRelatedProducts&&j.length?n.jsxs("section",{className:"mt-12",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Related products"}),n.jsx("div",{className:"mt-4",children:n.jsx(fo,{products:j,columns:{base:2,md:4,lg:4},layout:p.relatedProducts.layout.layout,imageCrop:p.relatedProducts.layout.imageCrop,getProductHref:S=>R(S.slug),onAddToCart:S=>s.addItem({productId:S.id,unitPrice:S.price,currency:S.currency,titleSnapshot:S.title,imageSnapshot:S.images[0]?.url,paymentResource:S.id},1)})})]}):null]})})}function tN({className:e,checkoutHref:t}){const{config:r}=Re(),{settings:s}=or(),o=t??"/checkout",a=r.checkout.allowPromoCodes&&s.checkout.promoCodes;return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-10",children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Cart"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"Review items, adjust quantities, then check out."}),n.jsx("div",{className:"mt-8",children:n.jsx(Fp,{onCheckout:()=>{typeof window<"u"&&window.location.assign(o)},showPromoCode:a})})]})})}function nN({className:e,routes:t}){const{config:r}=Re(),s=Dt(),o=Va(),a=r.customer?.isSignedIn??!!r.customer?.id,c=!(r.checkout.requireAccount?!1:r.checkout.guestCheckout??!0)&&!a;x.useEffect(()=>{o.kind==="success"&&s.clear()},[o.kind]);const l=t?.shop??"/shop",d=t?.orders??"/account/orders",m=t?.login;return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-10",children:[n.jsx(ho,{result:o,onContinueShopping:()=>{typeof window<"u"&&window.location.assign(l)},onViewOrders:()=>{typeof window<"u"&&window.location.assign(d)}}),o.kind==="idle"?n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Checkout"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:r.checkout.mode==="none"?"Confirm and pay.":"Enter details, then complete payment."})]}),n.jsx("div",{className:"mt-8",children:n.jsx(Ld,{children:c?n.jsxs(Rt,{className:"rounded-2xl",children:[n.jsx(Er,{className:"pb-4",children:n.jsx(Tr,{className:"text-base",children:"Sign in required"})}),n.jsxs(Gt,{children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"This store requires an account to complete checkout."}),m?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",onClick:()=>{typeof window<"u"&&window.location.assign(m)},children:"Sign in"})}):null]})]}):n.jsx(Bp,{left:n.jsxs("div",{className:"space-y-6",children:[n.jsx(Wp,{}),n.jsxs(Rt,{className:"rounded-2xl",children:[n.jsx(Er,{className:"pb-4",children:n.jsx(Tr,{className:"text-base",children:"Payment"})}),n.jsxs(Gt,{children:[n.jsx(St,{className:"mb-4"}),n.jsx(Hp,{})]})]})]}),right:n.jsx("div",{className:"lg:sticky lg:top-24",children:n.jsx(Zp,{})})})})})]}):null]})})}function rN({className:e,isSignedIn:t=!0,onLogin:r}){const{orders:s,isLoading:o,error:a}=zd(),[i,c]=x.useState(null);return t?n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-5xl px-4 py-10 sm:py-12",children:[n.jsxs("header",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Orders"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"View past purchases and receipts."})]}),!o&&!a&&!i&&s.length>0?n.jsxs("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:[s.length," order",s.length===1?"":"s"]}):null]}),a?n.jsx(Zt,{className:"mt-8",description:a}):null,o?n.jsxs("div",{className:"mt-8 grid gap-4",children:[n.jsx(De,{className:"h-32 rounded-2xl"}),n.jsx(De,{className:"h-32 rounded-2xl"}),n.jsx(De,{className:"h-32 rounded-2xl"})]}):s.length===0?n.jsx("div",{className:"mt-8",children:n.jsx(tr,{title:"No orders yet",description:"When you purchase something, it will show up here."})}):i?n.jsx("div",{className:"mt-8",children:n.jsx(Yp,{order:i,onBack:()=>c(null)})}):n.jsx("div",{className:"mt-8",children:n.jsx(Qp,{orders:s,onView:c})})]})}):n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-10 dark:bg-neutral-950",e),children:n.jsx("div",{className:"mx-auto max-w-4xl",children:n.jsx(tr,{title:"Sign in to view your orders",description:"Your purchase history will appear here once you're logged in.",actionLabel:r?"Sign in":void 0,onAction:r})})})}function sN({className:e}){return n.jsxs("svg",{className:e,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"6 9 6 2 18 2 18 9"}),n.jsx("path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"}),n.jsx("rect",{x:"6",y:"14",width:"12",height:"8"})]})}function oN({className:e}){return n.jsx("svg",{className:e,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})})}function aN(e){switch(e){case"x402":return"Crypto (x402)";case"credits":return"Credits";case"stripe":return"Card";default:return"Payment"}}function iN({order:e,source:t,purchaseId:r,customerEmail:s,customerName:o,className:a,onBack:i}){const{config:c}=Re(),l=t??e.source,d=r??e.purchaseId,m=s??e.customerEmail,u=o??e.customerName,p=c.brand?.name??"Store",h=c.brand?.logoUrl,_=()=>{typeof window<"u"&&window.print()},g=new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"}),f=new Date(e.createdAt).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return n.jsxs("div",{className:H("min-h-screen bg-neutral-100 dark:bg-neutral-900 print:bg-white print:dark:bg-white",a),children:[n.jsx("div",{className:"border-b border-neutral-200 bg-white px-4 py-3 dark:border-neutral-800 dark:bg-neutral-950 print:hidden",children:n.jsxs("div",{className:"mx-auto flex max-w-2xl items-center justify-between",children:[i?n.jsxs(ie,{type:"button",variant:"ghost",size:"sm",onClick:i,children:[n.jsx(oN,{className:"mr-1"})," Back"]}):n.jsx("div",{}),n.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:_,children:[n.jsx(sN,{className:"mr-2"})," Print Receipt"]})]})}),n.jsx("div",{className:"mx-auto max-w-2xl px-4 py-8 print:max-w-none print:px-0 print:py-0",children:n.jsxs("div",{className:"rounded-xl border border-neutral-200 bg-white p-8 shadow-sm dark:border-neutral-800 dark:bg-neutral-950 print:border-0 print:shadow-none print:dark:bg-white print:dark:text-neutral-950",children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-neutral-200 pb-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[h?n.jsx("img",{src:h,alt:p,className:"h-10 w-10 rounded-lg object-contain"}):null,n.jsx("div",{className:"text-xl font-semibold",children:p})]}),n.jsxs("div",{className:"text-right",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Receipt"}),n.jsx("div",{className:"mt-1 font-mono text-sm",children:e.id})]})]}),n.jsxs("div",{className:"mt-6 grid grid-cols-2 gap-4 text-sm sm:grid-cols-3",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Date"}),n.jsx("div",{className:"mt-1 font-medium",children:g}),n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:f})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Payment Method"}),n.jsx("div",{className:"mt-1 font-medium",children:aN(l)})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Status"}),n.jsx("div",{className:"mt-1",children:n.jsx(Pn,{variant:"outline",className:"capitalize print:border-neutral-300",children:e.status})})]})]}),(u||m)&&n.jsxs("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Customer"}),u&&n.jsx("div",{className:"mt-1 font-medium",children:u}),m&&n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:m})]}),n.jsx("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-neutral-200 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("th",{className:"pb-3 text-left font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Item"}),n.jsx("th",{className:"pb-3 text-center font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Qty"}),n.jsx("th",{className:"pb-3 text-right font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Price"})]})}),n.jsx("tbody",{children:e.items.map((w,j)=>n.jsxs("tr",{className:"border-b border-neutral-100 dark:border-neutral-800/50 print:dark:border-neutral-100",children:[n.jsx("td",{className:"py-3",children:n.jsx("div",{className:"font-medium",children:w.title})}),n.jsx("td",{className:"py-3 text-center text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:w.qty}),n.jsx("td",{className:"py-3 text-right",children:Qe({amount:w.unitPrice*w.qty,currency:w.currency})})]},`${w.title}-${j}`))})]})}),n.jsxs("div",{className:"mt-4 flex flex-col items-end gap-2 text-sm",children:[n.jsxs("div",{className:"flex w-48 justify-between",children:[n.jsx("span",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Subtotal"}),n.jsx("span",{children:Qe({amount:e.total,currency:e.currency})})]}),n.jsxs("div",{className:"flex w-48 justify-between border-t border-neutral-200 pt-2 text-base font-semibold dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("span",{children:"Total"}),n.jsx("span",{children:Qe({amount:e.total,currency:e.currency})})]})]}),d&&n.jsxs("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Transaction ID"}),n.jsx("div",{className:"mt-1 break-all font-mono text-xs",children:d})]}),n.jsxs("div",{className:"mt-8 border-t border-neutral-200 pt-6 text-center text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400 print:dark:border-neutral-200 print:dark:text-neutral-500",children:[n.jsx("p",{children:"Thank you for your purchase!"}),n.jsx("p",{className:"mt-1",children:"If you have any questions, please contact support."})]})]})})]})}function cN({className:e}){return n.jsx("svg",{className:H("h-4 w-4 flex-shrink-0",e),viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})}function lN({className:e,title:t="Choose Your Plan",subtitle:r="Select the plan that best fits your needs.",annualSavingsBadge:s="2 months free",popularBadgeText:o="Best Deal",footerNotice:a}){const{config:i}=Re(),{tiers:c,status:l,isLoading:d,error:m}=Fd(),[u,p]=x.useState("monthly"),h=!!i.adapter.createSubscriptionCheckoutSession,_=async g=>{if(!i.adapter.createSubscriptionCheckoutSession)return;const f=await i.adapter.createSubscriptionCheckoutSession({tierId:g,interval:u,successUrl:i.checkout.successUrl,cancelUrl:i.checkout.cancelUrl});f.kind==="redirect"&&typeof window<"u"&&window.location.assign(f.url)};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-16",children:[n.jsxs("div",{className:"text-center",children:[n.jsx("h1",{className:"text-5xl font-bold tracking-tight",children:t}),n.jsx("p",{className:"mt-4 text-base text-neutral-600 dark:text-neutral-400",children:r})]}),n.jsx("div",{className:"mt-10 flex justify-center",children:n.jsxs("div",{className:"inline-flex items-center rounded-full bg-neutral-200/60 p-1 dark:bg-neutral-800/60",children:[n.jsxs("button",{type:"button",onClick:()=>p("annual"),className:H("relative flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-all",u==="annual"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:["Yearly",s&&n.jsx("span",{className:H("rounded-full px-2 py-0.5 text-xs font-medium",u==="annual"?"bg-white/20 text-white dark:bg-neutral-900/20 dark:text-neutral-900":"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900"),children:s})]}),n.jsx("button",{type:"button",onClick:()=>p("monthly"),className:H("rounded-full px-4 py-2 text-sm font-medium transition-all",u==="monthly"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:"Monthly"})]})}),m?n.jsx(Zt,{className:"mt-10",description:m}):null,d?n.jsxs("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[n.jsx(De,{className:"h-[480px] rounded-2xl"}),n.jsx(De,{className:"h-[480px] rounded-2xl"}),n.jsx(De,{className:"h-[480px] rounded-2xl"})]}):c.length===0?n.jsx("div",{className:"mt-12",children:n.jsx(tr,{title:"No plans available",description:"Subscription plans will appear here once configured."})}):n.jsx("div",{className:"mt-12 grid gap-6 md:grid-cols-3 items-start",children:c.map(g=>{const f=l?.isActive&&l.currentTierId===g.id,w=u==="annual"&&g.priceAnnual?g.priceAnnual:g.priceMonthly,j=g.isPopular,b=g.inventoryQuantity!=null,v=b?Math.max(0,(g.inventoryQuantity??0)-(g.inventorySold??0)):null,k=b&&v===0,R=b&&v!=null&&v>0&&v<=5,[N,...C]=g.features;return n.jsxs("div",{className:H("relative flex flex-col rounded-2xl border p-6 transition-shadow",j?"border-neutral-900 bg-neutral-900 text-white shadow-xl dark:border-white dark:bg-white dark:text-neutral-900":"border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-900"),children:[j&&o&&n.jsx("div",{className:"absolute -top-3 right-4",children:n.jsx("span",{className:"rounded-full bg-neutral-100 px-3 py-1 text-xs font-semibold text-neutral-900 shadow-sm dark:bg-neutral-800 dark:text-white",children:o})}),n.jsxs("div",{className:"mb-6",children:[n.jsx("h3",{className:"text-xl font-bold",children:g.title}),g.description&&n.jsx("p",{className:H("mt-2 text-sm leading-relaxed",j?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:g.description})]}),n.jsxs("div",{className:"mb-6",children:[n.jsx("div",{className:"text-5xl font-bold tracking-tight",children:Qe({amount:w,currency:g.currency||i.currency})}),n.jsxs("div",{className:H("mt-2 text-sm",j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:["Per ",u==="annual"?"year":"month",", billed ",u==="annual"?"annually":"monthly"]})]}),b&&n.jsx("div",{className:H("mb-3 text-xs font-medium",k?"text-red-600 dark:text-red-400":R?j?"text-amber-300 dark:text-amber-600":"text-amber-600 dark:text-amber-400":j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:k?"Sold out":`${v} remaining`}),n.jsx(ie,{type:"button",className:H("mb-6 w-full rounded-full py-3 font-medium",j?"bg-white text-neutral-900 hover:bg-neutral-100 dark:bg-neutral-900 dark:text-white dark:hover:bg-neutral-800":""),variant:j?"default":"outline",disabled:f||!h||k,onClick:()=>void _(g.id),children:k?"Sold Out":f?"Current Plan":"Purchase"}),N&&n.jsx("div",{className:H("mb-4 text-sm font-semibold",j?"":"text-neutral-900 dark:text-white"),children:N}),C.length>0&&n.jsx("ul",{className:"space-y-3",children:C.map((T,O)=>n.jsxs("li",{className:"flex items-start gap-3",children:[n.jsx(cN,{className:H("mt-0.5",j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400")}),n.jsx("span",{className:H("text-sm leading-relaxed",j?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:T})]},O))})]},g.id)})}),a&&n.jsx("div",{className:"mt-12 text-center",children:n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400 leading-relaxed max-w-2xl mx-auto",children:a})})]})})}function dN(e){const{processCartCheckout:t}=Rs();return x.useMemo(()=>({...e,async createCheckoutSession(r){const s=await t(r.cart,r.options.successUrl,r.options.cancelUrl,r.options.metadata,r.customer.email,r.options.discountCode);if(!s.success)throw new Error(s.error||"Checkout failed");return{kind:"redirect",url:r.options.successUrl??"/"}},async resolveCheckoutReturn({query:r}){return Wa(r)}}),[e,t])}const uN=Object.freeze(Object.defineProperty({__proto__:null,Accordion:dp,AccordionContent:Nr,AccordionItem:Sr,AccordionTrigger:Cr,AddressForm:_a,Badge:Pn,Breadcrumbs:Ti,Button:ie,Card:Rt,CardContent:Gt,CardDescription:iu,CardFooter:cu,CardHeader:Er,CardTitle:Tr,CartLineItem:Ri,CartPageContent:Fp,CartPanel:$p,CartProvider:ng,CartSidebar:$r,CartSummary:Oi,CartTemplate:tN,CategoryNav:wa,CategoryTemplate:XC,CedrosShopProvider:$h,CheckoutCancelPage:VC,CheckoutForm:Wp,CheckoutLayout:Bp,CheckoutProvider:Ld,CheckoutReceipt:ho,CheckoutSuccessPage:WC,CheckoutTemplate:nN,Dialog:pi,DialogClose:Qk,DialogContent:eo,DialogDescription:gi,DialogFooter:Bm,DialogHeader:hi,DialogOverlay:fi,DialogPortal:Fm,DialogTitle:to,DialogTrigger:Gk,EmptyState:tr,ErrorBoundary:AS,ErrorState:Zt,FAQItem:Mp,FAQList:PC,FilterPanel:Ts,Input:Be,InventoryVerificationDialog:qp,Label:at,OrderCard:Gp,OrderDetails:Yp,OrderList:Qp,OrderReview:Zp,PaymentStep:Hp,Price:po,ProductCard:Dp,ProductGallery:Ni,ProductGrid:fo,ProductTemplate:eN,PromoCodeInput:Mi,PurchaseHistoryTemplate:rN,QuantitySelector:Ai,QuickViewDialog:Ei,ReceiptTemplate:iN,SearchInput:Ii,Select:Ns,SelectContent:Mr,SelectGroup:Ak,SelectItem:Dr,SelectTrigger:Or,SelectValue:Ps,Separator:St,Sheet:no,SheetClose:Um,SheetContent:Fr,SheetDescription:Vm,SheetHeader:so,SheetOverlay:xi,SheetPortal:Wm,SheetTitle:oo,SheetTrigger:ro,ShippingMethodSelector:Up,ShopTemplate:YC,Skeleton:De,SubscriptionTemplate:lN,Tabs:Si,TabsContent:Ep,TabsList:uo,TabsTrigger:Lr,ToastProvider:oC,VariantSelector:Pi,createMockCommerceAdapter:Wh,createPaywallCommerceAdapter:Gh,parseCheckoutReturn:Wa,readCatalogUrlState:qa,useAIRelatedProducts:Vd,useCart:Dt,useCartInventory:Za,useCatalogUrlSync:Ha,useCategories:Ua,useCedrosPayCheckoutAdapter:dN,useCedrosShop:Re,useCheckout:$s,useCheckoutResultFromUrl:Va,useHoldExpiry:Wb,useInventoryVerification:Ud,useOptionalToast:mo,useOrders:zd,usePaymentMethodsConfig:Wd,useProduct:$d,useProducts:zs,useShippingMethods:Bd,useStandaloneCheckout:Ob,useStorefrontSettings:or,useSubscriptionData:Fd,useToast:sC,validateCommerceAdapterContract:Zb},Symbol.toStringTag,{value:"Module"}));exports.CEDROS_EVENTS=gn;exports.CSP_PRESETS=Pf;exports.CedrosPay=$f;exports.CedrosPayAdminDashboard=yh;exports.CouponsSection=zl;exports.CreditsButton=Pa;exports.CreditsSubscribeButton=jh;exports.CryptoButton=Aa;exports.ERROR_CATEGORIES=Cl;exports.PaymentMethodBadge=wh;exports.PaymentModal=Ol;exports.ProductPrice=bh;exports.ProductsSection=Ll;exports.PurchaseButton=Ml;exports.RPC_PROVIDERS=Nf;exports.RefundsSection=Fl;exports.SECURITY_RECOMMENDATIONS=Lh;exports.SettingsSection=Ia;exports.StripeButton=Na;exports.SubscribeButton=_h;exports.SubscriptionManagementPanel=Ah;exports.TransactionsSection=$l;exports.calculateDiscountPercentage=uf;exports.cedrosPayPlugin=vh;exports.createDedupedClickHandler=Mn;exports.createTranslator=Tl;exports.detectLocale=Al;exports.emitPaymentError=kt;exports.emitPaymentProcessing=un;exports.emitPaymentStart=Ln;exports.emitPaymentSuccess=$n;exports.emitWalletConnect=Xo;exports.emitWalletConnected=Sl;exports.emitWalletError=is;exports.formatCSP=Pl;exports.formatCouponCodes=df;exports.generateCSP=Cf;exports.generateCSPDirectives=Nl;exports.getAvailableLocales=Ef;exports.getLocalizedError=Tf;exports.getModalCloseButtonStyles=Ca;exports.getUserErrorMessage=jf;exports.index=uN;exports.isRetryableError=_f;exports.loadLocale=El;exports.logSecurityReport=Dh;exports.parseCouponCodes=lf;exports.stackCheckoutCoupons=mf;exports.useCreditsPayment=Il;exports.useCreditsSubscription=Xl;exports.useLocalizedError=If;exports.usePaymentMode=nr;exports.useStripeCheckout=Rs;exports.useSubscription=Kl;exports.useSubscriptionManagement=Jl;exports.useTranslation=xn;exports.useX402Payment=Rl;exports.validateSecurity=Mh;
|
|
135
|
+
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return x.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},Hk="DialogDescriptionWarning",Zk=({contentRef:e,descriptionId:t})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Mm(Hk).contentName}}.`;return x.useEffect(()=>{const o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(s))},[s,e,t]),null},Dm=wm,Lm=jm,$m=Sm,Ys=Cm,Ks=Nm,Xs=Am,Js=Tm,zm=Rm;const pi=Dm,Gk=Lm,Fm=$m,Qk=zm,fi=x.forwardRef(({className:e,...t},r)=>n.jsx(Ys,{ref:r,className:H("fixed inset-0 z-50 bg-neutral-950/40 backdrop-blur-sm transition-opacity data-[state=closed]:opacity-0 data-[state=open]:opacity-100",e),...t}));fi.displayName=Ys.displayName;const eo=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(Fm,{children:[n.jsx(fi,{}),n.jsx(Ks,{ref:s,className:H("fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border border-neutral-200 bg-white p-6 shadow-lg outline-none transition data-[state=closed]:opacity-0 data-[state=closed]:scale-95 data-[state=open]:opacity-100 data-[state=open]:scale-100 dark:border-neutral-800 dark:bg-neutral-950","rounded-2xl",e),...r,children:t})]}));eo.displayName=Ks.displayName;const hi=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-center sm:text-left",e),...t}),Bm=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t}),to=x.forwardRef(({className:e,...t},r)=>n.jsx(Xs,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));to.displayName=Xs.displayName;const gi=x.forwardRef(({className:e,...t},r)=>n.jsx(Js,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));gi.displayName=Js.displayName;const no=Dm,ro=Lm,Um=zm,Wm=$m,xi=x.forwardRef(({className:e,...t},r)=>n.jsx(Ys,{ref:r,className:H("fixed inset-0 z-50 bg-neutral-950/40 backdrop-blur-sm transition-opacity data-[state=closed]:opacity-0 data-[state=open]:opacity-100",e),...t}));xi.displayName=Ys.displayName;const Yk=Ga("fixed z-50 gap-4 bg-white p-6 shadow-lg outline-none transition duration-200 ease-out dark:bg-neutral-950",{variants:{side:{top:"inset-x-0 top-0 border-b border-neutral-200 data-[state=closed]:-translate-y-full data-[state=open]:translate-y-0 dark:border-neutral-800",bottom:"inset-x-0 bottom-0 border-t border-neutral-200 data-[state=closed]:translate-y-full data-[state=open]:translate-y-0 dark:border-neutral-800",left:"inset-y-0 left-0 h-full w-3/4 border-r border-neutral-200 data-[state=closed]:-translate-x-full data-[state=open]:translate-x-0 sm:max-w-sm dark:border-neutral-800",right:"inset-y-0 right-0 h-full w-3/4 border-l border-neutral-200 data-[state=closed]:translate-x-full data-[state=open]:translate-x-0 sm:max-w-sm dark:border-neutral-800",popup:"bottom-4 right-4 w-[420px] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-2rem)] overflow-hidden rounded-2xl border border-neutral-200 p-4 data-[state=closed]:translate-y-2 data-[state=open]:translate-y-0 data-[state=closed]:opacity-0 data-[state=open]:opacity-100 data-[state=closed]:scale-95 data-[state=open]:scale-100 dark:border-neutral-800"}},defaultVariants:{side:"right"}}),Fr=x.forwardRef(({side:e="right",className:t,children:r,overlayClassName:s,...o},a)=>n.jsxs(Wm,{children:[n.jsx(xi,{className:s}),n.jsx(Ks,{ref:a,className:H(Yk({side:e}),t),...o,children:r})]}));Fr.displayName=Ks.displayName;const so=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-left",e),...t}),oo=x.forwardRef(({className:e,...t},r)=>n.jsx(Xs,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));oo.displayName=Xs.displayName;const Vm=x.forwardRef(({className:e,...t},r)=>n.jsx(Js,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));Vm.displayName=Js.displayName;var ao="Collapsible",[Kk,qm]=vn(ao),[Xk,yi]=Kk(ao),Hm=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:s,defaultOpen:o,disabled:a,onOpenChange:i,...c}=e,[l,d]=hn({prop:s,defaultProp:o??!1,onChange:i,caller:ao});return n.jsx(Xk,{scope:r,disabled:a,contentId:qt(),open:l,onOpenToggle:x.useCallback(()=>d(m=>!m),[d]),children:n.jsx(ve.div,{"data-state":vi(l),"data-disabled":a?"":void 0,...c,ref:t})})});Hm.displayName=ao;var Zm="CollapsibleTrigger",Gm=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,...s}=e,o=yi(Zm,r);return n.jsx(ve.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":vi(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...s,ref:t,onClick:_e(e.onClick,o.onOpenToggle)})});Gm.displayName=Zm;var bi="CollapsibleContent",Qm=x.forwardRef((e,t)=>{const{forceMount:r,...s}=e,o=yi(bi,e.__scopeCollapsible);return n.jsx(mr,{present:r||o.open,children:({present:a})=>n.jsx(Jk,{...s,ref:t,present:a})})});Qm.displayName=bi;var Jk=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:s,children:o,...a}=e,i=yi(bi,r),[c,l]=x.useState(s),d=x.useRef(null),m=Ee(t,d),u=x.useRef(0),p=u.current,h=x.useRef(0),_=h.current,g=i.open||c,f=x.useRef(g),w=x.useRef(void 0);return x.useEffect(()=>{const j=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(j)},[]),Xe(()=>{const j=d.current;if(j){w.current=w.current||{transitionDuration:j.style.transitionDuration,animationName:j.style.animationName},j.style.transitionDuration="0s",j.style.animationName="none";const v=j.getBoundingClientRect();u.current=v.height,h.current=v.width,f.current||(j.style.transitionDuration=w.current.transitionDuration,j.style.animationName=w.current.animationName),l(s)}},[i.open,s]),n.jsx(ve.div,{"data-state":vi(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...a,ref:m,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":_?`${_}px`:void 0,...e.style},children:g&&o})});function vi(e){return e?"open":"closed"}var eS=Hm,tS=Gm,nS=Qm,$t="Accordion",rS=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[wi,sS,oS]=Ya($t),[io]=vn($t,[oS,qm]),_i=qm(),Ym=y.forwardRef((e,t)=>{const{type:r,...s}=e,o=s,a=s;return n.jsx(wi.Provider,{scope:e.__scopeAccordion,children:r==="multiple"?n.jsx(lS,{...a,ref:t}):n.jsx(cS,{...o,ref:t})})});Ym.displayName=$t;var[Km,aS]=io($t),[Xm,iS]=io($t,{collapsible:!1}),cS=y.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},collapsible:a=!1,...i}=e,[c,l]=hn({prop:r,defaultProp:s??"",onChange:o,caller:$t});return n.jsx(Km,{scope:e.__scopeAccordion,value:y.useMemo(()=>c?[c]:[],[c]),onItemOpen:l,onItemClose:y.useCallback(()=>a&&l(""),[a,l]),children:n.jsx(Xm,{scope:e.__scopeAccordion,collapsible:a,children:n.jsx(Jm,{...i,ref:t})})})}),lS=y.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},...a}=e,[i,c]=hn({prop:r,defaultProp:s??[],onChange:o,caller:$t}),l=y.useCallback(m=>c((u=[])=>[...u,m]),[c]),d=y.useCallback(m=>c((u=[])=>u.filter(p=>p!==m)),[c]);return n.jsx(Km,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:d,children:n.jsx(Xm,{scope:e.__scopeAccordion,collapsible:!0,children:n.jsx(Jm,{...a,ref:t})})})}),[dS,co]=io($t),Jm=y.forwardRef((e,t)=>{const{__scopeAccordion:r,disabled:s,dir:o,orientation:a="vertical",...i}=e,c=y.useRef(null),l=Ee(c,t),d=sS(r),u=Fs(o)==="ltr",p=_e(e.onKeyDown,h=>{if(!rS.includes(h.key))return;const _=h.target,g=d().filter(C=>!C.ref.current?.disabled),f=g.findIndex(C=>C.ref.current===_),w=g.length;if(f===-1)return;h.preventDefault();let j=f;const v=0,b=w-1,k=()=>{j=f+1,j>b&&(j=v)},R=()=>{j=f-1,j<v&&(j=b)};switch(h.key){case"Home":j=v;break;case"End":j=b;break;case"ArrowRight":a==="horizontal"&&(u?k():R());break;case"ArrowDown":a==="vertical"&&k();break;case"ArrowLeft":a==="horizontal"&&(u?R():k());break;case"ArrowUp":a==="vertical"&&R();break}const N=j%w;g[N].ref.current?.focus()});return n.jsx(dS,{scope:r,disabled:s,direction:o,orientation:a,children:n.jsx(wi.Slot,{scope:r,children:n.jsx(ve.div,{...i,"data-orientation":a,ref:l,onKeyDown:s?void 0:p})})})}),Es="AccordionItem",[uS,ji]=io(Es),ep=y.forwardRef((e,t)=>{const{__scopeAccordion:r,value:s,...o}=e,a=co(Es,r),i=aS(Es,r),c=_i(r),l=qt(),d=s&&i.value.includes(s)||!1,m=a.disabled||e.disabled;return n.jsx(uS,{scope:r,open:d,disabled:m,triggerId:l,children:n.jsx(eS,{"data-orientation":a.orientation,"data-state":ap(d),...c,...o,ref:t,disabled:m,open:d,onOpenChange:u=>{u?i.onItemOpen(s):i.onItemClose(s)}})})});ep.displayName=Es;var tp="AccordionHeader",np=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=co($t,r),a=ji(tp,r);return n.jsx(ve.h3,{"data-orientation":o.orientation,"data-state":ap(a.open),"data-disabled":a.disabled?"":void 0,...s,ref:t})});np.displayName=tp;var ha="AccordionTrigger",rp=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=co($t,r),a=ji(ha,r),i=iS(ha,r),c=_i(r);return n.jsx(wi.ItemSlot,{scope:r,children:n.jsx(tS,{"aria-disabled":a.open&&!i.collapsible||void 0,"data-orientation":o.orientation,id:a.triggerId,...c,...s,ref:t})})});rp.displayName=ha;var sp="AccordionContent",op=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=co($t,r),a=ji(sp,r),i=_i(r);return n.jsx(nS,{role:"region","aria-labelledby":a.triggerId,"data-orientation":o.orientation,...i,...s,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});op.displayName=sp;function ap(e){return e?"open":"closed"}var mS=Ym,ip=ep,pS=np,cp=rp,lp=op;const dp=mS,Sr=x.forwardRef(({className:e,...t},r)=>n.jsx(ip,{ref:r,className:H("border-b border-neutral-200 dark:border-neutral-800",e),...t}));Sr.displayName=ip.displayName;const Cr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(pS,{className:"flex",children:n.jsxs(cp,{ref:s,className:H("flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline",e),...r,children:[t,n.jsx("span",{className:"ml-3 text-neutral-500 dark:text-neutral-400","aria-hidden":!0,children:"▾"})]})}));Cr.displayName=cp.displayName;const Nr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(lp,{ref:s,className:H("overflow-hidden text-sm",e),...r,children:n.jsx("div",{className:"pb-4 pt-0",children:t})}));Nr.displayName=lp.displayName;var Bo="rovingFocusGroup.onEntryFocus",fS={bubbles:!1,cancelable:!0},Br="RovingFocusGroup",[ga,up,hS]=Ya(Br),[gS,mp]=vn(Br,[hS]),[xS,yS]=gS(Br),pp=x.forwardRef((e,t)=>n.jsx(ga.Provider,{scope:e.__scopeRovingFocusGroup,children:n.jsx(ga.Slot,{scope:e.__scopeRovingFocusGroup,children:n.jsx(bS,{...e,ref:t})})}));pp.displayName=Br;var bS=x.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,orientation:s,loop:o=!1,dir:a,currentTabStopId:i,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:m=!1,...u}=e,p=x.useRef(null),h=Ee(t,p),_=Fs(a),[g,f]=hn({prop:i,defaultProp:c??null,onChange:l,caller:Br}),[w,j]=x.useState(!1),v=mn(d),b=up(r),k=x.useRef(!1),[R,N]=x.useState(0);return x.useEffect(()=>{const C=p.current;if(C)return C.addEventListener(Bo,v),()=>C.removeEventListener(Bo,v)},[v]),n.jsx(xS,{scope:r,orientation:s,dir:_,loop:o,currentTabStopId:g,onItemFocus:x.useCallback(C=>f(C),[f]),onItemShiftTab:x.useCallback(()=>j(!0),[]),onFocusableItemAdd:x.useCallback(()=>N(C=>C+1),[]),onFocusableItemRemove:x.useCallback(()=>N(C=>C-1),[]),children:n.jsx(ve.div,{tabIndex:w||R===0?-1:0,"data-orientation":s,...u,ref:h,style:{outline:"none",...e.style},onMouseDown:_e(e.onMouseDown,()=>{k.current=!0}),onFocus:_e(e.onFocus,C=>{const T=!k.current;if(C.target===C.currentTarget&&T&&!w){const O=new CustomEvent(Bo,fS);if(C.currentTarget.dispatchEvent(O),!O.defaultPrevented){const $=b().filter(D=>D.focusable),S=$.find(D=>D.active),A=$.find(D=>D.id===g),B=[S,A,...$].filter(Boolean).map(D=>D.ref.current);gp(B,m)}}k.current=!1}),onBlur:_e(e.onBlur,()=>j(!1))})})}),fp="RovingFocusGroupItem",hp=x.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,focusable:s=!0,active:o=!1,tabStopId:a,children:i,...c}=e,l=qt(),d=a||l,m=yS(fp,r),u=m.currentTabStopId===d,p=up(r),{onFocusableItemAdd:h,onFocusableItemRemove:_,currentTabStopId:g}=m;return x.useEffect(()=>{if(s)return h(),()=>_()},[s,h,_]),n.jsx(ga.ItemSlot,{scope:r,id:d,focusable:s,active:o,children:n.jsx(ve.span,{tabIndex:u?0:-1,"data-orientation":m.orientation,...c,ref:t,onMouseDown:_e(e.onMouseDown,f=>{s?m.onItemFocus(d):f.preventDefault()}),onFocus:_e(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:_e(e.onKeyDown,f=>{if(f.key==="Tab"&&f.shiftKey){m.onItemShiftTab();return}if(f.target!==f.currentTarget)return;const w=_S(f,m.orientation,m.dir);if(w!==void 0){if(f.metaKey||f.ctrlKey||f.altKey||f.shiftKey)return;f.preventDefault();let v=p().filter(b=>b.focusable).map(b=>b.ref.current);if(w==="last")v.reverse();else if(w==="prev"||w==="next"){w==="prev"&&v.reverse();const b=v.indexOf(f.currentTarget);v=m.loop?jS(v,b+1):v.slice(b+1)}setTimeout(()=>gp(v))}}),children:typeof i=="function"?i({isCurrentTabStop:u,hasTabStop:g!=null}):i})})});hp.displayName=fp;var vS={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function wS(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function _S(e,t,r){const s=wS(e.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(s))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(s)))return vS[s]}function gp(e,t=!1){const r=document.activeElement;for(const s of e)if(s===r||(s.focus({preventScroll:t}),document.activeElement!==r))return}function jS(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var kS=pp,SS=hp,lo="Tabs",[CS]=vn(lo,[mp]),xp=mp(),[NS,ki]=CS(lo),yp=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,onValueChange:o,defaultValue:a,orientation:i="horizontal",dir:c,activationMode:l="automatic",...d}=e,m=Fs(c),[u,p]=hn({prop:s,onChange:o,defaultProp:a??"",caller:lo});return n.jsx(NS,{scope:r,baseId:qt(),value:u,onValueChange:p,orientation:i,dir:m,activationMode:l,children:n.jsx(ve.div,{dir:m,"data-orientation":i,...d,ref:t})})});yp.displayName=lo;var bp="TabsList",vp=x.forwardRef((e,t)=>{const{__scopeTabs:r,loop:s=!0,...o}=e,a=ki(bp,r),i=xp(r);return n.jsx(kS,{asChild:!0,...i,orientation:a.orientation,dir:a.dir,loop:s,children:n.jsx(ve.div,{role:"tablist","aria-orientation":a.orientation,...o,ref:t})})});vp.displayName=bp;var wp="TabsTrigger",_p=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,disabled:o=!1,...a}=e,i=ki(wp,r),c=xp(r),l=Sp(i.baseId,s),d=Cp(i.baseId,s),m=s===i.value;return n.jsx(SS,{asChild:!0,...c,focusable:!o,active:m,children:n.jsx(ve.button,{type:"button",role:"tab","aria-selected":m,"aria-controls":d,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:l,...a,ref:t,onMouseDown:_e(e.onMouseDown,u=>{!o&&u.button===0&&u.ctrlKey===!1?i.onValueChange(s):u.preventDefault()}),onKeyDown:_e(e.onKeyDown,u=>{[" ","Enter"].includes(u.key)&&i.onValueChange(s)}),onFocus:_e(e.onFocus,()=>{const u=i.activationMode!=="manual";!m&&!o&&u&&i.onValueChange(s)})})})});_p.displayName=wp;var jp="TabsContent",kp=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,forceMount:o,children:a,...i}=e,c=ki(jp,r),l=Sp(c.baseId,s),d=Cp(c.baseId,s),m=s===c.value,u=x.useRef(m);return x.useEffect(()=>{const p=requestAnimationFrame(()=>u.current=!1);return()=>cancelAnimationFrame(p)},[]),n.jsx(mr,{present:o||m,children:({present:p})=>n.jsx(ve.div,{"data-state":m?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!p,id:d,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:u.current?"0s":void 0},children:p&&a})})});kp.displayName=jp;function Sp(e,t){return`${e}-trigger-${t}`}function Cp(e,t){return`${e}-content-${t}`}var PS=yp,Np=vp,Pp=_p,Ap=kp;const Si=PS,uo=x.forwardRef(({className:e,...t},r)=>n.jsx(Np,{ref:r,className:H("inline-flex h-10 items-center justify-center rounded-md bg-neutral-100 p-1 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400",e),...t}));uo.displayName=Np.displayName;const Lr=x.forwardRef(({className:e,...t},r)=>n.jsx(Pp,{ref:r,className:H("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-neutral-950 data-[state=active]:shadow-sm dark:ring-offset-neutral-950 dark:focus-visible:ring-neutral-50/20 dark:data-[state=active]:bg-neutral-950 dark:data-[state=active]:text-neutral-50",e),...t}));Lr.displayName=Pp.displayName;const Ep=x.forwardRef(({className:e,...t},r)=>n.jsx(Ap,{ref:r,className:H("mt-2 ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 dark:ring-offset-neutral-950 dark:focus-visible:ring-neutral-50/20",e),...t}));Ep.displayName=Ap.displayName;function tr({title:e,description:t,actionLabel:r,onAction:s,className:o}){return n.jsx("div",{className:H("flex flex-col items-center justify-center rounded-xl border border-neutral-200 bg-white p-10 text-center dark:border-neutral-800 dark:bg-neutral-950",o),children:n.jsxs("div",{className:"max-w-sm",children:[n.jsx("h3",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:e}),t?n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}):null,r&&s?n.jsx("div",{className:"mt-5",children:n.jsx(ie,{type:"button",onClick:s,variant:"secondary",children:r})}):null]})})}function Zt({title:e,description:t,onRetry:r,className:s}){return n.jsxs("div",{className:H("rounded-xl border border-neutral-200 bg-white p-6 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h3",{className:"text-sm font-semibold",children:e??"Something went wrong"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}),r?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"Try again"})}):null]})}class AS extends x.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error):n.jsx(Zt,{description:this.state.error.message}):this.props.children}}function ES(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}const TS=e=>{switch(e){case"success":return OS;case"info":return DS;case"warning":return MS;case"error":return LS;default:return null}},IS=Array(12).fill(0),RS=({visible:e,className:t})=>y.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},y.createElement("div",{className:"sonner-spinner"},IS.map((r,s)=>y.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),OS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),MS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),DS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),LS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),$S=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},y.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),zS=()=>{const[e,t]=y.useState(document.hidden);return y.useEffect(()=>{const r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),e};let xa=1;class FS{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const r=this.subscribers.indexOf(t);this.subscribers.splice(r,1)}),this.publish=t=>{this.subscribers.forEach(r=>r(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var r;const{message:s,...o}=t,a=typeof t?.id=="number"||((r=t.id)==null?void 0:r.length)>0?t.id:xa++,i=this.toasts.find(l=>l.id===a),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(a)&&this.dismissedToasts.delete(a),i?this.toasts=this.toasts.map(l=>l.id===a?(this.publish({...l,...t,id:a,title:s}),{...l,...t,id:a,dismissible:c,title:s}):l):this.addToast({title:s,...o,dismissible:c,id:a}),a},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(r=>r({id:t,dismiss:!0})))):this.toasts.forEach(r=>{this.subscribers.forEach(s=>s({id:r.id,dismiss:!0}))}),t),this.message=(t,r)=>this.create({...r,message:t}),this.error=(t,r)=>this.create({...r,message:t,type:"error"}),this.success=(t,r)=>this.create({...r,type:"success",message:t}),this.info=(t,r)=>this.create({...r,type:"info",message:t}),this.warning=(t,r)=>this.create({...r,type:"warning",message:t}),this.loading=(t,r)=>this.create({...r,type:"loading",message:t}),this.promise=(t,r)=>{if(!r)return;let s;r.loading!==void 0&&(s=this.create({...r,promise:t,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));const o=Promise.resolve(t instanceof Function?t():t);let a=s!==void 0,i;const c=o.then(async d=>{if(i=["resolve",d],y.isValidElement(d))a=!1,this.create({id:s,type:"default",message:d});else if(US(d)&&!d.ok){a=!1;const u=typeof r.error=="function"?await r.error(`HTTP error! status: ${d.status}`):r.error,p=typeof r.description=="function"?await r.description(`HTTP error! status: ${d.status}`):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,..._})}else if(d instanceof Error){a=!1;const u=typeof r.error=="function"?await r.error(d):r.error,p=typeof r.description=="function"?await r.description(d):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,..._})}else if(r.success!==void 0){a=!1;const u=typeof r.success=="function"?await r.success(d):r.success,p=typeof r.description=="function"?await r.description(d):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"success",description:p,..._})}}).catch(async d=>{if(i=["reject",d],r.error!==void 0){a=!1;const m=typeof r.error=="function"?await r.error(d):r.error,u=typeof r.description=="function"?await r.description(d):r.description,h=typeof m=="object"&&!y.isValidElement(m)?m:{message:m};this.create({id:s,type:"error",description:u,...h})}}).finally(()=>{a&&(this.dismiss(s),s=void 0),r.finally==null||r.finally.call(r)}),l=()=>new Promise((d,m)=>c.then(()=>i[0]==="reject"?m(i[1]):d(i[1])).catch(m));return typeof s!="string"&&typeof s!="number"?{unwrap:l}:Object.assign(s,{unwrap:l})},this.custom=(t,r)=>{const s=r?.id||xa++;return this.create({jsx:t(s),id:s,...r}),s},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ht=new FS,BS=(e,t)=>{const r=t?.id||xa++;return ht.addToast({title:e,...t,id:r}),r},US=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",WS=BS,VS=()=>ht.toasts,qS=()=>ht.getActiveToasts(),HS=Object.assign(WS,{success:ht.success,info:ht.info,warning:ht.warning,error:ht.error,custom:ht.custom,message:ht.message,promise:ht.promise,dismiss:ht.dismiss,loading:ht.loading},{getHistory:VS,getToasts:qS});ES("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function ss(e){return e.label!==void 0}const ZS=3,GS="24px",QS="16px",cl=4e3,YS=356,KS=14,XS=45,JS=200;function Bt(...e){return e.filter(Boolean).join(" ")}function eC(e){const[t,r]=e.split("-"),s=[];return t&&s.push(t),r&&s.push(r),s}const tC=e=>{var t,r,s,o,a,i,c,l,d;const{invert:m,toast:u,unstyled:p,interacting:h,setHeights:_,visibleToasts:g,heights:f,index:w,toasts:j,expanded:v,removeToast:b,defaultRichColors:k,closeButton:R,style:N,cancelButtonStyle:C,actionButtonStyle:T,className:O="",descriptionClassName:$="",duration:S,position:A,gap:I,expandByDefault:B,classNames:D,icons:E,closeButtonAriaLabel:P="Close toast"}=e,[z,Z]=y.useState(null),[K,L]=y.useState(null),[W,Y]=y.useState(!1),[V,ce]=y.useState(!1),[F,ee]=y.useState(!1),[pe,q]=y.useState(!1),[ne,le]=y.useState(!1),[fe,Pe]=y.useState(0),[Ve,qe]=y.useState(0),He=y.useRef(u.duration||S||cl),xt=y.useRef(null),Ge=y.useRef(null),zt=w===0,lt=w+1<=g,te=u.type,xe=u.dismissible!==!1,ge=u.className||"",dt=u.descriptionClassName||"",yt=y.useMemo(()=>f.findIndex(he=>he.toastId===u.id)||0,[f,u.id]),ut=y.useMemo(()=>{var he;return(he=u.closeButton)!=null?he:R},[u.closeButton,R]),U=y.useMemo(()=>u.duration||S||cl,[u.duration,S]),re=y.useRef(0),de=y.useRef(0),ke=y.useRef(0),Se=y.useRef(null),[Me,Fn]=A.split("-"),jt=y.useMemo(()=>f.reduce((he,Le,we)=>we>=yt?he:he+Le.height,0),[f,yt]),Xt=zS(),pr=u.invert||m,jn=te==="loading";de.current=y.useMemo(()=>yt*I+jt,[yt,jt]),y.useEffect(()=>{He.current=U},[U]),y.useEffect(()=>{Y(!0)},[]),y.useEffect(()=>{const he=Ge.current;if(he){const Le=he.getBoundingClientRect().height;return qe(Le),_(we=>[{toastId:u.id,height:Le,position:u.position},...we]),()=>_(we=>we.filter($e=>$e.toastId!==u.id))}},[_,u.id]),y.useLayoutEffect(()=>{if(!W)return;const he=Ge.current,Le=he.style.height;he.style.height="auto";const we=he.getBoundingClientRect().height;he.style.height=Le,qe(we),_($e=>$e.find(ze=>ze.toastId===u.id)?$e.map(ze=>ze.toastId===u.id?{...ze,height:we}:ze):[{toastId:u.id,height:we,position:u.position},...$e])},[W,u.title,u.description,_,u.id,u.jsx,u.action,u.cancel]);const Ft=y.useCallback(()=>{ce(!0),Pe(de.current),_(he=>he.filter(Le=>Le.toastId!==u.id)),setTimeout(()=>{b(u)},JS)},[u,b,_,de]);y.useEffect(()=>{if(u.promise&&te==="loading"||u.duration===1/0||u.type==="loading")return;let he;return v||h||Xt?(()=>{if(ke.current<re.current){const $e=new Date().getTime()-re.current;He.current=He.current-$e}ke.current=new Date().getTime()})():(()=>{He.current!==1/0&&(re.current=new Date().getTime(),he=setTimeout(()=>{u.onAutoClose==null||u.onAutoClose.call(u,u),Ft()},He.current))})(),()=>clearTimeout(he)},[v,h,u,te,Xt,Ft]),y.useEffect(()=>{u.delete&&(Ft(),u.onDismiss==null||u.onDismiss.call(u,u))},[Ft,u.delete]);function Bn(){var he;if(E?.loading){var Le;return y.createElement("div",{className:Bt(D?.loader,u==null||(Le=u.classNames)==null?void 0:Le.loader,"sonner-loader"),"data-visible":te==="loading"},E.loading)}return y.createElement(RS,{className:Bt(D?.loader,u==null||(he=u.classNames)==null?void 0:he.loader),visible:te==="loading"})}const Un=u.icon||E?.[te]||TS(te);var Ur,on;return y.createElement("li",{tabIndex:0,ref:Ge,className:Bt(O,ge,D?.toast,u==null||(t=u.classNames)==null?void 0:t.toast,D?.default,D?.[te],u==null||(r=u.classNames)==null?void 0:r[te]),"data-sonner-toast":"","data-rich-colors":(Ur=u.richColors)!=null?Ur:k,"data-styled":!(u.jsx||u.unstyled||p),"data-mounted":W,"data-promise":!!u.promise,"data-swiped":ne,"data-removed":V,"data-visible":lt,"data-y-position":Me,"data-x-position":Fn,"data-index":w,"data-front":zt,"data-swiping":F,"data-dismissible":xe,"data-type":te,"data-invert":pr,"data-swipe-out":pe,"data-swipe-direction":K,"data-expanded":!!(v||B&&W),"data-testid":u.testId,style:{"--index":w,"--toasts-before":w,"--z-index":j.length-w,"--offset":`${V?fe:de.current}px`,"--initial-height":B?"auto":`${Ve}px`,...N,...u.style},onDragEnd:()=>{ee(!1),Z(null),Se.current=null},onPointerDown:he=>{he.button!==2&&(jn||!xe||(xt.current=new Date,Pe(de.current),he.target.setPointerCapture(he.pointerId),he.target.tagName!=="BUTTON"&&(ee(!0),Se.current={x:he.clientX,y:he.clientY})))},onPointerUp:()=>{var he,Le,we;if(pe||!xe)return;Se.current=null;const $e=Number(((he=Ge.current)==null?void 0:he.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Wn=Number(((Le=Ge.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),ze=new Date().getTime()-((we=xt.current)==null?void 0:we.getTime()),Je=z==="x"?$e:Wn,kn=Math.abs(Je)/ze;if(Math.abs(Je)>=XS||kn>.11){Pe(de.current),u.onDismiss==null||u.onDismiss.call(u,u),L(z==="x"?$e>0?"right":"left":Wn>0?"down":"up"),Ft(),q(!0);return}else{var mt,bt;(mt=Ge.current)==null||mt.style.setProperty("--swipe-amount-x","0px"),(bt=Ge.current)==null||bt.style.setProperty("--swipe-amount-y","0px")}le(!1),ee(!1),Z(null)},onPointerMove:he=>{var Le,we,$e;if(!Se.current||!xe||((Le=window.getSelection())==null?void 0:Le.toString().length)>0)return;const ze=he.clientY-Se.current.y,Je=he.clientX-Se.current.x;var kn;const mt=(kn=e.swipeDirections)!=null?kn:eC(A);!z&&(Math.abs(Je)>1||Math.abs(ze)>1)&&Z(Math.abs(Je)>Math.abs(ze)?"x":"y");let bt={x:0,y:0};const vt=tt=>1/(1.5+Math.abs(tt)/20);if(z==="y"){if(mt.includes("top")||mt.includes("bottom"))if(mt.includes("top")&&ze<0||mt.includes("bottom")&&ze>0)bt.y=ze;else{const tt=ze*vt(ze);bt.y=Math.abs(tt)<Math.abs(ze)?tt:ze}}else if(z==="x"&&(mt.includes("left")||mt.includes("right")))if(mt.includes("left")&&Je<0||mt.includes("right")&&Je>0)bt.x=Je;else{const tt=Je*vt(Je);bt.x=Math.abs(tt)<Math.abs(Je)?tt:Je}(Math.abs(bt.x)>0||Math.abs(bt.y)>0)&&le(!0),(we=Ge.current)==null||we.style.setProperty("--swipe-amount-x",`${bt.x}px`),($e=Ge.current)==null||$e.style.setProperty("--swipe-amount-y",`${bt.y}px`)}},ut&&!u.jsx&&te!=="loading"?y.createElement("button",{"aria-label":P,"data-disabled":jn,"data-close-button":!0,onClick:jn||!xe?()=>{}:()=>{Ft(),u.onDismiss==null||u.onDismiss.call(u,u)},className:Bt(D?.closeButton,u==null||(s=u.classNames)==null?void 0:s.closeButton)},(on=E?.close)!=null?on:$S):null,(te||u.icon||u.promise)&&u.icon!==null&&(E?.[te]!==null||u.icon)?y.createElement("div",{"data-icon":"",className:Bt(D?.icon,u==null||(o=u.classNames)==null?void 0:o.icon)},u.promise||u.type==="loading"&&!u.icon?u.icon||Bn():null,u.type!=="loading"?Un:null):null,y.createElement("div",{"data-content":"",className:Bt(D?.content,u==null||(a=u.classNames)==null?void 0:a.content)},y.createElement("div",{"data-title":"",className:Bt(D?.title,u==null||(i=u.classNames)==null?void 0:i.title)},u.jsx?u.jsx:typeof u.title=="function"?u.title():u.title),u.description?y.createElement("div",{"data-description":"",className:Bt($,dt,D?.description,u==null||(c=u.classNames)==null?void 0:c.description)},typeof u.description=="function"?u.description():u.description):null),y.isValidElement(u.cancel)?u.cancel:u.cancel&&ss(u.cancel)?y.createElement("button",{"data-button":!0,"data-cancel":!0,style:u.cancelButtonStyle||C,onClick:he=>{ss(u.cancel)&&xe&&(u.cancel.onClick==null||u.cancel.onClick.call(u.cancel,he),Ft())},className:Bt(D?.cancelButton,u==null||(l=u.classNames)==null?void 0:l.cancelButton)},u.cancel.label):null,y.isValidElement(u.action)?u.action:u.action&&ss(u.action)?y.createElement("button",{"data-button":!0,"data-action":!0,style:u.actionButtonStyle||T,onClick:he=>{ss(u.action)&&(u.action.onClick==null||u.action.onClick.call(u.action,he),!he.defaultPrevented&&Ft())},className:Bt(D?.actionButton,u==null||(d=u.classNames)==null?void 0:d.actionButton)},u.action.label):null)};function ll(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function nC(e,t){const r={};return[e,t].forEach((s,o)=>{const a=o===1,i=a?"--mobile-offset":"--offset",c=a?QS:GS;function l(d){["top","right","bottom","left"].forEach(m=>{r[`${i}-${m}`]=typeof d=="number"?`${d}px`:d})}typeof s=="number"||typeof s=="string"?l(s):typeof s=="object"?["top","right","bottom","left"].forEach(d=>{s[d]===void 0?r[`${i}-${d}`]=c:r[`${i}-${d}`]=typeof s[d]=="number"?`${s[d]}px`:s[d]}):l(c)}),r}const rC=y.forwardRef(function(t,r){const{id:s,invert:o,position:a="bottom-right",hotkey:i=["altKey","KeyT"],expand:c,closeButton:l,className:d,offset:m,mobileOffset:u,theme:p="light",richColors:h,duration:_,style:g,visibleToasts:f=ZS,toastOptions:w,dir:j=ll(),gap:v=KS,icons:b,containerAriaLabel:k="Notifications"}=t,[R,N]=y.useState([]),C=y.useMemo(()=>s?R.filter(W=>W.toasterId===s):R.filter(W=>!W.toasterId),[R,s]),T=y.useMemo(()=>Array.from(new Set([a].concat(C.filter(W=>W.position).map(W=>W.position)))),[C,a]),[O,$]=y.useState([]),[S,A]=y.useState(!1),[I,B]=y.useState(!1),[D,E]=y.useState(p!=="system"?p:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),P=y.useRef(null),z=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),Z=y.useRef(null),K=y.useRef(!1),L=y.useCallback(W=>{N(Y=>{var V;return(V=Y.find(ce=>ce.id===W.id))!=null&&V.delete||ht.dismiss(W.id),Y.filter(({id:ce})=>ce!==W.id)})},[]);return y.useEffect(()=>ht.subscribe(W=>{if(W.dismiss){requestAnimationFrame(()=>{N(Y=>Y.map(V=>V.id===W.id?{...V,delete:!0}:V))});return}setTimeout(()=>{ka.flushSync(()=>{N(Y=>{const V=Y.findIndex(ce=>ce.id===W.id);return V!==-1?[...Y.slice(0,V),{...Y[V],...W},...Y.slice(V+1)]:[W,...Y]})})})}),[R]),y.useEffect(()=>{if(p!=="system"){E(p);return}if(p==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?E("dark"):E("light")),typeof window>"u")return;const W=window.matchMedia("(prefers-color-scheme: dark)");try{W.addEventListener("change",({matches:Y})=>{E(Y?"dark":"light")})}catch{W.addListener(({matches:V})=>{try{E(V?"dark":"light")}catch(ce){console.error(ce)}})}},[p]),y.useEffect(()=>{R.length<=1&&A(!1)},[R]),y.useEffect(()=>{const W=Y=>{var V;if(i.every(ee=>Y[ee]||Y.code===ee)){var F;A(!0),(F=P.current)==null||F.focus()}Y.code==="Escape"&&(document.activeElement===P.current||(V=P.current)!=null&&V.contains(document.activeElement))&&A(!1)};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[i]),y.useEffect(()=>{if(P.current)return()=>{Z.current&&(Z.current.focus({preventScroll:!0}),Z.current=null,K.current=!1)}},[P.current]),y.createElement("section",{ref:r,"aria-label":`${k} ${z}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},T.map((W,Y)=>{var V;const[ce,F]=W.split("-");return C.length?y.createElement("ol",{key:W,dir:j==="auto"?ll():j,tabIndex:-1,ref:P,className:d,"data-sonner-toaster":!0,"data-sonner-theme":D,"data-y-position":ce,"data-x-position":F,style:{"--front-toast-height":`${((V=O[0])==null?void 0:V.height)||0}px`,"--width":`${YS}px`,"--gap":`${v}px`,...g,...nC(m,u)},onBlur:ee=>{K.current&&!ee.currentTarget.contains(ee.relatedTarget)&&(K.current=!1,Z.current&&(Z.current.focus({preventScroll:!0}),Z.current=null))},onFocus:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||K.current||(K.current=!0,Z.current=ee.relatedTarget)},onMouseEnter:()=>A(!0),onMouseMove:()=>A(!0),onMouseLeave:()=>{I||A(!1)},onDragEnd:()=>A(!1),onPointerDown:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||B(!0)},onPointerUp:()=>B(!1)},C.filter(ee=>!ee.position&&Y===0||ee.position===W).map((ee,pe)=>{var q,ne;return y.createElement(tC,{key:ee.id,icons:b,index:pe,toast:ee,defaultRichColors:h,duration:(q=w?.duration)!=null?q:_,className:w?.className,descriptionClassName:w?.descriptionClassName,invert:o,visibleToasts:f,closeButton:(ne=w?.closeButton)!=null?ne:l,interacting:I,position:W,style:w?.style,unstyled:w?.unstyled,classNames:w?.classNames,cancelButtonStyle:w?.cancelButtonStyle,actionButtonStyle:w?.actionButtonStyle,closeButtonAriaLabel:w?.closeButtonAriaLabel,removeToast:L,toasts:C.filter(le=>le.position==ee.position),heights:O.filter(le=>le.position==ee.position),setHeights:$,expandByDefault:c,gap:v,expanded:S,swipeDirections:t.swipeDirections})})):null}))}),Ci=x.createContext(null);function sC(){const e=x.useContext(Ci);if(!e)throw new Error("useToast must be used within ToastProvider");return e}function mo(){return x.useContext(Ci)}function oC({children:e}){const t=x.useCallback(r=>{const s=r.title??"",o=r.description;HS(s||o||"Notification",{description:s?o:void 0,duration:r.durationMs??5e3,action:r.actionLabel&&r.onAction?{label:r.actionLabel,onClick:()=>r.onAction?.()}:void 0})},[]);return n.jsxs(Ci.Provider,{value:{toast:t},children:[e,n.jsx(rC,{position:"top-center",closeButton:!0,expand:!0,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:pointer-events-auto group-[.toaster]:w-full group-[.toaster]:rounded-xl group-[.toaster]:border group-[.toaster]:border-neutral-200 group-[.toaster]:bg-white group-[.toaster]:p-4 group-[.toaster]:shadow-lg dark:group-[.toaster]:border-neutral-800 dark:group-[.toaster]:bg-neutral-950",title:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",description:"text-sm text-neutral-600 dark:text-neutral-400",actionButton:"h-8 rounded-md border border-neutral-200 bg-white px-3 text-xs font-medium text-neutral-900 shadow-sm hover:bg-neutral-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:hover:bg-neutral-900",cancelButton:"h-8 rounded-md bg-neutral-100 px-3 text-xs font-medium text-neutral-900 hover:bg-neutral-200 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-700",closeButton:"rounded-md text-neutral-600 opacity-0 transition-opacity hover:bg-neutral-100 hover:text-neutral-900 group-hover:opacity-100 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-neutral-50"}}})]})}const{entries:Tp,setPrototypeOf:dl,isFrozen:aC,getPrototypeOf:iC,getOwnPropertyDescriptor:cC}=Object;let{freeze:it,seal:Ct,create:ya}=Object,{apply:ba,construct:va}=typeof Reflect<"u"&&Reflect;it||(it=function(t){return t});Ct||(Ct=function(t){return t});ba||(ba=function(t,r){for(var s=arguments.length,o=new Array(s>2?s-2:0),a=2;a<s;a++)o[a-2]=arguments[a];return t.apply(r,o)});va||(va=function(t){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return new t(...s)});const os=ct(Array.prototype.forEach),lC=ct(Array.prototype.lastIndexOf),ul=ct(Array.prototype.pop),gr=ct(Array.prototype.push),dC=ct(Array.prototype.splice),ms=ct(String.prototype.toLowerCase),Uo=ct(String.prototype.toString),Wo=ct(String.prototype.match),xr=ct(String.prototype.replace),uC=ct(String.prototype.indexOf),mC=ct(String.prototype.trim),It=ct(Object.prototype.hasOwnProperty),nt=ct(RegExp.prototype.test),yr=pC(TypeError);function ct(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return ba(e,t,s)}}function pC(e){return function(){for(var t=arguments.length,r=new Array(t),s=0;s<t;s++)r[s]=arguments[s];return va(e,r)}}function be(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ms;dl&&dl(e,null);let s=t.length;for(;s--;){let o=t[s];if(typeof o=="string"){const a=r(o);a!==o&&(aC(t)||(t[s]=a),o=a)}e[o]=!0}return e}function fC(e){for(let t=0;t<e.length;t++)It(e,t)||(e[t]=null);return e}function Ut(e){const t=ya(null);for(const[r,s]of Tp(e))It(e,r)&&(Array.isArray(s)?t[r]=fC(s):s&&typeof s=="object"&&s.constructor===Object?t[r]=Ut(s):t[r]=s);return t}function br(e,t){for(;e!==null;){const s=cC(e,t);if(s){if(s.get)return ct(s.get);if(typeof s.value=="function")return ct(s.value)}e=iC(e)}function r(){return null}return r}const ml=it(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Vo=it(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),qo=it(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),hC=it(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ho=it(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),gC=it(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),pl=it(["#text"]),fl=it(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Zo=it(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),hl=it(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),as=it(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),xC=Ct(/\{\{[\w\W]*|[\w\W]*\}\}/gm),yC=Ct(/<%[\w\W]*|[\w\W]*%>/gm),bC=Ct(/\$\{[\w\W]*/gm),vC=Ct(/^data-[\-\w.\u00B7-\uFFFF]+$/),wC=Ct(/^aria-[\-\w]+$/),Ip=Ct(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),_C=Ct(/^(?:\w+script|data):/i),jC=Ct(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Rp=Ct(/^html$/i),kC=Ct(/^[a-z][.\w]*(-[.\w]+)+$/i);var gl=Object.freeze({__proto__:null,ARIA_ATTR:wC,ATTR_WHITESPACE:jC,CUSTOM_ELEMENT:kC,DATA_ATTR:vC,DOCTYPE_NAME:Rp,ERB_EXPR:yC,IS_ALLOWED_URI:Ip,IS_SCRIPT_OR_DATA:_C,MUSTACHE_EXPR:xC,TMPLIT_EXPR:bC});const vr={element:1,text:3,progressingInstruction:7,comment:8,document:9},SC=function(){return typeof window>"u"?null:window},CC=function(t,r){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(s=r.getAttribute(o));const a="dompurify"+(s?"#"+s:"");try{return t.createPolicy(a,{createHTML(i){return i},createScriptURL(i){return i}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},xl=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Op(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:SC();const t=ue=>Op(ue);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==vr.document||!e.Element)return t.isSupported=!1,t;let{document:r}=e;const s=r,o=s.currentScript,{DocumentFragment:a,HTMLTemplateElement:i,Node:c,Element:l,NodeFilter:d,NamedNodeMap:m=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:p,trustedTypes:h}=e,_=l.prototype,g=br(_,"cloneNode"),f=br(_,"remove"),w=br(_,"nextSibling"),j=br(_,"childNodes"),v=br(_,"parentNode");if(typeof i=="function"){const ue=r.createElement("template");ue.content&&ue.content.ownerDocument&&(r=ue.content.ownerDocument)}let b,k="";const{implementation:R,createNodeIterator:N,createDocumentFragment:C,getElementsByTagName:T}=r,{importNode:O}=s;let $=xl();t.isSupported=typeof Tp=="function"&&typeof v=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:S,ERB_EXPR:A,TMPLIT_EXPR:I,DATA_ATTR:B,ARIA_ATTR:D,IS_SCRIPT_OR_DATA:E,ATTR_WHITESPACE:P,CUSTOM_ELEMENT:z}=gl;let{IS_ALLOWED_URI:Z}=gl,K=null;const L=be({},[...ml,...Vo,...qo,...Ho,...pl]);let W=null;const Y=be({},[...fl,...Zo,...hl,...as]);let V=Object.seal(ya(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ce=null,F=null;const ee=Object.seal(ya(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let pe=!0,q=!0,ne=!1,le=!0,fe=!1,Pe=!0,Ve=!1,qe=!1,He=!1,xt=!1,Ge=!1,zt=!1,lt=!0,te=!1;const xe="user-content-";let ge=!0,dt=!1,yt={},ut=null;const U=be({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let re=null;const de=be({},["audio","video","img","source","image","track"]);let ke=null;const Se=be({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Me="http://www.w3.org/1998/Math/MathML",Fn="http://www.w3.org/2000/svg",jt="http://www.w3.org/1999/xhtml";let Xt=jt,pr=!1,jn=null;const Ft=be({},[Me,Fn,jt],Uo);let Bn=be({},["mi","mo","mn","ms","mtext"]),Un=be({},["annotation-xml"]);const Ur=be({},["title","style","font","a","script"]);let on=null;const he=["application/xhtml+xml","text/html"],Le="text/html";let we=null,$e=null;const Wn=r.createElement("form"),ze=function(M){return M instanceof RegExp||M instanceof Function},Je=function(){let M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!($e&&$e===M)){if((!M||typeof M!="object")&&(M={}),M=Ut(M),on=he.indexOf(M.PARSER_MEDIA_TYPE)===-1?Le:M.PARSER_MEDIA_TYPE,we=on==="application/xhtml+xml"?Uo:ms,K=It(M,"ALLOWED_TAGS")?be({},M.ALLOWED_TAGS,we):L,W=It(M,"ALLOWED_ATTR")?be({},M.ALLOWED_ATTR,we):Y,jn=It(M,"ALLOWED_NAMESPACES")?be({},M.ALLOWED_NAMESPACES,Uo):Ft,ke=It(M,"ADD_URI_SAFE_ATTR")?be(Ut(Se),M.ADD_URI_SAFE_ATTR,we):Se,re=It(M,"ADD_DATA_URI_TAGS")?be(Ut(de),M.ADD_DATA_URI_TAGS,we):de,ut=It(M,"FORBID_CONTENTS")?be({},M.FORBID_CONTENTS,we):U,ce=It(M,"FORBID_TAGS")?be({},M.FORBID_TAGS,we):Ut({}),F=It(M,"FORBID_ATTR")?be({},M.FORBID_ATTR,we):Ut({}),yt=It(M,"USE_PROFILES")?M.USE_PROFILES:!1,pe=M.ALLOW_ARIA_ATTR!==!1,q=M.ALLOW_DATA_ATTR!==!1,ne=M.ALLOW_UNKNOWN_PROTOCOLS||!1,le=M.ALLOW_SELF_CLOSE_IN_ATTR!==!1,fe=M.SAFE_FOR_TEMPLATES||!1,Pe=M.SAFE_FOR_XML!==!1,Ve=M.WHOLE_DOCUMENT||!1,xt=M.RETURN_DOM||!1,Ge=M.RETURN_DOM_FRAGMENT||!1,zt=M.RETURN_TRUSTED_TYPE||!1,He=M.FORCE_BODY||!1,lt=M.SANITIZE_DOM!==!1,te=M.SANITIZE_NAMED_PROPS||!1,ge=M.KEEP_CONTENT!==!1,dt=M.IN_PLACE||!1,Z=M.ALLOWED_URI_REGEXP||Ip,Xt=M.NAMESPACE||jt,Bn=M.MATHML_TEXT_INTEGRATION_POINTS||Bn,Un=M.HTML_INTEGRATION_POINTS||Un,V=M.CUSTOM_ELEMENT_HANDLING||{},M.CUSTOM_ELEMENT_HANDLING&&ze(M.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(V.tagNameCheck=M.CUSTOM_ELEMENT_HANDLING.tagNameCheck),M.CUSTOM_ELEMENT_HANDLING&&ze(M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(V.attributeNameCheck=M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),M.CUSTOM_ELEMENT_HANDLING&&typeof M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(V.allowCustomizedBuiltInElements=M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),fe&&(q=!1),Ge&&(xt=!0),yt&&(K=be({},pl),W=[],yt.html===!0&&(be(K,ml),be(W,fl)),yt.svg===!0&&(be(K,Vo),be(W,Zo),be(W,as)),yt.svgFilters===!0&&(be(K,qo),be(W,Zo),be(W,as)),yt.mathMl===!0&&(be(K,Ho),be(W,hl),be(W,as))),M.ADD_TAGS&&(typeof M.ADD_TAGS=="function"?ee.tagCheck=M.ADD_TAGS:(K===L&&(K=Ut(K)),be(K,M.ADD_TAGS,we))),M.ADD_ATTR&&(typeof M.ADD_ATTR=="function"?ee.attributeCheck=M.ADD_ATTR:(W===Y&&(W=Ut(W)),be(W,M.ADD_ATTR,we))),M.ADD_URI_SAFE_ATTR&&be(ke,M.ADD_URI_SAFE_ATTR,we),M.FORBID_CONTENTS&&(ut===U&&(ut=Ut(ut)),be(ut,M.FORBID_CONTENTS,we)),M.ADD_FORBID_CONTENTS&&(ut===U&&(ut=Ut(ut)),be(ut,M.ADD_FORBID_CONTENTS,we)),ge&&(K["#text"]=!0),Ve&&be(K,["html","head","body"]),K.table&&(be(K,["tbody"]),delete ce.tbody),M.TRUSTED_TYPES_POLICY){if(typeof M.TRUSTED_TYPES_POLICY.createHTML!="function")throw yr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof M.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw yr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');b=M.TRUSTED_TYPES_POLICY,k=b.createHTML("")}else b===void 0&&(b=CC(h,o)),b!==null&&typeof k=="string"&&(k=b.createHTML(""));it&&it(M),$e=M}},kn=be({},[...Vo,...qo,...hC]),mt=be({},[...Ho,...gC]),bt=function(M){let X=v(M);(!X||!X.tagName)&&(X={namespaceURI:Xt,tagName:"template"});const ae=ms(M.tagName),Ae=ms(X.tagName);return jn[M.namespaceURI]?M.namespaceURI===Fn?X.namespaceURI===jt?ae==="svg":X.namespaceURI===Me?ae==="svg"&&(Ae==="annotation-xml"||Bn[Ae]):!!kn[ae]:M.namespaceURI===Me?X.namespaceURI===jt?ae==="math":X.namespaceURI===Fn?ae==="math"&&Un[Ae]:!!mt[ae]:M.namespaceURI===jt?X.namespaceURI===Fn&&!Un[Ae]||X.namespaceURI===Me&&!Bn[Ae]?!1:!mt[ae]&&(Ur[ae]||!kn[ae]):!!(on==="application/xhtml+xml"&&jn[M.namespaceURI]):!1},vt=function(M){gr(t.removed,{element:M});try{v(M).removeChild(M)}catch{f(M)}},tt=function(M,X){try{gr(t.removed,{attribute:X.getAttributeNode(M),from:X})}catch{gr(t.removed,{attribute:null,from:X})}if(X.removeAttribute(M),M==="is")if(xt||Ge)try{vt(X)}catch{}else try{X.setAttribute(M,"")}catch{}},go=function(M){let X=null,ae=null;if(He)M="<remove></remove>"+M;else{const Fe=Wo(M,/^[\r\n\t ]+/);ae=Fe&&Fe[0]}on==="application/xhtml+xml"&&Xt===jt&&(M='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+M+"</body></html>");const Ae=b?b.createHTML(M):M;if(Xt===jt)try{X=new p().parseFromString(Ae,on)}catch{}if(!X||!X.documentElement){X=R.createDocument(Xt,"template",null);try{X.documentElement.innerHTML=pr?k:Ae}catch{}}const et=X.body||X.documentElement;return M&&ae&&et.insertBefore(r.createTextNode(ae),et.childNodes[0]||null),Xt===jt?T.call(X,Ve?"html":"body")[0]:Ve?X.documentElement:et},Li=function(M){return N.call(M.ownerDocument||M,M,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},xo=function(M){return M instanceof u&&(typeof M.nodeName!="string"||typeof M.textContent!="string"||typeof M.removeChild!="function"||!(M.attributes instanceof m)||typeof M.removeAttribute!="function"||typeof M.setAttribute!="function"||typeof M.namespaceURI!="string"||typeof M.insertBefore!="function"||typeof M.hasChildNodes!="function")},$i=function(M){return typeof c=="function"&&M instanceof c};function Jt(ue,M,X){os(ue,ae=>{ae.call(t,M,X,$e)})}const zi=function(M){let X=null;if(Jt($.beforeSanitizeElements,M,null),xo(M))return vt(M),!0;const ae=we(M.nodeName);if(Jt($.uponSanitizeElement,M,{tagName:ae,allowedTags:K}),Pe&&M.hasChildNodes()&&!$i(M.firstElementChild)&&nt(/<[/\w!]/g,M.innerHTML)&&nt(/<[/\w!]/g,M.textContent)||M.nodeType===vr.progressingInstruction||Pe&&M.nodeType===vr.comment&&nt(/<[/\w]/g,M.data))return vt(M),!0;if(!(ee.tagCheck instanceof Function&&ee.tagCheck(ae))&&(!K[ae]||ce[ae])){if(!ce[ae]&&Bi(ae)&&(V.tagNameCheck instanceof RegExp&&nt(V.tagNameCheck,ae)||V.tagNameCheck instanceof Function&&V.tagNameCheck(ae)))return!1;if(ge&&!ut[ae]){const Ae=v(M)||M.parentNode,et=j(M)||M.childNodes;if(et&&Ae){const Fe=et.length;for(let pt=Fe-1;pt>=0;--pt){const en=g(et[pt],!0);en.__removalCount=(M.__removalCount||0)+1,Ae.insertBefore(en,w(M))}}}return vt(M),!0}return M instanceof l&&!bt(M)||(ae==="noscript"||ae==="noembed"||ae==="noframes")&&nt(/<\/no(script|embed|frames)/i,M.innerHTML)?(vt(M),!0):(fe&&M.nodeType===vr.text&&(X=M.textContent,os([S,A,I],Ae=>{X=xr(X,Ae," ")}),M.textContent!==X&&(gr(t.removed,{element:M.cloneNode()}),M.textContent=X)),Jt($.afterSanitizeElements,M,null),!1)},Fi=function(M,X,ae){if(lt&&(X==="id"||X==="name")&&(ae in r||ae in Wn))return!1;if(!(q&&!F[X]&&nt(B,X))){if(!(pe&&nt(D,X))){if(!(ee.attributeCheck instanceof Function&&ee.attributeCheck(X,M))){if(!W[X]||F[X]){if(!(Bi(M)&&(V.tagNameCheck instanceof RegExp&&nt(V.tagNameCheck,M)||V.tagNameCheck instanceof Function&&V.tagNameCheck(M))&&(V.attributeNameCheck instanceof RegExp&&nt(V.attributeNameCheck,X)||V.attributeNameCheck instanceof Function&&V.attributeNameCheck(X,M))||X==="is"&&V.allowCustomizedBuiltInElements&&(V.tagNameCheck instanceof RegExp&&nt(V.tagNameCheck,ae)||V.tagNameCheck instanceof Function&&V.tagNameCheck(ae))))return!1}else if(!ke[X]){if(!nt(Z,xr(ae,P,""))){if(!((X==="src"||X==="xlink:href"||X==="href")&&M!=="script"&&uC(ae,"data:")===0&&re[M])){if(!(ne&&!nt(E,xr(ae,P,"")))){if(ae)return!1}}}}}}}return!0},Bi=function(M){return M!=="annotation-xml"&&Wo(M,z)},Ui=function(M){Jt($.beforeSanitizeAttributes,M,null);const{attributes:X}=M;if(!X||xo(M))return;const ae={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:W,forceKeepAttr:void 0};let Ae=X.length;for(;Ae--;){const et=X[Ae],{name:Fe,namespaceURI:pt,value:en}=et,Vn=we(Fe),yo=en;let Ye=Fe==="value"?yo:mC(yo);if(ae.attrName=Vn,ae.attrValue=Ye,ae.keepAttr=!0,ae.forceKeepAttr=void 0,Jt($.uponSanitizeAttribute,M,ae),Ye=ae.attrValue,te&&(Vn==="id"||Vn==="name")&&(tt(Fe,M),Ye=xe+Ye),Pe&&nt(/((--!?|])>)|<\/(style|title|textarea)/i,Ye)){tt(Fe,M);continue}if(Vn==="attributename"&&Wo(Ye,"href")){tt(Fe,M);continue}if(ae.forceKeepAttr)continue;if(!ae.keepAttr){tt(Fe,M);continue}if(!le&&nt(/\/>/i,Ye)){tt(Fe,M);continue}fe&&os([S,A,I],Vi=>{Ye=xr(Ye,Vi," ")});const Wi=we(M.nodeName);if(!Fi(Wi,Vn,Ye)){tt(Fe,M);continue}if(b&&typeof h=="object"&&typeof h.getAttributeType=="function"&&!pt)switch(h.getAttributeType(Wi,Vn)){case"TrustedHTML":{Ye=b.createHTML(Ye);break}case"TrustedScriptURL":{Ye=b.createScriptURL(Ye);break}}if(Ye!==yo)try{pt?M.setAttributeNS(pt,Fe,Ye):M.setAttribute(Fe,Ye),xo(M)?vt(M):ul(t.removed)}catch{tt(Fe,M)}}Jt($.afterSanitizeAttributes,M,null)},Kp=function ue(M){let X=null;const ae=Li(M);for(Jt($.beforeSanitizeShadowDOM,M,null);X=ae.nextNode();)Jt($.uponSanitizeShadowNode,X,null),zi(X),Ui(X),X.content instanceof a&&ue(X.content);Jt($.afterSanitizeShadowDOM,M,null)};return t.sanitize=function(ue){let M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},X=null,ae=null,Ae=null,et=null;if(pr=!ue,pr&&(ue="<!-->"),typeof ue!="string"&&!$i(ue))if(typeof ue.toString=="function"){if(ue=ue.toString(),typeof ue!="string")throw yr("dirty is not a string, aborting")}else throw yr("toString is not a function");if(!t.isSupported)return ue;if(qe||Je(M),t.removed=[],typeof ue=="string"&&(dt=!1),dt){if(ue.nodeName){const en=we(ue.nodeName);if(!K[en]||ce[en])throw yr("root node is forbidden and cannot be sanitized in-place")}}else if(ue instanceof c)X=go("<!---->"),ae=X.ownerDocument.importNode(ue,!0),ae.nodeType===vr.element&&ae.nodeName==="BODY"||ae.nodeName==="HTML"?X=ae:X.appendChild(ae);else{if(!xt&&!fe&&!Ve&&ue.indexOf("<")===-1)return b&&zt?b.createHTML(ue):ue;if(X=go(ue),!X)return xt?null:zt?k:""}X&&He&&vt(X.firstChild);const Fe=Li(dt?ue:X);for(;Ae=Fe.nextNode();)zi(Ae),Ui(Ae),Ae.content instanceof a&&Kp(Ae.content);if(dt)return ue;if(xt){if(Ge)for(et=C.call(X.ownerDocument);X.firstChild;)et.appendChild(X.firstChild);else et=X;return(W.shadowroot||W.shadowrootmode)&&(et=O.call(s,et,!0)),et}let pt=Ve?X.outerHTML:X.innerHTML;return Ve&&K["!doctype"]&&X.ownerDocument&&X.ownerDocument.doctype&&X.ownerDocument.doctype.name&&nt(Rp,X.ownerDocument.doctype.name)&&(pt="<!DOCTYPE "+X.ownerDocument.doctype.name+`>
|
|
136
|
+
`+pt),fe&&os([S,A,I],en=>{pt=xr(pt,en," ")}),b&&zt?b.createHTML(pt):pt},t.setConfig=function(){let ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Je(ue),qe=!0},t.clearConfig=function(){$e=null,qe=!1},t.isValidAttribute=function(ue,M,X){$e||Je({});const ae=we(ue),Ae=we(M);return Fi(ae,Ae,X)},t.addHook=function(ue,M){typeof M=="function"&&gr($[ue],M)},t.removeHook=function(ue,M){if(M!==void 0){const X=lC($[ue],M);return X===-1?void 0:dC($[ue],X,1)[0]}return ul($[ue])},t.removeHooks=function(ue){$[ue]=[]},t.removeAllHooks=function(){$=xl()},t}var NC=Op();function Mp({faq:e,className:t,expanded:r,defaultExpanded:s=!1,onExpandedChange:o,showKeywords:a=!1,dangerouslySetAnswerHTML:i=!1}){const[c,l]=x.useState(s),d=r!==void 0,m=d?r:c,u=()=>{const p=!m;d||l(p),o?.(p)};return n.jsxs("div",{className:H("border border-neutral-200 rounded-lg overflow-hidden dark:border-neutral-800",t),children:[n.jsxs("button",{type:"button",onClick:u,className:H("w-full flex items-center justify-between px-4 py-3 text-left","bg-neutral-50 hover:bg-neutral-100 dark:bg-neutral-900 dark:hover:bg-neutral-800","transition-colors duration-150"),"aria-expanded":m,children:[n.jsx("span",{className:"font-medium text-neutral-900 dark:text-neutral-100 pr-4",children:e.question}),n.jsx("svg",{className:H("w-5 h-5 text-neutral-500 transition-transform duration-200 flex-shrink-0",m&&"rotate-180"),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),m&&n.jsxs("div",{className:"px-4 py-3 bg-white dark:bg-neutral-950",children:[i?n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 prose prose-sm dark:prose-invert max-w-none",dangerouslySetInnerHTML:{__html:NC.sanitize(e.answer,{ALLOWED_TAGS:["b","i","em","strong","a","p","br","ul","ol","li"],ALLOWED_ATTR:["href","target","rel"]})}}):n.jsx("p",{className:"text-sm text-neutral-600 dark:text-neutral-400 whitespace-pre-wrap",children:e.answer}),a&&e.keywords&&e.keywords.length>0&&n.jsx("div",{className:"mt-3 flex flex-wrap gap-1",children:e.keywords.map(p=>n.jsx("span",{className:"px-2 py-0.5 text-xs bg-neutral-100 text-neutral-600 rounded dark:bg-neutral-800 dark:text-neutral-400",children:p},p))})]})]})}function PC({faqs:e,className:t,accordion:r=!1,showKeywords:s=!1,dangerouslySetAnswerHTML:o=!1,emptyMessage:a="No FAQs available."}){const[i,c]=x.useState(null),l=e.filter(d=>d.active!==!1);return l.length===0?n.jsx("div",{className:H("text-center py-8 text-neutral-500 dark:text-neutral-400",t),children:a}):n.jsx("div",{className:H("space-y-2",t),children:l.map(d=>n.jsx(Mp,{faq:d,showKeywords:s,dangerouslySetAnswerHTML:o,expanded:r?i===d.id:void 0,onExpandedChange:r?m=>c(m?d.id:null):void 0},d.id))})}function Qe({amount:e,currency:t}){return new Intl.NumberFormat(void 0,{style:"currency",currency:t}).format(e)}function po({amount:e,currency:t,compareAt:r,className:s,size:o="default"}){const a=typeof r=="number"&&r>e;return n.jsxs("div",{className:H("flex items-baseline gap-2 tabular-nums",s),children:[n.jsx("span",{className:H("font-semibold",o==="sm"?"text-sm":"text-base"),children:Qe({amount:e,currency:t})}),a?n.jsx("span",{className:H("text-neutral-500 line-through dark:text-neutral-400",o==="sm"?"text-xs":"text-sm"),children:Qe({amount:r,currency:t})}):null]})}const AC={large:"aspect-[4/5]",square:"aspect-square",compact:"aspect-[3/4]"},EC={center:"object-center",top:"object-top",bottom:"object-bottom",left:"object-left",right:"object-right"};function Dp({product:e,href:t,onAddToCart:r,onQuickView:s,className:o,layout:a="large",imageCrop:i="center"}){const c=e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0,l=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:null;return n.jsxs(Rt,{className:H("group flex h-full flex-col overflow-hidden rounded-2xl",o),children:[n.jsxs("div",{className:"relative",children:[n.jsx("a",{href:t,className:"block","aria-label":`View ${e.title}`,children:n.jsx("div",{className:H("overflow-hidden bg-neutral-100 dark:bg-neutral-900",AC[a]),children:n.jsx("img",{src:e.images[0]?.url,alt:e.images[0]?.alt??e.title,className:H("h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]",EC[i]),loading:"lazy"})})}),a!=="compact"&&e.tags?.length?n.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 flex gap-1 p-3",children:e.tags.slice(0,2).map(d=>n.jsx(Pn,{className:"pointer-events-none bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:d},d))}):null,c?n.jsx("div",{className:"pointer-events-none absolute left-3 top-3",children:n.jsx(Pn,{variant:"secondary",className:"bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:"Out of stock"})}):l!=null&&l>0&&l<=5?n.jsx("div",{className:"pointer-events-none absolute left-3 top-3",children:n.jsxs(Pn,{variant:"secondary",className:"bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:["Only ",l," left"]})}):null,s?n.jsx("div",{className:"absolute right-3 top-3 opacity-0 transition-opacity group-hover:opacity-100",children:n.jsx(ie,{type:"button",size:"sm",variant:"secondary",className:"h-9",onClick:()=>s(e),children:"Quick view"})}):null]}),n.jsxs("div",{className:H("flex flex-1 flex-col",a==="compact"?"p-3":"p-4"),children:[n.jsx("div",{className:"flex items-start justify-between gap-3",children:n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:H("line-clamp-1 font-medium text-neutral-950 dark:text-neutral-50",a==="compact"?"text-xs":"text-sm"),children:e.title}),n.jsx("div",{className:"mt-1",children:n.jsx(po,{amount:e.price,currency:e.currency,compareAt:e.compareAtPrice,size:a==="compact"?"sm":"default"})})]})}),a==="large"&&n.jsx("p",{className:"mt-2 line-clamp-2 min-h-8 text-xs leading-4 text-neutral-600 dark:text-neutral-400",children:e.description}),n.jsx("div",{className:H("mt-auto",a==="compact"?"pt-3":"pt-4"),children:n.jsx(ie,{type:"button",className:"w-full",size:a==="compact"?"sm":"default",onClick:()=>r?.(e,null),disabled:c,children:c?"Out of stock":"Add to cart"})})]})]})}function fo({products:e,columns:t,onAddToCart:r,onQuickView:s,getProductHref:o,className:a,layout:i,imageCrop:c}){const l=t?.base??2,d=t?.md??3,m=t?.lg??3,u={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4"},p={1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4"},h={1:"lg:grid-cols-1",2:"lg:grid-cols-2",3:"lg:grid-cols-3",4:"lg:grid-cols-4"},_=H("grid gap-4",u[Math.min(4,Math.max(1,l))],p[Math.min(4,Math.max(1,d))],h[Math.min(4,Math.max(1,m))]);return n.jsx("div",{className:H(_,a),children:e.map(g=>n.jsx(Dp,{product:g,href:o?o(g):void 0,onAddToCart:r,onQuickView:s,layout:i,imageCrop:c},g.id))})}function Ni({images:e,className:t}){const[r,s]=x.useState(0),o=e[r];return e.length===0?n.jsx("div",{className:H("aspect-square w-full rounded-xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",t)}):n.jsxs("div",{className:H("space-y-3",t),children:[n.jsx("div",{className:"aspect-square overflow-hidden rounded-2xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:n.jsx("img",{src:o?.url,alt:o?.alt??"",className:"h-full w-full object-cover",loading:"eager"})}),e.length>1?n.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:e.map((a,i)=>{const c=i===r;return n.jsx("button",{type:"button",className:H("h-16 w-16 shrink-0 overflow-hidden rounded-lg border",c?"border-neutral-900 dark:border-neutral-50":"border-neutral-200 dark:border-neutral-800"),onClick:()=>s(i),"aria-label":`View image ${i+1}`,children:n.jsx("img",{src:a.url,alt:a.alt??"",className:"h-full w-full object-cover",loading:"lazy"})},a.url)})}):null]})}function TC(e){const t=new Set;for(const r of e)for(const s of Object.keys(r.options))t.add(s);return Array.from(t)}function IC(e,t){const r=new Set;for(const s of e){const o=s.options[t];o&&r.add(o)}return Array.from(r)}function yl(e,t){return e.find(r=>Object.entries(t).every(([s,o])=>r.options[s]===o))??null}function Lp(e){return e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0}function RC(e){return e.inventoryStatus==="low"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity>0&&e.inventoryQuantity<=5}function OC(e){const t=Lp(e),r=!t&&RC(e),s=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0;return{isOutOfStock:t,isLow:r,quantity:s}}function MC(e,t,r,s){const o={...t,[r]:s},a=e.filter(i=>Object.entries(o).every(([c,l])=>i.options[c]===l));return a.length===0?!1:a.some(i=>!Lp(i))}function Pi({product:e,value:t,onChange:r,className:s,showInventory:o=!0,disableOutOfStock:a=!1}){const i=x.useMemo(()=>e.variants??[],[e.variants]),c=x.useMemo(()=>TC(i),[i]),l=x.useMemo(()=>yl(i,t.selectedOptions),[i,t.selectedOptions]),d=x.useMemo(()=>l?OC(l):null,[l]);return i.length===0||c.length===0?null:n.jsxs("div",{className:H("space-y-4",s),children:[c.map(m=>{const u=IC(i,m),p=t.selectedOptions[m];return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-baseline justify-between",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-950 dark:text-neutral-50",children:m}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:p||"Select"})]}),n.jsx("div",{className:"flex flex-wrap gap-2",children:u.map(h=>{const _=h===p,g=MC(i,t.selectedOptions,m,h),f=a&&!g;return n.jsxs(ie,{type:"button",size:"sm",variant:_?"default":"outline",onClick:()=>{const w={...t.selectedOptions,[m]:h},j=yl(i,w);r({selectedOptions:w,variant:j})},"aria-pressed":_,disabled:f,className:H(!g&&!f&&"opacity-50 line-through"),children:[h,!g&&!f&&n.jsx("span",{className:"ml-1 text-[10px] opacity-70",children:"(Out)"})]},h)})})]},m)}),o&&l&&d&&n.jsx("div",{className:"pt-2",children:d.isOutOfStock?n.jsx("div",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:"Out of stock"}):d.isLow&&d.quantity!==void 0?n.jsxs("div",{className:"text-sm text-amber-600 dark:text-amber-400",children:["Only ",n.jsx("span",{className:"font-semibold",children:d.quantity})," left"]}):null})]})}function Ai({qty:e,onChange:t,min:r=1,max:s,className:o}){const a=Number.isFinite(e)?Math.max(r,Math.floor(e)):r,i=a>r,c=typeof s=="number"?a<s:!0;return n.jsxs("div",{className:H("flex items-center gap-2",o),children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(Math.max(r,a-1)),disabled:!i,"aria-label":"Decrease quantity",children:"-"}),n.jsx(Be,{inputMode:"numeric",pattern:"[0-9]*",value:String(a),onChange:l=>{const d=Math.floor(Number(l.target.value));if(!Number.isFinite(d))return;const m=Math.max(r,typeof s=="number"?Math.min(s,d):d);t(m)},className:"h-10 w-16 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(a+1),disabled:!c,"aria-label":"Increase quantity",children:"+"})]})}function Ei({product:e,open:t,onOpenChange:r,productHref:s,onAddToCart:o,className:a}){const[i,c]=x.useState(1),[l,d]=x.useState({selectedOptions:{},variant:null});if(x.useEffect(()=>{if(e)if(c(1),e.variants?.length){const p=e.variants[0];d({selectedOptions:{...p.options},variant:p})}else d({selectedOptions:{},variant:null})},[e?.id]),!e)return null;const m=l.variant?.price??e.price,u=l.variant?.compareAtPrice??e.compareAtPrice;return n.jsx(pi,{open:t,onOpenChange:r,children:n.jsxs(eo,{className:H("max-w-3xl",a),children:[n.jsx(hi,{children:n.jsxs(to,{className:"flex items-center justify-between gap-3",children:[n.jsx("span",{className:"truncate",children:e.title}),s?n.jsx("a",{href:s(e.slug),className:"text-sm font-normal text-neutral-700 hover:underline dark:text-neutral-300",children:"View details"}):null]})}),n.jsxs("div",{className:"grid gap-8 md:grid-cols-2",children:[n.jsx(Ni,{images:e.images}),n.jsxs("div",{className:"space-y-5",children:[n.jsxs("div",{children:[n.jsx(po,{amount:m,currency:e.currency,compareAt:u}),n.jsx("p",{className:"mt-3 text-sm text-neutral-600 dark:text-neutral-400",children:e.description})]}),n.jsx(Pi,{product:e,value:{selectedOptions:l.selectedOptions,variantId:l.variant?.id},onChange:p=>d(p)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(Ai,{qty:i,onChange:c}),n.jsx(ie,{type:"button",className:"flex-1",onClick:()=>{o(e,l.variant,i),r(!1)},children:"Add to cart"})]}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:e.inventoryStatus==="out_of_stock"?"Out of stock":"In stock"})]})]})]})})}function wa({categories:e,activeSlug:t,onSelect:r,className:s}){return n.jsx("nav",{className:H("space-y-1",s),"aria-label":"Categories",children:e.map(o=>{const a=t===o.slug;return n.jsxs("button",{type:"button",className:H("flex w-full items-center justify-between rounded-md px-3 py-2 text-sm transition-colors",a?"bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900":"text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"),onClick:()=>r?.(o),"aria-current":a?"page":void 0,children:[n.jsx("span",{className:"truncate",children:o.name}),n.jsx("span",{className:"text-xs opacity-70",children:"›"})]},o.id)})})}function Ti({items:e,className:t}){return n.jsx("nav",{className:H("flex items-center gap-2 text-xs text-neutral-600 dark:text-neutral-400",t),"aria-label":"Breadcrumb",children:e.map((r,s)=>n.jsxs("span",{className:"flex items-center gap-2",children:[r.href?n.jsx("a",{href:r.href,className:"hover:underline",children:r.label}):n.jsx("span",{className:"text-neutral-900 dark:text-neutral-50",children:r.label}),s<e.length-1?n.jsx("span",{"aria-hidden":!0,children:"·"}):null]},`${r.label}-${s}`))})}function Ii({value:e,onChange:t,placeholder:r="Search products…",className:s}){return n.jsxs("div",{className:H("relative",s),children:[n.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-3 flex items-center text-neutral-500 dark:text-neutral-400","aria-hidden":!0,children:"⌕"}),n.jsx(Be,{value:e,onChange:o=>t(o.target.value),placeholder:r,className:"pl-9","aria-label":"Search"})]})}function Ts({facets:e,value:t,onChange:r,onClear:s,className:o,enabledFilters:a}){const i=e.tags??[],c=new Set(t.tags??[]),l=a?.tags??!0,d=a?.priceRange??!0,m=a?.inStock??!0;return l||d||m?n.jsxs("div",{className:H("space-y-4",o),children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Filters"}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-8 px-2 text-xs",onClick:s,children:"Clear"})]}),n.jsx(St,{}),l&&i.length?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Tags"}),n.jsx("div",{className:"space-y-2",children:i.map(p=>n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:c.has(p),onChange:h=>{const _=new Set(c);h.target.checked?_.add(p):_.delete(p),r({...t,tags:Array.from(_)})}}),p]},p))})]}):null,d&&e.price?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Price"}),n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-1",children:[n.jsx(at,{className:"text-xs",htmlFor:"price-min",children:"Min"}),n.jsx(Be,{id:"price-min",inputMode:"decimal",placeholder:String(e.price.min),value:t.priceMin??"",onChange:p=>{const h=Number(p.target.value);r({...t,priceMin:Number.isFinite(h)&&p.target.value!==""?h:void 0})}})]}),n.jsxs("div",{className:"grid gap-1",children:[n.jsx(at,{className:"text-xs",htmlFor:"price-max",children:"Max"}),n.jsx(Be,{id:"price-max",inputMode:"decimal",placeholder:String(e.price.max),value:t.priceMax??"",onChange:p=>{const h=Number(p.target.value);r({...t,priceMax:Number.isFinite(h)&&p.target.value!==""?h:void 0})}})]})]})]}):null,m?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Availability"}),n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:t.inStock??!1,onChange:p=>r({...t,inStock:p.target.checked})}),"In stock"]})]}):null]}):null}function bl(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}function DC(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("path",{d:"M3 6h18"}),n.jsx("path",{d:"M8 6V4h8v2"}),n.jsx("path",{d:"M6 6l1 16h10l1-16"}),n.jsx("path",{d:"M10 11v6"}),n.jsx("path",{d:"M14 11v6"})]})}function Ri({item:e,onRemove:t,onSetQty:r,variant:s="table",className:o,inventory:a}){const i=e.unitPrice*e.qty,[c,l]=x.useState(!1),d=x.useMemo(()=>{if(a?.availableQty)return a.availableQty},[a?.availableQty]),m=!a?.isOutOfStock&&(d===void 0||e.qty<d),u=x.useMemo(()=>a?a.isOutOfStock?{type:"error",message:a.message||"Out of stock"}:a.exceedsAvailable?{type:"warning",message:a.message||"Quantity exceeds available stock"}:a.isLowStock?{type:"info",message:a.message||"Low stock"}:null:null,[a]);return x.useEffect(()=>{c&&e.qty!==1&&l(!1)},[c,e.qty]),s==="compact"?n.jsxs("div",{className:H("flex items-start gap-3",o),children:[n.jsx("div",{className:"h-12 w-12 shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:e.imageSnapshot?n.jsx("img",{src:e.imageSnapshot,alt:e.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"truncate text-sm font-medium text-neutral-950 dark:text-neutral-50",children:e.titleSnapshot}),n.jsx("div",{className:"mt-0.5 text-xs tabular-nums text-neutral-600 dark:text-neutral-400",children:Qe({amount:i,currency:e.currency})}),u&&n.jsxs("div",{className:H("mt-1 flex items-center gap-1 text-[11px]",u.type==="error"&&"text-red-600 dark:text-red-400",u.type==="warning"&&"text-amber-600 dark:text-amber-400",u.type==="info"&&"text-blue-600 dark:text-blue-400"),children:[n.jsx(bl,{className:"h-3 w-3 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsx("div",{className:"flex h-12 w-[140px] shrink-0 items-center justify-end",children:c?n.jsxs("div",{className:"flex w-full flex-col items-center justify-center gap-2",children:[n.jsx("div",{className:"text-center text-[11px] font-medium leading-none text-neutral-600 dark:text-neutral-400",children:"Remove item?"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",variant:"outline",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:()=>l(!1),children:"Cancel"}),n.jsx(ie,{type:"button",variant:"destructive",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:t,children:"Confirm"})]})]}):n.jsxs("div",{className:"flex items-center justify-end gap-1.5 whitespace-nowrap",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":e.qty===1?"Remove item":"Decrease quantity",onClick:()=>{if(e.qty===1){l(!0);return}r(e.qty-1)},children:e.qty===1?n.jsx(DC,{className:"h-4 w-4"}):"-"}),n.jsx(Be,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const h=Math.floor(Number(p.target.value));if(!Number.isFinite(h))return;const _=Math.max(1,d?Math.min(d,h):h);r(_)},className:"h-8 w-11 px-2 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]})})]})})]}):n.jsxs("div",{className:H("grid grid-cols-[64px_1fr] items-start gap-x-4 gap-y-3 sm:grid-cols-[64px_1fr_176px_120px]",o),children:[n.jsx("div",{className:"h-16 w-16 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:e.imageSnapshot?n.jsx("img",{src:e.imageSnapshot,alt:e.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsxs("div",{className:"col-start-2 row-start-1 min-w-0",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsx("div",{className:"truncate text-sm font-medium text-neutral-950 dark:text-neutral-50",children:e.titleSnapshot}),n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50 sm:hidden",children:Qe({amount:i,currency:e.currency})})]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[Qe({amount:e.unitPrice,currency:e.currency})," each"]}),u&&n.jsxs("div",{className:H("mt-1.5 flex items-center gap-1 text-xs",u.type==="error"&&"text-red-600 dark:text-red-400",u.type==="warning"&&"text-amber-600 dark:text-amber-400",u.type==="info"&&"text-blue-600 dark:text-blue-400"),children:[n.jsx(bl,{className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsxs("div",{className:"col-span-2 col-start-1 row-start-2 flex items-center justify-between gap-3 sm:col-span-1 sm:col-start-3 sm:row-start-1 sm:justify-center",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Decrease quantity",onClick:()=>r(Math.max(1,e.qty-1)),children:"-"}),n.jsx(Be,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const h=Math.floor(Number(p.target.value));if(!Number.isFinite(h))return;const _=Math.max(1,d?Math.min(d,h):h);r(_)},className:"h-9 w-14 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-9 px-2 text-xs text-red-600 dark:text-red-400 sm:hidden",onClick:t,children:"Remove"})]}),n.jsxs("div",{className:"hidden sm:col-start-4 sm:row-start-1 sm:flex sm:flex-col sm:items-center sm:text-center",children:[n.jsx("div",{className:"text-sm font-semibold tabular-nums text-neutral-950 dark:text-neutral-50",children:Qe({amount:i,currency:e.currency})}),n.jsx(ie,{type:"button",variant:"ghost",className:"mt-1 h-8 px-2 text-xs text-red-600 dark:text-red-400",onClick:t,children:"Remove"})]})]})}function Oi({currency:e,subtotal:t,itemCount:r,onCheckout:s,isCheckoutDisabled:o,checkoutDisabledReason:a,onRemoveUnavailable:i,className:c}){return n.jsxs("div",{className:H("space-y-4",c),children:[n.jsx(St,{}),n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsxs("div",{className:"flex items-center gap-2 text-neutral-600 dark:text-neutral-400",children:[n.jsx("span",{children:"Subtotal"}),typeof r=="number"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-neutral-300 dark:text-neutral-700",children:"·"}),n.jsxs("span",{className:"tabular-nums",children:[r," item",r===1?"":"s"]})]}):null]}),n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:t,currency:e})})]}),n.jsx(ie,{type:"button",onClick:s,disabled:o,className:"w-full",children:"Checkout"}),o&&a&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-center text-xs text-amber-600 dark:text-amber-400",children:a}),i&&n.jsx("button",{type:"button",onClick:i,className:"mx-auto block text-xs text-neutral-500 underline underline-offset-2 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-300",children:"Remove unavailable items"})]})]})}function $p({onCheckout:e,className:t}){const{config:r}=Re(),s=Dt(),{getItemInventory:o,hasIssues:a}=Za({items:s.items,refreshInterval:3e4,skip:s.items.length===0}),i=()=>{for(const c of s.items){const l=o(c.productId,c.variantId);(l?.isOutOfStock||l?.exceedsAvailable)&&s.removeItem(c.productId,c.variantId)}};return s.items.length===0?n.jsx(tr,{title:"Cart is empty",description:"Add items from the catalog to check out.",className:t}):n.jsxs("div",{className:H("flex h-full flex-col rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-800 dark:bg-neutral-950",t),children:[n.jsx("div",{className:"-mr-4 min-h-0 flex-1 overflow-y-auto overflow-x-hidden pr-4",children:n.jsx("div",{className:"divide-y divide-neutral-200 dark:divide-neutral-800",children:s.items.map(c=>n.jsx("div",{className:"py-3",children:n.jsx(Ri,{variant:"compact",item:c,onRemove:()=>s.removeItem(c.productId,c.variantId),onSetQty:l=>s.setQty(c.productId,c.variantId,l),inventory:o(c.productId,c.variantId)})},`${c.productId}::${c.variantId??""}`))})}),n.jsx("div",{className:"mt-4 space-y-4",children:n.jsx(Oi,{currency:r.currency,subtotal:s.subtotal,itemCount:s.count,onCheckout:e,isCheckoutDisabled:s.items.length===0||a,checkoutDisabledReason:a?"Some items have inventory issues":void 0,onRemoveUnavailable:a?i:void 0})})]})}const zp=x.forwardRef(({className:e,...t},r)=>n.jsx("textarea",{ref:r,className:H("flex min-h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm transition-colors placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-50/20",e),...t}));zp.displayName="Textarea";function LC(){const[e,t]=x.useState(!1);return x.useEffect(()=>{const r=window.matchMedia?.("(prefers-reduced-motion: reduce)");if(!r)return;const s=()=>t(r.matches);return s(),r.addEventListener?.("change",s),()=>r.removeEventListener?.("change",s)},[]),e}function vl({children:e,className:t}){const r=x.useRef(null),s=LC();return x.useEffect(()=>{const o=r.current;!o||s||o.animate([{opacity:0,transform:"translateY(6px)"},{opacity:1,transform:"translateY(0px)"}],{duration:180,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)",fill:"both"})},[s]),n.jsx("div",{ref:r,className:t,children:e})}function Go(){return`${Date.now()}_${Math.random().toString(16).slice(2)}`}function $C({className:e}){const[t,r]=x.useState(""),[s,o]=x.useState(!1),[a,i]=x.useState(()=>[{id:Go(),role:"agent",text:"Hi! How can we help today? We can recommend products or answer support questions.",createdAt:Date.now()}]),[c,l]=x.useState("…");x.useEffect(()=>{if(!s)return;const h=[".","..","..."];let _=0;const g=window.setInterval(()=>{_=(_+1)%h.length,l(h[_])},450);return()=>window.clearInterval(g)},[s]);const d=x.useRef(null),m=x.useRef(null);x.useEffect(()=>{const h=d.current;h&&(h.scrollTop=h.scrollHeight)},[a.length]);const u=x.useCallback(()=>{const h=m.current;if(!h)return;const _=120;h.style.height="0px";const g=Math.min(_,Math.max(40,h.scrollHeight));h.style.height=`${g}px`,h.style.overflowY=h.scrollHeight>_?"auto":"hidden"},[]);x.useEffect(()=>{u()},[t,u]);const p=x.useCallback(()=>{const h=t.trim();h&&(i(_=>[..._,{id:Go(),role:"user",text:h,createdAt:Date.now()}]),r(""),o(!0),window.setTimeout(()=>{i(_=>[..._,{id:Go(),role:"agent",text:"Got it. Want recommendations, sizing help, or help with an order?",createdAt:Date.now()}]),o(!1)},450))},[t]);return n.jsxs("div",{className:H("flex h-full min-h-0 flex-col",e),children:[n.jsxs("div",{ref:d,className:"min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain rounded-2xl border border-neutral-200 bg-white p-4 dark:border-neutral-800 dark:bg-neutral-950",children:[a.map(h=>n.jsx(vl,{className:H("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsx("div",{className:H("max-w-[85%] rounded-2xl px-3 py-2 text-sm leading-5",h.role==="user"?"bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900":"bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50"),children:n.jsx("span",{className:"whitespace-pre-wrap break-words",children:h.text})})},h.id)),s?n.jsx(vl,{className:"flex justify-start",children:n.jsx("div",{className:"max-w-[85%] rounded-2xl bg-neutral-100 px-3 py-2 text-sm leading-5 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",children:c})}):null]}),n.jsxs("div",{className:"mt-3 flex shrink-0 items-end gap-2",children:[n.jsx(zp,{ref:m,rows:1,value:t,onChange:h=>r(h.target.value),placeholder:"Type a message…",className:"max-h-[120px] resize-none",onKeyDown:h=>{h.key==="Enter"&&(h.shiftKey||(h.preventDefault(),p()))}}),n.jsx(ie,{type:"button",onClick:p,disabled:!t.trim(),className:"h-10 shrink-0",children:"Send"})]})]})}function $r({trigger:e,side:t="right",open:r,onOpenChange:s,onCheckout:o,preferredTab:a,className:i}){const[c,l]=x.useState(a??"cart");return x.useEffect(()=>{r&&l(a??"cart")},[r,a]),n.jsxs(no,{modal:!1,open:r,onOpenChange:s,children:[e?n.jsx(ro,{asChild:!0,children:e}):null,n.jsxs(Fr,{side:t,overlayClassName:t==="popup"?"pointer-events-none bg-transparent backdrop-blur-none":"pointer-events-none bg-neutral-950/40 backdrop-blur-none",className:H(t==="bottom"?"h-[85vh] rounded-t-2xl":void 0,t==="popup"?"shadow-xl":"w-full sm:max-w-md",t==="popup"?"h-[min(640px,calc(100vh-2rem))]":void 0,t==="popup"?void 0:"p-4","flex flex-col overflow-hidden",i),children:[n.jsx(so,{className:"space-y-0",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx(Si,{value:c,onValueChange:d=>l(d),children:n.jsxs(uo,{className:"h-9",children:[n.jsx(Lr,{value:"cart",className:"text-sm",children:"Cart"}),n.jsx(Lr,{value:"chat",className:"text-sm",children:"Chat"})]})}),n.jsx(Um,{asChild:!0,children:n.jsx(ie,{type:"button",size:"icon",variant:"ghost",className:"h-9 w-9 rounded-full text-lg leading-none","aria-label":"Close cart",children:"X"})})]})}),n.jsx("div",{className:"mt-3 min-h-0 flex-1 overflow-hidden",children:c==="chat"?n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Get help finding a product or ask us any questions. We’re both your shopping assistant and support chat."}),n.jsx("div",{className:"mt-3 min-h-0 flex-1",children:n.jsx($C,{className:"h-full"})})]}):n.jsx($p,{onCheckout:()=>{o(),s?.(!1)},className:"h-full border-0 bg-transparent p-0 shadow-none"})})]})]})}function Mi({value:e,onApply:t,className:r}){const[s,o]=x.useState(e??"");return x.useEffect(()=>{o(e??"")},[e]),n.jsxs("div",{className:H("space-y-2",r),children:[n.jsx("div",{className:"text-sm font-medium text-neutral-950 dark:text-neutral-50",children:"Promo code"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Be,{value:s,onChange:a=>o(a.target.value),placeholder:"SAVE10","aria-label":"Promo code"}),n.jsx(ie,{type:"button",variant:"outline",onClick:()=>t(s.trim()||void 0),children:"Apply"})]})]})}function Fp({onCheckout:e,showPromoCode:t,className:r}){const{config:s}=Re(),o=Dt(),{getItemInventory:a,hasIssues:i}=Za({items:o.items,refreshInterval:3e4,skip:o.items.length===0}),c=()=>{for(const l of o.items){const d=a(l.productId,l.variantId);(d?.isOutOfStock||d?.exceedsAvailable)&&o.removeItem(l.productId,l.variantId)}};return o.items.length===0?n.jsx(tr,{title:"Your cart is empty",description:"Add a few products and come back here when you're ready to check out.",className:r}):n.jsxs("div",{className:H("grid items-start gap-6 lg:grid-cols-[1fr_360px]",r),children:[n.jsxs("div",{className:"self-start rounded-2xl border border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsxs("div",{className:"hidden grid-cols-[64px_1fr_176px_120px] gap-x-4 px-5 py-3 text-xs font-medium text-neutral-500 dark:text-neutral-400 sm:grid",children:[n.jsx("div",{}),n.jsx("div",{children:"Item"}),n.jsx("div",{className:"text-center",children:"Qty"}),n.jsx("div",{className:"text-center",children:"Total"})]}),n.jsx("div",{className:"divide-y divide-neutral-200 dark:divide-neutral-800",children:o.items.map(l=>n.jsx("div",{className:"px-4 py-4 sm:px-5",children:n.jsx(Ri,{item:l,onRemove:()=>o.removeItem(l.productId,l.variantId),onSetQty:d=>o.setQty(l.productId,l.variantId,d),inventory:a(l.productId,l.variantId)})},`${l.productId}::${l.variantId??""}`))})]}),n.jsx("div",{className:"lg:sticky lg:top-24 self-start",children:n.jsxs("div",{className:"rounded-2xl border border-neutral-200 bg-white p-5 shadow-sm dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Summary"}),n.jsx(St,{className:"my-4"}),n.jsxs("div",{className:"space-y-4",children:[t?n.jsx(Mi,{value:o.promoCode,onApply:o.setPromoCode}):null,n.jsx(Oi,{currency:s.currency,subtotal:o.subtotal,onCheckout:e,isCheckoutDisabled:o.items.length===0||i,checkoutDisabledReason:i?"Some items have inventory issues":void 0,onRemoveUnavailable:i?c:void 0})]})]})})]})}function Bp({left:e,right:t,className:r}){return n.jsxs("div",{className:H("grid items-start gap-8 lg:grid-cols-[1fr_420px]",r),children:[n.jsx("div",{children:e}),n.jsx("div",{children:t})]})}function _a({title:e,value:t,onChange:r,errors:s,className:o}){return n.jsxs("section",{className:H("space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",o),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:e}),n.jsxs("div",{className:"grid gap-3",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-line1`,children:"Address line 1"}),n.jsx(Be,{id:`${e}-line1`,value:t.line1,onChange:a=>r({...t,line1:a.target.value}),"aria-invalid":!!s?.line1}),s?.line1?n.jsx("div",{className:"text-xs text-red-600",children:s.line1}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-line2`,children:"Address line 2"}),n.jsx(Be,{id:`${e}-line2`,value:t.line2??"",onChange:a=>r({...t,line2:a.target.value})})]}),n.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-city`,children:"City"}),n.jsx(Be,{id:`${e}-city`,value:t.city,onChange:a=>r({...t,city:a.target.value}),"aria-invalid":!!s?.city}),s?.city?n.jsx("div",{className:"text-xs text-red-600",children:s.city}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-state`,children:"State"}),n.jsx(Be,{id:`${e}-state`,value:t.state??"",onChange:a=>r({...t,state:a.target.value})})]})]}),n.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-postal`,children:"Postal code"}),n.jsx(Be,{id:`${e}-postal`,value:t.postalCode,onChange:a=>r({...t,postalCode:a.target.value}),"aria-invalid":!!s?.postalCode}),s?.postalCode?n.jsx("div",{className:"text-xs text-red-600",children:s.postalCode}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-country`,children:"Country"}),n.jsx(Be,{id:`${e}-country`,value:t.country,onChange:a=>r({...t,country:a.target.value}),"aria-invalid":!!s?.country}),s?.country?n.jsx("div",{className:"text-xs text-red-600",children:s.country}):null]})]})]})]})}function Up({methods:e,value:t,onChange:r,currency:s,className:o}){return e.length===0?null:n.jsxs("section",{className:H("space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",o),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Shipping method"}),n.jsx("div",{className:"space-y-2",children:e.map(a=>{const i=a.id===t;return n.jsxs(ie,{type:"button",variant:i?"default":"outline",className:"h-auto w-full justify-between px-4 py-3",onClick:()=>r(a.id),"aria-pressed":i,children:[n.jsxs("div",{className:"text-left",children:[n.jsx("div",{className:"text-sm font-medium",children:a.label}),a.detail?n.jsx("div",{className:"text-xs opacity-80",children:a.detail}):null]}),n.jsx("div",{className:"text-sm font-semibold",children:Qe({amount:a.price,currency:a.currency||s})})]},a.id)})})]})}function Qo({message:e}){return e?n.jsx("div",{className:"text-xs text-red-600",children:e}):null}function Wp({className:e}){const{config:t}=Re(),r=$s(),s=Dt(),o=t.checkout.mode,a=x.useMemo(()=>cs(s.items,{requireEmail:t.checkout.requireEmail??!0,defaultMode:o,allowShipping:t.checkout.allowShipping??!1}),[s.items,t.checkout.allowShipping,t.checkout.requireEmail,o]),i=(t.checkout.allowShipping??!1)&&a.shippingAddress&&(o==="shipping"||o==="full"),c=a.email!=="none"||a.name!=="none"||a.phone!=="none",l={line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"},d=r.values.shippingAddress??l,m=r.values.billingAddress??l,u=Bd({enabled:!!t.adapter.getShippingMethods&&i,customer:{email:r.values.email||void 0,name:r.values.name||void 0,shippingAddress:d}});return n.jsxs("form",{className:H("space-y-6",e),onSubmit:p=>p.preventDefault(),children:[a.isDigitalOnly?n.jsx(Rt,{className:"rounded-2xl",children:n.jsxs(Gt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Digital delivery"}),n.jsx("div",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:a.fulfillmentNotes||"This is a digital product and will be available from your account after purchase."})]})}):null,a.hasPhysical&&!(t.checkout.allowShipping??!1)?n.jsx(Rt,{className:"rounded-2xl border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/30",children:n.jsxs(Gt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-red-900 dark:text-red-200",children:"Shipping required"}),n.jsx("div",{className:"mt-1 text-sm text-red-800/90 dark:text-red-200/80",children:"Your cart contains shippable items, but shipping is disabled for this checkout."})]})}):null,c?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Contact"}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:a.email==="required"||a.name==="required"||a.phone==="required"?"Required":"Optional"})]}),n.jsxs("div",{className:"grid gap-3",children:[a.email!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-email",children:"Email"}),n.jsx(Be,{id:"checkout-email",value:r.values.email??"",onChange:p=>r.setField("email",p.target.value),placeholder:"you@company.com","aria-invalid":!!r.fieldErrors.email,required:a.email==="required"}),n.jsx(Qo,{message:r.fieldErrors.email})]}):null,a.name!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-name",children:"Name"}),n.jsx(Be,{id:"checkout-name",value:r.values.name??"",onChange:p=>r.setField("name",p.target.value),placeholder:"Full name","aria-invalid":!!r.fieldErrors.name,required:a.name==="required"}),n.jsx(Qo,{message:r.fieldErrors.name})]}):null,a.phone!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-phone",children:"Phone"}),n.jsx(Be,{id:"checkout-phone",value:r.values.phone??"",onChange:p=>r.setField("phone",p.target.value),placeholder:"Phone number","aria-invalid":!!r.fieldErrors.phone,required:a.phone==="required"}),n.jsx(Qo,{message:r.fieldErrors.phone})]}):null]})]}):null,i?n.jsx(_a,{title:"Shipping address",value:d,onChange:p=>r.setField("shippingAddress",p),errors:{line1:r.fieldErrors["shippingAddress.line1"],city:r.fieldErrors["shippingAddress.city"],postalCode:r.fieldErrors["shippingAddress.postalCode"],country:r.fieldErrors["shippingAddress.country"]}}):null,i&&u.methods.length?n.jsx(Up,{methods:u.methods,value:r.values.shippingMethodId,onChange:p=>r.setField("shippingMethodId",p),currency:t.currency}):null,o==="full"?n.jsx(_a,{title:"Billing address",value:m,onChange:p=>r.setField("billingAddress",p)}):null,t.checkout.allowTipping?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Tip"}),n.jsxs("div",{className:"grid gap-2",children:[n.jsxs(at,{htmlFor:"checkout-tip",children:["Tip amount (",t.currency,")"]}),n.jsx(Be,{id:"checkout-tip",inputMode:"decimal",value:String(r.values.tipAmount??0),onChange:p=>r.setField("tipAmount",Number(p.target.value)||0)})]})]}):null,o==="full"?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Notes"}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-notes",children:"Order notes (optional)"}),n.jsx(Be,{id:"checkout-notes",value:r.values.notes??"",onChange:p=>r.setField("notes",p.target.value),placeholder:"Delivery instructions, gift note…"})]})]}):null]})}function Vp(){if(typeof window>"u")return!1;const e=window,t=["phantom","solflare","backpack","glow","slope","sollet","coin98","clover","mathWallet","ledger","torus","walletconnect"];for(const r of t){const s=e[r];if(s&&typeof s=="object"&&"solana"in s&&s.solana)return!0}return!!e.solana}const zC=Object.freeze(Object.defineProperty({__proto__:null,detectSolanaWallets:Vp},Symbol.toStringTag,{value:"Module"}));function FC(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}function BC(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("path",{d:"M3 6h18"}),n.jsx("path",{d:"M8 6V4h8v2"}),n.jsx("path",{d:"M6 6l1 16h10l1-16"})]})}function qp({open:e,onOpenChange:t,issues:r,onRemoveItem:s,onUpdateQuantity:o,onGoToCart:a,className:i}){const c=r.some(l=>l.type==="out_of_stock"||l.type==="product_unavailable");return n.jsx(pi,{open:e,onOpenChange:t,children:n.jsxs(eo,{className:H("sm:max-w-lg",i),children:[n.jsxs(hi,{children:[n.jsxs(to,{className:"flex items-center gap-2",children:[n.jsx(FC,{className:"h-5 w-5 text-amber-500"}),"Inventory Update"]}),n.jsx(gi,{children:c?"Some items in your cart are no longer available.":"Some items in your cart have limited availability."})]}),n.jsx("div",{className:"my-4 divide-y divide-neutral-200 dark:divide-neutral-800",children:r.map(l=>n.jsx(UC,{issue:l,onRemove:()=>s(l.productId,l.variantId),onUpdateQty:d=>o(l.productId,l.variantId,d)},`${l.productId}::${l.variantId??""}`))}),n.jsxs(Bm,{className:"flex-col gap-2 sm:flex-row",children:[a?n.jsx(ie,{type:"button",variant:"outline",onClick:()=>{t(!1),a()},children:"Go to Cart"}):null,n.jsx(ie,{type:"button",onClick:()=>t(!1),children:"Continue"})]})]})})}function UC({issue:e,onRemove:t,onUpdateQty:r}){const s=e.type==="out_of_stock"||e.type==="product_unavailable";return n.jsxs("div",{className:"flex items-start gap-3 py-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-900 dark:text-neutral-100",children:e.title}),n.jsx("div",{className:H("mt-0.5 text-sm",s?"text-red-600 dark:text-red-400":"text-amber-600 dark:text-amber-400"),children:e.message}),e.type==="insufficient_stock"&&e.availableQty>0?n.jsxs("div",{className:"mt-1 text-xs text-neutral-500 dark:text-neutral-400",children:["You requested ",e.requestedQty,", but only ",e.availableQty," available"]}):null]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.type==="insufficient_stock"&&e.availableQty>0?n.jsxs(ie,{type:"button",size:"sm",variant:"outline",onClick:()=>r(e.availableQty),children:["Update to ",e.availableQty]}):null,n.jsxs(ie,{type:"button",size:"sm",variant:"ghost",className:"text-red-600 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-950/30 dark:hover:text-red-300",onClick:t,children:[n.jsx(BC,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Remove"})]})]})]})}function Hp({className:e,ctaLabel:t,renderEmbedded:r,embeddedFallback:s,renderCustom:o,customFallback:a}){const{config:i}=Re(),c=Dt(),l=$s(),{config:d,isLoading:m}=Wd(),[u,p]=x.useState(!1);x.useEffect(()=>{p(Vp())},[]);const h=Ud({items:c.items}),[_,g]=x.useState(!1),f=x.useMemo(()=>i.checkout.paymentMethods&&i.checkout.paymentMethods.length?i.checkout.paymentMethods:[{id:"card",label:"Card",ctaLabel:"Pay now"}],[i.checkout.paymentMethods]),w=x.useMemo(()=>f.filter(A=>!(A.id==="card"&&!d.card||A.id==="crypto"&&!d.crypto||A.id==="credits"&&!d.credits||A.id==="crypto"&&!u)),[u,f,d]),[j,v]=x.useState((w[0]??f[0]).id);x.useEffect(()=>{w.length&&(w.some(S=>S.id===j)||v(w[0].id))},[j,w]),x.useEffect(()=>{l.reset()},[j]);const b=w.find(S=>S.id===j)??f.find(S=>S.id===j)??f[0],k=b.description??(j==="crypto"?"Pay using a connected wallet.":void 0),R=j==="crypto"&&!u,N=m||l.status==="validating"||l.status==="creating_session"||l.status==="redirecting"||h.isVerifying,C=t??b.ctaLabel??(i.checkout.mode==="none"?"Continue to payment":"Pay now"),T=x.useCallback(async S=>{const A=await h.verify();if(!A.ok&&A.issues.length>0){g(!0);return}l.createCheckoutSession({paymentMethodId:S})},[l,h]),O=l.session?.kind==="embedded"?l.session:null,$=l.session?.kind==="custom"?l.session:null;return n.jsxs("div",{className:H("space-y-3",e),children:[w.length>1?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs font-medium text-neutral-600 dark:text-neutral-400",children:"Payment method"}),n.jsx(Si,{value:j,onValueChange:v,children:n.jsx(uo,{className:"w-full",children:w.map(S=>n.jsx(Lr,{value:S.id,className:"flex-1",disabled:N,children:S.label},S.id))})})]}):null,l.error?n.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-900/40 dark:bg-red-950/30 dark:text-red-200",children:l.error}):null,$?n.jsx("div",{className:"space-y-3",children:o?o($):a??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Checkout session created. Provide `renderCustom` to render a custom payment UI."})}):O?n.jsx("div",{className:"space-y-3",children:r?r(O):s??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Embedded checkout session created. Provide `renderEmbedded` to render your payment UI."})}):n.jsx(ie,{type:"button",className:"w-full",disabled:c.items.length===0||N||R,onClick:()=>{T(j)},children:h.isVerifying?"Checking availability…":N?"Processing…":C}),!O&&!$?n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:R?"Install a browser wallet to enable crypto payments.":k??"You will be redirected to complete your payment."}):null,n.jsx(qp,{open:_,onOpenChange:S=>{g(S),S||h.reset()},issues:h.result?.issues??[],onRemoveItem:(S,A)=>{c.removeItem(S,A)},onUpdateQuantity:(S,A,I)=>{c.setQty(S,A,I)}})]})}function Zp({className:e}){const{config:t}=Re(),r=Dt(),s=$s(),{settings:o}=or(),a=(t.checkout.allowPromoCodes??!1)&&o.checkout.promoCodes;return n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",e),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order review"}),n.jsx(St,{className:"my-3"}),n.jsx("div",{className:"space-y-3",children:r.items.map(i=>n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[n.jsx("div",{className:"h-10 w-10 shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:i.imageSnapshot?n.jsx("img",{src:i.imageSnapshot,alt:i.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"line-clamp-1 text-sm text-neutral-950 dark:text-neutral-50",children:i.titleSnapshot}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Qty ",i.qty]})]})]}),n.jsx("div",{className:"text-sm font-semibold tabular-nums text-neutral-950 dark:text-neutral-50",children:Qe({amount:i.unitPrice*i.qty,currency:i.currency})})]},`${i.productId}::${i.variantId??""}`))}),n.jsx(St,{className:"my-3"}),a?n.jsx(Mi,{value:s.values.discountCode??r.promoCode,onApply:i=>{s.setField("discountCode",i??""),r.setPromoCode(i)}}):null,a?n.jsx(St,{className:"my-3"}):null,n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("span",{className:"text-neutral-600 dark:text-neutral-400",children:"Subtotal"}),n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:r.subtotal,currency:t.currency})})]})]})}function ho({result:e,onContinueShopping:t,onViewOrders:r,className:s}){return e.kind==="idle"?null:e.kind==="success"?n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-600 dark:text-neutral-400",children:"Receipt"}),n.jsx("h2",{className:"mt-2 text-2xl font-semibold",children:"Payment successful"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"Thanks for your purchase. You’ll receive a confirmation email shortly."}),e.order?n.jsxs("div",{className:"mt-5 rounded-xl border border-neutral-200 bg-neutral-50 p-4 dark:border-neutral-800 dark:bg-neutral-900/40",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:["Order ",e.order.id]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[new Date(e.order.createdAt).toLocaleString()," · ",e.order.status]})]}),n.jsx("div",{className:"text-sm font-semibold",children:Qe({amount:e.order.total,currency:e.order.currency})})]}),n.jsxs("div",{className:"mt-3 space-y-2",children:[e.order.items.slice(0,4).map((o,a)=>n.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[n.jsx("div",{className:"min-w-0 truncate",children:o.title}),n.jsxs("div",{className:"shrink-0 text-neutral-600 dark:text-neutral-400",children:["Qty ",o.qty]})]},`${o.title}-${a}`)),e.order.items.length>4?n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["+",e.order.items.length-4," more item(s)"]}):null]}),n.jsxs("div",{className:"mt-3 flex gap-3 text-sm",children:[e.order.receiptUrl?n.jsx("a",{href:e.order.receiptUrl,className:"hover:underline",children:"Receipt"}):null,e.order.invoiceUrl?n.jsx("a",{href:e.order.invoiceUrl,className:"hover:underline",children:"Invoice"}):null]})]}):e.orderId?n.jsxs("p",{className:"mt-4 text-xs text-neutral-500 dark:text-neutral-400",children:["Session/Order ID: ",n.jsx("span",{className:"font-mono",children:e.orderId})]}):null,n.jsxs("div",{className:"mt-6 flex flex-col gap-2 sm:flex-row",children:[t?n.jsx(ie,{type:"button",onClick:t,children:"Continue shopping"}):null,r?n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"View orders"}):null]})]}):e.kind==="cancel"?n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Checkout cancelled"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"No charges were made. You can continue shopping and try again."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]}):n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Payment failed"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:e.message??"Something went wrong while processing your payment."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]})}function WC({onContinueShopping:e,onViewOrders:t,className:r,receiptClassName:s}){const o=Va();return o.kind==="idle"?n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",r),children:n.jsx("div",{className:"text-center text-neutral-600 dark:text-neutral-400",children:"Loading order details..."})}):n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",r),children:n.jsx(ho,{result:o,onContinueShopping:e,onViewOrders:t,className:H("w-full max-w-lg",s)})})}function VC({onContinueShopping:e,className:t,receiptClassName:r}){const s={kind:"cancel"};return n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",t),children:n.jsx(ho,{result:s,onContinueShopping:e,className:H("w-full max-w-lg",r)})})}function qC(e){switch(e){case"created":return"secondary";case"paid":return"default";case"processing":return"secondary";case"fulfilled":return"outline";case"shipped":return"default";case"delivered":return"outline";case"cancelled":return"outline";case"refunded":return"outline";default:return"secondary"}}function Gp({order:e,onView:t,className:r}){const s=`${e.items.length} item${e.items.length===1?"":"s"}`,o=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),a=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(Rt,{className:H("group overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm transition-shadow hover:shadow-md dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsx(Gt,{className:"p-5",children:n.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-x-4 gap-y-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsx("div",{className:"mt-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:o})]}),n.jsx("div",{className:"flex items-start justify-end",children:n.jsx(Pn,{variant:qC(e.status),className:"capitalize",children:a})}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:s}),n.jsx("div",{className:"text-right text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:e.total,currency:e.currency})}),n.jsxs("div",{className:"col-span-2 mt-3 flex items-center justify-between gap-3 border-t border-neutral-200/70 pt-3 dark:border-neutral-800",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:()=>t(e),children:"Details"}):null]})]})})})}function Qp({orders:e,onView:t,className:r}){return n.jsx("div",{className:H("grid gap-4",r),children:e.map(s=>n.jsx(Gp,{order:s,onView:t},s.id))})}function HC(e){switch(e){case"paid":return"default";case"processing":return"secondary";case"fulfilled":return"outline";case"cancelled":return"outline";case"refunded":return"outline";default:return"secondary"}}function Yp({order:e,onBack:t,className:r}){const s=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),o=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(Rt,{className:H("overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsxs(Gt,{className:"p-6",children:[n.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-neutral-600 dark:text-neutral-400",children:[n.jsx("span",{children:s}),n.jsx("span",{className:"text-neutral-300 dark:text-neutral-700",children:"·"}),n.jsx("span",{children:o})]})]}),n.jsxs("div",{className:"flex items-center gap-2 sm:justify-end",children:[n.jsx(Pn,{variant:HC(e.status),className:"capitalize",children:o}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:t,children:"Back"}):null]})]}),n.jsx(St,{className:"my-5"}),n.jsx("div",{className:"space-y-3",children:e.items.map((a,i)=>n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"truncate text-sm text-neutral-950 dark:text-neutral-50",children:a.title}),n.jsxs("div",{className:"mt-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:["Qty ",a.qty]})]}),n.jsx("div",{className:"text-right text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:a.unitPrice*a.qty,currency:a.currency})})]},`${a.title}-${i}`))}),n.jsx(St,{className:"my-5"}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Total"}),n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:e.total,currency:e.currency})})]}),e.receiptUrl||e.invoiceUrl?n.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-2",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}):null]})})}function Di(e){const t={};e.shippingProfile&&(t.shippingProfile=e.shippingProfile),e.checkoutRequirements&&(t.checkoutRequirements=JSON.stringify(e.checkoutRequirements)),e.fulfillment?.type&&(t.fulfillmentType=e.fulfillment.type),e.fulfillment?.notes&&(t.fulfillmentNotes=e.fulfillment.notes);const r=e.attributes?.shippingCountries;return typeof r=="string"&&r.trim()&&(t.shippingCountries=r),Object.keys(t).length?t:void 0}function ZC(e){return n.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:n.jsx("path",{d:"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"})})}const GC={shop:"/shop",category:e=>`/shop/${e}`,product:e=>`/product/${e}`,cart:"/cart",checkout:"/checkout",orders:"/account/orders",subscribe:"/subscribe"};function QC(e){const t=new Set;let r=Number.POSITIVE_INFINITY,s=0;for(const i of e){for(const c of i.tags??[])t.add(c);r=Math.min(r,i.price),s=Math.max(s,i.price)}const o=Array.from(t).slice(0,12),a=Number.isFinite(r)?{min:r,max:s}:void 0;return{tags:o,price:a}}function YC({className:e,routes:t,initialCategorySlug:r}){const{config:s}=Re(),o=Dt(),a=mo(),i={...GC,...t},[c,l]=x.useState("cart"),[d,m]=x.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(min-width: 1024px)")?.matches??!1);x.useEffect(()=>{if(typeof window>"u")return;const F=window.matchMedia?.("(min-width: 1024px)");if(!F)return;const ee=()=>m(F.matches);return ee(),F.addEventListener?.("change",ee),()=>F.removeEventListener?.("change",ee)},[]);const{categories:u,isLoading:p,error:h}=Ua(),_=x.useMemo(()=>qa({includeCategory:!0}),[]),[g,f]=x.useState(_?.search??""),[w,j]=x.useState(r??_?.category),[v,b]=x.useState(_?.page??1),[k,R]=x.useState(_?.sort??"featured"),[N,C]=x.useState(_?.filters??{}),{data:T,isLoading:O,error:$}=zs({category:w,search:g.trim()||void 0,filters:N,sort:k,page:v,pageSize:24}),S=x.useMemo(()=>QC(T?.items??[]),[T?.items]),{settings:A}=or(),I=A.catalog.filters,B=A.catalog.sort,D=x.useMemo(()=>{const F=[];return B.featured&&F.push({value:"featured",label:"Featured"}),B.priceAsc&&F.push({value:"price_asc",label:"Price: Low to High"}),B.priceDesc&&F.push({value:"price_desc",label:"Price: High to Low"}),F.length===0&&F.push({value:"featured",label:"Featured"}),F},[B]);x.useEffect(()=>{D.some(F=>F.value===k)||R(D[0].value)},[D,k]),Ha({search:g,sort:k,page:v,category:w,filters:N},{includeCategory:!0});const[E,P]=x.useState(!1),[z,Z]=x.useState(!1),[K,L]=x.useState(null),[W,Y]=x.useState(!1),V=F=>{j(F.slug),b(1),P(!1)},ce=x.useCallback((F,ee,pe)=>{o.addItem({productId:F.id,variantId:ee?.id,unitPrice:F.price,currency:F.currency,titleSnapshot:ee?`${F.title} — ${ee.title}`:F.title,imageSnapshot:F.images[0]?.url,paymentResource:F.id,metadata:Di(F)},pe),a?.toast({title:"Added to cart",description:F.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(i.cart):(l("cart"),Z(!0)))}})},[o,i.cart,a]);return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:i.shop,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(Ii,{value:g,onChange:f})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(no,{open:E,onOpenChange:P,children:[n.jsx(ro,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Fr,{side:"left",children:[n.jsx(so,{children:n.jsx(oo,{children:"Browse"})}),n.jsxs("div",{className:"mt-4",children:[h?n.jsx(Zt,{description:h}):null,p?n.jsxs("div",{className:"space-y-2",children:[n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"})]}):n.jsxs("div",{className:"space-y-6",children:[n.jsx(wa,{categories:u,activeSlug:w,onSelect:V}),n.jsx(Ts,{facets:S,value:N,onChange:F=>{C(F),b(1)},onClear:()=>{C({}),b(1)},enabledFilters:I}),D.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Ns,{value:k,onValueChange:F=>{R(F),b(1)},children:[n.jsx(Or,{"aria-label":"Sort",children:n.jsx(Ps,{placeholder:"Sort"})}),n.jsx(Mr,{children:D.map(F=>n.jsx(Dr,{value:F.value,children:F.label},F.value))})]})]})]})]})]})]}),n.jsx($r,{open:!d&&z,onOpenChange:Z,side:"bottom",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx($r,{open:d&&z,onOpenChange:Z,side:"popup",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(i.checkout)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",z?"lg:hidden":void 0),onClick:()=>{l("chat"),Z(!0)},"aria-label":"Open chat",children:[n.jsx(ZC,{className:"h-4 w-4"}),"Chat"]}),n.jsxs("main",{className:"mx-auto grid max-w-7xl items-start gap-6 px-4 py-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:n.jsxs(Rt,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:[n.jsx(Er,{className:"pb-4",children:n.jsx(Tr,{className:"text-base",children:"Browse"})}),n.jsxs(Gt,{className:"flex-1 space-y-6 overflow-y-auto pr-2",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Categories"}),h?n.jsx(Zt,{className:"mt-3",description:h}):null,p?n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"})]}):n.jsx("div",{className:"mt-3",children:n.jsx(wa,{categories:u,activeSlug:w,onSelect:V})})]}),D.length>1&&n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsx("div",{className:"mt-2",children:n.jsxs(Ns,{value:k,onValueChange:F=>{R(F),b(1)},children:[n.jsx(Or,{"aria-label":"Sort",children:n.jsx(Ps,{placeholder:"Sort"})}),n.jsx(Mr,{children:D.map(F=>n.jsx(Dr,{value:F.value,children:F.label},F.value))})]})})]}),n.jsx(Ts,{facets:S,value:N,onChange:F=>{C(F),b(1)},onClear:()=>{C({}),b(1)},enabledFilters:I})]})]})})}),n.jsxs("section",{children:[n.jsx("div",{className:"flex items-end justify-between gap-3",children:n.jsxs("div",{children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:A.shopPage.title||"Shop"}),A.shopPage.description&&n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:A.shopPage.description})]})}),$?n.jsx(Zt,{className:"mt-6",description:$}):null,O?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((F,ee)=>n.jsx(De,{className:"aspect-[4/5] rounded-2xl"},ee))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(fo,{products:T?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:F=>i.product(F.slug),onAddToCart:F=>ce(F,null,1),onQuickView:F=>{L(F),Y(!0)},layout:A.shopLayout.layout,imageCrop:A.shopLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:v<=1,onClick:()=>b(F=>Math.max(1,F-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",v]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!T?.hasNextPage,onClick:()=>b(F=>F+1),children:"Next"})]})]})]})]}),n.jsx(Ei,{product:K,open:W,onOpenChange:Y,productHref:F=>i.product(F),onAddToCart:(F,ee,pe)=>ce(F,ee,pe)})]})}function KC(e){return n.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:n.jsx("path",{d:"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"})})}function XC({categorySlug:e,className:t,routes:r}){const{config:s}=Re(),o=Dt(),a=mo(),{categories:i}=Ua(),[c,l]=x.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(min-width: 1024px)")?.matches??!1);x.useEffect(()=>{if(typeof window>"u")return;const q=window.matchMedia?.("(min-width: 1024px)");if(!q)return;const ne=()=>l(q.matches);return ne(),q.addEventListener?.("change",ne),()=>q.removeEventListener?.("change",ne)},[]);const[d,m]=x.useState(!1),[u,p]=x.useState(!1),[h,_]=x.useState("cart"),g=x.useMemo(()=>qa({includeCategory:!1}),[]),[f,w]=x.useState(g?.search??""),[j,v]=x.useState(g?.page??1),[b,k]=x.useState(g?.sort??"featured"),[R,N]=x.useState(g?.filters??{}),[C,T]=x.useState(null),[O,$]=x.useState(!1),S=i.find(q=>q.slug===e)??null,{data:A,isLoading:I,error:B}=zs({category:e,search:f.trim()||void 0,filters:R,sort:b,page:j,pageSize:24}),D=r?.product??(q=>`/product/${q}`),E=r?.shop??"/shop",P=r?.cart??"/cart",z=r?.checkout??"/checkout",Z=x.useMemo(()=>{const q=A?.items??[],ne=new Set;let le=Number.POSITIVE_INFINITY,fe=0;for(const qe of q){for(const He of qe.tags??[])ne.add(He);le=Math.min(le,qe.price),fe=Math.max(fe,qe.price)}const Pe=Array.from(ne).slice(0,12),Ve=Number.isFinite(le)?{min:le,max:fe}:void 0;return{tags:Pe,price:Ve}},[A?.items]),{settings:K}=or(),L=K.catalog.filters,W=K.catalog.sort,Y=x.useMemo(()=>{const q=[];return W.featured&&q.push({value:"featured",label:"Featured"}),W.priceAsc&&q.push({value:"price_asc",label:"Price: Low to High"}),W.priceDesc&&q.push({value:"price_desc",label:"Price: High to Low"}),q.length===0&&q.push({value:"featured",label:"Featured"}),q},[W]);x.useEffect(()=>{Y.some(q=>q.value===b)||k(Y[0].value)},[Y,b]),Ha({search:f,sort:b,page:j,filters:R},{includeCategory:!1});const V=x.useCallback((q,ne,le)=>{o.addItem({productId:q.id,variantId:ne?.id,unitPrice:q.price,currency:q.currency,titleSnapshot:ne?`${q.title} — ${ne.title}`:q.title,imageSnapshot:q.images[0]?.url,paymentResource:q.id,metadata:Di(q)},le),a?.toast({title:"Added to cart",description:q.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(P):(_("cart"),p(!0)))}})},[o,P,a]),ce=q=>{N(q),v(1)},F=()=>{N({}),v(1)},ee=q=>{k(q),v(1)},pe=n.jsx(Rt,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:n.jsxs(Gt,{className:"flex-1 space-y-5 overflow-y-auto pr-2 pt-6",children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-neutral-500 dark:text-neutral-400",children:"Category"}),n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2 text-xs",children:n.jsx("a",{href:E,children:"All categories"})})]}),n.jsx("div",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:S?.name??e}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:S?.description??"Browse products in this category."})]}),Y.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Ns,{value:b,onValueChange:ee,children:[n.jsx(Or,{"aria-label":"Sort",children:n.jsx(Ps,{placeholder:"Sort"})}),n.jsx(Mr,{children:Y.map(q=>n.jsx(Dr,{value:q.value,children:q.label},q.value))})]})]}),n.jsx(St,{}),n.jsx(Ts,{facets:Z,value:R,onChange:ce,onClear:F,enabledFilters:L})]})});return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:E,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(Ii,{value:f,onChange:w})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(no,{open:d,onOpenChange:m,children:[n.jsx(ro,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Fr,{side:"left",children:[n.jsx(so,{children:n.jsx(oo,{children:"Filters"})}),n.jsx("div",{className:"mt-4",children:pe})]})]}),n.jsx($r,{open:!c&&u,onOpenChange:p,side:"bottom",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(z)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>_("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx($r,{open:c&&u,onOpenChange:p,side:"popup",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(z)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>_("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(z)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",u?"lg:hidden":void 0),onClick:()=>{_("chat"),p(!0)},"aria-label":"Open chat",children:[n.jsx(KC,{className:"h-4 w-4"}),"Chat"]}),n.jsxs("main",{className:"mx-auto max-w-7xl px-4 py-8",children:[n.jsx(Ti,{items:[{label:"Shop",href:E},{label:S?.name??e}]}),n.jsxs("div",{className:"mt-6",children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:S?.name??"Category"}),n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:S?.description??"Browse products in this category."})]}),B?n.jsx(Zt,{className:"mt-6",description:B}):null,n.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:pe})}),n.jsx("div",{children:I?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((q,ne)=>n.jsx(De,{className:"aspect-[4/5] rounded-2xl"},ne))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(fo,{products:A?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:q=>D(q.slug),onAddToCart:q=>V(q,null,1),onQuickView:q=>{T(q),$(!0)},layout:K.categoryLayout.layout,imageCrop:K.categoryLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:j<=1,onClick:()=>v(q=>Math.max(1,q-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",j]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!A?.hasNextPage,onClick:()=>v(q=>q+1),children:"Next"})]})]})})]}),n.jsx(Ei,{product:C,open:O,onOpenChange:$,productHref:q=>D(q),onAddToCart:(q,ne,le)=>V(q,ne,le)})]})]})}function JC(e){return!e||typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function eN({slug:e,className:t,routes:r}){const s=Dt(),o=mo(),{product:a,isLoading:i,error:c}=$d(e),[l,d]=x.useState(1),[m,u]=x.useState({selectedOptions:{},variant:null});x.useEffect(()=>{if(!a||!a.variants?.length)return;const S=a.variants[0];u({selectedOptions:{...S.options},variant:S})},[a?.id]);const{settings:p}=or(),{mode:h,maxItems:_}=p.relatedProducts,g=Vd({productId:a?.id,enabled:h==="ai"&&!!a?.id}),f=x.useMemo(()=>h==="by_category"&&a?.categoryIds?.length?{category:a.categoryIds[0],page:1,pageSize:_+1}:{page:1,pageSize:_+4},[h,_,a?.categoryIds]),w=zs(f),j=x.useMemo(()=>{const A=(w.data?.items??[]).filter(I=>I.slug!==e);if(h==="manual"&&a){const I=a.attributes?.relatedProductIds||a.attributes?.related_product_ids;if(I){const B=JC(String(I));if(B.length>0){const D=new Map(A.map(P=>[P.id,P]));return B.map(P=>D.get(P)).filter(P=>!!P).slice(0,_)}}}if(h==="ai"&&g.relatedProductIds&&g.relatedProductIds.length>0){const I=new Map(A.map(D=>[D.id,D])),B=g.relatedProductIds.map(D=>I.get(D)).filter(D=>!!D);if(B.length>0)return B.slice(0,_)}return A.slice(0,_)},[w.data?.items,e,h,_,a,g.relatedProductIds]),v=r?.shop??"/shop",b=r?.checkout??"/checkout",k=r?.cart??"/cart",R=r?.product??(S=>`/product/${S}`);if(i)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsxs("div",{className:"mx-auto max-w-6xl",children:[n.jsx(De,{className:"h-5 w-40"}),n.jsxs("div",{className:"mt-6 grid gap-8 lg:grid-cols-2",children:[n.jsx(De,{className:"aspect-square rounded-2xl"}),n.jsxs("div",{className:"space-y-4",children:[n.jsx(De,{className:"h-8 w-2/3"}),n.jsx(De,{className:"h-6 w-32"}),n.jsx(De,{className:"h-20"}),n.jsx(De,{className:"h-11"})]})]})]})});if(c)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsx("div",{className:"mx-auto max-w-6xl",children:n.jsx(Zt,{description:c})})});if(!a)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsx("div",{className:"mx-auto max-w-6xl",children:n.jsx(Zt,{description:"Product not found."})})});const N=m.variant?.price??a.price,C=m.variant?.compareAtPrice??a.compareAtPrice,T=a.inventoryStatus==="out_of_stock"||typeof a.inventoryQuantity=="number"&&a.inventoryQuantity<=0,O=()=>{T||(s.addItem({productId:a.id,variantId:m.variant?.id,unitPrice:N,currency:a.currency,titleSnapshot:m.variant?`${a.title} — ${m.variant.title}`:a.title,imageSnapshot:a.images[0]?.url,paymentResource:a.id,metadata:Di(a)},l),o?.toast({title:"Added to cart",description:a.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&window.location.assign(k)}}))},$=()=>{T||(O(),typeof window<"u"&&window.location.assign(b))};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-8",children:[n.jsx(Ti,{items:[{label:"Shop",href:v},{label:a.title}]}),n.jsxs("div",{className:"mt-6 grid gap-10 lg:grid-cols-2",children:[n.jsx(Ni,{images:a.images}),n.jsxs("div",{className:"space-y-6",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:a.title}),n.jsx("div",{className:"mt-3",children:n.jsx(po,{amount:N,currency:a.currency,compareAt:C})}),T?n.jsx("div",{className:"mt-2 text-sm font-medium text-red-700 dark:text-red-300",children:"Out of stock"}):typeof a.inventoryQuantity=="number"&&a.inventoryQuantity>0&&a.inventoryQuantity<=5?n.jsxs("div",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:["Only ",n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:a.inventoryQuantity})," left"]}):null,n.jsx("p",{className:"mt-4 text-sm text-neutral-600 dark:text-neutral-400",children:a.description})]}),n.jsx(Pi,{product:a,value:{selectedOptions:m.selectedOptions,variantId:m.variant?.id},onChange:S=>u(S)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(Ai,{qty:l,onChange:d}),n.jsx(ie,{type:"button",onClick:O,className:"flex-1",disabled:T,children:T?"Out of stock":"Add to cart"}),n.jsx(ie,{type:"button",variant:"outline",onClick:$,disabled:T,children:"Buy now"})]}),(p.sections.showDescription||p.sections.showSpecs||p.sections.showShipping)&&n.jsxs(dp,{type:"single",collapsible:!0,defaultValue:p.sections.showDescription?"desc":void 0,children:[p.sections.showDescription&&n.jsxs(Sr,{value:"desc",children:[n.jsx(Cr,{children:"Description"}),n.jsx(Nr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.description})})]}),p.sections.showSpecs&&n.jsxs(Sr,{value:"specs",children:[n.jsx(Cr,{children:"Specs"}),n.jsx(Nr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.attributes?n.jsx("div",{className:"space-y-1",children:Object.entries(a.attributes).map(([S,A])=>n.jsxs("div",{children:[n.jsxs("span",{className:"font-medium text-neutral-950 dark:text-neutral-50",children:[S,":"]})," ",String(A)]},S))}):"No specs provided."})})]}),p.sections.showShipping&&n.jsxs(Sr,{value:"ship",children:[n.jsx(Cr,{children:"Shipping & returns"}),n.jsx(Nr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Ships in 2–3 business days. Easy returns within 30 days."})})]})]})]})]}),p.sections.showRelatedProducts&&j.length?n.jsxs("section",{className:"mt-12",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Related products"}),n.jsx("div",{className:"mt-4",children:n.jsx(fo,{products:j,columns:{base:2,md:4,lg:4},layout:p.relatedProducts.layout.layout,imageCrop:p.relatedProducts.layout.imageCrop,getProductHref:S=>R(S.slug),onAddToCart:S=>s.addItem({productId:S.id,unitPrice:S.price,currency:S.currency,titleSnapshot:S.title,imageSnapshot:S.images[0]?.url,paymentResource:S.id},1)})})]}):null]})})}function tN({className:e,checkoutHref:t}){const{config:r}=Re(),{settings:s}=or(),o=t??"/checkout",a=r.checkout.allowPromoCodes&&s.checkout.promoCodes;return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-10",children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Cart"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"Review items, adjust quantities, then check out."}),n.jsx("div",{className:"mt-8",children:n.jsx(Fp,{onCheckout:()=>{typeof window<"u"&&window.location.assign(o)},showPromoCode:a})})]})})}function nN({className:e,routes:t}){const{config:r}=Re(),s=Dt(),o=Va(),a=r.customer?.isSignedIn??!!r.customer?.id,c=!(r.checkout.requireAccount?!1:r.checkout.guestCheckout??!0)&&!a;x.useEffect(()=>{o.kind==="success"&&s.clear()},[o.kind]);const l=t?.shop??"/shop",d=t?.orders??"/account/orders",m=t?.login;return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-10",children:[n.jsx(ho,{result:o,onContinueShopping:()=>{typeof window<"u"&&window.location.assign(l)},onViewOrders:()=>{typeof window<"u"&&window.location.assign(d)}}),o.kind==="idle"?n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Checkout"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:r.checkout.mode==="none"?"Confirm and pay.":"Enter details, then complete payment."})]}),n.jsx("div",{className:"mt-8",children:n.jsx(Ld,{children:c?n.jsxs(Rt,{className:"rounded-2xl",children:[n.jsx(Er,{className:"pb-4",children:n.jsx(Tr,{className:"text-base",children:"Sign in required"})}),n.jsxs(Gt,{children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"This store requires an account to complete checkout."}),m?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",onClick:()=>{typeof window<"u"&&window.location.assign(m)},children:"Sign in"})}):null]})]}):n.jsx(Bp,{left:n.jsxs("div",{className:"space-y-6",children:[n.jsx(Wp,{}),n.jsxs(Rt,{className:"rounded-2xl",children:[n.jsx(Er,{className:"pb-4",children:n.jsx(Tr,{className:"text-base",children:"Payment"})}),n.jsxs(Gt,{children:[n.jsx(St,{className:"mb-4"}),n.jsx(Hp,{})]})]})]}),right:n.jsx("div",{className:"lg:sticky lg:top-24",children:n.jsx(Zp,{})})})})})]}):null]})})}function rN({className:e,isSignedIn:t=!0,onLogin:r}){const{orders:s,isLoading:o,error:a}=zd(),[i,c]=x.useState(null);return t?n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-5xl px-4 py-10 sm:py-12",children:[n.jsxs("header",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Orders"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"View past purchases and receipts."})]}),!o&&!a&&!i&&s.length>0?n.jsxs("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:[s.length," order",s.length===1?"":"s"]}):null]}),a?n.jsx(Zt,{className:"mt-8",description:a}):null,o?n.jsxs("div",{className:"mt-8 grid gap-4",children:[n.jsx(De,{className:"h-32 rounded-2xl"}),n.jsx(De,{className:"h-32 rounded-2xl"}),n.jsx(De,{className:"h-32 rounded-2xl"})]}):s.length===0?n.jsx("div",{className:"mt-8",children:n.jsx(tr,{title:"No orders yet",description:"When you purchase something, it will show up here."})}):i?n.jsx("div",{className:"mt-8",children:n.jsx(Yp,{order:i,onBack:()=>c(null)})}):n.jsx("div",{className:"mt-8",children:n.jsx(Qp,{orders:s,onView:c})})]})}):n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-10 dark:bg-neutral-950",e),children:n.jsx("div",{className:"mx-auto max-w-4xl",children:n.jsx(tr,{title:"Sign in to view your orders",description:"Your purchase history will appear here once you're logged in.",actionLabel:r?"Sign in":void 0,onAction:r})})})}function sN({className:e}){return n.jsxs("svg",{className:e,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"6 9 6 2 18 2 18 9"}),n.jsx("path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"}),n.jsx("rect",{x:"6",y:"14",width:"12",height:"8"})]})}function oN({className:e}){return n.jsx("svg",{className:e,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})})}function aN(e){switch(e){case"x402":return"Crypto (x402)";case"credits":return"Credits";case"stripe":return"Card";default:return"Payment"}}function iN({order:e,source:t,purchaseId:r,customerEmail:s,customerName:o,className:a,onBack:i}){const{config:c}=Re(),l=t??e.source,d=r??e.purchaseId,m=s??e.customerEmail,u=o??e.customerName,p=c.brand?.name??"Store",h=c.brand?.logoUrl,_=()=>{typeof window<"u"&&window.print()},g=new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"}),f=new Date(e.createdAt).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return n.jsxs("div",{className:H("min-h-screen bg-neutral-100 dark:bg-neutral-900 print:bg-white print:dark:bg-white",a),children:[n.jsx("div",{className:"border-b border-neutral-200 bg-white px-4 py-3 dark:border-neutral-800 dark:bg-neutral-950 print:hidden",children:n.jsxs("div",{className:"mx-auto flex max-w-2xl items-center justify-between",children:[i?n.jsxs(ie,{type:"button",variant:"ghost",size:"sm",onClick:i,children:[n.jsx(oN,{className:"mr-1"})," Back"]}):n.jsx("div",{}),n.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:_,children:[n.jsx(sN,{className:"mr-2"})," Print Receipt"]})]})}),n.jsx("div",{className:"mx-auto max-w-2xl px-4 py-8 print:max-w-none print:px-0 print:py-0",children:n.jsxs("div",{className:"rounded-xl border border-neutral-200 bg-white p-8 shadow-sm dark:border-neutral-800 dark:bg-neutral-950 print:border-0 print:shadow-none print:dark:bg-white print:dark:text-neutral-950",children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-neutral-200 pb-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[h?n.jsx("img",{src:h,alt:p,className:"h-10 w-10 rounded-lg object-contain"}):null,n.jsx("div",{className:"text-xl font-semibold",children:p})]}),n.jsxs("div",{className:"text-right",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Receipt"}),n.jsx("div",{className:"mt-1 font-mono text-sm",children:e.id})]})]}),n.jsxs("div",{className:"mt-6 grid grid-cols-2 gap-4 text-sm sm:grid-cols-3",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Date"}),n.jsx("div",{className:"mt-1 font-medium",children:g}),n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:f})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Payment Method"}),n.jsx("div",{className:"mt-1 font-medium",children:aN(l)})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Status"}),n.jsx("div",{className:"mt-1",children:n.jsx(Pn,{variant:"outline",className:"capitalize print:border-neutral-300",children:e.status})})]})]}),(u||m)&&n.jsxs("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Customer"}),u&&n.jsx("div",{className:"mt-1 font-medium",children:u}),m&&n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:m})]}),n.jsx("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-neutral-200 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("th",{className:"pb-3 text-left font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Item"}),n.jsx("th",{className:"pb-3 text-center font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Qty"}),n.jsx("th",{className:"pb-3 text-right font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Price"})]})}),n.jsx("tbody",{children:e.items.map((w,j)=>n.jsxs("tr",{className:"border-b border-neutral-100 dark:border-neutral-800/50 print:dark:border-neutral-100",children:[n.jsx("td",{className:"py-3",children:n.jsx("div",{className:"font-medium",children:w.title})}),n.jsx("td",{className:"py-3 text-center text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:w.qty}),n.jsx("td",{className:"py-3 text-right",children:Qe({amount:w.unitPrice*w.qty,currency:w.currency})})]},`${w.title}-${j}`))})]})}),n.jsxs("div",{className:"mt-4 flex flex-col items-end gap-2 text-sm",children:[n.jsxs("div",{className:"flex w-48 justify-between",children:[n.jsx("span",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Subtotal"}),n.jsx("span",{children:Qe({amount:e.total,currency:e.currency})})]}),n.jsxs("div",{className:"flex w-48 justify-between border-t border-neutral-200 pt-2 text-base font-semibold dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("span",{children:"Total"}),n.jsx("span",{children:Qe({amount:e.total,currency:e.currency})})]})]}),d&&n.jsxs("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Transaction ID"}),n.jsx("div",{className:"mt-1 break-all font-mono text-xs",children:d})]}),n.jsxs("div",{className:"mt-8 border-t border-neutral-200 pt-6 text-center text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400 print:dark:border-neutral-200 print:dark:text-neutral-500",children:[n.jsx("p",{children:"Thank you for your purchase!"}),n.jsx("p",{className:"mt-1",children:"If you have any questions, please contact support."})]})]})})]})}function cN({className:e}){return n.jsx("svg",{className:H("h-4 w-4 flex-shrink-0",e),viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})}function lN({className:e,title:t="Choose Your Plan",subtitle:r="Select the plan that best fits your needs.",annualSavingsBadge:s="2 months free",popularBadgeText:o="Best Deal",footerNotice:a}){const{config:i}=Re(),{tiers:c,status:l,isLoading:d,error:m}=Fd(),[u,p]=x.useState("monthly"),h=!!i.adapter.createSubscriptionCheckoutSession,_=async g=>{if(!i.adapter.createSubscriptionCheckoutSession)return;const f=await i.adapter.createSubscriptionCheckoutSession({tierId:g,interval:u,successUrl:i.checkout.successUrl,cancelUrl:i.checkout.cancelUrl});f.kind==="redirect"&&typeof window<"u"&&window.location.assign(f.url)};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-16",children:[n.jsxs("div",{className:"text-center",children:[n.jsx("h1",{className:"text-5xl font-bold tracking-tight",children:t}),n.jsx("p",{className:"mt-4 text-base text-neutral-600 dark:text-neutral-400",children:r})]}),n.jsx("div",{className:"mt-10 flex justify-center",children:n.jsxs("div",{className:"inline-flex items-center rounded-full bg-neutral-200/60 p-1 dark:bg-neutral-800/60",children:[n.jsxs("button",{type:"button",onClick:()=>p("annual"),className:H("relative flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-all",u==="annual"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:["Yearly",s&&n.jsx("span",{className:H("rounded-full px-2 py-0.5 text-xs font-medium",u==="annual"?"bg-white/20 text-white dark:bg-neutral-900/20 dark:text-neutral-900":"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900"),children:s})]}),n.jsx("button",{type:"button",onClick:()=>p("monthly"),className:H("rounded-full px-4 py-2 text-sm font-medium transition-all",u==="monthly"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:"Monthly"})]})}),m?n.jsx(Zt,{className:"mt-10",description:m}):null,d?n.jsxs("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[n.jsx(De,{className:"h-[480px] rounded-2xl"}),n.jsx(De,{className:"h-[480px] rounded-2xl"}),n.jsx(De,{className:"h-[480px] rounded-2xl"})]}):c.length===0?n.jsx("div",{className:"mt-12",children:n.jsx(tr,{title:"No plans available",description:"Subscription plans will appear here once configured."})}):n.jsx("div",{className:"mt-12 grid gap-6 md:grid-cols-3 items-start",children:c.map(g=>{const f=l?.isActive&&l.currentTierId===g.id,w=u==="annual"&&g.priceAnnual?g.priceAnnual:g.priceMonthly,j=g.isPopular,v=g.inventoryQuantity!=null,b=v?Math.max(0,(g.inventoryQuantity??0)-(g.inventorySold??0)):null,k=v&&b===0,R=v&&b!=null&&b>0&&b<=5,[N,...C]=g.features;return n.jsxs("div",{className:H("relative flex flex-col rounded-2xl border p-6 transition-shadow",j?"border-neutral-900 bg-neutral-900 text-white shadow-xl dark:border-white dark:bg-white dark:text-neutral-900":"border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-900"),children:[j&&o&&n.jsx("div",{className:"absolute -top-3 right-4",children:n.jsx("span",{className:"rounded-full bg-neutral-100 px-3 py-1 text-xs font-semibold text-neutral-900 shadow-sm dark:bg-neutral-800 dark:text-white",children:o})}),n.jsxs("div",{className:"mb-6",children:[n.jsx("h3",{className:"text-xl font-bold",children:g.title}),g.description&&n.jsx("p",{className:H("mt-2 text-sm leading-relaxed",j?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:g.description})]}),n.jsxs("div",{className:"mb-6",children:[n.jsx("div",{className:"text-5xl font-bold tracking-tight",children:Qe({amount:w,currency:g.currency||i.currency})}),n.jsxs("div",{className:H("mt-2 text-sm",j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:["Per ",u==="annual"?"year":"month",", billed ",u==="annual"?"annually":"monthly"]})]}),v&&n.jsx("div",{className:H("mb-3 text-xs font-medium",k?"text-red-600 dark:text-red-400":R?j?"text-amber-300 dark:text-amber-600":"text-amber-600 dark:text-amber-400":j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:k?"Sold out":`${b} remaining`}),n.jsx(ie,{type:"button",className:H("mb-6 w-full rounded-full py-3 font-medium",j?"bg-white text-neutral-900 hover:bg-neutral-100 dark:bg-neutral-900 dark:text-white dark:hover:bg-neutral-800":""),variant:j?"default":"outline",disabled:f||!h||k,onClick:()=>void _(g.id),children:k?"Sold Out":f?"Current Plan":"Purchase"}),N&&n.jsx("div",{className:H("mb-4 text-sm font-semibold",j?"":"text-neutral-900 dark:text-white"),children:N}),C.length>0&&n.jsx("ul",{className:"space-y-3",children:C.map((T,O)=>n.jsxs("li",{className:"flex items-start gap-3",children:[n.jsx(cN,{className:H("mt-0.5",j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400")}),n.jsx("span",{className:H("text-sm leading-relaxed",j?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:T})]},O))})]},g.id)})}),a&&n.jsx("div",{className:"mt-12 text-center",children:n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400 leading-relaxed max-w-2xl mx-auto",children:a})})]})})}function dN(e){const{processCartCheckout:t}=Rs();return x.useMemo(()=>({...e,async createCheckoutSession(r){const s=await t(r.cart,r.options.successUrl,r.options.cancelUrl,r.options.metadata,r.customer.email,r.options.discountCode);if(!s.success)throw new Error(s.error||"Checkout failed");return{kind:"redirect",url:r.options.successUrl??"/"}},async resolveCheckoutReturn({query:r}){return Wa(r)}}),[e,t])}const uN=Object.freeze(Object.defineProperty({__proto__:null,Accordion:dp,AccordionContent:Nr,AccordionItem:Sr,AccordionTrigger:Cr,AddressForm:_a,Badge:Pn,Breadcrumbs:Ti,Button:ie,Card:Rt,CardContent:Gt,CardDescription:iu,CardFooter:cu,CardHeader:Er,CardTitle:Tr,CartLineItem:Ri,CartPageContent:Fp,CartPanel:$p,CartProvider:ng,CartSidebar:$r,CartSummary:Oi,CartTemplate:tN,CategoryNav:wa,CategoryTemplate:XC,CedrosShopProvider:$h,CheckoutCancelPage:VC,CheckoutForm:Wp,CheckoutLayout:Bp,CheckoutProvider:Ld,CheckoutReceipt:ho,CheckoutSuccessPage:WC,CheckoutTemplate:nN,Dialog:pi,DialogClose:Qk,DialogContent:eo,DialogDescription:gi,DialogFooter:Bm,DialogHeader:hi,DialogOverlay:fi,DialogPortal:Fm,DialogTitle:to,DialogTrigger:Gk,EmptyState:tr,ErrorBoundary:AS,ErrorState:Zt,FAQItem:Mp,FAQList:PC,FilterPanel:Ts,Input:Be,InventoryVerificationDialog:qp,Label:at,OrderCard:Gp,OrderDetails:Yp,OrderList:Qp,OrderReview:Zp,PaymentStep:Hp,Price:po,ProductCard:Dp,ProductGallery:Ni,ProductGrid:fo,ProductTemplate:eN,PromoCodeInput:Mi,PurchaseHistoryTemplate:rN,QuantitySelector:Ai,QuickViewDialog:Ei,ReceiptTemplate:iN,SearchInput:Ii,Select:Ns,SelectContent:Mr,SelectGroup:Ak,SelectItem:Dr,SelectTrigger:Or,SelectValue:Ps,Separator:St,Sheet:no,SheetClose:Um,SheetContent:Fr,SheetDescription:Vm,SheetHeader:so,SheetOverlay:xi,SheetPortal:Wm,SheetTitle:oo,SheetTrigger:ro,ShippingMethodSelector:Up,ShopTemplate:YC,Skeleton:De,SubscriptionTemplate:lN,Tabs:Si,TabsContent:Ep,TabsList:uo,TabsTrigger:Lr,ToastProvider:oC,VariantSelector:Pi,createMockCommerceAdapter:Wh,createPaywallCommerceAdapter:Gh,parseCheckoutReturn:Wa,readCatalogUrlState:qa,useAIRelatedProducts:Vd,useCart:Dt,useCartInventory:Za,useCatalogUrlSync:Ha,useCategories:Ua,useCedrosPayCheckoutAdapter:dN,useCedrosShop:Re,useCheckout:$s,useCheckoutResultFromUrl:Va,useHoldExpiry:Wv,useInventoryVerification:Ud,useOptionalToast:mo,useOrders:zd,usePaymentMethodsConfig:Wd,useProduct:$d,useProducts:zs,useShippingMethods:Bd,useStandaloneCheckout:Ov,useStorefrontSettings:or,useSubscriptionData:Fd,useToast:sC,validateCommerceAdapterContract:Zv},Symbol.toStringTag,{value:"Module"}));exports.CEDROS_EVENTS=gn;exports.CSP_PRESETS=Pf;exports.CedrosPay=$f;exports.CedrosPayAdminDashboard=yh;exports.CouponsSection=zl;exports.CreditsButton=Pa;exports.CreditsSubscribeButton=jh;exports.CryptoButton=Aa;exports.ERROR_CATEGORIES=Cl;exports.PaymentMethodBadge=wh;exports.PaymentModal=Ol;exports.ProductPrice=vh;exports.ProductsSection=Ll;exports.PurchaseButton=Ml;exports.RPC_PROVIDERS=Nf;exports.RefundsSection=Fl;exports.SECURITY_RECOMMENDATIONS=Lh;exports.SettingsSection=Ia;exports.StripeButton=Na;exports.SubscribeButton=_h;exports.SubscriptionManagementPanel=Ah;exports.TransactionsSection=$l;exports.calculateDiscountPercentage=uf;exports.cedrosPayPlugin=bh;exports.createDedupedClickHandler=Mn;exports.createTranslator=Tl;exports.detectLocale=Al;exports.emitPaymentError=kt;exports.emitPaymentProcessing=un;exports.emitPaymentStart=Ln;exports.emitPaymentSuccess=$n;exports.emitWalletConnect=Xo;exports.emitWalletConnected=Sl;exports.emitWalletError=is;exports.formatCSP=Pl;exports.formatCouponCodes=df;exports.generateCSP=Cf;exports.generateCSPDirectives=Nl;exports.getAvailableLocales=Ef;exports.getLocalizedError=Tf;exports.getModalCloseButtonStyles=Ca;exports.getUserErrorMessage=jf;exports.index=uN;exports.isRetryableError=_f;exports.loadLocale=El;exports.logSecurityReport=Dh;exports.parseCouponCodes=lf;exports.stackCheckoutCoupons=mf;exports.useCreditsPayment=Il;exports.useCreditsSubscription=Xl;exports.useLocalizedError=If;exports.usePaymentMode=nr;exports.useStripeCheckout=Rs;exports.useSubscription=Kl;exports.useSubscriptionManagement=Jl;exports.useTranslation=xn;exports.useX402Payment=Rl;exports.validateSecurity=Mh;
|