@cedros/pay-react 1.1.8 → 1.1.10

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.
@@ -1,136 +0,0 @@
1
- "use strict";var Kp=Object.create;var Vi=Object.defineProperty;var Xp=Object.getOwnPropertyDescriptor;var Jp=Object.getOwnPropertyNames;var ef=Object.getPrototypeOf,tf=Object.prototype.hasOwnProperty;var nf=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Jp(t))!tf.call(e,o)&&o!==r&&Vi(e,o,{get:()=>t[o],enumerable:!(s=Xp(t,o))||s.enumerable});return e};var rf=(e,t,r)=>(r=e!=null?Kp(ef(e)):{},nf(t||!e||!e.__esModule?Vi(r,"default",{value:e,enumerable:!0}):r,e));const n=require("react/jsx-runtime"),v=require("react"),Y=require("./CedrosContext-C2v_s8cc.js"),ja=require("@solana/wallet-adapter-react"),Hi=require("@solana/wallet-adapter-base"),sf=require("@solana/wallet-adapter-react-ui"),of=require("@solana/web3.js"),Zi=require("./index-WcOlBYZJ.js"),ka=require("react-dom");function _l(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=_l(v),Ts=_l(ka);function af(e){return!e||!e.coupon_codes?[]:e.coupon_codes.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function cf(e,t=", "){return e.join(t)}function lf(e,t){return e<=0?0:(e-t)/e*100}function df(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 wl(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return 1;const r=Math.floor(t);return r>0?r:1}function ms(e){return e.map(t=>({resource:t.resource,quantity:wl(t.quantity),variantId:t.variantId,metadata:t.metadata}))}function cn(e){return e.reduce((t,r)=>t+wl(r.quantity),0)}function uf(e){return!!(e&&e.length>0&&(e.length>1||e.length===1&&(e[0].quantity??1)>1))}const mf={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 ps(e){return mf[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,Qo=new Map,Yo=new Map,kl=200,Sa=2e3;function pf(e){const t=Yo.get(e);return t?Date.now()<t?!0:(Yo.delete(e),!1):!1}function ff(e,t=kl){const r=Date.now()+t;Yo.set(e,r)}function hf(e,t=Sa){const r=jl.get(e);if(!r)return!1;const o=Date.now()-r;return o<t?(Y.getLogger().debug(`[Deduplication] Duplicate request blocked: ${e} (${o}ms ago)`),!0):!1}function gf(e){jl.set(e,Date.now())}function yf(e){return Qo.get(e)||null}function xf(e,t){Qo.set(e,t);const r=()=>{Qo.delete(e),gf(e)};return t.then(r,r),t}async function vf(e,t,r={}){const{windowMs:s=Sa,throwOnDuplicate:o=!0}=r,a=yf(e);if(a)return Y.getLogger().debug(`[Deduplication] Reusing in-flight request: ${e}`),a;if(hf(e,s)){if(o)throw new Error(`Duplicate request blocked: ${e}`);return Y.getLogger().warn(`[Deduplication] Duplicate request blocked but not throwing: ${e}`),Promise.reject(new Error("Duplicate request"))}const i=t();return xf(e,i)}function Rn(e,t,r={}){const{cooldownMs:s=kl,deduplicationWindowMs:o=Sa}=r;return async()=>{if(pf(e)){Y.getLogger().debug(`[Deduplication] Button in cooldown: ${e}`);return}ff(e,s);try{await vf(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 fn={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 On(e,t){if(typeof window>"u")return;const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!1});window.dispatchEvent(r)}function Mn(e,t,r){On(fn.PAYMENT_START,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function Ko(e){On(fn.WALLET_CONNECT,{timestamp:Date.now(),wallet:e})}function Sl(e,t){On(fn.WALLET_CONNECTED,{timestamp:Date.now(),wallet:e,publicKey:t})}function as(e,t){On(fn.WALLET_ERROR,{timestamp:Date.now(),wallet:t,error:e})}function ln(e,t,r){On(fn.PAYMENT_PROCESSING,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function Dn(e,t,r,s){On(fn.PAYMENT_SUCCESS,{timestamp:Date.now(),method:e,transactionId:t,resource:r,itemCount:s})}function jt(e,t,r,s){On(fn.PAYMENT_ERROR,{timestamp:Date.now(),method:e,error:t,resource:r,itemCount:s})}class an 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,an.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 ps(this.code)}static fromErrorResponse(t,r){const s=t.error.retryable??Cl.RETRYABLE.includes(t.error.code);return new an(t.error.code,t.error.message,s,t.error.details,r)}static fromUnknown(t){return t instanceof an?t:t instanceof Error?new an("internal_error",t.message,!1):new an("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 bf(e){return e instanceof an&&e.canRetry()}function _f(e){return e instanceof an?e.getUserMessage():e instanceof Error?e.message:String(e)}function wf(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 jf(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=wf(t);if(m.push(u),r){const f=jf(r);m.includes(f)||m.push(f)}s.forEach(f=>{m.includes(f)||m.push(f)}),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 kf(e={},t="header"){const r=Nl(e);return Pl(r,t)}const Sf={HELIUS:"https://*.helius-rpc.com",QUICKNODE:"https://*.quicknode.pro",ALCHEMY:"https://*.alchemy.com",ANKR:"https://rpc.ankr.com",TRITON:"https://*.rpcpool.com"},Cf={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 jr(e){return new Date(e).toLocaleString()}function Is(){const{stripeManager:e}=Y.useCedrosContext(),[t,r]=v.useState({status:"idle",error:null,transactionId:null}),s=v.useRef(!1),o=v.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 f={resource:c,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p};try{const g=await e.processPayment(f);return r({status:g.success?"success":"error",error:g.success?null:g.error||"Payment failed",transactionId:g.success&&g.transactionId||null}),g}catch(g){const h=g instanceof Error?g.message:"Payment failed";return r({status:"error",error:h,transactionId:null}),{success:!1,error:h}}finally{s.current=!1}},[e]),a=v.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 f=ms(c);try{const g=await e.processCartCheckout({items:f,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p});return r({status:g.success?"success":"error",error:g.success?null:g.error||"Cart checkout failed",transactionId:g.success&&g.transactionId||null}),g}catch(g){const h=g instanceof Error?g.message:"Cart checkout failed";return r({status:"error",error:h,transactionId:null}),{success:!1,error:h}}finally{s.current=!1}},[e]),i=v.useCallback(()=>{r({status:"idle",error:null,transactionId:null}),s.current=!1},[]);return{...t,processPayment:o,processCartCheckout:a,reset:i}}function nr(e,t){return v.useMemo(()=>{const r=uf(t),s=e||(t?.length===1?t[0].resource:"");return{isCartMode:r,effectiveResource:s}},[e,t])}const Nf=(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.":""))))})},xo=new Map;let Ur=null;async function Gi(e){if(xo.has(e))return xo.get(e);try{const t=await Nf(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 xo.set(e,r),r}catch{return null}}async function Pf(){if(Ur)return Ur;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 Ur=t.length>0?t:["en"],Ur}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 Af(e,t,r=!0){const s=t.errors[e];if(!s){const o=ps(e);return r&&o.action?`${o.message} ${o.action}`:o.message}return r&&s.action?`${s.message} ${s.action}`:s.message}function hn(e){const[t,r]=v.useState(null),[s,o]=v.useState(!0),a=v.useMemo(()=>e||Al(),[e]);return v.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:v.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 Ef(e,t=!0){const{translations:r}=hn();if(!r){const o=ps(e);return t&&o.action?`${o.message} ${o.action}`:o.message}const s=r.errors[e];if(!s){const o=ps(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:f,error:g,transactionId:h,processPayment:b,processCartCheckout:w}=Is(),y=Y.useCedrosTheme(),{isCartMode:_,effectiveResource:j}=nr(e,t),{t:C,translations:I}=hn(),S=c||C("ui.pay_with_card"),N=y.unstyled?p:`${y.className} cedros-theme__stripe-button ${p}`.trim(),$=g&&typeof g!="string"?g?.code??null:null,P=g?typeof g=="string"?g:(O=>{if(!O||!I)return"";const T=I.errors[O];return T?T.action?`${T.message} ${T.action}`:T.message:""})($):null,A=v.useCallback(async()=>{Y.getLogger().debug("[StripeButton] executePayment with couponCode:",i);const O=_&&t?cn(t):void 0;if(Mn("stripe",j,O),d&&d("stripe"),!_&&!j){const W="Invalid payment configuration: missing resource or items";Y.getLogger().error("[StripeButton]",W),jt("stripe",W,j,O),u&&u(W);return}let T;ln("stripe",j,O),_&&t?(Y.getLogger().debug("[StripeButton] Processing cart checkout with coupon:",i),T=await w(t,r,s,o,a,i)):j&&(Y.getLogger().debug("[StripeButton] Processing single payment with coupon:",i),T=await b(j,r,s,o,a,i)),T&&T.success&&T.transactionId?(Dn("stripe",T.transactionId,j,O),m&&m(T.transactionId)):T&&!T.success&&T.error&&(jt("stripe",T.error,j,O),u&&u(T.error))},[i,_,j,t,r,s,o,a,w,b,d,m,u]),L=v.useMemo(()=>_&&t?`stripe-cart-${t.map(O=>O.resource).join("-")}`:`stripe-${j||"unknown"}`,[_,t,j]),z=v.useMemo(()=>Rn(L,A),[L,A]),D=f==="loading",R=l||D;return n.jsxs("div",{className:N,style:y.unstyled?{}:y.style,children:[n.jsx("button",{onClick:z,disabled:R,className:y.unstyled?p:"cedros-theme__button cedros-theme__stripe",type:"button",children:D?C("ui.processing"):S}),P&&n.jsx("div",{className:y.unstyled?"":"cedros-theme__error",children:P}),h&&n.jsx("div",{className:y.unstyled?"":"cedros-theme__success",children:C("ui.payment_successful")})]})}function Il(){const{creditsManager:e}=Y.useCedrosContext(),[t,r]=v.useState({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s=v.useRef(!1),o=v.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(f=>({...f,status:"error",error:p})),null}},[e]),a=v.useCallback(async(d,m)=>{r(u=>({...u,status:"loading",error:null}));try{const u=ms(d),p=await e.requestCartQuote(u,m);return r(f=>({...f,status:"idle"})),p}catch(u){const p=u instanceof Error?u.message:"Failed to fetch cart credits quote";return r(f=>({...f,status:"error",error:p})),null}},[e]),i=v.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 f=await e.processPayment(d,m,u,p);return r({status:f.success?"success":"error",error:f.success?null:f.error||"Credits payment failed",transactionId:f.success&&f.transactionId||null,requirement:null,holdId:null}),f}finally{s.current=!1}},[e]),c=v.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 f=ms(d),g=await e.requestCartQuote(f,u);if(!g)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 b=(await e.createCartHold({cartId:g.cartId,authToken:m})).holdId;r(y=>({...y,holdId:b}));const w=await e.authorizeCartPayment({cartId:g.cartId,holdId:b,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(f){const g=f instanceof Error?f.message:"Cart credits payment failed";return r({status:"error",error:g,transactionId:null,requirement:null,holdId:null}),{success:!1,error:g}}finally{s.current=!1}},[e]),l=v.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:f,processPayment:g,processCartPayment:h}=Il(),b=Y.useCedrosTheme(),{isCartMode:w,effectiveResource:y}=nr(e,t),{t:_,translations:j}=hn(),C=a||_("ui.pay_with_credits")||"Pay with Credits",I=b.unstyled?m:`${b.className} cedros-theme__credits-button ${m}`.trim(),S=p&&typeof p!="string"?p?.code??null:null,$=p?typeof p=="string"?p:(D=>{if(!D||!j)return"";const R=j.errors[D];return R?R.action?`${R.message} ${R.action}`:R.message:""})(S):null,k=v.useCallback(async()=>{Y.getLogger().debug("[CreditsButton] executePayment");const D=w&&t?cn(t):void 0;if(Mn("credits",y,D),c&&c("credits"),!r){const O="Authentication required: please log in to pay with credits";Y.getLogger().error("[CreditsButton]",O),jt("credits",O,y,D),d&&d(O);return}if(!w&&!y){const O="Invalid payment configuration: missing resource";Y.getLogger().error("[CreditsButton]",O),jt("credits",O,y,D),d&&d(O);return}let R;ln("credits",y,D),w&&t?(Y.getLogger().debug("[CreditsButton] Processing cart checkout"),R=await h(t,r,o,s)):y&&(Y.getLogger().debug("[CreditsButton] Processing single payment"),R=await g(y,r,o,s)),R&&R.success&&R.transactionId?(Dn("credits",R.transactionId,y,D),l&&l(R.transactionId)):R&&!R.success&&R.error&&(jt("credits",R.error,y,D),d&&d(R.error))},[r,w,y,t,o,s,g,h,c,l,d]),P=v.useMemo(()=>w&&t?`credits-cart-${t.map(D=>D.resource).join("-")}`:`credits-${y||"unknown"}`,[w,t,y]),A=v.useMemo(()=>Rn(P,k),[P,k]),L=u==="loading",z=i||L;return n.jsxs("div",{className:I,style:b.unstyled?{}:b.style,children:[n.jsx("button",{onClick:A,disabled:z,className:b.unstyled?m:"cedros-theme__button cedros-theme__credits",type:"button",children:L?_("ui.processing"):C}),$&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__error",children:$}),f&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__success",children:_("ui.payment_successful")})]})}function Rl(){const{x402Manager:e,walletManager:t}=Y.useCedrosContext(),{publicKey:r,signTransaction:s}=ja.useWallet(),[o,a]=v.useState({status:"idle",error:null,transactionId:null}),[i,c]=v.useState(null),[l,d]=v.useState(null),m=v.useRef(!1),u=v.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=v.useCallback(async w=>{try{a(_=>({..._,status:"loading"}));const y=await e.requestQuote({resource:w});if(!e.validateRequirement(y))throw new Error("Invalid requirement received from server");return c(y),a(_=>({..._,status:"idle"})),y}catch(y){const _=Y.formatError(y,"Failed to fetch requirement");throw a({status:"error",error:_,transactionId:null}),y}},[e]),f=v.useCallback(async(w,y,_,j,C="regular")=>{if(!!w.extra?.feePayer){console.log("⚡ [useX402Payment] GASLESS FLOW - Backend pays fees"),console.log("🔨 [useX402Payment] Requesting backend to build gasless transaction");const{transaction:S,blockhash:N}=await e.buildGaslessTransaction({resourceId:y,userWallet:r.toString(),feePayer:w.extra.feePayer,couponCode:_});console.log("📦 [useX402Payment] Deserializing transaction from backend");const $=t.deserializeTransaction(S);console.log("✍️ [useX402Payment] Requesting wallet to partially sign (transfer authority only)");const k=await t.partiallySignTransaction({transaction:$,signTransaction:s,blockhash:N});console.log("📤 [useX402Payment] Submitting partially-signed transaction to backend");const P=await e.submitGaslessTransaction({resource:y,partialTx:k,couponCode:_,metadata:j,resourceType:C,requirement:w});return P.success&&P.settlement&&d(P.settlement),P}else{const S=await t.buildTransaction({requirement:w,payerPublicKey:r}),N=await t.signTransaction({transaction:S,signTransaction:s}),$=t.buildPaymentPayload({requirement:w,signedTx:N,payerPublicKey:r}),k=await e.submitPayment({resource:y,payload:$,couponCode:_,metadata:j,resourceType:C});return k.success&&k.settlement&&d(k.settlement),k}},[r,s,e,t]),g=v.useCallback(async(w,y,_)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const j=u();if(!j.valid)return{success:!1,error:j.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{console.log("🔍 [useX402Payment] Fetching fresh quote for resource:",w);const C=await e.requestQuote({resource:w,couponCode:y});console.log("✅ [useX402Payment] Got quote:",{payTo:C.payTo,amount:C.maxAmountRequired}),c(C),console.log("⚙️ [useX402Payment] Executing payment flow with fresh requirement");const I=await f(C,w,y,_,"regular");return I.success?a({status:"success",error:null,transactionId:I.transactionId||"payment-success"}):a({status:"error",error:I.error||"Payment failed",transactionId:null}),I}catch(C){const I=Y.formatError(C,"Payment failed");return a({status:"error",error:I,transactionId:null}),{success:!1,error:I}}finally{m.current=!1}},[u,e,f]),h=v.useCallback(async(w,y,_)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const j=u();if(!j.valid)return{success:!1,error:j.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{const C=ms(w),I=await e.requestCartQuote({items:C,metadata:y,couponCode:_}),S=I.cartId,N=I.quote;if(!e.validateRequirement(N))throw new Error("Invalid cart quote received from server");c(N);const $=await f(N,S,_,y,"cart");return $.success?a({status:"success",error:null,transactionId:$.transactionId||"cart-payment-success"}):a({status:"error",error:$.error||"Cart payment failed",transactionId:null}),$}catch(C){const I=Y.formatError(C,"Cart payment failed");return a({status:"error",error:I,transactionId:null}),{success:!1,error:I}}finally{m.current=!1}},[u,e,f]),b=v.useCallback(()=>{a({status:"idle",error:null,transactionId:null}),c(null),d(null),m.current=!1},[]);return{...o,requirement:i,settlement:l,fetchQuote:p,processPayment:g,processCartPayment:h,reset:b}}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:f,connect:g,disconnect:h,select:b,wallets:w,wallet:y,publicKey:_}=ja.useWallet(),{status:j,error:C,transactionId:I,processPayment:S,processCartPayment:N}=Rl(),$=Y.useCedrosTheme(),{solanaError:k}=Y.useCedrosContext(),{isCartMode:P,effectiveResource:A}=nr(e,t),{t:L,translations:z}=hn(),D=r||L("ui.pay_with_crypto"),R=C&&typeof C!="string"?C?.code??null:null,O=k&&typeof k!="string"?k?.code??null:null,T=ee=>{if(!ee||!z)return"";const je=z.errors[ee];return je?je.action?`${je.message} ${je.action}`:je.message:""},W=C?typeof C=="string"?C:T(R):null,E=k?typeof k=="string"?k:T(O):null,q=v.useRef(S),ne=v.useRef(N);v.useEffect(()=>{q.current=S,ne.current=N},[S,N]);const U=v.useMemo(()=>w.map(ee=>`${ee.adapter.name}-${ee.readyState}`).join(","),[w]),K=v.useMemo(()=>w.filter(({readyState:ee})=>ee===Hi.WalletReadyState.Installed||ee===Hi.WalletReadyState.Loadable),[U]);v.useEffect(()=>{if(j==="success"&&I){const ee=P&&t?cn(t):void 0;Dn("crypto",I,A,ee),a&&a(I)}},[j,I,a,P,t,A]),v.useEffect(()=>{if(j==="error"&&C){const ee=P&&t?cn(t):void 0;jt("crypto",C,A,ee),i&&i(C)}},[j,C,i,P,t,A]);const J=typeof window<"u"&&window.top!==window.self,[he,B]=v.useState(!1),[X,me]=v.useState(!1),[V,re]=v.useState(null),le=k;v.useEffect(()=>{let ee=!1;return ee||(async()=>{if(X&&y&&!p&&!f){Y.getLogger().debug("[CryptoButton] Wallet detected, attempting auto-connect:",y.adapter.name),me(!1),Ko(y.adapter.name);try{await g(),ee||Y.getLogger().debug("[CryptoButton] Auto-connect successful")}catch(Oe){if(!ee){Y.getLogger().error("[CryptoButton] Auto-connect failed:",Oe);const F=Oe instanceof Error?Oe.message:"Failed to connect wallet";as(F,y.adapter.name),re(null)}}}})(),()=>{ee=!0}},[y,X,p,f,g]),v.useEffect(()=>{if(Y.getLogger().debug("[CryptoButton] Payment useEffect triggered",{connected:p,hasPendingPayment:!!V,hasPublicKey:!!_,pendingPaymentType:V?.type}),p&&V&&_&&y){Sl(y.adapter.name,_.toString()),Y.getLogger().debug("[CryptoButton] All conditions met! Processing pending payment:",V);const ee=V;re(null),B(!1);const je=ee.type==="cart"&&ee.items?cn(ee.items):void 0;ln("crypto",ee.resource,je),ee.type==="cart"&&ee.items?(Y.getLogger().debug("[CryptoButton] Auto-processing cart payment"),ne.current(ee.items,ee.metadata,ee.couponCode)):ee.type==="single"&&ee.resource&&(Y.getLogger().debug("[CryptoButton] Auto-processing single payment"),q.current(ee.resource,ee.couponCode,ee.metadata))}},[p,V,_,y]);const pe=v.useCallback(async()=>{Y.getLogger().debug("[CryptoButton] executePaymentFlow called",{connected:p,wallet:y?.adapter.name,couponCode:u,isCartMode:P,hasItems:!!t,effectiveResource:A});const ee=P&&t?cn(t):void 0;if(Mn("crypto",A,ee),o&&o("crypto"),le){Y.getLogger().error("[CryptoButton] Solana dependencies missing:",le),jt("crypto",le,A,ee),i&&i(le);return}if(J){const je=l||window.location.href;try{if(new URL(je,window.location.origin).origin!==window.location.origin)throw Y.getLogger().error("[CryptoButton] Blocked attempt to open external URL:",je),new Error("Cannot open external URLs from embedded context");window.open(je,"_blank","noopener,noreferrer")}catch(Oe){throw Y.getLogger().error("[CryptoButton] URL validation failed:",Oe),Oe}return}if(p)ln("crypto",A,ee),P&&t?(Y.getLogger().debug("[CryptoButton] Processing cart payment with coupon:",u),await N(t,m,u)):A&&(Y.getLogger().debug("[CryptoButton] Processing single payment with coupon:",u),await S(A,u,m));else{let je=!1;if(P&&t?(Y.getLogger().debug("[CryptoButton] Setting pending cart payment with coupon:",u),re({type:"cart",items:t,metadata:m,couponCode:u}),je=!0):A&&(Y.getLogger().debug("[CryptoButton] Setting pending single payment with coupon:",u),re({type:"single",resource:A,metadata:m,couponCode:u}),je=!0),!je){Y.getLogger().error("[CryptoButton] No valid payment to process");return}try{if(y)Y.getLogger().debug("[CryptoButton] Wallet already selected, connecting:",y.adapter.name),Ko(y.adapter.name),await g();else{if(Y.getLogger().debug("[CryptoButton] No wallet selected, showing selector. Available wallets:",K.map(Oe=>Oe.adapter.name)),K.length===0){re(null);const Oe="No wallets available";throw as(Oe),new Error(Oe)}B(!0)}}catch(Oe){re(null);const F=Oe instanceof Error?Oe.message:"Failed to connect wallet";Y.getLogger().error("[CryptoButton] Connection error:",F),as(F,y?.adapter.name)}}},[p,y,u,P,t,A,J,l,K,g,m,N,S,le,o,i]),Re=v.useMemo(()=>P&&t?`crypto-cart-${t.map(ee=>ee.resource).join("-")}`:`crypto-${A||"unknown"}`,[P,t,A]),He=v.useMemo(()=>Rn(Re,pe,{cooldownMs:200,deduplicationWindowMs:0}),[Re,pe]),Ze=j==="loading",Ge=s||Ze||f||!!le,Qe=Ze?L("ui.processing"):D,Pe=v.useCallback(async()=>{try{me(!1),p&&await h(),b(null),B(!0)}catch(ee){Y.getLogger().error("Failed to change wallet:",ee)}},[p,h,b]),rt=v.useCallback(ee=>{Y.getLogger().debug("[CryptoButton] Wallet clicked:",ee),B(!1),b(ee),me(!0),Y.getLogger().debug("[CryptoButton] Wallet selected, useEffect will auto-connect")},[b]),Ce=v.useCallback(async()=>{try{if(await h(),re(null),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(ee){ee instanceof Error&&ee.name==="QuotaExceededError"?Y.getLogger().warn("localStorage quota exceeded when removing wallet preference"):Y.getLogger().error("Failed to clear wallet preference from localStorage:",ee)}}catch(ee){Y.getLogger().error("Failed to disconnect wallet:",ee)}},[h]);return n.jsxs("div",{className:$.unstyled?c:`${$.className} cedros-theme__crypto-button ${c||""}`,style:$.unstyled?{}:$.style,children:[n.jsx("button",{onClick:He,disabled:Ge,className:$.unstyled?c:"cedros-theme__button cedros-theme__crypto",type:"button",children:Qe}),he&&!d&&n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:$.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>B(!1),children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:$.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 ${$.tokens.modalBorder}`},onClick:ee=>ee.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:$.tokens.surfaceText},children:L("wallet.select_wallet")}),n.jsx("button",{onClick:()=>B(!1),style:Ca($.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:K.map(ee=>n.jsxs("button",{onClick:()=>rt(ee.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:$.tokens.surfaceBackground,border:`1px solid ${$.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:$.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:je=>{je.currentTarget.style.backgroundColor=$.tokens.modalBackground,je.currentTarget.style.borderColor=$.tokens.surfaceText,je.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:je=>{je.currentTarget.style.backgroundColor=$.tokens.surfaceBackground,je.currentTarget.style.borderColor=$.tokens.surfaceBorder,je.currentTarget.style.transform="translateY(0)"},type:"button",children:[n.jsx(sf.WalletIcon,{wallet:ee,style:{width:"24px",height:"24px"}}),n.jsx("span",{style:{fontWeight:500},children:ee.adapter.name})]},ee.adapter.name))})]})}),p&&!d&&!he&&n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:$.tokens.surfaceText,opacity:.7},children:[n.jsx("button",{onClick:Pe,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:"Change Wallet"}),n.jsx("button",{onClick:Ce,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:L("ui.disconnect")})]}),!d&&E&&n.jsx("div",{className:$.unstyled?"":"cedros-theme__error",children:E}),!d&&W&&n.jsx("div",{className:$.unstyled?"":"cedros-theme__error",children:W}),!d&&I&&n.jsx("div",{className:$.unstyled?"":"cedros-theme__success",children:L("ui.payment_successful")})]})}const Tf=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:f,onCryptoSuccess:g,onCreditsSuccess:h,onStripeError:b,onCryptoError:w,onCreditsError:y,customerEmail:_,successUrl:j,cancelUrl:C,metadata:I,couponCode:S,authToken:N,testPageUrl:$,hideMessages:k=!1})=>{const{tokens:P}=Y.useCedrosTheme();return v.useEffect(()=>{const A=L=>{L.key==="Escape"&&e&&t()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[e,t]),v.useEffect(()=>{if(e){const A=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${A}px`,document.body.style.width="100%",document.body.style.overflowY="scroll",()=>{const L=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,L)}}},[e]),e?n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:P.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:t,children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:P.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 ${P.modalBorder}`},onClick:A=>A.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:P.surfaceText},children:"Choose Payment Method"}),n.jsx("button",{onClick:t,style:Ca(P.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:f||u,onError:b||p,customerEmail:_,successUrl:j,cancelUrl:C,metadata:I,couponCode:S}),l&&n.jsx(Aa,{resource:r,items:s,label:a,onAttempt:m,onSuccess:g||u,onError:w||p,testPageUrl:$,hideMessages:k,metadata:I,couponCode:S}),d&&n.jsx(Pa,{resource:r,items:s,label:i,authToken:N,onAttempt:m?()=>m("credits"):void 0,onSuccess:h||u,onError:y||p,metadata:I,couponCode:S})]})]})}):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:f,onCreditsSuccess:g,onStripeError:h,onCryptoError:b,onCreditsError:w,customerEmail:y,successUrl:_,cancelUrl:j,metadata:C,couponCode:I,authToken:S,autoDetectWallets:N=!0,testPageUrl:$,hideMessages:k=!1,renderModal:P})=>{const A=Y.useCedrosTheme(),[L,z]=v.useState(!1),{status:D,processPayment:R,processCartCheckout:O}=Is(),{isCartMode:T,effectiveResource:W}=nr(e,t),{t:E}=hn(),q=r||E("ui.purchase"),ne=s||E("ui.card"),U=o||E("ui.usdc_solana"),K=a||E("ui.pay_with_credits")||"Pay with Credits",J=v.useCallback(async()=>{if(N&&i){const{detectSolanaWallets:V}=await Promise.resolve().then(()=>$C);if(!V()){const re=T?void 0:W,le=T&&t?cn(t):void 0;Mn("stripe",re,le),d&&d("stripe"),ln("stripe",re,le);let pe;T&&t?pe=await O(t,_,j,C,y,I):W&&(pe=await R(W,_,j,C,y,I)),pe&&pe.success&&pe.transactionId?(Dn("stripe",pe.transactionId,re,le),p?p(pe.transactionId):m&&m(pe.transactionId)):pe&&!pe.success&&pe.error&&(jt("stripe",pe.error,re,le),h?h(pe.error):u&&u(pe.error));return}}z(!0)},[N,i,T,t,W,O,R,_,j,C,y,I,m,u,p,h,d]),he=v.useMemo(()=>T&&t?`purchase-cart-${t.map(V=>V.resource).join("-")}`:`purchase-${W||"unknown"}`,[T,t,W]),B=v.useMemo(()=>Rn(he,J),[he,J]),X=D==="loading",me={isOpen:L,onClose:()=>z(!1),resource:T?void 0:W,items:T?t:void 0,cardLabel:ne,cryptoLabel:U,creditsLabel:K,showCard:i,showCrypto:c,showCredits:l,onPaymentAttempt:d,onPaymentSuccess:V=>{z(!1),m?.(V)},onPaymentError:V=>{z(!1),u?.(V)},onStripeSuccess:V=>{z(!1),p?.(V)},onCryptoSuccess:V=>{z(!1),f?.(V)},onCreditsSuccess:V=>{z(!1),g?.(V)},onStripeError:V=>{z(!1),h?.(V)},onCryptoError:V=>{z(!1),b?.(V)},onCreditsError:V=>{z(!1),w?.(V)},customerEmail:y,successUrl:_,cancelUrl:j,metadata:C,couponCode:I,authToken:S,testPageUrl:$,hideMessages:k};return n.jsxs("div",{className:A.unstyled?"":A.className,style:A.unstyled?{}:A.style,children:[n.jsx("button",{onClick:B,disabled:X,className:A.unstyled?"":"cedros-theme__button cedros-theme__stripe",style:{width:"100%",cursor:X?"not-allowed":"pointer",opacity:X?.6:1},type:"button",children:X?E("ui.processing"):q}),P?P(me):n.jsx(Ol,{...me})]})},If={"mainnet-beta":"https://api.mainnet-beta.solana.com",devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com"};function Rf(){const[e,t]=v.useState(null);return v.useEffect(()=>{let r=!1;return import("@solana/wallet-adapter-react").then(s=>{r||t(s)}),()=>{r=!0}},[]),e}function Of({endpoint:e,wallets:t,children:r}){const s=Rf();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 Mf=v.lazy(()=>Promise.resolve().then(()=>Tf).then(e=>({default:e.CryptoButton})));function Df(e){const{resource:t,items:r,checkout:s={},display:o={},callbacks:a={},advanced:i={}}=e,{config:c,walletPool:l}=Y.useCedrosContext(),d=Y.useCedrosTheme(),{isCartMode:m}=nr(t,r),u=o.showCrypto??!0,p=v.useMemo(()=>({marginTop:"0.5rem",fontSize:"0.875rem",color:d.tokens.surfaceText,opacity:.7,textAlign:"center"}),[d.tokens.surfaceText]),f=v.useMemo(()=>u?i.wallets&&i.wallets.length>0?i.wallets:l.getAdapters():[],[i.wallets,l,u]),g=v.useMemo(()=>r?cn(r):0,[r]),h=v.useMemo(()=>a.onPaymentSuccess?z=>a.onPaymentSuccess({transactionId:z,method:"stripe"}):void 0,[a.onPaymentSuccess]),b=v.useMemo(()=>a.onPaymentSuccess?z=>a.onPaymentSuccess({transactionId:z,method:"crypto"}):void 0,[a.onPaymentSuccess]),w=v.useMemo(()=>a.onPaymentError?z=>a.onPaymentError({message:z,method:"stripe"}):void 0,[a.onPaymentError]),y=v.useMemo(()=>a.onPaymentError?z=>a.onPaymentError({message:z,method:"crypto"}):void 0,[a.onPaymentError]),_=v.useMemo(()=>a.onPaymentSuccess?z=>a.onPaymentSuccess({transactionId:z,method:"credits"}):void 0,[a.onPaymentSuccess]),j=v.useMemo(()=>a.onPaymentError?z=>a.onPaymentError({message:z,method:"credits"}):void 0,[a.onPaymentError]),C=v.useMemo(()=>a.onPaymentAttempt?()=>a.onPaymentAttempt("credits"):void 0,[a.onPaymentAttempt]),I=u?c.solanaEndpoint??If[c.solanaCluster]:"";if(!t&&(!r||r.length===0))return Y.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 S=o.showCard??!0,N=o.showCredits??!1,$=o.showPurchaseButton??!1,k=o.layout??"vertical",P=o.hideMessages??!1,A=i.autoDetectWallets??!0,L=n.jsx("div",{className:d.unstyled?o.className:`cedros-theme__pay ${o.className||""}`,children:n.jsxs("div",{className:d.unstyled?"":`cedros-theme__pay-content cedros-theme__pay-content--${k}`,children:[$?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:S,showCrypto:u,onPaymentAttempt:a.onPaymentAttempt,onPaymentSuccess:h,onPaymentError:w,onStripeSuccess:h,onCryptoSuccess:b,onStripeError:w,onCryptoError:y,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,autoDetectWallets:A,testPageUrl:i.testPageUrl,hideMessages:P,renderModal:o.renderModal}):n.jsxs(n.Fragment,{children:[S&&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:h,onError:w}),u&&n.jsx(v.Suspense,{fallback:null,children:n.jsx(Mf,{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:b,onError:y,testPageUrl:i.testPageUrl,hideMessages:P})}),N&&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:C,onSuccess:_,onError:j})]}),m&&r&&r.length>1&&!P&&n.jsxs("div",{style:p,children:["Checking out ",g," items"]})]})});return n.jsx("div",{className:d.unstyled?o.className:d.className,style:d.unstyled?{}:d.style,children:u?n.jsx(Of,{endpoint:I,wallets:f,children:L}):L})}const G={products:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),n.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),n.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),n.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),n.jsx("path",{d:"M3 3v5h5"}),n.jsx("path",{d:"M12 7v5l4 2"})]}),settings:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),n.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"}),n.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),n.jsx("path",{d:"M8 16H3v5"})]}),check:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})}),plus:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),n.jsx("path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9"}),n.jsx("path",{d:"M12 3v6"})]}),arrowUp:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7-7 7 7"}),n.jsx("path",{d:"M12 19V5"})]}),arrowDown:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7 7 7-7"}),n.jsx("path",{d:"M12 5v14"})]}),delete:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),n.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),faq:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),n.jsx("path",{d:"M12 17h.01"})]}),chat:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),n.jsx("path",{d:"M2 12h20"})]}),ai:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),n.jsx("path",{d:"M10 10v.5"}),n.jsx("path",{d:"M14 10v.5"}),n.jsx("path",{d:"M12 14v2"}),n.jsx("path",{d:"M8 18h8"}),n.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),n.jsx("path",{d:"M6 12v6"}),n.jsx("path",{d:"M18 12v6"})]}),notifications:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),n.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),n.jsx("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),n.jsx("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),n.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),n.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),n.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),n.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),n.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),n.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),n.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),n.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),n.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),n.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),n.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),n.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),n.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),n.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),n.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),n.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),n.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function 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?G.loading:G.refresh})]})}function Lf({serverUrl:e,productId:t,apiKey:r,authManager:s}){const[o,a]=v.useState(null),[i,c]=v.useState(!1),[l,d]=v.useState(!1),[m,u]=v.useState(null),p=v.useCallback(async()=>{if(t){c(!0),u(null);try{let h;if(s?.isAuthenticated())h=await s.fetchWithAuth(`/admin/products/${t}/variations`);else{const b={"Content-Type":"application/json"};r&&(b["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variations`,{headers:b});if(!w.ok)throw new Error(`Failed to fetch variations: ${w.status}`);h=await w.json()}h.variationConfig||(h.variationConfig={variationTypes:[]}),h.variants||(h.variants=[]),a(h)}catch(h){const b=h instanceof Error?h.message:"Failed to fetch variations";u(b),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,r,s]),f=v.useCallback(async h=>{if(!t)return null;d(!0),u(null);try{let b;if(s?.isAuthenticated())b=await s.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(h)});else{const w={"Content-Type":"application/json"};r&&(w["X-API-Key"]=r);const y=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:w,body:JSON.stringify(h)});if(!y.ok)throw new Error(`Failed to save variations: ${y.status}`);b=await y.json()}return a({productId:t,variationConfig:b.variationConfig,variants:b.variants}),{variantsCreated:b.variantsCreated}}catch(b){const w=b instanceof Error?b.message:"Failed to save variations";return u(w),null}finally{d(!1)}},[e,t,r,s]),g=v.useCallback(async h=>{if(!t||h.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:h})});else{const b={"Content-Type":"application/json"};r&&(b["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:b,body:JSON.stringify({updates:h})});if(!w.ok)throw new Error(`Failed to update inventory: ${w.status}`)}if(o){const b=new Map(h.map(w=>[w.variantId,w]));a({...o,variants:o.variants.map(w=>{const y=b.get(w.id);return y?{...w,inventoryQuantity:y.inventoryQuantity,inventoryStatus:y.inventoryStatus??w.inventoryStatus}:w})})}return!0}catch(b){const w=b instanceof Error?b.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:f,bulkUpdateInventory:g,isSaving:l}}function Qi(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function $f({value:e,onChange:t,maxTypes:r=5,maxValuesPerType:s=20,disabled:o=!1}){const[a,i]=v.useState(null),[c,l]=v.useState(""),[d,m]=v.useState({}),u=e.variationTypes,p=v.useCallback(()=>{if(!c.trim()||u.length>=r)return;const _={id:Qi(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,_]}),l(""),i(_.id)},[c,u,r,t]),f=v.useCallback(_=>{t({variationTypes:u.filter(j=>j.id!==_).map((j,C)=>({...j,displayOrder:C}))}),a===_&&i(null)},[u,t,a]),g=v.useCallback((_,j)=>{t({variationTypes:u.map(C=>C.id===_?{...C,name:j}:C)})},[u,t]),h=v.useCallback((_,j)=>{const C=u.findIndex(N=>N.id===_);if(C===-1||j==="up"&&C===0||j==="down"&&C===u.length-1)return;const I=[...u],S=j==="up"?C-1:C+1;[I[C],I[S]]=[I[S],I[C]],t({variationTypes:I.map((N,$)=>({...N,displayOrder:$}))})},[u,t]),b=v.useCallback(_=>{const j=(d[_]||"").trim();if(!j)return;const C=u.find(S=>S.id===_);if(!C||C.values.length>=s)return;const I={id:Qi(),label:j};t({variationTypes:u.map(S=>S.id===_?{...S,values:[...S.values,I]}:S)}),m(S=>({...S,[_]:""}))},[u,d,s,t]),w=v.useCallback((_,j)=>{t({variationTypes:u.map(C=>C.id===_?{...C,values:C.values.filter(I=>I.id!==j)}:C)})},[u,t]),y=v.useCallback((_,j,C)=>{t({variationTypes:u.map(I=>I.id===_?{...I,values:I.values.map(S=>S.id===j?{...S,label:C}:S)}:I)})},[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((_,j)=>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:()=>h(_.id,"up"),disabled:o||j===0,title:"Move up",children:G.arrowUp}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>h(_.id,"down"),disabled:o||j===u.length-1,title:"Move down",children:G.arrowDown})]}),n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:_.name,onChange:C=>g(_.id,C.target.value),disabled:o,placeholder:"Type name"}),n.jsxs("span",{className:"cedros-admin__variation-value-count",children:[_.values.length," values"]}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===_.id?null:_.id),children:a===_.id?"Collapse":"Edit values"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>f(_.id),disabled:o,title:"Remove type",children:G.delete})]}),a===_.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 "',_.name,'"']}),n.jsxs("span",{style:{fontSize:11,opacity:.7},children:[_.values.length,"/",s]})]}),_.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:_.values.map(C=>n.jsxs("div",{className:"cedros-admin__variation-value-item",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:C.label,onChange:I=>y(_.id,C.id,I.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(_.id,C.id),disabled:o,title:"Remove value",children:G.close})]},C.id))}),_.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[_.id]||"",onChange:C=>m(I=>({...I,[_.id]:C.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),b(_.id))}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>b(_.id),disabled:o||!d[_.id]?.trim(),children:"Add"})]})]})]},_.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:_=>l(_.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:_=>{_.key==="Enter"&&(_.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]=v.useState(!1),c=v.useRef(null),d=r.find(m=>m.value===e)?.label||s;return v.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]),v.useEffect(()=>{const m=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[a]),n.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[n.jsx("span",{children:d}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:G.chevronDown})]}),a&&n.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:r.map(m=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${m.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{m.disabled||(t(m.value),i(!1))},role:"option","aria-selected":m.value===e,disabled:m.disabled,children:[m.label,m.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:G.check})]},m.value))})]})}function ct({value:e,onChange:t,options:r,label:s,description:o,disabled:a,className:i,style:c}){const[l,d]=v.useState(!1),m=v.useRef(null),p=r.find(f=>f.value===e)?.label||"Select...";return v.useEffect(()=>{const f=g=>{m.current&&!m.current.contains(g.target)&&d(!1)};if(l)return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[l]),v.useEffect(()=>{const f=g=>{g.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[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:G.chevronDown})]}),l&&n.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:r.map(f=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${f.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{f.disabled||(t(f.value),d(!1))},role:"option","aria-selected":f.value===e,disabled:f.disabled,children:[f.label,f.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:G.check})]},f.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 zf(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 Ff(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 Bf({variationConfig:e,variants:t,onChange:r,defaultPrice:s=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=v.useMemo(()=>zf(e.variationTypes),[e.variationTypes]),l=v.useMemo(()=>{const h=new Map;for(const b of t)h.set(Ff(b),b);return h},[t]),{existingRows:d,possibleRows:m}=v.useMemo(()=>{const h=[],b=[];for(const w of c){const y=l.get(w.key);y?h.push({combo:w,variant:y}):b.push(w)}return{existingRows:h,possibleRows:b}},[c,l]),u=v.useCallback((h,b)=>{r(t.map(w=>w.id===h?{...w,...b}:w))},[t,r]),p=v.useCallback(h=>{r(t.filter(b=>b.id!==h))},[t,r]),f=v.useCallback(h=>{if(t.length>=a)return;const b={id:Yi(),title:h.title,options:h.options,optionValueIds:h.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};r([...t,b])},[t,r,a,s]),g=v.useCallback(()=>{const h=a-t.length,w=m.slice(0,h).map(y=>({id:Yi(),title:y.title,options:y.options,optionValueIds:y.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:g,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:h,variant:b})=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:h.title}),n.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(h.options).map(([w,y])=>`${w}: ${y}`).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:b.price??"",onChange:w=>u(b.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:b.inventoryQuantity??"",onChange:w=>u(b.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:b.sku??"",onChange:w=>u(b.id,{sku:w.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),n.jsx("td",{children:n.jsx(Dl,{value:b.inventoryStatus??"in_stock",onChange:w=>u(b.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(b.id),disabled:i,title:"Remove variant",children:G.trash})})]},b.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(h=>n.jsxs("tr",{className:"cedros-admin__variant-possible",children:[n.jsx("td",{children:n.jsx("span",{style:{opacity:.6},children:h.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:()=>f(h),disabled:i,title:"Create variant",children:G.plus})})]},h.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 Uf({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:f}=Lf({serverUrl:e,productId:t,apiKey:a,authManager:i}),[g,h]=v.useState({variationTypes:[]}),[b,w]=v.useState([]),[y,_]=v.useState(!1),[j,C]=v.useState(!1);v.useEffect(()=>{u()},[u]),v.useEffect(()=>{l&&(h(l.variationConfig),w(l.variants),_(!1))},[l]);const I=v.useCallback($=>{h($),_(!0),C(!1)},[]),S=v.useCallback($=>{w($),_(!0),C(!1)},[]),N=v.useCallback(async()=>{const $=new Set((l?.variants??[]).map(z=>z.id)),k=b.filter(z=>!$.has(z.id)),P=b.filter(z=>$.has(z.id)),A=(l?.variants??[]).filter(z=>!b.some(D=>D.id===z.id)).map(z=>z.id);await p({variationConfig:g,createVariants:k.map(z=>({optionValueIds:z.optionValueIds??[],inventoryQuantity:z.inventoryQuantity,sku:z.sku,price:z.price})),updateVariants:P.map(z=>({id:z.id,inventoryQuantity:z.inventoryQuantity,sku:z.sku,price:z.price,inventoryStatus:z.inventoryStatus})),deleteVariantIds:A.length>0?A:void 0})&&(_(!1),C(!0),setTimeout(()=>C(!1),3e3))},[g,b,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:G.close})]}),n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading variations..."]})]}):n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),n.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[j&&n.jsxs("span",{className:"cedros-admin__success-text",children:[G.check," Saved"]}),y&&n.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:N,disabled:f||!y,children:f?"Saving...":"Save Changes"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:G.close})]})]}),m&&n.jsx("div",{className:"cedros-admin__error-banner",children:m}),n.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx($f,{value:g,onChange:I,disabled:f})}),g.variationTypes.length>0&&n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(Bf,{variationConfig:g,variants:b,onChange:S,defaultPrice:s,currencySymbol:o,disabled:f})})]})]})}function Ll({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=v.useState([]),[i,c]=v.useState(!0),[l,d]=v.useState(!1),[m,u]=v.useState(!1),[p,f]=v.useState(null),[g,h]=v.useState(null),[b,w]=v.useState(null),[y,_]=v.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:""}),j=D=>{const R=D.tagsCsv.split(",").map(U=>U.trim()).filter(Boolean),O=D.categoryIdsCsv.split(",").map(U=>U.trim()).filter(Boolean),T={email:D.checkoutEmail,name:D.checkoutName,phone:D.checkoutPhone,shippingAddress:D.checkoutShippingAddress,billingAddress:D.checkoutBillingAddress},W=D.fulfillmentType==="shipping"?"physical":"digital",E={title:D.title,slug:D.slug||D.id,shipping_profile:W,inventory_status:D.inventoryStatus,checkout_requirements:JSON.stringify(T),fulfillment_type:D.fulfillmentType};D.imageUrl&&(E.image_url=D.imageUrl);const q=D.compareAtUsd?Math.round(Number(D.compareAtUsd)*100):0;q&&(E.compare_at_amount_cents=String(q)),R.length&&(E.tags=JSON.stringify(R)),O.length&&(E.category_ids=JSON.stringify(O)),D.fulfillmentNotes&&(E.fulfillment_notes=D.fulfillmentNotes);const ne=D.shippingCountriesCsv.split(",").map(U=>U.trim().toUpperCase()).filter(Boolean);return ne.length&&(E.shippingCountries=ne.join(","),E.shipping_countries=ne.join(",")),E},C=D=>D.metadata?.title||D.description||D.id,I=D=>D.metadata?.image_url,S=v.useCallback(async()=>{try{let D;if(s?.isAuthenticated())D=await s.fetchWithAuth(`/admin/products?limit=${r}`);else{const R={"Content-Type":"application/json"};t&&(R["X-API-Key"]=t);const O=await fetch(`${e}/admin/products?limit=${r}`,{headers:R});if(!O.ok)throw new Error(`Failed to fetch products: ${O.status}`);D=await O.json()}a(D.products||[])}catch{a([{id:"premium-article",description:"Premium Article Access",fiatAmountCents:500,fiatCurrency:"usd",cryptoAtomicAmount:5e6,cryptoToken:"USDC",active:!0},{id:"video-course",description:"Video Course Bundle",fiatAmountCents:2999,fiatCurrency:"usd",cryptoAtomicAmount:2999e4,cryptoToken:"USDC",active:!0},{id:"api-credits",description:"API Credits Pack",fiatAmountCents:1e3,fiatCurrency:"usd",cryptoAtomicAmount:1e7,cryptoToken:"USDC",active:!0}])}finally{c(!1)}},[e,t,r,s]);v.useEffect(()=>{S()},[S]);const N=async D=>{if(D.preventDefault(),!(!y.id||!y.description)){if(f(null),y.fulfillmentType==="shipping"&&y.checkoutShippingAddress&&!y.shippingCountriesCsv.split(",").map(O=>O.trim()).filter(Boolean).length){f("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:R}=y,O=y.inventoryQuantity===""?void 0:Number.isFinite(Number(y.inventoryQuantity))?Number(y.inventoryQuantity):void 0,T=Number(y.priceUsd)||0,W=Math.round(T*100),E=Math.round(T*1e6),q={id:y.id,description:y.description,fiatAmountCents:W,fiatCurrency:y.fiatCurrency,cryptoAtomicAmount:E,cryptoToken:y.cryptoToken,...O!==void 0?{inventoryQuantity:O}:{},metadata:{...R?{product_type:R}:{},...j(y)}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(q)});else{const ne={"Content-Type":"application/json"};t&&(ne["X-API-Key"]=t);const U=await fetch(`${e}/admin/products`,{method:"POST",headers:ne,body:JSON.stringify(q)});if(!U.ok)throw new Error(`Failed to create product: ${U.status}`)}_({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),d(!1),S()}catch{const O=Number(y.priceUsd)||0;a(T=>[...T,{id:y.id,title:y.title||void 0,slug:y.slug||void 0,imageUrl:y.imageUrl||void 0,description:y.description,fiatAmountCents:Math.round(O*100),fiatCurrency:y.fiatCurrency,cryptoAtomicAmount:Math.round(O*1e6),cryptoToken:y.cryptoToken,inventoryQuantity:y.inventoryQuantity===""?void 0:Number.isFinite(Number(y.inventoryQuantity))?Number(y.inventoryQuantity):void 0,active:!0,metadata:{...y.productType?{product_type:y.productType}:{},...j(y)}}]),_({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),d(!1)}finally{u(!1)}}},$=D=>`$${(D/100).toFixed(2)}`,k=D=>{switch(D){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},P=v.useMemo(()=>{const D=o.filter(O=>O.active).length,R=o.reduce((O,T)=>{const W=T.variations?.length??0;return O+(W>0?W:1)},0);return{activeCount:D,totalSkus:R}},[o]),A=D=>{w(R=>!R||R.key!==D?{key:D,direction:"asc"}:{key:D,direction:R.direction==="asc"?"desc":"asc"})},L=D=>!b||b.key!==D?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:G.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:b.direction==="asc"?G.chevronUp:G.chevronDown}),z=v.useMemo(()=>{if(!b)return o;const D=b.direction==="asc"?1:-1,R=O=>{switch(b.key){case"product":return C(O);case"type":return k(O.metadata?.product_type);case"price":return O.fiatAmountCents??0;case"status":return O.active?1:0;case"id":default:return O.id}};return[...o].sort((O,T)=>{const W=R(O),E=R(T);return typeof W=="number"&&typeof E=="number"?(W-E)*D:String(W).localeCompare(String(E),void 0,{sensitivity:"base"})*D})},[o,b]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(rr,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:P.activeCount,variant:P.activeCount>0?"success":"muted"},{label:"Total SKUs",value:P.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:()=>{f(null),d(!l)},children:[l?G.close:G.plus,l?"Cancel":"Add Product"]})]}),l&&n.jsxs("form",{onSubmit:N,className:"cedros-admin__add-form",children:[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:y.id,onChange:D=>_(R=>({...R,id:D.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:y.title,onChange:D=>_(R=>({...R,title:D.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:y.slug,onChange:D=>_(R=>({...R,slug:D.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:y.imageUrl,onChange:D=>_(R=>({...R,imageUrl:D.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:y.description,onChange:D=>_(R=>({...R,description:D.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ct,{value:y.productType,onChange:D=>_(R=>({...R,productType:D})),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(ct,{value:y.fulfillmentType,onChange:D=>{const R=D;_(O=>({...O,fulfillmentType:R,checkoutShippingAddress:R==="shipping"?O.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),y.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ct,{value:y.inventoryStatus,onChange:D=>_(R=>({...R,inventoryStatus:D})),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:y.inventoryQuantity,onChange:D=>_(R=>({...R,inventoryQuantity:D.target.value===""?"":parseInt(D.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:y.compareAtUsd===""?"":y.compareAtUsd,onChange:D=>_(R=>({...R,compareAtUsd:D.target.value===""?"":parseFloat(D.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:y.priceUsd===""?"":y.priceUsd,onChange:D=>_(R=>({...R,priceUsd:D.target.value===""?"":parseFloat(D.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:y.tagsCsv,onChange:D=>_(R=>({...R,tagsCsv:D.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:y.categoryIdsCsv,onChange:D=>_(R=>({...R,categoryIdsCsv:D.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ct,{value:y.checkoutEmail,onChange:D=>_(R=>({...R,checkoutEmail:D})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),n.jsx(ct,{value:y.checkoutName,onChange:D=>_(R=>({...R,checkoutName:D})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),n.jsx(ct,{value:y.checkoutPhone,onChange:D=>_(R=>({...R,checkoutPhone:D})),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:[y.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:y.checkoutShippingAddress,onChange:D=>_(R=>({...R,checkoutShippingAddress:D.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:y.checkoutBillingAddress,onChange:D=>_(R=>({...R,checkoutBillingAddress:D.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:y.fulfillmentNotes,onChange:D=>_(R=>({...R,fulfillmentNotes:D.target.value})),placeholder:y.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),y.fulfillmentType==="shipping"&&y.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:y.shippingCountriesCsv,onChange:D=>_(R=>({...R,shippingCountriesCsv:D.target.value})),placeholder:"e.g., US,CA"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Product"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading products..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":b?.key==="id"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>A("id"),children:["ID",L("id")]})}),n.jsx("th",{"aria-sort":b?.key==="product"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>A("product"),children:["Product",L("product")]})}),n.jsx("th",{"aria-sort":b?.key==="type"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>A("type"),children:["Type",L("type")]})}),n.jsx("th",{"aria-sort":b?.key==="price"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>A("price"),children:["Price",L("price")]})}),n.jsx("th",{"aria-sort":b?.key==="status"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>A("status"),children:["Status",L("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:z.map(D=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:D.id})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[I(D)?n.jsx("img",{src:I(D),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):n.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:C(D)}),n.jsx("span",{style:{opacity:.8},children:D.description})]})]})}),n.jsx("td",{children:k(D.metadata?.product_type)}),n.jsx("td",{children:$(D.fiatAmountCents)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${D.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:D.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:()=>h(D),children:"Variations"})]})})]},D.id))})]})}),g&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>h(null),children:n.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:D=>D.stopPropagation(),children:n.jsx(Uf,{serverUrl:e,productId:g.id,productTitle:C(g),defaultPrice:g.fiatAmountCents/100,apiKey:t,authManager:s,onClose:()=>h(null)})})})]})}function $l({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=v.useState([]),[i,c]=v.useState(null),[l,d]=v.useState(!0),[m,u]=v.useState(!0),[p,f]=v.useState(""),[g,h]=v.useState(null),b=v.useCallback(async()=>{u(!0);try{let C;if(s?.isAuthenticated())C=await s.fetchWithAuth("/admin/stats");else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const S=await fetch(`${e}/admin/stats`,{headers:I});if(!S.ok)throw new Error(`Failed to fetch stats: ${S.status}`);C=await S.json()}c(C)}catch{c({totalRevenue:12450,totalTransactions:342,activeProducts:8,pendingRefunds:3,revenueByMethod:{stripe:8200,x402:3150,credits:1100},transactionsByMethod:{stripe:210,x402:98,credits:34}})}finally{u(!1)}},[e,t,s]);v.useEffect(()=>{b()},[b]),v.useEffect(()=>{(async()=>{try{let I;const S=new URLSearchParams({limit:r.toString()});p&&S.set("method",p);const N=`/admin/transactions?${S}`;if(s?.isAuthenticated())I=await s.fetchWithAuth(N);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const k=await fetch(`${e}${N}`,{headers:$});if(!k.ok)throw new Error(`Failed to fetch transactions: ${k.status}`);I=await k.json()}a(I.transactions||[])}catch{a([{id:"txn_1",resourceId:"premium-article",method:"stripe",amount:5,currency:"usd",status:"completed",paidAt:new Date().toISOString()},{id:"txn_2",resourceId:"video-course",method:"x402",amount:29.99,currency:"usdc",status:"completed",paidAt:new Date(Date.now()-36e5).toISOString()},{id:"txn_3",resourceId:"api-credits",method:"credits",amount:10,currency:"credits",status:"completed",paidAt:new Date(Date.now()-72e5).toISOString()}])}finally{d(!1)}})()},[e,t,r,p,s]);const w=C=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(C),y=C=>{h(I=>!I||I.key!==C?{key:C,direction:"asc"}:{key:C,direction:I.direction==="asc"?"desc":"asc"})},_=C=>!g||g.key!==C?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:G.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:g.direction==="asc"?G.chevronUp:G.chevronDown}),j=v.useMemo(()=>{if(!g)return o;const C=g.direction==="asc"?1:-1,I=S=>{switch(g.key){case"resource":return S.resourceId;case"method":return S.method;case"amount":return S.amount;case"status":return S.status;case"date":return new Date(S.paidAt).getTime();case"id":default:return S.id}};return[...o].sort((S,N)=>{const $=I(S),k=I(N);return typeof $=="number"&&typeof k=="number"?($-k)*C:String($).localeCompare(String(k),void 0,{sensitivity:"base"})*C})},[o,g]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(rr,{stats:[{label:"Revenue",value:w(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:w(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:w(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:w(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:m,onRefresh:b}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),n.jsx(Dl,{value:p,onChange:f,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading transactions..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":g?.key==="id"?g?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>y("id"),children:["ID",_("id")]})}),n.jsx("th",{"aria-sort":g?.key==="resource"?g?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>y("resource"),children:["Resource",_("resource")]})}),n.jsx("th",{"aria-sort":g?.key==="method"?g?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>y("method"),children:["Method",_("method")]})}),n.jsx("th",{"aria-sort":g?.key==="amount"?g?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>y("amount"),children:["Amount",_("amount")]})}),n.jsx("th",{"aria-sort":g?.key==="status"?g?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>y("status"),children:["Status",_("status")]})}),n.jsx("th",{"aria-sort":g?.key==="date"?g?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>y("date"),children:["Date",_("date")]})})]})}),n.jsx("tbody",{children:j.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:jr(C.paidAt)})]},C.id))})]})})]})}function zl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=v.useState([]),[i,c]=v.useState(!0),[l,d]=v.useState(!1),[m,u]=v.useState(!1),[p,f]=v.useState(null),[g,h]=v.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}),b=v.useCallback(async()=>{try{let S;const N=`/admin/coupons?limit=${r}`;if(s?.isAuthenticated())S=await s.fetchWithAuth(N);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const k=await fetch(`${e}${N}`,{headers:$});if(!k.ok)throw new Error(`Failed to fetch coupons: ${k.status}`);S=await k.json()}a(S.coupons||[])}catch(S){Y.getLogger().error("[CouponsSection] Failed to fetch coupons:",S,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([{code:"SAVE20",discountType:"percentage",discountValue:20,active:!0,usageLimit:100,usageCount:42},{code:"LAUNCH10",discountType:"fixed",discountValue:10,currency:"usd",active:!0,usageCount:15},{code:"EXPIRED50",discountType:"percentage",discountValue:50,active:!1,usageCount:100,expiresAt:"2024-12-31"}])}finally{c(!1)}},[e,t,r,s]);v.useEffect(()=>{b()},[b]);const w=async S=>{if(S.preventDefault(),!(!g.code||g.discountValue<=0)){u(!0);try{const N=g.minimumAmountUsd?Math.round(Number(g.minimumAmountUsd)*100):void 0,$=g.productIdsCsv.split(",").map(A=>A.trim()).filter(Boolean),k=g.categoryIdsCsv.split(",").map(A=>A.trim()).filter(Boolean),P={code:g.code,discountType:g.discountType,discountValue:g.discountValue,usageLimit:g.usageLimit,active:!0,usageCount:0,scope:g.scope,...$.length?{productIds:$}:{},...k.length?{categoryIds:k}:{},...g.paymentMethod!=="any"?{paymentMethod:g.paymentMethod}:{},...g.autoApply?{autoApply:!0}:{},...g.appliesAt!=="both"?{appliesAt:g.appliesAt}:{},...g.startsAt?{startsAt:g.startsAt}:{},...g.expiresAt?{expiresAt:g.expiresAt}:{},...N?{minimumAmountCents:N}:{},...g.usageLimitPerCustomer?{usageLimitPerCustomer:g.usageLimitPerCustomer}:{},...g.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(P)});else{const A={"Content-Type":"application/json"};t&&(A["X-API-Key"]=t);const L=await fetch(`${e}/admin/coupons`,{method:"POST",headers:A,body:JSON.stringify(P)});if(!L.ok)throw new Error(`Failed to create coupon: ${L.status}`)}h({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),b()}catch(N){Y.getLogger().error("[CouponsSection] Failed to add coupon:",N,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t});const $=g.minimumAmountUsd?Math.round(Number(g.minimumAmountUsd)*100):void 0,k=g.productIdsCsv.split(",").map(A=>A.trim()).filter(Boolean),P=g.categoryIdsCsv.split(",").map(A=>A.trim()).filter(Boolean);a(A=>[...A,{code:g.code,discountType:g.discountType,discountValue:g.discountValue,usageLimit:g.usageLimit,active:!0,usageCount:0,scope:g.scope,productIds:k.length?k:void 0,categoryIds:P.length?P:void 0,paymentMethod:g.paymentMethod!=="any"?g.paymentMethod:void 0,autoApply:g.autoApply||void 0,appliesAt:g.appliesAt!=="both"?g.appliesAt:void 0,startsAt:g.startsAt||void 0,expiresAt:g.expiresAt||void 0,minimumAmountCents:$,usageLimitPerCustomer:g.usageLimitPerCustomer,firstPurchaseOnly:g.firstPurchaseOnly||void 0}]),h({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),d(!1)}finally{u(!1)}}},y=o.filter(S=>S.active).length,_=o.reduce((S,N)=>S+(N.usageCount??0),0),j=S=>{f(N=>!N||N.key!==S?{key:S,direction:"asc"}:{key:S,direction:N.direction==="asc"?"desc":"asc"})},C=S=>!p||p.key!==S?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:G.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:p.direction==="asc"?G.chevronUp:G.chevronDown}),I=v.useMemo(()=>{if(!p)return o;const S=p.direction==="asc"?1:-1,N=$=>{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(($,k)=>{const P=N($),A=N(k);return typeof P=="number"&&typeof A=="number"?(P-A)*S:String(P).localeCompare(String(A),void 0,{sensitivity:"base"})*S})},[o,p]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(rr,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:y,variant:y>0?"success":"muted"},{label:"Redemptions",value:_}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?G.close:G.plus,l?"Cancel":"Add Coupon"]})]}),l&&n.jsxs("form",{onSubmit:w,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:g.code,onChange:S=>h(N=>({...N,code:S.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),n.jsx(ct,{value:g.discountType,onChange:S=>h(N=>({...N,discountType:S})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",g.discountType==="percentage"?"(%)":"($)"]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:g.discountValue||"",onChange:S=>h(N=>({...N,discountValue:parseFloat(S.target.value)||0})),placeholder:g.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:g.discountType==="percentage"?"1":"0.01",required:!0})]}),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:g.usageLimit||"",onChange:S=>h(N=>({...N,usageLimit:S.target.value?parseInt(S.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:g.expiresAt,onChange:S=>h(N=>({...N,expiresAt:S.target.value}))})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ct,{value:g.scope,onChange:S=>h(N=>({...N,scope:S})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),n.jsx(ct,{value:g.paymentMethod,onChange:S=>h(N=>({...N,paymentMethod:S})),options:[{value:"any",label:"Any Payment Method"},{value:"stripe",label:"Stripe (Card) Only"},{value:"x402",label:"Crypto (x402) Only"},{value:"credits",label:"Credits Only"}],label:"Payment Method"}),n.jsx(ct,{value:g.appliesAt,onChange:S=>h(N=>({...N,appliesAt:S})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),g.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:g.productIdsCsv,onChange:S=>h(N=>({...N,productIdsCsv:S.target.value})),placeholder:"e.g., prod_123, prod_456"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:g.startsAt,onChange:S=>h(N=>({...N,startsAt:S.target.value}))})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:g.autoApply,onChange:S=>h(N=>({...N,autoApply:S.target.checked}))}),"Automatically apply when conditions met"]})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:g.minimumAmountUsd===""?"":g.minimumAmountUsd,onChange:S=>h(N=>({...N,minimumAmountUsd:S.target.value===""?"":parseFloat(S.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:g.usageLimitPerCustomer||"",onChange:S=>h(N=>({...N,usageLimitPerCustomer:S.target.value?parseInt(S.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:g.firstPurchaseOnly,onChange:S=>h(N=>({...N,firstPurchaseOnly:S.target.checked}))}),"New customers only"]})]})]}),g.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:g.categoryIdsCsv,onChange:S=>h(N=>({...N,categoryIdsCsv:S.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Coupon"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading coupons..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":p?.key==="code"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("code"),children:["Code",C("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:()=>j("discount"),children:["Discount",C("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:()=>j("usage"),children:["Usage",C("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:()=>j("status"),children:["Status",C("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:I.map(S=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:S.code})}),n.jsx("td",{children:S.discountType==="percentage"?`${S.discountValue}%`:`$${S.discountValue.toFixed(2)}`}),n.jsxs("td",{children:[S.usageCount,S.usageLimit?` / ${S.usageLimit}`:""]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${S.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:S.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},S.code))})]})})]})}function Fl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=v.useState([]),[i,c]=v.useState(!0),[l,d]=v.useState(null),[m,u]=v.useState([]),[p,f]=v.useState(!0),[g,h]=v.useState(null),[b,w]=v.useState(null),[y,_]=v.useState([]),[j,C]=v.useState(!0),[I,S]=v.useState(null),[N,$]=v.useState(null),[k,P]=v.useState(null),[A,L]=v.useState("");v.useEffect(()=>{(async()=>{try{let te;const se=`/admin/refunds?limit=${r}`;if(s?.isAuthenticated())te=await s.fetchWithAuth(se);else{const ge={"Content-Type":"application/json"};t&&(ge["X-API-Key"]=t);const be=await fetch(`${e}${se}`,{headers:ge});if(!be.ok)throw new Error(`Failed to fetch x402 refunds: ${be.status}`);te=await be.json()}a(te.refunds||[])}catch(te){Y.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",te,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([{id:"ref_1",transactionId:"txn_42",amount:29.99,currency:"usd",status:"pending",reason:"Customer request",createdAt:new Date().toISOString()},{id:"ref_2",transactionId:"txn_38",amount:5,currency:"usd",status:"completed",createdAt:new Date(Date.now()-864e5).toISOString()}])}finally{c(!1)}})()},[e,t,r,s]);const z=v.useCallback(async()=>{try{let F;const te=`/admin/credits/refund-requests?status=pending&limit=${r}&offset=0`;if(s?.isAuthenticated())F=await s.fetchWithAuth(te);else{const ge={"Content-Type":"application/json"};t&&(ge["X-API-Key"]=t);const be=await fetch(`${e}${te}`,{headers:ge});if(!be.ok)throw new Error(`Failed to fetch credits refund requests: ${be.status}`);F=await be.json()}const se=Array.isArray(F)?F:"refundRequests"in F?F.refundRequests:F.requests||[];u(se)}catch(F){Y.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",F,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([{id:"crr_demo1",originalTransactionId:"ctx_demo1",userId:"user_demo1",amountLamports:25e5,currency:"USD",status:"pending",reason:"Requested by customer",createdAt:new Date().toISOString()}])}finally{f(!1)}},[e,t,r,s]);v.useEffect(()=>{z()},[z]);const D=async F=>{h(F.id);try{const te=`/admin/credits/refund-requests/${F.id}/process`,se=JSON.stringify({amountLamports:F.amountLamports,reason:F.reason});if(s?.isAuthenticated())await s.fetchWithAuth(te,{method:"POST",body:se});else{const ge={"Content-Type":"application/json"};t&&(ge["X-API-Key"]=t);const be=await fetch(`${e}${te}`,{method:"POST",headers:ge,body:se});if(!be.ok)throw new Error(`Failed to process credits refund: ${be.status}`)}await z()}catch(te){Y.getLogger().error("[RefundsSection] Failed to process credits refund:",te,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:F.id}),u(se=>se.map(ge=>ge.id===F.id?{...ge,status:"processed"}:ge))}finally{h(null)}},R=F=>{L(F.reason??""),P(F)},O=()=>{P(null),L("")},T=async()=>{if(!k)return;const F=k,te=A;O(),h(F.id);try{const se=`/admin/credits/refund-requests/${F.id}/reject`,ge=JSON.stringify({reason:te});if(s?.isAuthenticated())await s.fetchWithAuth(se,{method:"POST",body:ge});else{const be={"Content-Type":"application/json"};t&&(be["X-API-Key"]=t);const Ae=await fetch(`${e}${se}`,{method:"POST",headers:be,body:ge});if(!Ae.ok)throw new Error(`Failed to reject credits refund: ${Ae.status}`)}await z()}catch(se){Y.getLogger().error("[RefundsSection] Failed to reject credits refund:",se,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:F.id}),u(ge=>ge.map(be=>be.id===F.id?{...be,status:"rejected",rejectedAt:new Date().toISOString(),rejectedReason:te||null}:be))}finally{h(null)}},W=v.useCallback(async()=>{try{let F;const te=`/admin/stripe/refunds?limit=${r}`;if(s?.isAuthenticated())F=await s.fetchWithAuth(te);else{const se={"Content-Type":"application/json"};t&&(se["X-API-Key"]=t);const ge=await fetch(`${e}${te}`,{headers:se});if(!ge.ok)throw new Error(`Failed to fetch Stripe refunds: ${ge.status}`);F=await ge.json()}_(F.refunds||[])}catch(F){Y.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",F,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),_([{id:"rr_demo1",stripeRefundId:"re_demo1",chargeId:"ch_demo1",paymentIntentId:"pi_demo1",amount:4999,currency:"usd",status:"succeeded",reason:"requested_by_customer",createdAt:new Date().toISOString()},{id:"rr_demo2",stripeRefundId:null,chargeId:null,paymentIntentId:"pi_demo2",amount:1500,currency:"usd",status:"pending",reason:"duplicate",createdAt:new Date(Date.now()-36e5).toISOString()}])}finally{C(!1)}},[e,t,r,s]);v.useEffect(()=>{W()},[W]);const E=async F=>{S(F);try{const te=`/admin/stripe/refunds/${F}/process`;if(s?.isAuthenticated())await s.fetchWithAuth(te,{method:"POST"});else{const se={"Content-Type":"application/json"};t&&(se["X-API-Key"]=t);const ge=await fetch(`${e}${te}`,{method:"POST",headers:se});if(!ge.ok)throw new Error(`Failed to process refund: ${ge.status}`)}await W()}catch(te){Y.getLogger().error("[RefundsSection] Failed to process Stripe refund:",te,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:F}),_(se=>se.map(ge=>ge.id===F?{...ge,stripeRefundId:ge.stripeRefundId??"re_demo_processed",status:"succeeded"}:ge))}finally{S(null)}},q=(F,te)=>new Intl.NumberFormat("en-US",{style:"currency",currency:te}).format(F/100),ne=F=>F?F.replace(/_/g," ").replace(/\b\w/g,te=>te.toUpperCase()):"—",U=F=>{switch(F){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},K=(F,te)=>te?te.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(F/1e6)} (USD credits)`:`${F.toLocaleString()} ${te.toUpperCase()} (atomic)`:`${F.toLocaleString()} (atomic)`,J=F=>{switch(F){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},he=F=>F.stripeRefundId??"—",B=F=>F.chargeId??"—",X=y.filter(F=>F.status==="pending"||F.status==="requires_action").length,me=m.filter(F=>F.status==="pending").length,V=o.filter(F=>F.status==="pending").length,re=X+me+V,le=y.filter(F=>F.status==="succeeded").reduce((F,te)=>F+te.amount,0),pe=m.filter(F=>F.status==="processed").reduce((F,te)=>F+te.amountLamports,0),Re=o.filter(F=>F.status==="completed").reduce((F,te)=>F+te.amount,0),He=le/100+pe/1e6+Re,Ze=F=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(F),Ge=j||p||i,Qe=F=>{$(te=>!te||te.key!==F?{key:F,direction:"asc"}:{key:F,direction:te.direction==="asc"?"desc":"asc"})},Pe=F=>{w(te=>!te||te.key!==F?{key:F,direction:"asc"}:{key:F,direction:te.direction==="asc"?"desc":"asc"})},rt=F=>{d(te=>!te||te.key!==F?{key:F,direction:"asc"}:{key:F,direction:te.direction==="asc"?"desc":"asc"})},Ce=(F,te)=>!F||!te?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:G.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:te==="asc"?G.chevronUp:G.chevronDown}),ee=v.useMemo(()=>{if(!N)return y;const F=N.direction==="asc"?1:-1,te=se=>{switch(N.key){case"stripe":return se.stripeRefundId??"";case"charge":return se.chargeId??"";case"amount":return se.amount??0;case"reason":return se.reason??"";case"status":return se.status??"";case"date":return new Date(se.createdAt).getTime();case"id":default:return se.id}};return[...y].sort((se,ge)=>{const be=te(se),Ae=te(ge);return typeof be=="number"&&typeof Ae=="number"?(be-Ae)*F:String(be).localeCompare(String(Ae),void 0,{sensitivity:"base"})*F})},[y,N]),je=v.useMemo(()=>{if(!b)return m;const F=b.direction==="asc"?1:-1,te=se=>{switch(b.key){case"original":return se.originalTransactionId??"";case"user":return se.userId??"";case"amount":return se.amountLamports??0;case"reason":return se.reason??"";case"status":return se.status??"";case"date":return new Date(se.createdAt).getTime();case"id":default:return se.id}};return[...m].sort((se,ge)=>{const be=te(se),Ae=te(ge);return typeof be=="number"&&typeof Ae=="number"?(be-Ae)*F:String(be).localeCompare(String(Ae),void 0,{sensitivity:"base"})*F})},[m,b]),Oe=v.useMemo(()=>{if(!l)return o;const F=l.direction==="asc"?1:-1,te=se=>{switch(l.key){case"transaction":return se.transactionId??"";case"amount":return se.amount??0;case"reason":return se.reason??"";case"status":return se.status??"";case"date":return new Date(se.createdAt).getTime();case"id":default:return se.id}};return[...o].sort((se,ge)=>{const be=te(se),Ae=te(ge);return typeof be=="number"&&typeof Ae=="number"?(be-Ae)*F:String(be).localeCompare(String(Ae),void 0,{sensitivity:"base"})*F})},[o,l]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(rr,{stats:[{label:"Pending",value:re,variant:re>0?"warning":"muted"},{label:"Card Pending",value:X,description:"Stripe"},{label:"Credits Pending",value:me},{label:"Crypto Pending",value:V,description:"x402"},{label:"Total Refunded",value:Ze(He),variant:"success"}],isLoading:Ge}),n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),j?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading Stripe refunds..."]}):y.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":N?.key==="id"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Qe("id"),children:["Request ID",Ce(N?.key==="id",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="stripe"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Qe("stripe"),children:["Stripe Refund ID",Ce(N?.key==="stripe",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="charge"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Qe("charge"),children:["Charge",Ce(N?.key==="charge",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="amount"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Qe("amount"),children:["Amount",Ce(N?.key==="amount",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="reason"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Qe("reason"),children:["Reason",Ce(N?.key==="reason",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="status"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Qe("status"),children:["Status",Ce(N?.key==="status",N?.direction)]})}),n.jsx("th",{"aria-sort":N?.key==="date"?N?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Qe("date"),children:["Date",Ce(N?.key==="date",N?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:ee.map(F=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:F.id})}),n.jsx("td",{children:n.jsx("code",{children:he(F)})}),n.jsx("td",{children:n.jsx("code",{children:B(F)})}),n.jsx("td",{children:q(F.amount,F.currency)}),n.jsx("td",{children:ne(F.reason)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${J(F.status)}`,children:F.status})}),n.jsx("td",{children:jr(F.createdAt)}),n.jsx("td",{children:(F.status==="pending"||F.status==="requires_action")&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>E(F.id),disabled:I===F.id,children:I===F.id?"Processing...":"Process"})})]},F.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:[G.loading," Loading credits refunds..."]}):m.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":b?.key==="id"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Pe("id"),children:["Request ID",Ce(b?.key==="id",b?.direction)]})}),n.jsx("th",{"aria-sort":b?.key==="original"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Pe("original"),children:["Original Tx",Ce(b?.key==="original",b?.direction)]})}),n.jsx("th",{"aria-sort":b?.key==="user"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Pe("user"),children:["User",Ce(b?.key==="user",b?.direction)]})}),n.jsx("th",{"aria-sort":b?.key==="amount"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Pe("amount"),children:["Amount",Ce(b?.key==="amount",b?.direction)]})}),n.jsx("th",{"aria-sort":b?.key==="reason"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Pe("reason"),children:["Reason",Ce(b?.key==="reason",b?.direction)]})}),n.jsx("th",{"aria-sort":b?.key==="status"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Pe("status"),children:["Status",Ce(b?.key==="status",b?.direction)]})}),n.jsx("th",{"aria-sort":b?.key==="date"?b?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Pe("date"),children:["Date",Ce(b?.key==="date",b?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:je.map(F=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:F.id})}),n.jsx("td",{children:n.jsx("code",{children:F.originalTransactionId})}),n.jsx("td",{children:n.jsx("code",{children:F.userId??"—"})}),n.jsx("td",{children:K(F.amountLamports,F.currency)}),n.jsx("td",{children:F.reason??"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${U(F.status)}`,children:F.status})}),n.jsx("td",{children:jr(F.createdAt)}),n.jsx("td",{children:F.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:()=>D(F),disabled:g===F.id,children:g===F.id?"Processing...":"Process"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>R(F),disabled:g===F.id,children:"Reject"})]}):null})]},F.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading x402 refunds..."]}):o.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>rt("id"),children:["ID",Ce(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:()=>rt("transaction"),children:["Transaction",Ce(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:()=>rt("amount"),children:["Amount",Ce(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:()=>rt("reason"),children:["Reason",Ce(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:()=>rt("status"),children:["Status",Ce(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:()=>rt("date"),children:["Date",Ce(l?.key==="date",l?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:Oe.map(F=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:F.id})}),n.jsx("td",{children:n.jsx("code",{children:F.transactionId})}),n.jsxs("td",{children:["$",F.amount.toFixed(2)]}),n.jsx("td",{children:F.reason||"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${F.status}`,children:F.status})}),n.jsx("td",{children:jr(F.createdAt)}),n.jsx("td",{children:F.status==="pending"&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",children:"Process"})})]},F.id))})]})}),k&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:O,children:n.jsxs("div",{className:"cedros-admin__modal",onClick:F=>F.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:O,"aria-label":"Close",children:G.close})]}),n.jsxs("div",{className:"cedros-admin__modal-body",children:[n.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",n.jsx("code",{children:k.id})," for ",K(k.amountLamports,k.currency),"."]}),n.jsxs("label",{className:"cedros-admin__form-field",children:[n.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),n.jsx("textarea",{className:"cedros-admin__input",value:A,onChange:F=>L(F.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:O,children:"Cancel"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:T,children:"Reject Refund"})]})]})})]})}async function Wf(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 qf{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 Wf(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 vt="[REDACTED]";function Ta({data:e,onSave:t,debounceMs:r=1500,savedDurationMs:s=2e3,enabled:o=!0,skipInitial:a=!0}){const[i,c]=v.useState("idle"),[l,d]=v.useState(null),m=v.useRef(!0),u=v.useRef(null),p=v.useRef(null),f=v.useRef(e);f.current=e;const g=v.useCallback(async()=>{c("saving"),d(null);try{await t(f.current),c("saved"),p.current=setTimeout(()=>{c("idle")},s)}catch(w){c("error"),d(w instanceof Error?w.message:"Save failed")}},[t,s]),h=v.useCallback(async()=>{u.current&&(clearTimeout(u.current),u.current=null),await g()},[g]),b=v.useCallback(()=>{c("idle"),d(null)},[]);return v.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(()=>{g()},r),()=>{u.current&&clearTimeout(u.current)}}},[e,o,a,r,g]),v.useEffect(()=>()=>{u.current&&clearTimeout(u.current),p.current&&clearTimeout(p.current)},[]),{status:i,error:l,saveNow:h,reset:b}}function Vf(e){if(!e||e.trim()==="")return{valid:!0};try{return new of.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 Hf({category:e,config:t,originalConfig:r,isLoading:s=!1,onSave:o}){const[a,i]=v.useState(t),[c,l]=v.useState(new Set);v.useEffect(()=>{i(t)},[t]);const d=v.useMemo(()=>{const y={...a};for(const _ of Object.keys(y))if(Bl(e,_)){const j=r[_],C=y[_];(C===vt||C===j)&&(y[_]=vt)}return y},[a,r,e]),{status:m,error:u}=Ta({data:d,onSave:o,debounceMs:1500}),p=v.useCallback((y,_)=>{i(j=>({...j,[y]:_}))},[]),f=v.useCallback(y=>{l(_=>{const j=new Set(_);return j.has(y)?j.delete(y):j.add(y),j})},[]),g=y=>y?n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:y}):null,h=(y,_)=>{const j=Ki(e,y,r[y]??_);if(j.type==="dropdown"&&j.options)return n.jsx(ct,{value:_,onChange:S=>p(y,S),options:j.options.map(S=>({value:S,label:S})),label:j.label,description:j.description,disabled:s});if(j.type==="token_mint")return n.jsx(Zf,{label:j.label,value:_,onChange:S=>p(y,S),decimals:a.token_decimals??6,onDecimalsChange:S=>p("token_decimals",S),disabled:s,description:j.description,customSymbol:a.custom_token_symbol||"",customIcon:a.custom_token_icon||"",onCustomSymbolChange:S=>p("custom_token_symbol",S),onCustomIconChange:S=>p("custom_token_icon",S)});if(j.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":_,onClick:()=>p(y,!_),disabled:s,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:_?"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:_?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:j.label})]}),g(j.description)]});if(j.type==="solana_address"){const S=_||"",N=Vf(S);return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:j.label}),n.jsxs("div",{style:{position:"relative"},children:[n.jsx("input",{type:"text",className:`cedros-admin__input ${N.valid?"":"cedros-admin__input--error"}`,value:S,onChange:$=>p(y,$.target.value),disabled:s,placeholder:"e.g. 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",style:{width:"100%",fontFamily:"monospace",fontSize:"0.875rem",borderColor:N.valid?void 0:"var(--cedros-admin-error, #dc2626)",paddingRight:S&&N.valid?"2rem":void 0}}),S&&N.valid&&n.jsx("span",{style:{position:"absolute",right:10,top:"50%",transform:"translateY(-50%)",color:"var(--cedros-admin-success, #16a34a)",fontSize:"1rem"},title:"Valid Solana address",children:"✓"})]}),!N.valid&&n.jsx("span",{style:{color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.75rem",marginTop:"0.25rem",display:"block"},children:N.error}),g(j.description)]})}if(j.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:_,onChange:S=>p(y,S.target.checked),disabled:s}),j.label]}),g(j.description)]});if(j.type==="number")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[j.label,j.unit&&n.jsxs("span",{className:"cedros-admin__field-unit",children:[" (",j.unit,")"]})]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:_,onChange:S=>p(y,parseFloat(S.target.value)||0),disabled:s}),g(j.description)]});if(j.type==="secret_array")return n.jsx(Gf,{label:j.label,value:_,onChange:S=>p(y,S),disabled:s,description:j.description});if(j.type==="array"){const S=_;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:j.label}),n.jsx("textarea",{className:"cedros-admin__textarea",value:S.join(`
2
- `),onChange:N=>p(y,N.target.value.split(`
3
- `).filter(Boolean)),placeholder:"One item per line",rows:3,disabled:s}),g(j.description)]})}if(j.type==="object")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:j.label}),n.jsx("textarea",{className:"cedros-admin__textarea cedros-admin__textarea--mono",value:JSON.stringify(_,null,2),onChange:S=>{try{p(y,JSON.parse(S.target.value))}catch{}},rows:5,disabled:s}),g(j.description)]});const C=c.has(y),I=j.isSecret&&!C&&_===vt?vt:_;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[j.label,j.isSecret&&n.jsx("span",{className:"cedros-admin__field-secret",children:" (secret)"})]}),n.jsxs("div",{className:"cedros-admin__input-group",children:[n.jsx("input",{type:j.isSecret&&!C?"password":"text",className:"cedros-admin__input",value:I,onChange:S=>p(y,S.target.value),disabled:s,placeholder:j.isSecret?"••••••••":""}),j.isSecret&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>f(y),style:{padding:"0.5rem",minWidth:"auto"},title:C?"Hide":"Show",children:C?G.eyeOff:G.eye})]}),g(j.description)]})},b=Object.keys(a),w=y=>{const _=Ki(e,y,r[y]??a[y]);if(_.hidden||_.showWhen&&!a[_.showWhen])return!1;if(y==="token_decimals"){const j=a.token_mint;if(j&&Y.STABLECOIN_METADATA[j])return!1}return!0};return n.jsxs("div",{className:"cedros-admin__config-editor",children:[n.jsx("div",{className:"cedros-admin__config-fields",children:b.filter(w).map(y=>n.jsx("div",{className:"cedros-admin__config-field",children:h(y,a[y])},y))}),n.jsx("div",{className:"cedros-admin__config-actions",children:n.jsx("div",{className:"cedros-admin__autosave-status",children:n.jsx(Qf,{status:m,error:u})})})]})}function Zf({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]=v.useState(!1),f=Object.entries(Y.STABLECOIN_METADATA),h=!!Y.STABLECOIN_METADATA[t],w=u||!!t&&!h,y=_=>{if(_==="custom")p(!0),h&&r("");else{p(!1),r(_);const j=Y.STABLECOIN_METADATA[_];j&&o&&o(j.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:[f.map(([_,j])=>n.jsxs("button",{type:"button",onClick:()=>y(_),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:t===_?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:t===_?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:t===_?600:400},children:[n.jsx("img",{src:j.icon,alt:j.symbol,style:{width:20,height:20,borderRadius:"50%"},onError:C=>{C.target.style.display="none"}}),n.jsx("span",{children:j.symbol})]},_)),n.jsxs("button",{type:"button",onClick:()=>y("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:_=>r(_.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:_=>d?.(_.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:_=>m?.(_.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:_=>{_.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:_=>o?.(parseInt(_.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&&h&&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 Gf({label:e,value:t,onChange:r,disabled:s=!1,description:o}){const[a,i]=v.useState(new Set),[c,l]=v.useState(null),[d,m]=v.useState(""),u=Array.isArray(t)?t:[],p=_=>{i(j=>{const C=new Set(j);return C.has(_)?C.delete(_):C.add(_),C})},f=()=>{r([...u,""]),l(u.length),m("")},g=(_,j)=>{const C=[...u];C[_]=j,r(C)},h=_=>{const j=u.filter((C,I)=>I!==_);r(j),i(C=>{const I=new Set;return C.forEach(S=>{S<_?I.add(S):S>_&&I.add(S-1)}),I})},b=_=>{l(_),m(u[_]||"")},w=()=>{c!==null&&(g(c,d),l(null),m(""))},y=()=>{c!==null&&u[c]===""&&h(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:f,disabled:s,style:{display:"flex",alignItems:"center",gap:"0.25rem",padding:"0.25rem 0.5rem",fontSize:"0.75rem",border:"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.375rem",background:"var(--cedros-admin-bg, #fff)",cursor:s?"not-allowed":"pointer",opacity:s?.5:1},children:[G.plus,"Add"]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u.length===0&&n.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"0.875rem",border:"1px dashed var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem"},children:'No items. Click "Add" to create one.'}),u.map((_,j)=>{const C=a.has(j),I=c===j,S=_===vt;return n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.375rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:I?n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:d,onChange:N=>m(N.target.value),placeholder:"Enter wallet keypair...",autoFocus:!0,style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem"},onKeyDown:N=>{N.key==="Enter"&&w(),N.key==="Escape"&&y()}}),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:G.check}),n.jsx("button",{type:"button",onClick:y,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-text-muted, #64748b)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Cancel",children:G.close})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C&&!S?_:S?"[REDACTED]":"••••••••••••••••••••"}),n.jsx("button",{type:"button",onClick:()=>p(j),disabled:s||S,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s||S?"not-allowed":"pointer",opacity:s||S?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:C?"Hide":"Show",children:C?G.eyeOff:G.eye}),n.jsx("button",{type:"button",onClick:()=>b(j),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:"Edit",children:G.settings}),n.jsx("button",{type:"button",onClick:()=>h(j),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-error, #ef4444)"},title:"Delete",children:G.trash})]})},j)})]}),o&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.5rem"},children:o})]})}function Qf({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${e}`,style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx(n.Fragment,{children:n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"})}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx(n.Fragment,{children:n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})})]})}function Ul({serverUrl:e,apiKey:t,authManager:r,category:s,title:o,description:a,enabledField:i="enabled",showEnabledToggle:c=!1}){const l=v.useMemo(()=>new qf(e,void 0,r),[e,r]),[d,m]=v.useState(null),[u,p]=v.useState([]),[f,g]=v.useState(!1),[h,b]=v.useState(!0),[w,y]=v.useState(null),[_,j]=v.useState(null),[C,I]=v.useState(!1),S=Ea[s]||{label:s,icon:"⚙️"},N=o||S.label,$=a||S.description,k=v.useCallback(()=>({stripe:{secret_key:vt,webhook_secret:vt,publishable_key:"pk_test_xxx",success_url:"https://example.com/success",cancel_url:"https://example.com/cancel",mode:"test",enabled:!0},x402:{enabled:!1,payment_address:"",token_mint:"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",token_decimals:6,network:"mainnet-beta",rpc_url:"",gasless_enabled:!1,server_wallets:vt},server:{address:":8080",read_timeout:"15s",write_timeout:"15s",cors_allowed_origins:["http://localhost:3000"],admin_metrics_api_key:vt},logging:{level:"info",format:"json",environment:"production"},metrics:{admin_metrics_api_key:vt},security:{cors_allowed_origins:["http://localhost:3000"]},cedros_login:{enabled:!1,credits_enabled:!1,base_url:"",api_key:vt,timeout:30},email:{enabled:!1,provider:"",smtp_host:"",smtp_port:587,smtp_user:"",smtp_password:vt,from_address:"",from_name:""},webhook:{enabled:!1,url:"",secret:vt,retry_attempts:3}})[s]||{},[s]),P=v.useCallback(async()=>{b(!0),y(null);try{const W=await l.getConfig(s,!0);m(W)}catch{m({category:s,config:k(),updatedAt:new Date().toISOString(),secretsRedacted:!0})}finally{b(!1)}},[l,s,k]);v.useEffect(()=>{P()},[P]);const A=v.useCallback(async()=>{try{const W=await l.getHistory(s,20);p(W.history)}catch{p([{id:"1",configKey:`${s}.updated`,action:"UPDATE",changedAt:new Date().toISOString(),changedBy:"admin"}])}},[l,s]);v.useEffect(()=>{f&&A()},[f,A]);const L=v.useCallback(async W=>{await l.updateConfig(s,W,"Updated via admin dashboard"),await P()},[l,s,P]),z=v.useCallback(async W=>l.validateConfig(s,W),[l,s]),[D,R]=v.useState(!1),O=v.useCallback(async()=>{if(!d||D)return;const E=!!!d.config[i],q={...d.config,[i]:E};R(!0),m({...d,config:q});try{await l.updateConfig(s,q,`${E?"Enabled":"Disabled"} via admin dashboard`)}catch(ne){console.warn("Failed to save enabled state to server (demo mode?):",ne)}finally{R(!1)}},[d,l,s,i,D]),T=!!d?.config[i];return h&&!d?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading ",N," settings..."]})}):w?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__error",children:["Failed to load settings: ",w]})}):n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{children:[n.jsxs("h3",{className:"cedros-admin__section-title",children:[n.jsx("span",{style:{marginRight:"0.5rem"},children:S.icon}),N]}),$&&n.jsx("p",{className:"cedros-admin__text-muted",style:{marginTop:"0.25rem"},children:$})]}),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:T?"var(--cedros-admin-text, #171717)":"var(--cedros-admin-muted, #737373)"},children:T?"Enabled":"Disabled"}),n.jsx("button",{type:"button",role:"switch","aria-checked":T,onClick:O,disabled:D,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:T?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:D?"wait":"pointer",position:"relative",transition:"background-color 0.2s",flexShrink:0,opacity:D?.6:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:T?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&&!T?.6:1,pointerEvents:c&&!T?"none":"auto"},children:[c&&!T&&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(Hf,{category:d.category,config:d.config,originalConfig:d.config,onSave:L,onValidate:z,onCancel:()=>P()})]}),f&&n.jsxs("div",{className:"cedros-admin__settings-history",style:{marginTop:"1.5rem"},children:[n.jsx("h4",{style:{marginBottom:"0.75rem",fontWeight:600},children:"Change History"}),u.length===0?n.jsx("p",{className:"cedros-admin__text-muted",children:"No history entries found."}):n.jsx("div",{className:"cedros-admin__settings-timeline",children:u.map(W=>n.jsxs("div",{className:"cedros-admin__settings-timeline-item",children:[n.jsx("div",{className:"cedros-admin__settings-timeline-dot"}),n.jsxs("div",{className:"cedros-admin__settings-timeline-content",children:[n.jsxs("div",{className:"cedros-admin__settings-timeline-header",children:[n.jsx("code",{children:W.configKey}),n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${W.action.toLowerCase()}`,children:W.action})]}),n.jsxs("div",{className:"cedros-admin__settings-timeline-meta",children:[jr(W.changedAt)," by ",W.changedBy]})]})]},W.id))})]}),_&&n.jsx("div",{style:{marginTop:"1rem",padding:"0.75rem 1rem",borderRadius:"0.375rem",backgroundColor:_.valid?"var(--cedros-admin-success-bg, #dcfce7)":"var(--cedros-admin-error-bg, #fef2f2)",border:`1px solid ${_.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:_.valid?"var(--cedros-admin-success, #16a34a)":"var(--cedros-admin-error, #dc2626)",marginBottom:_.errors.length>0||_.warnings.length>0?"0.5rem":0},children:_.valid?"✓ Configuration is valid":"✗ Validation failed"}),_.errors.length>0&&n.jsx("ul",{style:{margin:0,paddingLeft:"1.25rem",color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.875rem"},children:_.errors.map((W,E)=>n.jsx("li",{children:W},E))}),_.warnings.length>0&&n.jsx("ul",{style:{margin:_.errors.length>0?"0.5rem 0 0":0,paddingLeft:"1.25rem",color:"var(--cedros-admin-warning, #ca8a04)",fontSize:"0.875rem"},children:_.warnings.map((W,E)=>n.jsx("li",{children:W},E))})]}),n.jsx("button",{type:"button",onClick:()=>j(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:()=>g(!f),children:f?"Hide History":"History"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",disabled:C||!d,onClick:async()=>{if(d){I(!0),j(null);try{const W=await z(d.config);j(W)}catch(W){j({valid:!1,errors:[W instanceof Error?W.message:"Validation failed"],warnings:[]})}finally{I(!1)}}},children:C?"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]=v.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 Yf=Object.freeze(Object.defineProperty({__proto__:null,SettingsSection:Ia},Symbol.toStringTag,{value:"Module"})),ke={enabled:!1,plans:[],pageTitle:"Choose Your Plan",pageSubtitle:"Select the plan that best fits your needs.",annualSavingsBadge:"2 months free",popularBadgeText:"Best Deal",footerNotice:""},Kf={title:"New Plan",description:"",priceMonthlyUsd:0,priceAnnualUsd:0,features:[],featureHighlight:"",buttonText:"Purchase",isPopular:!1,isActive:!0,sortOrder:0};function Xf(){return`plan_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Wl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=v.useState(ke),[a,i]=v.useState(!0),[c,l]=v.useState(null),[d,m]=v.useState("plans"),[u,p]=v.useState("idle"),[f,g]=v.useState({enabled:ke.enabled,pageTitle:ke.pageTitle,pageSubtitle:ke.pageSubtitle,annualSavingsBadge:ke.annualSavingsBadge,popularBadgeText:ke.popularBadgeText,footerNotice:ke.footerNotice}),[h,b]=v.useState(f),[w,y]=v.useState(""),_=v.useCallback(async()=>{try{let E;const q="/admin/subscriptions/settings";if(r?.isAuthenticated())E=await r.fetchWithAuth(q);else{const ne={"Content-Type":"application/json"};t&&(ne["X-API-Key"]=t);const U=await fetch(`${e}${q}`,{headers:ne});if(!U.ok)throw new Error(`Failed to fetch settings: ${U.status}`);E=await U.json()}o({...ke,...E}),g({enabled:E.enabled??ke.enabled,pageTitle:E.pageTitle??ke.pageTitle,pageSubtitle:E.pageSubtitle??ke.pageSubtitle,annualSavingsBadge:E.annualSavingsBadge??ke.annualSavingsBadge,popularBadgeText:E.popularBadgeText??ke.popularBadgeText,footerNotice:E.footerNotice??ke.footerNotice}),b({enabled:E.enabled??ke.enabled,pageTitle:E.pageTitle??ke.pageTitle,pageSubtitle:E.pageSubtitle??ke.pageSubtitle,annualSavingsBadge:E.annualSavingsBadge??ke.annualSavingsBadge,popularBadgeText:E.popularBadgeText??ke.popularBadgeText,footerNotice:E.footerNotice??ke.footerNotice}),y(JSON.stringify(E.plans??[]))}catch{const E={...ke,enabled:!0,plans:[{id:"plan_starter",title:"Starter",description:"For individuals",priceMonthlyUsd:9,priceAnnualUsd:90,features:["100 requests/month","Email support"],isActive:!0,sortOrder:0,activeSubscribers:142},{id:"plan_pro",title:"Pro",description:"For professionals",priceMonthlyUsd:29,priceAnnualUsd:290,features:["Unlimited requests","Priority support","API access"],isPopular:!0,isActive:!0,sortOrder:1,activeSubscribers:89},{id:"plan_enterprise",title:"Enterprise",description:"For teams",priceMonthlyUsd:99,priceAnnualUsd:990,features:["Everything in Pro","SSO","Dedicated support"],isActive:!0,sortOrder:2,activeSubscribers:23}]};o(E),g({enabled:E.enabled,pageTitle:E.pageTitle??ke.pageTitle,pageSubtitle:E.pageSubtitle??ke.pageSubtitle,annualSavingsBadge:E.annualSavingsBadge??ke.annualSavingsBadge,popularBadgeText:E.popularBadgeText??ke.popularBadgeText,footerNotice:E.footerNotice??ke.footerNotice}),b({enabled:E.enabled,pageTitle:E.pageTitle??ke.pageTitle,pageSubtitle:E.pageSubtitle??ke.pageSubtitle,annualSavingsBadge:E.annualSavingsBadge??ke.annualSavingsBadge,popularBadgeText:E.popularBadgeText??ke.popularBadgeText,footerNotice:E.footerNotice??ke.footerNotice}),y(JSON.stringify(E.plans))}finally{i(!1)}},[e,t,r]);v.useEffect(()=>{_()},[_]);const j=v.useCallback(async E=>{try{const q="/admin/subscriptions/settings",ne=JSON.stringify(E);if(r?.isAuthenticated())await r.fetchWithAuth(q,{method:"PUT",body:ne});else{const U={"Content-Type":"application/json"};t&&(U["X-API-Key"]=t);const K=await fetch(`${e}${q}`,{method:"PUT",headers:U,body:ne});if(!K.ok)throw new Error(`Failed to save settings: ${K.status}`)}return!0}catch{return!0}},[r,t,e]),C=v.useMemo(()=>h.enabled!==f.enabled||h.pageTitle!==f.pageTitle||h.pageSubtitle!==f.pageSubtitle||h.annualSavingsBadge!==f.annualSavingsBadge||h.popularBadgeText!==f.popularBadgeText||h.footerNotice!==f.footerNotice,[f,h]),I=v.useMemo(()=>JSON.stringify(s.plans),[s.plans]),S=v.useMemo(()=>w!==I,[I,w]),N=v.useCallback(async()=>{const E={...s,enabled:f.enabled,pageTitle:f.pageTitle,pageSubtitle:f.pageSubtitle,annualSavingsBadge:f.annualSavingsBadge,popularBadgeText:f.popularBadgeText,footerNotice:f.footerNotice};p("saving");const q=await j(E);o(E),q&&(b({enabled:E.enabled,pageTitle:E.pageTitle,pageSubtitle:E.pageSubtitle,annualSavingsBadge:E.annualSavingsBadge,popularBadgeText:E.popularBadgeText,footerNotice:E.footerNotice}),y(JSON.stringify(E.plans))),p(q?"saved":"error"),setTimeout(()=>p("idle"),1500)},[f,j,s]);v.useEffect(()=>{if(d!=="page"||a||!C)return;const E=setTimeout(N,600);return()=>clearTimeout(E)},[d,C,a,N]),v.useEffect(()=>{if(d!=="plans"||a||!S)return;const E=setTimeout(N,800);return()=>clearTimeout(E)},[d,S,a,N]);const $=()=>{const E={...Kf,id:Xf(),sortOrder:s.plans.length};o(q=>({...q,plans:[...q.plans,E]})),l(E.id)},k=(E,q)=>{o(ne=>({...ne,plans:ne.plans.map(U=>U.id===E?{...U,...q}:U)}))},P=E=>{confirm("Delete this plan? This cannot be undone.")&&(o(q=>({...q,plans:q.plans.filter(ne=>ne.id!==E)})),c===E&&l(null))},A=(E,q)=>{const ne=s.plans.findIndex(J=>J.id===E);if(ne===-1||q==="up"&&ne===0||q==="down"&&ne===s.plans.length-1)return;const U=[...s.plans],K=q==="up"?ne-1:ne+1;[U[ne],U[K]]=[U[K],U[ne]],o(J=>({...J,plans:U}))},L=E=>{k(E,{features:[...s.plans.find(q=>q.id===E)?.features||[],""]})},z=(E,q,ne)=>{const U=s.plans.find(J=>J.id===E);if(!U)return;const K=[...U.features];K[q]=ne,k(E,{features:K})},D=(E,q)=>{const ne=s.plans.find(K=>K.id===E);if(!ne)return;const U=ne.features.filter((K,J)=>J!==q);k(E,{features:U})};if(a)return n.jsx("div",{className:"cedros-admin__page",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading subscription settings..."]})});const R=s.plans.filter(E=>E.isActive).length,O=s.plans.reduce((E,q)=>E+(q.activeSubscribers??0),0),T=f.enabled,W=s.plans.filter(E=>E.isActive).map(E=>({label:E.title,value:E.activeSubscribers??0,description:"subscribers"}));return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(rr,{stats:[{label:"Status",value:T?"Enabled":"Disabled",variant:T?"success":"muted"},{label:"Active Plans",value:R,variant:R>0?"success":"muted"},{label:"Total Subscribers",value:O,variant:O>0?"success":"muted"},...W],isLoading:a}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Subscription Settings"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[d==="plans"&&n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:$,disabled:!T,children:[G.plus,"Add Plan"]}),n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${u}`,children:[u==="saving"&&"Saving...",u==="saved"&&"Saved",u==="error"&&"Error"]})]})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="plans"?"cedros-admin__tab--active":""}`,onClick:()=>m("plans"),children:"Plans"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="page"?"cedros-admin__tab--active":""}`,onClick:()=>m("page"),children:"Page Settings"})]}),d==="page"&&n.jsxs("div",{children:[n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Subscriptions"}),n.jsxs("label",{className:"cedros-admin__toggle",children:[n.jsx("input",{type:"checkbox",className:"cedros-admin__toggle-input",checked:f.enabled,onChange:E=>g(q=>({...q,enabled:E.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:f.pageTitle||"",onChange:E=>g(q=>({...q,pageTitle:E.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:f.pageSubtitle||"",onChange:E=>g(q=>({...q,pageSubtitle:E.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:f.annualSavingsBadge||"",onChange:E=>g(q=>({...q,annualSavingsBadge:E.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:f.popularBadgeText||"",onChange:E=>g(q=>({...q,popularBadgeText:E.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:f.footerNotice||"",onChange:E=>g(q=>({...q,footerNotice:E.target.value})),placeholder:"For information regarding invoices, taxes..."})]})})]}),d==="plans"&&n.jsxs("div",{children:[!T&&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((E,q)=>{const ne=c===E.id;return n.jsxs("div",{style:{border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:8,overflow:"hidden",background:E.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(ne?null:E.id),children:[n.jsx("span",{style:{opacity:.5},children:ne?G.chevronDown:G.chevronRight}),n.jsxs("div",{style:{flex:1},children:[n.jsx("span",{style:{fontWeight:600},children:E.title||"Untitled Plan"}),E.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"}),!E.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:["$",E.priceMonthlyUsd,"/mo · $",E.priceAnnualUsd,"/yr"]}),n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},onClick:U=>U.stopPropagation(),children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>A(E.id,"up"),disabled:q===0,title:"Move up",style:{padding:"4px 8px"},children:G.chevronUp}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>A(E.id,"down"),disabled:q===s.plans.length-1,title:"Move down",style:{padding:"4px 8px"},children:G.chevronDown}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>P(E.id),title:"Delete plan",style:{padding:"4px 8px",color:"#dc2626"},children:G.trash})]})]}),ne&&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:E.title,onChange:U=>k(E.id,{title:U.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:E.buttonText||"",onChange:U=>k(E.id,{buttonText:U.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:E.description,onChange:U=>k(E.id,{description:U.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:E.priceMonthlyUsd||"",onChange:U=>k(E.id,{priceMonthlyUsd:parseFloat(U.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:E.priceAnnualUsd||"",onChange:U=>k(E.id,{priceAnnualUsd:parseFloat(U.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:E.featureHighlight||"",onChange:U=>k(E.id,{featureHighlight:U.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:E.isPopular||!1,onChange:U=>k(E.id,{isPopular:U.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:E.isActive,onChange:U=>k(E.id,{isActive:U.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:E.inventoryQuantity!=null,onChange:U=>k(E.id,{inventoryQuantity:U.target.checked?100:null})}),"Limit quantity available"]})}),E.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:E.inventoryQuantity??"",onChange:U=>k(E.id,{inventoryQuantity:parseInt(U.target.value)||0}),min:"0",style:{width:100}}),E.inventorySold!=null&&E.inventorySold>0&&n.jsxs("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:[E.inventorySold," sold · ",Math.max(0,E.inventoryQuantity-E.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 (",E.features.length,")"]}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>L(E.id),style:{fontSize:12,padding:"4px 8px"},children:"+ Add Feature"})]}),E.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:E.features.map((U,K)=>n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsxs("span",{style:{opacity:.4,fontSize:12},children:[K+1,"."]}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:U,onChange:J=>z(E.id,K,J.target.value),placeholder:"e.g., Powered by MiniMax M2.1",style:{flex:1}}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>D(E.id,K),style:{padding:"4px 8px",color:"#dc2626"},title:"Remove feature",children:G.trash})]},K))})]})]})]},E.id)})})]})]})]})}const Jf=Object.freeze(Object.defineProperty({__proto__:null,SubscriptionsSection:Wl},Symbol.toStringTag,{value:"Module"})),vo={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:""}},eh=[{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."}],bo=[{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"}],th=[{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 ql({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=v.useState("shop-page"),[a,i]=v.useState(vo),[c,l]=v.useState(!0),[d,m]=v.useState(!0),u=v.useCallback(async()=>{try{let k;const P="/admin/config/storefront";if(r?.isAuthenticated())k=await r.fetchWithAuth(P);else{const A={"Content-Type":"application/json"};t&&(A["X-API-Key"]=t);const L=await fetch(`${e}${P}`,{headers:A});if(!L.ok)throw new Error(`Failed to fetch settings: ${L.status}`);k=await L.json()}i({...vo,...k.config})}catch{i(vo)}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);v.useEffect(()=>{u()},[u]);const p=v.useCallback(async k=>{const P="/admin/config/storefront",A=JSON.stringify({config:k});try{if(r?.isAuthenticated())await r.fetchWithAuth(P,{method:"PUT",body:A});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const z=await fetch(`${e}${P}`,{method:"PUT",headers:L,body:A});if(!z.ok)throw new Error(`Failed to save settings: ${z.status}`)}}catch{}},[e,t,r]),{status:f,error:g}=Ta({data:a,onSave:p,debounceMs:1500,enabled:!d}),h=k=>{i(P=>({...P,relatedProducts:{...P.relatedProducts,mode:k}}))},b=k=>{i(P=>({...P,relatedProducts:{...P.relatedProducts,maxItems:k}}))},w=(k,P)=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,layout:{...A.relatedProducts.layout,[k]:P}}}))},y=(k,P)=>{i(A=>({...A,catalog:{...A.catalog,filters:{...A.catalog.filters,[k]:P}}}))},_=(k,P)=>{const A=a.catalog.sort,L=Object.values(A).filter(Boolean).length;!P&&L<=1||i(z=>({...z,catalog:{...z.catalog,sort:{...z.catalog.sort,[k]:P}}}))},j=(k,P)=>{i(A=>({...A,checkout:{...A.checkout,[k]:P}}))},C=(k,P)=>{i(A=>({...A,shopLayout:{...A.shopLayout,[k]:P}}))},I=(k,P)=>{i(A=>({...A,categoryLayout:{...A.categoryLayout,[k]:P}}))},S=(k,P)=>{i(A=>({...A,sections:{...A.sections,[k]:P}}))},N=(k,P)=>{i(A=>({...A,inventory:{...A.inventory,[k]:P}}))},$=(k,P)=>{i(A=>({...A,shopPage:{...A.shopPage,[k]:P}}))};return c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading storefront settings..."]})}):n.jsxs("div",{className:"cedros-admin__storefront-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Storefront"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure catalog filters, product layouts, and checkout settings."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[th.map(k=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===k.id?"cedros-admin__tab--active":""}`,onClick:()=>o(k.id),children:k.label},k.id)),n.jsx("div",{style:{flex:1}}),n.jsx(nh,{status:f,error:g})]}),s==="shop-page"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Shop Page Content"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Customize the title and description shown on your shop page."}),n.jsxs("div",{className:"cedros-admin__field",style:{marginBottom:"1.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.shopPage.title,onChange:k=>$("title",k.target.value),placeholder:"Shop"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"The main heading displayed on your shop page."})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Description"}),n.jsx("textarea",{className:"cedros-admin__textarea",value:a.shopPage.description,onChange:k=>$("description",k.target.value),placeholder:"Browse our collection of products...",rows:3,style:{resize:"vertical"}}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"A short description or subtitle shown below the title. Leave empty to hide."})]})]}),s==="catalog"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Catalog Filters"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which filters appear in the shop and category page sidebars."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.catalog.filters.tags,onChange:k=>y("tags",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Tags"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter products by tags (multi-select checkboxes)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.catalog.filters.priceRange,onChange:k=>y("priceRange",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price Range"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter by minimum and maximum price"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.catalog.filters.inStock,onChange:k=>y("inStock",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"In Stock"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show only products that are in stock"})]})]})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Sort Options"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sort options appear in the shop and category pages. At least one must be enabled."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.catalog.sort.featured,onChange:k=>_("featured",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Featured"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Default sort order (as returned by backend)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.catalog.sort.priceAsc,onChange:k=>_("priceAsc",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: Low to High"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price ascending"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.catalog.sort.priceDesc,onChange:k=>_("priceDesc",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: High to Low"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price descending"})]})]})]})]})]}),s==="layouts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Product Layouts"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Configure product card layouts for shop and category pages."}),n.jsxs("div",{style:{marginBottom:"2rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Shop Page"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:bo.map(k=>{const P=a.shopLayout.layout===k.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${P?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:P?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"shopLayout",value:k.value,checked:P,onChange:()=>C("layout",k.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:k.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:k.description})]})]},k.value)})}),n.jsx(ct,{value:a.shopLayout.imageCrop,onChange:k=>C("imageCrop",k),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:bo.map(k=>{const P=a.categoryLayout.layout===k.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${P?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:P?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"categoryLayout",value:k.value,checked:P,onChange:()=>I("layout",k.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:k.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:k.description})]})]},k.value)})}),n.jsx(ct,{value:a.categoryLayout.imageCrop,onChange:k=>I("imageCrop",k),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:eh.map(k=>{const P=a.relatedProducts.mode===k.value,A=k.badge==="Coming Soon";return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"1rem",border:`2px solid ${P?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:8,cursor:A?"not-allowed":"pointer",opacity:A?.6:1,background:P?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedProductsMode",value:k.value,checked:P,onChange:()=>!A&&h(k.value),disabled:A,style:{marginTop:2}}),n.jsxs("div",{style:{flex:1},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("span",{style:{fontWeight:600},children:k.label}),k.badge&&n.jsx("span",{style:{fontSize:11,padding:"2px 6px",borderRadius:4,background:"#6366f1",color:"#fff"},children:k.badge})]}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:13,opacity:.75},children:k.description})]})]},k.value)})}),a.relatedProducts.mode==="manual"&&n.jsxs("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #f5f5f5)",borderRadius:8,border:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("strong",{style:{fontSize:14},children:"How to set related products:"}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.8},children:["When editing a product, add a ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"relatedProductIds"})," field to its metadata containing a comma-separated list of product IDs."]}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.6},children:["Example: ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"prod_123,prod_456,prod_789"})]})]}),n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Max Related Products"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.relatedProducts.maxItems,onChange:k=>b(Math.max(1,Math.min(12,parseInt(k.target.value)||4))),min:1,max:12}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How many related products to show (1-12)"})]}),n.jsxs("div",{style:{marginTop:"1.5rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Display Layout"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:bo.map(k=>{const P=a.relatedProducts.layout.layout===k.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${P?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:P?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedLayout",value:k.value,checked:P,onChange:()=>w("layout",k.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:k.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:k.description})]})]},k.value)})}),n.jsx(ct,{value:a.relatedProducts.layout.imageCrop,onChange:k=>w("imageCrop",k),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(xt,{checked:a.sections.showDescription,onChange:k=>S("showDescription",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Description"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Expandable description accordion"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.sections.showSpecs,onChange:k=>S("showSpecs",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Specifications"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product attributes and details"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.sections.showShipping,onChange:k=>S("showShipping",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Shipping & Returns"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Shipping and return policy information"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.sections.showRelatedProducts,onChange:k=>S("showRelatedProducts",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Related Products"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product recommendations section"})]})]})]})]})]}),s==="checkout"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Checkout Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure checkout and cart page features."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.checkout.promoCodes,onChange:k=>j("promoCodes",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Promo Codes"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show promo/coupon code input on cart and checkout pages"})]})]})})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Inventory Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure inventory verification and reservation behavior."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.inventory.preCheckoutVerification,onChange:k=>N("preCheckoutVerification",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Pre-Checkout Verification"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Verify inventory availability before processing payment"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(xt,{checked:a.inventory.holdsEnabled,onChange:k=>N("holdsEnabled",k)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Inventory Holds"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Reserve inventory when items are added to cart"})]})]})]}),a.inventory.holdsEnabled&&n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200,marginTop:"1rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Hold Duration (minutes)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.inventory.holdDurationMinutes,onChange:k=>N("holdDurationMinutes",Math.max(5,Math.min(60,parseInt(k.target.value)||15))),min:5,max:60}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How long to reserve inventory in carts (5-60 minutes)"})]})]})]})]})}function nh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function xt({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 rh=Object.freeze(Object.defineProperty({__proto__:null,StorefrontSection:ql},Symbol.toStringTag,{value:"Module"})),wo=[{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"}],Xo=[{task:"site_chat",label:"Site Chat",description:"The conversational model that crafts responses to customer messages",defaultPrompt:`You are a friendly and helpful shopping assistant for our store. Your role is to:
4
-
5
- - Help customers find products that match their needs
6
- - Answer questions about products, shipping, returns, and store policies
7
- - Provide personalized recommendations based on customer preferences
8
- - Use the Product Searcher tool when customers are looking for specific items
9
-
10
- Guidelines:
11
- - Be warm, conversational, and concise
12
- - Stay focused on helping with shopping-related questions
13
- - If you don't know something specific about a product, say so honestly
14
- - Never make up product details, prices, or availability
15
- - For complex issues (order problems, refunds), direct customers to contact support`},{task:"product_searcher",label:"Product Searcher",description:"Tool used by Site Chat to find products based on customer queries",defaultPrompt:`You are a product search assistant. Given a customer's query, extract relevant search parameters to find matching products.
16
-
17
- Extract the following when present:
18
- - Keywords: Main search terms
19
- - Category: Product category or type
20
- - Price range: Min/max price if mentioned
21
- - Attributes: Color, size, material, brand, or other specifications
22
- - Sort preference: Price, popularity, newest, etc.
23
-
24
- Return structured search parameters. Be liberal in interpretation - if a customer says "something for my mom's birthday under $50" extract: keywords=gift, price_max=50, occasion=birthday.
25
-
26
- Do not make assumptions about specific products. Focus only on extracting search intent.`},{task:"related_product_finder",label:"Related Product Finder",description:"AI-powered recommendations for related products on product pages",defaultPrompt:`You are a product recommendation engine. Given a product, suggest related items that customers might also be interested in.
27
-
28
- Consider these recommendation types:
29
- - Complementary items: Products that go well together (e.g., phone case for a phone)
30
- - Similar alternatives: Products in the same category with different features or price points
31
- - Frequently bought together: Items commonly purchased as a set
32
- - Upsells: Premium versions or upgrades
33
-
34
- Guidelines:
35
- - Prioritize relevance over variety
36
- - Consider the product's category, price range, and use case
37
- - Return product IDs or search criteria for related items
38
- - Aim for 4-8 recommendations with a mix of types`},{task:"product_detail_assistant",label:"Product Detail Assistant",description:"Admin tool to generate product descriptions, suggest tags, and fill out product details",defaultPrompt:`You are a product copywriting assistant helping store administrators create compelling product listings.
39
-
40
- You can help with:
41
- - Writing engaging product descriptions that highlight key features and benefits
42
- - Suggesting relevant tags and categories for better discoverability
43
- - Creating SEO-friendly titles and meta descriptions
44
- - Generating bullet points for key features
45
- - Writing size guides or care instructions when applicable
46
-
47
- Guidelines:
48
- - Match the store's brand voice (ask if unclear)
49
- - Focus on benefits, not just features
50
- - Use sensory language when appropriate
51
- - Keep descriptions scannable with short paragraphs
52
- - Avoid superlatives and unverifiable claims
53
- - Include relevant keywords naturally for SEO`}],sh=[{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:Xo.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function Vl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=v.useState("api-keys"),[a,i]=v.useState(Ji),[c,l]=v.useState(!0),[d,m]=v.useState(!1),[u,p]=v.useState(null),[f,g]=v.useState(!1),h=v.useRef(null),[b,w]=v.useState({gemini:"",openai:""}),[y,_]=v.useState({gemini:!1,openai:!1});v.useEffect(()=>{async function k(){try{let P;if(r?.isAuthenticated())P=await r.fetchWithAuth("/admin/config/ai");else{const A={"Content-Type":"application/json"};t&&(A["X-API-Key"]=t);const L=await fetch(`${e}/admin/config/ai`,{headers:A});if(!L.ok)throw new Error(`Failed to fetch: ${L.status}`);P=await L.json()}P.settings&&i(P.settings)}catch{i(Ji)}finally{l(!1)}}k()},[e,t,r]);const j=v.useCallback(async k=>{const P=b[k];if(P.trim()){m(!0),p(null);try{const A={provider:k,apiKey:P};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(A)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:L,body:JSON.stringify(A)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(L=>({...L,apiKeys:L.apiKeys.map(z=>z.provider===k?{...z,isConfigured:!0,maskedKey:`${P.slice(0,4)}...${P.slice(-4)}`,updatedAt:new Date().toISOString()}:z)})),w(L=>({...L,[k]:""})),g(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>g(!1),3e3)}catch(A){p(A instanceof Error?A.message:"Failed to save API key")}finally{m(!1)}}},[b,e,t,r]),C=v.useCallback(async k=>{if(confirm(`Are you sure you want to delete the ${k==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),p(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${k}`,{method:"DELETE"});else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const A=await fetch(`${e}/admin/config/ai/api-key/${k}`,{method:"DELETE",headers:P});if(!A.ok)throw new Error(`Failed to delete: ${A.status}`)}i(P=>({...P,apiKeys:P.apiKeys.map(A=>A.provider===k?{provider:k,isConfigured:!1}:A)}))}catch(P){p(P instanceof Error?P.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),I=v.useCallback(async(k,P)=>{m(!0),p(null);try{const A={task:k,model:P};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(A)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:L,body:JSON.stringify(A)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(L=>({...L,taskAssignments:L.taskAssignments.map(z=>z.task===k?{...z,assignedModel:P}:z)})),g(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>g(!1),3e3)}catch(A){p(A instanceof Error?A.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),S=v.useCallback(k=>{if(k==="not_set")return!0;const P=wo.find(L=>L.id===k);return P?.provider?a.apiKeys.find(L=>L.provider===P.provider)?.isConfigured??!1:!0},[a.apiKeys]),N=v.useMemo(()=>wo.map(k=>{const P=S(k.id);return{value:k.id,label:P?k.label:`${k.label} (API key required)`,disabled:!P}}),[S]),$=v.useCallback(async(k,P)=>{m(!0),p(null);try{const A={task:k,systemPrompt:P};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(A)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:L,body:JSON.stringify(A)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(L=>({...L,taskAssignments:L.taskAssignments.map(z=>z.task===k?{...z,systemPrompt:P}:z)})),g(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>g(!1),3e3)}catch(A){p(A instanceof Error?A.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return v.useEffect(()=>()=>{h.current&&clearTimeout(h.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),f&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[G.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:sh.map(k=>{const P=a.apiKeys.find(L=>L.provider===k.id),A=P?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:k.label}),A&&P?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",P.maskedKey,P.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(P.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${A?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:A?"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:y[k.id]?"text":"password",className:"cedros-admin__input",placeholder:A?"Enter new key to replace":k.placeholder,value:b[k.id],onChange:L=>w(z=>({...z,[k.id]:L.target.value})),onBlur:()=>{b[k.id].trim()&&j(k.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>_(L=>({...L,[k.id]:!L[k.id]})),title:y[k.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:y[k.id]?G.eyeOff:G.eye}),A&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(k.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:G.trash})]})})]},k.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(k=>{const P=Xo.find(L=>L.task===k.task),A=wo.find(L=>L.id===k.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:P?.label??k.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:P?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ct,{value:k.assignedModel,onChange:L=>I(k.task,L),options:N,label:"",disabled:d,style:{flex:1,maxWidth:280}}),A&&A.provider&&n.jsx("span",{className:`cedros-admin__badge ${S(A.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:S(A.id)?"Ready":"Missing API Key"})]})]},k.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(k=>{const P=Xo.find(A=>A.task===k.task);return n.jsx(oh,{task:k.task,label:P?.label??k.task,description:P?.description??"",initialPrompt:k.systemPrompt??"",onSave:$},k.task)})})]})]})}function oh({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=v.useState(s),[c,l]=v.useState("idle"),d=v.useRef(null),m=v.useRef(null),u=v.useRef(!0);return v.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]),v.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(ah,{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 ah({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const ih=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:Vl},Symbol.toStringTag,{value:"Module"}));function Vn({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(Vn,{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(Vn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(Vn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(Vn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(Vn,{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(Vn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function Hl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=v.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 ch=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:Hl},Symbol.toStringTag,{value:"Module"})),jo={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]=v.useState("messages"),[a,i]=v.useState(jo),[c,l]=v.useState(!0),[d,m]=v.useState(!0),[u,p]=v.useState(new Set),f=v.useCallback(async()=>{try{let y;const _="/admin/config/messaging";if(r?.isAuthenticated())y=await r.fetchWithAuth(_);else{const j={"Content-Type":"application/json"};t&&(j["X-API-Key"]=t);const C=await fetch(`${e}${_}`,{headers:j});if(!C.ok)throw new Error(`Failed to fetch: ${C.status}`);y=await C.json()}i({...jo,...y.config})}catch{i(jo)}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);v.useEffect(()=>{f()},[f]);const g=v.useCallback(async y=>{const _="/admin/config/messaging",j={...y};u.has("smtp_password")||delete j.smtp_password,u.has("webhook_secret")||delete j.webhook_secret;const C=JSON.stringify({config:j});try{if(r?.isAuthenticated())await r.fetchWithAuth(_,{method:"PUT",body:C});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const S=await fetch(`${e}${_}`,{method:"PUT",headers:I,body:C});if(!S.ok)throw new Error(`Failed to save: ${S.status}`)}}catch{}},[e,t,r,u]),{status:h,error:b}=Ta({data:a,onSave:g,debounceMs:1500,enabled:!d}),w=(y,_)=>{(y==="smtp_password"||y==="webhook_secret")&&p(j=>new Set(j).add(y)),i(j=>({...j,[y]:_}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[G.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(lh,{status:h,error:b})]}),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:()=>w("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:()=>w("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:y=>w("smtp_host",y.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:y=>w("smtp_port",parseInt(y.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:y=>w("smtp_username",y.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:u.has("smtp_password")?a.smtp_password:"",onChange:y=>w("smtp_password",y.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:y=>w("from_email",y.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:y=>w("from_name",y.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:y=>w("webhook_url",y.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:u.has("webhook_secret")?a.webhook_secret:"",onChange:y=>w("webhook_secret",y.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:y=>w("webhook_timeout",parseInt(y.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function lh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function 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 dh=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:Zl},Symbol.toStringTag,{value:"Module"}));function Jo(e){return!e||typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function Gl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=v.useState([]),[i,c]=v.useState(!0),[l,d]=v.useState(!1),[m,u]=v.useState(null),[p,f]=v.useState(!1),[g,h]=v.useState(""),[b,w]=v.useState("all"),[y,_]=v.useState(null),[j,C]=v.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),I=v.useCallback(async()=>{c(!0);try{let O;const T=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())O=await s.fetchWithAuth(T);else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const E=await fetch(`${e}${T}`,{headers:W});if(!E.ok)throw new Error(`Failed to fetch FAQs: ${E.status}`);O=await E.json()}a(O.faqs||[])}catch{a([{id:"faq_1",question:"What is your return policy?",answer:"We accept returns within 30 days of purchase. Items must be unused and in original packaging.",keywords:["returns","refund","policy"],active:!0,useInChat:!0,displayOnPage:!0,createdAt:"2026-01-15T10:00:00Z"},{id:"faq_2",question:"How long does shipping take?",answer:"Standard shipping takes 5-7 business days. Express shipping is available for 2-3 day delivery.",keywords:["shipping","delivery","time"],active:!0,useInChat:!0,displayOnPage:!0,createdAt:"2026-01-16T10:00:00Z"},{id:"faq_3",question:"Do you ship internationally?",answer:"Yes, we ship to most countries. International shipping typically takes 10-14 business days.",keywords:["international","shipping","global"],active:!1,useInChat:!0,displayOnPage:!1,createdAt:"2026-01-17T10:00:00Z"}])}finally{c(!1)}},[e,t,r,s]);v.useEffect(()=>{I()},[I]);const S=async O=>{if(O.preventDefault(),!(!j.question.trim()||!j.answer.trim())){f(!0);try{const T=j.keywordsCsv.split(",").map(E=>E.trim().toLowerCase()).filter(Boolean),W={question:j.question.trim(),answer:j.answer.trim(),keywords:T,active:j.active,useInChat:j.useInChat,displayOnPage:j.displayOnPage};if(m){const E=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(E,{method:"PUT",body:JSON.stringify(W)});else{const q={"Content-Type":"application/json"};t&&(q["X-API-Key"]=t);const ne=await fetch(`${e}${E}`,{method:"PUT",headers:q,body:JSON.stringify(W)});if(!ne.ok)throw new Error(`Failed to update FAQ: ${ne.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(W)});else{const E={"Content-Type":"application/json"};t&&(E["X-API-Key"]=t);const q=await fetch(`${e}/admin/faqs`,{method:"POST",headers:E,body:JSON.stringify(W)});if(!q.ok)throw new Error(`Failed to create FAQ: ${q.status}`)}k(),I()}catch{a(m?T=>T.map(W=>W.id===m.id?{...W,question:j.question.trim(),answer:j.answer.trim(),keywords:Jo(j.keywordsCsv).map(E=>E.toLowerCase()),active:j.active,useInChat:j.useInChat,displayOnPage:j.displayOnPage,updatedAt:new Date().toISOString()}:W):T=>[...T,{id:`faq_${Date.now()}`,question:j.question.trim(),answer:j.answer.trim(),keywords:Jo(j.keywordsCsv).map(W=>W.toLowerCase()),active:j.active,useInChat:j.useInChat,displayOnPage:j.displayOnPage,createdAt:new Date().toISOString()}]),k()}finally{f(!1)}}},N=async O=>{try{const T=`/admin/faqs/${O}`;if(s?.isAuthenticated())await s.fetchWithAuth(T,{method:"DELETE"});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const E=await fetch(`${e}${T}`,{method:"DELETE",headers:W});if(!E.ok)throw new Error(`Failed to delete FAQ: ${E.status}`)}I()}catch{a(T=>T.filter(W=>W.id!==O))}_(null)},$=async O=>{try{const T=`/admin/faqs/${O.id}`,W={...O,active:!O.active};if(s?.isAuthenticated())await s.fetchWithAuth(T,{method:"PUT",body:JSON.stringify(W)});else{const E={"Content-Type":"application/json"};t&&(E["X-API-Key"]=t);const q=await fetch(`${e}${T}`,{method:"PUT",headers:E,body:JSON.stringify(W)});if(!q.ok)throw new Error(`Failed to update FAQ: ${q.status}`)}I()}catch{a(T=>T.map(W=>W.id===O.id?{...W,active:!W.active}:W))}},k=()=>{C({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},P=O=>{C({question:O.question,answer:O.answer,keywordsCsv:O.keywords.join(", "),active:O.active,useInChat:O.useInChat??!0,displayOnPage:O.displayOnPage??!0}),u(O),d(!0)},A=o.length,L=o.filter(O=>O.active).length,z=o.filter(O=>O.active&&O.useInChat).length,D=o.filter(O=>O.active&&O.displayOnPage).length,R=v.useMemo(()=>o.filter(O=>{if(b==="active"&&!O.active||b==="inactive"&&O.active)return!1;if(g){const T=g.toLowerCase();return O.question.toLowerCase().includes(T)||O.answer.toLowerCase().includes(T)||O.keywords.some(W=>W.includes(T))}return!0}),[o,b,g]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(rr,{stats:[{label:"Total FAQs",value:A},{label:"Active",value:L,variant:"success"},{label:"In Chat",value:z},{label:"On Page",value:D}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__btn cedros-admin__btn--primary",onClick:()=>{k(),d(!0)},children:[G.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:g,onChange:O=>h(O.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:b,onChange:O=>w(O.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:S,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__btn--icon",onClick:k,children:G.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:j.question,onChange:O=>C(T=>({...T,question:O.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:j.answer,onChange:O=>C(T=>({...T,answer:O.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:j.keywordsCsv,onChange:O=>C(T=>({...T,keywordsCsv:O.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:j.active,onChange:O=>C(T=>({...T,active:O.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:j.useInChat,onChange:O=>C(T=>({...T,useInChat:O.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:j.displayOnPage,onChange:O=>C(T=>({...T,displayOnPage:O.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__btn",onClick:k,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__btn cedros-admin__btn--primary",disabled:p||!j.question.trim()||!j.answer.trim(),children:p?G.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading,n.jsx("span",{children:"Loading FAQs..."})]}):R.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:g||b!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:R.map(O=>n.jsxs("div",{className:`cedros-admin__faq-item ${O.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 ${O.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),O.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:O.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[O.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:O.keywords.map(T=>n.jsx("span",{className:"cedros-admin__tag",children:T},T))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[O.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[G.chat," Chat"]}),O.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[G.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>$(O),title:O.active?"Deactivate":"Activate",children:O.active?G.eyeOff:G.eye}),n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>P(O),title:"Edit",children:G.edit}),n.jsx("button",{className:"cedros-admin__btn--icon cedros-admin__btn--danger",onClick:()=>_(O.id),title:"Delete",children:G.trash})]}),y===O.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:()=>_(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__btn cedros-admin__btn--danger",onClick:()=>N(O.id),children:"Delete"})]})]})})]},O.id))})]})]})}const uh=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:Gl},Symbol.toStringTag,{value:"Module"}));class mh{serverUrl;walletSigner=null;jwtToken=null;isAdmin=!1;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdmin?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,Y.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,this.isAdmin=r,Y.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t,isAdmin:r})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=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`;Y.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await Y.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 Y.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 ph({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=ja.useWallet(),o=v.useMemo(()=>new mh(e),[e]);v.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]),v.useEffect(()=>{o.setCedrosLoginAuth(t??null,r)},[o,t,r]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!(t&&r),d=v.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=v.useCallback((u,p)=>o.fetchWithAuth(u,p),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const Ql=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:G.transactions},{id:"products",label:"Products",icon:G.products},{id:"subscriptions",label:"Subscriptions",icon:G.calendarRepeat},{id:"coupons",label:"Coupons",icon:G.coupons},{id:"refunds",label:"Refunds",icon:G.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:G.storefront},{id:"ai-settings",label:"Store AI",icon:G.brain},{id:"faqs",label:"Knowledge Base",icon:G.faq},{id:"payment-settings",label:"Payment Options",icon:G.creditCard},{id:"messaging",label:"Store Messages",icon:G.mail},{id:"settings",label:"Store Server",icon:G.server}]}],fh=Ql.flatMap(e=>e.sections);function hh(){const[e,t]=v.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return v.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 gh(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,f]=v.useState(o),[g,h]=v.useState(!0),[b,w]=v.useState(new Set),y=v.useCallback(P=>{w(A=>{const L=new Set(A);return L.has(P)?L.delete(P):L.add(P),L})},[]),_=Y.useCedrosThemeOptional(),j=hh(),I=gh(u,_?.mode??null,j)==="dark"?"cedros-admin--dark":"",{authManager:S}=ph({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),N=v.useCallback(P=>{f(P),c?.(P)},[c]),k=fh.filter(P=>s.includes(P.id)).find(P=>P.id===p);return v.useEffect(()=>{const P=setTimeout(()=>h(!1),500);return()=>clearTimeout(P)},[]),g?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${I} ${l}`,children:[G.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${I} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[G.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:Ql.map(P=>{const A=P.sections.filter(z=>s.includes(z.id));if(A.length===0)return null;const L=P.collapsible&&b.has(P.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[P.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>y(P.label),"aria-expanded":!L,children:[P.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${L?"":"cedros-admin__nav-label-icon--expanded"}`,children:G.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:P.label}),!L&&A.map(z=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${p===z.id?"cedros-admin__nav-item--active":""}`,onClick:()=>N(z.id),"aria-current":p===z.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:z.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:z.label})]},z.id))]},P.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:G.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:k?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[p==="products"&&n.jsx(Ll,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),p==="subscriptions"&&n.jsx(Wl,{serverUrl:e,apiKey:t,authManager:S}),p==="transactions"&&n.jsx($l,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),p==="coupons"&&n.jsx(zl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),p==="refunds"&&n.jsx(Fl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),p==="storefront"&&n.jsx(ql,{serverUrl:e,apiKey:t,authManager:S}),p==="ai-settings"&&n.jsx(Vl,{serverUrl:e,apiKey:t,authManager:S}),p==="faqs"&&n.jsx(Gl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),p==="payment-settings"&&n.jsx(Hl,{serverUrl:e,apiKey:t,authManager:S}),p==="messaging"&&n.jsx(Zl,{serverUrl:e,apiKey:t,authManager:S}),p==="settings"&&n.jsx(Ia,{serverUrl:e,apiKey:t,authManager:S})]})]})]})}const Nt=e=>v.lazy(async()=>{const s=(await e()).default;return{default:({pluginContext:a})=>{const i={serverUrl:a.serverUrl};return n.jsx(s,{...i})}}}),xh={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:G.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:G.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:G.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:G.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:G.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:G.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:G.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:G.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:G.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:G.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:G.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:Nt(()=>Promise.resolve().then(()=>require("./sections-DT8Vsm7s.js")).then(e=>({default:e.ProductsSection}))),subscriptions:Nt(()=>Promise.resolve().then(()=>Jf).then(e=>({default:e.SubscriptionsSection}))),transactions:Nt(()=>Promise.resolve().then(()=>require("./sections-DT8Vsm7s.js")).then(e=>({default:e.TransactionsSection}))),coupons:Nt(()=>Promise.resolve().then(()=>require("./sections-DT8Vsm7s.js")).then(e=>({default:e.CouponsSection}))),refunds:Nt(()=>Promise.resolve().then(()=>require("./sections-DT8Vsm7s.js")).then(e=>({default:e.RefundsSection}))),storefront:Nt(()=>Promise.resolve().then(()=>rh).then(e=>({default:e.StorefrontSection}))),"ai-settings":Nt(()=>Promise.resolve().then(()=>ih).then(e=>({default:e.AISettingsSection}))),faqs:Nt(()=>Promise.resolve().then(()=>uh).then(e=>({default:e.FAQSection}))),"payment-settings":Nt(()=>Promise.resolve().then(()=>ch).then(e=>({default:e.PaymentSettingsSection}))),messaging:Nt(()=>Promise.resolve().then(()=>dh).then(e=>({default:e.MessagingSection}))),settings:Nt(()=>Promise.resolve().then(()=>Yf).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 bh({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 Yl(){const{subscriptionManager:e}=Y.useCedrosContext(),[t,r]=v.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=v.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=v.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=v.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=v.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:f,className:g=""}){const{status:h,error:b,sessionId:w,processSubscription:y}=Yl(),_=Y.useCedrosTheme(),{t:j,translations:C}=hn(),I=d||j("ui.subscribe"),S=_.unstyled?g:`${_.className} cedros-theme__stripe-button ${g}`.trim(),N=b&&typeof b!="string"?b?.code??null:null,k=b?typeof b=="string"?b:(R=>{if(!R||!C)return"";const O=C.errors[R];return O?O.action?`${O.message} ${O.action}`:O.message:""})(N):null,P=v.useCallback(async()=>{Y.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),Mn("stripe",e),u&&u("stripe"),ln("stripe",e);const R=await y({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});R.success&&R.transactionId?(Dn("stripe",R.transactionId,e),p&&p(R.transactionId)):!R.success&&R.error&&(jt("stripe",R.error,e),f&&f(R.error))},[e,t,r,s,c,i,l,o,a,y,u,p,f]),A=v.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),L=v.useMemo(()=>Rn(A,P),[A,P]),z=h==="loading",D=m||z;return n.jsxs("div",{className:S,style:_.unstyled?{}:_.style,children:[n.jsx("button",{onClick:L,disabled:D,className:_.unstyled?g:"cedros-theme__button cedros-theme__stripe",type:"button",children:z?j("ui.processing"):I}),k&&n.jsx("div",{className:_.unstyled?"":"cedros-theme__error",children:k}),w&&n.jsx("div",{className:_.unstyled?"":"cedros-theme__success",children:j("ui.redirecting_to_checkout")})]})}function Kl(){const{subscriptionManager:e,creditsManager:t}=Y.useCedrosContext(),[r,s]=v.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=v.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=Y.formatError(m,"Failed to check subscription status");return s(p=>({...p,status:"error",error:u})),null}},[e]),a=v.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=Y.formatError(u,"Failed to get subscription quote");return s(f=>({...f,status:"error",error:p})),null}},[t]),i=v.useCallback(async(l,d,m,u)=>{if(!m){const p="Authentication required for credits payment";return s(f=>({...f,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(f=>({...f,status:"error",error:p.error||"Credits subscription payment failed"})),p}catch(p){const f=Y.formatError(p,"Credits subscription payment failed");return s(g=>({...g,status:"error",error:f})),{success:!1,error:f}}},[t]),c=v.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 wh({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:f=!1}){const{status:g,error:h,subscriptionStatus:b,expiresAt:w,checkStatus:y,processPayment:_}=Kl(),j=Y.useCedrosTheme(),{t:C,translations:I}=hn(),S=v.useRef(y);v.useEffect(()=>{S.current=y},[y]),v.useEffect(()=>{f&&o&&(Y.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),S.current(e,o))},[f,o,e]);const N=i||C("ui.subscribe_with_credits")||"Subscribe with Credits",$=h&&typeof h!="string"?h?.code??null:null,P=h?typeof h=="string"?h:(E=>{if(!E||!I)return"";const q=I.errors[E];return q?q.action?`${q.message} ${q.action}`:q.message:""})($):null,A=v.useCallback(async()=>{if(Y.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),Mn("credits",e),l&&l("credits"),!s){const q="Authentication required: please log in to subscribe with credits";Y.getLogger().error("[CreditsSubscribeButton]",q),jt("credits",q,e),m&&m(q);return}ln("credits",e);const E=await _(e,t,s,{couponCode:a,intervalDays:r});E.success&&E.transactionId?(Dn("credits",E.transactionId,e),d&&d(E.transactionId)):!E.success&&E.error&&(jt("credits",E.error,e),m&&m(E.error))},[e,t,r,s,a,_,l,d,m]),L=v.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),z=v.useMemo(()=>Rn(L,A,{cooldownMs:200,deduplicationWindowMs:0}),[L,A]),D=g==="loading"||g==="checking",R=b==="active"||b==="trialing",O=c||D||R;let T=N;if(D)T=C("ui.processing");else if(R&&w){const E=new Date(w).toLocaleDateString();T=`${C("ui.subscribed_until")} ${E}`}else R&&(T=C("ui.subscribed"));const W=j.unstyled?u:`${j.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:W,style:j.unstyled?{}:j.style,children:[n.jsx("button",{onClick:z,disabled:O,className:j.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:T}),!p&&P&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__error",children:P}),!p&&R&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__success",children:C("ui.subscription_active")})]})}function Xl(){const{subscriptionChangeManager:e}=Y.useCedrosContext(),[t,r]=v.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=v.useRef(t);s.current=t;const o=v.useCallback(async(u,p)=>{r(f=>({...f,status:"loading",error:null}));try{const f=await e.getDetails(u,p);return r(g=>({...g,status:"success",subscription:f,userId:p})),f}catch(f){const g=f instanceof Error?f.message:"Failed to load subscription";return r(h=>({...h,status:"error",error:g})),null}},[e]),a=v.useCallback(async(u,p,f,g)=>{r(h=>({...h,status:"loading",error:null}));try{const h={currentResource:u,newResource:p,userId:f,newInterval:g},b=await e.previewChange(h);return r(w=>({...w,status:"idle",changePreview:b})),b}catch(h){const b=h instanceof Error?h.message:"Failed to preview change";return r(w=>({...w,status:"error",error:b})),null}},[e]),i=v.useCallback(async u=>{const{subscription:p,userId:f}=s.current;if(!p||!f)return r(g=>({...g,status:"error",error:"No subscription loaded"})),null;r(g=>({...g,status:"loading",error:null}));try{const g={currentResource:p.resource,newResource:u.newResource,userId:f,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},h=await e.changeSubscription(g);return h.success?r(b=>({...b,status:"success",subscription:b.subscription?{...b.subscription,resource:h.newResource,interval:h.newInterval,status:h.status}:null,changePreview:null})):r(b=>({...b,status:"error",error:h.error||"Failed to change subscription"})),h}catch(g){const h=g instanceof Error?g.message:"Failed to change subscription";return r(b=>({...b,status:"error",error:h})),null}},[e]),c=v.useCallback(async u=>{const{subscription:p,userId:f}=s.current;if(!p||!f)return r(g=>({...g,status:"error",error:"No subscription loaded"})),null;r(g=>({...g,status:"loading",error:null}));try{const g={resource:p.resource,userId:f,immediate:u},h=await e.cancel(g);if(h.success){const b=u?"canceled":p.status;r(w=>({...w,status:"success",subscription:w.subscription?{...w.subscription,status:b,cancelAtPeriodEnd:!u}:null}))}else r(b=>({...b,status:"error",error:h.error||"Failed to cancel subscription"}));return h}catch(g){const h=g instanceof Error?g.message:"Failed to cancel subscription";return r(b=>({...b,status:"error",error:h})),null}},[e]),l=v.useCallback(async(u,p)=>{r(f=>({...f,status:"loading",error:null}));try{const f=await e.getBillingPortalUrl({userId:u,returnUrl:p});return window.location.href=f.url,f}catch(f){const g=f instanceof Error?f.message:"Failed to open billing portal";return r(h=>({...h,status:"error",error:g})),null}},[e]),d=v.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=v.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 jh={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"},kh={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 Sh(e){const t=e?kh:jh;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 Sn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function Jl(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function Ch(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 Nh({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:[Sn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[Sn(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:["-",Sn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:Sn(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:Sn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:Jl(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 Ph({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=Y.useCedrosTheme(),m=v.useMemo(()=>Sh(d==="dark"),[d]),{subscription:u,changePreview:p,status:f,error:g,loadSubscription:h,previewChange:b,changeSubscription:w,cancelSubscription:y,openBillingPortal:_,clearPreview:j}=Xl();v.useEffect(()=>{h(e,t)},[e,t,h]);const C=v.useCallback(async(k,P)=>{await b(e,k,t,P)},[e,t,b]),I=v.useCallback(async()=>{if(!p)return;const k=r.find(A=>A.price===p.newPlanPrice&&A.currency===p.currency);(await w({newResource:k?.resource||e,newInterval:k?.interval,immediate:!0}))?.success&&k&&s?.(k.resource,k.interval)},[p,r,e,w,s]),S=v.useCallback(async k=>{(await y(k))?.success&&o?.()},[y,o]),N=v.useCallback(()=>{_(t,a)},[t,a,_]),$=f==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[g&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:g}),$&&!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:Ch(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:[Sn(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:Jl(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),p&&n.jsx(Nh,{preview:p,onConfirm:I,onCancel:j,isLoading:$,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(k=>{const P=k.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...P?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:k.name}),n.jsxs("div",{style:m.planPrice,children:[Sn(k.price,k.currency),"/",k.interval]}),k.description&&n.jsx("div",{style:m.planDescription,children:k.description}),P?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>C(k.resource,k.interval),style:m.changePlanButton,disabled:$,children:k.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},k.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:N,style:m.portalButton,disabled:$,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>S(!1),style:m.cancelSubscriptionButton,disabled:$,children:"Cancel Subscription"})]})]})]})}function Ah(){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 Eh(){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 Th(){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 Ih(){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 Rh(){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 Oh(){const e=[Ah(),Eh(),Th(),Ih(),Rh()],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 Mh(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 Dh={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=v.createContext(null);function De(){const e=v.useContext(Ra);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function Oa(){return v.useContext(Ra)}function Lh({config:e,children:t}){return n.jsx(Ra.Provider,{value:{config:e},children:t})}function Pt(e){return new Promise(t=>setTimeout(t,e))}const ed=[{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."}],fs=[{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 ko=[];const Wr={};function $h(e,t){let r=e;if(t.category&&t.category!=="all"){const l=ed.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 zh(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 Fh(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 Bh(e){const t=new Date().toISOString(),r=e.cart.map(o=>{const a=fs.find(i=>i.id===o.resource||i.slug===o.resource)??fs[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 Uh(){return{async listProducts(e){await Pt(150);const t=e.page??1,r=e.pageSize??24,s=$h(fs,e),o=zh(s,e.sort);return Fh(o,t,r)},async getProductBySlug(e){return await Pt(100),fs.find(t=>t.slug===e)??null},async listCategories(){return await Pt(80),ed},async getOrderHistory(){return await Pt(120),ko},async getCart({customerId:e}){return await Pt(80),Wr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await Pt(120);const r=Wr[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 Wr[e]=a,a},async updateCart({customerId:e,cart:t}){await Pt(60),Wr[e]=t},async createCheckoutSession(e){await Pt(250);const t=Bh(e);if(ko=[t,...ko].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 Pt(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 Pt(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await Pt(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function td(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Wh(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 Vh(e){if(e&&(e==="physical"||e==="digital"))return e}function Hh(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=Wh(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=Hh(a);return{id:e.id,slug:e.slug??e.id,title:e.title??td(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:Vh(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function So(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 Jt(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 Zh(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,p=(d-1)*m,f=new URLSearchParams;f.set("limit",String(u)),f.set("offset",String(p)),l.search&&f.set("search",l.search),l.category&&f.set("category",l.category),l.sort&&f.set("sort",l.sort),l.filters?.inStock&&f.set("in_stock","true"),l.filters?.minPrice!=null&&f.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&f.set("max_price",String(l.filters.maxPrice));const g=l.filters?.tags,h=Array.isArray(g)?g:typeof g=="string"?[g]:[];h.length&&f.set("tags",h.join(","));const b=await Jt(e.serverUrl,`/paywall/v1/products?${f.toString()}`,e.apiKey),{products:w,total:y}=So(b);return{items:w.map(qr),page:d,pageSize:m,total:y,hasNextPage:typeof y=="number"?p+u<y:w.length===u}},getProductBySlug:async l=>{try{const d=await Jt(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 Jt(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 f=await Jt(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:g}=So(f),h=g.find(b=>b.slug===l||b.id===l);return h?qr(h):null}}},listCategories:async()=>{const l=await Jt(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=So(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:td(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await Jt(e.serverUrl,"/admin/config/storefront",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([Jt(e.serverUrl,"/admin/config/stripe",e.apiKey),Jt(e.serverUrl,"/admin/config/x402",e.apiKey),Jt(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,f=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:p,credits:f}}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 Gh(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function jn(e){return`${e.productId}::${e.variantId??""}`}const Qh={items:[]};function Yh(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=jn(t.item);return e.items.find(a=>jn(a)===s)?{...e,items:e.items.map(a=>jn(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=>jn(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=>jn(o)!==s)}:{...e,items:e.items.map(o=>jn(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=>jn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return Gh(t)}}function Kh(e){return e.reduce((t,r)=>t+r.qty,0)}function Xh(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 Jh(e,t){try{const r=e.getItem(t);return r?JSON.parse(r):null}catch{return null}}function eg(e,t,r){try{e.setItem(t,JSON.stringify(r))}catch{}}const nd=v.createContext(null);function Mt(){const e=v.useContext(nd);if(!e)throw new Error("useCart must be used within CartProvider");return e}function tg({children:e}){const{config:t}=De(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=v.useReducer(Yh,Qh),[d,m]=v.useState(!1),u=v.useRef(!1),p=v.useRef(null);v.useEffect(()=>{const b=nc();if(!b)return;const w=Jh(b,r);w&&Array.isArray(w.items)&&l({type:"cart/hydrate",state:w}),m(!0)},[r]),v.useEffect(()=>{const b=nc();b&&eg(b,r,c)},[c,r]),v.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const b=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});b&&Array.isArray(b.items)&&(l({type:"cart/hydrate",state:b}),p.current=JSON.stringify(b))}catch{}})()))},[t.adapter,s,d,o,c]),v.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const b=JSON.stringify(c);if(p.current===b)return;const w=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{p.current=b}).catch(()=>{})},a);return()=>window.clearTimeout(w)},[t.adapter,s,d,o,c,a]);const f=v.useCallback((b,w)=>{const y=c.items.find(_=>_.productId===b&&_.variantId===w);if(y)return{holdId:y.holdId,expiresAt:y.holdExpiresAt}},[c.items]),g=v.useCallback((b,w,y)=>{l({type:"cart/updateHold",productId:b,variantId:w,holdExpiresAt:y})},[]),h=v.useMemo(()=>{const b=Kh(c.items),w=Xh(c.items);return{items:c.items,promoCode:c.promoCode,count:b,subtotal:w,addItem:(y,_)=>l({type:"cart/add",item:y,qty:_}),removeItem:(y,_)=>l({type:"cart/remove",productId:y,variantId:_}),setQty:(y,_,j)=>l({type:"cart/setQty",productId:y,variantId:_,qty:j}),clear:()=>l({type:"cart/clear"}),setPromoCode:y=>l({type:"cart/setPromoCode",promoCode:y}),holdsSupported:i,getItemHold:f,updateItemHold:g}},[c.items,c.promoCode,i,f,g]);return n.jsx(nd.Provider,{value:h,children:e})}function Z(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const 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 rd extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const sd={};function Nn(e){return sd}function od(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 ng(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 Se(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 Ln(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function gn(...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 rg(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ad="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function hs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const sg=Ma(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Nr(e){if(hs(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(hs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function id(e){return Nr(e)?{...e}:Array.isArray(e)?[...e]:e}const og=new Set(["string","number","symbol"]);function Rs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function ue(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ag(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const ig={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 cg(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=gn(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 Ln(this,"shape",i),i},checks:[]});return yn(e,a)}function lg(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=gn(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 Ln(this,"shape",i),i},checks:[]});return yn(e,a)}function dg(e,t){if(!Nr(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=gn(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Ln(this,"shape",a),a}});return yn(e,o)}function ug(e,t){if(!Nr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=gn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return Ln(this,"shape",s),s}});return yn(e,r)}function mg(e,t){const r=gn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return Ln(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return yn(e,r)}function pg(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=gn(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 Ln(this,"shape",l),l},checks:[]});return yn(t,i)}function fg(e,t,r){const s=gn(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 Ln(this,"shape",a),a}});return yn(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 cd(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Vr(e){return typeof e=="string"?e:e?.message}function Pn(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Vr(e.inst?._zod.def?.error?.(e))??Vr(t?.error?.(e))??Vr(r.customError?.(e))??Vr(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 Pr(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const ld=(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})},dd=Z("$ZodError",ld),ud=Z("$ZodError",ld,{Parent:Error});function hg(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 gg(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=>Pn(l,a,Nn())));throw ad(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=>Pn(l,a,Nn())));throw ad(c,o?.callee),c}return i.value},Os=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??dd)(a.issues.map(i=>Pn(i,o,Nn())))}:{success:!0,data:a.value}},yg=Os(ud),Ms=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=>Pn(i,o,Nn())))}:{success:!0,data:a.value}},xg=Ms(ud),vg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return za(e)(t,r,o)},bg=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)},wg=e=>async(t,r,s)=>Fa(e)(t,r,s),jg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Os(e)(t,r,o)},kg=e=>(t,r,s)=>Os(e)(t,r,s),Sg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ms(e)(t,r,o)},Cg=e=>async(t,r,s)=>Ms(e)(t,r,s),Ng=/^[cC][^\s-]{8,}$/,Pg=/^[0-9a-z]+$/,Ag=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Eg=/^[0-9a-vA-V]{20}$/,Tg=/^[A-Za-z0-9]{27}$/,Ig=/^[a-zA-Z0-9_-]{21}$/,Rg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Og=/^([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)$/,Mg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Dg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Lg(){return new RegExp(Dg,"u")}const $g=/^(?:(?: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])$/,zg=/^(([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}|:))$/,Fg=/^((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])$/,Bg=/^(([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])$/,Ug=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,md=/^[A-Za-z0-9_-]*$/,Wg=/^\+[1-9]\d{6,14}$/,pd="(?:(?:\\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(`^${pd}$`);function fd(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 Vg(e){return new RegExp(`^${fd(e)}$`)}function Hg(e){const t=fd({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(`^${pd}T(?:${s})$`)}const Zg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Gg=/^-?\d+$/,Qg=/^-?\d+(?:\.\d+)?$/,Yg=/^[^A-Z]*$/,Kg=/^[^a-z]*$/,ht=Z("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),hd={number:"number",bigint:"bigint",object:"date"},gd=Z("$ZodCheckLessThan",(e,t)=>{ht.init(e,t);const r=hd[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=Z("$ZodCheckGreaterThan",(e,t)=>{ht.init(e,t);const r=hd[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})}}),Xg=Z("$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):ng(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})}}),Jg=Z("$ZodCheckNumberFormat",(e,t)=>{ht.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=ig[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=Gg)}),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})}}),ey=Z("$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})}}),ty=Z("$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})}}),ny=Z("$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})}}),Ds=Z("$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=()=>{})}),ry=Z("$ZodCheckRegex",(e,t)=>{Ds.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})}}),sy=Z("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Yg),Ds.init(e,t)}),oy=Z("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Kg),Ds.init(e,t)}),ay=Z("$ZodCheckIncludes",(e,t)=>{ht.init(e,t);const r=Rs(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})}}),iy=Z("$ZodCheckStartsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`^${Rs(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})}}),cy=Z("$ZodCheckEndsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`.*${Rs(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})}}),ly=Z("$ZodCheckOverwrite",(e,t)=>{ht.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class dy{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
54
- `).filter(i=>i),o=Math.min(...s.map(i=>i.length-i.trimStart().length)),a=s.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...r,o.join(`
55
- `))}}const uy={major:4,minor:3,patch:6},qe=Z("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=uy;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,f=u._zod.check(i);if(f instanceof Promise&&l?.async===!1)throw new Kn;if(m||f instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await f,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)}}Se(e,"~standard",()=>({validate:o=>{try{const a=yg(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return xg(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ba=Z("$ZodString",(e,t)=>{qe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Zg(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}}),Ie=Z("$ZodStringFormat",(e,t)=>{Ds.init(e,t),Ba.init(e,t)}),my=Z("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Og),Ie.init(e,t)}),py=Z("$ZodUUID",(e,t)=>{if(t.version){const s={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(s===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=oc(s))}else t.pattern??(t.pattern=oc());Ie.init(e,t)}),fy=Z("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Mg),Ie.init(e,t)}),hy=Z("$ZodURL",(e,t)=>{Ie.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})}}}),gy=Z("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Lg()),Ie.init(e,t)}),yy=Z("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ig),Ie.init(e,t)}),xy=Z("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ng),Ie.init(e,t)}),vy=Z("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Pg),Ie.init(e,t)}),by=Z("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ag),Ie.init(e,t)}),_y=Z("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Eg),Ie.init(e,t)}),wy=Z("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Tg),Ie.init(e,t)}),jy=Z("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Hg(t)),Ie.init(e,t)}),ky=Z("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=qg),Ie.init(e,t)}),Sy=Z("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Vg(t)),Ie.init(e,t)}),Cy=Z("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Rg),Ie.init(e,t)}),Ny=Z("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=$g),Ie.init(e,t),e._zod.bag.format="ipv4"}),Py=Z("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=zg),Ie.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})}}}),Ay=Z("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Fg),Ie.init(e,t)}),Ey=Z("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Bg),Ie.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 xd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Ty=Z("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ug),Ie.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{xd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Iy(e){if(!md.test(e))return!1;const t=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return xd(r)}const Ry=Z("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=md),Ie.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{Iy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Oy=Z("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Wg),Ie.init(e,t)});function My(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 Dy=Z("$ZodJWT",(e,t)=>{Ie.init(e,t),e._zod.check=r=>{My(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),vd=Z("$ZodNumber",(e,t)=>{qe.init(e,t),e._zod.pattern=e._zod.bag.pattern??Qg,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}}),Ly=Z("$ZodNumberFormat",(e,t)=>{Jg.init(e,t),vd.init(e,t)}),$y=Z("$ZodUnknown",(e,t)=>{qe.init(e,t),e._zod.parse=r=>r}),zy=Z("$ZodNever",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function ac(e,t,r){e.issues.length&&t.issues.push(...cd(r,e.issues)),t.value[r]=e.value}const Fy=Z("$ZodArray",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const a=[];for(let i=0;i<o.length;i++){const c=o[i],l=t.element._zod.run({value:c,issues:[]},s);l instanceof Promise?a.push(l.then(d=>ac(d,r,i))):ac(l,r,i)}return a.length?Promise.all(a).then(()=>r):r}});function gs(e,t,r,s,o){if(e.issues.length){if(o&&!(r in s))return;t.issues.push(...cd(r,e.issues))}e.value===void 0?r in s&&(t.value[r]=void 0):t.value[r]=e.value}function bd(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=ag(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(f=>gs(f,r,u,t,m))):gs(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 By=Z("$ZodObject",(e,t)=>{if(qe.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}const s=Ma(()=>bd(t));Se(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=hs,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 f=u[p],g=f._zod.optout==="optional",h=f._zod.run({value:d[p],issues:[]},l);h instanceof Promise?m.push(h.then(b=>gs(b,c,p,d,g))):gs(h,c,p,d,g)}return a?_d(m,d,c,l,s.value,e):m.length?Promise.all(m).then(()=>c):c}}),Uy=Z("$ZodObjectJIT",(e,t)=>{By.init(e,t);const r=e._zod.parse,s=Ma(()=>bd(t)),o=p=>{const f=new dy(["shape","payload","ctx"]),g=s.value,h=_=>{const j=sc(_);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};f.write("const input = payload.value;");const b=Object.create(null);let w=0;for(const _ of g.keys)b[_]=`key_${w++}`;f.write("const newResult = {};");for(const _ of g.keys){const j=b[_],C=sc(_),S=p[_]?._zod?.optout==="optional";f.write(`const ${j} = ${h(_)};`),S?f.write(`
56
- if (${j}.issues.length) {
57
- if (${C} in input) {
58
- payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
59
- ...iss,
60
- path: iss.path ? [${C}, ...iss.path] : [${C}]
61
- })));
62
- }
63
- }
64
-
65
- if (${j}.value === undefined) {
66
- if (${C} in input) {
67
- newResult[${C}] = undefined;
68
- }
69
- } else {
70
- newResult[${C}] = ${j}.value;
71
- }
72
-
73
- `):f.write(`
74
- if (${j}.issues.length) {
75
- payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
76
- ...iss,
77
- path: iss.path ? [${C}, ...iss.path] : [${C}]
78
- })));
79
- }
80
-
81
- if (${j}.value === undefined) {
82
- if (${C} in input) {
83
- newResult[${C}] = undefined;
84
- }
85
- } else {
86
- newResult[${C}] = ${j}.value;
87
- }
88
-
89
- `)}f.write("payload.value = newResult;"),f.write("return payload;");const y=f.compile();return(_,j)=>y(p,_,j)};let a;const i=hs,c=!sd.jitless,d=c&&sg.value,m=t.catchall;let u;e._zod.parse=(p,f)=>{u??(u=s.value);const g=p.value;return i(g)?c&&d&&f?.async===!1&&f.jitless!==!0?(a||(a=o(t.shape)),p=a(p,f),m?_d([],g,p,f,u,e):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:g,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=>Pn(i,s,Nn())))}),t)}const Wy=Z("$ZodUnion",(e,t)=>{qe.init(e,t),Se(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Se(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Se(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Se(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)}}),qy=Z("$ZodIntersection",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>{const o=r.value,a=t.left._zod.run({value:o,issues:[]},s),i=t.right._zod.run({value:o,issues:[]},s);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([l,d])=>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(Nr(e)&&Nr(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 Vy=Z("$ZodEnum",(e,t)=>{qe.init(e,t);const r=od(t.entries),s=new Set(r);e._zod.values=s,e._zod.pattern=new RegExp(`^(${r.filter(o=>og.has(typeof o)).map(o=>typeof o=="string"?Rs(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}}),Hy=Z("$ZodTransform",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new rd(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 wd=Z("$ZodOptional",(e,t)=>{qe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Se(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)}}),Zy=Z("$ZodExactOptional",(e,t)=>{wd.init(e,t),Se(e._zod,"values",()=>t.innerType._zod.values),Se(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,s)=>t.innerType._zod.run(r,s)}),Gy=Z("$ZodNullable",(e,t)=>{qe.init(e,t),Se(e._zod,"optin",()=>t.innerType._zod.optin),Se(e._zod,"optout",()=>t.innerType._zod.optout),Se(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${La(r.source)}|null)$`):void 0}),Se(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)}),Qy=Z("$ZodDefault",(e,t)=>{qe.init(e,t),e._zod.optin="optional",Se(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 Yy=Z("$ZodPrefault",(e,t)=>{qe.init(e,t),e._zod.optin="optional",Se(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))}),Ky=Z("$ZodNonOptional",(e,t)=>{qe.init(e,t),Se(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 Xy=Z("$ZodCatch",(e,t)=>{qe.init(e,t),Se(e._zod,"optin",()=>t.innerType._zod.optin),Se(e._zod,"optout",()=>t.innerType._zod.optout),Se(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=>Pn(i,s,Nn()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>Pn(a,s,Nn()))},input:r.value}),r.issues=[]),r)}}),Jy=Z("$ZodPipe",(e,t)=>{qe.init(e,t),Se(e._zod,"values",()=>t.in._zod.values),Se(e._zod,"optin",()=>t.in._zod.optin),Se(e._zod,"optout",()=>t.out._zod.optout),Se(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=>Hr(i,t.in,s)):Hr(a,t.in,s)}const o=t.in._zod.run(r,s);return o instanceof Promise?o.then(a=>Hr(a,t.out,s)):Hr(o,t.out,s)}});function Hr(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const ex=Z("$ZodReadonly",(e,t)=>{qe.init(e,t),Se(e._zod,"propValues",()=>t.innerType._zod.propValues),Se(e._zod,"values",()=>t.innerType._zod.values),Se(e._zod,"optin",()=>t.innerType?._zod?.optin),Se(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 tx=Z("$ZodCustom",(e,t)=>{ht.init(e,t),qe.init(e,t),e._zod.parse=(r,s)=>r,e._zod.check=r=>{const s=r.value,o=t.fn(s);if(o instanceof Promise)return o.then(a=>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(Pr(o))}}var fc;class nx{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 rx(){return new nx}(fc=globalThis).__zod_globalRegistry??(fc.__zod_globalRegistry=rx());const _r=globalThis.__zod_globalRegistry;function sx(e,t){return new e({type:"string",...ue(t)})}function ox(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ue(t)})}function hc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ue(t)})}function ax(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ue(t)})}function ix(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ue(t)})}function cx(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ue(t)})}function lx(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ue(t)})}function dx(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ue(t)})}function ux(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ue(t)})}function mx(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ue(t)})}function px(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ue(t)})}function fx(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ue(t)})}function hx(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ue(t)})}function gx(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ue(t)})}function yx(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ue(t)})}function xx(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ue(t)})}function vx(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ue(t)})}function bx(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ue(t)})}function _x(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ue(t)})}function wx(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ue(t)})}function jx(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ue(t)})}function kx(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ue(t)})}function Sx(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ue(t)})}function Cx(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ue(t)})}function Nx(e,t){return new e({type:"string",format:"date",check:"string_format",...ue(t)})}function Px(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ue(t)})}function Ax(e,t){return new e({type:"string",format:"duration",check:"string_format",...ue(t)})}function Ex(e,t){return new e({type:"number",checks:[],...ue(t)})}function Tx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ue(t)})}function Ix(e){return new e({type:"unknown"})}function Rx(e,t){return new e({type:"never",...ue(t)})}function gc(e,t){return new gd({check:"less_than",...ue(t),value:e,inclusive:!1})}function Co(e,t){return new gd({check:"less_than",...ue(t),value:e,inclusive:!0})}function yc(e,t){return new yd({check:"greater_than",...ue(t),value:e,inclusive:!1})}function No(e,t){return new yd({check:"greater_than",...ue(t),value:e,inclusive:!0})}function xc(e,t){return new Xg({check:"multiple_of",...ue(t),value:e})}function jd(e,t){return new ey({check:"max_length",...ue(t),maximum:e})}function ys(e,t){return new ty({check:"min_length",...ue(t),minimum:e})}function kd(e,t){return new ny({check:"length_equals",...ue(t),length:e})}function Ox(e,t){return new ry({check:"string_format",format:"regex",...ue(t),pattern:e})}function Mx(e){return new sy({check:"string_format",format:"lowercase",...ue(e)})}function Dx(e){return new oy({check:"string_format",format:"uppercase",...ue(e)})}function Lx(e,t){return new ay({check:"string_format",format:"includes",...ue(t),includes:e})}function $x(e,t){return new iy({check:"string_format",format:"starts_with",...ue(t),prefix:e})}function zx(e,t){return new cy({check:"string_format",format:"ends_with",...ue(t),suffix:e})}function sr(e){return new ly({check:"overwrite",tx:e})}function Fx(e){return sr(t=>t.normalize(e))}function Bx(){return sr(e=>e.trim())}function Ux(){return sr(e=>e.toLowerCase())}function Wx(){return sr(e=>e.toUpperCase())}function qx(){return sr(e=>rg(e))}function Vx(e,t,r){return new e({type:"array",element:t,...ue(r)})}function Hx(e,t,r){return new e({type:"custom",check:"custom",fn:t,...ue(r)})}function Zx(e){const t=Gx(r=>(r.addIssue=s=>{if(typeof s=="string")r.issues.push(Pr(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(Pr(o))}},e(r.value,r)));return t}function Gx(e,t){const r=new ht({check:"custom",...ue(t)});return r._zod.check=e,r}function Sd(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 Je(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,f=t.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(e,t,p,m)}const u=e._zod.parent;u&&(i.ref||(i.ref=u),Je(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"&&at(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 Cd(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??(g=>g);if(u)return{ref:p(u)};const f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${c}/${f}`}}if(i[1]===r)return{ref:"#"};const d=`#/${c}/`,m=i[1].schema.id??`__schema${e.counter++}`;return{defId:m,ref:d+m}},a=i=>{if(i[1].schema.$ref)return;const c=i[1],{ref:l,defId:d}=o(i);c.def={...c.schema},d&&(c.defId=d);const m=c.schema;for(const u in m)delete m[u];m.$ref=l};if(e.cycles==="throw")for(const i of e.seen.entries()){const c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
90
-
91
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const c=i[1];if(t===i[0]){a(i);continue}if(e.external){const d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){a(i);continue}}if(e.metadataRegistry.get(i[0])?.id){a(i);continue}if(c.cycle){a(i);continue}if(c.count>1&&e.reused==="ref"){a(i);continue}}}function Nd(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),f=p.schema;if(f.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(f)):Object.assign(l,f),Object.assign(l,d),i._zod.parent===m)for(const h in l)h==="$ref"||h==="allOf"||h in d||delete l[h];if(f.$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]}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 f in l)f==="$ref"||f==="allOf"||f in p.def&&JSON.stringify(l[f])===JSON.stringify(p.def[f])&&delete l[f]}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:xs(t,"input",e.processors),output:xs(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function at(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 at(s.element,r);if(s.type==="set")return at(s.valueType,r);if(s.type==="lazy")return at(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 at(s.innerType,r);if(s.type==="intersection")return at(s.left,r)||at(s.right,r);if(s.type==="record"||s.type==="map")return at(s.keyType,r)||at(s.valueType,r);if(s.type==="pipe")return at(s.in,r)||at(s.out,r);if(s.type==="object"){for(const o in s.shape)if(at(s.shape[o],r))return!0;return!1}if(s.type==="union"){for(const o of s.options)if(at(o,r))return!0;return!1}if(s.type==="tuple"){for(const o of s.items)if(at(o,r))return!0;return!!(s.rest&&at(s.rest,r))}return!1}const Qx=(e,t={})=>r=>{const s=Sd({...r,processors:t});return Je(e,s),Cd(s,e),Nd(s,e)},xs=(e,t,r={})=>s=>{const{libraryOptions:o,target:a}=s??{},i=Sd({...o??{},target:a,io:t,processors:r});return Je(e,i),Cd(i,e),Nd(i,e)},Yx={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Kx=(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=Yx[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}))])}},Xx=(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)},Jx=(e,t,r,s)=>{r.not={}},ev=(e,t,r,s)=>{},tv=(e,t,r,s)=>{const o=e._zod.def,a=od(o.entries);a.every(i=>typeof i=="number")&&(r.type="number"),a.every(i=>typeof i=="string")&&(r.type="string"),r.enum=a},nv=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},rv=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},sv=(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=Je(a.element,t,{...s,path:[...s.path,"items"]})},ov=(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]=Je(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=Je(a.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},av=(e,t,r,s)=>{const o=e._zod.def,a=o.inclusive===!1,i=o.options.map((c,l)=>Je(c,t,{...s,path:[...s.path,a?"oneOf":"anyOf",l]}));a?r.oneOf=i:r.anyOf=i},iv=(e,t,r,s)=>{const o=e._zod.def,a=Je(o.left,t,{...s,path:[...s.path,"allOf",0]}),i=Je(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},cv=(e,t,r,s)=>{const o=e._zod.def,a=Je(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"}]},lv=(e,t,r,s)=>{const o=e._zod.def;Je(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},dv=(e,t,r,s)=>{const o=e._zod.def;Je(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},uv=(e,t,r,s)=>{const o=e._zod.def;Je(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)))},mv=(e,t,r,s)=>{const o=e._zod.def;Je(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},pv=(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;Je(a,t,s);const i=t.seen.get(e);i.ref=a},fv=(e,t,r,s)=>{const o=e._zod.def;Je(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.readOnly=!0},Pd=(e,t,r,s)=>{const o=e._zod.def;Je(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},hv=Z("ZodISODateTime",(e,t)=>{jy.init(e,t),Le.init(e,t)});function gv(e){return Cx(hv,e)}const yv=Z("ZodISODate",(e,t)=>{ky.init(e,t),Le.init(e,t)});function xv(e){return Nx(yv,e)}const vv=Z("ZodISOTime",(e,t)=>{Sy.init(e,t),Le.init(e,t)});function bv(e){return Px(vv,e)}const _v=Z("ZodISODuration",(e,t)=>{Cy.init(e,t),Le.init(e,t)});function wv(e){return Ax(_v,e)}const jv=(e,t)=>{dd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>gg(e,r)},flatten:{value:r=>hg(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}}})},Ct=Z("ZodError",jv,{Parent:Error}),kv=za(Ct),Sv=Fa(Ct),Cv=Os(Ct),Nv=Ms(Ct),Pv=vg(Ct),Av=bg(Ct),Ev=_g(Ct),Tv=wg(Ct),Iv=jg(Ct),Rv=kg(Ct),Ov=Sg(Ct),Mv=Cg(Ct),Ve=Z("ZodType",(e,t)=>(qe.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:xs(e,"input"),output:xs(e,"output")}}),e.toJSONSchema=Qx(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(gn(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)=>yn(e,r,s),e.brand=()=>e,e.register=((r,s)=>(r.add(e,s),e)),e.parse=(r,s)=>kv(e,r,s,{callee:e.parse}),e.safeParse=(r,s)=>Cv(e,r,s),e.parseAsync=async(r,s)=>Sv(e,r,s,{callee:e.parseAsync}),e.safeParseAsync=async(r,s)=>Nv(e,r,s),e.spa=e.safeParseAsync,e.encode=(r,s)=>Pv(e,r,s),e.decode=(r,s)=>Av(e,r,s),e.encodeAsync=async(r,s)=>Ev(e,r,s),e.decodeAsync=async(r,s)=>Tv(e,r,s),e.safeEncode=(r,s)=>Iv(e,r,s),e.safeDecode=(r,s)=>Rv(e,r,s),e.safeEncodeAsync=async(r,s)=>Ov(e,r,s),e.safeDecodeAsync=async(r,s)=>Mv(e,r,s),e.refine=(r,s)=>e.check(Ab(r,s)),e.superRefine=r=>e.check(Eb(r)),e.overwrite=r=>e.check(sr(r)),e.optional=()=>wc(e),e.exactOptional=()=>gb(e),e.nullable=()=>jc(e),e.nullish=()=>wc(jc(e)),e.nonoptional=r=>wb(e,r),e.array=()=>ab(e),e.or=r=>lb([e,r]),e.and=r=>ub(e,r),e.transform=r=>kc(e,fb(r)),e.default=r=>vb(e,r),e.prefault=r=>_b(e,r),e.catch=r=>kb(e,r),e.pipe=r=>kc(e,r),e.readonly=()=>Nb(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)),Ad=Z("_ZodString",(e,t)=>{Ba.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Kx(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(Ox(...s)),e.includes=(...s)=>e.check(Lx(...s)),e.startsWith=(...s)=>e.check($x(...s)),e.endsWith=(...s)=>e.check(zx(...s)),e.min=(...s)=>e.check(ys(...s)),e.max=(...s)=>e.check(jd(...s)),e.length=(...s)=>e.check(kd(...s)),e.nonempty=(...s)=>e.check(ys(1,...s)),e.lowercase=s=>e.check(Mx(s)),e.uppercase=s=>e.check(Dx(s)),e.trim=()=>e.check(Bx()),e.normalize=(...s)=>e.check(Fx(...s)),e.toLowerCase=()=>e.check(Ux()),e.toUpperCase=()=>e.check(Wx()),e.slugify=()=>e.check(qx())}),Dv=Z("ZodString",(e,t)=>{Ba.init(e,t),Ad.init(e,t),e.email=r=>e.check(ox(Lv,r)),e.url=r=>e.check(dx($v,r)),e.jwt=r=>e.check(Sx(Jv,r)),e.emoji=r=>e.check(ux(zv,r)),e.guid=r=>e.check(hc(vc,r)),e.uuid=r=>e.check(ax(Zr,r)),e.uuidv4=r=>e.check(ix(Zr,r)),e.uuidv6=r=>e.check(cx(Zr,r)),e.uuidv7=r=>e.check(lx(Zr,r)),e.nanoid=r=>e.check(mx(Fv,r)),e.guid=r=>e.check(hc(vc,r)),e.cuid=r=>e.check(px(Bv,r)),e.cuid2=r=>e.check(fx(Uv,r)),e.ulid=r=>e.check(hx(Wv,r)),e.base64=r=>e.check(wx(Yv,r)),e.base64url=r=>e.check(jx(Kv,r)),e.xid=r=>e.check(gx(qv,r)),e.ksuid=r=>e.check(yx(Vv,r)),e.ipv4=r=>e.check(xx(Hv,r)),e.ipv6=r=>e.check(vx(Zv,r)),e.cidrv4=r=>e.check(bx(Gv,r)),e.cidrv6=r=>e.check(_x(Qv,r)),e.e164=r=>e.check(kx(Xv,r)),e.datetime=r=>e.check(gv(r)),e.date=r=>e.check(xv(r)),e.time=r=>e.check(bv(r)),e.duration=r=>e.check(wv(r))});function it(e){return sx(Dv,e)}const Le=Z("ZodStringFormat",(e,t)=>{Ie.init(e,t),Ad.init(e,t)}),Lv=Z("ZodEmail",(e,t)=>{fy.init(e,t),Le.init(e,t)}),vc=Z("ZodGUID",(e,t)=>{my.init(e,t),Le.init(e,t)}),Zr=Z("ZodUUID",(e,t)=>{py.init(e,t),Le.init(e,t)}),$v=Z("ZodURL",(e,t)=>{hy.init(e,t),Le.init(e,t)}),zv=Z("ZodEmoji",(e,t)=>{gy.init(e,t),Le.init(e,t)}),Fv=Z("ZodNanoID",(e,t)=>{yy.init(e,t),Le.init(e,t)}),Bv=Z("ZodCUID",(e,t)=>{xy.init(e,t),Le.init(e,t)}),Uv=Z("ZodCUID2",(e,t)=>{vy.init(e,t),Le.init(e,t)}),Wv=Z("ZodULID",(e,t)=>{by.init(e,t),Le.init(e,t)}),qv=Z("ZodXID",(e,t)=>{_y.init(e,t),Le.init(e,t)}),Vv=Z("ZodKSUID",(e,t)=>{wy.init(e,t),Le.init(e,t)}),Hv=Z("ZodIPv4",(e,t)=>{Ny.init(e,t),Le.init(e,t)}),Zv=Z("ZodIPv6",(e,t)=>{Py.init(e,t),Le.init(e,t)}),Gv=Z("ZodCIDRv4",(e,t)=>{Ay.init(e,t),Le.init(e,t)}),Qv=Z("ZodCIDRv6",(e,t)=>{Ey.init(e,t),Le.init(e,t)}),Yv=Z("ZodBase64",(e,t)=>{Ty.init(e,t),Le.init(e,t)}),Kv=Z("ZodBase64URL",(e,t)=>{Ry.init(e,t),Le.init(e,t)}),Xv=Z("ZodE164",(e,t)=>{Oy.init(e,t),Le.init(e,t)}),Jv=Z("ZodJWT",(e,t)=>{Dy.init(e,t),Le.init(e,t)}),Ed=Z("ZodNumber",(e,t)=>{vd.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Xx(e,s,o),e.gt=(s,o)=>e.check(yc(s,o)),e.gte=(s,o)=>e.check(No(s,o)),e.min=(s,o)=>e.check(No(s,o)),e.lt=(s,o)=>e.check(gc(s,o)),e.lte=(s,o)=>e.check(Co(s,o)),e.max=(s,o)=>e.check(Co(s,o)),e.int=s=>e.check(bc(s)),e.safe=s=>e.check(bc(s)),e.positive=s=>e.check(yc(0,s)),e.nonnegative=s=>e.check(No(0,s)),e.negative=s=>e.check(gc(0,s)),e.nonpositive=s=>e.check(Co(0,s)),e.multipleOf=(s,o)=>e.check(xc(s,o)),e.step=(s,o)=>e.check(xc(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 eb(e){return Ex(Ed,e)}const tb=Z("ZodNumberFormat",(e,t)=>{Ly.init(e,t),Ed.init(e,t)});function bc(e){return Tx(tb,e)}const nb=Z("ZodUnknown",(e,t)=>{$y.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ev()});function _c(){return Ix(nb)}const rb=Z("ZodNever",(e,t)=>{zy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Jx(e,r,s)});function sb(e){return Rx(rb,e)}const ob=Z("ZodArray",(e,t)=>{Fy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>sv(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(jd(r,s)),e.length=(r,s)=>e.check(kd(r,s)),e.unwrap=()=>e.element});function ab(e,t){return Vx(ob,e,t)}const ib=Z("ZodObject",(e,t)=>{Uy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ov(e,r,s,o),Se(e,"shape",()=>t.shape),e.keyof=()=>mb(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:_c()}),e.loose=()=>e.clone({...e._zod.def,catchall:_c()}),e.strict=()=>e.clone({...e._zod.def,catchall:sb()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>dg(e,r),e.safeExtend=r=>ug(e,r),e.merge=r=>mg(e,r),e.pick=r=>cg(e,r),e.omit=r=>lg(e,r),e.partial=(...r)=>pg(Id,e,r[0]),e.required=(...r)=>fg(Rd,e,r[0])});function Td(e,t){const r={type:"object",shape:e??{},...ue(t)};return new ib(r)}const cb=Z("ZodUnion",(e,t)=>{Wy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>av(e,r,s,o),e.options=t.options});function lb(e,t){return new cb({type:"union",options:e,...ue(t)})}const db=Z("ZodIntersection",(e,t)=>{qy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>iv(e,r,s,o)});function ub(e,t){return new db({type:"intersection",left:e,right:t})}const na=Z("ZodEnum",(e,t)=>{Vy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(s,o,a)=>tv(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:[],...ue(o),entries:a})},e.exclude=(s,o)=>{const a={...t.entries};for(const i of s)if(r.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new na({...t,checks:[],...ue(o),entries:a})}});function mb(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new na({type:"enum",entries:r,...ue(t)})}const pb=Z("ZodTransform",(e,t)=>{Hy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>rv(e,r),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new rd(e.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(Pr(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(Pr(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(a=>(r.value=a,r)):(r.value=o,r)}});function fb(e){return new pb({type:"transform",transform:e})}const Id=Z("ZodOptional",(e,t)=>{wd.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Pd(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function wc(e){return new Id({type:"optional",innerType:e})}const hb=Z("ZodExactOptional",(e,t)=>{Zy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Pd(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function gb(e){return new hb({type:"optional",innerType:e})}const yb=Z("ZodNullable",(e,t)=>{Gy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>cv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function jc(e){return new yb({type:"nullable",innerType:e})}const xb=Z("ZodDefault",(e,t)=>{Qy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>dv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function vb(e,t){return new xb({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():id(t)}})}const bb=Z("ZodPrefault",(e,t)=>{Yy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>uv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function _b(e,t){return new bb({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():id(t)}})}const Rd=Z("ZodNonOptional",(e,t)=>{Ky.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>lv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function wb(e,t){return new Rd({type:"nonoptional",innerType:e,...ue(t)})}const jb=Z("ZodCatch",(e,t)=>{Xy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>mv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function kb(e,t){return new jb({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Sb=Z("ZodPipe",(e,t)=>{Jy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>pv(e,r,s,o),e.in=t.in,e.out=t.out});function kc(e,t){return new Sb({type:"pipe",in:e,out:t})}const Cb=Z("ZodReadonly",(e,t)=>{ex.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>fv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Nb(e){return new Cb({type:"readonly",innerType:e})}const Pb=Z("ZodCustom",(e,t)=>{tx.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>nv(e,r)});function Ab(e,t={}){return Hx(Pb,e,t)}function Eb(e){return Zx(e)}const Gr=Td({line1:it().min(1,"Address line 1 is required"),line2:it().optional(),city:it().min(1,"City is required"),state:it().optional(),postalCode:it().min(1,"Postal code is required"),country:it().min(2,"Country is required")});function Tb(e){return Td({email:e.requireEmail?it().email("Valid email required"):it().email("Valid email required").optional(),name:e.requireName?it().min(1,"Name is required"):it().optional(),phone:e.requirePhone?it().min(6,"Phone is required"):it().optional(),notes:it().max(500).optional(),shippingAddress:e.requireShippingAddress?Gr:Gr.optional(),billingAddress:e.requireBillingAddress?Gr:Gr.optional(),discountCode:it().optional(),tipAmount:eb().min(0).optional(),shippingMethodId:it().optional()})}const Sc={none:0,optional:1,required:2};function Po(e,t){return Sc[e]>=Sc[t]?e:t}function Ib(e){if(!e)return null;try{const t=JSON.parse(e);return!t||typeof t!="object"?null:t}catch{return null}}function is(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 f=Ib(u.metadata?.checkoutRequirements);f&&(f.email&&(a=Po(a,f.email)),f.name&&(i=Po(i,f.name)),f.phone&&(c=Po(c,f.phone)),typeof f.shippingAddress=="boolean"&&(l=l||f.shippingAddress),typeof f.billingAddress=="boolean"&&(d=d||f.billingAddress));const g=u.metadata?.fulfillmentNotes;g&&o.add(g)}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 Od=v.createContext(null);function Md(){const{config:e}=De(),t=Mt(),r=v.useMemo(()=>({line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"}),[]),s=v.useMemo(()=>{const y=is(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});return Tb({requireEmail:y.email==="required",requireName:y.name==="required",requirePhone:y.phone==="required",requireShippingAddress:y.shippingAddress,requireBillingAddress:y.billingAddress})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail]),[o,a]=v.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:""}));v.useEffect(()=>{const y=is(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});a(_=>{const j={..._};return y.email==="required"&&!j.email&&(j.email=""),y.shippingAddress&&!j.shippingAddress&&(j.shippingAddress=r),y.billingAddress&&!j.billingAddress&&(j.billingAddress=r),y.shippingAddress||(j.shippingAddress=void 0),y.billingAddress||(j.billingAddress=void 0),j})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail,r]);const[i,c]=v.useState({}),[l,d]=v.useState("idle"),[m,u]=v.useState(null),[p,f]=v.useState(null),g=v.useCallback(()=>{c({}),d("idle"),u(null),f(null)},[]),h=v.useCallback((y,_)=>{a(j=>({...j,[y]:_}))},[]),b=v.useCallback(()=>{d("validating"),u(null);const y=s.safeParse(o);if(y.success)return c({}),d("idle"),{ok:!0,values:y.data};const _={};for(const j of y.error.issues)_[j.path.join(".")]=j.message;return c(_),d("error"),u("Please fix the highlighted fields."),{ok:!1}},[s,o]),w=v.useCallback(async y=>{const _=b();if(!_.ok)return{ok:!1};d("creating_session"),u(null),f(null);const j=t.items.map(N=>({resource:N.paymentResource??N.productId,quantity:N.qty,variantId:N.variantId})),C=is(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1}),I=new Set;if(C.shippingAddress)for(const N of t.items){const $=N.metadata?.shippingCountries;if($)for(const k of $.split(",")){const P=k.trim().toUpperCase();P&&I.add(P)}}const S={...I.size?{shippingCountries:Array.from(I).join(","),shipping_countries:Array.from(I).join(",")}:{}};try{const N=await e.adapter.createCheckoutSession({cart:j,customer:{email:_.values.email||void 0,name:_.values.name||void 0,phone:_.values.phone||void 0,notes:_.values.notes||void 0,shippingAddress:_.values.shippingAddress,billingAddress:_.values.billingAddress},options:{currency:e.currency,successUrl:e.checkout.successUrl,cancelUrl:e.checkout.cancelUrl,allowPromoCodes:e.checkout.allowPromoCodes,metadata:Object.keys(S).length?S:void 0,discountCode:(e.checkout.allowPromoCodes?_.values.discountCode||t.promoCode:void 0)||void 0,tipAmount:e.checkout.allowTipping&&_.values.tipAmount||void 0,shippingMethodId:e.checkout.allowShipping&&_.values.shippingMethodId||void 0,paymentMethodId:y?.paymentMethodId}});return N.kind==="redirect"?(f(N),d("redirecting"),typeof window<"u"&&window.location.assign(N.url),{ok:!0,session:N}):(f(N),d("success"),{ok:!0,session:N})}catch(N){return d("error"),u(N instanceof Error?N.message:"Checkout failed"),{ok:!1}}},[t.items,t.promoCode,e.adapter,e.checkout,e.currency,b]);return{values:o,setValues:a,setField:h,fieldErrors:i,status:l,error:m,session:p,reset:g,validate:b,createCheckoutSession:w}}function Dd({children:e}){const t=Md();return n.jsx(Od.Provider,{value:t,children:e})}function Ls(){const e=v.useContext(Od);if(!e)throw new Error("useCheckout must be used within CheckoutProvider");return e}function Rb(){return Md()}function Ua(){const{config:e}=De(),[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 $s(e){const{config:t}=De(),[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 Ld(e){const{config:t}=De(),[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 $d(){const{config:e}=De(),[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 zd(){const{config:e}=De(),[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 Fd({enabled:e,customer:t}){const{config:r}=De(),[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 Ob(e){const t={};return e.forEach((r,s)=>{t[s]=r}),t}function qa(){const{config:e}=De(),[t,r]=x.useState({kind:"idle"});return x.useEffect(()=>{if(typeof window>"u")return;const s=new URLSearchParams(window.location.search),o=Ob(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 Mb(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 Db(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 Va({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=Mb(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")),Db(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 Lb(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 $b(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}=Lb(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}=De(),[o,a]=x.useState(new Map),[i,c]=x.useState(!1),[l,d]=x.useState(null),m=x.useMemo(()=>{const g=new Set;for(const h of e)g.add(h.productId);return Array.from(g)},[e]),u=x.useCallback(async()=>{if(r||m.length===0){a(new Map);return}c(!0),d(null);try{const g=await Promise.all(m.map(async w=>{try{return await s.adapter.getProductBySlug(w)}catch{return null}})),h=new Map;for(const w of g)w&&(h.set(w.id,w),w.slug&&w.slug!==w.id&&h.set(w.slug,w));const b=new Map;for(const w of e){const y=Cc(w.productId,w.variantId),_=h.get(w.productId)??null;b.set(y,$b(w,_))}a(b)}catch(g){d(g instanceof Error?g.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 g=setInterval(u,t);return()=>clearInterval(g)},[u,m.length,t,r]);const p=x.useCallback((g,h)=>o.get(Cc(g,h)),[o]),f=x.useMemo(()=>{for(const g of o.values())if(g.isOutOfStock||g.exceedsAvailable)return!0;return!1},[o]);return{inventory:o,isLoading:i,error:l,refresh:u,getItemInventory:p,hasIssues:f}}function zb(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 Fb(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 Bb(e,t){const r=Fb(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}=zb(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 Bd({items:e}){const{config:t}=De(),[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 h=>{try{return await t.adapter.getProductBySlug(h)}catch{return null}})),p=new Map;for(const h of u)h&&(p.set(h.id,h),h.slug&&h.slug!==h.id&&p.set(h.slug,h));const f=[];for(const h of e){const b=p.get(h.productId)??null,w=Bb(h,b);w&&f.push(w)}const g={ok:f.length===0,issues:f,verifiedAt:new Date};return s(g),a(!1),g}catch(u){const p=u instanceof Error?u.message:"Failed to verify inventory";c(p),a(!1);const f={ok:!1,issues:[],verifiedAt:new Date};return s(f),f}},[t.adapter,e,l]),m=x.useCallback(()=>{s(null),c(null)},[]);return{result:r,isVerifying:o,error:i,verify:d,reset:m}}function Ub({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,f=[],g=[];for(const h of l){if(!h.holdExpiresAt)continue;const b=new Date(h.holdExpiresAt),w=b.getTime()-u,y=`${h.productId}::${h.variantId??""}`;w<=0?(f.push({productId:h.productId,variantId:h.variantId}),c.current.has(y)||(c.current.add(y),t?.({productId:h.productId,variantId:h.variantId,title:h.titleSnapshot,expiredAt:b}))):w<=p&&g.push({productId:h.productId,variantId:h.variantId,expiresAt:b,remainingMs:w})}o(f),i(g)};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 Wb(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]=v.useState(Ne),[a,i]=v.useState(!!r?.getStorefrontSettings);return v.useEffect(()=>{if(!r?.getStorefrontSettings){i(!1);return}let c=!1;async function l(){try{const d=await r.getStorefrontSettings();!c&&d&&o(Wb(d))}catch{}finally{c||i(!1)}}return l(),()=>{c=!0}},[r]),{settings:s,isLoading:a}}const qb={card:!0,crypto:!0,credits:!1};function Ud(){const t=Oa()?.config?.adapter,[r,s]=v.useState(qb),[o,a]=v.useState(!!t?.getPaymentMethodsConfig);return v.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 Vb(e){return e.productId?`id:${e.productId}`:e.name?`name:${e.name}`:""}function Wd(e={}){const{productId:t,product:r,enabled:s=!0}=e,a=Oa()?.config?.adapter,[i,c]=v.useState(null),[l,d]=v.useState(null),[m,u]=v.useState(!1),[p,f]=v.useState(null),g=v.useRef(0),h=v.useCallback(async()=>{const b=t?{productId:t}:r?{name:r.name,description:r.description,tags:r.tags,categoryIds:r.categoryIds}:{};if(!b.productId&&!b.name)return;if(!a?.getAIRelatedProducts){f("AI recommendations not available");return}const w=Vb(b),y=Nc.get(w);if(y){c(y.relatedProductIds),d(y.reasoning),f(null);return}const _=++g.current;u(!0),f(null);try{const j=await a.getAIRelatedProducts(b);_===g.current&&(c(j.relatedProductIds),d(j.reasoning),f(null),w&&Nc.set(w,j))}catch(j){if(_===g.current){const C=j instanceof Error?j.message:"Failed to get AI recommendations";f(C),c(null),d(null)}}finally{_===g.current&&u(!1)}},[a,t,r]);return v.useEffect(()=>{s&&(!t&&!r?.name||h())},[s,t,r?.name,h]),{relatedProductIds:i,reasoning:l,isLoading:m,error:p,refetch:h}}function Me(e,t){if(!e)throw new Error(t)}function At(e){return typeof e=="string"&&e.trim().length>0}async function Hb(e,t={}){const r=t.pageSize??10,s=await e.listCategories();Me(Array.isArray(s),"listCategories() must return an array");for(const i of s)Me(At(i.id),"Category.id is required"),Me(At(i.slug),"Category.slug is required"),Me(At(i.name),"Category.name is required");const o=await e.listProducts({page:1,pageSize:r});if(Me(o&&Array.isArray(o.items),"listProducts() must return { items: Product[] }"),Me(typeof o.page=="number","listProducts().page must be a number"),Me(typeof o.pageSize=="number","listProducts().pageSize must be a number"),o.items.length>0){const i=o.items[0];Me(At(i.id),"Product.id is required"),Me(At(i.slug),"Product.slug is required"),Me(At(i.title),"Product.title is required"),Me(typeof i.description=="string","Product.description must be a string"),Me(Array.isArray(i.images),"Product.images must be an array"),Me(typeof i.price=="number","Product.price must be a number"),Me(At(i.currency),"Product.currency is required"),Me(Array.isArray(i.tags),"Product.tags must be an array"),Me(Array.isArray(i.categoryIds),"Product.categoryIds must be an array");const c=await e.getProductBySlug(i.slug);Me(c===null||At(c.id),"getProductBySlug() must return Product or null")}const a=await e.getOrderHistory();Me(Array.isArray(a),"getOrderHistory() must return an array");for(const i of a)Me(At(i.id),"Order.id is required"),Me(At(i.createdAt),"Order.createdAt is required"),Me(typeof i.total=="number","Order.total must be a number"),Me(At(i.currency),"Order.currency is required"),Me(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 Te(...e){return x.useCallback(ar(...e),e)}var Zb=Symbol.for("react.lazy"),vs=x[" use ".trim().toString()];function Gb(e){return typeof e=="object"&&e!==null&&"then"in e}function qd(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Zb&&"_payload"in e&&Gb(e._payload)}function Vd(e){const t=Yb(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(Xb);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 Qb=Vd("Slot");function Yb(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=e0(o),c=Jb(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 Kb=Symbol("radix.slottable");function Xb(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Kb}function Jb(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 e0(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 Hd(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=Hd(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function Zd(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=Hd(e))&&(s&&(s+=" "),s+=t);return s}const Ac=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Ec=Zd,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,...f}=m;return Object.entries(f).every(g=>{let[h,b]=g;return Array.isArray(b)?b.includes({...a,...c}[h]):{...a,...c}[h]===b})?[...d,u,p]:d},[]);return Ec(e,i,l,r?.class,r?.className)},t0=(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},n0=(e,t)=>({classGroupId:e,validator:t}),Gd=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),bs="-",Tc=[],r0="arbitrary..",s0=e=>{const t=a0(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return o0(i);const c=i.split(bs),l=c[0]===""&&c.length>1?1:0;return Qd(c,l,t)},getConflictingClassGroupIds:(i,c)=>{if(c){const l=s[i],d=r[i];return l?d?t0(d,l):l:d||Tc}return r[i]||Tc}}},Qd=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],a=r.nextPart.get(o);if(a){const d=Qd(e,t+1,a);if(d)return d}const i=r.validators;if(i===null)return;const c=t===0?e.join(bs):e.slice(t).join(bs),l=i.length;for(let d=0;d<l;d++){const m=i[d];if(m.validator(c))return m.classGroupId}},o0=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?r0+s:void 0})(),a0=e=>{const{theme:t,classGroups:r}=e;return i0(r,t)},i0=(e,t)=>{const r=Gd();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];c0(i,t,r,s)}},c0=(e,t,r,s)=>{if(typeof e=="string"){l0(e,t,r);return}if(typeof e=="function"){d0(e,t,r,s);return}u0(e,t,r,s)},l0=(e,t,r)=>{const s=e===""?t:Yd(t,e);s.classGroupId=r},d0=(e,t,r,s)=>{if(m0(e)){Qa(e(s),t,r,s);return}t.validators===null&&(t.validators=[]),t.validators.push(n0(r,e))},u0=(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,Yd(t,c),r,s)}},Yd=(e,t)=>{let r=e;const s=t.split(bs),o=s.length;for(let a=0;a<o;a++){const i=s[a];let c=r.nextPart.get(i);c||(c=Gd(),r.nextPart.set(i,c)),r=c}return r},m0=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,p0=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=":",f0=[],Rc=(e,t,r,s,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),h0=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 h=0;h<m;h++){const b=o[h];if(i===0&&c===0){if(b===Ic){a.push(o.slice(l,h)),l=h+1;continue}if(b==="/"){d=h;continue}}b==="["?i++:b==="]"?i--:b==="("?c++:b===")"&&c--}const u=a.length===0?o:o.slice(l);let p=u,f=!1;u.endsWith(sa)?(p=u.slice(0,-1),f=!0):u.startsWith(sa)&&(p=u.slice(1),f=!0);const g=d&&d>l?d-l:void 0;return Rc(a,f,p,g)};if(t){const o=t+Ic,a=s;s=i=>i.startsWith(o)?a(i.slice(o.length)):Rc(f0,!1,i,void 0,!0)}if(r){const o=s;s=a=>r({className:a,parseClassName:o})}return s},g0=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:p0(e.cacheSize),parseClassName:h0(e),sortModifiers:g0(e),...s0(e)}),x0=/\s+/,v0=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:a}=t,i=[],c=e.trim().split(x0);let l="";for(let d=c.length-1;d>=0;d-=1){const m=c[d],{isExternal:u,modifiers:p,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:h}=r(m);if(u){l=m+(l.length>0?" "+l:l);continue}let b=!!h,w=s(b?g.substring(0,h):g);if(!w){if(!b){l=m+(l.length>0?" "+l:l);continue}if(w=s(g),!w){l=m+(l.length>0?" "+l:l);continue}b=!1}const y=p.length===0?"":p.length===1?p[0]:a(p).join(":"),_=f?y+sa:y,j=_+w;if(i.indexOf(j)>-1)continue;i.push(j);const C=o(w,b);for(let I=0;I<C.length;++I){const S=C[I];i.push(_+S)}l=m+(l.length>0?" "+l:l)}return l},b0=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=Kd(r))&&(o&&(o+=" "),o+=s);return o},Kd=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=Kd(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(b0(...l))},w0=[],Ye=e=>{const t=r=>r[e]||w0;return t.isThemeGetter=!0,t},Xd=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Jd=/^\((?:(\w[\w-]*):)?(.+)\)$/i,j0=/^\d+\/\d+$/,k0=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,S0=/\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$/,C0=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,N0=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,P0=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Hn=e=>j0.test(e),ye=e=>!!e&&!Number.isNaN(Number(e)),sn=e=>!!e&&Number.isInteger(Number(e)),Ao=e=>e.endsWith("%")&&ye(e.slice(0,-1)),en=e=>k0.test(e),A0=()=>!0,E0=e=>S0.test(e)&&!C0.test(e),eu=()=>!1,T0=e=>N0.test(e),I0=e=>P0.test(e),R0=e=>!oe(e)&&!ae(e),O0=e=>ir(e,ru,eu),oe=e=>Xd.test(e),kn=e=>ir(e,su,E0),Eo=e=>ir(e,z0,ye),Oc=e=>ir(e,tu,eu),M0=e=>ir(e,nu,I0),Qr=e=>ir(e,ou,T0),ae=e=>Jd.test(e),hr=e=>cr(e,su),D0=e=>cr(e,F0),Mc=e=>cr(e,tu),L0=e=>cr(e,ru),$0=e=>cr(e,nu),Yr=e=>cr(e,ou,!0),ir=(e,t,r)=>{const s=Xd.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},cr=(e,t,r=!1)=>{const s=Jd.exec(e);return s?s[1]?t(s[1]):r:!1},tu=e=>e==="position"||e==="percentage",nu=e=>e==="image"||e==="url",ru=e=>e==="length"||e==="size"||e==="bg-size",su=e=>e==="length",z0=e=>e==="number",F0=e=>e==="family-name",ou=e=>e==="shadow",B0=()=>{const e=Ye("color"),t=Ye("font"),r=Ye("text"),s=Ye("font-weight"),o=Ye("tracking"),a=Ye("leading"),i=Ye("breakpoint"),c=Ye("container"),l=Ye("spacing"),d=Ye("radius"),m=Ye("shadow"),u=Ye("inset-shadow"),p=Ye("text-shadow"),f=Ye("drop-shadow"),g=Ye("blur"),h=Ye("perspective"),b=Ye("aspect"),w=Ye("ease"),y=Ye("animate"),_=()=>["auto","avoid","all","avoid-page","page","left","right","column"],j=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],C=()=>[...j(),ae,oe],I=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],N=()=>[ae,oe,l],$=()=>[Hn,"full","auto",...N()],k=()=>[sn,"none","subgrid",ae,oe],P=()=>["auto",{span:["full",sn,ae,oe]},sn,ae,oe],A=()=>[sn,"auto",ae,oe],L=()=>["auto","min","max","fr",ae,oe],z=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],D=()=>["start","end","center","stretch","center-safe","end-safe"],R=()=>["auto",...N()],O=()=>[Hn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...N()],T=()=>[e,ae,oe],W=()=>[...j(),Mc,Oc,{position:[ae,oe]}],E=()=>["no-repeat",{repeat:["","x","y","space","round"]}],q=()=>["auto","cover","contain",L0,O0,{size:[ae,oe]}],ne=()=>[Ao,hr,kn],U=()=>["","none","full",d,ae,oe],K=()=>["",ye,hr,kn],J=()=>["solid","dashed","dotted","double"],he=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],B=()=>[ye,Ao,Mc,Oc],X=()=>["","none",g,ae,oe],me=()=>["none",ye,ae,oe],V=()=>["none",ye,ae,oe],re=()=>[ye,ae,oe],le=()=>[Hn,"full",...N()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[en],breakpoint:[en],color:[A0],container:[en],"drop-shadow":[en],ease:["in","out","in-out"],font:[R0],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[en],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[en],shadow:[en],spacing:["px",ye],text:[en],"text-shadow":[en],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Hn,oe,ae,b]}],container:["container"],columns:[{columns:[ye,oe,ae,c]}],"break-after":[{"break-after":_()}],"break-before":[{"break-before":_()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:C()}],overflow:[{overflow:I()}],"overflow-x":[{"overflow-x":I()}],"overflow-y":[{"overflow-y":I()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:$()}],"inset-x":[{"inset-x":$()}],"inset-y":[{"inset-y":$()}],start:[{start:$()}],end:[{end:$()}],top:[{top:$()}],right:[{right:$()}],bottom:[{bottom:$()}],left:[{left:$()}],visibility:["visible","invisible","collapse"],z:[{z:[sn,"auto",ae,oe]}],basis:[{basis:[Hn,"full","auto",c,...N()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ye,Hn,"auto","initial","none",oe]}],grow:[{grow:["",ye,ae,oe]}],shrink:[{shrink:["",ye,ae,oe]}],order:[{order:[sn,"first","last","none",ae,oe]}],"grid-cols":[{"grid-cols":k()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":A()}],"col-end":[{"col-end":A()}],"grid-rows":[{"grid-rows":k()}],"row-start-end":[{row:P()}],"row-start":[{"row-start":A()}],"row-end":[{"row-end":A()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":L()}],"auto-rows":[{"auto-rows":L()}],gap:[{gap:N()}],"gap-x":[{"gap-x":N()}],"gap-y":[{"gap-y":N()}],"justify-content":[{justify:[...z(),"normal"]}],"justify-items":[{"justify-items":[...D(),"normal"]}],"justify-self":[{"justify-self":["auto",...D()]}],"align-content":[{content:["normal",...z()]}],"align-items":[{items:[...D(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...D(),{baseline:["","last"]}]}],"place-content":[{"place-content":z()}],"place-items":[{"place-items":[...D(),"baseline"]}],"place-self":[{"place-self":["auto",...D()]}],p:[{p:N()}],px:[{px:N()}],py:[{py:N()}],ps:[{ps:N()}],pe:[{pe:N()}],pt:[{pt:N()}],pr:[{pr:N()}],pb:[{pb:N()}],pl:[{pl:N()}],m:[{m:R()}],mx:[{mx:R()}],my:[{my:R()}],ms:[{ms:R()}],me:[{me:R()}],mt:[{mt:R()}],mr:[{mr:R()}],mb:[{mb:R()}],ml:[{ml:R()}],"space-x":[{"space-x":N()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":N()}],"space-y-reverse":["space-y-reverse"],size:[{size:O()}],w:[{w:[c,"screen",...O()]}],"min-w":[{"min-w":[c,"screen","none",...O()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[i]},...O()]}],h:[{h:["screen","lh",...O()]}],"min-h":[{"min-h":["screen","lh","none",...O()]}],"max-h":[{"max-h":["screen","lh",...O()]}],"font-size":[{text:["base",r,hr,kn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,ae,Eo]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ao,oe]}],"font-family":[{font:[D0,oe,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,ae,oe]}],"line-clamp":[{"line-clamp":[ye,"none",ae,Eo]}],leading:[{leading:[a,...N()]}],"list-image":[{"list-image":["none",ae,oe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",ae,oe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:T()}],"text-color":[{text:T()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[ye,"from-font","auto",ae,kn]}],"text-decoration-color":[{decoration:T()}],"underline-offset":[{"underline-offset":[ye,"auto",ae,oe]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:N()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",ae,oe]}],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",ae,oe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:W()}],"bg-repeat":[{bg:E()}],"bg-size":[{bg:q()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},sn,ae,oe],radial:["",ae,oe],conic:[sn,ae,oe]},$0,M0]}],"bg-color":[{bg:T()}],"gradient-from-pos":[{from:ne()}],"gradient-via-pos":[{via:ne()}],"gradient-to-pos":[{to:ne()}],"gradient-from":[{from:T()}],"gradient-via":[{via:T()}],"gradient-to":[{to:T()}],rounded:[{rounded:U()}],"rounded-s":[{"rounded-s":U()}],"rounded-e":[{"rounded-e":U()}],"rounded-t":[{"rounded-t":U()}],"rounded-r":[{"rounded-r":U()}],"rounded-b":[{"rounded-b":U()}],"rounded-l":[{"rounded-l":U()}],"rounded-ss":[{"rounded-ss":U()}],"rounded-se":[{"rounded-se":U()}],"rounded-ee":[{"rounded-ee":U()}],"rounded-es":[{"rounded-es":U()}],"rounded-tl":[{"rounded-tl":U()}],"rounded-tr":[{"rounded-tr":U()}],"rounded-br":[{"rounded-br":U()}],"rounded-bl":[{"rounded-bl":U()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:T()}],"border-color-x":[{"border-x":T()}],"border-color-y":[{"border-y":T()}],"border-color-s":[{"border-s":T()}],"border-color-e":[{"border-e":T()}],"border-color-t":[{"border-t":T()}],"border-color-r":[{"border-r":T()}],"border-color-b":[{"border-b":T()}],"border-color-l":[{"border-l":T()}],"divide-color":[{divide:T()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ye,ae,oe]}],"outline-w":[{outline:["",ye,hr,kn]}],"outline-color":[{outline:T()}],shadow:[{shadow:["","none",m,Yr,Qr]}],"shadow-color":[{shadow:T()}],"inset-shadow":[{"inset-shadow":["none",u,Yr,Qr]}],"inset-shadow-color":[{"inset-shadow":T()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:T()}],"ring-offset-w":[{"ring-offset":[ye,kn]}],"ring-offset-color":[{"ring-offset":T()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":T()}],"text-shadow":[{"text-shadow":["none",p,Yr,Qr]}],"text-shadow-color":[{"text-shadow":T()}],opacity:[{opacity:[ye,ae,oe]}],"mix-blend":[{"mix-blend":[...he(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":he()}],"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":B()}],"mask-image-linear-to-pos":[{"mask-linear-to":B()}],"mask-image-linear-from-color":[{"mask-linear-from":T()}],"mask-image-linear-to-color":[{"mask-linear-to":T()}],"mask-image-t-from-pos":[{"mask-t-from":B()}],"mask-image-t-to-pos":[{"mask-t-to":B()}],"mask-image-t-from-color":[{"mask-t-from":T()}],"mask-image-t-to-color":[{"mask-t-to":T()}],"mask-image-r-from-pos":[{"mask-r-from":B()}],"mask-image-r-to-pos":[{"mask-r-to":B()}],"mask-image-r-from-color":[{"mask-r-from":T()}],"mask-image-r-to-color":[{"mask-r-to":T()}],"mask-image-b-from-pos":[{"mask-b-from":B()}],"mask-image-b-to-pos":[{"mask-b-to":B()}],"mask-image-b-from-color":[{"mask-b-from":T()}],"mask-image-b-to-color":[{"mask-b-to":T()}],"mask-image-l-from-pos":[{"mask-l-from":B()}],"mask-image-l-to-pos":[{"mask-l-to":B()}],"mask-image-l-from-color":[{"mask-l-from":T()}],"mask-image-l-to-color":[{"mask-l-to":T()}],"mask-image-x-from-pos":[{"mask-x-from":B()}],"mask-image-x-to-pos":[{"mask-x-to":B()}],"mask-image-x-from-color":[{"mask-x-from":T()}],"mask-image-x-to-color":[{"mask-x-to":T()}],"mask-image-y-from-pos":[{"mask-y-from":B()}],"mask-image-y-to-pos":[{"mask-y-to":B()}],"mask-image-y-from-color":[{"mask-y-from":T()}],"mask-image-y-to-color":[{"mask-y-to":T()}],"mask-image-radial":[{"mask-radial":[ae,oe]}],"mask-image-radial-from-pos":[{"mask-radial-from":B()}],"mask-image-radial-to-pos":[{"mask-radial-to":B()}],"mask-image-radial-from-color":[{"mask-radial-from":T()}],"mask-image-radial-to-color":[{"mask-radial-to":T()}],"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":j()}],"mask-image-conic-pos":[{"mask-conic":[ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":B()}],"mask-image-conic-to-pos":[{"mask-conic-to":B()}],"mask-image-conic-from-color":[{"mask-conic-from":T()}],"mask-image-conic-to-color":[{"mask-conic-to":T()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:W()}],"mask-repeat":[{mask:E()}],"mask-size":[{mask:q()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",ae,oe]}],filter:[{filter:["","none",ae,oe]}],blur:[{blur:X()}],brightness:[{brightness:[ye,ae,oe]}],contrast:[{contrast:[ye,ae,oe]}],"drop-shadow":[{"drop-shadow":["","none",f,Yr,Qr]}],"drop-shadow-color":[{"drop-shadow":T()}],grayscale:[{grayscale:["",ye,ae,oe]}],"hue-rotate":[{"hue-rotate":[ye,ae,oe]}],invert:[{invert:["",ye,ae,oe]}],saturate:[{saturate:[ye,ae,oe]}],sepia:[{sepia:["",ye,ae,oe]}],"backdrop-filter":[{"backdrop-filter":["","none",ae,oe]}],"backdrop-blur":[{"backdrop-blur":X()}],"backdrop-brightness":[{"backdrop-brightness":[ye,ae,oe]}],"backdrop-contrast":[{"backdrop-contrast":[ye,ae,oe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ye,ae,oe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ye,ae,oe]}],"backdrop-invert":[{"backdrop-invert":["",ye,ae,oe]}],"backdrop-opacity":[{"backdrop-opacity":[ye,ae,oe]}],"backdrop-saturate":[{"backdrop-saturate":[ye,ae,oe]}],"backdrop-sepia":[{"backdrop-sepia":["",ye,ae,oe]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":N()}],"border-spacing-x":[{"border-spacing-x":N()}],"border-spacing-y":[{"border-spacing-y":N()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",ae,oe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ye,"initial",ae,oe]}],ease:[{ease:["linear","initial",w,ae,oe]}],delay:[{delay:[ye,ae,oe]}],animate:[{animate:["none",y,ae,oe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[h,ae,oe]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:me()}],"rotate-x":[{"rotate-x":me()}],"rotate-y":[{"rotate-y":me()}],"rotate-z":[{"rotate-z":me()}],scale:[{scale:V()}],"scale-x":[{"scale-x":V()}],"scale-y":[{"scale-y":V()}],"scale-z":[{"scale-z":V()}],"scale-3d":["scale-3d"],skew:[{skew:re()}],"skew-x":[{"skew-x":re()}],"skew-y":[{"skew-y":re()}],transform:[{transform:[ae,oe,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"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:T()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:T()}],"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",ae,oe]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":N()}],"scroll-mx":[{"scroll-mx":N()}],"scroll-my":[{"scroll-my":N()}],"scroll-ms":[{"scroll-ms":N()}],"scroll-me":[{"scroll-me":N()}],"scroll-mt":[{"scroll-mt":N()}],"scroll-mr":[{"scroll-mr":N()}],"scroll-mb":[{"scroll-mb":N()}],"scroll-ml":[{"scroll-ml":N()}],"scroll-p":[{"scroll-p":N()}],"scroll-px":[{"scroll-px":N()}],"scroll-py":[{"scroll-py":N()}],"scroll-ps":[{"scroll-ps":N()}],"scroll-pe":[{"scroll-pe":N()}],"scroll-pt":[{"scroll-pt":N()}],"scroll-pr":[{"scroll-pr":N()}],"scroll-pb":[{"scroll-pb":N()}],"scroll-pl":[{"scroll-pl":N()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",ae,oe]}],fill:[{fill:["none",...T()]}],"stroke-w":[{stroke:[ye,hr,kn,Eo]}],stroke:[{stroke:["none",...T()]}],"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"]}},U0=_0(B0);function H(...e){return U0(Zd(e))}const W0=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"}}),ce=x.forwardRef(({className:e,variant:t,size:r,asChild:s,...o},a)=>{const i=s?Qb:"button";return n.jsx(i,{className:H(W0({variant:t,size:r}),e),ref:a,...o})});ce.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 Cn({className:e,variant:t,...r}){return n.jsx("div",{className:H(q0({variant:t}),e),...r})}const It=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}));It.displayName="Card";const Ar=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex flex-col space-y-1.5 p-6",e),...t}));Ar.displayName="CardHeader";const Er=x.forwardRef(({className:e,...t},r)=>n.jsx("h3",{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));Er.displayName="CardTitle";const au=x.forwardRef(({className:e,...t},r)=>n.jsx("p",{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));au.displayName="CardDescription";const Ht=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("p-6 pt-0",e),...t}));Ht.displayName="CardContent";const iu=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex items-center p-6 pt-0",e),...t}));iu.displayName="CardFooter";const We=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}));We.displayName="Input";const lt=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}));lt.displayName="Label";var V0=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],H0=V0.reduce((e,t)=>{const r=Vd(`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}},{}),Z0="Separator",Dc="horizontal",G0=["horizontal","vertical"],cu=x.forwardRef((e,t)=>{const{decorative:r,orientation:s=Dc,...o}=e,a=Q0(s)?s:Dc,c=r?{role:"none"}:{"aria-orientation":a==="vertical"?a:void 0,role:"separator"};return n.jsx(H0.div,{"data-orientation":a,...c,...o,ref:t})});cu.displayName=Z0;function Q0(e){return G0.includes(e)}var lu=cu;const kt=x.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...s},o)=>n.jsx(lu,{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}));kt.displayName=lu.displayName;function $e({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 we(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e?.(o),r===!1||!o.defaultPrevented)return t?.(o)}}function Y0(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 xn(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:f,...g}=u,h=p?.[e]?.[l]||c,b=x.useMemo(()=>g,Object.values(g));return n.jsx(h.Provider,{value:b,children:f})};d.displayName=a+"Provider";function m(u,p){const f=p?.[e]?.[l]||c,g=x.useContext(f);if(g)return g;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,K0(o,...t)]}function K0(...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=X0(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(e_);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 X0(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=n_(o),c=t_(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 J0=Symbol("radix.slottable");function e_(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===J0}function t_(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 n_(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]=xn(t),[o,a]=r(t,{collectionRef:{current:null},itemMap:new Map}),i=h=>{const{scope:b,children:w}=h,y=v.useRef(null),_=v.useRef(new Map).current;return n.jsx(o,{scope:b,itemMap:_,collectionRef:y,children:w})};i.displayName=t;const c=e+"CollectionSlot",l=$c(c),d=v.forwardRef((h,b)=>{const{scope:w,children:y}=h,_=a(c,w),j=Te(b,_.collectionRef);return n.jsx(l,{ref:j,children:y})});d.displayName=c;const m=e+"CollectionItemSlot",u="data-radix-collection-item",p=$c(m),f=v.forwardRef((h,b)=>{const{scope:w,children:y,..._}=h,j=v.useRef(null),C=Te(b,j),I=a(m,w);return v.useEffect(()=>(I.itemMap.set(j,{ref:j,..._}),()=>void I.itemMap.delete(j))),n.jsx(p,{[u]:"",ref:C,children:y})});f.displayName=m;function g(h){const b=a(e+"CollectionConsumer",h);return v.useCallback(()=>{const y=b.collectionRef.current;if(!y)return[];const _=Array.from(y.querySelectorAll(`[${u}]`));return Array.from(b.itemMap.values()).sort((I,S)=>_.indexOf(I.ref.current)-_.indexOf(S.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:i,Slot:d,ItemSlot:f},g,s]}var r_=x.createContext(void 0);function zs(e){const t=x.useContext(r_);return e||t||"ltr"}function s_(e){const t=o_(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(i_);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 o_(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=l_(o),c=c_(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 a_=Symbol("radix.slottable");function i_(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===a_}function c_(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 l_(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 d_=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ve=d_.reduce((e,t)=>{const r=s_(`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 u_(e,t){e&&Ts.flushSync(()=>e.dispatchEvent(t))}function dn(e){const t=x.useRef(e);return x.useEffect(()=>{t.current=e}),x.useMemo(()=>(...r)=>t.current?.(...r),[])}function m_(e,t=globalThis?.document){const r=dn(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 p_="DismissableLayer",oa="dismissableLayer.update",f_="dismissableLayer.pointerDownOutside",h_="dismissableLayer.focusOutside",zc,du=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(du),[m,u]=x.useState(null),p=m?.ownerDocument??globalThis?.document,[,f]=x.useState({}),g=Te(t,S=>u(S)),h=Array.from(d.layers),[b]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),w=h.indexOf(b),y=m?h.indexOf(m):-1,_=d.layersWithOutsidePointerEventsDisabled.size>0,j=y>=w,C=x_(S=>{const N=S.target,$=[...d.branches].some(k=>k.contains(N));!j||$||(o?.(S),i?.(S),S.defaultPrevented||c?.())},p),I=v_(S=>{const N=S.target;[...d.branches].some(k=>k.contains(N))||(a?.(S),i?.(S),S.defaultPrevented||c?.())},p);return m_(S=>{y===d.layers.size-1&&(s?.(S),!S.defaultPrevented&&c&&(S.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 S=()=>f({});return document.addEventListener(oa,S),()=>document.removeEventListener(oa,S)},[]),n.jsx(ve.div,{...l,ref:g,style:{pointerEvents:_?j?"auto":"none":void 0,...e.style},onFocusCapture:we(e.onFocusCapture,I.onFocusCapture),onBlurCapture:we(e.onBlurCapture,I.onBlurCapture),onPointerDownCapture:we(e.onPointerDownCapture,C.onPointerDownCapture)})});Ka.displayName=p_;var g_="DismissableLayerBranch",y_=x.forwardRef((e,t)=>{const r=x.useContext(du),s=x.useRef(null),o=Te(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})});y_.displayName=g_;function x_(e,t=globalThis?.document){const r=dn(e),s=x.useRef(!1),o=x.useRef(()=>{});return x.useEffect(()=>{const a=c=>{if(c.target&&!s.current){let l=function(){uu(f_,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 v_(e,t=globalThis?.document){const r=dn(e),s=x.useRef(!1);return x.useEffect(()=>{const o=a=>{a.target&&!s.current&&uu(h_,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 uu(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?u_(o,a):o.dispatchEvent(a)}var To=0;function mu(){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()),To++,()=>{To===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),To--}},[])}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 Io="focusScope.autoFocusOnMount",Ro="focusScope.autoFocusOnUnmount",Uc={bubbles:!1,cancelable:!0},b_="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=dn(o),m=dn(a),u=x.useRef(null),p=Te(t,h=>l(h)),f=x.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;x.useEffect(()=>{if(s){let h=function(_){if(f.paused||!c)return;const j=_.target;c.contains(j)?u.current=j:on(u.current,{select:!0})},b=function(_){if(f.paused||!c)return;const j=_.relatedTarget;j!==null&&(c.contains(j)||on(u.current,{select:!0}))},w=function(_){if(document.activeElement===document.body)for(const C of _)C.removedNodes.length>0&&on(c)};document.addEventListener("focusin",h),document.addEventListener("focusout",b);const y=new MutationObserver(w);return c&&y.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",b),y.disconnect()}}},[s,c,f.paused]),x.useEffect(()=>{if(c){qc.add(f);const h=document.activeElement;if(!c.contains(h)){const w=new CustomEvent(Io,Uc);c.addEventListener(Io,d),c.dispatchEvent(w),w.defaultPrevented||(__(C_(pu(c)),{select:!0}),document.activeElement===h&&on(c))}return()=>{c.removeEventListener(Io,d),setTimeout(()=>{const w=new CustomEvent(Ro,Uc);c.addEventListener(Ro,m),c.dispatchEvent(w),w.defaultPrevented||on(h??document.body,{select:!0}),c.removeEventListener(Ro,m),qc.remove(f)},0)}}},[c,d,m,f]);const g=x.useCallback(h=>{if(!r&&!s||f.paused)return;const b=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,w=document.activeElement;if(b&&w){const y=h.currentTarget,[_,j]=w_(y);_&&j?!h.shiftKey&&w===j?(h.preventDefault(),r&&on(_,{select:!0})):h.shiftKey&&w===_&&(h.preventDefault(),r&&on(j,{select:!0})):w===y&&h.preventDefault()}},[r,s,f.paused]);return n.jsx(ve.div,{tabIndex:-1,...i,ref:p,onKeyDown:g})});Xa.displayName=b_;function __(e,{select:t=!1}={}){const r=document.activeElement;for(const s of e)if(on(s,{select:t}),document.activeElement!==r)return}function w_(e){const t=pu(e),r=Wc(t,e),s=Wc(t.reverse(),e);return[r,s]}function pu(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(!j_(r,{upTo:t}))return r}function j_(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 k_(e){return e instanceof HTMLInputElement&&"select"in e}function on(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&k_(e)&&t&&e.select()}}var qc=S_();function S_(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=Vc(e,t),e.unshift(t)},remove(t){e=Vc(e,t),e[0]?.resume()}}}function Vc(e,t){const r=[...e],s=r.indexOf(t);return s!==-1&&r.splice(s,1),r}function C_(e){return e.filter(t=>t.tagName!=="A")}var et=globalThis?.document?x.useLayoutEffect:()=>{},N_=x[" useId ".trim().toString()]||(()=>{}),P_=0;function Wt(e){const[t,r]=x.useState(N_());return et(()=>{r(s=>s??String(P_++))},[e]),t?`radix-${t}`:""}const A_=["top","right","bottom","left"],un=Math.min,bt=Math.max,_s=Math.round,Kr=Math.floor,qt=e=>({x:e,y:e}),E_={left:"right",right:"left",bottom:"top",top:"bottom"},T_={start:"end",end:"start"};function aa(e,t,r){return bt(e,un(t,r))}function tn(e,t){return typeof e=="function"?e(t):e}function nn(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 I_=new Set(["top","bottom"]);function Ut(e){return I_.has(nn(e))?"y":"x"}function ti(e){return Ja(Ut(e))}function R_(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=ws(i)),[i,ws(i)]}function O_(e){const t=ws(e);return[ia(e),t,ia(t)]}function ia(e){return e.replace(/start|end/g,t=>T_[t])}const Hc=["left","right"],Zc=["right","left"],M_=["top","bottom"],D_=["bottom","top"];function L_(e,t,r){switch(e){case"top":case"bottom":return r?t?Zc:Hc:t?Hc:Zc;case"left":case"right":return t?M_:D_;default:return[]}}function $_(e,t,r,s){const o=lr(e);let a=L_(nn(e),r==="start",s);return o&&(a=a.map(i=>i+"-"+o),t&&(a=a.concat(a.map(ia)))),a}function ws(e){return e.replace(/left|right|bottom|top/g,t=>E_[t])}function z_(e){return{top:0,right:0,bottom:0,left:0,...e}}function fu(e){return typeof e!="number"?z_(e):{top:e,right:e,bottom:e,left:e}}function js(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=Ut(t),i=ti(t),c=ei(i),l=nn(t),d=a==="y",m=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[c]/2-o[c]/2;let f;switch(l){case"top":f={x:m,y:s.y-o.height};break;case"bottom":f={x:m,y:s.y+s.height};break;case"right":f={x:s.x+s.width,y:u};break;case"left":f={x:s.x-o.width,y:u};break;default:f={x:s.x,y:s.y}}switch(lr(t)){case"start":f[i]-=p*(r&&d?-1:1);break;case"end":f[i]+=p*(r&&d?-1:1);break}return f}const F_=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,f={},g=0;for(let h=0;h<c.length;h++){const{name:b,fn:w}=c[h],{x:y,y:_,data:j,reset:C}=await w({x:m,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:f,rects:d,platform:i,elements:{reference:e,floating:t}});m=y??m,u=_??u,f={...f,[b]:{...f[b],...j}},C&&g<=50&&(g++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(d=C.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:m,y:u}=Gc(d,p,l)),h=-1)}return{x:m,y:u,placement:p,strategy:o,middlewareData:f}};async function Tr(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:f=0}=tn(t,e),g=fu(f),b=c[p?u==="floating"?"reference":"floating":u],w=js(await a.getClippingRect({element:(r=await(a.isElement==null?void 0:a.isElement(b)))==null||r?b:b.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(c.floating)),boundary:d,rootBoundary:m,strategy:l})),y=u==="floating"?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,_=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),j=await(a.isElement==null?void 0:a.isElement(_))?await(a.getScale==null?void 0:a.getScale(_))||{x:1,y:1}:{x:1,y:1},C=js(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:y,offsetParent:_,strategy:l}):y);return{top:(w.top-C.top+g.top)/j.y,bottom:(C.bottom-w.bottom+g.bottom)/j.y,left:(w.left-C.left+g.left)/j.x,right:(C.right-w.right+g.right)/j.x}}const B_=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:s,placement:o,rects:a,platform:i,elements:c,middlewareData:l}=t,{element:d,padding:m=0}=tn(e,t)||{};if(d==null)return{};const u=fu(m),p={x:r,y:s},f=ti(o),g=ei(f),h=await i.getDimensions(d),b=f==="y",w=b?"top":"left",y=b?"bottom":"right",_=b?"clientHeight":"clientWidth",j=a.reference[g]+a.reference[f]-p[f]-a.floating[g],C=p[f]-a.reference[f],I=await(i.getOffsetParent==null?void 0:i.getOffsetParent(d));let S=I?I[_]:0;(!S||!await(i.isElement==null?void 0:i.isElement(I)))&&(S=c.floating[_]||a.floating[g]);const N=j/2-C/2,$=S/2-h[g]/2-1,k=un(u[w],$),P=un(u[y],$),A=k,L=S-h[g]-P,z=S/2-h[g]/2+N,D=aa(A,z,L),R=!l.arrow&&lr(o)!=null&&z!==D&&a.reference[g]/2-(z<A?k:P)-h[g]/2<0,O=R?z<A?z-A:z-L:0;return{[f]:p[f]+O,data:{[f]:D,centerOffset:z-D-O,...R&&{alignmentOffset:O}},reset:R}}}),U_=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:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:h=!0,...b}=tn(e,t);if((r=a.arrow)!=null&&r.alignmentOffset)return{};const w=nn(o),y=Ut(c),_=nn(c)===c,j=await(l.isRTL==null?void 0:l.isRTL(d.floating)),C=p||(_||!h?[ws(c)]:O_(c)),I=g!=="none";!p&&I&&C.push(...$_(c,h,g,j));const S=[c,...C],N=await Tr(t,b),$=[];let k=((s=a.flip)==null?void 0:s.overflows)||[];if(m&&$.push(N[w]),u){const z=R_(o,i,j);$.push(N[z[0]],N[z[1]])}if(k=[...k,{placement:o,overflows:$}],!$.every(z=>z<=0)){var P,A;const z=(((P=a.flip)==null?void 0:P.index)||0)+1,D=S[z];if(D&&(!(u==="alignment"?y!==Ut(D):!1)||k.every(T=>Ut(T.placement)===y?T.overflows[0]>0:!0)))return{data:{index:z,overflows:k},reset:{placement:D}};let R=(A=k.filter(O=>O.overflows[0]<=0).sort((O,T)=>O.overflows[1]-T.overflows[1])[0])==null?void 0:A.placement;if(!R)switch(f){case"bestFit":{var L;const O=(L=k.filter(T=>{if(I){const W=Ut(T.placement);return W===y||W==="y"}return!0}).map(T=>[T.placement,T.overflows.filter(W=>W>0).reduce((W,E)=>W+E,0)]).sort((T,W)=>T[1]-W[1])[0])==null?void 0:L[0];O&&(R=O);break}case"initialPlacement":R=c;break}if(o!==R)return{reset:{placement:R}}}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 A_.some(t=>e[t]>=0)}const W_=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:s="referenceHidden",...o}=tn(e,t);switch(s){case"referenceHidden":{const a=await Tr(t,{...o,elementContext:"reference"}),i=Qc(a,r.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Yc(i)}}}case"escaped":{const a=await Tr(t,{...o,altBoundary:!0}),i=Qc(a,r.floating);return{data:{escapedOffsets:i,escaped:Yc(i)}}}default:return{}}}}},hu=new Set(["left","top"]);async function q_(e,t){const{placement:r,platform:s,elements:o}=e,a=await(s.isRTL==null?void 0:s.isRTL(o.floating)),i=nn(r),c=lr(r),l=Ut(r)==="y",d=hu.has(i)?-1:1,m=a&&l?-1:1,u=tn(t,e);let{mainAxis:p,crossAxis:f,alignmentAxis:g}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return c&&typeof g=="number"&&(f=c==="end"?g*-1:g),l?{x:f*m,y:p*d}:{x:p*d,y:f*m}}const V_=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 q_(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}}}}},H_=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:b=>{let{x:w,y}=b;return{x:w,y}}},...l}=tn(e,t),d={x:r,y:s},m=await Tr(t,l),u=Ut(nn(o)),p=Ja(u);let f=d[p],g=d[u];if(a){const b=p==="y"?"top":"left",w=p==="y"?"bottom":"right",y=f+m[b],_=f-m[w];f=aa(y,f,_)}if(i){const b=u==="y"?"top":"left",w=u==="y"?"bottom":"right",y=g+m[b],_=g-m[w];g=aa(y,g,_)}const h=c.fn({...t,[p]:f,[u]:g});return{...h,data:{x:h.x-r,y:h.y-s,enabled:{[p]:a,[u]:i}}}}}},Z_=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:r,y:s,placement:o,rects:a,middlewareData:i}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=tn(e,t),m={x:r,y:s},u=Ut(o),p=Ja(u);let f=m[p],g=m[u];const h=tn(c,t),b=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){const _=p==="y"?"height":"width",j=a.reference[p]-a.floating[_]+b.mainAxis,C=a.reference[p]+a.reference[_]-b.mainAxis;f<j?f=j:f>C&&(f=C)}if(d){var w,y;const _=p==="y"?"width":"height",j=hu.has(nn(o)),C=a.reference[u]-a.floating[_]+(j&&((w=i.offset)==null?void 0:w[u])||0)+(j?0:b.crossAxis),I=a.reference[u]+a.reference[_]+(j?0:((y=i.offset)==null?void 0:y[u])||0)-(j?b.crossAxis:0);g<C?g=C:g>I&&(g=I)}return{[p]:f,[u]:g}}}},G_=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var r,s;const{placement:o,rects:a,platform:i,elements:c}=t,{apply:l=()=>{},...d}=tn(e,t),m=await Tr(t,d),u=nn(o),p=lr(o),f=Ut(o)==="y",{width:g,height:h}=a.floating;let b,w;u==="top"||u==="bottom"?(b=u,w=p===(await(i.isRTL==null?void 0:i.isRTL(c.floating))?"start":"end")?"left":"right"):(w=u,b=p==="end"?"top":"bottom");const y=h-m.top-m.bottom,_=g-m.left-m.right,j=un(h-m[b],y),C=un(g-m[w],_),I=!t.middlewareData.shift;let S=j,N=C;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(N=_),(s=t.middlewareData.shift)!=null&&s.enabled.y&&(S=y),I&&!p){const k=bt(m.left,0),P=bt(m.right,0),A=bt(m.top,0),L=bt(m.bottom,0);f?N=g-2*(k!==0||P!==0?k+P:bt(m.left,m.right)):S=h-2*(A!==0||L!==0?A+L:bt(m.top,m.bottom))}await l({...t,availableWidth:N,availableHeight:S});const $=await i.getDimensions(c.floating);return g!==$.width||h!==$.height?{reset:{rects:!0}}:{}}}};function Fs(){return typeof window<"u"}function dr(e){return gu(e)?(e.nodeName||"").toLowerCase():"#document"}function _t(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Gt(e){var t;return(t=(gu(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function gu(e){return Fs()?e instanceof Node||e instanceof _t(e).Node:!1}function Rt(e){return Fs()?e instanceof Element||e instanceof _t(e).Element:!1}function Zt(e){return Fs()?e instanceof HTMLElement||e instanceof _t(e).HTMLElement:!1}function Kc(e){return!Fs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof _t(e).ShadowRoot}const Q_=new Set(["inline","contents"]);function $r(e){const{overflow:t,overflowX:r,overflowY:s,display:o}=Ot(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+r)&&!Q_.has(o)}const Y_=new Set(["table","td","th"]);function K_(e){return Y_.has(dr(e))}const X_=[":popover-open",":modal"];function Bs(e){return X_.some(t=>{try{return e.matches(t)}catch{return!1}})}const J_=["transform","translate","scale","rotate","perspective"],ew=["transform","translate","scale","rotate","perspective","filter"],tw=["paint","layout","strict","content"];function ni(e){const t=ri(),r=Rt(e)?Ot(e):e;return J_.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)||ew.some(s=>(r.willChange||"").includes(s))||tw.some(s=>(r.contain||"").includes(s))}function nw(e){let t=mn(e);for(;Zt(t)&&!er(t);){if(ni(t))return t;if(Bs(t))return null;t=mn(t)}return null}function ri(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const rw=new Set(["html","body","#document"]);function er(e){return rw.has(dr(e))}function Ot(e){return _t(e).getComputedStyle(e)}function Us(e){return Rt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function mn(e){if(dr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Kc(e)&&e.host||Gt(e);return Kc(t)?t.host:t}function yu(e){const t=mn(e);return er(t)?e.ownerDocument?e.ownerDocument.body:e.body:Zt(t)&&$r(t)?t:yu(t)}function Ir(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||[],$r(o)?o:[],c&&r?Ir(c):[])}return t.concat(o,Ir(o,[],r))}function ca(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function xu(e){const t=Ot(e);let r=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Zt(e),a=o?e.offsetWidth:r,i=o?e.offsetHeight:s,c=_s(r)!==a||_s(s)!==i;return c&&(r=a,s=i),{width:r,height:s,$:c}}function si(e){return Rt(e)?e:e.contextElement}function Xn(e){const t=si(e);if(!Zt(t))return qt(1);const r=t.getBoundingClientRect(),{width:s,height:o,$:a}=xu(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 sw=qt(0);function vu(e){const t=_t(e);return!ri()||!t.visualViewport?sw:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function ow(e,t,r){return t===void 0&&(t=!1),!r||t&&r!==_t(e)?!1:t}function An(e,t,r,s){t===void 0&&(t=!1),r===void 0&&(r=!1);const o=e.getBoundingClientRect(),a=si(e);let i=qt(1);t&&(s?Rt(s)&&(i=Xn(s)):i=Xn(e));const c=ow(a,r,s)?vu(a):qt(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),f=s&&Rt(s)?_t(s):s;let g=p,h=ca(g);for(;h&&s&&f!==g;){const b=Xn(h),w=h.getBoundingClientRect(),y=Ot(h),_=w.left+(h.clientLeft+parseFloat(y.paddingLeft))*b.x,j=w.top+(h.clientTop+parseFloat(y.paddingTop))*b.y;l*=b.x,d*=b.y,m*=b.x,u*=b.y,l+=_,d+=j,g=_t(h),h=ca(g)}}return js({width:m,height:u,x:l,y:d})}function Ws(e,t){const r=Us(e).scrollLeft;return t?t.left+r:An(Gt(e)).left+r}function bu(e,t){const r=e.getBoundingClientRect(),s=r.left+t.scrollLeft-Ws(e,r),o=r.top+t.scrollTop;return{x:s,y:o}}function aw(e){let{elements:t,rect:r,offsetParent:s,strategy:o}=e;const a=o==="fixed",i=Gt(s),c=t?Bs(t.floating):!1;if(s===i||c&&a)return r;let l={scrollLeft:0,scrollTop:0},d=qt(1);const m=qt(0),u=Zt(s);if((u||!u&&!a)&&((dr(s)!=="body"||$r(i))&&(l=Us(s)),Zt(s))){const f=An(s);d=Xn(s),m.x=f.x+s.clientLeft,m.y=f.y+s.clientTop}const p=i&&!u&&!a?bu(i,l):qt(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 iw(e){return Array.from(e.getClientRects())}function cw(e){const t=Gt(e),r=Us(e),s=e.ownerDocument.body,o=bt(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),a=bt(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-r.scrollLeft+Ws(e);const c=-r.scrollTop;return Ot(s).direction==="rtl"&&(i+=bt(t.clientWidth,s.clientWidth)-o),{width:o,height:a,x:i,y:c}}const Xc=25;function lw(e,t){const r=_t(e),s=Gt(e),o=r.visualViewport;let a=s.clientWidth,i=s.clientHeight,c=0,l=0;if(o){a=o.width,i=o.height;const m=ri();(!m||m&&t==="fixed")&&(c=o.offsetLeft,l=o.offsetTop)}const d=Ws(s);if(d<=0){const m=s.ownerDocument,u=m.body,p=getComputedStyle(u),f=m.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,g=Math.abs(s.clientWidth-u.clientWidth-f);g<=Xc&&(a-=g)}else d<=Xc&&(a+=d);return{width:a,height:i,x:c,y:l}}const dw=new Set(["absolute","fixed"]);function uw(e,t){const r=An(e,!0,t==="fixed"),s=r.top+e.clientTop,o=r.left+e.clientLeft,a=Zt(e)?Xn(e):qt(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=lw(e,r);else if(t==="document")s=cw(Gt(e));else if(Rt(t))s=uw(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 js(s)}function _u(e,t){const r=mn(e);return r===t||!Rt(r)||er(r)?!1:Ot(r).position==="fixed"||_u(r,t)}function mw(e,t){const r=t.get(e);if(r)return r;let s=Ir(e,[],!1).filter(c=>Rt(c)&&dr(c)!=="body"),o=null;const a=Ot(e).position==="fixed";let i=a?mn(e):e;for(;Rt(i)&&!er(i);){const c=Ot(i),l=ni(i);!l&&c.position==="fixed"&&(o=null),(a?!l&&!o:!l&&c.position==="static"&&!!o&&dw.has(o.position)||$r(i)&&!l&&_u(e,i))?s=s.filter(m=>m!==i):o=c,i=mn(i)}return t.set(e,s),s}function pw(e){let{element:t,boundary:r,rootBoundary:s,strategy:o}=e;const i=[...r==="clippingAncestors"?Bs(t)?[]:mw(t,this._c):[].concat(r),s],c=i[0],l=i.reduce((d,m)=>{const u=Jc(t,m,o);return d.top=bt(u.top,d.top),d.right=un(u.right,d.right),d.bottom=un(u.bottom,d.bottom),d.left=bt(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 fw(e){const{width:t,height:r}=xu(e);return{width:t,height:r}}function hw(e,t,r){const s=Zt(t),o=Gt(t),a=r==="fixed",i=An(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=qt(0);function d(){l.x=Ws(o)}if(s||!s&&!a)if((dr(t)!=="body"||$r(o))&&(c=Us(t)),s){const f=An(t,!0,a,t);l.x=f.x+t.clientLeft,l.y=f.y+t.clientTop}else o&&d();a&&!s&&o&&d();const m=o&&!s&&!a?bu(o,c):qt(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 Oo(e){return Ot(e).position==="static"}function el(e,t){if(!Zt(e)||Ot(e).position==="fixed")return null;if(t)return t(e);let r=e.offsetParent;return Gt(e)===r&&(r=r.ownerDocument.body),r}function wu(e,t){const r=_t(e);if(Bs(e))return r;if(!Zt(e)){let o=mn(e);for(;o&&!er(o);){if(Rt(o)&&!Oo(o))return o;o=mn(o)}return r}let s=el(e,t);for(;s&&K_(s)&&Oo(s);)s=el(s,t);return s&&er(s)&&Oo(s)&&!ni(s)?r:s||nw(e)||r}const gw=async function(e){const t=this.getOffsetParent||wu,r=this.getDimensions,s=await r(e.floating);return{reference:hw(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function yw(e){return Ot(e).direction==="rtl"}const xw={convertOffsetParentRelativeRectToViewportRelativeRect:aw,getDocumentElement:Gt,getClippingRect:pw,getOffsetParent:wu,getElementRects:gw,getClientRects:iw,getDimensions:fw,getScale:Xn,isElement:Rt,isRTL:yw};function ju(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function vw(e,t){let r=null,s;const o=Gt(e);function a(){var c;clearTimeout(s),(c=r)==null||c.disconnect(),r=null}function i(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:m,top:u,width:p,height:f}=d;if(c||t(),!p||!f)return;const g=Kr(u),h=Kr(o.clientWidth-(m+p)),b=Kr(o.clientHeight-(u+f)),w=Kr(m),_={rootMargin:-g+"px "+-h+"px "+-b+"px "+-w+"px",threshold:bt(0,un(1,l))||1};let j=!0;function C(I){const S=I[0].intersectionRatio;if(S!==l){if(!j)return i();S?i(!1,S):s=setTimeout(()=>{i(!1,1e-7)},1e3)}S===1&&!ju(d,e.getBoundingClientRect())&&i(),j=!1}try{r=new IntersectionObserver(C,{..._,root:o.ownerDocument})}catch{r=new IntersectionObserver(C,_)}r.observe(e)}return i(!0),a}function bw(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?Ir(d):[],...Ir(t)]:[];m.forEach(w=>{o&&w.addEventListener("scroll",r,{passive:!0}),a&&w.addEventListener("resize",r)});const u=d&&c?vw(d,r):null;let p=-1,f=null;i&&(f=new ResizeObserver(w=>{let[y]=w;y&&y.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var _;(_=f)==null||_.observe(t)})),r()}),d&&!l&&f.observe(d),f.observe(t));let g,h=l?An(e):null;l&&b();function b(){const w=An(e);h&&!ju(h,w)&&r(),h=w,g=requestAnimationFrame(b)}return r(),()=>{var w;m.forEach(y=>{o&&y.removeEventListener("scroll",r),a&&y.removeEventListener("resize",r)}),u?.(),(w=f)==null||w.disconnect(),f=null,l&&cancelAnimationFrame(g)}}const _w=V_,ww=H_,jw=U_,kw=G_,Sw=W_,tl=B_,Cw=Z_,Nw=(e,t,r)=>{const s=new Map,o={platform:xw,...r},a={...o.platform,_c:s};return F_(e,t,{...o,platform:a})};var Pw=typeof document<"u",Aw=function(){},cs=Pw?v.useLayoutEffect:Aw;function ks(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(!ks(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)&&!ks(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function ku(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function nl(e,t){const r=ku(e);return Math.round(t*r)/r}function Mo(e){const t=x.useRef(e);return cs(()=>{t.current=e}),t}function Ew(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,f]=x.useState(s);ks(p,s)||f(s);const[g,h]=x.useState(null),[b,w]=x.useState(null),y=x.useCallback(T=>{T!==I.current&&(I.current=T,h(T))},[]),_=x.useCallback(T=>{T!==S.current&&(S.current=T,w(T))},[]),j=a||g,C=i||b,I=x.useRef(null),S=x.useRef(null),N=x.useRef(m),$=l!=null,k=Mo(l),P=Mo(o),A=Mo(d),L=x.useCallback(()=>{if(!I.current||!S.current)return;const T={placement:t,strategy:r,middleware:p};P.current&&(T.platform=P.current),Nw(I.current,S.current,T).then(W=>{const E={...W,isPositioned:A.current!==!1};z.current&&!ks(N.current,E)&&(N.current=E,Ts.flushSync(()=>{u(E)}))})},[p,t,r,P,A]);cs(()=>{d===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,u(T=>({...T,isPositioned:!1})))},[d]);const z=x.useRef(!1);cs(()=>(z.current=!0,()=>{z.current=!1}),[]),cs(()=>{if(j&&(I.current=j),C&&(S.current=C),j&&C){if(k.current)return k.current(j,C,L);L()}},[j,C,L,k,$]);const D=x.useMemo(()=>({reference:I,floating:S,setReference:y,setFloating:_}),[y,_]),R=x.useMemo(()=>({reference:j,floating:C}),[j,C]),O=x.useMemo(()=>{const T={position:r,left:0,top:0};if(!R.floating)return T;const W=nl(R.floating,m.x),E=nl(R.floating,m.y);return c?{...T,transform:"translate("+W+"px, "+E+"px)",...ku(R.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:W,top:E}},[r,c,R.floating,m.x,m.y]);return x.useMemo(()=>({...m,update:L,refs:D,elements:R,floatingStyles:O}),[m,L,D,R,O])}const Tw=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):{}}}},Iw=(e,t)=>({..._w(e),options:[e,t]}),Rw=(e,t)=>({...ww(e),options:[e,t]}),Ow=(e,t)=>({...Cw(e),options:[e,t]}),Mw=(e,t)=>({...jw(e),options:[e,t]}),Dw=(e,t)=>({...kw(e),options:[e,t]}),Lw=(e,t)=>({...Sw(e),options:[e,t]}),$w=(e,t)=>({...Tw(e),options:[e,t]});var zw="Arrow",Su=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"})})});Su.displayName=zw;var Fw=Su;function Bw(e){const[t,r]=x.useState(void 0);return et(()=>{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",[Cu,Nu]=xn(oi),[Uw,Pu]=Cu(oi),Au=e=>{const{__scopePopper:t,children:r}=e,[s,o]=x.useState(null);return n.jsx(Uw,{scope:t,anchor:s,onAnchorChange:o,children:r})};Au.displayName=oi;var Eu="PopperAnchor",Tu=x.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:s,...o}=e,a=Pu(Eu,r),i=x.useRef(null),c=Te(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})});Tu.displayName=Eu;var ai="PopperContent",[Ww,qw]=Cu(ai),Iu=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:f="optimized",onPlaced:g,...h}=e,b=Pu(ai,r),[w,y]=x.useState(null),_=Te(t,B=>y(B)),[j,C]=x.useState(null),I=Bw(j),S=I?.width??0,N=I?.height??0,$=s+(a!=="center"?"-"+a:""),k=typeof m=="number"?m:{top:0,right:0,bottom:0,left:0,...m},P=Array.isArray(d)?d:[d],A=P.length>0,L={padding:k,boundary:P.filter(Hw),altBoundary:A},{refs:z,floatingStyles:D,placement:R,isPositioned:O,middlewareData:T}=Ew({strategy:"fixed",placement:$,whileElementsMounted:(...B)=>bw(...B,{animationFrame:f==="always"}),elements:{reference:b.anchor},middleware:[Iw({mainAxis:o+N,alignmentAxis:i}),l&&Rw({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?Ow():void 0,...L}),l&&Mw({...L}),Dw({...L,apply:({elements:B,rects:X,availableWidth:me,availableHeight:V})=>{const{width:re,height:le}=X.reference,pe=B.floating.style;pe.setProperty("--radix-popper-available-width",`${me}px`),pe.setProperty("--radix-popper-available-height",`${V}px`),pe.setProperty("--radix-popper-anchor-width",`${re}px`),pe.setProperty("--radix-popper-anchor-height",`${le}px`)}}),j&&$w({element:j,padding:c}),Zw({arrowWidth:S,arrowHeight:N}),p&&Lw({strategy:"referenceHidden",...L})]}),[W,E]=Mu(R),q=dn(g);et(()=>{O&&q?.()},[O,q]);const ne=T.arrow?.x,U=T.arrow?.y,K=T.arrow?.centerOffset!==0,[J,he]=x.useState();return et(()=>{w&&he(window.getComputedStyle(w).zIndex)},[w]),n.jsx("div",{ref:z.setFloating,"data-radix-popper-content-wrapper":"",style:{...D,transform:O?D.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:J,"--radix-popper-transform-origin":[T.transformOrigin?.x,T.transformOrigin?.y].join(" "),...T.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:n.jsx(Ww,{scope:r,placedSide:W,onArrowChange:C,arrowX:ne,arrowY:U,shouldHideArrow:K,children:n.jsx(ve.div,{"data-side":W,"data-align":E,...h,ref:_,style:{...h.style,animation:O?void 0:"none"}})})})});Iu.displayName=ai;var Ru="PopperArrow",Vw={top:"bottom",right:"left",bottom:"top",left:"right"},Ou=x.forwardRef(function(t,r){const{__scopePopper:s,...o}=t,a=qw(Ru,s),i=Vw[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(Fw,{...o,ref:r,style:{...o.style,display:"block"}})})});Ou.displayName=Ru;function Hw(e){return e!==null}var Zw=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]=Mu(r),u={start:"0%",center:"50%",end:"100%"}[m],p=(o.arrow?.x??0)+c/2,f=(o.arrow?.y??0)+l/2;let g="",h="";return d==="bottom"?(g=i?u:`${p}px`,h=`${-l}px`):d==="top"?(g=i?u:`${p}px`,h=`${s.floating.height+l}px`):d==="right"?(g=`${-l}px`,h=i?u:`${f}px`):d==="left"&&(g=`${s.floating.width+l}px`,h=i?u:`${f}px`),{data:{x:g,y:h}}}});function Mu(e){const[t,r="center"]=e.split("-");return[t,r]}var Gw=Au,Qw=Tu,Yw=Iu,Kw=Ou,Xw="Portal",ii=x.forwardRef((e,t)=>{const{container:r,...s}=e,[o,a]=x.useState(!1);et(()=>a(!0),[]);const i=r||o&&globalThis?.document?.body;return i?ka.createPortal(n.jsx(ve.div,{...s,ref:t}),i):null});ii.displayName=Xw;function Jw(e){const t=ej(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(nj);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 ej(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=sj(o),c=rj(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 tj=Symbol("radix.slottable");function nj(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===tj}function rj(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 sj(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 oj=x[" useInsertionEffect ".trim().toString()]||et;function pn({prop:e,defaultProp:t,onChange:r=()=>{},caller:s}){const[o,a,i]=aj({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=ij(m)?m(e):m;u!==e&&i.current?.(u)}else a(m)},[c,e,a,i]);return[l,d]}function aj({defaultProp:e,onChange:t}){const[r,s]=x.useState(e),o=x.useRef(r),a=x.useRef(t);return oj(()=>{a.current=t},[t]),x.useEffect(()=>{o.current!==r&&(a.current?.(r),o.current=r)},[r,o]),[r,s,a]}function ij(e){return typeof e=="function"}function cj(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 Du=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"}),lj="VisuallyHidden",dj=x.forwardRef((e,t)=>n.jsx(ve.span,{...e,ref:t,style:{...Du,...e.style}}));dj.displayName=lj;var uj=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Zn=new WeakMap,Xr=new WeakMap,Jr={},Do=0,Lu=function(e){return e&&(e.host||Lu(e.parentNode))},mj=function(e,t){return t.map(function(r){if(e.contains(r))return r;var s=Lu(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})},pj=function(e,t,r,s){var o=mj(t,Array.isArray(e)?e:[e]);Jr[r]||(Jr[r]=new WeakMap);var a=Jr[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 f=p.getAttribute(s),g=f!==null&&f!=="false",h=(Zn.get(p)||0)+1,b=(a.get(p)||0)+1;Zn.set(p,h),a.set(p,b),i.push(p),h===1&&g&&Xr.set(p,!0),b===1&&p.setAttribute(r,"true"),g||p.setAttribute(s,"true")}catch(w){console.error("aria-hidden: cannot operate on ",p,w)}})};return m(t),c.clear(),Do++,function(){i.forEach(function(u){var p=Zn.get(u)-1,f=a.get(u)-1;Zn.set(u,p),a.set(u,f),p||(Xr.has(u)||u.removeAttribute(s),Xr.delete(u)),f||u.removeAttribute(r)}),Do--,Do||(Zn=new WeakMap,Zn=new WeakMap,Xr=new WeakMap,Jr={})}},$u=function(e,t,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(e)?e:[e]),o=uj(e);return o?(s.push.apply(s,Array.from(o.querySelectorAll("[aria-live], script"))),pj(s,o,r,"aria-hidden")):function(){return null}},Bt=function(){return Bt=Object.assign||function(t){for(var r,s=1,o=arguments.length;s<o;s++){r=arguments[s];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])}return t},Bt.apply(this,arguments)};function zu(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 fj(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 ls="right-scroll-bar-position",ds="width-before-scroll-bar",hj="with-scroll-bars-hidden",gj="--removed-body-scroll-bar-size";function Lo(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function yj(e,t){var r=v.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 xj=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 Lo(o,s)})});return xj(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)||Lo(c,null)}),a.forEach(function(c){o.has(c)||Lo(c,i)})}rl.set(r,e)},[e]),r}function bj(e){return e}function _j(e,t){t===void 0&&(t=bj);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 wj(e){e===void 0&&(e={});var t=_j(null);return t.options=Bt({async:!0,ssr:!1},e),t}var Fu=function(e){var t=e.sideCar,r=zu(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,Bt({},r))};Fu.isSideCarExport=!0;function jj(e,t){return e.useMedium(t),Fu}var Bu=wj(),$o=function(){},qs=x.forwardRef(function(e,t){var r=x.useRef(null),s=x.useState({onScrollCapture:$o,onWheelCapture:$o,onTouchMoveCapture:$o}),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,f=e.noRelative,g=e.noIsolation,h=e.inert,b=e.allowPinchZoom,w=e.as,y=w===void 0?"div":w,_=e.gapMode,j=zu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,I=vj([r,t]),S=Bt(Bt({},j),o);return x.createElement(x.Fragment,null,m&&x.createElement(C,{sideCar:Bu,removeScrollBar:d,shards:u,noRelative:f,noIsolation:g,inert:h,setCallbacks:a,allowPinchZoom:!!b,lockRef:r,gapMode:_}),i?x.cloneElement(x.Children.only(c),Bt(Bt({},S),{ref:I})):x.createElement(y,Bt({},S,{className:l,ref:I}),c))});qs.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};qs.classNames={fullWidth:ds,zeroRight:ls};var kj=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Sj(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=kj();return t&&e.setAttribute("nonce",t),e}function Cj(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Nj(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Pj=function(){var e=0,t=null;return{add:function(r){e==0&&(t=Sj())&&(Cj(t,r),Nj(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Aj=function(){var e=Pj();return function(t,r){x.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])}},Uu=function(){var e=Aj(),t=function(r){var s=r.styles,o=r.dynamic;return e(s,o),null};return t},Ej={left:0,top:0,right:0,gap:0},zo=function(e){return parseInt(e||"",10)||0},Tj=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[zo(r),zo(s),zo(o)]},Ij=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Ej;var t=Tj(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])}},Rj=Uu(),Jn="data-scroll-locked",Oj=function(e,t,r,s){var o=e.left,a=e.top,i=e.right,c=e.gap;return r===void 0&&(r="margin"),`
92
- .`.concat(hj,` {
93
- overflow: hidden `).concat(s,`;
94
- padding-right: `).concat(c,"px ").concat(s,`;
95
- }
96
- body[`).concat(Jn,`] {
97
- overflow: hidden `).concat(s,`;
98
- overscroll-behavior: contain;
99
- `).concat([t&&"position: relative ".concat(s,";"),r==="margin"&&`
100
- padding-left: `.concat(o,`px;
101
- padding-top: `).concat(a,`px;
102
- padding-right: `).concat(i,`px;
103
- margin-left:0;
104
- margin-top:0;
105
- margin-right: `).concat(c,"px ").concat(s,`;
106
- `),r==="padding"&&"padding-right: ".concat(c,"px ").concat(s,";")].filter(Boolean).join(""),`
107
- }
108
-
109
- .`).concat(ls,` {
110
- right: `).concat(c,"px ").concat(s,`;
111
- }
112
-
113
- .`).concat(ds,` {
114
- margin-right: `).concat(c,"px ").concat(s,`;
115
- }
116
-
117
- .`).concat(ls," .").concat(ls,` {
118
- right: 0 `).concat(s,`;
119
- }
120
-
121
- .`).concat(ds," .").concat(ds,` {
122
- margin-right: 0 `).concat(s,`;
123
- }
124
-
125
- body[`).concat(Jn,`] {
126
- `).concat(gj,": ").concat(c,`px;
127
- }
128
- `)},sl=function(){var e=parseInt(document.body.getAttribute(Jn)||"0",10);return isFinite(e)?e:0},Mj=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())}},[])},Dj=function(e){var t=e.noRelative,r=e.noImportant,s=e.gapMode,o=s===void 0?"margin":s;Mj();var a=x.useMemo(function(){return Ij(o)},[o]);return x.createElement(Rj,{styles:Oj(a,!t,o,r?"":"!important")})},la=!1;if(typeof window<"u")try{var es=Object.defineProperty({},"passive",{get:function(){return la=!0,!0}});window.addEventListener("test",es,es),window.removeEventListener("test",es,es)}catch{la=!1}var Gn=la?{passive:!1}:!1,Lj=function(e){return e.tagName==="TEXTAREA"},Wu=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!Lj(e)&&r[t]==="visible")},$j=function(e){return Wu(e,"overflowY")},zj=function(e){return Wu(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=Vu(e,s),i=a[1],c=a[2];if(i>c)return!0}s=s.parentNode}while(s&&s!==r.body);return!1},Fj=function(e){var t=e.scrollTop,r=e.scrollHeight,s=e.clientHeight;return[t,r,s]},Bj=function(e){var t=e.scrollLeft,r=e.scrollWidth,s=e.clientWidth;return[t,r,s]},qu=function(e,t){return e==="v"?$j(t):zj(t)},Vu=function(e,t){return e==="v"?Fj(t):Bj(t)},Uj=function(e,t){return e==="h"&&t==="rtl"?-1:1},Wj=function(e,t,r,s,o){var a=Uj(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 f=Vu(e,c),g=f[0],h=f[1],b=f[2],w=h-b-a*g;(g||w)&&qu(e,c)&&(u+=w,p+=g);var y=c.parentNode;c=y&&y.nodeType===Node.DOCUMENT_FRAGMENT_NODE?y.host:y}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},ts=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]},Vj=function(e){return`
129
- .block-interactivity-`.concat(e,` {pointer-events: none;}
130
- .allow-interactivity-`).concat(e,` {pointer-events: all;}
131
- `)},Hj=0,Qn=[];function Zj(e){var t=x.useRef([]),r=x.useRef([0,0]),s=x.useRef(),o=x.useState(Hj++)[0],a=x.useState(Uu)[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 h=fj([e.lockRef.current],(e.shards||[]).map(il),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var c=x.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!i.current.allowPinchZoom;var w=ts(h),y=r.current,_="deltaX"in h?h.deltaX:y[0]-w[0],j="deltaY"in h?h.deltaY:y[1]-w[1],C,I=h.target,S=Math.abs(_)>Math.abs(j)?"h":"v";if("touches"in h&&S==="h"&&I.type==="range")return!1;var N=window.getSelection(),$=N&&N.anchorNode,k=$?$===I||$.contains(I):!1;if(k)return!1;var P=ol(S,I);if(!P)return!0;if(P?C=S:(C=S==="v"?"h":"v",P=ol(S,I)),!P)return!1;if(!s.current&&"changedTouches"in h&&(_||j)&&(s.current=C),!C)return!0;var A=s.current||C;return Wj(A,b,h,A==="h"?_:j)},[]),l=x.useCallback(function(h){var b=h;if(!(!Qn.length||Qn[Qn.length-1]!==a)){var w="deltaY"in b?al(b):ts(b),y=t.current.filter(function(C){return C.name===b.type&&(C.target===b.target||b.target===C.shadowParent)&&qj(C.delta,w)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var _=(i.current.shards||[]).map(il).filter(Boolean).filter(function(C){return C.contains(b.target)}),j=_.length>0?c(b,_[0]):!i.current.noIsolation;j&&b.cancelable&&b.preventDefault()}}},[]),d=x.useCallback(function(h,b,w,y){var _={name:h,delta:b,target:w,should:y,shadowParent:Gj(w)};t.current.push(_),setTimeout(function(){t.current=t.current.filter(function(j){return j!==_})},1)},[]),m=x.useCallback(function(h){r.current=ts(h),s.current=void 0},[]),u=x.useCallback(function(h){d(h.type,al(h),h.target,c(h,e.lockRef.current))},[]),p=x.useCallback(function(h){d(h.type,ts(h),h.target,c(h,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(h){return h!==a}),document.removeEventListener("wheel",l,Gn),document.removeEventListener("touchmove",l,Gn),document.removeEventListener("touchstart",m,Gn)}},[]);var f=e.removeScrollBar,g=e.inert;return x.createElement(x.Fragment,null,g?x.createElement(a,{styles:Vj(o)}):null,f?x.createElement(Dj,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Gj(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Qj=jj(Bu,Zj);var ci=x.forwardRef(function(e,t){return x.createElement(qs,Bt({},e,{ref:t,sideCar:Qj}))});ci.classNames=qs.classNames;var Yj=[" ","Enter","ArrowUp","ArrowDown"],Kj=[" ","Enter"],En="Select",[Vs,Hs,Xj]=Ya(En),[ur]=xn(En,[Xj,Nu]),Zs=Nu(),[Jj,vn]=ur(En),[ek,tk]=ur(En),Hu=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:f,form:g}=e,h=Zs(t),[b,w]=x.useState(null),[y,_]=x.useState(null),[j,C]=x.useState(!1),I=zs(d),[S,N]=pn({prop:s,defaultProp:o??!1,onChange:a,caller:En}),[$,k]=pn({prop:i,defaultProp:c,onChange:l,caller:En}),P=x.useRef(null),A=b?g||!!b.closest("form"):!0,[L,z]=x.useState(new Set),D=Array.from(L).map(R=>R.props.value).join(";");return n.jsx(Gw,{...h,children:n.jsxs(Jj,{required:f,scope:t,trigger:b,onTriggerChange:w,valueNode:y,onValueNodeChange:_,valueNodeHasChildren:j,onValueNodeHasChildrenChange:C,contentId:Wt(),value:$,onValueChange:k,open:S,onOpenChange:N,dir:I,triggerPointerDownPosRef:P,disabled:p,children:[n.jsx(Vs.Provider,{scope:t,children:n.jsx(ek,{scope:e.__scopeSelect,onNativeOptionAdd:x.useCallback(R=>{z(O=>new Set(O).add(R))},[]),onNativeOptionRemove:x.useCallback(R=>{z(O=>{const T=new Set(O);return T.delete(R),T})},[]),children:r})}),A?n.jsxs(mm,{"aria-hidden":!0,required:f,tabIndex:-1,name:m,autoComplete:u,value:$,onChange:R=>k(R.target.value),disabled:p,form:g,children:[$===void 0?n.jsx("option",{value:""}):null,Array.from(L)]},D):null]})})};Hu.displayName=En;var Zu="SelectTrigger",Gu=x.forwardRef((e,t)=>{const{__scopeSelect:r,disabled:s=!1,...o}=e,a=Zs(r),i=vn(Zu,r),c=i.disabled||s,l=Te(t,i.onTriggerChange),d=Hs(r),m=x.useRef("touch"),[u,p,f]=fm(h=>{const b=d().filter(_=>!_.disabled),w=b.find(_=>_.value===i.value),y=hm(b,h,w);y!==void 0&&i.onValueChange(y.value)}),g=h=>{c||(i.onOpenChange(!0),f()),h&&(i.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return n.jsx(Qw,{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":pm(i.value)?"":void 0,...o,ref:l,onClick:we(o.onClick,h=>{h.currentTarget.focus(),m.current!=="mouse"&&g(h)}),onPointerDown:we(o.onPointerDown,h=>{m.current=h.pointerType;const b=h.target;b.hasPointerCapture(h.pointerId)&&b.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:we(o.onKeyDown,h=>{const b=u.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&p(h.key),!(b&&h.key===" ")&&Yj.includes(h.key)&&(g(),h.preventDefault())})})})});Gu.displayName=Zu;var Qu="SelectValue",Yu=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,children:a,placeholder:i="",...c}=e,l=vn(Qu,r),{onValueNodeHasChildrenChange:d}=l,m=a!==void 0,u=Te(t,l.onValueNodeChange);return et(()=>{d(m)},[d,m]),n.jsx(ve.span,{...c,ref:u,style:{pointerEvents:"none"},children:pm(l.value)?n.jsx(n.Fragment,{children:i}):a})});Yu.displayName=Qu;var nk="SelectIcon",Ku=x.forwardRef((e,t)=>{const{__scopeSelect:r,children:s,...o}=e;return n.jsx(ve.span,{"aria-hidden":!0,...o,ref:t,children:s||"▼"})});Ku.displayName=nk;var rk="SelectPortal",Xu=e=>n.jsx(ii,{asChild:!0,...e});Xu.displayName=rk;var Tn="SelectContent",Ju=x.forwardRef((e,t)=>{const r=vn(Tn,e.__scopeSelect),[s,o]=x.useState();if(et(()=>{o(new DocumentFragment)},[]),!r.open){const a=s;return a?Ts.createPortal(n.jsx(em,{scope:e.__scopeSelect,children:n.jsx(Vs.Slot,{scope:e.__scopeSelect,children:n.jsx("div",{children:e.children})})}),a):null}return n.jsx(tm,{...e,ref:t})});Ju.displayName=Tn;var Et=10,[em,bn]=ur(Tn),sk="SelectContentImpl",ok=Jw("SelectContent.RemoveScroll"),tm=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:f,sticky:g,hideWhenDetached:h,avoidCollisions:b,...w}=e,y=vn(Tn,r),[_,j]=x.useState(null),[C,I]=x.useState(null),S=Te(t,B=>j(B)),[N,$]=x.useState(null),[k,P]=x.useState(null),A=Hs(r),[L,z]=x.useState(!1),D=x.useRef(!1);x.useEffect(()=>{if(_)return $u(_)},[_]),mu();const R=x.useCallback(B=>{const[X,...me]=A().map(le=>le.ref.current),[V]=me.slice(-1),re=document.activeElement;for(const le of B)if(le===re||(le?.scrollIntoView({block:"nearest"}),le===X&&C&&(C.scrollTop=0),le===V&&C&&(C.scrollTop=C.scrollHeight),le?.focus(),document.activeElement!==re))return},[A,C]),O=x.useCallback(()=>R([N,_]),[R,N,_]);x.useEffect(()=>{L&&O()},[L,O]);const{onOpenChange:T,triggerPointerDownPosRef:W}=y;x.useEffect(()=>{if(_){let B={x:0,y:0};const X=V=>{B={x:Math.abs(Math.round(V.pageX)-(W.current?.x??0)),y:Math.abs(Math.round(V.pageY)-(W.current?.y??0))}},me=V=>{B.x<=10&&B.y<=10?V.preventDefault():_.contains(V.target)||T(!1),document.removeEventListener("pointermove",X),W.current=null};return W.current!==null&&(document.addEventListener("pointermove",X),document.addEventListener("pointerup",me,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",X),document.removeEventListener("pointerup",me,{capture:!0})}}},[_,T,W]),x.useEffect(()=>{const B=()=>T(!1);return window.addEventListener("blur",B),window.addEventListener("resize",B),()=>{window.removeEventListener("blur",B),window.removeEventListener("resize",B)}},[T]);const[E,q]=fm(B=>{const X=A().filter(re=>!re.disabled),me=X.find(re=>re.ref.current===document.activeElement),V=hm(X,B,me);V&&setTimeout(()=>V.ref.current.focus())}),ne=x.useCallback((B,X,me)=>{const V=!D.current&&!me;(y.value!==void 0&&y.value===X||V)&&($(B),V&&(D.current=!0))},[y.value]),U=x.useCallback(()=>_?.focus(),[_]),K=x.useCallback((B,X,me)=>{const V=!D.current&&!me;(y.value!==void 0&&y.value===X||V)&&P(B)},[y.value]),J=s==="popper"?da:nm,he=J===da?{side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:p,collisionPadding:f,sticky:g,hideWhenDetached:h,avoidCollisions:b}:{};return n.jsx(em,{scope:r,content:_,viewport:C,onViewportChange:I,itemRefCallback:ne,selectedItem:N,onItemLeave:U,itemTextRefCallback:K,focusSelectedItem:O,selectedItemText:k,position:s,isPositioned:L,searchRef:E,children:n.jsx(ci,{as:ok,allowPinchZoom:!0,children:n.jsx(Xa,{asChild:!0,trapped:y.open,onMountAutoFocus:B=>{B.preventDefault()},onUnmountAutoFocus:we(o,B=>{y.trigger?.focus({preventScroll:!0}),B.preventDefault()}),children:n.jsx(Ka,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:B=>B.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:n.jsx(J,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:B=>B.preventDefault(),...w,...he,onPlaced:()=>z(!0),ref:S,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:we(w.onKeyDown,B=>{const X=B.ctrlKey||B.altKey||B.metaKey;if(B.key==="Tab"&&B.preventDefault(),!X&&B.key.length===1&&q(B.key),["ArrowUp","ArrowDown","Home","End"].includes(B.key)){let V=A().filter(re=>!re.disabled).map(re=>re.ref.current);if(["ArrowUp","End"].includes(B.key)&&(V=V.slice().reverse()),["ArrowUp","ArrowDown"].includes(B.key)){const re=B.target,le=V.indexOf(re);V=V.slice(le+1)}setTimeout(()=>R(V)),B.preventDefault()}})})})})})})});tm.displayName=sk;var ak="SelectItemAlignedPosition",nm=x.forwardRef((e,t)=>{const{__scopeSelect:r,onPlaced:s,...o}=e,a=vn(Tn,r),i=bn(Tn,r),[c,l]=x.useState(null),[d,m]=x.useState(null),u=Te(t,S=>m(S)),p=Hs(r),f=x.useRef(!1),g=x.useRef(!0),{viewport:h,selectedItem:b,selectedItemText:w,focusSelectedItem:y}=i,_=x.useCallback(()=>{if(a.trigger&&a.valueNode&&c&&d&&h&&b&&w){const S=a.trigger.getBoundingClientRect(),N=d.getBoundingClientRect(),$=a.valueNode.getBoundingClientRect(),k=w.getBoundingClientRect();if(a.dir!=="rtl"){const re=k.left-N.left,le=$.left-re,pe=S.left-le,Re=S.width+pe,He=Math.max(Re,N.width),Ze=window.innerWidth-Et,Ge=Lc(le,[Et,Math.max(Et,Ze-He)]);c.style.minWidth=Re+"px",c.style.left=Ge+"px"}else{const re=N.right-k.right,le=window.innerWidth-$.right-re,pe=window.innerWidth-S.right-le,Re=S.width+pe,He=Math.max(Re,N.width),Ze=window.innerWidth-Et,Ge=Lc(le,[Et,Math.max(Et,Ze-He)]);c.style.minWidth=Re+"px",c.style.right=Ge+"px"}const P=p(),A=window.innerHeight-Et*2,L=h.scrollHeight,z=window.getComputedStyle(d),D=parseInt(z.borderTopWidth,10),R=parseInt(z.paddingTop,10),O=parseInt(z.borderBottomWidth,10),T=parseInt(z.paddingBottom,10),W=D+R+L+T+O,E=Math.min(b.offsetHeight*5,W),q=window.getComputedStyle(h),ne=parseInt(q.paddingTop,10),U=parseInt(q.paddingBottom,10),K=S.top+S.height/2-Et,J=A-K,he=b.offsetHeight/2,B=b.offsetTop+he,X=D+R+B,me=W-X;if(X<=K){const re=P.length>0&&b===P[P.length-1].ref.current;c.style.bottom="0px";const le=d.clientHeight-h.offsetTop-h.offsetHeight,pe=Math.max(J,he+(re?U:0)+le+O),Re=X+pe;c.style.height=Re+"px"}else{const re=P.length>0&&b===P[0].ref.current;c.style.top="0px";const pe=Math.max(K,D+h.offsetTop+(re?ne:0)+he)+me;c.style.height=pe+"px",h.scrollTop=X-K+h.offsetTop}c.style.margin=`${Et}px 0`,c.style.minHeight=E+"px",c.style.maxHeight=A+"px",s?.(),requestAnimationFrame(()=>f.current=!0)}},[p,a.trigger,a.valueNode,c,d,h,b,w,a.dir,s]);et(()=>_(),[_]);const[j,C]=x.useState();et(()=>{d&&C(window.getComputedStyle(d).zIndex)},[d]);const I=x.useCallback(S=>{S&&g.current===!0&&(_(),y?.(),g.current=!1)},[_,y]);return n.jsx(ck,{scope:r,contentWrapper:c,shouldExpandOnScrollRef:f,onScrollButtonChange:I,children:n.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:j},children:n.jsx(ve.div,{...o,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});nm.displayName=ak;var ik="SelectPopperPosition",da=x.forwardRef((e,t)=>{const{__scopeSelect:r,align:s="start",collisionPadding:o=Et,...a}=e,i=Zs(r);return n.jsx(Yw,{...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=ik;var[ck,li]=ur(Tn,{}),ua="SelectViewport",rm=x.forwardRef((e,t)=>{const{__scopeSelect:r,nonce:s,...o}=e,a=bn(ua,r),i=li(ua,r),c=Te(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(Vs.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:we(o.onScroll,d=>{const m=d.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:p}=i;if(p?.current&&u){const f=Math.abs(l.current-m.scrollTop);if(f>0){const g=window.innerHeight-Et*2,h=parseFloat(u.style.minHeight),b=parseFloat(u.style.height),w=Math.max(h,b);if(w<g){const y=w+f,_=Math.min(g,y),j=y-_;u.style.height=_+"px",u.style.bottom==="0px"&&(m.scrollTop=j>0?j:0,u.style.justifyContent="flex-end")}}}l.current=m.scrollTop})})})]})});rm.displayName=ua;var sm="SelectGroup",[lk,dk]=ur(sm),om=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Wt();return n.jsx(lk,{scope:r,id:o,children:n.jsx(ve.div,{role:"group","aria-labelledby":o,...s,ref:t})})});om.displayName=sm;var am="SelectLabel",uk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=dk(am,r);return n.jsx(ve.div,{id:o.id,...s,ref:t})});uk.displayName=am;var Ss="SelectItem",[mk,im]=ur(Ss),cm=x.forwardRef((e,t)=>{const{__scopeSelect:r,value:s,disabled:o=!1,textValue:a,...i}=e,c=vn(Ss,r),l=bn(Ss,r),d=c.value===s,[m,u]=x.useState(a??""),[p,f]=x.useState(!1),g=Te(t,y=>l.itemRefCallback?.(y,s,o)),h=Wt(),b=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(mk,{scope:r,value:s,disabled:o,textId:h,isSelected:d,onItemTextChange:x.useCallback(y=>{u(_=>_||(y?.textContent??"").trim())},[]),children:n.jsx(Vs.ItemSlot,{scope:r,value:s,disabled:o,textValue:m,children:n.jsx(ve.div,{role:"option","aria-labelledby":h,"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:g,onFocus:we(i.onFocus,()=>f(!0)),onBlur:we(i.onBlur,()=>f(!1)),onClick:we(i.onClick,()=>{b.current!=="mouse"&&w()}),onPointerUp:we(i.onPointerUp,()=>{b.current==="mouse"&&w()}),onPointerDown:we(i.onPointerDown,y=>{b.current=y.pointerType}),onPointerMove:we(i.onPointerMove,y=>{b.current=y.pointerType,o?l.onItemLeave?.():b.current==="mouse"&&y.currentTarget.focus({preventScroll:!0})}),onPointerLeave:we(i.onPointerLeave,y=>{y.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:we(i.onKeyDown,y=>{l.searchRef?.current!==""&&y.key===" "||(Kj.includes(y.key)&&w(),y.key===" "&&y.preventDefault())})})})})});cm.displayName=Ss;var wr="SelectItemText",lm=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,...a}=e,i=vn(wr,r),c=bn(wr,r),l=im(wr,r),d=tk(wr,r),[m,u]=x.useState(null),p=Te(t,w=>u(w),l.onItemTextChange,w=>c.itemTextRefCallback?.(w,l.value,l.disabled)),f=m?.textContent,g=x.useMemo(()=>n.jsx("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:h,onNativeOptionRemove:b}=d;return et(()=>(h(g),()=>b(g)),[h,b,g]),n.jsxs(n.Fragment,{children:[n.jsx(ve.span,{id:l.textId,...a,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Ts.createPortal(a.children,i.valueNode):null]})});lm.displayName=wr;var dm="SelectItemIndicator",pk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return im(dm,r).isSelected?n.jsx(ve.span,{"aria-hidden":!0,...s,ref:t}):null});pk.displayName=dm;var ma="SelectScrollUpButton",fk=x.forwardRef((e,t)=>{const r=bn(ma,e.__scopeSelect),s=li(ma,e.__scopeSelect),[o,a]=x.useState(!1),i=Te(t,s.onScrollButtonChange);return et(()=>{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(um,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});fk.displayName=ma;var pa="SelectScrollDownButton",hk=x.forwardRef((e,t)=>{const r=bn(pa,e.__scopeSelect),s=li(pa,e.__scopeSelect),[o,a]=x.useState(!1),i=Te(t,s.onScrollButtonChange);return et(()=>{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(um,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});hk.displayName=pa;var um=x.forwardRef((e,t)=>{const{__scopeSelect:r,onAutoScroll:s,...o}=e,a=bn("SelectScrollButton",r),i=x.useRef(null),c=Hs(r),l=x.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return x.useEffect(()=>()=>l(),[l]),et(()=>{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:we(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(s,50))}),onPointerMove:we(o.onPointerMove,()=>{a.onItemLeave?.(),i.current===null&&(i.current=window.setInterval(s,50))}),onPointerLeave:we(o.onPointerLeave,()=>{l()})})}),gk="SelectSeparator",yk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return n.jsx(ve.div,{"aria-hidden":!0,...s,ref:t})});yk.displayName=gk;var fa="SelectArrow",xk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Zs(r),a=vn(fa,r),i=bn(fa,r);return a.open&&i.position==="popper"?n.jsx(Kw,{...o,...s,ref:t}):null});xk.displayName=fa;var vk="SelectBubbleInput",mm=x.forwardRef(({__scopeSelect:e,value:t,...r},s)=>{const o=x.useRef(null),a=Te(s,o),i=cj(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:{...Du,...r.style},ref:a,defaultValue:t})});mm.displayName=vk;function pm(e){return e===""||e===void 0}function fm(e){const t=dn(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 hm(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=bk(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 bk(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var _k=Hu,gm=Gu,wk=Yu,jk=Ku,kk=Xu,ym=Ju,Sk=rm,Ck=om,xm=cm,Nk=lm;const Cs=_k,Pk=Ck,Ns=wk,Rr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(gm,{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(jk,{className:"ml-2 text-neutral-500 dark:text-neutral-400",children:"▾"})]}));Rr.displayName=gm.displayName;const Or=x.forwardRef(({className:e,children:t,position:r="popper",...s},o)=>n.jsx(kk,{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(Sk,{className:H("p-1",r==="popper"?"w-full":void 0),children:t})})}));Or.displayName=ym.displayName;const Mr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(xm,{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(Nk,{children:t})}));Mr.displayName=xm.displayName;function Ak(e,t){return x.useReducer((r,s)=>t[r][s]??r,e)}var mr=e=>{const{present:t,children:r}=e,s=Ek(t),o=typeof r=="function"?r({present:s.isPresent}):x.Children.only(r),a=Te(s.ref,Tk(o));return typeof r=="function"||s.isPresent?x.cloneElement(o,{ref:a}):null};mr.displayName="Presence";function Ek(e){const[t,r]=x.useState(),s=x.useRef(null),o=x.useRef(e),a=x.useRef("none"),i=e?"mounted":"unmounted",[c,l]=Ak(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return x.useEffect(()=>{const d=ns(s.current);a.current=c==="mounted"?d:"none"},[c]),et(()=>{const d=s.current,m=o.current;if(m!==e){const p=a.current,f=ns(d);e?l("MOUNT"):f==="none"||d?.display==="none"?l("UNMOUNT"):l(m&&p!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),et(()=>{if(t){let d;const m=t.ownerDocument.defaultView??window,u=f=>{const h=ns(s.current).includes(CSS.escape(f.animationName));if(f.target===t&&h&&(l("ANIMATION_END"),!o.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},p=f=>{f.target===t&&(a.current=ns(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 ns(e){return e?.animationName||"none"}function Tk(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 Ik(e){const t=Rk(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(Mk);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 Rk(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=Lk(o),c=Dk(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 Ok=Symbol("radix.slottable");function Mk(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ok}function Dk(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 Lk(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 Gs="Dialog",[vm]=xn(Gs),[$k,Dt]=vm(Gs),bm=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]=pn({prop:s,defaultProp:o??!1,onChange:a,caller:Gs});return n.jsx($k,{scope:t,triggerRef:c,contentRef:l,contentId:Wt(),titleId:Wt(),descriptionId:Wt(),open:d,onOpenChange:m,onOpenToggle:x.useCallback(()=>m(u=>!u),[m]),modal:i,children:r})};bm.displayName=Gs;var _m="DialogTrigger",wm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(_m,r),a=Te(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:we(e.onClick,o.onOpenToggle)})});wm.displayName=_m;var di="DialogPortal",[zk,jm]=vm(di,{forceMount:void 0}),km=e=>{const{__scopeDialog:t,forceMount:r,children:s,container:o}=e,a=Dt(di,t);return n.jsx(zk,{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})}))})};km.displayName=di;var Ps="DialogOverlay",Sm=x.forwardRef((e,t)=>{const r=jm(Ps,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Dt(Ps,e.__scopeDialog);return a.modal?n.jsx(mr,{present:s||a.open,children:n.jsx(Bk,{...o,ref:t})}):null});Sm.displayName=Ps;var Fk=Ik("DialogOverlay.RemoveScroll"),Bk=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(Ps,r);return n.jsx(ci,{as:Fk,allowPinchZoom:!0,shards:[o.contentRef],children:n.jsx(ve.div,{"data-state":mi(o.open),...s,ref:t,style:{pointerEvents:"auto",...s.style}})})}),In="DialogContent",Cm=x.forwardRef((e,t)=>{const r=jm(In,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Dt(In,e.__scopeDialog);return n.jsx(mr,{present:s||a.open,children:a.modal?n.jsx(Uk,{...o,ref:t}):n.jsx(Wk,{...o,ref:t})})});Cm.displayName=In;var Uk=x.forwardRef((e,t)=>{const r=Dt(In,e.__scopeDialog),s=x.useRef(null),o=Te(t,r.contentRef,s);return x.useEffect(()=>{const a=s.current;if(a)return $u(a)},[]),n.jsx(Nm,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:we(e.onCloseAutoFocus,a=>{a.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:we(e.onPointerDownOutside,a=>{const i=a.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&a.preventDefault()}),onFocusOutside:we(e.onFocusOutside,a=>a.preventDefault())})}),Wk=x.forwardRef((e,t)=>{const r=Dt(In,e.__scopeDialog),s=x.useRef(!1),o=x.useRef(!1);return n.jsx(Nm,{...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()}})}),Nm=x.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,...i}=e,c=Dt(In,r),l=x.useRef(null),d=Te(t,l);return mu(),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(Hk,{contentRef:l,descriptionId:c.descriptionId})]})]})}),ui="DialogTitle",Pm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(ui,r);return n.jsx(ve.h2,{id:o.titleId,...s,ref:t})});Pm.displayName=ui;var Am="DialogDescription",Em=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(Am,r);return n.jsx(ve.p,{id:o.descriptionId,...s,ref:t})});Em.displayName=Am;var Tm="DialogClose",Im=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Dt(Tm,r);return n.jsx(ve.button,{type:"button",...s,ref:t,onClick:we(e.onClick,()=>o.onOpenChange(!1))})});Im.displayName=Tm;function mi(e){return e?"open":"closed"}var Rm="DialogTitleWarning",[uN,Om]=Y0(Rm,{contentName:In,titleName:ui,docsSlug:"dialog"}),qk=({titleId:e})=>{const t=Om(Rm),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
132
-
133
- If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
134
-
135
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return x.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},Vk="DialogDescriptionWarning",Hk=({contentRef:e,descriptionId:t})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Om(Vk).contentName}}.`;return x.useEffect(()=>{const o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(s))},[s,e,t]),null},Mm=bm,Dm=wm,Lm=km,Qs=Sm,Ys=Cm,Ks=Pm,Xs=Em,$m=Im;const pi=Mm,Zk=Dm,zm=Lm,Gk=$m,fi=x.forwardRef(({className:e,...t},r)=>n.jsx(Qs,{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=Qs.displayName;const Js=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(zm,{children:[n.jsx(fi,{}),n.jsx(Ys,{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})]}));Js.displayName=Ys.displayName;const hi=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-center sm:text-left",e),...t}),Fm=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t}),eo=x.forwardRef(({className:e,...t},r)=>n.jsx(Ks,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));eo.displayName=Ks.displayName;const gi=x.forwardRef(({className:e,...t},r)=>n.jsx(Xs,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));gi.displayName=Xs.displayName;const to=Mm,no=Dm,Bm=$m,Um=Lm,yi=x.forwardRef(({className:e,...t},r)=>n.jsx(Qs,{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}));yi.displayName=Qs.displayName;const Qk=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"}}),zr=x.forwardRef(({side:e="right",className:t,children:r,overlayClassName:s,...o},a)=>n.jsxs(Um,{children:[n.jsx(yi,{className:s}),n.jsx(Ys,{ref:a,className:H(Qk({side:e}),t),...o,children:r})]}));zr.displayName=Ys.displayName;const ro=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-left",e),...t}),so=x.forwardRef(({className:e,...t},r)=>n.jsx(Ks,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));so.displayName=Ks.displayName;const Wm=x.forwardRef(({className:e,...t},r)=>n.jsx(Xs,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));Wm.displayName=Xs.displayName;var oo="Collapsible",[Yk,qm]=xn(oo),[Kk,xi]=Yk(oo),Vm=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:s,defaultOpen:o,disabled:a,onOpenChange:i,...c}=e,[l,d]=pn({prop:s,defaultProp:o??!1,onChange:i,caller:oo});return n.jsx(Kk,{scope:r,disabled:a,contentId:Wt(),open:l,onOpenToggle:x.useCallback(()=>d(m=>!m),[d]),children:n.jsx(ve.div,{"data-state":bi(l),"data-disabled":a?"":void 0,...c,ref:t})})});Vm.displayName=oo;var Hm="CollapsibleTrigger",Zm=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,...s}=e,o=xi(Hm,r);return n.jsx(ve.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:we(e.onClick,o.onOpenToggle)})});Zm.displayName=Hm;var vi="CollapsibleContent",Gm=x.forwardRef((e,t)=>{const{forceMount:r,...s}=e,o=xi(vi,e.__scopeCollapsible);return n.jsx(mr,{present:r||o.open,children:({present:a})=>n.jsx(Xk,{...s,ref:t,present:a})})});Gm.displayName=vi;var Xk=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:s,children:o,...a}=e,i=xi(vi,r),[c,l]=x.useState(s),d=x.useRef(null),m=Te(t,d),u=x.useRef(0),p=u.current,f=x.useRef(0),g=f.current,h=i.open||c,b=x.useRef(h),w=x.useRef(void 0);return x.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),et(()=>{const y=d.current;if(y){w.current=w.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const _=y.getBoundingClientRect();u.current=_.height,f.current=_.width,b.current||(y.style.transitionDuration=w.current.transitionDuration,y.style.animationName=w.current.animationName),l(s)}},[i.open,s]),n.jsx(ve.div,{"data-state":bi(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!h,...a,ref:m,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:h&&o})});function bi(e){return e?"open":"closed"}var Jk=Vm,eS=Zm,tS=Gm,Lt="Accordion",nS=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[_i,rS,sS]=Ya(Lt),[ao]=xn(Lt,[sS,qm]),wi=qm(),Qm=v.forwardRef((e,t)=>{const{type:r,...s}=e,o=s,a=s;return n.jsx(_i.Provider,{scope:e.__scopeAccordion,children:r==="multiple"?n.jsx(cS,{...a,ref:t}):n.jsx(iS,{...o,ref:t})})});Qm.displayName=Lt;var[Ym,oS]=ao(Lt),[Km,aS]=ao(Lt,{collapsible:!1}),iS=v.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},collapsible:a=!1,...i}=e,[c,l]=pn({prop:r,defaultProp:s??"",onChange:o,caller:Lt});return n.jsx(Ym,{scope:e.__scopeAccordion,value:v.useMemo(()=>c?[c]:[],[c]),onItemOpen:l,onItemClose:v.useCallback(()=>a&&l(""),[a,l]),children:n.jsx(Km,{scope:e.__scopeAccordion,collapsible:a,children:n.jsx(Xm,{...i,ref:t})})})}),cS=v.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},...a}=e,[i,c]=pn({prop:r,defaultProp:s??[],onChange:o,caller:Lt}),l=v.useCallback(m=>c((u=[])=>[...u,m]),[c]),d=v.useCallback(m=>c((u=[])=>u.filter(p=>p!==m)),[c]);return n.jsx(Ym,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:d,children:n.jsx(Km,{scope:e.__scopeAccordion,collapsible:!0,children:n.jsx(Xm,{...a,ref:t})})})}),[lS,io]=ao(Lt),Xm=v.forwardRef((e,t)=>{const{__scopeAccordion:r,disabled:s,dir:o,orientation:a="vertical",...i}=e,c=v.useRef(null),l=Te(c,t),d=rS(r),u=zs(o)==="ltr",p=we(e.onKeyDown,f=>{if(!nS.includes(f.key))return;const g=f.target,h=d().filter(N=>!N.ref.current?.disabled),b=h.findIndex(N=>N.ref.current===g),w=h.length;if(b===-1)return;f.preventDefault();let y=b;const _=0,j=w-1,C=()=>{y=b+1,y>j&&(y=_)},I=()=>{y=b-1,y<_&&(y=j)};switch(f.key){case"Home":y=_;break;case"End":y=j;break;case"ArrowRight":a==="horizontal"&&(u?C():I());break;case"ArrowDown":a==="vertical"&&C();break;case"ArrowLeft":a==="horizontal"&&(u?I():C());break;case"ArrowUp":a==="vertical"&&I();break}const S=y%w;h[S].ref.current?.focus()});return n.jsx(lS,{scope:r,disabled:s,direction:o,orientation:a,children:n.jsx(_i.Slot,{scope:r,children:n.jsx(ve.div,{...i,"data-orientation":a,ref:l,onKeyDown:s?void 0:p})})})}),As="AccordionItem",[dS,ji]=ao(As),Jm=v.forwardRef((e,t)=>{const{__scopeAccordion:r,value:s,...o}=e,a=io(As,r),i=oS(As,r),c=wi(r),l=Wt(),d=s&&i.value.includes(s)||!1,m=a.disabled||e.disabled;return n.jsx(dS,{scope:r,open:d,disabled:m,triggerId:l,children:n.jsx(Jk,{"data-orientation":a.orientation,"data-state":op(d),...c,...o,ref:t,disabled:m,open:d,onOpenChange:u=>{u?i.onItemOpen(s):i.onItemClose(s)}})})});Jm.displayName=As;var ep="AccordionHeader",tp=v.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=io(Lt,r),a=ji(ep,r);return n.jsx(ve.h3,{"data-orientation":o.orientation,"data-state":op(a.open),"data-disabled":a.disabled?"":void 0,...s,ref:t})});tp.displayName=ep;var ha="AccordionTrigger",np=v.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=io(Lt,r),a=ji(ha,r),i=aS(ha,r),c=wi(r);return n.jsx(_i.ItemSlot,{scope:r,children:n.jsx(eS,{"aria-disabled":a.open&&!i.collapsible||void 0,"data-orientation":o.orientation,id:a.triggerId,...c,...s,ref:t})})});np.displayName=ha;var rp="AccordionContent",sp=v.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=io(Lt,r),a=ji(rp,r),i=wi(r);return n.jsx(tS,{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}})});sp.displayName=rp;function op(e){return e?"open":"closed"}var uS=Qm,ap=Jm,mS=tp,ip=np,cp=sp;const lp=uS,kr=x.forwardRef(({className:e,...t},r)=>n.jsx(ap,{ref:r,className:H("border-b border-neutral-200 dark:border-neutral-800",e),...t}));kr.displayName=ap.displayName;const Sr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(mS,{className:"flex",children:n.jsxs(ip,{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:"▾"})]})}));Sr.displayName=ip.displayName;const Cr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(cp,{ref:s,className:H("overflow-hidden text-sm",e),...r,children:n.jsx("div",{className:"pb-4 pt-0",children:t})}));Cr.displayName=cp.displayName;var Fo="rovingFocusGroup.onEntryFocus",pS={bubbles:!1,cancelable:!0},Fr="RovingFocusGroup",[ga,dp,fS]=Ya(Fr),[hS,up]=xn(Fr,[fS]),[gS,yS]=hS(Fr),mp=x.forwardRef((e,t)=>n.jsx(ga.Provider,{scope:e.__scopeRovingFocusGroup,children:n.jsx(ga.Slot,{scope:e.__scopeRovingFocusGroup,children:n.jsx(xS,{...e,ref:t})})}));mp.displayName=Fr;var xS=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),f=Te(t,p),g=zs(a),[h,b]=pn({prop:i,defaultProp:c??null,onChange:l,caller:Fr}),[w,y]=x.useState(!1),_=dn(d),j=dp(r),C=x.useRef(!1),[I,S]=x.useState(0);return x.useEffect(()=>{const N=p.current;if(N)return N.addEventListener(Fo,_),()=>N.removeEventListener(Fo,_)},[_]),n.jsx(gS,{scope:r,orientation:s,dir:g,loop:o,currentTabStopId:h,onItemFocus:x.useCallback(N=>b(N),[b]),onItemShiftTab:x.useCallback(()=>y(!0),[]),onFocusableItemAdd:x.useCallback(()=>S(N=>N+1),[]),onFocusableItemRemove:x.useCallback(()=>S(N=>N-1),[]),children:n.jsx(ve.div,{tabIndex:w||I===0?-1:0,"data-orientation":s,...u,ref:f,style:{outline:"none",...e.style},onMouseDown:we(e.onMouseDown,()=>{C.current=!0}),onFocus:we(e.onFocus,N=>{const $=!C.current;if(N.target===N.currentTarget&&$&&!w){const k=new CustomEvent(Fo,pS);if(N.currentTarget.dispatchEvent(k),!k.defaultPrevented){const P=j().filter(R=>R.focusable),A=P.find(R=>R.active),L=P.find(R=>R.id===h),D=[A,L,...P].filter(Boolean).map(R=>R.ref.current);hp(D,m)}}C.current=!1}),onBlur:we(e.onBlur,()=>y(!1))})})}),pp="RovingFocusGroupItem",fp=x.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,focusable:s=!0,active:o=!1,tabStopId:a,children:i,...c}=e,l=Wt(),d=a||l,m=yS(pp,r),u=m.currentTabStopId===d,p=dp(r),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:h}=m;return x.useEffect(()=>{if(s)return f(),()=>g()},[s,f,g]),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:we(e.onMouseDown,b=>{s?m.onItemFocus(d):b.preventDefault()}),onFocus:we(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:we(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){m.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const w=_S(b,m.orientation,m.dir);if(w!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let _=p().filter(j=>j.focusable).map(j=>j.ref.current);if(w==="last")_.reverse();else if(w==="prev"||w==="next"){w==="prev"&&_.reverse();const j=_.indexOf(b.currentTarget);_=m.loop?wS(_,j+1):_.slice(j+1)}setTimeout(()=>hp(_))}}),children:typeof i=="function"?i({isCurrentTabStop:u,hasTabStop:h!=null}):i})})});fp.displayName=pp;var vS={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function bS(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function _S(e,t,r){const s=bS(e.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(s))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(s)))return vS[s]}function hp(e,t=!1){const r=document.activeElement;for(const s of e)if(s===r||(s.focus({preventScroll:t}),document.activeElement!==r))return}function wS(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var jS=mp,kS=fp,co="Tabs",[SS]=xn(co,[up]),gp=up(),[CS,ki]=SS(co),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=zs(c),[u,p]=pn({prop:s,onChange:o,defaultProp:a??"",caller:co});return n.jsx(CS,{scope:r,baseId:Wt(),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=co;var xp="TabsList",vp=x.forwardRef((e,t)=>{const{__scopeTabs:r,loop:s=!0,...o}=e,a=ki(xp,r),i=gp(r);return n.jsx(jS,{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=xp;var bp="TabsTrigger",_p=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,disabled:o=!1,...a}=e,i=ki(bp,r),c=gp(r),l=kp(i.baseId,s),d=Sp(i.baseId,s),m=s===i.value;return n.jsx(kS,{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:we(e.onMouseDown,u=>{!o&&u.button===0&&u.ctrlKey===!1?i.onValueChange(s):u.preventDefault()}),onKeyDown:we(e.onKeyDown,u=>{[" ","Enter"].includes(u.key)&&i.onValueChange(s)}),onFocus:we(e.onFocus,()=>{const u=i.activationMode!=="manual";!m&&!o&&u&&i.onValueChange(s)})})})});_p.displayName=bp;var wp="TabsContent",jp=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,forceMount:o,children:a,...i}=e,c=ki(wp,r),l=kp(c.baseId,s),d=Sp(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})})});jp.displayName=wp;function kp(e,t){return`${e}-trigger-${t}`}function Sp(e,t){return`${e}-content-${t}`}var NS=yp,Cp=vp,Np=_p,Pp=jp;const Si=NS,lo=x.forwardRef(({className:e,...t},r)=>n.jsx(Cp,{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}));lo.displayName=Cp.displayName;const Dr=x.forwardRef(({className:e,...t},r)=>n.jsx(Np,{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}));Dr.displayName=Np.displayName;const Ap=x.forwardRef(({className:e,...t},r)=>n.jsx(Pp,{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}));Ap.displayName=Pp.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(ce,{type:"button",onClick:s,variant:"secondary",children:r})}):null]})})}function Vt({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(ce,{type:"button",variant:"outline",onClick:r,children:"Try again"})}):null]})}class PS 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(Vt,{description:this.state.error.message}):this.props.children}}function AS(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 ES=e=>{switch(e){case"success":return RS;case"info":return MS;case"warning":return OS;case"error":return DS;default:return null}},TS=Array(12).fill(0),IS=({visible:e,className:t})=>v.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},v.createElement("div",{className:"sonner-spinner"},TS.map((r,s)=>v.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),RS=v.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},v.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"})),OS=v.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},v.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"})),MS=v.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},v.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"})),DS=v.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},v.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"})),LS=v.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"},v.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),v.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),$S=()=>{const[e,t]=v.useState(document.hidden);return v.useEffect(()=>{const r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),e};let ya=1;class zS{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:ya++,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],v.isValidElement(d))a=!1,this.create({id:s,type:"default",message:d});else if(BS(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,g=typeof u=="object"&&!v.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,...g})}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,g=typeof u=="object"&&!v.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,...g})}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,g=typeof u=="object"&&!v.isValidElement(u)?u:{message:u};this.create({id:s,type:"success",description:p,...g})}}).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,f=typeof m=="object"&&!v.isValidElement(m)?m:{message:m};this.create({id:s,type:"error",description:u,...f})}}).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||ya++;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 zS,FS=(e,t)=>{const r=t?.id||ya++;return ft.addToast({title:e,...t,id:r}),r},BS=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",US=FS,WS=()=>ft.toasts,qS=()=>ft.getActiveToasts(),VS=Object.assign(US,{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:WS,getToasts:qS});AS("[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 rs(e){return e.label!==void 0}const HS=3,ZS="24px",GS="16px",cl=4e3,QS=356,YS=14,KS=45,XS=200;function zt(...e){return e.filter(Boolean).join(" ")}function JS(e){const[t,r]=e.split("-"),s=[];return t&&s.push(t),r&&s.push(r),s}const eC=e=>{var t,r,s,o,a,i,c,l,d;const{invert:m,toast:u,unstyled:p,interacting:f,setHeights:g,visibleToasts:h,heights:b,index:w,toasts:y,expanded:_,removeToast:j,defaultRichColors:C,closeButton:I,style:S,cancelButtonStyle:N,actionButtonStyle:$,className:k="",descriptionClassName:P="",duration:A,position:L,gap:z,expandByDefault:D,classNames:R,icons:O,closeButtonAriaLabel:T="Close toast"}=e,[W,E]=v.useState(null),[q,ne]=v.useState(null),[U,K]=v.useState(!1),[J,he]=v.useState(!1),[B,X]=v.useState(!1),[me,V]=v.useState(!1),[re,le]=v.useState(!1),[pe,Re]=v.useState(0),[He,Ze]=v.useState(0),Ge=v.useRef(u.duration||A||cl),Qe=v.useRef(null),Pe=v.useRef(null),rt=w===0,Ce=w+1<=h,ee=u.type,je=u.dismissible!==!1,Oe=u.className||"",F=u.descriptionClassName||"",te=v.useMemo(()=>b.findIndex(fe=>fe.toastId===u.id)||0,[b,u.id]),se=v.useMemo(()=>{var fe;return(fe=u.closeButton)!=null?fe:I},[u.closeButton,I]),ge=v.useMemo(()=>u.duration||A||cl,[u.duration,A]),be=v.useRef(0),Ae=v.useRef(0),$n=v.useRef(0),Qt=v.useRef(null),[zn,Fn]=L.split("-"),wt=v.useMemo(()=>b.reduce((fe,ze,_e)=>_e>=te?fe:fe+ze.height,0),[b,te]),Yt=$S(),pr=u.invert||m,_n=ee==="loading";Ae.current=v.useMemo(()=>te*z+wt,[te,wt]),v.useEffect(()=>{Ge.current=ge},[ge]),v.useEffect(()=>{K(!0)},[]),v.useEffect(()=>{const fe=Pe.current;if(fe){const ze=fe.getBoundingClientRect().height;return Ze(ze),g(_e=>[{toastId:u.id,height:ze,position:u.position},..._e]),()=>g(_e=>_e.filter(Fe=>Fe.toastId!==u.id))}},[g,u.id]),v.useLayoutEffect(()=>{if(!U)return;const fe=Pe.current,ze=fe.style.height;fe.style.height="auto";const _e=fe.getBoundingClientRect().height;fe.style.height=ze,Ze(_e),g(Fe=>Fe.find(Be=>Be.toastId===u.id)?Fe.map(Be=>Be.toastId===u.id?{...Be,height:_e}:Be):[{toastId:u.id,height:_e,position:u.position},...Fe])},[U,u.title,u.description,g,u.id,u.jsx,u.action,u.cancel]);const $t=v.useCallback(()=>{he(!0),Re(Ae.current),g(fe=>fe.filter(ze=>ze.toastId!==u.id)),setTimeout(()=>{j(u)},XS)},[u,j,g,Ae]);v.useEffect(()=>{if(u.promise&&ee==="loading"||u.duration===1/0||u.type==="loading")return;let fe;return _||f||Yt?(()=>{if($n.current<be.current){const Fe=new Date().getTime()-be.current;Ge.current=Ge.current-Fe}$n.current=new Date().getTime()})():(()=>{Ge.current!==1/0&&(be.current=new Date().getTime(),fe=setTimeout(()=>{u.onAutoClose==null||u.onAutoClose.call(u,u),$t()},Ge.current))})(),()=>clearTimeout(fe)},[_,f,u,ee,Yt,$t]),v.useEffect(()=>{u.delete&&($t(),u.onDismiss==null||u.onDismiss.call(u,u))},[$t,u.delete]);function Bn(){var fe;if(O?.loading){var ze;return v.createElement("div",{className:zt(R?.loader,u==null||(ze=u.classNames)==null?void 0:ze.loader,"sonner-loader"),"data-visible":ee==="loading"},O.loading)}return v.createElement(IS,{className:zt(R?.loader,u==null||(fe=u.classNames)==null?void 0:fe.loader),visible:ee==="loading"})}const Un=u.icon||O?.[ee]||ES(ee);var Br,rn;return v.createElement("li",{tabIndex:0,ref:Pe,className:zt(k,Oe,R?.toast,u==null||(t=u.classNames)==null?void 0:t.toast,R?.default,R?.[ee],u==null||(r=u.classNames)==null?void 0:r[ee]),"data-sonner-toast":"","data-rich-colors":(Br=u.richColors)!=null?Br:C,"data-styled":!(u.jsx||u.unstyled||p),"data-mounted":U,"data-promise":!!u.promise,"data-swiped":re,"data-removed":J,"data-visible":Ce,"data-y-position":zn,"data-x-position":Fn,"data-index":w,"data-front":rt,"data-swiping":B,"data-dismissible":je,"data-type":ee,"data-invert":pr,"data-swipe-out":me,"data-swipe-direction":q,"data-expanded":!!(_||D&&U),"data-testid":u.testId,style:{"--index":w,"--toasts-before":w,"--z-index":y.length-w,"--offset":`${J?pe:Ae.current}px`,"--initial-height":D?"auto":`${He}px`,...S,...u.style},onDragEnd:()=>{X(!1),E(null),Qt.current=null},onPointerDown:fe=>{fe.button!==2&&(_n||!je||(Qe.current=new Date,Re(Ae.current),fe.target.setPointerCapture(fe.pointerId),fe.target.tagName!=="BUTTON"&&(X(!0),Qt.current={x:fe.clientX,y:fe.clientY})))},onPointerUp:()=>{var fe,ze,_e;if(me||!je)return;Qt.current=null;const Fe=Number(((fe=Pe.current)==null?void 0:fe.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Wn=Number(((ze=Pe.current)==null?void 0:ze.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Be=new Date().getTime()-((_e=Qe.current)==null?void 0:_e.getTime()),tt=W==="x"?Fe:Wn,wn=Math.abs(tt)/Be;if(Math.abs(tt)>=KS||wn>.11){Re(Ae.current),u.onDismiss==null||u.onDismiss.call(u,u),ne(W==="x"?Fe>0?"right":"left":Wn>0?"down":"up"),$t(),V(!0);return}else{var mt,gt;(mt=Pe.current)==null||mt.style.setProperty("--swipe-amount-x","0px"),(gt=Pe.current)==null||gt.style.setProperty("--swipe-amount-y","0px")}le(!1),X(!1),E(null)},onPointerMove:fe=>{var ze,_e,Fe;if(!Qt.current||!je||((ze=window.getSelection())==null?void 0:ze.toString().length)>0)return;const Be=fe.clientY-Qt.current.y,tt=fe.clientX-Qt.current.x;var wn;const mt=(wn=e.swipeDirections)!=null?wn:JS(L);!W&&(Math.abs(tt)>1||Math.abs(Be)>1)&&E(Math.abs(tt)>Math.abs(Be)?"x":"y");let gt={x:0,y:0};const yt=st=>1/(1.5+Math.abs(st)/20);if(W==="y"){if(mt.includes("top")||mt.includes("bottom"))if(mt.includes("top")&&Be<0||mt.includes("bottom")&&Be>0)gt.y=Be;else{const st=Be*yt(Be);gt.y=Math.abs(st)<Math.abs(Be)?st:Be}}else if(W==="x"&&(mt.includes("left")||mt.includes("right")))if(mt.includes("left")&&tt<0||mt.includes("right")&&tt>0)gt.x=tt;else{const st=tt*yt(tt);gt.x=Math.abs(st)<Math.abs(tt)?st:tt}(Math.abs(gt.x)>0||Math.abs(gt.y)>0)&&le(!0),(_e=Pe.current)==null||_e.style.setProperty("--swipe-amount-x",`${gt.x}px`),(Fe=Pe.current)==null||Fe.style.setProperty("--swipe-amount-y",`${gt.y}px`)}},se&&!u.jsx&&ee!=="loading"?v.createElement("button",{"aria-label":T,"data-disabled":_n,"data-close-button":!0,onClick:_n||!je?()=>{}:()=>{$t(),u.onDismiss==null||u.onDismiss.call(u,u)},className:zt(R?.closeButton,u==null||(s=u.classNames)==null?void 0:s.closeButton)},(rn=O?.close)!=null?rn:LS):null,(ee||u.icon||u.promise)&&u.icon!==null&&(O?.[ee]!==null||u.icon)?v.createElement("div",{"data-icon":"",className:zt(R?.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,v.createElement("div",{"data-content":"",className:zt(R?.content,u==null||(a=u.classNames)==null?void 0:a.content)},v.createElement("div",{"data-title":"",className:zt(R?.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?v.createElement("div",{"data-description":"",className:zt(P,F,R?.description,u==null||(c=u.classNames)==null?void 0:c.description)},typeof u.description=="function"?u.description():u.description):null),v.isValidElement(u.cancel)?u.cancel:u.cancel&&rs(u.cancel)?v.createElement("button",{"data-button":!0,"data-cancel":!0,style:u.cancelButtonStyle||N,onClick:fe=>{rs(u.cancel)&&je&&(u.cancel.onClick==null||u.cancel.onClick.call(u.cancel,fe),$t())},className:zt(R?.cancelButton,u==null||(l=u.classNames)==null?void 0:l.cancelButton)},u.cancel.label):null,v.isValidElement(u.action)?u.action:u.action&&rs(u.action)?v.createElement("button",{"data-button":!0,"data-action":!0,style:u.actionButtonStyle||$,onClick:fe=>{rs(u.action)&&(u.action.onClick==null||u.action.onClick.call(u.action,fe),!fe.defaultPrevented&&$t())},className:zt(R?.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 tC(e,t){const r={};return[e,t].forEach((s,o)=>{const a=o===1,i=a?"--mobile-offset":"--offset",c=a?GS:ZS;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 nC=v.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:f,duration:g,style:h,visibleToasts:b=HS,toastOptions:w,dir:y=ll(),gap:_=YS,icons:j,containerAriaLabel:C="Notifications"}=t,[I,S]=v.useState([]),N=v.useMemo(()=>s?I.filter(U=>U.toasterId===s):I.filter(U=>!U.toasterId),[I,s]),$=v.useMemo(()=>Array.from(new Set([a].concat(N.filter(U=>U.position).map(U=>U.position)))),[N,a]),[k,P]=v.useState([]),[A,L]=v.useState(!1),[z,D]=v.useState(!1),[R,O]=v.useState(p!=="system"?p:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),T=v.useRef(null),W=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),E=v.useRef(null),q=v.useRef(!1),ne=v.useCallback(U=>{S(K=>{var J;return(J=K.find(he=>he.id===U.id))!=null&&J.delete||ft.dismiss(U.id),K.filter(({id:he})=>he!==U.id)})},[]);return v.useEffect(()=>ft.subscribe(U=>{if(U.dismiss){requestAnimationFrame(()=>{S(K=>K.map(J=>J.id===U.id?{...J,delete:!0}:J))});return}setTimeout(()=>{ka.flushSync(()=>{S(K=>{const J=K.findIndex(he=>he.id===U.id);return J!==-1?[...K.slice(0,J),{...K[J],...U},...K.slice(J+1)]:[U,...K]})})})}),[I]),v.useEffect(()=>{if(p!=="system"){O(p);return}if(p==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?O("dark"):O("light")),typeof window>"u")return;const U=window.matchMedia("(prefers-color-scheme: dark)");try{U.addEventListener("change",({matches:K})=>{O(K?"dark":"light")})}catch{U.addListener(({matches:J})=>{try{O(J?"dark":"light")}catch(he){console.error(he)}})}},[p]),v.useEffect(()=>{I.length<=1&&L(!1)},[I]),v.useEffect(()=>{const U=K=>{var J;if(i.every(X=>K[X]||K.code===X)){var B;L(!0),(B=T.current)==null||B.focus()}K.code==="Escape"&&(document.activeElement===T.current||(J=T.current)!=null&&J.contains(document.activeElement))&&L(!1)};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[i]),v.useEffect(()=>{if(T.current)return()=>{E.current&&(E.current.focus({preventScroll:!0}),E.current=null,q.current=!1)}},[T.current]),v.createElement("section",{ref:r,"aria-label":`${C} ${W}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},$.map((U,K)=>{var J;const[he,B]=U.split("-");return N.length?v.createElement("ol",{key:U,dir:y==="auto"?ll():y,tabIndex:-1,ref:T,className:d,"data-sonner-toaster":!0,"data-sonner-theme":R,"data-y-position":he,"data-x-position":B,style:{"--front-toast-height":`${((J=k[0])==null?void 0:J.height)||0}px`,"--width":`${QS}px`,"--gap":`${_}px`,...h,...tC(m,u)},onBlur:X=>{q.current&&!X.currentTarget.contains(X.relatedTarget)&&(q.current=!1,E.current&&(E.current.focus({preventScroll:!0}),E.current=null))},onFocus:X=>{X.target instanceof HTMLElement&&X.target.dataset.dismissible==="false"||q.current||(q.current=!0,E.current=X.relatedTarget)},onMouseEnter:()=>L(!0),onMouseMove:()=>L(!0),onMouseLeave:()=>{z||L(!1)},onDragEnd:()=>L(!1),onPointerDown:X=>{X.target instanceof HTMLElement&&X.target.dataset.dismissible==="false"||D(!0)},onPointerUp:()=>D(!1)},N.filter(X=>!X.position&&K===0||X.position===U).map((X,me)=>{var V,re;return v.createElement(eC,{key:X.id,icons:j,index:me,toast:X,defaultRichColors:f,duration:(V=w?.duration)!=null?V:g,className:w?.className,descriptionClassName:w?.descriptionClassName,invert:o,visibleToasts:b,closeButton:(re=w?.closeButton)!=null?re:l,interacting:z,position:U,style:w?.style,unstyled:w?.unstyled,classNames:w?.classNames,cancelButtonStyle:w?.cancelButtonStyle,actionButtonStyle:w?.actionButtonStyle,closeButtonAriaLabel:w?.closeButtonAriaLabel,removeToast:ne,toasts:N.filter(le=>le.position==X.position),heights:k.filter(le=>le.position==X.position),setHeights:P,expandByDefault:c,gap:_,expanded:A,swipeDirections:t.swipeDirections})})):null}))}),Ci=x.createContext(null);function rC(){const e=x.useContext(Ci);if(!e)throw new Error("useToast must be used within ToastProvider");return e}function uo(){return x.useContext(Ci)}function sC({children:e}){const t=x.useCallback(r=>{const s=r.title??"",o=r.description;VS(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(nC,{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:Ep,setPrototypeOf:dl,isFrozen:oC,getPrototypeOf:aC,getOwnPropertyDescriptor:iC}=Object;let{freeze:dt,seal:St,create:xa}=Object,{apply:va,construct:ba}=typeof Reflect<"u"&&Reflect;dt||(dt=function(t){return t});St||(St=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 ss=ut(Array.prototype.forEach),cC=ut(Array.prototype.lastIndexOf),ul=ut(Array.prototype.pop),gr=ut(Array.prototype.push),lC=ut(Array.prototype.splice),us=ut(String.prototype.toLowerCase),Bo=ut(String.prototype.toString),Uo=ut(String.prototype.match),yr=ut(String.prototype.replace),dC=ut(String.prototype.indexOf),uC=ut(String.prototype.trim),Tt=ut(Object.prototype.hasOwnProperty),ot=ut(RegExp.prototype.test),xr=mC(TypeError);function ut(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 mC(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 xe(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:us;dl&&dl(e,null);let s=t.length;for(;s--;){let o=t[s];if(typeof o=="string"){const a=r(o);a!==o&&(oC(t)||(t[s]=a),o=a)}e[o]=!0}return e}function pC(e){for(let t=0;t<e.length;t++)Tt(e,t)||(e[t]=null);return e}function Ft(e){const t=xa(null);for(const[r,s]of Ep(e))Tt(e,r)&&(Array.isArray(s)?t[r]=pC(s):s&&typeof s=="object"&&s.constructor===Object?t[r]=Ft(s):t[r]=s);return t}function vr(e,t){for(;e!==null;){const s=iC(e,t);if(s){if(s.get)return ut(s.get);if(typeof s.value=="function")return ut(s.value)}e=aC(e)}function r(){return null}return r}const ml=dt(["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"]),Wo=dt(["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=dt(["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"]),fC=dt(["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"]),Vo=dt(["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"]),hC=dt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),pl=dt(["#text"]),fl=dt(["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"]),Ho=dt(["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=dt(["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"]),os=dt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),gC=St(/\{\{[\w\W]*|[\w\W]*\}\}/gm),yC=St(/<%[\w\W]*|[\w\W]*%>/gm),xC=St(/\$\{[\w\W]*/gm),vC=St(/^data-[\-\w.\u00B7-\uFFFF]+$/),bC=St(/^aria-[\-\w]+$/),Tp=St(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),_C=St(/^(?:\w+script|data):/i),wC=St(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ip=St(/^html$/i),jC=St(/^[a-z][.\w]*(-[.\w]+)+$/i);var gl=Object.freeze({__proto__:null,ARIA_ATTR:bC,ATTR_WHITESPACE:wC,CUSTOM_ELEMENT:jC,DATA_ATTR:vC,DOCTYPE_NAME:Ip,ERB_EXPR:yC,IS_ALLOWED_URI:Tp,IS_SCRIPT_OR_DATA:_C,MUSTACHE_EXPR:gC,TMPLIT_EXPR:xC});const br={element:1,text:3,progressingInstruction:7,comment:8,document:9},kC=function(){return typeof window>"u"?null:window},SC=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}},yl=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Rp(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:kC();const t=de=>Rp(de);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:f}=e,g=l.prototype,h=vr(g,"cloneNode"),b=vr(g,"remove"),w=vr(g,"nextSibling"),y=vr(g,"childNodes"),_=vr(g,"parentNode");if(typeof i=="function"){const de=r.createElement("template");de.content&&de.content.ownerDocument&&(r=de.content.ownerDocument)}let j,C="";const{implementation:I,createNodeIterator:S,createDocumentFragment:N,getElementsByTagName:$}=r,{importNode:k}=s;let P=yl();t.isSupported=typeof Ep=="function"&&typeof _=="function"&&I&&I.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:A,ERB_EXPR:L,TMPLIT_EXPR:z,DATA_ATTR:D,ARIA_ATTR:R,IS_SCRIPT_OR_DATA:O,ATTR_WHITESPACE:T,CUSTOM_ELEMENT:W}=gl;let{IS_ALLOWED_URI:E}=gl,q=null;const ne=xe({},[...ml,...Wo,...qo,...Vo,...pl]);let U=null;const K=xe({},[...fl,...Ho,...hl,...os]);let J=Object.seal(xa(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}})),he=null,B=null;const X=Object.seal(xa(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let me=!0,V=!0,re=!1,le=!0,pe=!1,Re=!0,He=!1,Ze=!1,Ge=!1,Qe=!1,Pe=!1,rt=!1,Ce=!0,ee=!1;const je="user-content-";let Oe=!0,F=!1,te={},se=null;const ge=xe({},["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 be=null;const Ae=xe({},["audio","video","img","source","image","track"]);let $n=null;const Qt=xe({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),zn="http://www.w3.org/1998/Math/MathML",Fn="http://www.w3.org/2000/svg",wt="http://www.w3.org/1999/xhtml";let Yt=wt,pr=!1,_n=null;const $t=xe({},[zn,Fn,wt],Bo);let Bn=xe({},["mi","mo","mn","ms","mtext"]),Un=xe({},["annotation-xml"]);const Br=xe({},["title","style","font","a","script"]);let rn=null;const fe=["application/xhtml+xml","text/html"],ze="text/html";let _e=null,Fe=null;const Wn=r.createElement("form"),Be=function(M){return M instanceof RegExp||M instanceof Function},tt=function(){let M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Fe&&Fe===M)){if((!M||typeof M!="object")&&(M={}),M=Ft(M),rn=fe.indexOf(M.PARSER_MEDIA_TYPE)===-1?ze:M.PARSER_MEDIA_TYPE,_e=rn==="application/xhtml+xml"?Bo:us,q=Tt(M,"ALLOWED_TAGS")?xe({},M.ALLOWED_TAGS,_e):ne,U=Tt(M,"ALLOWED_ATTR")?xe({},M.ALLOWED_ATTR,_e):K,_n=Tt(M,"ALLOWED_NAMESPACES")?xe({},M.ALLOWED_NAMESPACES,Bo):$t,$n=Tt(M,"ADD_URI_SAFE_ATTR")?xe(Ft(Qt),M.ADD_URI_SAFE_ATTR,_e):Qt,be=Tt(M,"ADD_DATA_URI_TAGS")?xe(Ft(Ae),M.ADD_DATA_URI_TAGS,_e):Ae,se=Tt(M,"FORBID_CONTENTS")?xe({},M.FORBID_CONTENTS,_e):ge,he=Tt(M,"FORBID_TAGS")?xe({},M.FORBID_TAGS,_e):Ft({}),B=Tt(M,"FORBID_ATTR")?xe({},M.FORBID_ATTR,_e):Ft({}),te=Tt(M,"USE_PROFILES")?M.USE_PROFILES:!1,me=M.ALLOW_ARIA_ATTR!==!1,V=M.ALLOW_DATA_ATTR!==!1,re=M.ALLOW_UNKNOWN_PROTOCOLS||!1,le=M.ALLOW_SELF_CLOSE_IN_ATTR!==!1,pe=M.SAFE_FOR_TEMPLATES||!1,Re=M.SAFE_FOR_XML!==!1,He=M.WHOLE_DOCUMENT||!1,Qe=M.RETURN_DOM||!1,Pe=M.RETURN_DOM_FRAGMENT||!1,rt=M.RETURN_TRUSTED_TYPE||!1,Ge=M.FORCE_BODY||!1,Ce=M.SANITIZE_DOM!==!1,ee=M.SANITIZE_NAMED_PROPS||!1,Oe=M.KEEP_CONTENT!==!1,F=M.IN_PLACE||!1,E=M.ALLOWED_URI_REGEXP||Tp,Yt=M.NAMESPACE||wt,Bn=M.MATHML_TEXT_INTEGRATION_POINTS||Bn,Un=M.HTML_INTEGRATION_POINTS||Un,J=M.CUSTOM_ELEMENT_HANDLING||{},M.CUSTOM_ELEMENT_HANDLING&&Be(M.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(J.tagNameCheck=M.CUSTOM_ELEMENT_HANDLING.tagNameCheck),M.CUSTOM_ELEMENT_HANDLING&&Be(M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(J.attributeNameCheck=M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),M.CUSTOM_ELEMENT_HANDLING&&typeof M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(J.allowCustomizedBuiltInElements=M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),pe&&(V=!1),Pe&&(Qe=!0),te&&(q=xe({},pl),U=[],te.html===!0&&(xe(q,ml),xe(U,fl)),te.svg===!0&&(xe(q,Wo),xe(U,Ho),xe(U,os)),te.svgFilters===!0&&(xe(q,qo),xe(U,Ho),xe(U,os)),te.mathMl===!0&&(xe(q,Vo),xe(U,hl),xe(U,os))),M.ADD_TAGS&&(typeof M.ADD_TAGS=="function"?X.tagCheck=M.ADD_TAGS:(q===ne&&(q=Ft(q)),xe(q,M.ADD_TAGS,_e))),M.ADD_ATTR&&(typeof M.ADD_ATTR=="function"?X.attributeCheck=M.ADD_ATTR:(U===K&&(U=Ft(U)),xe(U,M.ADD_ATTR,_e))),M.ADD_URI_SAFE_ATTR&&xe($n,M.ADD_URI_SAFE_ATTR,_e),M.FORBID_CONTENTS&&(se===ge&&(se=Ft(se)),xe(se,M.FORBID_CONTENTS,_e)),M.ADD_FORBID_CONTENTS&&(se===ge&&(se=Ft(se)),xe(se,M.ADD_FORBID_CONTENTS,_e)),Oe&&(q["#text"]=!0),He&&xe(q,["html","head","body"]),q.table&&(xe(q,["tbody"]),delete he.tbody),M.TRUSTED_TYPES_POLICY){if(typeof M.TRUSTED_TYPES_POLICY.createHTML!="function")throw xr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof M.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw xr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');j=M.TRUSTED_TYPES_POLICY,C=j.createHTML("")}else j===void 0&&(j=SC(f,o)),j!==null&&typeof C=="string"&&(C=j.createHTML(""));dt&&dt(M),Fe=M}},wn=xe({},[...Wo,...qo,...fC]),mt=xe({},[...Vo,...hC]),gt=function(M){let Q=_(M);(!Q||!Q.tagName)&&(Q={namespaceURI:Yt,tagName:"template"});const ie=us(M.tagName),Ee=us(Q.tagName);return _n[M.namespaceURI]?M.namespaceURI===Fn?Q.namespaceURI===wt?ie==="svg":Q.namespaceURI===zn?ie==="svg"&&(Ee==="annotation-xml"||Bn[Ee]):!!wn[ie]:M.namespaceURI===zn?Q.namespaceURI===wt?ie==="math":Q.namespaceURI===Fn?ie==="math"&&Un[Ee]:!!mt[ie]:M.namespaceURI===wt?Q.namespaceURI===Fn&&!Un[Ee]||Q.namespaceURI===zn&&!Bn[Ee]?!1:!mt[ie]&&(Br[ie]||!wn[ie]):!!(rn==="application/xhtml+xml"&&_n[M.namespaceURI]):!1},yt=function(M){gr(t.removed,{element:M});try{_(M).removeChild(M)}catch{b(M)}},st=function(M,Q){try{gr(t.removed,{attribute:Q.getAttributeNode(M),from:Q})}catch{gr(t.removed,{attribute:null,from:Q})}if(Q.removeAttribute(M),M==="is")if(Qe||Pe)try{yt(Q)}catch{}else try{Q.setAttribute(M,"")}catch{}},ho=function(M){let Q=null,ie=null;if(Ge)M="<remove></remove>"+M;else{const Ue=Uo(M,/^[\r\n\t ]+/);ie=Ue&&Ue[0]}rn==="application/xhtml+xml"&&Yt===wt&&(M='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+M+"</body></html>");const Ee=j?j.createHTML(M):M;if(Yt===wt)try{Q=new p().parseFromString(Ee,rn)}catch{}if(!Q||!Q.documentElement){Q=I.createDocument(Yt,"template",null);try{Q.documentElement.innerHTML=pr?C:Ee}catch{}}const nt=Q.body||Q.documentElement;return M&&ie&&nt.insertBefore(r.createTextNode(ie),nt.childNodes[0]||null),Yt===wt?$.call(Q,He?"html":"body")[0]:He?Q.documentElement:nt},Li=function(M){return S.call(M.ownerDocument||M,M,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},go=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 Kt(de,M,Q){ss(de,ie=>{ie.call(t,M,Q,Fe)})}const zi=function(M){let Q=null;if(Kt(P.beforeSanitizeElements,M,null),go(M))return yt(M),!0;const ie=_e(M.nodeName);if(Kt(P.uponSanitizeElement,M,{tagName:ie,allowedTags:q}),Re&&M.hasChildNodes()&&!$i(M.firstElementChild)&&ot(/<[/\w!]/g,M.innerHTML)&&ot(/<[/\w!]/g,M.textContent)||M.nodeType===br.progressingInstruction||Re&&M.nodeType===br.comment&&ot(/<[/\w]/g,M.data))return yt(M),!0;if(!(X.tagCheck instanceof Function&&X.tagCheck(ie))&&(!q[ie]||he[ie])){if(!he[ie]&&Bi(ie)&&(J.tagNameCheck instanceof RegExp&&ot(J.tagNameCheck,ie)||J.tagNameCheck instanceof Function&&J.tagNameCheck(ie)))return!1;if(Oe&&!se[ie]){const Ee=_(M)||M.parentNode,nt=y(M)||M.childNodes;if(nt&&Ee){const Ue=nt.length;for(let pt=Ue-1;pt>=0;--pt){const Xt=h(nt[pt],!0);Xt.__removalCount=(M.__removalCount||0)+1,Ee.insertBefore(Xt,w(M))}}}return yt(M),!0}return M instanceof l&&!gt(M)||(ie==="noscript"||ie==="noembed"||ie==="noframes")&&ot(/<\/no(script|embed|frames)/i,M.innerHTML)?(yt(M),!0):(pe&&M.nodeType===br.text&&(Q=M.textContent,ss([A,L,z],Ee=>{Q=yr(Q,Ee," ")}),M.textContent!==Q&&(gr(t.removed,{element:M.cloneNode()}),M.textContent=Q)),Kt(P.afterSanitizeElements,M,null),!1)},Fi=function(M,Q,ie){if(Ce&&(Q==="id"||Q==="name")&&(ie in r||ie in Wn))return!1;if(!(V&&!B[Q]&&ot(D,Q))){if(!(me&&ot(R,Q))){if(!(X.attributeCheck instanceof Function&&X.attributeCheck(Q,M))){if(!U[Q]||B[Q]){if(!(Bi(M)&&(J.tagNameCheck instanceof RegExp&&ot(J.tagNameCheck,M)||J.tagNameCheck instanceof Function&&J.tagNameCheck(M))&&(J.attributeNameCheck instanceof RegExp&&ot(J.attributeNameCheck,Q)||J.attributeNameCheck instanceof Function&&J.attributeNameCheck(Q,M))||Q==="is"&&J.allowCustomizedBuiltInElements&&(J.tagNameCheck instanceof RegExp&&ot(J.tagNameCheck,ie)||J.tagNameCheck instanceof Function&&J.tagNameCheck(ie))))return!1}else if(!$n[Q]){if(!ot(E,yr(ie,T,""))){if(!((Q==="src"||Q==="xlink:href"||Q==="href")&&M!=="script"&&dC(ie,"data:")===0&&be[M])){if(!(re&&!ot(O,yr(ie,T,"")))){if(ie)return!1}}}}}}}return!0},Bi=function(M){return M!=="annotation-xml"&&Uo(M,W)},Ui=function(M){Kt(P.beforeSanitizeAttributes,M,null);const{attributes:Q}=M;if(!Q||go(M))return;const ie={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:U,forceKeepAttr:void 0};let Ee=Q.length;for(;Ee--;){const nt=Q[Ee],{name:Ue,namespaceURI:pt,value:Xt}=nt,qn=_e(Ue),yo=Xt;let Xe=Ue==="value"?yo:uC(yo);if(ie.attrName=qn,ie.attrValue=Xe,ie.keepAttr=!0,ie.forceKeepAttr=void 0,Kt(P.uponSanitizeAttribute,M,ie),Xe=ie.attrValue,ee&&(qn==="id"||qn==="name")&&(st(Ue,M),Xe=je+Xe),Re&&ot(/((--!?|])>)|<\/(style|title|textarea)/i,Xe)){st(Ue,M);continue}if(qn==="attributename"&&Uo(Xe,"href")){st(Ue,M);continue}if(ie.forceKeepAttr)continue;if(!ie.keepAttr){st(Ue,M);continue}if(!le&&ot(/\/>/i,Xe)){st(Ue,M);continue}pe&&ss([A,L,z],qi=>{Xe=yr(Xe,qi," ")});const Wi=_e(M.nodeName);if(!Fi(Wi,qn,Xe)){st(Ue,M);continue}if(j&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!pt)switch(f.getAttributeType(Wi,qn)){case"TrustedHTML":{Xe=j.createHTML(Xe);break}case"TrustedScriptURL":{Xe=j.createScriptURL(Xe);break}}if(Xe!==yo)try{pt?M.setAttributeNS(pt,Ue,Xe):M.setAttribute(Ue,Xe),go(M)?yt(M):ul(t.removed)}catch{st(Ue,M)}}Kt(P.afterSanitizeAttributes,M,null)},Yp=function de(M){let Q=null;const ie=Li(M);for(Kt(P.beforeSanitizeShadowDOM,M,null);Q=ie.nextNode();)Kt(P.uponSanitizeShadowNode,Q,null),zi(Q),Ui(Q),Q.content instanceof a&&de(Q.content);Kt(P.afterSanitizeShadowDOM,M,null)};return t.sanitize=function(de){let M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Q=null,ie=null,Ee=null,nt=null;if(pr=!de,pr&&(de="<!-->"),typeof de!="string"&&!$i(de))if(typeof de.toString=="function"){if(de=de.toString(),typeof de!="string")throw xr("dirty is not a string, aborting")}else throw xr("toString is not a function");if(!t.isSupported)return de;if(Ze||tt(M),t.removed=[],typeof de=="string"&&(F=!1),F){if(de.nodeName){const Xt=_e(de.nodeName);if(!q[Xt]||he[Xt])throw xr("root node is forbidden and cannot be sanitized in-place")}}else if(de instanceof c)Q=ho("<!---->"),ie=Q.ownerDocument.importNode(de,!0),ie.nodeType===br.element&&ie.nodeName==="BODY"||ie.nodeName==="HTML"?Q=ie:Q.appendChild(ie);else{if(!Qe&&!pe&&!He&&de.indexOf("<")===-1)return j&&rt?j.createHTML(de):de;if(Q=ho(de),!Q)return Qe?null:rt?C:""}Q&&Ge&&yt(Q.firstChild);const Ue=Li(F?de:Q);for(;Ee=Ue.nextNode();)zi(Ee),Ui(Ee),Ee.content instanceof a&&Yp(Ee.content);if(F)return de;if(Qe){if(Pe)for(nt=N.call(Q.ownerDocument);Q.firstChild;)nt.appendChild(Q.firstChild);else nt=Q;return(U.shadowroot||U.shadowrootmode)&&(nt=k.call(s,nt,!0)),nt}let pt=He?Q.outerHTML:Q.innerHTML;return He&&q["!doctype"]&&Q.ownerDocument&&Q.ownerDocument.doctype&&Q.ownerDocument.doctype.name&&ot(Ip,Q.ownerDocument.doctype.name)&&(pt="<!DOCTYPE "+Q.ownerDocument.doctype.name+`>
136
- `+pt),pe&&ss([A,L,z],Xt=>{pt=yr(pt,Xt," ")}),j&&rt?j.createHTML(pt):pt},t.setConfig=function(){let de=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};tt(de),Ze=!0},t.clearConfig=function(){Fe=null,Ze=!1},t.isValidAttribute=function(de,M,Q){Fe||tt({});const ie=_e(de),Ee=_e(M);return Fi(ie,Ee,Q)},t.addHook=function(de,M){typeof M=="function"&&gr(P[de],M)},t.removeHook=function(de,M){if(M!==void 0){const Q=cC(P[de],M);return Q===-1?void 0:lC(P[de],Q,1)[0]}return ul(P[de])},t.removeHooks=function(de){P[de]=[]},t.removeAllHooks=function(){P=yl()},t}var CC=Rp();function Op({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:CC.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 NC({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(Op,{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 Ke({amount:e,currency:t}){return new Intl.NumberFormat(void 0,{style:"currency",currency:t}).format(e)}function mo({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:Ke({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:Ke({amount:r,currency:t})}):null]})}const PC={large:"aspect-[4/5]",square:"aspect-square",compact:"aspect-[3/4]"},AC={center:"object-center",top:"object-top",bottom:"object-bottom",left:"object-left",right:"object-right"};function Mp({product:e,href:t,onAddToCart:r,onQuickView:s,className:o,layout:a="large",imageCrop:i="center"}){const c=e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0,l=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:null;return n.jsxs(It,{className:H("group flex h-full flex-col overflow-hidden rounded-2xl",o),children:[n.jsxs("div",{className:"relative",children:[n.jsx("a",{href:t,className:"block","aria-label":`View ${e.title}`,children:n.jsx("div",{className:H("overflow-hidden bg-neutral-100 dark:bg-neutral-900",PC[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]",AC[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(Cn,{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(Cn,{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(Cn,{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(ce,{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(mo,{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(ce,{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 po({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"},f={1:"lg:grid-cols-1",2:"lg:grid-cols-2",3:"lg:grid-cols-3",4:"lg:grid-cols-4"},g=H("grid gap-4",u[Math.min(4,Math.max(1,l))],p[Math.min(4,Math.max(1,d))],f[Math.min(4,Math.max(1,m))]);return n.jsx("div",{className:H(g,a),children:e.map(h=>n.jsx(Mp,{product:h,href:o?o(h):void 0,onAddToCart:r,onQuickView:s,layout:i,imageCrop:c},h.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 EC(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 TC(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 xl(e,t){return e.find(r=>Object.entries(t).every(([s,o])=>r.options[s]===o))??null}function Dp(e){return e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0}function IC(e){return e.inventoryStatus==="low"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity>0&&e.inventoryQuantity<=5}function RC(e){const t=Dp(e),r=!t&&IC(e),s=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0;return{isOutOfStock:t,isLow:r,quantity:s}}function OC(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=>!Dp(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(()=>EC(i),[i]),l=x.useMemo(()=>xl(i,t.selectedOptions),[i,t.selectedOptions]),d=x.useMemo(()=>l?RC(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=TC(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(f=>{const g=f===p,h=OC(i,t.selectedOptions,m,f),b=a&&!h;return n.jsxs(ce,{type:"button",size:"sm",variant:g?"default":"outline",onClick:()=>{const w={...t.selectedOptions,[m]:f},y=xl(i,w);r({selectedOptions:w,variant:y})},"aria-pressed":g,disabled:b,className:H(!h&&!b&&"opacity-50 line-through"),children:[f,!h&&!b&&n.jsx("span",{className:"ml-1 text-[10px] opacity-70",children:"(Out)"})]},f)})})]},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(ce,{type:"button",size:"icon",variant:"outline",onClick:()=>t(Math.max(r,a-1)),disabled:!i,"aria-label":"Decrease quantity",children:"-"}),n.jsx(We,{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(ce,{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(Js,{className:H("max-w-3xl",a),children:[n.jsx(hi,{children:n.jsxs(eo,{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(mo,{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(ce,{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 _a({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(We,{value:e,onChange:o=>t(o.target.value),placeholder:r,className:"pl-9","aria-label":"Search"})]})}function Es({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(ce,{type:"button",variant:"ghost",className:"h-8 px-2 text-xs",onClick:s,children:"Clear"})]}),n.jsx(kt,{}),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:f=>{const g=new Set(c);f.target.checked?g.add(p):g.delete(p),r({...t,tags:Array.from(g)})}}),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(lt,{className:"text-xs",htmlFor:"price-min",children:"Min"}),n.jsx(We,{id:"price-min",inputMode:"decimal",placeholder:String(e.price.min),value:t.priceMin??"",onChange:p=>{const f=Number(p.target.value);r({...t,priceMin:Number.isFinite(f)&&p.target.value!==""?f:void 0})}})]}),n.jsxs("div",{className:"grid gap-1",children:[n.jsx(lt,{className:"text-xs",htmlFor:"price-max",children:"Max"}),n.jsx(We,{id:"price-max",inputMode:"decimal",placeholder:String(e.price.max),value:t.priceMax??"",onChange:p=>{const f=Number(p.target.value);r({...t,priceMax:Number.isFinite(f)&&p.target.value!==""?f: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 MC(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:Ke({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(ce,{type:"button",variant:"outline",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:()=>l(!1),children:"Cancel"}),n.jsx(ce,{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(ce,{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(MC,{className:"h-4 w-4"}):"-"}),n.jsx(We,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const f=Math.floor(Number(p.target.value));if(!Number.isFinite(f))return;const g=Math.max(1,d?Math.min(d,f):f);r(g)},className:"h-8 w-11 px-2 text-center","aria-label":"Quantity"}),n.jsx(ce,{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:Ke({amount:i,currency:e.currency})})]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[Ke({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(ce,{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(We,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const f=Math.floor(Number(p.target.value));if(!Number.isFinite(f))return;const g=Math.max(1,d?Math.min(d,f):f);r(g)},className:"h-9 w-14 text-center","aria-label":"Quantity"}),n.jsx(ce,{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(ce,{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:Ke({amount:i,currency:e.currency})}),n.jsx(ce,{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(kt,{}),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:Ke({amount:t,currency:e})})]}),n.jsx(ce,{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 Lp({onCheckout:e,className:t}){const{config:r}=De(),s=Mt(),{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 $p=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}));$p.displayName="Textarea";function DC(){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=DC();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 Zo(){return`${Date.now()}_${Math.random().toString(16).slice(2)}`}function LC({className:e}){const[t,r]=x.useState(""),[s,o]=x.useState(!1),[a,i]=x.useState(()=>[{id:Zo(),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 f=[".","..","..."];let g=0;const h=window.setInterval(()=>{g=(g+1)%f.length,l(f[g])},450);return()=>window.clearInterval(h)},[s]);const d=x.useRef(null),m=x.useRef(null);x.useEffect(()=>{const f=d.current;f&&(f.scrollTop=f.scrollHeight)},[a.length]);const u=x.useCallback(()=>{const f=m.current;if(!f)return;const g=120;f.style.height="0px";const h=Math.min(g,Math.max(40,f.scrollHeight));f.style.height=`${h}px`,f.style.overflowY=f.scrollHeight>g?"auto":"hidden"},[]);x.useEffect(()=>{u()},[t,u]);const p=x.useCallback(()=>{const f=t.trim();f&&(i(g=>[...g,{id:Zo(),role:"user",text:f,createdAt:Date.now()}]),r(""),o(!0),window.setTimeout(()=>{i(g=>[...g,{id:Zo(),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(f=>n.jsx(bl,{className:H("flex",f.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",f.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:f.text})})},f.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($p,{ref:m,rows:1,value:t,onChange:f=>r(f.target.value),placeholder:"Type a message…",className:"max-h-[120px] resize-none",onKeyDown:f=>{f.key==="Enter"&&(f.shiftKey||(f.preventDefault(),p()))}}),n.jsx(ce,{type:"button",onClick:p,disabled:!t.trim(),className:"h-10 shrink-0",children:"Send"})]})]})}function Lr({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(to,{modal:!1,open:r,onOpenChange:s,children:[e?n.jsx(no,{asChild:!0,children:e}):null,n.jsxs(zr,{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(ro,{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(lo,{className:"h-9",children:[n.jsx(Dr,{value:"cart",className:"text-sm",children:"Cart"}),n.jsx(Dr,{value:"chat",className:"text-sm",children:"Chat"})]})}),n.jsx(Bm,{asChild:!0,children:n.jsx(ce,{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(LC,{className:"h-full"})})]}):n.jsx(Lp,{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(We,{value:s,onChange:a=>o(a.target.value),placeholder:"SAVE10","aria-label":"Promo code"}),n.jsx(ce,{type:"button",variant:"outline",onClick:()=>t(s.trim()||void 0),children:"Apply"})]})]})}function zp({onCheckout:e,showPromoCode:t,className:r}){const{config:s}=De(),o=Mt(),{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(kt,{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 Fp({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 wa({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(lt,{htmlFor:`${e}-line1`,children:"Address line 1"}),n.jsx(We,{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(lt,{htmlFor:`${e}-line2`,children:"Address line 2"}),n.jsx(We,{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(lt,{htmlFor:`${e}-city`,children:"City"}),n.jsx(We,{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(lt,{htmlFor:`${e}-state`,children:"State"}),n.jsx(We,{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(lt,{htmlFor:`${e}-postal`,children:"Postal code"}),n.jsx(We,{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(lt,{htmlFor:`${e}-country`,children:"Country"}),n.jsx(We,{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 Bp({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(ce,{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:Ke({amount:a.price,currency:a.currency||s})})]},a.id)})})]})}function Go({message:e}){return e?n.jsx("div",{className:"text-xs text-red-600",children:e}):null}function Up({className:e}){const{config:t}=De(),r=Ls(),s=Mt(),o=t.checkout.mode,a=x.useMemo(()=>is(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=Fd({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(It,{className:"rounded-2xl",children:n.jsxs(Ht,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Digital delivery"}),n.jsx("div",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:a.fulfillmentNotes||"This is a digital product and will be available from your account after purchase."})]})}):null,a.hasPhysical&&!(t.checkout.allowShipping??!1)?n.jsx(It,{className:"rounded-2xl border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/30",children:n.jsxs(Ht,{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(lt,{htmlFor:"checkout-email",children:"Email"}),n.jsx(We,{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(Go,{message:r.fieldErrors.email})]}):null,a.name!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(lt,{htmlFor:"checkout-name",children:"Name"}),n.jsx(We,{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(Go,{message:r.fieldErrors.name})]}):null,a.phone!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(lt,{htmlFor:"checkout-phone",children:"Phone"}),n.jsx(We,{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(Go,{message:r.fieldErrors.phone})]}):null]})]}):null,i?n.jsx(wa,{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(Bp,{methods:u.methods,value:r.values.shippingMethodId,onChange:p=>r.setField("shippingMethodId",p),currency:t.currency}):null,o==="full"?n.jsx(wa,{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(lt,{htmlFor:"checkout-tip",children:["Tip amount (",t.currency,")"]}),n.jsx(We,{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(lt,{htmlFor:"checkout-notes",children:"Order notes (optional)"}),n.jsx(We,{id:"checkout-notes",value:r.values.notes??"",onChange:p=>r.setField("notes",p.target.value),placeholder:"Delivery instructions, gift note…"})]})]}):null]})}function Wp(){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 $C=Object.freeze(Object.defineProperty({__proto__:null,detectSolanaWallets:Wp},Symbol.toStringTag,{value:"Module"}));function zC(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 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("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(Js,{className:H("sm:max-w-lg",i),children:[n.jsxs(hi,{children:[n.jsxs(eo,{className:"flex items-center gap-2",children:[n.jsx(zC,{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(BC,{issue:l,onRemove:()=>s(l.productId,l.variantId),onUpdateQty:d=>o(l.productId,l.variantId,d)},`${l.productId}::${l.variantId??""}`))}),n.jsxs(Fm,{className:"flex-col gap-2 sm:flex-row",children:[a?n.jsx(ce,{type:"button",variant:"outline",onClick:()=>{t(!1),a()},children:"Go to Cart"}):null,n.jsx(ce,{type:"button",onClick:()=>t(!1),children:"Continue"})]})]})})}function BC({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(ce,{type:"button",size:"sm",variant:"outline",onClick:()=>r(e.availableQty),children:["Update to ",e.availableQty]}):null,n.jsxs(ce,{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(FC,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Remove"})]})]})]})}function Vp({className:e,ctaLabel:t,renderEmbedded:r,embeddedFallback:s,renderCustom:o,customFallback:a}){const{config:i}=De(),c=Mt(),l=Ls(),{config:d,isLoading:m}=Ud(),[u,p]=x.useState(!1);x.useEffect(()=>{p(Wp())},[]);const f=Bd({items:c.items}),[g,h]=x.useState(!1),b=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(()=>b.filter(L=>!(L.id==="card"&&!d.card||L.id==="crypto"&&!d.crypto||L.id==="credits"&&!d.credits||L.id==="crypto"&&!u)),[u,b,d]),[y,_]=x.useState((w[0]??b[0]).id);x.useEffect(()=>{w.length&&(w.some(A=>A.id===y)||_(w[0].id))},[y,w]),x.useEffect(()=>{l.reset()},[y]);const j=w.find(A=>A.id===y)??b.find(A=>A.id===y)??b[0],C=j.description??(y==="crypto"?"Pay using a connected wallet.":void 0),I=y==="crypto"&&!u,S=m||l.status==="validating"||l.status==="creating_session"||l.status==="redirecting"||f.isVerifying,N=t??j.ctaLabel??(i.checkout.mode==="none"?"Continue to payment":"Pay now"),$=x.useCallback(async A=>{const L=await f.verify();if(!L.ok&&L.issues.length>0){h(!0);return}l.createCheckoutSession({paymentMethodId:A})},[l,f]),k=l.session?.kind==="embedded"?l.session:null,P=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:y,onValueChange:_,children:n.jsx(lo,{className:"w-full",children:w.map(A=>n.jsx(Dr,{value:A.id,className:"flex-1",disabled:S,children:A.label},A.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,P?n.jsx("div",{className:"space-y-3",children:o?o(P):a??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Checkout session created. Provide `renderCustom` to render a custom payment UI."})}):k?n.jsx("div",{className:"space-y-3",children:r?r(k):s??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Embedded checkout session created. Provide `renderEmbedded` to render your payment UI."})}):n.jsx(ce,{type:"button",className:"w-full",disabled:c.items.length===0||S||I,onClick:()=>{$(y)},children:f.isVerifying?"Checking availability…":S?"Processing…":N}),!k&&!P?n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:I?"Install a browser wallet to enable crypto payments.":C??"You will be redirected to complete your payment."}):null,n.jsx(qp,{open:g,onOpenChange:A=>{h(A),A||f.reset()},issues:f.result?.issues??[],onRemoveItem:(A,L)=>{c.removeItem(A,L)},onUpdateQuantity:(A,L,z)=>{c.setQty(A,L,z)}})]})}function Hp({className:e}){const{config:t}=De(),r=Mt(),s=Ls(),{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(kt,{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:Ke({amount:i.unitPrice*i.qty,currency:i.currency})})]},`${i.productId}::${i.variantId??""}`))}),n.jsx(kt,{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(kt,{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:Ke({amount:r.subtotal,currency:t.currency})})]})]})}function fo({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:Ke({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(ce,{type:"button",onClick:t,children:"Continue shopping"}):null,r?n.jsx(ce,{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(ce,{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(ce,{type:"button",onClick:t,children:"Back to shop"})}):null]})}function UC({onContinueShopping:e,onViewOrders:t,className:r,receiptClassName:s}){const o=qa();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(fo,{result:o,onContinueShopping:e,onViewOrders:t,className:H("w-full max-w-lg",s)})})}function WC({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(fo,{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 Zp({order:e,onView:t,className:r}){const s=`${e.items.length} item${e.items.length===1?"":"s"}`,o=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),a=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(It,{className:H("group overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm transition-shadow hover:shadow-md dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsx(Ht,{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(Cn,{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:Ke({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(ce,{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(ce,{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(ce,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:()=>t(e),children:"Details"}):null]})]})})})}function Gp({orders:e,onView:t,className:r}){return n.jsx("div",{className:H("grid gap-4",r),children:e.map(s=>n.jsx(Zp,{order:s,onView:t},s.id))})}function VC(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 Qp({order:e,onBack:t,className:r}){const s=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),o=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(It,{className:H("overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsxs(Ht,{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(Cn,{variant:VC(e.status),className:"capitalize",children:o}),t?n.jsx(ce,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:t,children:"Back"}):null]})]}),n.jsx(kt,{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:Ke({amount:a.unitPrice*a.qty,currency:a.currency})})]},`${a.title}-${i}`))}),n.jsx(kt,{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:Ke({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(ce,{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(ce,{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 HC(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 ZC={shop:"/shop",category:e=>`/shop/${e}`,product:e=>`/product/${e}`,cart:"/cart",checkout:"/checkout",orders:"/account/orders",subscribe:"/subscribe"};function GC(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 QC({className:e,routes:t,initialCategorySlug:r}){const{config:s}=De(),o=Mt(),a=uo(),i={...ZC,...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 B=window.matchMedia?.("(min-width: 1024px)");if(!B)return;const X=()=>m(B.matches);return X(),B.addEventListener?.("change",X),()=>B.removeEventListener?.("change",X)},[]);const{categories:u,isLoading:p,error:f}=Ua(),g=x.useMemo(()=>Va({includeCategory:!0}),[]),[h,b]=x.useState(g?.search??""),[w,y]=x.useState(r??g?.category),[_,j]=x.useState(g?.page??1),[C,I]=x.useState(g?.sort??"featured"),[S,N]=x.useState(g?.filters??{}),{data:$,isLoading:k,error:P}=$s({category:w,search:h.trim()||void 0,filters:S,sort:C,page:_,pageSize:24}),A=x.useMemo(()=>GC($?.items??[]),[$?.items]),{settings:L}=or(),z=L.catalog.filters,D=L.catalog.sort,R=x.useMemo(()=>{const B=[];return D.featured&&B.push({value:"featured",label:"Featured"}),D.priceAsc&&B.push({value:"price_asc",label:"Price: Low to High"}),D.priceDesc&&B.push({value:"price_desc",label:"Price: High to Low"}),B.length===0&&B.push({value:"featured",label:"Featured"}),B},[D]);x.useEffect(()=>{R.some(B=>B.value===C)||I(R[0].value)},[R,C]),Ha({search:h,sort:C,page:_,category:w,filters:S},{includeCategory:!0});const[O,T]=x.useState(!1),[W,E]=x.useState(!1),[q,ne]=x.useState(null),[U,K]=x.useState(!1),J=B=>{y(B.slug),j(1),T(!1)},he=x.useCallback((B,X,me)=>{o.addItem({productId:B.id,variantId:X?.id,unitPrice:B.price,currency:B.currency,titleSnapshot:X?`${B.title} — ${X.title}`:B.title,imageSnapshot:B.images[0]?.url,paymentResource:B.id,metadata:Di(B)},me),a?.toast({title:"Added to cart",description:B.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(i.cart):(l("cart"),E(!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:h,onChange:b})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(to,{open:O,onOpenChange:T,children:[n.jsx(no,{asChild:!0,children:n.jsx(ce,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(zr,{side:"left",children:[n.jsx(ro,{children:n.jsx(so,{children:"Browse"})}),n.jsxs("div",{className:"mt-4",children:[f?n.jsx(Vt,{description:f}):null,p?n.jsxs("div",{className:"space-y-2",children:[n.jsx($e,{className:"h-9"}),n.jsx($e,{className:"h-9"}),n.jsx($e,{className:"h-9"})]}):n.jsxs("div",{className:"space-y-6",children:[n.jsx(_a,{categories:u,activeSlug:w,onSelect:J}),n.jsx(Es,{facets:A,value:S,onChange:B=>{N(B),j(1)},onClear:()=>{N({}),j(1)},enabledFilters:z}),R.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Cs,{value:C,onValueChange:B=>{I(B),j(1)},children:[n.jsx(Rr,{"aria-label":"Sort",children:n.jsx(Ns,{placeholder:"Sort"})}),n.jsx(Or,{children:R.map(B=>n.jsx(Mr,{value:B.value,children:B.label},B.value))})]})]})]})]})]})]}),n.jsx(Lr,{open:!d&&W,onOpenChange:E,side:"bottom",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ce,{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(Lr,{open:d&&W,onOpenChange:E,side:"popup",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ce,{type:"button",variant:"outline",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ce,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(i.checkout)},children:"Checkout"})]})]})}),n.jsxs(ce,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",W?"lg:hidden":void 0),onClick:()=>{l("chat"),E(!0)},"aria-label":"Open chat",children:[n.jsx(HC,{className:"h-4 w-4"}),"Chat"]}),n.jsxs("main",{className:"mx-auto grid max-w-7xl items-start gap-6 px-4 py-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:n.jsxs(It,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:[n.jsx(Ar,{className:"pb-4",children:n.jsx(Er,{className:"text-base",children:"Browse"})}),n.jsxs(Ht,{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"}),f?n.jsx(Vt,{className:"mt-3",description:f}):null,p?n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx($e,{className:"h-9"}),n.jsx($e,{className:"h-9"}),n.jsx($e,{className:"h-9"})]}):n.jsx("div",{className:"mt-3",children:n.jsx(_a,{categories:u,activeSlug:w,onSelect:J})})]}),R.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(Cs,{value:C,onValueChange:B=>{I(B),j(1)},children:[n.jsx(Rr,{"aria-label":"Sort",children:n.jsx(Ns,{placeholder:"Sort"})}),n.jsx(Or,{children:R.map(B=>n.jsx(Mr,{value:B.value,children:B.label},B.value))})]})})]}),n.jsx(Es,{facets:A,value:S,onChange:B=>{N(B),j(1)},onClear:()=>{N({}),j(1)},enabledFilters:z})]})]})})}),n.jsxs("section",{children:[n.jsx("div",{className:"flex items-end justify-between gap-3",children:n.jsxs("div",{children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:L.shopPage.title||"Shop"}),L.shopPage.description&&n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:L.shopPage.description})]})}),P?n.jsx(Vt,{className:"mt-6",description:P}):null,k?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((B,X)=>n.jsx($e,{className:"aspect-[4/5] rounded-2xl"},X))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(po,{products:$?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:B=>i.product(B.slug),onAddToCart:B=>he(B,null,1),onQuickView:B=>{ne(B),K(!0)},layout:L.shopLayout.layout,imageCrop:L.shopLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ce,{type:"button",variant:"outline",disabled:_<=1,onClick:()=>j(B=>Math.max(1,B-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",_]}),n.jsx(ce,{type:"button",variant:"outline",disabled:!$?.hasNextPage,onClick:()=>j(B=>B+1),children:"Next"})]})]})]})]}),n.jsx(Ei,{product:q,open:U,onOpenChange:K,productHref:B=>i.product(B),onAddToCart:(B,X,me)=>he(B,X,me)})]})}function YC(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 KC({categorySlug:e,className:t,routes:r}){const{config:s}=De(),o=Mt(),a=uo(),{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 V=window.matchMedia?.("(min-width: 1024px)");if(!V)return;const re=()=>l(V.matches);return re(),V.addEventListener?.("change",re),()=>V.removeEventListener?.("change",re)},[]);const[d,m]=x.useState(!1),[u,p]=x.useState(!1),[f,g]=x.useState("cart"),h=x.useMemo(()=>Va({includeCategory:!1}),[]),[b,w]=x.useState(h?.search??""),[y,_]=x.useState(h?.page??1),[j,C]=x.useState(h?.sort??"featured"),[I,S]=x.useState(h?.filters??{}),[N,$]=x.useState(null),[k,P]=x.useState(!1),A=i.find(V=>V.slug===e)??null,{data:L,isLoading:z,error:D}=$s({category:e,search:b.trim()||void 0,filters:I,sort:j,page:y,pageSize:24}),R=r?.product??(V=>`/product/${V}`),O=r?.shop??"/shop",T=r?.cart??"/cart",W=r?.checkout??"/checkout",E=x.useMemo(()=>{const V=L?.items??[],re=new Set;let le=Number.POSITIVE_INFINITY,pe=0;for(const Ze of V){for(const Ge of Ze.tags??[])re.add(Ge);le=Math.min(le,Ze.price),pe=Math.max(pe,Ze.price)}const Re=Array.from(re).slice(0,12),He=Number.isFinite(le)?{min:le,max:pe}:void 0;return{tags:Re,price:He}},[L?.items]),{settings:q}=or(),ne=q.catalog.filters,U=q.catalog.sort,K=x.useMemo(()=>{const V=[];return U.featured&&V.push({value:"featured",label:"Featured"}),U.priceAsc&&V.push({value:"price_asc",label:"Price: Low to High"}),U.priceDesc&&V.push({value:"price_desc",label:"Price: High to Low"}),V.length===0&&V.push({value:"featured",label:"Featured"}),V},[U]);x.useEffect(()=>{K.some(V=>V.value===j)||C(K[0].value)},[K,j]),Ha({search:b,sort:j,page:y,filters:I},{includeCategory:!1});const J=x.useCallback((V,re,le)=>{o.addItem({productId:V.id,variantId:re?.id,unitPrice:V.price,currency:V.currency,titleSnapshot:re?`${V.title} — ${re.title}`:V.title,imageSnapshot:V.images[0]?.url,paymentResource:V.id,metadata:Di(V)},le),a?.toast({title:"Added to cart",description:V.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(T):(g("cart"),p(!0)))}})},[o,T,a]),he=V=>{S(V),_(1)},B=()=>{S({}),_(1)},X=V=>{C(V),_(1)},me=n.jsx(It,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:n.jsxs(Ht,{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(ce,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2 text-xs",children:n.jsx("a",{href:O,children:"All categories"})})]}),n.jsx("div",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:A?.name??e}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:A?.description??"Browse products in this category."})]}),K.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Cs,{value:j,onValueChange:X,children:[n.jsx(Rr,{"aria-label":"Sort",children:n.jsx(Ns,{placeholder:"Sort"})}),n.jsx(Or,{children:K.map(V=>n.jsx(Mr,{value:V.value,children:V.label},V.value))})]})]}),n.jsx(kt,{}),n.jsx(Es,{facets:E,value:I,onChange:he,onClear:B,enabledFilters:ne})]})});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:O,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(Ii,{value:b,onChange:w})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(to,{open:d,onOpenChange:m,children:[n.jsx(no,{asChild:!0,children:n.jsx(ce,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(zr,{side:"left",children:[n.jsx(ro,{children:n.jsx(so,{children:"Filters"})}),n.jsx("div",{className:"mt-4",children:me})]})]}),n.jsx(Lr,{open:!c&&u,onOpenChange:p,side:"bottom",preferredTab:f,onCheckout:()=>{typeof window<"u"&&window.location.assign(W)},trigger:n.jsxs(ce,{type:"button",variant:"default",onClick:()=>g("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx(Lr,{open:c&&u,onOpenChange:p,side:"popup",preferredTab:f,onCheckout:()=>{typeof window<"u"&&window.location.assign(W)},trigger:n.jsxs(ce,{type:"button",variant:"outline",onClick:()=>g("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ce,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(W)},children:"Checkout"})]})]})}),n.jsxs(ce,{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:()=>{g("chat"),p(!0)},"aria-label":"Open chat",children:[n.jsx(YC,{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:O},{label:A?.name??e}]}),n.jsxs("div",{className:"mt-6",children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:A?.name??"Category"}),n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:A?.description??"Browse products in this category."})]}),D?n.jsx(Vt,{className:"mt-6",description:D}):null,n.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:me})}),n.jsx("div",{children:z?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((V,re)=>n.jsx($e,{className:"aspect-[4/5] rounded-2xl"},re))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(po,{products:L?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:V=>R(V.slug),onAddToCart:V=>J(V,null,1),onQuickView:V=>{$(V),P(!0)},layout:q.categoryLayout.layout,imageCrop:q.categoryLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ce,{type:"button",variant:"outline",disabled:y<=1,onClick:()=>_(V=>Math.max(1,V-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",y]}),n.jsx(ce,{type:"button",variant:"outline",disabled:!L?.hasNextPage,onClick:()=>_(V=>V+1),children:"Next"})]})]})})]}),n.jsx(Ei,{product:N,open:k,onOpenChange:P,productHref:V=>R(V),onAddToCart:(V,re,le)=>J(V,re,le)})]})]})}function XC({slug:e,className:t,routes:r}){const s=Mt(),o=uo(),{product:a,isLoading:i,error:c}=Ld(e),[l,d]=x.useState(1),[m,u]=x.useState({selectedOptions:{},variant:null});x.useEffect(()=>{if(!a||!a.variants?.length)return;const A=a.variants[0];u({selectedOptions:{...A.options},variant:A})},[a?.id]);const{settings:p}=or(),{mode:f,maxItems:g}=p.relatedProducts,h=Wd({productId:a?.id,enabled:f==="ai"&&!!a?.id}),b=x.useMemo(()=>f==="by_category"&&a?.categoryIds?.length?{category:a.categoryIds[0],page:1,pageSize:g+1}:{page:1,pageSize:g+4},[f,g,a?.categoryIds]),w=$s(b),y=x.useMemo(()=>{const L=(w.data?.items??[]).filter(z=>z.slug!==e);if(f==="manual"&&a){const z=a.attributes?.relatedProductIds||a.attributes?.related_product_ids;if(z){const D=Jo(String(z));if(D.length>0){const R=new Map(L.map(T=>[T.id,T]));return D.map(T=>R.get(T)).filter(T=>!!T).slice(0,g)}}}if(f==="ai"&&h.relatedProductIds&&h.relatedProductIds.length>0){const z=new Map(L.map(R=>[R.id,R])),D=h.relatedProductIds.map(R=>z.get(R)).filter(R=>!!R);if(D.length>0)return D.slice(0,g)}return L.slice(0,g)},[w.data?.items,e,f,g,a,h.relatedProductIds]),_=r?.shop??"/shop",j=r?.checkout??"/checkout",C=r?.cart??"/cart",I=r?.product??(A=>`/product/${A}`);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($e,{className:"h-5 w-40"}),n.jsxs("div",{className:"mt-6 grid gap-8 lg:grid-cols-2",children:[n.jsx($e,{className:"aspect-square rounded-2xl"}),n.jsxs("div",{className:"space-y-4",children:[n.jsx($e,{className:"h-8 w-2/3"}),n.jsx($e,{className:"h-6 w-32"}),n.jsx($e,{className:"h-20"}),n.jsx($e,{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(Vt,{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(Vt,{description:"Product not found."})})});const S=m.variant?.price??a.price,N=m.variant?.compareAtPrice??a.compareAtPrice,$=a.inventoryStatus==="out_of_stock"||typeof a.inventoryQuantity=="number"&&a.inventoryQuantity<=0,k=()=>{$||(s.addItem({productId:a.id,variantId:m.variant?.id,unitPrice:S,currency:a.currency,titleSnapshot:m.variant?`${a.title} — ${m.variant.title}`:a.title,imageSnapshot:a.images[0]?.url,paymentResource:a.id,metadata:Di(a)},l),o?.toast({title:"Added to cart",description:a.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&window.location.assign(C)}}))},P=()=>{$||(k(),typeof window<"u"&&window.location.assign(j))};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:_},{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(mo,{amount:S,currency:a.currency,compareAt:N})}),$?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:A=>u(A)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(Ai,{qty:l,onChange:d}),n.jsx(ce,{type:"button",onClick:k,className:"flex-1",disabled:$,children:$?"Out of stock":"Add to cart"}),n.jsx(ce,{type:"button",variant:"outline",onClick:P,disabled:$,children:"Buy now"})]}),(p.sections.showDescription||p.sections.showSpecs||p.sections.showShipping)&&n.jsxs(lp,{type:"single",collapsible:!0,defaultValue:p.sections.showDescription?"desc":void 0,children:[p.sections.showDescription&&n.jsxs(kr,{value:"desc",children:[n.jsx(Sr,{children:"Description"}),n.jsx(Cr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.description})})]}),p.sections.showSpecs&&n.jsxs(kr,{value:"specs",children:[n.jsx(Sr,{children:"Specs"}),n.jsx(Cr,{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(([A,L])=>n.jsxs("div",{children:[n.jsxs("span",{className:"font-medium text-neutral-950 dark:text-neutral-50",children:[A,":"]})," ",String(L)]},A))}):"No specs provided."})})]}),p.sections.showShipping&&n.jsxs(kr,{value:"ship",children:[n.jsx(Sr,{children:"Shipping & returns"}),n.jsx(Cr,{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&&y.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(po,{products:y,columns:{base:2,md:4,lg:4},layout:p.relatedProducts.layout.layout,imageCrop:p.relatedProducts.layout.imageCrop,getProductHref:A=>I(A.slug),onAddToCart:A=>s.addItem({productId:A.id,unitPrice:A.price,currency:A.currency,titleSnapshot:A.title,imageSnapshot:A.images[0]?.url,paymentResource:A.id},1)})})]}):null]})})}function JC({className:e,checkoutHref:t}){const{config:r}=De(),{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(zp,{onCheckout:()=>{typeof window<"u"&&window.location.assign(o)},showPromoCode:a})})]})})}function eN({className:e,routes:t}){const{config:r}=De(),s=Mt(),o=qa(),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(fo,{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(Dd,{children:c?n.jsxs(It,{className:"rounded-2xl",children:[n.jsx(Ar,{className:"pb-4",children:n.jsx(Er,{className:"text-base",children:"Sign in required"})}),n.jsxs(Ht,{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(ce,{type:"button",onClick:()=>{typeof window<"u"&&window.location.assign(m)},children:"Sign in"})}):null]})]}):n.jsx(Fp,{left:n.jsxs("div",{className:"space-y-6",children:[n.jsx(Up,{}),n.jsxs(It,{className:"rounded-2xl",children:[n.jsx(Ar,{className:"pb-4",children:n.jsx(Er,{className:"text-base",children:"Payment"})}),n.jsxs(Ht,{children:[n.jsx(kt,{className:"mb-4"}),n.jsx(Vp,{})]})]})]}),right:n.jsx("div",{className:"lg:sticky lg:top-24",children:n.jsx(Hp,{})})})})})]}):null]})})}function tN({className:e,isSignedIn:t=!0,onLogin:r}){const{orders:s,isLoading:o,error:a}=$d(),[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(Vt,{className:"mt-8",description:a}):null,o?n.jsxs("div",{className:"mt-8 grid gap-4",children:[n.jsx($e,{className:"h-32 rounded-2xl"}),n.jsx($e,{className:"h-32 rounded-2xl"}),n.jsx($e,{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(Qp,{order:i,onBack:()=>c(null)})}):n.jsx("div",{className:"mt-8",children:n.jsx(Gp,{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 nN({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 rN({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 sN(e){switch(e){case"x402":return"Crypto (x402)";case"credits":return"Credits";case"stripe":return"Card";default:return"Payment"}}function oN({order:e,source:t,purchaseId:r,customerEmail:s,customerName:o,className:a,onBack:i}){const{config:c}=De(),l=t??e.source,d=r??e.purchaseId,m=s??e.customerEmail,u=o??e.customerName,p=c.brand?.name??"Store",f=c.brand?.logoUrl,g=()=>{typeof window<"u"&&window.print()},h=new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"}),b=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(ce,{type:"button",variant:"ghost",size:"sm",onClick:i,children:[n.jsx(rN,{className:"mr-1"})," Back"]}):n.jsx("div",{}),n.jsxs(ce,{type:"button",variant:"outline",size:"sm",onClick:g,children:[n.jsx(nN,{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:[f?n.jsx("img",{src:f,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:h}),n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:b})]}),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:sN(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(Cn,{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,y)=>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:Ke({amount:w.unitPrice*w.qty,currency:w.currency})})]},`${w.title}-${y}`))})]})}),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:Ke({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:Ke({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 aN({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 iN({className:e,title:t="Choose Your Plan",subtitle:r="Select the plan that best fits your needs.",annualSavingsBadge:s="2 months free",popularBadgeText:o="Best Deal",footerNotice:a}){const{config:i}=De(),{tiers:c,status:l,isLoading:d,error:m}=zd(),[u,p]=x.useState("monthly"),f=!!i.adapter.createSubscriptionCheckoutSession,g=async h=>{if(!i.adapter.createSubscriptionCheckoutSession)return;const b=await i.adapter.createSubscriptionCheckoutSession({tierId:h,interval:u,successUrl:i.checkout.successUrl,cancelUrl:i.checkout.cancelUrl});b.kind==="redirect"&&typeof window<"u"&&window.location.assign(b.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(Vt,{className:"mt-10",description:m}):null,d?n.jsxs("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[n.jsx($e,{className:"h-[480px] rounded-2xl"}),n.jsx($e,{className:"h-[480px] rounded-2xl"}),n.jsx($e,{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(h=>{const b=l?.isActive&&l.currentTierId===h.id,w=u==="annual"&&h.priceAnnual?h.priceAnnual:h.priceMonthly,y=h.isPopular,_=h.inventoryQuantity!=null,j=_?Math.max(0,(h.inventoryQuantity??0)-(h.inventorySold??0)):null,C=_&&j===0,I=_&&j!=null&&j>0&&j<=5,[S,...N]=h.features;return n.jsxs("div",{className:H("relative flex flex-col rounded-2xl border p-6 transition-shadow",y?"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:[y&&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:h.title}),h.description&&n.jsx("p",{className:H("mt-2 text-sm leading-relaxed",y?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:h.description})]}),n.jsxs("div",{className:"mb-6",children:[n.jsx("div",{className:"text-5xl font-bold tracking-tight",children:Ke({amount:w,currency:h.currency||i.currency})}),n.jsxs("div",{className:H("mt-2 text-sm",y?"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"]})]}),_&&n.jsx("div",{className:H("mb-3 text-xs font-medium",C?"text-red-600 dark:text-red-400":I?y?"text-amber-300 dark:text-amber-600":"text-amber-600 dark:text-amber-400":y?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:C?"Sold out":`${j} remaining`}),n.jsx(ce,{type:"button",className:H("mb-6 w-full rounded-full py-3 font-medium",y?"bg-white text-neutral-900 hover:bg-neutral-100 dark:bg-neutral-900 dark:text-white dark:hover:bg-neutral-800":""),variant:y?"default":"outline",disabled:b||!f||C,onClick:()=>void g(h.id),children:C?"Sold Out":b?"Current Plan":"Purchase"}),S&&n.jsx("div",{className:H("mb-4 text-sm font-semibold",y?"":"text-neutral-900 dark:text-white"),children:S}),N.length>0&&n.jsx("ul",{className:"space-y-3",children:N.map(($,k)=>n.jsxs("li",{className:"flex items-start gap-3",children:[n.jsx(aN,{className:H("mt-0.5",y?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400")}),n.jsx("span",{className:H("text-sm leading-relaxed",y?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:$})]},k))})]},h.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 cN(e){const{processCartCheckout:t}=Is();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 lN=Object.freeze(Object.defineProperty({__proto__:null,Accordion:lp,AccordionContent:Cr,AccordionItem:kr,AccordionTrigger:Sr,AddressForm:wa,Badge:Cn,Breadcrumbs:Ti,Button:ce,Card:It,CardContent:Ht,CardDescription:au,CardFooter:iu,CardHeader:Ar,CardTitle:Er,CartLineItem:Ri,CartPageContent:zp,CartPanel:Lp,CartProvider:tg,CartSidebar:Lr,CartSummary:Oi,CartTemplate:JC,CategoryNav:_a,CategoryTemplate:KC,CedrosShopProvider:Lh,CheckoutCancelPage:WC,CheckoutForm:Up,CheckoutLayout:Fp,CheckoutProvider:Dd,CheckoutReceipt:fo,CheckoutSuccessPage:UC,CheckoutTemplate:eN,Dialog:pi,DialogClose:Gk,DialogContent:Js,DialogDescription:gi,DialogFooter:Fm,DialogHeader:hi,DialogOverlay:fi,DialogPortal:zm,DialogTitle:eo,DialogTrigger:Zk,EmptyState:tr,ErrorBoundary:PS,ErrorState:Vt,FAQItem:Op,FAQList:NC,FilterPanel:Es,Input:We,InventoryVerificationDialog:qp,Label:lt,OrderCard:Zp,OrderDetails:Qp,OrderList:Gp,OrderReview:Hp,PaymentStep:Vp,Price:mo,ProductCard:Mp,ProductGallery:Ni,ProductGrid:po,ProductTemplate:XC,PromoCodeInput:Mi,PurchaseHistoryTemplate:tN,QuantitySelector:Ai,QuickViewDialog:Ei,ReceiptTemplate:oN,SearchInput:Ii,Select:Cs,SelectContent:Or,SelectGroup:Pk,SelectItem:Mr,SelectTrigger:Rr,SelectValue:Ns,Separator:kt,Sheet:to,SheetClose:Bm,SheetContent:zr,SheetDescription:Wm,SheetHeader:ro,SheetOverlay:yi,SheetPortal:Um,SheetTitle:so,SheetTrigger:no,ShippingMethodSelector:Bp,ShopTemplate:QC,Skeleton:$e,SubscriptionTemplate:iN,Tabs:Si,TabsContent:Ap,TabsList:lo,TabsTrigger:Dr,ToastProvider:sC,VariantSelector:Pi,createMockCommerceAdapter:Uh,createPaywallCommerceAdapter:Zh,parseCheckoutReturn:Wa,readCatalogUrlState:Va,useAIRelatedProducts:Wd,useCart:Mt,useCartInventory:Za,useCatalogUrlSync:Ha,useCategories:Ua,useCedrosPayCheckoutAdapter:cN,useCedrosShop:De,useCheckout:Ls,useCheckoutResultFromUrl:qa,useHoldExpiry:Ub,useInventoryVerification:Bd,useOptionalToast:uo,useOrders:$d,usePaymentMethodsConfig:Ud,useProduct:Ld,useProducts:$s,useShippingMethods:Fd,useStandaloneCheckout:Rb,useStorefrontSettings:or,useSubscriptionData:zd,useToast:rC,validateCommerceAdapterContract:Hb},Symbol.toStringTag,{value:"Module"}));exports.CEDROS_EVENTS=fn;exports.CSP_PRESETS=Cf;exports.CedrosPay=Df;exports.CedrosPayAdminDashboard=yh;exports.CouponsSection=zl;exports.CreditsButton=Pa;exports.CreditsSubscribeButton=wh;exports.CryptoButton=Aa;exports.ERROR_CATEGORIES=Cl;exports.PaymentMethodBadge=bh;exports.PaymentModal=Ol;exports.ProductPrice=vh;exports.ProductsSection=Ll;exports.PurchaseButton=Ml;exports.RPC_PROVIDERS=Sf;exports.RefundsSection=Fl;exports.SECURITY_RECOMMENDATIONS=Dh;exports.SettingsSection=Ia;exports.StripeButton=Na;exports.SubscribeButton=_h;exports.SubscriptionManagementPanel=Ph;exports.TransactionsSection=$l;exports.calculateDiscountPercentage=lf;exports.cedrosPayPlugin=xh;exports.createDedupedClickHandler=Rn;exports.createTranslator=Tl;exports.detectLocale=Al;exports.emitPaymentError=jt;exports.emitPaymentProcessing=ln;exports.emitPaymentStart=Mn;exports.emitPaymentSuccess=Dn;exports.emitWalletConnect=Ko;exports.emitWalletConnected=Sl;exports.emitWalletError=as;exports.formatCSP=Pl;exports.formatCouponCodes=cf;exports.generateCSP=kf;exports.generateCSPDirectives=Nl;exports.getAvailableLocales=Pf;exports.getLocalizedError=Af;exports.getModalCloseButtonStyles=Ca;exports.getUserErrorMessage=_f;exports.index=lN;exports.isRetryableError=bf;exports.loadLocale=El;exports.logSecurityReport=Mh;exports.parseCouponCodes=af;exports.stackCheckoutCoupons=df;exports.useCreditsPayment=Il;exports.useCreditsSubscription=Kl;exports.useLocalizedError=Ef;exports.usePaymentMode=nr;exports.useStripeCheckout=Is;exports.useSubscription=Yl;exports.useSubscriptionManagement=Xl;exports.useTranslation=hn;exports.useX402Payment=Rl;exports.validateSecurity=Oh;