@cedros/pay-react 1.1.12 → 1.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/plugin.d.ts.map +1 -1
- package/dist/crypto-only.js +1 -1
- package/dist/crypto-only.mjs +2 -2
- package/dist/{index-ByDbfwun.mjs → index-BXWLgJay.mjs} +3707 -3489
- package/dist/{index-UQAK8nZe.js → index-v_WdS7Ec.js} +18 -18
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{sections-Dtgg3Yjs.js → sections-C0OrGKfh.js} +1 -1
- package/dist/{sections-DE8RekVc.mjs → sections-Dn071Aox.mjs} +1 -1
- package/dist/stripe-only.js +1 -1
- package/dist/stripe-only.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var Xp=Object.create;var qi=Object.defineProperty;var Jp=Object.getOwnPropertyDescriptor;var ef=Object.getOwnPropertyNames;var tf=Object.getPrototypeOf,nf=Object.prototype.hasOwnProperty;var rf=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ef(t))!nf.call(e,o)&&o!==r&&qi(e,o,{get:()=>t[o],enumerable:!(s=Jp(t,o))||s.enumerable});return e};var sf=(e,t,r)=>(r=e!=null?Xp(tf(e)):{},rf(t||!e||!e.__esModule?qi(r,"default",{value:e,enumerable:!0}):r,e));const n=require("react/jsx-runtime"),y=require("react"),J=require("./CedrosContext-C2v_s8cc.js"),ja=require("@solana/wallet-adapter-react"),Hi=require("@solana/wallet-adapter-base"),of=require("@solana/wallet-adapter-react-ui"),af=require("@solana/web3.js"),Zi=require("./index-WcOlBYZJ.js"),ka=require("react-dom");function wl(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const x=wl(y),Is=wl(ka);function cf(e){return!e||!e.coupon_codes?[]:e.coupon_codes.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function lf(e,t=", "){return e.join(t)}function df(e,t){return e<=0?0:(e-t)/e*100}function uf(e,t){if(!t||t.length===0)return e;let r=e,s=0;for(const o of t)if(o.discountType==="percentage"){const a=1-o.discountValue/100;r=r*a}else o.discountType==="fixed"&&(s+=o.discountValue);return r=r-s,r<0&&(r=0),Math.ceil(r*100)/100}function _l(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return 1;const r=Math.floor(t);return r>0?r:1}function ps(e){return e.map(t=>({resource:t.resource,quantity:_l(t.quantity),variantId:t.variantId,metadata:t.metadata}))}function dn(e){return e.reduce((t,r)=>t+_l(r.quantity),0)}function mf(e){return!!(e&&e.length>0&&(e.length>1||e.length===1&&(e[0].quantity??1)>1))}const pf={invalid_payment_proof:{message:"Payment verification failed",action:"Please try your payment again. If this continues, contact support.",technicalHint:"Invalid payment proof format"},invalid_signature:{message:"Transaction signature is invalid",action:"Please approve the transaction in your wallet and try again.",technicalHint:"Transaction signature verification failed"},invalid_transaction:{message:"Transaction format is invalid",action:"Please try your payment again. If this continues, try updating your wallet app.",technicalHint:"Malformed transaction structure"},transaction_not_found:{message:"Transaction not found on the blockchain",action:"Your transaction may still be processing. Please wait a moment and check your wallet, or try again.",technicalHint:"Transaction signature not found on-chain"},transaction_not_confirmed:{message:"Transaction is still processing",action:"Please wait a moment for the blockchain to confirm your transaction, then try again.",technicalHint:"Transaction not yet confirmed"},transaction_failed:{message:"Transaction failed on the blockchain",action:"Check your wallet for details. You may need to adjust your transaction settings or add more SOL for fees.",technicalHint:"On-chain transaction failure"},transaction_expired:{message:"Transaction took too long to process",action:"Please try your payment again. Consider increasing transaction priority if your wallet supports it.",technicalHint:"Transaction blockhash expired"},invalid_recipient:{message:"Payment was sent to the wrong address",action:"Please try again and ensure you approve the correct transaction in your wallet.",technicalHint:"Recipient address mismatch"},invalid_sender:{message:"Payment sender wallet is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Sender address validation failed"},unauthorized_refund_issuer:{message:"You are not authorized to issue refunds",action:"Only authorized accounts can process refunds. Please contact support if you believe this is an error.",technicalHint:"Refund issuer not in authorized list"},amount_below_minimum:{message:"Payment amount is too low",action:"Please check the required amount and try again.",technicalHint:"Amount below minimum threshold"},amount_mismatch:{message:"Payment amount does not match the quote",action:"The price may have changed. Please refresh and try your payment again.",technicalHint:"Amount does not match quote"},insufficient_funds_sol:{message:"Not enough SOL for transaction fees",action:"Add at least 0.001 SOL to your wallet to cover network fees, then try again.",technicalHint:"Insufficient SOL balance for fees"},insufficient_funds_token:{message:"Insufficient balance in your wallet",action:"Add more funds to your wallet and try again.",technicalHint:"Insufficient token balance"},invalid_token_mint:{message:"Incorrect payment token",action:"Please pay with the correct token as shown in the payment details.",technicalHint:"Token mint address mismatch"},not_spl_transfer:{message:"Transaction is not a valid token transfer",action:"Please ensure you are sending the correct token type from your wallet.",technicalHint:"Transaction is not an SPL token transfer"},missing_token_account:{message:"Token account not found",action:"Your wallet may need to create a token account first. Try again or use a different wallet.",technicalHint:"Associated token account does not exist"},invalid_token_program:{message:"Invalid token program",action:"Please try your payment again. If this continues, try using a different wallet.",technicalHint:"Token program ID mismatch"},missing_memo:{message:"Payment memo is required but was not included",action:"Please try your payment again and ensure transaction details are approved in your wallet.",technicalHint:"Required memo instruction missing"},invalid_memo:{message:"Payment memo format is invalid",action:"Please try your payment again.",technicalHint:"Memo does not match expected format"},payment_already_used:{message:"This payment has already been processed",action:"Check your transaction history. If you need to make another payment, please start a new transaction.",technicalHint:"Payment signature already recorded"},signature_reused:{message:"Transaction signature has already been used",action:"Please create a new payment transaction.",technicalHint:"Duplicate signature detected"},quote_expired:{message:"Payment quote has expired",action:"Prices are updated frequently. Please refresh and try your payment again.",technicalHint:"Quote timestamp expired"},missing_field:{message:"Required information is missing",action:"Please check all required fields and try again.",technicalHint:"Required field not provided"},invalid_field:{message:"Some information is invalid",action:"Please check your input and try again.",technicalHint:"Field validation failed"},invalid_amount:{message:"Payment amount is invalid",action:"Please check the amount and try again.",technicalHint:"Amount validation failed"},invalid_wallet:{message:"Wallet address is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Wallet address validation failed"},invalid_resource:{message:"Invalid item selection",action:"Please refresh the page and try again.",technicalHint:"Resource ID validation failed"},invalid_coupon:{message:"Invalid coupon code",action:"Please check the coupon code and try again.",technicalHint:"Coupon code format invalid"},invalid_cart_item:{message:"One or more cart items are invalid",action:"Please review your cart and try again.",technicalHint:"Cart item validation failed"},empty_cart:{message:"Your cart is empty",action:"Please add items to your cart before checking out.",technicalHint:"Cart contains no items"},resource_not_found:{message:"Item not found",action:"This item may no longer be available. Please refresh and try again.",technicalHint:"Resource not found in database"},cart_not_found:{message:"Shopping cart not found",action:"Your cart may have expired. Please start a new order.",technicalHint:"Cart ID not found"},refund_not_found:{message:"Refund not found",action:"Please check your refund reference number or contact support.",technicalHint:"Refund ID not found"},product_not_found:{message:"Product not available",action:"This product may no longer be available. Please browse our current selection.",technicalHint:"Product ID not found"},coupon_not_found:{message:"Coupon code not found",action:"Please check the coupon code or remove it to continue.",technicalHint:"Coupon code not in database"},session_not_found:{message:"Payment session expired",action:"Please start a new payment.",technicalHint:"Session ID not found or expired"},cart_already_paid:{message:"This order has already been paid",action:"Check your order history. If you need to make another purchase, please start a new order.",technicalHint:"Cart marked as paid"},refund_already_processed:{message:"This refund has already been processed",action:"Check your transaction history or contact support for details.",technicalHint:"Refund already completed"},coupon_expired:{message:"Coupon has expired",action:"Please remove the coupon code or use a different code.",technicalHint:"Coupon expiration date passed"},coupon_usage_limit_reached:{message:"Coupon usage limit reached",action:"This coupon has been fully redeemed. Please try a different code.",technicalHint:"Coupon max uses exceeded"},coupon_not_applicable:{message:"Coupon cannot be applied to this purchase",action:"Please check the coupon terms or remove it to continue.",technicalHint:"Coupon conditions not met"},coupon_wrong_payment_method:{message:"Coupon not valid for this payment method",action:"Try a different payment method or remove the coupon code.",technicalHint:"Coupon restricted to specific payment methods"},stripe_error:{message:"Card payment service temporarily unavailable",action:"Please try again in a moment, or use cryptocurrency payment instead.",technicalHint:"Stripe API error"},rpc_error:{message:"Blockchain network temporarily unavailable",action:"Please try again in a moment, or use card payment instead.",technicalHint:"Solana RPC error"},network_error:{message:"Network connection issue",action:"Please check your internet connection and try again.",technicalHint:"Network request failed"},internal_error:{message:"Something went wrong on our end",action:"Please try again. If this continues, contact support.",technicalHint:"Internal server error"},database_error:{message:"Service temporarily unavailable",action:"Please try again in a moment.",technicalHint:"Database operation failed"},config_error:{message:"Service configuration error",action:"Please contact support for assistance.",technicalHint:"Server misconfiguration"}};function fs(e){return pf[e]||{message:"An unexpected error occurred",action:"Please try again or contact support if this continues.",technicalHint:`Unknown error code: ${e}`}}const jl=new Map,Yo=new Map,Ko=new Map,kl=200,Sa=2e3;function ff(e){const t=Ko.get(e);return t?Date.now()<t?!0:(Ko.delete(e),!1):!1}function hf(e,t=kl){const r=Date.now()+t;Ko.set(e,r)}function gf(e,t=Sa){const r=jl.get(e);if(!r)return!1;const o=Date.now()-r;return o<t?(J.getLogger().debug(`[Deduplication] Duplicate request blocked: ${e} (${o}ms ago)`),!0):!1}function xf(e){jl.set(e,Date.now())}function yf(e){return Yo.get(e)||null}function vf(e,t){Yo.set(e,t);const r=()=>{Yo.delete(e),xf(e)};return t.then(r,r),t}async function bf(e,t,r={}){const{windowMs:s=Sa,throwOnDuplicate:o=!0}=r,a=yf(e);if(a)return J.getLogger().debug(`[Deduplication] Reusing in-flight request: ${e}`),a;if(gf(e,s)){if(o)throw new Error(`Duplicate request blocked: ${e}`);return J.getLogger().warn(`[Deduplication] Duplicate request blocked but not throwing: ${e}`),Promise.reject(new Error("Duplicate request"))}const i=t();return vf(e,i)}function Mn(e,t,r={}){const{cooldownMs:s=kl,deduplicationWindowMs:o=Sa}=r;return async()=>{if(ff(e)){J.getLogger().debug(`[Deduplication] Button in cooldown: ${e}`);return}hf(e,s);try{await bf(e,async()=>{const a=t();a instanceof Promise&&await a},{windowMs:o,throwOnDuplicate:!1})}catch(a){if(a instanceof Error&&a.message.includes("Duplicate request"))return;throw a}}}function Ca(e){return{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:e,opacity:.6,padding:"0.25rem",lineHeight:1}}const gn={PAYMENT_START:"cedros:payment:start",WALLET_CONNECT:"cedros:wallet:connect",WALLET_CONNECTED:"cedros:wallet:connected",WALLET_ERROR:"cedros:wallet:error",PAYMENT_PROCESSING:"cedros:payment:processing",PAYMENT_SUCCESS:"cedros:payment:success",PAYMENT_ERROR:"cedros:payment:error"};function Dn(e,t){if(typeof window>"u")return;const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!1});window.dispatchEvent(r)}function Ln(e,t,r){Dn(gn.PAYMENT_START,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function Xo(e){Dn(gn.WALLET_CONNECT,{timestamp:Date.now(),wallet:e})}function Sl(e,t){Dn(gn.WALLET_CONNECTED,{timestamp:Date.now(),wallet:e,publicKey:t})}function is(e,t){Dn(gn.WALLET_ERROR,{timestamp:Date.now(),wallet:t,error:e})}function un(e,t,r){Dn(gn.PAYMENT_PROCESSING,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function $n(e,t,r,s){Dn(gn.PAYMENT_SUCCESS,{timestamp:Date.now(),method:e,transactionId:t,resource:r,itemCount:s})}function kt(e,t,r,s){Dn(gn.PAYMENT_ERROR,{timestamp:Date.now(),method:e,error:t,resource:r,itemCount:s})}class ln extends Error{code;retryable;details;httpStatus;constructor(t,r,s=!1,o,a){super(r),this.name="PaymentError",this.code=t,this.retryable=s,this.details=o,this.httpStatus=a,Object.setPrototypeOf(this,ln.prototype)}canRetry(){return this.retryable}is(t){return this.code===t}isInCategory(t){return t.includes(this.code)}getUserMessage(){const t=this.getErrorInfo();return t.action?`${t.message} ${t.action}`:t.message}getShortMessage(){return this.getErrorInfo().message}getAction(){return this.getErrorInfo().action}getErrorInfo(){return fs(this.code)}static fromErrorResponse(t,r){const s=t.error.retryable??Cl.RETRYABLE.includes(t.error.code);return new ln(t.error.code,t.error.message,s,t.error.details,r)}static fromUnknown(t){return t instanceof ln?t:t instanceof Error?new ln("internal_error",t.message,!1):new ln("internal_error",String(t),!1)}}const Cl={INSUFFICIENT_FUNDS:["insufficient_funds_sol","insufficient_funds_token"],TRANSACTION_PENDING:["transaction_not_confirmed","transaction_not_found"],VALIDATION:["missing_field","invalid_field","invalid_amount","invalid_wallet","invalid_resource","invalid_cart_item","empty_cart"],COUPON:["invalid_coupon","coupon_not_found","coupon_expired","coupon_usage_limit_reached","coupon_not_applicable","coupon_wrong_payment_method"],RETRYABLE:["transaction_not_confirmed","rpc_error","network_error","stripe_error"],NOT_FOUND:["resource_not_found","cart_not_found","refund_not_found","product_not_found","coupon_not_found","session_not_found","credits_hold_not_found"],CREDITS:["insufficient_credits","credits_hold_expired","credits_hold_not_found"],SECURITY:["invalid_redirect_url","rate_limit_exceeded","nonce_already_used"]};function wf(e){return e instanceof ln&&e.canRetry()}function _f(e){return e instanceof ln?e.getUserMessage():e instanceof Error?e.message:String(e)}function jf(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 kf(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=jf(t);if(m.push(u),r){const h=kf(r);m.includes(h)||m.push(h)}s.forEach(h=>{m.includes(h)||m.push(h)}),m.push(...i);const p=["'self'"];return l&&p.push("https://js.stripe.com","https://checkout.stripe.com"),p.push(...c),{scriptSrc:d,connectSrc:m,frameSrc:p}}function Pl(e,t="header"){const{scriptSrc:r,connectSrc:s,frameSrc:o}=e;switch(t){case"header":case"meta":case"nextjs":case"nginx":{const a=[];return r.length>0&&a.push(`script-src ${r.join(" ")}`),s.length>0&&a.push(`connect-src ${s.join(" ")}`),o.length>0&&a.push(`frame-src ${o.join(" ")}`),a.join("; ")}case"helmet":{const a={};return r.length>0&&(a.scriptSrc=r),s.length>0&&(a.connectSrc=s),o.length>0&&(a.frameSrc=o),a}case"directives":return{scriptSrc:r,connectSrc:s,frameSrc:o};default:throw new Error(`Unknown CSP format: ${t}`)}}function Sf(e={},t="header"){const r=Nl(e);return Pl(r,t)}const Cf={HELIUS:"https://*.helius-rpc.com",QUICKNODE:"https://*.quicknode.pro",ALCHEMY:"https://*.alchemy.com",ANKR:"https://rpc.ankr.com",TRITON:"https://*.rpcpool.com"},Nf={MAINNET_CUSTOM_RPC:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),MAINNET_NEXTJS:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),DEVNET:()=>({solanaCluster:"devnet",allowUnsafeScripts:!1}),CRYPTO_ONLY:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,includeStripe:!1}),STRIPE_ONLY:()=>({solanaCluster:"mainnet-beta",includeStripe:!0,customRpcProviders:[]})};function kr(e){return new Date(e).toLocaleString()}function Rs(){const{stripeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,transactionId:null}),s=y.useRef(!1),o=y.useCallback(async(c,l,d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const h={resource:c,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p};try{const _=await e.processPayment(h);return r({status:_.success?"success":"error",error:_.success?null:_.error||"Payment failed",transactionId:_.success&&_.transactionId||null}),_}catch(_){const g=_ instanceof Error?_.message:"Payment failed";return r({status:"error",error:g,transactionId:null}),{success:!1,error:g}}finally{s.current=!1}},[e]),a=y.useCallback(async(c,l,d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const h=ps(c);try{const _=await e.processCartCheckout({items:h,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p});return r({status:_.success?"success":"error",error:_.success?null:_.error||"Cart checkout failed",transactionId:_.success&&_.transactionId||null}),_}catch(_){const g=_ instanceof Error?_.message:"Cart checkout failed";return r({status:"error",error:g,transactionId:null}),{success:!1,error:g}}finally{s.current=!1}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,transactionId:null}),s.current=!1},[]);return{...t,processPayment:o,processCartCheckout:a,reset:i}}function nr(e,t){return y.useMemo(()=>{const r=mf(t),s=e||(t?.length===1?t[0].resource:"");return{isCartMode:r,effectiveResource:s}},[e,t])}const Pf=(e,t,r)=>{const s=e[t];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((o,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},vo=new Map;let Wr=null;async function Gi(e){if(vo.has(e))return vo.get(e);try{const t=await Pf(Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),`./translations/${e}.json`,3),r=t.default||t;return vo.set(e,r),r}catch{return null}}async function Af(){if(Wr)return Wr;const e=Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),t=[];for(const r in e){const s=r.match(/\.\/translations\/([a-z]{2,3}(?:-[A-Z]{2})?)\.json$/);s&&t.push(s[1])}return Wr=t.length>0?t:["en"],Wr}function Al(){return typeof navigator>"u"?"en":(navigator.language||navigator.userLanguage||"en").split("-")[0].toLowerCase()}async function El(e){let t=await Gi(e);if(t||(t=await Gi("en"),t))return t;throw new Error("Critical: No translation files found, not even en.json")}function Tl(e){return(t,r)=>{const s=t.split(".");let o=e;for(const a of s)if(o&&typeof o=="object"&&a in o)o=o[a];else return t;return typeof o!="string"?t:r?Object.entries(r).reduce((a,[i,c])=>a.replace(new RegExp(`\\{${i}\\}`,"g"),c),o):o}}function Ef(e,t,r=!0){const s=t.errors[e];if(!s){const o=fs(e);return r&&o.action?`${o.message} ${o.action}`:o.message}return r&&s.action?`${s.message} ${s.action}`:s.message}function xn(e){const[t,r]=y.useState(null),[s,o]=y.useState(!0),a=y.useMemo(()=>e||Al(),[e]);return y.useEffect(()=>{let c=!1;return(async()=>{o(!0);try{const d=await El(a);c||(r(d),o(!1))}catch(d){console.error("[CedrosPay] Failed to load translations:",d),c||o(!1)}})(),()=>{c=!0}},[a]),{t:y.useMemo(()=>t?Tl(t):c=>({"ui.purchase":"Purchase","ui.pay_with_card":"Pay with Card","ui.pay_with_crypto":"Pay with USDC","ui.pay_with_usdc":"Pay with USDC","ui.card":"Card","ui.usdc_solana":"USDC (Solana)","ui.crypto":"Crypto","ui.processing":"Processing...","ui.loading":"Loading...","ui.connect_wallet":"Connect Wallet","ui.connecting":"Connecting..."})[c]||c,[t]),locale:a,isLoading:s,translations:t}}function Tf(e,t=!0){const{translations:r}=xn();if(!r){const o=fs(e);return t&&o.action?`${o.message} ${o.action}`:o.message}const s=r.errors[e];if(!s){const o=fs(e);return t&&o.action?`${o.message} ${o.action}`:o.message}return t&&s.action?`${s.message} ${s.action}`:s.message}function Na({resource:e,items:t,successUrl:r,cancelUrl:s,metadata:o,customerEmail:a,couponCode:i,label:c,disabled:l=!1,onAttempt:d,onSuccess:m,onError:u,className:p=""}){const{status:h,error:_,transactionId:g,processPayment:f,processCartCheckout:w}=Rs(),j=J.useCedrosTheme(),{isCartMode:b,effectiveResource:v}=nr(e,t),{t:k,translations:R}=xn(),N=c||k("ui.pay_with_card"),C=j.unstyled?p:`${j.className} cedros-theme__stripe-button ${p}`.trim(),T=_&&typeof _!="string"?_?.code??null:null,$=_?typeof _=="string"?_:(E=>{if(!E||!R)return"";const P=R.errors[E];return P?P.action?`${P.message} ${P.action}`:P.message:""})(T):null,S=y.useCallback(async()=>{J.getLogger().debug("[StripeButton] executePayment with couponCode:",i);const E=b&&t?dn(t):void 0;if(Ln("stripe",v,E),d&&d("stripe"),!b&&!v){const z="Invalid payment configuration: missing resource or items";J.getLogger().error("[StripeButton]",z),kt("stripe",z,v,E),u&&u(z);return}let P;un("stripe",v,E),b&&t?(J.getLogger().debug("[StripeButton] Processing cart checkout with coupon:",i),P=await w(t,r,s,o,a,i)):v&&(J.getLogger().debug("[StripeButton] Processing single payment with coupon:",i),P=await f(v,r,s,o,a,i)),P&&P.success&&P.transactionId?($n("stripe",P.transactionId,v,E),m&&m(P.transactionId)):P&&!P.success&&P.error&&(kt("stripe",P.error,v,E),u&&u(P.error))},[i,b,v,t,r,s,o,a,w,f,d,m,u]),A=y.useMemo(()=>b&&t?`stripe-cart-${t.map(E=>E.resource).join("-")}`:`stripe-${v||"unknown"}`,[b,t,v]),I=y.useMemo(()=>Mn(A,S),[A,S]),B=h==="loading",D=l||B;return n.jsxs("div",{className:C,style:j.unstyled?{}:j.style,children:[n.jsx("button",{onClick:I,disabled:D,className:j.unstyled?p:"cedros-theme__button cedros-theme__stripe",type:"button",children:B?k("ui.processing"):N}),$&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__error",children:$}),g&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__success",children:k("ui.payment_successful")})]})}function Il(){const{creditsManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s=y.useRef(!1),o=y.useCallback(async(d,m)=>{r(u=>({...u,status:"loading",error:null}));try{const u=await e.requestQuote(d,m);return r(p=>({...p,status:"idle",requirement:u})),u}catch(u){const p=u instanceof Error?u.message:"Failed to fetch credits quote";return r(h=>({...h,status:"error",error:p})),null}},[e]),a=y.useCallback(async(d,m)=>{r(u=>({...u,status:"loading",error:null}));try{const u=ps(d),p=await e.requestCartQuote(u,m);return r(h=>({...h,status:"idle"})),p}catch(u){const p=u instanceof Error?u.message:"Failed to fetch cart credits quote";return r(h=>({...h,status:"error",error:p})),null}},[e]),i=y.useCallback(async(d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=await e.processPayment(d,m,u,p);return r({status:h.success?"success":"error",error:h.success?null:h.error||"Credits payment failed",transactionId:h.success&&h.transactionId||null,requirement:null,holdId:null}),h}finally{s.current=!1}},[e]),c=y.useCallback(async(d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=ps(d),_=await e.requestCartQuote(h,u);if(!_)return r({status:"error",error:"Credits payment not available for this cart",transactionId:null,requirement:null,holdId:null}),{success:!1,error:"Credits payment not available"};const f=(await e.createCartHold({cartId:_.cartId,authToken:m})).holdId;r(j=>({...j,holdId:f}));const w=await e.authorizeCartPayment({cartId:_.cartId,holdId:f,authToken:m,metadata:p});return r({status:w.success?"success":"error",error:w.success?null:w.error||"Cart credits payment failed",transactionId:w.success&&w.transactionId||null,requirement:null,holdId:null}),{success:w.success,transactionId:w.transactionId,error:w.error}}catch(h){const _=h instanceof Error?h.message:"Cart credits payment failed";return r({status:"error",error:_,transactionId:null,requirement:null,holdId:null}),{success:!1,error:_}}finally{s.current=!1}},[e]),l=y.useCallback(()=>{r({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s.current=!1},[]);return{...t,fetchQuote:o,fetchCartQuote:a,processPayment:i,processCartPayment:c,reset:l}}function Pa({resource:e,items:t,authToken:r,metadata:s,couponCode:o,label:a,disabled:i=!1,onAttempt:c,onSuccess:l,onError:d,className:m=""}){const{status:u,error:p,transactionId:h,processPayment:_,processCartPayment:g}=Il(),f=J.useCedrosTheme(),{isCartMode:w,effectiveResource:j}=nr(e,t),{t:b,translations:v}=xn(),k=a||b("ui.pay_with_credits")||"Pay with Credits",R=f.unstyled?m:`${f.className} cedros-theme__credits-button ${m}`.trim(),N=p&&typeof p!="string"?p?.code??null:null,T=p?typeof p=="string"?p:(B=>{if(!B||!v)return"";const D=v.errors[B];return D?D.action?`${D.message} ${D.action}`:D.message:""})(N):null,O=y.useCallback(async()=>{J.getLogger().debug("[CreditsButton] executePayment");const B=w&&t?dn(t):void 0;if(Ln("credits",j,B),c&&c("credits"),!r){const E="Authentication required: please log in to pay with credits";J.getLogger().error("[CreditsButton]",E),kt("credits",E,j,B),d&&d(E);return}if(!w&&!j){const E="Invalid payment configuration: missing resource";J.getLogger().error("[CreditsButton]",E),kt("credits",E,j,B),d&&d(E);return}let D;un("credits",j,B),w&&t?(J.getLogger().debug("[CreditsButton] Processing cart checkout"),D=await g(t,r,o,s)):j&&(J.getLogger().debug("[CreditsButton] Processing single payment"),D=await _(j,r,o,s)),D&&D.success&&D.transactionId?($n("credits",D.transactionId,j,B),l&&l(D.transactionId)):D&&!D.success&&D.error&&(kt("credits",D.error,j,B),d&&d(D.error))},[r,w,j,t,o,s,_,g,c,l,d]),$=y.useMemo(()=>w&&t?`credits-cart-${t.map(B=>B.resource).join("-")}`:`credits-${j||"unknown"}`,[w,t,j]),S=y.useMemo(()=>Mn($,O),[$,O]),A=u==="loading",I=i||A;return n.jsxs("div",{className:R,style:f.unstyled?{}:f.style,children:[n.jsx("button",{onClick:S,disabled:I,className:f.unstyled?m:"cedros-theme__button cedros-theme__credits",type:"button",children:A?b("ui.processing"):k}),T&&n.jsx("div",{className:f.unstyled?"":"cedros-theme__error",children:T}),h&&n.jsx("div",{className:f.unstyled?"":"cedros-theme__success",children:b("ui.payment_successful")})]})}function Rl(){const{x402Manager:e,walletManager:t}=J.useCedrosContext(),{publicKey:r,signTransaction:s}=ja.useWallet(),[o,a]=y.useState({status:"idle",error:null,transactionId:null}),[i,c]=y.useState(null),[l,d]=y.useState(null),m=y.useRef(!1),u=y.useCallback(()=>{if(!r){const w="Wallet not connected";return a({status:"error",error:w,transactionId:null}),{valid:!1,error:w}}if(!s){const w="Wallet does not support signing";return a({status:"error",error:w,transactionId:null}),{valid:!1,error:w}}return{valid:!0}},[r,s]),p=y.useCallback(async w=>{try{a(b=>({...b,status:"loading"}));const j=await e.requestQuote({resource:w});if(!e.validateRequirement(j))throw new Error("Invalid requirement received from server");return c(j),a(b=>({...b,status:"idle"})),j}catch(j){const b=J.formatError(j,"Failed to fetch requirement");throw a({status:"error",error:b,transactionId:null}),j}},[e]),h=y.useCallback(async(w,j,b,v,k="regular")=>{if(!!w.extra?.feePayer){console.log("⚡ [useX402Payment] GASLESS FLOW - Backend pays fees"),console.log("🔨 [useX402Payment] Requesting backend to build gasless transaction");const{transaction:N,blockhash:C}=await e.buildGaslessTransaction({resourceId:j,userWallet:r.toString(),feePayer:w.extra.feePayer,couponCode:b});console.log("📦 [useX402Payment] Deserializing transaction from backend");const T=t.deserializeTransaction(N);console.log("✍️ [useX402Payment] Requesting wallet to partially sign (transfer authority only)");const O=await t.partiallySignTransaction({transaction:T,signTransaction:s,blockhash:C});console.log("📤 [useX402Payment] Submitting partially-signed transaction to backend");const $=await e.submitGaslessTransaction({resource:j,partialTx:O,couponCode:b,metadata:v,resourceType:k,requirement:w});return $.success&&$.settlement&&d($.settlement),$}else{const N=await t.buildTransaction({requirement:w,payerPublicKey:r}),C=await t.signTransaction({transaction:N,signTransaction:s}),T=t.buildPaymentPayload({requirement:w,signedTx:C,payerPublicKey:r}),O=await e.submitPayment({resource:j,payload:T,couponCode:b,metadata:v,resourceType:k});return O.success&&O.settlement&&d(O.settlement),O}},[r,s,e,t]),_=y.useCallback(async(w,j,b)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const v=u();if(!v.valid)return{success:!1,error:v.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{console.log("🔍 [useX402Payment] Fetching fresh quote for resource:",w);const k=await e.requestQuote({resource:w,couponCode:j});console.log("✅ [useX402Payment] Got quote:",{payTo:k.payTo,amount:k.maxAmountRequired}),c(k),console.log("⚙️ [useX402Payment] Executing payment flow with fresh requirement");const R=await h(k,w,j,b,"regular");return R.success?a({status:"success",error:null,transactionId:R.transactionId||"payment-success"}):a({status:"error",error:R.error||"Payment failed",transactionId:null}),R}catch(k){const R=J.formatError(k,"Payment failed");return a({status:"error",error:R,transactionId:null}),{success:!1,error:R}}finally{m.current=!1}},[u,e,h]),g=y.useCallback(async(w,j,b)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const v=u();if(!v.valid)return{success:!1,error:v.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{const k=ps(w),R=await e.requestCartQuote({items:k,metadata:j,couponCode:b}),N=R.cartId,C=R.quote;if(!e.validateRequirement(C))throw new Error("Invalid cart quote received from server");c(C);const T=await h(C,N,b,j,"cart");return T.success?a({status:"success",error:null,transactionId:T.transactionId||"cart-payment-success"}):a({status:"error",error:T.error||"Cart payment failed",transactionId:null}),T}catch(k){const R=J.formatError(k,"Cart payment failed");return a({status:"error",error:R,transactionId:null}),{success:!1,error:R}}finally{m.current=!1}},[u,e,h]),f=y.useCallback(()=>{a({status:"idle",error:null,transactionId:null}),c(null),d(null),m.current=!1},[]);return{...o,requirement:i,settlement:l,fetchQuote:p,processPayment:_,processCartPayment:g,reset:f}}function Aa({resource:e,items:t,label:r,disabled:s=!1,onAttempt:o,onSuccess:a,onError:i,className:c="",testPageUrl:l,hideMessages:d=!1,metadata:m,couponCode:u}){const{connected:p,connecting:h,connect:_,disconnect:g,select:f,wallets:w,wallet:j,publicKey:b}=ja.useWallet(),{status:v,error:k,transactionId:R,processPayment:N,processCartPayment:C}=Rl(),T=J.useCedrosTheme(),{solanaError:O}=J.useCedrosContext(),{isCartMode:$,effectiveResource:S}=nr(e,t),{t:A,translations:I}=xn(),B=r||A("ui.pay_with_crypto"),D=k&&typeof k!="string"?k?.code??null:null,E=O&&typeof O!="string"?O?.code??null:null,P=te=>{if(!te||!I)return"";const xe=I.errors[te];return xe?xe.action?`${xe.message} ${xe.action}`:xe.message:""},z=k?typeof k=="string"?k:P(D):null,Z=O?typeof O=="string"?O:P(E):null,K=y.useRef(N),L=y.useRef(C);y.useEffect(()=>{K.current=N,L.current=C},[N,C]);const W=y.useMemo(()=>w.map(te=>`${te.adapter.name}-${te.readyState}`).join(","),[w]),Y=y.useMemo(()=>w.filter(({readyState:te})=>te===Hi.WalletReadyState.Installed||te===Hi.WalletReadyState.Loadable),[W]);y.useEffect(()=>{if(v==="success"&&R){const te=$&&t?dn(t):void 0;$n("crypto",R,S,te),a&&a(R)}},[v,R,a,$,t,S]),y.useEffect(()=>{if(v==="error"&&k){const te=$&&t?dn(t):void 0;kt("crypto",k,S,te),i&&i(k)}},[v,k,i,$,t,S]);const V=typeof window<"u"&&window.top!==window.self,[ce,F]=y.useState(!1),[ee,pe]=y.useState(!1),[q,ne]=y.useState(null),le=O;y.useEffect(()=>{let te=!1;return te||(async()=>{if(ee&&j&&!p&&!h){J.getLogger().debug("[CryptoButton] Wallet detected, attempting auto-connect:",j.adapter.name),pe(!1),Xo(j.adapter.name);try{await _(),te||J.getLogger().debug("[CryptoButton] Auto-connect successful")}catch(ge){if(!te){J.getLogger().error("[CryptoButton] Auto-connect failed:",ge);const dt=ge instanceof Error?ge.message:"Failed to connect wallet";is(dt,j.adapter.name),ne(null)}}}})(),()=>{te=!0}},[j,ee,p,h,_]),y.useEffect(()=>{if(J.getLogger().debug("[CryptoButton] Payment useEffect triggered",{connected:p,hasPendingPayment:!!q,hasPublicKey:!!b,pendingPaymentType:q?.type}),p&&q&&b&&j){Sl(j.adapter.name,b.toString()),J.getLogger().debug("[CryptoButton] All conditions met! Processing pending payment:",q);const te=q;ne(null),F(!1);const xe=te.type==="cart"&&te.items?dn(te.items):void 0;un("crypto",te.resource,xe),te.type==="cart"&&te.items?(J.getLogger().debug("[CryptoButton] Auto-processing cart payment"),L.current(te.items,te.metadata,te.couponCode)):te.type==="single"&&te.resource&&(J.getLogger().debug("[CryptoButton] Auto-processing single payment"),K.current(te.resource,te.couponCode,te.metadata))}},[p,q,b,j]);const fe=y.useCallback(async()=>{J.getLogger().debug("[CryptoButton] executePaymentFlow called",{connected:p,wallet:j?.adapter.name,couponCode:u,isCartMode:$,hasItems:!!t,effectiveResource:S});const te=$&&t?dn(t):void 0;if(Ln("crypto",S,te),o&&o("crypto"),le){J.getLogger().error("[CryptoButton] Solana dependencies missing:",le),kt("crypto",le,S,te),i&&i(le);return}if(V){const xe=l||window.location.href;try{if(new URL(xe,window.location.origin).origin!==window.location.origin)throw J.getLogger().error("[CryptoButton] Blocked attempt to open external URL:",xe),new Error("Cannot open external URLs from embedded context");window.open(xe,"_blank","noopener,noreferrer")}catch(ge){throw J.getLogger().error("[CryptoButton] URL validation failed:",ge),ge}return}if(p)un("crypto",S,te),$&&t?(J.getLogger().debug("[CryptoButton] Processing cart payment with coupon:",u),await C(t,m,u)):S&&(J.getLogger().debug("[CryptoButton] Processing single payment with coupon:",u),await N(S,u,m));else{let xe=!1;if($&&t?(J.getLogger().debug("[CryptoButton] Setting pending cart payment with coupon:",u),ne({type:"cart",items:t,metadata:m,couponCode:u}),xe=!0):S&&(J.getLogger().debug("[CryptoButton] Setting pending single payment with coupon:",u),ne({type:"single",resource:S,metadata:m,couponCode:u}),xe=!0),!xe){J.getLogger().error("[CryptoButton] No valid payment to process");return}try{if(j)J.getLogger().debug("[CryptoButton] Wallet already selected, connecting:",j.adapter.name),Xo(j.adapter.name),await _();else{if(J.getLogger().debug("[CryptoButton] No wallet selected, showing selector. Available wallets:",Y.map(ge=>ge.adapter.name)),Y.length===0){ne(null);const ge="No wallets available";throw is(ge),new Error(ge)}F(!0)}}catch(ge){ne(null);const dt=ge instanceof Error?ge.message:"Failed to connect wallet";J.getLogger().error("[CryptoButton] Connection error:",dt),is(dt,j?.adapter.name)}}},[p,j,u,$,t,S,V,l,Y,_,m,C,N,le,o,i]),Pe=y.useMemo(()=>$&&t?`crypto-cart-${t.map(te=>te.resource).join("-")}`:`crypto-${S||"unknown"}`,[$,t,S]),Ve=y.useMemo(()=>Mn(Pe,fe,{cooldownMs:200,deduplicationWindowMs:0}),[Pe,fe]),qe=v==="loading",He=s||qe||h||!!le,gt=qe?A("ui.processing"):B,Ge=y.useCallback(async()=>{try{pe(!1),p&&await g(),f(null),F(!0)}catch(te){J.getLogger().error("Failed to change wallet:",te)}},[p,g,f]),zt=y.useCallback(te=>{J.getLogger().debug("[CryptoButton] Wallet clicked:",te),F(!1),f(te),pe(!0),J.getLogger().debug("[CryptoButton] Wallet selected, useEffect will auto-connect")},[f]),lt=y.useCallback(async()=>{try{if(await g(),ne(null),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(te){te instanceof Error&&te.name==="QuotaExceededError"?J.getLogger().warn("localStorage quota exceeded when removing wallet preference"):J.getLogger().error("Failed to clear wallet preference from localStorage:",te)}}catch(te){J.getLogger().error("Failed to disconnect wallet:",te)}},[g]);return n.jsxs("div",{className:T.unstyled?c:`${T.className} cedros-theme__crypto-button ${c||""}`,style:T.unstyled?{}:T.style,children:[n.jsx("button",{onClick:Ve,disabled:He,className:T.unstyled?c:"cedros-theme__button cedros-theme__crypto",type:"button",children:gt}),ce&&!d&&n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:T.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>F(!1),children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:T.tokens.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${T.tokens.modalBorder}`},onClick:te=>te.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:T.tokens.surfaceText},children:A("wallet.select_wallet")}),n.jsx("button",{onClick:()=>F(!1),style:Ca(T.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:Y.map(te=>n.jsxs("button",{onClick:()=>zt(te.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:T.tokens.surfaceBackground,border:`1px solid ${T.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:T.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:xe=>{xe.currentTarget.style.backgroundColor=T.tokens.modalBackground,xe.currentTarget.style.borderColor=T.tokens.surfaceText,xe.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:xe=>{xe.currentTarget.style.backgroundColor=T.tokens.surfaceBackground,xe.currentTarget.style.borderColor=T.tokens.surfaceBorder,xe.currentTarget.style.transform="translateY(0)"},type:"button",children:[n.jsx(of.WalletIcon,{wallet:te,style:{width:"24px",height:"24px"}}),n.jsx("span",{style:{fontWeight:500},children:te.adapter.name})]},te.adapter.name))})]})}),p&&!d&&!ce&&n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:T.tokens.surfaceText,opacity:.7},children:[n.jsx("button",{onClick:Ge,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:"Change Wallet"}),n.jsx("button",{onClick:lt,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:A("ui.disconnect")})]}),!d&&Z&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__error",children:Z}),!d&&z&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__error",children:z}),!d&&R&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__success",children:A("ui.payment_successful")})]})}const If=Object.freeze(Object.defineProperty({__proto__:null,CryptoButton:Aa},Symbol.toStringTag,{value:"Module"})),Ol=({isOpen:e,onClose:t,resource:r,items:s,cardLabel:o="Card",cryptoLabel:a="USDC (Solana)",creditsLabel:i="Pay with Credits",showCard:c=!0,showCrypto:l=!0,showCredits:d=!1,onPaymentAttempt:m,onPaymentSuccess:u,onPaymentError:p,onStripeSuccess:h,onCryptoSuccess:_,onCreditsSuccess:g,onStripeError:f,onCryptoError:w,onCreditsError:j,customerEmail:b,successUrl:v,cancelUrl:k,metadata:R,couponCode:N,authToken:C,testPageUrl:T,hideMessages:O=!1})=>{const{tokens:$}=J.useCedrosTheme();return y.useEffect(()=>{const S=A=>{A.key==="Escape"&&e&&t()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[e,t]),y.useEffect(()=>{if(e){const S=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${S}px`,document.body.style.width="100%",document.body.style.overflowY="scroll",()=>{const A=document.body.style.top?Math.abs(parseInt(document.body.style.top.replace("px",""),10)):0;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflowY="",window.scrollTo(0,A)}}},[e]),e?n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:$.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:t,children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:$.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${$.modalBorder}`},onClick:S=>S.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:$.surfaceText},children:"Choose Payment Method"}),n.jsx("button",{onClick:t,style:Ca($.surfaceText),"aria-label":"Close modal",children:"×"})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[c&&n.jsx(Na,{resource:r,items:s,label:o,onAttempt:m,onSuccess:h||u,onError:f||p,customerEmail:b,successUrl:v,cancelUrl:k,metadata:R,couponCode:N}),l&&n.jsx(Aa,{resource:r,items:s,label:a,onAttempt:m,onSuccess:_||u,onError:w||p,testPageUrl:T,hideMessages:O,metadata:R,couponCode:N}),d&&n.jsx(Pa,{resource:r,items:s,label:i,authToken:C,onAttempt:m?()=>m("credits"):void 0,onSuccess:g||u,onError:j||p,metadata:R,couponCode:N})]})]})}):null},Ml=({resource:e,items:t,label:r,cardLabel:s,cryptoLabel:o,creditsLabel:a,showCard:i=!0,showCrypto:c=!0,showCredits:l=!1,onPaymentAttempt:d,onPaymentSuccess:m,onPaymentError:u,onStripeSuccess:p,onCryptoSuccess:h,onCreditsSuccess:_,onStripeError:g,onCryptoError:f,onCreditsError:w,customerEmail:j,successUrl:b,cancelUrl:v,metadata:k,couponCode:R,authToken:N,autoDetectWallets:C=!0,testPageUrl:T,hideMessages:O=!1,renderModal:$})=>{const S=J.useCedrosTheme(),[A,I]=y.useState(!1),{status:B,processPayment:D,processCartCheckout:E}=Rs(),{isCartMode:P,effectiveResource:z}=nr(e,t),{t:Z}=xn(),K=r||Z("ui.purchase"),L=s||Z("ui.card"),W=o||Z("ui.usdc_solana"),Y=a||Z("ui.pay_with_credits")||"Pay with Credits",V=y.useCallback(async()=>{if(C&&i){const{detectSolanaWallets:q}=await Promise.resolve().then(()=>$C);if(!q()){const ne=P?void 0:z,le=P&&t?dn(t):void 0;Ln("stripe",ne,le),d&&d("stripe"),un("stripe",ne,le);let fe;P&&t?fe=await E(t,b,v,k,j,R):z&&(fe=await D(z,b,v,k,j,R)),fe&&fe.success&&fe.transactionId?($n("stripe",fe.transactionId,ne,le),p?p(fe.transactionId):m&&m(fe.transactionId)):fe&&!fe.success&&fe.error&&(kt("stripe",fe.error,ne,le),g?g(fe.error):u&&u(fe.error));return}}I(!0)},[C,i,P,t,z,E,D,b,v,k,j,R,m,u,p,g,d]),ce=y.useMemo(()=>P&&t?`purchase-cart-${t.map(q=>q.resource).join("-")}`:`purchase-${z||"unknown"}`,[P,t,z]),F=y.useMemo(()=>Mn(ce,V),[ce,V]),ee=B==="loading",pe={isOpen:A,onClose:()=>I(!1),resource:P?void 0:z,items:P?t:void 0,cardLabel:L,cryptoLabel:W,creditsLabel:Y,showCard:i,showCrypto:c,showCredits:l,onPaymentAttempt:d,onPaymentSuccess:q=>{I(!1),m?.(q)},onPaymentError:q=>{I(!1),u?.(q)},onStripeSuccess:q=>{I(!1),p?.(q)},onCryptoSuccess:q=>{I(!1),h?.(q)},onCreditsSuccess:q=>{I(!1),_?.(q)},onStripeError:q=>{I(!1),g?.(q)},onCryptoError:q=>{I(!1),f?.(q)},onCreditsError:q=>{I(!1),w?.(q)},customerEmail:j,successUrl:b,cancelUrl:v,metadata:k,couponCode:R,authToken:N,testPageUrl:T,hideMessages:O};return n.jsxs("div",{className:S.unstyled?"":S.className,style:S.unstyled?{}:S.style,children:[n.jsx("button",{onClick:F,disabled:ee,className:S.unstyled?"":"cedros-theme__button cedros-theme__stripe",style:{width:"100%",cursor:ee?"not-allowed":"pointer",opacity:ee?.6:1},type:"button",children:ee?Z("ui.processing"):K}),$?$(pe):n.jsx(Ol,{...pe})]})},Rf={"mainnet-beta":"https://api.mainnet-beta.solana.com",devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com"};function Of(){const[e,t]=y.useState(null);return y.useEffect(()=>{let r=!1;return import("@solana/wallet-adapter-react").then(s=>{r||t(s)}),()=>{r=!0}},[]),e}function Mf({endpoint:e,wallets:t,children:r}){const s=Of();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 Df=y.lazy(()=>Promise.resolve().then(()=>If).then(e=>({default:e.CryptoButton})));function Lf(e){const{resource:t,items:r,checkout:s={},display:o={},callbacks:a={},advanced:i={}}=e,{config:c,walletPool:l}=J.useCedrosContext(),d=J.useCedrosTheme(),{isCartMode:m}=nr(t,r),u=o.showCrypto??!0,p=y.useMemo(()=>({marginTop:"0.5rem",fontSize:"0.875rem",color:d.tokens.surfaceText,opacity:.7,textAlign:"center"}),[d.tokens.surfaceText]),h=y.useMemo(()=>u?i.wallets&&i.wallets.length>0?i.wallets:l.getAdapters():[],[i.wallets,l,u]),_=y.useMemo(()=>r?dn(r):0,[r]),g=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"stripe"}):void 0,[a.onPaymentSuccess]),f=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"crypto"}):void 0,[a.onPaymentSuccess]),w=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"stripe"}):void 0,[a.onPaymentError]),j=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"crypto"}):void 0,[a.onPaymentError]),b=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"credits"}):void 0,[a.onPaymentSuccess]),v=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"credits"}):void 0,[a.onPaymentError]),k=y.useMemo(()=>a.onPaymentAttempt?()=>a.onPaymentAttempt("credits"):void 0,[a.onPaymentAttempt]),R=u?c.solanaEndpoint??Rf[c.solanaCluster]:"";if(!t&&(!r||r.length===0))return J.getLogger().error('CedrosPay: Must provide either "resource" or "items" prop'),n.jsx("div",{className:o.className,style:{color:d.tokens.errorText},children:"Configuration error: No resource or items provided"});const N=o.showCard??!0,C=o.showCredits??!1,T=o.showPurchaseButton??!1,O=o.layout??"vertical",$=o.hideMessages??!1,S=i.autoDetectWallets??!0,A=n.jsx("div",{className:d.unstyled?o.className:`cedros-theme__pay ${o.className||""}`,children:n.jsxs("div",{className:d.unstyled?"":`cedros-theme__pay-content cedros-theme__pay-content--${O}`,children:[T?n.jsx(Ml,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,label:o.purchaseLabel,cardLabel:o.cardLabel,cryptoLabel:o.cryptoLabel,showCard:N,showCrypto:u,onPaymentAttempt:a.onPaymentAttempt,onPaymentSuccess:g,onPaymentError:w,onStripeSuccess:g,onCryptoSuccess:f,onStripeError:w,onCryptoError:j,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,autoDetectWallets:S,testPageUrl:i.testPageUrl,hideMessages:$,renderModal:o.renderModal}):n.jsxs(n.Fragment,{children:[N&&n.jsx(Na,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,label:o.cardLabel,onAttempt:a.onPaymentAttempt,onSuccess:g,onError:w}),u&&n.jsx(y.Suspense,{fallback:null,children:n.jsx(Df,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,metadata:s.metadata,couponCode:s.couponCode,label:o.cryptoLabel,onAttempt:a.onPaymentAttempt,onSuccess:f,onError:j,testPageUrl:i.testPageUrl,hideMessages:$})}),C&&n.jsx(Pa,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,authToken:s.authToken,metadata:s.metadata,couponCode:s.couponCode,label:o.creditsLabel,onAttempt:k,onSuccess:b,onError:v})]}),m&&r&&r.length>1&&!$&&n.jsxs("div",{style:p,children:["Checking out ",_," items"]})]})});return n.jsx("div",{className:d.unstyled?o.className:d.className,style:d.unstyled?{}:d.style,children:u?n.jsx(Mf,{endpoint:R,wallets:h,children:A}):A})}const Q={products:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),n.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),n.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),n.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),n.jsx("path",{d:"M3 3v5h5"}),n.jsx("path",{d:"M12 7v5l4 2"})]}),settings:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),n.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"}),n.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),n.jsx("path",{d:"M8 16H3v5"})]}),check:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})}),plus:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),n.jsx("path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9"}),n.jsx("path",{d:"M12 3v6"})]}),arrowUp:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7-7 7 7"}),n.jsx("path",{d:"M12 19V5"})]}),arrowDown:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7 7 7-7"}),n.jsx("path",{d:"M12 5v14"})]}),delete:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),n.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),faq:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),n.jsx("path",{d:"M12 17h.01"})]}),chat:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),n.jsx("path",{d:"M2 12h20"})]}),ai:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),n.jsx("path",{d:"M10 10v.5"}),n.jsx("path",{d:"M14 10v.5"}),n.jsx("path",{d:"M12 14v2"}),n.jsx("path",{d:"M8 18h8"}),n.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),n.jsx("path",{d:"M6 12v6"}),n.jsx("path",{d:"M18 12v6"})]}),notifications:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),n.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),n.jsx("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),n.jsx("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),n.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),n.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),n.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),n.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),n.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),n.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),n.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),n.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),n.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),n.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),n.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),n.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),n.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),n.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),n.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),n.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),n.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function Yt({message:e,onRetry:t}){return e?n.jsxs("div",{className:"cedros-admin__error-banner",children:[n.jsx("span",{children:e}),t&&n.jsxs("button",{type:"button",className:"cedros-admin__error-banner-retry",onClick:t,children:[Q.refresh," Retry"]})]}):null}function rr({stats:e,isLoading:t=!1,onRefresh:r}){return n.jsxs("div",{className:"cedros-admin__stats-bar",children:[n.jsx("div",{className:"cedros-admin__stats-bar-grid",children:e.map((s,o)=>n.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[n.jsx("span",{className:"cedros-admin__stats-bar-label",children:s.label}),n.jsx("span",{className:`cedros-admin__stats-bar-value ${s.variant?`cedros-admin__stats-bar-value--${s.variant}`:""}`,children:t?n.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):s.value}),s.description&&n.jsx("span",{className:"cedros-admin__stats-bar-desc",children:s.description})]},o))}),r&&n.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:r,disabled:t,title:"Refresh stats",children:t?Q.loading:Q.refresh})]})}function $f({serverUrl:e,productId:t,apiKey:r,authManager:s}){const[o,a]=y.useState(null),[i,c]=y.useState(!1),[l,d]=y.useState(!1),[m,u]=y.useState(null),p=y.useCallback(async()=>{if(t){c(!0),u(null);try{let g;if(s?.isAuthenticated())g=await s.fetchWithAuth(`/admin/products/${t}/variations`);else{const f={"Content-Type":"application/json"};r&&(f["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variations`,{headers:f});if(!w.ok)throw new Error(`Failed to fetch variations: ${w.status}`);g=await w.json()}g.variationConfig||(g.variationConfig={variationTypes:[]}),g.variants||(g.variants=[]),a(g)}catch(g){const f=g instanceof Error?g.message:"Failed to fetch variations";u(f),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,r,s]),h=y.useCallback(async g=>{if(!t)return null;d(!0),u(null);try{let f;if(s?.isAuthenticated())f=await s.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(g)});else{const w={"Content-Type":"application/json"};r&&(w["X-API-Key"]=r);const j=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:w,body:JSON.stringify(g)});if(!j.ok)throw new Error(`Failed to save variations: ${j.status}`);f=await j.json()}return a({productId:t,variationConfig:f.variationConfig,variants:f.variants}),{variantsCreated:f.variantsCreated}}catch(f){const w=f instanceof Error?f.message:"Failed to save variations";return u(w),null}finally{d(!1)}},[e,t,r,s]),_=y.useCallback(async g=>{if(!t||g.length===0)return!1;d(!0),u(null);try{if(s?.isAuthenticated())await s.fetchWithAuth(`/admin/products/${t}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:g})});else{const f={"Content-Type":"application/json"};r&&(f["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:f,body:JSON.stringify({updates:g})});if(!w.ok)throw new Error(`Failed to update inventory: ${w.status}`)}if(o){const f=new Map(g.map(w=>[w.variantId,w]));a({...o,variants:o.variants.map(w=>{const j=f.get(w.id);return j?{...w,inventoryQuantity:j.inventoryQuantity,inventoryStatus:j.inventoryStatus??w.inventoryStatus}:w})})}return!0}catch(f){const w=f instanceof Error?f.message:"Failed to update inventory";return u(w),!1}finally{d(!1)}},[e,t,r,s,o]);return{data:o,isLoading:i,error:m,fetch:p,save:h,bulkUpdateInventory:_,isSaving:l}}function Qi(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function zf({value:e,onChange:t,maxTypes:r=5,maxValuesPerType:s=20,disabled:o=!1}){const[a,i]=y.useState(null),[c,l]=y.useState(""),[d,m]=y.useState({}),u=e.variationTypes,p=y.useCallback(()=>{if(!c.trim()||u.length>=r)return;const b={id:Qi(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,b]}),l(""),i(b.id)},[c,u,r,t]),h=y.useCallback(b=>{t({variationTypes:u.filter(v=>v.id!==b).map((v,k)=>({...v,displayOrder:k}))}),a===b&&i(null)},[u,t,a]),_=y.useCallback((b,v)=>{t({variationTypes:u.map(k=>k.id===b?{...k,name:v}:k)})},[u,t]),g=y.useCallback((b,v)=>{const k=u.findIndex(C=>C.id===b);if(k===-1||v==="up"&&k===0||v==="down"&&k===u.length-1)return;const R=[...u],N=v==="up"?k-1:k+1;[R[k],R[N]]=[R[N],R[k]],t({variationTypes:R.map((C,T)=>({...C,displayOrder:T}))})},[u,t]),f=y.useCallback(b=>{const v=(d[b]||"").trim();if(!v)return;const k=u.find(N=>N.id===b);if(!k||k.values.length>=s)return;const R={id:Qi(),label:v};t({variationTypes:u.map(N=>N.id===b?{...N,values:[...N.values,R]}:N)}),m(N=>({...N,[b]:""}))},[u,d,s,t]),w=y.useCallback((b,v)=>{t({variationTypes:u.map(k=>k.id===b?{...k,values:k.values.filter(R=>R.id!==v)}:k)})},[u,t]),j=y.useCallback((b,v,k)=>{t({variationTypes:u.map(R=>R.id===b?{...R,values:R.values.map(N=>N.id===v?{...N,label:k}:N)}:R)})},[u,t]);return n.jsxs("div",{className:"cedros-admin__variation-editor",children:[n.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[u.length,"/",r," types"]})]}),u.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):n.jsx("div",{className:"cedros-admin__variation-type-list",children:u.map((b,v)=>n.jsxs("div",{className:"cedros-admin__variation-type-item",children:[n.jsxs("div",{className:"cedros-admin__variation-type-header",children:[n.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(b.id,"up"),disabled:o||v===0,title:"Move up",children:Q.arrowUp}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(b.id,"down"),disabled:o||v===u.length-1,title:"Move down",children:Q.arrowDown})]}),n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:b.name,onChange:k=>_(b.id,k.target.value),disabled:o,placeholder:"Type name"}),n.jsxs("span",{className:"cedros-admin__variation-value-count",children:[b.values.length," values"]}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===b.id?null:b.id),children:a===b.id?"Collapse":"Edit values"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>h(b.id),disabled:o,title:"Remove type",children:Q.delete})]}),a===b.id&&n.jsxs("div",{className:"cedros-admin__variation-values",children:[n.jsxs("div",{className:"cedros-admin__variation-values-header",children:[n.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',b.name,'"']}),n.jsxs("span",{style:{fontSize:11,opacity:.7},children:[b.values.length,"/",s]})]}),b.values.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):n.jsx("div",{className:"cedros-admin__variation-value-list",children:b.values.map(k=>n.jsxs("div",{className:"cedros-admin__variation-value-item",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:k.label,onChange:R=>j(b.id,k.id,R.target.value),disabled:o}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>w(b.id,k.id),disabled:o,title:"Remove value",children:Q.close})]},k.id))}),b.values.length<s&&n.jsxs("div",{className:"cedros-admin__variation-add-value",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:d[b.id]||"",onChange:k=>m(R=>({...R,[b.id]:k.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),f(b.id))}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>f(b.id),disabled:o||!d[b.id]?.trim(),children:"Add"})]})]})]},b.id))}),u.length<r&&n.jsxs("div",{className:"cedros-admin__variation-add-type",children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:b=>l(b.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),p())}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:p,disabled:o||!c.trim(),children:"Add Type"})]})]})}function Dl({value:e,onChange:t,options:r,placeholder:s="Filter",disabled:o}){const[a,i]=y.useState(!1),c=y.useRef(null),d=r.find(m=>m.value===e)?.label||s;return y.useEffect(()=>{const m=u=>{c.current&&!c.current.contains(u.target)&&i(!1)};if(a)return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[a]),y.useEffect(()=>{const m=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[a]),n.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[n.jsx("span",{children:d}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:Q.chevronDown})]}),a&&n.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:r.map(m=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${m.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{m.disabled||(t(m.value),i(!1))},role:"option","aria-selected":m.value===e,disabled:m.disabled,children:[m.label,m.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:Q.check})]},m.value))})]})}function ot({value:e,onChange:t,options:r,label:s,description:o,disabled:a,className:i,style:c}){const[l,d]=y.useState(!1),m=y.useRef(null),p=r.find(h=>h.value===e)?.label||"Select...";return y.useEffect(()=>{const h=_=>{m.current&&!m.current.contains(_.target)&&d(!1)};if(l)return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[l]),y.useEffect(()=>{const h=_=>{_.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[l]),n.jsxs("div",{className:`cedros-admin__field ${i||""}`,style:c,children:[n.jsx("label",{className:"cedros-admin__field-label",children:s}),n.jsxs("div",{className:"cedros-admin__dropdown cedros-admin__dropdown--form",ref:m,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger cedros-admin__dropdown-trigger--form",onClick:()=>!a&&d(!l),"aria-expanded":l,"aria-haspopup":"listbox",disabled:a,children:[n.jsx("span",{children:p}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${l?"cedros-admin__dropdown-chevron--open":""}`,children:Q.chevronDown})]}),l&&n.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:r.map(h=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${h.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{h.disabled||(t(h.value),d(!1))},role:"option","aria-selected":h.value===e,disabled:h.disabled,children:[h.label,h.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:Q.check})]},h.value))})]}),o&&n.jsx("p",{className:"cedros-admin__field-description",children:o})]})}function Yi(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ff(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 Bf(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 Uf({variationConfig:e,variants:t,onChange:r,defaultPrice:s=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=y.useMemo(()=>Ff(e.variationTypes),[e.variationTypes]),l=y.useMemo(()=>{const g=new Map;for(const f of t)g.set(Bf(f),f);return g},[t]),{existingRows:d,possibleRows:m}=y.useMemo(()=>{const g=[],f=[];for(const w of c){const j=l.get(w.key);j?g.push({combo:w,variant:j}):f.push(w)}return{existingRows:g,possibleRows:f}},[c,l]),u=y.useCallback((g,f)=>{r(t.map(w=>w.id===g?{...w,...f}:w))},[t,r]),p=y.useCallback(g=>{r(t.filter(f=>f.id!==g))},[t,r]),h=y.useCallback(g=>{if(t.length>=a)return;const f={id:Yi(),title:g.title,options:g.options,optionValueIds:g.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};r([...t,f])},[t,r,a,s]),_=y.useCallback(()=>{const g=a-t.length,w=m.slice(0,g).map(j=>({id:Yi(),title:j.title,options:j.options,optionValueIds:j.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));r([...t,...w])},[t,r,m,a,s]);return e.variationTypes.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):c.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):n.jsxs("div",{className:"cedros-admin__variant-grid",children:[n.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[t.length,"/",a," variants (",c.length," ","possible)"]})]}),m.length>0&&t.length<a&&n.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[n.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:_,disabled:i,children:["Generate All (",Math.min(m.length,a-t.length),")"]}),n.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{children:"Variant"}),n.jsx("th",{style:{width:100},children:"Price"}),n.jsx("th",{style:{width:80},children:"Qty"}),n.jsx("th",{style:{width:100},children:"SKU"}),n.jsx("th",{style:{width:100},children:"Status"}),n.jsx("th",{style:{width:80},children:"Actions"})]})}),n.jsxs("tbody",{children:[d.map(({combo:g,variant:f})=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:g.title}),n.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(g.options).map(([w,j])=>`${w}: ${j}`).join(", ")})]})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx("span",{children:o}),n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:f.price??"",onChange:w=>u(f.id,{price:w.target.value===""?void 0:parseFloat(w.target.value)||0}),disabled:i,min:"0",step:"0.01",style:{width:70}})]})}),n.jsx("td",{children:n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:f.inventoryQuantity??"",onChange:w=>u(f.id,{inventoryQuantity:w.target.value===""?void 0:parseInt(w.target.value)||0}),disabled:i,min:"0",style:{width:60}})}),n.jsx("td",{children:n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:f.sku??"",onChange:w=>u(f.id,{sku:w.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),n.jsx("td",{children:n.jsx(Dl,{value:f.inventoryStatus??"in_stock",onChange:w=>u(f.id,{inventoryStatus:w}),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],disabled:i})}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>p(f.id),disabled:i,title:"Remove variant",children:Q.trash})})]},f.id)),m.length>0&&t.length<a&&n.jsxs(n.Fragment,{children:[n.jsx("tr",{className:"cedros-admin__variant-separator",children:n.jsx("td",{colSpan:6,children:n.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",m.length,")"]})})}),m.slice(0,10).map(g=>n.jsxs("tr",{className:"cedros-admin__variant-possible",children:[n.jsx("td",{children:n.jsx("span",{style:{opacity:.6},children:g.title})}),n.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>h(g),disabled:i,title:"Create variant",children:Q.plus})})]},g.key)),m.length>10&&n.jsx("tr",{className:"cedros-admin__variant-more",children:n.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",m.length-10," more combinations"]})})]})]})]})})]})}function Wf({serverUrl:e,productId:t,productTitle:r,defaultPrice:s=0,currencySymbol:o="$",apiKey:a,authManager:i,onClose:c}){const{data:l,isLoading:d,error:m,fetch:u,save:p,isSaving:h}=$f({serverUrl:e,productId:t,apiKey:a,authManager:i}),[_,g]=y.useState({variationTypes:[]}),[f,w]=y.useState([]),[j,b]=y.useState(!1),[v,k]=y.useState(!1);y.useEffect(()=>{u()},[u]),y.useEffect(()=>{l&&(g(l.variationConfig),w(l.variants),b(!1))},[l]);const R=y.useCallback(T=>{g(T),b(!0),k(!1)},[]),N=y.useCallback(T=>{w(T),b(!0),k(!1)},[]),C=y.useCallback(async()=>{const T=new Set((l?.variants??[]).map(I=>I.id)),O=f.filter(I=>!T.has(I.id)),$=f.filter(I=>T.has(I.id)),S=(l?.variants??[]).filter(I=>!f.some(B=>B.id===I.id)).map(I=>I.id);await p({variationConfig:_,createVariants:O.map(I=>({optionValueIds:I.optionValueIds??[],inventoryQuantity:I.inventoryQuantity,sku:I.sku,price:I.price})),updateVariants:$.map(I=>({id:I.id,inventoryQuantity:I.inventoryQuantity,sku:I.sku,price:I.price,inventoryStatus:I.inventoryStatus})),deleteVariantIds:S.length>0?S:void 0})&&(b(!1),k(!0),setTimeout(()=>k(!1),3e3))},[_,f,l?.variants,p]);return d?n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading variations..."]})]}):n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),n.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[v&&n.jsxs("span",{className:"cedros-admin__success-text",children:[Q.check," Saved"]}),j&&n.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:C,disabled:h||!j,children:h?"Saving...":"Save Changes"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Q.close})]})]}),m&&n.jsx("div",{className:"cedros-admin__error-banner",children:m}),n.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(zf,{value:_,onChange:R,disabled:h})}),_.variationTypes.length>0&&n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(Uf,{variationConfig:_,variants:f,onChange:N,defaultPrice:s,currencySymbol:o,disabled:h})})]})]})}function Ll({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(!1),[p,h]=y.useState(null),[_,g]=y.useState(null),[f,w]=y.useState(null),[j,b]=y.useState(null),[v,k]=y.useState({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),R=E=>{const P=E.tagsCsv.split(",").map(V=>V.trim()).filter(Boolean),z=E.categoryIdsCsv.split(",").map(V=>V.trim()).filter(Boolean),Z={email:E.checkoutEmail,name:E.checkoutName,phone:E.checkoutPhone,shippingAddress:E.checkoutShippingAddress,billingAddress:E.checkoutBillingAddress},K=E.fulfillmentType==="shipping"?"physical":"digital",L={title:E.title,slug:E.slug||E.id,shipping_profile:K,inventory_status:E.inventoryStatus,checkout_requirements:JSON.stringify(Z),fulfillment_type:E.fulfillmentType};E.imageUrl&&(L.image_url=E.imageUrl);const W=E.compareAtUsd?Math.round(Number(E.compareAtUsd)*100):0;W&&(L.compare_at_amount_cents=String(W)),P.length&&(L.tags=JSON.stringify(P)),z.length&&(L.category_ids=JSON.stringify(z)),E.fulfillmentNotes&&(L.fulfillment_notes=E.fulfillmentNotes);const Y=E.shippingCountriesCsv.split(",").map(V=>V.trim().toUpperCase()).filter(Boolean);return Y.length&&(L.shippingCountries=Y.join(","),L.shipping_countries=Y.join(",")),L},N=E=>E.metadata?.title||E.description||E.id,C=E=>E.metadata?.image_url,T=y.useCallback(async()=>{try{b(null);let E;if(s?.isAuthenticated())E=await s.fetchWithAuth(`/admin/products?limit=${r}`);else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const z=await fetch(`${e}/admin/products?limit=${r}`,{headers:P});if(!z.ok)throw new Error(`Failed to fetch products: ${z.status}`);E=await z.json()}a(E.products||[])}catch{a([]),b("Failed to load products")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{T()},[T]);const O=async E=>{if(E.preventDefault(),!(!v.id||!v.description)){if(h(null),v.fulfillmentType==="shipping"&&v.checkoutShippingAddress&&!v.shippingCountriesCsv.split(",").map(z=>z.trim()).filter(Boolean).length){h("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:P}=v,z=v.inventoryQuantity===""?void 0:Number.isFinite(Number(v.inventoryQuantity))?Number(v.inventoryQuantity):void 0,Z=Number(v.priceUsd)||0,K=Math.round(Z*100),L=Math.round(Z*1e6),W={id:v.id,description:v.description,fiatAmountCents:K,fiatCurrency:v.fiatCurrency,cryptoAtomicAmount:L,cryptoToken:v.cryptoToken,...z!==void 0?{inventoryQuantity:z}:{},metadata:{...P?{product_type:P}:{},...R(v)}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(W)});else{const Y={"Content-Type":"application/json"};t&&(Y["X-API-Key"]=t);const V=await fetch(`${e}/admin/products`,{method:"POST",headers:Y,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to create product: ${V.status}`)}k({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),d(!1),T()}catch(P){h(P instanceof Error?P.message:"Failed to create product")}finally{u(!1)}}},$=E=>`$${(E/100).toFixed(2)}`,S=E=>{switch(E){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},A=y.useMemo(()=>{const E=o.filter(z=>z.active).length,P=o.reduce((z,Z)=>{const K=Z.variations?.length??0;return z+(K>0?K:1)},0);return{activeCount:E,totalSkus:P}},[o]),I=E=>{w(P=>!P||P.key!==E?{key:E,direction:"asc"}:{key:E,direction:P.direction==="asc"?"desc":"asc"})},B=E=>!f||f.key!==E?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:f.direction==="asc"?Q.chevronUp:Q.chevronDown}),D=y.useMemo(()=>{if(!f)return o;const E=f.direction==="asc"?1:-1,P=z=>{switch(f.key){case"product":return N(z);case"type":return S(z.metadata?.product_type);case"price":return z.fiatAmountCents??0;case"status":return z.active?1:0;case"id":default:return z.id}};return[...o].sort((z,Z)=>{const K=P(z),L=P(Z);return typeof K=="number"&&typeof L=="number"?(K-L)*E:String(K).localeCompare(String(L),void 0,{sensitivity:"base"})*E})},[o,f]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:j,onRetry:T}),n.jsx(rr,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:A.activeCount,variant:A.activeCount>0?"success":"muted"},{label:"Total SKUs",value:A.totalSkus}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{h(null),d(!l)},children:[l?Q.close:Q.plus,l?"Cancel":"Add Product"]})]}),l&&n.jsxs("form",{onSubmit:O,className:"cedros-admin__add-form",children:[p&&n.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:p}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.id,onChange:E=>k(P=>({...P,id:E.target.value})),placeholder:"e.g., premium-article",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.title,onChange:E=>k(P=>({...P,title:E.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.slug,onChange:E=>k(P=>({...P,slug:E.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:v.imageUrl,onChange:E=>k(P=>({...P,imageUrl:E.target.value})),placeholder:"https://..."})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.description,onChange:E=>k(P=>({...P,description:E.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:v.productType,onChange:E=>k(P=>({...P,productType:E})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"}],label:"Product Type"}),n.jsx(ot,{value:v.fulfillmentType,onChange:E=>{const P=E;k(z=>({...z,fulfillmentType:P,checkoutShippingAddress:P==="shipping"?z.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),v.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:v.inventoryStatus,onChange:E=>k(P=>({...P,inventoryStatus:E})),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],label:"Inventory status"}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v.inventoryQuantity,onChange:E=>k(P=>({...P,inventoryQuantity:E.target.value===""?"":parseInt(E.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v.compareAtUsd===""?"":v.compareAtUsd,onChange:E=>k(P=>({...P,compareAtUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v.priceUsd===""?"":v.priceUsd,onChange:E=>k(P=>({...P,priceUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.tagsCsv,onChange:E=>k(P=>({...P,tagsCsv:E.target.value})),placeholder:"e.g., core, new, gift"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.categoryIdsCsv,onChange:E=>k(P=>({...P,categoryIdsCsv:E.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:v.checkoutEmail,onChange:E=>k(P=>({...P,checkoutEmail:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),n.jsx(ot,{value:v.checkoutName,onChange:E=>k(P=>({...P,checkoutName:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),n.jsx(ot,{value:v.checkoutPhone,onChange:E=>k(P=>({...P,checkoutPhone:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[v.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:v.checkoutShippingAddress,onChange:E=>k(P=>({...P,checkoutShippingAddress:E.target.checked}))}),"Collect shipping address"]})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:v.checkoutBillingAddress,onChange:E=>k(P=>({...P,checkoutBillingAddress:E.target.checked}))}),"Collect billing address"]})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.fulfillmentNotes,onChange:E=>k(P=>({...P,fulfillmentNotes:E.target.value})),placeholder:v.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),v.fulfillmentType==="shipping"&&v.checkoutShippingAddress&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.shippingCountriesCsv,onChange:E=>k(P=>({...P,shippingCountriesCsv:E.target.value})),placeholder:"e.g., US,CA"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Product"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading products..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("id"),children:["ID",B("id")]})}),n.jsx("th",{"aria-sort":f?.key==="product"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("product"),children:["Product",B("product")]})}),n.jsx("th",{"aria-sort":f?.key==="type"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("type"),children:["Type",B("type")]})}),n.jsx("th",{"aria-sort":f?.key==="price"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("price"),children:["Price",B("price")]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("status"),children:["Status",B("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:D.map(E=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:E.id})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[C(E)?n.jsx("img",{src:C(E),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):n.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:N(E)}),n.jsx("span",{style:{opacity:.8},children:E.description})]})]})}),n.jsx("td",{children:S(E.metadata?.product_type)}),n.jsx("td",{children:$(E.fiatAmountCents)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${E.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:E.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>g(E),children:"Variations"})]})})]},E.id))})]})}),_&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>g(null),children:n.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:E=>E.stopPropagation(),children:n.jsx(Wf,{serverUrl:e,productId:_.id,productTitle:N(_),defaultPrice:_.fiatAmountCents/100,apiKey:t,authManager:s,onClose:()=>g(null)})})})]})}function $l({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(null),[l,d]=y.useState(!0),[m,u]=y.useState(!0),[p,h]=y.useState(null),[_,g]=y.useState(""),[f,w]=y.useState(null),j=y.useCallback(async()=>{u(!0);try{h(null);let C;if(s?.isAuthenticated())C=await s.fetchWithAuth("/admin/stats");else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const O=await fetch(`${e}/admin/stats`,{headers:T});if(!O.ok)throw new Error(`Failed to fetch stats: ${O.status}`);C=await O.json()}c(C)}catch{c(null),h("Failed to load payment stats")}finally{u(!1)}},[e,t,s]);y.useEffect(()=>{j()},[j]);const b=y.useCallback(async()=>{try{h(null);let C;const T=new URLSearchParams({limit:r.toString()});_&&T.set("method",_);const O=`/admin/transactions?${T}`;if(s?.isAuthenticated())C=await s.fetchWithAuth(O);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const S=await fetch(`${e}${O}`,{headers:$});if(!S.ok)throw new Error(`Failed to fetch transactions: ${S.status}`);C=await S.json()}a(C.transactions||[])}catch{a([]),h("Failed to load transactions")}finally{d(!1)}},[e,t,r,_,s]);y.useEffect(()=>{b()},[b]);const v=C=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(C),k=C=>{w(T=>!T||T.key!==C?{key:C,direction:"asc"}:{key:C,direction:T.direction==="asc"?"desc":"asc"})},R=C=>!f||f.key!==C?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:f.direction==="asc"?Q.chevronUp:Q.chevronDown}),N=y.useMemo(()=>{if(!f)return o;const C=f.direction==="asc"?1:-1,T=O=>{switch(f.key){case"resource":return O.resourceId;case"method":return O.method;case"amount":return O.amount;case"status":return O.status;case"date":return new Date(O.paidAt).getTime();case"id":default:return O.id}};return[...o].sort((O,$)=>{const S=T(O),A=T($);return typeof S=="number"&&typeof A=="number"?(S-A)*C:String(S).localeCompare(String(A),void 0,{sensitivity:"base"})*C})},[o,f]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:p,onRetry:()=>{j(),b()}}),n.jsx(rr,{stats:[{label:"Revenue",value:v(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:v(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:v(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:v(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:m,onRefresh:j}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),n.jsx(Dl,{value:_,onChange:g,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading transactions..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("id"),children:["ID",R("id")]})}),n.jsx("th",{"aria-sort":f?.key==="resource"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("resource"),children:["Resource",R("resource")]})}),n.jsx("th",{"aria-sort":f?.key==="method"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("method"),children:["Method",R("method")]})}),n.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("amount"),children:["Amount",R("amount")]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("status"),children:["Status",R("status")]})}),n.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("date"),children:["Date",R("date")]})})]})}),n.jsx("tbody",{children:N.map(C=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:C.id})}),n.jsx("td",{children:C.resourceId}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.method}`,children:C.method})}),n.jsxs("td",{children:["$",C.amount.toFixed(2)," ",C.currency.toUpperCase()]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.status}`,children:C.status})}),n.jsx("td",{children:kr(C.paidAt)})]},C.id))})]})})]})}function zl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(!1),[p,h]=y.useState(null),[_,g]=y.useState(null),[f,w]=y.useState({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),j=y.useCallback(async()=>{try{g(null);let T;const O=`/admin/coupons?limit=${r}`;if(s?.isAuthenticated())T=await s.fetchWithAuth(O);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const S=await fetch(`${e}${O}`,{headers:$});if(!S.ok)throw new Error(`Failed to fetch coupons: ${S.status}`);T=await S.json()}a(T.coupons||[])}catch(T){J.getLogger().error("[CouponsSection] Failed to fetch coupons:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),g("Failed to load coupons")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{j()},[j]);const b=async T=>{if(T.preventDefault(),!(!f.code||f.discountValue<=0)){u(!0);try{const O=f.minimumAmountUsd?Math.round(Number(f.minimumAmountUsd)*100):void 0,$=f.productIdsCsv.split(",").map(I=>I.trim()).filter(Boolean),S=f.categoryIdsCsv.split(",").map(I=>I.trim()).filter(Boolean),A={code:f.code,discountType:f.discountType,discountValue:f.discountValue,usageLimit:f.usageLimit,active:!0,usageCount:0,scope:f.scope,...$.length?{productIds:$}:{},...S.length?{categoryIds:S}:{},...f.paymentMethod!=="any"?{paymentMethod:f.paymentMethod}:{},...f.autoApply?{autoApply:!0}:{},...f.appliesAt!=="both"?{appliesAt:f.appliesAt}:{},...f.startsAt?{startsAt:f.startsAt}:{},...f.expiresAt?{expiresAt:f.expiresAt}:{},...O?{minimumAmountCents:O}:{},...f.usageLimitPerCustomer?{usageLimitPerCustomer:f.usageLimitPerCustomer}:{},...f.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(A)});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/coupons`,{method:"POST",headers:I,body:JSON.stringify(A)});if(!B.ok)throw new Error(`Failed to create coupon: ${B.status}`)}w({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),d(!1),j()}catch(O){J.getLogger().error("[CouponsSection] Failed to add coupon:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),g("Failed to create coupon")}finally{u(!1)}}},v=o.filter(T=>T.active).length,k=o.reduce((T,O)=>T+(O.usageCount??0),0),R=T=>{h(O=>!O||O.key!==T?{key:T,direction:"asc"}:{key:T,direction:O.direction==="asc"?"desc":"asc"})},N=T=>!p||p.key!==T?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:p.direction==="asc"?Q.chevronUp:Q.chevronDown}),C=y.useMemo(()=>{if(!p)return o;const T=p.direction==="asc"?1:-1,O=$=>{switch(p.key){case"discount":return $.discountValue??0;case"usage":return $.usageCount??0;case"status":return $.active?1:0;case"code":default:return $.code}};return[...o].sort(($,S)=>{const A=O($),I=O(S);return typeof A=="number"&&typeof I=="number"?(A-I)*T:String(A).localeCompare(String(I),void 0,{sensitivity:"base"})*T})},[o,p]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:_,onRetry:j}),n.jsx(rr,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:v,variant:v>0?"success":"muted"},{label:"Redemptions",value:k}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?Q.close:Q.plus,l?"Cancel":"Add Coupon"]})]}),l&&n.jsxs("form",{onSubmit:b,className:"cedros-admin__add-form",children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.code,onChange:T=>w(O=>({...O,code:T.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),n.jsx(ot,{value:f.discountType,onChange:T=>w(O=>({...O,discountType:T})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",f.discountType==="percentage"?"(%)":"($)"]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.discountValue||"",onChange:T=>w(O=>({...O,discountValue:parseFloat(T.target.value)||0})),placeholder:f.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:f.discountType==="percentage"?"1":"0.01",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.usageLimit||"",onChange:T=>w(O=>({...O,usageLimit:T.target.value?parseInt(T.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:f.expiresAt,onChange:T=>w(O=>({...O,expiresAt:T.target.value}))})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(ot,{value:f.scope,onChange:T=>w(O=>({...O,scope:T})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),n.jsx(ot,{value:f.paymentMethod,onChange:T=>w(O=>({...O,paymentMethod:T})),options:[{value:"any",label:"Any Payment Method"},{value:"stripe",label:"Stripe (Card) Only"},{value:"x402",label:"Crypto (x402) Only"},{value:"credits",label:"Credits Only"}],label:"Payment Method"}),n.jsx(ot,{value:f.appliesAt,onChange:T=>w(O=>({...O,appliesAt:T})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),f.scope==="specific_products"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.productIdsCsv,onChange:T=>w(O=>({...O,productIdsCsv:T.target.value})),placeholder:"e.g., prod_123, prod_456"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:f.startsAt,onChange:T=>w(O=>({...O,startsAt:T.target.value}))})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:f.autoApply,onChange:T=>w(O=>({...O,autoApply:T.target.checked}))}),"Automatically apply when conditions met"]})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.minimumAmountUsd===""?"":f.minimumAmountUsd,onChange:T=>w(O=>({...O,minimumAmountUsd:T.target.value===""?"":parseFloat(T.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.usageLimitPerCustomer||"",onChange:T=>w(O=>({...O,usageLimitPerCustomer:T.target.value?parseInt(T.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:f.firstPurchaseOnly,onChange:T=>w(O=>({...O,firstPurchaseOnly:T.target.checked}))}),"New customers only"]})]})]}),f.scope==="specific_categories"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.categoryIdsCsv,onChange:T=>w(O=>({...O,categoryIdsCsv:T.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Coupon"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading coupons..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":p?.key==="code"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("code"),children:["Code",N("code")]})}),n.jsx("th",{"aria-sort":p?.key==="discount"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("discount"),children:["Discount",N("discount")]})}),n.jsx("th",{"aria-sort":p?.key==="usage"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("usage"),children:["Usage",N("usage")]})}),n.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("status"),children:["Status",N("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:C.map(T=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:T.code})}),n.jsx("td",{children:T.discountType==="percentage"?`${T.discountValue}%`:`$${T.discountValue.toFixed(2)}`}),n.jsxs("td",{children:[T.usageCount,T.usageLimit?` / ${T.usageLimit}`:""]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${T.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:T.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},T.code))})]})})]})}function Fl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(null),[m,u]=y.useState([]),[p,h]=y.useState(!0),[_,g]=y.useState(null),[f,w]=y.useState(null),[j,b]=y.useState([]),[v,k]=y.useState(!0),[R,N]=y.useState(null),[C,T]=y.useState(null),[O,$]=y.useState(null),[S,A]=y.useState(""),[I,B]=y.useState(null),D=y.useCallback(async()=>{try{let U;const re=`/admin/refunds?limit=${r}`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{headers:de});if(!ke.ok)throw new Error(`Failed to fetch x402 refunds: ${ke.status}`);U=await ke.json()}a(U.refunds||[])}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),B("Failed to load x402 refunds")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{D()},[D]);const E=y.useCallback(async()=>{try{let U;const re=`/admin/credits/refund-requests?status=pending&limit=${r}&offset=0`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const ke={"Content-Type":"application/json"};t&&(ke["X-API-Key"]=t);const Se=await fetch(`${e}${re}`,{headers:ke});if(!Se.ok)throw new Error(`Failed to fetch credits refund requests: ${Se.status}`);U=await Se.json()}const de=Array.isArray(U)?U:"refundRequests"in U?U.refundRequests:U.requests||[];u(de)}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([]),B("Failed to load credits refunds")}finally{h(!1)}},[e,t,r,s]);y.useEffect(()=>{E()},[E]);const P=async U=>{g(U.id);try{const re=`/admin/credits/refund-requests/${U.id}/process`,de=JSON.stringify({amountLamports:U.amountLamports,reason:U.reason});if(s?.isAuthenticated())await s.fetchWithAuth(re,{method:"POST",body:de});else{const ke={"Content-Type":"application/json"};t&&(ke["X-API-Key"]=t);const Se=await fetch(`${e}${re}`,{method:"POST",headers:ke,body:de});if(!Se.ok)throw new Error(`Failed to process credits refund: ${Se.status}`)}await E()}catch(re){J.getLogger().error("[RefundsSection] Failed to process credits refund:",re,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:U.id}),B("Failed to process credits refund")}finally{g(null)}},z=U=>{A(U.reason??""),$(U)},Z=()=>{$(null),A("")},K=async()=>{if(!O)return;const U=O,re=S;Z(),g(U.id);try{const de=`/admin/credits/refund-requests/${U.id}/reject`,ke=JSON.stringify({reason:re});if(s?.isAuthenticated())await s.fetchWithAuth(de,{method:"POST",body:ke});else{const Se={"Content-Type":"application/json"};t&&(Se["X-API-Key"]=t);const Me=await fetch(`${e}${de}`,{method:"POST",headers:Se,body:ke});if(!Me.ok)throw new Error(`Failed to reject credits refund: ${Me.status}`)}await E()}catch(de){J.getLogger().error("[RefundsSection] Failed to reject credits refund:",de,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:U.id}),B("Failed to reject credits refund")}finally{g(null)}},L=y.useCallback(async()=>{try{let U;const re=`/admin/stripe/refunds?limit=${r}`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{headers:de});if(!ke.ok)throw new Error(`Failed to fetch Stripe refunds: ${ke.status}`);U=await ke.json()}b(U.refunds||[])}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),b([]),B("Failed to load Stripe refunds")}finally{k(!1)}},[e,t,r,s]);y.useEffect(()=>{L()},[L]);const W=async U=>{N(U);try{const re=`/admin/stripe/refunds/${U}/process`;if(s?.isAuthenticated())await s.fetchWithAuth(re,{method:"POST"});else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{method:"POST",headers:de});if(!ke.ok)throw new Error(`Failed to process refund: ${ke.status}`)}await L()}catch(re){J.getLogger().error("[RefundsSection] Failed to process Stripe refund:",re,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:U}),B("Failed to process Stripe refund")}finally{N(null)}},Y=(U,re)=>new Intl.NumberFormat("en-US",{style:"currency",currency:re}).format(U/100),V=U=>U?U.replace(/_/g," ").replace(/\b\w/g,re=>re.toUpperCase()):"—",ce=U=>{switch(U){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},F=(U,re)=>re?re.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(U/1e6)} (USD credits)`:`${U.toLocaleString()} ${re.toUpperCase()} (atomic)`:`${U.toLocaleString()} (atomic)`,ee=U=>{switch(U){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},pe=U=>U.stripeRefundId??"—",q=U=>U.chargeId??"—",ne=j.filter(U=>U.status==="pending"||U.status==="requires_action").length,le=m.filter(U=>U.status==="pending").length,fe=o.filter(U=>U.status==="pending").length,Pe=ne+le+fe,Ve=j.filter(U=>U.status==="succeeded").reduce((U,re)=>U+re.amount,0),qe=m.filter(U=>U.status==="processed").reduce((U,re)=>U+re.amountLamports,0),He=o.filter(U=>U.status==="completed").reduce((U,re)=>U+re.amount,0),gt=Ve/100+qe/1e6+He,Ge=U=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(U),zt=v||p||i,lt=U=>{T(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},te=U=>{w(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},xe=U=>{d(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},ge=(U,re)=>!U||!re?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:re==="asc"?Q.chevronUp:Q.chevronDown}),dt=y.useMemo(()=>{if(!C)return j;const U=C.direction==="asc"?1:-1,re=de=>{switch(C.key){case"stripe":return de.stripeRefundId??"";case"charge":return de.chargeId??"";case"amount":return de.amount??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...j].sort((de,ke)=>{const Se=re(de),Me=re(ke);return typeof Se=="number"&&typeof Me=="number"?(Se-Me)*U:String(Se).localeCompare(String(Me),void 0,{sensitivity:"base"})*U})},[j,C]),xt=y.useMemo(()=>{if(!f)return m;const U=f.direction==="asc"?1:-1,re=de=>{switch(f.key){case"original":return de.originalTransactionId??"";case"user":return de.userId??"";case"amount":return de.amountLamports??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...m].sort((de,ke)=>{const Se=re(de),Me=re(ke);return typeof Se=="number"&&typeof Me=="number"?(Se-Me)*U:String(Se).localeCompare(String(Me),void 0,{sensitivity:"base"})*U})},[m,f]),ut=y.useMemo(()=>{if(!l)return o;const U=l.direction==="asc"?1:-1,re=de=>{switch(l.key){case"transaction":return de.transactionId??"";case"amount":return de.amount??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...o].sort((de,ke)=>{const Se=re(de),Me=re(ke);return typeof Se=="number"&&typeof Me=="number"?(Se-Me)*U:String(Se).localeCompare(String(Me),void 0,{sensitivity:"base"})*U})},[o,l]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:I,onRetry:()=>{D(),E(),L()}}),n.jsx(rr,{stats:[{label:"Pending",value:Pe,variant:Pe>0?"warning":"muted"},{label:"Card Pending",value:ne,description:"Stripe"},{label:"Credits Pending",value:le},{label:"Crypto Pending",value:fe,description:"x402"},{label:"Total Refunded",value:Ge(gt),variant:"success"}],isLoading:zt}),n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),v?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading Stripe refunds..."]}):j.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":C?.key==="id"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("id"),children:["Request ID",ge(C?.key==="id",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="stripe"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("stripe"),children:["Stripe Refund ID",ge(C?.key==="stripe",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="charge"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("charge"),children:["Charge",ge(C?.key==="charge",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="amount"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("amount"),children:["Amount",ge(C?.key==="amount",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="reason"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("reason"),children:["Reason",ge(C?.key==="reason",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="status"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("status"),children:["Status",ge(C?.key==="status",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="date"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>lt("date"),children:["Date",ge(C?.key==="date",C?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:dt.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:pe(U)})}),n.jsx("td",{children:n.jsx("code",{children:q(U)})}),n.jsx("td",{children:Y(U.amount,U.currency)}),n.jsx("td",{children:V(U.reason)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${ee(U.status)}`,children:U.status})}),n.jsx("td",{children:kr(U.createdAt)}),n.jsx("td",{children:(U.status==="pending"||U.status==="requires_action")&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>W(U.id),disabled:R===U.id,children:R===U.id?"Processing...":"Process"})})]},U.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),p?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading credits refunds..."]}):m.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("id"),children:["Request ID",ge(f?.key==="id",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="original"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("original"),children:["Original Tx",ge(f?.key==="original",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="user"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("user"),children:["User",ge(f?.key==="user",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("amount"),children:["Amount",ge(f?.key==="amount",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="reason"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("reason"),children:["Reason",ge(f?.key==="reason",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("status"),children:["Status",ge(f?.key==="status",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("date"),children:["Date",ge(f?.key==="date",f?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:xt.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:U.originalTransactionId})}),n.jsx("td",{children:n.jsx("code",{children:U.userId??"—"})}),n.jsx("td",{children:F(U.amountLamports,U.currency)}),n.jsx("td",{children:U.reason??"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${ce(U.status)}`,children:U.status})}),n.jsx("td",{children:kr(U.createdAt)}),n.jsx("td",{children:U.status==="pending"?n.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>P(U),disabled:_===U.id,children:_===U.id?"Processing...":"Process"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>z(U),disabled:_===U.id,children:"Reject"})]}):null})]},U.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading x402 refunds..."]}):o.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("id"),children:["ID",ge(l?.key==="id",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="transaction"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("transaction"),children:["Transaction",ge(l?.key==="transaction",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="amount"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("amount"),children:["Amount",ge(l?.key==="amount",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="reason"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("reason"),children:["Reason",ge(l?.key==="reason",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="status"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("status"),children:["Status",ge(l?.key==="status",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="date"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("date"),children:["Date",ge(l?.key==="date",l?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:ut.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:U.transactionId})}),n.jsxs("td",{children:["$",U.amount.toFixed(2)]}),n.jsx("td",{children:U.reason||"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${U.status}`,children:U.status})}),n.jsx("td",{children:kr(U.createdAt)}),n.jsx("td",{children:U.status==="pending"&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",children:"Process"})})]},U.id))})]})}),O&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:Z,children:n.jsxs("div",{className:"cedros-admin__modal",onClick:U=>U.stopPropagation(),children:[n.jsxs("div",{className:"cedros-admin__modal-header",children:[n.jsx("h3",{className:"cedros-admin__modal-title",children:"Reject Refund Request"}),n.jsx("button",{type:"button",className:"cedros-admin__modal-close",onClick:Z,"aria-label":"Close",children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__modal-body",children:[n.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",n.jsx("code",{children:O.id})," for ",F(O.amountLamports,O.currency),"."]}),n.jsxs("label",{className:"cedros-admin__form-field",children:[n.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),n.jsx("textarea",{className:"cedros-admin__input",value:S,onChange:U=>A(U.target.value),placeholder:"Enter rejection reason...",rows:3,style:{resize:"vertical"}})]})]}),n.jsxs("div",{className:"cedros-admin__modal-footer",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--outline",onClick:Z,children:"Cancel"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:K,children:"Reject Refund"})]})]})})]})}async function Vf(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 Vf(this.auth);Object.assign(s,a)}const o=await fetch(`${this.serverUrl}${t}`,{...r,headers:s});if(!o.ok){const a=await o.text();throw new Error(`API error ${o.status}: ${a}`)}return o.json()}async listCategories(t=100){return this.fetch(`/admin/config?limit=${t}`)}async getConfig(t,r=!0){return this.fetch(`/admin/config/${t}?redact_secrets=${r}`)}async updateConfig(t,r,s){await this.fetch(`/admin/config/${t}`,{method:"PUT",body:JSON.stringify({config:r,description:s})})}async patchConfig(t,r,s){await this.fetch(`/admin/config/${t}`,{method:"PATCH",body:JSON.stringify({updates:r,description:s})})}async batchUpdate(t){await this.fetch("/admin/config/batch",{method:"POST",body:JSON.stringify({updates:t})})}async validateConfig(t,r){return this.fetch("/admin/config/validate",{method:"POST",body:JSON.stringify({category:t,config:r})})}async getHistory(t,r=50){const s=new URLSearchParams({limit:r.toString()});return t&&s.set("category",t),this.fetch(`/admin/config/history?${s}`)}}const Ea={server:{label:"Server",secrets:[],icon:"🖥️",fields:{admin_metrics_api_key:{hidden:!0},cors_allowed_origins:{hidden:!0}}},security:{label:"Security",description:"Configure CORS, rate limiting, and other security settings",secrets:[],icon:"🔒",fields:{cors_allowed_origins:{description:'List of allowed origins for CORS requests. Use ["*"] to allow all origins (not recommended for production).'}}},metrics:{label:"Metrics",description:"Configure metrics collection and API access",secrets:["admin_metrics_api_key"],icon:"📊",fields:{admin_metrics_api_key:{description:"API key for accessing the admin metrics endpoint. Keep this secret."}}},logging:{label:"Logging",secrets:[],icon:"📝",fields:{level:{type:"dropdown",options:["trace","debug","info","warn","error"]},format:{hidden:!0},environment:{hidden:!0}}},stripe:{label:"Stripe",secrets:["secret_key","webhook_secret"],icon:"💳",fields:{enabled:{hidden:!0},mode:{type:"dropdown",options:["test","live"]},success_url:{hidden:!0},cancel_url:{hidden:!0}}},x402:{label:"X402 (Crypto)",secrets:["server_wallets"],icon:"⚡",fields:{enabled:{hidden:!0},payment_address:{type:"solana_address",description:"The Solana wallet address where payments are received. This is where customer funds are sent."},token_mint:{type:"token_mint",description:"The SPL token used for payments. Most commonly USDC."},token_decimals:{type:"number",description:"Number of decimal places for the token (e.g., USDC has 6 decimals).",hidden:!0},custom_token_symbol:{description:'Display symbol for your custom token (e.g., "MYTOKEN").',hidden:!0},custom_token_icon:{description:"URL to your token's icon image.",hidden:!0},rpc_url:{description:"Custom Solana RPC endpoint. Leave empty to use the default public RPC."},gasless_enabled:{type:"toggle",description:"When enabled, your server pays transaction fees so customers don't need SOL."},server_wallets:{type:"secret_array",description:"Server keypair(s) used to sign and pay for transactions. Required for gasless payments.",showWhen:"gasless_enabled"},network:{hidden:!0}}},paywall:{label:"Paywall",secrets:[],icon:"🚪",fields:{product_cache_ttl:{type:"number",unit:"seconds"}}},coupons:{label:"Coupons",secrets:[],icon:"🎟️",fields:{cache_ttl:{type:"number",unit:"seconds"}}},subscriptions:{label:"Subscriptions",secrets:[],icon:"🔄",fields:{grace_period_hours:{type:"number",unit:"hours"}}},callbacks:{label:"Callbacks",secrets:["hmac_secret"],icon:"🔔"},email:{label:"Email",description:"Email receipts for customers after purchase",secrets:["smtp_password"],icon:"📧",fields:{enabled:{hidden:!0},provider:{type:"dropdown",options:["sendgrid","mailgun","postmark","ses","resend","custom"],description:"Email service provider."},smtp_host:{description:"SMTP server hostname.",showWhen:"provider"},smtp_port:{type:"number",description:"SMTP server port (typically 587 for TLS).",showWhen:"provider"},smtp_user:{description:"SMTP authentication username or API key name.",showWhen:"provider"},smtp_password:{description:"SMTP password or API key.",showWhen:"provider"},from_address:{description:"Sender email address (e.g., orders@yourstore.com)."},from_name:{description:'Sender display name (e.g., "Your Store").'}}},webhook:{label:"Webhook",description:"HTTP notifications when purchases occur",secrets:["secret"],icon:"🔔",fields:{enabled:{hidden:!0},url:{description:"URL to receive POST notifications (e.g., https://api.yoursite.com/webhooks/orders)."},secret:{description:"Shared secret for HMAC-SHA256 signature verification."},retry_attempts:{type:"number",description:"Number of retry attempts on failure (default: 3)."}}},messaging:{label:"Messaging",description:"Email and webhook notifications for purchases",secrets:["smtp_password","webhook_secret"],icon:"📬",fields:{email_enabled:{type:"boolean",description:"Send order confirmation emails to customers."},smtp_host:{description:"SMTP server hostname.",showWhen:"email_enabled"},smtp_port:{type:"number",description:"SMTP server port (typically 587 for TLS).",showWhen:"email_enabled"},smtp_username:{description:"SMTP authentication username or API key.",showWhen:"email_enabled"},smtp_password:{description:"SMTP password or API key.",showWhen:"email_enabled"},from_email:{description:"Sender email address (e.g., orders@yourstore.com).",showWhen:"email_enabled"},from_name:{description:'Sender display name (e.g., "Your Store").',showWhen:"email_enabled"},webhook_enabled:{type:"boolean",description:"Send webhook notifications when purchases complete."},webhook_url:{description:"URL to receive POST notifications.",showWhen:"webhook_enabled"},webhook_secret:{description:"Shared secret for HMAC-SHA256 signature verification.",showWhen:"webhook_enabled"},webhook_timeout:{type:"number",description:"Request timeout in seconds (default: 30).",showWhen:"webhook_enabled"}}},monitoring:{label:"Monitoring",secrets:[],icon:"📊",fields:{check_interval:{type:"number",unit:"seconds"},low_balance_threshold:{type:"number",unit:"SOL"}}},rate_limit:{label:"Rate Limiting",secrets:[],icon:"⏱️"},circuit_breaker:{label:"Circuit Breaker",secrets:[],icon:"🔌"},admin:{label:"Admin Keys",secrets:[],icon:"👤"},api_keys:{label:"API Keys",secrets:[],icon:"🔐"},cedros_login:{label:"Cedros Login",secrets:["api_key"],icon:"🔑",fields:{enabled:{hidden:!0},credits_enabled:{hidden:!0},base_url:{hidden:!0},timeout:{hidden:!0}}},storefront:{label:"Storefront",description:"Product pages & display settings",secrets:[],icon:"🏪",fields:{"relatedProducts.mode":{type:"dropdown",options:["most_recent","by_category","manual","ai"]},"relatedProducts.maxItems":{type:"number"}}}};function Bl(e,t){return Ea[e]?.secrets.includes(t)??!1}const wr="[REDACTED]";function Ta({data:e,onSave:t,debounceMs:r=1500,savedDurationMs:s=2e3,enabled:o=!0,skipInitial:a=!0}){const[i,c]=y.useState("idle"),[l,d]=y.useState(null),m=y.useRef(!0),u=y.useRef(null),p=y.useRef(null),h=y.useRef(e);h.current=e;const _=y.useCallback(async()=>{c("saving"),d(null);try{await t(h.current),c("saved"),p.current=setTimeout(()=>{c("idle")},s)}catch(w){c("error"),d(w instanceof Error?w.message:"Save failed")}},[t,s]),g=y.useCallback(async()=>{u.current&&(clearTimeout(u.current),u.current=null),await _()},[_]),f=y.useCallback(()=>{c("idle"),d(null)},[]);return y.useEffect(()=>{if(o){if(a&&m.current){m.current=!1;return}return u.current&&clearTimeout(u.current),p.current&&clearTimeout(p.current),c("pending"),u.current=setTimeout(()=>{_()},r),()=>{u.current&&clearTimeout(u.current)}}},[e,o,a,r,_]),y.useEffect(()=>()=>{u.current&&clearTimeout(u.current),p.current&&clearTimeout(p.current)},[]),{status:i,error:l,saveNow:g,reset:f}}function Hf(e){if(!e||e.trim()==="")return{valid:!0};try{return new af.PublicKey(e.trim()),{valid:!0}}catch{return{valid:!1,error:"Invalid Solana address"}}}function Ki(e,t,r){const s=Bl(e,t),o=t.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase()),i=Ea[e]?.fields?.[t],c={isSecret:s,label:o,description:i?.description,hidden:i?.hidden,showWhen:i?.showWhen};return i?.type==="dropdown"&&i.options?{...c,type:"dropdown",options:i.options}:i?.type==="token_mint"?{...c,type:"token_mint"}:i?.type==="toggle"?{...c,type:"toggle"}:i?.type==="secret_array"?{...c,type:"secret_array",isSecret:!0}:i?.type==="solana_address"?{...c,type:"solana_address"}:i?.type==="number"?{...c,type:"number",unit:i.unit}:typeof r=="boolean"?{...c,type:"boolean"}:typeof r=="number"?{...c,type:"number",unit:i?.unit}:Array.isArray(r)?{...c,type:"array"}:typeof r=="object"&&r!==null?{...c,type:"object"}:{...c,type:"string"}}function Zf({category:e,config:t,originalConfig:r,isLoading:s=!1,onSave:o}){const[a,i]=y.useState(t),[c,l]=y.useState(new Set);y.useEffect(()=>{i(t)},[t]);const d=y.useMemo(()=>{const j={...a};for(const b of Object.keys(j))if(Bl(e,b)){const v=r[b],k=j[b];(k===wr||k===v)&&(j[b]=wr)}return j},[a,r,e]),{status:m,error:u}=Ta({data:d,onSave:o,debounceMs:1500}),p=y.useCallback((j,b)=>{i(v=>({...v,[j]:b}))},[]),h=y.useCallback(j=>{l(b=>{const v=new Set(b);return v.has(j)?v.delete(j):v.add(j),v})},[]),_=j=>j?n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:j}):null,g=(j,b)=>{const v=Ki(e,j,r[j]??b);if(v.type==="dropdown"&&v.options)return n.jsx(ot,{value:b,onChange:N=>p(j,N),options:v.options.map(N=>({value:N,label:N})),label:v.label,description:v.description,disabled:s});if(v.type==="token_mint")return n.jsx(Gf,{label:v.label,value:b,onChange:N=>p(j,N),decimals:a.token_decimals??6,onDecimalsChange:N=>p("token_decimals",N),disabled:s,description:v.description,customSymbol:a.custom_token_symbol||"",customIcon:a.custom_token_icon||"",onCustomSymbolChange:N=>p("custom_token_symbol",N),onCustomIconChange:N=>p("custom_token_icon",N)});if(v.type==="toggle")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("button",{type:"button",role:"switch","aria-checked":b,onClick:()=>p(j,!b),disabled:s,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:b?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:s?"not-allowed":"pointer",position:"relative",transition:"background-color 0.2s",opacity:s?.5:1,flexShrink:0},children:n.jsx("span",{style:{position:"absolute",top:2,left:b?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})}),n.jsx("span",{className:"cedros-admin__field-label",style:{marginBottom:0},children:v.label})]}),_(v.description)]});if(v.type==="solana_address"){const N=b||"",C=Hf(N);return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:v.label}),n.jsxs("div",{style:{position:"relative"},children:[n.jsx("input",{type:"text",className:`cedros-admin__input ${C.valid?"":"cedros-admin__input--error"}`,value:N,onChange:T=>p(j,T.target.value),disabled:s,placeholder:"e.g. 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",style:{width:"100%",fontFamily:"monospace",fontSize:"0.875rem",borderColor:C.valid?void 0:"var(--cedros-admin-error, #dc2626)",paddingRight:N&&C.valid?"2rem":void 0}}),N&&C.valid&&n.jsx("span",{style:{position:"absolute",right:10,top:"50%",transform:"translateY(-50%)",color:"var(--cedros-admin-success, #16a34a)",fontSize:"1rem"},title:"Valid Solana address",children:"✓"})]}),!C.valid&&n.jsx("span",{style:{color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.75rem",marginTop:"0.25rem",display:"block"},children:C.error}),_(v.description)]})}if(v.type==="boolean")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__checkbox",children:[n.jsx("input",{type:"checkbox",checked:b,onChange:N=>p(j,N.target.checked),disabled:s}),v.label]}),_(v.description)]});if(v.type==="number")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[v.label,v.unit&&n.jsxs("span",{className:"cedros-admin__field-unit",children:[" (",v.unit,")"]})]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:b,onChange:N=>p(j,parseFloat(N.target.value)||0),disabled:s}),_(v.description)]});if(v.type==="secret_array")return n.jsx(Qf,{label:v.label,value:b,onChange:N=>p(j,N),disabled:s,description:v.description});if(v.type==="array"){const N=b;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:v.label}),n.jsx("textarea",{className:"cedros-admin__textarea",value:N.join(`
|
|
1
|
+
"use strict";var tf=Object.create;var Hi=Object.defineProperty;var nf=Object.getOwnPropertyDescriptor;var rf=Object.getOwnPropertyNames;var sf=Object.getPrototypeOf,of=Object.prototype.hasOwnProperty;var af=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rf(t))!of.call(e,o)&&o!==r&&Hi(e,o,{get:()=>t[o],enumerable:!(s=nf(t,o))||s.enumerable});return e};var cf=(e,t,r)=>(r=e!=null?tf(sf(e)):{},af(t||!e||!e.__esModule?Hi(r,"default",{value:e,enumerable:!0}):r,e));const n=require("react/jsx-runtime"),y=require("react"),J=require("./CedrosContext-C2v_s8cc.js"),ka=require("@solana/wallet-adapter-react"),Zi=require("@solana/wallet-adapter-base"),lf=require("@solana/wallet-adapter-react-ui"),df=require("@solana/web3.js"),Gi=require("./index-WcOlBYZJ.js"),Sa=require("react-dom");function kl(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=kl(y),Rs=kl(Sa);function uf(e){return!e||!e.coupon_codes?[]:e.coupon_codes.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function mf(e,t=", "){return e.join(t)}function pf(e,t){return e<=0?0:(e-t)/e*100}function ff(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 Sl(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return 1;const r=Math.floor(t);return r>0?r:1}function fs(e){return e.map(t=>({resource:t.resource,quantity:Sl(t.quantity),variantId:t.variantId,metadata:t.metadata}))}function un(e){return e.reduce((t,r)=>t+Sl(r.quantity),0)}function hf(e){return!!(e&&e.length>0&&(e.length>1||e.length===1&&(e[0].quantity??1)>1))}const gf={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 hs(e){return gf[e]||{message:"An unexpected error occurred",action:"Please try again or contact support if this continues.",technicalHint:`Unknown error code: ${e}`}}const Cl=new Map,Ko=new Map,Xo=new Map,Nl=200,Ca=2e3;function xf(e){const t=Xo.get(e);return t?Date.now()<t?!0:(Xo.delete(e),!1):!1}function yf(e,t=Nl){const r=Date.now()+t;Xo.set(e,r)}function vf(e,t=Ca){const r=Cl.get(e);if(!r)return!1;const o=Date.now()-r;return o<t?(J.getLogger().debug(`[Deduplication] Duplicate request blocked: ${e} (${o}ms ago)`),!0):!1}function bf(e){Cl.set(e,Date.now())}function wf(e){return Ko.get(e)||null}function _f(e,t){Ko.set(e,t);const r=()=>{Ko.delete(e),bf(e)};return t.then(r,r),t}async function jf(e,t,r={}){const{windowMs:s=Ca,throwOnDuplicate:o=!0}=r,a=wf(e);if(a)return J.getLogger().debug(`[Deduplication] Reusing in-flight request: ${e}`),a;if(vf(e,s)){if(o)throw new Error(`Duplicate request blocked: ${e}`);return J.getLogger().warn(`[Deduplication] Duplicate request blocked but not throwing: ${e}`),Promise.reject(new Error("Duplicate request"))}const i=t();return _f(e,i)}function Ln(e,t,r={}){const{cooldownMs:s=Nl,deduplicationWindowMs:o=Ca}=r;return async()=>{if(xf(e)){J.getLogger().debug(`[Deduplication] Button in cooldown: ${e}`);return}yf(e,s);try{await jf(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 Na(e){return{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:e,opacity:.6,padding:"0.25rem",lineHeight:1}}const xn={PAYMENT_START:"cedros:payment:start",WALLET_CONNECT:"cedros:wallet:connect",WALLET_CONNECTED:"cedros:wallet:connected",WALLET_ERROR:"cedros:wallet:error",PAYMENT_PROCESSING:"cedros:payment:processing",PAYMENT_SUCCESS:"cedros:payment:success",PAYMENT_ERROR:"cedros:payment:error"};function Dn(e,t){if(typeof window>"u")return;const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!1});window.dispatchEvent(r)}function $n(e,t,r){Dn(xn.PAYMENT_START,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function Jo(e){Dn(xn.WALLET_CONNECT,{timestamp:Date.now(),wallet:e})}function Pl(e,t){Dn(xn.WALLET_CONNECTED,{timestamp:Date.now(),wallet:e,publicKey:t})}function cs(e,t){Dn(xn.WALLET_ERROR,{timestamp:Date.now(),wallet:t,error:e})}function mn(e,t,r){Dn(xn.PAYMENT_PROCESSING,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function zn(e,t,r,s){Dn(xn.PAYMENT_SUCCESS,{timestamp:Date.now(),method:e,transactionId:t,resource:r,itemCount:s})}function St(e,t,r,s){Dn(xn.PAYMENT_ERROR,{timestamp:Date.now(),method:e,error:t,resource:r,itemCount:s})}class dn 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,dn.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 hs(this.code)}static fromErrorResponse(t,r){const s=t.error.retryable??Al.RETRYABLE.includes(t.error.code);return new dn(t.error.code,t.error.message,s,t.error.details,r)}static fromUnknown(t){return t instanceof dn?t:t instanceof Error?new dn("internal_error",t.message,!1):new dn("internal_error",String(t),!1)}}const Al={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 kf(e){return e instanceof dn&&e.canRetry()}function Sf(e){return e instanceof dn?e.getUserMessage():e instanceof Error?e.message:String(e)}function Cf(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 Nf(e){try{const t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e}}function El(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=Cf(t);if(m.push(u),r){const h=Nf(r);m.includes(h)||m.push(h)}s.forEach(h=>{m.includes(h)||m.push(h)}),m.push(...i);const p=["'self'"];return l&&p.push("https://js.stripe.com","https://checkout.stripe.com"),p.push(...c),{scriptSrc:d,connectSrc:m,frameSrc:p}}function Tl(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 Pf(e={},t="header"){const r=El(e);return Tl(r,t)}const Af={HELIUS:"https://*.helius-rpc.com",QUICKNODE:"https://*.quicknode.pro",ALCHEMY:"https://*.alchemy.com",ANKR:"https://rpc.ankr.com",TRITON:"https://*.rpcpool.com"},Ef={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 Sr(e){return new Date(e).toLocaleString()}function Os(){const{stripeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,transactionId:null}),s=y.useRef(!1),o=y.useCallback(async(c,l,d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const h={resource:c,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p};try{const _=await e.processPayment(h);return r({status:_.success?"success":"error",error:_.success?null:_.error||"Payment failed",transactionId:_.success&&_.transactionId||null}),_}catch(_){const g=_ instanceof Error?_.message:"Payment failed";return r({status:"error",error:g,transactionId:null}),{success:!1,error:g}}finally{s.current=!1}},[e]),a=y.useCallback(async(c,l,d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const h=fs(c);try{const _=await e.processCartCheckout({items:h,successUrl:l,cancelUrl:d,metadata:m,customerEmail:u,couponCode:p});return r({status:_.success?"success":"error",error:_.success?null:_.error||"Cart checkout failed",transactionId:_.success&&_.transactionId||null}),_}catch(_){const g=_ instanceof Error?_.message:"Cart checkout failed";return r({status:"error",error:g,transactionId:null}),{success:!1,error:g}}finally{s.current=!1}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,transactionId:null}),s.current=!1},[]);return{...t,processPayment:o,processCartCheckout:a,reset:i}}function rr(e,t){return y.useMemo(()=>{const r=hf(t),s=e||(t?.length===1?t[0].resource:"");return{isCartMode:r,effectiveResource:s}},[e,t])}const Tf=(e,t,r)=>{const s=e[t];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((o,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},bo=new Map;let Vr=null;async function Qi(e){if(bo.has(e))return bo.get(e);try{const t=await Tf(Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),`./translations/${e}.json`,3),r=t.default||t;return bo.set(e,r),r}catch{return null}}async function If(){if(Vr)return Vr;const e=Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),t=[];for(const r in e){const s=r.match(/\.\/translations\/([a-z]{2,3}(?:-[A-Z]{2})?)\.json$/);s&&t.push(s[1])}return Vr=t.length>0?t:["en"],Vr}function Il(){return typeof navigator>"u"?"en":(navigator.language||navigator.userLanguage||"en").split("-")[0].toLowerCase()}async function Rl(e){let t=await Qi(e);if(t||(t=await Qi("en"),t))return t;throw new Error("Critical: No translation files found, not even en.json")}function Ol(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 Rf(e,t,r=!0){const s=t.errors[e];if(!s){const o=hs(e);return r&&o.action?`${o.message} ${o.action}`:o.message}return r&&s.action?`${s.message} ${s.action}`:s.message}function yn(e){const[t,r]=y.useState(null),[s,o]=y.useState(!0),a=y.useMemo(()=>e||Il(),[e]);return y.useEffect(()=>{let c=!1;return(async()=>{o(!0);try{const d=await Rl(a);c||(r(d),o(!1))}catch(d){console.error("[CedrosPay] Failed to load translations:",d),c||o(!1)}})(),()=>{c=!0}},[a]),{t:y.useMemo(()=>t?Ol(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 Of(e,t=!0){const{translations:r}=yn();if(!r){const o=hs(e);return t&&o.action?`${o.message} ${o.action}`:o.message}const s=r.errors[e];if(!s){const o=hs(e);return t&&o.action?`${o.message} ${o.action}`:o.message}return t&&s.action?`${s.message} ${s.action}`:s.message}function Pa({resource:e,items:t,successUrl:r,cancelUrl:s,metadata:o,customerEmail:a,couponCode:i,label:c,disabled:l=!1,onAttempt:d,onSuccess:m,onError:u,className:p=""}){const{status:h,error:_,transactionId:g,processPayment:f,processCartCheckout:w}=Os(),j=J.useCedrosTheme(),{isCartMode:b,effectiveResource:v}=rr(e,t),{t:k,translations:R}=yn(),N=c||k("ui.pay_with_card"),C=j.unstyled?p:`${j.className} cedros-theme__stripe-button ${p}`.trim(),T=_&&typeof _!="string"?_?.code??null:null,$=_?typeof _=="string"?_:(E=>{if(!E||!R)return"";const P=R.errors[E];return P?P.action?`${P.message} ${P.action}`:P.message:""})(T):null,S=y.useCallback(async()=>{J.getLogger().debug("[StripeButton] executePayment with couponCode:",i);const E=b&&t?un(t):void 0;if($n("stripe",v,E),d&&d("stripe"),!b&&!v){const z="Invalid payment configuration: missing resource or items";J.getLogger().error("[StripeButton]",z),St("stripe",z,v,E),u&&u(z);return}let P;mn("stripe",v,E),b&&t?(J.getLogger().debug("[StripeButton] Processing cart checkout with coupon:",i),P=await w(t,r,s,o,a,i)):v&&(J.getLogger().debug("[StripeButton] Processing single payment with coupon:",i),P=await f(v,r,s,o,a,i)),P&&P.success&&P.transactionId?(zn("stripe",P.transactionId,v,E),m&&m(P.transactionId)):P&&!P.success&&P.error&&(St("stripe",P.error,v,E),u&&u(P.error))},[i,b,v,t,r,s,o,a,w,f,d,m,u]),A=y.useMemo(()=>b&&t?`stripe-cart-${t.map(E=>E.resource).join("-")}`:`stripe-${v||"unknown"}`,[b,t,v]),I=y.useMemo(()=>Ln(A,S),[A,S]),B=h==="loading",L=l||B;return n.jsxs("div",{className:C,style:j.unstyled?{}:j.style,children:[n.jsx("button",{onClick:I,disabled:L,className:j.unstyled?p:"cedros-theme__button cedros-theme__stripe",type:"button",children:B?k("ui.processing"):N}),$&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__error",children:$}),g&&n.jsx("div",{className:j.unstyled?"":"cedros-theme__success",children:k("ui.payment_successful")})]})}function Ml(){const{creditsManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s=y.useRef(!1),o=y.useCallback(async(d,m)=>{r(u=>({...u,status:"loading",error:null}));try{const u=await e.requestQuote(d,m);return r(p=>({...p,status:"idle",requirement:u})),u}catch(u){const p=u instanceof Error?u.message:"Failed to fetch credits quote";return r(h=>({...h,status:"error",error:p})),null}},[e]),a=y.useCallback(async(d,m)=>{r(u=>({...u,status:"loading",error:null}));try{const u=fs(d),p=await e.requestCartQuote(u,m);return r(h=>({...h,status:"idle"})),p}catch(u){const p=u instanceof Error?u.message:"Failed to fetch cart credits quote";return r(h=>({...h,status:"error",error:p})),null}},[e]),i=y.useCallback(async(d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=await e.processPayment(d,m,u,p);return r({status:h.success?"success":"error",error:h.success?null:h.error||"Credits payment failed",transactionId:h.success&&h.transactionId||null,requirement:null,holdId:null}),h}finally{s.current=!1}},[e]),c=y.useCallback(async(d,m,u,p)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const h=fs(d),_=await e.requestCartQuote(h,u);if(!_)return r({status:"error",error:"Credits payment not available for this cart",transactionId:null,requirement:null,holdId:null}),{success:!1,error:"Credits payment not available"};const f=(await e.createCartHold({cartId:_.cartId,authToken:m})).holdId;r(j=>({...j,holdId:f}));const w=await e.authorizeCartPayment({cartId:_.cartId,holdId:f,authToken:m,metadata:p});return r({status:w.success?"success":"error",error:w.success?null:w.error||"Cart credits payment failed",transactionId:w.success&&w.transactionId||null,requirement:null,holdId:null}),{success:w.success,transactionId:w.transactionId,error:w.error}}catch(h){const _=h instanceof Error?h.message:"Cart credits payment failed";return r({status:"error",error:_,transactionId:null,requirement:null,holdId:null}),{success:!1,error:_}}finally{s.current=!1}},[e]),l=y.useCallback(()=>{r({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s.current=!1},[]);return{...t,fetchQuote:o,fetchCartQuote:a,processPayment:i,processCartPayment:c,reset:l}}function Aa({resource:e,items:t,authToken:r,metadata:s,couponCode:o,label:a,disabled:i=!1,onAttempt:c,onSuccess:l,onError:d,className:m=""}){const{status:u,error:p,transactionId:h,processPayment:_,processCartPayment:g}=Ml(),f=J.useCedrosTheme(),{isCartMode:w,effectiveResource:j}=rr(e,t),{t:b,translations:v}=yn(),k=a||b("ui.pay_with_credits")||"Pay with Credits",R=f.unstyled?m:`${f.className} cedros-theme__credits-button ${m}`.trim(),N=p&&typeof p!="string"?p?.code??null:null,T=p?typeof p=="string"?p:(B=>{if(!B||!v)return"";const L=v.errors[B];return L?L.action?`${L.message} ${L.action}`:L.message:""})(N):null,O=y.useCallback(async()=>{J.getLogger().debug("[CreditsButton] executePayment");const B=w&&t?un(t):void 0;if($n("credits",j,B),c&&c("credits"),!r){const E="Authentication required: please log in to pay with credits";J.getLogger().error("[CreditsButton]",E),St("credits",E,j,B),d&&d(E);return}if(!w&&!j){const E="Invalid payment configuration: missing resource";J.getLogger().error("[CreditsButton]",E),St("credits",E,j,B),d&&d(E);return}let L;mn("credits",j,B),w&&t?(J.getLogger().debug("[CreditsButton] Processing cart checkout"),L=await g(t,r,o,s)):j&&(J.getLogger().debug("[CreditsButton] Processing single payment"),L=await _(j,r,o,s)),L&&L.success&&L.transactionId?(zn("credits",L.transactionId,j,B),l&&l(L.transactionId)):L&&!L.success&&L.error&&(St("credits",L.error,j,B),d&&d(L.error))},[r,w,j,t,o,s,_,g,c,l,d]),$=y.useMemo(()=>w&&t?`credits-cart-${t.map(B=>B.resource).join("-")}`:`credits-${j||"unknown"}`,[w,t,j]),S=y.useMemo(()=>Ln($,O),[$,O]),A=u==="loading",I=i||A;return n.jsxs("div",{className:R,style:f.unstyled?{}:f.style,children:[n.jsx("button",{onClick:S,disabled:I,className:f.unstyled?m:"cedros-theme__button cedros-theme__credits",type:"button",children:A?b("ui.processing"):k}),T&&n.jsx("div",{className:f.unstyled?"":"cedros-theme__error",children:T}),h&&n.jsx("div",{className:f.unstyled?"":"cedros-theme__success",children:b("ui.payment_successful")})]})}function Ll(){const{x402Manager:e,walletManager:t}=J.useCedrosContext(),{publicKey:r,signTransaction:s}=ka.useWallet(),[o,a]=y.useState({status:"idle",error:null,transactionId:null}),[i,c]=y.useState(null),[l,d]=y.useState(null),m=y.useRef(!1),u=y.useCallback(()=>{if(!r){const w="Wallet not connected";return a({status:"error",error:w,transactionId:null}),{valid:!1,error:w}}if(!s){const w="Wallet does not support signing";return a({status:"error",error:w,transactionId:null}),{valid:!1,error:w}}return{valid:!0}},[r,s]),p=y.useCallback(async w=>{try{a(b=>({...b,status:"loading"}));const j=await e.requestQuote({resource:w});if(!e.validateRequirement(j))throw new Error("Invalid requirement received from server");return c(j),a(b=>({...b,status:"idle"})),j}catch(j){const b=J.formatError(j,"Failed to fetch requirement");throw a({status:"error",error:b,transactionId:null}),j}},[e]),h=y.useCallback(async(w,j,b,v,k="regular")=>{if(!!w.extra?.feePayer){console.log("⚡ [useX402Payment] GASLESS FLOW - Backend pays fees"),console.log("🔨 [useX402Payment] Requesting backend to build gasless transaction");const{transaction:N,blockhash:C}=await e.buildGaslessTransaction({resourceId:j,userWallet:r.toString(),feePayer:w.extra.feePayer,couponCode:b});console.log("📦 [useX402Payment] Deserializing transaction from backend");const T=t.deserializeTransaction(N);console.log("✍️ [useX402Payment] Requesting wallet to partially sign (transfer authority only)");const O=await t.partiallySignTransaction({transaction:T,signTransaction:s,blockhash:C});console.log("📤 [useX402Payment] Submitting partially-signed transaction to backend");const $=await e.submitGaslessTransaction({resource:j,partialTx:O,couponCode:b,metadata:v,resourceType:k,requirement:w});return $.success&&$.settlement&&d($.settlement),$}else{const N=await t.buildTransaction({requirement:w,payerPublicKey:r}),C=await t.signTransaction({transaction:N,signTransaction:s}),T=t.buildPaymentPayload({requirement:w,signedTx:C,payerPublicKey:r}),O=await e.submitPayment({resource:j,payload:T,couponCode:b,metadata:v,resourceType:k});return O.success&&O.settlement&&d(O.settlement),O}},[r,s,e,t]),_=y.useCallback(async(w,j,b)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const v=u();if(!v.valid)return{success:!1,error:v.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{console.log("🔍 [useX402Payment] Fetching fresh quote for resource:",w);const k=await e.requestQuote({resource:w,couponCode:j});console.log("✅ [useX402Payment] Got quote:",{payTo:k.payTo,amount:k.maxAmountRequired}),c(k),console.log("⚙️ [useX402Payment] Executing payment flow with fresh requirement");const R=await h(k,w,j,b,"regular");return R.success?a({status:"success",error:null,transactionId:R.transactionId||"payment-success"}):a({status:"error",error:R.error||"Payment failed",transactionId:null}),R}catch(k){const R=J.formatError(k,"Payment failed");return a({status:"error",error:R,transactionId:null}),{success:!1,error:R}}finally{m.current=!1}},[u,e,h]),g=y.useCallback(async(w,j,b)=>{if(m.current)return{success:!1,error:"Payment already in progress"};const v=u();if(!v.valid)return{success:!1,error:v.error};m.current=!0,a({status:"loading",error:null,transactionId:null});try{const k=fs(w),R=await e.requestCartQuote({items:k,metadata:j,couponCode:b}),N=R.cartId,C=R.quote;if(!e.validateRequirement(C))throw new Error("Invalid cart quote received from server");c(C);const T=await h(C,N,b,j,"cart");return T.success?a({status:"success",error:null,transactionId:T.transactionId||"cart-payment-success"}):a({status:"error",error:T.error||"Cart payment failed",transactionId:null}),T}catch(k){const R=J.formatError(k,"Cart payment failed");return a({status:"error",error:R,transactionId:null}),{success:!1,error:R}}finally{m.current=!1}},[u,e,h]),f=y.useCallback(()=>{a({status:"idle",error:null,transactionId:null}),c(null),d(null),m.current=!1},[]);return{...o,requirement:i,settlement:l,fetchQuote:p,processPayment:_,processCartPayment:g,reset:f}}function Ea({resource:e,items:t,label:r,disabled:s=!1,onAttempt:o,onSuccess:a,onError:i,className:c="",testPageUrl:l,hideMessages:d=!1,metadata:m,couponCode:u}){const{connected:p,connecting:h,connect:_,disconnect:g,select:f,wallets:w,wallet:j,publicKey:b}=ka.useWallet(),{status:v,error:k,transactionId:R,processPayment:N,processCartPayment:C}=Ll(),T=J.useCedrosTheme(),{solanaError:O}=J.useCedrosContext(),{isCartMode:$,effectiveResource:S}=rr(e,t),{t:A,translations:I}=yn(),B=r||A("ui.pay_with_crypto"),L=k&&typeof k!="string"?k?.code??null:null,E=O&&typeof O!="string"?O?.code??null:null,P=te=>{if(!te||!I)return"";const xe=I.errors[te];return xe?xe.action?`${xe.message} ${xe.action}`:xe.message:""},z=k?typeof k=="string"?k:P(L):null,Z=O?typeof O=="string"?O:P(E):null,K=y.useRef(N),D=y.useRef(C);y.useEffect(()=>{K.current=N,D.current=C},[N,C]);const W=y.useMemo(()=>w.map(te=>`${te.adapter.name}-${te.readyState}`).join(","),[w]),Y=y.useMemo(()=>w.filter(({readyState:te})=>te===Zi.WalletReadyState.Installed||te===Zi.WalletReadyState.Loadable),[W]);y.useEffect(()=>{if(v==="success"&&R){const te=$&&t?un(t):void 0;zn("crypto",R,S,te),a&&a(R)}},[v,R,a,$,t,S]),y.useEffect(()=>{if(v==="error"&&k){const te=$&&t?un(t):void 0;St("crypto",k,S,te),i&&i(k)}},[v,k,i,$,t,S]);const V=typeof window<"u"&&window.top!==window.self,[ce,F]=y.useState(!1),[ee,pe]=y.useState(!1),[q,ne]=y.useState(null),le=O;y.useEffect(()=>{let te=!1;return te||(async()=>{if(ee&&j&&!p&&!h){J.getLogger().debug("[CryptoButton] Wallet detected, attempting auto-connect:",j.adapter.name),pe(!1),Jo(j.adapter.name);try{await _(),te||J.getLogger().debug("[CryptoButton] Auto-connect successful")}catch(ge){if(!te){J.getLogger().error("[CryptoButton] Auto-connect failed:",ge);const ut=ge instanceof Error?ge.message:"Failed to connect wallet";cs(ut,j.adapter.name),ne(null)}}}})(),()=>{te=!0}},[j,ee,p,h,_]),y.useEffect(()=>{if(J.getLogger().debug("[CryptoButton] Payment useEffect triggered",{connected:p,hasPendingPayment:!!q,hasPublicKey:!!b,pendingPaymentType:q?.type}),p&&q&&b&&j){Pl(j.adapter.name,b.toString()),J.getLogger().debug("[CryptoButton] All conditions met! Processing pending payment:",q);const te=q;ne(null),F(!1);const xe=te.type==="cart"&&te.items?un(te.items):void 0;mn("crypto",te.resource,xe),te.type==="cart"&&te.items?(J.getLogger().debug("[CryptoButton] Auto-processing cart payment"),D.current(te.items,te.metadata,te.couponCode)):te.type==="single"&&te.resource&&(J.getLogger().debug("[CryptoButton] Auto-processing single payment"),K.current(te.resource,te.couponCode,te.metadata))}},[p,q,b,j]);const fe=y.useCallback(async()=>{J.getLogger().debug("[CryptoButton] executePaymentFlow called",{connected:p,wallet:j?.adapter.name,couponCode:u,isCartMode:$,hasItems:!!t,effectiveResource:S});const te=$&&t?un(t):void 0;if($n("crypto",S,te),o&&o("crypto"),le){J.getLogger().error("[CryptoButton] Solana dependencies missing:",le),St("crypto",le,S,te),i&&i(le);return}if(V){const xe=l||window.location.href;try{if(new URL(xe,window.location.origin).origin!==window.location.origin)throw J.getLogger().error("[CryptoButton] Blocked attempt to open external URL:",xe),new Error("Cannot open external URLs from embedded context");window.open(xe,"_blank","noopener,noreferrer")}catch(ge){throw J.getLogger().error("[CryptoButton] URL validation failed:",ge),ge}return}if(p)mn("crypto",S,te),$&&t?(J.getLogger().debug("[CryptoButton] Processing cart payment with coupon:",u),await C(t,m,u)):S&&(J.getLogger().debug("[CryptoButton] Processing single payment with coupon:",u),await N(S,u,m));else{let xe=!1;if($&&t?(J.getLogger().debug("[CryptoButton] Setting pending cart payment with coupon:",u),ne({type:"cart",items:t,metadata:m,couponCode:u}),xe=!0):S&&(J.getLogger().debug("[CryptoButton] Setting pending single payment with coupon:",u),ne({type:"single",resource:S,metadata:m,couponCode:u}),xe=!0),!xe){J.getLogger().error("[CryptoButton] No valid payment to process");return}try{if(j)J.getLogger().debug("[CryptoButton] Wallet already selected, connecting:",j.adapter.name),Jo(j.adapter.name),await _();else{if(J.getLogger().debug("[CryptoButton] No wallet selected, showing selector. Available wallets:",Y.map(ge=>ge.adapter.name)),Y.length===0){ne(null);const ge="No wallets available";throw cs(ge),new Error(ge)}F(!0)}}catch(ge){ne(null);const ut=ge instanceof Error?ge.message:"Failed to connect wallet";J.getLogger().error("[CryptoButton] Connection error:",ut),cs(ut,j?.adapter.name)}}},[p,j,u,$,t,S,V,l,Y,_,m,C,N,le,o,i]),Pe=y.useMemo(()=>$&&t?`crypto-cart-${t.map(te=>te.resource).join("-")}`:`crypto-${S||"unknown"}`,[$,t,S]),qe=y.useMemo(()=>Ln(Pe,fe,{cooldownMs:200,deduplicationWindowMs:0}),[Pe,fe]),He=v==="loading",Ze=s||He||h||!!le,xt=He?A("ui.processing"):B,Qe=y.useCallback(async()=>{try{pe(!1),p&&await g(),f(null),F(!0)}catch(te){J.getLogger().error("Failed to change wallet:",te)}},[p,g,f]),Ft=y.useCallback(te=>{J.getLogger().debug("[CryptoButton] Wallet clicked:",te),F(!1),f(te),pe(!0),J.getLogger().debug("[CryptoButton] Wallet selected, useEffect will auto-connect")},[f]),dt=y.useCallback(async()=>{try{if(await g(),ne(null),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(te){te instanceof Error&&te.name==="QuotaExceededError"?J.getLogger().warn("localStorage quota exceeded when removing wallet preference"):J.getLogger().error("Failed to clear wallet preference from localStorage:",te)}}catch(te){J.getLogger().error("Failed to disconnect wallet:",te)}},[g]);return n.jsxs("div",{className:T.unstyled?c:`${T.className} cedros-theme__crypto-button ${c||""}`,style:T.unstyled?{}:T.style,children:[n.jsx("button",{onClick:qe,disabled:Ze,className:T.unstyled?c:"cedros-theme__button cedros-theme__crypto",type:"button",children:xt}),ce&&!d&&n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:T.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>F(!1),children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:T.tokens.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${T.tokens.modalBorder}`},onClick:te=>te.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:T.tokens.surfaceText},children:A("wallet.select_wallet")}),n.jsx("button",{onClick:()=>F(!1),style:Na(T.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:Y.map(te=>n.jsxs("button",{onClick:()=>Ft(te.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:T.tokens.surfaceBackground,border:`1px solid ${T.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:T.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:xe=>{xe.currentTarget.style.backgroundColor=T.tokens.modalBackground,xe.currentTarget.style.borderColor=T.tokens.surfaceText,xe.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:xe=>{xe.currentTarget.style.backgroundColor=T.tokens.surfaceBackground,xe.currentTarget.style.borderColor=T.tokens.surfaceBorder,xe.currentTarget.style.transform="translateY(0)"},type:"button",children:[n.jsx(lf.WalletIcon,{wallet:te,style:{width:"24px",height:"24px"}}),n.jsx("span",{style:{fontWeight:500},children:te.adapter.name})]},te.adapter.name))})]})}),p&&!d&&!ce&&n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:T.tokens.surfaceText,opacity:.7},children:[n.jsx("button",{onClick:Qe,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:"Change Wallet"}),n.jsx("button",{onClick:dt,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:A("ui.disconnect")})]}),!d&&Z&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__error",children:Z}),!d&&z&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__error",children:z}),!d&&R&&n.jsx("div",{className:T.unstyled?"":"cedros-theme__success",children:A("ui.payment_successful")})]})}const Mf=Object.freeze(Object.defineProperty({__proto__:null,CryptoButton:Ea},Symbol.toStringTag,{value:"Module"})),Dl=({isOpen:e,onClose:t,resource:r,items:s,cardLabel:o="Card",cryptoLabel:a="USDC (Solana)",creditsLabel:i="Pay with Credits",showCard:c=!0,showCrypto:l=!0,showCredits:d=!1,onPaymentAttempt:m,onPaymentSuccess:u,onPaymentError:p,onStripeSuccess:h,onCryptoSuccess:_,onCreditsSuccess:g,onStripeError:f,onCryptoError:w,onCreditsError:j,customerEmail:b,successUrl:v,cancelUrl:k,metadata:R,couponCode:N,authToken:C,testPageUrl:T,hideMessages:O=!1})=>{const{tokens:$}=J.useCedrosTheme();return y.useEffect(()=>{const S=A=>{A.key==="Escape"&&e&&t()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[e,t]),y.useEffect(()=>{if(e){const S=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${S}px`,document.body.style.width="100%",document.body.style.overflowY="scroll",()=>{const A=document.body.style.top?Math.abs(parseInt(document.body.style.top.replace("px",""),10)):0;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflowY="",window.scrollTo(0,A)}}},[e]),e?n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:$.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:t,children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:$.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${$.modalBorder}`},onClick:S=>S.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:$.surfaceText},children:"Choose Payment Method"}),n.jsx("button",{onClick:t,style:Na($.surfaceText),"aria-label":"Close modal",children:"×"})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[c&&n.jsx(Pa,{resource:r,items:s,label:o,onAttempt:m,onSuccess:h||u,onError:f||p,customerEmail:b,successUrl:v,cancelUrl:k,metadata:R,couponCode:N}),l&&n.jsx(Ea,{resource:r,items:s,label:a,onAttempt:m,onSuccess:_||u,onError:w||p,testPageUrl:T,hideMessages:O,metadata:R,couponCode:N}),d&&n.jsx(Aa,{resource:r,items:s,label:i,authToken:C,onAttempt:m?()=>m("credits"):void 0,onSuccess:g||u,onError:j||p,metadata:R,couponCode:N})]})]})}):null},$l=({resource:e,items:t,label:r,cardLabel:s,cryptoLabel:o,creditsLabel:a,showCard:i=!0,showCrypto:c=!0,showCredits:l=!1,onPaymentAttempt:d,onPaymentSuccess:m,onPaymentError:u,onStripeSuccess:p,onCryptoSuccess:h,onCreditsSuccess:_,onStripeError:g,onCryptoError:f,onCreditsError:w,customerEmail:j,successUrl:b,cancelUrl:v,metadata:k,couponCode:R,authToken:N,autoDetectWallets:C=!0,testPageUrl:T,hideMessages:O=!1,renderModal:$})=>{const S=J.useCedrosTheme(),[A,I]=y.useState(!1),{status:B,processPayment:L,processCartCheckout:E}=Os(),{isCartMode:P,effectiveResource:z}=rr(e,t),{t:Z}=yn(),K=r||Z("ui.purchase"),D=s||Z("ui.card"),W=o||Z("ui.usdc_solana"),Y=a||Z("ui.pay_with_credits")||"Pay with Credits",V=y.useCallback(async()=>{if(C&&i){const{detectSolanaWallets:q}=await Promise.resolve().then(()=>ZC);if(!q()){const ne=P?void 0:z,le=P&&t?un(t):void 0;$n("stripe",ne,le),d&&d("stripe"),mn("stripe",ne,le);let fe;P&&t?fe=await E(t,b,v,k,j,R):z&&(fe=await L(z,b,v,k,j,R)),fe&&fe.success&&fe.transactionId?(zn("stripe",fe.transactionId,ne,le),p?p(fe.transactionId):m&&m(fe.transactionId)):fe&&!fe.success&&fe.error&&(St("stripe",fe.error,ne,le),g?g(fe.error):u&&u(fe.error));return}}I(!0)},[C,i,P,t,z,E,L,b,v,k,j,R,m,u,p,g,d]),ce=y.useMemo(()=>P&&t?`purchase-cart-${t.map(q=>q.resource).join("-")}`:`purchase-${z||"unknown"}`,[P,t,z]),F=y.useMemo(()=>Ln(ce,V),[ce,V]),ee=B==="loading",pe={isOpen:A,onClose:()=>I(!1),resource:P?void 0:z,items:P?t:void 0,cardLabel:D,cryptoLabel:W,creditsLabel:Y,showCard:i,showCrypto:c,showCredits:l,onPaymentAttempt:d,onPaymentSuccess:q=>{I(!1),m?.(q)},onPaymentError:q=>{I(!1),u?.(q)},onStripeSuccess:q=>{I(!1),p?.(q)},onCryptoSuccess:q=>{I(!1),h?.(q)},onCreditsSuccess:q=>{I(!1),_?.(q)},onStripeError:q=>{I(!1),g?.(q)},onCryptoError:q=>{I(!1),f?.(q)},onCreditsError:q=>{I(!1),w?.(q)},customerEmail:j,successUrl:b,cancelUrl:v,metadata:k,couponCode:R,authToken:N,testPageUrl:T,hideMessages:O};return n.jsxs("div",{className:S.unstyled?"":S.className,style:S.unstyled?{}:S.style,children:[n.jsx("button",{onClick:F,disabled:ee,className:S.unstyled?"":"cedros-theme__button cedros-theme__stripe",style:{width:"100%",cursor:ee?"not-allowed":"pointer",opacity:ee?.6:1},type:"button",children:ee?Z("ui.processing"):K}),$?$(pe):n.jsx(Dl,{...pe})]})},Lf={"mainnet-beta":"https://api.mainnet-beta.solana.com",devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com"};function Df(){const[e,t]=y.useState(null);return y.useEffect(()=>{let r=!1;return import("@solana/wallet-adapter-react").then(s=>{r||t(s)}),()=>{r=!0}},[]),e}function $f({endpoint:e,wallets:t,children:r}){const s=Df();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 zf=y.lazy(()=>Promise.resolve().then(()=>Mf).then(e=>({default:e.CryptoButton})));function Ff(e){const{resource:t,items:r,checkout:s={},display:o={},callbacks:a={},advanced:i={}}=e,{config:c,walletPool:l}=J.useCedrosContext(),d=J.useCedrosTheme(),{isCartMode:m}=rr(t,r),u=o.showCrypto??!0,p=y.useMemo(()=>({marginTop:"0.5rem",fontSize:"0.875rem",color:d.tokens.surfaceText,opacity:.7,textAlign:"center"}),[d.tokens.surfaceText]),h=y.useMemo(()=>u?i.wallets&&i.wallets.length>0?i.wallets:l.getAdapters():[],[i.wallets,l,u]),_=y.useMemo(()=>r?un(r):0,[r]),g=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"stripe"}):void 0,[a.onPaymentSuccess]),f=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"crypto"}):void 0,[a.onPaymentSuccess]),w=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"stripe"}):void 0,[a.onPaymentError]),j=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"crypto"}):void 0,[a.onPaymentError]),b=y.useMemo(()=>a.onPaymentSuccess?I=>a.onPaymentSuccess({transactionId:I,method:"credits"}):void 0,[a.onPaymentSuccess]),v=y.useMemo(()=>a.onPaymentError?I=>a.onPaymentError({message:I,method:"credits"}):void 0,[a.onPaymentError]),k=y.useMemo(()=>a.onPaymentAttempt?()=>a.onPaymentAttempt("credits"):void 0,[a.onPaymentAttempt]),R=u?c.solanaEndpoint??Lf[c.solanaCluster]:"";if(!t&&(!r||r.length===0))return J.getLogger().error('CedrosPay: Must provide either "resource" or "items" prop'),n.jsx("div",{className:o.className,style:{color:d.tokens.errorText},children:"Configuration error: No resource or items provided"});const N=o.showCard??!0,C=o.showCredits??!1,T=o.showPurchaseButton??!1,O=o.layout??"vertical",$=o.hideMessages??!1,S=i.autoDetectWallets??!0,A=n.jsx("div",{className:d.unstyled?o.className:`cedros-theme__pay ${o.className||""}`,children:n.jsxs("div",{className:d.unstyled?"":`cedros-theme__pay-content cedros-theme__pay-content--${O}`,children:[T?n.jsx($l,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,label:o.purchaseLabel,cardLabel:o.cardLabel,cryptoLabel:o.cryptoLabel,showCard:N,showCrypto:u,onPaymentAttempt:a.onPaymentAttempt,onPaymentSuccess:g,onPaymentError:w,onStripeSuccess:g,onCryptoSuccess:f,onStripeError:w,onCryptoError:j,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,autoDetectWallets:S,testPageUrl:i.testPageUrl,hideMessages:$,renderModal:o.renderModal}):n.jsxs(n.Fragment,{children:[N&&n.jsx(Pa,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,label:o.cardLabel,onAttempt:a.onPaymentAttempt,onSuccess:g,onError:w}),u&&n.jsx(y.Suspense,{fallback:null,children:n.jsx(zf,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,metadata:s.metadata,couponCode:s.couponCode,label:o.cryptoLabel,onAttempt:a.onPaymentAttempt,onSuccess:f,onError:j,testPageUrl:i.testPageUrl,hideMessages:$})}),C&&n.jsx(Aa,{resource:m?void 0:t||r?.[0]?.resource,items:m?r:void 0,authToken:s.authToken,metadata:s.metadata,couponCode:s.couponCode,label:o.creditsLabel,onAttempt:k,onSuccess:b,onError:v})]}),m&&r&&r.length>1&&!$&&n.jsxs("div",{style:p,children:["Checking out ",_," items"]})]})});return n.jsx("div",{className:d.unstyled?o.className:d.className,style:d.unstyled?{}:d.style,children:u?n.jsx($f,{endpoint:R,wallets:h,children:A}):A})}const Q={products:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),n.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),n.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),n.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),n.jsx("path",{d:"M3 3v5h5"}),n.jsx("path",{d:"M12 7v5l4 2"})]}),settings:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),n.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"}),n.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),n.jsx("path",{d:"M8 16H3v5"})]}),check:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})}),plus:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),n.jsx("path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9"}),n.jsx("path",{d:"M12 3v6"})]}),arrowUp:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7-7 7 7"}),n.jsx("path",{d:"M12 19V5"})]}),arrowDown:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7 7 7-7"}),n.jsx("path",{d:"M12 5v14"})]}),delete:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),n.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),faq:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),n.jsx("path",{d:"M12 17h.01"})]}),chat:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),n.jsx("path",{d:"M2 12h20"})]}),ai:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),n.jsx("path",{d:"M10 10v.5"}),n.jsx("path",{d:"M14 10v.5"}),n.jsx("path",{d:"M12 14v2"}),n.jsx("path",{d:"M8 18h8"}),n.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),n.jsx("path",{d:"M6 12v6"}),n.jsx("path",{d:"M18 12v6"})]}),notifications:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),n.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),n.jsx("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),n.jsx("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),n.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),n.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),n.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),n.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),n.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),n.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),n.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),n.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),n.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),n.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),n.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),n.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),n.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),n.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),n.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),n.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),n.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),n.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function Kt({message:e,onRetry:t}){return e?n.jsxs("div",{className:"cedros-admin__error-banner",children:[n.jsx("span",{children:e}),t&&n.jsxs("button",{type:"button",className:"cedros-admin__error-banner-retry",onClick:t,children:[Q.refresh," Retry"]})]}):null}function sr({stats:e,isLoading:t=!1,onRefresh:r}){return n.jsxs("div",{className:"cedros-admin__stats-bar",children:[n.jsx("div",{className:"cedros-admin__stats-bar-grid",children:e.map((s,o)=>n.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[n.jsx("span",{className:"cedros-admin__stats-bar-label",children:s.label}),n.jsx("span",{className:`cedros-admin__stats-bar-value ${s.variant?`cedros-admin__stats-bar-value--${s.variant}`:""}`,children:t?n.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):s.value}),s.description&&n.jsx("span",{className:"cedros-admin__stats-bar-desc",children:s.description})]},o))}),r&&n.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:r,disabled:t,title:"Refresh stats",children:t?Q.loading:Q.refresh})]})}function Bf({serverUrl:e,productId:t,apiKey:r,authManager:s}){const[o,a]=y.useState(null),[i,c]=y.useState(!1),[l,d]=y.useState(!1),[m,u]=y.useState(null),p=y.useCallback(async()=>{if(t){c(!0),u(null);try{let g;if(s?.isAuthenticated())g=await s.fetchWithAuth(`/admin/products/${t}/variations`);else{const f={"Content-Type":"application/json"};r&&(f["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variations`,{headers:f});if(!w.ok)throw new Error(`Failed to fetch variations: ${w.status}`);g=await w.json()}g.variationConfig||(g.variationConfig={variationTypes:[]}),g.variants||(g.variants=[]),a(g)}catch(g){const f=g instanceof Error?g.message:"Failed to fetch variations";u(f),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,r,s]),h=y.useCallback(async g=>{if(!t)return null;d(!0),u(null);try{let f;if(s?.isAuthenticated())f=await s.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(g)});else{const w={"Content-Type":"application/json"};r&&(w["X-API-Key"]=r);const j=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:w,body:JSON.stringify(g)});if(!j.ok)throw new Error(`Failed to save variations: ${j.status}`);f=await j.json()}return a({productId:t,variationConfig:f.variationConfig,variants:f.variants}),{variantsCreated:f.variantsCreated}}catch(f){const w=f instanceof Error?f.message:"Failed to save variations";return u(w),null}finally{d(!1)}},[e,t,r,s]),_=y.useCallback(async g=>{if(!t||g.length===0)return!1;d(!0),u(null);try{if(s?.isAuthenticated())await s.fetchWithAuth(`/admin/products/${t}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:g})});else{const f={"Content-Type":"application/json"};r&&(f["X-API-Key"]=r);const w=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:f,body:JSON.stringify({updates:g})});if(!w.ok)throw new Error(`Failed to update inventory: ${w.status}`)}if(o){const f=new Map(g.map(w=>[w.variantId,w]));a({...o,variants:o.variants.map(w=>{const j=f.get(w.id);return j?{...w,inventoryQuantity:j.inventoryQuantity,inventoryStatus:j.inventoryStatus??w.inventoryStatus}:w})})}return!0}catch(f){const w=f instanceof Error?f.message:"Failed to update inventory";return u(w),!1}finally{d(!1)}},[e,t,r,s,o]);return{data:o,isLoading:i,error:m,fetch:p,save:h,bulkUpdateInventory:_,isSaving:l}}function Yi(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Uf({value:e,onChange:t,maxTypes:r=5,maxValuesPerType:s=20,disabled:o=!1}){const[a,i]=y.useState(null),[c,l]=y.useState(""),[d,m]=y.useState({}),u=e.variationTypes,p=y.useCallback(()=>{if(!c.trim()||u.length>=r)return;const b={id:Yi(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,b]}),l(""),i(b.id)},[c,u,r,t]),h=y.useCallback(b=>{t({variationTypes:u.filter(v=>v.id!==b).map((v,k)=>({...v,displayOrder:k}))}),a===b&&i(null)},[u,t,a]),_=y.useCallback((b,v)=>{t({variationTypes:u.map(k=>k.id===b?{...k,name:v}:k)})},[u,t]),g=y.useCallback((b,v)=>{const k=u.findIndex(C=>C.id===b);if(k===-1||v==="up"&&k===0||v==="down"&&k===u.length-1)return;const R=[...u],N=v==="up"?k-1:k+1;[R[k],R[N]]=[R[N],R[k]],t({variationTypes:R.map((C,T)=>({...C,displayOrder:T}))})},[u,t]),f=y.useCallback(b=>{const v=(d[b]||"").trim();if(!v)return;const k=u.find(N=>N.id===b);if(!k||k.values.length>=s)return;const R={id:Yi(),label:v};t({variationTypes:u.map(N=>N.id===b?{...N,values:[...N.values,R]}:N)}),m(N=>({...N,[b]:""}))},[u,d,s,t]),w=y.useCallback((b,v)=>{t({variationTypes:u.map(k=>k.id===b?{...k,values:k.values.filter(R=>R.id!==v)}:k)})},[u,t]),j=y.useCallback((b,v,k)=>{t({variationTypes:u.map(R=>R.id===b?{...R,values:R.values.map(N=>N.id===v?{...N,label:k}:N)}:R)})},[u,t]);return n.jsxs("div",{className:"cedros-admin__variation-editor",children:[n.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[u.length,"/",r," types"]})]}),u.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):n.jsx("div",{className:"cedros-admin__variation-type-list",children:u.map((b,v)=>n.jsxs("div",{className:"cedros-admin__variation-type-item",children:[n.jsxs("div",{className:"cedros-admin__variation-type-header",children:[n.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(b.id,"up"),disabled:o||v===0,title:"Move up",children:Q.arrowUp}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(b.id,"down"),disabled:o||v===u.length-1,title:"Move down",children:Q.arrowDown})]}),n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:b.name,onChange:k=>_(b.id,k.target.value),disabled:o,placeholder:"Type name"}),n.jsxs("span",{className:"cedros-admin__variation-value-count",children:[b.values.length," values"]}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===b.id?null:b.id),children:a===b.id?"Collapse":"Edit values"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>h(b.id),disabled:o,title:"Remove type",children:Q.delete})]}),a===b.id&&n.jsxs("div",{className:"cedros-admin__variation-values",children:[n.jsxs("div",{className:"cedros-admin__variation-values-header",children:[n.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',b.name,'"']}),n.jsxs("span",{style:{fontSize:11,opacity:.7},children:[b.values.length,"/",s]})]}),b.values.length===0?n.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):n.jsx("div",{className:"cedros-admin__variation-value-list",children:b.values.map(k=>n.jsxs("div",{className:"cedros-admin__variation-value-item",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:k.label,onChange:R=>j(b.id,k.id,R.target.value),disabled:o}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>w(b.id,k.id),disabled:o,title:"Remove value",children:Q.close})]},k.id))}),b.values.length<s&&n.jsxs("div",{className:"cedros-admin__variation-add-value",children:[n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:d[b.id]||"",onChange:k=>m(R=>({...R,[b.id]:k.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),f(b.id))}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>f(b.id),disabled:o||!d[b.id]?.trim(),children:"Add"})]})]})]},b.id))}),u.length<r&&n.jsxs("div",{className:"cedros-admin__variation-add-type",children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:b=>l(b.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),p())}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:p,disabled:o||!c.trim(),children:"Add Type"})]})]})}function zl({value:e,onChange:t,options:r,placeholder:s="Filter",disabled:o}){const[a,i]=y.useState(!1),c=y.useRef(null),d=r.find(m=>m.value===e)?.label||s;return y.useEffect(()=>{const m=u=>{c.current&&!c.current.contains(u.target)&&i(!1)};if(a)return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[a]),y.useEffect(()=>{const m=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[a]),n.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[n.jsx("span",{children:d}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:Q.chevronDown})]}),a&&n.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:r.map(m=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${m.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{m.disabled||(t(m.value),i(!1))},role:"option","aria-selected":m.value===e,disabled:m.disabled,children:[m.label,m.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:Q.check})]},m.value))})]})}function at({value:e,onChange:t,options:r,label:s,description:o,disabled:a,className:i,style:c}){const[l,d]=y.useState(!1),m=y.useRef(null),p=r.find(h=>h.value===e)?.label||"Select...";return y.useEffect(()=>{const h=_=>{m.current&&!m.current.contains(_.target)&&d(!1)};if(l)return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[l]),y.useEffect(()=>{const h=_=>{_.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[l]),n.jsxs("div",{className:`cedros-admin__field ${i||""}`,style:c,children:[n.jsx("label",{className:"cedros-admin__field-label",children:s}),n.jsxs("div",{className:"cedros-admin__dropdown cedros-admin__dropdown--form",ref:m,children:[n.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger cedros-admin__dropdown-trigger--form",onClick:()=>!a&&d(!l),"aria-expanded":l,"aria-haspopup":"listbox",disabled:a,children:[n.jsx("span",{children:p}),n.jsx("span",{className:`cedros-admin__dropdown-chevron ${l?"cedros-admin__dropdown-chevron--open":""}`,children:Q.chevronDown})]}),l&&n.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:r.map(h=>n.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${h.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{h.disabled||(t(h.value),d(!1))},role:"option","aria-selected":h.value===e,disabled:h.disabled,children:[h.label,h.value===e&&n.jsx("span",{className:"cedros-admin__dropdown-check",children:Q.check})]},h.value))})]}),o&&n.jsx("p",{className:"cedros-admin__field-description",children:o})]})}function Ki(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Wf(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 Vf(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 qf({variationConfig:e,variants:t,onChange:r,defaultPrice:s=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=y.useMemo(()=>Wf(e.variationTypes),[e.variationTypes]),l=y.useMemo(()=>{const g=new Map;for(const f of t)g.set(Vf(f),f);return g},[t]),{existingRows:d,possibleRows:m}=y.useMemo(()=>{const g=[],f=[];for(const w of c){const j=l.get(w.key);j?g.push({combo:w,variant:j}):f.push(w)}return{existingRows:g,possibleRows:f}},[c,l]),u=y.useCallback((g,f)=>{r(t.map(w=>w.id===g?{...w,...f}:w))},[t,r]),p=y.useCallback(g=>{r(t.filter(f=>f.id!==g))},[t,r]),h=y.useCallback(g=>{if(t.length>=a)return;const f={id:Ki(),title:g.title,options:g.options,optionValueIds:g.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};r([...t,f])},[t,r,a,s]),_=y.useCallback(()=>{const g=a-t.length,w=m.slice(0,g).map(j=>({id:Ki(),title:j.title,options:j.options,optionValueIds:j.optionValueIds,price:s,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));r([...t,...w])},[t,r,m,a,s]);return e.variationTypes.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):c.length===0?n.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):n.jsxs("div",{className:"cedros-admin__variant-grid",children:[n.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[n.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),n.jsxs("span",{style:{fontSize:12,opacity:.7},children:[t.length,"/",a," variants (",c.length," ","possible)"]})]}),m.length>0&&t.length<a&&n.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[n.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:_,disabled:i,children:["Generate All (",Math.min(m.length,a-t.length),")"]}),n.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{children:"Variant"}),n.jsx("th",{style:{width:100},children:"Price"}),n.jsx("th",{style:{width:80},children:"Qty"}),n.jsx("th",{style:{width:100},children:"SKU"}),n.jsx("th",{style:{width:100},children:"Status"}),n.jsx("th",{style:{width:80},children:"Actions"})]})}),n.jsxs("tbody",{children:[d.map(({combo:g,variant:f})=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:g.title}),n.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(g.options).map(([w,j])=>`${w}: ${j}`).join(", ")})]})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx("span",{children:o}),n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:f.price??"",onChange:w=>u(f.id,{price:w.target.value===""?void 0:parseFloat(w.target.value)||0}),disabled:i,min:"0",step:"0.01",style:{width:70}})]})}),n.jsx("td",{children:n.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:f.inventoryQuantity??"",onChange:w=>u(f.id,{inventoryQuantity:w.target.value===""?void 0:parseInt(w.target.value)||0}),disabled:i,min:"0",style:{width:60}})}),n.jsx("td",{children:n.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:f.sku??"",onChange:w=>u(f.id,{sku:w.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),n.jsx("td",{children:n.jsx(zl,{value:f.inventoryStatus??"in_stock",onChange:w=>u(f.id,{inventoryStatus:w}),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],disabled:i})}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>p(f.id),disabled:i,title:"Remove variant",children:Q.trash})})]},f.id)),m.length>0&&t.length<a&&n.jsxs(n.Fragment,{children:[n.jsx("tr",{className:"cedros-admin__variant-separator",children:n.jsx("td",{colSpan:6,children:n.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",m.length,")"]})})}),m.slice(0,10).map(g=>n.jsxs("tr",{className:"cedros-admin__variant-possible",children:[n.jsx("td",{children:n.jsx("span",{style:{opacity:.6},children:g.title})}),n.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),n.jsx("td",{children:n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>h(g),disabled:i,title:"Create variant",children:Q.plus})})]},g.key)),m.length>10&&n.jsx("tr",{className:"cedros-admin__variant-more",children:n.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",m.length-10," more combinations"]})})]})]})]})})]})}function Hf({serverUrl:e,productId:t,productTitle:r,defaultPrice:s=0,currencySymbol:o="$",apiKey:a,authManager:i,onClose:c}){const{data:l,isLoading:d,error:m,fetch:u,save:p,isSaving:h}=Bf({serverUrl:e,productId:t,apiKey:a,authManager:i}),[_,g]=y.useState({variationTypes:[]}),[f,w]=y.useState([]),[j,b]=y.useState(!1),[v,k]=y.useState(!1);y.useEffect(()=>{u()},[u]),y.useEffect(()=>{l&&(g(l.variationConfig),w(l.variants),b(!1))},[l]);const R=y.useCallback(T=>{g(T),b(!0),k(!1)},[]),N=y.useCallback(T=>{w(T),b(!0),k(!1)},[]),C=y.useCallback(async()=>{const T=new Set((l?.variants??[]).map(I=>I.id)),O=f.filter(I=>!T.has(I.id)),$=f.filter(I=>T.has(I.id)),S=(l?.variants??[]).filter(I=>!f.some(B=>B.id===I.id)).map(I=>I.id);await p({variationConfig:_,createVariants:O.map(I=>({optionValueIds:I.optionValueIds??[],inventoryQuantity:I.inventoryQuantity,sku:I.sku,price:I.price})),updateVariants:$.map(I=>({id:I.id,inventoryQuantity:I.inventoryQuantity,sku:I.sku,price:I.price,inventoryStatus:I.inventoryStatus})),deleteVariantIds:S.length>0?S:void 0})&&(b(!1),k(!0),setTimeout(()=>k(!1),3e3))},[_,f,l?.variants,p]);return d?n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading variations..."]})]}):n.jsxs("div",{className:"cedros-admin__variations-editor",children:[n.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:r?`Variations: ${r}`:"Product Variations"}),n.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[v&&n.jsxs("span",{className:"cedros-admin__success-text",children:[Q.check," Saved"]}),j&&n.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:C,disabled:h||!j,children:h?"Saving...":"Save Changes"}),c&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Q.close})]})]}),m&&n.jsx("div",{className:"cedros-admin__error-banner",children:m}),n.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(Uf,{value:_,onChange:R,disabled:h})}),_.variationTypes.length>0&&n.jsx("div",{className:"cedros-admin__variations-editor-section",children:n.jsx(qf,{variationConfig:_,variants:f,onChange:N,defaultPrice:s,currencySymbol:o,disabled:h})})]})]})}function Fl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(!1),[p,h]=y.useState(null),[_,g]=y.useState(null),[f,w]=y.useState(null),[j,b]=y.useState(null),[v,k]=y.useState({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),R=E=>{const P=E.tagsCsv.split(",").map(V=>V.trim()).filter(Boolean),z=E.categoryIdsCsv.split(",").map(V=>V.trim()).filter(Boolean),Z={email:E.checkoutEmail,name:E.checkoutName,phone:E.checkoutPhone,shippingAddress:E.checkoutShippingAddress,billingAddress:E.checkoutBillingAddress},K=E.fulfillmentType==="shipping"?"physical":"digital",D={title:E.title,slug:E.slug||E.id,shipping_profile:K,inventory_status:E.inventoryStatus,checkout_requirements:JSON.stringify(Z),fulfillment_type:E.fulfillmentType};E.imageUrl&&(D.image_url=E.imageUrl);const W=E.compareAtUsd?Math.round(Number(E.compareAtUsd)*100):0;W&&(D.compare_at_amount_cents=String(W)),P.length&&(D.tags=JSON.stringify(P)),z.length&&(D.category_ids=JSON.stringify(z)),E.fulfillmentNotes&&(D.fulfillment_notes=E.fulfillmentNotes);const Y=E.shippingCountriesCsv.split(",").map(V=>V.trim().toUpperCase()).filter(Boolean);return Y.length&&(D.shippingCountries=Y.join(","),D.shipping_countries=Y.join(",")),D},N=E=>E.metadata?.title||E.description||E.id,C=E=>E.metadata?.image_url,T=y.useCallback(async()=>{try{b(null);let E;if(s?.isAuthenticated())E=await s.fetchWithAuth(`/admin/products?limit=${r}`);else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const z=await fetch(`${e}/admin/products?limit=${r}`,{headers:P});if(!z.ok)throw new Error(`Failed to fetch products: ${z.status}`);E=await z.json()}a(E.products||[])}catch{a([]),b("Failed to load products")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{T()},[T]);const O=async E=>{if(E.preventDefault(),!(!v.id||!v.description)){if(h(null),v.fulfillmentType==="shipping"&&v.checkoutShippingAddress&&!v.shippingCountriesCsv.split(",").map(z=>z.trim()).filter(Boolean).length){h("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:P}=v,z=v.inventoryQuantity===""?void 0:Number.isFinite(Number(v.inventoryQuantity))?Number(v.inventoryQuantity):void 0,Z=Number(v.priceUsd)||0,K=Math.round(Z*100),D=Math.round(Z*1e6),W={id:v.id,description:v.description,fiatAmountCents:K,fiatCurrency:v.fiatCurrency,cryptoAtomicAmount:D,cryptoToken:v.cryptoToken,...z!==void 0?{inventoryQuantity:z}:{},metadata:{...P?{product_type:P}:{},...R(v)}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(W)});else{const Y={"Content-Type":"application/json"};t&&(Y["X-API-Key"]=t);const V=await fetch(`${e}/admin/products`,{method:"POST",headers:Y,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to create product: ${V.status}`)}k({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),d(!1),T()}catch(P){h(P instanceof Error?P.message:"Failed to create product")}finally{u(!1)}}},$=E=>`$${(E/100).toFixed(2)}`,S=E=>{switch(E){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},A=y.useMemo(()=>{const E=o.filter(z=>z.active).length,P=o.reduce((z,Z)=>{const K=Z.variations?.length??0;return z+(K>0?K:1)},0);return{activeCount:E,totalSkus:P}},[o]),I=E=>{w(P=>!P||P.key!==E?{key:E,direction:"asc"}:{key:E,direction:P.direction==="asc"?"desc":"asc"})},B=E=>!f||f.key!==E?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:f.direction==="asc"?Q.chevronUp:Q.chevronDown}),L=y.useMemo(()=>{if(!f)return o;const E=f.direction==="asc"?1:-1,P=z=>{switch(f.key){case"product":return N(z);case"type":return S(z.metadata?.product_type);case"price":return z.fiatAmountCents??0;case"status":return z.active?1:0;case"id":default:return z.id}};return[...o].sort((z,Z)=>{const K=P(z),D=P(Z);return typeof K=="number"&&typeof D=="number"?(K-D)*E:String(K).localeCompare(String(D),void 0,{sensitivity:"base"})*E})},[o,f]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Kt,{message:j,onRetry:T}),n.jsx(sr,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:A.activeCount,variant:A.activeCount>0?"success":"muted"},{label:"Total SKUs",value:A.totalSkus}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{h(null),d(!l)},children:[l?Q.close:Q.plus,l?"Cancel":"Add Product"]})]}),l&&n.jsxs("form",{onSubmit:O,className:"cedros-admin__add-form",children:[p&&n.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:p}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.id,onChange:E=>k(P=>({...P,id:E.target.value})),placeholder:"e.g., premium-article",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.title,onChange:E=>k(P=>({...P,title:E.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.slug,onChange:E=>k(P=>({...P,slug:E.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:v.imageUrl,onChange:E=>k(P=>({...P,imageUrl:E.target.value})),placeholder:"https://..."})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.description,onChange:E=>k(P=>({...P,description:E.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(at,{value:v.productType,onChange:E=>k(P=>({...P,productType:E})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"}],label:"Product Type"}),n.jsx(at,{value:v.fulfillmentType,onChange:E=>{const P=E;k(z=>({...z,fulfillmentType:P,checkoutShippingAddress:P==="shipping"?z.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),v.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(at,{value:v.inventoryStatus,onChange:E=>k(P=>({...P,inventoryStatus:E})),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],label:"Inventory status"}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v.inventoryQuantity,onChange:E=>k(P=>({...P,inventoryQuantity:E.target.value===""?"":parseInt(E.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v.compareAtUsd===""?"":v.compareAtUsd,onChange:E=>k(P=>({...P,compareAtUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:v.priceUsd===""?"":v.priceUsd,onChange:E=>k(P=>({...P,priceUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.tagsCsv,onChange:E=>k(P=>({...P,tagsCsv:E.target.value})),placeholder:"e.g., core, new, gift"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.categoryIdsCsv,onChange:E=>k(P=>({...P,categoryIdsCsv:E.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(at,{value:v.checkoutEmail,onChange:E=>k(P=>({...P,checkoutEmail:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),n.jsx(at,{value:v.checkoutName,onChange:E=>k(P=>({...P,checkoutName:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),n.jsx(at,{value:v.checkoutPhone,onChange:E=>k(P=>({...P,checkoutPhone:E})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[v.fulfillmentType==="shipping"&&n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:v.checkoutShippingAddress,onChange:E=>k(P=>({...P,checkoutShippingAddress:E.target.checked}))}),"Collect shipping address"]})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:v.checkoutBillingAddress,onChange:E=>k(P=>({...P,checkoutBillingAddress:E.target.checked}))}),"Collect billing address"]})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.fulfillmentNotes,onChange:E=>k(P=>({...P,fulfillmentNotes:E.target.value})),placeholder:v.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),v.fulfillmentType==="shipping"&&v.checkoutShippingAddress&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:v.shippingCountriesCsv,onChange:E=>k(P=>({...P,shippingCountriesCsv:E.target.value})),placeholder:"e.g., US,CA"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Product"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading products..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("id"),children:["ID",B("id")]})}),n.jsx("th",{"aria-sort":f?.key==="product"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("product"),children:["Product",B("product")]})}),n.jsx("th",{"aria-sort":f?.key==="type"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("type"),children:["Type",B("type")]})}),n.jsx("th",{"aria-sort":f?.key==="price"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("price"),children:["Price",B("price")]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>I("status"),children:["Status",B("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:L.map(E=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:E.id})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[C(E)?n.jsx("img",{src:C(E),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):n.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),n.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.jsx("span",{style:{fontWeight:600},children:N(E)}),n.jsx("span",{style:{opacity:.8},children:E.description})]})]})}),n.jsx("td",{children:S(E.metadata?.product_type)}),n.jsx("td",{children:$(E.fiatAmountCents)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${E.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:E.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>g(E),children:"Variations"})]})})]},E.id))})]})}),_&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>g(null),children:n.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:E=>E.stopPropagation(),children:n.jsx(Hf,{serverUrl:e,productId:_.id,productTitle:N(_),defaultPrice:_.fiatAmountCents/100,apiKey:t,authManager:s,onClose:()=>g(null)})})})]})}function Bl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(null),[l,d]=y.useState(!0),[m,u]=y.useState(!0),[p,h]=y.useState(null),[_,g]=y.useState(""),[f,w]=y.useState(null),j=y.useCallback(async()=>{u(!0);try{h(null);let C;if(s?.isAuthenticated())C=await s.fetchWithAuth("/admin/stats");else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const O=await fetch(`${e}/admin/stats`,{headers:T});if(!O.ok)throw new Error(`Failed to fetch stats: ${O.status}`);C=await O.json()}c(C)}catch{c(null),h("Failed to load payment stats")}finally{u(!1)}},[e,t,s]);y.useEffect(()=>{j()},[j]);const b=y.useCallback(async()=>{try{h(null);let C;const T=new URLSearchParams({limit:r.toString()});_&&T.set("method",_);const O=`/admin/transactions?${T}`;if(s?.isAuthenticated())C=await s.fetchWithAuth(O);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const S=await fetch(`${e}${O}`,{headers:$});if(!S.ok)throw new Error(`Failed to fetch transactions: ${S.status}`);C=await S.json()}a(C.transactions||[])}catch{a([]),h("Failed to load transactions")}finally{d(!1)}},[e,t,r,_,s]);y.useEffect(()=>{b()},[b]);const v=C=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(C),k=C=>{w(T=>!T||T.key!==C?{key:C,direction:"asc"}:{key:C,direction:T.direction==="asc"?"desc":"asc"})},R=C=>!f||f.key!==C?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:f.direction==="asc"?Q.chevronUp:Q.chevronDown}),N=y.useMemo(()=>{if(!f)return o;const C=f.direction==="asc"?1:-1,T=O=>{switch(f.key){case"resource":return O.resourceId;case"method":return O.method;case"amount":return O.amount;case"status":return O.status;case"date":return new Date(O.paidAt).getTime();case"id":default:return O.id}};return[...o].sort((O,$)=>{const S=T(O),A=T($);return typeof S=="number"&&typeof A=="number"?(S-A)*C:String(S).localeCompare(String(A),void 0,{sensitivity:"base"})*C})},[o,f]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Kt,{message:p,onRetry:()=>{j(),b()}}),n.jsx(sr,{stats:[{label:"Revenue",value:v(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:v(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:v(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:v(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:m,onRefresh:j}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),n.jsx(zl,{value:_,onChange:g,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading transactions..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("id"),children:["ID",R("id")]})}),n.jsx("th",{"aria-sort":f?.key==="resource"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("resource"),children:["Resource",R("resource")]})}),n.jsx("th",{"aria-sort":f?.key==="method"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("method"),children:["Method",R("method")]})}),n.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("amount"),children:["Amount",R("amount")]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("status"),children:["Status",R("status")]})}),n.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>k("date"),children:["Date",R("date")]})})]})}),n.jsx("tbody",{children:N.map(C=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:C.id})}),n.jsx("td",{children:C.resourceId}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.method}`,children:C.method})}),n.jsxs("td",{children:["$",C.amount.toFixed(2)," ",C.currency.toUpperCase()]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.status}`,children:C.status})}),n.jsx("td",{children:Sr(C.paidAt)})]},C.id))})]})})]})}function Ul({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(!1),[p,h]=y.useState(null),[_,g]=y.useState(null),[f,w]=y.useState({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),j=y.useCallback(async()=>{try{g(null);let T;const O=`/admin/coupons?limit=${r}`;if(s?.isAuthenticated())T=await s.fetchWithAuth(O);else{const $={"Content-Type":"application/json"};t&&($["X-API-Key"]=t);const S=await fetch(`${e}${O}`,{headers:$});if(!S.ok)throw new Error(`Failed to fetch coupons: ${S.status}`);T=await S.json()}a(T.coupons||[])}catch(T){J.getLogger().error("[CouponsSection] Failed to fetch coupons:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),g("Failed to load coupons")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{j()},[j]);const b=async T=>{if(T.preventDefault(),!(!f.code||f.discountValue<=0)){u(!0);try{const O=f.minimumAmountUsd?Math.round(Number(f.minimumAmountUsd)*100):void 0,$=f.productIdsCsv.split(",").map(I=>I.trim()).filter(Boolean),S=f.categoryIdsCsv.split(",").map(I=>I.trim()).filter(Boolean),A={code:f.code,discountType:f.discountType,discountValue:f.discountValue,usageLimit:f.usageLimit,active:!0,usageCount:0,scope:f.scope,...$.length?{productIds:$}:{},...S.length?{categoryIds:S}:{},...f.paymentMethod!=="any"?{paymentMethod:f.paymentMethod}:{},...f.autoApply?{autoApply:!0}:{},...f.appliesAt!=="both"?{appliesAt:f.appliesAt}:{},...f.startsAt?{startsAt:f.startsAt}:{},...f.expiresAt?{expiresAt:f.expiresAt}:{},...O?{minimumAmountCents:O}:{},...f.usageLimitPerCustomer?{usageLimitPerCustomer:f.usageLimitPerCustomer}:{},...f.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(s?.isAuthenticated())await s.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(A)});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/coupons`,{method:"POST",headers:I,body:JSON.stringify(A)});if(!B.ok)throw new Error(`Failed to create coupon: ${B.status}`)}w({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),d(!1),j()}catch(O){J.getLogger().error("[CouponsSection] Failed to add coupon:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),g("Failed to create coupon")}finally{u(!1)}}},v=o.filter(T=>T.active).length,k=o.reduce((T,O)=>T+(O.usageCount??0),0),R=T=>{h(O=>!O||O.key!==T?{key:T,direction:"asc"}:{key:T,direction:O.direction==="asc"?"desc":"asc"})},N=T=>!p||p.key!==T?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:p.direction==="asc"?Q.chevronUp:Q.chevronDown}),C=y.useMemo(()=>{if(!p)return o;const T=p.direction==="asc"?1:-1,O=$=>{switch(p.key){case"discount":return $.discountValue??0;case"usage":return $.usageCount??0;case"status":return $.active?1:0;case"code":default:return $.code}};return[...o].sort(($,S)=>{const A=O($),I=O(S);return typeof A=="number"&&typeof I=="number"?(A-I)*T:String(A).localeCompare(String(I),void 0,{sensitivity:"base"})*T})},[o,p]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Kt,{message:_,onRetry:j}),n.jsx(sr,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:v,variant:v>0?"success":"muted"},{label:"Redemptions",value:k}],isLoading:i}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?Q.close:Q.plus,l?"Cancel":"Add Coupon"]})]}),l&&n.jsxs("form",{onSubmit:b,className:"cedros-admin__add-form",children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.code,onChange:T=>w(O=>({...O,code:T.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),n.jsx(at,{value:f.discountType,onChange:T=>w(O=>({...O,discountType:T})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",f.discountType==="percentage"?"(%)":"($)"]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.discountValue||"",onChange:T=>w(O=>({...O,discountValue:parseFloat(T.target.value)||0})),placeholder:f.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:f.discountType==="percentage"?"1":"0.01",required:!0})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.usageLimit||"",onChange:T=>w(O=>({...O,usageLimit:T.target.value?parseInt(T.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:f.expiresAt,onChange:T=>w(O=>({...O,expiresAt:T.target.value}))})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx(at,{value:f.scope,onChange:T=>w(O=>({...O,scope:T})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),n.jsx(at,{value:f.paymentMethod,onChange:T=>w(O=>({...O,paymentMethod:T})),options:[{value:"any",label:"Any Payment Method"},{value:"stripe",label:"Stripe (Card) Only"},{value:"x402",label:"Crypto (x402) Only"},{value:"credits",label:"Credits Only"}],label:"Payment Method"}),n.jsx(at,{value:f.appliesAt,onChange:T=>w(O=>({...O,appliesAt:T})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),f.scope==="specific_products"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.productIdsCsv,onChange:T=>w(O=>({...O,productIdsCsv:T.target.value})),placeholder:"e.g., prod_123, prod_456"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),n.jsx("input",{type:"date",className:"cedros-admin__input",value:f.startsAt,onChange:T=>w(O=>({...O,startsAt:T.target.value}))})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:f.autoApply,onChange:T=>w(O=>({...O,autoApply:T.target.checked}))}),"Automatically apply when conditions met"]})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.minimumAmountUsd===""?"":f.minimumAmountUsd,onChange:T=>w(O=>({...O,minimumAmountUsd:T.target.value===""?"":parseFloat(T.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:f.usageLimitPerCustomer||"",onChange:T=>w(O=>({...O,usageLimitPerCustomer:T.target.value?parseInt(T.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("input",{type:"checkbox",checked:f.firstPurchaseOnly,onChange:T=>w(O=>({...O,firstPurchaseOnly:T.target.checked}))}),"New customers only"]})]})]}),f.scope==="specific_categories"&&n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:f.categoryIdsCsv,onChange:T=>w(O=>({...O,categoryIdsCsv:T.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),n.jsx("div",{className:"cedros-admin__form-actions",children:n.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:m,children:m?"Creating...":"Create Coupon"})})]}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading coupons..."]}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":p?.key==="code"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("code"),children:["Code",N("code")]})}),n.jsx("th",{"aria-sort":p?.key==="discount"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("discount"),children:["Discount",N("discount")]})}),n.jsx("th",{"aria-sort":p?.key==="usage"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("usage"),children:["Usage",N("usage")]})}),n.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("status"),children:["Status",N("status")]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:C.map(T=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:T.code})}),n.jsx("td",{children:T.discountType==="percentage"?`${T.discountValue}%`:`$${T.discountValue.toFixed(2)}`}),n.jsxs("td",{children:[T.usageCount,T.usageLimit?` / ${T.usageLimit}`:""]}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge ${T.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:T.active?"Active":"Inactive"})}),n.jsx("td",{children:n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},T.code))})]})})]})}function Wl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(null),[m,u]=y.useState([]),[p,h]=y.useState(!0),[_,g]=y.useState(null),[f,w]=y.useState(null),[j,b]=y.useState([]),[v,k]=y.useState(!0),[R,N]=y.useState(null),[C,T]=y.useState(null),[O,$]=y.useState(null),[S,A]=y.useState(""),[I,B]=y.useState(null),L=y.useCallback(async()=>{try{let U;const re=`/admin/refunds?limit=${r}`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{headers:de});if(!ke.ok)throw new Error(`Failed to fetch x402 refunds: ${ke.status}`);U=await ke.json()}a(U.refunds||[])}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),B("Failed to load x402 refunds")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{L()},[L]);const E=y.useCallback(async()=>{try{let U;const re=`/admin/credits/refund-requests?status=pending&limit=${r}&offset=0`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const ke={"Content-Type":"application/json"};t&&(ke["X-API-Key"]=t);const Se=await fetch(`${e}${re}`,{headers:ke});if(!Se.ok)throw new Error(`Failed to fetch credits refund requests: ${Se.status}`);U=await Se.json()}const de=Array.isArray(U)?U:"refundRequests"in U?U.refundRequests:U.requests||[];u(de)}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([]),B("Failed to load credits refunds")}finally{h(!1)}},[e,t,r,s]);y.useEffect(()=>{E()},[E]);const P=async U=>{g(U.id);try{const re=`/admin/credits/refund-requests/${U.id}/process`,de=JSON.stringify({amountLamports:U.amountLamports,reason:U.reason});if(s?.isAuthenticated())await s.fetchWithAuth(re,{method:"POST",body:de});else{const ke={"Content-Type":"application/json"};t&&(ke["X-API-Key"]=t);const Se=await fetch(`${e}${re}`,{method:"POST",headers:ke,body:de});if(!Se.ok)throw new Error(`Failed to process credits refund: ${Se.status}`)}await E()}catch(re){J.getLogger().error("[RefundsSection] Failed to process credits refund:",re,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:U.id}),B("Failed to process credits refund")}finally{g(null)}},z=U=>{A(U.reason??""),$(U)},Z=()=>{$(null),A("")},K=async()=>{if(!O)return;const U=O,re=S;Z(),g(U.id);try{const de=`/admin/credits/refund-requests/${U.id}/reject`,ke=JSON.stringify({reason:re});if(s?.isAuthenticated())await s.fetchWithAuth(de,{method:"POST",body:ke});else{const Se={"Content-Type":"application/json"};t&&(Se["X-API-Key"]=t);const Le=await fetch(`${e}${de}`,{method:"POST",headers:Se,body:ke});if(!Le.ok)throw new Error(`Failed to reject credits refund: ${Le.status}`)}await E()}catch(de){J.getLogger().error("[RefundsSection] Failed to reject credits refund:",de,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:U.id}),B("Failed to reject credits refund")}finally{g(null)}},D=y.useCallback(async()=>{try{let U;const re=`/admin/stripe/refunds?limit=${r}`;if(s?.isAuthenticated())U=await s.fetchWithAuth(re);else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{headers:de});if(!ke.ok)throw new Error(`Failed to fetch Stripe refunds: ${ke.status}`);U=await ke.json()}b(U.refunds||[])}catch(U){J.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",U,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),b([]),B("Failed to load Stripe refunds")}finally{k(!1)}},[e,t,r,s]);y.useEffect(()=>{D()},[D]);const W=async U=>{N(U);try{const re=`/admin/stripe/refunds/${U}/process`;if(s?.isAuthenticated())await s.fetchWithAuth(re,{method:"POST"});else{const de={"Content-Type":"application/json"};t&&(de["X-API-Key"]=t);const ke=await fetch(`${e}${re}`,{method:"POST",headers:de});if(!ke.ok)throw new Error(`Failed to process refund: ${ke.status}`)}await D()}catch(re){J.getLogger().error("[RefundsSection] Failed to process Stripe refund:",re,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:U}),B("Failed to process Stripe refund")}finally{N(null)}},Y=(U,re)=>new Intl.NumberFormat("en-US",{style:"currency",currency:re}).format(U/100),V=U=>U?U.replace(/_/g," ").replace(/\b\w/g,re=>re.toUpperCase()):"—",ce=U=>{switch(U){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},F=(U,re)=>re?re.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(U/1e6)} (USD credits)`:`${U.toLocaleString()} ${re.toUpperCase()} (atomic)`:`${U.toLocaleString()} (atomic)`,ee=U=>{switch(U){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},pe=U=>U.stripeRefundId??"—",q=U=>U.chargeId??"—",ne=j.filter(U=>U.status==="pending"||U.status==="requires_action").length,le=m.filter(U=>U.status==="pending").length,fe=o.filter(U=>U.status==="pending").length,Pe=ne+le+fe,qe=j.filter(U=>U.status==="succeeded").reduce((U,re)=>U+re.amount,0),He=m.filter(U=>U.status==="processed").reduce((U,re)=>U+re.amountLamports,0),Ze=o.filter(U=>U.status==="completed").reduce((U,re)=>U+re.amount,0),xt=qe/100+He/1e6+Ze,Qe=U=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(U),Ft=v||p||i,dt=U=>{T(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},te=U=>{w(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},xe=U=>{d(re=>!re||re.key!==U?{key:U,direction:"asc"}:{key:U,direction:re.direction==="asc"?"desc":"asc"})},ge=(U,re)=>!U||!re?n.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Q.chevronUp}):n.jsx("span",{className:"cedros-admin__sort-icon",children:re==="asc"?Q.chevronUp:Q.chevronDown}),ut=y.useMemo(()=>{if(!C)return j;const U=C.direction==="asc"?1:-1,re=de=>{switch(C.key){case"stripe":return de.stripeRefundId??"";case"charge":return de.chargeId??"";case"amount":return de.amount??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...j].sort((de,ke)=>{const Se=re(de),Le=re(ke);return typeof Se=="number"&&typeof Le=="number"?(Se-Le)*U:String(Se).localeCompare(String(Le),void 0,{sensitivity:"base"})*U})},[j,C]),yt=y.useMemo(()=>{if(!f)return m;const U=f.direction==="asc"?1:-1,re=de=>{switch(f.key){case"original":return de.originalTransactionId??"";case"user":return de.userId??"";case"amount":return de.amountLamports??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...m].sort((de,ke)=>{const Se=re(de),Le=re(ke);return typeof Se=="number"&&typeof Le=="number"?(Se-Le)*U:String(Se).localeCompare(String(Le),void 0,{sensitivity:"base"})*U})},[m,f]),mt=y.useMemo(()=>{if(!l)return o;const U=l.direction==="asc"?1:-1,re=de=>{switch(l.key){case"transaction":return de.transactionId??"";case"amount":return de.amount??0;case"reason":return de.reason??"";case"status":return de.status??"";case"date":return new Date(de.createdAt).getTime();case"id":default:return de.id}};return[...o].sort((de,ke)=>{const Se=re(de),Le=re(ke);return typeof Se=="number"&&typeof Le=="number"?(Se-Le)*U:String(Se).localeCompare(String(Le),void 0,{sensitivity:"base"})*U})},[o,l]);return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Kt,{message:I,onRetry:()=>{L(),E(),D()}}),n.jsx(sr,{stats:[{label:"Pending",value:Pe,variant:Pe>0?"warning":"muted"},{label:"Card Pending",value:ne,description:"Stripe"},{label:"Credits Pending",value:le},{label:"Crypto Pending",value:fe,description:"x402"},{label:"Total Refunded",value:Qe(xt),variant:"success"}],isLoading:Ft}),n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),v?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading Stripe refunds..."]}):j.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":C?.key==="id"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>dt("id"),children:["Request ID",ge(C?.key==="id",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="stripe"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>dt("stripe"),children:["Stripe Refund ID",ge(C?.key==="stripe",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="charge"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>dt("charge"),children:["Charge",ge(C?.key==="charge",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="amount"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>dt("amount"),children:["Amount",ge(C?.key==="amount",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="reason"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>dt("reason"),children:["Reason",ge(C?.key==="reason",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="status"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>dt("status"),children:["Status",ge(C?.key==="status",C?.direction)]})}),n.jsx("th",{"aria-sort":C?.key==="date"?C?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>dt("date"),children:["Date",ge(C?.key==="date",C?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:ut.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:pe(U)})}),n.jsx("td",{children:n.jsx("code",{children:q(U)})}),n.jsx("td",{children:Y(U.amount,U.currency)}),n.jsx("td",{children:V(U.reason)}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${ee(U.status)}`,children:U.status})}),n.jsx("td",{children:Sr(U.createdAt)}),n.jsx("td",{children:(U.status==="pending"||U.status==="requires_action")&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>W(U.id),disabled:R===U.id,children:R===U.id?"Processing...":"Process"})})]},U.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),p?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading credits refunds..."]}):m.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("id"),children:["Request ID",ge(f?.key==="id",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="original"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("original"),children:["Original Tx",ge(f?.key==="original",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="user"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("user"),children:["User",ge(f?.key==="user",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("amount"),children:["Amount",ge(f?.key==="amount",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="reason"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("reason"),children:["Reason",ge(f?.key==="reason",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("status"),children:["Status",ge(f?.key==="status",f?.direction)]})}),n.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>te("date"),children:["Date",ge(f?.key==="date",f?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:yt.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:U.originalTransactionId})}),n.jsx("td",{children:n.jsx("code",{children:U.userId??"—"})}),n.jsx("td",{children:F(U.amountLamports,U.currency)}),n.jsx("td",{children:U.reason??"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${ce(U.status)}`,children:U.status})}),n.jsx("td",{children:Sr(U.createdAt)}),n.jsx("td",{children:U.status==="pending"?n.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>P(U),disabled:_===U.id,children:_===U.id?"Processing...":"Process"}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>z(U),disabled:_===U.id,children:"Reject"})]}):null})]},U.id))})]})}),n.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:n.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading x402 refunds..."]}):o.length===0?n.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):n.jsx("div",{className:"cedros-admin__table-container",children:n.jsxs("table",{className:"cedros-admin__table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("id"),children:["ID",ge(l?.key==="id",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="transaction"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("transaction"),children:["Transaction",ge(l?.key==="transaction",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="amount"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("amount"),children:["Amount",ge(l?.key==="amount",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="reason"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("reason"),children:["Reason",ge(l?.key==="reason",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="status"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("status"),children:["Status",ge(l?.key==="status",l?.direction)]})}),n.jsx("th",{"aria-sort":l?.key==="date"?l?.direction==="asc"?"ascending":"descending":"none",children:n.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xe("date"),children:["Date",ge(l?.key==="date",l?.direction)]})}),n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:mt.map(U=>n.jsxs("tr",{children:[n.jsx("td",{children:n.jsx("code",{children:U.id})}),n.jsx("td",{children:n.jsx("code",{children:U.transactionId})}),n.jsxs("td",{children:["$",U.amount.toFixed(2)]}),n.jsx("td",{children:U.reason||"—"}),n.jsx("td",{children:n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${U.status}`,children:U.status})}),n.jsx("td",{children:Sr(U.createdAt)}),n.jsx("td",{children:U.status==="pending"&&n.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",children:"Process"})})]},U.id))})]})}),O&&n.jsx("div",{className:"cedros-admin__modal-overlay",onClick:Z,children:n.jsxs("div",{className:"cedros-admin__modal",onClick:U=>U.stopPropagation(),children:[n.jsxs("div",{className:"cedros-admin__modal-header",children:[n.jsx("h3",{className:"cedros-admin__modal-title",children:"Reject Refund Request"}),n.jsx("button",{type:"button",className:"cedros-admin__modal-close",onClick:Z,"aria-label":"Close",children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__modal-body",children:[n.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",n.jsx("code",{children:O.id})," for ",F(O.amountLamports,O.currency),"."]}),n.jsxs("label",{className:"cedros-admin__form-field",children:[n.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),n.jsx("textarea",{className:"cedros-admin__input",value:S,onChange:U=>A(U.target.value),placeholder:"Enter rejection reason...",rows:3,style:{resize:"vertical"}})]})]}),n.jsxs("div",{className:"cedros-admin__modal-footer",children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--outline",onClick:Z,children:"Cancel"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:K,children:"Reject Refund"})]})]})})]})}async function Zf(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 Gf{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 Zf(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 Ta={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 Vl(e,t){return Ta[e]?.secrets.includes(t)??!1}const _r="[REDACTED]";function Ia({data:e,onSave:t,debounceMs:r=1500,savedDurationMs:s=2e3,enabled:o=!0,skipInitial:a=!0}){const[i,c]=y.useState("idle"),[l,d]=y.useState(null),m=y.useRef(!0),u=y.useRef(null),p=y.useRef(null),h=y.useRef(e);h.current=e;const _=y.useCallback(async()=>{c("saving"),d(null);try{await t(h.current),c("saved"),p.current=setTimeout(()=>{c("idle")},s)}catch(w){c("error"),d(w instanceof Error?w.message:"Save failed")}},[t,s]),g=y.useCallback(async()=>{u.current&&(clearTimeout(u.current),u.current=null),await _()},[_]),f=y.useCallback(()=>{c("idle"),d(null)},[]);return y.useEffect(()=>{if(o){if(a&&m.current){m.current=!1;return}return u.current&&clearTimeout(u.current),p.current&&clearTimeout(p.current),c("pending"),u.current=setTimeout(()=>{_()},r),()=>{u.current&&clearTimeout(u.current)}}},[e,o,a,r,_]),y.useEffect(()=>()=>{u.current&&clearTimeout(u.current),p.current&&clearTimeout(p.current)},[]),{status:i,error:l,saveNow:g,reset:f}}function Qf(e){if(!e||e.trim()==="")return{valid:!0};try{return new df.PublicKey(e.trim()),{valid:!0}}catch{return{valid:!1,error:"Invalid Solana address"}}}function Xi(e,t,r){const s=Vl(e,t),o=t.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase()),i=Ta[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 Yf({category:e,config:t,originalConfig:r,isLoading:s=!1,onSave:o}){const[a,i]=y.useState(t),[c,l]=y.useState(new Set);y.useEffect(()=>{i(t)},[t]);const d=y.useMemo(()=>{const j={...a};for(const b of Object.keys(j))if(Vl(e,b)){const v=r[b],k=j[b];(k===_r||k===v)&&(j[b]=_r)}return j},[a,r,e]),{status:m,error:u}=Ia({data:d,onSave:o,debounceMs:1500}),p=y.useCallback((j,b)=>{i(v=>({...v,[j]:b}))},[]),h=y.useCallback(j=>{l(b=>{const v=new Set(b);return v.has(j)?v.delete(j):v.add(j),v})},[]),_=j=>j?n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:j}):null,g=(j,b)=>{const v=Xi(e,j,r[j]??b);if(v.type==="dropdown"&&v.options)return n.jsx(at,{value:b,onChange:N=>p(j,N),options:v.options.map(N=>({value:N,label:N})),label:v.label,description:v.description,disabled:s});if(v.type==="token_mint")return n.jsx(Kf,{label:v.label,value:b,onChange:N=>p(j,N),decimals:a.token_decimals??6,onDecimalsChange:N=>p("token_decimals",N),disabled:s,description:v.description,customSymbol:a.custom_token_symbol||"",customIcon:a.custom_token_icon||"",onCustomSymbolChange:N=>p("custom_token_symbol",N),onCustomIconChange:N=>p("custom_token_icon",N)});if(v.type==="toggle")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("button",{type:"button",role:"switch","aria-checked":b,onClick:()=>p(j,!b),disabled:s,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:b?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:s?"not-allowed":"pointer",position:"relative",transition:"background-color 0.2s",opacity:s?.5:1,flexShrink:0},children:n.jsx("span",{style:{position:"absolute",top:2,left:b?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})}),n.jsx("span",{className:"cedros-admin__field-label",style:{marginBottom:0},children:v.label})]}),_(v.description)]});if(v.type==="solana_address"){const N=b||"",C=Qf(N);return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:v.label}),n.jsxs("div",{style:{position:"relative"},children:[n.jsx("input",{type:"text",className:`cedros-admin__input ${C.valid?"":"cedros-admin__input--error"}`,value:N,onChange:T=>p(j,T.target.value),disabled:s,placeholder:"e.g. 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",style:{width:"100%",fontFamily:"monospace",fontSize:"0.875rem",borderColor:C.valid?void 0:"var(--cedros-admin-error, #dc2626)",paddingRight:N&&C.valid?"2rem":void 0}}),N&&C.valid&&n.jsx("span",{style:{position:"absolute",right:10,top:"50%",transform:"translateY(-50%)",color:"var(--cedros-admin-success, #16a34a)",fontSize:"1rem"},title:"Valid Solana address",children:"✓"})]}),!C.valid&&n.jsx("span",{style:{color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.75rem",marginTop:"0.25rem",display:"block"},children:C.error}),_(v.description)]})}if(v.type==="boolean")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__checkbox",children:[n.jsx("input",{type:"checkbox",checked:b,onChange:N=>p(j,N.target.checked),disabled:s}),v.label]}),_(v.description)]});if(v.type==="number")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[v.label,v.unit&&n.jsxs("span",{className:"cedros-admin__field-unit",children:[" (",v.unit,")"]})]}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:b,onChange:N=>p(j,parseFloat(N.target.value)||0),disabled:s}),_(v.description)]});if(v.type==="secret_array")return n.jsx(Xf,{label:v.label,value:b,onChange:N=>p(j,N),disabled:s,description:v.description});if(v.type==="array"){const N=b;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:v.label}),n.jsx("textarea",{className:"cedros-admin__textarea",value:N.join(`
|
|
2
2
|
`),onChange:C=>p(j,C.target.value.split(`
|
|
3
|
-
`).filter(Boolean)),placeholder:"One item per line",rows:3,disabled:s}),_(v.description)]})}if(v.type==="object")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:v.label}),n.jsx("textarea",{className:"cedros-admin__textarea cedros-admin__textarea--mono",value:JSON.stringify(b,null,2),onChange:N=>{try{p(j,JSON.parse(N.target.value))}catch{}},rows:5,disabled:s}),_(v.description)]});const k=c.has(j),R=v.isSecret&&!k&&b===wr?wr:b;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[v.label,v.isSecret&&n.jsx("span",{className:"cedros-admin__field-secret",children:" (secret)"})]}),n.jsxs("div",{className:"cedros-admin__input-group",children:[n.jsx("input",{type:v.isSecret&&!k?"password":"text",className:"cedros-admin__input",value:R,onChange:N=>p(j,N.target.value),disabled:s,placeholder:v.isSecret?"••••••••":""}),v.isSecret&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>h(j),style:{padding:"0.5rem",minWidth:"auto"},title:k?"Hide":"Show",children:k?Q.eyeOff:Q.eye})]}),_(v.description)]})},f=Object.keys(a),w=j=>{const b=Ki(e,j,r[j]??a[j]);if(b.hidden||b.showWhen&&!a[b.showWhen])return!1;if(j==="token_decimals"){const v=a.token_mint;if(v&&J.STABLECOIN_METADATA[v])return!1}return!0};return n.jsxs("div",{className:"cedros-admin__config-editor",children:[n.jsx("div",{className:"cedros-admin__config-fields",children:f.filter(w).map(j=>n.jsx("div",{className:"cedros-admin__config-field",children:g(j,a[j])},j))}),n.jsx("div",{className:"cedros-admin__config-actions",children:n.jsx("div",{className:"cedros-admin__autosave-status",children:n.jsx(Yf,{status:m,error:u})})})]})}function Gf({label:e,value:t,onChange:r,decimals:s,onDecimalsChange:o,disabled:a=!1,description:i,customSymbol:c="",customIcon:l="",onCustomSymbolChange:d,onCustomIconChange:m}){const[u,p]=y.useState(!1),h=Object.entries(J.STABLECOIN_METADATA),g=!!J.STABLECOIN_METADATA[t],w=u||!!t&&!g,j=b=>{if(b==="custom")p(!0),g&&r("");else{p(!1),r(b);const v=J.STABLECOIN_METADATA[b];v&&o&&o(v.decimals),d&&d(""),m&&m("")}};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:e}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem"},children:[h.map(([b,v])=>n.jsxs("button",{type:"button",onClick:()=>j(b),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:t===b?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:t===b?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:t===b?600:400},children:[n.jsx("img",{src:v.icon,alt:v.symbol,style:{width:20,height:20,borderRadius:"50%"},onError:k=>{k.target.style.display="none"}}),n.jsx("span",{children:v.symbol})]},b)),n.jsxs("button",{type:"button",onClick:()=>j("custom"),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:w?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:w?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:w?600:400},children:[n.jsx("span",{style:{fontSize:"1rem"},children:"+"}),n.jsx("span",{children:"Custom"})]})]}),w&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"1rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:[n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Mint Address"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:t,onChange:b=>r(b.target.value),placeholder:"e.g., EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",disabled:a,style:{fontFamily:"monospace",fontSize:"0.875rem"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Symbol"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:b=>d?.(b.target.value),placeholder:"e.g., MYTOKEN",disabled:a,style:{textTransform:"uppercase"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Icon URL"}),n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:l,onChange:b=>m?.(b.target.value),placeholder:"https://example.com/token-logo.png",disabled:a,style:{flex:1}}),l&&n.jsx("img",{src:l,alt:"Token icon preview",style:{width:32,height:32,borderRadius:"50%",border:"1px solid var(--cedros-admin-border, #e5e7eb)",objectFit:"cover"},onError:b=>{b.target.style.display="none"}})]}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Shown to customers during checkout"})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Decimals"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:s??6,onChange:b=>o?.(parseInt(b.target.value,10)||0),min:0,max:18,disabled:a,style:{width:"100px"}}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Most SPL tokens use 6 decimals (like USDC)"})]})]}),t&&g&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",fontFamily:"monospace",wordBreak:"break-all"},children:t}),i&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:i})]})]})}function Qf({label:e,value:t,onChange:r,disabled:s=!1,description:o}){const[a,i]=y.useState(new Set),[c,l]=y.useState(null),[d,m]=y.useState(""),u=Array.isArray(t)?t:[],p=b=>{i(v=>{const k=new Set(v);return k.has(b)?k.delete(b):k.add(b),k})},h=()=>{r([...u,""]),l(u.length),m("")},_=(b,v)=>{const k=[...u];k[b]=v,r(k)},g=b=>{const v=u.filter((k,R)=>R!==b);r(v),i(k=>{const R=new Set;return k.forEach(N=>{N<b?R.add(N):N>b&&R.add(N-1)}),R})},f=b=>{l(b),m(u[b]||"")},w=()=>{c!==null&&(_(c,d),l(null),m(""))},j=()=>{c!==null&&u[c]===""&&g(c),l(null),m("")};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",style:{marginBottom:0},children:e}),n.jsxs("button",{type:"button",onClick:h,disabled:s,style:{display:"flex",alignItems:"center",gap:"0.25rem",padding:"0.25rem 0.5rem",fontSize:"0.75rem",border:"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.375rem",background:"var(--cedros-admin-bg, #fff)",cursor:s?"not-allowed":"pointer",opacity:s?.5:1},children:[Q.plus,"Add"]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u.length===0&&n.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"0.875rem",border:"1px dashed var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem"},children:'No items. Click "Add" to create one.'}),u.map((b,v)=>{const k=a.has(v),R=c===v,N=b===wr;return n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.375rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:R?n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:d,onChange:C=>m(C.target.value),placeholder:"Enter wallet keypair...",autoFocus:!0,style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem"},onKeyDown:C=>{C.key==="Enter"&&w(),C.key==="Escape"&&j()}}),n.jsx("button",{type:"button",onClick:w,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-success, #22c55e)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Save",children:Q.check}),n.jsx("button",{type:"button",onClick:j,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-text-muted, #64748b)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Cancel",children:Q.close})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k&&!N?b:N?"[REDACTED]":"••••••••••••••••••••"}),n.jsx("button",{type:"button",onClick:()=>p(v),disabled:s||N,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s||N?"not-allowed":"pointer",opacity:s||N?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:k?"Hide":"Show",children:k?Q.eyeOff:Q.eye}),n.jsx("button",{type:"button",onClick:()=>f(v),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:"Edit",children:Q.settings}),n.jsx("button",{type:"button",onClick:()=>g(v),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-error, #ef4444)"},title:"Delete",children:Q.trash})]})},v)})]}),o&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.5rem"},children:o})]})}function Yf({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${e}`,style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx(n.Fragment,{children:n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"})}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx(n.Fragment,{children:n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})})]})}function Ul({serverUrl:e,apiKey:t,authManager:r,category:s,title:o,description:a,enabledField:i="enabled",showEnabledToggle:c=!1}){const l=y.useMemo(()=>new qf(e,void 0,r),[e,r]),[d,m]=y.useState(null),[u,p]=y.useState([]),[h,_]=y.useState(!1),[g,f]=y.useState(!0),[w,j]=y.useState(null),[b,v]=y.useState(null),[k,R]=y.useState(!1),N=Ea[s]||{label:s,icon:"⚙️"},C=o||N.label,T=a||N.description,O=y.useCallback(async()=>{f(!0),j(null);try{const P=await l.getConfig(s,!0);m(P)}catch{m(null),j("Failed to load settings")}finally{f(!1)}},[l,s]);y.useEffect(()=>{O()},[O]);const $=y.useCallback(async()=>{try{const P=await l.getHistory(s,20);p(P.history)}catch{p([])}},[l,s]);y.useEffect(()=>{h&&$()},[h,$]);const S=y.useCallback(async P=>{await l.updateConfig(s,P,"Updated via admin dashboard"),await O()},[l,s,O]),A=y.useCallback(async P=>l.validateConfig(s,P),[l,s]),[I,B]=y.useState(!1),D=y.useCallback(async()=>{if(!d||I)return;const P=!!d.config[i],z=!P,Z={...d.config,[i]:z};B(!0),m({...d,config:Z});try{await l.updateConfig(s,Z,`${z?"Enabled":"Disabled"} via admin dashboard`)}catch(K){m({...d,config:{...d.config,[i]:P}}),j(K instanceof Error?K.message:"Failed to save enabled state")}finally{B(!1)}},[d,l,s,i,I]),E=!!d?.config[i];return g&&!d?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading ",C," settings..."]})}):n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx(Yt,{message:w,onRetry:O}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{children:[n.jsxs("h3",{className:"cedros-admin__section-title",children:[n.jsx("span",{style:{marginRight:"0.5rem"},children:N.icon}),C]}),T&&n.jsx("p",{className:"cedros-admin__text-muted",style:{marginTop:"0.25rem"},children:T})]}),c&&d&&i in d.config&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("span",{style:{fontSize:"0.875rem",color:E?"var(--cedros-admin-text, #171717)":"var(--cedros-admin-muted, #737373)"},children:E?"Enabled":"Disabled"}),n.jsx("button",{type:"button",role:"switch","aria-checked":E,onClick:D,disabled:I,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:E?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:I?"wait":"pointer",position:"relative",transition:"background-color 0.2s",flexShrink:0,opacity:I?.6:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:E?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})]})]}),d&&n.jsxs("div",{className:"cedros-admin__settings-editor",style:{marginTop:"1rem",opacity:c&&!E?.6:1,pointerEvents:c&&!E?"none":"auto"},children:[c&&!E&&n.jsx("div",{style:{padding:"0.75rem 1rem",marginBottom:"1rem",backgroundColor:"var(--cedros-admin-warning-bg, #fef3c7)",border:"1px solid var(--cedros-admin-warning-border, #f59e0b)",borderRadius:"0.375rem",fontSize:"0.875rem",color:"var(--cedros-admin-warning-text, #92400e)",pointerEvents:"auto"},children:"This payment method is disabled. Enable it using the toggle above to accept payments."}),n.jsx(Zf,{category:d.category,config:d.config,originalConfig:d.config,onSave:S,onValidate:A,onCancel:()=>O()})]}),h&&n.jsxs("div",{className:"cedros-admin__settings-history",style:{marginTop:"1.5rem"},children:[n.jsx("h4",{style:{marginBottom:"0.75rem",fontWeight:600},children:"Change History"}),u.length===0?n.jsx("p",{className:"cedros-admin__text-muted",children:"No history entries found."}):n.jsx("div",{className:"cedros-admin__settings-timeline",children:u.map(P=>n.jsxs("div",{className:"cedros-admin__settings-timeline-item",children:[n.jsx("div",{className:"cedros-admin__settings-timeline-dot"}),n.jsxs("div",{className:"cedros-admin__settings-timeline-content",children:[n.jsxs("div",{className:"cedros-admin__settings-timeline-header",children:[n.jsx("code",{children:P.configKey}),n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${P.action.toLowerCase()}`,children:P.action})]}),n.jsxs("div",{className:"cedros-admin__settings-timeline-meta",children:[kr(P.changedAt)," by ",P.changedBy]})]})]},P.id))})]}),b&&n.jsx("div",{style:{marginTop:"1rem",padding:"0.75rem 1rem",borderRadius:"0.375rem",backgroundColor:b.valid?"var(--cedros-admin-success-bg, #dcfce7)":"var(--cedros-admin-error-bg, #fef2f2)",border:`1px solid ${b.valid?"var(--cedros-admin-success-border, #86efac)":"var(--cedros-admin-error-border, #fecaca)"}`},children:n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:600,color:b.valid?"var(--cedros-admin-success, #16a34a)":"var(--cedros-admin-error, #dc2626)",marginBottom:b.errors.length>0||b.warnings.length>0?"0.5rem":0},children:b.valid?"✓ Configuration is valid":"✗ Validation failed"}),b.errors.length>0&&n.jsx("ul",{style:{margin:0,paddingLeft:"1.25rem",color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.875rem"},children:b.errors.map((P,z)=>n.jsx("li",{children:P},z))}),b.warnings.length>0&&n.jsx("ul",{style:{margin:b.errors.length>0?"0.5rem 0 0":0,paddingLeft:"1.25rem",color:"var(--cedros-admin-warning, #ca8a04)",fontSize:"0.875rem"},children:b.warnings.map((P,z)=>n.jsx("li",{children:P},z))})]}),n.jsx("button",{type:"button",onClick:()=>v(null),style:{background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"1.25rem",lineHeight:1},title:"Dismiss",children:"×"})]})}),n.jsxs("div",{style:{marginTop:"1.5rem",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:()=>_(!h),children:h?"Hide History":"History"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",disabled:k||!d,onClick:async()=>{if(d){R(!0),v(null);try{const P=await A(d.config);v(P)}catch(P){v({valid:!1,errors:[P instanceof Error?P.message:"Validation failed"],warnings:[]})}finally{R(!1)}}},children:k?"Validating...":"Validate"})]})]})}const Xi=[{id:"logging",label:"Logging",category:"logging",description:"Configure log levels, format, and environment settings."},{id:"metrics",label:"Metrics",category:"metrics",description:"Configure metrics collection and API access for monitoring."},{id:"security",label:"Security",category:"security",description:"Configure CORS, rate limiting, and other security settings."}];function Ia({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("logging"),a=Xi.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__server-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Server"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure logging, metrics, and security settings."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:Xi.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(Ul,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description},a.category)})]})}const Kf=Object.freeze(Object.defineProperty({__proto__:null,SettingsSection:Ia},Symbol.toStringTag,{value:"Module"})),je={enabled:!1,plans:[],pageTitle:"Choose Your Plan",pageSubtitle:"Select the plan that best fits your needs.",annualSavingsBadge:"2 months free",popularBadgeText:"Best Deal",footerNotice:""},Xf={title:"New Plan",description:"",priceMonthlyUsd:0,priceAnnualUsd:0,features:[],featureHighlight:"",buttonText:"Purchase",isPopular:!1,isActive:!0,sortOrder:0};function Jf(){return`plan_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Wl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState(je),[a,i]=y.useState(!0),[c,l]=y.useState(null),[d,m]=y.useState("plans"),[u,p]=y.useState("idle"),[h,_]=y.useState(null),[g,f]=y.useState({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),[w,j]=y.useState(g),[b,v]=y.useState(""),k=y.useCallback(async()=>{try{_(null);let L;const W="/admin/subscriptions/settings";if(r?.isAuthenticated())L=await r.fetchWithAuth(W);else{const Y={"Content-Type":"application/json"};t&&(Y["X-API-Key"]=t);const V=await fetch(`${e}${W}`,{headers:Y});if(!V.ok)throw new Error(`Failed to fetch settings: ${V.status}`);L=await V.json()}o({...je,...L}),f({enabled:L.enabled??je.enabled,pageTitle:L.pageTitle??je.pageTitle,pageSubtitle:L.pageSubtitle??je.pageSubtitle,annualSavingsBadge:L.annualSavingsBadge??je.annualSavingsBadge,popularBadgeText:L.popularBadgeText??je.popularBadgeText,footerNotice:L.footerNotice??je.footerNotice}),j({enabled:L.enabled??je.enabled,pageTitle:L.pageTitle??je.pageTitle,pageSubtitle:L.pageSubtitle??je.pageSubtitle,annualSavingsBadge:L.annualSavingsBadge??je.annualSavingsBadge,popularBadgeText:L.popularBadgeText??je.popularBadgeText,footerNotice:L.footerNotice??je.footerNotice}),v(JSON.stringify(L.plans??[]))}catch{o(je),f({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),j({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),v(JSON.stringify([])),_("Failed to load subscription settings")}finally{i(!1)}},[e,t,r]);y.useEffect(()=>{k()},[k]);const R=y.useCallback(async L=>{try{_(null);const W="/admin/subscriptions/settings",Y=JSON.stringify(L);if(r?.isAuthenticated())await r.fetchWithAuth(W,{method:"PUT",body:Y});else{const V={"Content-Type":"application/json"};t&&(V["X-API-Key"]=t);const ce=await fetch(`${e}${W}`,{method:"PUT",headers:V,body:Y});if(!ce.ok)throw new Error(`Failed to save settings: ${ce.status}`)}return!0}catch{return _("Failed to save subscription settings"),!1}},[r,t,e]),N=y.useMemo(()=>w.enabled!==g.enabled||w.pageTitle!==g.pageTitle||w.pageSubtitle!==g.pageSubtitle||w.annualSavingsBadge!==g.annualSavingsBadge||w.popularBadgeText!==g.popularBadgeText||w.footerNotice!==g.footerNotice,[g,w]),C=y.useMemo(()=>JSON.stringify(s.plans),[s.plans]),T=y.useMemo(()=>b!==C,[C,b]),O=y.useCallback(async()=>{const L={...s,enabled:g.enabled,pageTitle:g.pageTitle,pageSubtitle:g.pageSubtitle,annualSavingsBadge:g.annualSavingsBadge,popularBadgeText:g.popularBadgeText,footerNotice:g.footerNotice};p("saving");const W=await R(L);o(L),W&&(j({enabled:L.enabled,pageTitle:L.pageTitle,pageSubtitle:L.pageSubtitle,annualSavingsBadge:L.annualSavingsBadge,popularBadgeText:L.popularBadgeText,footerNotice:L.footerNotice}),v(JSON.stringify(L.plans))),p(W?"saved":"error"),setTimeout(()=>p("idle"),1500)},[g,R,s]);y.useEffect(()=>{if(d!=="page"||a||!N)return;const L=setTimeout(O,600);return()=>clearTimeout(L)},[d,N,a,O]),y.useEffect(()=>{if(d!=="plans"||a||!T)return;const L=setTimeout(O,800);return()=>clearTimeout(L)},[d,T,a,O]);const $=()=>{const L={...Xf,id:Jf(),sortOrder:s.plans.length};o(W=>({...W,plans:[...W.plans,L]})),l(L.id)},S=(L,W)=>{o(Y=>({...Y,plans:Y.plans.map(V=>V.id===L?{...V,...W}:V)}))},A=L=>{confirm("Delete this plan? This cannot be undone.")&&(o(W=>({...W,plans:W.plans.filter(Y=>Y.id!==L)})),c===L&&l(null))},I=(L,W)=>{const Y=s.plans.findIndex(F=>F.id===L);if(Y===-1||W==="up"&&Y===0||W==="down"&&Y===s.plans.length-1)return;const V=[...s.plans],ce=W==="up"?Y-1:Y+1;[V[Y],V[ce]]=[V[ce],V[Y]],o(F=>({...F,plans:V}))},B=L=>{S(L,{features:[...s.plans.find(W=>W.id===L)?.features||[],""]})},D=(L,W,Y)=>{const V=s.plans.find(F=>F.id===L);if(!V)return;const ce=[...V.features];ce[W]=Y,S(L,{features:ce})},E=(L,W)=>{const Y=s.plans.find(ce=>ce.id===L);if(!Y)return;const V=Y.features.filter((ce,F)=>F!==W);S(L,{features:V})};if(a)return n.jsx("div",{className:"cedros-admin__page",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading subscription settings..."]})});const P=s.plans.filter(L=>L.isActive).length,z=s.plans.reduce((L,W)=>L+(W.activeSubscribers??0),0),Z=g.enabled,K=s.plans.filter(L=>L.isActive).map(L=>({label:L.title,value:L.activeSubscribers??0,description:"subscribers"}));return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Yt,{message:h,onRetry:k}),n.jsx(rr,{stats:[{label:"Status",value:Z?"Enabled":"Disabled",variant:Z?"success":"muted"},{label:"Active Plans",value:P,variant:P>0?"success":"muted"},{label:"Total Subscribers",value:z,variant:z>0?"success":"muted"},...K],isLoading:a}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Subscription Settings"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[d==="plans"&&n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:$,disabled:!Z,children:[Q.plus,"Add Plan"]}),n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${u}`,children:[u==="saving"&&"Saving...",u==="saved"&&"Saved",u==="error"&&"Error"]})]})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="plans"?"cedros-admin__tab--active":""}`,onClick:()=>m("plans"),children:"Plans"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="page"?"cedros-admin__tab--active":""}`,onClick:()=>m("page"),children:"Page Settings"})]}),d==="page"&&n.jsxs("div",{children:[n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Subscriptions"}),n.jsxs("label",{className:"cedros-admin__toggle",children:[n.jsx("input",{type:"checkbox",className:"cedros-admin__toggle-input",checked:g.enabled,onChange:L=>f(W=>({...W,enabled:L.target.checked}))}),n.jsx("span",{className:"cedros-admin__toggle-track",children:n.jsx("span",{className:"cedros-admin__toggle-thumb"})}),n.jsx("span",{className:"cedros-admin__toggle-label",children:"Enable Subscriptions"})]})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.pageTitle||"",onChange:L=>f(W=>({...W,pageTitle:L.target.value})),placeholder:"Choose Your Plan"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Subtitle"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.pageSubtitle||"",onChange:L=>f(W=>({...W,pageSubtitle:L.target.value})),placeholder:"Select the plan that best fits your needs."})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Savings Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.annualSavingsBadge||"",onChange:L=>f(W=>({...W,annualSavingsBadge:L.target.value})),placeholder:"2 months free"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Popular Plan Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.popularBadgeText||"",onChange:L=>f(W=>({...W,popularBadgeText:L.target.value})),placeholder:"Best Deal"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Footer Notice (optional)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.footerNotice||"",onChange:L=>f(W=>({...W,footerNotice:L.target.value})),placeholder:"For information regarding invoices, taxes..."})]})})]}),d==="plans"&&n.jsxs("div",{children:[!Z&&n.jsx("div",{style:{padding:"1.5rem",textAlign:"center",opacity:.6},children:"Subscriptions are disabled. Enable them to configure plans."}),s.plans.length===0?n.jsx("div",{style:{padding:"2rem",textAlign:"center",opacity:.6,border:"1px dashed currentColor",borderRadius:8},children:'No plans configured. Click "Add Plan" to create your first subscription tier.'}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:s.plans.map((L,W)=>{const Y=c===L.id;return n.jsxs("div",{style:{border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:8,overflow:"hidden",background:L.isPopular?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"1rem",padding:"0.75rem 1rem",cursor:"pointer"},onClick:()=>l(Y?null:L.id),children:[n.jsx("span",{style:{opacity:.5},children:Y?Q.chevronDown:Q.chevronRight}),n.jsxs("div",{style:{flex:1},children:[n.jsx("span",{style:{fontWeight:600},children:L.title||"Untitled Plan"}),L.isPopular&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:11,padding:"2px 6px",borderRadius:4,background:"var(--cedros-admin-primary, #171717)",color:"#fff"},children:"Popular"}),!L.isActive&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:11,padding:"2px 6px",borderRadius:4,background:"#9ca3af",color:"#fff"},children:"Inactive"})]}),n.jsxs("span",{style:{opacity:.6,fontSize:14},children:["$",L.priceMonthlyUsd,"/mo · $",L.priceAnnualUsd,"/yr"]}),n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},onClick:V=>V.stopPropagation(),children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>I(L.id,"up"),disabled:W===0,title:"Move up",style:{padding:"4px 8px"},children:Q.chevronUp}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>I(L.id,"down"),disabled:W===s.plans.length-1,title:"Move down",style:{padding:"4px 8px"},children:Q.chevronDown}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>A(L.id),title:"Delete plan",style:{padding:"4px 8px",color:"#dc2626"},children:Q.trash})]})]}),Y&&n.jsxs("div",{style:{padding:"1rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Plan Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.title,onChange:V=>S(L.id,{title:V.target.value}),placeholder:"e.g., Starter"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Button Text"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.buttonText||"",onChange:V=>S(L.id,{buttonText:V.target.value}),placeholder:"Purchase"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.description,onChange:V=>S(L.id,{description:V.target.value}),placeholder:"For entry-level developers managing lightweight workloads"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Monthly Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:L.priceMonthlyUsd||"",onChange:V=>S(L.id,{priceMonthlyUsd:parseFloat(V.target.value)||0}),placeholder:"10",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:L.priceAnnualUsd||"",onChange:V=>S(L.id,{priceAnnualUsd:parseFloat(V.target.value)||0}),placeholder:"100",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Feature Highlight"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:L.featureHighlight||"",onChange:V=>S(L.id,{featureHighlight:V.target.value}),placeholder:"100 prompts every 5 hours"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Bold text shown above feature list"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:L.isPopular||!1,onChange:V=>S(L.id,{isPopular:V.target.checked})}),"Mark as Popular (featured styling)"]})}),n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:L.isActive,onChange:V=>S(L.id,{isActive:V.target.checked})}),"Active (available for purchase)"]})})]}),n.jsxs("div",{className:"cedros-admin__form-row",style:{marginTop:"0.5rem"},children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:L.inventoryQuantity!=null,onChange:V=>S(L.id,{inventoryQuantity:V.target.checked?100:null})}),"Limit quantity available"]})}),L.inventoryQuantity!=null&&n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Total Available"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:L.inventoryQuantity??"",onChange:V=>S(L.id,{inventoryQuantity:parseInt(V.target.value)||0}),min:"0",style:{width:100}}),L.inventorySold!=null&&L.inventorySold>0&&n.jsxs("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:[L.inventorySold," sold · ",Math.max(0,L.inventoryQuantity-L.inventorySold)," remaining"]})]})]}),n.jsxs("div",{style:{marginTop:"1rem"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[n.jsxs("label",{className:"cedros-admin__field-label",style:{margin:0},children:["Feature List (",L.features.length,")"]}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>B(L.id),style:{fontSize:12,padding:"4px 8px"},children:"+ Add Feature"})]}),L.features.length===0?n.jsx("div",{style:{padding:"1rem",textAlign:"center",opacity:.5,fontSize:13,border:"1px dashed currentColor",borderRadius:6},children:'No features. Click "Add Feature" to add bullet points.'}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:L.features.map((V,ce)=>n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsxs("span",{style:{opacity:.4,fontSize:12},children:[ce+1,"."]}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:V,onChange:F=>D(L.id,ce,F.target.value),placeholder:"e.g., Powered by MiniMax M2.1",style:{flex:1}}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>E(L.id,ce),style:{padding:"4px 8px",color:"#dc2626"},title:"Remove feature",children:Q.trash})]},ce))})]})]})]},L.id)})})]})]})]})}const eh=Object.freeze(Object.defineProperty({__proto__:null,SubscriptionsSection:Wl},Symbol.toStringTag,{value:"Module"})),bo={relatedProducts:{mode:"most_recent",maxItems:4,layout:{layout:"large",imageCrop:"center"}},catalog:{filters:{tags:!0,priceRange:!0,inStock:!0},sort:{featured:!0,priceAsc:!0,priceDesc:!0}},checkout:{promoCodes:!0},shopLayout:{layout:"large",imageCrop:"center"},categoryLayout:{layout:"large",imageCrop:"center"},sections:{showDescription:!0,showSpecs:!0,showShipping:!0,showRelatedProducts:!0},inventory:{preCheckoutVerification:!0,holdsEnabled:!1,holdDurationMinutes:15},shopPage:{title:"Shop",description:""}},th=[{value:"most_recent",label:"Most Recent",description:"Show the most recently added products (excluding current product)."},{value:"by_category",label:"By Category",description:"Show products from the same category as the current product."},{value:"manual",label:"Manual Selection",description:"Specify related products per-product using relatedProductIds in metadata."},{value:"ai",label:"AI Recommendations",description:"Let AI analyze products and suggest the best matches. Requires AI to be configured in AI Settings."}],wo=[{value:"large",label:"Large",description:"Portrait cards (4:5) with full product info, description, and tags."},{value:"square",label:"Square",description:"Square cards (1:1) showing title and price only."},{value:"compact",label:"Compact",description:"Compact cards (3:4) with smaller text to fit more products."}],_o=[{value:"center",label:"Center"},{value:"top",label:"Top"},{value:"bottom",label:"Bottom"},{value:"left",label:"Left"},{value:"right",label:"Right"}],nh=[{id:"shop-page",label:"Shop Page"},{id:"catalog",label:"Catalog"},{id:"layouts",label:"Layouts"},{id:"product-pages",label:"Product Pages"},{id:"checkout",label:"Checkout"}];function Vl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("shop-page"),[a,i]=y.useState(bo),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),h=y.useCallback(async()=>{try{p(null);let S;const A="/admin/config/storefront";if(r?.isAuthenticated())S=await r.fetchWithAuth(A);else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}${A}`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch settings: ${B.status}`);S=await B.json()}i({...bo,...S.config})}catch{i(bo),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{h()},[h]);const _=y.useCallback(async S=>{const A="/admin/config/storefront",I=JSON.stringify({config:S});try{if(r?.isAuthenticated())await r.fetchWithAuth(A,{method:"PUT",body:I});else{const B={"Content-Type":"application/json"};t&&(B["X-API-Key"]=t);const D=await fetch(`${e}${A}`,{method:"PUT",headers:B,body:I});if(!D.ok)throw new Error(`Failed to save settings: ${D.status}`)}}catch{throw p("Failed to save storefront settings"),new Error("Save failed")}},[e,t,r]),{status:g,error:f}=Ta({data:a,onSave:_,debounceMs:1500,enabled:!d}),w=S=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,mode:S}}))},j=S=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,maxItems:S}}))},b=(S,A)=>{i(I=>({...I,relatedProducts:{...I.relatedProducts,layout:{...I.relatedProducts.layout,[S]:A}}}))},v=(S,A)=>{i(I=>({...I,catalog:{...I.catalog,filters:{...I.catalog.filters,[S]:A}}}))},k=(S,A)=>{const I=a.catalog.sort,B=Object.values(I).filter(Boolean).length;!A&&B<=1||i(D=>({...D,catalog:{...D.catalog,sort:{...D.catalog.sort,[S]:A}}}))},R=(S,A)=>{i(I=>({...I,checkout:{...I.checkout,[S]:A}}))},N=(S,A)=>{i(I=>({...I,shopLayout:{...I.shopLayout,[S]:A}}))},C=(S,A)=>{i(I=>({...I,categoryLayout:{...I.categoryLayout,[S]:A}}))},T=(S,A)=>{i(I=>({...I,sections:{...I.sections,[S]:A}}))},O=(S,A)=>{i(I=>({...I,inventory:{...I.inventory,[S]:A}}))},$=(S,A)=>{i(I=>({...I,shopPage:{...I.shopPage,[S]:A}}))};return c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading storefront settings..."]})}):n.jsxs("div",{className:"cedros-admin__storefront-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Storefront"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure catalog filters, product layouts, and checkout settings."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[nh.map(S=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===S.id?"cedros-admin__tab--active":""}`,onClick:()=>o(S.id),children:S.label},S.id)),n.jsx("div",{style:{flex:1}}),n.jsx(rh,{status:g,error:f})]}),n.jsx(Yt,{message:u,onRetry:h}),s==="shop-page"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Shop Page Content"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Customize the title and description shown on your shop page."}),n.jsxs("div",{className:"cedros-admin__field",style:{marginBottom:"1.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.shopPage.title,onChange:S=>$("title",S.target.value),placeholder:"Shop"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"The main heading displayed on your shop page."})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Description"}),n.jsx("textarea",{className:"cedros-admin__textarea",value:a.shopPage.description,onChange:S=>$("description",S.target.value),placeholder:"Browse our collection of products...",rows:3,style:{resize:"vertical"}}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"A short description or subtitle shown below the title. Leave empty to hide."})]})]}),s==="catalog"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Catalog Filters"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which filters appear in the shop and category page sidebars."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.filters.tags,onChange:S=>v("tags",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Tags"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter products by tags (multi-select checkboxes)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.filters.priceRange,onChange:S=>v("priceRange",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price Range"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter by minimum and maximum price"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.filters.inStock,onChange:S=>v("inStock",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"In Stock"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show only products that are in stock"})]})]})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Sort Options"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sort options appear in the shop and category pages. At least one must be enabled."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.sort.featured,onChange:S=>k("featured",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Featured"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Default sort order (as returned by backend)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.sort.priceAsc,onChange:S=>k("priceAsc",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: Low to High"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price ascending"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.catalog.sort.priceDesc,onChange:S=>k("priceDesc",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: High to Low"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price descending"})]})]})]})]})]}),s==="layouts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Product Layouts"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Configure product card layouts for shop and category pages."}),n.jsxs("div",{style:{marginBottom:"2rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Shop Page"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:wo.map(S=>{const A=a.shopLayout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"shopLayout",value:S.value,checked:A,onChange:()=>N("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(ot,{value:a.shopLayout.imageCrop,onChange:S=>N("imageCrop",S),options:_o,label:"Image Crop",style:{maxWidth:180}})]}),n.jsxs("div",{style:{paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Category Pages"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:wo.map(S=>{const A=a.categoryLayout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"categoryLayout",value:S.value,checked:A,onChange:()=>C("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(ot,{value:a.categoryLayout.imageCrop,onChange:S=>C("imageCrop",S),options:_o,label:"Image Crop",style:{maxWidth:180}})]})]}),s==="product-pages"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Related Products"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure how related products are displayed on product detail pages."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"1.5rem"},children:th.map(S=>{const A=a.relatedProducts.mode===S.value,I=S.badge==="Coming Soon";return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"1rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:8,cursor:I?"not-allowed":"pointer",opacity:I?.6:1,background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedProductsMode",value:S.value,checked:A,onChange:()=>!I&&w(S.value),disabled:I,style:{marginTop:2}}),n.jsxs("div",{style:{flex:1},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("span",{style:{fontWeight:600},children:S.label}),S.badge&&n.jsx("span",{style:{fontSize:11,padding:"2px 6px",borderRadius:4,background:"#6366f1",color:"#fff"},children:S.badge})]}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:13,opacity:.75},children:S.description})]})]},S.value)})}),a.relatedProducts.mode==="manual"&&n.jsxs("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #f5f5f5)",borderRadius:8,border:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("strong",{style:{fontSize:14},children:"How to set related products:"}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.8},children:["When editing a product, add a ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"relatedProductIds"})," field to its metadata containing a comma-separated list of product IDs."]}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.6},children:["Example: ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"prod_123,prod_456,prod_789"})]})]}),n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Max Related Products"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.relatedProducts.maxItems,onChange:S=>j(Math.max(1,Math.min(12,parseInt(S.target.value)||4))),min:1,max:12}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How many related products to show (1-12)"})]}),n.jsxs("div",{style:{marginTop:"1.5rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Display Layout"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:wo.map(S=>{const A=a.relatedProducts.layout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedLayout",value:S.value,checked:A,onChange:()=>b("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(ot,{value:a.relatedProducts.layout.imageCrop,onChange:S=>b("imageCrop",S),options:_o,label:"Image Crop",style:{maxWidth:180}})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Page Sections"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sections appear on product detail pages."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showDescription,onChange:S=>T("showDescription",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Description"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Expandable description accordion"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showSpecs,onChange:S=>T("showSpecs",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Specifications"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product attributes and details"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showShipping,onChange:S=>T("showShipping",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Shipping & Returns"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Shipping and return policy information"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.sections.showRelatedProducts,onChange:S=>T("showRelatedProducts",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Related Products"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product recommendations section"})]})]})]})]})]}),s==="checkout"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Checkout Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure checkout and cart page features."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.checkout.promoCodes,onChange:S=>R("promoCodes",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Promo Codes"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show promo/coupon code input on cart and checkout pages"})]})]})})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Inventory Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure inventory verification and reservation behavior."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.inventory.preCheckoutVerification,onChange:S=>O("preCheckoutVerification",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Pre-Checkout Verification"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Verify inventory availability before processing payment"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(bt,{checked:a.inventory.holdsEnabled,onChange:S=>O("holdsEnabled",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Inventory Holds"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Reserve inventory when items are added to cart"})]})]})]}),a.inventory.holdsEnabled&&n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200,marginTop:"1rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Hold Duration (minutes)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.inventory.holdDurationMinutes,onChange:S=>O("holdDurationMinutes",Math.max(5,Math.min(60,parseInt(S.target.value)||15))),min:5,max:60}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How long to reserve inventory in carts (5-60 minutes)"})]})]})]})]})}function rh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function bt({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:()=>t(!e),style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const sh=Object.freeze(Object.defineProperty({__proto__:null,StorefrontSection:Vl},Symbol.toStringTag,{value:"Module"})),jo=[{id:"not_set",label:"Not Set",provider:null},{id:"gemini-2.5-flash",label:"Gemini 2.5 Flash",provider:"gemini"},{id:"gemini-2.5-pro",label:"Gemini 2.5 Pro",provider:"gemini"},{id:"openai-4o",label:"OpenAI 4o",provider:"openai"},{id:"openai-5.1",label:"OpenAI 5.1",provider:"openai"},{id:"openai-5.2",label:"OpenAI 5.2",provider:"openai"}],Jo=[{task:"site_chat",label:"Site Chat",description:"The conversational model that crafts responses to customer messages",defaultPrompt:`You are a friendly and helpful shopping assistant for our store. Your role is to:
|
|
3
|
+
`).filter(Boolean)),placeholder:"One item per line",rows:3,disabled:s}),_(v.description)]})}if(v.type==="object")return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:v.label}),n.jsx("textarea",{className:"cedros-admin__textarea cedros-admin__textarea--mono",value:JSON.stringify(b,null,2),onChange:N=>{try{p(j,JSON.parse(N.target.value))}catch{}},rows:5,disabled:s}),_(v.description)]});const k=c.has(j),R=v.isSecret&&!k&&b===_r?_r:b;return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("label",{className:"cedros-admin__field-label",children:[v.label,v.isSecret&&n.jsx("span",{className:"cedros-admin__field-secret",children:" (secret)"})]}),n.jsxs("div",{className:"cedros-admin__input-group",children:[n.jsx("input",{type:v.isSecret&&!k?"password":"text",className:"cedros-admin__input",value:R,onChange:N=>p(j,N.target.value),disabled:s,placeholder:v.isSecret?"••••••••":""}),v.isSecret&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>h(j),style:{padding:"0.5rem",minWidth:"auto"},title:k?"Hide":"Show",children:k?Q.eyeOff:Q.eye})]}),_(v.description)]})},f=Object.keys(a),w=j=>{const b=Xi(e,j,r[j]??a[j]);if(b.hidden||b.showWhen&&!a[b.showWhen])return!1;if(j==="token_decimals"){const v=a.token_mint;if(v&&J.STABLECOIN_METADATA[v])return!1}return!0};return n.jsxs("div",{className:"cedros-admin__config-editor",children:[n.jsx("div",{className:"cedros-admin__config-fields",children:f.filter(w).map(j=>n.jsx("div",{className:"cedros-admin__config-field",children:g(j,a[j])},j))}),n.jsx("div",{className:"cedros-admin__config-actions",children:n.jsx("div",{className:"cedros-admin__autosave-status",children:n.jsx(Jf,{status:m,error:u})})})]})}function Kf({label:e,value:t,onChange:r,decimals:s,onDecimalsChange:o,disabled:a=!1,description:i,customSymbol:c="",customIcon:l="",onCustomSymbolChange:d,onCustomIconChange:m}){const[u,p]=y.useState(!1),h=Object.entries(J.STABLECOIN_METADATA),g=!!J.STABLECOIN_METADATA[t],w=u||!!t&&!g,j=b=>{if(b==="custom")p(!0),g&&r("");else{p(!1),r(b);const v=J.STABLECOIN_METADATA[b];v&&o&&o(v.decimals),d&&d(""),m&&m("")}};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:e}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem"},children:[h.map(([b,v])=>n.jsxs("button",{type:"button",onClick:()=>j(b),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:t===b?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:t===b?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:t===b?600:400},children:[n.jsx("img",{src:v.icon,alt:v.symbol,style:{width:20,height:20,borderRadius:"50%"},onError:k=>{k.target.style.display="none"}}),n.jsx("span",{children:v.symbol})]},b)),n.jsxs("button",{type:"button",onClick:()=>j("custom"),disabled:a,style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",border:w?"2px solid var(--cedros-admin-primary, #171717)":"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem",background:w?"var(--cedros-admin-primary-bg, #f5f5f5)":"var(--cedros-admin-bg, #fff)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,fontWeight:w?600:400},children:[n.jsx("span",{style:{fontSize:"1rem"},children:"+"}),n.jsx("span",{children:"Custom"})]})]}),w&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"1rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:[n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Mint Address"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:t,onChange:b=>r(b.target.value),placeholder:"e.g., EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",disabled:a,style:{fontFamily:"monospace",fontSize:"0.875rem"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Symbol"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:b=>d?.(b.target.value),placeholder:"e.g., MYTOKEN",disabled:a,style:{textTransform:"uppercase"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Icon URL"}),n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:l,onChange:b=>m?.(b.target.value),placeholder:"https://example.com/token-logo.png",disabled:a,style:{flex:1}}),l&&n.jsx("img",{src:l,alt:"Token icon preview",style:{width:32,height:32,borderRadius:"50%",border:"1px solid var(--cedros-admin-border, #e5e7eb)",objectFit:"cover"},onError:b=>{b.target.style.display="none"}})]}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Shown to customers during checkout"})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontSize:"0.75rem",fontWeight:500,marginBottom:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)"},children:"Token Decimals"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:s??6,onChange:b=>o?.(parseInt(b.target.value,10)||0),min:0,max:18,disabled:a,style:{width:"100px"}}),n.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #94a3b8)",marginTop:"0.25rem"},children:"Most SPL tokens use 6 decimals (like USDC)"})]})]}),t&&g&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",fontFamily:"monospace",wordBreak:"break-all"},children:t}),i&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.25rem"},children:i})]})]})}function Xf({label:e,value:t,onChange:r,disabled:s=!1,description:o}){const[a,i]=y.useState(new Set),[c,l]=y.useState(null),[d,m]=y.useState(""),u=Array.isArray(t)?t:[],p=b=>{i(v=>{const k=new Set(v);return k.has(b)?k.delete(b):k.add(b),k})},h=()=>{r([...u,""]),l(u.length),m("")},_=(b,v)=>{const k=[...u];k[b]=v,r(k)},g=b=>{const v=u.filter((k,R)=>R!==b);r(v),i(k=>{const R=new Set;return k.forEach(N=>{N<b?R.add(N):N>b&&R.add(N-1)}),R})},f=b=>{l(b),m(u[b]||"")},w=()=>{c!==null&&(_(c,d),l(null),m(""))},j=()=>{c!==null&&u[c]===""&&g(c),l(null),m("")};return n.jsxs("div",{className:"cedros-admin__field",children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",style:{marginBottom:0},children:e}),n.jsxs("button",{type:"button",onClick:h,disabled:s,style:{display:"flex",alignItems:"center",gap:"0.25rem",padding:"0.25rem 0.5rem",fontSize:"0.75rem",border:"1px solid var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.375rem",background:"var(--cedros-admin-bg, #fff)",cursor:s?"not-allowed":"pointer",opacity:s?.5:1},children:[Q.plus,"Add"]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u.length===0&&n.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"0.875rem",border:"1px dashed var(--cedros-admin-border, #d4d4d4)",borderRadius:"0.5rem"},children:'No items. Click "Add" to create one.'}),u.map((b,v)=>{const k=a.has(v),R=c===v,N=b===_r;return n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"var(--cedros-admin-bg-muted, #f9fafb)",borderRadius:"0.375rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)"},children:R?n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",className:"cedros-admin__input",value:d,onChange:C=>m(C.target.value),placeholder:"Enter wallet keypair...",autoFocus:!0,style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem"},onKeyDown:C=>{C.key==="Enter"&&w(),C.key==="Escape"&&j()}}),n.jsx("button",{type:"button",onClick:w,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-success, #22c55e)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Save",children:Q.check}),n.jsx("button",{type:"button",onClick:j,style:{padding:"0.375rem",border:"none",background:"var(--cedros-admin-text-muted, #64748b)",color:"#fff",borderRadius:"0.25rem",cursor:"pointer"},title:"Cancel",children:Q.close})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1,fontFamily:"monospace",fontSize:"0.75rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k&&!N?b:N?"[REDACTED]":"••••••••••••••••••••"}),n.jsx("button",{type:"button",onClick:()=>p(v),disabled:s||N,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s||N?"not-allowed":"pointer",opacity:s||N?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:k?"Hide":"Show",children:k?Q.eyeOff:Q.eye}),n.jsx("button",{type:"button",onClick:()=>f(v),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-text-muted, #64748b)"},title:"Edit",children:Q.settings}),n.jsx("button",{type:"button",onClick:()=>g(v),disabled:s,style:{padding:"0.375rem",border:"none",background:"transparent",cursor:s?"not-allowed":"pointer",opacity:s?.5:1,color:"var(--cedros-admin-error, #ef4444)"},title:"Delete",children:Q.trash})]})},v)})]}),o&&n.jsx("div",{style:{fontSize:"0.75rem",color:"var(--cedros-admin-text-muted, #64748b)",marginTop:"0.5rem"},children:o})]})}function Jf({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${e}`,style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx(n.Fragment,{children:n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"})}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx(n.Fragment,{children:n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})})]})}function ql({serverUrl:e,apiKey:t,authManager:r,category:s,title:o,description:a,enabledField:i="enabled",showEnabledToggle:c=!1}){const l=y.useMemo(()=>new Gf(e,void 0,r),[e,r]),[d,m]=y.useState(null),[u,p]=y.useState([]),[h,_]=y.useState(!1),[g,f]=y.useState(!0),[w,j]=y.useState(null),[b,v]=y.useState(null),[k,R]=y.useState(!1),N=Ta[s]||{label:s,icon:"⚙️"},C=o||N.label,T=a||N.description,O=y.useCallback(async()=>{f(!0),j(null);try{const P=await l.getConfig(s,!0);m(P)}catch{m(null),j("Failed to load settings")}finally{f(!1)}},[l,s]);y.useEffect(()=>{O()},[O]);const $=y.useCallback(async()=>{try{const P=await l.getHistory(s,20);p(P.history)}catch{p([])}},[l,s]);y.useEffect(()=>{h&&$()},[h,$]);const S=y.useCallback(async P=>{await l.updateConfig(s,P,"Updated via admin dashboard"),await O()},[l,s,O]),A=y.useCallback(async P=>l.validateConfig(s,P),[l,s]),[I,B]=y.useState(!1),L=y.useCallback(async()=>{if(!d||I)return;const P=!!d.config[i],z=!P,Z={...d.config,[i]:z};B(!0),m({...d,config:Z});try{await l.updateConfig(s,Z,`${z?"Enabled":"Disabled"} via admin dashboard`)}catch(K){m({...d,config:{...d.config,[i]:P}}),j(K instanceof Error?K.message:"Failed to save enabled state")}finally{B(!1)}},[d,l,s,i,I]),E=!!d?.config[i];return g&&!d?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading ",C," settings..."]})}):n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx(Kt,{message:w,onRetry:O}),n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{children:[n.jsxs("h3",{className:"cedros-admin__section-title",children:[n.jsx("span",{style:{marginRight:"0.5rem"},children:N.icon}),C]}),T&&n.jsx("p",{className:"cedros-admin__text-muted",style:{marginTop:"0.25rem"},children:T})]}),c&&d&&i in d.config&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("span",{style:{fontSize:"0.875rem",color:E?"var(--cedros-admin-text, #171717)":"var(--cedros-admin-muted, #737373)"},children:E?"Enabled":"Disabled"}),n.jsx("button",{type:"button",role:"switch","aria-checked":E,onClick:L,disabled:I,style:{width:44,height:24,borderRadius:12,border:"none",backgroundColor:E?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:I?"wait":"pointer",position:"relative",transition:"background-color 0.2s",flexShrink:0,opacity:I?.6:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:E?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"#fff",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})]})]}),d&&n.jsxs("div",{className:"cedros-admin__settings-editor",style:{marginTop:"1rem",opacity:c&&!E?.6:1,pointerEvents:c&&!E?"none":"auto"},children:[c&&!E&&n.jsx("div",{style:{padding:"0.75rem 1rem",marginBottom:"1rem",backgroundColor:"var(--cedros-admin-warning-bg, #fef3c7)",border:"1px solid var(--cedros-admin-warning-border, #f59e0b)",borderRadius:"0.375rem",fontSize:"0.875rem",color:"var(--cedros-admin-warning-text, #92400e)",pointerEvents:"auto"},children:"This payment method is disabled. Enable it using the toggle above to accept payments."}),n.jsx(Yf,{category:d.category,config:d.config,originalConfig:d.config,onSave:S,onValidate:A,onCancel:()=>O()})]}),h&&n.jsxs("div",{className:"cedros-admin__settings-history",style:{marginTop:"1.5rem"},children:[n.jsx("h4",{style:{marginBottom:"0.75rem",fontWeight:600},children:"Change History"}),u.length===0?n.jsx("p",{className:"cedros-admin__text-muted",children:"No history entries found."}):n.jsx("div",{className:"cedros-admin__settings-timeline",children:u.map(P=>n.jsxs("div",{className:"cedros-admin__settings-timeline-item",children:[n.jsx("div",{className:"cedros-admin__settings-timeline-dot"}),n.jsxs("div",{className:"cedros-admin__settings-timeline-content",children:[n.jsxs("div",{className:"cedros-admin__settings-timeline-header",children:[n.jsx("code",{children:P.configKey}),n.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${P.action.toLowerCase()}`,children:P.action})]}),n.jsxs("div",{className:"cedros-admin__settings-timeline-meta",children:[Sr(P.changedAt)," by ",P.changedBy]})]})]},P.id))})]}),b&&n.jsx("div",{style:{marginTop:"1rem",padding:"0.75rem 1rem",borderRadius:"0.375rem",backgroundColor:b.valid?"var(--cedros-admin-success-bg, #dcfce7)":"var(--cedros-admin-error-bg, #fef2f2)",border:`1px solid ${b.valid?"var(--cedros-admin-success-border, #86efac)":"var(--cedros-admin-error-border, #fecaca)"}`},children:n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:600,color:b.valid?"var(--cedros-admin-success, #16a34a)":"var(--cedros-admin-error, #dc2626)",marginBottom:b.errors.length>0||b.warnings.length>0?"0.5rem":0},children:b.valid?"✓ Configuration is valid":"✗ Validation failed"}),b.errors.length>0&&n.jsx("ul",{style:{margin:0,paddingLeft:"1.25rem",color:"var(--cedros-admin-error, #dc2626)",fontSize:"0.875rem"},children:b.errors.map((P,z)=>n.jsx("li",{children:P},z))}),b.warnings.length>0&&n.jsx("ul",{style:{margin:b.errors.length>0?"0.5rem 0 0":0,paddingLeft:"1.25rem",color:"var(--cedros-admin-warning, #ca8a04)",fontSize:"0.875rem"},children:b.warnings.map((P,z)=>n.jsx("li",{children:P},z))})]}),n.jsx("button",{type:"button",onClick:()=>v(null),style:{background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"var(--cedros-admin-text-muted, #64748b)",fontSize:"1.25rem",lineHeight:1},title:"Dismiss",children:"×"})]})}),n.jsxs("div",{style:{marginTop:"1.5rem",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:()=>_(!h),children:h?"Hide History":"History"}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",disabled:k||!d,onClick:async()=>{if(d){R(!0),v(null);try{const P=await A(d.config);v(P)}catch(P){v({valid:!1,errors:[P instanceof Error?P.message:"Validation failed"],warnings:[]})}finally{R(!1)}}},children:k?"Validating...":"Validate"})]})]})}const Ji=[{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 Ra({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("logging"),a=Ji.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:Ji.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(ql,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description},a.category)})]})}const eh=Object.freeze(Object.defineProperty({__proto__:null,SettingsSection:Ra},Symbol.toStringTag,{value:"Module"})),je={enabled:!1,plans:[],pageTitle:"Choose Your Plan",pageSubtitle:"Select the plan that best fits your needs.",annualSavingsBadge:"2 months free",popularBadgeText:"Best Deal",footerNotice:""},th={title:"New Plan",description:"",priceMonthlyUsd:0,priceAnnualUsd:0,features:[],featureHighlight:"",buttonText:"Purchase",isPopular:!1,isActive:!0,sortOrder:0};function nh(){return`plan_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Hl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState(je),[a,i]=y.useState(!0),[c,l]=y.useState(null),[d,m]=y.useState("plans"),[u,p]=y.useState("idle"),[h,_]=y.useState(null),[g,f]=y.useState({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),[w,j]=y.useState(g),[b,v]=y.useState(""),k=y.useCallback(async()=>{try{_(null);let D;const W="/admin/subscriptions/settings";if(r?.isAuthenticated())D=await r.fetchWithAuth(W);else{const Y={"Content-Type":"application/json"};t&&(Y["X-API-Key"]=t);const V=await fetch(`${e}${W}`,{headers:Y});if(!V.ok)throw new Error(`Failed to fetch settings: ${V.status}`);D=await V.json()}o({...je,...D}),f({enabled:D.enabled??je.enabled,pageTitle:D.pageTitle??je.pageTitle,pageSubtitle:D.pageSubtitle??je.pageSubtitle,annualSavingsBadge:D.annualSavingsBadge??je.annualSavingsBadge,popularBadgeText:D.popularBadgeText??je.popularBadgeText,footerNotice:D.footerNotice??je.footerNotice}),j({enabled:D.enabled??je.enabled,pageTitle:D.pageTitle??je.pageTitle,pageSubtitle:D.pageSubtitle??je.pageSubtitle,annualSavingsBadge:D.annualSavingsBadge??je.annualSavingsBadge,popularBadgeText:D.popularBadgeText??je.popularBadgeText,footerNotice:D.footerNotice??je.footerNotice}),v(JSON.stringify(D.plans??[]))}catch{o(je),f({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),j({enabled:je.enabled,pageTitle:je.pageTitle,pageSubtitle:je.pageSubtitle,annualSavingsBadge:je.annualSavingsBadge,popularBadgeText:je.popularBadgeText,footerNotice:je.footerNotice}),v(JSON.stringify([])),_("Failed to load subscription settings")}finally{i(!1)}},[e,t,r]);y.useEffect(()=>{k()},[k]);const R=y.useCallback(async D=>{try{_(null);const W="/admin/subscriptions/settings",Y=JSON.stringify(D);if(r?.isAuthenticated())await r.fetchWithAuth(W,{method:"PUT",body:Y});else{const V={"Content-Type":"application/json"};t&&(V["X-API-Key"]=t);const ce=await fetch(`${e}${W}`,{method:"PUT",headers:V,body:Y});if(!ce.ok)throw new Error(`Failed to save settings: ${ce.status}`)}return!0}catch{return _("Failed to save subscription settings"),!1}},[r,t,e]),N=y.useMemo(()=>w.enabled!==g.enabled||w.pageTitle!==g.pageTitle||w.pageSubtitle!==g.pageSubtitle||w.annualSavingsBadge!==g.annualSavingsBadge||w.popularBadgeText!==g.popularBadgeText||w.footerNotice!==g.footerNotice,[g,w]),C=y.useMemo(()=>JSON.stringify(s.plans),[s.plans]),T=y.useMemo(()=>b!==C,[C,b]),O=y.useCallback(async()=>{const D={...s,enabled:g.enabled,pageTitle:g.pageTitle,pageSubtitle:g.pageSubtitle,annualSavingsBadge:g.annualSavingsBadge,popularBadgeText:g.popularBadgeText,footerNotice:g.footerNotice};p("saving");const W=await R(D);o(D),W&&(j({enabled:D.enabled,pageTitle:D.pageTitle,pageSubtitle:D.pageSubtitle,annualSavingsBadge:D.annualSavingsBadge,popularBadgeText:D.popularBadgeText,footerNotice:D.footerNotice}),v(JSON.stringify(D.plans))),p(W?"saved":"error"),setTimeout(()=>p("idle"),1500)},[g,R,s]);y.useEffect(()=>{if(d!=="page"||a||!N)return;const D=setTimeout(O,600);return()=>clearTimeout(D)},[d,N,a,O]),y.useEffect(()=>{if(d!=="plans"||a||!T)return;const D=setTimeout(O,800);return()=>clearTimeout(D)},[d,T,a,O]);const $=()=>{const D={...th,id:nh(),sortOrder:s.plans.length};o(W=>({...W,plans:[...W.plans,D]})),l(D.id)},S=(D,W)=>{o(Y=>({...Y,plans:Y.plans.map(V=>V.id===D?{...V,...W}:V)}))},A=D=>{confirm("Delete this plan? This cannot be undone.")&&(o(W=>({...W,plans:W.plans.filter(Y=>Y.id!==D)})),c===D&&l(null))},I=(D,W)=>{const Y=s.plans.findIndex(F=>F.id===D);if(Y===-1||W==="up"&&Y===0||W==="down"&&Y===s.plans.length-1)return;const V=[...s.plans],ce=W==="up"?Y-1:Y+1;[V[Y],V[ce]]=[V[ce],V[Y]],o(F=>({...F,plans:V}))},B=D=>{S(D,{features:[...s.plans.find(W=>W.id===D)?.features||[],""]})},L=(D,W,Y)=>{const V=s.plans.find(F=>F.id===D);if(!V)return;const ce=[...V.features];ce[W]=Y,S(D,{features:ce})},E=(D,W)=>{const Y=s.plans.find(ce=>ce.id===D);if(!Y)return;const V=Y.features.filter((ce,F)=>F!==W);S(D,{features:V})};if(a)return n.jsx("div",{className:"cedros-admin__page",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading subscription settings..."]})});const P=s.plans.filter(D=>D.isActive).length,z=s.plans.reduce((D,W)=>D+(W.activeSubscribers??0),0),Z=g.enabled,K=s.plans.filter(D=>D.isActive).map(D=>({label:D.title,value:D.activeSubscribers??0,description:"subscribers"}));return n.jsxs("div",{className:"cedros-admin__page",children:[n.jsx(Kt,{message:h,onRetry:k}),n.jsx(sr,{stats:[{label:"Status",value:Z?"Enabled":"Disabled",variant:Z?"success":"muted"},{label:"Active Plans",value:P,variant:P>0?"success":"muted"},{label:"Total Subscribers",value:z,variant:z>0?"success":"muted"},...K],isLoading:a}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Subscription Settings"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[d==="plans"&&n.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:$,disabled:!Z,children:[Q.plus,"Add Plan"]}),n.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${u}`,children:[u==="saving"&&"Saving...",u==="saved"&&"Saved",u==="error"&&"Error"]})]})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="plans"?"cedros-admin__tab--active":""}`,onClick:()=>m("plans"),children:"Plans"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${d==="page"?"cedros-admin__tab--active":""}`,onClick:()=>m("page"),children:"Page Settings"})]}),d==="page"&&n.jsxs("div",{children:[n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Subscriptions"}),n.jsxs("label",{className:"cedros-admin__toggle",children:[n.jsx("input",{type:"checkbox",className:"cedros-admin__toggle-input",checked:g.enabled,onChange:D=>f(W=>({...W,enabled:D.target.checked}))}),n.jsx("span",{className:"cedros-admin__toggle-track",children:n.jsx("span",{className:"cedros-admin__toggle-thumb"})}),n.jsx("span",{className:"cedros-admin__toggle-label",children:"Enable Subscriptions"})]})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.pageTitle||"",onChange:D=>f(W=>({...W,pageTitle:D.target.value})),placeholder:"Choose Your Plan"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Subtitle"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.pageSubtitle||"",onChange:D=>f(W=>({...W,pageSubtitle:D.target.value})),placeholder:"Select the plan that best fits your needs."})]})]}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Savings Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.annualSavingsBadge||"",onChange:D=>f(W=>({...W,annualSavingsBadge:D.target.value})),placeholder:"2 months free"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Popular Plan Badge"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.popularBadgeText||"",onChange:D=>f(W=>({...W,popularBadgeText:D.target.value})),placeholder:"Best Deal"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Footer Notice (optional)"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:g.footerNotice||"",onChange:D=>f(W=>({...W,footerNotice:D.target.value})),placeholder:"For information regarding invoices, taxes..."})]})})]}),d==="plans"&&n.jsxs("div",{children:[!Z&&n.jsx("div",{style:{padding:"1.5rem",textAlign:"center",opacity:.6},children:"Subscriptions are disabled. Enable them to configure plans."}),s.plans.length===0?n.jsx("div",{style:{padding:"2rem",textAlign:"center",opacity:.6,border:"1px dashed currentColor",borderRadius:8},children:'No plans configured. Click "Add Plan" to create your first subscription tier.'}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:s.plans.map((D,W)=>{const Y=c===D.id;return n.jsxs("div",{style:{border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:8,overflow:"hidden",background:D.isPopular?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"1rem",padding:"0.75rem 1rem",cursor:"pointer"},onClick:()=>l(Y?null:D.id),children:[n.jsx("span",{style:{opacity:.5},children:Y?Q.chevronDown:Q.chevronRight}),n.jsxs("div",{style:{flex:1},children:[n.jsx("span",{style:{fontWeight:600},children:D.title||"Untitled Plan"}),D.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"}),!D.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:["$",D.priceMonthlyUsd,"/mo · $",D.priceAnnualUsd,"/yr"]}),n.jsxs("div",{style:{display:"flex",gap:"0.25rem"},onClick:V=>V.stopPropagation(),children:[n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>I(D.id,"up"),disabled:W===0,title:"Move up",style:{padding:"4px 8px"},children:Q.chevronUp}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>I(D.id,"down"),disabled:W===s.plans.length-1,title:"Move down",style:{padding:"4px 8px"},children:Q.chevronDown}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>A(D.id),title:"Delete plan",style:{padding:"4px 8px",color:"#dc2626"},children:Q.trash})]})]}),Y&&n.jsxs("div",{style:{padding:"1rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Plan Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:D.title,onChange:V=>S(D.id,{title:V.target.value}),placeholder:"e.g., Starter"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Button Text"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:D.buttonText||"",onChange:V=>S(D.id,{buttonText:V.target.value}),placeholder:"Purchase"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Description"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:D.description,onChange:V=>S(D.id,{description:V.target.value}),placeholder:"For entry-level developers managing lightweight workloads"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Monthly Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:D.priceMonthlyUsd||"",onChange:V=>S(D.id,{priceMonthlyUsd:parseFloat(V.target.value)||0}),placeholder:"10",min:"0",step:"0.01"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Annual Price (USD)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:D.priceAnnualUsd||"",onChange:V=>S(D.id,{priceAnnualUsd:parseFloat(V.target.value)||0}),placeholder:"100",min:"0",step:"0.01"})]})]}),n.jsx("div",{className:"cedros-admin__form-row",children:n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Feature Highlight"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:D.featureHighlight||"",onChange:V=>S(D.id,{featureHighlight:V.target.value}),placeholder:"100 prompts every 5 hours"}),n.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Bold text shown above feature list"})]})}),n.jsxs("div",{className:"cedros-admin__form-row",children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:D.isPopular||!1,onChange:V=>S(D.id,{isPopular:V.target.checked})}),"Mark as Popular (featured styling)"]})}),n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:D.isActive,onChange:V=>S(D.id,{isActive:V.target.checked})}),"Active (available for purchase)"]})})]}),n.jsxs("div",{className:"cedros-admin__form-row",style:{marginTop:"0.5rem"},children:[n.jsx("div",{className:"cedros-admin__field",children:n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:D.inventoryQuantity!=null,onChange:V=>S(D.id,{inventoryQuantity:V.target.checked?100:null})}),"Limit quantity available"]})}),D.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:D.inventoryQuantity??"",onChange:V=>S(D.id,{inventoryQuantity:parseInt(V.target.value)||0}),min:"0",style:{width:100}}),D.inventorySold!=null&&D.inventorySold>0&&n.jsxs("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:[D.inventorySold," sold · ",Math.max(0,D.inventoryQuantity-D.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 (",D.features.length,")"]}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>B(D.id),style:{fontSize:12,padding:"4px 8px"},children:"+ Add Feature"})]}),D.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:D.features.map((V,ce)=>n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsxs("span",{style:{opacity:.4,fontSize:12},children:[ce+1,"."]}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:V,onChange:F=>L(D.id,ce,F.target.value),placeholder:"e.g., Powered by MiniMax M2.1",style:{flex:1}}),n.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>E(D.id,ce),style:{padding:"4px 8px",color:"#dc2626"},title:"Remove feature",children:Q.trash})]},ce))})]})]})]},D.id)})})]})]})]})}const rh=Object.freeze(Object.defineProperty({__proto__:null,SubscriptionsSection:Hl},Symbol.toStringTag,{value:"Module"})),wo={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:""}},sh=[{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."}],_o=[{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."}],jo=[{value:"center",label:"Center"},{value:"top",label:"Top"},{value:"bottom",label:"Bottom"},{value:"left",label:"Left"},{value:"right",label:"Right"}],oh=[{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 Zl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("shop-page"),[a,i]=y.useState(wo),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),h=y.useCallback(async()=>{try{p(null);let S;const A="/admin/config/storefront";if(r?.isAuthenticated())S=await r.fetchWithAuth(A);else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}${A}`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch settings: ${B.status}`);S=await B.json()}i({...wo,...S.config})}catch{i(wo),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{h()},[h]);const _=y.useCallback(async S=>{const A="/admin/config/storefront",I=JSON.stringify({config:S});try{if(r?.isAuthenticated())await r.fetchWithAuth(A,{method:"PUT",body:I});else{const B={"Content-Type":"application/json"};t&&(B["X-API-Key"]=t);const L=await fetch(`${e}${A}`,{method:"PUT",headers:B,body:I});if(!L.ok)throw new Error(`Failed to save settings: ${L.status}`)}}catch{throw p("Failed to save storefront settings"),new Error("Save failed")}},[e,t,r]),{status:g,error:f}=Ia({data:a,onSave:_,debounceMs:1500,enabled:!d}),w=S=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,mode:S}}))},j=S=>{i(A=>({...A,relatedProducts:{...A.relatedProducts,maxItems:S}}))},b=(S,A)=>{i(I=>({...I,relatedProducts:{...I.relatedProducts,layout:{...I.relatedProducts.layout,[S]:A}}}))},v=(S,A)=>{i(I=>({...I,catalog:{...I.catalog,filters:{...I.catalog.filters,[S]:A}}}))},k=(S,A)=>{const I=a.catalog.sort,B=Object.values(I).filter(Boolean).length;!A&&B<=1||i(L=>({...L,catalog:{...L.catalog,sort:{...L.catalog.sort,[S]:A}}}))},R=(S,A)=>{i(I=>({...I,checkout:{...I.checkout,[S]:A}}))},N=(S,A)=>{i(I=>({...I,shopLayout:{...I.shopLayout,[S]:A}}))},C=(S,A)=>{i(I=>({...I,categoryLayout:{...I.categoryLayout,[S]:A}}))},T=(S,A)=>{i(I=>({...I,sections:{...I.sections,[S]:A}}))},O=(S,A)=>{i(I=>({...I,inventory:{...I.inventory,[S]:A}}))},$=(S,A)=>{i(I=>({...I,shopPage:{...I.shopPage,[S]:A}}))};return c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading storefront settings..."]})}):n.jsxs("div",{className:"cedros-admin__storefront-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Storefront"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure catalog filters, product layouts, and checkout settings."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[oh.map(S=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===S.id?"cedros-admin__tab--active":""}`,onClick:()=>o(S.id),children:S.label},S.id)),n.jsx("div",{style:{flex:1}}),n.jsx(ah,{status:g,error:f})]}),n.jsx(Kt,{message:u,onRetry:h}),s==="shop-page"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Shop Page Content"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Customize the title and description shown on your shop page."}),n.jsxs("div",{className:"cedros-admin__field",style:{marginBottom:"1.5rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Title"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.shopPage.title,onChange:S=>$("title",S.target.value),placeholder:"Shop"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"The main heading displayed on your shop page."})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Page Description"}),n.jsx("textarea",{className:"cedros-admin__textarea",value:a.shopPage.description,onChange:S=>$("description",S.target.value),placeholder:"Browse our collection of products...",rows:3,style:{resize:"vertical"}}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"A short description or subtitle shown below the title. Leave empty to hide."})]})]}),s==="catalog"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Catalog Filters"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which filters appear in the shop and category page sidebars."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.catalog.filters.tags,onChange:S=>v("tags",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Tags"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter products by tags (multi-select checkboxes)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.catalog.filters.priceRange,onChange:S=>v("priceRange",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price Range"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Filter by minimum and maximum price"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.catalog.filters.inStock,onChange:S=>v("inStock",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"In Stock"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show only products that are in stock"})]})]})]})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Sort Options"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Choose which sort options appear in the shop and category pages. At least one must be enabled."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.catalog.sort.featured,onChange:S=>k("featured",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Featured"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Default sort order (as returned by backend)"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.catalog.sort.priceAsc,onChange:S=>k("priceAsc",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: Low to High"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price ascending"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.catalog.sort.priceDesc,onChange:S=>k("priceDesc",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Price: High to Low"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Sort products by price descending"})]})]})]})]})]}),s==="layouts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Product Layouts"}),n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:14,opacity:.7},children:"Configure product card layouts for shop and category pages."}),n.jsxs("div",{style:{marginBottom:"2rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Shop Page"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:_o.map(S=>{const A=a.shopLayout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"shopLayout",value:S.value,checked:A,onChange:()=>N("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(at,{value:a.shopLayout.imageCrop,onChange:S=>N("imageCrop",S),options:jo,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:_o.map(S=>{const A=a.categoryLayout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"categoryLayout",value:S.value,checked:A,onChange:()=>C("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(at,{value:a.categoryLayout.imageCrop,onChange:S=>C("imageCrop",S),options:jo,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:sh.map(S=>{const A=a.relatedProducts.mode===S.value,I=S.badge==="Coming Soon";return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"1rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:8,cursor:I?"not-allowed":"pointer",opacity:I?.6:1,background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedProductsMode",value:S.value,checked:A,onChange:()=>!I&&w(S.value),disabled:I,style:{marginTop:2}}),n.jsxs("div",{style:{flex:1},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[n.jsx("span",{style:{fontWeight:600},children:S.label}),S.badge&&n.jsx("span",{style:{fontSize:11,padding:"2px 6px",borderRadius:4,background:"#6366f1",color:"#fff"},children:S.badge})]}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:13,opacity:.75},children:S.description})]})]},S.value)})}),a.relatedProducts.mode==="manual"&&n.jsxs("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #f5f5f5)",borderRadius:8,border:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("strong",{style:{fontSize:14},children:"How to set related products:"}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.8},children:["When editing a product, add a ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"relatedProductIds"})," field to its metadata containing a comma-separated list of product IDs."]}),n.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:13,opacity:.6},children:["Example: ",n.jsx("code",{style:{background:"rgba(0,0,0,0.1)",padding:"2px 4px",borderRadius:3},children:"prod_123,prod_456,prod_789"})]})]}),n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Max Related Products"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.relatedProducts.maxItems,onChange:S=>j(Math.max(1,Math.min(12,parseInt(S.target.value)||4))),min:1,max:12}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How many related products to show (1-12)"})]}),n.jsxs("div",{style:{marginTop:"1.5rem"},children:[n.jsx("div",{style:{fontWeight:500,marginBottom:"0.75rem"},children:"Display Layout"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},children:_o.map(S=>{const A=a.relatedProducts.layout.layout===S.value;return n.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:"0.75rem",border:`2px solid ${A?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #e5e5e5)"}`,borderRadius:6,cursor:"pointer",background:A?"var(--cedros-admin-bg-accent, #f5f5f5)":void 0,transition:"border-color 0.15s, background 0.15s"},children:[n.jsx("input",{type:"radio",name:"relatedLayout",value:S.value,checked:A,onChange:()=>b("layout",S.value),style:{marginTop:2}}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:S.label}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:12,opacity:.6},children:S.description})]})]},S.value)})}),n.jsx(at,{value:a.relatedProducts.layout.imageCrop,onChange:S=>b("imageCrop",S),options:jo,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(wt,{checked:a.sections.showDescription,onChange:S=>T("showDescription",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Description"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Expandable description accordion"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.sections.showSpecs,onChange:S=>T("showSpecs",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Specifications"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product attributes and details"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.sections.showShipping,onChange:S=>T("showShipping",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Shipping & Returns"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Shipping and return policy information"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.sections.showRelatedProducts,onChange:S=>T("showRelatedProducts",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Related Products"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Product recommendations section"})]})]})]})]})]}),s==="checkout"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsxs("div",{children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Checkout Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure checkout and cart page features."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.checkout.promoCodes,onChange:S=>R("promoCodes",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Promo Codes"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Show promo/coupon code input on cart and checkout pages"})]})]})})]}),n.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid var(--cedros-admin-border, #e5e5e5)"},children:[n.jsx("h4",{style:{marginBottom:"0.5rem",fontWeight:600},children:"Inventory Settings"}),n.jsx("p",{style:{marginBottom:"1rem",fontSize:14,opacity:.7},children:"Configure inventory verification and reservation behavior."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.inventory.preCheckoutVerification,onChange:S=>O("preCheckoutVerification",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Pre-Checkout Verification"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Verify inventory availability before processing payment"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(wt,{checked:a.inventory.holdsEnabled,onChange:S=>O("holdsEnabled",S)}),n.jsxs("div",{children:[n.jsx("span",{style:{fontWeight:500},children:"Inventory Holds"}),n.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:13,opacity:.6},children:"Reserve inventory when items are added to cart"})]})]})]}),a.inventory.holdsEnabled&&n.jsxs("div",{className:"cedros-admin__field",style:{maxWidth:200,marginTop:"1rem"},children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Hold Duration (minutes)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.inventory.holdDurationMinutes,onChange:S=>O("holdDurationMinutes",Math.max(5,Math.min(60,parseInt(S.target.value)||15))),min:5,max:60}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:12,opacity:.6},children:"How long to reserve inventory in carts (5-60 minutes)"})]})]})]})]})}function ah({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function wt({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 ih=Object.freeze(Object.defineProperty({__proto__:null,StorefrontSection:Zl},Symbol.toStringTag,{value:"Module"})),ko=[{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"}],ea=[{task:"site_chat",label:"Site Chat",description:"The conversational model that crafts responses to customer messages",defaultPrompt:`You are a friendly and helpful shopping assistant for our store. Your role is to:
|
|
4
4
|
|
|
5
5
|
- Help customers find products that match their needs
|
|
6
6
|
- Answer questions about products, shipping, returns, and store policies
|
|
@@ -50,9 +50,9 @@ Guidelines:
|
|
|
50
50
|
- Use sensory language when appropriate
|
|
51
51
|
- Keep descriptions scannable with short paragraphs
|
|
52
52
|
- Avoid superlatives and unverifiable claims
|
|
53
|
-
- Include relevant keywords naturally for SEO`}],oh=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],Ji={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:Jo.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function ql({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("api-keys"),[a,i]=y.useState(Ji),[c,l]=y.useState(!0),[d,m]=y.useState(!1),[u,p]=y.useState(null),[h,_]=y.useState(!1),[g,f]=y.useState(null),w=y.useRef(null),[j,b]=y.useState({gemini:"",openai:""}),[v,k]=y.useState({gemini:!1,openai:!1}),R=y.useCallback(async()=>{try{let A;if(r?.isAuthenticated())A=await r.fetchWithAuth("/admin/config/ai");else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch: ${B.status}`);A=await B.json()}A.settings&&i(A.settings)}catch{i(Ji),f("Could not load saved AI settings. Showing defaults.")}finally{l(!1)}},[e,t,r]);y.useEffect(()=>{R()},[R]);const N=y.useCallback(async A=>{const I=j[A];if(I.trim()){m(!0),p(null);try{const B={provider:A,apiKey:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,apiKeys:D.apiKeys.map(E=>E.provider===A?{...E,isConfigured:!0,maskedKey:`${I.slice(0,4)}...${I.slice(-4)}`,updatedAt:new Date().toISOString()}:E)})),b(D=>({...D,[A]:""})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save API key")}finally{m(!1)}}},[j,e,t,r]),C=y.useCallback(async A=>{if(confirm(`Are you sure you want to delete the ${A==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),p(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${A}`,{method:"DELETE"});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai/api-key/${A}`,{method:"DELETE",headers:I});if(!B.ok)throw new Error(`Failed to delete: ${B.status}`)}i(I=>({...I,apiKeys:I.apiKeys.map(B=>B.provider===A?{provider:A,isConfigured:!1}:B)}))}catch(I){p(I instanceof Error?I.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),T=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,model:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,assignedModel:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),O=y.useCallback(A=>{if(A==="not_set")return!0;const I=jo.find(D=>D.id===A);return I?.provider?a.apiKeys.find(D=>D.provider===I.provider)?.isConfigured??!1:!0},[a.apiKeys]),$=y.useMemo(()=>jo.map(A=>{const I=O(A.id);return{value:A.id,label:I?A.label:`${A.label} (API key required)`,disabled:!I}}),[O]),S=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,systemPrompt:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,systemPrompt:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return y.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),n.jsx(Yt,{message:g,onRetry:R}),h&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[Q.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:oh.map(A=>{const I=a.apiKeys.find(D=>D.provider===A.id),B=I?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:A.label}),B&&I?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",I.maskedKey,I.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(I.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${B?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:B?"Configured":"Not Set"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:v[A.id]?"text":"password",className:"cedros-admin__input",placeholder:B?"Enter new key to replace":A.placeholder,value:j[A.id],onChange:D=>b(E=>({...E,[A.id]:D.target.value})),onBlur:()=>{j[A.id].trim()&&N(A.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>k(D=>({...D,[A.id]:!D[A.id]})),title:v[A.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:v[A.id]?Q.eyeOff:Q.eye}),B&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(A.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:Q.trash})]})})]},A.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(D=>D.task===A.task),B=jo.find(D=>D.id===A.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:I?.label??A.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:I?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ot,{value:A.assignedModel,onChange:D=>T(A.task,D),options:$,label:"",disabled:d,style:{flex:1,maxWidth:280}}),B&&B.provider&&n.jsx("span",{className:`cedros-admin__badge ${O(B.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:O(B.id)?"Ready":"Missing API Key"})]})]},A.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(B=>B.task===A.task);return n.jsx(ah,{task:A.task,label:I?.label??A.task,description:I?.description??"",initialPrompt:A.systemPrompt??"",onSave:S},A.task)})})]})]})}function ah({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=y.useState(s),[c,l]=y.useState("idle"),d=y.useRef(null),m=y.useRef(null),u=y.useRef(!0);return y.useEffect(()=>{if(u.current){u.current=!1;return}return d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),l("pending"),d.current=setTimeout(async()=>{l("saving");try{await o(e,a),l("saved"),m.current=setTimeout(()=>l("idle"),2e3)}catch{l("error")}},1500),()=>{d.current&&clearTimeout(d.current)}},[a,e,o]),y.useEffect(()=>()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current)},[]),n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:t}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:r})]}),n.jsx(ih,{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 ih({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const ch=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:ql},Symbol.toStringTag,{value:"Module"}));function qn({href:e,children:t}){return n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:t})}const ec=[{id:"stripe",label:"Stripe",category:"stripe",description:n.jsxs(n.Fragment,{children:["Configure your Stripe integration for card payments. Get your API keys from the"," ",n.jsx(qn,{href:"https://dashboard.stripe.com/apikeys",children:"Stripe Dashboard"}),"."]})},{id:"crypto",label:"Crypto",category:"x402",description:n.jsxs(n.Fragment,{children:["Configure Solana wallet and token settings for crypto payments. Get a fast RPC endpoint from"," ",n.jsx(qn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(qn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(qn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(qn,{href:"https://solflare.com",children:"Solflare"})," wallet."]})},{id:"credits",label:"Credits",category:"cedros_login",description:n.jsxs(n.Fragment,{children:["Configure Cedros Login integration for credits payments. See the"," ",n.jsx(qn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function Hl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("stripe"),a=ec.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__payment-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Payment Options"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure payment methods including Stripe, crypto, and credits."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:ec.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(Ul,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description,showEnabledToggle:!0},a.category)})]})}const lh=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:Hl},Symbol.toStringTag,{value:"Module"})),ko={email_enabled:!1,smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function Zl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("messages"),[a,i]=y.useState(ko),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),[h,_]=y.useState(new Set),g=y.useCallback(async()=>{try{p(null);let v;const k="/admin/config/messaging";if(r?.isAuthenticated())v=await r.fetchWithAuth(k);else{const R={"Content-Type":"application/json"};t&&(R["X-API-Key"]=t);const N=await fetch(`${e}${k}`,{headers:R});if(!N.ok)throw new Error(`Failed to fetch: ${N.status}`);v=await N.json()}i({...ko,...v.config})}catch{i(ko),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{g()},[g]);const f=y.useCallback(async v=>{const k="/admin/config/messaging",R={...v};h.has("smtp_password")||delete R.smtp_password,h.has("webhook_secret")||delete R.webhook_secret;const N=JSON.stringify({config:R});try{if(r?.isAuthenticated())await r.fetchWithAuth(k,{method:"PUT",body:N});else{const C={"Content-Type":"application/json"};t&&(C["X-API-Key"]=t);const T=await fetch(`${e}${k}`,{method:"PUT",headers:C,body:N});if(!T.ok)throw new Error(`Failed to save: ${T.status}`)}}catch{throw p("Failed to save messaging settings"),new Error("Save failed")}},[e,t,r,h]),{status:w,error:j}=Ta({data:a,onSave:f,debounceMs:1500,enabled:!d}),b=(v,k)=>{(v==="smtp_password"||v==="webhook_secret")&&_(R=>new Set(R).add(v)),i(R=>({...R,[v]:k}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[Q.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(dh,{status:w,error:j})]}),n.jsx(Yt,{message:u,onRetry:g}),n.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[s==="messages"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.email_enabled,onChange:()=>b("email_enabled",!a.email_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.webhook_enabled,onChange:()=>b("webhook_enabled",!a.webhook_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),s==="email"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure your email provider for sending customer notifications."}),!a.email_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:v=>b("smtp_host",v.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:v=>b("smtp_port",parseInt(v.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:v=>b("smtp_username",v.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("smtp_password")?a.smtp_password:"",onChange:v=>b("smtp_password",v.target.value),placeholder:a.smtp_password?"••••••••":"Enter password",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),n.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:v=>b("from_email",v.target.value),placeholder:"orders@yourstore.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:v=>b("from_name",v.target.value),placeholder:"Your Store",disabled:!a.email_enabled})]})]})]}),s==="webhooks"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:v=>b("webhook_url",v.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("webhook_secret")?a.webhook_secret:"",onChange:v=>b("webhook_secret",v.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:v=>b("webhook_timeout",parseInt(v.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function dh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function tc({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:t,style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const uh=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:Zl},Symbol.toStringTag,{value:"Module"}));function Gl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(null),[p,h]=y.useState(!1),[_,g]=y.useState(""),[f,w]=y.useState("all"),[j,b]=y.useState(null),[v,k]=y.useState(null),[R,N]=y.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),C=y.useCallback(async()=>{c(!0);try{k(null);let z;const Z=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())z=await s.fetchWithAuth(Z);else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{headers:K});if(!L.ok)throw new Error(`Failed to fetch FAQs: ${L.status}`);z=await L.json()}a(z.faqs||[])}catch{a([]),k("Failed to load FAQs")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{C()},[C]);const T=async z=>{if(z.preventDefault(),!(!R.question.trim()||!R.answer.trim())){h(!0);try{const Z=R.keywordsCsv.split(",").map(L=>L.trim().toLowerCase()).filter(Boolean),K={question:R.question.trim(),answer:R.answer.trim(),keywords:Z,active:R.active,useInChat:R.useInChat,displayOnPage:R.displayOnPage};if(m){const L=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(L,{method:"PUT",body:JSON.stringify(K)});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const Y=await fetch(`${e}${L}`,{method:"PUT",headers:W,body:JSON.stringify(K)});if(!Y.ok)throw new Error(`Failed to update FAQ: ${Y.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}/admin/faqs`,{method:"POST",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to create FAQ: ${W.status}`)}S(),C()}catch{k(m?"Failed to update FAQ":"Failed to create FAQ")}finally{h(!1)}}},O=async z=>{try{const Z=`/admin/faqs/${z}`;if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"DELETE"});else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{method:"DELETE",headers:K});if(!L.ok)throw new Error(`Failed to delete FAQ: ${L.status}`)}C()}catch{k("Failed to delete FAQ")}b(null)},$=async z=>{try{const Z=`/admin/faqs/${z.id}`,K={...z,active:!z.active};if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"PUT",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}${Z}`,{method:"PUT",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to update FAQ: ${W.status}`)}C()}catch{k("Failed to update FAQ status")}},S=()=>{N({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},A=z=>{N({question:z.question,answer:z.answer,keywordsCsv:z.keywords.join(", "),active:z.active,useInChat:z.useInChat??!0,displayOnPage:z.displayOnPage??!0}),u(z),d(!0)},I=o.length,B=o.filter(z=>z.active).length,D=o.filter(z=>z.active&&z.useInChat).length,E=o.filter(z=>z.active&&z.displayOnPage).length,P=y.useMemo(()=>o.filter(z=>{if(f==="active"&&!z.active||f==="inactive"&&z.active)return!1;if(_){const Z=_.toLowerCase();return z.question.toLowerCase().includes(Z)||z.answer.toLowerCase().includes(Z)||z.keywords.some(K=>K.includes(Z))}return!0}),[o,f,_]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(Yt,{message:v,onRetry:C}),n.jsx(rr,{stats:[{label:"Total FAQs",value:I},{label:"Active",value:B,variant:"success"},{label:"In Chat",value:D},{label:"On Page",value:E}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__btn cedros-admin__btn--primary",onClick:()=>{S(),d(!0)},children:[Q.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:_,onChange:z=>g(z.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:f,onChange:z=>w(z.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:T,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__btn--icon",onClick:S,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:R.question,onChange:z=>N(Z=>({...Z,question:z.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),n.jsx("textarea",{value:R.answer,onChange:z=>N(Z=>({...Z,answer:z.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),n.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),n.jsx("input",{type:"text",value:R.keywordsCsv,onChange:z=>N(Z=>({...Z,keywordsCsv:z.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),n.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.active,onChange:z=>N(Z=>({...Z,active:z.target.checked}))}),n.jsx("span",{children:"Active"})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),n.jsxs("div",{className:"cedros-admin__checkbox-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.useInChat,onChange:z=>N(Z=>({...Z,useInChat:z.target.checked}))}),n.jsx("span",{children:"Use in AI Chat"})]}),n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.displayOnPage,onChange:z=>N(Z=>({...Z,displayOnPage:z.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__btn",onClick:S,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__btn cedros-admin__btn--primary",disabled:p||!R.question.trim()||!R.answer.trim(),children:p?Q.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading,n.jsx("span",{children:"Loading FAQs..."})]}):P.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:_||f!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:P.map(z=>n.jsxs("div",{className:`cedros-admin__faq-item ${z.active?"":"cedros-admin__faq-item--inactive"}`,children:[n.jsxs("div",{className:"cedros-admin__faq-content",children:[n.jsxs("div",{className:"cedros-admin__faq-question",children:[n.jsx("span",{className:`cedros-admin__status-dot ${z.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),z.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:z.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[z.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:z.keywords.map(Z=>n.jsx("span",{className:"cedros-admin__tag",children:Z},Z))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[z.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[Q.chat," Chat"]}),z.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[Q.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>$(z),title:z.active?"Deactivate":"Activate",children:z.active?Q.eyeOff:Q.eye}),n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>A(z),title:"Edit",children:Q.edit}),n.jsx("button",{className:"cedros-admin__btn--icon cedros-admin__btn--danger",onClick:()=>b(z.id),title:"Delete",children:Q.trash})]}),j===z.id&&n.jsx("div",{className:"cedros-admin__confirm-overlay",children:n.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[n.jsx("p",{children:"Delete this FAQ?"}),n.jsxs("div",{className:"cedros-admin__confirm-actions",children:[n.jsx("button",{className:"cedros-admin__btn",onClick:()=>b(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__btn cedros-admin__btn--danger",onClick:()=>O(z.id),children:"Delete"})]})]})})]},z.id))})]})]})}const mh=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:Gl},Symbol.toStringTag,{value:"Module"}));class Ql{serverUrl;walletSigner=null;jwtToken=null;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,J.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,J.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=Zi.bs58.encode(this.walletSigner.publicKey.toBytes()),i=Zi.bs58.encode(o);return{"X-Signer":a,"X-Message":r.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const r=`${this.serverUrl}/paywall/v1/nonce`;J.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await J.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!s.ok){const o=await s.text();throw new Error(`Failed to fetch nonce: ${s.status} ${o}`)}return await s.json()}async fetchWithAuth(t,r={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,r.method||"GET"),a=await this.createAuthHeaders(o),i={"Content-Type":"application/json",...r.headers||{},...a},c=await J.fetchWithTimeout(`${this.serverUrl}${t}`,{...r,headers:i});if(!c.ok){const l=await c.text();throw new Error(`Admin API error ${c.status}: ${l}`)}return await c.json()}getPurposeFromPath(t,r){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[r])return o[r];if(t.startsWith("/admin/products/")){if(r==="PUT")return"admin_products_update";if(r==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(r==="PUT")return"admin_coupons_update";if(r==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(r==="GET")return"admin_config_get";if(r==="PUT")return"admin_config_update";if(r==="PATCH")return"admin_config_patch"}return`admin_${r.toLowerCase()}`}}function ph({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=ja.useWallet(),o=y.useMemo(()=>{const u=new Ql(e);return u.setCedrosLoginAuth(t??null,r),u},[e,t,r]);y.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!t,d=y.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=y.useCallback((u,p)=>o.fetchWithAuth(u,p),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const Yl=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions},{id:"products",label:"Products",icon:Q.products},{id:"subscriptions",label:"Subscriptions",icon:Q.calendarRepeat},{id:"coupons",label:"Coupons",icon:Q.coupons},{id:"refunds",label:"Refunds",icon:Q.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:Q.storefront},{id:"ai-settings",label:"Store AI",icon:Q.brain},{id:"faqs",label:"Knowledge Base",icon:Q.faq},{id:"payment-settings",label:"Payment Options",icon:Q.creditCard},{id:"messaging",label:"Store Messages",icon:Q.mail},{id:"settings",label:"Store Server",icon:Q.server}]}],fh=Yl.flatMap(e=>e.sections);function hh(){const[e,t]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return y.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=o=>t(o.matches?"dark":"light");return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[]),e}function gh(e,t,r){return e!=="system"?e:t||r}function xh({serverUrl:e,apiKey:t,title:r="Cedros Pay",sections:s=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:m=!1,theme:u="system"}){const[p,h]=y.useState(o),[_,g]=y.useState(!0),[f,w]=y.useState(new Set),j=y.useCallback($=>{w(S=>{const A=new Set(S);return A.has($)?A.delete($):A.add($),A})},[]),b=J.useCedrosThemeOptional(),v=hh(),R=gh(u,b?.mode??null,v)==="dark"?"cedros-admin--dark":"",{authManager:N}=ph({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),C=y.useCallback($=>{h($),c?.($)},[c]),O=fh.filter($=>s.includes($.id)).find($=>$.id===p);return y.useEffect(()=>{const $=setTimeout(()=>g(!1),500);return()=>clearTimeout($)},[]),_?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${R} ${l}`,children:[Q.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${R} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[Q.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:Yl.map($=>{const S=$.sections.filter(I=>s.includes(I.id));if(S.length===0)return null;const A=$.collapsible&&f.has($.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[$.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>j($.label),"aria-expanded":!A,children:[$.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${A?"":"cedros-admin__nav-label-icon--expanded"}`,children:Q.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:$.label}),!A&&S.map(I=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${p===I.id?"cedros-admin__nav-item--active":""}`,onClick:()=>C(I.id),"aria-current":p===I.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:I.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:I.label})]},I.id))]},$.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:Q.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:O?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[p==="products"&&n.jsx(Ll,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="subscriptions"&&n.jsx(Wl,{serverUrl:e,apiKey:t,authManager:N}),p==="transactions"&&n.jsx($l,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="coupons"&&n.jsx(zl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="refunds"&&n.jsx(Fl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="storefront"&&n.jsx(Vl,{serverUrl:e,apiKey:t,authManager:N}),p==="ai-settings"&&n.jsx(ql,{serverUrl:e,apiKey:t,authManager:N}),p==="faqs"&&n.jsx(Gl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="payment-settings"&&n.jsx(Hl,{serverUrl:e,apiKey:t,authManager:N}),p==="messaging"&&n.jsx(Zl,{serverUrl:e,apiKey:t,authManager:N}),p==="settings"&&n.jsx(Ia,{serverUrl:e,apiKey:t,authManager:N})]})]})]})}const Pt=e=>y.lazy(async()=>{const s=(await e()).default;return{default:({pluginContext:a})=>{const i=a.getAccessToken(),c=y.useMemo(()=>{const d=new Ql(a.serverUrl);return d.setCedrosLoginAuth(i??null),d},[a.serverUrl,i]),l={serverUrl:a.serverUrl,authManager:c};return n.jsx(s,{...l})}}}),yh={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:Q.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:Q.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:Q.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:Q.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:Q.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:Q.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:Q.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:Q.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:Q.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:Q.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:Pt(()=>Promise.resolve().then(()=>require("./sections-Dtgg3Yjs.js")).then(e=>({default:e.ProductsSection}))),subscriptions:Pt(()=>Promise.resolve().then(()=>eh).then(e=>({default:e.SubscriptionsSection}))),transactions:Pt(()=>Promise.resolve().then(()=>require("./sections-Dtgg3Yjs.js")).then(e=>({default:e.TransactionsSection}))),coupons:Pt(()=>Promise.resolve().then(()=>require("./sections-Dtgg3Yjs.js")).then(e=>({default:e.CouponsSection}))),refunds:Pt(()=>Promise.resolve().then(()=>require("./sections-Dtgg3Yjs.js")).then(e=>({default:e.RefundsSection}))),storefront:Pt(()=>Promise.resolve().then(()=>sh).then(e=>({default:e.StorefrontSection}))),"ai-settings":Pt(()=>Promise.resolve().then(()=>ch).then(e=>({default:e.AISettingsSection}))),faqs:Pt(()=>Promise.resolve().then(()=>mh).then(e=>({default:e.FAQSection}))),"payment-settings":Pt(()=>Promise.resolve().then(()=>lh).then(e=>({default:e.PaymentSettingsSection}))),messaging:Pt(()=>Promise.resolve().then(()=>uh).then(e=>({default:e.MessagingSection}))),settings:Pt(()=>Promise.resolve().then(()=>Kf).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 Kl(){const{subscriptionManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=y.useCallback(async c=>{r(d=>({...d,status:"loading",error:null}));const l=await e.processSubscription(c);return r(d=>({...d,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l},[e]),o=y.useCallback(async c=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(c);return r(d=>({...d,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const d=l instanceof Error?l.message:"Failed to check subscription status";throw r(m=>({...m,status:"error",error:d})),l}},[e]),a=y.useCallback(async(c,l,d)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await e.requestSubscriptionQuote(c,l,d);return r(u=>({...u,status:"idle"})),m}catch(m){const u=m instanceof Error?m.message:"Failed to get subscription quote";throw r(p=>({...p,status:"error",error:u})),m}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:s,checkStatus:o,requestQuote:a,reset:i}}function wh({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:m=!1,onAttempt:u,onSuccess:p,onError:h,className:_=""}){const{status:g,error:f,sessionId:w,processSubscription:j}=Kl(),b=J.useCedrosTheme(),{t:v,translations:k}=xn(),R=d||v("ui.subscribe"),N=b.unstyled?_:`${b.className} cedros-theme__stripe-button ${_}`.trim(),C=f&&typeof f!="string"?f?.code??null:null,O=f?typeof f=="string"?f:(D=>{if(!D||!k)return"";const E=k.errors[D];return E?E.action?`${E.message} ${E.action}`:E.message:""})(C):null,$=y.useCallback(async()=>{J.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),Ln("stripe",e),u&&u("stripe"),un("stripe",e);const D=await j({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});D.success&&D.transactionId?($n("stripe",D.transactionId,e),p&&p(D.transactionId)):!D.success&&D.error&&(kt("stripe",D.error,e),h&&h(D.error))},[e,t,r,s,c,i,l,o,a,j,u,p,h]),S=y.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),A=y.useMemo(()=>Mn(S,$),[S,$]),I=g==="loading",B=m||I;return n.jsxs("div",{className:N,style:b.unstyled?{}:b.style,children:[n.jsx("button",{onClick:A,disabled:B,className:b.unstyled?_:"cedros-theme__button cedros-theme__stripe",type:"button",children:I?v("ui.processing"):R}),O&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__error",children:O}),w&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__success",children:v("ui.redirecting_to_checkout")})]})}function Xl(){const{subscriptionManager:e,creditsManager:t}=J.useCedrosContext(),[r,s]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=y.useCallback(async(l,d)=>{s(m=>({...m,status:"checking",error:null}));try{const m=await e.checkSubscriptionStatus({resource:l,userId:d});return s(u=>({...u,status:m.active?"success":"idle",subscriptionStatus:m.status,expiresAt:m.expiresAt||m.currentPeriodEnd||null})),m}catch(m){const u=J.formatError(m,"Failed to check subscription status");return s(p=>({...p,status:"error",error:u})),null}},[e]),a=y.useCallback(async(l,d,m)=>{s(u=>({...u,status:"loading",error:null}));try{const u=await t.requestQuote(l,m?.couponCode);return s(p=>({...p,status:"idle",creditsRequirement:u})),u}catch(u){const p=J.formatError(u,"Failed to get subscription quote");return s(h=>({...h,status:"error",error:p})),null}},[t]),i=y.useCallback(async(l,d,m,u)=>{if(!m){const p="Authentication required for credits payment";return s(h=>({...h,status:"error",error:p})),{success:!1,error:p}}s(p=>({...p,status:"loading",error:null}));try{const p=await t.processPayment(l,m,u?.couponCode,{interval:d,...u?.intervalDays&&{intervalDays:String(u.intervalDays)}});return p.success?s({status:"success",error:null,sessionId:p.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(h=>({...h,status:"error",error:p.error||"Credits subscription payment failed"})),p}catch(p){const h=J.formatError(p,"Credits subscription payment failed");return s(_=>({..._,status:"error",error:h})),{success:!1,error:h}}},[t]),c=y.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:o,requestQuote:a,processPayment:i,reset:c}}function _h({resource:e,interval:t,intervalDays:r,authToken:s,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:m,className:u="",hideMessages:p=!1,autoCheckStatus:h=!1}){const{status:_,error:g,subscriptionStatus:f,expiresAt:w,checkStatus:j,processPayment:b}=Xl(),v=J.useCedrosTheme(),{t:k,translations:R}=xn(),N=y.useRef(j);y.useEffect(()=>{N.current=j},[j]),y.useEffect(()=>{h&&o&&(J.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),N.current(e,o))},[h,o,e]);const C=i||k("ui.subscribe_with_credits")||"Subscribe with Credits",T=g&&typeof g!="string"?g?.code??null:null,$=g?typeof g=="string"?g:(Z=>{if(!Z||!R)return"";const K=R.errors[Z];return K?K.action?`${K.message} ${K.action}`:K.message:""})(T):null,S=y.useCallback(async()=>{if(J.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),Ln("credits",e),l&&l("credits"),!s){const K="Authentication required: please log in to subscribe with credits";J.getLogger().error("[CreditsSubscribeButton]",K),kt("credits",K,e),m&&m(K);return}un("credits",e);const Z=await b(e,t,s,{couponCode:a,intervalDays:r});Z.success&&Z.transactionId?($n("credits",Z.transactionId,e),d&&d(Z.transactionId)):!Z.success&&Z.error&&(kt("credits",Z.error,e),m&&m(Z.error))},[e,t,r,s,a,b,l,d,m]),A=y.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),I=y.useMemo(()=>Mn(A,S,{cooldownMs:200,deduplicationWindowMs:0}),[A,S]),B=_==="loading"||_==="checking",D=f==="active"||f==="trialing",E=c||B||D;let P=C;if(B)P=k("ui.processing");else if(D&&w){const Z=new Date(w).toLocaleDateString();P=`${k("ui.subscribed_until")} ${Z}`}else D&&(P=k("ui.subscribed"));const z=v.unstyled?u:`${v.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:z,style:v.unstyled?{}:v.style,children:[n.jsx("button",{onClick:I,disabled:E,className:v.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:P}),!p&&$&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__error",children:$}),!p&&D&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__success",children:k("ui.subscription_active")})]})}function Jl(){const{subscriptionChangeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=y.useRef(t);s.current=t;const o=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,p);return r(_=>({..._,status:"success",subscription:h,userId:p})),h}catch(h){const _=h instanceof Error?h.message:"Failed to load subscription";return r(g=>({...g,status:"error",error:_})),null}},[e]),a=y.useCallback(async(u,p,h,_)=>{r(g=>({...g,status:"loading",error:null}));try{const g={currentResource:u,newResource:p,userId:h,newInterval:_},f=await e.previewChange(g);return r(w=>({...w,status:"idle",changePreview:f})),f}catch(g){const f=g instanceof Error?g.message:"Failed to preview change";return r(w=>({...w,status:"error",error:f})),null}},[e]),i=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={currentResource:p.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},g=await e.changeSubscription(_);return g.success?r(f=>({...f,status:"success",subscription:f.subscription?{...f.subscription,resource:g.newResource,interval:g.newInterval,status:g.status}:null,changePreview:null})):r(f=>({...f,status:"error",error:g.error||"Failed to change subscription"})),g}catch(_){const g=_ instanceof Error?_.message:"Failed to change subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),c=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={resource:p.resource,userId:h,immediate:u},g=await e.cancel(_);if(g.success){const f=u?"canceled":p.status;r(w=>({...w,status:"success",subscription:w.subscription?{...w.subscription,status:f,cancelAtPeriodEnd:!u}:null}))}else r(f=>({...f,status:"error",error:g.error||"Failed to cancel subscription"}));return g}catch(_){const g=_ instanceof Error?_.message:"Failed to cancel subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),l=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:p});return window.location.href=h.url,h}catch(h){const _=h instanceof Error?h.message:"Failed to open billing portal";return r(g=>({...g,status:"error",error:_})),null}},[e]),d=y.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=y.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:o,previewChange:a,changeSubscription:i,cancelSubscription:c,openBillingPortal:l,clearPreview:d,reset:m}}const 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 Nn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function ed(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function 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:[Nn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[Nn(e.newPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Days remaining:"}),n.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Unused credit:"}),n.jsxs("span",{children:["-",Nn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:Nn(e.prorationDetails.newPlanCost,e.currency)})]})]}),n.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[n.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),n.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:Nn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:ed(e.effectiveDate)})]})]}),n.jsxs("div",{style:o.previewActions,children:[n.jsx("button",{onClick:r,style:o.cancelButton,disabled:s,children:"Cancel"}),n.jsx("button",{onClick:t,style:o.confirmButton,disabled:s,children:s?"Processing...":"Confirm Change"})]})]})}function Ph({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=J.useCedrosTheme(),m=y.useMemo(()=>Sh(d==="dark"),[d]),{subscription:u,changePreview:p,status:h,error:_,loadSubscription:g,previewChange:f,changeSubscription:w,cancelSubscription:j,openBillingPortal:b,clearPreview:v}=Jl();y.useEffect(()=>{g(e,t)},[e,t,g]);const k=y.useCallback(async(O,$)=>{await f(e,O,t,$)},[e,t,f]),R=y.useCallback(async()=>{if(!p)return;const O=r.find(S=>S.price===p.newPlanPrice&&S.currency===p.currency);(await w({newResource:O?.resource||e,newInterval:O?.interval,immediate:!0}))?.success&&O&&s?.(O.resource,O.interval)},[p,r,e,w,s]),N=y.useCallback(async O=>{(await j(O))?.success&&o?.()},[j,o]),C=y.useCallback(()=>{b(t,a)},[t,a,b]),T=h==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[_&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:_}),T&&!u&&n.jsx("div",{className:"cedros-subscription-loading",style:m.loading,children:"Loading subscription..."}),u&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"cedros-subscription-details",style:m.details,children:[n.jsx("h3",{style:m.title,children:"Current Subscription"}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Plan:"}),n.jsx("span",{style:m.value,children:u.resource})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Status:"}),n.jsx("span",{style:{...m.statusBadge,backgroundColor: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:[Nn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Current period ends:"}),n.jsx("span",{style:m.value,children:ed(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),p&&n.jsx(Nh,{preview:p,onConfirm:R,onCancel:v,isLoading:T,styles:m}),r.length>0&&!p&&n.jsxs("div",{className:"cedros-available-plans",style:m.plansSection,children:[n.jsx("h4",{style:m.plansTitle,children:"Available Plans"}),n.jsx("div",{style:m.plansList,children:r.map(O=>{const $=O.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...$?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:O.name}),n.jsxs("div",{style:m.planPrice,children:[Nn(O.price,O.currency),"/",O.interval]}),O.description&&n.jsx("div",{style:m.planDescription,children:O.description}),$?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>k(O.resource,O.interval),style:m.changePlanButton,disabled:T,children:O.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},O.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:C,style:m.portalButton,disabled:T,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>N(!1),style:m.cancelSubscriptionButton,disabled:T,children:"Cancel Subscription"})]})]})]})}function 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=y.createContext(null);function Re(){const e=y.useContext(Ra);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function Oa(){return y.useContext(Ra)}function Lh({config:e,children:t}){return n.jsx(Ra.Provider,{value:{config:e},children:t})}function At(e){return new Promise(t=>setTimeout(t,e))}const td=[{id:"cat_all",slug:"all",name:"All Products",description:"Everything in the catalog."},{id:"cat_apparel",slug:"apparel",name:"Apparel",description:"Soft goods and daily wear."},{id:"cat_accessories",slug:"accessories",name:"Accessories",description:"Carry, attach, decorate."}],hs=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];let So=[];const Vr={};function $h(e,t){let r=e;if(t.category&&t.category!=="all"){const l=td.find(d=>d.slug===t.category||d.id===t.category);l&&(r=r.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();r=r.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const s=t.filters??{},o=s.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));r=r.filter(d=>d.tags?.some(m=>l.has(m)))}const a=typeof s.priceMin=="number"?s.priceMin:void 0,i=typeof s.priceMax=="number"?s.priceMax:void 0;return typeof a=="number"&&(r=r.filter(l=>l.price>=a)),typeof i=="number"&&(r=r.filter(l=>l.price<=i)),(typeof s.inStock=="boolean"?s.inStock:void 0)===!0&&(r=r.filter(l=>l.inventoryStatus!=="out_of_stock")),r}function 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=hs.find(i=>i.id===o.resource||i.slug===o.resource)??hs[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),s=r.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:s,currency:e.options.currency,items:r,receiptUrl:e.options.successUrl}}function Uh(){return{async listProducts(e){await At(150);const t=e.page??1,r=e.pageSize??24,s=$h(hs,e),o=zh(s,e.sort);return Fh(o,t,r)},async getProductBySlug(e){return await At(100),hs.find(t=>t.slug===e)??null},async listCategories(){return await At(80),td},async getOrderHistory(){return await At(120),So},async getCart({customerId:e}){return await At(80),Vr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await At(120);const r=Vr[e]??{items:[]},s=new Map,o=i=>{const c=`${i.productId}::${i.variantId??""}`,l=s.get(c);l?s.set(c,{...l,qty:l.qty+i.qty}):s.set(c,i)};for(const i of r.items)o(i);for(const i of t.items)o(i);const a={items:Array.from(s.values()),promoCode:t.promoCode??r.promoCode};return Vr[e]=a,a},async updateCart({customerId:e,cart:t}){await At(60),Vr[e]=t},async createCheckoutSession(e){await At(250);const t=Bh(e);if(So=[t,...So].slice(0,25),e.options.successUrl){const r=new URL(e.options.successUrl,"http://localhost");return r.searchParams.set("demoOrderId",t.id),{kind:"redirect",url:r.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:t.id}}},async listSubscriptionTiers(){return await At(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await At(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await At(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function nd(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Wh(e){return e?e.toUpperCase():"USD"}function Vh(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function qh(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??nd(e.id),description:e.description??"",images:r,price:s/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:Vh(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:qh(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function Co(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],r=e.total??e.count;return{products:t,total:r}}async function tn(e,t,r){const s={};r&&(s["X-API-Key"]=r);const o=await fetch(`${e}${t}`,{headers:s});if(!o.ok){const a=await o.text().catch(()=>""),i=new Error(`Request failed (${o.status}): ${a}`);throw i.status=o.status,i}return o.json()}function Zh(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,p=(d-1)*m,h=new URLSearchParams;h.set("limit",String(u)),h.set("offset",String(p)),l.search&&h.set("search",l.search),l.category&&h.set("category",l.category),l.sort&&h.set("sort",l.sort),l.filters?.inStock&&h.set("in_stock","true"),l.filters?.minPrice!=null&&h.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&h.set("max_price",String(l.filters.maxPrice));const _=l.filters?.tags,g=Array.isArray(_)?_:typeof _=="string"?[_]:[];g.length&&h.set("tags",g.join(","));const f=await tn(e.serverUrl,`/paywall/v1/products?${h.toString()}`,e.apiKey),{products:w,total:j}=Co(f);return{items:w.map(qr),page:d,pageSize:m,total:j,hasNextPage:typeof j=="number"?p+u<j:w.length===u}},getProductBySlug:async l=>{try{const d=await tn(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(l)}`,e.apiKey);return qr(d)}catch(d){const m=d?.status;if(m!==404&&m!==405)throw d;try{const u=await tn(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(l)}`,e.apiKey);return qr(u)}catch(u){const p=u?.status;if(p!==404&&p!==405)throw u;const h=await tn(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:_}=Co(h),g=_.find(f=>f.slug===l||f.id===l);return g?qr(g):null}}},listCategories:async()=>{const l=await tn(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=Co(l),m=new Set;for(const u of d)for(const p of u.categoryIds??[])m.add(p);return Array.from(m).map(u=>({id:u,slug:u,name:nd(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await tn(e.serverUrl,"/admin/config/storefront",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([tn(e.serverUrl,"/admin/config/stripe",e.apiKey),tn(e.serverUrl,"/admin/config/x402",e.apiKey),tn(e.serverUrl,"/admin/config/cedros_login",e.apiKey)]),u=l.status==="fulfilled"?!!l.value?.config?.enabled:!1,p=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:p,credits:h}}catch{return null}},getAIRelatedProducts:async l=>{const d={"Content-Type":"application/json"};e.apiKey&&(d["X-API-Key"]=e.apiKey);const m=await fetch(`${e.serverUrl}/admin/ai/related-products`,{method:"POST",headers:d,body:JSON.stringify(l)});if(!m.ok){const u=await m.text().catch(()=>"");throw new Error(`AI related products request failed (${m.status}): ${u}`)}return m.json()}}}function Gh(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function Sn(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=Sn(t.item);return e.items.find(a=>Sn(a)===s)?{...e,items:e.items.map(a=>Sn(a)===s?{...a,qty:a.qty+r}:a)}:{...e,items:[...e.items,{...t.item,qty:r}]}}case"cart/remove":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(s=>Sn(s)!==r)}}case"cart/setQty":{const r=Math.max(0,Math.floor(t.qty)),s=`${t.productId}::${t.variantId??""}`;return r===0?{...e,items:e.items.filter(o=>Sn(o)!==s)}:{...e,items:e.items.map(o=>Sn(o)===s?{...o,qty:r}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(s=>Sn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return 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 rd=y.createContext(null);function Dt(){const e=y.useContext(rd);if(!e)throw new Error("useCart must be used within CartProvider");return e}function tg({children:e}){const{config:t}=Re(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=y.useReducer(Yh,Qh),[d,m]=y.useState(!1),u=y.useRef(!1),p=y.useRef(null);y.useEffect(()=>{const f=nc();if(!f)return;const w=Jh(f,r);w&&Array.isArray(w.items)&&l({type:"cart/hydrate",state:w}),m(!0)},[r]),y.useEffect(()=>{const f=nc();f&&eg(f,r,c)},[c,r]),y.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const f=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});f&&Array.isArray(f.items)&&(l({type:"cart/hydrate",state:f}),p.current=JSON.stringify(f))}catch{}})()))},[t.adapter,s,d,o,c]),y.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const f=JSON.stringify(c);if(p.current===f)return;const w=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{p.current=f}).catch(()=>{})},a);return()=>window.clearTimeout(w)},[t.adapter,s,d,o,c,a]);const h=y.useCallback((f,w)=>{const j=c.items.find(b=>b.productId===f&&b.variantId===w);if(j)return{holdId:j.holdId,expiresAt:j.holdExpiresAt}},[c.items]),_=y.useCallback((f,w,j)=>{l({type:"cart/updateHold",productId:f,variantId:w,holdExpiresAt:j})},[]),g=y.useMemo(()=>{const f=Kh(c.items),w=Xh(c.items);return{items:c.items,promoCode:c.promoCode,count:f,subtotal:w,addItem:(j,b)=>l({type:"cart/add",item:j,qty:b}),removeItem:(j,b)=>l({type:"cart/remove",productId:j,variantId:b}),setQty:(j,b,v)=>l({type:"cart/setQty",productId:j,variantId:b,qty:v}),clear:()=>l({type:"cart/clear"}),setPromoCode:j=>l({type:"cart/setPromoCode",promoCode:j}),holdsSupported:i,getItemHold:h,updateItemHold:_}},[c.items,c.promoCode,i,h,_]);return n.jsx(rd.Provider,{value:g,children:e})}function G(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const p=m[u];p in c||(c[p]=d[p].bind(c))}}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=r?.Parent?new a:this;s(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Kn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class sd extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const od={};function An(e){return od}function ad(e){const t=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,o])=>t.indexOf(+s)===-1).map(([s,o])=>o)}function ea(e,t){return typeof t=="bigint"?t.toString():t}function Ma(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Da(e){return e==null}function La(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function 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 Ce(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==rc)return s===void 0&&(s=rc,s=r()),s},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function zn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function yn(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}function sc(e){return JSON.stringify(e)}function rg(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const id="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const sg=Ma(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Pr(e){if(gs(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(gs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function cd(e){return Pr(e)?{...e}:Array.isArray(e)?[...e]:e}const og=new Set(["string","number","symbol"]);function Os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function me(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function 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=yn(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return zn(this,"shape",i),i},checks:[]});return vn(e,a)}function 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=yn(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return zn(this,"shape",i),i},checks:[]});return vn(e,a)}function dg(e,t){if(!Pr(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=yn(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return zn(this,"shape",a),a}});return vn(e,o)}function ug(e,t){if(!Pr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return zn(this,"shape",s),s}});return vn(e,r)}function mg(e,t){const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return zn(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return vn(e,r)}function 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=yn(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(r)for(const d in r){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return zn(this,"shape",l),l},checks:[]});return vn(t,i)}function fg(e,t,r){const s=yn(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(r)for(const i in r){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return zn(this,"shape",a),a}});return vn(t,s)}function Yn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ld(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Hr(e){return typeof e=="string"?e:e?.message}function En(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Hr(e.inst?._zod.def?.error?.(e))??Hr(t?.error?.(e))??Hr(r.customError?.(e))??Hr(r.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function $a(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ar(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const dd=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ea,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ud=G("$ZodError",dd),md=G("$ZodError",dd,{Parent:Error});function 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=>En(l,a,An())));throw id(c,o?.callee),c}return i.value},Fa=e=>async(t,r,s,o)=>{const a=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>En(l,a,An())));throw id(c,o?.callee),c}return i.value},Ms=e=>(t,r,s)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Kn;return a.issues.length?{success:!1,error:new(e??ud)(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},xg=Ms(md),Ds=e=>async(t,r,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},yg=Ds(md),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),wg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Fa(e)(t,r,o)},_g=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 Ms(e)(t,r,o)},kg=e=>(t,r,s)=>Ms(e)(t,r,s),Sg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ds(e)(t,r,o)},Cg=e=>async(t,r,s)=>Ds(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}=))?$/,pd=/^[A-Za-z0-9_-]*$/,Wg=/^\+[1-9]\d{6,14}$/,fd="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Vg=new RegExp(`^${fd}$`);function hd(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qg(e){return new RegExp(`^${hd(e)}$`)}function Hg(e){const t=hd({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${fd}T(?:${s})$`)}const 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=G("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),gd={number:"number",bigint:"bigint",object:"date"},xd=G("$ZodCheckLessThan",(e,t)=>{ht.init(e,t);const r=gd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yd=G("$ZodCheckGreaterThan",(e,t)=>{ht.init(e,t);const r=gd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xg=G("$ZodCheckMultipleOf",(e,t)=>{ht.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):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=G("$ZodCheckNumberFormat",(e,t)=>{ht.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=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})}}),ex=G("$ZodCheckMaxLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const o=s.value;if(o.length<=t.maximum)return;const i=$a(o);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tx=G("$ZodCheckMinLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const o=s.value;if(o.length>=t.minimum)return;const i=$a(o);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),nx=G("$ZodCheckLengthEquals",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=s=>{const o=s.value,a=o.length;if(a===t.length)return;const i=$a(o),c=a>t.length;s.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),Ls=G("$ZodCheckStringFormat",(e,t)=>{var r,s;ht.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),rx=G("$ZodCheckRegex",(e,t)=>{Ls.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),sx=G("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Yg),Ls.init(e,t)}),ox=G("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Kg),Ls.init(e,t)}),ax=G("$ZodCheckIncludes",(e,t)=>{ht.init(e,t);const r=Os(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(s)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),ix=G("$ZodCheckStartsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`^${Os(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),cx=G("$ZodCheckEndsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`.*${Os(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),lx=G("$ZodCheckOverwrite",(e,t)=>{ht.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class dx{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
|
|
53
|
+
- Include relevant keywords naturally for SEO`}],ch=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],ec={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:ea.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function Gl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("api-keys"),[a,i]=y.useState(ec),[c,l]=y.useState(!0),[d,m]=y.useState(!1),[u,p]=y.useState(null),[h,_]=y.useState(!1),[g,f]=y.useState(null),w=y.useRef(null),[j,b]=y.useState({gemini:"",openai:""}),[v,k]=y.useState({gemini:!1,openai:!1}),R=y.useCallback(async()=>{try{let A;if(r?.isAuthenticated())A=await r.fetchWithAuth("/admin/config/ai");else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch: ${B.status}`);A=await B.json()}A.settings&&i(A.settings)}catch{i(ec),f("Could not load saved AI settings. Showing defaults.")}finally{l(!1)}},[e,t,r]);y.useEffect(()=>{R()},[R]);const N=y.useCallback(async A=>{const I=j[A];if(I.trim()){m(!0),p(null);try{const B={provider:A,apiKey:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(B)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:L,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(L=>({...L,apiKeys:L.apiKeys.map(E=>E.provider===A?{...E,isConfigured:!0,maskedKey:`${I.slice(0,4)}...${I.slice(-4)}`,updatedAt:new Date().toISOString()}:E)})),b(L=>({...L,[A]:""})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save API key")}finally{m(!1)}}},[j,e,t,r]),C=y.useCallback(async A=>{if(confirm(`Are you sure you want to delete the ${A==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),p(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${A}`,{method:"DELETE"});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai/api-key/${A}`,{method:"DELETE",headers:I});if(!B.ok)throw new Error(`Failed to delete: ${B.status}`)}i(I=>({...I,apiKeys:I.apiKeys.map(B=>B.provider===A?{provider:A,isConfigured:!1}:B)}))}catch(I){p(I instanceof Error?I.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),T=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,model:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(B)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:L,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(L=>({...L,taskAssignments:L.taskAssignments.map(E=>E.task===A?{...E,assignedModel:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),O=y.useCallback(A=>{if(A==="not_set")return!0;const I=ko.find(L=>L.id===A);return I?.provider?a.apiKeys.find(L=>L.provider===I.provider)?.isConfigured??!1:!0},[a.apiKeys]),$=y.useMemo(()=>ko.map(A=>{const I=O(A.id);return{value:A.id,label:I?A.label:`${A.label} (API key required)`,disabled:!I}}),[O]),S=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,systemPrompt:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(B)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:L,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(L=>({...L,taskAssignments:L.taskAssignments.map(E=>E.task===A?{...E,systemPrompt:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return y.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),n.jsx(Kt,{message:g,onRetry:R}),h&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[Q.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:ch.map(A=>{const I=a.apiKeys.find(L=>L.provider===A.id),B=I?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:A.label}),B&&I?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",I.maskedKey,I.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(I.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${B?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:B?"Configured":"Not Set"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:v[A.id]?"text":"password",className:"cedros-admin__input",placeholder:B?"Enter new key to replace":A.placeholder,value:j[A.id],onChange:L=>b(E=>({...E,[A.id]:L.target.value})),onBlur:()=>{j[A.id].trim()&&N(A.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>k(L=>({...L,[A.id]:!L[A.id]})),title:v[A.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:v[A.id]?Q.eyeOff:Q.eye}),B&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(A.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:Q.trash})]})})]},A.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(A=>{const I=ea.find(L=>L.task===A.task),B=ko.find(L=>L.id===A.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:I?.label??A.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:I?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(at,{value:A.assignedModel,onChange:L=>T(A.task,L),options:$,label:"",disabled:d,style:{flex:1,maxWidth:280}}),B&&B.provider&&n.jsx("span",{className:`cedros-admin__badge ${O(B.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:O(B.id)?"Ready":"Missing API Key"})]})]},A.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(A=>{const I=ea.find(B=>B.task===A.task);return n.jsx(lh,{task:A.task,label:I?.label??A.task,description:I?.description??"",initialPrompt:A.systemPrompt??"",onSave:S},A.task)})})]})]})}function lh({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=y.useState(s),[c,l]=y.useState("idle"),d=y.useRef(null),m=y.useRef(null),u=y.useRef(!0);return y.useEffect(()=>{if(u.current){u.current=!1;return}return d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),l("pending"),d.current=setTimeout(async()=>{l("saving");try{await o(e,a),l("saved"),m.current=setTimeout(()=>l("idle"),2e3)}catch{l("error")}},1500),()=>{d.current&&clearTimeout(d.current)}},[a,e,o]),y.useEffect(()=>()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current)},[]),n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:t}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:r})]}),n.jsx(dh,{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 dh({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const uh=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:Gl},Symbol.toStringTag,{value:"Module"}));function Hn({href:e,children:t}){return n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:t})}const tc=[{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(Hn,{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(Hn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(Hn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(Hn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(Hn,{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(Hn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function Ql({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("stripe"),a=tc.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:tc.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(ql,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description,showEnabledToggle:!0},a.category)})]})}const mh=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:Ql},Symbol.toStringTag,{value:"Module"})),So={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 Yl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("messages"),[a,i]=y.useState(So),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),[h,_]=y.useState(new Set),g=y.useCallback(async()=>{try{p(null);let v;const k="/admin/config/messaging";if(r?.isAuthenticated())v=await r.fetchWithAuth(k);else{const R={"Content-Type":"application/json"};t&&(R["X-API-Key"]=t);const N=await fetch(`${e}${k}`,{headers:R});if(!N.ok)throw new Error(`Failed to fetch: ${N.status}`);v=await N.json()}i({...So,...v.config})}catch{i(So),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{g()},[g]);const f=y.useCallback(async v=>{const k="/admin/config/messaging",R={...v};h.has("smtp_password")||delete R.smtp_password,h.has("webhook_secret")||delete R.webhook_secret;const N=JSON.stringify({config:R});try{if(r?.isAuthenticated())await r.fetchWithAuth(k,{method:"PUT",body:N});else{const C={"Content-Type":"application/json"};t&&(C["X-API-Key"]=t);const T=await fetch(`${e}${k}`,{method:"PUT",headers:C,body:N});if(!T.ok)throw new Error(`Failed to save: ${T.status}`)}}catch{throw p("Failed to save messaging settings"),new Error("Save failed")}},[e,t,r,h]),{status:w,error:j}=Ia({data:a,onSave:f,debounceMs:1500,enabled:!d}),b=(v,k)=>{(v==="smtp_password"||v==="webhook_secret")&&_(R=>new Set(R).add(v)),i(R=>({...R,[v]:k}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[Q.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(ph,{status:w,error:j})]}),n.jsx(Kt,{message:u,onRetry:g}),n.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[s==="messages"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(nc,{checked:a.email_enabled,onChange:()=>b("email_enabled",!a.email_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(nc,{checked:a.webhook_enabled,onChange:()=>b("webhook_enabled",!a.webhook_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),s==="email"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure your email provider for sending customer notifications."}),!a.email_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:v=>b("smtp_host",v.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:v=>b("smtp_port",parseInt(v.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:v=>b("smtp_username",v.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("smtp_password")?a.smtp_password:"",onChange:v=>b("smtp_password",v.target.value),placeholder:a.smtp_password?"••••••••":"Enter password",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),n.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:v=>b("from_email",v.target.value),placeholder:"orders@yourstore.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:v=>b("from_name",v.target.value),placeholder:"Your Store",disabled:!a.email_enabled})]})]})]}),s==="webhooks"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:v=>b("webhook_url",v.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("webhook_secret")?a.webhook_secret:"",onChange:v=>b("webhook_secret",v.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:v=>b("webhook_timeout",parseInt(v.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function ph({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function nc({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 fh=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:Yl},Symbol.toStringTag,{value:"Module"}));function Kl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(null),[p,h]=y.useState(!1),[_,g]=y.useState(""),[f,w]=y.useState("all"),[j,b]=y.useState(null),[v,k]=y.useState(null),[R,N]=y.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),C=y.useCallback(async()=>{c(!0);try{k(null);let z;const Z=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())z=await s.fetchWithAuth(Z);else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const D=await fetch(`${e}${Z}`,{headers:K});if(!D.ok)throw new Error(`Failed to fetch FAQs: ${D.status}`);z=await D.json()}a(z.faqs||[])}catch{a([]),k("Failed to load FAQs")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{C()},[C]);const T=async z=>{if(z.preventDefault(),!(!R.question.trim()||!R.answer.trim())){h(!0);try{const Z=R.keywordsCsv.split(",").map(D=>D.trim().toLowerCase()).filter(Boolean),K={question:R.question.trim(),answer:R.answer.trim(),keywords:Z,active:R.active,useInChat:R.useInChat,displayOnPage:R.displayOnPage};if(m){const D=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(D,{method:"PUT",body:JSON.stringify(K)});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const Y=await fetch(`${e}${D}`,{method:"PUT",headers:W,body:JSON.stringify(K)});if(!Y.ok)throw new Error(`Failed to update FAQ: ${Y.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(K)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const W=await fetch(`${e}/admin/faqs`,{method:"POST",headers:D,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to create FAQ: ${W.status}`)}S(),C()}catch{k(m?"Failed to update FAQ":"Failed to create FAQ")}finally{h(!1)}}},O=async z=>{try{const Z=`/admin/faqs/${z}`;if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"DELETE"});else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const D=await fetch(`${e}${Z}`,{method:"DELETE",headers:K});if(!D.ok)throw new Error(`Failed to delete FAQ: ${D.status}`)}C()}catch{k("Failed to delete FAQ")}b(null)},$=async z=>{try{const Z=`/admin/faqs/${z.id}`,K={...z,active:!z.active};if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"PUT",body:JSON.stringify(K)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const W=await fetch(`${e}${Z}`,{method:"PUT",headers:D,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to update FAQ: ${W.status}`)}C()}catch{k("Failed to update FAQ status")}},S=()=>{N({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},A=z=>{N({question:z.question,answer:z.answer,keywordsCsv:z.keywords.join(", "),active:z.active,useInChat:z.useInChat??!0,displayOnPage:z.displayOnPage??!0}),u(z),d(!0)},I=o.length,B=o.filter(z=>z.active).length,L=o.filter(z=>z.active&&z.useInChat).length,E=o.filter(z=>z.active&&z.displayOnPage).length,P=y.useMemo(()=>o.filter(z=>{if(f==="active"&&!z.active||f==="inactive"&&z.active)return!1;if(_){const Z=_.toLowerCase();return z.question.toLowerCase().includes(Z)||z.answer.toLowerCase().includes(Z)||z.keywords.some(K=>K.includes(Z))}return!0}),[o,f,_]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(Kt,{message:v,onRetry:C}),n.jsx(sr,{stats:[{label:"Total FAQs",value:I},{label:"Active",value:B,variant:"success"},{label:"In Chat",value:L},{label:"On Page",value:E}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__btn cedros-admin__btn--primary",onClick:()=>{S(),d(!0)},children:[Q.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:_,onChange:z=>g(z.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:f,onChange:z=>w(z.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:T,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__btn--icon",onClick:S,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:R.question,onChange:z=>N(Z=>({...Z,question:z.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),n.jsx("textarea",{value:R.answer,onChange:z=>N(Z=>({...Z,answer:z.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),n.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),n.jsx("input",{type:"text",value:R.keywordsCsv,onChange:z=>N(Z=>({...Z,keywordsCsv:z.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),n.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.active,onChange:z=>N(Z=>({...Z,active:z.target.checked}))}),n.jsx("span",{children:"Active"})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),n.jsxs("div",{className:"cedros-admin__checkbox-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.useInChat,onChange:z=>N(Z=>({...Z,useInChat:z.target.checked}))}),n.jsx("span",{children:"Use in AI Chat"})]}),n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.displayOnPage,onChange:z=>N(Z=>({...Z,displayOnPage:z.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__btn",onClick:S,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__btn cedros-admin__btn--primary",disabled:p||!R.question.trim()||!R.answer.trim(),children:p?Q.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading,n.jsx("span",{children:"Loading FAQs..."})]}):P.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:_||f!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:P.map(z=>n.jsxs("div",{className:`cedros-admin__faq-item ${z.active?"":"cedros-admin__faq-item--inactive"}`,children:[n.jsxs("div",{className:"cedros-admin__faq-content",children:[n.jsxs("div",{className:"cedros-admin__faq-question",children:[n.jsx("span",{className:`cedros-admin__status-dot ${z.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),z.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:z.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[z.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:z.keywords.map(Z=>n.jsx("span",{className:"cedros-admin__tag",children:Z},Z))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[z.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[Q.chat," Chat"]}),z.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[Q.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>$(z),title:z.active?"Deactivate":"Activate",children:z.active?Q.eyeOff:Q.eye}),n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>A(z),title:"Edit",children:Q.edit}),n.jsx("button",{className:"cedros-admin__btn--icon cedros-admin__btn--danger",onClick:()=>b(z.id),title:"Delete",children:Q.trash})]}),j===z.id&&n.jsx("div",{className:"cedros-admin__confirm-overlay",children:n.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[n.jsx("p",{children:"Delete this FAQ?"}),n.jsxs("div",{className:"cedros-admin__confirm-actions",children:[n.jsx("button",{className:"cedros-admin__btn",onClick:()=>b(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__btn cedros-admin__btn--danger",onClick:()=>O(z.id),children:"Delete"})]})]})})]},z.id))})]})]})}const hh=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:Kl},Symbol.toStringTag,{value:"Module"}));class Xl{serverUrl;walletSigner=null;jwtToken=null;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,J.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,J.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=Gi.bs58.encode(this.walletSigner.publicKey.toBytes()),i=Gi.bs58.encode(o);return{"X-Signer":a,"X-Message":r.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const r=`${this.serverUrl}/paywall/v1/nonce`;J.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await J.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!s.ok){const o=await s.text();throw new Error(`Failed to fetch nonce: ${s.status} ${o}`)}return await s.json()}async fetchWithAuth(t,r={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,r.method||"GET"),a=await this.createAuthHeaders(o),i={"Content-Type":"application/json",...r.headers||{},...a},c=await J.fetchWithTimeout(`${this.serverUrl}${t}`,{...r,headers:i});if(!c.ok){const l=await c.text();throw new Error(`Admin API error ${c.status}: ${l}`)}return await c.json()}getPurposeFromPath(t,r){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[r])return o[r];if(t.startsWith("/admin/products/")){if(r==="PUT")return"admin_products_update";if(r==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(r==="PUT")return"admin_coupons_update";if(r==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(r==="GET")return"admin_config_get";if(r==="PUT")return"admin_config_update";if(r==="PATCH")return"admin_config_patch"}return`admin_${r.toLowerCase()}`}}function gh({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=ka.useWallet(),o=y.useMemo(()=>{const u=new Xl(e);return u.setCedrosLoginAuth(t??null,r),u},[e,t,r]);y.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!t,d=y.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=y.useCallback((u,p)=>o.fetchWithAuth(u,p),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const Jl=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions},{id:"products",label:"Products",icon:Q.products},{id:"subscriptions",label:"Subscriptions",icon:Q.calendarRepeat},{id:"coupons",label:"Coupons",icon:Q.coupons},{id:"refunds",label:"Refunds",icon:Q.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:Q.storefront},{id:"ai-settings",label:"Store AI",icon:Q.brain},{id:"faqs",label:"Knowledge Base",icon:Q.faq},{id:"payment-settings",label:"Payment Options",icon:Q.creditCard},{id:"messaging",label:"Store Messages",icon:Q.mail},{id:"settings",label:"Store Server",icon:Q.server}]}],xh=Jl.flatMap(e=>e.sections);function yh(){const[e,t]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return y.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=o=>t(o.matches?"dark":"light");return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[]),e}function vh(e,t,r){return e!=="system"?e:t||r}function bh({serverUrl:e,apiKey:t,title:r="Cedros Pay",sections:s=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:m=!1,theme:u="system"}){const[p,h]=y.useState(o),[_,g]=y.useState(!0),[f,w]=y.useState(new Set),j=y.useCallback($=>{w(S=>{const A=new Set(S);return A.has($)?A.delete($):A.add($),A})},[]),b=J.useCedrosThemeOptional(),v=yh(),R=vh(u,b?.mode??null,v)==="dark"?"cedros-admin--dark":"",{authManager:N}=gh({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),C=y.useCallback($=>{h($),c?.($)},[c]),O=xh.filter($=>s.includes($.id)).find($=>$.id===p);return y.useEffect(()=>{const $=setTimeout(()=>g(!1),500);return()=>clearTimeout($)},[]),_?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${R} ${l}`,children:[Q.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${R} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[Q.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:Jl.map($=>{const S=$.sections.filter(I=>s.includes(I.id));if(S.length===0)return null;const A=$.collapsible&&f.has($.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[$.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>j($.label),"aria-expanded":!A,children:[$.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${A?"":"cedros-admin__nav-label-icon--expanded"}`,children:Q.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:$.label}),!A&&S.map(I=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${p===I.id?"cedros-admin__nav-item--active":""}`,onClick:()=>C(I.id),"aria-current":p===I.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:I.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:I.label})]},I.id))]},$.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:Q.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:O?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[p==="products"&&n.jsx(Fl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="subscriptions"&&n.jsx(Hl,{serverUrl:e,apiKey:t,authManager:N}),p==="transactions"&&n.jsx(Bl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="coupons"&&n.jsx(Ul,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="refunds"&&n.jsx(Wl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="storefront"&&n.jsx(Zl,{serverUrl:e,apiKey:t,authManager:N}),p==="ai-settings"&&n.jsx(Gl,{serverUrl:e,apiKey:t,authManager:N}),p==="faqs"&&n.jsx(Kl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="payment-settings"&&n.jsx(Ql,{serverUrl:e,apiKey:t,authManager:N}),p==="messaging"&&n.jsx(Yl,{serverUrl:e,apiKey:t,authManager:N}),p==="settings"&&n.jsx(Ra,{serverUrl:e,apiKey:t,authManager:N})]})]})]})}const wh=y.createContext(null);function _h(){const e=y.useContext(wh);if(!e)throw new Error("useCedrosLogin must be used within a CedrosLoginProvider");return e}function jh(e,t,r,s){function o(a){return a instanceof r?a:new r(function(i){i(a)})}return new(r||(r=Promise))(function(a,i){function c(m){try{d(s.next(m))}catch(u){i(u)}}function l(m){try{d(s.throw(m))}catch(u){i(u)}}function d(m){m.done?a(m.value):o(m.value).then(c,l)}d((s=s.apply(e,[])).next())})}class Re{constructor(){this.mutex=Promise.resolve()}lock(){let t=()=>{};return this.mutex=this.mutex.then(()=>new Promise(t)),new Promise(r=>{t=r})}dispatch(t){return jh(this,void 0,void 0,function*(){const r=yield this.lock();try{return yield Promise.resolve(t())}finally{r()}})}}function kh(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}const rc=kh();rc.TextEncoder&&new rc.TextEncoder;const sc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Sh=new Uint8Array(256);for(let e=0;e<sc.length;e++)Sh[sc.charCodeAt(e)]=e;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;new Re;const Ch={sm:16,md:24,lg:32,xl:48};y.memo(function({size:e="md",className:t="",style:r,label:s="Loading",announce:o=!1}){const a=Ch[e],i=n.jsxs("svg",{className:`cedros-spinner ${t}`,width:a,height:a,viewBox:"0 0 24 24",fill:"none",style:r,"aria-label":s,role:"status","aria-hidden":o?"true":void 0,children:[n.jsx("circle",{className:"cedros-spinner-track",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeOpacity:"0.25"}),n.jsx("circle",{className:"cedros-spinner-head",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"31.4 31.4",transform:"rotate(-90 12 12)",children:n.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"1s",repeatCount:"indefinite"})})]});return o?n.jsxs("span",{"aria-live":"polite","aria-busy":"true",children:[i,n.jsx("span",{className:"cedros-sr-only",children:s})]}):i});y.memo(function({error:e,className:t="",onDismiss:r,autoFocus:s=!1}){const o=y.useRef(null);if(y.useEffect(()=>{e&&s&&o.current&&o.current.focus()},[e,s]),!e)return null;const a=typeof e=="string"?e:e.message;return n.jsxs("div",{ref:o,className:`cedros-error ${t}`,role:"alert","aria-live":"assertive",tabIndex:s?-1:void 0,children:[n.jsxs("svg",{className:"cedros-error-icon",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[n.jsx("circle",{cx:"8",cy:"8",r:"7",stroke:"currentColor",strokeWidth:"1.5"}),n.jsx("path",{d:"M8 4.5v4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),n.jsx("circle",{cx:"8",cy:"11",r:"0.75",fill:"currentColor"})]}),n.jsx("span",{className:"cedros-error-message",children:a}),r&&n.jsx("button",{type:"button",className:"cedros-error-dismiss",onClick:r,"aria-label":"Dismiss error",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:n.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5l7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]})});const At=e=>y.lazy(async()=>{const s=(await e()).default;return{default:({pluginContext:a})=>{const c=_h()?._internal?.getAccessToken()??a.getAccessToken(),l=y.useMemo(()=>{const m=new Xl(a.serverUrl);return m.setCedrosLoginAuth(c??null),m},[a.serverUrl,c]),d={serverUrl:a.serverUrl,authManager:l};return n.jsx(s,{...d})}}}),Nh={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:Q.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:Q.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:Q.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:Q.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:Q.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:Q.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:Q.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:Q.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:Q.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:Q.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:At(()=>Promise.resolve().then(()=>require("./sections-C0OrGKfh.js")).then(e=>({default:e.ProductsSection}))),subscriptions:At(()=>Promise.resolve().then(()=>rh).then(e=>({default:e.SubscriptionsSection}))),transactions:At(()=>Promise.resolve().then(()=>require("./sections-C0OrGKfh.js")).then(e=>({default:e.TransactionsSection}))),coupons:At(()=>Promise.resolve().then(()=>require("./sections-C0OrGKfh.js")).then(e=>({default:e.CouponsSection}))),refunds:At(()=>Promise.resolve().then(()=>require("./sections-C0OrGKfh.js")).then(e=>({default:e.RefundsSection}))),storefront:At(()=>Promise.resolve().then(()=>ih).then(e=>({default:e.StorefrontSection}))),"ai-settings":At(()=>Promise.resolve().then(()=>uh).then(e=>({default:e.AISettingsSection}))),faqs:At(()=>Promise.resolve().then(()=>hh).then(e=>({default:e.FAQSection}))),"payment-settings":At(()=>Promise.resolve().then(()=>mh).then(e=>({default:e.PaymentSettingsSection}))),messaging:At(()=>Promise.resolve().then(()=>fh).then(e=>({default:e.MessagingSection}))),settings:At(()=>Promise.resolve().then(()=>eh).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 Ph({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 Ah({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 ed(){const{subscriptionManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=y.useCallback(async c=>{r(d=>({...d,status:"loading",error:null}));const l=await e.processSubscription(c);return r(d=>({...d,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l},[e]),o=y.useCallback(async c=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(c);return r(d=>({...d,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const d=l instanceof Error?l.message:"Failed to check subscription status";throw r(m=>({...m,status:"error",error:d})),l}},[e]),a=y.useCallback(async(c,l,d)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await e.requestSubscriptionQuote(c,l,d);return r(u=>({...u,status:"idle"})),m}catch(m){const u=m instanceof Error?m.message:"Failed to get subscription quote";throw r(p=>({...p,status:"error",error:u})),m}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:s,checkStatus:o,requestQuote:a,reset:i}}function Eh({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:m=!1,onAttempt:u,onSuccess:p,onError:h,className:_=""}){const{status:g,error:f,sessionId:w,processSubscription:j}=ed(),b=J.useCedrosTheme(),{t:v,translations:k}=yn(),R=d||v("ui.subscribe"),N=b.unstyled?_:`${b.className} cedros-theme__stripe-button ${_}`.trim(),C=f&&typeof f!="string"?f?.code??null:null,O=f?typeof f=="string"?f:(L=>{if(!L||!k)return"";const E=k.errors[L];return E?E.action?`${E.message} ${E.action}`:E.message:""})(C):null,$=y.useCallback(async()=>{J.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),$n("stripe",e),u&&u("stripe"),mn("stripe",e);const L=await j({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});L.success&&L.transactionId?(zn("stripe",L.transactionId,e),p&&p(L.transactionId)):!L.success&&L.error&&(St("stripe",L.error,e),h&&h(L.error))},[e,t,r,s,c,i,l,o,a,j,u,p,h]),S=y.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),A=y.useMemo(()=>Ln(S,$),[S,$]),I=g==="loading",B=m||I;return n.jsxs("div",{className:N,style:b.unstyled?{}:b.style,children:[n.jsx("button",{onClick:A,disabled:B,className:b.unstyled?_:"cedros-theme__button cedros-theme__stripe",type:"button",children:I?v("ui.processing"):R}),O&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__error",children:O}),w&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__success",children:v("ui.redirecting_to_checkout")})]})}function td(){const{subscriptionManager:e,creditsManager:t}=J.useCedrosContext(),[r,s]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=y.useCallback(async(l,d)=>{s(m=>({...m,status:"checking",error:null}));try{const m=await e.checkSubscriptionStatus({resource:l,userId:d});return s(u=>({...u,status:m.active?"success":"idle",subscriptionStatus:m.status,expiresAt:m.expiresAt||m.currentPeriodEnd||null})),m}catch(m){const u=J.formatError(m,"Failed to check subscription status");return s(p=>({...p,status:"error",error:u})),null}},[e]),a=y.useCallback(async(l,d,m)=>{s(u=>({...u,status:"loading",error:null}));try{const u=await t.requestQuote(l,m?.couponCode);return s(p=>({...p,status:"idle",creditsRequirement:u})),u}catch(u){const p=J.formatError(u,"Failed to get subscription quote");return s(h=>({...h,status:"error",error:p})),null}},[t]),i=y.useCallback(async(l,d,m,u)=>{if(!m){const p="Authentication required for credits payment";return s(h=>({...h,status:"error",error:p})),{success:!1,error:p}}s(p=>({...p,status:"loading",error:null}));try{const p=await t.processPayment(l,m,u?.couponCode,{interval:d,...u?.intervalDays&&{intervalDays:String(u.intervalDays)}});return p.success?s({status:"success",error:null,sessionId:p.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(h=>({...h,status:"error",error:p.error||"Credits subscription payment failed"})),p}catch(p){const h=J.formatError(p,"Credits subscription payment failed");return s(_=>({..._,status:"error",error:h})),{success:!1,error:h}}},[t]),c=y.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:o,requestQuote:a,processPayment:i,reset:c}}function Th({resource:e,interval:t,intervalDays:r,authToken:s,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:m,className:u="",hideMessages:p=!1,autoCheckStatus:h=!1}){const{status:_,error:g,subscriptionStatus:f,expiresAt:w,checkStatus:j,processPayment:b}=td(),v=J.useCedrosTheme(),{t:k,translations:R}=yn(),N=y.useRef(j);y.useEffect(()=>{N.current=j},[j]),y.useEffect(()=>{h&&o&&(J.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),N.current(e,o))},[h,o,e]);const C=i||k("ui.subscribe_with_credits")||"Subscribe with Credits",T=g&&typeof g!="string"?g?.code??null:null,$=g?typeof g=="string"?g:(Z=>{if(!Z||!R)return"";const K=R.errors[Z];return K?K.action?`${K.message} ${K.action}`:K.message:""})(T):null,S=y.useCallback(async()=>{if(J.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),$n("credits",e),l&&l("credits"),!s){const K="Authentication required: please log in to subscribe with credits";J.getLogger().error("[CreditsSubscribeButton]",K),St("credits",K,e),m&&m(K);return}mn("credits",e);const Z=await b(e,t,s,{couponCode:a,intervalDays:r});Z.success&&Z.transactionId?(zn("credits",Z.transactionId,e),d&&d(Z.transactionId)):!Z.success&&Z.error&&(St("credits",Z.error,e),m&&m(Z.error))},[e,t,r,s,a,b,l,d,m]),A=y.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),I=y.useMemo(()=>Ln(A,S,{cooldownMs:200,deduplicationWindowMs:0}),[A,S]),B=_==="loading"||_==="checking",L=f==="active"||f==="trialing",E=c||B||L;let P=C;if(B)P=k("ui.processing");else if(L&&w){const Z=new Date(w).toLocaleDateString();P=`${k("ui.subscribed_until")} ${Z}`}else L&&(P=k("ui.subscribed"));const z=v.unstyled?u:`${v.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:z,style:v.unstyled?{}:v.style,children:[n.jsx("button",{onClick:I,disabled:E,className:v.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:P}),!p&&$&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__error",children:$}),!p&&L&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__success",children:k("ui.subscription_active")})]})}function nd(){const{subscriptionChangeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=y.useRef(t);s.current=t;const o=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,p);return r(_=>({..._,status:"success",subscription:h,userId:p})),h}catch(h){const _=h instanceof Error?h.message:"Failed to load subscription";return r(g=>({...g,status:"error",error:_})),null}},[e]),a=y.useCallback(async(u,p,h,_)=>{r(g=>({...g,status:"loading",error:null}));try{const g={currentResource:u,newResource:p,userId:h,newInterval:_},f=await e.previewChange(g);return r(w=>({...w,status:"idle",changePreview:f})),f}catch(g){const f=g instanceof Error?g.message:"Failed to preview change";return r(w=>({...w,status:"error",error:f})),null}},[e]),i=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={currentResource:p.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},g=await e.changeSubscription(_);return g.success?r(f=>({...f,status:"success",subscription:f.subscription?{...f.subscription,resource:g.newResource,interval:g.newInterval,status:g.status}:null,changePreview:null})):r(f=>({...f,status:"error",error:g.error||"Failed to change subscription"})),g}catch(_){const g=_ instanceof Error?_.message:"Failed to change subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),c=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={resource:p.resource,userId:h,immediate:u},g=await e.cancel(_);if(g.success){const f=u?"canceled":p.status;r(w=>({...w,status:"success",subscription:w.subscription?{...w.subscription,status:f,cancelAtPeriodEnd:!u}:null}))}else r(f=>({...f,status:"error",error:g.error||"Failed to cancel subscription"}));return g}catch(_){const g=_ instanceof Error?_.message:"Failed to cancel subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),l=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:p});return window.location.href=h.url,h}catch(h){const _=h instanceof Error?h.message:"Failed to open billing portal";return r(g=>({...g,status:"error",error:_})),null}},[e]),d=y.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=y.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:o,previewChange:a,changeSubscription:i,cancelSubscription:c,openBillingPortal:l,clearPreview:d,reset:m}}const Ih={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"},Rh={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 Oh(e){const t=e?Rh:Ih;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 Pn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function rd(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function Mh(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 Lh({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:[Pn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[Pn(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:["-",Pn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:Pn(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:Pn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:rd(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 Dh({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=J.useCedrosTheme(),m=y.useMemo(()=>Oh(d==="dark"),[d]),{subscription:u,changePreview:p,status:h,error:_,loadSubscription:g,previewChange:f,changeSubscription:w,cancelSubscription:j,openBillingPortal:b,clearPreview:v}=nd();y.useEffect(()=>{g(e,t)},[e,t,g]);const k=y.useCallback(async(O,$)=>{await f(e,O,t,$)},[e,t,f]),R=y.useCallback(async()=>{if(!p)return;const O=r.find(S=>S.price===p.newPlanPrice&&S.currency===p.currency);(await w({newResource:O?.resource||e,newInterval:O?.interval,immediate:!0}))?.success&&O&&s?.(O.resource,O.interval)},[p,r,e,w,s]),N=y.useCallback(async O=>{(await j(O))?.success&&o?.()},[j,o]),C=y.useCallback(()=>{b(t,a)},[t,a,b]),T=h==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[_&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:_}),T&&!u&&n.jsx("div",{className:"cedros-subscription-loading",style:m.loading,children:"Loading subscription..."}),u&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"cedros-subscription-details",style:m.details,children:[n.jsx("h3",{style:m.title,children:"Current Subscription"}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Plan:"}),n.jsx("span",{style:m.value,children:u.resource})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Status:"}),n.jsx("span",{style:{...m.statusBadge,backgroundColor:Mh(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:[Pn(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:rd(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),p&&n.jsx(Lh,{preview:p,onConfirm:R,onCancel:v,isLoading:T,styles:m}),r.length>0&&!p&&n.jsxs("div",{className:"cedros-available-plans",style:m.plansSection,children:[n.jsx("h4",{style:m.plansTitle,children:"Available Plans"}),n.jsx("div",{style:m.plansList,children:r.map(O=>{const $=O.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...$?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:O.name}),n.jsxs("div",{style:m.planPrice,children:[Pn(O.price,O.currency),"/",O.interval]}),O.description&&n.jsx("div",{style:m.planDescription,children:O.description}),$?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>k(O.resource,O.interval),style:m.changePlanButton,disabled:T,children:O.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},O.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:C,style:m.portalButton,disabled:T,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>N(!1),style:m.cancelSubscriptionButton,disabled:T,children:"Cancel Subscription"})]})]})]})}function $h(){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 zh(){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 Fh(){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 Bh(){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 Uh(){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 Wh(){const e=[$h(),zh(),Fh(),Bh(),Uh()],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 Vh(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 qh={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"},Oa=y.createContext(null);function Oe(){const e=y.useContext(Oa);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function Ma(){return y.useContext(Oa)}function Hh({config:e,children:t}){return n.jsx(Oa.Provider,{value:{config:e},children:t})}function Et(e){return new Promise(t=>setTimeout(t,e))}const sd=[{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."}],gs=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];let Co=[];const qr={};function Zh(e,t){let r=e;if(t.category&&t.category!=="all"){const l=sd.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 Gh(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 Qh(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 Yh(e){const t=new Date().toISOString(),r=e.cart.map(o=>{const a=gs.find(i=>i.id===o.resource||i.slug===o.resource)??gs[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 Kh(){return{async listProducts(e){await Et(150);const t=e.page??1,r=e.pageSize??24,s=Zh(gs,e),o=Gh(s,e.sort);return Qh(o,t,r)},async getProductBySlug(e){return await Et(100),gs.find(t=>t.slug===e)??null},async listCategories(){return await Et(80),sd},async getOrderHistory(){return await Et(120),Co},async getCart({customerId:e}){return await Et(80),qr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await Et(120);const r=qr[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 qr[e]=a,a},async updateCart({customerId:e,cart:t}){await Et(60),qr[e]=t},async createCheckoutSession(e){await Et(250);const t=Yh(e);if(Co=[t,...Co].slice(0,25),e.options.successUrl){const r=new URL(e.options.successUrl,"http://localhost");return r.searchParams.set("demoOrderId",t.id),{kind:"redirect",url:r.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:t.id}}},async listSubscriptionTiers(){return await Et(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 Et(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await Et(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function od(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Xh(e){return e?e.toUpperCase():"USD"}function Jh(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function eg(e){if(e&&(e==="physical"||e==="digital"))return e}function tg(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 Hr(e){const t=Xh(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=tg(a);return{id:e.id,slug:e.slug??e.id,title:e.title??od(e.id),description:e.description??"",images:r,price:s/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:Jh(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:eg(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function No(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 nn(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 ng(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,p=(d-1)*m,h=new URLSearchParams;h.set("limit",String(u)),h.set("offset",String(p)),l.search&&h.set("search",l.search),l.category&&h.set("category",l.category),l.sort&&h.set("sort",l.sort),l.filters?.inStock&&h.set("in_stock","true"),l.filters?.minPrice!=null&&h.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&h.set("max_price",String(l.filters.maxPrice));const _=l.filters?.tags,g=Array.isArray(_)?_:typeof _=="string"?[_]:[];g.length&&h.set("tags",g.join(","));const f=await nn(e.serverUrl,`/paywall/v1/products?${h.toString()}`,e.apiKey),{products:w,total:j}=No(f);return{items:w.map(Hr),page:d,pageSize:m,total:j,hasNextPage:typeof j=="number"?p+u<j:w.length===u}},getProductBySlug:async l=>{try{const d=await nn(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(l)}`,e.apiKey);return Hr(d)}catch(d){const m=d?.status;if(m!==404&&m!==405)throw d;try{const u=await nn(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(l)}`,e.apiKey);return Hr(u)}catch(u){const p=u?.status;if(p!==404&&p!==405)throw u;const h=await nn(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:_}=No(h),g=_.find(f=>f.slug===l||f.id===l);return g?Hr(g):null}}},listCategories:async()=>{const l=await nn(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=No(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:od(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await nn(e.serverUrl,"/admin/config/storefront",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([nn(e.serverUrl,"/admin/config/stripe",e.apiKey),nn(e.serverUrl,"/admin/config/x402",e.apiKey),nn(e.serverUrl,"/admin/config/cedros_login",e.apiKey)]),u=l.status==="fulfilled"?!!l.value?.config?.enabled:!1,p=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:p,credits:h}}catch{return null}},getAIRelatedProducts:async l=>{const d={"Content-Type":"application/json"};e.apiKey&&(d["X-API-Key"]=e.apiKey);const m=await fetch(`${e.serverUrl}/admin/ai/related-products`,{method:"POST",headers:d,body:JSON.stringify(l)});if(!m.ok){const u=await m.text().catch(()=>"");throw new Error(`AI related products request failed (${m.status}): ${u}`)}return m.json()}}}function rg(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function Cn(e){return`${e.productId}::${e.variantId??""}`}const sg={items:[]};function og(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=Cn(t.item);return e.items.find(a=>Cn(a)===s)?{...e,items:e.items.map(a=>Cn(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=>Cn(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=>Cn(o)!==s)}:{...e,items:e.items.map(o=>Cn(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=>Cn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return rg(t)}}function ag(e){return e.reduce((t,r)=>t+r.qty,0)}function ig(e){return e.reduce((t,r)=>t+r.qty*r.unitPrice,0)}function oc(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function cg(e,t){try{const r=e.getItem(t);return r?JSON.parse(r):null}catch{return null}}function lg(e,t,r){try{e.setItem(t,JSON.stringify(r))}catch{}}const ad=y.createContext(null);function Dt(){const e=y.useContext(ad);if(!e)throw new Error("useCart must be used within CartProvider");return e}function dg({children:e}){const{config:t}=Oe(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=y.useReducer(og,sg),[d,m]=y.useState(!1),u=y.useRef(!1),p=y.useRef(null);y.useEffect(()=>{const f=oc();if(!f)return;const w=cg(f,r);w&&Array.isArray(w.items)&&l({type:"cart/hydrate",state:w}),m(!0)},[r]),y.useEffect(()=>{const f=oc();f&&lg(f,r,c)},[c,r]),y.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const f=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});f&&Array.isArray(f.items)&&(l({type:"cart/hydrate",state:f}),p.current=JSON.stringify(f))}catch{}})()))},[t.adapter,s,d,o,c]),y.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const f=JSON.stringify(c);if(p.current===f)return;const w=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{p.current=f}).catch(()=>{})},a);return()=>window.clearTimeout(w)},[t.adapter,s,d,o,c,a]);const h=y.useCallback((f,w)=>{const j=c.items.find(b=>b.productId===f&&b.variantId===w);if(j)return{holdId:j.holdId,expiresAt:j.holdExpiresAt}},[c.items]),_=y.useCallback((f,w,j)=>{l({type:"cart/updateHold",productId:f,variantId:w,holdExpiresAt:j})},[]),g=y.useMemo(()=>{const f=ag(c.items),w=ig(c.items);return{items:c.items,promoCode:c.promoCode,count:f,subtotal:w,addItem:(j,b)=>l({type:"cart/add",item:j,qty:b}),removeItem:(j,b)=>l({type:"cart/remove",productId:j,variantId:b}),setQty:(j,b,v)=>l({type:"cart/setQty",productId:j,variantId:b,qty:v}),clear:()=>l({type:"cart/clear"}),setPromoCode:j=>l({type:"cart/setPromoCode",promoCode:j}),holdsSupported:i,getItemHold:h,updateItemHold:_}},[c.items,c.promoCode,i,h,_]);return n.jsx(ad.Provider,{value:g,children:e})}function G(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const p=m[u];p in c||(c[p]=d[p].bind(c))}}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=r?.Parent?new a:this;s(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Xn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class id extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const cd={};function En(e){return cd}function ld(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 ta(e,t){return typeof t=="bigint"?t.toString():t}function La(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Da(e){return e==null}function $a(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ug(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 ac=Symbol("evaluating");function Ce(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==ac)return s===void 0&&(s=ac,s=r()),s},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Fn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function vn(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}function ic(e){return JSON.stringify(e)}function mg(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const dd="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function xs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const pg=La(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ar(e){if(xs(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(xs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ud(e){return Ar(e)?{...e}:Array.isArray(e)?[...e]:e}const fg=new Set(["string","number","symbol"]);function Ms(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function me(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function hg(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const gg={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 xg(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=vn(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 Fn(this,"shape",i),i},checks:[]});return bn(e,a)}function yg(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=vn(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 Fn(this,"shape",i),i},checks:[]});return bn(e,a)}function vg(e,t){if(!Ar(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=vn(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Fn(this,"shape",a),a}});return bn(e,o)}function bg(e,t){if(!Ar(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=vn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return Fn(this,"shape",s),s}});return bn(e,r)}function wg(e,t){const r=vn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return Fn(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return bn(e,r)}function _g(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=vn(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 Fn(this,"shape",l),l},checks:[]});return bn(t,i)}function jg(e,t,r){const s=vn(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 Fn(this,"shape",a),a}});return bn(t,s)}function Kn(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 md(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Zr(e){return typeof e=="string"?e:e?.message}function Tn(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Zr(e.inst?._zod.def?.error?.(e))??Zr(t?.error?.(e))??Zr(r.customError?.(e))??Zr(r.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function za(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Er(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const pd=(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,ta,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},fd=G("$ZodError",pd),hd=G("$ZodError",pd,{Parent:Error});function kg(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 Sg(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 Fa=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 Xn;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>Tn(l,a,En())));throw dd(c,o?.callee),c}return i.value},Ba=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=>Tn(l,a,En())));throw dd(c,o?.callee),c}return i.value},Ls=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 Xn;return a.issues.length?{success:!1,error:new(e??fd)(a.issues.map(i=>Tn(i,o,En())))}:{success:!0,data:a.value}},Cg=Ls(hd),Ds=e=>async(t,r,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>Tn(i,o,En())))}:{success:!0,data:a.value}},Ng=Ds(hd),Pg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Fa(e)(t,r,o)},Ag=e=>(t,r,s)=>Fa(e)(t,r,s),Eg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ba(e)(t,r,o)},Tg=e=>async(t,r,s)=>Ba(e)(t,r,s),Ig=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ls(e)(t,r,o)},Rg=e=>(t,r,s)=>Ls(e)(t,r,s),Og=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ds(e)(t,r,o)},Mg=e=>async(t,r,s)=>Ds(e)(t,r,s),Lg=/^[cC][^\s-]{8,}$/,Dg=/^[0-9a-z]+$/,$g=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,zg=/^[0-9a-vA-V]{20}$/,Fg=/^[A-Za-z0-9]{27}$/,Bg=/^[a-zA-Z0-9_-]{21}$/,Ug=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Wg=/^([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})$/,cc=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)$/,Vg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,qg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Hg(){return new RegExp(qg,"u")}const Zg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Gg=/^(([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}|:))$/,Qg=/^((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])$/,Yg=/^(([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])$/,Kg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gd=/^[A-Za-z0-9_-]*$/,Xg=/^\+[1-9]\d{6,14}$/,xd="(?:(?:\\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])))",Jg=new RegExp(`^${xd}$`);function yd(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 ex(e){return new RegExp(`^${yd(e)}$`)}function tx(e){const t=yd({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(`^${xd}T(?:${s})$`)}const nx=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},rx=/^-?\d+$/,sx=/^-?\d+(?:\.\d+)?$/,ox=/^[^A-Z]*$/,ax=/^[^a-z]*$/,gt=G("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),vd={number:"number",bigint:"bigint",object:"date"},bd=G("$ZodCheckLessThan",(e,t)=>{gt.init(e,t);const r=vd[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})}}),wd=G("$ZodCheckGreaterThan",(e,t)=>{gt.init(e,t);const r=vd[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})}}),ix=G("$ZodCheckMultipleOf",(e,t)=>{gt.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ug(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})}}),cx=G("$ZodCheckNumberFormat",(e,t)=>{gt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=gg[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=rx)}),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})}}),lx=G("$ZodCheckMaxLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const o=s.value;if(o.length<=t.maximum)return;const i=za(o);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),dx=G("$ZodCheckMinLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const o=s.value;if(o.length>=t.minimum)return;const i=za(o);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ux=G("$ZodCheckLengthEquals",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=s=>{const o=s.value,a=o.length;if(a===t.length)return;const i=za(o),c=a>t.length;s.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),$s=G("$ZodCheckStringFormat",(e,t)=>{var r,s;gt.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),mx=G("$ZodCheckRegex",(e,t)=>{$s.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),px=G("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ox),$s.init(e,t)}),fx=G("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ax),$s.init(e,t)}),hx=G("$ZodCheckIncludes",(e,t)=>{gt.init(e,t);const r=Ms(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})}}),gx=G("$ZodCheckStartsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`^${Ms(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})}}),xx=G("$ZodCheckEndsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`.*${Ms(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})}}),yx=G("$ZodCheckOverwrite",(e,t)=>{gt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class vx{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
|
|
54
54
|
`).filter(i=>i),o=Math.min(...s.map(i=>i.length-i.trimStart().length)),a=s.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...r,o.join(`
|
|
55
|
-
`))}}const
|
|
55
|
+
`))}}const bx={major:4,minor:3,patch:6},We=G("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=bx;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=Kn(i),m;for(const u of c){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(d)continue;const p=i.issues.length,h=u._zod.check(i);if(h instanceof Promise&&l?.async===!1)throw new Xn;if(m||h instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await h,i.issues.length!==p&&(d||(d=Kn(i,p)))});else{if(i.issues.length===p)continue;d||(d=Kn(i,p))}}return m?m.then(()=>i):i},a=(i,c,l)=>{if(Kn(i))return i.aborted=!0,i;const d=o(c,s,l);if(d instanceof Promise){if(l.async===!1)throw new Xn;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 Xn;return l.then(d=>o(d,s,c))}return o(l,s,c)}}Ce(e,"~standard",()=>({validate:o=>{try{const a=Cg(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return Ng(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ua=G("$ZodString",(e,t)=>{We.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??nx(e._zod.bag),e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Te=G("$ZodStringFormat",(e,t)=>{$s.init(e,t),Ua.init(e,t)}),wx=G("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Wg),Te.init(e,t)}),_x=G("$ZodUUID",(e,t)=>{if(t.version){const s={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(s===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=cc(s))}else t.pattern??(t.pattern=cc());Te.init(e,t)}),jx=G("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Vg),Te.init(e,t)}),kx=G("$ZodURL",(e,t)=>{Te.init(e,t),e._zod.check=r=>{try{const s=r.value.trim(),o=new URL(s);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Sx=G("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Hg()),Te.init(e,t)}),Cx=G("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Bg),Te.init(e,t)}),Nx=G("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Lg),Te.init(e,t)}),Px=G("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Dg),Te.init(e,t)}),Ax=G("$ZodULID",(e,t)=>{t.pattern??(t.pattern=$g),Te.init(e,t)}),Ex=G("$ZodXID",(e,t)=>{t.pattern??(t.pattern=zg),Te.init(e,t)}),Tx=G("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Fg),Te.init(e,t)}),Ix=G("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=tx(t)),Te.init(e,t)}),Rx=G("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Jg),Te.init(e,t)}),Ox=G("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=ex(t)),Te.init(e,t)}),Mx=G("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ug),Te.init(e,t)}),Lx=G("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Zg),Te.init(e,t),e._zod.bag.format="ipv4"}),Dx=G("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Gg),Te.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),$x=G("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Qg),Te.init(e,t)}),zx=G("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Yg),Te.init(e,t),e._zod.check=r=>{const s=r.value.split("/");try{if(s.length!==2)throw new Error;const[o,a]=s;if(!a)throw new Error;const i=Number(a);if(`${i}`!==a)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function _d(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Fx=G("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Kg),Te.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{_d(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Bx(e){if(!gd.test(e))return!1;const t=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return _d(r)}const Ux=G("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=gd),Te.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{Bx(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Wx=G("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Xg),Te.init(e,t)});function Vx(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 qx=G("$ZodJWT",(e,t)=>{Te.init(e,t),e._zod.check=r=>{Vx(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),jd=G("$ZodNumber",(e,t)=>{We.init(e,t),e._zod.pattern=e._zod.bag.pattern??sx,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}}),Hx=G("$ZodNumberFormat",(e,t)=>{cx.init(e,t),jd.init(e,t)}),Zx=G("$ZodUnknown",(e,t)=>{We.init(e,t),e._zod.parse=r=>r}),Gx=G("$ZodNever",(e,t)=>{We.init(e,t),e._zod.parse=(r,s)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function lc(e,t,r){e.issues.length&&t.issues.push(...md(r,e.issues)),t.value[r]=e.value}const Qx=G("$ZodArray",(e,t)=>{We.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=>lc(d,r,i))):lc(l,r,i)}return a.length?Promise.all(a).then(()=>r):r}});function ys(e,t,r,s,o){if(e.issues.length){if(o&&!(r in s))return;t.issues.push(...md(r,e.issues))}e.value===void 0?r in s&&(t.value[r]=void 0):t.value[r]=e.value}function kd(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=hg(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Sd(e,t,r,s,o,a){const i=[],c=o.keySet,l=o.catchall._zod,d=l.def.type,m=l.optout==="optional";for(const u in t){if(c.has(u))continue;if(d==="never"){i.push(u);continue}const p=l.run({value:t[u],issues:[]},s);p instanceof Promise?e.push(p.then(h=>ys(h,r,u,t,m))):ys(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 Yx=G("$ZodObject",(e,t)=>{if(We.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=La(()=>kd(t));Ce(e._zod,"propValues",()=>{const c=t.shape,l={};for(const d in c){const m=c[d]._zod;if(m.values){l[d]??(l[d]=new Set);for(const u of m.values)l[d].add(u)}}return l});const o=xs,a=t.catchall;let i;e._zod.parse=(c,l)=>{i??(i=s.value);const d=c.value;if(!o(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const m=[],u=i.shape;for(const p of i.keys){const h=u[p],_=h._zod.optout==="optional",g=h._zod.run({value:d[p],issues:[]},l);g instanceof Promise?m.push(g.then(f=>ys(f,c,p,d,_))):ys(g,c,p,d,_)}return a?Sd(m,d,c,l,s.value,e):m.length?Promise.all(m).then(()=>c):c}}),Kx=G("$ZodObjectJIT",(e,t)=>{Yx.init(e,t);const r=e._zod.parse,s=La(()=>kd(t)),o=p=>{const h=new vx(["shape","payload","ctx"]),_=s.value,g=b=>{const v=ic(b);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};h.write("const input = payload.value;");const f=Object.create(null);let w=0;for(const b of _.keys)f[b]=`key_${w++}`;h.write("const newResult = {};");for(const b of _.keys){const v=f[b],k=ic(b),N=p[b]?._zod?.optout==="optional";h.write(`const ${v} = ${g(b)};`),N?h.write(`
|
|
56
56
|
if (${v}.issues.length) {
|
|
57
57
|
if (${k} in input) {
|
|
58
58
|
payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
|
|
@@ -86,14 +86,14 @@ Guidelines:
|
|
|
86
86
|
newResult[${k}] = ${v}.value;
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
-
`)}h.write("payload.value = newResult;"),h.write("return payload;");const j=h.compile();return(b,v)=>j(p,b,v)};let a;const i=gs,c=!od.jitless,d=c&&sg.value,m=t.catchall;let u;e._zod.parse=(p,h)=>{u??(u=s.value);const _=p.value;return i(_)?c&&d&&h?.async===!1&&h.jitless!==!0?(a||(a=o(t.shape)),p=a(p,h),m?_d([],_,p,h,u,e):p):r(p,h):(p.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),p)}});function ic(e,t,r,s){for(const a of e)if(a.issues.length===0)return t.value=a.value,t;const o=e.filter(a=>!Yn(a));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(a=>a.issues.map(i=>En(i,s,An())))}),t)}const Wx=G("$ZodUnion",(e,t)=>{Ue.init(e,t),Ce(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Ce(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Ce(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Ce(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${o.map(a=>La(a.source)).join("|")})$`)}});const r=t.options.length===1,s=t.options[0]._zod.run;e._zod.parse=(o,a)=>{if(r)return s(o,a);let i=!1;const c=[];for(const l of t.options){const d=l._zod.run({value:o.value,issues:[]},a);if(d instanceof Promise)c.push(d),i=!0;else{if(d.issues.length===0)return d;c.push(d)}}return i?Promise.all(c).then(l=>ic(l,o,e,a)):ic(c,o,e,a)}}),Vx=G("$ZodIntersection",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>{const o=r.value,a=t.left._zod.run({value:o,issues:[]},s),i=t.right._zod.run({value:o,issues:[]},s);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([l,d])=>cc(r,l,d)):cc(r,a,i)}});function ta(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Pr(e)&&Pr(t)){const r=Object.keys(t),s=Object.keys(e).filter(a=>r.indexOf(a)!==-1),o={...e,...t};for(const a of s){const i=ta(e[a],t[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};o[a]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let s=0;s<e.length;s++){const o=e[s],a=t[s],i=ta(o,a);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function cc(e,t,r){const s=new Map;let o;for(const c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(const l of c.keys)s.has(l)||s.set(l,{}),s.get(l).l=!0}else e.issues.push(c);for(const c of r.issues)if(c.code==="unrecognized_keys")for(const l of c.keys)s.has(l)||s.set(l,{}),s.get(l).r=!0;else e.issues.push(c);const a=[...s].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length&&o&&e.issues.push({...o,keys:a}),Yn(e))return e;const i=ta(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const qx=G("$ZodEnum",(e,t)=>{Ue.init(e,t);const r=ad(t.entries),s=new Set(r);e._zod.values=s,e._zod.pattern=new RegExp(`^(${r.filter(o=>og.has(typeof o)).map(o=>typeof o=="string"?Os(o):o.toString()).join("|")})$`),e._zod.parse=(o,a)=>{const i=o.value;return s.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Hx=G("$ZodTransform",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new sd(e.constructor.name);const o=t.transform(r.value,r);if(s.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Kn;return r.value=o,r}});function lc(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const jd=G("$ZodOptional",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${La(r.source)})?$`):void 0}),e._zod.parse=(r,s)=>{if(t.innerType._zod.optin==="optional"){const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>lc(a,r.value)):lc(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,s)}}),Zx=G("$ZodExactOptional",(e,t)=>{jd.init(e,t),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,s)=>t.innerType._zod.run(r,s)}),Gx=G("$ZodNullable",(e,t)=>{Ue.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${La(r.source)}|null)$`):void 0}),Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,s)=>r.value===null?r:t.innerType._zod.run(r,s)}),Qx=G("$ZodDefault",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>dc(a,t)):dc(o,t)}});function dc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Yx=G("$ZodPrefault",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>(s.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,s))}),Kx=G("$ZodNonOptional",(e,t)=>{Ue.init(e,t),Ce(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(s=>s!==void 0)):void 0}),e._zod.parse=(r,s)=>{const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>uc(a,e)):uc(o,e)}});function uc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Xx=G("$ZodCatch",(e,t)=>{Ue.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(i=>En(i,s,An()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>En(a,s,An()))},input:r.value}),r.issues=[]),r)}}),Jx=G("$ZodPipe",(e,t)=>{Ue.init(e,t),Ce(e._zod,"values",()=>t.in._zod.values),Ce(e._zod,"optin",()=>t.in._zod.optin),Ce(e._zod,"optout",()=>t.out._zod.optout),Ce(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,s)=>{if(s.direction==="backward"){const a=t.out._zod.run(r,s);return a instanceof Promise?a.then(i=>Zr(i,t.in,s)):Zr(a,t.in,s)}const o=t.in._zod.run(r,s);return o instanceof Promise?o.then(a=>Zr(a,t.out,s)):Zr(o,t.out,s)}});function Zr(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const ey=G("$ZodReadonly",(e,t)=>{Ue.init(e,t),Ce(e._zod,"propValues",()=>t.innerType._zod.propValues),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"optin",()=>t.innerType?._zod?.optin),Ce(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(mc):mc(o)}});function mc(e){return e.value=Object.freeze(e.value),e}const ty=G("$ZodCustom",(e,t)=>{ht.init(e,t),Ue.init(e,t),e._zod.parse=(r,s)=>r,e._zod.check=r=>{const s=r.value,o=t.fn(s);if(o instanceof Promise)return o.then(a=>pc(a,r,s,e));pc(o,r,s,e)}});function pc(e,t,r,s){if(!e){const o={code:"custom",input:r,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(o.params=s._zod.def.params),t.issues.push(Ar(o))}}var fc;class ny{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 ry(){return new ny}(fc=globalThis).__zod_globalRegistry??(fc.__zod_globalRegistry=ry());const _r=globalThis.__zod_globalRegistry;function sy(e,t){return new e({type:"string",...me(t)})}function oy(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...me(t)})}function hc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...me(t)})}function ay(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...me(t)})}function iy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...me(t)})}function cy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...me(t)})}function ly(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...me(t)})}function dy(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...me(t)})}function uy(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...me(t)})}function my(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...me(t)})}function py(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...me(t)})}function fy(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...me(t)})}function hy(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...me(t)})}function gy(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...me(t)})}function xy(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...me(t)})}function yy(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...me(t)})}function vy(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...me(t)})}function by(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...me(t)})}function wy(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...me(t)})}function _y(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...me(t)})}function jy(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...me(t)})}function ky(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...me(t)})}function Sy(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...me(t)})}function Cy(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...me(t)})}function Ny(e,t){return new e({type:"string",format:"date",check:"string_format",...me(t)})}function Py(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...me(t)})}function Ay(e,t){return new e({type:"string",format:"duration",check:"string_format",...me(t)})}function Ey(e,t){return new e({type:"number",checks:[],...me(t)})}function Ty(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...me(t)})}function Iy(e){return new e({type:"unknown"})}function Ry(e,t){return new e({type:"never",...me(t)})}function gc(e,t){return new xd({check:"less_than",...me(t),value:e,inclusive:!1})}function No(e,t){return new xd({check:"less_than",...me(t),value:e,inclusive:!0})}function xc(e,t){return new yd({check:"greater_than",...me(t),value:e,inclusive:!1})}function Po(e,t){return new yd({check:"greater_than",...me(t),value:e,inclusive:!0})}function yc(e,t){return new Xg({check:"multiple_of",...me(t),value:e})}function kd(e,t){return new ex({check:"max_length",...me(t),maximum:e})}function ys(e,t){return new tx({check:"min_length",...me(t),minimum:e})}function Sd(e,t){return new nx({check:"length_equals",...me(t),length:e})}function Oy(e,t){return new rx({check:"string_format",format:"regex",...me(t),pattern:e})}function My(e){return new sx({check:"string_format",format:"lowercase",...me(e)})}function Dy(e){return new ox({check:"string_format",format:"uppercase",...me(e)})}function Ly(e,t){return new ax({check:"string_format",format:"includes",...me(t),includes:e})}function $y(e,t){return new ix({check:"string_format",format:"starts_with",...me(t),prefix:e})}function zy(e,t){return new cx({check:"string_format",format:"ends_with",...me(t),suffix:e})}function sr(e){return new lx({check:"overwrite",tx:e})}function Fy(e){return sr(t=>t.normalize(e))}function By(){return sr(e=>e.trim())}function Uy(){return sr(e=>e.toLowerCase())}function Wy(){return sr(e=>e.toUpperCase())}function Vy(){return sr(e=>rg(e))}function qy(e,t,r){return new e({type:"array",element:t,...me(r)})}function Hy(e,t,r){return new e({type:"custom",check:"custom",fn:t,...me(r)})}function Zy(e){const t=Gy(r=>(r.addIssue=s=>{if(typeof s=="string")r.issues.push(Ar(s,r.value,t._zod.def));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Ar(o))}},e(r.value,r)));return t}function Gy(e,t){const r=new ht({check:"custom",...me(t)});return r._zod.check=e,r}function Cd(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??_r,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Ke(e,t,r={path:[],schemaPath:[]}){var s;const o=e._zod.def,a=t.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);const c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{const m={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,m);else{const p=i.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,p,m)}const u=e._zod.parent;u&&(i.ref||(i.ref=u),Ke(u,t,m),t.seen.get(u).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),t.io==="input"&&rt(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&i.schema._prefault&&((s=i.schema).default??(s.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Nd(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const i of e.seen.entries()){const c=e.metadataRegistry.get(i[0])?.id;if(c){const l=s.get(c);if(l&&l!==i[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(c,i[0])}}const o=i=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const u=e.external.registry.get(i[0])?.id,p=e.external.uri??(_=>_);if(u)return{ref:p(u)};const h=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=h,{defId:h,ref:`${p("__shared")}#/${c}/${h}`}}if(i[1]===r)return{ref:"#"};const d=`#/${c}/`,m=i[1].schema.id??`__schema${e.counter++}`;return{defId:m,ref:d+m}},a=i=>{if(i[1].schema.$ref)return;const c=i[1],{ref:l,defId:d}=o(i);c.def={...c.schema},d&&(c.defId=d);const m=c.schema;for(const u in m)delete m[u];m.$ref=l};if(e.cycles==="throw")for(const i of e.seen.entries()){const c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
89
|
+
`)}h.write("payload.value = newResult;"),h.write("return payload;");const j=h.compile();return(b,v)=>j(p,b,v)};let a;const i=xs,c=!cd.jitless,d=c&&pg.value,m=t.catchall;let u;e._zod.parse=(p,h)=>{u??(u=s.value);const _=p.value;return i(_)?c&&d&&h?.async===!1&&h.jitless!==!0?(a||(a=o(t.shape)),p=a(p,h),m?Sd([],_,p,h,u,e):p):r(p,h):(p.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),p)}});function dc(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=>!Kn(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=>Tn(i,s,En())))}),t)}const Xx=G("$ZodUnion",(e,t)=>{We.init(e,t),Ce(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Ce(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Ce(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Ce(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${o.map(a=>$a(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=>dc(l,o,e,a)):dc(c,o,e,a)}}),Jx=G("$ZodIntersection",(e,t)=>{We.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])=>uc(r,l,d)):uc(r,a,i)}});function na(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(Ar(e)&&Ar(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=na(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=na(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 uc(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}),Kn(e))return e;const i=na(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 ey=G("$ZodEnum",(e,t)=>{We.init(e,t);const r=ld(t.entries),s=new Set(r);e._zod.values=s,e._zod.pattern=new RegExp(`^(${r.filter(o=>fg.has(typeof o)).map(o=>typeof o=="string"?Ms(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}}),ty=G("$ZodTransform",(e,t)=>{We.init(e,t),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new id(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 Xn;return r.value=o,r}});function mc(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Cd=G("$ZodOptional",(e,t)=>{We.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${$a(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=>mc(a,r.value)):mc(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,s)}}),ny=G("$ZodExactOptional",(e,t)=>{Cd.init(e,t),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,s)=>t.innerType._zod.run(r,s)}),ry=G("$ZodNullable",(e,t)=>{We.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${$a(r.source)}|null)$`):void 0}),Ce(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,s)=>r.value===null?r:t.innerType._zod.run(r,s)}),sy=G("$ZodDefault",(e,t)=>{We.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>pc(a,t)):pc(o,t)}});function pc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const oy=G("$ZodPrefault",(e,t)=>{We.init(e,t),e._zod.optin="optional",Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>(s.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,s))}),ay=G("$ZodNonOptional",(e,t)=>{We.init(e,t),Ce(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(s=>s!==void 0)):void 0}),e._zod.parse=(r,s)=>{const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>fc(a,e)):fc(o,e)}});function fc(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 iy=G("$ZodCatch",(e,t)=>{We.init(e,t),Ce(e._zod,"optin",()=>t.innerType._zod.optin),Ce(e._zod,"optout",()=>t.innerType._zod.optout),Ce(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(i=>Tn(i,s,En()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>Tn(a,s,En()))},input:r.value}),r.issues=[]),r)}}),cy=G("$ZodPipe",(e,t)=>{We.init(e,t),Ce(e._zod,"values",()=>t.in._zod.values),Ce(e._zod,"optin",()=>t.in._zod.optin),Ce(e._zod,"optout",()=>t.out._zod.optout),Ce(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,s)=>{if(s.direction==="backward"){const a=t.out._zod.run(r,s);return a instanceof Promise?a.then(i=>Gr(i,t.in,s)):Gr(a,t.in,s)}const o=t.in._zod.run(r,s);return o instanceof Promise?o.then(a=>Gr(a,t.out,s)):Gr(o,t.out,s)}});function Gr(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const ly=G("$ZodReadonly",(e,t)=>{We.init(e,t),Ce(e._zod,"propValues",()=>t.innerType._zod.propValues),Ce(e._zod,"values",()=>t.innerType._zod.values),Ce(e._zod,"optin",()=>t.innerType?._zod?.optin),Ce(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(hc):hc(o)}});function hc(e){return e.value=Object.freeze(e.value),e}const dy=G("$ZodCustom",(e,t)=>{gt.init(e,t),We.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=>gc(a,r,s,e));gc(o,r,s,e)}});function gc(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(Er(o))}}var xc;class uy{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 my(){return new uy}(xc=globalThis).__zod_globalRegistry??(xc.__zod_globalRegistry=my());const jr=globalThis.__zod_globalRegistry;function py(e,t){return new e({type:"string",...me(t)})}function fy(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...me(t)})}function yc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...me(t)})}function hy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...me(t)})}function gy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...me(t)})}function xy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...me(t)})}function yy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...me(t)})}function vy(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...me(t)})}function by(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...me(t)})}function wy(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...me(t)})}function _y(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...me(t)})}function jy(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...me(t)})}function ky(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...me(t)})}function Sy(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...me(t)})}function Cy(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...me(t)})}function Ny(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...me(t)})}function Py(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...me(t)})}function Ay(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...me(t)})}function Ey(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...me(t)})}function Ty(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...me(t)})}function Iy(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...me(t)})}function Ry(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...me(t)})}function Oy(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...me(t)})}function My(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...me(t)})}function Ly(e,t){return new e({type:"string",format:"date",check:"string_format",...me(t)})}function Dy(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...me(t)})}function $y(e,t){return new e({type:"string",format:"duration",check:"string_format",...me(t)})}function zy(e,t){return new e({type:"number",checks:[],...me(t)})}function Fy(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...me(t)})}function By(e){return new e({type:"unknown"})}function Uy(e,t){return new e({type:"never",...me(t)})}function vc(e,t){return new bd({check:"less_than",...me(t),value:e,inclusive:!1})}function Po(e,t){return new bd({check:"less_than",...me(t),value:e,inclusive:!0})}function bc(e,t){return new wd({check:"greater_than",...me(t),value:e,inclusive:!1})}function Ao(e,t){return new wd({check:"greater_than",...me(t),value:e,inclusive:!0})}function wc(e,t){return new ix({check:"multiple_of",...me(t),value:e})}function Nd(e,t){return new lx({check:"max_length",...me(t),maximum:e})}function vs(e,t){return new dx({check:"min_length",...me(t),minimum:e})}function Pd(e,t){return new ux({check:"length_equals",...me(t),length:e})}function Wy(e,t){return new mx({check:"string_format",format:"regex",...me(t),pattern:e})}function Vy(e){return new px({check:"string_format",format:"lowercase",...me(e)})}function qy(e){return new fx({check:"string_format",format:"uppercase",...me(e)})}function Hy(e,t){return new hx({check:"string_format",format:"includes",...me(t),includes:e})}function Zy(e,t){return new gx({check:"string_format",format:"starts_with",...me(t),prefix:e})}function Gy(e,t){return new xx({check:"string_format",format:"ends_with",...me(t),suffix:e})}function or(e){return new yx({check:"overwrite",tx:e})}function Qy(e){return or(t=>t.normalize(e))}function Yy(){return or(e=>e.trim())}function Ky(){return or(e=>e.toLowerCase())}function Xy(){return or(e=>e.toUpperCase())}function Jy(){return or(e=>mg(e))}function ev(e,t,r){return new e({type:"array",element:t,...me(r)})}function tv(e,t,r){return new e({type:"custom",check:"custom",fn:t,...me(r)})}function nv(e){const t=rv(r=>(r.addIssue=s=>{if(typeof s=="string")r.issues.push(Er(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(Er(o))}},e(r.value,r)));return t}function rv(e,t){const r=new gt({check:"custom",...me(t)});return r._zod.check=e,r}function Ad(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??jr,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 Xe(e,t,r={path:[],schemaPath:[]}){var s;const o=e._zod.def,a=t.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);const c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{const m={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,m);else{const p=i.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,p,m)}const u=e._zod.parent;u&&(i.ref||(i.ref=u),Xe(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"&&st(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 Ed(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const i of e.seen.entries()){const c=e.metadataRegistry.get(i[0])?.id;if(c){const l=s.get(c);if(l&&l!==i[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(c,i[0])}}const o=i=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const u=e.external.registry.get(i[0])?.id,p=e.external.uri??(_=>_);if(u)return{ref:p(u)};const h=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=h,{defId:h,ref:`${p("__shared")}#/${c}/${h}`}}if(i[1]===r)return{ref:"#"};const d=`#/${c}/`,m=i[1].schema.id??`__schema${e.counter++}`;return{defId:m,ref:d+m}},a=i=>{if(i[1].schema.$ref)return;const c=i[1],{ref:l,defId:d}=o(i);c.def={...c.schema},d&&(c.defId=d);const m=c.schema;for(const u in m)delete m[u];m.$ref=l};if(e.cycles==="throw")for(const i of e.seen.entries()){const c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
90
90
|
|
|
91
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const c=i[1];if(t===i[0]){a(i);continue}if(e.external){const d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){a(i);continue}}if(e.metadataRegistry.get(i[0])?.id){a(i);continue}if(c.cycle){a(i);continue}if(c.count>1&&e.reused==="ref"){a(i);continue}}}function Pd(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i=>{const c=e.seen.get(i);if(c.ref===null)return;const l=c.def??c.schema,d={...l},m=c.ref;if(c.ref=null,m){s(m);const p=e.seen.get(m),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(h)):Object.assign(l,h),Object.assign(l,d),i._zod.parent===m)for(const g in l)g==="$ref"||g==="allOf"||g in d||delete l[g];if(h.$ref&&p.def)for(const g in l)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(l[g])===JSON.stringify(p.def[g])&&delete l[g]}const u=i._zod.parent;if(u&&u!==m){s(u);const p=e.seen.get(u);if(p?.schema.$ref&&(l.$ref=p.schema.$ref,p.def))for(const h in l)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(l[h])===JSON.stringify(p.def[h])&&delete l[h]}e.override({zodSchema:i,jsonSchema:l,path:c.path??[]})};for(const i of[...e.seen.entries()].reverse())s(i[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(i)}Object.assign(o,r.def??r.schema);const a=e.external?.defs??{};for(const i of e.seen.entries()){const c=i[1];c.def&&c.defId&&(a[c.defId]=c.def)}e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?o.$defs=a:o.definitions=a);try{const i=JSON.parse(JSON.stringify(o));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:vs(t,"input",e.processors),output:vs(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function rt(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return rt(s.element,r);if(s.type==="set")return rt(s.valueType,r);if(s.type==="lazy")return rt(s.getter(),r);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return rt(s.innerType,r);if(s.type==="intersection")return rt(s.left,r)||rt(s.right,r);if(s.type==="record"||s.type==="map")return rt(s.keyType,r)||rt(s.valueType,r);if(s.type==="pipe")return rt(s.in,r)||rt(s.out,r);if(s.type==="object"){for(const o in s.shape)if(rt(s.shape[o],r))return!0;return!1}if(s.type==="union"){for(const o of s.options)if(rt(o,r))return!0;return!1}if(s.type==="tuple"){for(const o of s.items)if(rt(o,r))return!0;return!!(s.rest&&rt(s.rest,r))}return!1}const Qy=(e,t={})=>r=>{const s=Cd({...r,processors:t});return Ke(e,s),Nd(s,e),Pd(s,e)},vs=(e,t,r={})=>s=>{const{libraryOptions:o,target:a}=s??{},i=Cd({...o??{},target:a,io:t,processors:r});return Ke(e,i),Nd(i,e),Pd(i,e)},Yy={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ky=(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=Yy[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}))])}},Xy=(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)},Jy=(e,t,r,s)=>{r.not={}},ev=(e,t,r,s)=>{},tv=(e,t,r,s)=>{const o=e._zod.def,a=ad(o.entries);a.every(i=>typeof i=="number")&&(r.type="number"),a.every(i=>typeof i=="string")&&(r.type="string"),r.enum=a},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=Ke(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]=Ke(i[d],t,{...s,path:[...s.path,"properties",d]});const c=new Set(Object.keys(i)),l=new Set([...c].filter(d=>{const m=a.shape[d]._zod;return t.io==="input"?m.optin===void 0:m.optout===void 0}));l.size>0&&(o.required=Array.from(l)),a.catchall?._zod.def.type==="never"?o.additionalProperties=!1:a.catchall?a.catchall&&(o.additionalProperties=Ke(a.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},av=(e,t,r,s)=>{const o=e._zod.def,a=o.inclusive===!1,i=o.options.map((c,l)=>Ke(c,t,{...s,path:[...s.path,a?"oneOf":"anyOf",l]}));a?r.oneOf=i:r.anyOf=i},iv=(e,t,r,s)=>{const o=e._zod.def,a=Ke(o.left,t,{...s,path:[...s.path,"allOf",0]}),i=Ke(o.right,t,{...s,path:[...s.path,"allOf",1]}),c=d=>"allOf"in d&&Object.keys(d).length===1,l=[...c(a)?a.allOf:[a],...c(i)?i.allOf:[i]];r.allOf=l},cv=(e,t,r,s)=>{const o=e._zod.def,a=Ke(o.innerType,t,s),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]},lv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},dv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},uv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},mv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType;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;Ke(a,t,s);const i=t.seen.get(e);i.ref=a},fv=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.readOnly=!0},Ad=(e,t,r,s)=>{const o=e._zod.def;Ke(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},hv=G("ZodISODateTime",(e,t)=>{jx.init(e,t),Oe.init(e,t)});function gv(e){return Cy(hv,e)}const xv=G("ZodISODate",(e,t)=>{kx.init(e,t),Oe.init(e,t)});function yv(e){return Ny(xv,e)}const vv=G("ZodISOTime",(e,t)=>{Sx.init(e,t),Oe.init(e,t)});function bv(e){return Py(vv,e)}const wv=G("ZodISODuration",(e,t)=>{Cx.init(e,t),Oe.init(e,t)});function _v(e){return Ay(wv,e)}const jv=(e,t)=>{ud.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}}})},Nt=G("ZodError",jv,{Parent:Error}),kv=za(Nt),Sv=Fa(Nt),Cv=Ms(Nt),Nv=Ds(Nt),Pv=vg(Nt),Av=bg(Nt),Ev=wg(Nt),Tv=_g(Nt),Iv=jg(Nt),Rv=kg(Nt),Ov=Sg(Nt),Mv=Cg(Nt),We=G("ZodType",(e,t)=>(Ue.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:vs(e,"input"),output:vs(e,"output")}}),e.toJSONSchema=Qy(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(yn(t,{checks:[...t.checks??[],...r.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0}),e.with=e.check,e.clone=(r,s)=>vn(e,r,s),e.brand=()=>e,e.register=((r,s)=>(r.add(e,s),e)),e.parse=(r,s)=>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=()=>_c(e),e.exactOptional=()=>gb(e),e.nullable=()=>jc(e),e.nullish=()=>_c(jc(e)),e.nonoptional=r=>_b(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=>wb(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)),Ed=G("_ZodString",(e,t)=>{Ba.init(e,t),We.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Ky(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(Oy(...s)),e.includes=(...s)=>e.check(Ly(...s)),e.startsWith=(...s)=>e.check($y(...s)),e.endsWith=(...s)=>e.check(zy(...s)),e.min=(...s)=>e.check(ys(...s)),e.max=(...s)=>e.check(kd(...s)),e.length=(...s)=>e.check(Sd(...s)),e.nonempty=(...s)=>e.check(ys(1,...s)),e.lowercase=s=>e.check(My(s)),e.uppercase=s=>e.check(Dy(s)),e.trim=()=>e.check(By()),e.normalize=(...s)=>e.check(Fy(...s)),e.toLowerCase=()=>e.check(Uy()),e.toUpperCase=()=>e.check(Wy()),e.slugify=()=>e.check(Vy())}),Dv=G("ZodString",(e,t)=>{Ba.init(e,t),Ed.init(e,t),e.email=r=>e.check(oy(Lv,r)),e.url=r=>e.check(dy($v,r)),e.jwt=r=>e.check(Sy(Jv,r)),e.emoji=r=>e.check(uy(zv,r)),e.guid=r=>e.check(hc(vc,r)),e.uuid=r=>e.check(ay(Gr,r)),e.uuidv4=r=>e.check(iy(Gr,r)),e.uuidv6=r=>e.check(cy(Gr,r)),e.uuidv7=r=>e.check(ly(Gr,r)),e.nanoid=r=>e.check(my(Fv,r)),e.guid=r=>e.check(hc(vc,r)),e.cuid=r=>e.check(py(Bv,r)),e.cuid2=r=>e.check(fy(Uv,r)),e.ulid=r=>e.check(hy(Wv,r)),e.base64=r=>e.check(_y(Yv,r)),e.base64url=r=>e.check(jy(Kv,r)),e.xid=r=>e.check(gy(Vv,r)),e.ksuid=r=>e.check(xy(qv,r)),e.ipv4=r=>e.check(yy(Hv,r)),e.ipv6=r=>e.check(vy(Zv,r)),e.cidrv4=r=>e.check(by(Gv,r)),e.cidrv6=r=>e.check(wy(Qv,r)),e.e164=r=>e.check(ky(Xv,r)),e.datetime=r=>e.check(gv(r)),e.date=r=>e.check(yv(r)),e.time=r=>e.check(bv(r)),e.duration=r=>e.check(_v(r))});function st(e){return sy(Dv,e)}const Oe=G("ZodStringFormat",(e,t)=>{Te.init(e,t),Ed.init(e,t)}),Lv=G("ZodEmail",(e,t)=>{fx.init(e,t),Oe.init(e,t)}),vc=G("ZodGUID",(e,t)=>{mx.init(e,t),Oe.init(e,t)}),Gr=G("ZodUUID",(e,t)=>{px.init(e,t),Oe.init(e,t)}),$v=G("ZodURL",(e,t)=>{hx.init(e,t),Oe.init(e,t)}),zv=G("ZodEmoji",(e,t)=>{gx.init(e,t),Oe.init(e,t)}),Fv=G("ZodNanoID",(e,t)=>{xx.init(e,t),Oe.init(e,t)}),Bv=G("ZodCUID",(e,t)=>{yx.init(e,t),Oe.init(e,t)}),Uv=G("ZodCUID2",(e,t)=>{vx.init(e,t),Oe.init(e,t)}),Wv=G("ZodULID",(e,t)=>{bx.init(e,t),Oe.init(e,t)}),Vv=G("ZodXID",(e,t)=>{wx.init(e,t),Oe.init(e,t)}),qv=G("ZodKSUID",(e,t)=>{_x.init(e,t),Oe.init(e,t)}),Hv=G("ZodIPv4",(e,t)=>{Nx.init(e,t),Oe.init(e,t)}),Zv=G("ZodIPv6",(e,t)=>{Px.init(e,t),Oe.init(e,t)}),Gv=G("ZodCIDRv4",(e,t)=>{Ax.init(e,t),Oe.init(e,t)}),Qv=G("ZodCIDRv6",(e,t)=>{Ex.init(e,t),Oe.init(e,t)}),Yv=G("ZodBase64",(e,t)=>{Tx.init(e,t),Oe.init(e,t)}),Kv=G("ZodBase64URL",(e,t)=>{Rx.init(e,t),Oe.init(e,t)}),Xv=G("ZodE164",(e,t)=>{Ox.init(e,t),Oe.init(e,t)}),Jv=G("ZodJWT",(e,t)=>{Dx.init(e,t),Oe.init(e,t)}),Td=G("ZodNumber",(e,t)=>{bd.init(e,t),We.init(e,t),e._zod.processJSONSchema=(s,o,a)=>Xy(e,s,o),e.gt=(s,o)=>e.check(xc(s,o)),e.gte=(s,o)=>e.check(Po(s,o)),e.min=(s,o)=>e.check(Po(s,o)),e.lt=(s,o)=>e.check(gc(s,o)),e.lte=(s,o)=>e.check(No(s,o)),e.max=(s,o)=>e.check(No(s,o)),e.int=s=>e.check(bc(s)),e.safe=s=>e.check(bc(s)),e.positive=s=>e.check(xc(0,s)),e.nonnegative=s=>e.check(Po(0,s)),e.negative=s=>e.check(gc(0,s)),e.nonpositive=s=>e.check(No(0,s)),e.multipleOf=(s,o)=>e.check(yc(s,o)),e.step=(s,o)=>e.check(yc(s,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function eb(e){return Ey(Td,e)}const tb=G("ZodNumberFormat",(e,t)=>{Lx.init(e,t),Td.init(e,t)});function bc(e){return Ty(tb,e)}const nb=G("ZodUnknown",(e,t)=>{$x.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ev()});function wc(){return Iy(nb)}const rb=G("ZodNever",(e,t)=>{zx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Jy(e,r,s)});function sb(e){return Ry(rb,e)}const ob=G("ZodArray",(e,t)=>{Fx.init(e,t),We.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(kd(r,s)),e.length=(r,s)=>e.check(Sd(r,s)),e.unwrap=()=>e.element});function ab(e,t){return qy(ob,e,t)}const ib=G("ZodObject",(e,t)=>{Ux.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>ov(e,r,s,o),Ce(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:wc()}),e.loose=()=>e.clone({...e._zod.def,catchall:wc()}),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(Rd,e,r[0]),e.required=(...r)=>fg(Od,e,r[0])});function Id(e,t){const r={type:"object",shape:e??{},...me(t)};return new ib(r)}const cb=G("ZodUnion",(e,t)=>{Wx.init(e,t),We.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,...me(t)})}const db=G("ZodIntersection",(e,t)=>{Vx.init(e,t),We.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=G("ZodEnum",(e,t)=>{qx.init(e,t),We.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:[],...me(o),entries:a})},e.exclude=(s,o)=>{const a={...t.entries};for(const i of s)if(r.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new na({...t,checks:[],...me(o),entries:a})}});function mb(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new na({type:"enum",entries:r,...me(t)})}const pb=G("ZodTransform",(e,t)=>{Hx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>rv(e,r),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new sd(e.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(Ar(a,r.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(Ar(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(a=>(r.value=a,r)):(r.value=o,r)}});function fb(e){return new pb({type:"transform",transform:e})}const Rd=G("ZodOptional",(e,t)=>{jd.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Ad(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function _c(e){return new Rd({type:"optional",innerType:e})}const hb=G("ZodExactOptional",(e,t)=>{Zx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Ad(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function gb(e){return new hb({type:"optional",innerType:e})}const xb=G("ZodNullable",(e,t)=>{Gx.init(e,t),We.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 xb({type:"nullable",innerType:e})}const yb=G("ZodDefault",(e,t)=>{Qx.init(e,t),We.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 yb({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():cd(t)}})}const bb=G("ZodPrefault",(e,t)=>{Yx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>uv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function wb(e,t){return new bb({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():cd(t)}})}const Od=G("ZodNonOptional",(e,t)=>{Kx.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>lv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function _b(e,t){return new Od({type:"nonoptional",innerType:e,...me(t)})}const jb=G("ZodCatch",(e,t)=>{Xx.init(e,t),We.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=G("ZodPipe",(e,t)=>{Jx.init(e,t),We.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=G("ZodReadonly",(e,t)=>{ey.init(e,t),We.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=G("ZodCustom",(e,t)=>{ty.init(e,t),We.init(e,t),e._zod.processJSONSchema=(r,s,o)=>nv(e,r)});function Ab(e,t={}){return Hy(Pb,e,t)}function Eb(e){return Zy(e)}const Qr=Id({line1:st().min(1,"Address line 1 is required"),line2:st().optional(),city:st().min(1,"City is required"),state:st().optional(),postalCode:st().min(1,"Postal code is required"),country:st().min(2,"Country is required")});function Tb(e){return Id({email:e.requireEmail?st().email("Valid email required"):st().email("Valid email required").optional(),name:e.requireName?st().min(1,"Name is required"):st().optional(),phone:e.requirePhone?st().min(6,"Phone is required"):st().optional(),notes:st().max(500).optional(),shippingAddress:e.requireShippingAddress?Qr:Qr.optional(),billingAddress:e.requireBillingAddress?Qr:Qr.optional(),discountCode:st().optional(),tipAmount:eb().min(0).optional(),shippingMethodId:st().optional()})}const Sc={none:0,optional:1,required:2};function Ao(e,t){return Sc[e]>=Sc[t]?e:t}function Ib(e){if(!e)return null;try{const t=JSON.parse(e);return!t||typeof t!="object"?null:t}catch{return null}}function cs(e,t){let r=!1,s=!1;const o=new Set;let a=t.requireEmail?"required":"none",i=t.defaultMode==="none"?"none":"optional",c=t.defaultMode==="full"?"optional":"none",l=t.allowShipping&&(t.defaultMode==="shipping"||t.defaultMode==="full"),d=t.defaultMode==="full";for(const u of e){u.metadata?.shippingProfile==="digital"?r=!0:s=!0;const h=Ib(u.metadata?.checkoutRequirements);h&&(h.email&&(a=Ao(a,h.email)),h.name&&(i=Ao(i,h.name)),h.phone&&(c=Ao(c,h.phone)),typeof h.shippingAddress=="boolean"&&(l=l||h.shippingAddress),typeof h.billingAddress=="boolean"&&(d=d||h.billingAddress));const _=u.metadata?.fulfillmentNotes;_&&o.add(_)}const m=r&&!s;return m&&(l=!1),{email:a,name:i,phone:c,shippingAddress:l,billingAddress:d,fulfillmentNotes:Array.from(o).join(" "),isDigitalOnly:m,hasPhysical:s}}const Md=y.createContext(null);function Dd(){const{config:e}=Re(),t=Dt(),r=y.useMemo(()=>({line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"}),[]),s=y.useMemo(()=>{const j=cs(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});return Tb({requireEmail:j.email==="required",requireName:j.name==="required",requirePhone:j.phone==="required",requireShippingAddress:j.shippingAddress,requireBillingAddress:j.billingAddress})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail]),[o,a]=y.useState(()=>({email:e.checkout.requireEmail??!0?"":void 0,name:"",phone:"",notes:"",shippingAddress:e.checkout.mode==="shipping"||e.checkout.mode==="full"?r:void 0,billingAddress:e.checkout.mode==="full"?r:void 0,discountCode:"",tipAmount:0,shippingMethodId:""}));y.useEffect(()=>{const j=cs(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});a(b=>{const v={...b};return j.email==="required"&&!v.email&&(v.email=""),j.shippingAddress&&!v.shippingAddress&&(v.shippingAddress=r),j.billingAddress&&!v.billingAddress&&(v.billingAddress=r),j.shippingAddress||(v.shippingAddress=void 0),j.billingAddress||(v.billingAddress=void 0),v})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail,r]);const[i,c]=y.useState({}),[l,d]=y.useState("idle"),[m,u]=y.useState(null),[p,h]=y.useState(null),_=y.useCallback(()=>{c({}),d("idle"),u(null),h(null)},[]),g=y.useCallback((j,b)=>{a(v=>({...v,[j]:b}))},[]),f=y.useCallback(()=>{d("validating"),u(null);const j=s.safeParse(o);if(j.success)return c({}),d("idle"),{ok:!0,values:j.data};const b={};for(const v of j.error.issues)b[v.path.join(".")]=v.message;return c(b),d("error"),u("Please fix the highlighted fields."),{ok:!1}},[s,o]),w=y.useCallback(async j=>{const b=f();if(!b.ok)return{ok:!1};d("creating_session"),u(null),h(null);const v=t.items.map(C=>({resource:C.paymentResource??C.productId,quantity:C.qty,variantId:C.variantId})),k=cs(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1}),R=new Set;if(k.shippingAddress)for(const C of t.items){const T=C.metadata?.shippingCountries;if(T)for(const O of T.split(",")){const $=O.trim().toUpperCase();$&&R.add($)}}const N={...R.size?{shippingCountries:Array.from(R).join(","),shipping_countries:Array.from(R).join(",")}:{}};try{const C=await e.adapter.createCheckoutSession({cart:v,customer:{email:b.values.email||void 0,name:b.values.name||void 0,phone:b.values.phone||void 0,notes:b.values.notes||void 0,shippingAddress:b.values.shippingAddress,billingAddress:b.values.billingAddress},options:{currency:e.currency,successUrl:e.checkout.successUrl,cancelUrl:e.checkout.cancelUrl,allowPromoCodes:e.checkout.allowPromoCodes,metadata:Object.keys(N).length?N:void 0,discountCode:(e.checkout.allowPromoCodes?b.values.discountCode||t.promoCode:void 0)||void 0,tipAmount:e.checkout.allowTipping&&b.values.tipAmount||void 0,shippingMethodId:e.checkout.allowShipping&&b.values.shippingMethodId||void 0,paymentMethodId:j?.paymentMethodId}});return C.kind==="redirect"?(h(C),d("redirecting"),typeof window<"u"&&window.location.assign(C.url),{ok:!0,session:C}):(h(C),d("success"),{ok:!0,session:C})}catch(C){return d("error"),u(C instanceof Error?C.message:"Checkout failed"),{ok:!1}}},[t.items,t.promoCode,e.adapter,e.checkout,e.currency,f]);return{values:o,setValues:a,setField:g,fieldErrors:i,status:l,error:m,session:p,reset:_,validate:f,createCheckoutSession:w}}function Ld({children:e}){const t=Dd();return n.jsx(Md.Provider,{value:t,children:e})}function $s(){const e=y.useContext(Md);if(!e)throw new Error("useCheckout must be used within CheckoutProvider");return e}function Rb(){return Dd()}function Ua(){const{config:e}=Re(),[t,r]=x.useState([]),[s,o]=x.useState(!0),[a,i]=x.useState(null);return x.useEffect(()=>{let c=!1;return o(!0),i(null),e.adapter.listCategories().then(l=>{c||r(l)}).catch(l=>{c||i(l instanceof Error?l.message:"Failed to load categories")}).finally(()=>{c||o(!1)}),()=>{c=!0}},[e.adapter]),{categories:t,isLoading:s,error:a}}function zs(e){const{config:t}=Re(),[r,s]=x.useState(null),[o,a]=x.useState(!0),[i,c]=x.useState(null),l=JSON.stringify(e.filters??{});return x.useEffect(()=>{let d=!1;return a(!0),c(null),t.adapter.listProducts(e).then(m=>{d||s(m)}).catch(m=>{d||c(m instanceof Error?m.message:"Failed to load products")}).finally(()=>{d||a(!1)}),()=>{d=!0}},[t.adapter,e.category,e.search,e.sort,e.page,e.pageSize,l]),{data:r,isLoading:o,error:i}}function $d(e){const{config:t}=Re(),[r,s]=x.useState(null),[o,a]=x.useState(!0),[i,c]=x.useState(null);return x.useEffect(()=>{let l=!1;return a(!0),c(null),t.adapter.getProductBySlug(e).then(d=>{l||s(d)}).catch(d=>{l||c(d instanceof Error?d.message:"Failed to load product")}).finally(()=>{l||a(!1)}),()=>{l=!0}},[t.adapter,e]),{product:r,isLoading:o,error:i}}function zd(){const{config:e}=Re(),[t,r]=x.useState([]),[s,o]=x.useState(!0),[a,i]=x.useState(null);return x.useEffect(()=>{let c=!1;return o(!0),i(null),e.adapter.getOrderHistory().then(l=>{c||r(l)}).catch(l=>{c||i(l instanceof Error?l.message:"Failed to load orders")}).finally(()=>{c||o(!1)}),()=>{c=!0}},[e.adapter]),{orders:t,isLoading:s,error:a}}function Fd(){const{config:e}=Re(),[t,r]=x.useState([]),[s,o]=x.useState(null),[a,i]=x.useState(!0),[c,l]=x.useState(null);return x.useEffect(()=>{let d=!1;async function m(){i(!0),l(null);try{const[u,p]=await Promise.all([e.adapter.listSubscriptionTiers?.()??Promise.resolve([]),e.adapter.getSubscriptionStatus?.()??Promise.resolve(null)]);if(d)return;r(u),o(p)}catch(u){if(d)return;l(u instanceof Error?u.message:"Failed to load subscriptions")}finally{d||i(!1)}}return m(),()=>{d=!0}},[e.adapter]),{tiers:t,status:s,isLoading:a,error:c}}function Bd({enabled:e,customer:t}){const{config:r}=Re(),[s,o]=x.useState([]),[a,i]=x.useState(!1),[c,l]=x.useState(null),d=JSON.stringify(t.shippingAddress??{});return x.useEffect(()=>{let m=!1;if(!e||!r.adapter.getShippingMethods){o([]);return}return i(!0),l(null),r.adapter.getShippingMethods({currency:r.currency,customer:t}).then(u=>{m||o(u)}).catch(u=>{m||l(u instanceof Error?u.message:"Failed to load shipping methods")}).finally(()=>{m||i(!1)}),()=>{m=!0}},[r.adapter,r.currency,e,t.email,t.name,d]),{methods:s,isLoading:a,error:c}}function fr(e,...t){for(const r of t){const s=e[r];if(s)return s}}function Wa(e){const t=fr(e,"error","error_message","message");if(t)return{kind:"error",message:t};const r=fr(e,"canceled","cancelled","cancel","canceled_at");if(r&&r!=="0"&&r!=="false")return{kind:"cancel"};const s=fr(e,"orderId","order_id","demoOrderId"),o=fr(e,"session_id","checkout_session_id");if(s||o)return{kind:"success",orderId:s??o};const a=(fr(e,"status","checkout")??"").toLowerCase();return a==="success"?{kind:"success",orderId:s}:a==="cancel"||a==="canceled"?{kind:"cancel"}:a==="error"?{kind:"error"}:{kind:"idle"}}function Ob(e){const t={};return e.forEach((r,s)=>{t[s]=r}),t}function Va(){const{config:e}=Re(),[t,r]=x.useState({kind:"idle"});return x.useEffect(()=>{if(typeof window>"u")return;const s=new URLSearchParams(window.location.search),o=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 qa({includeCategory:e}){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),r=t.get("q")??"",s=t.get("sort")??"featured",o=ra(t.get("page"))??1,a=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}=Re(),[o,a]=x.useState(new Map),[i,c]=x.useState(!1),[l,d]=x.useState(null),m=x.useMemo(()=>{const _=new Set;for(const g of e)_.add(g.productId);return Array.from(_)},[e]),u=x.useCallback(async()=>{if(r||m.length===0){a(new Map);return}c(!0),d(null);try{const _=await Promise.all(m.map(async w=>{try{return await s.adapter.getProductBySlug(w)}catch{return null}})),g=new Map;for(const w of _)w&&(g.set(w.id,w),w.slug&&w.slug!==w.id&&g.set(w.slug,w));const f=new Map;for(const w of e){const j=Cc(w.productId,w.variantId),b=g.get(w.productId)??null;f.set(j,$b(w,b))}a(f)}catch(_){d(_ instanceof Error?_.message:"Failed to check inventory")}finally{c(!1)}},[s.adapter,e,m,r]);x.useEffect(()=>{u()},[u]),x.useEffect(()=>{if(r||t<=0||m.length===0)return;const _=setInterval(u,t);return()=>clearInterval(_)},[u,m.length,t,r]);const p=x.useCallback((_,g)=>o.get(Cc(_,g)),[o]),h=x.useMemo(()=>{for(const _ of o.values())if(_.isOutOfStock||_.exceedsAvailable)return!0;return!1},[o]);return{inventory:o,isLoading:i,error:l,refresh:u,getItemInventory:p,hasIssues:h}}function 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 Ud({items:e}){const{config:t}=Re(),[r,s]=x.useState(null),[o,a]=x.useState(!1),[i,c]=x.useState(null),l=x.useMemo(()=>{const u=new Set;for(const p of e)u.add(p.productId);return Array.from(u)},[e]),d=x.useCallback(async()=>{if(e.length===0){const u={ok:!0,issues:[],verifiedAt:new Date};return s(u),u}a(!0),c(null);try{const u=await Promise.all(l.map(async g=>{try{return await t.adapter.getProductBySlug(g)}catch{return null}})),p=new Map;for(const g of u)g&&(p.set(g.id,g),g.slug&&g.slug!==g.id&&p.set(g.slug,g));const h=[];for(const g of e){const f=p.get(g.productId)??null,w=Bb(g,f);w&&h.push(w)}const _={ok:h.length===0,issues:h,verifiedAt:new Date};return s(_),a(!1),_}catch(u){const p=u instanceof Error?u.message:"Failed to verify inventory";c(p),a(!1);const h={ok:!1,issues:[],verifiedAt:new Date};return s(h),h}},[t.adapter,e,l]),m=x.useCallback(()=>{s(null),c(null)},[]);return{result:r,isVerifying:o,error:i,verify:d,reset:m}}function 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,h=[],_=[];for(const g of l){if(!g.holdExpiresAt)continue;const f=new Date(g.holdExpiresAt),w=f.getTime()-u,j=`${g.productId}::${g.variantId??""}`;w<=0?(h.push({productId:g.productId,variantId:g.variantId}),c.current.has(j)||(c.current.add(j),t?.({productId:g.productId,variantId:g.variantId,title:g.titleSnapshot,expiredAt:f}))):w<=p&&_.push({productId:g.productId,variantId:g.variantId,expiresAt:f,remainingMs:w})}o(h),i(_)};d();const m=setInterval(d,1e4);return()=>clearInterval(m)},[r,l,t]),x.useEffect(()=>{const d=new Set(l.map(m=>`${m.productId}::${m.variantId??""}`));for(const m of c.current)d.has(m)||c.current.delete(m)},[l]),{expiringItems:a,expiredItems:s}}const Ne={relatedProducts:{mode:"most_recent",maxItems:4,layout:{layout:"large",imageCrop:"center"}},catalog:{filters:{tags:!0,priceRange:!0,inStock:!0},sort:{featured:!0,priceAsc:!0,priceDesc:!0}},checkout:{promoCodes:!0},shopLayout:{layout:"large",imageCrop:"center"},categoryLayout:{layout:"large",imageCrop:"center"},sections:{showDescription:!0,showSpecs:!0,showShipping:!0,showRelatedProducts:!0},inventory:{preCheckoutVerification:!0,holdsEnabled:!1,holdDurationMinutes:15},shopPage:{title:"Shop",description:""}};function 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]=y.useState(Ne),[a,i]=y.useState(!!r?.getStorefrontSettings);return y.useEffect(()=>{if(!r?.getStorefrontSettings){i(!1);return}let c=!1;async function l(){try{const d=await r.getStorefrontSettings();!c&&d&&o(Wb(d))}catch{}finally{c||i(!1)}}return l(),()=>{c=!0}},[r]),{settings:s,isLoading:a}}const Vb={card:!0,crypto:!0,credits:!1};function Wd(){const t=Oa()?.config?.adapter,[r,s]=y.useState(Vb),[o,a]=y.useState(!!t?.getPaymentMethodsConfig);return y.useEffect(()=>{if(!t?.getPaymentMethodsConfig){a(!1);return}let i=!1;async function c(){try{const l=await t.getPaymentMethodsConfig();!i&&l&&s(l)}catch{}finally{i||a(!1)}}return c(),()=>{i=!0}},[t]),{config:r,isLoading:o}}const Nc=new Map;function qb(e){return e.productId?`id:${e.productId}`:e.name?`name:${e.name}`:""}function Vd(e={}){const{productId:t,product:r,enabled:s=!0}=e,a=Oa()?.config?.adapter,[i,c]=y.useState(null),[l,d]=y.useState(null),[m,u]=y.useState(!1),[p,h]=y.useState(null),_=y.useRef(0),g=y.useCallback(async()=>{const f=t?{productId:t}:r?{name:r.name,description:r.description,tags:r.tags,categoryIds:r.categoryIds}:{};if(!f.productId&&!f.name)return;if(!a?.getAIRelatedProducts){h("AI recommendations not available");return}const w=qb(f),j=Nc.get(w);if(j){c(j.relatedProductIds),d(j.reasoning),h(null);return}const b=++_.current;u(!0),h(null);try{const v=await a.getAIRelatedProducts(f);b===_.current&&(c(v.relatedProductIds),d(v.reasoning),h(null),w&&Nc.set(w,v))}catch(v){if(b===_.current){const k=v instanceof Error?v.message:"Failed to get AI recommendations";h(k),c(null),d(null)}}finally{b===_.current&&u(!1)}},[a,t,r]);return y.useEffect(()=>{s&&(!t&&!r?.name||g())},[s,t,r?.name,g]),{relatedProductIds:i,reasoning:l,isLoading:m,error:p,refetch:g}}function Ie(e,t){if(!e)throw new Error(t)}function Et(e){return typeof e=="string"&&e.trim().length>0}async function Hb(e,t={}){const r=t.pageSize??10,s=await e.listCategories();Ie(Array.isArray(s),"listCategories() must return an array");for(const i of s)Ie(Et(i.id),"Category.id is required"),Ie(Et(i.slug),"Category.slug is required"),Ie(Et(i.name),"Category.name is required");const o=await e.listProducts({page:1,pageSize:r});if(Ie(o&&Array.isArray(o.items),"listProducts() must return { items: Product[] }"),Ie(typeof o.page=="number","listProducts().page must be a number"),Ie(typeof o.pageSize=="number","listProducts().pageSize must be a number"),o.items.length>0){const i=o.items[0];Ie(Et(i.id),"Product.id is required"),Ie(Et(i.slug),"Product.slug is required"),Ie(Et(i.title),"Product.title is required"),Ie(typeof i.description=="string","Product.description must be a string"),Ie(Array.isArray(i.images),"Product.images must be an array"),Ie(typeof i.price=="number","Product.price must be a number"),Ie(Et(i.currency),"Product.currency is required"),Ie(Array.isArray(i.tags),"Product.tags must be an array"),Ie(Array.isArray(i.categoryIds),"Product.categoryIds must be an array");const c=await e.getProductBySlug(i.slug);Ie(c===null||Et(c.id),"getProductBySlug() must return Product or null")}const a=await e.getOrderHistory();Ie(Array.isArray(a),"getOrderHistory() must return an array");for(const i of a)Ie(Et(i.id),"Order.id is required"),Ie(Et(i.createdAt),"Order.createdAt is required"),Ie(typeof i.total=="number","Order.total must be a number"),Ie(Et(i.currency),"Order.currency is required"),Ie(Array.isArray(i.items),"Order.items must be an array")}function Pc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ar(...e){return t=>{let r=!1;const s=e.map(o=>{const a=Pc(o,t);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let o=0;o<s.length;o++){const a=s[o];typeof a=="function"?a():Pc(e[o],null)}}}}function Ee(...e){return x.useCallback(ar(...e),e)}var Zb=Symbol.for("react.lazy"),bs=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 Hd(e){const t=Yb(e),r=x.forwardRef((s,o)=>{let{children:a,...i}=s;qd(a)&&typeof bs=="function"&&(a=bs(a._payload));const c=x.Children.toArray(a),l=c.find(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=Hd("Slot");function Yb(e){const t=x.forwardRef((r,s)=>{let{children:o,...a}=r;if(qd(o)&&typeof bs=="function"&&(o=bs(o._payload)),x.isValidElement(o)){const i=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 Zd(e){var t,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(r=Zd(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function Gd(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=Zd(e))&&(s&&(s+=" "),s+=t);return s}const Ac=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Ec=Gd,Ga=(e,t)=>r=>{var s;if(t?.variants==null)return Ec(e,r?.class,r?.className);const{variants:o,defaultVariants:a}=t,i=Object.keys(o).map(d=>{const m=r?.[d],u=a?.[d];if(m===null)return null;const p=Ac(m)||Ac(u);return o[d][p]}),c=r&&Object.entries(r).reduce((d,m)=>{let[u,p]=m;return p===void 0||(d[u]=p),d},{}),l=t==null||(s=t.compoundVariants)===null||s===void 0?void 0:s.reduce((d,m)=>{let{class:u,className:p,...h}=m;return Object.entries(h).every(_=>{let[g,f]=_;return Array.isArray(f)?f.includes({...a,...c}[g]):{...a,...c}[g]===f})?[...d,u,p]:d},[]);return Ec(e,i,l,r?.class,r?.className)},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}),Qd=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),ws="-",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(ws),l=c[0]===""&&c.length>1?1:0;return Yd(c,l,t)},getConflictingClassGroupIds:(i,c)=>{if(c){const l=s[i],d=r[i];return l?d?t0(d,l):l:d||Tc}return r[i]||Tc}}},Yd=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],a=r.nextPart.get(o);if(a){const d=Yd(e,t+1,a);if(d)return d}const i=r.validators;if(i===null)return;const c=t===0?e.join(ws):e.slice(t).join(ws),l=i.length;for(let d=0;d<l;d++){const m=i[d];if(m.validator(c))return m.classGroupId}},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=Qd();for(const s in e){const o=e[s];Qa(o,r,s,t)}return r},Qa=(e,t,r,s)=>{const o=e.length;for(let a=0;a<o;a++){const i=e[a];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:Kd(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,Kd(t,c),r,s)}},Kd=(e,t)=>{let r=e;const s=t.split(ws),o=s.length;for(let a=0;a<o;a++){const i=s[a];let c=r.nextPart.get(i);c||(c=Qd(),r.nextPart.set(i,c)),r=c}return r},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 g=0;g<m;g++){const f=o[g];if(i===0&&c===0){if(f===Ic){a.push(o.slice(l,g)),l=g+1;continue}if(f==="/"){d=g;continue}}f==="["?i++:f==="]"?i--:f==="("?c++:f===")"&&c--}const u=a.length===0?o:o.slice(l);let p=u,h=!1;u.endsWith(sa)?(p=u.slice(0,-1),h=!0):u.startsWith(sa)&&(p=u.slice(1),h=!0);const _=d&&d>l?d-l:void 0;return Rc(a,h,p,_)};if(t){const o=t+Ic,a=s;s=i=>i.startsWith(o)?a(i.slice(o.length)):Rc(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}},x0=e=>({cache:p0(e.cacheSize),parseClassName:h0(e),sortModifiers:g0(e),...s0(e)}),y0=/\s+/,v0=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:a}=t,i=[],c=e.trim().split(y0);let l="";for(let d=c.length-1;d>=0;d-=1){const m=c[d],{isExternal:u,modifiers:p,hasImportantModifier:h,baseClassName:_,maybePostfixModifierPosition:g}=r(m);if(u){l=m+(l.length>0?" "+l:l);continue}let f=!!g,w=s(f?_.substring(0,g):_);if(!w){if(!f){l=m+(l.length>0?" "+l:l);continue}if(w=s(_),!w){l=m+(l.length>0?" "+l:l);continue}f=!1}const j=p.length===0?"":p.length===1?p[0]:a(p).join(":"),b=h?j+sa:j,v=b+w;if(i.indexOf(v)>-1)continue;i.push(v);const k=o(w,f);for(let R=0;R<k.length;++R){const N=k[R];i.push(b+N)}l=m+(l.length>0?" "+l:l)}return l},b0=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=Xd(r))&&(o&&(o+=" "),o+=s);return o},Xd=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=Xd(e[s]))&&(r&&(r+=" "),r+=t);return r},w0=(e,...t)=>{let r,s,o,a;const i=l=>{const d=t.reduce((m,u)=>u(m),e());return r=x0(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))},_0=[],Ze=e=>{const t=r=>r[e]||_0;return t.isThemeGetter=!0,t},Jd=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,eu=/^\((?:(\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)),an=e=>!!e&&Number.isInteger(Number(e)),Eo=e=>e.endsWith("%")&&ye(e.slice(0,-1)),nn=e=>k0.test(e),A0=()=>!0,E0=e=>S0.test(e)&&!C0.test(e),tu=()=>!1,T0=e=>N0.test(e),I0=e=>P0.test(e),R0=e=>!se(e)&&!oe(e),O0=e=>ir(e,su,tu),se=e=>Jd.test(e),Cn=e=>ir(e,ou,E0),To=e=>ir(e,z0,ye),Oc=e=>ir(e,nu,tu),M0=e=>ir(e,ru,I0),Yr=e=>ir(e,au,T0),oe=e=>eu.test(e),hr=e=>cr(e,ou),D0=e=>cr(e,F0),Mc=e=>cr(e,nu),L0=e=>cr(e,su),$0=e=>cr(e,ru),Kr=e=>cr(e,au,!0),ir=(e,t,r)=>{const s=Jd.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},cr=(e,t,r=!1)=>{const s=eu.exec(e);return s?s[1]?t(s[1]):r:!1},nu=e=>e==="position"||e==="percentage",ru=e=>e==="image"||e==="url",su=e=>e==="length"||e==="size"||e==="bg-size",ou=e=>e==="length",z0=e=>e==="number",F0=e=>e==="family-name",au=e=>e==="shadow",B0=()=>{const e=Ze("color"),t=Ze("font"),r=Ze("text"),s=Ze("font-weight"),o=Ze("tracking"),a=Ze("leading"),i=Ze("breakpoint"),c=Ze("container"),l=Ze("spacing"),d=Ze("radius"),m=Ze("shadow"),u=Ze("inset-shadow"),p=Ze("text-shadow"),h=Ze("drop-shadow"),_=Ze("blur"),g=Ze("perspective"),f=Ze("aspect"),w=Ze("ease"),j=Ze("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],v=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],k=()=>[...v(),oe,se],R=()=>["auto","hidden","clip","visible","scroll"],N=()=>["auto","contain","none"],C=()=>[oe,se,l],T=()=>[Hn,"full","auto",...C()],O=()=>[an,"none","subgrid",oe,se],$=()=>["auto",{span:["full",an,oe,se]},an,oe,se],S=()=>[an,"auto",oe,se],A=()=>["auto","min","max","fr",oe,se],I=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],B=()=>["start","end","center","stretch","center-safe","end-safe"],D=()=>["auto",...C()],E=()=>[Hn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...C()],P=()=>[e,oe,se],z=()=>[...v(),Mc,Oc,{position:[oe,se]}],Z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],K=()=>["auto","cover","contain",L0,O0,{size:[oe,se]}],L=()=>[Eo,hr,Cn],W=()=>["","none","full",d,oe,se],Y=()=>["",ye,hr,Cn],V=()=>["solid","dashed","dotted","double"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],F=()=>[ye,Eo,Mc,Oc],ee=()=>["","none",_,oe,se],pe=()=>["none",ye,oe,se],q=()=>["none",ye,oe,se],ne=()=>[ye,oe,se],le=()=>[Hn,"full",...C()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[nn],breakpoint:[nn],color:[A0],container:[nn],"drop-shadow":[nn],ease:["in","out","in-out"],font:[R0],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[nn],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[nn],shadow:[nn],spacing:["px",ye],text:[nn],"text-shadow":[nn],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Hn,se,oe,f]}],container:["container"],columns:[{columns:[ye,se,oe,c]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:k()}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:N()}],"overscroll-x":[{"overscroll-x":N()}],"overscroll-y":[{"overscroll-y":N()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{start:T()}],end:[{end:T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[an,"auto",oe,se]}],basis:[{basis:[Hn,"full","auto",c,...C()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ye,Hn,"auto","initial","none",se]}],grow:[{grow:["",ye,oe,se]}],shrink:[{shrink:["",ye,oe,se]}],order:[{order:[an,"first","last","none",oe,se]}],"grid-cols":[{"grid-cols":O()}],"col-start-end":[{col:$()}],"col-start":[{"col-start":S()}],"col-end":[{"col-end":S()}],"grid-rows":[{"grid-rows":O()}],"row-start-end":[{row:$()}],"row-start":[{"row-start":S()}],"row-end":[{"row-end":S()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":A()}],"auto-rows":[{"auto-rows":A()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...I(),"normal"]}],"justify-items":[{"justify-items":[...B(),"normal"]}],"justify-self":[{"justify-self":["auto",...B()]}],"align-content":[{content:["normal",...I()]}],"align-items":[{items:[...B(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...B(),{baseline:["","last"]}]}],"place-content":[{"place-content":I()}],"place-items":[{"place-items":[...B(),"baseline"]}],"place-self":[{"place-self":["auto",...B()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:D()}],mx:[{mx:D()}],my:[{my:D()}],ms:[{ms:D()}],me:[{me:D()}],mt:[{mt:D()}],mr:[{mr:D()}],mb:[{mb:D()}],ml:[{ml:D()}],"space-x":[{"space-x":C()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":C()}],"space-y-reverse":["space-y-reverse"],size:[{size:E()}],w:[{w:[c,"screen",...E()]}],"min-w":[{"min-w":[c,"screen","none",...E()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[i]},...E()]}],h:[{h:["screen","lh",...E()]}],"min-h":[{"min-h":["screen","lh","none",...E()]}],"max-h":[{"max-h":["screen","lh",...E()]}],"font-size":[{text:["base",r,hr,Cn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,oe,To]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Eo,se]}],"font-family":[{font:[D0,se,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,oe,se]}],"line-clamp":[{"line-clamp":[ye,"none",oe,To]}],leading:[{leading:[a,...C()]}],"list-image":[{"list-image":["none",oe,se]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",oe,se]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:P()}],"text-color":[{text:P()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:[ye,"from-font","auto",oe,Cn]}],"text-decoration-color":[{decoration:P()}],"underline-offset":[{"underline-offset":[ye,"auto",oe,se]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",oe,se]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",oe,se]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:Z()}],"bg-size":[{bg:K()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},an,oe,se],radial:["",oe,se],conic:[an,oe,se]},$0,M0]}],"bg-color":[{bg:P()}],"gradient-from-pos":[{from:L()}],"gradient-via-pos":[{via:L()}],"gradient-to-pos":[{to:L()}],"gradient-from":[{from:P()}],"gradient-via":[{via:P()}],"gradient-to":[{to:P()}],rounded:[{rounded:W()}],"rounded-s":[{"rounded-s":W()}],"rounded-e":[{"rounded-e":W()}],"rounded-t":[{"rounded-t":W()}],"rounded-r":[{"rounded-r":W()}],"rounded-b":[{"rounded-b":W()}],"rounded-l":[{"rounded-l":W()}],"rounded-ss":[{"rounded-ss":W()}],"rounded-se":[{"rounded-se":W()}],"rounded-ee":[{"rounded-ee":W()}],"rounded-es":[{"rounded-es":W()}],"rounded-tl":[{"rounded-tl":W()}],"rounded-tr":[{"rounded-tr":W()}],"rounded-br":[{"rounded-br":W()}],"rounded-bl":[{"rounded-bl":W()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...V(),"hidden","none"]}],"divide-style":[{divide:[...V(),"hidden","none"]}],"border-color":[{border:P()}],"border-color-x":[{"border-x":P()}],"border-color-y":[{"border-y":P()}],"border-color-s":[{"border-s":P()}],"border-color-e":[{"border-e":P()}],"border-color-t":[{"border-t":P()}],"border-color-r":[{"border-r":P()}],"border-color-b":[{"border-b":P()}],"border-color-l":[{"border-l":P()}],"divide-color":[{divide:P()}],"outline-style":[{outline:[...V(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ye,oe,se]}],"outline-w":[{outline:["",ye,hr,Cn]}],"outline-color":[{outline:P()}],shadow:[{shadow:["","none",m,Kr,Yr]}],"shadow-color":[{shadow:P()}],"inset-shadow":[{"inset-shadow":["none",u,Kr,Yr]}],"inset-shadow-color":[{"inset-shadow":P()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:P()}],"ring-offset-w":[{"ring-offset":[ye,Cn]}],"ring-offset-color":[{"ring-offset":P()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":P()}],"text-shadow":[{"text-shadow":["none",p,Kr,Yr]}],"text-shadow-color":[{"text-shadow":P()}],opacity:[{opacity:[ye,oe,se]}],"mix-blend":[{"mix-blend":[...ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":F()}],"mask-image-linear-to-pos":[{"mask-linear-to":F()}],"mask-image-linear-from-color":[{"mask-linear-from":P()}],"mask-image-linear-to-color":[{"mask-linear-to":P()}],"mask-image-t-from-pos":[{"mask-t-from":F()}],"mask-image-t-to-pos":[{"mask-t-to":F()}],"mask-image-t-from-color":[{"mask-t-from":P()}],"mask-image-t-to-color":[{"mask-t-to":P()}],"mask-image-r-from-pos":[{"mask-r-from":F()}],"mask-image-r-to-pos":[{"mask-r-to":F()}],"mask-image-r-from-color":[{"mask-r-from":P()}],"mask-image-r-to-color":[{"mask-r-to":P()}],"mask-image-b-from-pos":[{"mask-b-from":F()}],"mask-image-b-to-pos":[{"mask-b-to":F()}],"mask-image-b-from-color":[{"mask-b-from":P()}],"mask-image-b-to-color":[{"mask-b-to":P()}],"mask-image-l-from-pos":[{"mask-l-from":F()}],"mask-image-l-to-pos":[{"mask-l-to":F()}],"mask-image-l-from-color":[{"mask-l-from":P()}],"mask-image-l-to-color":[{"mask-l-to":P()}],"mask-image-x-from-pos":[{"mask-x-from":F()}],"mask-image-x-to-pos":[{"mask-x-to":F()}],"mask-image-x-from-color":[{"mask-x-from":P()}],"mask-image-x-to-color":[{"mask-x-to":P()}],"mask-image-y-from-pos":[{"mask-y-from":F()}],"mask-image-y-to-pos":[{"mask-y-to":F()}],"mask-image-y-from-color":[{"mask-y-from":P()}],"mask-image-y-to-color":[{"mask-y-to":P()}],"mask-image-radial":[{"mask-radial":[oe,se]}],"mask-image-radial-from-pos":[{"mask-radial-from":F()}],"mask-image-radial-to-pos":[{"mask-radial-to":F()}],"mask-image-radial-from-color":[{"mask-radial-from":P()}],"mask-image-radial-to-color":[{"mask-radial-to":P()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":v()}],"mask-image-conic-pos":[{"mask-conic":[ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":F()}],"mask-image-conic-to-pos":[{"mask-conic-to":F()}],"mask-image-conic-from-color":[{"mask-conic-from":P()}],"mask-image-conic-to-color":[{"mask-conic-to":P()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:Z()}],"mask-size":[{mask:K()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",oe,se]}],filter:[{filter:["","none",oe,se]}],blur:[{blur:ee()}],brightness:[{brightness:[ye,oe,se]}],contrast:[{contrast:[ye,oe,se]}],"drop-shadow":[{"drop-shadow":["","none",h,Kr,Yr]}],"drop-shadow-color":[{"drop-shadow":P()}],grayscale:[{grayscale:["",ye,oe,se]}],"hue-rotate":[{"hue-rotate":[ye,oe,se]}],invert:[{invert:["",ye,oe,se]}],saturate:[{saturate:[ye,oe,se]}],sepia:[{sepia:["",ye,oe,se]}],"backdrop-filter":[{"backdrop-filter":["","none",oe,se]}],"backdrop-blur":[{"backdrop-blur":ee()}],"backdrop-brightness":[{"backdrop-brightness":[ye,oe,se]}],"backdrop-contrast":[{"backdrop-contrast":[ye,oe,se]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ye,oe,se]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ye,oe,se]}],"backdrop-invert":[{"backdrop-invert":["",ye,oe,se]}],"backdrop-opacity":[{"backdrop-opacity":[ye,oe,se]}],"backdrop-saturate":[{"backdrop-saturate":[ye,oe,se]}],"backdrop-sepia":[{"backdrop-sepia":["",ye,oe,se]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",oe,se]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ye,"initial",oe,se]}],ease:[{ease:["linear","initial",w,oe,se]}],delay:[{delay:[ye,oe,se]}],animate:[{animate:["none",j,oe,se]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,oe,se]}],"perspective-origin":[{"perspective-origin":k()}],rotate:[{rotate:pe()}],"rotate-x":[{"rotate-x":pe()}],"rotate-y":[{"rotate-y":pe()}],"rotate-z":[{"rotate-z":pe()}],scale:[{scale:q()}],"scale-x":[{"scale-x":q()}],"scale-y":[{"scale-y":q()}],"scale-z":[{"scale-z":q()}],"scale-3d":["scale-3d"],skew:[{skew:ne()}],"skew-x":[{"skew-x":ne()}],"skew-y":[{"skew-y":ne()}],transform:[{transform:[oe,se,"","none","gpu","cpu"]}],"transform-origin":[{origin:k()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:le()}],"translate-x":[{"translate-x":le()}],"translate-y":[{"translate-y":le()}],"translate-z":[{"translate-z":le()}],"translate-none":["translate-none"],accent:[{accent:P()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:P()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",oe,se]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",oe,se]}],fill:[{fill:["none",...P()]}],"stroke-w":[{stroke:[ye,hr,Cn,To]}],stroke:[{stroke:["none",...P()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},U0=w0(B0);function H(...e){return U0(Gd(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"}}),ie=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})});ie.displayName="Button";const V0=Ga("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors",{variants:{variant:{default:"border-transparent bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900",secondary:"border-transparent bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",outline:"border-neutral-200 text-neutral-900 dark:border-neutral-800 dark:text-neutral-50"}},defaultVariants:{variant:"secondary"}});function Pn({className:e,variant:t,...r}){return n.jsx("div",{className:H(V0({variant:t}),e),...r})}const Rt=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("rounded-xl border border-neutral-200 bg-white text-neutral-950 shadow-sm dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",e),...t}));Rt.displayName="Card";const Er=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex flex-col space-y-1.5 p-6",e),...t}));Er.displayName="CardHeader";const Tr=x.forwardRef(({className:e,...t},r)=>n.jsx("h3",{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));Tr.displayName="CardTitle";const iu=x.forwardRef(({className:e,...t},r)=>n.jsx("p",{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));iu.displayName="CardDescription";const Gt=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("p-6 pt-0",e),...t}));Gt.displayName="CardContent";const cu=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex items-center p-6 pt-0",e),...t}));cu.displayName="CardFooter";const Be=x.forwardRef(({className:e,...t},r)=>n.jsx("input",{ref:r,className:H("flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-50/20",e),...t}));Be.displayName="Input";const at=x.forwardRef(({className:e,...t},r)=>n.jsx("label",{ref:r,className:H("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",e),...t}));at.displayName="Label";var q0=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],H0=q0.reduce((e,t)=>{const r=Hd(`Primitive.${t}`),s=x.forwardRef((o,a)=>{const{asChild:i,...c}=o,l=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(l,{...c,ref:a})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{}),Z0="Separator",Dc="horizontal",G0=["horizontal","vertical"],lu=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})});lu.displayName=Z0;function Q0(e){return G0.includes(e)}var du=lu;const St=x.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...s},o)=>n.jsx(du,{ref:o,decorative:r,orientation:t,className:H("shrink-0 bg-neutral-200 dark:bg-neutral-800",t==="horizontal"?"h-px w-full":"h-full w-px",e),...s}));St.displayName=du.displayName;function De({className:e,...t}){return n.jsx("div",{className:H("animate-pulse rounded-md bg-neutral-100 dark:bg-neutral-800",e),...t})}function Lc(e,[t,r]){return Math.min(r,Math.max(t,e))}function _e(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e?.(o),r===!1||!o.defaultPrevented)return t?.(o)}}function 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 bn(e,t=[]){let r=[];function s(a,i){const c=x.createContext(i),l=r.length;r=[...r,i];const d=u=>{const{scope:p,children:h,..._}=u,g=p?.[e]?.[l]||c,f=x.useMemo(()=>_,Object.values(_));return n.jsx(g.Provider,{value:f,children:h})};d.displayName=a+"Provider";function m(u,p){const h=p?.[e]?.[l]||c,_=x.useContext(h);if(_)return _;if(i!==void 0)return i;throw new Error(`\`${u}\` must be used within \`${a}\``)}return[d,m]}const o=()=>{const a=r.map(i=>x.createContext(i));return function(c){const l=c?.[e]||a;return x.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return o.scopeName=e,[s,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(ew);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=nw(o),c=tw(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 ew(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===J0}function tw(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 nw(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function Ya(e){const t=e+"CollectionProvider",[r,s]=bn(t),[o,a]=r(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:f,children:w}=g,j=y.useRef(null),b=y.useRef(new Map).current;return n.jsx(o,{scope:f,itemMap:b,collectionRef:j,children:w})};i.displayName=t;const c=e+"CollectionSlot",l=$c(c),d=y.forwardRef((g,f)=>{const{scope:w,children:j}=g,b=a(c,w),v=Ee(f,b.collectionRef);return n.jsx(l,{ref:v,children:j})});d.displayName=c;const m=e+"CollectionItemSlot",u="data-radix-collection-item",p=$c(m),h=y.forwardRef((g,f)=>{const{scope:w,children:j,...b}=g,v=y.useRef(null),k=Ee(f,v),R=a(m,w);return y.useEffect(()=>(R.itemMap.set(v,{ref:v,...b}),()=>void R.itemMap.delete(v))),n.jsx(p,{[u]:"",ref:k,children:j})});h.displayName=m;function _(g){const f=a(e+"CollectionConsumer",g);return y.useCallback(()=>{const j=f.collectionRef.current;if(!j)return[];const b=Array.from(j.querySelectorAll(`[${u}]`));return Array.from(f.itemMap.values()).sort((R,N)=>b.indexOf(R.ref.current)-b.indexOf(N.ref.current))},[f.collectionRef,f.itemMap])}return[{Provider:i,Slot:d,ItemSlot:h},_,s]}var rw=x.createContext(void 0);function Fs(e){const t=x.useContext(rw);return e||t||"ltr"}function sw(e){const t=ow(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(iw);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 ow(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=lw(o),c=cw(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 aw=Symbol("radix.slottable");function iw(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===aw}function cw(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 lw(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 dw=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],be=dw.reduce((e,t)=>{const r=sw(`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 uw(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function mn(e){const t=x.useRef(e);return x.useEffect(()=>{t.current=e}),x.useMemo(()=>(...r)=>t.current?.(...r),[])}function mw(e,t=globalThis?.document){const r=mn(e);x.useEffect(()=>{const s=o=>{o.key==="Escape"&&r(o)};return t.addEventListener("keydown",s,{capture:!0}),()=>t.removeEventListener("keydown",s,{capture:!0})},[r,t])}var pw="DismissableLayer",oa="dismissableLayer.update",fw="dismissableLayer.pointerDownOutside",hw="dismissableLayer.focusOutside",zc,uu=x.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ka=x.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:i,onDismiss:c,...l}=e,d=x.useContext(uu),[m,u]=x.useState(null),p=m?.ownerDocument??globalThis?.document,[,h]=x.useState({}),_=Ee(t,N=>u(N)),g=Array.from(d.layers),[f]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),w=g.indexOf(f),j=m?g.indexOf(m):-1,b=d.layersWithOutsidePointerEventsDisabled.size>0,v=j>=w,k=yw(N=>{const C=N.target,T=[...d.branches].some(O=>O.contains(C));!v||T||(o?.(N),i?.(N),N.defaultPrevented||c?.())},p),R=vw(N=>{const C=N.target;[...d.branches].some(O=>O.contains(C))||(a?.(N),i?.(N),N.defaultPrevented||c?.())},p);return mw(N=>{j===d.layers.size-1&&(s?.(N),!N.defaultPrevented&&c&&(N.preventDefault(),c()))},p),x.useEffect(()=>{if(m)return r&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(zc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(m)),d.layers.add(m),Fc(),()=>{r&&d.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=zc)}},[m,p,r,d]),x.useEffect(()=>()=>{m&&(d.layers.delete(m),d.layersWithOutsidePointerEventsDisabled.delete(m),Fc())},[m,d]),x.useEffect(()=>{const N=()=>h({});return document.addEventListener(oa,N),()=>document.removeEventListener(oa,N)},[]),n.jsx(be.div,{...l,ref:_,style:{pointerEvents:b?v?"auto":"none":void 0,...e.style},onFocusCapture:_e(e.onFocusCapture,R.onFocusCapture),onBlurCapture:_e(e.onBlurCapture,R.onBlurCapture),onPointerDownCapture:_e(e.onPointerDownCapture,k.onPointerDownCapture)})});Ka.displayName=pw;var gw="DismissableLayerBranch",xw=x.forwardRef((e,t)=>{const r=x.useContext(uu),s=x.useRef(null),o=Ee(t,s);return x.useEffect(()=>{const a=s.current;if(a)return r.branches.add(a),()=>{r.branches.delete(a)}},[r.branches]),n.jsx(be.div,{...e,ref:o})});xw.displayName=gw;function yw(e,t=globalThis?.document){const r=mn(e),s=x.useRef(!1),o=x.useRef(()=>{});return x.useEffect(()=>{const a=c=>{if(c.target&&!s.current){let l=function(){mu(fw,r,d,{discrete:!0})};const d={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);s.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",a)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",a),t.removeEventListener("click",o.current)}},[t,r]),{onPointerDownCapture:()=>s.current=!0}}function vw(e,t=globalThis?.document){const r=mn(e),s=x.useRef(!1);return x.useEffect(()=>{const o=a=>{a.target&&!s.current&&mu(hw,r,{originalEvent:a},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,r]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function Fc(){const e=new CustomEvent(oa);document.dispatchEvent(e)}function mu(e,t,r,{discrete:s}){const o=r.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&o.addEventListener(e,t,{once:!0}),s?uw(o,a):o.dispatchEvent(a)}var Io=0;function pu(){x.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Bc()),document.body.insertAdjacentElement("beforeend",e[1]??Bc()),Io++,()=>{Io===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Io--}},[])}function Bc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Ro="focusScope.autoFocusOnMount",Oo="focusScope.autoFocusOnUnmount",Uc={bubbles:!1,cancelable:!0},bw="FocusScope",Xa=x.forwardRef((e,t)=>{const{loop:r=!1,trapped:s=!1,onMountAutoFocus:o,onUnmountAutoFocus:a,...i}=e,[c,l]=x.useState(null),d=mn(o),m=mn(a),u=x.useRef(null),p=Ee(t,g=>l(g)),h=x.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;x.useEffect(()=>{if(s){let g=function(b){if(h.paused||!c)return;const v=b.target;c.contains(v)?u.current=v:cn(u.current,{select:!0})},f=function(b){if(h.paused||!c)return;const v=b.relatedTarget;v!==null&&(c.contains(v)||cn(u.current,{select:!0}))},w=function(b){if(document.activeElement===document.body)for(const k of b)k.removedNodes.length>0&&cn(c)};document.addEventListener("focusin",g),document.addEventListener("focusout",f);const j=new MutationObserver(w);return c&&j.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",f),j.disconnect()}}},[s,c,h.paused]),x.useEffect(()=>{if(c){Vc.add(h);const g=document.activeElement;if(!c.contains(g)){const w=new CustomEvent(Ro,Uc);c.addEventListener(Ro,d),c.dispatchEvent(w),w.defaultPrevented||(ww(Cw(fu(c)),{select:!0}),document.activeElement===g&&cn(c))}return()=>{c.removeEventListener(Ro,d),setTimeout(()=>{const w=new CustomEvent(Oo,Uc);c.addEventListener(Oo,m),c.dispatchEvent(w),w.defaultPrevented||cn(g??document.body,{select:!0}),c.removeEventListener(Oo,m),Vc.remove(h)},0)}}},[c,d,m,h]);const _=x.useCallback(g=>{if(!r&&!s||h.paused)return;const f=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,w=document.activeElement;if(f&&w){const j=g.currentTarget,[b,v]=_w(j);b&&v?!g.shiftKey&&w===v?(g.preventDefault(),r&&cn(b,{select:!0})):g.shiftKey&&w===b&&(g.preventDefault(),r&&cn(v,{select:!0})):w===j&&g.preventDefault()}},[r,s,h.paused]);return n.jsx(be.div,{tabIndex:-1,...i,ref:p,onKeyDown:_})});Xa.displayName=bw;function ww(e,{select:t=!1}={}){const r=document.activeElement;for(const s of e)if(cn(s,{select:t}),document.activeElement!==r)return}function _w(e){const t=fu(e),r=Wc(t,e),s=Wc(t.reverse(),e);return[r,s]}function fu(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const o=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||o?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function Wc(e,t){for(const r of e)if(!jw(r,{upTo:t}))return r}function jw(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 kw(e){return e instanceof HTMLInputElement&&"select"in e}function cn(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&kw(e)&&t&&e.select()}}var Vc=Sw();function Sw(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=qc(e,t),e.unshift(t)},remove(t){e=qc(e,t),e[0]?.resume()}}}function qc(e,t){const r=[...e],s=r.indexOf(t);return s!==-1&&r.splice(s,1),r}function Cw(e){return e.filter(t=>t.tagName!=="A")}var Xe=globalThis?.document?x.useLayoutEffect:()=>{},Nw=x[" useId ".trim().toString()]||(()=>{}),Pw=0;function qt(e){const[t,r]=x.useState(Nw());return Xe(()=>{r(s=>s??String(Pw++))},[e]),t?`radix-${t}`:""}const Aw=["top","right","bottom","left"],pn=Math.min,wt=Math.max,_s=Math.round,Xr=Math.floor,Ht=e=>({x:e,y:e}),Ew={left:"right",right:"left",bottom:"top",top:"bottom"},Tw={start:"end",end:"start"};function aa(e,t,r){return wt(e,pn(t,r))}function rn(e,t){return typeof e=="function"?e(t):e}function sn(e){return e.split("-")[0]}function lr(e){return e.split("-")[1]}function Ja(e){return e==="x"?"y":"x"}function ei(e){return e==="y"?"height":"width"}const Iw=new Set(["top","bottom"]);function Vt(e){return Iw.has(sn(e))?"y":"x"}function ti(e){return Ja(Vt(e))}function Rw(e,t,r){r===void 0&&(r=!1);const s=lr(e),o=ti(e),a=ei(o);let i=o==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(i=js(i)),[i,js(i)]}function Ow(e){const t=js(e);return[ia(e),t,ia(t)]}function ia(e){return e.replace(/start|end/g,t=>Tw[t])}const Hc=["left","right"],Zc=["right","left"],Mw=["top","bottom"],Dw=["bottom","top"];function Lw(e,t,r){switch(e){case"top":case"bottom":return r?t?Zc:Hc:t?Hc:Zc;case"left":case"right":return t?Mw:Dw;default:return[]}}function $w(e,t,r,s){const o=lr(e);let a=Lw(sn(e),r==="start",s);return o&&(a=a.map(i=>i+"-"+o),t&&(a=a.concat(a.map(ia)))),a}function js(e){return e.replace(/left|right|bottom|top/g,t=>Ew[t])}function zw(e){return{top:0,right:0,bottom:0,left:0,...e}}function hu(e){return typeof e!="number"?zw(e):{top:e,right:e,bottom:e,left:e}}function ks(e){const{x:t,y:r,width:s,height:o}=e;return{width:s,height:o,top:r,left:t,right:t+s,bottom:r+o,x:t,y:r}}function Gc(e,t,r){let{reference:s,floating:o}=e;const a=Vt(t),i=ti(t),c=ei(i),l=sn(t),d=a==="y",m=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[c]/2-o[c]/2;let h;switch(l){case"top":h={x:m,y:s.y-o.height};break;case"bottom":h={x:m,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(lr(t)){case"start":h[i]-=p*(r&&d?-1:1);break;case"end":h[i]+=p*(r&&d?-1:1);break}return h}const Fw=async(e,t,r)=>{const{placement:s="bottom",strategy:o="absolute",middleware:a=[],platform:i}=r,c=a.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let d=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:u}=Gc(d,s,l),p=s,h={},_=0;for(let g=0;g<c.length;g++){const{name:f,fn:w}=c[g],{x:j,y:b,data:v,reset:k}=await w({x:m,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:h,rects:d,platform:i,elements:{reference:e,floating:t}});m=j??m,u=b??u,h={...h,[f]:{...h[f],...v}},k&&_<=50&&(_++,typeof k=="object"&&(k.placement&&(p=k.placement),k.rects&&(d=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:m,y:u}=Gc(d,p,l)),g=-1)}return{x:m,y:u,placement:p,strategy:o,middlewareData:h}};async function Ir(e,t){var r;t===void 0&&(t={});const{x:s,y:o,platform:a,rects:i,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:m="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=rn(t,e),_=hu(h),f=c[p?u==="floating"?"reference":"floating":u],w=ks(await a.getClippingRect({element:(r=await(a.isElement==null?void 0:a.isElement(f)))==null||r?f:f.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(c.floating)),boundary:d,rootBoundary:m,strategy:l})),j=u==="floating"?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,b=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),v=await(a.isElement==null?void 0:a.isElement(b))?await(a.getScale==null?void 0:a.getScale(b))||{x:1,y:1}:{x:1,y:1},k=ks(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:j,offsetParent:b,strategy:l}):j);return{top:(w.top-k.top+_.top)/v.y,bottom:(k.bottom-w.bottom+_.bottom)/v.y,left:(w.left-k.left+_.left)/v.x,right:(k.right-w.right+_.right)/v.x}}const Bw=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:s,placement:o,rects:a,platform:i,elements:c,middlewareData:l}=t,{element:d,padding:m=0}=rn(e,t)||{};if(d==null)return{};const u=hu(m),p={x:r,y:s},h=ti(o),_=ei(h),g=await i.getDimensions(d),f=h==="y",w=f?"top":"left",j=f?"bottom":"right",b=f?"clientHeight":"clientWidth",v=a.reference[_]+a.reference[h]-p[h]-a.floating[_],k=p[h]-a.reference[h],R=await(i.getOffsetParent==null?void 0:i.getOffsetParent(d));let N=R?R[b]:0;(!N||!await(i.isElement==null?void 0:i.isElement(R)))&&(N=c.floating[b]||a.floating[_]);const C=v/2-k/2,T=N/2-g[_]/2-1,O=pn(u[w],T),$=pn(u[j],T),S=O,A=N-g[_]-$,I=N/2-g[_]/2+C,B=aa(S,I,A),D=!l.arrow&&lr(o)!=null&&I!==B&&a.reference[_]/2-(I<S?O:$)-g[_]/2<0,E=D?I<S?I-S:I-A:0;return{[h]:p[h]+E,data:{[h]:B,centerOffset:I-B-E,...D&&{alignmentOffset:E}},reset:D}}}),Uw=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var r,s;const{placement:o,middlewareData:a,rects:i,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:m=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:_="none",flipAlignment:g=!0,...f}=rn(e,t);if((r=a.arrow)!=null&&r.alignmentOffset)return{};const w=sn(o),j=Vt(c),b=sn(c)===c,v=await(l.isRTL==null?void 0:l.isRTL(d.floating)),k=p||(b||!g?[js(c)]:Ow(c)),R=_!=="none";!p&&R&&k.push(...$w(c,g,_,v));const N=[c,...k],C=await Ir(t,f),T=[];let O=((s=a.flip)==null?void 0:s.overflows)||[];if(m&&T.push(C[w]),u){const I=Rw(o,i,v);T.push(C[I[0]],C[I[1]])}if(O=[...O,{placement:o,overflows:T}],!T.every(I=>I<=0)){var $,S;const I=((($=a.flip)==null?void 0:$.index)||0)+1,B=N[I];if(B&&(!(u==="alignment"?j!==Vt(B):!1)||O.every(P=>Vt(P.placement)===j?P.overflows[0]>0:!0)))return{data:{index:I,overflows:O},reset:{placement:B}};let D=(S=O.filter(E=>E.overflows[0]<=0).sort((E,P)=>E.overflows[1]-P.overflows[1])[0])==null?void 0:S.placement;if(!D)switch(h){case"bestFit":{var A;const E=(A=O.filter(P=>{if(R){const z=Vt(P.placement);return z===j||z==="y"}return!0}).map(P=>[P.placement,P.overflows.filter(z=>z>0).reduce((z,Z)=>z+Z,0)]).sort((P,z)=>P[1]-z[1])[0])==null?void 0:A[0];E&&(D=E);break}case"initialPlacement":D=c;break}if(o!==D)return{reset:{placement:D}}}return{}}}};function Qc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Yc(e){return Aw.some(t=>e[t]>=0)}const Ww=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:s="referenceHidden",...o}=rn(e,t);switch(s){case"referenceHidden":{const a=await Ir(t,{...o,elementContext:"reference"}),i=Qc(a,r.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Yc(i)}}}case"escaped":{const a=await Ir(t,{...o,altBoundary:!0}),i=Qc(a,r.floating);return{data:{escapedOffsets:i,escaped:Yc(i)}}}default:return{}}}}},gu=new Set(["left","top"]);async function Vw(e,t){const{placement:r,platform:s,elements:o}=e,a=await(s.isRTL==null?void 0:s.isRTL(o.floating)),i=sn(r),c=lr(r),l=Vt(r)==="y",d=gu.has(i)?-1:1,m=a&&l?-1:1,u=rn(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:_}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return c&&typeof _=="number"&&(h=c==="end"?_*-1:_),l?{x:h*m,y:p*d}:{x:p*d,y:h*m}}const qw=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 Vw(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}}}}},Hw=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:s,placement:o}=t,{mainAxis:a=!0,crossAxis:i=!1,limiter:c={fn:f=>{let{x:w,y:j}=f;return{x:w,y:j}}},...l}=rn(e,t),d={x:r,y:s},m=await Ir(t,l),u=Vt(sn(o)),p=Ja(u);let h=d[p],_=d[u];if(a){const f=p==="y"?"top":"left",w=p==="y"?"bottom":"right",j=h+m[f],b=h-m[w];h=aa(j,h,b)}if(i){const f=u==="y"?"top":"left",w=u==="y"?"bottom":"right",j=_+m[f],b=_-m[w];_=aa(j,_,b)}const g=c.fn({...t,[p]:h,[u]:_});return{...g,data:{x:g.x-r,y:g.y-s,enabled:{[p]:a,[u]:i}}}}}},Zw=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:r,y:s,placement:o,rects:a,middlewareData:i}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=rn(e,t),m={x:r,y:s},u=Vt(o),p=Ja(u);let h=m[p],_=m[u];const g=rn(c,t),f=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const b=p==="y"?"height":"width",v=a.reference[p]-a.floating[b]+f.mainAxis,k=a.reference[p]+a.reference[b]-f.mainAxis;h<v?h=v:h>k&&(h=k)}if(d){var w,j;const b=p==="y"?"width":"height",v=gu.has(sn(o)),k=a.reference[u]-a.floating[b]+(v&&((w=i.offset)==null?void 0:w[u])||0)+(v?0:f.crossAxis),R=a.reference[u]+a.reference[b]+(v?0:((j=i.offset)==null?void 0:j[u])||0)-(v?f.crossAxis:0);_<k?_=k:_>R&&(_=R)}return{[p]:h,[u]:_}}}},Gw=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var r,s;const{placement:o,rects:a,platform:i,elements:c}=t,{apply:l=()=>{},...d}=rn(e,t),m=await Ir(t,d),u=sn(o),p=lr(o),h=Vt(o)==="y",{width:_,height:g}=a.floating;let f,w;u==="top"||u==="bottom"?(f=u,w=p===(await(i.isRTL==null?void 0:i.isRTL(c.floating))?"start":"end")?"left":"right"):(w=u,f=p==="end"?"top":"bottom");const j=g-m.top-m.bottom,b=_-m.left-m.right,v=pn(g-m[f],j),k=pn(_-m[w],b),R=!t.middlewareData.shift;let N=v,C=k;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(C=b),(s=t.middlewareData.shift)!=null&&s.enabled.y&&(N=j),R&&!p){const O=wt(m.left,0),$=wt(m.right,0),S=wt(m.top,0),A=wt(m.bottom,0);h?C=_-2*(O!==0||$!==0?O+$:wt(m.left,m.right)):N=g-2*(S!==0||A!==0?S+A:wt(m.top,m.bottom))}await l({...t,availableWidth:C,availableHeight:N});const T=await i.getDimensions(c.floating);return _!==T.width||g!==T.height?{reset:{rects:!0}}:{}}}};function Bs(){return typeof window<"u"}function dr(e){return xu(e)?(e.nodeName||"").toLowerCase():"#document"}function _t(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Kt(e){var t;return(t=(xu(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function xu(e){return Bs()?e instanceof Node||e instanceof _t(e).Node:!1}function Ot(e){return Bs()?e instanceof Element||e instanceof _t(e).Element:!1}function Qt(e){return Bs()?e instanceof HTMLElement||e instanceof _t(e).HTMLElement:!1}function Kc(e){return!Bs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof _t(e).ShadowRoot}const Qw=new Set(["inline","contents"]);function zr(e){const{overflow:t,overflowX:r,overflowY:s,display:o}=Mt(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+r)&&!Qw.has(o)}const Yw=new Set(["table","td","th"]);function Kw(e){return Yw.has(dr(e))}const Xw=[":popover-open",":modal"];function Us(e){return Xw.some(t=>{try{return e.matches(t)}catch{return!1}})}const Jw=["transform","translate","scale","rotate","perspective"],e_=["transform","translate","scale","rotate","perspective","filter"],t_=["paint","layout","strict","content"];function ni(e){const t=ri(),r=Ot(e)?Mt(e):e;return Jw.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)||e_.some(s=>(r.willChange||"").includes(s))||t_.some(s=>(r.contain||"").includes(s))}function n_(e){let t=fn(e);for(;Qt(t)&&!er(t);){if(ni(t))return t;if(Us(t))return null;t=fn(t)}return null}function ri(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const r_=new Set(["html","body","#document"]);function er(e){return r_.has(dr(e))}function Mt(e){return _t(e).getComputedStyle(e)}function Ws(e){return Ot(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function fn(e){if(dr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Kc(e)&&e.host||Kt(e);return Kc(t)?t.host:t}function yu(e){const t=fn(e);return er(t)?e.ownerDocument?e.ownerDocument.body:e.body:Qt(t)&&zr(t)?t:yu(t)}function Rr(e,t,r){var s;t===void 0&&(t=[]),r===void 0&&(r=!0);const o=yu(e),a=o===((s=e.ownerDocument)==null?void 0:s.body),i=_t(o);if(a){const c=ca(i);return t.concat(i,i.visualViewport||[],zr(o)?o:[],c&&r?Rr(c):[])}return t.concat(o,Rr(o,[],r))}function ca(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function vu(e){const t=Mt(e);let r=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Qt(e),a=o?e.offsetWidth:r,i=o?e.offsetHeight:s,c=_s(r)!==a||_s(s)!==i;return c&&(r=a,s=i),{width:r,height:s,$:c}}function si(e){return Ot(e)?e:e.contextElement}function Xn(e){const t=si(e);if(!Qt(t))return Ht(1);const r=t.getBoundingClientRect(),{width:s,height:o,$:a}=vu(t);let i=(a?_s(r.width):r.width)/s,c=(a?_s(r.height):r.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!c||!Number.isFinite(c))&&(c=1),{x:i,y:c}}const s_=Ht(0);function bu(e){const t=_t(e);return!ri()||!t.visualViewport?s_:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function o_(e,t,r){return t===void 0&&(t=!1),!r||t&&r!==_t(e)?!1:t}function Tn(e,t,r,s){t===void 0&&(t=!1),r===void 0&&(r=!1);const o=e.getBoundingClientRect(),a=si(e);let i=Ht(1);t&&(s?Ot(s)&&(i=Xn(s)):i=Xn(e));const c=o_(a,r,s)?bu(a):Ht(0);let l=(o.left+c.x)/i.x,d=(o.top+c.y)/i.y,m=o.width/i.x,u=o.height/i.y;if(a){const p=_t(a),h=s&&Ot(s)?_t(s):s;let _=p,g=ca(_);for(;g&&s&&h!==_;){const f=Xn(g),w=g.getBoundingClientRect(),j=Mt(g),b=w.left+(g.clientLeft+parseFloat(j.paddingLeft))*f.x,v=w.top+(g.clientTop+parseFloat(j.paddingTop))*f.y;l*=f.x,d*=f.y,m*=f.x,u*=f.y,l+=b,d+=v,_=_t(g),g=ca(_)}}return ks({width:m,height:u,x:l,y:d})}function Vs(e,t){const r=Ws(e).scrollLeft;return t?t.left+r:Tn(Kt(e)).left+r}function wu(e,t){const r=e.getBoundingClientRect(),s=r.left+t.scrollLeft-Vs(e,r),o=r.top+t.scrollTop;return{x:s,y:o}}function a_(e){let{elements:t,rect:r,offsetParent:s,strategy:o}=e;const a=o==="fixed",i=Kt(s),c=t?Us(t.floating):!1;if(s===i||c&&a)return r;let l={scrollLeft:0,scrollTop:0},d=Ht(1);const m=Ht(0),u=Qt(s);if((u||!u&&!a)&&((dr(s)!=="body"||zr(i))&&(l=Ws(s)),Qt(s))){const h=Tn(s);d=Xn(s),m.x=h.x+s.clientLeft,m.y=h.y+s.clientTop}const p=i&&!u&&!a?wu(i,l):Ht(0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-l.scrollLeft*d.x+m.x+p.x,y:r.y*d.y-l.scrollTop*d.y+m.y+p.y}}function i_(e){return Array.from(e.getClientRects())}function c_(e){const t=Kt(e),r=Ws(e),s=e.ownerDocument.body,o=wt(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),a=wt(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-r.scrollLeft+Vs(e);const c=-r.scrollTop;return Mt(s).direction==="rtl"&&(i+=wt(t.clientWidth,s.clientWidth)-o),{width:o,height:a,x:i,y:c}}const Xc=25;function l_(e,t){const r=_t(e),s=Kt(e),o=r.visualViewport;let a=s.clientWidth,i=s.clientHeight,c=0,l=0;if(o){a=o.width,i=o.height;const m=ri();(!m||m&&t==="fixed")&&(c=o.offsetLeft,l=o.offsetTop)}const d=Vs(s);if(d<=0){const m=s.ownerDocument,u=m.body,p=getComputedStyle(u),h=m.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,_=Math.abs(s.clientWidth-u.clientWidth-h);_<=Xc&&(a-=_)}else d<=Xc&&(a+=d);return{width:a,height:i,x:c,y:l}}const d_=new Set(["absolute","fixed"]);function u_(e,t){const r=Tn(e,!0,t==="fixed"),s=r.top+e.clientTop,o=r.left+e.clientLeft,a=Qt(e)?Xn(e):Ht(1),i=e.clientWidth*a.x,c=e.clientHeight*a.y,l=o*a.x,d=s*a.y;return{width:i,height:c,x:l,y:d}}function Jc(e,t,r){let s;if(t==="viewport")s=l_(e,r);else if(t==="document")s=c_(Kt(e));else if(Ot(t))s=u_(t,r);else{const o=bu(e);s={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ks(s)}function _u(e,t){const r=fn(e);return r===t||!Ot(r)||er(r)?!1:Mt(r).position==="fixed"||_u(r,t)}function m_(e,t){const r=t.get(e);if(r)return r;let s=Rr(e,[],!1).filter(c=>Ot(c)&&dr(c)!=="body"),o=null;const a=Mt(e).position==="fixed";let i=a?fn(e):e;for(;Ot(i)&&!er(i);){const c=Mt(i),l=ni(i);!l&&c.position==="fixed"&&(o=null),(a?!l&&!o:!l&&c.position==="static"&&!!o&&d_.has(o.position)||zr(i)&&!l&&_u(e,i))?s=s.filter(m=>m!==i):o=c,i=fn(i)}return t.set(e,s),s}function p_(e){let{element:t,boundary:r,rootBoundary:s,strategy:o}=e;const i=[...r==="clippingAncestors"?Us(t)?[]:m_(t,this._c):[].concat(r),s],c=i[0],l=i.reduce((d,m)=>{const u=Jc(t,m,o);return d.top=wt(u.top,d.top),d.right=pn(u.right,d.right),d.bottom=pn(u.bottom,d.bottom),d.left=wt(u.left,d.left),d},Jc(t,c,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function f_(e){const{width:t,height:r}=vu(e);return{width:t,height:r}}function h_(e,t,r){const s=Qt(t),o=Kt(t),a=r==="fixed",i=Tn(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=Ht(0);function d(){l.x=Vs(o)}if(s||!s&&!a)if((dr(t)!=="body"||zr(o))&&(c=Ws(t)),s){const h=Tn(t,!0,a,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&d();a&&!s&&o&&d();const m=o&&!s&&!a?wu(o,c):Ht(0),u=i.left+c.scrollLeft-l.x-m.x,p=i.top+c.scrollTop-l.y-m.y;return{x:u,y:p,width:i.width,height:i.height}}function Mo(e){return Mt(e).position==="static"}function el(e,t){if(!Qt(e)||Mt(e).position==="fixed")return null;if(t)return t(e);let r=e.offsetParent;return Kt(e)===r&&(r=r.ownerDocument.body),r}function ju(e,t){const r=_t(e);if(Us(e))return r;if(!Qt(e)){let o=fn(e);for(;o&&!er(o);){if(Ot(o)&&!Mo(o))return o;o=fn(o)}return r}let s=el(e,t);for(;s&&Kw(s)&&Mo(s);)s=el(s,t);return s&&er(s)&&Mo(s)&&!ni(s)?r:s||n_(e)||r}const g_=async function(e){const t=this.getOffsetParent||ju,r=this.getDimensions,s=await r(e.floating);return{reference:h_(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function x_(e){return Mt(e).direction==="rtl"}const y_={convertOffsetParentRelativeRectToViewportRelativeRect:a_,getDocumentElement:Kt,getClippingRect:p_,getOffsetParent:ju,getElementRects:g_,getClientRects:i_,getDimensions:f_,getScale:Xn,isElement:Ot,isRTL:x_};function ku(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function v_(e,t){let r=null,s;const o=Kt(e);function a(){var c;clearTimeout(s),(c=r)==null||c.disconnect(),r=null}function i(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:m,top:u,width:p,height:h}=d;if(c||t(),!p||!h)return;const _=Xr(u),g=Xr(o.clientWidth-(m+p)),f=Xr(o.clientHeight-(u+h)),w=Xr(m),b={rootMargin:-_+"px "+-g+"px "+-f+"px "+-w+"px",threshold:wt(0,pn(1,l))||1};let v=!0;function k(R){const N=R[0].intersectionRatio;if(N!==l){if(!v)return i();N?i(!1,N):s=setTimeout(()=>{i(!1,1e-7)},1e3)}N===1&&!ku(d,e.getBoundingClientRect())&&i(),v=!1}try{r=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{r=new IntersectionObserver(k,b)}r.observe(e)}return i(!0),a}function b_(e,t,r,s){s===void 0&&(s={});const{ancestorScroll:o=!0,ancestorResize:a=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=s,d=si(e),m=o||a?[...d?Rr(d):[],...Rr(t)]:[];m.forEach(w=>{o&&w.addEventListener("scroll",r,{passive:!0}),a&&w.addEventListener("resize",r)});const u=d&&c?v_(d,r):null;let p=-1,h=null;i&&(h=new ResizeObserver(w=>{let[j]=w;j&&j.target===d&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var b;(b=h)==null||b.observe(t)})),r()}),d&&!l&&h.observe(d),h.observe(t));let _,g=l?Tn(e):null;l&&f();function f(){const w=Tn(e);g&&!ku(g,w)&&r(),g=w,_=requestAnimationFrame(f)}return r(),()=>{var w;m.forEach(j=>{o&&j.removeEventListener("scroll",r),a&&j.removeEventListener("resize",r)}),u?.(),(w=h)==null||w.disconnect(),h=null,l&&cancelAnimationFrame(_)}}const w_=qw,__=Hw,j_=Uw,k_=Gw,S_=Ww,tl=Bw,C_=Zw,N_=(e,t,r)=>{const s=new Map,o={platform:y_,...r},a={...o.platform,_c:s};return Fw(e,t,{...o,platform:a})};var P_=typeof document<"u",A_=function(){},ls=P_?y.useLayoutEffect:A_;function Ss(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let r,s,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(s=r;s--!==0;)if(!Ss(e[s],t[s]))return!1;return!0}if(o=Object.keys(e),r=o.length,r!==Object.keys(t).length)return!1;for(s=r;s--!==0;)if(!{}.hasOwnProperty.call(t,o[s]))return!1;for(s=r;s--!==0;){const a=o[s];if(!(a==="_owner"&&e.$$typeof)&&!Ss(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function Su(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function nl(e,t){const r=Su(e);return Math.round(t*r)/r}function Do(e){const t=x.useRef(e);return ls(()=>{t.current=e}),t}function E_(e){e===void 0&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:s=[],platform:o,elements:{reference:a,floating:i}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[m,u]=x.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=x.useState(s);Ss(p,s)||h(s);const[_,g]=x.useState(null),[f,w]=x.useState(null),j=x.useCallback(P=>{P!==R.current&&(R.current=P,g(P))},[]),b=x.useCallback(P=>{P!==N.current&&(N.current=P,w(P))},[]),v=a||_,k=i||f,R=x.useRef(null),N=x.useRef(null),C=x.useRef(m),T=l!=null,O=Do(l),$=Do(o),S=Do(d),A=x.useCallback(()=>{if(!R.current||!N.current)return;const P={placement:t,strategy:r,middleware:p};$.current&&(P.platform=$.current),N_(R.current,N.current,P).then(z=>{const Z={...z,isPositioned:S.current!==!1};I.current&&!Ss(C.current,Z)&&(C.current=Z,Is.flushSync(()=>{u(Z)}))})},[p,t,r,$,S]);ls(()=>{d===!1&&C.current.isPositioned&&(C.current.isPositioned=!1,u(P=>({...P,isPositioned:!1})))},[d]);const I=x.useRef(!1);ls(()=>(I.current=!0,()=>{I.current=!1}),[]),ls(()=>{if(v&&(R.current=v),k&&(N.current=k),v&&k){if(O.current)return O.current(v,k,A);A()}},[v,k,A,O,T]);const B=x.useMemo(()=>({reference:R,floating:N,setReference:j,setFloating:b}),[j,b]),D=x.useMemo(()=>({reference:v,floating:k}),[v,k]),E=x.useMemo(()=>{const P={position:r,left:0,top:0};if(!D.floating)return P;const z=nl(D.floating,m.x),Z=nl(D.floating,m.y);return c?{...P,transform:"translate("+z+"px, "+Z+"px)",...Su(D.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:z,top:Z}},[r,c,D.floating,m.x,m.y]);return x.useMemo(()=>({...m,update:A,refs:B,elements:D,floatingStyles:E}),[m,A,B,D,E])}const T_=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):{}}}},I_=(e,t)=>({...w_(e),options:[e,t]}),R_=(e,t)=>({...__(e),options:[e,t]}),O_=(e,t)=>({...C_(e),options:[e,t]}),M_=(e,t)=>({...j_(e),options:[e,t]}),D_=(e,t)=>({...k_(e),options:[e,t]}),L_=(e,t)=>({...S_(e),options:[e,t]}),$_=(e,t)=>({...T_(e),options:[e,t]});var z_="Arrow",Cu=x.forwardRef((e,t)=>{const{children:r,width:s=10,height:o=5,...a}=e;return n.jsx(be.svg,{...a,ref:t,width:s,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:n.jsx("polygon",{points:"0,0 30,0 15,10"})})});Cu.displayName=z_;var F_=Cu;function B_(e){const[t,r]=x.useState(void 0);return Xe(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const s=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const a=o[0];let i,c;if("borderBoxSize"in a){const l=a.borderBoxSize,d=Array.isArray(l)?l[0]:l;i=d.inlineSize,c=d.blockSize}else i=e.offsetWidth,c=e.offsetHeight;r({width:i,height:c})});return s.observe(e,{box:"border-box"}),()=>s.unobserve(e)}else r(void 0)},[e]),t}var oi="Popper",[Nu,Pu]=bn(oi),[U_,Au]=Nu(oi),Eu=e=>{const{__scopePopper:t,children:r}=e,[s,o]=x.useState(null);return n.jsx(U_,{scope:t,anchor:s,onAnchorChange:o,children:r})};Eu.displayName=oi;var Tu="PopperAnchor",Iu=x.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:s,...o}=e,a=Au(Tu,r),i=x.useRef(null),c=Ee(t,i),l=x.useRef(null);return x.useEffect(()=>{const d=l.current;l.current=s?.current||i.current,d!==l.current&&a.onAnchorChange(l.current)}),s?null:n.jsx(be.div,{...o,ref:c})});Iu.displayName=Tu;var ai="PopperContent",[W_,V_]=Nu(ai),Ru=x.forwardRef((e,t)=>{const{__scopePopper:r,side:s="bottom",sideOffset:o=0,align:a="center",alignOffset:i=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:m=0,sticky:u="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:_,...g}=e,f=Au(ai,r),[w,j]=x.useState(null),b=Ee(t,F=>j(F)),[v,k]=x.useState(null),R=B_(v),N=R?.width??0,C=R?.height??0,T=s+(a!=="center"?"-"+a:""),O=typeof m=="number"?m:{top:0,right:0,bottom:0,left:0,...m},$=Array.isArray(d)?d:[d],S=$.length>0,A={padding:O,boundary:$.filter(H_),altBoundary:S},{refs:I,floatingStyles:B,placement:D,isPositioned:E,middlewareData:P}=E_({strategy:"fixed",placement:T,whileElementsMounted:(...F)=>b_(...F,{animationFrame:h==="always"}),elements:{reference:f.anchor},middleware:[I_({mainAxis:o+C,alignmentAxis:i}),l&&R_({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?O_():void 0,...A}),l&&M_({...A}),D_({...A,apply:({elements:F,rects:ee,availableWidth:pe,availableHeight:q})=>{const{width:ne,height:le}=ee.reference,fe=F.floating.style;fe.setProperty("--radix-popper-available-width",`${pe}px`),fe.setProperty("--radix-popper-available-height",`${q}px`),fe.setProperty("--radix-popper-anchor-width",`${ne}px`),fe.setProperty("--radix-popper-anchor-height",`${le}px`)}}),v&&$_({element:v,padding:c}),Z_({arrowWidth:N,arrowHeight:C}),p&&L_({strategy:"referenceHidden",...A})]}),[z,Z]=Du(D),K=mn(_);Xe(()=>{E&&K?.()},[E,K]);const L=P.arrow?.x,W=P.arrow?.y,Y=P.arrow?.centerOffset!==0,[V,ce]=x.useState();return Xe(()=>{w&&ce(window.getComputedStyle(w).zIndex)},[w]),n.jsx("div",{ref:I.setFloating,"data-radix-popper-content-wrapper":"",style:{...B,transform:E?B.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:V,"--radix-popper-transform-origin":[P.transformOrigin?.x,P.transformOrigin?.y].join(" "),...P.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:n.jsx(W_,{scope:r,placedSide:z,onArrowChange:k,arrowX:L,arrowY:W,shouldHideArrow:Y,children:n.jsx(be.div,{"data-side":z,"data-align":Z,...g,ref:b,style:{...g.style,animation:E?void 0:"none"}})})})});Ru.displayName=ai;var Ou="PopperArrow",q_={top:"bottom",right:"left",bottom:"top",left:"right"},Mu=x.forwardRef(function(t,r){const{__scopePopper:s,...o}=t,a=V_(Ou,s),i=q_[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(F_,{...o,ref:r,style:{...o.style,display:"block"}})})});Mu.displayName=Ou;function H_(e){return e!==null}var Z_=e=>({name:"transformOrigin",options:e,fn(t){const{placement:r,rects:s,middlewareData:o}=t,i=o.arrow?.centerOffset!==0,c=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[d,m]=Du(r),u={start:"0%",center:"50%",end:"100%"}[m],p=(o.arrow?.x??0)+c/2,h=(o.arrow?.y??0)+l/2;let _="",g="";return d==="bottom"?(_=i?u:`${p}px`,g=`${-l}px`):d==="top"?(_=i?u:`${p}px`,g=`${s.floating.height+l}px`):d==="right"?(_=`${-l}px`,g=i?u:`${h}px`):d==="left"&&(_=`${s.floating.width+l}px`,g=i?u:`${h}px`),{data:{x:_,y:g}}}});function Du(e){const[t,r="center"]=e.split("-");return[t,r]}var G_=Eu,Q_=Iu,Y_=Ru,K_=Mu,X_="Portal",ii=x.forwardRef((e,t)=>{const{container:r,...s}=e,[o,a]=x.useState(!1);Xe(()=>a(!0),[]);const i=r||o&&globalThis?.document?.body;return i?ka.createPortal(n.jsx(be.div,{...s,ref:t}),i):null});ii.displayName=X_;function J_(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()]||Xe;function hn({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 Lu=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),lj="VisuallyHidden",dj=x.forwardRef((e,t)=>n.jsx(be.span,{...e,ref:t,style:{...Lu,...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,Jr=new WeakMap,es={},Lo=0,$u=function(e){return e&&(e.host||$u(e.parentNode))},mj=function(e,t){return t.map(function(r){if(e.contains(r))return r;var s=$u(r);return s&&e.contains(s)?s:(console.error("aria-hidden",r,"in not contained inside",e,". Doing nothing"),null)}).filter(function(r){return!!r})},pj=function(e,t,r,s){var o=mj(t,Array.isArray(e)?e:[e]);es[r]||(es[r]=new WeakMap);var a=es[r],i=[],c=new Set,l=new Set(o),d=function(u){!u||c.has(u)||(c.add(u),d(u.parentNode))};o.forEach(d);var m=function(u){!u||l.has(u)||Array.prototype.forEach.call(u.children,function(p){if(c.has(p))m(p);else try{var h=p.getAttribute(s),_=h!==null&&h!=="false",g=(Zn.get(p)||0)+1,f=(a.get(p)||0)+1;Zn.set(p,g),a.set(p,f),i.push(p),g===1&&_&&Jr.set(p,!0),f===1&&p.setAttribute(r,"true"),_||p.setAttribute(s,"true")}catch(w){console.error("aria-hidden: cannot operate on ",p,w)}})};return m(t),c.clear(),Lo++,function(){i.forEach(function(u){var p=Zn.get(u)-1,h=a.get(u)-1;Zn.set(u,p),a.set(u,h),p||(Jr.has(u)||u.removeAttribute(s),Jr.delete(u)),h||u.removeAttribute(r)}),Lo--,Lo||(Zn=new WeakMap,Zn=new WeakMap,Jr=new WeakMap,es={})}},zu=function(e,t,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(e)?e:[e]),o=uj(e);return o?(s.push.apply(s,Array.from(o.querySelectorAll("[aria-live], script"))),pj(s,o,r,"aria-hidden")):function(){return null}},Wt=function(){return Wt=Object.assign||function(t){for(var r,s=1,o=arguments.length;s<o;s++){r=arguments[s];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])}return t},Wt.apply(this,arguments)};function Fu(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,s=Object.getOwnPropertySymbols(e);o<s.length;o++)t.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(e,s[o])&&(r[s[o]]=e[s[o]]);return r}function 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 ds="right-scroll-bar-position",us="width-before-scroll-bar",hj="with-scroll-bars-hidden",gj="--removed-body-scroll-bar-size";function $o(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function xj(e,t){var r=y.useState(function(){return{value:e,callback:t,facade:{get current(){return r.value},set current(s){var o=r.value;o!==s&&(r.value=s,r.callback(s,o))}}}})[0];return r.callback=t,r.facade}var yj=typeof window<"u"?x.useLayoutEffect:x.useEffect,rl=new WeakMap;function vj(e,t){var r=xj(null,function(s){return e.forEach(function(o){return $o(o,s)})});return yj(function(){var s=rl.get(r);if(s){var o=new Set(s),a=new Set(e),i=r.current;o.forEach(function(c){a.has(c)||$o(c,null)}),a.forEach(function(c){o.has(c)||$o(c,i)})}rl.set(r,e)},[e]),r}function bj(e){return e}function wj(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 _j(e){e===void 0&&(e={});var t=wj(null);return t.options=Wt({async:!0,ssr:!1},e),t}var Bu=function(e){var t=e.sideCar,r=Fu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var s=t.read();if(!s)throw new Error("Sidecar medium not found");return x.createElement(s,Wt({},r))};Bu.isSideCarExport=!0;function jj(e,t){return e.useMedium(t),Bu}var Uu=_j(),zo=function(){},qs=x.forwardRef(function(e,t){var r=x.useRef(null),s=x.useState({onScrollCapture:zo,onWheelCapture:zo,onTouchMoveCapture:zo}),o=s[0],a=s[1],i=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,m=e.enabled,u=e.shards,p=e.sideCar,h=e.noRelative,_=e.noIsolation,g=e.inert,f=e.allowPinchZoom,w=e.as,j=w===void 0?"div":w,b=e.gapMode,v=Fu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=p,R=vj([r,t]),N=Wt(Wt({},v),o);return x.createElement(x.Fragment,null,m&&x.createElement(k,{sideCar:Uu,removeScrollBar:d,shards:u,noRelative:h,noIsolation:_,inert:g,setCallbacks:a,allowPinchZoom:!!f,lockRef:r,gapMode:b}),i?x.cloneElement(x.Children.only(c),Wt(Wt({},N),{ref:R})):x.createElement(j,Wt({},N,{className:l,ref:R}),c))});qs.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};qs.classNames={fullWidth:us,zeroRight:ds};var 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])}},Wu=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},Fo=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[Fo(r),Fo(s),Fo(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=Wu(),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(
|
|
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 Td(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i=>{const c=e.seen.get(i);if(c.ref===null)return;const l=c.def??c.schema,d={...l},m=c.ref;if(c.ref=null,m){s(m);const p=e.seen.get(m),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(h)):Object.assign(l,h),Object.assign(l,d),i._zod.parent===m)for(const g in l)g==="$ref"||g==="allOf"||g in d||delete l[g];if(h.$ref&&p.def)for(const g in l)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(l[g])===JSON.stringify(p.def[g])&&delete l[g]}const u=i._zod.parent;if(u&&u!==m){s(u);const p=e.seen.get(u);if(p?.schema.$ref&&(l.$ref=p.schema.$ref,p.def))for(const h in l)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(l[h])===JSON.stringify(p.def[h])&&delete l[h]}e.override({zodSchema:i,jsonSchema:l,path:c.path??[]})};for(const i of[...e.seen.entries()].reverse())s(i[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(i)}Object.assign(o,r.def??r.schema);const a=e.external?.defs??{};for(const i of e.seen.entries()){const c=i[1];c.def&&c.defId&&(a[c.defId]=c.def)}e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?o.$defs=a:o.definitions=a);try{const i=JSON.parse(JSON.stringify(o));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:bs(t,"input",e.processors),output:bs(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function st(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 st(s.element,r);if(s.type==="set")return st(s.valueType,r);if(s.type==="lazy")return st(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 st(s.innerType,r);if(s.type==="intersection")return st(s.left,r)||st(s.right,r);if(s.type==="record"||s.type==="map")return st(s.keyType,r)||st(s.valueType,r);if(s.type==="pipe")return st(s.in,r)||st(s.out,r);if(s.type==="object"){for(const o in s.shape)if(st(s.shape[o],r))return!0;return!1}if(s.type==="union"){for(const o of s.options)if(st(o,r))return!0;return!1}if(s.type==="tuple"){for(const o of s.items)if(st(o,r))return!0;return!!(s.rest&&st(s.rest,r))}return!1}const sv=(e,t={})=>r=>{const s=Ad({...r,processors:t});return Xe(e,s),Ed(s,e),Td(s,e)},bs=(e,t,r={})=>s=>{const{libraryOptions:o,target:a}=s??{},i=Ad({...o??{},target:a,io:t,processors:r});return Xe(e,i),Ed(i,e),Td(i,e)},ov={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},av=(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=ov[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}))])}},iv=(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)},cv=(e,t,r,s)=>{r.not={}},lv=(e,t,r,s)=>{},dv=(e,t,r,s)=>{const o=e._zod.def,a=ld(o.entries);a.every(i=>typeof i=="number")&&(r.type="number"),a.every(i=>typeof i=="string")&&(r.type="string"),r.enum=a},uv=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},mv=(e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},pv=(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=Xe(a.element,t,{...s,path:[...s.path,"items"]})},fv=(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]=Xe(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=Xe(a.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},hv=(e,t,r,s)=>{const o=e._zod.def,a=o.inclusive===!1,i=o.options.map((c,l)=>Xe(c,t,{...s,path:[...s.path,a?"oneOf":"anyOf",l]}));a?r.oneOf=i:r.anyOf=i},gv=(e,t,r,s)=>{const o=e._zod.def,a=Xe(o.left,t,{...s,path:[...s.path,"allOf",0]}),i=Xe(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},xv=(e,t,r,s)=>{const o=e._zod.def,a=Xe(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"}]},yv=(e,t,r,s)=>{const o=e._zod.def;Xe(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},vv=(e,t,r,s)=>{const o=e._zod.def;Xe(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},bv=(e,t,r,s)=>{const o=e._zod.def;Xe(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)))},wv=(e,t,r,s)=>{const o=e._zod.def;Xe(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},_v=(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;Xe(a,t,s);const i=t.seen.get(e);i.ref=a},jv=(e,t,r,s)=>{const o=e._zod.def;Xe(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType,r.readOnly=!0},Id=(e,t,r,s)=>{const o=e._zod.def;Xe(o.innerType,t,s);const a=t.seen.get(e);a.ref=o.innerType},kv=G("ZodISODateTime",(e,t)=>{Ix.init(e,t),Me.init(e,t)});function Sv(e){return My(kv,e)}const Cv=G("ZodISODate",(e,t)=>{Rx.init(e,t),Me.init(e,t)});function Nv(e){return Ly(Cv,e)}const Pv=G("ZodISOTime",(e,t)=>{Ox.init(e,t),Me.init(e,t)});function Av(e){return Dy(Pv,e)}const Ev=G("ZodISODuration",(e,t)=>{Mx.init(e,t),Me.init(e,t)});function Tv(e){return $y(Ev,e)}const Iv=(e,t)=>{fd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Sg(e,r)},flatten:{value:r=>kg(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,ta,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,ta,2)}},isEmpty:{get(){return e.issues.length===0}}})},Pt=G("ZodError",Iv,{Parent:Error}),Rv=Fa(Pt),Ov=Ba(Pt),Mv=Ls(Pt),Lv=Ds(Pt),Dv=Pg(Pt),$v=Ag(Pt),zv=Eg(Pt),Fv=Tg(Pt),Bv=Ig(Pt),Uv=Rg(Pt),Wv=Og(Pt),Vv=Mg(Pt),Ve=G("ZodType",(e,t)=>(We.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:bs(e,"input"),output:bs(e,"output")}}),e.toJSONSchema=sv(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(vn(t,{checks:[...t.checks??[],...r.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0}),e.with=e.check,e.clone=(r,s)=>bn(e,r,s),e.brand=()=>e,e.register=((r,s)=>(r.add(e,s),e)),e.parse=(r,s)=>Rv(e,r,s,{callee:e.parse}),e.safeParse=(r,s)=>Mv(e,r,s),e.parseAsync=async(r,s)=>Ov(e,r,s,{callee:e.parseAsync}),e.safeParseAsync=async(r,s)=>Lv(e,r,s),e.spa=e.safeParseAsync,e.encode=(r,s)=>Dv(e,r,s),e.decode=(r,s)=>$v(e,r,s),e.encodeAsync=async(r,s)=>zv(e,r,s),e.decodeAsync=async(r,s)=>Fv(e,r,s),e.safeEncode=(r,s)=>Bv(e,r,s),e.safeDecode=(r,s)=>Uv(e,r,s),e.safeEncodeAsync=async(r,s)=>Wv(e,r,s),e.safeDecodeAsync=async(r,s)=>Vv(e,r,s),e.refine=(r,s)=>e.check($b(r,s)),e.superRefine=r=>e.check(zb(r)),e.overwrite=r=>e.check(or(r)),e.optional=()=>Sc(e),e.exactOptional=()=>Sb(e),e.nullable=()=>Cc(e),e.nullish=()=>Sc(Cc(e)),e.nonoptional=r=>Tb(e,r),e.array=()=>hb(e),e.or=r=>yb([e,r]),e.and=r=>bb(e,r),e.transform=r=>Nc(e,jb(r)),e.default=r=>Pb(e,r),e.prefault=r=>Eb(e,r),e.catch=r=>Rb(e,r),e.pipe=r=>Nc(e,r),e.readonly=()=>Lb(e),e.describe=r=>{const s=e.clone();return jr.add(s,{description:r}),s},Object.defineProperty(e,"description",{get(){return jr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return jr.get(e);const s=e.clone();return jr.add(s,r[0]),s},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),Rd=G("_ZodString",(e,t)=>{Ua.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(s,o,a)=>av(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(Wy(...s)),e.includes=(...s)=>e.check(Hy(...s)),e.startsWith=(...s)=>e.check(Zy(...s)),e.endsWith=(...s)=>e.check(Gy(...s)),e.min=(...s)=>e.check(vs(...s)),e.max=(...s)=>e.check(Nd(...s)),e.length=(...s)=>e.check(Pd(...s)),e.nonempty=(...s)=>e.check(vs(1,...s)),e.lowercase=s=>e.check(Vy(s)),e.uppercase=s=>e.check(qy(s)),e.trim=()=>e.check(Yy()),e.normalize=(...s)=>e.check(Qy(...s)),e.toLowerCase=()=>e.check(Ky()),e.toUpperCase=()=>e.check(Xy()),e.slugify=()=>e.check(Jy())}),qv=G("ZodString",(e,t)=>{Ua.init(e,t),Rd.init(e,t),e.email=r=>e.check(fy(Hv,r)),e.url=r=>e.check(vy(Zv,r)),e.jwt=r=>e.check(Oy(cb,r)),e.emoji=r=>e.check(by(Gv,r)),e.guid=r=>e.check(yc(_c,r)),e.uuid=r=>e.check(hy(Qr,r)),e.uuidv4=r=>e.check(gy(Qr,r)),e.uuidv6=r=>e.check(xy(Qr,r)),e.uuidv7=r=>e.check(yy(Qr,r)),e.nanoid=r=>e.check(wy(Qv,r)),e.guid=r=>e.check(yc(_c,r)),e.cuid=r=>e.check(_y(Yv,r)),e.cuid2=r=>e.check(jy(Kv,r)),e.ulid=r=>e.check(ky(Xv,r)),e.base64=r=>e.check(Ty(ob,r)),e.base64url=r=>e.check(Iy(ab,r)),e.xid=r=>e.check(Sy(Jv,r)),e.ksuid=r=>e.check(Cy(eb,r)),e.ipv4=r=>e.check(Ny(tb,r)),e.ipv6=r=>e.check(Py(nb,r)),e.cidrv4=r=>e.check(Ay(rb,r)),e.cidrv6=r=>e.check(Ey(sb,r)),e.e164=r=>e.check(Ry(ib,r)),e.datetime=r=>e.check(Sv(r)),e.date=r=>e.check(Nv(r)),e.time=r=>e.check(Av(r)),e.duration=r=>e.check(Tv(r))});function ot(e){return py(qv,e)}const Me=G("ZodStringFormat",(e,t)=>{Te.init(e,t),Rd.init(e,t)}),Hv=G("ZodEmail",(e,t)=>{jx.init(e,t),Me.init(e,t)}),_c=G("ZodGUID",(e,t)=>{wx.init(e,t),Me.init(e,t)}),Qr=G("ZodUUID",(e,t)=>{_x.init(e,t),Me.init(e,t)}),Zv=G("ZodURL",(e,t)=>{kx.init(e,t),Me.init(e,t)}),Gv=G("ZodEmoji",(e,t)=>{Sx.init(e,t),Me.init(e,t)}),Qv=G("ZodNanoID",(e,t)=>{Cx.init(e,t),Me.init(e,t)}),Yv=G("ZodCUID",(e,t)=>{Nx.init(e,t),Me.init(e,t)}),Kv=G("ZodCUID2",(e,t)=>{Px.init(e,t),Me.init(e,t)}),Xv=G("ZodULID",(e,t)=>{Ax.init(e,t),Me.init(e,t)}),Jv=G("ZodXID",(e,t)=>{Ex.init(e,t),Me.init(e,t)}),eb=G("ZodKSUID",(e,t)=>{Tx.init(e,t),Me.init(e,t)}),tb=G("ZodIPv4",(e,t)=>{Lx.init(e,t),Me.init(e,t)}),nb=G("ZodIPv6",(e,t)=>{Dx.init(e,t),Me.init(e,t)}),rb=G("ZodCIDRv4",(e,t)=>{$x.init(e,t),Me.init(e,t)}),sb=G("ZodCIDRv6",(e,t)=>{zx.init(e,t),Me.init(e,t)}),ob=G("ZodBase64",(e,t)=>{Fx.init(e,t),Me.init(e,t)}),ab=G("ZodBase64URL",(e,t)=>{Ux.init(e,t),Me.init(e,t)}),ib=G("ZodE164",(e,t)=>{Wx.init(e,t),Me.init(e,t)}),cb=G("ZodJWT",(e,t)=>{qx.init(e,t),Me.init(e,t)}),Od=G("ZodNumber",(e,t)=>{jd.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(s,o,a)=>iv(e,s,o),e.gt=(s,o)=>e.check(bc(s,o)),e.gte=(s,o)=>e.check(Ao(s,o)),e.min=(s,o)=>e.check(Ao(s,o)),e.lt=(s,o)=>e.check(vc(s,o)),e.lte=(s,o)=>e.check(Po(s,o)),e.max=(s,o)=>e.check(Po(s,o)),e.int=s=>e.check(jc(s)),e.safe=s=>e.check(jc(s)),e.positive=s=>e.check(bc(0,s)),e.nonnegative=s=>e.check(Ao(0,s)),e.negative=s=>e.check(vc(0,s)),e.nonpositive=s=>e.check(Po(0,s)),e.multipleOf=(s,o)=>e.check(wc(s,o)),e.step=(s,o)=>e.check(wc(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 lb(e){return zy(Od,e)}const db=G("ZodNumberFormat",(e,t)=>{Hx.init(e,t),Od.init(e,t)});function jc(e){return Fy(db,e)}const ub=G("ZodUnknown",(e,t)=>{Zx.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>lv()});function kc(){return By(ub)}const mb=G("ZodNever",(e,t)=>{Gx.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>cv(e,r,s)});function pb(e){return Uy(mb,e)}const fb=G("ZodArray",(e,t)=>{Qx.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>pv(e,r,s,o),e.element=t.element,e.min=(r,s)=>e.check(vs(r,s)),e.nonempty=r=>e.check(vs(1,r)),e.max=(r,s)=>e.check(Nd(r,s)),e.length=(r,s)=>e.check(Pd(r,s)),e.unwrap=()=>e.element});function hb(e,t){return ev(fb,e,t)}const gb=G("ZodObject",(e,t)=>{Kx.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>fv(e,r,s,o),Ce(e,"shape",()=>t.shape),e.keyof=()=>wb(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:kc()}),e.loose=()=>e.clone({...e._zod.def,catchall:kc()}),e.strict=()=>e.clone({...e._zod.def,catchall:pb()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>vg(e,r),e.safeExtend=r=>bg(e,r),e.merge=r=>wg(e,r),e.pick=r=>xg(e,r),e.omit=r=>yg(e,r),e.partial=(...r)=>_g(Ld,e,r[0]),e.required=(...r)=>jg(Dd,e,r[0])});function Md(e,t){const r={type:"object",shape:e??{},...me(t)};return new gb(r)}const xb=G("ZodUnion",(e,t)=>{Xx.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>hv(e,r,s,o),e.options=t.options});function yb(e,t){return new xb({type:"union",options:e,...me(t)})}const vb=G("ZodIntersection",(e,t)=>{Jx.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>gv(e,r,s,o)});function bb(e,t){return new vb({type:"intersection",left:e,right:t})}const ra=G("ZodEnum",(e,t)=>{ey.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(s,o,a)=>dv(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 ra({...t,checks:[],...me(o),entries:a})},e.exclude=(s,o)=>{const a={...t.entries};for(const i of s)if(r.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new ra({...t,checks:[],...me(o),entries:a})}});function wb(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new ra({type:"enum",entries:r,...me(t)})}const _b=G("ZodTransform",(e,t)=>{ty.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>mv(e,r),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new id(e.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(Er(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(Er(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(a=>(r.value=a,r)):(r.value=o,r)}});function jb(e){return new _b({type:"transform",transform:e})}const Ld=G("ZodOptional",(e,t)=>{Cd.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Id(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Sc(e){return new Ld({type:"optional",innerType:e})}const kb=G("ZodExactOptional",(e,t)=>{ny.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>Id(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Sb(e){return new kb({type:"optional",innerType:e})}const Cb=G("ZodNullable",(e,t)=>{ry.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>xv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Cc(e){return new Cb({type:"nullable",innerType:e})}const Nb=G("ZodDefault",(e,t)=>{sy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>vv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Pb(e,t){return new Nb({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():ud(t)}})}const Ab=G("ZodPrefault",(e,t)=>{oy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>bv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Eb(e,t){return new Ab({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():ud(t)}})}const Dd=G("ZodNonOptional",(e,t)=>{ay.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>yv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Tb(e,t){return new Dd({type:"nonoptional",innerType:e,...me(t)})}const Ib=G("ZodCatch",(e,t)=>{iy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>wv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rb(e,t){return new Ib({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Ob=G("ZodPipe",(e,t)=>{cy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>_v(e,r,s,o),e.in=t.in,e.out=t.out});function Nc(e,t){return new Ob({type:"pipe",in:e,out:t})}const Mb=G("ZodReadonly",(e,t)=>{ly.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>jv(e,r,s,o),e.unwrap=()=>e._zod.def.innerType});function Lb(e){return new Mb({type:"readonly",innerType:e})}const Db=G("ZodCustom",(e,t)=>{dy.init(e,t),Ve.init(e,t),e._zod.processJSONSchema=(r,s,o)=>uv(e,r)});function $b(e,t={}){return tv(Db,e,t)}function zb(e){return nv(e)}const Yr=Md({line1:ot().min(1,"Address line 1 is required"),line2:ot().optional(),city:ot().min(1,"City is required"),state:ot().optional(),postalCode:ot().min(1,"Postal code is required"),country:ot().min(2,"Country is required")});function Fb(e){return Md({email:e.requireEmail?ot().email("Valid email required"):ot().email("Valid email required").optional(),name:e.requireName?ot().min(1,"Name is required"):ot().optional(),phone:e.requirePhone?ot().min(6,"Phone is required"):ot().optional(),notes:ot().max(500).optional(),shippingAddress:e.requireShippingAddress?Yr:Yr.optional(),billingAddress:e.requireBillingAddress?Yr:Yr.optional(),discountCode:ot().optional(),tipAmount:lb().min(0).optional(),shippingMethodId:ot().optional()})}const Pc={none:0,optional:1,required:2};function Eo(e,t){return Pc[e]>=Pc[t]?e:t}function Bb(e){if(!e)return null;try{const t=JSON.parse(e);return!t||typeof t!="object"?null:t}catch{return null}}function ls(e,t){let r=!1,s=!1;const o=new Set;let a=t.requireEmail?"required":"none",i=t.defaultMode==="none"?"none":"optional",c=t.defaultMode==="full"?"optional":"none",l=t.allowShipping&&(t.defaultMode==="shipping"||t.defaultMode==="full"),d=t.defaultMode==="full";for(const u of e){u.metadata?.shippingProfile==="digital"?r=!0:s=!0;const h=Bb(u.metadata?.checkoutRequirements);h&&(h.email&&(a=Eo(a,h.email)),h.name&&(i=Eo(i,h.name)),h.phone&&(c=Eo(c,h.phone)),typeof h.shippingAddress=="boolean"&&(l=l||h.shippingAddress),typeof h.billingAddress=="boolean"&&(d=d||h.billingAddress));const _=u.metadata?.fulfillmentNotes;_&&o.add(_)}const m=r&&!s;return m&&(l=!1),{email:a,name:i,phone:c,shippingAddress:l,billingAddress:d,fulfillmentNotes:Array.from(o).join(" "),isDigitalOnly:m,hasPhysical:s}}const $d=y.createContext(null);function zd(){const{config:e}=Oe(),t=Dt(),r=y.useMemo(()=>({line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"}),[]),s=y.useMemo(()=>{const j=ls(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});return Fb({requireEmail:j.email==="required",requireName:j.name==="required",requirePhone:j.phone==="required",requireShippingAddress:j.shippingAddress,requireBillingAddress:j.billingAddress})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail]),[o,a]=y.useState(()=>({email:e.checkout.requireEmail??!0?"":void 0,name:"",phone:"",notes:"",shippingAddress:e.checkout.mode==="shipping"||e.checkout.mode==="full"?r:void 0,billingAddress:e.checkout.mode==="full"?r:void 0,discountCode:"",tipAmount:0,shippingMethodId:""}));y.useEffect(()=>{const j=ls(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1});a(b=>{const v={...b};return j.email==="required"&&!v.email&&(v.email=""),j.shippingAddress&&!v.shippingAddress&&(v.shippingAddress=r),j.billingAddress&&!v.billingAddress&&(v.billingAddress=r),j.shippingAddress||(v.shippingAddress=void 0),j.billingAddress||(v.billingAddress=void 0),v})},[t.items,e.checkout.allowShipping,e.checkout.mode,e.checkout.requireEmail,r]);const[i,c]=y.useState({}),[l,d]=y.useState("idle"),[m,u]=y.useState(null),[p,h]=y.useState(null),_=y.useCallback(()=>{c({}),d("idle"),u(null),h(null)},[]),g=y.useCallback((j,b)=>{a(v=>({...v,[j]:b}))},[]),f=y.useCallback(()=>{d("validating"),u(null);const j=s.safeParse(o);if(j.success)return c({}),d("idle"),{ok:!0,values:j.data};const b={};for(const v of j.error.issues)b[v.path.join(".")]=v.message;return c(b),d("error"),u("Please fix the highlighted fields."),{ok:!1}},[s,o]),w=y.useCallback(async j=>{const b=f();if(!b.ok)return{ok:!1};d("creating_session"),u(null),h(null);const v=t.items.map(C=>({resource:C.paymentResource??C.productId,quantity:C.qty,variantId:C.variantId})),k=ls(t.items,{requireEmail:e.checkout.requireEmail??!0,defaultMode:e.checkout.mode,allowShipping:e.checkout.allowShipping??!1}),R=new Set;if(k.shippingAddress)for(const C of t.items){const T=C.metadata?.shippingCountries;if(T)for(const O of T.split(",")){const $=O.trim().toUpperCase();$&&R.add($)}}const N={...R.size?{shippingCountries:Array.from(R).join(","),shipping_countries:Array.from(R).join(",")}:{}};try{const C=await e.adapter.createCheckoutSession({cart:v,customer:{email:b.values.email||void 0,name:b.values.name||void 0,phone:b.values.phone||void 0,notes:b.values.notes||void 0,shippingAddress:b.values.shippingAddress,billingAddress:b.values.billingAddress},options:{currency:e.currency,successUrl:e.checkout.successUrl,cancelUrl:e.checkout.cancelUrl,allowPromoCodes:e.checkout.allowPromoCodes,metadata:Object.keys(N).length?N:void 0,discountCode:(e.checkout.allowPromoCodes?b.values.discountCode||t.promoCode:void 0)||void 0,tipAmount:e.checkout.allowTipping&&b.values.tipAmount||void 0,shippingMethodId:e.checkout.allowShipping&&b.values.shippingMethodId||void 0,paymentMethodId:j?.paymentMethodId}});return C.kind==="redirect"?(h(C),d("redirecting"),typeof window<"u"&&window.location.assign(C.url),{ok:!0,session:C}):(h(C),d("success"),{ok:!0,session:C})}catch(C){return d("error"),u(C instanceof Error?C.message:"Checkout failed"),{ok:!1}}},[t.items,t.promoCode,e.adapter,e.checkout,e.currency,f]);return{values:o,setValues:a,setField:g,fieldErrors:i,status:l,error:m,session:p,reset:_,validate:f,createCheckoutSession:w}}function Fd({children:e}){const t=zd();return n.jsx($d.Provider,{value:t,children:e})}function zs(){const e=y.useContext($d);if(!e)throw new Error("useCheckout must be used within CheckoutProvider");return e}function Ub(){return zd()}function Wa(){const{config:e}=Oe(),[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 Fs(e){const{config:t}=Oe(),[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 Bd(e){const{config:t}=Oe(),[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 Ud(){const{config:e}=Oe(),[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 Wd(){const{config:e}=Oe(),[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 Vd({enabled:e,customer:t}){const{config:r}=Oe(),[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 hr(e,...t){for(const r of t){const s=e[r];if(s)return s}}function Va(e){const t=hr(e,"error","error_message","message");if(t)return{kind:"error",message:t};const r=hr(e,"canceled","cancelled","cancel","canceled_at");if(r&&r!=="0"&&r!=="false")return{kind:"cancel"};const s=hr(e,"orderId","order_id","demoOrderId"),o=hr(e,"session_id","checkout_session_id");if(s||o)return{kind:"success",orderId:s??o};const a=(hr(e,"status","checkout")??"").toLowerCase();return a==="success"?{kind:"success",orderId:s}:a==="cancel"||a==="canceled"?{kind:"cancel"}:a==="error"?{kind:"error"}:{kind:"idle"}}function Wb(e){const t={};return e.forEach((r,s)=>{t[s]=r}),t}function qa(){const{config:e}=Oe(),[t,r]=x.useState({kind:"idle"});return x.useEffect(()=>{if(typeof window>"u")return;const s=new URLSearchParams(window.location.search),o=Wb(s);(async()=>{try{const a=e.adapter.resolveCheckoutReturn?await e.adapter.resolveCheckoutReturn({query:o}):Va(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 sa(e){if(!e)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Vb(e){const t=e.get("tags"),r=t?t.split(",").map(c=>c.trim()).filter(Boolean):void 0,s=sa(e.get("min")),o=sa(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 qb(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 Ha({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=sa(t.get("page"))??1,a=Vb(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 Za(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")),qb(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 Ac(e,t){return`${e}::${t??""}`}function Hb(e,t){if(t&&e.variants?.length){const r=e.variants.find(s=>s.id===t);if(r)return{qty:r.inventoryQuantity,status:r.inventoryStatus}}return{qty:e.inventoryQuantity,status:e.inventoryStatus}}function Zb(e,t){const r={productId:e.productId,variantId:e.variantId,isOutOfStock:!1,exceedsAvailable:!1,isLowStock:!1};if(!t)return{...r,isOutOfStock:!0,message:"This product is no longer available"};const{qty:s,status:o}=Hb(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 Ga({items:e,refreshInterval:t=3e4,skip:r=!1}){const{config:s}=Oe(),[o,a]=x.useState(new Map),[i,c]=x.useState(!1),[l,d]=x.useState(null),m=x.useMemo(()=>{const _=new Set;for(const g of e)_.add(g.productId);return Array.from(_)},[e]),u=x.useCallback(async()=>{if(r||m.length===0){a(new Map);return}c(!0),d(null);try{const _=await Promise.all(m.map(async w=>{try{return await s.adapter.getProductBySlug(w)}catch{return null}})),g=new Map;for(const w of _)w&&(g.set(w.id,w),w.slug&&w.slug!==w.id&&g.set(w.slug,w));const f=new Map;for(const w of e){const j=Ac(w.productId,w.variantId),b=g.get(w.productId)??null;f.set(j,Zb(w,b))}a(f)}catch(_){d(_ instanceof Error?_.message:"Failed to check inventory")}finally{c(!1)}},[s.adapter,e,m,r]);x.useEffect(()=>{u()},[u]),x.useEffect(()=>{if(r||t<=0||m.length===0)return;const _=setInterval(u,t);return()=>clearInterval(_)},[u,m.length,t,r]);const p=x.useCallback((_,g)=>o.get(Ac(_,g)),[o]),h=x.useMemo(()=>{for(const _ of o.values())if(_.isOutOfStock||_.exceedsAvailable)return!0;return!1},[o]);return{inventory:o,isLoading:i,error:l,refresh:u,getItemInventory:p,hasIssues:h}}function Gb(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 Qb(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 Yb(e,t){const r=Qb(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}=Gb(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 qd({items:e}){const{config:t}=Oe(),[r,s]=x.useState(null),[o,a]=x.useState(!1),[i,c]=x.useState(null),l=x.useMemo(()=>{const u=new Set;for(const p of e)u.add(p.productId);return Array.from(u)},[e]),d=x.useCallback(async()=>{if(e.length===0){const u={ok:!0,issues:[],verifiedAt:new Date};return s(u),u}a(!0),c(null);try{const u=await Promise.all(l.map(async g=>{try{return await t.adapter.getProductBySlug(g)}catch{return null}})),p=new Map;for(const g of u)g&&(p.set(g.id,g),g.slug&&g.slug!==g.id&&p.set(g.slug,g));const h=[];for(const g of e){const f=p.get(g.productId)??null,w=Yb(g,f);w&&h.push(w)}const _={ok:h.length===0,issues:h,verifiedAt:new Date};return s(_),a(!1),_}catch(u){const p=u instanceof Error?u.message:"Failed to verify inventory";c(p),a(!1);const h={ok:!1,issues:[],verifiedAt:new Date};return s(h),h}},[t.adapter,e,l]),m=x.useCallback(()=>{s(null),c(null)},[]);return{result:r,isVerifying:o,error:i,verify:d,reset:m}}function Kb({items:e,onExpiry:t,enabled:r=!0}){const[s,o]=x.useState([]),[a,i]=x.useState([]),c=x.useRef(new Set),l=x.useMemo(()=>r?e.filter(d=>d.holdId&&d.holdExpiresAt):[],[e,r]);return x.useEffect(()=>{if(!r||l.length===0){o([]),i([]);return}const d=()=>{const u=Date.now(),p=120*1e3,h=[],_=[];for(const g of l){if(!g.holdExpiresAt)continue;const f=new Date(g.holdExpiresAt),w=f.getTime()-u,j=`${g.productId}::${g.variantId??""}`;w<=0?(h.push({productId:g.productId,variantId:g.variantId}),c.current.has(j)||(c.current.add(j),t?.({productId:g.productId,variantId:g.variantId,title:g.titleSnapshot,expiredAt:f}))):w<=p&&_.push({productId:g.productId,variantId:g.variantId,expiresAt:f,remainingMs:w})}o(h),i(_)};d();const m=setInterval(d,1e4);return()=>clearInterval(m)},[r,l,t]),x.useEffect(()=>{const d=new Set(l.map(m=>`${m.productId}::${m.variantId??""}`));for(const m of c.current)d.has(m)||c.current.delete(m)},[l]),{expiringItems:a,expiredItems:s}}const Ne={relatedProducts:{mode:"most_recent",maxItems:4,layout:{layout:"large",imageCrop:"center"}},catalog:{filters:{tags:!0,priceRange:!0,inStock:!0},sort:{featured:!0,priceAsc:!0,priceDesc:!0}},checkout:{promoCodes:!0},shopLayout:{layout:"large",imageCrop:"center"},categoryLayout:{layout:"large",imageCrop:"center"},sections:{showDescription:!0,showSpecs:!0,showShipping:!0,showRelatedProducts:!0},inventory:{preCheckoutVerification:!0,holdsEnabled:!1,holdDurationMinutes:15},shopPage:{title:"Shop",description:""}};function Xb(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 ar(e={}){const r=Ma()?.config?.adapter,[s,o]=y.useState(Ne),[a,i]=y.useState(!!r?.getStorefrontSettings);return y.useEffect(()=>{if(!r?.getStorefrontSettings){i(!1);return}let c=!1;async function l(){try{const d=await r.getStorefrontSettings();!c&&d&&o(Xb(d))}catch{}finally{c||i(!1)}}return l(),()=>{c=!0}},[r]),{settings:s,isLoading:a}}const Jb={card:!0,crypto:!0,credits:!1};function Hd(){const t=Ma()?.config?.adapter,[r,s]=y.useState(Jb),[o,a]=y.useState(!!t?.getPaymentMethodsConfig);return y.useEffect(()=>{if(!t?.getPaymentMethodsConfig){a(!1);return}let i=!1;async function c(){try{const l=await t.getPaymentMethodsConfig();!i&&l&&s(l)}catch{}finally{i||a(!1)}}return c(),()=>{i=!0}},[t]),{config:r,isLoading:o}}const Ec=new Map;function e0(e){return e.productId?`id:${e.productId}`:e.name?`name:${e.name}`:""}function Zd(e={}){const{productId:t,product:r,enabled:s=!0}=e,a=Ma()?.config?.adapter,[i,c]=y.useState(null),[l,d]=y.useState(null),[m,u]=y.useState(!1),[p,h]=y.useState(null),_=y.useRef(0),g=y.useCallback(async()=>{const f=t?{productId:t}:r?{name:r.name,description:r.description,tags:r.tags,categoryIds:r.categoryIds}:{};if(!f.productId&&!f.name)return;if(!a?.getAIRelatedProducts){h("AI recommendations not available");return}const w=e0(f),j=Ec.get(w);if(j){c(j.relatedProductIds),d(j.reasoning),h(null);return}const b=++_.current;u(!0),h(null);try{const v=await a.getAIRelatedProducts(f);b===_.current&&(c(v.relatedProductIds),d(v.reasoning),h(null),w&&Ec.set(w,v))}catch(v){if(b===_.current){const k=v instanceof Error?v.message:"Failed to get AI recommendations";h(k),c(null),d(null)}}finally{b===_.current&&u(!1)}},[a,t,r]);return y.useEffect(()=>{s&&(!t&&!r?.name||g())},[s,t,r?.name,g]),{relatedProductIds:i,reasoning:l,isLoading:m,error:p,refetch:g}}function Ie(e,t){if(!e)throw new Error(t)}function Tt(e){return typeof e=="string"&&e.trim().length>0}async function t0(e,t={}){const r=t.pageSize??10,s=await e.listCategories();Ie(Array.isArray(s),"listCategories() must return an array");for(const i of s)Ie(Tt(i.id),"Category.id is required"),Ie(Tt(i.slug),"Category.slug is required"),Ie(Tt(i.name),"Category.name is required");const o=await e.listProducts({page:1,pageSize:r});if(Ie(o&&Array.isArray(o.items),"listProducts() must return { items: Product[] }"),Ie(typeof o.page=="number","listProducts().page must be a number"),Ie(typeof o.pageSize=="number","listProducts().pageSize must be a number"),o.items.length>0){const i=o.items[0];Ie(Tt(i.id),"Product.id is required"),Ie(Tt(i.slug),"Product.slug is required"),Ie(Tt(i.title),"Product.title is required"),Ie(typeof i.description=="string","Product.description must be a string"),Ie(Array.isArray(i.images),"Product.images must be an array"),Ie(typeof i.price=="number","Product.price must be a number"),Ie(Tt(i.currency),"Product.currency is required"),Ie(Array.isArray(i.tags),"Product.tags must be an array"),Ie(Array.isArray(i.categoryIds),"Product.categoryIds must be an array");const c=await e.getProductBySlug(i.slug);Ie(c===null||Tt(c.id),"getProductBySlug() must return Product or null")}const a=await e.getOrderHistory();Ie(Array.isArray(a),"getOrderHistory() must return an array");for(const i of a)Ie(Tt(i.id),"Order.id is required"),Ie(Tt(i.createdAt),"Order.createdAt is required"),Ie(typeof i.total=="number","Order.total must be a number"),Ie(Tt(i.currency),"Order.currency is required"),Ie(Array.isArray(i.items),"Order.items must be an array")}function Tc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ir(...e){return t=>{let r=!1;const s=e.map(o=>{const a=Tc(o,t);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let o=0;o<s.length;o++){const a=s[o];typeof a=="function"?a():Tc(e[o],null)}}}}function Ee(...e){return x.useCallback(ir(...e),e)}var n0=Symbol.for("react.lazy"),ws=x[" use ".trim().toString()];function r0(e){return typeof e=="object"&&e!==null&&"then"in e}function Gd(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===n0&&"_payload"in e&&r0(e._payload)}function Qd(e){const t=o0(e),r=x.forwardRef((s,o)=>{let{children:a,...i}=s;Gd(a)&&typeof ws=="function"&&(a=ws(a._payload));const c=x.Children.toArray(a),l=c.find(i0);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 s0=Qd("Slot");function o0(e){const t=x.forwardRef((r,s)=>{let{children:o,...a}=r;if(Gd(o)&&typeof ws=="function"&&(o=ws(o._payload)),x.isValidElement(o)){const i=l0(o),c=c0(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ir(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 a0=Symbol("radix.slottable");function i0(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===a0}function c0(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 l0(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 Yd(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=Yd(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function Kd(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=Yd(e))&&(s&&(s+=" "),s+=t);return s}const Ic=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Rc=Kd,Qa=(e,t)=>r=>{var s;if(t?.variants==null)return Rc(e,r?.class,r?.className);const{variants:o,defaultVariants:a}=t,i=Object.keys(o).map(d=>{const m=r?.[d],u=a?.[d];if(m===null)return null;const p=Ic(m)||Ic(u);return o[d][p]}),c=r&&Object.entries(r).reduce((d,m)=>{let[u,p]=m;return p===void 0||(d[u]=p),d},{}),l=t==null||(s=t.compoundVariants)===null||s===void 0?void 0:s.reduce((d,m)=>{let{class:u,className:p,...h}=m;return Object.entries(h).every(_=>{let[g,f]=_;return Array.isArray(f)?f.includes({...a,...c}[g]):{...a,...c}[g]===f})?[...d,u,p]:d},[]);return Rc(e,i,l,r?.class,r?.className)},d0=(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},u0=(e,t)=>({classGroupId:e,validator:t}),Xd=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),_s="-",Oc=[],m0="arbitrary..",p0=e=>{const t=h0(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return f0(i);const c=i.split(_s),l=c[0]===""&&c.length>1?1:0;return Jd(c,l,t)},getConflictingClassGroupIds:(i,c)=>{if(c){const l=s[i],d=r[i];return l?d?d0(d,l):l:d||Oc}return r[i]||Oc}}},Jd=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],a=r.nextPart.get(o);if(a){const d=Jd(e,t+1,a);if(d)return d}const i=r.validators;if(i===null)return;const c=t===0?e.join(_s):e.slice(t).join(_s),l=i.length;for(let d=0;d<l;d++){const m=i[d];if(m.validator(c))return m.classGroupId}},f0=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?m0+s:void 0})(),h0=e=>{const{theme:t,classGroups:r}=e;return g0(r,t)},g0=(e,t)=>{const r=Xd();for(const s in e){const o=e[s];Ya(o,r,s,t)}return r},Ya=(e,t,r,s)=>{const o=e.length;for(let a=0;a<o;a++){const i=e[a];x0(i,t,r,s)}},x0=(e,t,r,s)=>{if(typeof e=="string"){y0(e,t,r);return}if(typeof e=="function"){v0(e,t,r,s);return}b0(e,t,r,s)},y0=(e,t,r)=>{const s=e===""?t:eu(t,e);s.classGroupId=r},v0=(e,t,r,s)=>{if(w0(e)){Ya(e(s),t,r,s);return}t.validators===null&&(t.validators=[]),t.validators.push(u0(r,e))},b0=(e,t,r,s)=>{const o=Object.entries(e),a=o.length;for(let i=0;i<a;i++){const[c,l]=o[i];Ya(l,eu(t,c),r,s)}},eu=(e,t)=>{let r=e;const s=t.split(_s),o=s.length;for(let a=0;a<o;a++){const i=s[a];let c=r.nextPart.get(i);c||(c=Xd(),r.nextPart.set(i,c)),r=c}return r},w0=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,_0=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)}}},oa="!",Mc=":",j0=[],Lc=(e,t,r,s,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),k0=e=>{const{prefix:t,experimentalParseClassName:r}=e;let s=o=>{const a=[];let i=0,c=0,l=0,d;const m=o.length;for(let g=0;g<m;g++){const f=o[g];if(i===0&&c===0){if(f===Mc){a.push(o.slice(l,g)),l=g+1;continue}if(f==="/"){d=g;continue}}f==="["?i++:f==="]"?i--:f==="("?c++:f===")"&&c--}const u=a.length===0?o:o.slice(l);let p=u,h=!1;u.endsWith(oa)?(p=u.slice(0,-1),h=!0):u.startsWith(oa)&&(p=u.slice(1),h=!0);const _=d&&d>l?d-l:void 0;return Lc(a,h,p,_)};if(t){const o=t+Mc,a=s;s=i=>i.startsWith(o)?a(i.slice(o.length)):Lc(j0,!1,i,void 0,!0)}if(r){const o=s;s=a=>r({className:a,parseClassName:o})}return s},S0=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}},C0=e=>({cache:_0(e.cacheSize),parseClassName:k0(e),sortModifiers:S0(e),...p0(e)}),N0=/\s+/,P0=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:a}=t,i=[],c=e.trim().split(N0);let l="";for(let d=c.length-1;d>=0;d-=1){const m=c[d],{isExternal:u,modifiers:p,hasImportantModifier:h,baseClassName:_,maybePostfixModifierPosition:g}=r(m);if(u){l=m+(l.length>0?" "+l:l);continue}let f=!!g,w=s(f?_.substring(0,g):_);if(!w){if(!f){l=m+(l.length>0?" "+l:l);continue}if(w=s(_),!w){l=m+(l.length>0?" "+l:l);continue}f=!1}const j=p.length===0?"":p.length===1?p[0]:a(p).join(":"),b=h?j+oa:j,v=b+w;if(i.indexOf(v)>-1)continue;i.push(v);const k=o(w,f);for(let R=0;R<k.length;++R){const N=k[R];i.push(b+N)}l=m+(l.length>0?" "+l:l)}return l},A0=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=tu(r))&&(o&&(o+=" "),o+=s);return o},tu=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=tu(e[s]))&&(r&&(r+=" "),r+=t);return r},E0=(e,...t)=>{let r,s,o,a;const i=l=>{const d=t.reduce((m,u)=>u(m),e());return r=C0(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=P0(l,r);return o(l,m),m};return a=i,(...l)=>a(A0(...l))},T0=[],Ge=e=>{const t=r=>r[e]||T0;return t.isThemeGetter=!0,t},nu=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,ru=/^\((?:(\w[\w-]*):)?(.+)\)$/i,I0=/^\d+\/\d+$/,R0=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,O0=/\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$/,M0=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,L0=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,D0=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Zn=e=>I0.test(e),ye=e=>!!e&&!Number.isNaN(Number(e)),cn=e=>!!e&&Number.isInteger(Number(e)),To=e=>e.endsWith("%")&&ye(e.slice(0,-1)),rn=e=>R0.test(e),$0=()=>!0,z0=e=>O0.test(e)&&!M0.test(e),su=()=>!1,F0=e=>L0.test(e),B0=e=>D0.test(e),U0=e=>!se(e)&&!oe(e),W0=e=>cr(e,iu,su),se=e=>nu.test(e),Nn=e=>cr(e,cu,z0),Io=e=>cr(e,G0,ye),Dc=e=>cr(e,ou,su),V0=e=>cr(e,au,B0),Kr=e=>cr(e,lu,F0),oe=e=>ru.test(e),gr=e=>lr(e,cu),q0=e=>lr(e,Q0),$c=e=>lr(e,ou),H0=e=>lr(e,iu),Z0=e=>lr(e,au),Xr=e=>lr(e,lu,!0),cr=(e,t,r)=>{const s=nu.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},lr=(e,t,r=!1)=>{const s=ru.exec(e);return s?s[1]?t(s[1]):r:!1},ou=e=>e==="position"||e==="percentage",au=e=>e==="image"||e==="url",iu=e=>e==="length"||e==="size"||e==="bg-size",cu=e=>e==="length",G0=e=>e==="number",Q0=e=>e==="family-name",lu=e=>e==="shadow",Y0=()=>{const e=Ge("color"),t=Ge("font"),r=Ge("text"),s=Ge("font-weight"),o=Ge("tracking"),a=Ge("leading"),i=Ge("breakpoint"),c=Ge("container"),l=Ge("spacing"),d=Ge("radius"),m=Ge("shadow"),u=Ge("inset-shadow"),p=Ge("text-shadow"),h=Ge("drop-shadow"),_=Ge("blur"),g=Ge("perspective"),f=Ge("aspect"),w=Ge("ease"),j=Ge("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],v=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],k=()=>[...v(),oe,se],R=()=>["auto","hidden","clip","visible","scroll"],N=()=>["auto","contain","none"],C=()=>[oe,se,l],T=()=>[Zn,"full","auto",...C()],O=()=>[cn,"none","subgrid",oe,se],$=()=>["auto",{span:["full",cn,oe,se]},cn,oe,se],S=()=>[cn,"auto",oe,se],A=()=>["auto","min","max","fr",oe,se],I=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],B=()=>["start","end","center","stretch","center-safe","end-safe"],L=()=>["auto",...C()],E=()=>[Zn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...C()],P=()=>[e,oe,se],z=()=>[...v(),$c,Dc,{position:[oe,se]}],Z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],K=()=>["auto","cover","contain",H0,W0,{size:[oe,se]}],D=()=>[To,gr,Nn],W=()=>["","none","full",d,oe,se],Y=()=>["",ye,gr,Nn],V=()=>["solid","dashed","dotted","double"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],F=()=>[ye,To,$c,Dc],ee=()=>["","none",_,oe,se],pe=()=>["none",ye,oe,se],q=()=>["none",ye,oe,se],ne=()=>[ye,oe,se],le=()=>[Zn,"full",...C()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[rn],breakpoint:[rn],color:[$0],container:[rn],"drop-shadow":[rn],ease:["in","out","in-out"],font:[U0],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[rn],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[rn],shadow:[rn],spacing:["px",ye],text:[rn],"text-shadow":[rn],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Zn,se,oe,f]}],container:["container"],columns:[{columns:[ye,se,oe,c]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:k()}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:N()}],"overscroll-x":[{"overscroll-x":N()}],"overscroll-y":[{"overscroll-y":N()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{start:T()}],end:[{end:T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[cn,"auto",oe,se]}],basis:[{basis:[Zn,"full","auto",c,...C()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ye,Zn,"auto","initial","none",se]}],grow:[{grow:["",ye,oe,se]}],shrink:[{shrink:["",ye,oe,se]}],order:[{order:[cn,"first","last","none",oe,se]}],"grid-cols":[{"grid-cols":O()}],"col-start-end":[{col:$()}],"col-start":[{"col-start":S()}],"col-end":[{"col-end":S()}],"grid-rows":[{"grid-rows":O()}],"row-start-end":[{row:$()}],"row-start":[{"row-start":S()}],"row-end":[{"row-end":S()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":A()}],"auto-rows":[{"auto-rows":A()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...I(),"normal"]}],"justify-items":[{"justify-items":[...B(),"normal"]}],"justify-self":[{"justify-self":["auto",...B()]}],"align-content":[{content:["normal",...I()]}],"align-items":[{items:[...B(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...B(),{baseline:["","last"]}]}],"place-content":[{"place-content":I()}],"place-items":[{"place-items":[...B(),"baseline"]}],"place-self":[{"place-self":["auto",...B()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:L()}],mx:[{mx:L()}],my:[{my:L()}],ms:[{ms:L()}],me:[{me:L()}],mt:[{mt:L()}],mr:[{mr:L()}],mb:[{mb:L()}],ml:[{ml:L()}],"space-x":[{"space-x":C()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":C()}],"space-y-reverse":["space-y-reverse"],size:[{size:E()}],w:[{w:[c,"screen",...E()]}],"min-w":[{"min-w":[c,"screen","none",...E()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[i]},...E()]}],h:[{h:["screen","lh",...E()]}],"min-h":[{"min-h":["screen","lh","none",...E()]}],"max-h":[{"max-h":["screen","lh",...E()]}],"font-size":[{text:["base",r,gr,Nn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,oe,Io]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",To,se]}],"font-family":[{font:[q0,se,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,oe,se]}],"line-clamp":[{"line-clamp":[ye,"none",oe,Io]}],leading:[{leading:[a,...C()]}],"list-image":[{"list-image":["none",oe,se]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",oe,se]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:P()}],"text-color":[{text:P()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:[ye,"from-font","auto",oe,Nn]}],"text-decoration-color":[{decoration:P()}],"underline-offset":[{"underline-offset":[ye,"auto",oe,se]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",oe,se]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",oe,se]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:Z()}],"bg-size":[{bg:K()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},cn,oe,se],radial:["",oe,se],conic:[cn,oe,se]},Z0,V0]}],"bg-color":[{bg:P()}],"gradient-from-pos":[{from:D()}],"gradient-via-pos":[{via:D()}],"gradient-to-pos":[{to:D()}],"gradient-from":[{from:P()}],"gradient-via":[{via:P()}],"gradient-to":[{to:P()}],rounded:[{rounded:W()}],"rounded-s":[{"rounded-s":W()}],"rounded-e":[{"rounded-e":W()}],"rounded-t":[{"rounded-t":W()}],"rounded-r":[{"rounded-r":W()}],"rounded-b":[{"rounded-b":W()}],"rounded-l":[{"rounded-l":W()}],"rounded-ss":[{"rounded-ss":W()}],"rounded-se":[{"rounded-se":W()}],"rounded-ee":[{"rounded-ee":W()}],"rounded-es":[{"rounded-es":W()}],"rounded-tl":[{"rounded-tl":W()}],"rounded-tr":[{"rounded-tr":W()}],"rounded-br":[{"rounded-br":W()}],"rounded-bl":[{"rounded-bl":W()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...V(),"hidden","none"]}],"divide-style":[{divide:[...V(),"hidden","none"]}],"border-color":[{border:P()}],"border-color-x":[{"border-x":P()}],"border-color-y":[{"border-y":P()}],"border-color-s":[{"border-s":P()}],"border-color-e":[{"border-e":P()}],"border-color-t":[{"border-t":P()}],"border-color-r":[{"border-r":P()}],"border-color-b":[{"border-b":P()}],"border-color-l":[{"border-l":P()}],"divide-color":[{divide:P()}],"outline-style":[{outline:[...V(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ye,oe,se]}],"outline-w":[{outline:["",ye,gr,Nn]}],"outline-color":[{outline:P()}],shadow:[{shadow:["","none",m,Xr,Kr]}],"shadow-color":[{shadow:P()}],"inset-shadow":[{"inset-shadow":["none",u,Xr,Kr]}],"inset-shadow-color":[{"inset-shadow":P()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:P()}],"ring-offset-w":[{"ring-offset":[ye,Nn]}],"ring-offset-color":[{"ring-offset":P()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":P()}],"text-shadow":[{"text-shadow":["none",p,Xr,Kr]}],"text-shadow-color":[{"text-shadow":P()}],opacity:[{opacity:[ye,oe,se]}],"mix-blend":[{"mix-blend":[...ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":F()}],"mask-image-linear-to-pos":[{"mask-linear-to":F()}],"mask-image-linear-from-color":[{"mask-linear-from":P()}],"mask-image-linear-to-color":[{"mask-linear-to":P()}],"mask-image-t-from-pos":[{"mask-t-from":F()}],"mask-image-t-to-pos":[{"mask-t-to":F()}],"mask-image-t-from-color":[{"mask-t-from":P()}],"mask-image-t-to-color":[{"mask-t-to":P()}],"mask-image-r-from-pos":[{"mask-r-from":F()}],"mask-image-r-to-pos":[{"mask-r-to":F()}],"mask-image-r-from-color":[{"mask-r-from":P()}],"mask-image-r-to-color":[{"mask-r-to":P()}],"mask-image-b-from-pos":[{"mask-b-from":F()}],"mask-image-b-to-pos":[{"mask-b-to":F()}],"mask-image-b-from-color":[{"mask-b-from":P()}],"mask-image-b-to-color":[{"mask-b-to":P()}],"mask-image-l-from-pos":[{"mask-l-from":F()}],"mask-image-l-to-pos":[{"mask-l-to":F()}],"mask-image-l-from-color":[{"mask-l-from":P()}],"mask-image-l-to-color":[{"mask-l-to":P()}],"mask-image-x-from-pos":[{"mask-x-from":F()}],"mask-image-x-to-pos":[{"mask-x-to":F()}],"mask-image-x-from-color":[{"mask-x-from":P()}],"mask-image-x-to-color":[{"mask-x-to":P()}],"mask-image-y-from-pos":[{"mask-y-from":F()}],"mask-image-y-to-pos":[{"mask-y-to":F()}],"mask-image-y-from-color":[{"mask-y-from":P()}],"mask-image-y-to-color":[{"mask-y-to":P()}],"mask-image-radial":[{"mask-radial":[oe,se]}],"mask-image-radial-from-pos":[{"mask-radial-from":F()}],"mask-image-radial-to-pos":[{"mask-radial-to":F()}],"mask-image-radial-from-color":[{"mask-radial-from":P()}],"mask-image-radial-to-color":[{"mask-radial-to":P()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":v()}],"mask-image-conic-pos":[{"mask-conic":[ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":F()}],"mask-image-conic-to-pos":[{"mask-conic-to":F()}],"mask-image-conic-from-color":[{"mask-conic-from":P()}],"mask-image-conic-to-color":[{"mask-conic-to":P()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:Z()}],"mask-size":[{mask:K()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",oe,se]}],filter:[{filter:["","none",oe,se]}],blur:[{blur:ee()}],brightness:[{brightness:[ye,oe,se]}],contrast:[{contrast:[ye,oe,se]}],"drop-shadow":[{"drop-shadow":["","none",h,Xr,Kr]}],"drop-shadow-color":[{"drop-shadow":P()}],grayscale:[{grayscale:["",ye,oe,se]}],"hue-rotate":[{"hue-rotate":[ye,oe,se]}],invert:[{invert:["",ye,oe,se]}],saturate:[{saturate:[ye,oe,se]}],sepia:[{sepia:["",ye,oe,se]}],"backdrop-filter":[{"backdrop-filter":["","none",oe,se]}],"backdrop-blur":[{"backdrop-blur":ee()}],"backdrop-brightness":[{"backdrop-brightness":[ye,oe,se]}],"backdrop-contrast":[{"backdrop-contrast":[ye,oe,se]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ye,oe,se]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ye,oe,se]}],"backdrop-invert":[{"backdrop-invert":["",ye,oe,se]}],"backdrop-opacity":[{"backdrop-opacity":[ye,oe,se]}],"backdrop-saturate":[{"backdrop-saturate":[ye,oe,se]}],"backdrop-sepia":[{"backdrop-sepia":["",ye,oe,se]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",oe,se]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ye,"initial",oe,se]}],ease:[{ease:["linear","initial",w,oe,se]}],delay:[{delay:[ye,oe,se]}],animate:[{animate:["none",j,oe,se]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,oe,se]}],"perspective-origin":[{"perspective-origin":k()}],rotate:[{rotate:pe()}],"rotate-x":[{"rotate-x":pe()}],"rotate-y":[{"rotate-y":pe()}],"rotate-z":[{"rotate-z":pe()}],scale:[{scale:q()}],"scale-x":[{"scale-x":q()}],"scale-y":[{"scale-y":q()}],"scale-z":[{"scale-z":q()}],"scale-3d":["scale-3d"],skew:[{skew:ne()}],"skew-x":[{"skew-x":ne()}],"skew-y":[{"skew-y":ne()}],transform:[{transform:[oe,se,"","none","gpu","cpu"]}],"transform-origin":[{origin:k()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:le()}],"translate-x":[{"translate-x":le()}],"translate-y":[{"translate-y":le()}],"translate-z":[{"translate-z":le()}],"translate-none":["translate-none"],accent:[{accent:P()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:P()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",oe,se]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",oe,se]}],fill:[{fill:["none",...P()]}],"stroke-w":[{stroke:[ye,gr,Nn,Io]}],stroke:[{stroke:["none",...P()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},K0=E0(Y0);function H(...e){return K0(Kd(e))}const X0=Qa("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-neutral-50/20",{variants:{variant:{default:"bg-neutral-900 text-neutral-50 hover:bg-neutral-900/90 dark:bg-neutral-50 dark:text-neutral-900 dark:hover:bg-neutral-50/90",secondary:"bg-neutral-100 text-neutral-900 hover:bg-neutral-100/80 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800/80",outline:"border border-neutral-200 bg-transparent text-neutral-900 hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800",ghost:"bg-transparent text-neutral-900 hover:bg-neutral-100 dark:text-neutral-50 dark:hover:bg-neutral-800",destructive:"bg-red-600 text-neutral-50 hover:bg-red-600/90 dark:bg-red-500 dark:hover:bg-red-500/90",link:"bg-transparent text-neutral-900 underline-offset-4 hover:underline dark:text-neutral-50"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-6",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ie=x.forwardRef(({className:e,variant:t,size:r,asChild:s,...o},a)=>{const i=s?s0:"button";return n.jsx(i,{className:H(X0({variant:t,size:r}),e),ref:a,...o})});ie.displayName="Button";const J0=Qa("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 An({className:e,variant:t,...r}){return n.jsx("div",{className:H(J0({variant:t}),e),...r})}const Ot=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}));Ot.displayName="Card";const Tr=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex flex-col space-y-1.5 p-6",e),...t}));Tr.displayName="CardHeader";const Ir=x.forwardRef(({className:e,...t},r)=>n.jsx("h3",{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));Ir.displayName="CardTitle";const du=x.forwardRef(({className:e,...t},r)=>n.jsx("p",{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));du.displayName="CardDescription";const Qt=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("p-6 pt-0",e),...t}));Qt.displayName="CardContent";const uu=x.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:H("flex items-center p-6 pt-0",e),...t}));uu.displayName="CardFooter";const Ue=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}));Ue.displayName="Input";const it=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}));it.displayName="Label";var ew=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],tw=ew.reduce((e,t)=>{const r=Qd(`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}},{}),nw="Separator",zc="horizontal",rw=["horizontal","vertical"],mu=x.forwardRef((e,t)=>{const{decorative:r,orientation:s=zc,...o}=e,a=sw(s)?s:zc,c=r?{role:"none"}:{"aria-orientation":a==="vertical"?a:void 0,role:"separator"};return n.jsx(tw.div,{"data-orientation":a,...c,...o,ref:t})});mu.displayName=nw;function sw(e){return rw.includes(e)}var pu=mu;const Ct=x.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...s},o)=>n.jsx(pu,{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}));Ct.displayName=pu.displayName;function De({className:e,...t}){return n.jsx("div",{className:H("animate-pulse rounded-md bg-neutral-100 dark:bg-neutral-800",e),...t})}function Fc(e,[t,r]){return Math.min(r,Math.max(t,e))}function _e(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e?.(o),r===!1||!o.defaultPrevented)return t?.(o)}}function ow(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 wn(e,t=[]){let r=[];function s(a,i){const c=x.createContext(i),l=r.length;r=[...r,i];const d=u=>{const{scope:p,children:h,..._}=u,g=p?.[e]?.[l]||c,f=x.useMemo(()=>_,Object.values(_));return n.jsx(g.Provider,{value:f,children:h})};d.displayName=a+"Provider";function m(u,p){const h=p?.[e]?.[l]||c,_=x.useContext(h);if(_)return _;if(i!==void 0)return i;throw new Error(`\`${u}\` must be used within \`${a}\``)}return[d,m]}const o=()=>{const a=r.map(i=>x.createContext(i));return function(c){const l=c?.[e]||a;return x.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return o.scopeName=e,[s,aw(o,...t)]}function aw(...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 Bc(e){const t=iw(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(lw);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 iw(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=uw(o),c=dw(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ir(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 cw=Symbol("radix.slottable");function lw(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===cw}function dw(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 uw(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 Ka(e){const t=e+"CollectionProvider",[r,s]=wn(t),[o,a]=r(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:f,children:w}=g,j=y.useRef(null),b=y.useRef(new Map).current;return n.jsx(o,{scope:f,itemMap:b,collectionRef:j,children:w})};i.displayName=t;const c=e+"CollectionSlot",l=Bc(c),d=y.forwardRef((g,f)=>{const{scope:w,children:j}=g,b=a(c,w),v=Ee(f,b.collectionRef);return n.jsx(l,{ref:v,children:j})});d.displayName=c;const m=e+"CollectionItemSlot",u="data-radix-collection-item",p=Bc(m),h=y.forwardRef((g,f)=>{const{scope:w,children:j,...b}=g,v=y.useRef(null),k=Ee(f,v),R=a(m,w);return y.useEffect(()=>(R.itemMap.set(v,{ref:v,...b}),()=>void R.itemMap.delete(v))),n.jsx(p,{[u]:"",ref:k,children:j})});h.displayName=m;function _(g){const f=a(e+"CollectionConsumer",g);return y.useCallback(()=>{const j=f.collectionRef.current;if(!j)return[];const b=Array.from(j.querySelectorAll(`[${u}]`));return Array.from(f.itemMap.values()).sort((R,N)=>b.indexOf(R.ref.current)-b.indexOf(N.ref.current))},[f.collectionRef,f.itemMap])}return[{Provider:i,Slot:d,ItemSlot:h},_,s]}var mw=x.createContext(void 0);function Bs(e){const t=x.useContext(mw);return e||t||"ltr"}function pw(e){const t=fw(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(gw);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 fw(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=yw(o),c=xw(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ir(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 hw=Symbol("radix.slottable");function gw(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===hw}function xw(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 yw(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 vw=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],be=vw.reduce((e,t)=>{const r=pw(`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 bw(e,t){e&&Rs.flushSync(()=>e.dispatchEvent(t))}function pn(e){const t=x.useRef(e);return x.useEffect(()=>{t.current=e}),x.useMemo(()=>(...r)=>t.current?.(...r),[])}function ww(e,t=globalThis?.document){const r=pn(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 _w="DismissableLayer",aa="dismissableLayer.update",jw="dismissableLayer.pointerDownOutside",kw="dismissableLayer.focusOutside",Uc,fu=x.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Xa=x.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:i,onDismiss:c,...l}=e,d=x.useContext(fu),[m,u]=x.useState(null),p=m?.ownerDocument??globalThis?.document,[,h]=x.useState({}),_=Ee(t,N=>u(N)),g=Array.from(d.layers),[f]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),w=g.indexOf(f),j=m?g.indexOf(m):-1,b=d.layersWithOutsidePointerEventsDisabled.size>0,v=j>=w,k=Nw(N=>{const C=N.target,T=[...d.branches].some(O=>O.contains(C));!v||T||(o?.(N),i?.(N),N.defaultPrevented||c?.())},p),R=Pw(N=>{const C=N.target;[...d.branches].some(O=>O.contains(C))||(a?.(N),i?.(N),N.defaultPrevented||c?.())},p);return ww(N=>{j===d.layers.size-1&&(s?.(N),!N.defaultPrevented&&c&&(N.preventDefault(),c()))},p),x.useEffect(()=>{if(m)return r&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Uc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(m)),d.layers.add(m),Wc(),()=>{r&&d.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=Uc)}},[m,p,r,d]),x.useEffect(()=>()=>{m&&(d.layers.delete(m),d.layersWithOutsidePointerEventsDisabled.delete(m),Wc())},[m,d]),x.useEffect(()=>{const N=()=>h({});return document.addEventListener(aa,N),()=>document.removeEventListener(aa,N)},[]),n.jsx(be.div,{...l,ref:_,style:{pointerEvents:b?v?"auto":"none":void 0,...e.style},onFocusCapture:_e(e.onFocusCapture,R.onFocusCapture),onBlurCapture:_e(e.onBlurCapture,R.onBlurCapture),onPointerDownCapture:_e(e.onPointerDownCapture,k.onPointerDownCapture)})});Xa.displayName=_w;var Sw="DismissableLayerBranch",Cw=x.forwardRef((e,t)=>{const r=x.useContext(fu),s=x.useRef(null),o=Ee(t,s);return x.useEffect(()=>{const a=s.current;if(a)return r.branches.add(a),()=>{r.branches.delete(a)}},[r.branches]),n.jsx(be.div,{...e,ref:o})});Cw.displayName=Sw;function Nw(e,t=globalThis?.document){const r=pn(e),s=x.useRef(!1),o=x.useRef(()=>{});return x.useEffect(()=>{const a=c=>{if(c.target&&!s.current){let l=function(){hu(jw,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 Pw(e,t=globalThis?.document){const r=pn(e),s=x.useRef(!1);return x.useEffect(()=>{const o=a=>{a.target&&!s.current&&hu(kw,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 Wc(){const e=new CustomEvent(aa);document.dispatchEvent(e)}function hu(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?bw(o,a):o.dispatchEvent(a)}var Ro=0;function gu(){x.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Vc()),document.body.insertAdjacentElement("beforeend",e[1]??Vc()),Ro++,()=>{Ro===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ro--}},[])}function Vc(){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 Oo="focusScope.autoFocusOnMount",Mo="focusScope.autoFocusOnUnmount",qc={bubbles:!1,cancelable:!0},Aw="FocusScope",Ja=x.forwardRef((e,t)=>{const{loop:r=!1,trapped:s=!1,onMountAutoFocus:o,onUnmountAutoFocus:a,...i}=e,[c,l]=x.useState(null),d=pn(o),m=pn(a),u=x.useRef(null),p=Ee(t,g=>l(g)),h=x.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;x.useEffect(()=>{if(s){let g=function(b){if(h.paused||!c)return;const v=b.target;c.contains(v)?u.current=v:ln(u.current,{select:!0})},f=function(b){if(h.paused||!c)return;const v=b.relatedTarget;v!==null&&(c.contains(v)||ln(u.current,{select:!0}))},w=function(b){if(document.activeElement===document.body)for(const k of b)k.removedNodes.length>0&&ln(c)};document.addEventListener("focusin",g),document.addEventListener("focusout",f);const j=new MutationObserver(w);return c&&j.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",f),j.disconnect()}}},[s,c,h.paused]),x.useEffect(()=>{if(c){Zc.add(h);const g=document.activeElement;if(!c.contains(g)){const w=new CustomEvent(Oo,qc);c.addEventListener(Oo,d),c.dispatchEvent(w),w.defaultPrevented||(Ew(Mw(xu(c)),{select:!0}),document.activeElement===g&&ln(c))}return()=>{c.removeEventListener(Oo,d),setTimeout(()=>{const w=new CustomEvent(Mo,qc);c.addEventListener(Mo,m),c.dispatchEvent(w),w.defaultPrevented||ln(g??document.body,{select:!0}),c.removeEventListener(Mo,m),Zc.remove(h)},0)}}},[c,d,m,h]);const _=x.useCallback(g=>{if(!r&&!s||h.paused)return;const f=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,w=document.activeElement;if(f&&w){const j=g.currentTarget,[b,v]=Tw(j);b&&v?!g.shiftKey&&w===v?(g.preventDefault(),r&&ln(b,{select:!0})):g.shiftKey&&w===b&&(g.preventDefault(),r&&ln(v,{select:!0})):w===j&&g.preventDefault()}},[r,s,h.paused]);return n.jsx(be.div,{tabIndex:-1,...i,ref:p,onKeyDown:_})});Ja.displayName=Aw;function Ew(e,{select:t=!1}={}){const r=document.activeElement;for(const s of e)if(ln(s,{select:t}),document.activeElement!==r)return}function Tw(e){const t=xu(e),r=Hc(t,e),s=Hc(t.reverse(),e);return[r,s]}function xu(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 Hc(e,t){for(const r of e)if(!Iw(r,{upTo:t}))return r}function Iw(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 Rw(e){return e instanceof HTMLInputElement&&"select"in e}function ln(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&Rw(e)&&t&&e.select()}}var Zc=Ow();function Ow(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=Gc(e,t),e.unshift(t)},remove(t){e=Gc(e,t),e[0]?.resume()}}}function Gc(e,t){const r=[...e],s=r.indexOf(t);return s!==-1&&r.splice(s,1),r}function Mw(e){return e.filter(t=>t.tagName!=="A")}var Je=globalThis?.document?x.useLayoutEffect:()=>{},Lw=x[" useId ".trim().toString()]||(()=>{}),Dw=0;function Ht(e){const[t,r]=x.useState(Lw());return Je(()=>{r(s=>s??String(Dw++))},[e]),t?`radix-${t}`:""}const $w=["top","right","bottom","left"],fn=Math.min,_t=Math.max,js=Math.round,Jr=Math.floor,Zt=e=>({x:e,y:e}),zw={left:"right",right:"left",bottom:"top",top:"bottom"},Fw={start:"end",end:"start"};function ia(e,t,r){return _t(e,fn(t,r))}function sn(e,t){return typeof e=="function"?e(t):e}function on(e){return e.split("-")[0]}function dr(e){return e.split("-")[1]}function ei(e){return e==="x"?"y":"x"}function ti(e){return e==="y"?"height":"width"}const Bw=new Set(["top","bottom"]);function qt(e){return Bw.has(on(e))?"y":"x"}function ni(e){return ei(qt(e))}function Uw(e,t,r){r===void 0&&(r=!1);const s=dr(e),o=ni(e),a=ti(o);let i=o==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(i=ks(i)),[i,ks(i)]}function Ww(e){const t=ks(e);return[ca(e),t,ca(t)]}function ca(e){return e.replace(/start|end/g,t=>Fw[t])}const Qc=["left","right"],Yc=["right","left"],Vw=["top","bottom"],qw=["bottom","top"];function Hw(e,t,r){switch(e){case"top":case"bottom":return r?t?Yc:Qc:t?Qc:Yc;case"left":case"right":return t?Vw:qw;default:return[]}}function Zw(e,t,r,s){const o=dr(e);let a=Hw(on(e),r==="start",s);return o&&(a=a.map(i=>i+"-"+o),t&&(a=a.concat(a.map(ca)))),a}function ks(e){return e.replace(/left|right|bottom|top/g,t=>zw[t])}function Gw(e){return{top:0,right:0,bottom:0,left:0,...e}}function yu(e){return typeof e!="number"?Gw(e):{top:e,right:e,bottom:e,left:e}}function Ss(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 Kc(e,t,r){let{reference:s,floating:o}=e;const a=qt(t),i=ni(t),c=ti(i),l=on(t),d=a==="y",m=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[c]/2-o[c]/2;let h;switch(l){case"top":h={x:m,y:s.y-o.height};break;case"bottom":h={x:m,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(dr(t)){case"start":h[i]-=p*(r&&d?-1:1);break;case"end":h[i]+=p*(r&&d?-1:1);break}return h}const Qw=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}=Kc(d,s,l),p=s,h={},_=0;for(let g=0;g<c.length;g++){const{name:f,fn:w}=c[g],{x:j,y:b,data:v,reset:k}=await w({x:m,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:h,rects:d,platform:i,elements:{reference:e,floating:t}});m=j??m,u=b??u,h={...h,[f]:{...h[f],...v}},k&&_<=50&&(_++,typeof k=="object"&&(k.placement&&(p=k.placement),k.rects&&(d=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:m,y:u}=Kc(d,p,l)),g=-1)}return{x:m,y:u,placement:p,strategy:o,middlewareData:h}};async function Rr(e,t){var r;t===void 0&&(t={});const{x:s,y:o,platform:a,rects:i,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:m="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=sn(t,e),_=yu(h),f=c[p?u==="floating"?"reference":"floating":u],w=Ss(await a.getClippingRect({element:(r=await(a.isElement==null?void 0:a.isElement(f)))==null||r?f:f.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(c.floating)),boundary:d,rootBoundary:m,strategy:l})),j=u==="floating"?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,b=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),v=await(a.isElement==null?void 0:a.isElement(b))?await(a.getScale==null?void 0:a.getScale(b))||{x:1,y:1}:{x:1,y:1},k=Ss(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:j,offsetParent:b,strategy:l}):j);return{top:(w.top-k.top+_.top)/v.y,bottom:(k.bottom-w.bottom+_.bottom)/v.y,left:(w.left-k.left+_.left)/v.x,right:(k.right-w.right+_.right)/v.x}}const Yw=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}=sn(e,t)||{};if(d==null)return{};const u=yu(m),p={x:r,y:s},h=ni(o),_=ti(h),g=await i.getDimensions(d),f=h==="y",w=f?"top":"left",j=f?"bottom":"right",b=f?"clientHeight":"clientWidth",v=a.reference[_]+a.reference[h]-p[h]-a.floating[_],k=p[h]-a.reference[h],R=await(i.getOffsetParent==null?void 0:i.getOffsetParent(d));let N=R?R[b]:0;(!N||!await(i.isElement==null?void 0:i.isElement(R)))&&(N=c.floating[b]||a.floating[_]);const C=v/2-k/2,T=N/2-g[_]/2-1,O=fn(u[w],T),$=fn(u[j],T),S=O,A=N-g[_]-$,I=N/2-g[_]/2+C,B=ia(S,I,A),L=!l.arrow&&dr(o)!=null&&I!==B&&a.reference[_]/2-(I<S?O:$)-g[_]/2<0,E=L?I<S?I-S:I-A:0;return{[h]:p[h]+E,data:{[h]:B,centerOffset:I-B-E,...L&&{alignmentOffset:E}},reset:L}}}),Kw=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var r,s;const{placement:o,middlewareData:a,rects:i,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:m=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:_="none",flipAlignment:g=!0,...f}=sn(e,t);if((r=a.arrow)!=null&&r.alignmentOffset)return{};const w=on(o),j=qt(c),b=on(c)===c,v=await(l.isRTL==null?void 0:l.isRTL(d.floating)),k=p||(b||!g?[ks(c)]:Ww(c)),R=_!=="none";!p&&R&&k.push(...Zw(c,g,_,v));const N=[c,...k],C=await Rr(t,f),T=[];let O=((s=a.flip)==null?void 0:s.overflows)||[];if(m&&T.push(C[w]),u){const I=Uw(o,i,v);T.push(C[I[0]],C[I[1]])}if(O=[...O,{placement:o,overflows:T}],!T.every(I=>I<=0)){var $,S;const I=((($=a.flip)==null?void 0:$.index)||0)+1,B=N[I];if(B&&(!(u==="alignment"?j!==qt(B):!1)||O.every(P=>qt(P.placement)===j?P.overflows[0]>0:!0)))return{data:{index:I,overflows:O},reset:{placement:B}};let L=(S=O.filter(E=>E.overflows[0]<=0).sort((E,P)=>E.overflows[1]-P.overflows[1])[0])==null?void 0:S.placement;if(!L)switch(h){case"bestFit":{var A;const E=(A=O.filter(P=>{if(R){const z=qt(P.placement);return z===j||z==="y"}return!0}).map(P=>[P.placement,P.overflows.filter(z=>z>0).reduce((z,Z)=>z+Z,0)]).sort((P,z)=>P[1]-z[1])[0])==null?void 0:A[0];E&&(L=E);break}case"initialPlacement":L=c;break}if(o!==L)return{reset:{placement:L}}}return{}}}};function Xc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Jc(e){return $w.some(t=>e[t]>=0)}const Xw=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:s="referenceHidden",...o}=sn(e,t);switch(s){case"referenceHidden":{const a=await Rr(t,{...o,elementContext:"reference"}),i=Xc(a,r.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Jc(i)}}}case"escaped":{const a=await Rr(t,{...o,altBoundary:!0}),i=Xc(a,r.floating);return{data:{escapedOffsets:i,escaped:Jc(i)}}}default:return{}}}}},vu=new Set(["left","top"]);async function Jw(e,t){const{placement:r,platform:s,elements:o}=e,a=await(s.isRTL==null?void 0:s.isRTL(o.floating)),i=on(r),c=dr(r),l=qt(r)==="y",d=vu.has(i)?-1:1,m=a&&l?-1:1,u=sn(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:_}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return c&&typeof _=="number"&&(h=c==="end"?_*-1:_),l?{x:h*m,y:p*d}:{x:p*d,y:h*m}}const e_=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 Jw(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}}}}},t_=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:s,placement:o}=t,{mainAxis:a=!0,crossAxis:i=!1,limiter:c={fn:f=>{let{x:w,y:j}=f;return{x:w,y:j}}},...l}=sn(e,t),d={x:r,y:s},m=await Rr(t,l),u=qt(on(o)),p=ei(u);let h=d[p],_=d[u];if(a){const f=p==="y"?"top":"left",w=p==="y"?"bottom":"right",j=h+m[f],b=h-m[w];h=ia(j,h,b)}if(i){const f=u==="y"?"top":"left",w=u==="y"?"bottom":"right",j=_+m[f],b=_-m[w];_=ia(j,_,b)}const g=c.fn({...t,[p]:h,[u]:_});return{...g,data:{x:g.x-r,y:g.y-s,enabled:{[p]:a,[u]:i}}}}}},n_=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}=sn(e,t),m={x:r,y:s},u=qt(o),p=ei(u);let h=m[p],_=m[u];const g=sn(c,t),f=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const b=p==="y"?"height":"width",v=a.reference[p]-a.floating[b]+f.mainAxis,k=a.reference[p]+a.reference[b]-f.mainAxis;h<v?h=v:h>k&&(h=k)}if(d){var w,j;const b=p==="y"?"width":"height",v=vu.has(on(o)),k=a.reference[u]-a.floating[b]+(v&&((w=i.offset)==null?void 0:w[u])||0)+(v?0:f.crossAxis),R=a.reference[u]+a.reference[b]+(v?0:((j=i.offset)==null?void 0:j[u])||0)-(v?f.crossAxis:0);_<k?_=k:_>R&&(_=R)}return{[p]:h,[u]:_}}}},r_=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}=sn(e,t),m=await Rr(t,d),u=on(o),p=dr(o),h=qt(o)==="y",{width:_,height:g}=a.floating;let f,w;u==="top"||u==="bottom"?(f=u,w=p===(await(i.isRTL==null?void 0:i.isRTL(c.floating))?"start":"end")?"left":"right"):(w=u,f=p==="end"?"top":"bottom");const j=g-m.top-m.bottom,b=_-m.left-m.right,v=fn(g-m[f],j),k=fn(_-m[w],b),R=!t.middlewareData.shift;let N=v,C=k;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(C=b),(s=t.middlewareData.shift)!=null&&s.enabled.y&&(N=j),R&&!p){const O=_t(m.left,0),$=_t(m.right,0),S=_t(m.top,0),A=_t(m.bottom,0);h?C=_-2*(O!==0||$!==0?O+$:_t(m.left,m.right)):N=g-2*(S!==0||A!==0?S+A:_t(m.top,m.bottom))}await l({...t,availableWidth:C,availableHeight:N});const T=await i.getDimensions(c.floating);return _!==T.width||g!==T.height?{reset:{rects:!0}}:{}}}};function Us(){return typeof window<"u"}function ur(e){return bu(e)?(e.nodeName||"").toLowerCase():"#document"}function jt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Xt(e){var t;return(t=(bu(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function bu(e){return Us()?e instanceof Node||e instanceof jt(e).Node:!1}function Mt(e){return Us()?e instanceof Element||e instanceof jt(e).Element:!1}function Yt(e){return Us()?e instanceof HTMLElement||e instanceof jt(e).HTMLElement:!1}function el(e){return!Us()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof jt(e).ShadowRoot}const s_=new Set(["inline","contents"]);function Fr(e){const{overflow:t,overflowX:r,overflowY:s,display:o}=Lt(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+r)&&!s_.has(o)}const o_=new Set(["table","td","th"]);function a_(e){return o_.has(ur(e))}const i_=[":popover-open",":modal"];function Ws(e){return i_.some(t=>{try{return e.matches(t)}catch{return!1}})}const c_=["transform","translate","scale","rotate","perspective"],l_=["transform","translate","scale","rotate","perspective","filter"],d_=["paint","layout","strict","content"];function ri(e){const t=si(),r=Mt(e)?Lt(e):e;return c_.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)||l_.some(s=>(r.willChange||"").includes(s))||d_.some(s=>(r.contain||"").includes(s))}function u_(e){let t=hn(e);for(;Yt(t)&&!tr(t);){if(ri(t))return t;if(Ws(t))return null;t=hn(t)}return null}function si(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const m_=new Set(["html","body","#document"]);function tr(e){return m_.has(ur(e))}function Lt(e){return jt(e).getComputedStyle(e)}function Vs(e){return Mt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function hn(e){if(ur(e)==="html")return e;const t=e.assignedSlot||e.parentNode||el(e)&&e.host||Xt(e);return el(t)?t.host:t}function wu(e){const t=hn(e);return tr(t)?e.ownerDocument?e.ownerDocument.body:e.body:Yt(t)&&Fr(t)?t:wu(t)}function Or(e,t,r){var s;t===void 0&&(t=[]),r===void 0&&(r=!0);const o=wu(e),a=o===((s=e.ownerDocument)==null?void 0:s.body),i=jt(o);if(a){const c=la(i);return t.concat(i,i.visualViewport||[],Fr(o)?o:[],c&&r?Or(c):[])}return t.concat(o,Or(o,[],r))}function la(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function _u(e){const t=Lt(e);let r=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Yt(e),a=o?e.offsetWidth:r,i=o?e.offsetHeight:s,c=js(r)!==a||js(s)!==i;return c&&(r=a,s=i),{width:r,height:s,$:c}}function oi(e){return Mt(e)?e:e.contextElement}function Jn(e){const t=oi(e);if(!Yt(t))return Zt(1);const r=t.getBoundingClientRect(),{width:s,height:o,$:a}=_u(t);let i=(a?js(r.width):r.width)/s,c=(a?js(r.height):r.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!c||!Number.isFinite(c))&&(c=1),{x:i,y:c}}const p_=Zt(0);function ju(e){const t=jt(e);return!si()||!t.visualViewport?p_:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function f_(e,t,r){return t===void 0&&(t=!1),!r||t&&r!==jt(e)?!1:t}function In(e,t,r,s){t===void 0&&(t=!1),r===void 0&&(r=!1);const o=e.getBoundingClientRect(),a=oi(e);let i=Zt(1);t&&(s?Mt(s)&&(i=Jn(s)):i=Jn(e));const c=f_(a,r,s)?ju(a):Zt(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=jt(a),h=s&&Mt(s)?jt(s):s;let _=p,g=la(_);for(;g&&s&&h!==_;){const f=Jn(g),w=g.getBoundingClientRect(),j=Lt(g),b=w.left+(g.clientLeft+parseFloat(j.paddingLeft))*f.x,v=w.top+(g.clientTop+parseFloat(j.paddingTop))*f.y;l*=f.x,d*=f.y,m*=f.x,u*=f.y,l+=b,d+=v,_=jt(g),g=la(_)}}return Ss({width:m,height:u,x:l,y:d})}function qs(e,t){const r=Vs(e).scrollLeft;return t?t.left+r:In(Xt(e)).left+r}function ku(e,t){const r=e.getBoundingClientRect(),s=r.left+t.scrollLeft-qs(e,r),o=r.top+t.scrollTop;return{x:s,y:o}}function h_(e){let{elements:t,rect:r,offsetParent:s,strategy:o}=e;const a=o==="fixed",i=Xt(s),c=t?Ws(t.floating):!1;if(s===i||c&&a)return r;let l={scrollLeft:0,scrollTop:0},d=Zt(1);const m=Zt(0),u=Yt(s);if((u||!u&&!a)&&((ur(s)!=="body"||Fr(i))&&(l=Vs(s)),Yt(s))){const h=In(s);d=Jn(s),m.x=h.x+s.clientLeft,m.y=h.y+s.clientTop}const p=i&&!u&&!a?ku(i,l):Zt(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 g_(e){return Array.from(e.getClientRects())}function x_(e){const t=Xt(e),r=Vs(e),s=e.ownerDocument.body,o=_t(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),a=_t(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-r.scrollLeft+qs(e);const c=-r.scrollTop;return Lt(s).direction==="rtl"&&(i+=_t(t.clientWidth,s.clientWidth)-o),{width:o,height:a,x:i,y:c}}const tl=25;function y_(e,t){const r=jt(e),s=Xt(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=si();(!m||m&&t==="fixed")&&(c=o.offsetLeft,l=o.offsetTop)}const d=qs(s);if(d<=0){const m=s.ownerDocument,u=m.body,p=getComputedStyle(u),h=m.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,_=Math.abs(s.clientWidth-u.clientWidth-h);_<=tl&&(a-=_)}else d<=tl&&(a+=d);return{width:a,height:i,x:c,y:l}}const v_=new Set(["absolute","fixed"]);function b_(e,t){const r=In(e,!0,t==="fixed"),s=r.top+e.clientTop,o=r.left+e.clientLeft,a=Yt(e)?Jn(e):Zt(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 nl(e,t,r){let s;if(t==="viewport")s=y_(e,r);else if(t==="document")s=x_(Xt(e));else if(Mt(t))s=b_(t,r);else{const o=ju(e);s={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Ss(s)}function Su(e,t){const r=hn(e);return r===t||!Mt(r)||tr(r)?!1:Lt(r).position==="fixed"||Su(r,t)}function w_(e,t){const r=t.get(e);if(r)return r;let s=Or(e,[],!1).filter(c=>Mt(c)&&ur(c)!=="body"),o=null;const a=Lt(e).position==="fixed";let i=a?hn(e):e;for(;Mt(i)&&!tr(i);){const c=Lt(i),l=ri(i);!l&&c.position==="fixed"&&(o=null),(a?!l&&!o:!l&&c.position==="static"&&!!o&&v_.has(o.position)||Fr(i)&&!l&&Su(e,i))?s=s.filter(m=>m!==i):o=c,i=hn(i)}return t.set(e,s),s}function __(e){let{element:t,boundary:r,rootBoundary:s,strategy:o}=e;const i=[...r==="clippingAncestors"?Ws(t)?[]:w_(t,this._c):[].concat(r),s],c=i[0],l=i.reduce((d,m)=>{const u=nl(t,m,o);return d.top=_t(u.top,d.top),d.right=fn(u.right,d.right),d.bottom=fn(u.bottom,d.bottom),d.left=_t(u.left,d.left),d},nl(t,c,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function j_(e){const{width:t,height:r}=_u(e);return{width:t,height:r}}function k_(e,t,r){const s=Yt(t),o=Xt(t),a=r==="fixed",i=In(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=Zt(0);function d(){l.x=qs(o)}if(s||!s&&!a)if((ur(t)!=="body"||Fr(o))&&(c=Vs(t)),s){const h=In(t,!0,a,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&d();a&&!s&&o&&d();const m=o&&!s&&!a?ku(o,c):Zt(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 Lo(e){return Lt(e).position==="static"}function rl(e,t){if(!Yt(e)||Lt(e).position==="fixed")return null;if(t)return t(e);let r=e.offsetParent;return Xt(e)===r&&(r=r.ownerDocument.body),r}function Cu(e,t){const r=jt(e);if(Ws(e))return r;if(!Yt(e)){let o=hn(e);for(;o&&!tr(o);){if(Mt(o)&&!Lo(o))return o;o=hn(o)}return r}let s=rl(e,t);for(;s&&a_(s)&&Lo(s);)s=rl(s,t);return s&&tr(s)&&Lo(s)&&!ri(s)?r:s||u_(e)||r}const S_=async function(e){const t=this.getOffsetParent||Cu,r=this.getDimensions,s=await r(e.floating);return{reference:k_(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function C_(e){return Lt(e).direction==="rtl"}const N_={convertOffsetParentRelativeRectToViewportRelativeRect:h_,getDocumentElement:Xt,getClippingRect:__,getOffsetParent:Cu,getElementRects:S_,getClientRects:g_,getDimensions:j_,getScale:Jn,isElement:Mt,isRTL:C_};function Nu(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function P_(e,t){let r=null,s;const o=Xt(e);function a(){var c;clearTimeout(s),(c=r)==null||c.disconnect(),r=null}function i(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:m,top:u,width:p,height:h}=d;if(c||t(),!p||!h)return;const _=Jr(u),g=Jr(o.clientWidth-(m+p)),f=Jr(o.clientHeight-(u+h)),w=Jr(m),b={rootMargin:-_+"px "+-g+"px "+-f+"px "+-w+"px",threshold:_t(0,fn(1,l))||1};let v=!0;function k(R){const N=R[0].intersectionRatio;if(N!==l){if(!v)return i();N?i(!1,N):s=setTimeout(()=>{i(!1,1e-7)},1e3)}N===1&&!Nu(d,e.getBoundingClientRect())&&i(),v=!1}try{r=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{r=new IntersectionObserver(k,b)}r.observe(e)}return i(!0),a}function A_(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=oi(e),m=o||a?[...d?Or(d):[],...Or(t)]:[];m.forEach(w=>{o&&w.addEventListener("scroll",r,{passive:!0}),a&&w.addEventListener("resize",r)});const u=d&&c?P_(d,r):null;let p=-1,h=null;i&&(h=new ResizeObserver(w=>{let[j]=w;j&&j.target===d&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var b;(b=h)==null||b.observe(t)})),r()}),d&&!l&&h.observe(d),h.observe(t));let _,g=l?In(e):null;l&&f();function f(){const w=In(e);g&&!Nu(g,w)&&r(),g=w,_=requestAnimationFrame(f)}return r(),()=>{var w;m.forEach(j=>{o&&j.removeEventListener("scroll",r),a&&j.removeEventListener("resize",r)}),u?.(),(w=h)==null||w.disconnect(),h=null,l&&cancelAnimationFrame(_)}}const E_=e_,T_=t_,I_=Kw,R_=r_,O_=Xw,sl=Yw,M_=n_,L_=(e,t,r)=>{const s=new Map,o={platform:N_,...r},a={...o.platform,_c:s};return Qw(e,t,{...o,platform:a})};var D_=typeof document<"u",$_=function(){},ds=D_?y.useLayoutEffect:$_;function Cs(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(!Cs(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)&&!Cs(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function Pu(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function ol(e,t){const r=Pu(e);return Math.round(t*r)/r}function Do(e){const t=x.useRef(e);return ds(()=>{t.current=e}),t}function z_(e){e===void 0&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:s=[],platform:o,elements:{reference:a,floating:i}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[m,u]=x.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=x.useState(s);Cs(p,s)||h(s);const[_,g]=x.useState(null),[f,w]=x.useState(null),j=x.useCallback(P=>{P!==R.current&&(R.current=P,g(P))},[]),b=x.useCallback(P=>{P!==N.current&&(N.current=P,w(P))},[]),v=a||_,k=i||f,R=x.useRef(null),N=x.useRef(null),C=x.useRef(m),T=l!=null,O=Do(l),$=Do(o),S=Do(d),A=x.useCallback(()=>{if(!R.current||!N.current)return;const P={placement:t,strategy:r,middleware:p};$.current&&(P.platform=$.current),L_(R.current,N.current,P).then(z=>{const Z={...z,isPositioned:S.current!==!1};I.current&&!Cs(C.current,Z)&&(C.current=Z,Rs.flushSync(()=>{u(Z)}))})},[p,t,r,$,S]);ds(()=>{d===!1&&C.current.isPositioned&&(C.current.isPositioned=!1,u(P=>({...P,isPositioned:!1})))},[d]);const I=x.useRef(!1);ds(()=>(I.current=!0,()=>{I.current=!1}),[]),ds(()=>{if(v&&(R.current=v),k&&(N.current=k),v&&k){if(O.current)return O.current(v,k,A);A()}},[v,k,A,O,T]);const B=x.useMemo(()=>({reference:R,floating:N,setReference:j,setFloating:b}),[j,b]),L=x.useMemo(()=>({reference:v,floating:k}),[v,k]),E=x.useMemo(()=>{const P={position:r,left:0,top:0};if(!L.floating)return P;const z=ol(L.floating,m.x),Z=ol(L.floating,m.y);return c?{...P,transform:"translate("+z+"px, "+Z+"px)",...Pu(L.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:z,top:Z}},[r,c,L.floating,m.x,m.y]);return x.useMemo(()=>({...m,update:A,refs:B,elements:L,floatingStyles:E}),[m,A,B,L,E])}const F_=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?sl({element:s.current,padding:o}).fn(r):{}:s?sl({element:s,padding:o}).fn(r):{}}}},B_=(e,t)=>({...E_(e),options:[e,t]}),U_=(e,t)=>({...T_(e),options:[e,t]}),W_=(e,t)=>({...M_(e),options:[e,t]}),V_=(e,t)=>({...I_(e),options:[e,t]}),q_=(e,t)=>({...R_(e),options:[e,t]}),H_=(e,t)=>({...O_(e),options:[e,t]}),Z_=(e,t)=>({...F_(e),options:[e,t]});var G_="Arrow",Au=x.forwardRef((e,t)=>{const{children:r,width:s=10,height:o=5,...a}=e;return n.jsx(be.svg,{...a,ref:t,width:s,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:n.jsx("polygon",{points:"0,0 30,0 15,10"})})});Au.displayName=G_;var Q_=Au;function Y_(e){const[t,r]=x.useState(void 0);return Je(()=>{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 ai="Popper",[Eu,Tu]=wn(ai),[K_,Iu]=Eu(ai),Ru=e=>{const{__scopePopper:t,children:r}=e,[s,o]=x.useState(null);return n.jsx(K_,{scope:t,anchor:s,onAnchorChange:o,children:r})};Ru.displayName=ai;var Ou="PopperAnchor",Mu=x.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:s,...o}=e,a=Iu(Ou,r),i=x.useRef(null),c=Ee(t,i),l=x.useRef(null);return x.useEffect(()=>{const d=l.current;l.current=s?.current||i.current,d!==l.current&&a.onAnchorChange(l.current)}),s?null:n.jsx(be.div,{...o,ref:c})});Mu.displayName=Ou;var ii="PopperContent",[X_,J_]=Eu(ii),Lu=x.forwardRef((e,t)=>{const{__scopePopper:r,side:s="bottom",sideOffset:o=0,align:a="center",alignOffset:i=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:m=0,sticky:u="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:_,...g}=e,f=Iu(ii,r),[w,j]=x.useState(null),b=Ee(t,F=>j(F)),[v,k]=x.useState(null),R=Y_(v),N=R?.width??0,C=R?.height??0,T=s+(a!=="center"?"-"+a:""),O=typeof m=="number"?m:{top:0,right:0,bottom:0,left:0,...m},$=Array.isArray(d)?d:[d],S=$.length>0,A={padding:O,boundary:$.filter(tj),altBoundary:S},{refs:I,floatingStyles:B,placement:L,isPositioned:E,middlewareData:P}=z_({strategy:"fixed",placement:T,whileElementsMounted:(...F)=>A_(...F,{animationFrame:h==="always"}),elements:{reference:f.anchor},middleware:[B_({mainAxis:o+C,alignmentAxis:i}),l&&U_({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?W_():void 0,...A}),l&&V_({...A}),q_({...A,apply:({elements:F,rects:ee,availableWidth:pe,availableHeight:q})=>{const{width:ne,height:le}=ee.reference,fe=F.floating.style;fe.setProperty("--radix-popper-available-width",`${pe}px`),fe.setProperty("--radix-popper-available-height",`${q}px`),fe.setProperty("--radix-popper-anchor-width",`${ne}px`),fe.setProperty("--radix-popper-anchor-height",`${le}px`)}}),v&&Z_({element:v,padding:c}),nj({arrowWidth:N,arrowHeight:C}),p&&H_({strategy:"referenceHidden",...A})]}),[z,Z]=zu(L),K=pn(_);Je(()=>{E&&K?.()},[E,K]);const D=P.arrow?.x,W=P.arrow?.y,Y=P.arrow?.centerOffset!==0,[V,ce]=x.useState();return Je(()=>{w&&ce(window.getComputedStyle(w).zIndex)},[w]),n.jsx("div",{ref:I.setFloating,"data-radix-popper-content-wrapper":"",style:{...B,transform:E?B.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:V,"--radix-popper-transform-origin":[P.transformOrigin?.x,P.transformOrigin?.y].join(" "),...P.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:n.jsx(X_,{scope:r,placedSide:z,onArrowChange:k,arrowX:D,arrowY:W,shouldHideArrow:Y,children:n.jsx(be.div,{"data-side":z,"data-align":Z,...g,ref:b,style:{...g.style,animation:E?void 0:"none"}})})})});Lu.displayName=ii;var Du="PopperArrow",ej={top:"bottom",right:"left",bottom:"top",left:"right"},$u=x.forwardRef(function(t,r){const{__scopePopper:s,...o}=t,a=J_(Du,s),i=ej[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(Q_,{...o,ref:r,style:{...o.style,display:"block"}})})});$u.displayName=Du;function tj(e){return e!==null}var nj=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]=zu(r),u={start:"0%",center:"50%",end:"100%"}[m],p=(o.arrow?.x??0)+c/2,h=(o.arrow?.y??0)+l/2;let _="",g="";return d==="bottom"?(_=i?u:`${p}px`,g=`${-l}px`):d==="top"?(_=i?u:`${p}px`,g=`${s.floating.height+l}px`):d==="right"?(_=`${-l}px`,g=i?u:`${h}px`):d==="left"&&(_=`${s.floating.width+l}px`,g=i?u:`${h}px`),{data:{x:_,y:g}}}});function zu(e){const[t,r="center"]=e.split("-");return[t,r]}var rj=Ru,sj=Mu,oj=Lu,aj=$u,ij="Portal",ci=x.forwardRef((e,t)=>{const{container:r,...s}=e,[o,a]=x.useState(!1);Je(()=>a(!0),[]);const i=r||o&&globalThis?.document?.body;return i?Sa.createPortal(n.jsx(be.div,{...s,ref:t}),i):null});ci.displayName=ij;function cj(e){const t=lj(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(uj);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 lj(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=pj(o),c=mj(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ir(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 dj=Symbol("radix.slottable");function uj(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===dj}function mj(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 pj(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 fj=x[" useInsertionEffect ".trim().toString()]||Je;function gn({prop:e,defaultProp:t,onChange:r=()=>{},caller:s}){const[o,a,i]=hj({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=gj(m)?m(e):m;u!==e&&i.current?.(u)}else a(m)},[c,e,a,i]);return[l,d]}function hj({defaultProp:e,onChange:t}){const[r,s]=x.useState(e),o=x.useRef(r),a=x.useRef(t);return fj(()=>{a.current=t},[t]),x.useEffect(()=>{o.current!==r&&(a.current?.(r),o.current=r)},[r,o]),[r,s,a]}function gj(e){return typeof e=="function"}function xj(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 Fu=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"}),yj="VisuallyHidden",vj=x.forwardRef((e,t)=>n.jsx(be.span,{...e,ref:t,style:{...Fu,...e.style}}));vj.displayName=yj;var bj=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Gn=new WeakMap,es=new WeakMap,ts={},$o=0,Bu=function(e){return e&&(e.host||Bu(e.parentNode))},wj=function(e,t){return t.map(function(r){if(e.contains(r))return r;var s=Bu(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})},_j=function(e,t,r,s){var o=wj(t,Array.isArray(e)?e:[e]);ts[r]||(ts[r]=new WeakMap);var a=ts[r],i=[],c=new Set,l=new Set(o),d=function(u){!u||c.has(u)||(c.add(u),d(u.parentNode))};o.forEach(d);var m=function(u){!u||l.has(u)||Array.prototype.forEach.call(u.children,function(p){if(c.has(p))m(p);else try{var h=p.getAttribute(s),_=h!==null&&h!=="false",g=(Gn.get(p)||0)+1,f=(a.get(p)||0)+1;Gn.set(p,g),a.set(p,f),i.push(p),g===1&&_&&es.set(p,!0),f===1&&p.setAttribute(r,"true"),_||p.setAttribute(s,"true")}catch(w){console.error("aria-hidden: cannot operate on ",p,w)}})};return m(t),c.clear(),$o++,function(){i.forEach(function(u){var p=Gn.get(u)-1,h=a.get(u)-1;Gn.set(u,p),a.set(u,h),p||(es.has(u)||u.removeAttribute(s),es.delete(u)),h||u.removeAttribute(r)}),$o--,$o||(Gn=new WeakMap,Gn=new WeakMap,es=new WeakMap,ts={})}},Uu=function(e,t,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(e)?e:[e]),o=bj(e);return o?(s.push.apply(s,Array.from(o.querySelectorAll("[aria-live], script"))),_j(s,o,r,"aria-hidden")):function(){return null}},Vt=function(){return Vt=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},Vt.apply(this,arguments)};function Wu(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 jj(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 us="right-scroll-bar-position",ms="width-before-scroll-bar",kj="with-scroll-bars-hidden",Sj="--removed-body-scroll-bar-size";function zo(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Cj(e,t){var r=y.useState(function(){return{value:e,callback:t,facade:{get current(){return r.value},set current(s){var o=r.value;o!==s&&(r.value=s,r.callback(s,o))}}}})[0];return r.callback=t,r.facade}var Nj=typeof window<"u"?x.useLayoutEffect:x.useEffect,al=new WeakMap;function Pj(e,t){var r=Cj(null,function(s){return e.forEach(function(o){return zo(o,s)})});return Nj(function(){var s=al.get(r);if(s){var o=new Set(s),a=new Set(e),i=r.current;o.forEach(function(c){a.has(c)||zo(c,null)}),a.forEach(function(c){o.has(c)||zo(c,i)})}al.set(r,e)},[e]),r}function Aj(e){return e}function Ej(e,t){t===void 0&&(t=Aj);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 Tj(e){e===void 0&&(e={});var t=Ej(null);return t.options=Vt({async:!0,ssr:!1},e),t}var Vu=function(e){var t=e.sideCar,r=Wu(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,Vt({},r))};Vu.isSideCarExport=!0;function Ij(e,t){return e.useMedium(t),Vu}var qu=Tj(),Fo=function(){},Hs=x.forwardRef(function(e,t){var r=x.useRef(null),s=x.useState({onScrollCapture:Fo,onWheelCapture:Fo,onTouchMoveCapture:Fo}),o=s[0],a=s[1],i=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,m=e.enabled,u=e.shards,p=e.sideCar,h=e.noRelative,_=e.noIsolation,g=e.inert,f=e.allowPinchZoom,w=e.as,j=w===void 0?"div":w,b=e.gapMode,v=Wu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=p,R=Pj([r,t]),N=Vt(Vt({},v),o);return x.createElement(x.Fragment,null,m&&x.createElement(k,{sideCar:qu,removeScrollBar:d,shards:u,noRelative:h,noIsolation:_,inert:g,setCallbacks:a,allowPinchZoom:!!f,lockRef:r,gapMode:b}),i?x.cloneElement(x.Children.only(c),Vt(Vt({},N),{ref:R})):x.createElement(j,Vt({},N,{className:l,ref:R}),c))});Hs.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Hs.classNames={fullWidth:ms,zeroRight:us};var Rj=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Oj(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Rj();return t&&e.setAttribute("nonce",t),e}function Mj(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Lj(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Dj=function(){var e=0,t=null;return{add:function(r){e==0&&(t=Oj())&&(Mj(t,r),Lj(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},$j=function(){var e=Dj();return function(t,r){x.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])}},Hu=function(){var e=$j(),t=function(r){var s=r.styles,o=r.dynamic;return e(s,o),null};return t},zj={left:0,top:0,right:0,gap:0},Bo=function(e){return parseInt(e||"",10)||0},Fj=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[Bo(r),Bo(s),Bo(o)]},Bj=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return zj;var t=Fj(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])}},Uj=Hu(),er="data-scroll-locked",Wj=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(kj,` {
|
|
93
93
|
overflow: hidden `).concat(s,`;
|
|
94
94
|
padding-right: `).concat(c,"px ").concat(s,`;
|
|
95
95
|
}
|
|
96
|
-
body[`).concat(
|
|
96
|
+
body[`).concat(er,`] {
|
|
97
97
|
overflow: hidden `).concat(s,`;
|
|
98
98
|
overscroll-behavior: contain;
|
|
99
99
|
`).concat([t&&"position: relative ".concat(s,";"),r==="margin"&&`
|
|
@@ -106,31 +106,31 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
106
106
|
`),r==="padding"&&"padding-right: ".concat(c,"px ").concat(s,";")].filter(Boolean).join(""),`
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
-
.`).concat(
|
|
109
|
+
.`).concat(us,` {
|
|
110
110
|
right: `).concat(c,"px ").concat(s,`;
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
-
.`).concat(
|
|
113
|
+
.`).concat(ms,` {
|
|
114
114
|
margin-right: `).concat(c,"px ").concat(s,`;
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
-
.`).concat(
|
|
117
|
+
.`).concat(us," .").concat(us,` {
|
|
118
118
|
right: 0 `).concat(s,`;
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
-
.`).concat(
|
|
121
|
+
.`).concat(ms," .").concat(ms,` {
|
|
122
122
|
margin-right: 0 `).concat(s,`;
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
-
body[`).concat(
|
|
126
|
-
`).concat(
|
|
125
|
+
body[`).concat(er,`] {
|
|
126
|
+
`).concat(Sj,": ").concat(c,`px;
|
|
127
127
|
}
|
|
128
|
-
`)},
|
|
128
|
+
`)},il=function(){var e=parseInt(document.body.getAttribute(er)||"0",10);return isFinite(e)?e:0},Vj=function(){x.useEffect(function(){return document.body.setAttribute(er,(il()+1).toString()),function(){var e=il()-1;e<=0?document.body.removeAttribute(er):document.body.setAttribute(er,e.toString())}},[])},qj=function(e){var t=e.noRelative,r=e.noImportant,s=e.gapMode,o=s===void 0?"margin":s;Vj();var a=x.useMemo(function(){return Bj(o)},[o]);return x.createElement(Uj,{styles:Wj(a,!t,o,r?"":"!important")})},da=!1;if(typeof window<"u")try{var ns=Object.defineProperty({},"passive",{get:function(){return da=!0,!0}});window.addEventListener("test",ns,ns),window.removeEventListener("test",ns,ns)}catch{da=!1}var Qn=da?{passive:!1}:!1,Hj=function(e){return e.tagName==="TEXTAREA"},Zu=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!Hj(e)&&r[t]==="visible")},Zj=function(e){return Zu(e,"overflowY")},Gj=function(e){return Zu(e,"overflowX")},cl=function(e,t){var r=t.ownerDocument,s=t;do{typeof ShadowRoot<"u"&&s instanceof ShadowRoot&&(s=s.host);var o=Gu(e,s);if(o){var a=Qu(e,s),i=a[1],c=a[2];if(i>c)return!0}s=s.parentNode}while(s&&s!==r.body);return!1},Qj=function(e){var t=e.scrollTop,r=e.scrollHeight,s=e.clientHeight;return[t,r,s]},Yj=function(e){var t=e.scrollLeft,r=e.scrollWidth,s=e.clientWidth;return[t,r,s]},Gu=function(e,t){return e==="v"?Zj(t):Gj(t)},Qu=function(e,t){return e==="v"?Qj(t):Yj(t)},Kj=function(e,t){return e==="h"&&t==="rtl"?-1:1},Xj=function(e,t,r,s,o){var a=Kj(e,window.getComputedStyle(t).direction),i=a*s,c=r.target,l=t.contains(c),d=!1,m=i>0,u=0,p=0;do{if(!c)break;var h=Qu(e,c),_=h[0],g=h[1],f=h[2],w=g-f-a*_;(_||w)&&Gu(e,c)&&(u+=w,p+=_);var j=c.parentNode;c=j&&j.nodeType===Node.DOCUMENT_FRAGMENT_NODE?j.host:j}while(!l&&c!==document.body||l&&(t.contains(c)||t===c));return(m&&Math.abs(u)<1||!m&&Math.abs(p)<1)&&(d=!0),d},rs=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},ll=function(e){return[e.deltaX,e.deltaY]},dl=function(e){return e&&"current"in e?e.current:e},Jj=function(e,t){return e[0]===t[0]&&e[1]===t[1]},ek=function(e){return`
|
|
129
129
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
130
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(Wu)[0],i=x.useRef(e);x.useEffect(function(){i.current=e},[e]),x.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var g=fj([e.lockRef.current],(e.shards||[]).map(il),!0).filter(Boolean);return g.forEach(function(f){return f.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),g.forEach(function(f){return f.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var c=x.useCallback(function(g,f){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!i.current.allowPinchZoom;var w=ns(g),j=r.current,b="deltaX"in g?g.deltaX:j[0]-w[0],v="deltaY"in g?g.deltaY:j[1]-w[1],k,R=g.target,N=Math.abs(b)>Math.abs(v)?"h":"v";if("touches"in g&&N==="h"&&R.type==="range")return!1;var C=window.getSelection(),T=C&&C.anchorNode,O=T?T===R||T.contains(R):!1;if(O)return!1;var $=ol(N,R);if(!$)return!0;if($?k=N:(k=N==="v"?"h":"v",$=ol(N,R)),!$)return!1;if(!s.current&&"changedTouches"in g&&(b||v)&&(s.current=k),!k)return!0;var S=s.current||k;return Wj(S,f,g,S==="h"?b:v)},[]),l=x.useCallback(function(g){var f=g;if(!(!Qn.length||Qn[Qn.length-1]!==a)){var w="deltaY"in f?al(f):ns(f),j=t.current.filter(function(k){return k.name===f.type&&(k.target===f.target||f.target===k.shadowParent)&&Vj(k.delta,w)})[0];if(j&&j.should){f.cancelable&&f.preventDefault();return}if(!j){var b=(i.current.shards||[]).map(il).filter(Boolean).filter(function(k){return k.contains(f.target)}),v=b.length>0?c(f,b[0]):!i.current.noIsolation;v&&f.cancelable&&f.preventDefault()}}},[]),d=x.useCallback(function(g,f,w,j){var b={name:g,delta:f,target:w,should:j,shadowParent:Gj(w)};t.current.push(b),setTimeout(function(){t.current=t.current.filter(function(v){return v!==b})},1)},[]),m=x.useCallback(function(g){r.current=ns(g),s.current=void 0},[]),u=x.useCallback(function(g){d(g.type,al(g),g.target,c(g,e.lockRef.current))},[]),p=x.useCallback(function(g){d(g.type,ns(g),g.target,c(g,e.lockRef.current))},[]);x.useEffect(function(){return Qn.push(a),e.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:p}),document.addEventListener("wheel",l,Gn),document.addEventListener("touchmove",l,Gn),document.addEventListener("touchstart",m,Gn),function(){Qn=Qn.filter(function(g){return g!==a}),document.removeEventListener("wheel",l,Gn),document.removeEventListener("touchmove",l,Gn),document.removeEventListener("touchstart",m,Gn)}},[]);var h=e.removeScrollBar,_=e.inert;return x.createElement(x.Fragment,null,_?x.createElement(a,{styles:qj(o)}):null,h?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(Uu,Zj);var ci=x.forwardRef(function(e,t){return x.createElement(qs,Wt({},e,{ref:t,sideCar:Qj}))});ci.classNames=qs.classNames;var Yj=[" ","Enter","ArrowUp","ArrowDown"],Kj=[" ","Enter"],In="Select",[Hs,Zs,Xj]=Ya(In),[ur]=bn(In,[Xj,Pu]),Gs=Pu(),[Jj,wn]=ur(In),[ek,tk]=ur(In),Zu=e=>{const{__scopeSelect:t,children:r,open:s,defaultOpen:o,onOpenChange:a,value:i,defaultValue:c,onValueChange:l,dir:d,name:m,autoComplete:u,disabled:p,required:h,form:_}=e,g=Gs(t),[f,w]=x.useState(null),[j,b]=x.useState(null),[v,k]=x.useState(!1),R=Fs(d),[N,C]=hn({prop:s,defaultProp:o??!1,onChange:a,caller:In}),[T,O]=hn({prop:i,defaultProp:c,onChange:l,caller:In}),$=x.useRef(null),S=f?_||!!f.closest("form"):!0,[A,I]=x.useState(new Set),B=Array.from(A).map(D=>D.props.value).join(";");return n.jsx(G_,{...g,children:n.jsxs(Jj,{required:h,scope:t,trigger:f,onTriggerChange:w,valueNode:j,onValueNodeChange:b,valueNodeHasChildren:v,onValueNodeHasChildrenChange:k,contentId:qt(),value:T,onValueChange:O,open:N,onOpenChange:C,dir:R,triggerPointerDownPosRef:$,disabled:p,children:[n.jsx(Hs.Provider,{scope:t,children:n.jsx(ek,{scope:e.__scopeSelect,onNativeOptionAdd:x.useCallback(D=>{I(E=>new Set(E).add(D))},[]),onNativeOptionRemove:x.useCallback(D=>{I(E=>{const P=new Set(E);return P.delete(D),P})},[]),children:r})}),S?n.jsxs(pm,{"aria-hidden":!0,required:h,tabIndex:-1,name:m,autoComplete:u,value:T,onChange:D=>O(D.target.value),disabled:p,form:_,children:[T===void 0?n.jsx("option",{value:""}):null,Array.from(A)]},B):null]})})};Zu.displayName=In;var Gu="SelectTrigger",Qu=x.forwardRef((e,t)=>{const{__scopeSelect:r,disabled:s=!1,...o}=e,a=Gs(r),i=wn(Gu,r),c=i.disabled||s,l=Ee(t,i.onTriggerChange),d=Zs(r),m=x.useRef("touch"),[u,p,h]=hm(g=>{const f=d().filter(b=>!b.disabled),w=f.find(b=>b.value===i.value),j=gm(f,g,w);j!==void 0&&i.onValueChange(j.value)}),_=g=>{c||(i.onOpenChange(!0),h()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return n.jsx(Q_,{asChild:!0,...a,children:n.jsx(be.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":fm(i.value)?"":void 0,...o,ref:l,onClick:_e(o.onClick,g=>{g.currentTarget.focus(),m.current!=="mouse"&&_(g)}),onPointerDown:_e(o.onPointerDown,g=>{m.current=g.pointerType;const f=g.target;f.hasPointerCapture(g.pointerId)&&f.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(_(g),g.preventDefault())}),onKeyDown:_e(o.onKeyDown,g=>{const f=u.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&p(g.key),!(f&&g.key===" ")&&Yj.includes(g.key)&&(_(),g.preventDefault())})})})});Qu.displayName=Gu;var Yu="SelectValue",Ku=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,children:a,placeholder:i="",...c}=e,l=wn(Yu,r),{onValueNodeHasChildrenChange:d}=l,m=a!==void 0,u=Ee(t,l.onValueNodeChange);return Xe(()=>{d(m)},[d,m]),n.jsx(be.span,{...c,ref:u,style:{pointerEvents:"none"},children:fm(l.value)?n.jsx(n.Fragment,{children:i}):a})});Ku.displayName=Yu;var nk="SelectIcon",Xu=x.forwardRef((e,t)=>{const{__scopeSelect:r,children:s,...o}=e;return n.jsx(be.span,{"aria-hidden":!0,...o,ref:t,children:s||"▼"})});Xu.displayName=nk;var rk="SelectPortal",Ju=e=>n.jsx(ii,{asChild:!0,...e});Ju.displayName=rk;var Rn="SelectContent",em=x.forwardRef((e,t)=>{const r=wn(Rn,e.__scopeSelect),[s,o]=x.useState();if(Xe(()=>{o(new DocumentFragment)},[]),!r.open){const a=s;return a?Is.createPortal(n.jsx(tm,{scope:e.__scopeSelect,children:n.jsx(Hs.Slot,{scope:e.__scopeSelect,children:n.jsx("div",{children:e.children})})}),a):null}return n.jsx(nm,{...e,ref:t})});em.displayName=Rn;var Tt=10,[tm,_n]=ur(Rn),sk="SelectContentImpl",ok=J_("SelectContent.RemoveScroll"),nm=x.forwardRef((e,t)=>{const{__scopeSelect:r,position:s="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:a,onPointerDownOutside:i,side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:p,collisionPadding:h,sticky:_,hideWhenDetached:g,avoidCollisions:f,...w}=e,j=wn(Rn,r),[b,v]=x.useState(null),[k,R]=x.useState(null),N=Ee(t,F=>v(F)),[C,T]=x.useState(null),[O,$]=x.useState(null),S=Zs(r),[A,I]=x.useState(!1),B=x.useRef(!1);x.useEffect(()=>{if(b)return zu(b)},[b]),pu();const D=x.useCallback(F=>{const[ee,...pe]=S().map(le=>le.ref.current),[q]=pe.slice(-1),ne=document.activeElement;for(const le of F)if(le===ne||(le?.scrollIntoView({block:"nearest"}),le===ee&&k&&(k.scrollTop=0),le===q&&k&&(k.scrollTop=k.scrollHeight),le?.focus(),document.activeElement!==ne))return},[S,k]),E=x.useCallback(()=>D([C,b]),[D,C,b]);x.useEffect(()=>{A&&E()},[A,E]);const{onOpenChange:P,triggerPointerDownPosRef:z}=j;x.useEffect(()=>{if(b){let F={x:0,y:0};const ee=q=>{F={x:Math.abs(Math.round(q.pageX)-(z.current?.x??0)),y:Math.abs(Math.round(q.pageY)-(z.current?.y??0))}},pe=q=>{F.x<=10&&F.y<=10?q.preventDefault():b.contains(q.target)||P(!1),document.removeEventListener("pointermove",ee),z.current=null};return z.current!==null&&(document.addEventListener("pointermove",ee),document.addEventListener("pointerup",pe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ee),document.removeEventListener("pointerup",pe,{capture:!0})}}},[b,P,z]),x.useEffect(()=>{const F=()=>P(!1);return window.addEventListener("blur",F),window.addEventListener("resize",F),()=>{window.removeEventListener("blur",F),window.removeEventListener("resize",F)}},[P]);const[Z,K]=hm(F=>{const ee=S().filter(ne=>!ne.disabled),pe=ee.find(ne=>ne.ref.current===document.activeElement),q=gm(ee,F,pe);q&&setTimeout(()=>q.ref.current.focus())}),L=x.useCallback((F,ee,pe)=>{const q=!B.current&&!pe;(j.value!==void 0&&j.value===ee||q)&&(T(F),q&&(B.current=!0))},[j.value]),W=x.useCallback(()=>b?.focus(),[b]),Y=x.useCallback((F,ee,pe)=>{const q=!B.current&&!pe;(j.value!==void 0&&j.value===ee||q)&&$(F)},[j.value]),V=s==="popper"?da:rm,ce=V===da?{side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:p,collisionPadding:h,sticky:_,hideWhenDetached:g,avoidCollisions:f}:{};return n.jsx(tm,{scope:r,content:b,viewport:k,onViewportChange:R,itemRefCallback:L,selectedItem:C,onItemLeave:W,itemTextRefCallback:Y,focusSelectedItem:E,selectedItemText:O,position:s,isPositioned:A,searchRef:Z,children:n.jsx(ci,{as:ok,allowPinchZoom:!0,children:n.jsx(Xa,{asChild:!0,trapped:j.open,onMountAutoFocus:F=>{F.preventDefault()},onUnmountAutoFocus:_e(o,F=>{j.trigger?.focus({preventScroll:!0}),F.preventDefault()}),children:n.jsx(Ka,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:F=>F.preventDefault(),onDismiss:()=>j.onOpenChange(!1),children:n.jsx(V,{role:"listbox",id:j.contentId,"data-state":j.open?"open":"closed",dir:j.dir,onContextMenu:F=>F.preventDefault(),...w,...ce,onPlaced:()=>I(!0),ref:N,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:_e(w.onKeyDown,F=>{const ee=F.ctrlKey||F.altKey||F.metaKey;if(F.key==="Tab"&&F.preventDefault(),!ee&&F.key.length===1&&K(F.key),["ArrowUp","ArrowDown","Home","End"].includes(F.key)){let q=S().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);if(["ArrowUp","End"].includes(F.key)&&(q=q.slice().reverse()),["ArrowUp","ArrowDown"].includes(F.key)){const ne=F.target,le=q.indexOf(ne);q=q.slice(le+1)}setTimeout(()=>D(q)),F.preventDefault()}})})})})})})});nm.displayName=sk;var ak="SelectItemAlignedPosition",rm=x.forwardRef((e,t)=>{const{__scopeSelect:r,onPlaced:s,...o}=e,a=wn(Rn,r),i=_n(Rn,r),[c,l]=x.useState(null),[d,m]=x.useState(null),u=Ee(t,N=>m(N)),p=Zs(r),h=x.useRef(!1),_=x.useRef(!0),{viewport:g,selectedItem:f,selectedItemText:w,focusSelectedItem:j}=i,b=x.useCallback(()=>{if(a.trigger&&a.valueNode&&c&&d&&g&&f&&w){const N=a.trigger.getBoundingClientRect(),C=d.getBoundingClientRect(),T=a.valueNode.getBoundingClientRect(),O=w.getBoundingClientRect();if(a.dir!=="rtl"){const ne=O.left-C.left,le=T.left-ne,fe=N.left-le,Pe=N.width+fe,Ve=Math.max(Pe,C.width),qe=window.innerWidth-Tt,He=Lc(le,[Tt,Math.max(Tt,qe-Ve)]);c.style.minWidth=Pe+"px",c.style.left=He+"px"}else{const ne=C.right-O.right,le=window.innerWidth-T.right-ne,fe=window.innerWidth-N.right-le,Pe=N.width+fe,Ve=Math.max(Pe,C.width),qe=window.innerWidth-Tt,He=Lc(le,[Tt,Math.max(Tt,qe-Ve)]);c.style.minWidth=Pe+"px",c.style.right=He+"px"}const $=p(),S=window.innerHeight-Tt*2,A=g.scrollHeight,I=window.getComputedStyle(d),B=parseInt(I.borderTopWidth,10),D=parseInt(I.paddingTop,10),E=parseInt(I.borderBottomWidth,10),P=parseInt(I.paddingBottom,10),z=B+D+A+P+E,Z=Math.min(f.offsetHeight*5,z),K=window.getComputedStyle(g),L=parseInt(K.paddingTop,10),W=parseInt(K.paddingBottom,10),Y=N.top+N.height/2-Tt,V=S-Y,ce=f.offsetHeight/2,F=f.offsetTop+ce,ee=B+D+F,pe=z-ee;if(ee<=Y){const ne=$.length>0&&f===$[$.length-1].ref.current;c.style.bottom="0px";const le=d.clientHeight-g.offsetTop-g.offsetHeight,fe=Math.max(V,ce+(ne?W:0)+le+E),Pe=ee+fe;c.style.height=Pe+"px"}else{const ne=$.length>0&&f===$[0].ref.current;c.style.top="0px";const fe=Math.max(Y,B+g.offsetTop+(ne?L:0)+ce)+pe;c.style.height=fe+"px",g.scrollTop=ee-Y+g.offsetTop}c.style.margin=`${Tt}px 0`,c.style.minHeight=Z+"px",c.style.maxHeight=S+"px",s?.(),requestAnimationFrame(()=>h.current=!0)}},[p,a.trigger,a.valueNode,c,d,g,f,w,a.dir,s]);Xe(()=>b(),[b]);const[v,k]=x.useState();Xe(()=>{d&&k(window.getComputedStyle(d).zIndex)},[d]);const R=x.useCallback(N=>{N&&_.current===!0&&(b(),j?.(),_.current=!1)},[b,j]);return n.jsx(ck,{scope:r,contentWrapper:c,shouldExpandOnScrollRef:h,onScrollButtonChange:R,children:n.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:v},children:n.jsx(be.div,{...o,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});rm.displayName=ak;var ik="SelectPopperPosition",da=x.forwardRef((e,t)=>{const{__scopeSelect:r,align:s="start",collisionPadding:o=Tt,...a}=e,i=Gs(r);return n.jsx(Y_,{...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(Rn,{}),ua="SelectViewport",sm=x.forwardRef((e,t)=>{const{__scopeSelect:r,nonce:s,...o}=e,a=_n(ua,r),i=li(ua,r),c=Ee(t,a.onViewportChange),l=x.useRef(0);return n.jsxs(n.Fragment,{children:[n.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),n.jsx(Hs.Slot,{scope:r,children:n.jsx(be.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:_e(o.onScroll,d=>{const m=d.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:p}=i;if(p?.current&&u){const h=Math.abs(l.current-m.scrollTop);if(h>0){const _=window.innerHeight-Tt*2,g=parseFloat(u.style.minHeight),f=parseFloat(u.style.height),w=Math.max(g,f);if(w<_){const j=w+h,b=Math.min(_,j),v=j-b;u.style.height=b+"px",u.style.bottom==="0px"&&(m.scrollTop=v>0?v:0,u.style.justifyContent="flex-end")}}}l.current=m.scrollTop})})})]})});sm.displayName=ua;var om="SelectGroup",[lk,dk]=ur(om),am=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=qt();return n.jsx(lk,{scope:r,id:o,children:n.jsx(be.div,{role:"group","aria-labelledby":o,...s,ref:t})})});am.displayName=om;var im="SelectLabel",uk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=dk(im,r);return n.jsx(be.div,{id:o.id,...s,ref:t})});uk.displayName=im;var Cs="SelectItem",[mk,cm]=ur(Cs),lm=x.forwardRef((e,t)=>{const{__scopeSelect:r,value:s,disabled:o=!1,textValue:a,...i}=e,c=wn(Cs,r),l=_n(Cs,r),d=c.value===s,[m,u]=x.useState(a??""),[p,h]=x.useState(!1),_=Ee(t,j=>l.itemRefCallback?.(j,s,o)),g=qt(),f=x.useRef("touch"),w=()=>{o||(c.onValueChange(s),c.onOpenChange(!1))};if(s==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return n.jsx(mk,{scope:r,value:s,disabled:o,textId:g,isSelected:d,onItemTextChange:x.useCallback(j=>{u(b=>b||(j?.textContent??"").trim())},[]),children:n.jsx(Hs.ItemSlot,{scope:r,value:s,disabled:o,textValue:m,children:n.jsx(be.div,{role:"option","aria-labelledby":g,"data-highlighted":p?"":void 0,"aria-selected":d&&p,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:_,onFocus:_e(i.onFocus,()=>h(!0)),onBlur:_e(i.onBlur,()=>h(!1)),onClick:_e(i.onClick,()=>{f.current!=="mouse"&&w()}),onPointerUp:_e(i.onPointerUp,()=>{f.current==="mouse"&&w()}),onPointerDown:_e(i.onPointerDown,j=>{f.current=j.pointerType}),onPointerMove:_e(i.onPointerMove,j=>{f.current=j.pointerType,o?l.onItemLeave?.():f.current==="mouse"&&j.currentTarget.focus({preventScroll:!0})}),onPointerLeave:_e(i.onPointerLeave,j=>{j.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:_e(i.onKeyDown,j=>{l.searchRef?.current!==""&&j.key===" "||(Kj.includes(j.key)&&w(),j.key===" "&&j.preventDefault())})})})})});lm.displayName=Cs;var jr="SelectItemText",dm=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,...a}=e,i=wn(jr,r),c=_n(jr,r),l=cm(jr,r),d=tk(jr,r),[m,u]=x.useState(null),p=Ee(t,w=>u(w),l.onItemTextChange,w=>c.itemTextRefCallback?.(w,l.value,l.disabled)),h=m?.textContent,_=x.useMemo(()=>n.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:g,onNativeOptionRemove:f}=d;return Xe(()=>(g(_),()=>f(_)),[g,f,_]),n.jsxs(n.Fragment,{children:[n.jsx(be.span,{id:l.textId,...a,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Is.createPortal(a.children,i.valueNode):null]})});dm.displayName=jr;var um="SelectItemIndicator",pk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return cm(um,r).isSelected?n.jsx(be.span,{"aria-hidden":!0,...s,ref:t}):null});pk.displayName=um;var ma="SelectScrollUpButton",fk=x.forwardRef((e,t)=>{const r=_n(ma,e.__scopeSelect),s=li(ma,e.__scopeSelect),[o,a]=x.useState(!1),i=Ee(t,s.onScrollButtonChange);return Xe(()=>{if(r.viewport&&r.isPositioned){let c=function(){const d=l.scrollTop>0;a(d)};const l=r.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),o?n.jsx(mm,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});fk.displayName=ma;var pa="SelectScrollDownButton",hk=x.forwardRef((e,t)=>{const r=_n(pa,e.__scopeSelect),s=li(pa,e.__scopeSelect),[o,a]=x.useState(!1),i=Ee(t,s.onScrollButtonChange);return Xe(()=>{if(r.viewport&&r.isPositioned){let c=function(){const d=l.scrollHeight-l.clientHeight,m=Math.ceil(l.scrollTop)<d;a(m)};const l=r.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),o?n.jsx(mm,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});hk.displayName=pa;var mm=x.forwardRef((e,t)=>{const{__scopeSelect:r,onAutoScroll:s,...o}=e,a=_n("SelectScrollButton",r),i=x.useRef(null),c=Zs(r),l=x.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return x.useEffect(()=>()=>l(),[l]),Xe(()=>{c().find(m=>m.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),n.jsx(be.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:_e(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(s,50))}),onPointerMove:_e(o.onPointerMove,()=>{a.onItemLeave?.(),i.current===null&&(i.current=window.setInterval(s,50))}),onPointerLeave:_e(o.onPointerLeave,()=>{l()})})}),gk="SelectSeparator",xk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return n.jsx(be.div,{"aria-hidden":!0,...s,ref:t})});xk.displayName=gk;var fa="SelectArrow",yk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Gs(r),a=wn(fa,r),i=_n(fa,r);return a.open&&i.position==="popper"?n.jsx(K_,{...o,...s,ref:t}):null});yk.displayName=fa;var vk="SelectBubbleInput",pm=x.forwardRef(({__scopeSelect:e,value:t,...r},s)=>{const o=x.useRef(null),a=Ee(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(be.select,{...r,style:{...Lu,...r.style},ref:a,defaultValue:t})});pm.displayName=vk;function fm(e){return e===""||e===void 0}function hm(e){const t=mn(e),r=x.useRef(""),s=x.useRef(0),o=x.useCallback(i=>{const c=r.current+i;t(c),(function l(d){r.current=d,window.clearTimeout(s.current),d!==""&&(s.current=window.setTimeout(()=>l(""),1e3))})(c)},[t]),a=x.useCallback(()=>{r.current="",window.clearTimeout(s.current)},[]);return x.useEffect(()=>()=>window.clearTimeout(s.current),[]),[r,o,a]}function gm(e,t,r){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,a=r?e.indexOf(r):-1;let i=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 wk=Zu,xm=Qu,_k=Ku,jk=Xu,kk=Ju,ym=em,Sk=sm,Ck=am,vm=lm,Nk=dm;const Ns=wk,Pk=Ck,Ps=_k,Or=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(xm,{ref:s,className:H("flex h-10 w-full items-center justify-between rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:focus-visible:ring-neutral-50/20",e),...r,children:[t,n.jsx(jk,{className:"ml-2 text-neutral-500 dark:text-neutral-400",children:"▾"})]}));Or.displayName=xm.displayName;const Mr=x.forwardRef(({className:e,children:t,position:r="popper",...s},o)=>n.jsx(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})})}));Mr.displayName=ym.displayName;const Dr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(vm,{ref:s,className:H("relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-neutral-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-neutral-800",e),...r,children:n.jsx(Nk,{children:t})}));Dr.displayName=vm.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=Ee(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=rs(s.current);a.current=c==="mounted"?d:"none"},[c]),Xe(()=>{const d=s.current,m=o.current;if(m!==e){const p=a.current,h=rs(d);e?l("MOUNT"):h==="none"||d?.display==="none"?l("UNMOUNT"):l(m&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Xe(()=>{if(t){let d;const m=t.ownerDocument.defaultView??window,u=h=>{const g=rs(s.current).includes(CSS.escape(h.animationName));if(h.target===t&&g&&(l("ANIMATION_END"),!o.current)){const f=t.style.animationFillMode;t.style.animationFillMode="forwards",d=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=f)})}},p=h=>{h.target===t&&(a.current=rs(s.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{m.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:x.useCallback(d=>{s.current=d?getComputedStyle(d):null,r(d)},[])}}function rs(e){return e?.animationName||"none"}function 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 Qs="Dialog",[bm]=bn(Qs),[$k,Lt]=bm(Qs),wm=e=>{const{__scopeDialog:t,children:r,open:s,defaultOpen:o,onOpenChange:a,modal:i=!0}=e,c=x.useRef(null),l=x.useRef(null),[d,m]=hn({prop:s,defaultProp:o??!1,onChange:a,caller:Qs});return n.jsx($k,{scope:t,triggerRef:c,contentRef:l,contentId:qt(),titleId:qt(),descriptionId:qt(),open:d,onOpenChange:m,onOpenToggle:x.useCallback(()=>m(u=>!u),[m]),modal:i,children:r})};wm.displayName=Qs;var _m="DialogTrigger",jm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(_m,r),a=Ee(t,o.triggerRef);return n.jsx(be.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":mi(o.open),...s,ref:a,onClick:_e(e.onClick,o.onOpenToggle)})});jm.displayName=_m;var di="DialogPortal",[zk,km]=bm(di,{forceMount:void 0}),Sm=e=>{const{__scopeDialog:t,forceMount:r,children:s,container:o}=e,a=Lt(di,t);return n.jsx(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})}))})};Sm.displayName=di;var As="DialogOverlay",Cm=x.forwardRef((e,t)=>{const r=km(As,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Lt(As,e.__scopeDialog);return a.modal?n.jsx(mr,{present:s||a.open,children:n.jsx(Bk,{...o,ref:t})}):null});Cm.displayName=As;var Fk=Ik("DialogOverlay.RemoveScroll"),Bk=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(As,r);return n.jsx(ci,{as:Fk,allowPinchZoom:!0,shards:[o.contentRef],children:n.jsx(be.div,{"data-state":mi(o.open),...s,ref:t,style:{pointerEvents:"auto",...s.style}})})}),On="DialogContent",Nm=x.forwardRef((e,t)=>{const r=km(On,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=Lt(On,e.__scopeDialog);return n.jsx(mr,{present:s||a.open,children:a.modal?n.jsx(Uk,{...o,ref:t}):n.jsx(Wk,{...o,ref:t})})});Nm.displayName=On;var Uk=x.forwardRef((e,t)=>{const r=Lt(On,e.__scopeDialog),s=x.useRef(null),o=Ee(t,r.contentRef,s);return x.useEffect(()=>{const a=s.current;if(a)return zu(a)},[]),n.jsx(Pm,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:_e(e.onCloseAutoFocus,a=>{a.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:_e(e.onPointerDownOutside,a=>{const i=a.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&a.preventDefault()}),onFocusOutside:_e(e.onFocusOutside,a=>a.preventDefault())})}),Wk=x.forwardRef((e,t)=>{const r=Lt(On,e.__scopeDialog),s=x.useRef(!1),o=x.useRef(!1);return n.jsx(Pm,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(s.current||r.triggerRef.current?.focus(),a.preventDefault()),s.current=!1,o.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(s.current=!0,a.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=a.target;r.triggerRef.current?.contains(i)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&o.current&&a.preventDefault()}})}),Pm=x.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,...i}=e,c=Lt(On,r),l=x.useRef(null),d=Ee(t,l);return pu(),n.jsxs(n.Fragment,{children:[n.jsx(Xa,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:o,onUnmountAutoFocus:a,children:n.jsx(Ka,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":mi(c.open),...i,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),n.jsxs(n.Fragment,{children:[n.jsx(Vk,{titleId:c.titleId}),n.jsx(Hk,{contentRef:l,descriptionId:c.descriptionId})]})]})}),ui="DialogTitle",Am=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(ui,r);return n.jsx(be.h2,{id:o.titleId,...s,ref:t})});Am.displayName=ui;var Em="DialogDescription",Tm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(Em,r);return n.jsx(be.p,{id:o.descriptionId,...s,ref:t})});Tm.displayName=Em;var Im="DialogClose",Rm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=Lt(Im,r);return n.jsx(be.button,{type:"button",...s,ref:t,onClick:_e(e.onClick,()=>o.onOpenChange(!1))})});Rm.displayName=Im;function mi(e){return e?"open":"closed"}var Om="DialogTitleWarning",[mN,Mm]=Y0(Om,{contentName:On,titleName:ui,docsSlug:"dialog"}),Vk=({titleId:e})=>{const t=Mm(Om),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
131
|
+
`)},tk=0,Yn=[];function nk(e){var t=x.useRef([]),r=x.useRef([0,0]),s=x.useRef(),o=x.useState(tk++)[0],a=x.useState(Hu)[0],i=x.useRef(e);x.useEffect(function(){i.current=e},[e]),x.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var g=jj([e.lockRef.current],(e.shards||[]).map(dl),!0).filter(Boolean);return g.forEach(function(f){return f.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),g.forEach(function(f){return f.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var c=x.useCallback(function(g,f){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!i.current.allowPinchZoom;var w=rs(g),j=r.current,b="deltaX"in g?g.deltaX:j[0]-w[0],v="deltaY"in g?g.deltaY:j[1]-w[1],k,R=g.target,N=Math.abs(b)>Math.abs(v)?"h":"v";if("touches"in g&&N==="h"&&R.type==="range")return!1;var C=window.getSelection(),T=C&&C.anchorNode,O=T?T===R||T.contains(R):!1;if(O)return!1;var $=cl(N,R);if(!$)return!0;if($?k=N:(k=N==="v"?"h":"v",$=cl(N,R)),!$)return!1;if(!s.current&&"changedTouches"in g&&(b||v)&&(s.current=k),!k)return!0;var S=s.current||k;return Xj(S,f,g,S==="h"?b:v)},[]),l=x.useCallback(function(g){var f=g;if(!(!Yn.length||Yn[Yn.length-1]!==a)){var w="deltaY"in f?ll(f):rs(f),j=t.current.filter(function(k){return k.name===f.type&&(k.target===f.target||f.target===k.shadowParent)&&Jj(k.delta,w)})[0];if(j&&j.should){f.cancelable&&f.preventDefault();return}if(!j){var b=(i.current.shards||[]).map(dl).filter(Boolean).filter(function(k){return k.contains(f.target)}),v=b.length>0?c(f,b[0]):!i.current.noIsolation;v&&f.cancelable&&f.preventDefault()}}},[]),d=x.useCallback(function(g,f,w,j){var b={name:g,delta:f,target:w,should:j,shadowParent:rk(w)};t.current.push(b),setTimeout(function(){t.current=t.current.filter(function(v){return v!==b})},1)},[]),m=x.useCallback(function(g){r.current=rs(g),s.current=void 0},[]),u=x.useCallback(function(g){d(g.type,ll(g),g.target,c(g,e.lockRef.current))},[]),p=x.useCallback(function(g){d(g.type,rs(g),g.target,c(g,e.lockRef.current))},[]);x.useEffect(function(){return Yn.push(a),e.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:p}),document.addEventListener("wheel",l,Qn),document.addEventListener("touchmove",l,Qn),document.addEventListener("touchstart",m,Qn),function(){Yn=Yn.filter(function(g){return g!==a}),document.removeEventListener("wheel",l,Qn),document.removeEventListener("touchmove",l,Qn),document.removeEventListener("touchstart",m,Qn)}},[]);var h=e.removeScrollBar,_=e.inert;return x.createElement(x.Fragment,null,_?x.createElement(a,{styles:ek(o)}):null,h?x.createElement(qj,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function rk(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const sk=Ij(qu,nk);var li=x.forwardRef(function(e,t){return x.createElement(Hs,Vt({},e,{ref:t,sideCar:sk}))});li.classNames=Hs.classNames;var ok=[" ","Enter","ArrowUp","ArrowDown"],ak=[" ","Enter"],Rn="Select",[Zs,Gs,ik]=Ka(Rn),[mr]=wn(Rn,[ik,Tu]),Qs=Tu(),[ck,_n]=mr(Rn),[lk,dk]=mr(Rn),Yu=e=>{const{__scopeSelect:t,children:r,open:s,defaultOpen:o,onOpenChange:a,value:i,defaultValue:c,onValueChange:l,dir:d,name:m,autoComplete:u,disabled:p,required:h,form:_}=e,g=Qs(t),[f,w]=x.useState(null),[j,b]=x.useState(null),[v,k]=x.useState(!1),R=Bs(d),[N,C]=gn({prop:s,defaultProp:o??!1,onChange:a,caller:Rn}),[T,O]=gn({prop:i,defaultProp:c,onChange:l,caller:Rn}),$=x.useRef(null),S=f?_||!!f.closest("form"):!0,[A,I]=x.useState(new Set),B=Array.from(A).map(L=>L.props.value).join(";");return n.jsx(rj,{...g,children:n.jsxs(ck,{required:h,scope:t,trigger:f,onTriggerChange:w,valueNode:j,onValueNodeChange:b,valueNodeHasChildren:v,onValueNodeHasChildrenChange:k,contentId:Ht(),value:T,onValueChange:O,open:N,onOpenChange:C,dir:R,triggerPointerDownPosRef:$,disabled:p,children:[n.jsx(Zs.Provider,{scope:t,children:n.jsx(lk,{scope:e.__scopeSelect,onNativeOptionAdd:x.useCallback(L=>{I(E=>new Set(E).add(L))},[]),onNativeOptionRemove:x.useCallback(L=>{I(E=>{const P=new Set(E);return P.delete(L),P})},[]),children:r})}),S?n.jsxs(gm,{"aria-hidden":!0,required:h,tabIndex:-1,name:m,autoComplete:u,value:T,onChange:L=>O(L.target.value),disabled:p,form:_,children:[T===void 0?n.jsx("option",{value:""}):null,Array.from(A)]},B):null]})})};Yu.displayName=Rn;var Ku="SelectTrigger",Xu=x.forwardRef((e,t)=>{const{__scopeSelect:r,disabled:s=!1,...o}=e,a=Qs(r),i=_n(Ku,r),c=i.disabled||s,l=Ee(t,i.onTriggerChange),d=Gs(r),m=x.useRef("touch"),[u,p,h]=ym(g=>{const f=d().filter(b=>!b.disabled),w=f.find(b=>b.value===i.value),j=vm(f,g,w);j!==void 0&&i.onValueChange(j.value)}),_=g=>{c||(i.onOpenChange(!0),h()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return n.jsx(sj,{asChild:!0,...a,children:n.jsx(be.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":xm(i.value)?"":void 0,...o,ref:l,onClick:_e(o.onClick,g=>{g.currentTarget.focus(),m.current!=="mouse"&&_(g)}),onPointerDown:_e(o.onPointerDown,g=>{m.current=g.pointerType;const f=g.target;f.hasPointerCapture(g.pointerId)&&f.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(_(g),g.preventDefault())}),onKeyDown:_e(o.onKeyDown,g=>{const f=u.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&p(g.key),!(f&&g.key===" ")&&ok.includes(g.key)&&(_(),g.preventDefault())})})})});Xu.displayName=Ku;var Ju="SelectValue",em=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,children:a,placeholder:i="",...c}=e,l=_n(Ju,r),{onValueNodeHasChildrenChange:d}=l,m=a!==void 0,u=Ee(t,l.onValueNodeChange);return Je(()=>{d(m)},[d,m]),n.jsx(be.span,{...c,ref:u,style:{pointerEvents:"none"},children:xm(l.value)?n.jsx(n.Fragment,{children:i}):a})});em.displayName=Ju;var uk="SelectIcon",tm=x.forwardRef((e,t)=>{const{__scopeSelect:r,children:s,...o}=e;return n.jsx(be.span,{"aria-hidden":!0,...o,ref:t,children:s||"▼"})});tm.displayName=uk;var mk="SelectPortal",nm=e=>n.jsx(ci,{asChild:!0,...e});nm.displayName=mk;var On="SelectContent",rm=x.forwardRef((e,t)=>{const r=_n(On,e.__scopeSelect),[s,o]=x.useState();if(Je(()=>{o(new DocumentFragment)},[]),!r.open){const a=s;return a?Rs.createPortal(n.jsx(sm,{scope:e.__scopeSelect,children:n.jsx(Zs.Slot,{scope:e.__scopeSelect,children:n.jsx("div",{children:e.children})})}),a):null}return n.jsx(om,{...e,ref:t})});rm.displayName=On;var It=10,[sm,jn]=mr(On),pk="SelectContentImpl",fk=cj("SelectContent.RemoveScroll"),om=x.forwardRef((e,t)=>{const{__scopeSelect:r,position:s="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:a,onPointerDownOutside:i,side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:p,collisionPadding:h,sticky:_,hideWhenDetached:g,avoidCollisions:f,...w}=e,j=_n(On,r),[b,v]=x.useState(null),[k,R]=x.useState(null),N=Ee(t,F=>v(F)),[C,T]=x.useState(null),[O,$]=x.useState(null),S=Gs(r),[A,I]=x.useState(!1),B=x.useRef(!1);x.useEffect(()=>{if(b)return Uu(b)},[b]),gu();const L=x.useCallback(F=>{const[ee,...pe]=S().map(le=>le.ref.current),[q]=pe.slice(-1),ne=document.activeElement;for(const le of F)if(le===ne||(le?.scrollIntoView({block:"nearest"}),le===ee&&k&&(k.scrollTop=0),le===q&&k&&(k.scrollTop=k.scrollHeight),le?.focus(),document.activeElement!==ne))return},[S,k]),E=x.useCallback(()=>L([C,b]),[L,C,b]);x.useEffect(()=>{A&&E()},[A,E]);const{onOpenChange:P,triggerPointerDownPosRef:z}=j;x.useEffect(()=>{if(b){let F={x:0,y:0};const ee=q=>{F={x:Math.abs(Math.round(q.pageX)-(z.current?.x??0)),y:Math.abs(Math.round(q.pageY)-(z.current?.y??0))}},pe=q=>{F.x<=10&&F.y<=10?q.preventDefault():b.contains(q.target)||P(!1),document.removeEventListener("pointermove",ee),z.current=null};return z.current!==null&&(document.addEventListener("pointermove",ee),document.addEventListener("pointerup",pe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ee),document.removeEventListener("pointerup",pe,{capture:!0})}}},[b,P,z]),x.useEffect(()=>{const F=()=>P(!1);return window.addEventListener("blur",F),window.addEventListener("resize",F),()=>{window.removeEventListener("blur",F),window.removeEventListener("resize",F)}},[P]);const[Z,K]=ym(F=>{const ee=S().filter(ne=>!ne.disabled),pe=ee.find(ne=>ne.ref.current===document.activeElement),q=vm(ee,F,pe);q&&setTimeout(()=>q.ref.current.focus())}),D=x.useCallback((F,ee,pe)=>{const q=!B.current&&!pe;(j.value!==void 0&&j.value===ee||q)&&(T(F),q&&(B.current=!0))},[j.value]),W=x.useCallback(()=>b?.focus(),[b]),Y=x.useCallback((F,ee,pe)=>{const q=!B.current&&!pe;(j.value!==void 0&&j.value===ee||q)&&$(F)},[j.value]),V=s==="popper"?ua:am,ce=V===ua?{side:c,sideOffset:l,align:d,alignOffset:m,arrowPadding:u,collisionBoundary:p,collisionPadding:h,sticky:_,hideWhenDetached:g,avoidCollisions:f}:{};return n.jsx(sm,{scope:r,content:b,viewport:k,onViewportChange:R,itemRefCallback:D,selectedItem:C,onItemLeave:W,itemTextRefCallback:Y,focusSelectedItem:E,selectedItemText:O,position:s,isPositioned:A,searchRef:Z,children:n.jsx(li,{as:fk,allowPinchZoom:!0,children:n.jsx(Ja,{asChild:!0,trapped:j.open,onMountAutoFocus:F=>{F.preventDefault()},onUnmountAutoFocus:_e(o,F=>{j.trigger?.focus({preventScroll:!0}),F.preventDefault()}),children:n.jsx(Xa,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:F=>F.preventDefault(),onDismiss:()=>j.onOpenChange(!1),children:n.jsx(V,{role:"listbox",id:j.contentId,"data-state":j.open?"open":"closed",dir:j.dir,onContextMenu:F=>F.preventDefault(),...w,...ce,onPlaced:()=>I(!0),ref:N,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:_e(w.onKeyDown,F=>{const ee=F.ctrlKey||F.altKey||F.metaKey;if(F.key==="Tab"&&F.preventDefault(),!ee&&F.key.length===1&&K(F.key),["ArrowUp","ArrowDown","Home","End"].includes(F.key)){let q=S().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);if(["ArrowUp","End"].includes(F.key)&&(q=q.slice().reverse()),["ArrowUp","ArrowDown"].includes(F.key)){const ne=F.target,le=q.indexOf(ne);q=q.slice(le+1)}setTimeout(()=>L(q)),F.preventDefault()}})})})})})})});om.displayName=pk;var hk="SelectItemAlignedPosition",am=x.forwardRef((e,t)=>{const{__scopeSelect:r,onPlaced:s,...o}=e,a=_n(On,r),i=jn(On,r),[c,l]=x.useState(null),[d,m]=x.useState(null),u=Ee(t,N=>m(N)),p=Gs(r),h=x.useRef(!1),_=x.useRef(!0),{viewport:g,selectedItem:f,selectedItemText:w,focusSelectedItem:j}=i,b=x.useCallback(()=>{if(a.trigger&&a.valueNode&&c&&d&&g&&f&&w){const N=a.trigger.getBoundingClientRect(),C=d.getBoundingClientRect(),T=a.valueNode.getBoundingClientRect(),O=w.getBoundingClientRect();if(a.dir!=="rtl"){const ne=O.left-C.left,le=T.left-ne,fe=N.left-le,Pe=N.width+fe,qe=Math.max(Pe,C.width),He=window.innerWidth-It,Ze=Fc(le,[It,Math.max(It,He-qe)]);c.style.minWidth=Pe+"px",c.style.left=Ze+"px"}else{const ne=C.right-O.right,le=window.innerWidth-T.right-ne,fe=window.innerWidth-N.right-le,Pe=N.width+fe,qe=Math.max(Pe,C.width),He=window.innerWidth-It,Ze=Fc(le,[It,Math.max(It,He-qe)]);c.style.minWidth=Pe+"px",c.style.right=Ze+"px"}const $=p(),S=window.innerHeight-It*2,A=g.scrollHeight,I=window.getComputedStyle(d),B=parseInt(I.borderTopWidth,10),L=parseInt(I.paddingTop,10),E=parseInt(I.borderBottomWidth,10),P=parseInt(I.paddingBottom,10),z=B+L+A+P+E,Z=Math.min(f.offsetHeight*5,z),K=window.getComputedStyle(g),D=parseInt(K.paddingTop,10),W=parseInt(K.paddingBottom,10),Y=N.top+N.height/2-It,V=S-Y,ce=f.offsetHeight/2,F=f.offsetTop+ce,ee=B+L+F,pe=z-ee;if(ee<=Y){const ne=$.length>0&&f===$[$.length-1].ref.current;c.style.bottom="0px";const le=d.clientHeight-g.offsetTop-g.offsetHeight,fe=Math.max(V,ce+(ne?W:0)+le+E),Pe=ee+fe;c.style.height=Pe+"px"}else{const ne=$.length>0&&f===$[0].ref.current;c.style.top="0px";const fe=Math.max(Y,B+g.offsetTop+(ne?D:0)+ce)+pe;c.style.height=fe+"px",g.scrollTop=ee-Y+g.offsetTop}c.style.margin=`${It}px 0`,c.style.minHeight=Z+"px",c.style.maxHeight=S+"px",s?.(),requestAnimationFrame(()=>h.current=!0)}},[p,a.trigger,a.valueNode,c,d,g,f,w,a.dir,s]);Je(()=>b(),[b]);const[v,k]=x.useState();Je(()=>{d&&k(window.getComputedStyle(d).zIndex)},[d]);const R=x.useCallback(N=>{N&&_.current===!0&&(b(),j?.(),_.current=!1)},[b,j]);return n.jsx(xk,{scope:r,contentWrapper:c,shouldExpandOnScrollRef:h,onScrollButtonChange:R,children:n.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:v},children:n.jsx(be.div,{...o,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});am.displayName=hk;var gk="SelectPopperPosition",ua=x.forwardRef((e,t)=>{const{__scopeSelect:r,align:s="start",collisionPadding:o=It,...a}=e,i=Qs(r);return n.jsx(oj,{...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)"}})});ua.displayName=gk;var[xk,di]=mr(On,{}),ma="SelectViewport",im=x.forwardRef((e,t)=>{const{__scopeSelect:r,nonce:s,...o}=e,a=jn(ma,r),i=di(ma,r),c=Ee(t,a.onViewportChange),l=x.useRef(0);return n.jsxs(n.Fragment,{children:[n.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),n.jsx(Zs.Slot,{scope:r,children:n.jsx(be.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:_e(o.onScroll,d=>{const m=d.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:p}=i;if(p?.current&&u){const h=Math.abs(l.current-m.scrollTop);if(h>0){const _=window.innerHeight-It*2,g=parseFloat(u.style.minHeight),f=parseFloat(u.style.height),w=Math.max(g,f);if(w<_){const j=w+h,b=Math.min(_,j),v=j-b;u.style.height=b+"px",u.style.bottom==="0px"&&(m.scrollTop=v>0?v:0,u.style.justifyContent="flex-end")}}}l.current=m.scrollTop})})})]})});im.displayName=ma;var cm="SelectGroup",[yk,vk]=mr(cm),lm=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Ht();return n.jsx(yk,{scope:r,id:o,children:n.jsx(be.div,{role:"group","aria-labelledby":o,...s,ref:t})})});lm.displayName=cm;var dm="SelectLabel",bk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=vk(dm,r);return n.jsx(be.div,{id:o.id,...s,ref:t})});bk.displayName=dm;var Ns="SelectItem",[wk,um]=mr(Ns),mm=x.forwardRef((e,t)=>{const{__scopeSelect:r,value:s,disabled:o=!1,textValue:a,...i}=e,c=_n(Ns,r),l=jn(Ns,r),d=c.value===s,[m,u]=x.useState(a??""),[p,h]=x.useState(!1),_=Ee(t,j=>l.itemRefCallback?.(j,s,o)),g=Ht(),f=x.useRef("touch"),w=()=>{o||(c.onValueChange(s),c.onOpenChange(!1))};if(s==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return n.jsx(wk,{scope:r,value:s,disabled:o,textId:g,isSelected:d,onItemTextChange:x.useCallback(j=>{u(b=>b||(j?.textContent??"").trim())},[]),children:n.jsx(Zs.ItemSlot,{scope:r,value:s,disabled:o,textValue:m,children:n.jsx(be.div,{role:"option","aria-labelledby":g,"data-highlighted":p?"":void 0,"aria-selected":d&&p,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:_,onFocus:_e(i.onFocus,()=>h(!0)),onBlur:_e(i.onBlur,()=>h(!1)),onClick:_e(i.onClick,()=>{f.current!=="mouse"&&w()}),onPointerUp:_e(i.onPointerUp,()=>{f.current==="mouse"&&w()}),onPointerDown:_e(i.onPointerDown,j=>{f.current=j.pointerType}),onPointerMove:_e(i.onPointerMove,j=>{f.current=j.pointerType,o?l.onItemLeave?.():f.current==="mouse"&&j.currentTarget.focus({preventScroll:!0})}),onPointerLeave:_e(i.onPointerLeave,j=>{j.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:_e(i.onKeyDown,j=>{l.searchRef?.current!==""&&j.key===" "||(ak.includes(j.key)&&w(),j.key===" "&&j.preventDefault())})})})})});mm.displayName=Ns;var kr="SelectItemText",pm=x.forwardRef((e,t)=>{const{__scopeSelect:r,className:s,style:o,...a}=e,i=_n(kr,r),c=jn(kr,r),l=um(kr,r),d=dk(kr,r),[m,u]=x.useState(null),p=Ee(t,w=>u(w),l.onItemTextChange,w=>c.itemTextRefCallback?.(w,l.value,l.disabled)),h=m?.textContent,_=x.useMemo(()=>n.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:g,onNativeOptionRemove:f}=d;return Je(()=>(g(_),()=>f(_)),[g,f,_]),n.jsxs(n.Fragment,{children:[n.jsx(be.span,{id:l.textId,...a,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Rs.createPortal(a.children,i.valueNode):null]})});pm.displayName=kr;var fm="SelectItemIndicator",_k=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return um(fm,r).isSelected?n.jsx(be.span,{"aria-hidden":!0,...s,ref:t}):null});_k.displayName=fm;var pa="SelectScrollUpButton",jk=x.forwardRef((e,t)=>{const r=jn(pa,e.__scopeSelect),s=di(pa,e.__scopeSelect),[o,a]=x.useState(!1),i=Ee(t,s.onScrollButtonChange);return Je(()=>{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(hm,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});jk.displayName=pa;var fa="SelectScrollDownButton",kk=x.forwardRef((e,t)=>{const r=jn(fa,e.__scopeSelect),s=di(fa,e.__scopeSelect),[o,a]=x.useState(!1),i=Ee(t,s.onScrollButtonChange);return Je(()=>{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(hm,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=r;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});kk.displayName=fa;var hm=x.forwardRef((e,t)=>{const{__scopeSelect:r,onAutoScroll:s,...o}=e,a=jn("SelectScrollButton",r),i=x.useRef(null),c=Gs(r),l=x.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return x.useEffect(()=>()=>l(),[l]),Je(()=>{c().find(m=>m.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),n.jsx(be.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:_e(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(s,50))}),onPointerMove:_e(o.onPointerMove,()=>{a.onItemLeave?.(),i.current===null&&(i.current=window.setInterval(s,50))}),onPointerLeave:_e(o.onPointerLeave,()=>{l()})})}),Sk="SelectSeparator",Ck=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e;return n.jsx(be.div,{"aria-hidden":!0,...s,ref:t})});Ck.displayName=Sk;var ha="SelectArrow",Nk=x.forwardRef((e,t)=>{const{__scopeSelect:r,...s}=e,o=Qs(r),a=_n(ha,r),i=jn(ha,r);return a.open&&i.position==="popper"?n.jsx(aj,{...o,...s,ref:t}):null});Nk.displayName=ha;var Pk="SelectBubbleInput",gm=x.forwardRef(({__scopeSelect:e,value:t,...r},s)=>{const o=x.useRef(null),a=Ee(s,o),i=xj(t);return x.useEffect(()=>{const c=o.current;if(!c)return;const l=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&m){const u=new Event("change",{bubbles:!0});m.call(c,t),c.dispatchEvent(u)}},[i,t]),n.jsx(be.select,{...r,style:{...Fu,...r.style},ref:a,defaultValue:t})});gm.displayName=Pk;function xm(e){return e===""||e===void 0}function ym(e){const t=pn(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 vm(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=Ak(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 Ak(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var Ek=Yu,bm=Xu,Tk=em,Ik=tm,Rk=nm,wm=rm,Ok=im,Mk=lm,_m=mm,Lk=pm;const Ps=Ek,Dk=Mk,As=Tk,Mr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(bm,{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(Ik,{className:"ml-2 text-neutral-500 dark:text-neutral-400",children:"▾"})]}));Mr.displayName=bm.displayName;const Lr=x.forwardRef(({className:e,children:t,position:r="popper",...s},o)=>n.jsx(Rk,{children:n.jsx(wm,{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(Ok,{className:H("p-1",r==="popper"?"w-full":void 0),children:t})})}));Lr.displayName=wm.displayName;const Dr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(_m,{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(Lk,{children:t})}));Dr.displayName=_m.displayName;function $k(e,t){return x.useReducer((r,s)=>t[r][s]??r,e)}var pr=e=>{const{present:t,children:r}=e,s=zk(t),o=typeof r=="function"?r({present:s.isPresent}):x.Children.only(r),a=Ee(s.ref,Fk(o));return typeof r=="function"||s.isPresent?x.cloneElement(o,{ref:a}):null};pr.displayName="Presence";function zk(e){const[t,r]=x.useState(),s=x.useRef(null),o=x.useRef(e),a=x.useRef("none"),i=e?"mounted":"unmounted",[c,l]=$k(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return x.useEffect(()=>{const d=ss(s.current);a.current=c==="mounted"?d:"none"},[c]),Je(()=>{const d=s.current,m=o.current;if(m!==e){const p=a.current,h=ss(d);e?l("MOUNT"):h==="none"||d?.display==="none"?l("UNMOUNT"):l(m&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Je(()=>{if(t){let d;const m=t.ownerDocument.defaultView??window,u=h=>{const g=ss(s.current).includes(CSS.escape(h.animationName));if(h.target===t&&g&&(l("ANIMATION_END"),!o.current)){const f=t.style.animationFillMode;t.style.animationFillMode="forwards",d=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=f)})}},p=h=>{h.target===t&&(a.current=ss(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 ss(e){return e?.animationName||"none"}function Fk(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 Bk(e){const t=Uk(e),r=x.forwardRef((s,o)=>{const{children:a,...i}=s,c=x.Children.toArray(a),l=c.find(Vk);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 Uk(e){const t=x.forwardRef((r,s)=>{const{children:o,...a}=r;if(x.isValidElement(o)){const i=Hk(o),c=qk(a,o.props);return o.type!==x.Fragment&&(c.ref=s?ir(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 Wk=Symbol("radix.slottable");function Vk(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Wk}function qk(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 Hk(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 Ys="Dialog",[jm]=wn(Ys),[Zk,$t]=jm(Ys),km=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]=gn({prop:s,defaultProp:o??!1,onChange:a,caller:Ys});return n.jsx(Zk,{scope:t,triggerRef:c,contentRef:l,contentId:Ht(),titleId:Ht(),descriptionId:Ht(),open:d,onOpenChange:m,onOpenToggle:x.useCallback(()=>m(u=>!u),[m]),modal:i,children:r})};km.displayName=Ys;var Sm="DialogTrigger",Cm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=$t(Sm,r),a=Ee(t,o.triggerRef);return n.jsx(be.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":pi(o.open),...s,ref:a,onClick:_e(e.onClick,o.onOpenToggle)})});Cm.displayName=Sm;var ui="DialogPortal",[Gk,Nm]=jm(ui,{forceMount:void 0}),Pm=e=>{const{__scopeDialog:t,forceMount:r,children:s,container:o}=e,a=$t(ui,t);return n.jsx(Gk,{scope:t,forceMount:r,children:x.Children.map(s,i=>n.jsx(pr,{present:r||a.open,children:n.jsx(ci,{asChild:!0,container:o,children:i})}))})};Pm.displayName=ui;var Es="DialogOverlay",Am=x.forwardRef((e,t)=>{const r=Nm(Es,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=$t(Es,e.__scopeDialog);return a.modal?n.jsx(pr,{present:s||a.open,children:n.jsx(Yk,{...o,ref:t})}):null});Am.displayName=Es;var Qk=Bk("DialogOverlay.RemoveScroll"),Yk=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=$t(Es,r);return n.jsx(li,{as:Qk,allowPinchZoom:!0,shards:[o.contentRef],children:n.jsx(be.div,{"data-state":pi(o.open),...s,ref:t,style:{pointerEvents:"auto",...s.style}})})}),Mn="DialogContent",Em=x.forwardRef((e,t)=>{const r=Nm(Mn,e.__scopeDialog),{forceMount:s=r.forceMount,...o}=e,a=$t(Mn,e.__scopeDialog);return n.jsx(pr,{present:s||a.open,children:a.modal?n.jsx(Kk,{...o,ref:t}):n.jsx(Xk,{...o,ref:t})})});Em.displayName=Mn;var Kk=x.forwardRef((e,t)=>{const r=$t(Mn,e.__scopeDialog),s=x.useRef(null),o=Ee(t,r.contentRef,s);return x.useEffect(()=>{const a=s.current;if(a)return Uu(a)},[]),n.jsx(Tm,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:_e(e.onCloseAutoFocus,a=>{a.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:_e(e.onPointerDownOutside,a=>{const i=a.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&a.preventDefault()}),onFocusOutside:_e(e.onFocusOutside,a=>a.preventDefault())})}),Xk=x.forwardRef((e,t)=>{const r=$t(Mn,e.__scopeDialog),s=x.useRef(!1),o=x.useRef(!1);return n.jsx(Tm,{...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()}})}),Tm=x.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,...i}=e,c=$t(Mn,r),l=x.useRef(null),d=Ee(t,l);return gu(),n.jsxs(n.Fragment,{children:[n.jsx(Ja,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:o,onUnmountAutoFocus:a,children:n.jsx(Xa,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":pi(c.open),...i,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),n.jsxs(n.Fragment,{children:[n.jsx(Jk,{titleId:c.titleId}),n.jsx(tS,{contentRef:l,descriptionId:c.descriptionId})]})]})}),mi="DialogTitle",Im=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=$t(mi,r);return n.jsx(be.h2,{id:o.titleId,...s,ref:t})});Im.displayName=mi;var Rm="DialogDescription",Om=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=$t(Rm,r);return n.jsx(be.p,{id:o.descriptionId,...s,ref:t})});Om.displayName=Rm;var Mm="DialogClose",Lm=x.forwardRef((e,t)=>{const{__scopeDialog:r,...s}=e,o=$t(Mm,r);return n.jsx(be.button,{type:"button",...s,ref:t,onClick:_e(e.onClick,()=>o.onOpenChange(!1))})});Lm.displayName=Mm;function pi(e){return e?"open":"closed"}var Dm="DialogTitleWarning",[wN,$m]=ow(Dm,{contentName:Mn,titleName:mi,docsSlug:"dialog"}),Jk=({titleId:e})=>{const t=$m(Dm),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
132
132
|
|
|
133
133
|
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
134
134
|
|
|
135
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return x.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},qk="DialogDescriptionWarning",Hk=({contentRef:e,descriptionId:t})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Mm(qk).contentName}}.`;return x.useEffect(()=>{const o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(s))},[s,e,t]),null},Dm=wm,Lm=jm,$m=Sm,Ys=Cm,Ks=Nm,Xs=Am,Js=Tm,zm=Rm;const pi=Dm,Zk=Lm,Fm=$m,Gk=zm,fi=x.forwardRef(({className:e,...t},r)=>n.jsx(Ys,{ref:r,className:H("fixed inset-0 z-50 bg-neutral-950/40 backdrop-blur-sm transition-opacity data-[state=closed]:opacity-0 data-[state=open]:opacity-100",e),...t}));fi.displayName=Ys.displayName;const eo=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(Fm,{children:[n.jsx(fi,{}),n.jsx(Ks,{ref:s,className:H("fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border border-neutral-200 bg-white p-6 shadow-lg outline-none transition data-[state=closed]:opacity-0 data-[state=closed]:scale-95 data-[state=open]:opacity-100 data-[state=open]:scale-100 dark:border-neutral-800 dark:bg-neutral-950","rounded-2xl",e),...r,children:t})]}));eo.displayName=Ks.displayName;const hi=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-center sm:text-left",e),...t}),Bm=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t}),to=x.forwardRef(({className:e,...t},r)=>n.jsx(Xs,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));to.displayName=Xs.displayName;const gi=x.forwardRef(({className:e,...t},r)=>n.jsx(Js,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));gi.displayName=Js.displayName;const no=Dm,ro=Lm,Um=zm,Wm=$m,xi=x.forwardRef(({className:e,...t},r)=>n.jsx(Ys,{ref:r,className:H("fixed inset-0 z-50 bg-neutral-950/40 backdrop-blur-sm transition-opacity data-[state=closed]:opacity-0 data-[state=open]:opacity-100",e),...t}));xi.displayName=Ys.displayName;const 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"}}),Fr=x.forwardRef(({side:e="right",className:t,children:r,overlayClassName:s,...o},a)=>n.jsxs(Wm,{children:[n.jsx(xi,{className:s}),n.jsx(Ks,{ref:a,className:H(Qk({side:e}),t),...o,children:r})]}));Fr.displayName=Ks.displayName;const so=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-left",e),...t}),oo=x.forwardRef(({className:e,...t},r)=>n.jsx(Xs,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));oo.displayName=Xs.displayName;const Vm=x.forwardRef(({className:e,...t},r)=>n.jsx(Js,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));Vm.displayName=Js.displayName;var ao="Collapsible",[Yk,qm]=bn(ao),[Kk,yi]=Yk(ao),Hm=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:s,defaultOpen:o,disabled:a,onOpenChange:i,...c}=e,[l,d]=hn({prop:s,defaultProp:o??!1,onChange:i,caller:ao});return n.jsx(Kk,{scope:r,disabled:a,contentId:qt(),open:l,onOpenToggle:x.useCallback(()=>d(m=>!m),[d]),children:n.jsx(be.div,{"data-state":bi(l),"data-disabled":a?"":void 0,...c,ref:t})})});Hm.displayName=ao;var Zm="CollapsibleTrigger",Gm=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,...s}=e,o=yi(Zm,r);return n.jsx(be.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":bi(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...s,ref:t,onClick:_e(e.onClick,o.onOpenToggle)})});Gm.displayName=Zm;var vi="CollapsibleContent",Qm=x.forwardRef((e,t)=>{const{forceMount:r,...s}=e,o=yi(vi,e.__scopeCollapsible);return n.jsx(mr,{present:r||o.open,children:({present:a})=>n.jsx(Xk,{...s,ref:t,present:a})})});Qm.displayName=vi;var Xk=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:s,children:o,...a}=e,i=yi(vi,r),[c,l]=x.useState(s),d=x.useRef(null),m=Ee(t,d),u=x.useRef(0),p=u.current,h=x.useRef(0),_=h.current,g=i.open||c,f=x.useRef(g),w=x.useRef(void 0);return x.useEffect(()=>{const j=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(j)},[]),Xe(()=>{const j=d.current;if(j){w.current=w.current||{transitionDuration:j.style.transitionDuration,animationName:j.style.animationName},j.style.transitionDuration="0s",j.style.animationName="none";const b=j.getBoundingClientRect();u.current=b.height,h.current=b.width,f.current||(j.style.transitionDuration=w.current.transitionDuration,j.style.animationName=w.current.animationName),l(s)}},[i.open,s]),n.jsx(be.div,{"data-state":bi(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...a,ref:m,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":_?`${_}px`:void 0,...e.style},children:g&&o})});function bi(e){return e?"open":"closed"}var Jk=Hm,eS=Gm,tS=Qm,$t="Accordion",nS=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[wi,rS,sS]=Ya($t),[io]=bn($t,[sS,qm]),_i=qm(),Ym=y.forwardRef((e,t)=>{const{type:r,...s}=e,o=s,a=s;return n.jsx(wi.Provider,{scope:e.__scopeAccordion,children:r==="multiple"?n.jsx(cS,{...a,ref:t}):n.jsx(iS,{...o,ref:t})})});Ym.displayName=$t;var[Km,oS]=io($t),[Xm,aS]=io($t,{collapsible:!1}),iS=y.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},collapsible:a=!1,...i}=e,[c,l]=hn({prop:r,defaultProp:s??"",onChange:o,caller:$t});return n.jsx(Km,{scope:e.__scopeAccordion,value:y.useMemo(()=>c?[c]:[],[c]),onItemOpen:l,onItemClose:y.useCallback(()=>a&&l(""),[a,l]),children:n.jsx(Xm,{scope:e.__scopeAccordion,collapsible:a,children:n.jsx(Jm,{...i,ref:t})})})}),cS=y.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},...a}=e,[i,c]=hn({prop:r,defaultProp:s??[],onChange:o,caller:$t}),l=y.useCallback(m=>c((u=[])=>[...u,m]),[c]),d=y.useCallback(m=>c((u=[])=>u.filter(p=>p!==m)),[c]);return n.jsx(Km,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:d,children:n.jsx(Xm,{scope:e.__scopeAccordion,collapsible:!0,children:n.jsx(Jm,{...a,ref:t})})})}),[lS,co]=io($t),Jm=y.forwardRef((e,t)=>{const{__scopeAccordion:r,disabled:s,dir:o,orientation:a="vertical",...i}=e,c=y.useRef(null),l=Ee(c,t),d=rS(r),u=Fs(o)==="ltr",p=_e(e.onKeyDown,h=>{if(!nS.includes(h.key))return;const _=h.target,g=d().filter(C=>!C.ref.current?.disabled),f=g.findIndex(C=>C.ref.current===_),w=g.length;if(f===-1)return;h.preventDefault();let j=f;const b=0,v=w-1,k=()=>{j=f+1,j>v&&(j=b)},R=()=>{j=f-1,j<b&&(j=v)};switch(h.key){case"Home":j=b;break;case"End":j=v;break;case"ArrowRight":a==="horizontal"&&(u?k():R());break;case"ArrowDown":a==="vertical"&&k();break;case"ArrowLeft":a==="horizontal"&&(u?R():k());break;case"ArrowUp":a==="vertical"&&R();break}const N=j%w;g[N].ref.current?.focus()});return n.jsx(lS,{scope:r,disabled:s,direction:o,orientation:a,children:n.jsx(wi.Slot,{scope:r,children:n.jsx(be.div,{...i,"data-orientation":a,ref:l,onKeyDown:s?void 0:p})})})}),Es="AccordionItem",[dS,ji]=io(Es),ep=y.forwardRef((e,t)=>{const{__scopeAccordion:r,value:s,...o}=e,a=co(Es,r),i=oS(Es,r),c=_i(r),l=qt(),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":ap(d),...c,...o,ref:t,disabled:m,open:d,onOpenChange:u=>{u?i.onItemOpen(s):i.onItemClose(s)}})})});ep.displayName=Es;var tp="AccordionHeader",np=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=co($t,r),a=ji(tp,r);return n.jsx(be.h3,{"data-orientation":o.orientation,"data-state":ap(a.open),"data-disabled":a.disabled?"":void 0,...s,ref:t})});np.displayName=tp;var ha="AccordionTrigger",rp=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=co($t,r),a=ji(ha,r),i=aS(ha,r),c=_i(r);return n.jsx(wi.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})})});rp.displayName=ha;var sp="AccordionContent",op=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=co($t,r),a=ji(sp,r),i=_i(r);return n.jsx(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}})});op.displayName=sp;function ap(e){return e?"open":"closed"}var uS=Ym,ip=ep,mS=np,cp=rp,lp=op;const dp=uS,Sr=x.forwardRef(({className:e,...t},r)=>n.jsx(ip,{ref:r,className:H("border-b border-neutral-200 dark:border-neutral-800",e),...t}));Sr.displayName=ip.displayName;const Cr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(mS,{className:"flex",children:n.jsxs(cp,{ref:s,className:H("flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline",e),...r,children:[t,n.jsx("span",{className:"ml-3 text-neutral-500 dark:text-neutral-400","aria-hidden":!0,children:"▾"})]})}));Cr.displayName=cp.displayName;const Nr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(lp,{ref:s,className:H("overflow-hidden text-sm",e),...r,children:n.jsx("div",{className:"pb-4 pt-0",children:t})}));Nr.displayName=lp.displayName;var Bo="rovingFocusGroup.onEntryFocus",pS={bubbles:!1,cancelable:!0},Br="RovingFocusGroup",[ga,up,fS]=Ya(Br),[hS,mp]=bn(Br,[fS]),[gS,xS]=hS(Br),pp=x.forwardRef((e,t)=>n.jsx(ga.Provider,{scope:e.__scopeRovingFocusGroup,children:n.jsx(ga.Slot,{scope:e.__scopeRovingFocusGroup,children:n.jsx(yS,{...e,ref:t})})}));pp.displayName=Br;var yS=x.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,orientation:s,loop:o=!1,dir:a,currentTabStopId:i,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:m=!1,...u}=e,p=x.useRef(null),h=Ee(t,p),_=Fs(a),[g,f]=hn({prop:i,defaultProp:c??null,onChange:l,caller:Br}),[w,j]=x.useState(!1),b=mn(d),v=up(r),k=x.useRef(!1),[R,N]=x.useState(0);return x.useEffect(()=>{const C=p.current;if(C)return C.addEventListener(Bo,b),()=>C.removeEventListener(Bo,b)},[b]),n.jsx(gS,{scope:r,orientation:s,dir:_,loop:o,currentTabStopId:g,onItemFocus:x.useCallback(C=>f(C),[f]),onItemShiftTab:x.useCallback(()=>j(!0),[]),onFocusableItemAdd:x.useCallback(()=>N(C=>C+1),[]),onFocusableItemRemove:x.useCallback(()=>N(C=>C-1),[]),children:n.jsx(be.div,{tabIndex:w||R===0?-1:0,"data-orientation":s,...u,ref:h,style:{outline:"none",...e.style},onMouseDown:_e(e.onMouseDown,()=>{k.current=!0}),onFocus:_e(e.onFocus,C=>{const T=!k.current;if(C.target===C.currentTarget&&T&&!w){const O=new CustomEvent(Bo,pS);if(C.currentTarget.dispatchEvent(O),!O.defaultPrevented){const $=v().filter(D=>D.focusable),S=$.find(D=>D.active),A=$.find(D=>D.id===g),B=[S,A,...$].filter(Boolean).map(D=>D.ref.current);gp(B,m)}}k.current=!1}),onBlur:_e(e.onBlur,()=>j(!1))})})}),fp="RovingFocusGroupItem",hp=x.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,focusable:s=!0,active:o=!1,tabStopId:a,children:i,...c}=e,l=qt(),d=a||l,m=xS(fp,r),u=m.currentTabStopId===d,p=up(r),{onFocusableItemAdd:h,onFocusableItemRemove:_,currentTabStopId:g}=m;return x.useEffect(()=>{if(s)return h(),()=>_()},[s,h,_]),n.jsx(ga.ItemSlot,{scope:r,id:d,focusable:s,active:o,children:n.jsx(be.span,{tabIndex:u?0:-1,"data-orientation":m.orientation,...c,ref:t,onMouseDown:_e(e.onMouseDown,f=>{s?m.onItemFocus(d):f.preventDefault()}),onFocus:_e(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:_e(e.onKeyDown,f=>{if(f.key==="Tab"&&f.shiftKey){m.onItemShiftTab();return}if(f.target!==f.currentTarget)return;const w=wS(f,m.orientation,m.dir);if(w!==void 0){if(f.metaKey||f.ctrlKey||f.altKey||f.shiftKey)return;f.preventDefault();let b=p().filter(v=>v.focusable).map(v=>v.ref.current);if(w==="last")b.reverse();else if(w==="prev"||w==="next"){w==="prev"&&b.reverse();const v=b.indexOf(f.currentTarget);b=m.loop?_S(b,v+1):b.slice(v+1)}setTimeout(()=>gp(b))}}),children:typeof i=="function"?i({isCurrentTabStop:u,hasTabStop:g!=null}):i})})});hp.displayName=fp;var 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 wS(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 gp(e,t=!1){const r=document.activeElement;for(const s of e)if(s===r||(s.focus({preventScroll:t}),document.activeElement!==r))return}function _S(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var jS=pp,kS=hp,lo="Tabs",[SS]=bn(lo,[mp]),xp=mp(),[CS,ki]=SS(lo),yp=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,onValueChange:o,defaultValue:a,orientation:i="horizontal",dir:c,activationMode:l="automatic",...d}=e,m=Fs(c),[u,p]=hn({prop:s,onChange:o,defaultProp:a??"",caller:lo});return n.jsx(CS,{scope:r,baseId:qt(),value:u,onValueChange:p,orientation:i,dir:m,activationMode:l,children:n.jsx(be.div,{dir:m,"data-orientation":i,...d,ref:t})})});yp.displayName=lo;var vp="TabsList",bp=x.forwardRef((e,t)=>{const{__scopeTabs:r,loop:s=!0,...o}=e,a=ki(vp,r),i=xp(r);return n.jsx(jS,{asChild:!0,...i,orientation:a.orientation,dir:a.dir,loop:s,children:n.jsx(be.div,{role:"tablist","aria-orientation":a.orientation,...o,ref:t})})});bp.displayName=vp;var wp="TabsTrigger",_p=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,disabled:o=!1,...a}=e,i=ki(wp,r),c=xp(r),l=Sp(i.baseId,s),d=Cp(i.baseId,s),m=s===i.value;return n.jsx(kS,{asChild:!0,...c,focusable:!o,active:m,children:n.jsx(be.button,{type:"button",role:"tab","aria-selected":m,"aria-controls":d,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:l,...a,ref:t,onMouseDown:_e(e.onMouseDown,u=>{!o&&u.button===0&&u.ctrlKey===!1?i.onValueChange(s):u.preventDefault()}),onKeyDown:_e(e.onKeyDown,u=>{[" ","Enter"].includes(u.key)&&i.onValueChange(s)}),onFocus:_e(e.onFocus,()=>{const u=i.activationMode!=="manual";!m&&!o&&u&&i.onValueChange(s)})})})});_p.displayName=wp;var jp="TabsContent",kp=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,forceMount:o,children:a,...i}=e,c=ki(jp,r),l=Sp(c.baseId,s),d=Cp(c.baseId,s),m=s===c.value,u=x.useRef(m);return x.useEffect(()=>{const p=requestAnimationFrame(()=>u.current=!1);return()=>cancelAnimationFrame(p)},[]),n.jsx(mr,{present:o||m,children:({present:p})=>n.jsx(be.div,{"data-state":m?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!p,id:d,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:u.current?"0s":void 0},children:p&&a})})});kp.displayName=jp;function Sp(e,t){return`${e}-trigger-${t}`}function Cp(e,t){return`${e}-content-${t}`}var NS=yp,Np=bp,Pp=_p,Ap=kp;const Si=NS,uo=x.forwardRef(({className:e,...t},r)=>n.jsx(Np,{ref:r,className:H("inline-flex h-10 items-center justify-center rounded-md bg-neutral-100 p-1 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400",e),...t}));uo.displayName=Np.displayName;const Lr=x.forwardRef(({className:e,...t},r)=>n.jsx(Pp,{ref:r,className:H("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-neutral-950 data-[state=active]:shadow-sm dark:ring-offset-neutral-950 dark:focus-visible:ring-neutral-50/20 dark:data-[state=active]:bg-neutral-950 dark:data-[state=active]:text-neutral-50",e),...t}));Lr.displayName=Pp.displayName;const Ep=x.forwardRef(({className:e,...t},r)=>n.jsx(Ap,{ref:r,className:H("mt-2 ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 dark:ring-offset-neutral-950 dark:focus-visible:ring-neutral-50/20",e),...t}));Ep.displayName=Ap.displayName;function tr({title:e,description:t,actionLabel:r,onAction:s,className:o}){return n.jsx("div",{className:H("flex flex-col items-center justify-center rounded-xl border border-neutral-200 bg-white p-10 text-center dark:border-neutral-800 dark:bg-neutral-950",o),children:n.jsxs("div",{className:"max-w-sm",children:[n.jsx("h3",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:e}),t?n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}):null,r&&s?n.jsx("div",{className:"mt-5",children:n.jsx(ie,{type:"button",onClick:s,variant:"secondary",children:r})}):null]})})}function Zt({title:e,description:t,onRetry:r,className:s}){return n.jsxs("div",{className:H("rounded-xl border border-neutral-200 bg-white p-6 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h3",{className:"text-sm font-semibold",children:e??"Something went wrong"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}),r?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"Try again"})}):null]})}class 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(Zt,{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})=>y.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},y.createElement("div",{className:"sonner-spinner"},TS.map((r,s)=>y.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),RS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),OS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),MS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),DS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-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=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},y.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),$S=()=>{const[e,t]=y.useState(document.hidden);return y.useEffect(()=>{const r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),e};let xa=1;class 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:xa++,i=this.toasts.find(l=>l.id===a),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(a)&&this.dismissedToasts.delete(a),i?this.toasts=this.toasts.map(l=>l.id===a?(this.publish({...l,...t,id:a,title:s}),{...l,...t,id:a,dismissible:c,title:s}):l):this.addToast({title:s,...o,dismissible:c,id:a}),a},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(r=>r({id:t,dismiss:!0})))):this.toasts.forEach(r=>{this.subscribers.forEach(s=>s({id:r.id,dismiss:!0}))}),t),this.message=(t,r)=>this.create({...r,message:t}),this.error=(t,r)=>this.create({...r,message:t,type:"error"}),this.success=(t,r)=>this.create({...r,type:"success",message:t}),this.info=(t,r)=>this.create({...r,type:"info",message:t}),this.warning=(t,r)=>this.create({...r,type:"warning",message:t}),this.loading=(t,r)=>this.create({...r,type:"loading",message:t}),this.promise=(t,r)=>{if(!r)return;let s;r.loading!==void 0&&(s=this.create({...r,promise:t,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));const o=Promise.resolve(t instanceof Function?t():t);let a=s!==void 0,i;const c=o.then(async d=>{if(i=["resolve",d],y.isValidElement(d))a=!1,this.create({id:s,type:"default",message:d});else if(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,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,..._})}else if(d instanceof Error){a=!1;const u=typeof r.error=="function"?await r.error(d):r.error,p=typeof r.description=="function"?await r.description(d):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,..._})}else if(r.success!==void 0){a=!1;const u=typeof r.success=="function"?await r.success(d):r.success,p=typeof r.description=="function"?await r.description(d):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"success",description:p,..._})}}).catch(async d=>{if(i=["reject",d],r.error!==void 0){a=!1;const m=typeof r.error=="function"?await r.error(d):r.error,u=typeof r.description=="function"?await r.description(d):r.description,h=typeof m=="object"&&!y.isValidElement(m)?m:{message:m};this.create({id:s,type:"error",description:u,...h})}}).finally(()=>{a&&(this.dismiss(s),s=void 0),r.finally==null||r.finally.call(r)}),l=()=>new Promise((d,m)=>c.then(()=>i[0]==="reject"?m(i[1]):d(i[1])).catch(m));return typeof s!="string"&&typeof s!="number"?{unwrap:l}:Object.assign(s,{unwrap:l})},this.custom=(t,r)=>{const s=r?.id||xa++;return this.create({jsx:t(s),id:s,...r}),s},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ft=new zS,FS=(e,t)=>{const r=t?.id||xa++;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,VS=()=>ft.getActiveToasts(),qS=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:VS});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 ss(e){return e.label!==void 0}const HS=3,ZS="24px",GS="16px",cl=4e3,QS=356,YS=14,KS=45,XS=200;function Bt(...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:h,setHeights:_,visibleToasts:g,heights:f,index:w,toasts:j,expanded:b,removeToast:v,defaultRichColors:k,closeButton:R,style:N,cancelButtonStyle:C,actionButtonStyle:T,className:O="",descriptionClassName:$="",duration:S,position:A,gap:I,expandByDefault:B,classNames:D,icons:E,closeButtonAriaLabel:P="Close toast"}=e,[z,Z]=y.useState(null),[K,L]=y.useState(null),[W,Y]=y.useState(!1),[V,ce]=y.useState(!1),[F,ee]=y.useState(!1),[pe,q]=y.useState(!1),[ne,le]=y.useState(!1),[fe,Pe]=y.useState(0),[Ve,qe]=y.useState(0),He=y.useRef(u.duration||S||cl),gt=y.useRef(null),Ge=y.useRef(null),zt=w===0,lt=w+1<=g,te=u.type,xe=u.dismissible!==!1,ge=u.className||"",dt=u.descriptionClassName||"",xt=y.useMemo(()=>f.findIndex(he=>he.toastId===u.id)||0,[f,u.id]),ut=y.useMemo(()=>{var he;return(he=u.closeButton)!=null?he:R},[u.closeButton,R]),U=y.useMemo(()=>u.duration||S||cl,[u.duration,S]),re=y.useRef(0),de=y.useRef(0),ke=y.useRef(0),Se=y.useRef(null),[Me,Fn]=A.split("-"),jt=y.useMemo(()=>f.reduce((he,Le,we)=>we>=xt?he:he+Le.height,0),[f,xt]),Xt=$S(),pr=u.invert||m,jn=te==="loading";de.current=y.useMemo(()=>xt*I+jt,[xt,jt]),y.useEffect(()=>{He.current=U},[U]),y.useEffect(()=>{Y(!0)},[]),y.useEffect(()=>{const he=Ge.current;if(he){const Le=he.getBoundingClientRect().height;return qe(Le),_(we=>[{toastId:u.id,height:Le,position:u.position},...we]),()=>_(we=>we.filter($e=>$e.toastId!==u.id))}},[_,u.id]),y.useLayoutEffect(()=>{if(!W)return;const he=Ge.current,Le=he.style.height;he.style.height="auto";const we=he.getBoundingClientRect().height;he.style.height=Le,qe(we),_($e=>$e.find(ze=>ze.toastId===u.id)?$e.map(ze=>ze.toastId===u.id?{...ze,height:we}:ze):[{toastId:u.id,height:we,position:u.position},...$e])},[W,u.title,u.description,_,u.id,u.jsx,u.action,u.cancel]);const Ft=y.useCallback(()=>{ce(!0),Pe(de.current),_(he=>he.filter(Le=>Le.toastId!==u.id)),setTimeout(()=>{v(u)},XS)},[u,v,_,de]);y.useEffect(()=>{if(u.promise&&te==="loading"||u.duration===1/0||u.type==="loading")return;let he;return b||h||Xt?(()=>{if(ke.current<re.current){const $e=new Date().getTime()-re.current;He.current=He.current-$e}ke.current=new Date().getTime()})():(()=>{He.current!==1/0&&(re.current=new Date().getTime(),he=setTimeout(()=>{u.onAutoClose==null||u.onAutoClose.call(u,u),Ft()},He.current))})(),()=>clearTimeout(he)},[b,h,u,te,Xt,Ft]),y.useEffect(()=>{u.delete&&(Ft(),u.onDismiss==null||u.onDismiss.call(u,u))},[Ft,u.delete]);function Bn(){var he;if(E?.loading){var Le;return y.createElement("div",{className:Bt(D?.loader,u==null||(Le=u.classNames)==null?void 0:Le.loader,"sonner-loader"),"data-visible":te==="loading"},E.loading)}return y.createElement(IS,{className:Bt(D?.loader,u==null||(he=u.classNames)==null?void 0:he.loader),visible:te==="loading"})}const Un=u.icon||E?.[te]||ES(te);var Ur,on;return y.createElement("li",{tabIndex:0,ref:Ge,className:Bt(O,ge,D?.toast,u==null||(t=u.classNames)==null?void 0:t.toast,D?.default,D?.[te],u==null||(r=u.classNames)==null?void 0:r[te]),"data-sonner-toast":"","data-rich-colors":(Ur=u.richColors)!=null?Ur:k,"data-styled":!(u.jsx||u.unstyled||p),"data-mounted":W,"data-promise":!!u.promise,"data-swiped":ne,"data-removed":V,"data-visible":lt,"data-y-position":Me,"data-x-position":Fn,"data-index":w,"data-front":zt,"data-swiping":F,"data-dismissible":xe,"data-type":te,"data-invert":pr,"data-swipe-out":pe,"data-swipe-direction":K,"data-expanded":!!(b||B&&W),"data-testid":u.testId,style:{"--index":w,"--toasts-before":w,"--z-index":j.length-w,"--offset":`${V?fe:de.current}px`,"--initial-height":B?"auto":`${Ve}px`,...N,...u.style},onDragEnd:()=>{ee(!1),Z(null),Se.current=null},onPointerDown:he=>{he.button!==2&&(jn||!xe||(gt.current=new Date,Pe(de.current),he.target.setPointerCapture(he.pointerId),he.target.tagName!=="BUTTON"&&(ee(!0),Se.current={x:he.clientX,y:he.clientY})))},onPointerUp:()=>{var he,Le,we;if(pe||!xe)return;Se.current=null;const $e=Number(((he=Ge.current)==null?void 0:he.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Wn=Number(((Le=Ge.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),ze=new Date().getTime()-((we=gt.current)==null?void 0:we.getTime()),Je=z==="x"?$e:Wn,kn=Math.abs(Je)/ze;if(Math.abs(Je)>=KS||kn>.11){Pe(de.current),u.onDismiss==null||u.onDismiss.call(u,u),L(z==="x"?$e>0?"right":"left":Wn>0?"down":"up"),Ft(),q(!0);return}else{var mt,yt;(mt=Ge.current)==null||mt.style.setProperty("--swipe-amount-x","0px"),(yt=Ge.current)==null||yt.style.setProperty("--swipe-amount-y","0px")}le(!1),ee(!1),Z(null)},onPointerMove:he=>{var Le,we,$e;if(!Se.current||!xe||((Le=window.getSelection())==null?void 0:Le.toString().length)>0)return;const ze=he.clientY-Se.current.y,Je=he.clientX-Se.current.x;var kn;const mt=(kn=e.swipeDirections)!=null?kn:JS(A);!z&&(Math.abs(Je)>1||Math.abs(ze)>1)&&Z(Math.abs(Je)>Math.abs(ze)?"x":"y");let yt={x:0,y:0};const vt=tt=>1/(1.5+Math.abs(tt)/20);if(z==="y"){if(mt.includes("top")||mt.includes("bottom"))if(mt.includes("top")&&ze<0||mt.includes("bottom")&&ze>0)yt.y=ze;else{const tt=ze*vt(ze);yt.y=Math.abs(tt)<Math.abs(ze)?tt:ze}}else if(z==="x"&&(mt.includes("left")||mt.includes("right")))if(mt.includes("left")&&Je<0||mt.includes("right")&&Je>0)yt.x=Je;else{const tt=Je*vt(Je);yt.x=Math.abs(tt)<Math.abs(Je)?tt:Je}(Math.abs(yt.x)>0||Math.abs(yt.y)>0)&&le(!0),(we=Ge.current)==null||we.style.setProperty("--swipe-amount-x",`${yt.x}px`),($e=Ge.current)==null||$e.style.setProperty("--swipe-amount-y",`${yt.y}px`)}},ut&&!u.jsx&&te!=="loading"?y.createElement("button",{"aria-label":P,"data-disabled":jn,"data-close-button":!0,onClick:jn||!xe?()=>{}:()=>{Ft(),u.onDismiss==null||u.onDismiss.call(u,u)},className:Bt(D?.closeButton,u==null||(s=u.classNames)==null?void 0:s.closeButton)},(on=E?.close)!=null?on:LS):null,(te||u.icon||u.promise)&&u.icon!==null&&(E?.[te]!==null||u.icon)?y.createElement("div",{"data-icon":"",className:Bt(D?.icon,u==null||(o=u.classNames)==null?void 0:o.icon)},u.promise||u.type==="loading"&&!u.icon?u.icon||Bn():null,u.type!=="loading"?Un:null):null,y.createElement("div",{"data-content":"",className:Bt(D?.content,u==null||(a=u.classNames)==null?void 0:a.content)},y.createElement("div",{"data-title":"",className:Bt(D?.title,u==null||(i=u.classNames)==null?void 0:i.title)},u.jsx?u.jsx:typeof u.title=="function"?u.title():u.title),u.description?y.createElement("div",{"data-description":"",className:Bt($,dt,D?.description,u==null||(c=u.classNames)==null?void 0:c.description)},typeof u.description=="function"?u.description():u.description):null),y.isValidElement(u.cancel)?u.cancel:u.cancel&&ss(u.cancel)?y.createElement("button",{"data-button":!0,"data-cancel":!0,style:u.cancelButtonStyle||C,onClick:he=>{ss(u.cancel)&&xe&&(u.cancel.onClick==null||u.cancel.onClick.call(u.cancel,he),Ft())},className:Bt(D?.cancelButton,u==null||(l=u.classNames)==null?void 0:l.cancelButton)},u.cancel.label):null,y.isValidElement(u.action)?u.action:u.action&&ss(u.action)?y.createElement("button",{"data-button":!0,"data-action":!0,style:u.actionButtonStyle||T,onClick:he=>{ss(u.action)&&(u.action.onClick==null||u.action.onClick.call(u.action,he),!he.defaultPrevented&&Ft())},className:Bt(D?.actionButton,u==null||(d=u.classNames)==null?void 0:d.actionButton)},u.action.label):null)};function ll(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function 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=y.forwardRef(function(t,r){const{id:s,invert:o,position:a="bottom-right",hotkey:i=["altKey","KeyT"],expand:c,closeButton:l,className:d,offset:m,mobileOffset:u,theme:p="light",richColors:h,duration:_,style:g,visibleToasts:f=HS,toastOptions:w,dir:j=ll(),gap:b=YS,icons:v,containerAriaLabel:k="Notifications"}=t,[R,N]=y.useState([]),C=y.useMemo(()=>s?R.filter(W=>W.toasterId===s):R.filter(W=>!W.toasterId),[R,s]),T=y.useMemo(()=>Array.from(new Set([a].concat(C.filter(W=>W.position).map(W=>W.position)))),[C,a]),[O,$]=y.useState([]),[S,A]=y.useState(!1),[I,B]=y.useState(!1),[D,E]=y.useState(p!=="system"?p:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),P=y.useRef(null),z=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),Z=y.useRef(null),K=y.useRef(!1),L=y.useCallback(W=>{N(Y=>{var V;return(V=Y.find(ce=>ce.id===W.id))!=null&&V.delete||ft.dismiss(W.id),Y.filter(({id:ce})=>ce!==W.id)})},[]);return y.useEffect(()=>ft.subscribe(W=>{if(W.dismiss){requestAnimationFrame(()=>{N(Y=>Y.map(V=>V.id===W.id?{...V,delete:!0}:V))});return}setTimeout(()=>{ka.flushSync(()=>{N(Y=>{const V=Y.findIndex(ce=>ce.id===W.id);return V!==-1?[...Y.slice(0,V),{...Y[V],...W},...Y.slice(V+1)]:[W,...Y]})})})}),[R]),y.useEffect(()=>{if(p!=="system"){E(p);return}if(p==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?E("dark"):E("light")),typeof window>"u")return;const W=window.matchMedia("(prefers-color-scheme: dark)");try{W.addEventListener("change",({matches:Y})=>{E(Y?"dark":"light")})}catch{W.addListener(({matches:V})=>{try{E(V?"dark":"light")}catch(ce){console.error(ce)}})}},[p]),y.useEffect(()=>{R.length<=1&&A(!1)},[R]),y.useEffect(()=>{const W=Y=>{var V;if(i.every(ee=>Y[ee]||Y.code===ee)){var F;A(!0),(F=P.current)==null||F.focus()}Y.code==="Escape"&&(document.activeElement===P.current||(V=P.current)!=null&&V.contains(document.activeElement))&&A(!1)};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[i]),y.useEffect(()=>{if(P.current)return()=>{Z.current&&(Z.current.focus({preventScroll:!0}),Z.current=null,K.current=!1)}},[P.current]),y.createElement("section",{ref:r,"aria-label":`${k} ${z}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},T.map((W,Y)=>{var V;const[ce,F]=W.split("-");return C.length?y.createElement("ol",{key:W,dir:j==="auto"?ll():j,tabIndex:-1,ref:P,className:d,"data-sonner-toaster":!0,"data-sonner-theme":D,"data-y-position":ce,"data-x-position":F,style:{"--front-toast-height":`${((V=O[0])==null?void 0:V.height)||0}px`,"--width":`${QS}px`,"--gap":`${b}px`,...g,...tC(m,u)},onBlur:ee=>{K.current&&!ee.currentTarget.contains(ee.relatedTarget)&&(K.current=!1,Z.current&&(Z.current.focus({preventScroll:!0}),Z.current=null))},onFocus:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||K.current||(K.current=!0,Z.current=ee.relatedTarget)},onMouseEnter:()=>A(!0),onMouseMove:()=>A(!0),onMouseLeave:()=>{I||A(!1)},onDragEnd:()=>A(!1),onPointerDown:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||B(!0)},onPointerUp:()=>B(!1)},C.filter(ee=>!ee.position&&Y===0||ee.position===W).map((ee,pe)=>{var q,ne;return y.createElement(eC,{key:ee.id,icons:v,index:pe,toast:ee,defaultRichColors:h,duration:(q=w?.duration)!=null?q:_,className:w?.className,descriptionClassName:w?.descriptionClassName,invert:o,visibleToasts:f,closeButton:(ne=w?.closeButton)!=null?ne:l,interacting:I,position:W,style:w?.style,unstyled:w?.unstyled,classNames:w?.classNames,cancelButtonStyle:w?.cancelButtonStyle,actionButtonStyle:w?.actionButtonStyle,closeButtonAriaLabel:w?.closeButtonAriaLabel,removeToast:L,toasts:C.filter(le=>le.position==ee.position),heights:O.filter(le=>le.position==ee.position),setHeights:$,expandByDefault:c,gap:b,expanded:S,swipeDirections:t.swipeDirections})})):null}))}),Ci=x.createContext(null);function rC(){const e=x.useContext(Ci);if(!e)throw new Error("useToast must be used within ToastProvider");return e}function mo(){return x.useContext(Ci)}function sC({children:e}){const t=x.useCallback(r=>{const s=r.title??"",o=r.description;qS(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:Tp,setPrototypeOf:dl,isFrozen:oC,getPrototypeOf:aC,getOwnPropertyDescriptor:iC}=Object;let{freeze:it,seal:Ct,create:ya}=Object,{apply:va,construct:ba}=typeof Reflect<"u"&&Reflect;it||(it=function(t){return t});Ct||(Ct=function(t){return t});va||(va=function(t,r){for(var s=arguments.length,o=new Array(s>2?s-2:0),a=2;a<s;a++)o[a-2]=arguments[a];return t.apply(r,o)});ba||(ba=function(t){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return new t(...s)});const os=ct(Array.prototype.forEach),cC=ct(Array.prototype.lastIndexOf),ul=ct(Array.prototype.pop),gr=ct(Array.prototype.push),lC=ct(Array.prototype.splice),ms=ct(String.prototype.toLowerCase),Uo=ct(String.prototype.toString),Wo=ct(String.prototype.match),xr=ct(String.prototype.replace),dC=ct(String.prototype.indexOf),uC=ct(String.prototype.trim),It=ct(Object.prototype.hasOwnProperty),nt=ct(RegExp.prototype.test),yr=mC(TypeError);function ct(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return va(e,t,s)}}function 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 ve(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ms;dl&&dl(e,null);let s=t.length;for(;s--;){let o=t[s];if(typeof o=="string"){const a=r(o);a!==o&&(oC(t)||(t[s]=a),o=a)}e[o]=!0}return e}function pC(e){for(let t=0;t<e.length;t++)It(e,t)||(e[t]=null);return e}function Ut(e){const t=ya(null);for(const[r,s]of Tp(e))It(e,r)&&(Array.isArray(s)?t[r]=pC(s):s&&typeof s=="object"&&s.constructor===Object?t[r]=Ut(s):t[r]=s);return t}function vr(e,t){for(;e!==null;){const s=iC(e,t);if(s){if(s.get)return ct(s.get);if(typeof s.value=="function")return ct(s.value)}e=aC(e)}function r(){return null}return r}const ml=it(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Vo=it(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),qo=it(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),fC=it(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ho=it(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),hC=it(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),pl=it(["#text"]),fl=it(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Zo=it(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),hl=it(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),as=it(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),gC=Ct(/\{\{[\w\W]*|[\w\W]*\}\}/gm),xC=Ct(/<%[\w\W]*|[\w\W]*%>/gm),yC=Ct(/\$\{[\w\W]*/gm),vC=Ct(/^data-[\-\w.\u00B7-\uFFFF]+$/),bC=Ct(/^aria-[\-\w]+$/),Ip=Ct(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),wC=Ct(/^(?:\w+script|data):/i),_C=Ct(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Rp=Ct(/^html$/i),jC=Ct(/^[a-z][.\w]*(-[.\w]+)+$/i);var gl=Object.freeze({__proto__:null,ARIA_ATTR:bC,ATTR_WHITESPACE:_C,CUSTOM_ELEMENT:jC,DATA_ATTR:vC,DOCTYPE_NAME:Rp,ERB_EXPR:xC,IS_ALLOWED_URI:Ip,IS_SCRIPT_OR_DATA:wC,MUSTACHE_EXPR:gC,TMPLIT_EXPR:yC});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}},xl=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Op(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:kC();const t=ue=>Op(ue);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==br.document||!e.Element)return t.isSupported=!1,t;let{document:r}=e;const s=r,o=s.currentScript,{DocumentFragment:a,HTMLTemplateElement:i,Node:c,Element:l,NodeFilter:d,NamedNodeMap:m=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:p,trustedTypes:h}=e,_=l.prototype,g=vr(_,"cloneNode"),f=vr(_,"remove"),w=vr(_,"nextSibling"),j=vr(_,"childNodes"),b=vr(_,"parentNode");if(typeof i=="function"){const ue=r.createElement("template");ue.content&&ue.content.ownerDocument&&(r=ue.content.ownerDocument)}let v,k="";const{implementation:R,createNodeIterator:N,createDocumentFragment:C,getElementsByTagName:T}=r,{importNode:O}=s;let $=xl();t.isSupported=typeof Tp=="function"&&typeof b=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:S,ERB_EXPR:A,TMPLIT_EXPR:I,DATA_ATTR:B,ARIA_ATTR:D,IS_SCRIPT_OR_DATA:E,ATTR_WHITESPACE:P,CUSTOM_ELEMENT:z}=gl;let{IS_ALLOWED_URI:Z}=gl,K=null;const L=ve({},[...ml,...Vo,...qo,...Ho,...pl]);let W=null;const Y=ve({},[...fl,...Zo,...hl,...as]);let V=Object.seal(ya(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ce=null,F=null;const ee=Object.seal(ya(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let pe=!0,q=!0,ne=!1,le=!0,fe=!1,Pe=!0,Ve=!1,qe=!1,He=!1,gt=!1,Ge=!1,zt=!1,lt=!0,te=!1;const xe="user-content-";let ge=!0,dt=!1,xt={},ut=null;const U=ve({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let re=null;const de=ve({},["audio","video","img","source","image","track"]);let ke=null;const Se=ve({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Me="http://www.w3.org/1998/Math/MathML",Fn="http://www.w3.org/2000/svg",jt="http://www.w3.org/1999/xhtml";let Xt=jt,pr=!1,jn=null;const Ft=ve({},[Me,Fn,jt],Uo);let Bn=ve({},["mi","mo","mn","ms","mtext"]),Un=ve({},["annotation-xml"]);const Ur=ve({},["title","style","font","a","script"]);let on=null;const he=["application/xhtml+xml","text/html"],Le="text/html";let we=null,$e=null;const Wn=r.createElement("form"),ze=function(M){return M instanceof RegExp||M instanceof Function},Je=function(){let M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!($e&&$e===M)){if((!M||typeof M!="object")&&(M={}),M=Ut(M),on=he.indexOf(M.PARSER_MEDIA_TYPE)===-1?Le:M.PARSER_MEDIA_TYPE,we=on==="application/xhtml+xml"?Uo:ms,K=It(M,"ALLOWED_TAGS")?ve({},M.ALLOWED_TAGS,we):L,W=It(M,"ALLOWED_ATTR")?ve({},M.ALLOWED_ATTR,we):Y,jn=It(M,"ALLOWED_NAMESPACES")?ve({},M.ALLOWED_NAMESPACES,Uo):Ft,ke=It(M,"ADD_URI_SAFE_ATTR")?ve(Ut(Se),M.ADD_URI_SAFE_ATTR,we):Se,re=It(M,"ADD_DATA_URI_TAGS")?ve(Ut(de),M.ADD_DATA_URI_TAGS,we):de,ut=It(M,"FORBID_CONTENTS")?ve({},M.FORBID_CONTENTS,we):U,ce=It(M,"FORBID_TAGS")?ve({},M.FORBID_TAGS,we):Ut({}),F=It(M,"FORBID_ATTR")?ve({},M.FORBID_ATTR,we):Ut({}),xt=It(M,"USE_PROFILES")?M.USE_PROFILES:!1,pe=M.ALLOW_ARIA_ATTR!==!1,q=M.ALLOW_DATA_ATTR!==!1,ne=M.ALLOW_UNKNOWN_PROTOCOLS||!1,le=M.ALLOW_SELF_CLOSE_IN_ATTR!==!1,fe=M.SAFE_FOR_TEMPLATES||!1,Pe=M.SAFE_FOR_XML!==!1,Ve=M.WHOLE_DOCUMENT||!1,gt=M.RETURN_DOM||!1,Ge=M.RETURN_DOM_FRAGMENT||!1,zt=M.RETURN_TRUSTED_TYPE||!1,He=M.FORCE_BODY||!1,lt=M.SANITIZE_DOM!==!1,te=M.SANITIZE_NAMED_PROPS||!1,ge=M.KEEP_CONTENT!==!1,dt=M.IN_PLACE||!1,Z=M.ALLOWED_URI_REGEXP||Ip,Xt=M.NAMESPACE||jt,Bn=M.MATHML_TEXT_INTEGRATION_POINTS||Bn,Un=M.HTML_INTEGRATION_POINTS||Un,V=M.CUSTOM_ELEMENT_HANDLING||{},M.CUSTOM_ELEMENT_HANDLING&&ze(M.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(V.tagNameCheck=M.CUSTOM_ELEMENT_HANDLING.tagNameCheck),M.CUSTOM_ELEMENT_HANDLING&&ze(M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(V.attributeNameCheck=M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),M.CUSTOM_ELEMENT_HANDLING&&typeof M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(V.allowCustomizedBuiltInElements=M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),fe&&(q=!1),Ge&&(gt=!0),xt&&(K=ve({},pl),W=[],xt.html===!0&&(ve(K,ml),ve(W,fl)),xt.svg===!0&&(ve(K,Vo),ve(W,Zo),ve(W,as)),xt.svgFilters===!0&&(ve(K,qo),ve(W,Zo),ve(W,as)),xt.mathMl===!0&&(ve(K,Ho),ve(W,hl),ve(W,as))),M.ADD_TAGS&&(typeof M.ADD_TAGS=="function"?ee.tagCheck=M.ADD_TAGS:(K===L&&(K=Ut(K)),ve(K,M.ADD_TAGS,we))),M.ADD_ATTR&&(typeof M.ADD_ATTR=="function"?ee.attributeCheck=M.ADD_ATTR:(W===Y&&(W=Ut(W)),ve(W,M.ADD_ATTR,we))),M.ADD_URI_SAFE_ATTR&&ve(ke,M.ADD_URI_SAFE_ATTR,we),M.FORBID_CONTENTS&&(ut===U&&(ut=Ut(ut)),ve(ut,M.FORBID_CONTENTS,we)),M.ADD_FORBID_CONTENTS&&(ut===U&&(ut=Ut(ut)),ve(ut,M.ADD_FORBID_CONTENTS,we)),ge&&(K["#text"]=!0),Ve&&ve(K,["html","head","body"]),K.table&&(ve(K,["tbody"]),delete ce.tbody),M.TRUSTED_TYPES_POLICY){if(typeof M.TRUSTED_TYPES_POLICY.createHTML!="function")throw yr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof M.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw yr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');v=M.TRUSTED_TYPES_POLICY,k=v.createHTML("")}else v===void 0&&(v=SC(h,o)),v!==null&&typeof k=="string"&&(k=v.createHTML(""));it&&it(M),$e=M}},kn=ve({},[...Vo,...qo,...fC]),mt=ve({},[...Ho,...hC]),yt=function(M){let X=b(M);(!X||!X.tagName)&&(X={namespaceURI:Xt,tagName:"template"});const ae=ms(M.tagName),Ae=ms(X.tagName);return jn[M.namespaceURI]?M.namespaceURI===Fn?X.namespaceURI===jt?ae==="svg":X.namespaceURI===Me?ae==="svg"&&(Ae==="annotation-xml"||Bn[Ae]):!!kn[ae]:M.namespaceURI===Me?X.namespaceURI===jt?ae==="math":X.namespaceURI===Fn?ae==="math"&&Un[Ae]:!!mt[ae]:M.namespaceURI===jt?X.namespaceURI===Fn&&!Un[Ae]||X.namespaceURI===Me&&!Bn[Ae]?!1:!mt[ae]&&(Ur[ae]||!kn[ae]):!!(on==="application/xhtml+xml"&&jn[M.namespaceURI]):!1},vt=function(M){gr(t.removed,{element:M});try{b(M).removeChild(M)}catch{f(M)}},tt=function(M,X){try{gr(t.removed,{attribute:X.getAttributeNode(M),from:X})}catch{gr(t.removed,{attribute:null,from:X})}if(X.removeAttribute(M),M==="is")if(gt||Ge)try{vt(X)}catch{}else try{X.setAttribute(M,"")}catch{}},go=function(M){let X=null,ae=null;if(He)M="<remove></remove>"+M;else{const Fe=Wo(M,/^[\r\n\t ]+/);ae=Fe&&Fe[0]}on==="application/xhtml+xml"&&Xt===jt&&(M='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+M+"</body></html>");const Ae=v?v.createHTML(M):M;if(Xt===jt)try{X=new p().parseFromString(Ae,on)}catch{}if(!X||!X.documentElement){X=R.createDocument(Xt,"template",null);try{X.documentElement.innerHTML=pr?k:Ae}catch{}}const et=X.body||X.documentElement;return M&&ae&&et.insertBefore(r.createTextNode(ae),et.childNodes[0]||null),Xt===jt?T.call(X,Ve?"html":"body")[0]:Ve?X.documentElement:et},Li=function(M){return N.call(M.ownerDocument||M,M,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},xo=function(M){return M instanceof u&&(typeof M.nodeName!="string"||typeof M.textContent!="string"||typeof M.removeChild!="function"||!(M.attributes instanceof m)||typeof M.removeAttribute!="function"||typeof M.setAttribute!="function"||typeof M.namespaceURI!="string"||typeof M.insertBefore!="function"||typeof M.hasChildNodes!="function")},$i=function(M){return typeof c=="function"&&M instanceof c};function Jt(ue,M,X){os(ue,ae=>{ae.call(t,M,X,$e)})}const zi=function(M){let X=null;if(Jt($.beforeSanitizeElements,M,null),xo(M))return vt(M),!0;const ae=we(M.nodeName);if(Jt($.uponSanitizeElement,M,{tagName:ae,allowedTags:K}),Pe&&M.hasChildNodes()&&!$i(M.firstElementChild)&&nt(/<[/\w!]/g,M.innerHTML)&&nt(/<[/\w!]/g,M.textContent)||M.nodeType===br.progressingInstruction||Pe&&M.nodeType===br.comment&&nt(/<[/\w]/g,M.data))return vt(M),!0;if(!(ee.tagCheck instanceof Function&&ee.tagCheck(ae))&&(!K[ae]||ce[ae])){if(!ce[ae]&&Bi(ae)&&(V.tagNameCheck instanceof RegExp&&nt(V.tagNameCheck,ae)||V.tagNameCheck instanceof Function&&V.tagNameCheck(ae)))return!1;if(ge&&!ut[ae]){const Ae=b(M)||M.parentNode,et=j(M)||M.childNodes;if(et&&Ae){const Fe=et.length;for(let pt=Fe-1;pt>=0;--pt){const en=g(et[pt],!0);en.__removalCount=(M.__removalCount||0)+1,Ae.insertBefore(en,w(M))}}}return vt(M),!0}return M instanceof l&&!yt(M)||(ae==="noscript"||ae==="noembed"||ae==="noframes")&&nt(/<\/no(script|embed|frames)/i,M.innerHTML)?(vt(M),!0):(fe&&M.nodeType===br.text&&(X=M.textContent,os([S,A,I],Ae=>{X=xr(X,Ae," ")}),M.textContent!==X&&(gr(t.removed,{element:M.cloneNode()}),M.textContent=X)),Jt($.afterSanitizeElements,M,null),!1)},Fi=function(M,X,ae){if(lt&&(X==="id"||X==="name")&&(ae in r||ae in Wn))return!1;if(!(q&&!F[X]&&nt(B,X))){if(!(pe&&nt(D,X))){if(!(ee.attributeCheck instanceof Function&&ee.attributeCheck(X,M))){if(!W[X]||F[X]){if(!(Bi(M)&&(V.tagNameCheck instanceof RegExp&&nt(V.tagNameCheck,M)||V.tagNameCheck instanceof Function&&V.tagNameCheck(M))&&(V.attributeNameCheck instanceof RegExp&&nt(V.attributeNameCheck,X)||V.attributeNameCheck instanceof Function&&V.attributeNameCheck(X,M))||X==="is"&&V.allowCustomizedBuiltInElements&&(V.tagNameCheck instanceof RegExp&&nt(V.tagNameCheck,ae)||V.tagNameCheck instanceof Function&&V.tagNameCheck(ae))))return!1}else if(!ke[X]){if(!nt(Z,xr(ae,P,""))){if(!((X==="src"||X==="xlink:href"||X==="href")&&M!=="script"&&dC(ae,"data:")===0&&re[M])){if(!(ne&&!nt(E,xr(ae,P,"")))){if(ae)return!1}}}}}}}return!0},Bi=function(M){return M!=="annotation-xml"&&Wo(M,z)},Ui=function(M){Jt($.beforeSanitizeAttributes,M,null);const{attributes:X}=M;if(!X||xo(M))return;const ae={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:W,forceKeepAttr:void 0};let Ae=X.length;for(;Ae--;){const et=X[Ae],{name:Fe,namespaceURI:pt,value:en}=et,Vn=we(Fe),yo=en;let Ye=Fe==="value"?yo:uC(yo);if(ae.attrName=Vn,ae.attrValue=Ye,ae.keepAttr=!0,ae.forceKeepAttr=void 0,Jt($.uponSanitizeAttribute,M,ae),Ye=ae.attrValue,te&&(Vn==="id"||Vn==="name")&&(tt(Fe,M),Ye=xe+Ye),Pe&&nt(/((--!?|])>)|<\/(style|title|textarea)/i,Ye)){tt(Fe,M);continue}if(Vn==="attributename"&&Wo(Ye,"href")){tt(Fe,M);continue}if(ae.forceKeepAttr)continue;if(!ae.keepAttr){tt(Fe,M);continue}if(!le&&nt(/\/>/i,Ye)){tt(Fe,M);continue}fe&&os([S,A,I],Vi=>{Ye=xr(Ye,Vi," ")});const Wi=we(M.nodeName);if(!Fi(Wi,Vn,Ye)){tt(Fe,M);continue}if(v&&typeof h=="object"&&typeof h.getAttributeType=="function"&&!pt)switch(h.getAttributeType(Wi,Vn)){case"TrustedHTML":{Ye=v.createHTML(Ye);break}case"TrustedScriptURL":{Ye=v.createScriptURL(Ye);break}}if(Ye!==yo)try{pt?M.setAttributeNS(pt,Fe,Ye):M.setAttribute(Fe,Ye),xo(M)?vt(M):ul(t.removed)}catch{tt(Fe,M)}}Jt($.afterSanitizeAttributes,M,null)},Kp=function ue(M){let X=null;const ae=Li(M);for(Jt($.beforeSanitizeShadowDOM,M,null);X=ae.nextNode();)Jt($.uponSanitizeShadowNode,X,null),zi(X),Ui(X),X.content instanceof a&&ue(X.content);Jt($.afterSanitizeShadowDOM,M,null)};return t.sanitize=function(ue){let M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},X=null,ae=null,Ae=null,et=null;if(pr=!ue,pr&&(ue="<!-->"),typeof ue!="string"&&!$i(ue))if(typeof ue.toString=="function"){if(ue=ue.toString(),typeof ue!="string")throw yr("dirty is not a string, aborting")}else throw yr("toString is not a function");if(!t.isSupported)return ue;if(qe||Je(M),t.removed=[],typeof ue=="string"&&(dt=!1),dt){if(ue.nodeName){const en=we(ue.nodeName);if(!K[en]||ce[en])throw yr("root node is forbidden and cannot be sanitized in-place")}}else if(ue instanceof c)X=go("<!---->"),ae=X.ownerDocument.importNode(ue,!0),ae.nodeType===br.element&&ae.nodeName==="BODY"||ae.nodeName==="HTML"?X=ae:X.appendChild(ae);else{if(!gt&&!fe&&!Ve&&ue.indexOf("<")===-1)return v&&zt?v.createHTML(ue):ue;if(X=go(ue),!X)return gt?null:zt?k:""}X&&He&&vt(X.firstChild);const Fe=Li(dt?ue:X);for(;Ae=Fe.nextNode();)zi(Ae),Ui(Ae),Ae.content instanceof a&&Kp(Ae.content);if(dt)return ue;if(gt){if(Ge)for(et=C.call(X.ownerDocument);X.firstChild;)et.appendChild(X.firstChild);else et=X;return(W.shadowroot||W.shadowrootmode)&&(et=O.call(s,et,!0)),et}let pt=Ve?X.outerHTML:X.innerHTML;return Ve&&K["!doctype"]&&X.ownerDocument&&X.ownerDocument.doctype&&X.ownerDocument.doctype.name&&nt(Rp,X.ownerDocument.doctype.name)&&(pt="<!DOCTYPE "+X.ownerDocument.doctype.name+`>
|
|
136
|
-
`+pt),fe&&os([S,A,I],en=>{pt=xr(pt,en," ")}),v&&zt?v.createHTML(pt):pt},t.setConfig=function(){let ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Je(ue),qe=!0},t.clearConfig=function(){$e=null,qe=!1},t.isValidAttribute=function(ue,M,X){$e||Je({});const ae=we(ue),Ae=we(M);return Fi(ae,Ae,X)},t.addHook=function(ue,M){typeof M=="function"&&gr($[ue],M)},t.removeHook=function(ue,M){if(M!==void 0){const X=cC($[ue],M);return X===-1?void 0:lC($[ue],X,1)[0]}return ul($[ue])},t.removeHooks=function(ue){$[ue]=[]},t.removeAllHooks=function(){$=xl()},t}var CC=Op();function Mp({faq:e,className:t,expanded:r,defaultExpanded:s=!1,onExpandedChange:o,showKeywords:a=!1,dangerouslySetAnswerHTML:i=!1}){const[c,l]=x.useState(s),d=r!==void 0,m=d?r:c,u=()=>{const p=!m;d||l(p),o?.(p)};return n.jsxs("div",{className:H("border border-neutral-200 rounded-lg overflow-hidden dark:border-neutral-800",t),children:[n.jsxs("button",{type:"button",onClick:u,className:H("w-full flex items-center justify-between px-4 py-3 text-left","bg-neutral-50 hover:bg-neutral-100 dark:bg-neutral-900 dark:hover:bg-neutral-800","transition-colors duration-150"),"aria-expanded":m,children:[n.jsx("span",{className:"font-medium text-neutral-900 dark:text-neutral-100 pr-4",children:e.question}),n.jsx("svg",{className:H("w-5 h-5 text-neutral-500 transition-transform duration-200 flex-shrink-0",m&&"rotate-180"),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),m&&n.jsxs("div",{className:"px-4 py-3 bg-white dark:bg-neutral-950",children:[i?n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 prose prose-sm dark:prose-invert max-w-none",dangerouslySetInnerHTML:{__html: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(Mp,{faq:d,showKeywords:s,dangerouslySetAnswerHTML:o,expanded:r?i===d.id:void 0,onExpandedChange:r?m=>c(m?d.id:null):void 0},d.id))})}function Qe({amount:e,currency:t}){return new Intl.NumberFormat(void 0,{style:"currency",currency:t}).format(e)}function po({amount:e,currency:t,compareAt:r,className:s,size:o="default"}){const a=typeof r=="number"&&r>e;return n.jsxs("div",{className:H("flex items-baseline gap-2 tabular-nums",s),children:[n.jsx("span",{className:H("font-semibold",o==="sm"?"text-sm":"text-base"),children:Qe({amount:e,currency:t})}),a?n.jsx("span",{className:H("text-neutral-500 line-through dark:text-neutral-400",o==="sm"?"text-xs":"text-sm"),children:Qe({amount:r,currency:t})}):null]})}const 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 Dp({product:e,href:t,onAddToCart:r,onQuickView:s,className:o,layout:a="large",imageCrop:i="center"}){const c=e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0,l=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:null;return n.jsxs(Rt,{className:H("group flex h-full flex-col overflow-hidden rounded-2xl",o),children:[n.jsxs("div",{className:"relative",children:[n.jsx("a",{href:t,className:"block","aria-label":`View ${e.title}`,children:n.jsx("div",{className:H("overflow-hidden bg-neutral-100 dark:bg-neutral-900",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(Pn,{className:"pointer-events-none bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:d},d))}):null,c?n.jsx("div",{className:"pointer-events-none absolute left-3 top-3",children:n.jsx(Pn,{variant:"secondary",className:"bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:"Out of stock"})}):l!=null&&l>0&&l<=5?n.jsx("div",{className:"pointer-events-none absolute left-3 top-3",children:n.jsxs(Pn,{variant:"secondary",className:"bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:["Only ",l," left"]})}):null,s?n.jsx("div",{className:"absolute right-3 top-3 opacity-0 transition-opacity group-hover:opacity-100",children:n.jsx(ie,{type:"button",size:"sm",variant:"secondary",className:"h-9",onClick:()=>s(e),children:"Quick view"})}):null]}),n.jsxs("div",{className:H("flex flex-1 flex-col",a==="compact"?"p-3":"p-4"),children:[n.jsx("div",{className:"flex items-start justify-between gap-3",children:n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:H("line-clamp-1 font-medium text-neutral-950 dark:text-neutral-50",a==="compact"?"text-xs":"text-sm"),children:e.title}),n.jsx("div",{className:"mt-1",children:n.jsx(po,{amount:e.price,currency:e.currency,compareAt:e.compareAtPrice,size:a==="compact"?"sm":"default"})})]})}),a==="large"&&n.jsx("p",{className:"mt-2 line-clamp-2 min-h-8 text-xs leading-4 text-neutral-600 dark:text-neutral-400",children:e.description}),n.jsx("div",{className:H("mt-auto",a==="compact"?"pt-3":"pt-4"),children:n.jsx(ie,{type:"button",className:"w-full",size:a==="compact"?"sm":"default",onClick:()=>r?.(e,null),disabled:c,children:c?"Out of stock":"Add to cart"})})]})]})}function fo({products:e,columns:t,onAddToCart:r,onQuickView:s,getProductHref:o,className:a,layout:i,imageCrop:c}){const l=t?.base??2,d=t?.md??3,m=t?.lg??3,u={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4"},p={1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4"},h={1:"lg:grid-cols-1",2:"lg:grid-cols-2",3:"lg:grid-cols-3",4:"lg:grid-cols-4"},_=H("grid gap-4",u[Math.min(4,Math.max(1,l))],p[Math.min(4,Math.max(1,d))],h[Math.min(4,Math.max(1,m))]);return n.jsx("div",{className:H(_,a),children:e.map(g=>n.jsx(Dp,{product:g,href:o?o(g):void 0,onAddToCart:r,onQuickView:s,layout:i,imageCrop:c},g.id))})}function Ni({images:e,className:t}){const[r,s]=x.useState(0),o=e[r];return e.length===0?n.jsx("div",{className:H("aspect-square w-full rounded-xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",t)}):n.jsxs("div",{className:H("space-y-3",t),children:[n.jsx("div",{className:"aspect-square overflow-hidden rounded-2xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:n.jsx("img",{src:o?.url,alt:o?.alt??"",className:"h-full w-full object-cover",loading:"eager"})}),e.length>1?n.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:e.map((a,i)=>{const c=i===r;return n.jsx("button",{type:"button",className:H("h-16 w-16 shrink-0 overflow-hidden rounded-lg border",c?"border-neutral-900 dark:border-neutral-50":"border-neutral-200 dark:border-neutral-800"),onClick:()=>s(i),"aria-label":`View image ${i+1}`,children:n.jsx("img",{src:a.url,alt:a.alt??"",className:"h-full w-full object-cover",loading:"lazy"})},a.url)})}):null]})}function 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 yl(e,t){return e.find(r=>Object.entries(t).every(([s,o])=>r.options[s]===o))??null}function Lp(e){return e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0}function IC(e){return e.inventoryStatus==="low"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity>0&&e.inventoryQuantity<=5}function RC(e){const t=Lp(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=>!Lp(i))}function Pi({product:e,value:t,onChange:r,className:s,showInventory:o=!0,disableOutOfStock:a=!1}){const i=x.useMemo(()=>e.variants??[],[e.variants]),c=x.useMemo(()=>EC(i),[i]),l=x.useMemo(()=>yl(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(h=>{const _=h===p,g=OC(i,t.selectedOptions,m,h),f=a&&!g;return n.jsxs(ie,{type:"button",size:"sm",variant:_?"default":"outline",onClick:()=>{const w={...t.selectedOptions,[m]:h},j=yl(i,w);r({selectedOptions:w,variant:j})},"aria-pressed":_,disabled:f,className:H(!g&&!f&&"opacity-50 line-through"),children:[h,!g&&!f&&n.jsx("span",{className:"ml-1 text-[10px] opacity-70",children:"(Out)"})]},h)})})]},m)}),o&&l&&d&&n.jsx("div",{className:"pt-2",children:d.isOutOfStock?n.jsx("div",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:"Out of stock"}):d.isLow&&d.quantity!==void 0?n.jsxs("div",{className:"text-sm text-amber-600 dark:text-amber-400",children:["Only ",n.jsx("span",{className:"font-semibold",children:d.quantity})," left"]}):null})]})}function Ai({qty:e,onChange:t,min:r=1,max:s,className:o}){const a=Number.isFinite(e)?Math.max(r,Math.floor(e)):r,i=a>r,c=typeof s=="number"?a<s:!0;return n.jsxs("div",{className:H("flex items-center gap-2",o),children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(Math.max(r,a-1)),disabled:!i,"aria-label":"Decrease quantity",children:"-"}),n.jsx(Be,{inputMode:"numeric",pattern:"[0-9]*",value:String(a),onChange:l=>{const d=Math.floor(Number(l.target.value));if(!Number.isFinite(d))return;const m=Math.max(r,typeof s=="number"?Math.min(s,d):d);t(m)},className:"h-10 w-16 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(a+1),disabled:!c,"aria-label":"Increase quantity",children:"+"})]})}function Ei({product:e,open:t,onOpenChange:r,productHref:s,onAddToCart:o,className:a}){const[i,c]=x.useState(1),[l,d]=x.useState({selectedOptions:{},variant:null});if(x.useEffect(()=>{if(e)if(c(1),e.variants?.length){const p=e.variants[0];d({selectedOptions:{...p.options},variant:p})}else d({selectedOptions:{},variant:null})},[e?.id]),!e)return null;const m=l.variant?.price??e.price,u=l.variant?.compareAtPrice??e.compareAtPrice;return n.jsx(pi,{open:t,onOpenChange:r,children:n.jsxs(eo,{className:H("max-w-3xl",a),children:[n.jsx(hi,{children:n.jsxs(to,{className:"flex items-center justify-between gap-3",children:[n.jsx("span",{className:"truncate",children:e.title}),s?n.jsx("a",{href:s(e.slug),className:"text-sm font-normal text-neutral-700 hover:underline dark:text-neutral-300",children:"View details"}):null]})}),n.jsxs("div",{className:"grid gap-8 md:grid-cols-2",children:[n.jsx(Ni,{images:e.images}),n.jsxs("div",{className:"space-y-5",children:[n.jsxs("div",{children:[n.jsx(po,{amount:m,currency:e.currency,compareAt:u}),n.jsx("p",{className:"mt-3 text-sm text-neutral-600 dark:text-neutral-400",children:e.description})]}),n.jsx(Pi,{product:e,value:{selectedOptions:l.selectedOptions,variantId:l.variant?.id},onChange:p=>d(p)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(Ai,{qty:i,onChange:c}),n.jsx(ie,{type:"button",className:"flex-1",onClick:()=>{o(e,l.variant,i),r(!1)},children:"Add to cart"})]}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:e.inventoryStatus==="out_of_stock"?"Out of stock":"In stock"})]})]})]})})}function wa({categories:e,activeSlug:t,onSelect:r,className:s}){return n.jsx("nav",{className:H("space-y-1",s),"aria-label":"Categories",children:e.map(o=>{const a=t===o.slug;return n.jsxs("button",{type:"button",className:H("flex w-full items-center justify-between rounded-md px-3 py-2 text-sm transition-colors",a?"bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900":"text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"),onClick:()=>r?.(o),"aria-current":a?"page":void 0,children:[n.jsx("span",{className:"truncate",children:o.name}),n.jsx("span",{className:"text-xs opacity-70",children:"›"})]},o.id)})})}function Ti({items:e,className:t}){return n.jsx("nav",{className:H("flex items-center gap-2 text-xs text-neutral-600 dark:text-neutral-400",t),"aria-label":"Breadcrumb",children:e.map((r,s)=>n.jsxs("span",{className:"flex items-center gap-2",children:[r.href?n.jsx("a",{href:r.href,className:"hover:underline",children:r.label}):n.jsx("span",{className:"text-neutral-900 dark:text-neutral-50",children:r.label}),s<e.length-1?n.jsx("span",{"aria-hidden":!0,children:"·"}):null]},`${r.label}-${s}`))})}function Ii({value:e,onChange:t,placeholder:r="Search products…",className:s}){return n.jsxs("div",{className:H("relative",s),children:[n.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-3 flex items-center text-neutral-500 dark:text-neutral-400","aria-hidden":!0,children:"⌕"}),n.jsx(Be,{value:e,onChange:o=>t(o.target.value),placeholder:r,className:"pl-9","aria-label":"Search"})]})}function Ts({facets:e,value:t,onChange:r,onClear:s,className:o,enabledFilters:a}){const i=e.tags??[],c=new Set(t.tags??[]),l=a?.tags??!0,d=a?.priceRange??!0,m=a?.inStock??!0;return l||d||m?n.jsxs("div",{className:H("space-y-4",o),children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Filters"}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-8 px-2 text-xs",onClick:s,children:"Clear"})]}),n.jsx(St,{}),l&&i.length?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Tags"}),n.jsx("div",{className:"space-y-2",children:i.map(p=>n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:c.has(p),onChange:h=>{const _=new Set(c);h.target.checked?_.add(p):_.delete(p),r({...t,tags:Array.from(_)})}}),p]},p))})]}):null,d&&e.price?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Price"}),n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-1",children:[n.jsx(at,{className:"text-xs",htmlFor:"price-min",children:"Min"}),n.jsx(Be,{id:"price-min",inputMode:"decimal",placeholder:String(e.price.min),value:t.priceMin??"",onChange:p=>{const h=Number(p.target.value);r({...t,priceMin:Number.isFinite(h)&&p.target.value!==""?h:void 0})}})]}),n.jsxs("div",{className:"grid gap-1",children:[n.jsx(at,{className:"text-xs",htmlFor:"price-max",children:"Max"}),n.jsx(Be,{id:"price-max",inputMode:"decimal",placeholder:String(e.price.max),value:t.priceMax??"",onChange:p=>{const h=Number(p.target.value);r({...t,priceMax:Number.isFinite(h)&&p.target.value!==""?h:void 0})}})]})]})]}):null,m?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Availability"}),n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:t.inStock??!1,onChange:p=>r({...t,inStock:p.target.checked})}),"In stock"]})]}):null]}):null}function vl(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}function 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:Qe({amount:i,currency:e.currency})}),u&&n.jsxs("div",{className:H("mt-1 flex items-center gap-1 text-[11px]",u.type==="error"&&"text-red-600 dark:text-red-400",u.type==="warning"&&"text-amber-600 dark:text-amber-400",u.type==="info"&&"text-blue-600 dark:text-blue-400"),children:[n.jsx(vl,{className:"h-3 w-3 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsx("div",{className:"flex h-12 w-[140px] shrink-0 items-center justify-end",children:c?n.jsxs("div",{className:"flex w-full flex-col items-center justify-center gap-2",children:[n.jsx("div",{className:"text-center text-[11px] font-medium leading-none text-neutral-600 dark:text-neutral-400",children:"Remove item?"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",variant:"outline",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:()=>l(!1),children:"Cancel"}),n.jsx(ie,{type:"button",variant:"destructive",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:t,children:"Confirm"})]})]}):n.jsxs("div",{className:"flex items-center justify-end gap-1.5 whitespace-nowrap",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":e.qty===1?"Remove item":"Decrease quantity",onClick:()=>{if(e.qty===1){l(!0);return}r(e.qty-1)},children:e.qty===1?n.jsx(MC,{className:"h-4 w-4"}):"-"}),n.jsx(Be,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const h=Math.floor(Number(p.target.value));if(!Number.isFinite(h))return;const _=Math.max(1,d?Math.min(d,h):h);r(_)},className:"h-8 w-11 px-2 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]})})]})})]}):n.jsxs("div",{className:H("grid grid-cols-[64px_1fr] items-start gap-x-4 gap-y-3 sm:grid-cols-[64px_1fr_176px_120px]",o),children:[n.jsx("div",{className:"h-16 w-16 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:e.imageSnapshot?n.jsx("img",{src:e.imageSnapshot,alt:e.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsxs("div",{className:"col-start-2 row-start-1 min-w-0",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsx("div",{className:"truncate text-sm font-medium text-neutral-950 dark:text-neutral-50",children:e.titleSnapshot}),n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50 sm:hidden",children:Qe({amount:i,currency:e.currency})})]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[Qe({amount:e.unitPrice,currency:e.currency})," each"]}),u&&n.jsxs("div",{className:H("mt-1.5 flex items-center gap-1 text-xs",u.type==="error"&&"text-red-600 dark:text-red-400",u.type==="warning"&&"text-amber-600 dark:text-amber-400",u.type==="info"&&"text-blue-600 dark:text-blue-400"),children:[n.jsx(vl,{className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsxs("div",{className:"col-span-2 col-start-1 row-start-2 flex items-center justify-between gap-3 sm:col-span-1 sm:col-start-3 sm:row-start-1 sm:justify-center",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Decrease quantity",onClick:()=>r(Math.max(1,e.qty-1)),children:"-"}),n.jsx(Be,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const h=Math.floor(Number(p.target.value));if(!Number.isFinite(h))return;const _=Math.max(1,d?Math.min(d,h):h);r(_)},className:"h-9 w-14 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-9 px-2 text-xs text-red-600 dark:text-red-400 sm:hidden",onClick:t,children:"Remove"})]}),n.jsxs("div",{className:"hidden sm:col-start-4 sm:row-start-1 sm:flex sm:flex-col sm:items-center sm:text-center",children:[n.jsx("div",{className:"text-sm font-semibold tabular-nums text-neutral-950 dark:text-neutral-50",children:Qe({amount:i,currency:e.currency})}),n.jsx(ie,{type:"button",variant:"ghost",className:"mt-1 h-8 px-2 text-xs text-red-600 dark:text-red-400",onClick:t,children:"Remove"})]})]})}function Oi({currency:e,subtotal:t,itemCount:r,onCheckout:s,isCheckoutDisabled:o,checkoutDisabledReason:a,onRemoveUnavailable:i,className:c}){return n.jsxs("div",{className:H("space-y-4",c),children:[n.jsx(St,{}),n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsxs("div",{className:"flex items-center gap-2 text-neutral-600 dark:text-neutral-400",children:[n.jsx("span",{children:"Subtotal"}),typeof r=="number"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-neutral-300 dark:text-neutral-700",children:"·"}),n.jsxs("span",{className:"tabular-nums",children:[r," item",r===1?"":"s"]})]}):null]}),n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:t,currency:e})})]}),n.jsx(ie,{type:"button",onClick:s,disabled:o,className:"w-full",children:"Checkout"}),o&&a&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-center text-xs text-amber-600 dark:text-amber-400",children:a}),i&&n.jsx("button",{type:"button",onClick:i,className:"mx-auto block text-xs text-neutral-500 underline underline-offset-2 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-300",children:"Remove unavailable items"})]})]})}function $p({onCheckout:e,className:t}){const{config:r}=Re(),s=Dt(),{getItemInventory:o,hasIssues:a}=Za({items:s.items,refreshInterval:3e4,skip:s.items.length===0}),i=()=>{for(const c of s.items){const l=o(c.productId,c.variantId);(l?.isOutOfStock||l?.exceedsAvailable)&&s.removeItem(c.productId,c.variantId)}};return s.items.length===0?n.jsx(tr,{title:"Cart is empty",description:"Add items from the catalog to check out.",className:t}):n.jsxs("div",{className:H("flex h-full flex-col rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-800 dark:bg-neutral-950",t),children:[n.jsx("div",{className:"-mr-4 min-h-0 flex-1 overflow-y-auto overflow-x-hidden pr-4",children:n.jsx("div",{className:"divide-y divide-neutral-200 dark:divide-neutral-800",children:s.items.map(c=>n.jsx("div",{className:"py-3",children:n.jsx(Ri,{variant:"compact",item:c,onRemove:()=>s.removeItem(c.productId,c.variantId),onSetQty:l=>s.setQty(c.productId,c.variantId,l),inventory:o(c.productId,c.variantId)})},`${c.productId}::${c.variantId??""}`))})}),n.jsx("div",{className:"mt-4 space-y-4",children:n.jsx(Oi,{currency:r.currency,subtotal:s.subtotal,itemCount:s.count,onCheckout:e,isCheckoutDisabled:s.items.length===0||a,checkoutDisabledReason:a?"Some items have inventory issues":void 0,onRemoveUnavailable:a?i:void 0})})]})}const zp=x.forwardRef(({className:e,...t},r)=>n.jsx("textarea",{ref:r,className:H("flex min-h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-950 shadow-sm transition-colors placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-50/20",e),...t}));zp.displayName="Textarea";function 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 Go(){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:Go(),role:"agent",text:"Hi! How can we help today? We can recommend products or answer support questions.",createdAt:Date.now()}]),[c,l]=x.useState("…");x.useEffect(()=>{if(!s)return;const h=[".","..","..."];let _=0;const g=window.setInterval(()=>{_=(_+1)%h.length,l(h[_])},450);return()=>window.clearInterval(g)},[s]);const d=x.useRef(null),m=x.useRef(null);x.useEffect(()=>{const h=d.current;h&&(h.scrollTop=h.scrollHeight)},[a.length]);const u=x.useCallback(()=>{const h=m.current;if(!h)return;const _=120;h.style.height="0px";const g=Math.min(_,Math.max(40,h.scrollHeight));h.style.height=`${g}px`,h.style.overflowY=h.scrollHeight>_?"auto":"hidden"},[]);x.useEffect(()=>{u()},[t,u]);const p=x.useCallback(()=>{const h=t.trim();h&&(i(_=>[..._,{id:Go(),role:"user",text:h,createdAt:Date.now()}]),r(""),o(!0),window.setTimeout(()=>{i(_=>[..._,{id:Go(),role:"agent",text:"Got it. Want recommendations, sizing help, or help with an order?",createdAt:Date.now()}]),o(!1)},450))},[t]);return n.jsxs("div",{className:H("flex h-full min-h-0 flex-col",e),children:[n.jsxs("div",{ref:d,className:"min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain rounded-2xl border border-neutral-200 bg-white p-4 dark:border-neutral-800 dark:bg-neutral-950",children:[a.map(h=>n.jsx(bl,{className:H("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsx("div",{className:H("max-w-[85%] rounded-2xl px-3 py-2 text-sm leading-5",h.role==="user"?"bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900":"bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50"),children:n.jsx("span",{className:"whitespace-pre-wrap break-words",children:h.text})})},h.id)),s?n.jsx(bl,{className:"flex justify-start",children:n.jsx("div",{className:"max-w-[85%] rounded-2xl bg-neutral-100 px-3 py-2 text-sm leading-5 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",children:c})}):null]}),n.jsxs("div",{className:"mt-3 flex shrink-0 items-end gap-2",children:[n.jsx(zp,{ref:m,rows:1,value:t,onChange:h=>r(h.target.value),placeholder:"Type a message…",className:"max-h-[120px] resize-none",onKeyDown:h=>{h.key==="Enter"&&(h.shiftKey||(h.preventDefault(),p()))}}),n.jsx(ie,{type:"button",onClick:p,disabled:!t.trim(),className:"h-10 shrink-0",children:"Send"})]})]})}function $r({trigger:e,side:t="right",open:r,onOpenChange:s,onCheckout:o,preferredTab:a,className:i}){const[c,l]=x.useState(a??"cart");return x.useEffect(()=>{r&&l(a??"cart")},[r,a]),n.jsxs(no,{modal:!1,open:r,onOpenChange:s,children:[e?n.jsx(ro,{asChild:!0,children:e}):null,n.jsxs(Fr,{side:t,overlayClassName:t==="popup"?"pointer-events-none bg-transparent backdrop-blur-none":"pointer-events-none bg-neutral-950/40 backdrop-blur-none",className:H(t==="bottom"?"h-[85vh] rounded-t-2xl":void 0,t==="popup"?"shadow-xl":"w-full sm:max-w-md",t==="popup"?"h-[min(640px,calc(100vh-2rem))]":void 0,t==="popup"?void 0:"p-4","flex flex-col overflow-hidden",i),children:[n.jsx(so,{className:"space-y-0",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx(Si,{value:c,onValueChange:d=>l(d),children:n.jsxs(uo,{className:"h-9",children:[n.jsx(Lr,{value:"cart",className:"text-sm",children:"Cart"}),n.jsx(Lr,{value:"chat",className:"text-sm",children:"Chat"})]})}),n.jsx(Um,{asChild:!0,children:n.jsx(ie,{type:"button",size:"icon",variant:"ghost",className:"h-9 w-9 rounded-full text-lg leading-none","aria-label":"Close cart",children:"X"})})]})}),n.jsx("div",{className:"mt-3 min-h-0 flex-1 overflow-hidden",children:c==="chat"?n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Get help finding a product or ask us any questions. We’re both your shopping assistant and support chat."}),n.jsx("div",{className:"mt-3 min-h-0 flex-1",children:n.jsx(LC,{className:"h-full"})})]}):n.jsx($p,{onCheckout:()=>{o(),s?.(!1)},className:"h-full border-0 bg-transparent p-0 shadow-none"})})]})]})}function Mi({value:e,onApply:t,className:r}){const[s,o]=x.useState(e??"");return x.useEffect(()=>{o(e??"")},[e]),n.jsxs("div",{className:H("space-y-2",r),children:[n.jsx("div",{className:"text-sm font-medium text-neutral-950 dark:text-neutral-50",children:"Promo code"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Be,{value:s,onChange:a=>o(a.target.value),placeholder:"SAVE10","aria-label":"Promo code"}),n.jsx(ie,{type:"button",variant:"outline",onClick:()=>t(s.trim()||void 0),children:"Apply"})]})]})}function Fp({onCheckout:e,showPromoCode:t,className:r}){const{config:s}=Re(),o=Dt(),{getItemInventory:a,hasIssues:i}=Za({items:o.items,refreshInterval:3e4,skip:o.items.length===0}),c=()=>{for(const l of o.items){const d=a(l.productId,l.variantId);(d?.isOutOfStock||d?.exceedsAvailable)&&o.removeItem(l.productId,l.variantId)}};return o.items.length===0?n.jsx(tr,{title:"Your cart is empty",description:"Add a few products and come back here when you're ready to check out.",className:r}):n.jsxs("div",{className:H("grid items-start gap-6 lg:grid-cols-[1fr_360px]",r),children:[n.jsxs("div",{className:"self-start rounded-2xl border border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsxs("div",{className:"hidden grid-cols-[64px_1fr_176px_120px] gap-x-4 px-5 py-3 text-xs font-medium text-neutral-500 dark:text-neutral-400 sm:grid",children:[n.jsx("div",{}),n.jsx("div",{children:"Item"}),n.jsx("div",{className:"text-center",children:"Qty"}),n.jsx("div",{className:"text-center",children:"Total"})]}),n.jsx("div",{className:"divide-y divide-neutral-200 dark:divide-neutral-800",children:o.items.map(l=>n.jsx("div",{className:"px-4 py-4 sm:px-5",children:n.jsx(Ri,{item:l,onRemove:()=>o.removeItem(l.productId,l.variantId),onSetQty:d=>o.setQty(l.productId,l.variantId,d),inventory:a(l.productId,l.variantId)})},`${l.productId}::${l.variantId??""}`))})]}),n.jsx("div",{className:"lg:sticky lg:top-24 self-start",children:n.jsxs("div",{className:"rounded-2xl border border-neutral-200 bg-white p-5 shadow-sm dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Summary"}),n.jsx(St,{className:"my-4"}),n.jsxs("div",{className:"space-y-4",children:[t?n.jsx(Mi,{value:o.promoCode,onApply:o.setPromoCode}):null,n.jsx(Oi,{currency:s.currency,subtotal:o.subtotal,onCheckout:e,isCheckoutDisabled:o.items.length===0||i,checkoutDisabledReason:i?"Some items have inventory issues":void 0,onRemoveUnavailable:i?c:void 0})]})]})})]})}function Bp({left:e,right:t,className:r}){return n.jsxs("div",{className:H("grid items-start gap-8 lg:grid-cols-[1fr_420px]",r),children:[n.jsx("div",{children:e}),n.jsx("div",{children:t})]})}function _a({title:e,value:t,onChange:r,errors:s,className:o}){return n.jsxs("section",{className:H("space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",o),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:e}),n.jsxs("div",{className:"grid gap-3",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-line1`,children:"Address line 1"}),n.jsx(Be,{id:`${e}-line1`,value:t.line1,onChange:a=>r({...t,line1:a.target.value}),"aria-invalid":!!s?.line1}),s?.line1?n.jsx("div",{className:"text-xs text-red-600",children:s.line1}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-line2`,children:"Address line 2"}),n.jsx(Be,{id:`${e}-line2`,value:t.line2??"",onChange:a=>r({...t,line2:a.target.value})})]}),n.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-city`,children:"City"}),n.jsx(Be,{id:`${e}-city`,value:t.city,onChange:a=>r({...t,city:a.target.value}),"aria-invalid":!!s?.city}),s?.city?n.jsx("div",{className:"text-xs text-red-600",children:s.city}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-state`,children:"State"}),n.jsx(Be,{id:`${e}-state`,value:t.state??"",onChange:a=>r({...t,state:a.target.value})})]})]}),n.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-postal`,children:"Postal code"}),n.jsx(Be,{id:`${e}-postal`,value:t.postalCode,onChange:a=>r({...t,postalCode:a.target.value}),"aria-invalid":!!s?.postalCode}),s?.postalCode?n.jsx("div",{className:"text-xs text-red-600",children:s.postalCode}):null]}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:`${e}-country`,children:"Country"}),n.jsx(Be,{id:`${e}-country`,value:t.country,onChange:a=>r({...t,country:a.target.value}),"aria-invalid":!!s?.country}),s?.country?n.jsx("div",{className:"text-xs text-red-600",children:s.country}):null]})]})]})]})}function Up({methods:e,value:t,onChange:r,currency:s,className:o}){return e.length===0?null:n.jsxs("section",{className:H("space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",o),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Shipping method"}),n.jsx("div",{className:"space-y-2",children:e.map(a=>{const i=a.id===t;return n.jsxs(ie,{type:"button",variant:i?"default":"outline",className:"h-auto w-full justify-between px-4 py-3",onClick:()=>r(a.id),"aria-pressed":i,children:[n.jsxs("div",{className:"text-left",children:[n.jsx("div",{className:"text-sm font-medium",children:a.label}),a.detail?n.jsx("div",{className:"text-xs opacity-80",children:a.detail}):null]}),n.jsx("div",{className:"text-sm font-semibold",children:Qe({amount:a.price,currency:a.currency||s})})]},a.id)})})]})}function Qo({message:e}){return e?n.jsx("div",{className:"text-xs text-red-600",children:e}):null}function Wp({className:e}){const{config:t}=Re(),r=$s(),s=Dt(),o=t.checkout.mode,a=x.useMemo(()=>cs(s.items,{requireEmail:t.checkout.requireEmail??!0,defaultMode:o,allowShipping:t.checkout.allowShipping??!1}),[s.items,t.checkout.allowShipping,t.checkout.requireEmail,o]),i=(t.checkout.allowShipping??!1)&&a.shippingAddress&&(o==="shipping"||o==="full"),c=a.email!=="none"||a.name!=="none"||a.phone!=="none",l={line1:"",line2:"",city:"",state:"",postalCode:"",country:"US"},d=r.values.shippingAddress??l,m=r.values.billingAddress??l,u=Bd({enabled:!!t.adapter.getShippingMethods&&i,customer:{email:r.values.email||void 0,name:r.values.name||void 0,shippingAddress:d}});return n.jsxs("form",{className:H("space-y-6",e),onSubmit:p=>p.preventDefault(),children:[a.isDigitalOnly?n.jsx(Rt,{className:"rounded-2xl",children:n.jsxs(Gt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Digital delivery"}),n.jsx("div",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:a.fulfillmentNotes||"This is a digital product and will be available from your account after purchase."})]})}):null,a.hasPhysical&&!(t.checkout.allowShipping??!1)?n.jsx(Rt,{className:"rounded-2xl border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/30",children:n.jsxs(Gt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-red-900 dark:text-red-200",children:"Shipping required"}),n.jsx("div",{className:"mt-1 text-sm text-red-800/90 dark:text-red-200/80",children:"Your cart contains shippable items, but shipping is disabled for this checkout."})]})}):null,c?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Contact"}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:a.email==="required"||a.name==="required"||a.phone==="required"?"Required":"Optional"})]}),n.jsxs("div",{className:"grid gap-3",children:[a.email!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-email",children:"Email"}),n.jsx(Be,{id:"checkout-email",value:r.values.email??"",onChange:p=>r.setField("email",p.target.value),placeholder:"you@company.com","aria-invalid":!!r.fieldErrors.email,required:a.email==="required"}),n.jsx(Qo,{message:r.fieldErrors.email})]}):null,a.name!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-name",children:"Name"}),n.jsx(Be,{id:"checkout-name",value:r.values.name??"",onChange:p=>r.setField("name",p.target.value),placeholder:"Full name","aria-invalid":!!r.fieldErrors.name,required:a.name==="required"}),n.jsx(Qo,{message:r.fieldErrors.name})]}):null,a.phone!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-phone",children:"Phone"}),n.jsx(Be,{id:"checkout-phone",value:r.values.phone??"",onChange:p=>r.setField("phone",p.target.value),placeholder:"Phone number","aria-invalid":!!r.fieldErrors.phone,required:a.phone==="required"}),n.jsx(Qo,{message:r.fieldErrors.phone})]}):null]})]}):null,i?n.jsx(_a,{title:"Shipping address",value:d,onChange:p=>r.setField("shippingAddress",p),errors:{line1:r.fieldErrors["shippingAddress.line1"],city:r.fieldErrors["shippingAddress.city"],postalCode:r.fieldErrors["shippingAddress.postalCode"],country:r.fieldErrors["shippingAddress.country"]}}):null,i&&u.methods.length?n.jsx(Up,{methods:u.methods,value:r.values.shippingMethodId,onChange:p=>r.setField("shippingMethodId",p),currency:t.currency}):null,o==="full"?n.jsx(_a,{title:"Billing address",value:m,onChange:p=>r.setField("billingAddress",p)}):null,t.checkout.allowTipping?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Tip"}),n.jsxs("div",{className:"grid gap-2",children:[n.jsxs(at,{htmlFor:"checkout-tip",children:["Tip amount (",t.currency,")"]}),n.jsx(Be,{id:"checkout-tip",inputMode:"decimal",value:String(r.values.tipAmount??0),onChange:p=>r.setField("tipAmount",Number(p.target.value)||0)})]})]}):null,o==="full"?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Notes"}),n.jsxs("div",{className:"grid gap-2",children:[n.jsx(at,{htmlFor:"checkout-notes",children:"Order notes (optional)"}),n.jsx(Be,{id:"checkout-notes",value:r.values.notes??"",onChange:p=>r.setField("notes",p.target.value),placeholder:"Delivery instructions, gift note…"})]})]}):null]})}function Vp(){if(typeof window>"u")return!1;const e=window,t=["phantom","solflare","backpack","glow","slope","sollet","coin98","clover","mathWallet","ledger","torus","walletconnect"];for(const r of t){const s=e[r];if(s&&typeof s=="object"&&"solana"in s&&s.solana)return!0}return!!e.solana}const $C=Object.freeze(Object.defineProperty({__proto__:null,detectSolanaWallets:Vp},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(eo,{className:H("sm:max-w-lg",i),children:[n.jsxs(hi,{children:[n.jsxs(to,{className:"flex items-center gap-2",children:[n.jsx(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(Bm,{className:"flex-col gap-2 sm:flex-row",children:[a?n.jsx(ie,{type:"button",variant:"outline",onClick:()=>{t(!1),a()},children:"Go to Cart"}):null,n.jsx(ie,{type:"button",onClick:()=>t(!1),children:"Continue"})]})]})})}function 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(ie,{type:"button",size:"sm",variant:"outline",onClick:()=>r(e.availableQty),children:["Update to ",e.availableQty]}):null,n.jsxs(ie,{type:"button",size:"sm",variant:"ghost",className:"text-red-600 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-950/30 dark:hover:text-red-300",onClick:t,children:[n.jsx(FC,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Remove"})]})]})]})}function Hp({className:e,ctaLabel:t,renderEmbedded:r,embeddedFallback:s,renderCustom:o,customFallback:a}){const{config:i}=Re(),c=Dt(),l=$s(),{config:d,isLoading:m}=Wd(),[u,p]=x.useState(!1);x.useEffect(()=>{p(Vp())},[]);const h=Ud({items:c.items}),[_,g]=x.useState(!1),f=x.useMemo(()=>i.checkout.paymentMethods&&i.checkout.paymentMethods.length?i.checkout.paymentMethods:[{id:"card",label:"Card",ctaLabel:"Pay now"}],[i.checkout.paymentMethods]),w=x.useMemo(()=>f.filter(A=>!(A.id==="card"&&!d.card||A.id==="crypto"&&!d.crypto||A.id==="credits"&&!d.credits||A.id==="crypto"&&!u)),[u,f,d]),[j,b]=x.useState((w[0]??f[0]).id);x.useEffect(()=>{w.length&&(w.some(S=>S.id===j)||b(w[0].id))},[j,w]),x.useEffect(()=>{l.reset()},[j]);const v=w.find(S=>S.id===j)??f.find(S=>S.id===j)??f[0],k=v.description??(j==="crypto"?"Pay using a connected wallet.":void 0),R=j==="crypto"&&!u,N=m||l.status==="validating"||l.status==="creating_session"||l.status==="redirecting"||h.isVerifying,C=t??v.ctaLabel??(i.checkout.mode==="none"?"Continue to payment":"Pay now"),T=x.useCallback(async S=>{const A=await h.verify();if(!A.ok&&A.issues.length>0){g(!0);return}l.createCheckoutSession({paymentMethodId:S})},[l,h]),O=l.session?.kind==="embedded"?l.session:null,$=l.session?.kind==="custom"?l.session:null;return n.jsxs("div",{className:H("space-y-3",e),children:[w.length>1?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs font-medium text-neutral-600 dark:text-neutral-400",children:"Payment method"}),n.jsx(Si,{value:j,onValueChange:b,children:n.jsx(uo,{className:"w-full",children:w.map(S=>n.jsx(Lr,{value:S.id,className:"flex-1",disabled:N,children:S.label},S.id))})})]}):null,l.error?n.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-900/40 dark:bg-red-950/30 dark:text-red-200",children:l.error}):null,$?n.jsx("div",{className:"space-y-3",children:o?o($):a??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Checkout session created. Provide `renderCustom` to render a custom payment UI."})}):O?n.jsx("div",{className:"space-y-3",children:r?r(O):s??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Embedded checkout session created. Provide `renderEmbedded` to render your payment UI."})}):n.jsx(ie,{type:"button",className:"w-full",disabled:c.items.length===0||N||R,onClick:()=>{T(j)},children:h.isVerifying?"Checking availability…":N?"Processing…":C}),!O&&!$?n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:R?"Install a browser wallet to enable crypto payments.":k??"You will be redirected to complete your payment."}):null,n.jsx(qp,{open:_,onOpenChange:S=>{g(S),S||h.reset()},issues:h.result?.issues??[],onRemoveItem:(S,A)=>{c.removeItem(S,A)},onUpdateQuantity:(S,A,I)=>{c.setQty(S,A,I)}})]})}function Zp({className:e}){const{config:t}=Re(),r=Dt(),s=$s(),{settings:o}=or(),a=(t.checkout.allowPromoCodes??!1)&&o.checkout.promoCodes;return n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",e),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order review"}),n.jsx(St,{className:"my-3"}),n.jsx("div",{className:"space-y-3",children:r.items.map(i=>n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[n.jsx("div",{className:"h-10 w-10 shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:i.imageSnapshot?n.jsx("img",{src:i.imageSnapshot,alt:i.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"line-clamp-1 text-sm text-neutral-950 dark:text-neutral-50",children:i.titleSnapshot}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Qty ",i.qty]})]})]}),n.jsx("div",{className:"text-sm font-semibold tabular-nums text-neutral-950 dark:text-neutral-50",children:Qe({amount:i.unitPrice*i.qty,currency:i.currency})})]},`${i.productId}::${i.variantId??""}`))}),n.jsx(St,{className:"my-3"}),a?n.jsx(Mi,{value:s.values.discountCode??r.promoCode,onApply:i=>{s.setField("discountCode",i??""),r.setPromoCode(i)}}):null,a?n.jsx(St,{className:"my-3"}):null,n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("span",{className:"text-neutral-600 dark:text-neutral-400",children:"Subtotal"}),n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:r.subtotal,currency:t.currency})})]})]})}function ho({result:e,onContinueShopping:t,onViewOrders:r,className:s}){return e.kind==="idle"?null:e.kind==="success"?n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-600 dark:text-neutral-400",children:"Receipt"}),n.jsx("h2",{className:"mt-2 text-2xl font-semibold",children:"Payment successful"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"Thanks for your purchase. You’ll receive a confirmation email shortly."}),e.order?n.jsxs("div",{className:"mt-5 rounded-xl border border-neutral-200 bg-neutral-50 p-4 dark:border-neutral-800 dark:bg-neutral-900/40",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:["Order ",e.order.id]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[new Date(e.order.createdAt).toLocaleString()," · ",e.order.status]})]}),n.jsx("div",{className:"text-sm font-semibold",children:Qe({amount:e.order.total,currency:e.order.currency})})]}),n.jsxs("div",{className:"mt-3 space-y-2",children:[e.order.items.slice(0,4).map((o,a)=>n.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[n.jsx("div",{className:"min-w-0 truncate",children:o.title}),n.jsxs("div",{className:"shrink-0 text-neutral-600 dark:text-neutral-400",children:["Qty ",o.qty]})]},`${o.title}-${a}`)),e.order.items.length>4?n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["+",e.order.items.length-4," more item(s)"]}):null]}),n.jsxs("div",{className:"mt-3 flex gap-3 text-sm",children:[e.order.receiptUrl?n.jsx("a",{href:e.order.receiptUrl,className:"hover:underline",children:"Receipt"}):null,e.order.invoiceUrl?n.jsx("a",{href:e.order.invoiceUrl,className:"hover:underline",children:"Invoice"}):null]})]}):e.orderId?n.jsxs("p",{className:"mt-4 text-xs text-neutral-500 dark:text-neutral-400",children:["Session/Order ID: ",n.jsx("span",{className:"font-mono",children:e.orderId})]}):null,n.jsxs("div",{className:"mt-6 flex flex-col gap-2 sm:flex-row",children:[t?n.jsx(ie,{type:"button",onClick:t,children:"Continue shopping"}):null,r?n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"View orders"}):null]})]}):e.kind==="cancel"?n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Checkout cancelled"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"No charges were made. You can continue shopping and try again."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]}):n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Payment failed"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:e.message??"Something went wrong while processing your payment."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]})}function UC({onContinueShopping:e,onViewOrders:t,className:r,receiptClassName:s}){const o=Va();return o.kind==="idle"?n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",r),children:n.jsx("div",{className:"text-center text-neutral-600 dark:text-neutral-400",children:"Loading order details..."})}):n.jsx("div",{className:H("flex min-h-[50vh] items-center justify-center p-4",r),children:n.jsx(ho,{result:o,onContinueShopping:e,onViewOrders:t,className:H("w-full max-w-lg",s)})})}function 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(ho,{result:s,onContinueShopping:e,className:H("w-full max-w-lg",r)})})}function VC(e){switch(e){case"created":return"secondary";case"paid":return"default";case"processing":return"secondary";case"fulfilled":return"outline";case"shipped":return"default";case"delivered":return"outline";case"cancelled":return"outline";case"refunded":return"outline";default:return"secondary"}}function Gp({order:e,onView:t,className:r}){const s=`${e.items.length} item${e.items.length===1?"":"s"}`,o=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),a=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(Rt,{className:H("group overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm transition-shadow hover:shadow-md dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsx(Gt,{className:"p-5",children:n.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-x-4 gap-y-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsx("div",{className:"mt-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:o})]}),n.jsx("div",{className:"flex items-start justify-end",children:n.jsx(Pn,{variant:VC(e.status),className:"capitalize",children:a})}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:s}),n.jsx("div",{className:"text-right text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:e.total,currency:e.currency})}),n.jsxs("div",{className:"col-span-2 mt-3 flex items-center justify-between gap-3 border-t border-neutral-200/70 pt-3 dark:border-neutral-800",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:()=>t(e),children:"Details"}):null]})]})})})}function Qp({orders:e,onView:t,className:r}){return n.jsx("div",{className:H("grid gap-4",r),children:e.map(s=>n.jsx(Gp,{order:s,onView:t},s.id))})}function qC(e){switch(e){case"paid":return"default";case"processing":return"secondary";case"fulfilled":return"outline";case"cancelled":return"outline";case"refunded":return"outline";default:return"secondary"}}function Yp({order:e,onBack:t,className:r}){const s=new Date(e.createdAt).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),o=e.status.charAt(0).toUpperCase()+e.status.slice(1);return n.jsx(Rt,{className:H("overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsxs(Gt,{className:"p-6",children:[n.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-neutral-600 dark:text-neutral-400",children:[n.jsx("span",{children:s}),n.jsx("span",{className:"text-neutral-300 dark:text-neutral-700",children:"·"}),n.jsx("span",{children:o})]})]}),n.jsxs("div",{className:"flex items-center gap-2 sm:justify-end",children:[n.jsx(Pn,{variant:qC(e.status),className:"capitalize",children:o}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:t,children:"Back"}):null]})]}),n.jsx(St,{className:"my-5"}),n.jsx("div",{className:"space-y-3",children:e.items.map((a,i)=>n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"truncate text-sm text-neutral-950 dark:text-neutral-50",children:a.title}),n.jsxs("div",{className:"mt-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:["Qty ",a.qty]})]}),n.jsx("div",{className:"text-right text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:a.unitPrice*a.qty,currency:a.currency})})]},`${a.title}-${i}`))}),n.jsx(St,{className:"my-5"}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Total"}),n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:Qe({amount:e.total,currency:e.currency})})]}),e.receiptUrl||e.invoiceUrl?n.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-2",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}):null]})})}function Di(e){const t={};e.shippingProfile&&(t.shippingProfile=e.shippingProfile),e.checkoutRequirements&&(t.checkoutRequirements=JSON.stringify(e.checkoutRequirements)),e.fulfillment?.type&&(t.fulfillmentType=e.fulfillment.type),e.fulfillment?.notes&&(t.fulfillmentNotes=e.fulfillment.notes);const r=e.attributes?.shippingCountries;return typeof r=="string"&&r.trim()&&(t.shippingCountries=r),Object.keys(t).length?t:void 0}function 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}=Re(),o=Dt(),a=mo(),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 F=window.matchMedia?.("(min-width: 1024px)");if(!F)return;const ee=()=>m(F.matches);return ee(),F.addEventListener?.("change",ee),()=>F.removeEventListener?.("change",ee)},[]);const{categories:u,isLoading:p,error:h}=Ua(),_=x.useMemo(()=>qa({includeCategory:!0}),[]),[g,f]=x.useState(_?.search??""),[w,j]=x.useState(r??_?.category),[b,v]=x.useState(_?.page??1),[k,R]=x.useState(_?.sort??"featured"),[N,C]=x.useState(_?.filters??{}),{data:T,isLoading:O,error:$}=zs({category:w,search:g.trim()||void 0,filters:N,sort:k,page:b,pageSize:24}),S=x.useMemo(()=>GC(T?.items??[]),[T?.items]),{settings:A}=or(),I=A.catalog.filters,B=A.catalog.sort,D=x.useMemo(()=>{const F=[];return B.featured&&F.push({value:"featured",label:"Featured"}),B.priceAsc&&F.push({value:"price_asc",label:"Price: Low to High"}),B.priceDesc&&F.push({value:"price_desc",label:"Price: High to Low"}),F.length===0&&F.push({value:"featured",label:"Featured"}),F},[B]);x.useEffect(()=>{D.some(F=>F.value===k)||R(D[0].value)},[D,k]),Ha({search:g,sort:k,page:b,category:w,filters:N},{includeCategory:!0});const[E,P]=x.useState(!1),[z,Z]=x.useState(!1),[K,L]=x.useState(null),[W,Y]=x.useState(!1),V=F=>{j(F.slug),v(1),P(!1)},ce=x.useCallback((F,ee,pe)=>{o.addItem({productId:F.id,variantId:ee?.id,unitPrice:F.price,currency:F.currency,titleSnapshot:ee?`${F.title} — ${ee.title}`:F.title,imageSnapshot:F.images[0]?.url,paymentResource:F.id,metadata:Di(F)},pe),a?.toast({title:"Added to cart",description:F.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(i.cart):(l("cart"),Z(!0)))}})},[o,i.cart,a]);return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:i.shop,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(Ii,{value:g,onChange:f})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(no,{open:E,onOpenChange:P,children:[n.jsx(ro,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Fr,{side:"left",children:[n.jsx(so,{children:n.jsx(oo,{children:"Browse"})}),n.jsxs("div",{className:"mt-4",children:[h?n.jsx(Zt,{description:h}):null,p?n.jsxs("div",{className:"space-y-2",children:[n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"})]}):n.jsxs("div",{className:"space-y-6",children:[n.jsx(wa,{categories:u,activeSlug:w,onSelect:V}),n.jsx(Ts,{facets:S,value:N,onChange:F=>{C(F),v(1)},onClear:()=>{C({}),v(1)},enabledFilters:I}),D.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Ns,{value:k,onValueChange:F=>{R(F),v(1)},children:[n.jsx(Or,{"aria-label":"Sort",children:n.jsx(Ps,{placeholder:"Sort"})}),n.jsx(Mr,{children:D.map(F=>n.jsx(Dr,{value:F.value,children:F.label},F.value))})]})]})]})]})]})]}),n.jsx($r,{open:!d&&z,onOpenChange:Z,side:"bottom",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx($r,{open:d&&z,onOpenChange:Z,side:"popup",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(i.checkout)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",z?"lg:hidden":void 0),onClick:()=>{l("chat"),Z(!0)},"aria-label":"Open chat",children:[n.jsx(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(Rt,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:[n.jsx(Er,{className:"pb-4",children:n.jsx(Tr,{className:"text-base",children:"Browse"})}),n.jsxs(Gt,{className:"flex-1 space-y-6 overflow-y-auto pr-2",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Categories"}),h?n.jsx(Zt,{className:"mt-3",description:h}):null,p?n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"})]}):n.jsx("div",{className:"mt-3",children:n.jsx(wa,{categories:u,activeSlug:w,onSelect:V})})]}),D.length>1&&n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsx("div",{className:"mt-2",children:n.jsxs(Ns,{value:k,onValueChange:F=>{R(F),v(1)},children:[n.jsx(Or,{"aria-label":"Sort",children:n.jsx(Ps,{placeholder:"Sort"})}),n.jsx(Mr,{children:D.map(F=>n.jsx(Dr,{value:F.value,children:F.label},F.value))})]})})]}),n.jsx(Ts,{facets:S,value:N,onChange:F=>{C(F),v(1)},onClear:()=>{C({}),v(1)},enabledFilters:I})]})]})})}),n.jsxs("section",{children:[n.jsx("div",{className:"flex items-end justify-between gap-3",children:n.jsxs("div",{children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:A.shopPage.title||"Shop"}),A.shopPage.description&&n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:A.shopPage.description})]})}),$?n.jsx(Zt,{className:"mt-6",description:$}):null,O?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((F,ee)=>n.jsx(De,{className:"aspect-[4/5] rounded-2xl"},ee))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(fo,{products:T?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:F=>i.product(F.slug),onAddToCart:F=>ce(F,null,1),onQuickView:F=>{L(F),Y(!0)},layout:A.shopLayout.layout,imageCrop:A.shopLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:b<=1,onClick:()=>v(F=>Math.max(1,F-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",b]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!T?.hasNextPage,onClick:()=>v(F=>F+1),children:"Next"})]})]})]})]}),n.jsx(Ei,{product:K,open:W,onOpenChange:Y,productHref:F=>i.product(F),onAddToCart:(F,ee,pe)=>ce(F,ee,pe)})]})}function 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}=Re(),o=Dt(),a=mo(),{categories:i}=Ua(),[c,l]=x.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(min-width: 1024px)")?.matches??!1);x.useEffect(()=>{if(typeof window>"u")return;const q=window.matchMedia?.("(min-width: 1024px)");if(!q)return;const ne=()=>l(q.matches);return ne(),q.addEventListener?.("change",ne),()=>q.removeEventListener?.("change",ne)},[]);const[d,m]=x.useState(!1),[u,p]=x.useState(!1),[h,_]=x.useState("cart"),g=x.useMemo(()=>qa({includeCategory:!1}),[]),[f,w]=x.useState(g?.search??""),[j,b]=x.useState(g?.page??1),[v,k]=x.useState(g?.sort??"featured"),[R,N]=x.useState(g?.filters??{}),[C,T]=x.useState(null),[O,$]=x.useState(!1),S=i.find(q=>q.slug===e)??null,{data:A,isLoading:I,error:B}=zs({category:e,search:f.trim()||void 0,filters:R,sort:v,page:j,pageSize:24}),D=r?.product??(q=>`/product/${q}`),E=r?.shop??"/shop",P=r?.cart??"/cart",z=r?.checkout??"/checkout",Z=x.useMemo(()=>{const q=A?.items??[],ne=new Set;let le=Number.POSITIVE_INFINITY,fe=0;for(const qe of q){for(const He of qe.tags??[])ne.add(He);le=Math.min(le,qe.price),fe=Math.max(fe,qe.price)}const Pe=Array.from(ne).slice(0,12),Ve=Number.isFinite(le)?{min:le,max:fe}:void 0;return{tags:Pe,price:Ve}},[A?.items]),{settings:K}=or(),L=K.catalog.filters,W=K.catalog.sort,Y=x.useMemo(()=>{const q=[];return W.featured&&q.push({value:"featured",label:"Featured"}),W.priceAsc&&q.push({value:"price_asc",label:"Price: Low to High"}),W.priceDesc&&q.push({value:"price_desc",label:"Price: High to Low"}),q.length===0&&q.push({value:"featured",label:"Featured"}),q},[W]);x.useEffect(()=>{Y.some(q=>q.value===v)||k(Y[0].value)},[Y,v]),Ha({search:f,sort:v,page:j,filters:R},{includeCategory:!1});const V=x.useCallback((q,ne,le)=>{o.addItem({productId:q.id,variantId:ne?.id,unitPrice:q.price,currency:q.currency,titleSnapshot:ne?`${q.title} — ${ne.title}`:q.title,imageSnapshot:q.images[0]?.url,paymentResource:q.id,metadata:Di(q)},le),a?.toast({title:"Added to cart",description:q.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(P):(_("cart"),p(!0)))}})},[o,P,a]),ce=q=>{N(q),b(1)},F=()=>{N({}),b(1)},ee=q=>{k(q),b(1)},pe=n.jsx(Rt,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:n.jsxs(Gt,{className:"flex-1 space-y-5 overflow-y-auto pr-2 pt-6",children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-neutral-500 dark:text-neutral-400",children:"Category"}),n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2 text-xs",children:n.jsx("a",{href:E,children:"All categories"})})]}),n.jsx("div",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:S?.name??e}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:S?.description??"Browse products in this category."})]}),Y.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Ns,{value:v,onValueChange:ee,children:[n.jsx(Or,{"aria-label":"Sort",children:n.jsx(Ps,{placeholder:"Sort"})}),n.jsx(Mr,{children:Y.map(q=>n.jsx(Dr,{value:q.value,children:q.label},q.value))})]})]}),n.jsx(St,{}),n.jsx(Ts,{facets:Z,value:R,onChange:ce,onClear:F,enabledFilters:L})]})});return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:E,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(Ii,{value:f,onChange:w})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(no,{open:d,onOpenChange:m,children:[n.jsx(ro,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Fr,{side:"left",children:[n.jsx(so,{children:n.jsx(oo,{children:"Filters"})}),n.jsx("div",{className:"mt-4",children:pe})]})]}),n.jsx($r,{open:!c&&u,onOpenChange:p,side:"bottom",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(z)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>_("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx($r,{open:c&&u,onOpenChange:p,side:"popup",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(z)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>_("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(z)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",u?"lg:hidden":void 0),onClick:()=>{_("chat"),p(!0)},"aria-label":"Open chat",children:[n.jsx(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:E},{label:S?.name??e}]}),n.jsxs("div",{className:"mt-6",children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:S?.name??"Category"}),n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:S?.description??"Browse products in this category."})]}),B?n.jsx(Zt,{className:"mt-6",description:B}):null,n.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:pe})}),n.jsx("div",{children:I?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((q,ne)=>n.jsx(De,{className:"aspect-[4/5] rounded-2xl"},ne))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(fo,{products:A?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:q=>D(q.slug),onAddToCart:q=>V(q,null,1),onQuickView:q=>{T(q),$(!0)},layout:K.categoryLayout.layout,imageCrop:K.categoryLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:j<=1,onClick:()=>b(q=>Math.max(1,q-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",j]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!A?.hasNextPage,onClick:()=>b(q=>q+1),children:"Next"})]})]})})]}),n.jsx(Ei,{product:C,open:O,onOpenChange:$,productHref:q=>D(q),onAddToCart:(q,ne,le)=>V(q,ne,le)})]})]})}function XC(e){return!e||typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function JC({slug:e,className:t,routes:r}){const s=Dt(),o=mo(),{product:a,isLoading:i,error:c}=$d(e),[l,d]=x.useState(1),[m,u]=x.useState({selectedOptions:{},variant:null});x.useEffect(()=>{if(!a||!a.variants?.length)return;const S=a.variants[0];u({selectedOptions:{...S.options},variant:S})},[a?.id]);const{settings:p}=or(),{mode:h,maxItems:_}=p.relatedProducts,g=Vd({productId:a?.id,enabled:h==="ai"&&!!a?.id}),f=x.useMemo(()=>h==="by_category"&&a?.categoryIds?.length?{category:a.categoryIds[0],page:1,pageSize:_+1}:{page:1,pageSize:_+4},[h,_,a?.categoryIds]),w=zs(f),j=x.useMemo(()=>{const A=(w.data?.items??[]).filter(I=>I.slug!==e);if(h==="manual"&&a){const I=a.attributes?.relatedProductIds||a.attributes?.related_product_ids;if(I){const B=XC(String(I));if(B.length>0){const D=new Map(A.map(P=>[P.id,P]));return B.map(P=>D.get(P)).filter(P=>!!P).slice(0,_)}}}if(h==="ai"&&g.relatedProductIds&&g.relatedProductIds.length>0){const I=new Map(A.map(D=>[D.id,D])),B=g.relatedProductIds.map(D=>I.get(D)).filter(D=>!!D);if(B.length>0)return B.slice(0,_)}return A.slice(0,_)},[w.data?.items,e,h,_,a,g.relatedProductIds]),b=r?.shop??"/shop",v=r?.checkout??"/checkout",k=r?.cart??"/cart",R=r?.product??(S=>`/product/${S}`);if(i)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsxs("div",{className:"mx-auto max-w-6xl",children:[n.jsx(De,{className:"h-5 w-40"}),n.jsxs("div",{className:"mt-6 grid gap-8 lg:grid-cols-2",children:[n.jsx(De,{className:"aspect-square rounded-2xl"}),n.jsxs("div",{className:"space-y-4",children:[n.jsx(De,{className:"h-8 w-2/3"}),n.jsx(De,{className:"h-6 w-32"}),n.jsx(De,{className:"h-20"}),n.jsx(De,{className:"h-11"})]})]})]})});if(c)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsx("div",{className:"mx-auto max-w-6xl",children:n.jsx(Zt,{description:c})})});if(!a)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsx("div",{className:"mx-auto max-w-6xl",children:n.jsx(Zt,{description:"Product not found."})})});const N=m.variant?.price??a.price,C=m.variant?.compareAtPrice??a.compareAtPrice,T=a.inventoryStatus==="out_of_stock"||typeof a.inventoryQuantity=="number"&&a.inventoryQuantity<=0,O=()=>{T||(s.addItem({productId:a.id,variantId:m.variant?.id,unitPrice:N,currency:a.currency,titleSnapshot:m.variant?`${a.title} — ${m.variant.title}`:a.title,imageSnapshot:a.images[0]?.url,paymentResource:a.id,metadata:Di(a)},l),o?.toast({title:"Added to cart",description:a.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&window.location.assign(k)}}))},$=()=>{T||(O(),typeof window<"u"&&window.location.assign(v))};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-8",children:[n.jsx(Ti,{items:[{label:"Shop",href:b},{label:a.title}]}),n.jsxs("div",{className:"mt-6 grid gap-10 lg:grid-cols-2",children:[n.jsx(Ni,{images:a.images}),n.jsxs("div",{className:"space-y-6",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:a.title}),n.jsx("div",{className:"mt-3",children:n.jsx(po,{amount:N,currency:a.currency,compareAt:C})}),T?n.jsx("div",{className:"mt-2 text-sm font-medium text-red-700 dark:text-red-300",children:"Out of stock"}):typeof a.inventoryQuantity=="number"&&a.inventoryQuantity>0&&a.inventoryQuantity<=5?n.jsxs("div",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:["Only ",n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:a.inventoryQuantity})," left"]}):null,n.jsx("p",{className:"mt-4 text-sm text-neutral-600 dark:text-neutral-400",children:a.description})]}),n.jsx(Pi,{product:a,value:{selectedOptions:m.selectedOptions,variantId:m.variant?.id},onChange:S=>u(S)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(Ai,{qty:l,onChange:d}),n.jsx(ie,{type:"button",onClick:O,className:"flex-1",disabled:T,children:T?"Out of stock":"Add to cart"}),n.jsx(ie,{type:"button",variant:"outline",onClick:$,disabled:T,children:"Buy now"})]}),(p.sections.showDescription||p.sections.showSpecs||p.sections.showShipping)&&n.jsxs(dp,{type:"single",collapsible:!0,defaultValue:p.sections.showDescription?"desc":void 0,children:[p.sections.showDescription&&n.jsxs(Sr,{value:"desc",children:[n.jsx(Cr,{children:"Description"}),n.jsx(Nr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.description})})]}),p.sections.showSpecs&&n.jsxs(Sr,{value:"specs",children:[n.jsx(Cr,{children:"Specs"}),n.jsx(Nr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.attributes?n.jsx("div",{className:"space-y-1",children:Object.entries(a.attributes).map(([S,A])=>n.jsxs("div",{children:[n.jsxs("span",{className:"font-medium text-neutral-950 dark:text-neutral-50",children:[S,":"]})," ",String(A)]},S))}):"No specs provided."})})]}),p.sections.showShipping&&n.jsxs(Sr,{value:"ship",children:[n.jsx(Cr,{children:"Shipping & returns"}),n.jsx(Nr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Ships in 2–3 business days. Easy returns within 30 days."})})]})]})]})]}),p.sections.showRelatedProducts&&j.length?n.jsxs("section",{className:"mt-12",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Related products"}),n.jsx("div",{className:"mt-4",children:n.jsx(fo,{products:j,columns:{base:2,md:4,lg:4},layout:p.relatedProducts.layout.layout,imageCrop:p.relatedProducts.layout.imageCrop,getProductHref:S=>R(S.slug),onAddToCart:S=>s.addItem({productId:S.id,unitPrice:S.price,currency:S.currency,titleSnapshot:S.title,imageSnapshot:S.images[0]?.url,paymentResource:S.id},1)})})]}):null]})})}function eN({className:e,checkoutHref:t}){const{config:r}=Re(),{settings:s}=or(),o=t??"/checkout",a=r.checkout.allowPromoCodes&&s.checkout.promoCodes;return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-10",children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Cart"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"Review items, adjust quantities, then check out."}),n.jsx("div",{className:"mt-8",children:n.jsx(Fp,{onCheckout:()=>{typeof window<"u"&&window.location.assign(o)},showPromoCode:a})})]})})}function tN({className:e,routes:t}){const{config:r}=Re(),s=Dt(),o=Va(),a=r.customer?.isSignedIn??!!r.customer?.id,c=!(r.checkout.requireAccount?!1:r.checkout.guestCheckout??!0)&&!a;x.useEffect(()=>{o.kind==="success"&&s.clear()},[o.kind]);const l=t?.shop??"/shop",d=t?.orders??"/account/orders",m=t?.login;return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-10",children:[n.jsx(ho,{result:o,onContinueShopping:()=>{typeof window<"u"&&window.location.assign(l)},onViewOrders:()=>{typeof window<"u"&&window.location.assign(d)}}),o.kind==="idle"?n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Checkout"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:r.checkout.mode==="none"?"Confirm and pay.":"Enter details, then complete payment."})]}),n.jsx("div",{className:"mt-8",children:n.jsx(Ld,{children:c?n.jsxs(Rt,{className:"rounded-2xl",children:[n.jsx(Er,{className:"pb-4",children:n.jsx(Tr,{className:"text-base",children:"Sign in required"})}),n.jsxs(Gt,{children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"This store requires an account to complete checkout."}),m?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",onClick:()=>{typeof window<"u"&&window.location.assign(m)},children:"Sign in"})}):null]})]}):n.jsx(Bp,{left:n.jsxs("div",{className:"space-y-6",children:[n.jsx(Wp,{}),n.jsxs(Rt,{className:"rounded-2xl",children:[n.jsx(Er,{className:"pb-4",children:n.jsx(Tr,{className:"text-base",children:"Payment"})}),n.jsxs(Gt,{children:[n.jsx(St,{className:"mb-4"}),n.jsx(Hp,{})]})]})]}),right:n.jsx("div",{className:"lg:sticky lg:top-24",children:n.jsx(Zp,{})})})})})]}):null]})})}function nN({className:e,isSignedIn:t=!0,onLogin:r}){const{orders:s,isLoading:o,error:a}=zd(),[i,c]=x.useState(null);return t?n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-5xl px-4 py-10 sm:py-12",children:[n.jsxs("header",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Orders"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"View past purchases and receipts."})]}),!o&&!a&&!i&&s.length>0?n.jsxs("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:[s.length," order",s.length===1?"":"s"]}):null]}),a?n.jsx(Zt,{className:"mt-8",description:a}):null,o?n.jsxs("div",{className:"mt-8 grid gap-4",children:[n.jsx(De,{className:"h-32 rounded-2xl"}),n.jsx(De,{className:"h-32 rounded-2xl"}),n.jsx(De,{className:"h-32 rounded-2xl"})]}):s.length===0?n.jsx("div",{className:"mt-8",children:n.jsx(tr,{title:"No orders yet",description:"When you purchase something, it will show up here."})}):i?n.jsx("div",{className:"mt-8",children:n.jsx(Yp,{order:i,onBack:()=>c(null)})}):n.jsx("div",{className:"mt-8",children:n.jsx(Qp,{orders:s,onView:c})})]})}):n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-10 dark:bg-neutral-950",e),children:n.jsx("div",{className:"mx-auto max-w-4xl",children:n.jsx(tr,{title:"Sign in to view your orders",description:"Your purchase history will appear here once you're logged in.",actionLabel:r?"Sign in":void 0,onAction:r})})})}function rN({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 sN({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 oN(e){switch(e){case"x402":return"Crypto (x402)";case"credits":return"Credits";case"stripe":return"Card";default:return"Payment"}}function aN({order:e,source:t,purchaseId:r,customerEmail:s,customerName:o,className:a,onBack:i}){const{config:c}=Re(),l=t??e.source,d=r??e.purchaseId,m=s??e.customerEmail,u=o??e.customerName,p=c.brand?.name??"Store",h=c.brand?.logoUrl,_=()=>{typeof window<"u"&&window.print()},g=new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"}),f=new Date(e.createdAt).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return n.jsxs("div",{className:H("min-h-screen bg-neutral-100 dark:bg-neutral-900 print:bg-white print:dark:bg-white",a),children:[n.jsx("div",{className:"border-b border-neutral-200 bg-white px-4 py-3 dark:border-neutral-800 dark:bg-neutral-950 print:hidden",children:n.jsxs("div",{className:"mx-auto flex max-w-2xl items-center justify-between",children:[i?n.jsxs(ie,{type:"button",variant:"ghost",size:"sm",onClick:i,children:[n.jsx(sN,{className:"mr-1"})," Back"]}):n.jsx("div",{}),n.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:_,children:[n.jsx(rN,{className:"mr-2"})," Print Receipt"]})]})}),n.jsx("div",{className:"mx-auto max-w-2xl px-4 py-8 print:max-w-none print:px-0 print:py-0",children:n.jsxs("div",{className:"rounded-xl border border-neutral-200 bg-white p-8 shadow-sm dark:border-neutral-800 dark:bg-neutral-950 print:border-0 print:shadow-none print:dark:bg-white print:dark:text-neutral-950",children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-neutral-200 pb-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[h?n.jsx("img",{src:h,alt:p,className:"h-10 w-10 rounded-lg object-contain"}):null,n.jsx("div",{className:"text-xl font-semibold",children:p})]}),n.jsxs("div",{className:"text-right",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Receipt"}),n.jsx("div",{className:"mt-1 font-mono text-sm",children:e.id})]})]}),n.jsxs("div",{className:"mt-6 grid grid-cols-2 gap-4 text-sm sm:grid-cols-3",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Date"}),n.jsx("div",{className:"mt-1 font-medium",children:g}),n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:f})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Payment Method"}),n.jsx("div",{className:"mt-1 font-medium",children:oN(l)})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Status"}),n.jsx("div",{className:"mt-1",children:n.jsx(Pn,{variant:"outline",className:"capitalize print:border-neutral-300",children:e.status})})]})]}),(u||m)&&n.jsxs("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Customer"}),u&&n.jsx("div",{className:"mt-1 font-medium",children:u}),m&&n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:m})]}),n.jsx("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-neutral-200 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("th",{className:"pb-3 text-left font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Item"}),n.jsx("th",{className:"pb-3 text-center font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Qty"}),n.jsx("th",{className:"pb-3 text-right font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Price"})]})}),n.jsx("tbody",{children:e.items.map((w,j)=>n.jsxs("tr",{className:"border-b border-neutral-100 dark:border-neutral-800/50 print:dark:border-neutral-100",children:[n.jsx("td",{className:"py-3",children:n.jsx("div",{className:"font-medium",children:w.title})}),n.jsx("td",{className:"py-3 text-center text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:w.qty}),n.jsx("td",{className:"py-3 text-right",children:Qe({amount:w.unitPrice*w.qty,currency:w.currency})})]},`${w.title}-${j}`))})]})}),n.jsxs("div",{className:"mt-4 flex flex-col items-end gap-2 text-sm",children:[n.jsxs("div",{className:"flex w-48 justify-between",children:[n.jsx("span",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Subtotal"}),n.jsx("span",{children:Qe({amount:e.total,currency:e.currency})})]}),n.jsxs("div",{className:"flex w-48 justify-between border-t border-neutral-200 pt-2 text-base font-semibold dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("span",{children:"Total"}),n.jsx("span",{children:Qe({amount:e.total,currency:e.currency})})]})]}),d&&n.jsxs("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Transaction ID"}),n.jsx("div",{className:"mt-1 break-all font-mono text-xs",children:d})]}),n.jsxs("div",{className:"mt-8 border-t border-neutral-200 pt-6 text-center text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400 print:dark:border-neutral-200 print:dark:text-neutral-500",children:[n.jsx("p",{children:"Thank you for your purchase!"}),n.jsx("p",{className:"mt-1",children:"If you have any questions, please contact support."})]})]})})]})}function iN({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 cN({className:e,title:t="Choose Your Plan",subtitle:r="Select the plan that best fits your needs.",annualSavingsBadge:s="2 months free",popularBadgeText:o="Best Deal",footerNotice:a}){const{config:i}=Re(),{tiers:c,status:l,isLoading:d,error:m}=Fd(),[u,p]=x.useState("monthly"),h=!!i.adapter.createSubscriptionCheckoutSession,_=async g=>{if(!i.adapter.createSubscriptionCheckoutSession)return;const f=await i.adapter.createSubscriptionCheckoutSession({tierId:g,interval:u,successUrl:i.checkout.successUrl,cancelUrl:i.checkout.cancelUrl});f.kind==="redirect"&&typeof window<"u"&&window.location.assign(f.url)};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-16",children:[n.jsxs("div",{className:"text-center",children:[n.jsx("h1",{className:"text-5xl font-bold tracking-tight",children:t}),n.jsx("p",{className:"mt-4 text-base text-neutral-600 dark:text-neutral-400",children:r})]}),n.jsx("div",{className:"mt-10 flex justify-center",children:n.jsxs("div",{className:"inline-flex items-center rounded-full bg-neutral-200/60 p-1 dark:bg-neutral-800/60",children:[n.jsxs("button",{type:"button",onClick:()=>p("annual"),className:H("relative flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-all",u==="annual"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:["Yearly",s&&n.jsx("span",{className:H("rounded-full px-2 py-0.5 text-xs font-medium",u==="annual"?"bg-white/20 text-white dark:bg-neutral-900/20 dark:text-neutral-900":"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900"),children:s})]}),n.jsx("button",{type:"button",onClick:()=>p("monthly"),className:H("rounded-full px-4 py-2 text-sm font-medium transition-all",u==="monthly"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:"Monthly"})]})}),m?n.jsx(Zt,{className:"mt-10",description:m}):null,d?n.jsxs("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[n.jsx(De,{className:"h-[480px] rounded-2xl"}),n.jsx(De,{className:"h-[480px] rounded-2xl"}),n.jsx(De,{className:"h-[480px] rounded-2xl"})]}):c.length===0?n.jsx("div",{className:"mt-12",children:n.jsx(tr,{title:"No plans available",description:"Subscription plans will appear here once configured."})}):n.jsx("div",{className:"mt-12 grid gap-6 md:grid-cols-3 items-start",children:c.map(g=>{const f=l?.isActive&&l.currentTierId===g.id,w=u==="annual"&&g.priceAnnual?g.priceAnnual:g.priceMonthly,j=g.isPopular,b=g.inventoryQuantity!=null,v=b?Math.max(0,(g.inventoryQuantity??0)-(g.inventorySold??0)):null,k=b&&v===0,R=b&&v!=null&&v>0&&v<=5,[N,...C]=g.features;return n.jsxs("div",{className:H("relative flex flex-col rounded-2xl border p-6 transition-shadow",j?"border-neutral-900 bg-neutral-900 text-white shadow-xl dark:border-white dark:bg-white dark:text-neutral-900":"border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-900"),children:[j&&o&&n.jsx("div",{className:"absolute -top-3 right-4",children:n.jsx("span",{className:"rounded-full bg-neutral-100 px-3 py-1 text-xs font-semibold text-neutral-900 shadow-sm dark:bg-neutral-800 dark:text-white",children:o})}),n.jsxs("div",{className:"mb-6",children:[n.jsx("h3",{className:"text-xl font-bold",children:g.title}),g.description&&n.jsx("p",{className:H("mt-2 text-sm leading-relaxed",j?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:g.description})]}),n.jsxs("div",{className:"mb-6",children:[n.jsx("div",{className:"text-5xl font-bold tracking-tight",children:Qe({amount:w,currency:g.currency||i.currency})}),n.jsxs("div",{className:H("mt-2 text-sm",j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:["Per ",u==="annual"?"year":"month",", billed ",u==="annual"?"annually":"monthly"]})]}),b&&n.jsx("div",{className:H("mb-3 text-xs font-medium",k?"text-red-600 dark:text-red-400":R?j?"text-amber-300 dark:text-amber-600":"text-amber-600 dark:text-amber-400":j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:k?"Sold out":`${v} remaining`}),n.jsx(ie,{type:"button",className:H("mb-6 w-full rounded-full py-3 font-medium",j?"bg-white text-neutral-900 hover:bg-neutral-100 dark:bg-neutral-900 dark:text-white dark:hover:bg-neutral-800":""),variant:j?"default":"outline",disabled:f||!h||k,onClick:()=>void _(g.id),children:k?"Sold Out":f?"Current Plan":"Purchase"}),N&&n.jsx("div",{className:H("mb-4 text-sm font-semibold",j?"":"text-neutral-900 dark:text-white"),children:N}),C.length>0&&n.jsx("ul",{className:"space-y-3",children:C.map((T,O)=>n.jsxs("li",{className:"flex items-start gap-3",children:[n.jsx(iN,{className:H("mt-0.5",j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400")}),n.jsx("span",{className:H("text-sm leading-relaxed",j?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:T})]},O))})]},g.id)})}),a&&n.jsx("div",{className:"mt-12 text-center",children:n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400 leading-relaxed max-w-2xl mx-auto",children:a})})]})})}function lN(e){const{processCartCheckout:t}=Rs();return x.useMemo(()=>({...e,async createCheckoutSession(r){const s=await t(r.cart,r.options.successUrl,r.options.cancelUrl,r.options.metadata,r.customer.email,r.options.discountCode);if(!s.success)throw new Error(s.error||"Checkout failed");return{kind:"redirect",url:r.options.successUrl??"/"}},async resolveCheckoutReturn({query:r}){return Wa(r)}}),[e,t])}const dN=Object.freeze(Object.defineProperty({__proto__:null,Accordion:dp,AccordionContent:Nr,AccordionItem:Sr,AccordionTrigger:Cr,AddressForm:_a,Badge:Pn,Breadcrumbs:Ti,Button:ie,Card:Rt,CardContent:Gt,CardDescription:iu,CardFooter:cu,CardHeader:Er,CardTitle:Tr,CartLineItem:Ri,CartPageContent:Fp,CartPanel:$p,CartProvider:tg,CartSidebar:$r,CartSummary:Oi,CartTemplate:eN,CategoryNav:wa,CategoryTemplate:KC,CedrosShopProvider:Lh,CheckoutCancelPage:WC,CheckoutForm:Wp,CheckoutLayout:Bp,CheckoutProvider:Ld,CheckoutReceipt:ho,CheckoutSuccessPage:UC,CheckoutTemplate:tN,Dialog:pi,DialogClose:Gk,DialogContent:eo,DialogDescription:gi,DialogFooter:Bm,DialogHeader:hi,DialogOverlay:fi,DialogPortal:Fm,DialogTitle:to,DialogTrigger:Zk,EmptyState:tr,ErrorBoundary:PS,ErrorState:Zt,FAQItem:Mp,FAQList:NC,FilterPanel:Ts,Input:Be,InventoryVerificationDialog:qp,Label:at,OrderCard:Gp,OrderDetails:Yp,OrderList:Qp,OrderReview:Zp,PaymentStep:Hp,Price:po,ProductCard:Dp,ProductGallery:Ni,ProductGrid:fo,ProductTemplate:JC,PromoCodeInput:Mi,PurchaseHistoryTemplate:nN,QuantitySelector:Ai,QuickViewDialog:Ei,ReceiptTemplate:aN,SearchInput:Ii,Select:Ns,SelectContent:Mr,SelectGroup:Pk,SelectItem:Dr,SelectTrigger:Or,SelectValue:Ps,Separator:St,Sheet:no,SheetClose:Um,SheetContent:Fr,SheetDescription:Vm,SheetHeader:so,SheetOverlay:xi,SheetPortal:Wm,SheetTitle:oo,SheetTrigger:ro,ShippingMethodSelector:Up,ShopTemplate:QC,Skeleton:De,SubscriptionTemplate:cN,Tabs:Si,TabsContent:Ep,TabsList:uo,TabsTrigger:Lr,ToastProvider:sC,VariantSelector:Pi,createMockCommerceAdapter:Uh,createPaywallCommerceAdapter:Zh,parseCheckoutReturn:Wa,readCatalogUrlState:qa,useAIRelatedProducts:Vd,useCart:Dt,useCartInventory:Za,useCatalogUrlSync:Ha,useCategories:Ua,useCedrosPayCheckoutAdapter:lN,useCedrosShop:Re,useCheckout:$s,useCheckoutResultFromUrl:Va,useHoldExpiry:Ub,useInventoryVerification:Ud,useOptionalToast:mo,useOrders:zd,usePaymentMethodsConfig:Wd,useProduct:$d,useProducts:zs,useShippingMethods:Bd,useStandaloneCheckout:Rb,useStorefrontSettings:or,useSubscriptionData:Fd,useToast:rC,validateCommerceAdapterContract:Hb},Symbol.toStringTag,{value:"Module"}));exports.CEDROS_EVENTS=gn;exports.CSP_PRESETS=Nf;exports.CedrosPay=Lf;exports.CedrosPayAdminDashboard=xh;exports.CouponsSection=zl;exports.CreditsButton=Pa;exports.CreditsSubscribeButton=_h;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=Cf;exports.RefundsSection=Fl;exports.SECURITY_RECOMMENDATIONS=Dh;exports.SettingsSection=Ia;exports.StripeButton=Na;exports.SubscribeButton=wh;exports.SubscriptionManagementPanel=Ph;exports.TransactionsSection=$l;exports.calculateDiscountPercentage=df;exports.cedrosPayPlugin=yh;exports.createDedupedClickHandler=Mn;exports.createTranslator=Tl;exports.detectLocale=Al;exports.emitPaymentError=kt;exports.emitPaymentProcessing=un;exports.emitPaymentStart=Ln;exports.emitPaymentSuccess=$n;exports.emitWalletConnect=Xo;exports.emitWalletConnected=Sl;exports.emitWalletError=is;exports.formatCSP=Pl;exports.formatCouponCodes=lf;exports.generateCSP=Sf;exports.generateCSPDirectives=Nl;exports.getAvailableLocales=Af;exports.getLocalizedError=Ef;exports.getModalCloseButtonStyles=Ca;exports.getUserErrorMessage=_f;exports.index=dN;exports.isRetryableError=wf;exports.loadLocale=El;exports.logSecurityReport=Mh;exports.parseCouponCodes=cf;exports.stackCheckoutCoupons=uf;exports.useCreditsPayment=Il;exports.useCreditsSubscription=Xl;exports.useLocalizedError=Tf;exports.usePaymentMode=nr;exports.useStripeCheckout=Rs;exports.useSubscription=Kl;exports.useSubscriptionManagement=Jl;exports.useTranslation=xn;exports.useX402Payment=Rl;exports.validateSecurity=Oh;
|
|
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},eS="DialogDescriptionWarning",tS=({contentRef:e,descriptionId:t})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${$m(eS).contentName}}.`;return x.useEffect(()=>{const o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(s))},[s,e,t]),null},zm=km,Fm=Cm,Bm=Pm,Ks=Am,Xs=Em,Js=Im,eo=Om,Um=Lm;const fi=zm,nS=Fm,Wm=Bm,rS=Um,hi=x.forwardRef(({className:e,...t},r)=>n.jsx(Ks,{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}));hi.displayName=Ks.displayName;const to=x.forwardRef(({className:e,children:t,...r},s)=>n.jsxs(Wm,{children:[n.jsx(hi,{}),n.jsx(Xs,{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})]}));to.displayName=Xs.displayName;const gi=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-center sm:text-left",e),...t}),Vm=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t}),no=x.forwardRef(({className:e,...t},r)=>n.jsx(Js,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));no.displayName=Js.displayName;const xi=x.forwardRef(({className:e,...t},r)=>n.jsx(eo,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));xi.displayName=eo.displayName;const ro=zm,so=Fm,qm=Um,Hm=Bm,yi=x.forwardRef(({className:e,...t},r)=>n.jsx(Ks,{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=Ks.displayName;const sS=Qa("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"}}),Br=x.forwardRef(({side:e="right",className:t,children:r,overlayClassName:s,...o},a)=>n.jsxs(Hm,{children:[n.jsx(yi,{className:s}),n.jsx(Xs,{ref:a,className:H(sS({side:e}),t),...o,children:r})]}));Br.displayName=Xs.displayName;const oo=({className:e,...t})=>n.jsx("div",{className:H("flex flex-col space-y-2 text-left",e),...t}),ao=x.forwardRef(({className:e,...t},r)=>n.jsx(Js,{ref:r,className:H("text-lg font-semibold leading-none tracking-tight",e),...t}));ao.displayName=Js.displayName;const Zm=x.forwardRef(({className:e,...t},r)=>n.jsx(eo,{ref:r,className:H("text-sm text-neutral-500 dark:text-neutral-400",e),...t}));Zm.displayName=eo.displayName;var io="Collapsible",[oS,Gm]=wn(io),[aS,vi]=oS(io),Qm=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:s,defaultOpen:o,disabled:a,onOpenChange:i,...c}=e,[l,d]=gn({prop:s,defaultProp:o??!1,onChange:i,caller:io});return n.jsx(aS,{scope:r,disabled:a,contentId:Ht(),open:l,onOpenToggle:x.useCallback(()=>d(m=>!m),[d]),children:n.jsx(be.div,{"data-state":wi(l),"data-disabled":a?"":void 0,...c,ref:t})})});Qm.displayName=io;var Ym="CollapsibleTrigger",Km=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,...s}=e,o=vi(Ym,r);return n.jsx(be.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":wi(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...s,ref:t,onClick:_e(e.onClick,o.onOpenToggle)})});Km.displayName=Ym;var bi="CollapsibleContent",Xm=x.forwardRef((e,t)=>{const{forceMount:r,...s}=e,o=vi(bi,e.__scopeCollapsible);return n.jsx(pr,{present:r||o.open,children:({present:a})=>n.jsx(iS,{...s,ref:t,present:a})})});Xm.displayName=bi;var iS=x.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:s,children:o,...a}=e,i=vi(bi,r),[c,l]=x.useState(s),d=x.useRef(null),m=Ee(t,d),u=x.useRef(0),p=u.current,h=x.useRef(0),_=h.current,g=i.open||c,f=x.useRef(g),w=x.useRef(void 0);return x.useEffect(()=>{const j=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(j)},[]),Je(()=>{const j=d.current;if(j){w.current=w.current||{transitionDuration:j.style.transitionDuration,animationName:j.style.animationName},j.style.transitionDuration="0s",j.style.animationName="none";const b=j.getBoundingClientRect();u.current=b.height,h.current=b.width,f.current||(j.style.transitionDuration=w.current.transitionDuration,j.style.animationName=w.current.animationName),l(s)}},[i.open,s]),n.jsx(be.div,{"data-state":wi(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...a,ref:m,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":_?`${_}px`:void 0,...e.style},children:g&&o})});function wi(e){return e?"open":"closed"}var cS=Qm,lS=Km,dS=Xm,zt="Accordion",uS=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[_i,mS,pS]=Ka(zt),[co]=wn(zt,[pS,Gm]),ji=Gm(),Jm=y.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(xS,{...a,ref:t}):n.jsx(gS,{...o,ref:t})})});Jm.displayName=zt;var[ep,fS]=co(zt),[tp,hS]=co(zt,{collapsible:!1}),gS=y.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},collapsible:a=!1,...i}=e,[c,l]=gn({prop:r,defaultProp:s??"",onChange:o,caller:zt});return n.jsx(ep,{scope:e.__scopeAccordion,value:y.useMemo(()=>c?[c]:[],[c]),onItemOpen:l,onItemClose:y.useCallback(()=>a&&l(""),[a,l]),children:n.jsx(tp,{scope:e.__scopeAccordion,collapsible:a,children:n.jsx(np,{...i,ref:t})})})}),xS=y.forwardRef((e,t)=>{const{value:r,defaultValue:s,onValueChange:o=()=>{},...a}=e,[i,c]=gn({prop:r,defaultProp:s??[],onChange:o,caller:zt}),l=y.useCallback(m=>c((u=[])=>[...u,m]),[c]),d=y.useCallback(m=>c((u=[])=>u.filter(p=>p!==m)),[c]);return n.jsx(ep,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:d,children:n.jsx(tp,{scope:e.__scopeAccordion,collapsible:!0,children:n.jsx(np,{...a,ref:t})})})}),[yS,lo]=co(zt),np=y.forwardRef((e,t)=>{const{__scopeAccordion:r,disabled:s,dir:o,orientation:a="vertical",...i}=e,c=y.useRef(null),l=Ee(c,t),d=mS(r),u=Bs(o)==="ltr",p=_e(e.onKeyDown,h=>{if(!uS.includes(h.key))return;const _=h.target,g=d().filter(C=>!C.ref.current?.disabled),f=g.findIndex(C=>C.ref.current===_),w=g.length;if(f===-1)return;h.preventDefault();let j=f;const b=0,v=w-1,k=()=>{j=f+1,j>v&&(j=b)},R=()=>{j=f-1,j<b&&(j=v)};switch(h.key){case"Home":j=b;break;case"End":j=v;break;case"ArrowRight":a==="horizontal"&&(u?k():R());break;case"ArrowDown":a==="vertical"&&k();break;case"ArrowLeft":a==="horizontal"&&(u?R():k());break;case"ArrowUp":a==="vertical"&&R();break}const N=j%w;g[N].ref.current?.focus()});return n.jsx(yS,{scope:r,disabled:s,direction:o,orientation:a,children:n.jsx(_i.Slot,{scope:r,children:n.jsx(be.div,{...i,"data-orientation":a,ref:l,onKeyDown:s?void 0:p})})})}),Ts="AccordionItem",[vS,ki]=co(Ts),rp=y.forwardRef((e,t)=>{const{__scopeAccordion:r,value:s,...o}=e,a=lo(Ts,r),i=fS(Ts,r),c=ji(r),l=Ht(),d=s&&i.value.includes(s)||!1,m=a.disabled||e.disabled;return n.jsx(vS,{scope:r,open:d,disabled:m,triggerId:l,children:n.jsx(cS,{"data-orientation":a.orientation,"data-state":lp(d),...c,...o,ref:t,disabled:m,open:d,onOpenChange:u=>{u?i.onItemOpen(s):i.onItemClose(s)}})})});rp.displayName=Ts;var sp="AccordionHeader",op=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=lo(zt,r),a=ki(sp,r);return n.jsx(be.h3,{"data-orientation":o.orientation,"data-state":lp(a.open),"data-disabled":a.disabled?"":void 0,...s,ref:t})});op.displayName=sp;var ga="AccordionTrigger",ap=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=lo(zt,r),a=ki(ga,r),i=hS(ga,r),c=ji(r);return n.jsx(_i.ItemSlot,{scope:r,children:n.jsx(lS,{"aria-disabled":a.open&&!i.collapsible||void 0,"data-orientation":o.orientation,id:a.triggerId,...c,...s,ref:t})})});ap.displayName=ga;var ip="AccordionContent",cp=y.forwardRef((e,t)=>{const{__scopeAccordion:r,...s}=e,o=lo(zt,r),a=ki(ip,r),i=ji(r);return n.jsx(dS,{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}})});cp.displayName=ip;function lp(e){return e?"open":"closed"}var bS=Jm,dp=rp,wS=op,up=ap,mp=cp;const pp=bS,Cr=x.forwardRef(({className:e,...t},r)=>n.jsx(dp,{ref:r,className:H("border-b border-neutral-200 dark:border-neutral-800",e),...t}));Cr.displayName=dp.displayName;const Nr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(wS,{className:"flex",children:n.jsxs(up,{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:"▾"})]})}));Nr.displayName=up.displayName;const Pr=x.forwardRef(({className:e,children:t,...r},s)=>n.jsx(mp,{ref:s,className:H("overflow-hidden text-sm",e),...r,children:n.jsx("div",{className:"pb-4 pt-0",children:t})}));Pr.displayName=mp.displayName;var Uo="rovingFocusGroup.onEntryFocus",_S={bubbles:!1,cancelable:!0},Ur="RovingFocusGroup",[xa,fp,jS]=Ka(Ur),[kS,hp]=wn(Ur,[jS]),[SS,CS]=kS(Ur),gp=x.forwardRef((e,t)=>n.jsx(xa.Provider,{scope:e.__scopeRovingFocusGroup,children:n.jsx(xa.Slot,{scope:e.__scopeRovingFocusGroup,children:n.jsx(NS,{...e,ref:t})})}));gp.displayName=Ur;var NS=x.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,orientation:s,loop:o=!1,dir:a,currentTabStopId:i,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:m=!1,...u}=e,p=x.useRef(null),h=Ee(t,p),_=Bs(a),[g,f]=gn({prop:i,defaultProp:c??null,onChange:l,caller:Ur}),[w,j]=x.useState(!1),b=pn(d),v=fp(r),k=x.useRef(!1),[R,N]=x.useState(0);return x.useEffect(()=>{const C=p.current;if(C)return C.addEventListener(Uo,b),()=>C.removeEventListener(Uo,b)},[b]),n.jsx(SS,{scope:r,orientation:s,dir:_,loop:o,currentTabStopId:g,onItemFocus:x.useCallback(C=>f(C),[f]),onItemShiftTab:x.useCallback(()=>j(!0),[]),onFocusableItemAdd:x.useCallback(()=>N(C=>C+1),[]),onFocusableItemRemove:x.useCallback(()=>N(C=>C-1),[]),children:n.jsx(be.div,{tabIndex:w||R===0?-1:0,"data-orientation":s,...u,ref:h,style:{outline:"none",...e.style},onMouseDown:_e(e.onMouseDown,()=>{k.current=!0}),onFocus:_e(e.onFocus,C=>{const T=!k.current;if(C.target===C.currentTarget&&T&&!w){const O=new CustomEvent(Uo,_S);if(C.currentTarget.dispatchEvent(O),!O.defaultPrevented){const $=v().filter(L=>L.focusable),S=$.find(L=>L.active),A=$.find(L=>L.id===g),B=[S,A,...$].filter(Boolean).map(L=>L.ref.current);vp(B,m)}}k.current=!1}),onBlur:_e(e.onBlur,()=>j(!1))})})}),xp="RovingFocusGroupItem",yp=x.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,focusable:s=!0,active:o=!1,tabStopId:a,children:i,...c}=e,l=Ht(),d=a||l,m=CS(xp,r),u=m.currentTabStopId===d,p=fp(r),{onFocusableItemAdd:h,onFocusableItemRemove:_,currentTabStopId:g}=m;return x.useEffect(()=>{if(s)return h(),()=>_()},[s,h,_]),n.jsx(xa.ItemSlot,{scope:r,id:d,focusable:s,active:o,children:n.jsx(be.span,{tabIndex:u?0:-1,"data-orientation":m.orientation,...c,ref:t,onMouseDown:_e(e.onMouseDown,f=>{s?m.onItemFocus(d):f.preventDefault()}),onFocus:_e(e.onFocus,()=>m.onItemFocus(d)),onKeyDown:_e(e.onKeyDown,f=>{if(f.key==="Tab"&&f.shiftKey){m.onItemShiftTab();return}if(f.target!==f.currentTarget)return;const w=ES(f,m.orientation,m.dir);if(w!==void 0){if(f.metaKey||f.ctrlKey||f.altKey||f.shiftKey)return;f.preventDefault();let b=p().filter(v=>v.focusable).map(v=>v.ref.current);if(w==="last")b.reverse();else if(w==="prev"||w==="next"){w==="prev"&&b.reverse();const v=b.indexOf(f.currentTarget);b=m.loop?TS(b,v+1):b.slice(v+1)}setTimeout(()=>vp(b))}}),children:typeof i=="function"?i({isCurrentTabStop:u,hasTabStop:g!=null}):i})})});yp.displayName=xp;var PS={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function AS(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ES(e,t,r){const s=AS(e.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(s))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(s)))return PS[s]}function vp(e,t=!1){const r=document.activeElement;for(const s of e)if(s===r||(s.focus({preventScroll:t}),document.activeElement!==r))return}function TS(e,t){return e.map((r,s)=>e[(t+s)%e.length])}var IS=gp,RS=yp,uo="Tabs",[OS]=wn(uo,[hp]),bp=hp(),[MS,Si]=OS(uo),wp=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,onValueChange:o,defaultValue:a,orientation:i="horizontal",dir:c,activationMode:l="automatic",...d}=e,m=Bs(c),[u,p]=gn({prop:s,onChange:o,defaultProp:a??"",caller:uo});return n.jsx(MS,{scope:r,baseId:Ht(),value:u,onValueChange:p,orientation:i,dir:m,activationMode:l,children:n.jsx(be.div,{dir:m,"data-orientation":i,...d,ref:t})})});wp.displayName=uo;var _p="TabsList",jp=x.forwardRef((e,t)=>{const{__scopeTabs:r,loop:s=!0,...o}=e,a=Si(_p,r),i=bp(r);return n.jsx(IS,{asChild:!0,...i,orientation:a.orientation,dir:a.dir,loop:s,children:n.jsx(be.div,{role:"tablist","aria-orientation":a.orientation,...o,ref:t})})});jp.displayName=_p;var kp="TabsTrigger",Sp=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,disabled:o=!1,...a}=e,i=Si(kp,r),c=bp(r),l=Pp(i.baseId,s),d=Ap(i.baseId,s),m=s===i.value;return n.jsx(RS,{asChild:!0,...c,focusable:!o,active:m,children:n.jsx(be.button,{type:"button",role:"tab","aria-selected":m,"aria-controls":d,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:l,...a,ref:t,onMouseDown:_e(e.onMouseDown,u=>{!o&&u.button===0&&u.ctrlKey===!1?i.onValueChange(s):u.preventDefault()}),onKeyDown:_e(e.onKeyDown,u=>{[" ","Enter"].includes(u.key)&&i.onValueChange(s)}),onFocus:_e(e.onFocus,()=>{const u=i.activationMode!=="manual";!m&&!o&&u&&i.onValueChange(s)})})})});Sp.displayName=kp;var Cp="TabsContent",Np=x.forwardRef((e,t)=>{const{__scopeTabs:r,value:s,forceMount:o,children:a,...i}=e,c=Si(Cp,r),l=Pp(c.baseId,s),d=Ap(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(pr,{present:o||m,children:({present:p})=>n.jsx(be.div,{"data-state":m?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!p,id:d,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:u.current?"0s":void 0},children:p&&a})})});Np.displayName=Cp;function Pp(e,t){return`${e}-trigger-${t}`}function Ap(e,t){return`${e}-content-${t}`}var LS=wp,Ep=jp,Tp=Sp,Ip=Np;const Ci=LS,mo=x.forwardRef(({className:e,...t},r)=>n.jsx(Ep,{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}));mo.displayName=Ep.displayName;const $r=x.forwardRef(({className:e,...t},r)=>n.jsx(Tp,{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}));$r.displayName=Tp.displayName;const Rp=x.forwardRef(({className:e,...t},r)=>n.jsx(Ip,{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}));Rp.displayName=Ip.displayName;function nr({title:e,description:t,actionLabel:r,onAction:s,className:o}){return n.jsx("div",{className:H("flex flex-col items-center justify-center rounded-xl border border-neutral-200 bg-white p-10 text-center dark:border-neutral-800 dark:bg-neutral-950",o),children:n.jsxs("div",{className:"max-w-sm",children:[n.jsx("h3",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:e}),t?n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}):null,r&&s?n.jsx("div",{className:"mt-5",children:n.jsx(ie,{type:"button",onClick:s,variant:"secondary",children:r})}):null]})})}function Gt({title:e,description:t,onRetry:r,className:s}){return n.jsxs("div",{className:H("rounded-xl border border-neutral-200 bg-white p-6 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h3",{className:"text-sm font-semibold",children:e??"Something went wrong"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:t}),r?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"Try again"})}):null]})}class DS 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(Gt,{description:this.state.error.message}):this.props.children}}function $S(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 zS=e=>{switch(e){case"success":return US;case"info":return VS;case"warning":return WS;case"error":return qS;default:return null}},FS=Array(12).fill(0),BS=({visible:e,className:t})=>y.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},y.createElement("div",{className:"sonner-spinner"},FS.map((r,s)=>y.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),US=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),WS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),VS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),qS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},y.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),HS=y.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},y.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),ZS=()=>{const[e,t]=y.useState(document.hidden);return y.useEffect(()=>{const r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),e};let ya=1;class GS{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],y.isValidElement(d))a=!1,this.create({id:s,type:"default",message:d});else if(YS(d)&&!d.ok){a=!1;const u=typeof r.error=="function"?await r.error(`HTTP error! status: ${d.status}`):r.error,p=typeof r.description=="function"?await r.description(`HTTP error! status: ${d.status}`):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,..._})}else if(d instanceof Error){a=!1;const u=typeof r.error=="function"?await r.error(d):r.error,p=typeof r.description=="function"?await r.description(d):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:p,..._})}else if(r.success!==void 0){a=!1;const u=typeof r.success=="function"?await r.success(d):r.success,p=typeof r.description=="function"?await r.description(d):r.description,_=typeof u=="object"&&!y.isValidElement(u)?u:{message:u};this.create({id:s,type:"success",description:p,..._})}}).catch(async d=>{if(i=["reject",d],r.error!==void 0){a=!1;const m=typeof r.error=="function"?await r.error(d):r.error,u=typeof r.description=="function"?await r.description(d):r.description,h=typeof m=="object"&&!y.isValidElement(m)?m:{message:m};this.create({id:s,type:"error",description:u,...h})}}).finally(()=>{a&&(this.dismiss(s),s=void 0),r.finally==null||r.finally.call(r)}),l=()=>new Promise((d,m)=>c.then(()=>i[0]==="reject"?m(i[1]):d(i[1])).catch(m));return typeof s!="string"&&typeof s!="number"?{unwrap:l}:Object.assign(s,{unwrap:l})},this.custom=(t,r)=>{const s=r?.id||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 ht=new GS,QS=(e,t)=>{const r=t?.id||ya++;return ht.addToast({title:e,...t,id:r}),r},YS=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",KS=QS,XS=()=>ht.toasts,JS=()=>ht.getActiveToasts(),eC=Object.assign(KS,{success:ht.success,info:ht.info,warning:ht.warning,error:ht.error,custom:ht.custom,message:ht.message,promise:ht.promise,dismiss:ht.dismiss,loading:ht.loading},{getHistory:XS,getToasts:JS});$S("[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 os(e){return e.label!==void 0}const tC=3,nC="24px",rC="16px",ul=4e3,sC=356,oC=14,aC=45,iC=200;function Ut(...e){return e.filter(Boolean).join(" ")}function cC(e){const[t,r]=e.split("-"),s=[];return t&&s.push(t),r&&s.push(r),s}const lC=e=>{var t,r,s,o,a,i,c,l,d;const{invert:m,toast:u,unstyled:p,interacting:h,setHeights:_,visibleToasts:g,heights:f,index:w,toasts:j,expanded:b,removeToast:v,defaultRichColors:k,closeButton:R,style:N,cancelButtonStyle:C,actionButtonStyle:T,className:O="",descriptionClassName:$="",duration:S,position:A,gap:I,expandByDefault:B,classNames:L,icons:E,closeButtonAriaLabel:P="Close toast"}=e,[z,Z]=y.useState(null),[K,D]=y.useState(null),[W,Y]=y.useState(!1),[V,ce]=y.useState(!1),[F,ee]=y.useState(!1),[pe,q]=y.useState(!1),[ne,le]=y.useState(!1),[fe,Pe]=y.useState(0),[qe,He]=y.useState(0),Ze=y.useRef(u.duration||S||ul),xt=y.useRef(null),Qe=y.useRef(null),Ft=w===0,dt=w+1<=g,te=u.type,xe=u.dismissible!==!1,ge=u.className||"",ut=u.descriptionClassName||"",yt=y.useMemo(()=>f.findIndex(he=>he.toastId===u.id)||0,[f,u.id]),mt=y.useMemo(()=>{var he;return(he=u.closeButton)!=null?he:R},[u.closeButton,R]),U=y.useMemo(()=>u.duration||S||ul,[u.duration,S]),re=y.useRef(0),de=y.useRef(0),ke=y.useRef(0),Se=y.useRef(null),[Le,Bn]=A.split("-"),kt=y.useMemo(()=>f.reduce((he,$e,we)=>we>=yt?he:he+$e.height,0),[f,yt]),Jt=ZS(),fr=u.invert||m,kn=te==="loading";de.current=y.useMemo(()=>yt*I+kt,[yt,kt]),y.useEffect(()=>{Ze.current=U},[U]),y.useEffect(()=>{Y(!0)},[]),y.useEffect(()=>{const he=Qe.current;if(he){const $e=he.getBoundingClientRect().height;return He($e),_(we=>[{toastId:u.id,height:$e,position:u.position},...we]),()=>_(we=>we.filter(ze=>ze.toastId!==u.id))}},[_,u.id]),y.useLayoutEffect(()=>{if(!W)return;const he=Qe.current,$e=he.style.height;he.style.height="auto";const we=he.getBoundingClientRect().height;he.style.height=$e,He(we),_(ze=>ze.find(Fe=>Fe.toastId===u.id)?ze.map(Fe=>Fe.toastId===u.id?{...Fe,height:we}:Fe):[{toastId:u.id,height:we,position:u.position},...ze])},[W,u.title,u.description,_,u.id,u.jsx,u.action,u.cancel]);const Bt=y.useCallback(()=>{ce(!0),Pe(de.current),_(he=>he.filter($e=>$e.toastId!==u.id)),setTimeout(()=>{v(u)},iC)},[u,v,_,de]);y.useEffect(()=>{if(u.promise&&te==="loading"||u.duration===1/0||u.type==="loading")return;let he;return b||h||Jt?(()=>{if(ke.current<re.current){const ze=new Date().getTime()-re.current;Ze.current=Ze.current-ze}ke.current=new Date().getTime()})():(()=>{Ze.current!==1/0&&(re.current=new Date().getTime(),he=setTimeout(()=>{u.onAutoClose==null||u.onAutoClose.call(u,u),Bt()},Ze.current))})(),()=>clearTimeout(he)},[b,h,u,te,Jt,Bt]),y.useEffect(()=>{u.delete&&(Bt(),u.onDismiss==null||u.onDismiss.call(u,u))},[Bt,u.delete]);function Un(){var he;if(E?.loading){var $e;return y.createElement("div",{className:Ut(L?.loader,u==null||($e=u.classNames)==null?void 0:$e.loader,"sonner-loader"),"data-visible":te==="loading"},E.loading)}return y.createElement(BS,{className:Ut(L?.loader,u==null||(he=u.classNames)==null?void 0:he.loader),visible:te==="loading"})}const Wn=u.icon||E?.[te]||zS(te);var Wr,an;return y.createElement("li",{tabIndex:0,ref:Qe,className:Ut(O,ge,L?.toast,u==null||(t=u.classNames)==null?void 0:t.toast,L?.default,L?.[te],u==null||(r=u.classNames)==null?void 0:r[te]),"data-sonner-toast":"","data-rich-colors":(Wr=u.richColors)!=null?Wr:k,"data-styled":!(u.jsx||u.unstyled||p),"data-mounted":W,"data-promise":!!u.promise,"data-swiped":ne,"data-removed":V,"data-visible":dt,"data-y-position":Le,"data-x-position":Bn,"data-index":w,"data-front":Ft,"data-swiping":F,"data-dismissible":xe,"data-type":te,"data-invert":fr,"data-swipe-out":pe,"data-swipe-direction":K,"data-expanded":!!(b||B&&W),"data-testid":u.testId,style:{"--index":w,"--toasts-before":w,"--z-index":j.length-w,"--offset":`${V?fe:de.current}px`,"--initial-height":B?"auto":`${qe}px`,...N,...u.style},onDragEnd:()=>{ee(!1),Z(null),Se.current=null},onPointerDown:he=>{he.button!==2&&(kn||!xe||(xt.current=new Date,Pe(de.current),he.target.setPointerCapture(he.pointerId),he.target.tagName!=="BUTTON"&&(ee(!0),Se.current={x:he.clientX,y:he.clientY})))},onPointerUp:()=>{var he,$e,we;if(pe||!xe)return;Se.current=null;const ze=Number(((he=Qe.current)==null?void 0:he.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Vn=Number((($e=Qe.current)==null?void 0:$e.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Fe=new Date().getTime()-((we=xt.current)==null?void 0:we.getTime()),et=z==="x"?ze:Vn,Sn=Math.abs(et)/Fe;if(Math.abs(et)>=aC||Sn>.11){Pe(de.current),u.onDismiss==null||u.onDismiss.call(u,u),D(z==="x"?ze>0?"right":"left":Vn>0?"down":"up"),Bt(),q(!0);return}else{var pt,vt;(pt=Qe.current)==null||pt.style.setProperty("--swipe-amount-x","0px"),(vt=Qe.current)==null||vt.style.setProperty("--swipe-amount-y","0px")}le(!1),ee(!1),Z(null)},onPointerMove:he=>{var $e,we,ze;if(!Se.current||!xe||(($e=window.getSelection())==null?void 0:$e.toString().length)>0)return;const Fe=he.clientY-Se.current.y,et=he.clientX-Se.current.x;var Sn;const pt=(Sn=e.swipeDirections)!=null?Sn:cC(A);!z&&(Math.abs(et)>1||Math.abs(Fe)>1)&&Z(Math.abs(et)>Math.abs(Fe)?"x":"y");let vt={x:0,y:0};const bt=nt=>1/(1.5+Math.abs(nt)/20);if(z==="y"){if(pt.includes("top")||pt.includes("bottom"))if(pt.includes("top")&&Fe<0||pt.includes("bottom")&&Fe>0)vt.y=Fe;else{const nt=Fe*bt(Fe);vt.y=Math.abs(nt)<Math.abs(Fe)?nt:Fe}}else if(z==="x"&&(pt.includes("left")||pt.includes("right")))if(pt.includes("left")&&et<0||pt.includes("right")&&et>0)vt.x=et;else{const nt=et*bt(et);vt.x=Math.abs(nt)<Math.abs(et)?nt:et}(Math.abs(vt.x)>0||Math.abs(vt.y)>0)&&le(!0),(we=Qe.current)==null||we.style.setProperty("--swipe-amount-x",`${vt.x}px`),(ze=Qe.current)==null||ze.style.setProperty("--swipe-amount-y",`${vt.y}px`)}},mt&&!u.jsx&&te!=="loading"?y.createElement("button",{"aria-label":P,"data-disabled":kn,"data-close-button":!0,onClick:kn||!xe?()=>{}:()=>{Bt(),u.onDismiss==null||u.onDismiss.call(u,u)},className:Ut(L?.closeButton,u==null||(s=u.classNames)==null?void 0:s.closeButton)},(an=E?.close)!=null?an:HS):null,(te||u.icon||u.promise)&&u.icon!==null&&(E?.[te]!==null||u.icon)?y.createElement("div",{"data-icon":"",className:Ut(L?.icon,u==null||(o=u.classNames)==null?void 0:o.icon)},u.promise||u.type==="loading"&&!u.icon?u.icon||Un():null,u.type!=="loading"?Wn:null):null,y.createElement("div",{"data-content":"",className:Ut(L?.content,u==null||(a=u.classNames)==null?void 0:a.content)},y.createElement("div",{"data-title":"",className:Ut(L?.title,u==null||(i=u.classNames)==null?void 0:i.title)},u.jsx?u.jsx:typeof u.title=="function"?u.title():u.title),u.description?y.createElement("div",{"data-description":"",className:Ut($,ut,L?.description,u==null||(c=u.classNames)==null?void 0:c.description)},typeof u.description=="function"?u.description():u.description):null),y.isValidElement(u.cancel)?u.cancel:u.cancel&&os(u.cancel)?y.createElement("button",{"data-button":!0,"data-cancel":!0,style:u.cancelButtonStyle||C,onClick:he=>{os(u.cancel)&&xe&&(u.cancel.onClick==null||u.cancel.onClick.call(u.cancel,he),Bt())},className:Ut(L?.cancelButton,u==null||(l=u.classNames)==null?void 0:l.cancelButton)},u.cancel.label):null,y.isValidElement(u.action)?u.action:u.action&&os(u.action)?y.createElement("button",{"data-button":!0,"data-action":!0,style:u.actionButtonStyle||T,onClick:he=>{os(u.action)&&(u.action.onClick==null||u.action.onClick.call(u.action,he),!he.defaultPrevented&&Bt())},className:Ut(L?.actionButton,u==null||(d=u.classNames)==null?void 0:d.actionButton)},u.action.label):null)};function ml(){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 dC(e,t){const r={};return[e,t].forEach((s,o)=>{const a=o===1,i=a?"--mobile-offset":"--offset",c=a?rC:nC;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 uC=y.forwardRef(function(t,r){const{id:s,invert:o,position:a="bottom-right",hotkey:i=["altKey","KeyT"],expand:c,closeButton:l,className:d,offset:m,mobileOffset:u,theme:p="light",richColors:h,duration:_,style:g,visibleToasts:f=tC,toastOptions:w,dir:j=ml(),gap:b=oC,icons:v,containerAriaLabel:k="Notifications"}=t,[R,N]=y.useState([]),C=y.useMemo(()=>s?R.filter(W=>W.toasterId===s):R.filter(W=>!W.toasterId),[R,s]),T=y.useMemo(()=>Array.from(new Set([a].concat(C.filter(W=>W.position).map(W=>W.position)))),[C,a]),[O,$]=y.useState([]),[S,A]=y.useState(!1),[I,B]=y.useState(!1),[L,E]=y.useState(p!=="system"?p:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),P=y.useRef(null),z=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),Z=y.useRef(null),K=y.useRef(!1),D=y.useCallback(W=>{N(Y=>{var V;return(V=Y.find(ce=>ce.id===W.id))!=null&&V.delete||ht.dismiss(W.id),Y.filter(({id:ce})=>ce!==W.id)})},[]);return y.useEffect(()=>ht.subscribe(W=>{if(W.dismiss){requestAnimationFrame(()=>{N(Y=>Y.map(V=>V.id===W.id?{...V,delete:!0}:V))});return}setTimeout(()=>{Sa.flushSync(()=>{N(Y=>{const V=Y.findIndex(ce=>ce.id===W.id);return V!==-1?[...Y.slice(0,V),{...Y[V],...W},...Y.slice(V+1)]:[W,...Y]})})})}),[R]),y.useEffect(()=>{if(p!=="system"){E(p);return}if(p==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?E("dark"):E("light")),typeof window>"u")return;const W=window.matchMedia("(prefers-color-scheme: dark)");try{W.addEventListener("change",({matches:Y})=>{E(Y?"dark":"light")})}catch{W.addListener(({matches:V})=>{try{E(V?"dark":"light")}catch(ce){console.error(ce)}})}},[p]),y.useEffect(()=>{R.length<=1&&A(!1)},[R]),y.useEffect(()=>{const W=Y=>{var V;if(i.every(ee=>Y[ee]||Y.code===ee)){var F;A(!0),(F=P.current)==null||F.focus()}Y.code==="Escape"&&(document.activeElement===P.current||(V=P.current)!=null&&V.contains(document.activeElement))&&A(!1)};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[i]),y.useEffect(()=>{if(P.current)return()=>{Z.current&&(Z.current.focus({preventScroll:!0}),Z.current=null,K.current=!1)}},[P.current]),y.createElement("section",{ref:r,"aria-label":`${k} ${z}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},T.map((W,Y)=>{var V;const[ce,F]=W.split("-");return C.length?y.createElement("ol",{key:W,dir:j==="auto"?ml():j,tabIndex:-1,ref:P,className:d,"data-sonner-toaster":!0,"data-sonner-theme":L,"data-y-position":ce,"data-x-position":F,style:{"--front-toast-height":`${((V=O[0])==null?void 0:V.height)||0}px`,"--width":`${sC}px`,"--gap":`${b}px`,...g,...dC(m,u)},onBlur:ee=>{K.current&&!ee.currentTarget.contains(ee.relatedTarget)&&(K.current=!1,Z.current&&(Z.current.focus({preventScroll:!0}),Z.current=null))},onFocus:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||K.current||(K.current=!0,Z.current=ee.relatedTarget)},onMouseEnter:()=>A(!0),onMouseMove:()=>A(!0),onMouseLeave:()=>{I||A(!1)},onDragEnd:()=>A(!1),onPointerDown:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||B(!0)},onPointerUp:()=>B(!1)},C.filter(ee=>!ee.position&&Y===0||ee.position===W).map((ee,pe)=>{var q,ne;return y.createElement(lC,{key:ee.id,icons:v,index:pe,toast:ee,defaultRichColors:h,duration:(q=w?.duration)!=null?q:_,className:w?.className,descriptionClassName:w?.descriptionClassName,invert:o,visibleToasts:f,closeButton:(ne=w?.closeButton)!=null?ne:l,interacting:I,position:W,style:w?.style,unstyled:w?.unstyled,classNames:w?.classNames,cancelButtonStyle:w?.cancelButtonStyle,actionButtonStyle:w?.actionButtonStyle,closeButtonAriaLabel:w?.closeButtonAriaLabel,removeToast:D,toasts:C.filter(le=>le.position==ee.position),heights:O.filter(le=>le.position==ee.position),setHeights:$,expandByDefault:c,gap:b,expanded:S,swipeDirections:t.swipeDirections})})):null}))}),Ni=x.createContext(null);function mC(){const e=x.useContext(Ni);if(!e)throw new Error("useToast must be used within ToastProvider");return e}function po(){return x.useContext(Ni)}function pC({children:e}){const t=x.useCallback(r=>{const s=r.title??"",o=r.description;eC(s||o||"Notification",{description:s?o:void 0,duration:r.durationMs??5e3,action:r.actionLabel&&r.onAction?{label:r.actionLabel,onClick:()=>r.onAction?.()}:void 0})},[]);return n.jsxs(Ni.Provider,{value:{toast:t},children:[e,n.jsx(uC,{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:Op,setPrototypeOf:pl,isFrozen:fC,getPrototypeOf:hC,getOwnPropertyDescriptor:gC}=Object;let{freeze:ct,seal:Nt,create:va}=Object,{apply:ba,construct:wa}=typeof Reflect<"u"&&Reflect;ct||(ct=function(t){return t});Nt||(Nt=function(t){return t});ba||(ba=function(t,r){for(var s=arguments.length,o=new Array(s>2?s-2:0),a=2;a<s;a++)o[a-2]=arguments[a];return t.apply(r,o)});wa||(wa=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 as=lt(Array.prototype.forEach),xC=lt(Array.prototype.lastIndexOf),fl=lt(Array.prototype.pop),xr=lt(Array.prototype.push),yC=lt(Array.prototype.splice),ps=lt(String.prototype.toLowerCase),Wo=lt(String.prototype.toString),Vo=lt(String.prototype.match),yr=lt(String.prototype.replace),vC=lt(String.prototype.indexOf),bC=lt(String.prototype.trim),Rt=lt(Object.prototype.hasOwnProperty),rt=lt(RegExp.prototype.test),vr=wC(TypeError);function lt(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return ba(e,t,s)}}function wC(e){return function(){for(var t=arguments.length,r=new Array(t),s=0;s<t;s++)r[s]=arguments[s];return wa(e,r)}}function ve(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ps;pl&&pl(e,null);let s=t.length;for(;s--;){let o=t[s];if(typeof o=="string"){const a=r(o);a!==o&&(fC(t)||(t[s]=a),o=a)}e[o]=!0}return e}function _C(e){for(let t=0;t<e.length;t++)Rt(e,t)||(e[t]=null);return e}function Wt(e){const t=va(null);for(const[r,s]of Op(e))Rt(e,r)&&(Array.isArray(s)?t[r]=_C(s):s&&typeof s=="object"&&s.constructor===Object?t[r]=Wt(s):t[r]=s);return t}function br(e,t){for(;e!==null;){const s=gC(e,t);if(s){if(s.get)return lt(s.get);if(typeof s.value=="function")return lt(s.value)}e=hC(e)}function r(){return null}return r}const hl=ct(["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"]),qo=ct(["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"]),Ho=ct(["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"]),jC=ct(["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"]),Zo=ct(["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"]),kC=ct(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),gl=ct(["#text"]),xl=ct(["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"]),Go=ct(["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"]),yl=ct(["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"]),is=ct(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),SC=Nt(/\{\{[\w\W]*|[\w\W]*\}\}/gm),CC=Nt(/<%[\w\W]*|[\w\W]*%>/gm),NC=Nt(/\$\{[\w\W]*/gm),PC=Nt(/^data-[\-\w.\u00B7-\uFFFF]+$/),AC=Nt(/^aria-[\-\w]+$/),Mp=Nt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),EC=Nt(/^(?:\w+script|data):/i),TC=Nt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Lp=Nt(/^html$/i),IC=Nt(/^[a-z][.\w]*(-[.\w]+)+$/i);var vl=Object.freeze({__proto__:null,ARIA_ATTR:AC,ATTR_WHITESPACE:TC,CUSTOM_ELEMENT:IC,DATA_ATTR:PC,DOCTYPE_NAME:Lp,ERB_EXPR:CC,IS_ALLOWED_URI:Mp,IS_SCRIPT_OR_DATA:EC,MUSTACHE_EXPR:SC,TMPLIT_EXPR:NC});const wr={element:1,text:3,progressingInstruction:7,comment:8,document:9},RC=function(){return typeof window>"u"?null:window},OC=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}},bl=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Dp(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:RC();const t=ue=>Dp(ue);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==wr.document||!e.Element)return t.isSupported=!1,t;let{document:r}=e;const s=r,o=s.currentScript,{DocumentFragment:a,HTMLTemplateElement:i,Node:c,Element:l,NodeFilter:d,NamedNodeMap:m=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:p,trustedTypes:h}=e,_=l.prototype,g=br(_,"cloneNode"),f=br(_,"remove"),w=br(_,"nextSibling"),j=br(_,"childNodes"),b=br(_,"parentNode");if(typeof i=="function"){const ue=r.createElement("template");ue.content&&ue.content.ownerDocument&&(r=ue.content.ownerDocument)}let v,k="";const{implementation:R,createNodeIterator:N,createDocumentFragment:C,getElementsByTagName:T}=r,{importNode:O}=s;let $=bl();t.isSupported=typeof Op=="function"&&typeof b=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:S,ERB_EXPR:A,TMPLIT_EXPR:I,DATA_ATTR:B,ARIA_ATTR:L,IS_SCRIPT_OR_DATA:E,ATTR_WHITESPACE:P,CUSTOM_ELEMENT:z}=vl;let{IS_ALLOWED_URI:Z}=vl,K=null;const D=ve({},[...hl,...qo,...Ho,...Zo,...gl]);let W=null;const Y=ve({},[...xl,...Go,...yl,...is]);let V=Object.seal(va(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ce=null,F=null;const ee=Object.seal(va(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let pe=!0,q=!0,ne=!1,le=!0,fe=!1,Pe=!0,qe=!1,He=!1,Ze=!1,xt=!1,Qe=!1,Ft=!1,dt=!0,te=!1;const xe="user-content-";let ge=!0,ut=!1,yt={},mt=null;const U=ve({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let re=null;const de=ve({},["audio","video","img","source","image","track"]);let ke=null;const Se=ve({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Le="http://www.w3.org/1998/Math/MathML",Bn="http://www.w3.org/2000/svg",kt="http://www.w3.org/1999/xhtml";let Jt=kt,fr=!1,kn=null;const Bt=ve({},[Le,Bn,kt],Wo);let Un=ve({},["mi","mo","mn","ms","mtext"]),Wn=ve({},["annotation-xml"]);const Wr=ve({},["title","style","font","a","script"]);let an=null;const he=["application/xhtml+xml","text/html"],$e="text/html";let we=null,ze=null;const Vn=r.createElement("form"),Fe=function(M){return M instanceof RegExp||M instanceof Function},et=function(){let M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(ze&&ze===M)){if((!M||typeof M!="object")&&(M={}),M=Wt(M),an=he.indexOf(M.PARSER_MEDIA_TYPE)===-1?$e:M.PARSER_MEDIA_TYPE,we=an==="application/xhtml+xml"?Wo:ps,K=Rt(M,"ALLOWED_TAGS")?ve({},M.ALLOWED_TAGS,we):D,W=Rt(M,"ALLOWED_ATTR")?ve({},M.ALLOWED_ATTR,we):Y,kn=Rt(M,"ALLOWED_NAMESPACES")?ve({},M.ALLOWED_NAMESPACES,Wo):Bt,ke=Rt(M,"ADD_URI_SAFE_ATTR")?ve(Wt(Se),M.ADD_URI_SAFE_ATTR,we):Se,re=Rt(M,"ADD_DATA_URI_TAGS")?ve(Wt(de),M.ADD_DATA_URI_TAGS,we):de,mt=Rt(M,"FORBID_CONTENTS")?ve({},M.FORBID_CONTENTS,we):U,ce=Rt(M,"FORBID_TAGS")?ve({},M.FORBID_TAGS,we):Wt({}),F=Rt(M,"FORBID_ATTR")?ve({},M.FORBID_ATTR,we):Wt({}),yt=Rt(M,"USE_PROFILES")?M.USE_PROFILES:!1,pe=M.ALLOW_ARIA_ATTR!==!1,q=M.ALLOW_DATA_ATTR!==!1,ne=M.ALLOW_UNKNOWN_PROTOCOLS||!1,le=M.ALLOW_SELF_CLOSE_IN_ATTR!==!1,fe=M.SAFE_FOR_TEMPLATES||!1,Pe=M.SAFE_FOR_XML!==!1,qe=M.WHOLE_DOCUMENT||!1,xt=M.RETURN_DOM||!1,Qe=M.RETURN_DOM_FRAGMENT||!1,Ft=M.RETURN_TRUSTED_TYPE||!1,Ze=M.FORCE_BODY||!1,dt=M.SANITIZE_DOM!==!1,te=M.SANITIZE_NAMED_PROPS||!1,ge=M.KEEP_CONTENT!==!1,ut=M.IN_PLACE||!1,Z=M.ALLOWED_URI_REGEXP||Mp,Jt=M.NAMESPACE||kt,Un=M.MATHML_TEXT_INTEGRATION_POINTS||Un,Wn=M.HTML_INTEGRATION_POINTS||Wn,V=M.CUSTOM_ELEMENT_HANDLING||{},M.CUSTOM_ELEMENT_HANDLING&&Fe(M.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(V.tagNameCheck=M.CUSTOM_ELEMENT_HANDLING.tagNameCheck),M.CUSTOM_ELEMENT_HANDLING&&Fe(M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(V.attributeNameCheck=M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),M.CUSTOM_ELEMENT_HANDLING&&typeof M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(V.allowCustomizedBuiltInElements=M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),fe&&(q=!1),Qe&&(xt=!0),yt&&(K=ve({},gl),W=[],yt.html===!0&&(ve(K,hl),ve(W,xl)),yt.svg===!0&&(ve(K,qo),ve(W,Go),ve(W,is)),yt.svgFilters===!0&&(ve(K,Ho),ve(W,Go),ve(W,is)),yt.mathMl===!0&&(ve(K,Zo),ve(W,yl),ve(W,is))),M.ADD_TAGS&&(typeof M.ADD_TAGS=="function"?ee.tagCheck=M.ADD_TAGS:(K===D&&(K=Wt(K)),ve(K,M.ADD_TAGS,we))),M.ADD_ATTR&&(typeof M.ADD_ATTR=="function"?ee.attributeCheck=M.ADD_ATTR:(W===Y&&(W=Wt(W)),ve(W,M.ADD_ATTR,we))),M.ADD_URI_SAFE_ATTR&&ve(ke,M.ADD_URI_SAFE_ATTR,we),M.FORBID_CONTENTS&&(mt===U&&(mt=Wt(mt)),ve(mt,M.FORBID_CONTENTS,we)),M.ADD_FORBID_CONTENTS&&(mt===U&&(mt=Wt(mt)),ve(mt,M.ADD_FORBID_CONTENTS,we)),ge&&(K["#text"]=!0),qe&&ve(K,["html","head","body"]),K.table&&(ve(K,["tbody"]),delete ce.tbody),M.TRUSTED_TYPES_POLICY){if(typeof M.TRUSTED_TYPES_POLICY.createHTML!="function")throw vr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof M.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');v=M.TRUSTED_TYPES_POLICY,k=v.createHTML("")}else v===void 0&&(v=OC(h,o)),v!==null&&typeof k=="string"&&(k=v.createHTML(""));ct&&ct(M),ze=M}},Sn=ve({},[...qo,...Ho,...jC]),pt=ve({},[...Zo,...kC]),vt=function(M){let X=b(M);(!X||!X.tagName)&&(X={namespaceURI:Jt,tagName:"template"});const ae=ps(M.tagName),Ae=ps(X.tagName);return kn[M.namespaceURI]?M.namespaceURI===Bn?X.namespaceURI===kt?ae==="svg":X.namespaceURI===Le?ae==="svg"&&(Ae==="annotation-xml"||Un[Ae]):!!Sn[ae]:M.namespaceURI===Le?X.namespaceURI===kt?ae==="math":X.namespaceURI===Bn?ae==="math"&&Wn[Ae]:!!pt[ae]:M.namespaceURI===kt?X.namespaceURI===Bn&&!Wn[Ae]||X.namespaceURI===Le&&!Un[Ae]?!1:!pt[ae]&&(Wr[ae]||!Sn[ae]):!!(an==="application/xhtml+xml"&&kn[M.namespaceURI]):!1},bt=function(M){xr(t.removed,{element:M});try{b(M).removeChild(M)}catch{f(M)}},nt=function(M,X){try{xr(t.removed,{attribute:X.getAttributeNode(M),from:X})}catch{xr(t.removed,{attribute:null,from:X})}if(X.removeAttribute(M),M==="is")if(xt||Qe)try{bt(X)}catch{}else try{X.setAttribute(M,"")}catch{}},xo=function(M){let X=null,ae=null;if(Ze)M="<remove></remove>"+M;else{const Be=Vo(M,/^[\r\n\t ]+/);ae=Be&&Be[0]}an==="application/xhtml+xml"&&Jt===kt&&(M='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+M+"</body></html>");const Ae=v?v.createHTML(M):M;if(Jt===kt)try{X=new p().parseFromString(Ae,an)}catch{}if(!X||!X.documentElement){X=R.createDocument(Jt,"template",null);try{X.documentElement.innerHTML=fr?k:Ae}catch{}}const tt=X.body||X.documentElement;return M&&ae&&tt.insertBefore(r.createTextNode(ae),tt.childNodes[0]||null),Jt===kt?T.call(X,qe?"html":"body")[0]:qe?X.documentElement:tt},$i=function(M){return N.call(M.ownerDocument||M,M,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},yo=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")},zi=function(M){return typeof c=="function"&&M instanceof c};function en(ue,M,X){as(ue,ae=>{ae.call(t,M,X,ze)})}const Fi=function(M){let X=null;if(en($.beforeSanitizeElements,M,null),yo(M))return bt(M),!0;const ae=we(M.nodeName);if(en($.uponSanitizeElement,M,{tagName:ae,allowedTags:K}),Pe&&M.hasChildNodes()&&!zi(M.firstElementChild)&&rt(/<[/\w!]/g,M.innerHTML)&&rt(/<[/\w!]/g,M.textContent)||M.nodeType===wr.progressingInstruction||Pe&&M.nodeType===wr.comment&&rt(/<[/\w]/g,M.data))return bt(M),!0;if(!(ee.tagCheck instanceof Function&&ee.tagCheck(ae))&&(!K[ae]||ce[ae])){if(!ce[ae]&&Ui(ae)&&(V.tagNameCheck instanceof RegExp&&rt(V.tagNameCheck,ae)||V.tagNameCheck instanceof Function&&V.tagNameCheck(ae)))return!1;if(ge&&!mt[ae]){const Ae=b(M)||M.parentNode,tt=j(M)||M.childNodes;if(tt&&Ae){const Be=tt.length;for(let ft=Be-1;ft>=0;--ft){const tn=g(tt[ft],!0);tn.__removalCount=(M.__removalCount||0)+1,Ae.insertBefore(tn,w(M))}}}return bt(M),!0}return M instanceof l&&!vt(M)||(ae==="noscript"||ae==="noembed"||ae==="noframes")&&rt(/<\/no(script|embed|frames)/i,M.innerHTML)?(bt(M),!0):(fe&&M.nodeType===wr.text&&(X=M.textContent,as([S,A,I],Ae=>{X=yr(X,Ae," ")}),M.textContent!==X&&(xr(t.removed,{element:M.cloneNode()}),M.textContent=X)),en($.afterSanitizeElements,M,null),!1)},Bi=function(M,X,ae){if(dt&&(X==="id"||X==="name")&&(ae in r||ae in Vn))return!1;if(!(q&&!F[X]&&rt(B,X))){if(!(pe&&rt(L,X))){if(!(ee.attributeCheck instanceof Function&&ee.attributeCheck(X,M))){if(!W[X]||F[X]){if(!(Ui(M)&&(V.tagNameCheck instanceof RegExp&&rt(V.tagNameCheck,M)||V.tagNameCheck instanceof Function&&V.tagNameCheck(M))&&(V.attributeNameCheck instanceof RegExp&&rt(V.attributeNameCheck,X)||V.attributeNameCheck instanceof Function&&V.attributeNameCheck(X,M))||X==="is"&&V.allowCustomizedBuiltInElements&&(V.tagNameCheck instanceof RegExp&&rt(V.tagNameCheck,ae)||V.tagNameCheck instanceof Function&&V.tagNameCheck(ae))))return!1}else if(!ke[X]){if(!rt(Z,yr(ae,P,""))){if(!((X==="src"||X==="xlink:href"||X==="href")&&M!=="script"&&vC(ae,"data:")===0&&re[M])){if(!(ne&&!rt(E,yr(ae,P,"")))){if(ae)return!1}}}}}}}return!0},Ui=function(M){return M!=="annotation-xml"&&Vo(M,z)},Wi=function(M){en($.beforeSanitizeAttributes,M,null);const{attributes:X}=M;if(!X||yo(M))return;const ae={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:W,forceKeepAttr:void 0};let Ae=X.length;for(;Ae--;){const tt=X[Ae],{name:Be,namespaceURI:ft,value:tn}=tt,qn=we(Be),vo=tn;let Ke=Be==="value"?vo:bC(vo);if(ae.attrName=qn,ae.attrValue=Ke,ae.keepAttr=!0,ae.forceKeepAttr=void 0,en($.uponSanitizeAttribute,M,ae),Ke=ae.attrValue,te&&(qn==="id"||qn==="name")&&(nt(Be,M),Ke=xe+Ke),Pe&&rt(/((--!?|])>)|<\/(style|title|textarea)/i,Ke)){nt(Be,M);continue}if(qn==="attributename"&&Vo(Ke,"href")){nt(Be,M);continue}if(ae.forceKeepAttr)continue;if(!ae.keepAttr){nt(Be,M);continue}if(!le&&rt(/\/>/i,Ke)){nt(Be,M);continue}fe&&as([S,A,I],qi=>{Ke=yr(Ke,qi," ")});const Vi=we(M.nodeName);if(!Bi(Vi,qn,Ke)){nt(Be,M);continue}if(v&&typeof h=="object"&&typeof h.getAttributeType=="function"&&!ft)switch(h.getAttributeType(Vi,qn)){case"TrustedHTML":{Ke=v.createHTML(Ke);break}case"TrustedScriptURL":{Ke=v.createScriptURL(Ke);break}}if(Ke!==vo)try{ft?M.setAttributeNS(ft,Be,Ke):M.setAttribute(Be,Ke),yo(M)?bt(M):fl(t.removed)}catch{nt(Be,M)}}en($.afterSanitizeAttributes,M,null)},ef=function ue(M){let X=null;const ae=$i(M);for(en($.beforeSanitizeShadowDOM,M,null);X=ae.nextNode();)en($.uponSanitizeShadowNode,X,null),Fi(X),Wi(X),X.content instanceof a&&ue(X.content);en($.afterSanitizeShadowDOM,M,null)};return t.sanitize=function(ue){let M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},X=null,ae=null,Ae=null,tt=null;if(fr=!ue,fr&&(ue="<!-->"),typeof ue!="string"&&!zi(ue))if(typeof ue.toString=="function"){if(ue=ue.toString(),typeof ue!="string")throw vr("dirty is not a string, aborting")}else throw vr("toString is not a function");if(!t.isSupported)return ue;if(He||et(M),t.removed=[],typeof ue=="string"&&(ut=!1),ut){if(ue.nodeName){const tn=we(ue.nodeName);if(!K[tn]||ce[tn])throw vr("root node is forbidden and cannot be sanitized in-place")}}else if(ue instanceof c)X=xo("<!---->"),ae=X.ownerDocument.importNode(ue,!0),ae.nodeType===wr.element&&ae.nodeName==="BODY"||ae.nodeName==="HTML"?X=ae:X.appendChild(ae);else{if(!xt&&!fe&&!qe&&ue.indexOf("<")===-1)return v&&Ft?v.createHTML(ue):ue;if(X=xo(ue),!X)return xt?null:Ft?k:""}X&&Ze&&bt(X.firstChild);const Be=$i(ut?ue:X);for(;Ae=Be.nextNode();)Fi(Ae),Wi(Ae),Ae.content instanceof a&&ef(Ae.content);if(ut)return ue;if(xt){if(Qe)for(tt=C.call(X.ownerDocument);X.firstChild;)tt.appendChild(X.firstChild);else tt=X;return(W.shadowroot||W.shadowrootmode)&&(tt=O.call(s,tt,!0)),tt}let ft=qe?X.outerHTML:X.innerHTML;return qe&&K["!doctype"]&&X.ownerDocument&&X.ownerDocument.doctype&&X.ownerDocument.doctype.name&&rt(Lp,X.ownerDocument.doctype.name)&&(ft="<!DOCTYPE "+X.ownerDocument.doctype.name+`>
|
|
136
|
+
`+ft),fe&&as([S,A,I],tn=>{ft=yr(ft,tn," ")}),v&&Ft?v.createHTML(ft):ft},t.setConfig=function(){let ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};et(ue),He=!0},t.clearConfig=function(){ze=null,He=!1},t.isValidAttribute=function(ue,M,X){ze||et({});const ae=we(ue),Ae=we(M);return Bi(ae,Ae,X)},t.addHook=function(ue,M){typeof M=="function"&&xr($[ue],M)},t.removeHook=function(ue,M){if(M!==void 0){const X=xC($[ue],M);return X===-1?void 0:yC($[ue],X,1)[0]}return fl($[ue])},t.removeHooks=function(ue){$[ue]=[]},t.removeAllHooks=function(){$=bl()},t}var MC=Dp();function $p({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:MC.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 LC({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($p,{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 Ye({amount:e,currency:t}){return new Intl.NumberFormat(void 0,{style:"currency",currency:t}).format(e)}function fo({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:Ye({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:Ye({amount:r,currency:t})}):null]})}const DC={large:"aspect-[4/5]",square:"aspect-square",compact:"aspect-[3/4]"},$C={center:"object-center",top:"object-top",bottom:"object-bottom",left:"object-left",right:"object-right"};function zp({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(Ot,{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",DC[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]",$C[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(An,{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(An,{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(An,{variant:"secondary",className:"bg-white/90 text-neutral-900 backdrop-blur dark:bg-neutral-950/80 dark:text-neutral-50",children:["Only ",l," left"]})}):null,s?n.jsx("div",{className:"absolute right-3 top-3 opacity-0 transition-opacity group-hover:opacity-100",children:n.jsx(ie,{type:"button",size:"sm",variant:"secondary",className:"h-9",onClick:()=>s(e),children:"Quick view"})}):null]}),n.jsxs("div",{className:H("flex flex-1 flex-col",a==="compact"?"p-3":"p-4"),children:[n.jsx("div",{className:"flex items-start justify-between gap-3",children:n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:H("line-clamp-1 font-medium text-neutral-950 dark:text-neutral-50",a==="compact"?"text-xs":"text-sm"),children:e.title}),n.jsx("div",{className:"mt-1",children:n.jsx(fo,{amount:e.price,currency:e.currency,compareAt:e.compareAtPrice,size:a==="compact"?"sm":"default"})})]})}),a==="large"&&n.jsx("p",{className:"mt-2 line-clamp-2 min-h-8 text-xs leading-4 text-neutral-600 dark:text-neutral-400",children:e.description}),n.jsx("div",{className:H("mt-auto",a==="compact"?"pt-3":"pt-4"),children:n.jsx(ie,{type:"button",className:"w-full",size:a==="compact"?"sm":"default",onClick:()=>r?.(e,null),disabled:c,children:c?"Out of stock":"Add to cart"})})]})]})}function ho({products:e,columns:t,onAddToCart:r,onQuickView:s,getProductHref:o,className:a,layout:i,imageCrop:c}){const l=t?.base??2,d=t?.md??3,m=t?.lg??3,u={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4"},p={1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4"},h={1:"lg:grid-cols-1",2:"lg:grid-cols-2",3:"lg:grid-cols-3",4:"lg:grid-cols-4"},_=H("grid gap-4",u[Math.min(4,Math.max(1,l))],p[Math.min(4,Math.max(1,d))],h[Math.min(4,Math.max(1,m))]);return n.jsx("div",{className:H(_,a),children:e.map(g=>n.jsx(zp,{product:g,href:o?o(g):void 0,onAddToCart:r,onQuickView:s,layout:i,imageCrop:c},g.id))})}function Pi({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 zC(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 FC(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 wl(e,t){return e.find(r=>Object.entries(t).every(([s,o])=>r.options[s]===o))??null}function Fp(e){return e.inventoryStatus==="out_of_stock"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity<=0}function BC(e){return e.inventoryStatus==="low"||typeof e.inventoryQuantity=="number"&&e.inventoryQuantity>0&&e.inventoryQuantity<=5}function UC(e){const t=Fp(e),r=!t&&BC(e),s=typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0;return{isOutOfStock:t,isLow:r,quantity:s}}function WC(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=>!Fp(i))}function Ai({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(()=>zC(i),[i]),l=x.useMemo(()=>wl(i,t.selectedOptions),[i,t.selectedOptions]),d=x.useMemo(()=>l?UC(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=FC(i,m),p=t.selectedOptions[m];return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-baseline justify-between",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-950 dark:text-neutral-50",children:m}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:p||"Select"})]}),n.jsx("div",{className:"flex flex-wrap gap-2",children:u.map(h=>{const _=h===p,g=WC(i,t.selectedOptions,m,h),f=a&&!g;return n.jsxs(ie,{type:"button",size:"sm",variant:_?"default":"outline",onClick:()=>{const w={...t.selectedOptions,[m]:h},j=wl(i,w);r({selectedOptions:w,variant:j})},"aria-pressed":_,disabled:f,className:H(!g&&!f&&"opacity-50 line-through"),children:[h,!g&&!f&&n.jsx("span",{className:"ml-1 text-[10px] opacity-70",children:"(Out)"})]},h)})})]},m)}),o&&l&&d&&n.jsx("div",{className:"pt-2",children:d.isOutOfStock?n.jsx("div",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:"Out of stock"}):d.isLow&&d.quantity!==void 0?n.jsxs("div",{className:"text-sm text-amber-600 dark:text-amber-400",children:["Only ",n.jsx("span",{className:"font-semibold",children:d.quantity})," left"]}):null})]})}function Ei({qty:e,onChange:t,min:r=1,max:s,className:o}){const a=Number.isFinite(e)?Math.max(r,Math.floor(e)):r,i=a>r,c=typeof s=="number"?a<s:!0;return n.jsxs("div",{className:H("flex items-center gap-2",o),children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(Math.max(r,a-1)),disabled:!i,"aria-label":"Decrease quantity",children:"-"}),n.jsx(Ue,{inputMode:"numeric",pattern:"[0-9]*",value:String(a),onChange:l=>{const d=Math.floor(Number(l.target.value));if(!Number.isFinite(d))return;const m=Math.max(r,typeof s=="number"?Math.min(s,d):d);t(m)},className:"h-10 w-16 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",onClick:()=>t(a+1),disabled:!c,"aria-label":"Increase quantity",children:"+"})]})}function Ti({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(fi,{open:t,onOpenChange:r,children:n.jsxs(to,{className:H("max-w-3xl",a),children:[n.jsx(gi,{children:n.jsxs(no,{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(Pi,{images:e.images}),n.jsxs("div",{className:"space-y-5",children:[n.jsxs("div",{children:[n.jsx(fo,{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(Ai,{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(Ei,{qty:i,onChange:c}),n.jsx(ie,{type:"button",className:"flex-1",onClick:()=>{o(e,l.variant,i),r(!1)},children:"Add to cart"})]}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:e.inventoryStatus==="out_of_stock"?"Out of stock":"In stock"})]})]})]})})}function _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 Ii({items:e,className:t}){return n.jsx("nav",{className:H("flex items-center gap-2 text-xs text-neutral-600 dark:text-neutral-400",t),"aria-label":"Breadcrumb",children:e.map((r,s)=>n.jsxs("span",{className:"flex items-center gap-2",children:[r.href?n.jsx("a",{href:r.href,className:"hover:underline",children:r.label}):n.jsx("span",{className:"text-neutral-900 dark:text-neutral-50",children:r.label}),s<e.length-1?n.jsx("span",{"aria-hidden":!0,children:"·"}):null]},`${r.label}-${s}`))})}function Ri({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(Ue,{value:e,onChange:o=>t(o.target.value),placeholder:r,className:"pl-9","aria-label":"Search"})]})}function Is({facets:e,value:t,onChange:r,onClear:s,className:o,enabledFilters:a}){const i=e.tags??[],c=new Set(t.tags??[]),l=a?.tags??!0,d=a?.priceRange??!0,m=a?.inStock??!0;return l||d||m?n.jsxs("div",{className:H("space-y-4",o),children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Filters"}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-8 px-2 text-xs",onClick:s,children:"Clear"})]}),n.jsx(Ct,{}),l&&i.length?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Tags"}),n.jsx("div",{className:"space-y-2",children:i.map(p=>n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:c.has(p),onChange:h=>{const _=new Set(c);h.target.checked?_.add(p):_.delete(p),r({...t,tags:Array.from(_)})}}),p]},p))})]}):null,d&&e.price?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Price"}),n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"grid gap-1",children:[n.jsx(it,{className:"text-xs",htmlFor:"price-min",children:"Min"}),n.jsx(Ue,{id:"price-min",inputMode:"decimal",placeholder:String(e.price.min),value:t.priceMin??"",onChange:p=>{const h=Number(p.target.value);r({...t,priceMin:Number.isFinite(h)&&p.target.value!==""?h:void 0})}})]}),n.jsxs("div",{className:"grid gap-1",children:[n.jsx(it,{className:"text-xs",htmlFor:"price-max",children:"Max"}),n.jsx(Ue,{id:"price-max",inputMode:"decimal",placeholder:String(e.price.max),value:t.priceMax??"",onChange:p=>{const h=Number(p.target.value);r({...t,priceMax:Number.isFinite(h)&&p.target.value!==""?h:void 0})}})]})]})]}):null,m?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-medium",children:"Availability"}),n.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300",children:[n.jsx("input",{type:"checkbox",checked:t.inStock??!1,onChange:p=>r({...t,inStock:p.target.checked})}),"In stock"]})]}):null]}):null}function _l(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 VC(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 Oi({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:Ye({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(_l,{className:"h-3 w-3 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsx("div",{className:"flex h-12 w-[140px] shrink-0 items-center justify-end",children:c?n.jsxs("div",{className:"flex w-full flex-col items-center justify-center gap-2",children:[n.jsx("div",{className:"text-center text-[11px] font-medium leading-none text-neutral-600 dark:text-neutral-400",children:"Remove item?"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",variant:"outline",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:()=>l(!1),children:"Cancel"}),n.jsx(ie,{type:"button",variant:"destructive",className:"h-7 w-[62px] px-0 text-[11px] leading-none",onClick:t,children:"Confirm"})]})]}):n.jsxs("div",{className:"flex items-center justify-end gap-1.5 whitespace-nowrap",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":e.qty===1?"Remove item":"Decrease quantity",onClick:()=>{if(e.qty===1){l(!0);return}r(e.qty-1)},children:e.qty===1?n.jsx(VC,{className:"h-4 w-4"}):"-"}),n.jsx(Ue,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const h=Math.floor(Number(p.target.value));if(!Number.isFinite(h))return;const _=Math.max(1,d?Math.min(d,h):h);r(_)},className:"h-8 w-11 px-2 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]})})]})})]}):n.jsxs("div",{className:H("grid grid-cols-[64px_1fr] items-start gap-x-4 gap-y-3 sm:grid-cols-[64px_1fr_176px_120px]",o),children:[n.jsx("div",{className:"h-16 w-16 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900",children:e.imageSnapshot?n.jsx("img",{src:e.imageSnapshot,alt:e.titleSnapshot,className:"h-full w-full object-cover"}):null}),n.jsxs("div",{className:"col-start-2 row-start-1 min-w-0",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsx("div",{className:"truncate text-sm font-medium text-neutral-950 dark:text-neutral-50",children:e.titleSnapshot}),n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50 sm:hidden",children:Ye({amount:i,currency:e.currency})})]}),n.jsxs("div",{className:"mt-1 text-xs text-neutral-600 dark:text-neutral-400",children:[Ye({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(_l,{className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{children:u.message})]})]}),n.jsxs("div",{className:"col-span-2 col-start-1 row-start-2 flex items-center justify-between gap-3 sm:col-span-1 sm:col-start-3 sm:row-start-1 sm:justify-center",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Decrease quantity",onClick:()=>r(Math.max(1,e.qty-1)),children:"-"}),n.jsx(Ue,{inputMode:"numeric",pattern:"[0-9]*",value:String(e.qty),onChange:p=>{const h=Math.floor(Number(p.target.value));if(!Number.isFinite(h))return;const _=Math.max(1,d?Math.min(d,h):h);r(_)},className:"h-9 w-14 text-center","aria-label":"Quantity"}),n.jsx(ie,{type:"button",size:"icon",variant:"outline",className:"h-9 w-9","aria-label":"Increase quantity",onClick:()=>r(d?Math.min(d,e.qty+1):e.qty+1),disabled:!m,children:"+"})]}),n.jsx(ie,{type:"button",variant:"ghost",className:"h-9 px-2 text-xs text-red-600 dark:text-red-400 sm:hidden",onClick:t,children:"Remove"})]}),n.jsxs("div",{className:"hidden sm:col-start-4 sm:row-start-1 sm:flex sm:flex-col sm:items-center sm:text-center",children:[n.jsx("div",{className:"text-sm font-semibold tabular-nums text-neutral-950 dark:text-neutral-50",children:Ye({amount:i,currency:e.currency})}),n.jsx(ie,{type:"button",variant:"ghost",className:"mt-1 h-8 px-2 text-xs text-red-600 dark:text-red-400",onClick:t,children:"Remove"})]})]})}function Mi({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(Ct,{}),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:Ye({amount:t,currency:e})})]}),n.jsx(ie,{type:"button",onClick:s,disabled:o,className:"w-full",children:"Checkout"}),o&&a&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-center text-xs text-amber-600 dark:text-amber-400",children:a}),i&&n.jsx("button",{type:"button",onClick:i,className:"mx-auto block text-xs text-neutral-500 underline underline-offset-2 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-300",children:"Remove unavailable items"})]})]})}function Bp({onCheckout:e,className:t}){const{config:r}=Oe(),s=Dt(),{getItemInventory:o,hasIssues:a}=Ga({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(nr,{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(Oi,{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(Mi,{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 Up=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}));Up.displayName="Textarea";function qC(){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 jl({children:e,className:t}){const r=x.useRef(null),s=qC();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 Qo(){return`${Date.now()}_${Math.random().toString(16).slice(2)}`}function HC({className:e}){const[t,r]=x.useState(""),[s,o]=x.useState(!1),[a,i]=x.useState(()=>[{id:Qo(),role:"agent",text:"Hi! How can we help today? We can recommend products or answer support questions.",createdAt:Date.now()}]),[c,l]=x.useState("…");x.useEffect(()=>{if(!s)return;const h=[".","..","..."];let _=0;const g=window.setInterval(()=>{_=(_+1)%h.length,l(h[_])},450);return()=>window.clearInterval(g)},[s]);const d=x.useRef(null),m=x.useRef(null);x.useEffect(()=>{const h=d.current;h&&(h.scrollTop=h.scrollHeight)},[a.length]);const u=x.useCallback(()=>{const h=m.current;if(!h)return;const _=120;h.style.height="0px";const g=Math.min(_,Math.max(40,h.scrollHeight));h.style.height=`${g}px`,h.style.overflowY=h.scrollHeight>_?"auto":"hidden"},[]);x.useEffect(()=>{u()},[t,u]);const p=x.useCallback(()=>{const h=t.trim();h&&(i(_=>[..._,{id:Qo(),role:"user",text:h,createdAt:Date.now()}]),r(""),o(!0),window.setTimeout(()=>{i(_=>[..._,{id:Qo(),role:"agent",text:"Got it. Want recommendations, sizing help, or help with an order?",createdAt:Date.now()}]),o(!1)},450))},[t]);return n.jsxs("div",{className:H("flex h-full min-h-0 flex-col",e),children:[n.jsxs("div",{ref:d,className:"min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain rounded-2xl border border-neutral-200 bg-white p-4 dark:border-neutral-800 dark:bg-neutral-950",children:[a.map(h=>n.jsx(jl,{className:H("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsx("div",{className:H("max-w-[85%] rounded-2xl px-3 py-2 text-sm leading-5",h.role==="user"?"bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900":"bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50"),children:n.jsx("span",{className:"whitespace-pre-wrap break-words",children:h.text})})},h.id)),s?n.jsx(jl,{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(Up,{ref:m,rows:1,value:t,onChange:h=>r(h.target.value),placeholder:"Type a message…",className:"max-h-[120px] resize-none",onKeyDown:h=>{h.key==="Enter"&&(h.shiftKey||(h.preventDefault(),p()))}}),n.jsx(ie,{type:"button",onClick:p,disabled:!t.trim(),className:"h-10 shrink-0",children:"Send"})]})]})}function zr({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(ro,{modal:!1,open:r,onOpenChange:s,children:[e?n.jsx(so,{asChild:!0,children:e}):null,n.jsxs(Br,{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(oo,{className:"space-y-0",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx(Ci,{value:c,onValueChange:d=>l(d),children:n.jsxs(mo,{className:"h-9",children:[n.jsx($r,{value:"cart",className:"text-sm",children:"Cart"}),n.jsx($r,{value:"chat",className:"text-sm",children:"Chat"})]})}),n.jsx(qm,{asChild:!0,children:n.jsx(ie,{type:"button",size:"icon",variant:"ghost",className:"h-9 w-9 rounded-full text-lg leading-none","aria-label":"Close cart",children:"X"})})]})}),n.jsx("div",{className:"mt-3 min-h-0 flex-1 overflow-hidden",children:c==="chat"?n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Get help finding a product or ask us any questions. We’re both your shopping assistant and support chat."}),n.jsx("div",{className:"mt-3 min-h-0 flex-1",children:n.jsx(HC,{className:"h-full"})})]}):n.jsx(Bp,{onCheckout:()=>{o(),s?.(!1)},className:"h-full border-0 bg-transparent p-0 shadow-none"})})]})]})}function Li({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(Ue,{value:s,onChange:a=>o(a.target.value),placeholder:"SAVE10","aria-label":"Promo code"}),n.jsx(ie,{type:"button",variant:"outline",onClick:()=>t(s.trim()||void 0),children:"Apply"})]})]})}function Wp({onCheckout:e,showPromoCode:t,className:r}){const{config:s}=Oe(),o=Dt(),{getItemInventory:a,hasIssues:i}=Ga({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(nr,{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(Oi,{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(Ct,{className:"my-4"}),n.jsxs("div",{className:"space-y-4",children:[t?n.jsx(Li,{value:o.promoCode,onApply:o.setPromoCode}):null,n.jsx(Mi,{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 Vp({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 ja({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(it,{htmlFor:`${e}-line1`,children:"Address line 1"}),n.jsx(Ue,{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(it,{htmlFor:`${e}-line2`,children:"Address line 2"}),n.jsx(Ue,{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(it,{htmlFor:`${e}-city`,children:"City"}),n.jsx(Ue,{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(it,{htmlFor:`${e}-state`,children:"State"}),n.jsx(Ue,{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(it,{htmlFor:`${e}-postal`,children:"Postal code"}),n.jsx(Ue,{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(it,{htmlFor:`${e}-country`,children:"Country"}),n.jsx(Ue,{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 qp({methods:e,value:t,onChange:r,currency:s,className:o}){return e.length===0?null:n.jsxs("section",{className:H("space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",o),children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Shipping method"}),n.jsx("div",{className:"space-y-2",children:e.map(a=>{const i=a.id===t;return n.jsxs(ie,{type:"button",variant:i?"default":"outline",className:"h-auto w-full justify-between px-4 py-3",onClick:()=>r(a.id),"aria-pressed":i,children:[n.jsxs("div",{className:"text-left",children:[n.jsx("div",{className:"text-sm font-medium",children:a.label}),a.detail?n.jsx("div",{className:"text-xs opacity-80",children:a.detail}):null]}),n.jsx("div",{className:"text-sm font-semibold",children:Ye({amount:a.price,currency:a.currency||s})})]},a.id)})})]})}function Yo({message:e}){return e?n.jsx("div",{className:"text-xs text-red-600",children:e}):null}function Hp({className:e}){const{config:t}=Oe(),r=zs(),s=Dt(),o=t.checkout.mode,a=x.useMemo(()=>ls(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=Vd({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(Ot,{className:"rounded-2xl",children:n.jsxs(Qt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Digital delivery"}),n.jsx("div",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:a.fulfillmentNotes||"This is a digital product and will be available from your account after purchase."})]})}):null,a.hasPhysical&&!(t.checkout.allowShipping??!1)?n.jsx(Ot,{className:"rounded-2xl border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/30",children:n.jsxs(Qt,{className:"p-5",children:[n.jsx("div",{className:"text-sm font-semibold text-red-900 dark:text-red-200",children:"Shipping required"}),n.jsx("div",{className:"mt-1 text-sm text-red-800/90 dark:text-red-200/80",children:"Your cart contains shippable items, but shipping is disabled for this checkout."})]})}):null,c?n.jsxs("section",{className:"space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-950",children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[n.jsx("div",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Contact"}),n.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:a.email==="required"||a.name==="required"||a.phone==="required"?"Required":"Optional"})]}),n.jsxs("div",{className:"grid gap-3",children:[a.email!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(it,{htmlFor:"checkout-email",children:"Email"}),n.jsx(Ue,{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(Yo,{message:r.fieldErrors.email})]}):null,a.name!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(it,{htmlFor:"checkout-name",children:"Name"}),n.jsx(Ue,{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(Yo,{message:r.fieldErrors.name})]}):null,a.phone!=="none"?n.jsxs("div",{className:"grid gap-2",children:[n.jsx(it,{htmlFor:"checkout-phone",children:"Phone"}),n.jsx(Ue,{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(Yo,{message:r.fieldErrors.phone})]}):null]})]}):null,i?n.jsx(ja,{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(qp,{methods:u.methods,value:r.values.shippingMethodId,onChange:p=>r.setField("shippingMethodId",p),currency:t.currency}):null,o==="full"?n.jsx(ja,{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(it,{htmlFor:"checkout-tip",children:["Tip amount (",t.currency,")"]}),n.jsx(Ue,{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(it,{htmlFor:"checkout-notes",children:"Order notes (optional)"}),n.jsx(Ue,{id:"checkout-notes",value:r.values.notes??"",onChange:p=>r.setField("notes",p.target.value),placeholder:"Delivery instructions, gift note…"})]})]}):null]})}function Zp(){if(typeof window>"u")return!1;const e=window,t=["phantom","solflare","backpack","glow","slope","sollet","coin98","clover","mathWallet","ledger","torus","walletconnect"];for(const r of t){const s=e[r];if(s&&typeof s=="object"&&"solana"in s&&s.solana)return!0}return!!e.solana}const ZC=Object.freeze(Object.defineProperty({__proto__:null,detectSolanaWallets:Zp},Symbol.toStringTag,{value:"Module"}));function GC(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 QC(e){return n.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[n.jsx("path",{d:"M3 6h18"}),n.jsx("path",{d:"M8 6V4h8v2"}),n.jsx("path",{d:"M6 6l1 16h10l1-16"})]})}function Gp({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(fi,{open:e,onOpenChange:t,children:n.jsxs(to,{className:H("sm:max-w-lg",i),children:[n.jsxs(gi,{children:[n.jsxs(no,{className:"flex items-center gap-2",children:[n.jsx(GC,{className:"h-5 w-5 text-amber-500"}),"Inventory Update"]}),n.jsx(xi,{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(YC,{issue:l,onRemove:()=>s(l.productId,l.variantId),onUpdateQty:d=>o(l.productId,l.variantId,d)},`${l.productId}::${l.variantId??""}`))}),n.jsxs(Vm,{className:"flex-col gap-2 sm:flex-row",children:[a?n.jsx(ie,{type:"button",variant:"outline",onClick:()=>{t(!1),a()},children:"Go to Cart"}):null,n.jsx(ie,{type:"button",onClick:()=>t(!1),children:"Continue"})]})]})})}function YC({issue:e,onRemove:t,onUpdateQty:r}){const s=e.type==="out_of_stock"||e.type==="product_unavailable";return n.jsxs("div",{className:"flex items-start gap-3 py-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-900 dark:text-neutral-100",children:e.title}),n.jsx("div",{className:H("mt-0.5 text-sm",s?"text-red-600 dark:text-red-400":"text-amber-600 dark:text-amber-400"),children:e.message}),e.type==="insufficient_stock"&&e.availableQty>0?n.jsxs("div",{className:"mt-1 text-xs text-neutral-500 dark:text-neutral-400",children:["You requested ",e.requestedQty,", but only ",e.availableQty," available"]}):null]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.type==="insufficient_stock"&&e.availableQty>0?n.jsxs(ie,{type:"button",size:"sm",variant:"outline",onClick:()=>r(e.availableQty),children:["Update to ",e.availableQty]}):null,n.jsxs(ie,{type:"button",size:"sm",variant:"ghost",className:"text-red-600 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-950/30 dark:hover:text-red-300",onClick:t,children:[n.jsx(QC,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Remove"})]})]})]})}function Qp({className:e,ctaLabel:t,renderEmbedded:r,embeddedFallback:s,renderCustom:o,customFallback:a}){const{config:i}=Oe(),c=Dt(),l=zs(),{config:d,isLoading:m}=Hd(),[u,p]=x.useState(!1);x.useEffect(()=>{p(Zp())},[]);const h=qd({items:c.items}),[_,g]=x.useState(!1),f=x.useMemo(()=>i.checkout.paymentMethods&&i.checkout.paymentMethods.length?i.checkout.paymentMethods:[{id:"card",label:"Card",ctaLabel:"Pay now"}],[i.checkout.paymentMethods]),w=x.useMemo(()=>f.filter(A=>!(A.id==="card"&&!d.card||A.id==="crypto"&&!d.crypto||A.id==="credits"&&!d.credits||A.id==="crypto"&&!u)),[u,f,d]),[j,b]=x.useState((w[0]??f[0]).id);x.useEffect(()=>{w.length&&(w.some(S=>S.id===j)||b(w[0].id))},[j,w]),x.useEffect(()=>{l.reset()},[j]);const v=w.find(S=>S.id===j)??f.find(S=>S.id===j)??f[0],k=v.description??(j==="crypto"?"Pay using a connected wallet.":void 0),R=j==="crypto"&&!u,N=m||l.status==="validating"||l.status==="creating_session"||l.status==="redirecting"||h.isVerifying,C=t??v.ctaLabel??(i.checkout.mode==="none"?"Continue to payment":"Pay now"),T=x.useCallback(async S=>{const A=await h.verify();if(!A.ok&&A.issues.length>0){g(!0);return}l.createCheckoutSession({paymentMethodId:S})},[l,h]),O=l.session?.kind==="embedded"?l.session:null,$=l.session?.kind==="custom"?l.session:null;return n.jsxs("div",{className:H("space-y-3",e),children:[w.length>1?n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs font-medium text-neutral-600 dark:text-neutral-400",children:"Payment method"}),n.jsx(Ci,{value:j,onValueChange:b,children:n.jsx(mo,{className:"w-full",children:w.map(S=>n.jsx($r,{value:S.id,className:"flex-1",disabled:N,children:S.label},S.id))})})]}):null,l.error?n.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-900/40 dark:bg-red-950/30 dark:text-red-200",children:l.error}):null,$?n.jsx("div",{className:"space-y-3",children:o?o($):a??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Checkout session created. Provide `renderCustom` to render a custom payment UI."})}):O?n.jsx("div",{className:"space-y-3",children:r?r(O):s??n.jsx("div",{className:"rounded-lg border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-700 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300",children:"Embedded checkout session created. Provide `renderEmbedded` to render your payment UI."})}):n.jsx(ie,{type:"button",className:"w-full",disabled:c.items.length===0||N||R,onClick:()=>{T(j)},children:h.isVerifying?"Checking availability…":N?"Processing…":C}),!O&&!$?n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:R?"Install a browser wallet to enable crypto payments.":k??"You will be redirected to complete your payment."}):null,n.jsx(Gp,{open:_,onOpenChange:S=>{g(S),S||h.reset()},issues:h.result?.issues??[],onRemoveItem:(S,A)=>{c.removeItem(S,A)},onUpdateQuantity:(S,A,I)=>{c.setQty(S,A,I)}})]})}function Yp({className:e}){const{config:t}=Oe(),r=Dt(),s=zs(),{settings:o}=ar(),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(Ct,{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:Ye({amount:i.unitPrice*i.qty,currency:i.currency})})]},`${i.productId}::${i.variantId??""}`))}),n.jsx(Ct,{className:"my-3"}),a?n.jsx(Li,{value:s.values.discountCode??r.promoCode,onApply:i=>{s.setField("discountCode",i??""),r.setPromoCode(i)}}):null,a?n.jsx(Ct,{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:Ye({amount:r.subtotal,currency:t.currency})})]})]})}function go({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:Ye({amount:e.order.total,currency:e.order.currency})})]}),n.jsxs("div",{className:"mt-3 space-y-2",children:[e.order.items.slice(0,4).map((o,a)=>n.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[n.jsx("div",{className:"min-w-0 truncate",children:o.title}),n.jsxs("div",{className:"shrink-0 text-neutral-600 dark:text-neutral-400",children:["Qty ",o.qty]})]},`${o.title}-${a}`)),e.order.items.length>4?n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["+",e.order.items.length-4," more item(s)"]}):null]}),n.jsxs("div",{className:"mt-3 flex gap-3 text-sm",children:[e.order.receiptUrl?n.jsx("a",{href:e.order.receiptUrl,className:"hover:underline",children:"Receipt"}):null,e.order.invoiceUrl?n.jsx("a",{href:e.order.invoiceUrl,className:"hover:underline",children:"Invoice"}):null]})]}):e.orderId?n.jsxs("p",{className:"mt-4 text-xs text-neutral-500 dark:text-neutral-400",children:["Session/Order ID: ",n.jsx("span",{className:"font-mono",children:e.orderId})]}):null,n.jsxs("div",{className:"mt-6 flex flex-col gap-2 sm:flex-row",children:[t?n.jsx(ie,{type:"button",onClick:t,children:"Continue shopping"}):null,r?n.jsx(ie,{type:"button",variant:"outline",onClick:r,children:"View orders"}):null]})]}):e.kind==="cancel"?n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Checkout cancelled"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:"No charges were made. You can continue shopping and try again."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]}):n.jsxs("div",{className:H("rounded-2xl border border-neutral-200 bg-white p-8 text-neutral-950 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",s),children:[n.jsx("h2",{className:"text-2xl font-semibold",children:"Payment failed"}),n.jsx("p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:e.message??"Something went wrong while processing your payment."}),t?n.jsx("div",{className:"mt-6",children:n.jsx(ie,{type:"button",onClick:t,children:"Back to shop"})}):null]})}function KC({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(go,{result:o,onContinueShopping:e,onViewOrders:t,className:H("w-full max-w-lg",s)})})}function XC({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(go,{result:s,onContinueShopping:e,className:H("w-full max-w-lg",r)})})}function JC(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 Kp({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(Ot,{className:H("group overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm transition-shadow hover:shadow-md dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsx(Qt,{className:"p-5",children:n.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-x-4 gap-y-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsx("div",{className:"mt-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:o})]}),n.jsx("div",{className:"flex items-start justify-end",children:n.jsx(An,{variant:JC(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:Ye({amount:e.total,currency:e.currency})}),n.jsxs("div",{className:"col-span-2 mt-3 flex items-center justify-between gap-3 border-t border-neutral-200/70 pt-3 dark:border-neutral-800",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:()=>t(e),children:"Details"}):null]})]})})})}function Xp({orders:e,onView:t,className:r}){return n.jsx("div",{className:H("grid gap-4",r),children:e.map(s=>n.jsx(Kp,{order:s,onView:t},s.id))})}function eN(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 Jp({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(Ot,{className:H("overflow-hidden rounded-2xl border-neutral-200/70 bg-white shadow-sm dark:border-neutral-800 dark:bg-neutral-950",r),children:n.jsxs(Qt,{className:"p-6",children:[n.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[n.jsx("span",{className:"text-sm font-semibold text-neutral-950 dark:text-neutral-50",children:"Order"}),n.jsx("span",{className:"truncate font-mono text-sm font-semibold text-neutral-950/80 dark:text-neutral-50/80",children:e.id})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-neutral-600 dark:text-neutral-400",children:[n.jsx("span",{children:s}),n.jsx("span",{className:"text-neutral-300 dark:text-neutral-700",children:"·"}),n.jsx("span",{children:o})]})]}),n.jsxs("div",{className:"flex items-center gap-2 sm:justify-end",children:[n.jsx(An,{variant:eN(e.status),className:"capitalize",children:o}),t?n.jsx(ie,{type:"button",variant:"outline",size:"sm",className:"h-8",onClick:t,children:"Back"}):null]})]}),n.jsx(Ct,{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:Ye({amount:a.unitPrice*a.qty,currency:a.currency})})]},`${a.title}-${i}`))}),n.jsx(Ct,{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:Ye({amount:e.total,currency:e.currency})})]}),e.receiptUrl||e.invoiceUrl?n.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-2",children:[e.receiptUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.receiptUrl,target:"_blank",rel:"noreferrer",children:"Receipt"})}):null,e.invoiceUrl?n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2",children:n.jsx("a",{href:e.invoiceUrl,target:"_blank",rel:"noreferrer",children:"Invoice"})}):null]}):null]})})}function Di(e){const t={};e.shippingProfile&&(t.shippingProfile=e.shippingProfile),e.checkoutRequirements&&(t.checkoutRequirements=JSON.stringify(e.checkoutRequirements)),e.fulfillment?.type&&(t.fulfillmentType=e.fulfillment.type),e.fulfillment?.notes&&(t.fulfillmentNotes=e.fulfillment.notes);const r=e.attributes?.shippingCountries;return typeof r=="string"&&r.trim()&&(t.shippingCountries=r),Object.keys(t).length?t:void 0}function tN(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 nN={shop:"/shop",category:e=>`/shop/${e}`,product:e=>`/product/${e}`,cart:"/cart",checkout:"/checkout",orders:"/account/orders",subscribe:"/subscribe"};function rN(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 sN({className:e,routes:t,initialCategorySlug:r}){const{config:s}=Oe(),o=Dt(),a=po(),i={...nN,...t},[c,l]=x.useState("cart"),[d,m]=x.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(min-width: 1024px)")?.matches??!1);x.useEffect(()=>{if(typeof window>"u")return;const F=window.matchMedia?.("(min-width: 1024px)");if(!F)return;const ee=()=>m(F.matches);return ee(),F.addEventListener?.("change",ee),()=>F.removeEventListener?.("change",ee)},[]);const{categories:u,isLoading:p,error:h}=Wa(),_=x.useMemo(()=>Ha({includeCategory:!0}),[]),[g,f]=x.useState(_?.search??""),[w,j]=x.useState(r??_?.category),[b,v]=x.useState(_?.page??1),[k,R]=x.useState(_?.sort??"featured"),[N,C]=x.useState(_?.filters??{}),{data:T,isLoading:O,error:$}=Fs({category:w,search:g.trim()||void 0,filters:N,sort:k,page:b,pageSize:24}),S=x.useMemo(()=>rN(T?.items??[]),[T?.items]),{settings:A}=ar(),I=A.catalog.filters,B=A.catalog.sort,L=x.useMemo(()=>{const F=[];return B.featured&&F.push({value:"featured",label:"Featured"}),B.priceAsc&&F.push({value:"price_asc",label:"Price: Low to High"}),B.priceDesc&&F.push({value:"price_desc",label:"Price: High to Low"}),F.length===0&&F.push({value:"featured",label:"Featured"}),F},[B]);x.useEffect(()=>{L.some(F=>F.value===k)||R(L[0].value)},[L,k]),Za({search:g,sort:k,page:b,category:w,filters:N},{includeCategory:!0});const[E,P]=x.useState(!1),[z,Z]=x.useState(!1),[K,D]=x.useState(null),[W,Y]=x.useState(!1),V=F=>{j(F.slug),v(1),P(!1)},ce=x.useCallback((F,ee,pe)=>{o.addItem({productId:F.id,variantId:ee?.id,unitPrice:F.price,currency:F.currency,titleSnapshot:ee?`${F.title} — ${ee.title}`:F.title,imageSnapshot:F.images[0]?.url,paymentResource:F.id,metadata:Di(F)},pe),a?.toast({title:"Added to cart",description:F.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(i.cart):(l("cart"),Z(!0)))}})},[o,i.cart,a]);return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:i.shop,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(Ri,{value:g,onChange:f})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(ro,{open:E,onOpenChange:P,children:[n.jsx(so,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Br,{side:"left",children:[n.jsx(oo,{children:n.jsx(ao,{children:"Browse"})}),n.jsxs("div",{className:"mt-4",children:[h?n.jsx(Gt,{description:h}):null,p?n.jsxs("div",{className:"space-y-2",children:[n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"})]}):n.jsxs("div",{className:"space-y-6",children:[n.jsx(_a,{categories:u,activeSlug:w,onSelect:V}),n.jsx(Is,{facets:S,value:N,onChange:F=>{C(F),v(1)},onClear:()=>{C({}),v(1)},enabledFilters:I}),L.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Ps,{value:k,onValueChange:F=>{R(F),v(1)},children:[n.jsx(Mr,{"aria-label":"Sort",children:n.jsx(As,{placeholder:"Sort"})}),n.jsx(Lr,{children:L.map(F=>n.jsx(Dr,{value:F.value,children:F.label},F.value))})]})]})]})]})]})]}),n.jsx(zr,{open:!d&&z,onOpenChange:Z,side:"bottom",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx(zr,{open:d&&z,onOpenChange:Z,side:"popup",preferredTab:c,onCheckout:()=>{typeof window<"u"&&window.location.assign(i.checkout)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>l("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(i.checkout)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",z?"lg:hidden":void 0),onClick:()=>{l("chat"),Z(!0)},"aria-label":"Open chat",children:[n.jsx(tN,{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(Ot,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:[n.jsx(Tr,{className:"pb-4",children:n.jsx(Ir,{className:"text-base",children:"Browse"})}),n.jsxs(Qt,{className:"flex-1 space-y-6 overflow-y-auto pr-2",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Categories"}),h?n.jsx(Gt,{className:"mt-3",description:h}):null,p?n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"}),n.jsx(De,{className:"h-9"})]}):n.jsx("div",{className:"mt-3",children:n.jsx(_a,{categories:u,activeSlug:w,onSelect:V})})]}),L.length>1&&n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsx("div",{className:"mt-2",children:n.jsxs(Ps,{value:k,onValueChange:F=>{R(F),v(1)},children:[n.jsx(Mr,{"aria-label":"Sort",children:n.jsx(As,{placeholder:"Sort"})}),n.jsx(Lr,{children:L.map(F=>n.jsx(Dr,{value:F.value,children:F.label},F.value))})]})})]}),n.jsx(Is,{facets:S,value:N,onChange:F=>{C(F),v(1)},onClear:()=>{C({}),v(1)},enabledFilters:I})]})]})})}),n.jsxs("section",{children:[n.jsx("div",{className:"flex items-end justify-between gap-3",children:n.jsxs("div",{children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:A.shopPage.title||"Shop"}),A.shopPage.description&&n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:A.shopPage.description})]})}),$?n.jsx(Gt,{className:"mt-6",description:$}):null,O?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((F,ee)=>n.jsx(De,{className:"aspect-[4/5] rounded-2xl"},ee))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(ho,{products:T?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:F=>i.product(F.slug),onAddToCart:F=>ce(F,null,1),onQuickView:F=>{D(F),Y(!0)},layout:A.shopLayout.layout,imageCrop:A.shopLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:b<=1,onClick:()=>v(F=>Math.max(1,F-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",b]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!T?.hasNextPage,onClick:()=>v(F=>F+1),children:"Next"})]})]})]})]}),n.jsx(Ti,{product:K,open:W,onOpenChange:Y,productHref:F=>i.product(F),onAddToCart:(F,ee,pe)=>ce(F,ee,pe)})]})}function oN(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 aN({categorySlug:e,className:t,routes:r}){const{config:s}=Oe(),o=Dt(),a=po(),{categories:i}=Wa(),[c,l]=x.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(min-width: 1024px)")?.matches??!1);x.useEffect(()=>{if(typeof window>"u")return;const q=window.matchMedia?.("(min-width: 1024px)");if(!q)return;const ne=()=>l(q.matches);return ne(),q.addEventListener?.("change",ne),()=>q.removeEventListener?.("change",ne)},[]);const[d,m]=x.useState(!1),[u,p]=x.useState(!1),[h,_]=x.useState("cart"),g=x.useMemo(()=>Ha({includeCategory:!1}),[]),[f,w]=x.useState(g?.search??""),[j,b]=x.useState(g?.page??1),[v,k]=x.useState(g?.sort??"featured"),[R,N]=x.useState(g?.filters??{}),[C,T]=x.useState(null),[O,$]=x.useState(!1),S=i.find(q=>q.slug===e)??null,{data:A,isLoading:I,error:B}=Fs({category:e,search:f.trim()||void 0,filters:R,sort:v,page:j,pageSize:24}),L=r?.product??(q=>`/product/${q}`),E=r?.shop??"/shop",P=r?.cart??"/cart",z=r?.checkout??"/checkout",Z=x.useMemo(()=>{const q=A?.items??[],ne=new Set;let le=Number.POSITIVE_INFINITY,fe=0;for(const He of q){for(const Ze of He.tags??[])ne.add(Ze);le=Math.min(le,He.price),fe=Math.max(fe,He.price)}const Pe=Array.from(ne).slice(0,12),qe=Number.isFinite(le)?{min:le,max:fe}:void 0;return{tags:Pe,price:qe}},[A?.items]),{settings:K}=ar(),D=K.catalog.filters,W=K.catalog.sort,Y=x.useMemo(()=>{const q=[];return W.featured&&q.push({value:"featured",label:"Featured"}),W.priceAsc&&q.push({value:"price_asc",label:"Price: Low to High"}),W.priceDesc&&q.push({value:"price_desc",label:"Price: High to Low"}),q.length===0&&q.push({value:"featured",label:"Featured"}),q},[W]);x.useEffect(()=>{Y.some(q=>q.value===v)||k(Y[0].value)},[Y,v]),Za({search:f,sort:v,page:j,filters:R},{includeCategory:!1});const V=x.useCallback((q,ne,le)=>{o.addItem({productId:q.id,variantId:ne?.id,unitPrice:q.price,currency:q.currency,titleSnapshot:ne?`${q.title} — ${ne.title}`:q.title,imageSnapshot:q.images[0]?.url,paymentResource:q.id,metadata:Di(q)},le),a?.toast({title:"Added to cart",description:q.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&(window.matchMedia?.("(min-width: 1024px)").matches?window.location.assign(P):(_("cart"),p(!0)))}})},[o,P,a]),ce=q=>{N(q),b(1)},F=()=>{N({}),b(1)},ee=q=>{k(q),b(1)},pe=n.jsx(Ot,{className:"flex max-h-[calc(100vh-6rem)] flex-col rounded-2xl",children:n.jsxs(Qt,{className:"flex-1 space-y-5 overflow-y-auto pr-2 pt-6",children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-neutral-500 dark:text-neutral-400",children:"Category"}),n.jsx(ie,{asChild:!0,type:"button",variant:"ghost",size:"sm",className:"h-8 px-2 text-xs",children:n.jsx("a",{href:E,children:"All categories"})})]}),n.jsx("div",{className:"text-base font-semibold text-neutral-950 dark:text-neutral-50",children:S?.name??e}),n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:S?.description??"Browse products in this category."})]}),Y.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-sm font-semibold",children:"Sort"}),n.jsxs(Ps,{value:v,onValueChange:ee,children:[n.jsx(Mr,{"aria-label":"Sort",children:n.jsx(As,{placeholder:"Sort"})}),n.jsx(Lr,{children:Y.map(q=>n.jsx(Dr,{value:q.value,children:q.label},q.value))})]})]}),n.jsx(Ct,{}),n.jsx(Is,{facets:Z,value:R,onChange:ce,onClear:F,enabledFilters:D})]})});return n.jsxs("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:[n.jsx("header",{className:"sticky top-0 z-40 border-b border-neutral-200 bg-neutral-50/80 backdrop-blur dark:border-neutral-800 dark:bg-neutral-950/70",children:n.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-3 px-4 py-3",children:[n.jsx("a",{href:E,className:"text-sm font-semibold tracking-tight",children:s.brand?.name??"Shop"}),n.jsx("div",{className:"flex-1",children:n.jsx(Ri,{value:f,onChange:w})}),n.jsxs("div",{className:"flex items-center gap-2 lg:hidden",children:[n.jsxs(ro,{open:d,onOpenChange:m,children:[n.jsx(so,{asChild:!0,children:n.jsx(ie,{type:"button",variant:"outline",children:"Filters"})}),n.jsxs(Br,{side:"left",children:[n.jsx(oo,{children:n.jsx(ao,{children:"Filters"})}),n.jsx("div",{className:"mt-4",children:pe})]})]}),n.jsx(zr,{open:!c&&u,onOpenChange:p,side:"bottom",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(z)},trigger:n.jsxs(ie,{type:"button",variant:"default",onClick:()=>_("cart"),children:["Cart (",o.count,")"]})})]}),n.jsxs("div",{className:"hidden lg:flex items-center gap-2",children:[n.jsx(zr,{open:c&&u,onOpenChange:p,side:"popup",preferredTab:h,onCheckout:()=>{typeof window<"u"&&window.location.assign(z)},trigger:n.jsxs(ie,{type:"button",variant:"outline",onClick:()=>_("cart"),children:["Cart (",o.count,")"]})}),n.jsx(ie,{type:"button",variant:"default",onClick:()=>{typeof window<"u"&&window.location.assign(z)},children:"Checkout"})]})]})}),n.jsxs(ie,{type:"button",variant:"ghost",className:H("fixed bottom-4 right-4 z-30 hidden items-center gap-2 rounded-full border border-neutral-200 bg-white/90 px-3 py-2 text-xs font-medium text-neutral-900 shadow-sm backdrop-blur hover:bg-white dark:border-neutral-800 dark:bg-neutral-950/80 dark:text-neutral-50 dark:hover:bg-neutral-950 lg:flex",u?"lg:hidden":void 0),onClick:()=>{_("chat"),p(!0)},"aria-label":"Open chat",children:[n.jsx(oN,{className:"h-4 w-4"}),"Chat"]}),n.jsxs("main",{className:"mx-auto max-w-7xl px-4 py-8",children:[n.jsx(Ii,{items:[{label:"Shop",href:E},{label:S?.name??e}]}),n.jsxs("div",{className:"mt-6",children:[n.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:S?.name??"Category"}),n.jsx("p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:S?.description??"Browse products in this category."})]}),B?n.jsx(Gt,{className:"mt-6",description:B}):null,n.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-[280px_1fr]",children:[n.jsx("aside",{className:"hidden lg:block",children:n.jsx("div",{className:"sticky top-24",children:pe})}),n.jsx("div",{children:I?n.jsx("div",{className:"mt-6 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((q,ne)=>n.jsx(De,{className:"aspect-[4/5] rounded-2xl"},ne))}):n.jsxs("div",{className:"mt-6",children:[n.jsx(ho,{products:A?.items??[],columns:s.ui?.productGrid?.columns,getProductHref:q=>L(q.slug),onAddToCart:q=>V(q,null,1),onQuickView:q=>{T(q),$(!0)},layout:K.categoryLayout.layout,imageCrop:K.categoryLayout.imageCrop}),n.jsxs("div",{className:"mt-8 flex items-center justify-between",children:[n.jsx(ie,{type:"button",variant:"outline",disabled:j<=1,onClick:()=>b(q=>Math.max(1,q-1)),children:"Previous"}),n.jsxs("div",{className:"text-xs text-neutral-600 dark:text-neutral-400",children:["Page ",j]}),n.jsx(ie,{type:"button",variant:"outline",disabled:!A?.hasNextPage,onClick:()=>b(q=>q+1),children:"Next"})]})]})})]}),n.jsx(Ti,{product:C,open:O,onOpenChange:$,productHref:q=>L(q),onAddToCart:(q,ne,le)=>V(q,ne,le)})]})]})}function iN(e){return!e||typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function cN({slug:e,className:t,routes:r}){const s=Dt(),o=po(),{product:a,isLoading:i,error:c}=Bd(e),[l,d]=x.useState(1),[m,u]=x.useState({selectedOptions:{},variant:null});x.useEffect(()=>{if(!a||!a.variants?.length)return;const S=a.variants[0];u({selectedOptions:{...S.options},variant:S})},[a?.id]);const{settings:p}=ar(),{mode:h,maxItems:_}=p.relatedProducts,g=Zd({productId:a?.id,enabled:h==="ai"&&!!a?.id}),f=x.useMemo(()=>h==="by_category"&&a?.categoryIds?.length?{category:a.categoryIds[0],page:1,pageSize:_+1}:{page:1,pageSize:_+4},[h,_,a?.categoryIds]),w=Fs(f),j=x.useMemo(()=>{const A=(w.data?.items??[]).filter(I=>I.slug!==e);if(h==="manual"&&a){const I=a.attributes?.relatedProductIds||a.attributes?.related_product_ids;if(I){const B=iN(String(I));if(B.length>0){const L=new Map(A.map(P=>[P.id,P]));return B.map(P=>L.get(P)).filter(P=>!!P).slice(0,_)}}}if(h==="ai"&&g.relatedProductIds&&g.relatedProductIds.length>0){const I=new Map(A.map(L=>[L.id,L])),B=g.relatedProductIds.map(L=>I.get(L)).filter(L=>!!L);if(B.length>0)return B.slice(0,_)}return A.slice(0,_)},[w.data?.items,e,h,_,a,g.relatedProductIds]),b=r?.shop??"/shop",v=r?.checkout??"/checkout",k=r?.cart??"/cart",R=r?.product??(S=>`/product/${S}`);if(i)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsxs("div",{className:"mx-auto max-w-6xl",children:[n.jsx(De,{className:"h-5 w-40"}),n.jsxs("div",{className:"mt-6 grid gap-8 lg:grid-cols-2",children:[n.jsx(De,{className:"aspect-square rounded-2xl"}),n.jsxs("div",{className:"space-y-4",children:[n.jsx(De,{className:"h-8 w-2/3"}),n.jsx(De,{className:"h-6 w-32"}),n.jsx(De,{className:"h-20"}),n.jsx(De,{className:"h-11"})]})]})]})});if(c)return n.jsx("div",{className:H("min-h-screen bg-neutral-50 p-6 dark:bg-neutral-950",t),children:n.jsx("div",{className:"mx-auto max-w-6xl",children:n.jsx(Gt,{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(Gt,{description:"Product not found."})})});const N=m.variant?.price??a.price,C=m.variant?.compareAtPrice??a.compareAtPrice,T=a.inventoryStatus==="out_of_stock"||typeof a.inventoryQuantity=="number"&&a.inventoryQuantity<=0,O=()=>{T||(s.addItem({productId:a.id,variantId:m.variant?.id,unitPrice:N,currency:a.currency,titleSnapshot:m.variant?`${a.title} — ${m.variant.title}`:a.title,imageSnapshot:a.images[0]?.url,paymentResource:a.id,metadata:Di(a)},l),o?.toast({title:"Added to cart",description:a.title,actionLabel:"View cart",onAction:()=>{typeof window<"u"&&window.location.assign(k)}}))},$=()=>{T||(O(),typeof window<"u"&&window.location.assign(v))};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",t),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-8",children:[n.jsx(Ii,{items:[{label:"Shop",href:b},{label:a.title}]}),n.jsxs("div",{className:"mt-6 grid gap-10 lg:grid-cols-2",children:[n.jsx(Pi,{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(fo,{amount:N,currency:a.currency,compareAt:C})}),T?n.jsx("div",{className:"mt-2 text-sm font-medium text-red-700 dark:text-red-300",children:"Out of stock"}):typeof a.inventoryQuantity=="number"&&a.inventoryQuantity>0&&a.inventoryQuantity<=5?n.jsxs("div",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-400",children:["Only ",n.jsx("span",{className:"font-semibold text-neutral-950 dark:text-neutral-50",children:a.inventoryQuantity})," left"]}):null,n.jsx("p",{className:"mt-4 text-sm text-neutral-600 dark:text-neutral-400",children:a.description})]}),n.jsx(Ai,{product:a,value:{selectedOptions:m.selectedOptions,variantId:m.variant?.id},onChange:S=>u(S)}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx(Ei,{qty:l,onChange:d}),n.jsx(ie,{type:"button",onClick:O,className:"flex-1",disabled:T,children:T?"Out of stock":"Add to cart"}),n.jsx(ie,{type:"button",variant:"outline",onClick:$,disabled:T,children:"Buy now"})]}),(p.sections.showDescription||p.sections.showSpecs||p.sections.showShipping)&&n.jsxs(pp,{type:"single",collapsible:!0,defaultValue:p.sections.showDescription?"desc":void 0,children:[p.sections.showDescription&&n.jsxs(Cr,{value:"desc",children:[n.jsx(Nr,{children:"Description"}),n.jsx(Pr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.description})})]}),p.sections.showSpecs&&n.jsxs(Cr,{value:"specs",children:[n.jsx(Nr,{children:"Specs"}),n.jsx(Pr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.attributes?n.jsx("div",{className:"space-y-1",children:Object.entries(a.attributes).map(([S,A])=>n.jsxs("div",{children:[n.jsxs("span",{className:"font-medium text-neutral-950 dark:text-neutral-50",children:[S,":"]})," ",String(A)]},S))}):"No specs provided."})})]}),p.sections.showShipping&&n.jsxs(Cr,{value:"ship",children:[n.jsx(Nr,{children:"Shipping & returns"}),n.jsx(Pr,{children:n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Ships in 2–3 business days. Easy returns within 30 days."})})]})]})]})]}),p.sections.showRelatedProducts&&j.length?n.jsxs("section",{className:"mt-12",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Related products"}),n.jsx("div",{className:"mt-4",children:n.jsx(ho,{products:j,columns:{base:2,md:4,lg:4},layout:p.relatedProducts.layout.layout,imageCrop:p.relatedProducts.layout.imageCrop,getProductHref:S=>R(S.slug),onAddToCart:S=>s.addItem({productId:S.id,unitPrice:S.price,currency:S.currency,titleSnapshot:S.title,imageSnapshot:S.images[0]?.url,paymentResource:S.id},1)})})]}):null]})})}function lN({className:e,checkoutHref:t}){const{config:r}=Oe(),{settings:s}=ar(),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(Wp,{onCheckout:()=>{typeof window<"u"&&window.location.assign(o)},showPromoCode:a})})]})})}function dN({className:e,routes:t}){const{config:r}=Oe(),s=Dt(),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(go,{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(Fd,{children:c?n.jsxs(Ot,{className:"rounded-2xl",children:[n.jsx(Tr,{className:"pb-4",children:n.jsx(Ir,{className:"text-base",children:"Sign in required"})}),n.jsxs(Qt,{children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"This store requires an account to complete checkout."}),m?n.jsx("div",{className:"mt-4",children:n.jsx(ie,{type:"button",onClick:()=>{typeof window<"u"&&window.location.assign(m)},children:"Sign in"})}):null]})]}):n.jsx(Vp,{left:n.jsxs("div",{className:"space-y-6",children:[n.jsx(Hp,{}),n.jsxs(Ot,{className:"rounded-2xl",children:[n.jsx(Tr,{className:"pb-4",children:n.jsx(Ir,{className:"text-base",children:"Payment"})}),n.jsxs(Qt,{children:[n.jsx(Ct,{className:"mb-4"}),n.jsx(Qp,{})]})]})]}),right:n.jsx("div",{className:"lg:sticky lg:top-24",children:n.jsx(Yp,{})})})})})]}):null]})})}function uN({className:e,isSignedIn:t=!0,onLogin:r}){const{orders:s,isLoading:o,error:a}=Ud(),[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(Gt,{className:"mt-8",description:a}):null,o?n.jsxs("div",{className:"mt-8 grid gap-4",children:[n.jsx(De,{className:"h-32 rounded-2xl"}),n.jsx(De,{className:"h-32 rounded-2xl"}),n.jsx(De,{className:"h-32 rounded-2xl"})]}):s.length===0?n.jsx("div",{className:"mt-8",children:n.jsx(nr,{title:"No orders yet",description:"When you purchase something, it will show up here."})}):i?n.jsx("div",{className:"mt-8",children:n.jsx(Jp,{order:i,onBack:()=>c(null)})}):n.jsx("div",{className:"mt-8",children:n.jsx(Xp,{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(nr,{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 mN({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 pN({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 fN(e){switch(e){case"x402":return"Crypto (x402)";case"credits":return"Credits";case"stripe":return"Card";default:return"Payment"}}function hN({order:e,source:t,purchaseId:r,customerEmail:s,customerName:o,className:a,onBack:i}){const{config:c}=Oe(),l=t??e.source,d=r??e.purchaseId,m=s??e.customerEmail,u=o??e.customerName,p=c.brand?.name??"Store",h=c.brand?.logoUrl,_=()=>{typeof window<"u"&&window.print()},g=new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"}),f=new Date(e.createdAt).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return n.jsxs("div",{className:H("min-h-screen bg-neutral-100 dark:bg-neutral-900 print:bg-white print:dark:bg-white",a),children:[n.jsx("div",{className:"border-b border-neutral-200 bg-white px-4 py-3 dark:border-neutral-800 dark:bg-neutral-950 print:hidden",children:n.jsxs("div",{className:"mx-auto flex max-w-2xl items-center justify-between",children:[i?n.jsxs(ie,{type:"button",variant:"ghost",size:"sm",onClick:i,children:[n.jsx(pN,{className:"mr-1"})," Back"]}):n.jsx("div",{}),n.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:_,children:[n.jsx(mN,{className:"mr-2"})," Print Receipt"]})]})}),n.jsx("div",{className:"mx-auto max-w-2xl px-4 py-8 print:max-w-none print:px-0 print:py-0",children:n.jsxs("div",{className:"rounded-xl border border-neutral-200 bg-white p-8 shadow-sm dark:border-neutral-800 dark:bg-neutral-950 print:border-0 print:shadow-none print:dark:bg-white print:dark:text-neutral-950",children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-neutral-200 pb-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[h?n.jsx("img",{src:h,alt:p,className:"h-10 w-10 rounded-lg object-contain"}):null,n.jsx("div",{className:"text-xl font-semibold",children:p})]}),n.jsxs("div",{className:"text-right",children:[n.jsx("div",{className:"text-sm font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Receipt"}),n.jsx("div",{className:"mt-1 font-mono text-sm",children:e.id})]})]}),n.jsxs("div",{className:"mt-6 grid grid-cols-2 gap-4 text-sm sm:grid-cols-3",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Date"}),n.jsx("div",{className:"mt-1 font-medium",children:g}),n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:f})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Payment Method"}),n.jsx("div",{className:"mt-1 font-medium",children:fN(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(An,{variant:"outline",className:"capitalize print:border-neutral-300",children:e.status})})]})]}),(u||m)&&n.jsxs("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Customer"}),u&&n.jsx("div",{className:"mt-1 font-medium",children:u}),m&&n.jsx("div",{className:"text-sm text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:m})]}),n.jsx("div",{className:"mt-6 border-t border-neutral-200 pt-6 dark:border-neutral-800 print:dark:border-neutral-200",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-neutral-200 dark:border-neutral-800 print:dark:border-neutral-200",children:[n.jsx("th",{className:"pb-3 text-left font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Item"}),n.jsx("th",{className:"pb-3 text-center font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Qty"}),n.jsx("th",{className:"pb-3 text-right font-medium text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Price"})]})}),n.jsx("tbody",{children:e.items.map((w,j)=>n.jsxs("tr",{className:"border-b border-neutral-100 dark:border-neutral-800/50 print:dark:border-neutral-100",children:[n.jsx("td",{className:"py-3",children:n.jsx("div",{className:"font-medium",children:w.title})}),n.jsx("td",{className:"py-3 text-center text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:w.qty}),n.jsx("td",{className:"py-3 text-right",children:Ye({amount:w.unitPrice*w.qty,currency:w.currency})})]},`${w.title}-${j}`))})]})}),n.jsxs("div",{className:"mt-4 flex flex-col items-end gap-2 text-sm",children:[n.jsxs("div",{className:"flex w-48 justify-between",children:[n.jsx("span",{className:"text-neutral-600 dark:text-neutral-400 print:dark:text-neutral-600",children:"Subtotal"}),n.jsx("span",{children:Ye({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:Ye({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 gN({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 xN({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}=Oe(),{tiers:c,status:l,isLoading:d,error:m}=Wd(),[u,p]=x.useState("monthly"),h=!!i.adapter.createSubscriptionCheckoutSession,_=async g=>{if(!i.adapter.createSubscriptionCheckoutSession)return;const f=await i.adapter.createSubscriptionCheckoutSession({tierId:g,interval:u,successUrl:i.checkout.successUrl,cancelUrl:i.checkout.cancelUrl});f.kind==="redirect"&&typeof window<"u"&&window.location.assign(f.url)};return n.jsx("div",{className:H("min-h-screen bg-neutral-50 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50",e),children:n.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-16",children:[n.jsxs("div",{className:"text-center",children:[n.jsx("h1",{className:"text-5xl font-bold tracking-tight",children:t}),n.jsx("p",{className:"mt-4 text-base text-neutral-600 dark:text-neutral-400",children:r})]}),n.jsx("div",{className:"mt-10 flex justify-center",children:n.jsxs("div",{className:"inline-flex items-center rounded-full bg-neutral-200/60 p-1 dark:bg-neutral-800/60",children:[n.jsxs("button",{type:"button",onClick:()=>p("annual"),className:H("relative flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-all",u==="annual"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:["Yearly",s&&n.jsx("span",{className:H("rounded-full px-2 py-0.5 text-xs font-medium",u==="annual"?"bg-white/20 text-white dark:bg-neutral-900/20 dark:text-neutral-900":"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900"),children:s})]}),n.jsx("button",{type:"button",onClick:()=>p("monthly"),className:H("rounded-full px-4 py-2 text-sm font-medium transition-all",u==="monthly"?"bg-neutral-900 text-white dark:bg-white dark:text-neutral-900":"text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"),children:"Monthly"})]})}),m?n.jsx(Gt,{className:"mt-10",description:m}):null,d?n.jsxs("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[n.jsx(De,{className:"h-[480px] rounded-2xl"}),n.jsx(De,{className:"h-[480px] rounded-2xl"}),n.jsx(De,{className:"h-[480px] rounded-2xl"})]}):c.length===0?n.jsx("div",{className:"mt-12",children:n.jsx(nr,{title:"No plans available",description:"Subscription plans will appear here once configured."})}):n.jsx("div",{className:"mt-12 grid gap-6 md:grid-cols-3 items-start",children:c.map(g=>{const f=l?.isActive&&l.currentTierId===g.id,w=u==="annual"&&g.priceAnnual?g.priceAnnual:g.priceMonthly,j=g.isPopular,b=g.inventoryQuantity!=null,v=b?Math.max(0,(g.inventoryQuantity??0)-(g.inventorySold??0)):null,k=b&&v===0,R=b&&v!=null&&v>0&&v<=5,[N,...C]=g.features;return n.jsxs("div",{className:H("relative flex flex-col rounded-2xl border p-6 transition-shadow",j?"border-neutral-900 bg-neutral-900 text-white shadow-xl dark:border-white dark:bg-white dark:text-neutral-900":"border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-900"),children:[j&&o&&n.jsx("div",{className:"absolute -top-3 right-4",children:n.jsx("span",{className:"rounded-full bg-neutral-100 px-3 py-1 text-xs font-semibold text-neutral-900 shadow-sm dark:bg-neutral-800 dark:text-white",children:o})}),n.jsxs("div",{className:"mb-6",children:[n.jsx("h3",{className:"text-xl font-bold",children:g.title}),g.description&&n.jsx("p",{className:H("mt-2 text-sm leading-relaxed",j?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:g.description})]}),n.jsxs("div",{className:"mb-6",children:[n.jsx("div",{className:"text-5xl font-bold tracking-tight",children:Ye({amount:w,currency:g.currency||i.currency})}),n.jsxs("div",{className:H("mt-2 text-sm",j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:["Per ",u==="annual"?"year":"month",", billed ",u==="annual"?"annually":"monthly"]})]}),b&&n.jsx("div",{className:H("mb-3 text-xs font-medium",k?"text-red-600 dark:text-red-400":R?j?"text-amber-300 dark:text-amber-600":"text-amber-600 dark:text-amber-400":j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400"),children:k?"Sold out":`${v} remaining`}),n.jsx(ie,{type:"button",className:H("mb-6 w-full rounded-full py-3 font-medium",j?"bg-white text-neutral-900 hover:bg-neutral-100 dark:bg-neutral-900 dark:text-white dark:hover:bg-neutral-800":""),variant:j?"default":"outline",disabled:f||!h||k,onClick:()=>void _(g.id),children:k?"Sold Out":f?"Current Plan":"Purchase"}),N&&n.jsx("div",{className:H("mb-4 text-sm font-semibold",j?"":"text-neutral-900 dark:text-white"),children:N}),C.length>0&&n.jsx("ul",{className:"space-y-3",children:C.map((T,O)=>n.jsxs("li",{className:"flex items-start gap-3",children:[n.jsx(gN,{className:H("mt-0.5",j?"text-neutral-400 dark:text-neutral-500":"text-neutral-500 dark:text-neutral-400")}),n.jsx("span",{className:H("text-sm leading-relaxed",j?"text-neutral-300 dark:text-neutral-600":"text-neutral-600 dark:text-neutral-400"),children:T})]},O))})]},g.id)})}),a&&n.jsx("div",{className:"mt-12 text-center",children:n.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400 leading-relaxed max-w-2xl mx-auto",children:a})})]})})}function yN(e){const{processCartCheckout:t}=Os();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 Va(r)}}),[e,t])}const vN=Object.freeze(Object.defineProperty({__proto__:null,Accordion:pp,AccordionContent:Pr,AccordionItem:Cr,AccordionTrigger:Nr,AddressForm:ja,Badge:An,Breadcrumbs:Ii,Button:ie,Card:Ot,CardContent:Qt,CardDescription:du,CardFooter:uu,CardHeader:Tr,CardTitle:Ir,CartLineItem:Oi,CartPageContent:Wp,CartPanel:Bp,CartProvider:dg,CartSidebar:zr,CartSummary:Mi,CartTemplate:lN,CategoryNav:_a,CategoryTemplate:aN,CedrosShopProvider:Hh,CheckoutCancelPage:XC,CheckoutForm:Hp,CheckoutLayout:Vp,CheckoutProvider:Fd,CheckoutReceipt:go,CheckoutSuccessPage:KC,CheckoutTemplate:dN,Dialog:fi,DialogClose:rS,DialogContent:to,DialogDescription:xi,DialogFooter:Vm,DialogHeader:gi,DialogOverlay:hi,DialogPortal:Wm,DialogTitle:no,DialogTrigger:nS,EmptyState:nr,ErrorBoundary:DS,ErrorState:Gt,FAQItem:$p,FAQList:LC,FilterPanel:Is,Input:Ue,InventoryVerificationDialog:Gp,Label:it,OrderCard:Kp,OrderDetails:Jp,OrderList:Xp,OrderReview:Yp,PaymentStep:Qp,Price:fo,ProductCard:zp,ProductGallery:Pi,ProductGrid:ho,ProductTemplate:cN,PromoCodeInput:Li,PurchaseHistoryTemplate:uN,QuantitySelector:Ei,QuickViewDialog:Ti,ReceiptTemplate:hN,SearchInput:Ri,Select:Ps,SelectContent:Lr,SelectGroup:Dk,SelectItem:Dr,SelectTrigger:Mr,SelectValue:As,Separator:Ct,Sheet:ro,SheetClose:qm,SheetContent:Br,SheetDescription:Zm,SheetHeader:oo,SheetOverlay:yi,SheetPortal:Hm,SheetTitle:ao,SheetTrigger:so,ShippingMethodSelector:qp,ShopTemplate:sN,Skeleton:De,SubscriptionTemplate:xN,Tabs:Ci,TabsContent:Rp,TabsList:mo,TabsTrigger:$r,ToastProvider:pC,VariantSelector:Ai,createMockCommerceAdapter:Kh,createPaywallCommerceAdapter:ng,parseCheckoutReturn:Va,readCatalogUrlState:Ha,useAIRelatedProducts:Zd,useCart:Dt,useCartInventory:Ga,useCatalogUrlSync:Za,useCategories:Wa,useCedrosPayCheckoutAdapter:yN,useCedrosShop:Oe,useCheckout:zs,useCheckoutResultFromUrl:qa,useHoldExpiry:Kb,useInventoryVerification:qd,useOptionalToast:po,useOrders:Ud,usePaymentMethodsConfig:Hd,useProduct:Bd,useProducts:Fs,useShippingMethods:Vd,useStandaloneCheckout:Ub,useStorefrontSettings:ar,useSubscriptionData:Wd,useToast:mC,validateCommerceAdapterContract:t0},Symbol.toStringTag,{value:"Module"}));exports.CEDROS_EVENTS=xn;exports.CSP_PRESETS=Ef;exports.CedrosPay=Ff;exports.CedrosPayAdminDashboard=bh;exports.CouponsSection=Ul;exports.CreditsButton=Aa;exports.CreditsSubscribeButton=Th;exports.CryptoButton=Ea;exports.ERROR_CATEGORIES=Al;exports.PaymentMethodBadge=Ah;exports.PaymentModal=Dl;exports.ProductPrice=Ph;exports.ProductsSection=Fl;exports.PurchaseButton=$l;exports.RPC_PROVIDERS=Af;exports.RefundsSection=Wl;exports.SECURITY_RECOMMENDATIONS=qh;exports.SettingsSection=Ra;exports.StripeButton=Pa;exports.SubscribeButton=Eh;exports.SubscriptionManagementPanel=Dh;exports.TransactionsSection=Bl;exports.calculateDiscountPercentage=pf;exports.cedrosPayPlugin=Nh;exports.createDedupedClickHandler=Ln;exports.createTranslator=Ol;exports.detectLocale=Il;exports.emitPaymentError=St;exports.emitPaymentProcessing=mn;exports.emitPaymentStart=$n;exports.emitPaymentSuccess=zn;exports.emitWalletConnect=Jo;exports.emitWalletConnected=Pl;exports.emitWalletError=cs;exports.formatCSP=Tl;exports.formatCouponCodes=mf;exports.generateCSP=Pf;exports.generateCSPDirectives=El;exports.getAvailableLocales=If;exports.getLocalizedError=Rf;exports.getModalCloseButtonStyles=Na;exports.getUserErrorMessage=Sf;exports.index=vN;exports.isRetryableError=kf;exports.loadLocale=Rl;exports.logSecurityReport=Vh;exports.parseCouponCodes=uf;exports.stackCheckoutCoupons=ff;exports.useCreditsPayment=Ml;exports.useCreditsSubscription=td;exports.useLocalizedError=Of;exports.usePaymentMode=rr;exports.useStripeCheckout=Os;exports.useSubscription=ed;exports.useSubscriptionManagement=nd;exports.useTranslation=yn;exports.useX402Payment=Ll;exports.validateSecurity=Wh;
|