@tagadapay/headless-sdk 1.20.1 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.20.1
2
+ * @tagadapay/headless-sdk v1.21.0
3
3
  * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
6
- "use strict";var TagadaHeadlessReactBundle=(()=>{var jt=Object.create;var fe=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var Kt=Object.getOwnPropertyNames;var Bt=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var N=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var zt=(s,e)=>{for(var t in e)fe(s,t,{get:e[t],enumerable:!0})},Ze=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Kt(e))!Vt.call(s,r)&&r!==t&&fe(s,r,{get:()=>e[r],enumerable:!(n=$t(e,r))||n.enumerable});return s};var He=(s,e,t)=>(t=s!=null?jt(Bt(s)):{},Ze(e||!s||!s.__esModule?fe(t,"default",{value:s,enumerable:!0}):t,s)),Jt=s=>Ze(fe({},"__esModule",{value:!0}),s);var Nn={};zt(Nn,{CRYPTO_ONCHAIN_PAYMENT_METHOD:()=>je,CurrencyUtils:()=>Z,GoogleAutocompleteCore:()=>V,ISODataCore:()=>z,TagadaHeadlessProvider:()=>St,formatCryptoOnchainCountdown:()=>dt,formatMoney:()=>We,isCryptoOnchainMethod:()=>lt,loadGoogleMapsScript:()=>de,parseTokensFromUrl:()=>et,useCatalog:()=>Tt,useCheckout:()=>vt,useCountryOptions:()=>Ht,useCryptoOnchainPayment:()=>Rt,useCustomer:()=>xt,useGoogleAutocomplete:()=>Dt,useHeadlessClient:()=>E,useISOData:()=>De,useOffers:()=>Ot,useOrder:()=>At,usePayment:()=>It,useRegionOptions:()=>Ft,useRx:()=>Et,useStep:()=>Nt});var Y=N("react");var q=class extends Error{constructor(e,t,n,r){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=r}},he=class extends q{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},ye=class extends q{constructor(e,t=[],n,r){super(e,"validation_error",422,{errors:t,...r}),this.name="TagadaValidationError",this.errors=t,this.appCode=n}},ee=class extends q{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},Pe=class extends q{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}};var re=class extends q{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var Fe="headless",se="1.20.1";var Xe={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},ie=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken,this.redirect=e.redirect}static resolveBaseUrl(e,t){return t??Xe[e]??Xe.production}async request(e,t={}){var C;let{method:n="GET",body:r,headers:i={},params:o,token:a,signal:c}=t,u=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[h,v]of Object.entries(o))v!==void 0&&y.set(h,String(v));let d=y.toString();d&&(u+=`?${d}`)}let m={"Content-Type":"application/json","X-Tagada-SDK":`headless-sdk/${se}`,...i},l=a??this.apiKey??((C=this.getToken)==null?void 0:C.call(this));l&&(m["x-cms-token"]=l);let f=new AbortController,p=setTimeout(()=>f.abort(),this.timeout);try{let y=await fetch(u,{method:n,headers:m,body:r!=null?JSON.stringify(r):void 0,signal:c??f.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(p),y.ok){let d=await y.text();return d?JSON.parse(d):{}}throw await this.handleErrorResponse(y,e),new q("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(p),y instanceof q?y:y instanceof DOMException&&y.name==="AbortError"?new re(`Request to ${e} timed out after ${this.timeout}ms.`):new re(y instanceof Error?y.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let n={};try{n=await e.json()}catch{}let r=Qt(n.data),i=n.message||n.error||(typeof r.message=="string"?r.message:void 0)||(typeof n.data=="string"&&Object.keys(r).length===0?n.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof r.code=="string"?r.code:void 0;switch(e.status){case 401:case 403:throw new he(i);case 404:throw new ee(t,"");case 422:{let a=Array.isArray(n.errors)?n.errors:[];throw new ye(i,a,o,n)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new Pe(a)}default:throw new q(i,"api_error",e.status,n)}}};function Qt(s){if(s&&typeof s=="object")return s;if(typeof s!="string")return{};try{let e=JSON.parse(s);return e&&typeof e=="object"?e:{}}catch{return{}}}var oe=class s{constructor(e,t,n,r){this.http=e;this.storeId=t;this.onTokenChange=n;this.onSession=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,n){var a,c;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.call(this,t));let r={skipAsyncWait:"false"};n!=null&&n.currency&&(r.currency=n.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:r,token:this.sessionToken}),o=this.normalizeSession(i);this._currentSession=o;try{(c=this.onSession)==null||c.call(this,o)}catch{}return o}async createSession(e){var c,u,m;let t=e.items.map(l=>({variantId:l.variantId,priceId:l.priceId,...l.sellingPlanId!==void 0?{sellingPlanId:l.sellingPlanId}:{},...l.trialDays!==void 0?{trialDays:l.trialDays}:{},...l.trialPrice!==void 0?{trialPrice:l.trialPrice}:{},quantity:l.quantity})),n={storeId:this.storeId,lineItems:t};e.returnUrl&&(n.returnUrl=e.returnUrl),e.funnelSessionId&&(n.funnelSessionId=e.funnelSessionId),(c=e.discountCodes)!=null&&c.length&&(n.discountCodes=e.discountCodes),e.metadata&&Object.keys(e.metadata).length>0&&(n.metadata=e.metadata),e.customerMetadata&&Object.keys(e.customerMetadata).length>0&&(n.customerMetadata=e.customerMetadata),(u=e.customerTags)!=null&&u.length&&(n.customerTags=e.customerTags);let r={};e.currency&&(r.currency=e.currency),e.customerEmail&&(r.email=e.customerEmail,r.firstName=e.customerFirstName,r.lastName=e.customerLastName),Object.keys(r).length>0&&(n.customer=r);let i=await this.http.post("/api/v1/checkout/session/init",n),a=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((m=this.onTokenChange)==null||m.call(this,a)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:a,customerId:i.customerId}}async createSessionUrl(e){let{checkoutPath:t="/checkout",origin:n,...r}=e,i=await this.createSession(r),o=n??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:i.checkoutToken,sessionToken:i.sessionToken}),c=`${o}${t}?${a.toString()}`;return{...i,url:c}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("checkoutToken");if(!r)return null;let i=n.searchParams.get("sessionToken")??n.searchParams.get("token")??"";return{checkoutToken:r,sessionToken:i}}parseTokensFromUrl(e){return s.parseTokensFromUrl(e)}async updateCart(e,t){let n=t.map(r=>({variantId:r.variantId,priceId:r.priceId,...r.sellingPlanId!==void 0?{sellingPlanId:r.sellingPlanId}:{},quantity:r.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:n},{token:this.sessionToken})}async updateCustomer(e,t){t.email&&(this.customerEmail=t.email),t.firstName&&(this.customerFirstName=t.firstName),t.lastName&&(this.customerLastName=t.lastName),t.phone&&(this.customerPhone=t.phone)}async updateAddress(e,t){let n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),i=n??r??{},o=r??n,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}async updateCustomerAndAddress(e,t){t.customer.email&&(this.customerEmail=t.customer.email),t.customer.firstName&&(this.customerFirstName=t.customer.firstName),t.customer.lastName&&(this.customerLastName=t.customer.lastName),t.customer.phone&&(this.customerPhone=t.customer.phone);let n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),i=n??r??{},o=r??n,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return Yt({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let n=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${n}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(n=>this.normalizeShippingRate(n))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){var m;let t=e.checkoutSession,n=t.orderSummaries??[],r=e.summary??t.summary??n[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(m=r.currency??t.selectedPresentmentCurrency)==null?void 0:m.toUpperCase(),c=i.map(l=>{let f=l.price,p=l.variant??(f==null?void 0:f.variant)??{},C=l.product??p.product??{},y=(f==null?void 0:f.currencyOptions)??{},d=(a?y[a]:void 0)??y[Object.keys(y)[0]],h=(d==null?void 0:d.amount)??0;return{id:l.id,variantId:l.variantId,priceId:l.priceId,productName:C.name??"",variantName:p.name??"",quantity:l.quantity??1,unitAmount:h,totalAmount:h*(l.quantity??1),currency:a??"USD",imageUrl:p.imageUrl??C.imageUrl??"",...f!=null&&f.recurring?{recurring:{interval:f.interval??"month",intervalCount:f.intervalCount??1}}:{}}}),u=r.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:c,totals:{subtotal:r.subtotalAmount??0,discount:r.totalPromotionAmount??0,shipping:r.shippingCost??0,tax:r.totalTaxAmount??0,total:r.totalAdjustedAmount??r.totalAmount??u.reduce((l,f)=>l+(f.amount??0),0),currency:a??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName,phone:o.phone}:void 0,shippingAddress:this.normalizeAddress(t.shippingAddress),billingAddress:this.normalizeAddress(t.billingAddress),selectedShippingRateId:t.shippingRateId??null,metadata:t.metadata}}normalizeAddress(e){if(!e||typeof e!="object")return;let t=e,n={firstName:t.firstName,lastName:t.lastName,line1:t.line1??t.address1,line2:t.line2??t.address2,city:t.city,state:t.state,postalCode:t.postalCode??t.postal,country:t.country,phone:t.phone};return Object.values(n).some(r=>r!==void 0&&r!=="")?n:void 0}},et=oe.parseTokensFromUrl;function Yt(s){let e={};for(let[t,n]of Object.entries(s))n!=null&&n!==""&&(e[t]=n);return Object.keys(e).length>0?e:void 0}function Ce(s){var t,n;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(n=s.addressLines)==null?void 0:n[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return tt(e)?e:void 0}function Se(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),n={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:s.address1,line2:[s.address2,s.address3].filter(Boolean).join(" ")||void 0,city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return tt(n)?n:void 0}function tt(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var nt="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.1/dist/tagada-pixels.min.js";function at(s,e){return e()?Promise.resolve():new Promise((t,n)=>{let r=document.createElement("script");r.src=s,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error("runtime script failed to load")),document.head.appendChild(r)})}async function Wt(){if(typeof window>"u")return null;if(nt){let s=window;return s.TagadaPixels?s.TagadaPixels:(await at(nt,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var rt="__tgd_track",Zt="__tgd_aid",Xt="__tgd_sid",st=50,en=2e3,it=1e3,tn=64;function ve(s){if(!(!Array.isArray(s)||s.length===0))return s.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function ot(s){if(!s)return;let e={};for(let[t,n]of Object.entries(s))(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(e[t]=n);return Object.keys(e).length>0?e:void 0}var nn={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function qe(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function rn(s){let e={};for(let t of s){let{provider:n,id:r,idKey:i,...o}=t;(e[n]??(e[n]=[])).push({...o,enabled:!0,[i]:r,events:t.events??{}})}return e}var we=class{constructor(e,t,n){this.baseUrl=e;this.storeId=t;this.funnelKey=n;this.records=[];this.lastStep=new Map;this.signals=[];this.currentStepId=null;this.manifestHash=null;this.loadedProviders=[];this.configPromise=null;this.corePromise=null;this.enginePromise=null;this.flushTimer=null;this.listening=!1}flag(){try{return(localStorage.getItem(rt)??"").split(":")}catch{return[]}}enabled(){return this.flag()[0]===this.storeId}flagFunnelKey(){return this.flag()[1]||this.funnelKey}off(){return typeof window>"u"||!this.enabled()}arm(){try{localStorage.setItem(rt,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let n=(t==null?void 0:t.path)??window.location.pathname,r=`${e}|${n}`,i=Date.now(),o=this.lastStep.get(r);o!==void 0&&i-o<it||(this.remember(r,i),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:i,path:n}),this.pixels().then(a=>a==null?void 0:a.pageView(n,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let n=this.currentStepId;if(n===null)return;let r=nn[e],i=`${r??e}_${qe()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:i,props:ot(t)}),this.pixels().then(o=>r?o==null?void 0:o.track(r,t,{stepId:n,eventId:i}):o==null?void 0:o.trackCustom(e,t,{stepId:n})),this.core().then(o=>o==null?void 0:o.track(e,{...ot(t)??{},step_id:n,pixel_event_id:i})).catch(()=>{})}remember(e,t){for(let[n,r]of this.lastStep)t-r>=it&&this.lastStep.delete(n);for(;this.lastStep.size>=tn;){let n=this.lastStep.keys().next();if(n.done===!0)break;this.lastStep.delete(n.value)}this.lastStep.set(e,t)}identify(e){this.off()||(this.pixels().then(t=>t==null?void 0:t.identify({email:e.email,phone:e.phone,externalId:e.customerId})),this.core().then(t=>t==null?void 0:t.identify(e.customerId??null,{email:e.email,phone:e.phone,customerId:e.customerId})).catch(()=>{}))}consent(e){this.off()||this.pixels().then(t=>t==null?void 0:t.consent(e))}async health(){return typeof window>"u"?this.snapshot():(this.enabled()&&await this.config(),this.snapshot())}noteCheckout(e){this.notePixel("InitiateCheckout",e.checkoutSessionId,e)}notePaid(e){this.notePixel("Purchase",e.orderId,e)}notePixel(e,t,n){this.off()||this.pixels().then(r=>{var i;return r==null?void 0:r.track(e,{value:n.amount,currency:n.currency,contents:n.items,num_items:(i=n.items)==null?void 0:i.length},{eventId:`${e}_${t}`})})}noteSignal(e,t,n){this.off()||(this.signals.push({signal:e,value:t,detail:n}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:n}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:Fe,version:se},manifestHash:this.manifestHash,pixels:{loaded:this.loadedProviders.length>0,providers:[...this.loadedProviders]},signals:[...this.signals]}}config(){if(this.configPromise!==null)return this.configPromise;let e=`${this.baseUrl}/api/public/v1/sdk/config?storeId=${encodeURIComponent(this.storeId)}&funnel=${encodeURIComponent(this.flagFunnelKey())}`;return this.configPromise=(async()=>{try{let t=await fetch(e);if(!t.ok)return null;let n=await t.json();return this.manifestHash=n.manifestHash||null,n}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let n=await this.config();if(!n||!n.collect&&!n.experiments)return null;let r=this.baseUrl.replace(/\/+$/,""),i=window;return typeof((e=i.tgd)==null?void 0:e.init)!="function"&&await at(r+"/assets/js/tgd.js",()=>{var o;return typeof((o=i.tgd)==null?void 0:o.init)=="function"}),typeof((t=i.tgd)==null?void 0:t.init)!="function"?null:(i.tgd.init({storeId:this.storeId,apiHost:n.collect?new URL(n.collect.url).origin:r,bootstrap:this.bootstrap,_source:"headless",_manualPages:!0}),i.tgd)}catch{return null}})()),this.corePromise)}noteFunnelSession(e){this.off()||this.core().then(t=>t==null?void 0:t._link(e)).catch(()=>{})}pixels(){return this.enabled()?(this.enginePromise??(this.enginePromise=this.startEngine()),this.enginePromise):Promise.resolve(null)}async startEngine(){var e;try{let t=await this.config();if(t===null)return null;let n=await Wt();if(n===null)return null;let r=n.createPixelEngine({pixels:rn(t.pixels??[]),steps:t.steps,checkout:t.checkout,requireConsent:((e=t.consent)==null?void 0:e.required)===!0,onSignal:i=>this.onPixelSignal(i)});return await r.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(i=>i.provider))],r}catch{return null}}onPixelSignal(e){let t=e.detail??{};this.signals.push({signal:e.kind,value:e.provider,detail:t}),this.push({kind:"signal",signal:e.kind,value:e.provider,detail:t})}listen(){if(this.listening||typeof window>"u")return;this.listening=!0;let e=t=>{t.type==="visibilitychange"&&document.visibilityState!=="hidden"||this.flush()};window.addEventListener("pagehide",e),window.addEventListener("visibilitychange",e)}push(e){if(this.enabled()){if(this.records.push(e),this.records.length>=st){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),en))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let i=qe();return n.setItem(t,i),i}catch{return qe()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,st),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:Fe,version:se},anonymousId:this.identifier("local",Zt),sessionId:this.identifier("session",Xt),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let n=JSON.stringify(t),r=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(r,new Blob([n],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(r,{method:"POST",body:n,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var je="crypto_onchain";var ke=["paid","underpaid","failed","expired"];function lt(s){return s?s.trim().toLowerCase().replace(/-/g,"_").split(":")[0]===je:!1}function sn(s){let e=s.filter(r=>r.assets.length>0),t=e.find(r=>!r.testnet)??e[0];if(!t)return null;let n=t.assets.find(r=>r.stable)??t.assets[0];return{chainId:t.chainId,asset:n.symbol}}function on(s,e,t){var o,a;let n=((o=s.find(c=>c.chainId===e))==null?void 0:o.assets)??[],r=n.find(c=>c.symbol===t),i=n.find(c=>c.stable)??n[0];return{chainId:e,asset:((a=r??i)==null?void 0:a.symbol)??t}}function an(s){if(!s)return"waiting";if(s.paid)return"paid";switch(s.status){case"detected":case"overpaid":return"confirming";case"underpaid":return"underpaid";case"failed":return"failed";case"expired":return"expired";default:return s.expired?"expired":"waiting"}}function ct(s,e){if(!s)return 0;let t=Date.parse(s);return Number.isNaN(t)?0:Math.max(0,Math.floor((t-e)/1e3))}function dt(s){let e=Math.max(0,Math.floor(s)),t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=String(e%60).padStart(2,"0");return t>0?`${t}:${String(n).padStart(2,"0")}:${r}`:`${n}:${r}`}var Ge="Crypto payments are not available right now. Choose another payment method.",Ie=class{constructor(e,t){this.api=e;this.options=t;this.state={options:"idle",networks:[],selection:null,payment:null,paymentStatus:null,isCreating:!1,error:null};this.listeners=new Set;this.pollTimer=null;this.stopped=!1;this.paidNotified=!1;this.subscribe=this.subscribe.bind(this),this.getState=this.getState.bind(this)}getState(){return this.state}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getPhase(e=Date.now()){let{payment:t,paymentStatus:n}=this.state,r=an(n??(t?{status:t.status,paid:!1,expired:!1}:null));return t!==null&&r==="waiting"&&ct(t.expiresAt,e)===0?"expired":r}getSecondsLeft(e=Date.now()){var t;return ct(((t=this.state.payment)==null?void 0:t.expiresAt)??null,e)}async loadOptions(){this.setState({options:"loading",error:null});try{let e=await this.api.getCryptoOnchainOptions(this.options.checkoutSessionId);if(!e.ok)return this.setState({options:"unavailable",networks:[],selection:null,error:e.message||Ge}),this.state;let t=this.state.selection??sn(e.networks);this.setState(t?{options:"ready",networks:e.networks,selection:t}:{options:"unavailable",networks:e.networks,selection:null,error:Ge})}catch(e){this.setState({options:"unavailable",error:ut(e)})}return this.state}select(e){let t=this.state.selection;if(e.chainId!==void 0&&e.chainId!==(t==null?void 0:t.chainId)){this.setState({selection:on(this.state.networks,e.chainId,e.asset??(t==null?void 0:t.asset)??"")});return}e.asset!==void 0&&t&&this.setState({selection:{...t,asset:e.asset}})}async pay(e){let t=e??this.state.selection;if(!t)return{ok:!1,code:"ASSET_NOT_AVAILABLE",message:"Choose a network and a coin"};if(this.state.isCreating)return{ok:!1,code:"CHECKOUT_FAILED",message:"A payment is already being created"};this.setState({isCreating:!0,error:null,selection:t});try{let n=await this.api.createCryptoOnchainPayment({checkoutSessionId:this.options.checkoutSessionId,chainId:t.chainId,asset:t.asset});return n.ok?(this.stopped=!1,this.setState({isCreating:!1,payment:n.payment,paymentStatus:null}),this.schedulePoll(),n):(this.setState({isCreating:!1,error:n.message}),n)}catch(n){let r=ut(n);return this.setState({isCreating:!1,error:r}),{ok:!1,code:"CHECKOUT_FAILED",message:r}}}async refreshStatus(){var t,n,r;let e=this.state.payment;if(!e)return null;try{let i=await this.api.getCryptoOnchainStatus({checkoutSessionId:this.options.checkoutSessionId,cryptoOnchainPaymentId:e.cryptoOnchainPaymentId});if(!i.ok||((t=this.state.payment)==null?void 0:t.cryptoOnchainPaymentId)!==e.cryptoOnchainPaymentId)return null;let o={status:i.status,paymentId:i.paymentId,orderId:i.orderId,confirmations:i.confirmations,requiredConfirmations:i.requiredConfirmations,txHash:i.txHash,explorerTxUrl:i.explorerTxUrl,paid:i.paid,expired:i.expired,redirectUrl:i.redirectUrl};return this.setState({paymentStatus:o}),o.paid&&!this.paidNotified&&(this.paidNotified=!0,(r=(n=this.options).onPaid)==null||r.call(n,o)),o}catch{return null}}resume(){!this.state.payment||ke.includes(this.getPhase())||(this.stopped=!1,this.schedulePoll())}stop(){this.stopped=!0,this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=null}schedulePoll(){this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.refreshStatus(),!this.stopped&&!ke.includes(this.getPhase())&&this.schedulePoll()},this.options.pollIntervalMs??5e3)}setState(e){var t,n;this.state={...this.state,...e},(n=(t=this.options).onChange)==null||n.call(t,this.state),this.listeners.forEach(r=>r(this.state))}};function ut(s){return s instanceof Error&&s.message?s.message:Ge}var cn="https://secure.oceanpayment.com/pages/js/oceanpayment.js",Ke="oceanpayment-element";var un={fi:"en"};function pt(s){var t;let e=(t=s==null?void 0:s.split(/[-_]/)[0])==null?void 0:t.toLowerCase();return e?un[e]??e:"en"}var ln=3e4,ae=null;function mt(){let s=window;return s.Oceanpayment?Promise.resolve(s.Oceanpayment):ae||(ae=new Promise((e,t)=>{let n=document.createElement("script"),r=o=>{clearTimeout(i),n.remove(),ae=null,t(new Error(o))},i=setTimeout(()=>r("The Ocean Payment card form took too long to load"),ln);n.addEventListener("load",()=>{if(!s.Oceanpayment)return r("Ocean Payment script loaded without window.Oceanpayment");clearTimeout(i),e(s.Oceanpayment)}),n.addEventListener("error",()=>r("Failed to load the Ocean Payment card form")),n.src=cn,document.head.appendChild(n)}),ae)}var $e="tgd:headless:oceanpayment:pending",dn=30*60*1e3;function gt(s){try{sessionStorage.setItem($e,JSON.stringify({paymentId:s,at:Date.now()}))}catch{}}function pn(){try{let s=sessionStorage.getItem($e);if(!s)return;sessionStorage.removeItem($e);let{paymentId:e,at:t}=JSON.parse(s);return!e||!t||Date.now()-t>dn?void 0:e}catch{return}}function be(){if(typeof window>"u")return;let s=pn();if(s)try{let e=new URL(window.location.href);if(e.searchParams.get("paymentId"))return;e.searchParams.set("paymentId",s),e.searchParams.set("paymentAction","requireAction"),e.searchParams.set("paymentActionStatus","completed"),window.history.replaceState(window.history.state,"",e.toString())}catch{}}var ft=new Set(["failed","declined","rejected","error"]),te=null,gn=()=>!!te&&(!te.attached||te.element.isConnected),ht=Symbol("ocean-timed-out"),yt=Symbol("ocean-unmounted"),fn=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function hn(s){var o;let e=s.type==="credit-card",t=e?"card":s.type,n=s.settings??{},r=n.processors,i=n.publishableKey;return{enabled:!0,method:t,provider:e?void 0:s.type,type:e?"card":s.type,label:s.title,logoUrl:s.iconUrl,express:fn.has(t),integrationId:e?void 0:s.id,processorId:(o=r==null?void 0:r[0])==null?void 0:o.processorId,publishableKey:typeof i=="string"?i:void 0,metadata:s.metadata??void 0}}function yn(){if(typeof window>"u")return Promise.reject(new Error("Stripe Radar needs a browser"));let s=()=>window.Stripe,e=s();return e?Promise.resolve(e):new Promise((t,n)=>{let r=document.createElement("script");r.src="https://js.stripe.com/v3/",r.async=!0,r.onload=()=>{let i=s();i?t(i):n(new Error("Stripe.js loaded without window.Stripe"))},r.onerror=()=>n(new Error("Failed to load Stripe.js")),document.head.appendChild(r)})}var Re=class{constructor(e,t,n,r,i,o){this.http=e;this.storeId=t;this.environment=n;this.checkout=r;this.onPaid=i;this.onSignal=o;this.lastPaymentSetup=null}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return this.lastPaymentSetup=t.paymentSetupConfig,t.paymentSetupConfig;let n=this.readInjectedStepConfig();if(n)return this.lastPaymentSetup=n,n;try{let i=await this.http.get(`/api/v1/checkout-sessions/${e}/payment-setup`),o={...(i==null?void 0:i.config)??{}};return this.lastPaymentSetup=o,o}catch(i){if(!(i instanceof ee))throw i}let r=await this.getPaymentSetupFromPickerList(e);return this.lastPaymentSetup=r,r}async getPaymentSetupFromPickerList(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),n=Array.isArray(t)?t.map(hn):(t==null?void 0:t.methods)??[],r={};for(let i of n){let o=i.provider&&i.provider!==i.method?`${i.method}:${i.provider}`:i.method;r[o]=i}return r}async getExpressMethods(e,t){var i,o,a,c,u,m,l,f,p,C;let n=await this.getPaymentSetup(e,t),r={};for(let[y,d]of Object.entries(n)){if(!d.enabled)continue;if(y.startsWith("express_checkout:")&&d.methods){let O={available:!0,processorId:d.processorId,publishableKey:d.publishableKey,metadata:d.metadata};if((i=d.methods.apple_pay)!=null&&i.enabled){let g=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));r.applePay={...O,type:"apple_pay",available:!!g}}(c=d.methods.google_pay)!=null&&c.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((u=this.onSignal)==null||u.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay={...O,type:"google_pay"}),(m=d.methods.link)!=null&&m.enabled&&(r.link={...O,type:"link"}),(l=d.methods.klarna_express)!=null&&l.enabled&&(r.klarna={...O,type:"klarna_express"});continue}if(!d.express)continue;let h=d.method,v={type:h,available:!0,processorId:d.processorId,publishableKey:d.publishableKey,metadata:d.metadata};if(h==="apple_pay"||d.type==="apple_pay"){let O=typeof window<"u"&&"ApplePaySession"in window&&((p=(f=window.ApplePaySession)==null?void 0:f.canMakePayments)==null?void 0:p.call(f));r.applePay={...v,available:!!O}}else h==="google_pay"||d.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((C=this.onSignal)==null||C.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay=v):h==="paypal"?r.paypal=v:h==="klarna"||h==="klarna_express"?r.klarna=v:h==="link"&&(r.link=v)}return r}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e,t){let n=await this.getPaymentSetup(e,t);return Object.entries(n).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(r.cardholderName=e.cardholderName);let i=await n.tokenizeCardRaw(r);return{tagadaToken:t.createTagadaToken(i,n.getProvider().getProviderName()),rawToken:i}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,returnUrl:e.returnUrl,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata,returnUrl:e.returnUrl})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId,returnUrl:e.returnUrl})}async syncWalletContact(e,t){let{shippingAddress:n,billingAddress:r}=t;if(!n&&!r)return;if(!this.checkout)throw new Error("PaymentModule cannot persist the wallet contact: no CheckoutModule was provided. Build the SDK through createTagadaClient() rather than constructing PaymentModule directly.");let i={};t.email&&(i.email=t.email),t.phone&&(i.phone=t.phone),t.firstName&&(i.firstName=t.firstName),t.lastName&&(i.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:i,shippingAddress:n,billingAddress:r})}async processApplePay(e){var a,c,u,m,l,f,p,C,y;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:Ce(e.shippingContact),billingAddress:Ce(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((c=e.billingContact)==null?void 0:c.emailAddress),phone:((u=e.shippingContact)==null?void 0:u.phoneNumber)??((m=e.billingContact)==null?void 0:m.phoneNumber),firstName:((l=e.shippingContact)==null?void 0:l.givenName)??((f=e.billingContact)==null?void 0:f.givenName),lastName:((p=e.shippingContact)==null?void 0:p.familyName)??((C=e.billingContact)==null?void 0:C.familyName)});let t=e.merchantRegistrationId??((y=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:y.merchantRegistrationId),n=await this.loadCoreJs(),r=new n.Tokenizer({environment:this.environment});await r.initialize();let i=await r.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(n.createTagadaDigitalWalletToken(i,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:o,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async resolveApplePayRegistration(e){if(typeof window>"u")return null;let t=window.location.hostname.toLowerCase().split(":")[0];t.startsWith("www.")&&(t=t.slice(4));let n=i=>{var o;for(let a of Object.values(i??{})){let c=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!c||typeof c!="object")continue;let u=c[t];if(u!=null&&u.merchantRegistrationId)return{merchantRegistrationId:u.merchantRegistrationId,displayName:u.displayName}}return null},r=n(this.readInjectedStepConfig())??n(this.lastPaymentSetup);if(r)return r;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return n(await this.getPaymentSetup(e))}catch{return null}}async processGooglePay(e){var o,a,c,u;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:Se(e.shippingAddress),billingAddress:Se(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.emailAddress),phone:((c=e.shippingAddress)==null?void 0:c.phoneNumber)??((u=e.billingAddress)==null?void 0:u.phoneNumber)});let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r=await n.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(r,"google_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:i,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async processStripeExpress(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:!0})}async getCryptoOnchainOptions(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e)}/crypto-onchain/options`)}async createCryptoOnchainPayment(e){return this.http.post(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/session`,{chainId:e.chainId,asset:e.asset})}async getCryptoOnchainStatus(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/status`,{params:{cryptoOnchainPaymentId:e.cryptoOnchainPaymentId}})}createCryptoOnchainCheckout(e){return new Ie(this,e)}async getOceanPaymentConfig(e){let t=await this.http.post(`/api/v1/checkout-sessions/${e}/oceanpayment-embedded-config`,{});return{embedded:!!(t!=null&&t.embedded),sandboxed:!!(t!=null&&t.sandboxed)}}async mountOceanPayment(e){if(typeof window>"u")throw new Error("Ocean Payment needs a browser");let{checkoutSessionId:t,signal:n}=e,r=()=>Object.assign(new Error("Ocean Payment mount aborted"),{name:"AbortError"});if(n!=null&&n.aborted)throw r();let i=typeof e.container=="string"?document.querySelector(e.container):e.container;if(!i&&e.mode!=="redirect")throw new Error(`Ocean Payment container not found: ${String(e.container)}`);if(gn()||document.getElementById(Ke))throw new Error("An Ocean Payment card form is already mounted on this page");let o=window,a=document.createElement("div");a.id=Ke;let c={element:a,attached:!1};te=c;let u=()=>{te===c&&(te=null)},m=!0,l=null,f=g=>{let P=l;l=null,P==null||P(g)},p=()=>{m&&(m=!1,o.oceanpaymentCallBack===f&&delete o.oceanpaymentCallBack,a.remove(),u(),f(yt))};n==null||n.addEventListener("abort",p,{once:!0});let C,y;try{if(C=e.mode==="redirect"?{embedded:!1,sandboxed:!1}:await this.getOceanPaymentConfig(t),n!=null&&n.aborted||C.embedded&&(y=await mt(),n!=null&&n.aborted))throw r()}catch(g){throw p(),g}let d=!1;if(!y)return u(),{mode:"redirect",pay:async()=>{if(!m)return{status:"failed",error:"The Ocean Payment form was removed"};if(d)return{status:"failed",error:"Payment already in progress"};d=!0;try{let g=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-link`,{returnUrl:e.returnUrl??window.location.href});return!(g!=null&&g.url)||!g.paymentId?{status:"failed",error:"Ocean Payment is not available for this store"}:{status:"requires_redirect",redirectUrl:g.url,method:"GET",paymentId:g.paymentId}}catch(g){return{status:"failed",error:g instanceof Error?g.message:String(g)}}finally{d=!1}},unmount:p};let h=y;i.appendChild(a),c.attached=!0,o.oceanpaymentCallBack=f;let v=window.location.href;return h.init(C.sandboxed,"",pt(e.locale),{showCardName:!1}),{mode:"embedded",pay:async()=>{if(!m)return{status:"failed",error:"The Ocean Payment card form was removed"};if(d)return{status:"failed",error:"Payment already in progress"};d=!0;try{let g=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-payment`,{backUrl:v});if(!(g!=null&&g.paymentId)||!g.params)return{status:"failed",error:"Failed to start the payment"};let P=g.paymentId,w=await new Promise(j=>{let $=setTimeout(()=>{l=null,j(ht)},12e4);l=R=>{clearTimeout($),j(R)},h.checkout(g.params)});if(w===ht||w===yt)return this.pollUntilDone(P);if(w&&typeof w=="object"&&"msg"in w)return{status:"failed",error:String(w.msg||"Please check your card details.")};let I=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-result`,{paymentId:P,response:String(w)});return(I==null?void 0:I.status)==="requires_action"&&I.payUrl?(gt(P),{status:"requires_redirect",redirectUrl:I.payUrl,method:"GET",paymentId:P}):(I==null?void 0:I.status)==="succeeded"||(I==null?void 0:I.status)==="pending"?this.pollUntilDone(P):{status:"failed",error:(I==null?void 0:I.message)||"Payment declined"}}catch(g){return{status:"failed",error:g instanceof Error?g.message:String(g)}}finally{d=!1}},unmount:p}}async processPayment(e){!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e);return this.finalize(t,{returnUrl:e.returnUrl})}async finalize(e,t){var i,o,a;let n=e.payment,r=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return n.status==="succeeded"?(this.emitPaid((i=e.order)==null?void 0:i.id,n),{status:"succeeded",payment:n,order:e.order}):n.status==="failed"||n.status==="declined"?{status:"failed",error:((o=n.requireActionData)==null?void 0:o.message)||((a=n.requireActionData)==null?void 0:a.errorCode)||`Payment ${n.status}`,payment:n}:n.requireAction&&n.requireAction!=="none"&&n.requireActionData?this.handlePaymentAction(n,{returnUrl:r}):this.pollUntilDone(n.id)}async resumeAfterRedirect(e){return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;e!=null&&e.url||be();let t=(e==null?void 0:e.url)??window.location.href,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("paymentAction"),i=n.searchParams.get("paymentActionStatus"),o=n.searchParams.get("paymentId");if(r!=="requireAction"||i!=="completed"||!o)return null;let a=await this.resumeAfterRedirect(o);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let c=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(m=>c.delete(m));let u=c.toString();try{window.history.replaceState({},document.title,window.location.pathname+(u?"?"+u:""))}catch{}}return a}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<r;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||ft.has(o.status))return o;await new Promise(a=>setTimeout(a,n))}throw new Error(`Payment ${e} did not reach terminal status within ${r}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async markActionProcessed(e){try{await this.http.post("/api/v1/payments/require-action/processed",{paymentId:e})}catch{}}async handlePaymentAction(e,t){let n=e.requireActionData;switch(await this.markActionProcessed(e.id),n.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,n);case"redirect":return this.extractRedirect(e,n);case"stripe_radar":return this.handleStripeRadar(e);case"error":return{status:"failed",error:n.message||n.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,n)}}extractRedirect(e,t){var i,o;let n=(i=t.metadata)==null?void 0:i.redirect,r=(n==null?void 0:n.redirectUrl)||t.redirectUrl;return r?{status:"requires_redirect",redirectUrl:r,method:((o=n==null?void 0:n.method)==null?void 0:o.toUpperCase())||"GET",postData:n==null?void 0:n.data,paymentId:e.id}:{status:"failed",error:`Payment requires action (${t.type}) but no redirect URL was provided`,payment:e}}async handleThreedsAuth(e,t){var i,o;let n=(o=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:o.threedsSession;if(!(n!=null&&n.externalSessionId))return this.extractRedirect(e,e.requireActionData);let r;try{r=await import("@tagadapay/core-js")}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new r.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:n.externalSessionId,acsChallengeUrl:n.acsChallengeUrl,acsTransactionId:n.acsTransID,threeDSVersion:n.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async handleStripeRadar(e){var n,r;let t=(r=(n=e.requireActionData)==null?void 0:n.metadata)==null?void 0:r.radar;if(!(t!=null&&t.publishableKey))return{status:"failed",error:"Stripe Radar configuration missing",payment:e};try{let i=await yn(),{radarSession:o,error:a}=await i(t.publishableKey).createRadarSession();if(a||!o)throw new Error((a==null?void 0:a.message)||"No Radar session returned by Stripe");return await this.http.post("/api/v1/radar-sessions",{orderId:t.orderId,paymentId:e.id,stripeRadarSessionId:o.id,stripeRadarSessionData:o}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch(i){return{status:"failed",error:i instanceof Error?i.message:"Stripe Radar failed",payment:e}}}async pollUntilDone(e,t){var a;let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<r;){let c;try{c=await this.getPaymentStatus(e),o=0}catch{if(o++,o>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(u=>setTimeout(u,n));continue}if(c.status==="succeeded"||c.status==="pending"&&c.subStatus==="authorized")return c.status==="succeeded"&&this.emitPaid((a=c.order)==null?void 0:a.id,c),{status:"succeeded",payment:c,order:c.order};if(ft.has(c.status))return{status:"failed",error:c.status,payment:c};if(c.requireAction&&c.requireAction!=="none"&&c.requireActionData&&!c.requireActionData.processed)return this.handlePaymentAction(c,{});await new Promise(u=>setTimeout(u,n))}return{status:"pending",paymentId:e}}readInjectedStepConfig(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{let t=typeof e=="string"?JSON.parse(e):e;return(t==null?void 0:t.paymentSetupConfig)??null}catch{return null}}emitPaid(e,t){var n;if(!(!e||!this.onPaid))try{let r=(n=this.checkout)==null?void 0:n.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:ve(r==null?void 0:r.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var J=typeof document>"u"?null:document.currentScript,Pn=J!=null&&J.src?new URL("tagada-headless-commerce.min.js",J.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.1/dist/tagada-headless-commerce.min.js",Oe;function ne(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(Oe||(Oe=new Promise((s,e)=>{let t=document.createElement("script");t.src=Pn,t.async=!0,J!=null&&J.nonce&&(t.nonce=J.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?s(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(s=>{throw Oe=void 0,s})),Oe)}var ce=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ne().then(e=>new e.OffersModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getOffer","listOffers","previewOffer","enterFunnelStep","payPreviewedOffer","processOfferPayment","toggleOrderBump","listPostPurchaseOffers","acceptPostPurchaseOffer","declinePostPurchaseOffer"])ce.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var ue=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ne().then(e=>new e.CustomerModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getProfile","getByEmail","updateProfile","getOrders","getOrder","getSubscriptions","getSubscription","pauseSubscription","resumeSubscription","skipSubscription","rescheduleSubscription","updateSubscriptionQuantity","changeSubscriptionFrequency","swapSubscriptionProduct","updateSubscriptionPaymentMethod","cancelSubscription"])ue.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var le=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ne().then(e=>new e.CustomerPortalModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["requestCode","verifyCode","getConfig","getMe","cancelFlow","acceptCancelOffer","switchOption","getOffer","acceptOffer","addToNextOrder","getCredits","redeemCredits","buyCreditPack","requestEmailChangeCode","updateProfile","saveAddress","removeAddress","setDefaultAddress","addCard","removeCard","setDefaultPaymentMethod","retryPayment","buyAgain","joinMembership","buyNow","sendNow","reactivateSubscription","setSubscriptionCard","setSubscriptionAddress","skipDate","unskipDate"])le.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var xe=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var r,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(r=e==null?void 0:e.productIds)!=null&&r.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var Ae=class{constructor(e,t,n,r,i){this.http=e;this.storeId=t;this.checkout=n;this.accountId=r;this.onFunnelSession=i}async navigate(e){var a,c;let t=this.checkout.getCurrentSession();if(!t)throw new q("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let n=e.accountId??this.accountId;if(!n)throw new q("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let r=e.currentUrl??(typeof globalThis<"u"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,n,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:n,currentUrl:r});try{(c=this.onFunnelSession)==null||c.call(this,i)}catch{}return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:r}),funnelSessionId:i}}async ensureCmsSession(e,t,n){var o,a,c;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let r=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=r.token,this._cmsSessionId=r.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((o=n.customer)==null?void 0:o.locale)??Cn(),userAgent:Sn(),queryCurrency:((a=n.customer)==null?void 0:a.currency)??e.currency,queryLocale:(c=n.customer)==null?void 0:c.locale},{token:this._cmsToken});this._cmsCustomerId=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var l,f,p,C;let{funnelSessionId:t,stepId:n,session:r,input:i,currentUrl:o}=e,a=r.items.map(y=>({variantId:y.variantId,priceId:y.priceId,quantity:y.quantity})),c=i.discountCodes??(r.promotionCode?[r.promotionCode]:void 0),u={email:((l=i.customer)==null?void 0:l.email)??((f=r.customer)==null?void 0:f.email),currency:((p=i.customer)==null?void 0:p.currency)??r.currency,locale:(C=i.customer)==null?void 0:C.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:n,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:r.id,lineItems:a,customer:u,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:c,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function Cn(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Sn(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var Te=class{constructor(e,t){this.http=e;this.storeId=t}async getActivationStatus(e){let t=e??this.storeId;if(!t)throw new Error("rx.getActivationStatus: storeId is required");return this.http.get("/api/public/v1/rx/activation-status",{params:{storeId:t}})}async isRequiredForProduct(e,t){return this.http.get("/api/public/v1/rx/required-for-product",{params:{productId:e,clinicalNetworkId:t==null?void 0:t.clinicalNetworkId}})}async getCasesForOrder(e){return this.http.post("/api/public/v1/rx/cases/lookup",e)}async getIntakeContext(e){return this.http.post("/api/public/v1/rx/intake/context",e)}async submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",e)}async validateIntake(e){return this.http.post("/api/public/v1/rx/intake/validate",e)}async getQuestionsForProduct(e,t){return this.http.get("/api/public/v1/rx/questions-for-product",{params:t?{productId:e,variantId:t}:{productId:e}})}};var Ee=class{constructor(e,t){this.core=e;this.bootstrap=t;this.runtime=null;this.loading=null;this.settled=!1;this.reads=new Set;this.subscribers=[]}variant(e){var t,n,r,i;return((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.arm)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.variant)??null}start(){return typeof window>"u"?Promise.resolve():(this.loading??(this.loading=(async()=>{try{this.runtime=await this.core()}catch{}this.settled=!0;let e=this.runtime;for(let t of this.reads)try{e==null||e.getVariant(t)}catch{}this.reads.clear();for(let{key:t,cb:n}of this.subscribers.splice(0))try{e?e.onVariant(t,n):n(this.variant(t))}catch{}try{await(e==null?void 0:e.ready())}catch{}})()),this.loading)}read(e){this.settled||this.reads.add(e),this.start()}getVariant(e){return this.runtime?this.runtime.getVariant(e):(this.read(e),this.variant(e))}getPayload(e){var t,n,r,i;return this.runtime?this.runtime.getPayload(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.payload)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.payload)??null)}isEnabled(e){var t,n;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:n.enabled)??!1)}onVariant(e,t){if(this.runtime){this.runtime.onVariant(e,t);return}if(this.settled){t(this.variant(e));return}this.subscribers.push({key:e,cb:t}),this.start()}ready(){return this.start()}};var Be=class{constructor(e){let t=e.environment??"production",n=ie.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new ie({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new we(n,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new Ee(()=>this.track.core(),this.config.bootstrap);let r=i=>{this._sessionToken=i};this.checkout=new oe(this.http,this.config.storeId,r,i=>this.track.noteCheckout({checkoutSessionId:i.id,amount:i.totals.total,currency:i.totals.currency,items:ve(i.items)})),this.payment=new Re(this.http,this.config.storeId,t,this.checkout,i=>this.track.notePaid(i),(i,o)=>this.track.noteSignal("wallet_unavailable",i,o)),this.offers=new ce(this.http,this.config.storeId,this.payment),this.customer=new ue(this.http,this.config.storeId),this.portal=new le(this.http,this.config.storeId,r),this.catalog=new xe(this.http,this.config.storeId),this.funnel=new Ae(this.http,this.config.storeId,this.checkout,this.config.accountId,i=>this.track.noteFunnelSession(i)),this.rx=new Te(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function Pt(s){return new Be(s)}var wt=N("react/jsx-runtime"),Ct=(0,Y.createContext)(null);function wn(s){let e={storeId:s.storeId,environment:s.environment,apiKey:s.apiKey,baseUrl:s.baseUrl,accountId:s.accountId,funnel:s.funnel,timeout:s.timeout,bootstrap:s.bootstrap};return JSON.stringify(e)}function vn(s){if(s.config)return s.config;let{storeId:e,environment:t,apiKey:n,baseUrl:r}=s;return{storeId:e,environment:t,apiKey:n,baseUrl:r}}function St(s){let e=vn(s),t=wn(e),n=(0,Y.useMemo)(()=>Pt(e),[t]),r=(0,Y.useMemo)(()=>({client:n}),[n]);return(0,wt.jsx)(Ct.Provider,{value:r,children:s.children})}function E(){let s=(0,Y.useContext)(Ct);if(!s)throw new Error("useHeadlessClient must be used within <TagadaHeadlessProvider>");return s.client}var _=N("react");function vt(s,e){let t=E(),[n,r]=(0,_.useState)(null),[i,o]=(0,_.useState)(!1),[a,c]=(0,_.useState)(null),u=(0,_.useCallback)(async()=>{if(s){o(!0),c(null);try{let g=await t.checkout.loadSession(s,e);r(g)}catch(g){c(g instanceof Error?g:new Error(String(g)))}finally{o(!1)}}},[t,s,e]);(0,_.useEffect)(()=>{u()},[u]);let m=(0,_.useCallback)(async g=>{o(!0),c(null);try{let P=await t.checkout.createSession(g),w=new URL(window.location.href);w.searchParams.set("checkoutToken",P.checkoutToken),w.searchParams.set("token",P.sessionToken),window.history.replaceState({},"",w.toString());let I=await t.checkout.loadSession(P.checkoutToken,P.sessionToken);r(I)}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}},[t]),l=(0,_.useCallback)(async g=>{c(null);try{return await t.checkout.createSessionUrl(g)}catch(P){let w=P instanceof Error?P:new Error(String(P));throw c(w),w}},[t]),f=(0,_.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.updateCart(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),p=(0,_.useCallback)(async g=>{n&&await t.checkout.updateCustomer(n.id,g)},[t,n]),C=(0,_.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.updateAddress(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),y=(0,_.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.updateCustomerAndAddress(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),d=(0,_.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.applyPromoCode(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),h=(0,_.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.removePromoCode(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),v=(0,_.useCallback)(async()=>n?t.checkout.getShippingRates(n.id):[],[t,n]),O=(0,_.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.selectShippingRate(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]);return{session:n,isLoading:i,error:a,refresh:u,createSession:m,createSessionUrl:l,updateCart:f,updateCustomer:p,updateAddress:C,updateCustomerAndAddress:y,applyPromo:d,removePromo:h,getShippingRates:v,selectShippingRate:O}}var A=N("react");var kt=new Set;function _e(s){return kt.has(s)?!1:(kt.add(s),!0)}function It(s){let e=E(),[t,n]=(0,A.useState)(null),[r,i]=(0,A.useState)(null),[o,a]=(0,A.useState)(null),[c,u]=(0,A.useState)(!1),[m,l]=(0,A.useState)(null),[f,p]=(0,A.useState)(null),C=(0,A.useRef)(!1),y=(0,A.useRef)(!1),d=(0,A.useRef)(s);d.current=s,(0,A.useEffect)(()=>{if(typeof window>"u"||y.current)return;be();let R=new URLSearchParams(window.location.search),S=R.get("paymentAction"),k=R.get("paymentActionStatus"),U=R.get("paymentId");if(S!=="requireAction"||k!=="completed"||!U||(y.current=!0,!_e(U)))return;u(!0),p(null),(async()=>{var b,x,K,X;try{let M=await e.payment.resumeAfterRedirect(U),Me=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(Gt=>Me.delete(Gt));let qt=Me.toString()?`${window.location.pathname}?${Me.toString()}`:window.location.pathname;window.history.replaceState({},document.title,qt),M.status==="succeeded"?(x=(b=d.current)==null?void 0:b.onPaymentSuccess)==null||x.call(b,M):M.status==="failed"&&(p(new Error(M.error)),(X=(K=d.current)==null?void 0:K.onPaymentFailed)==null||X.call(K,M))}catch(M){p(M instanceof Error?M:new Error(String(M)))}finally{u(!1)}})()},[e]);let h=(0,A.useCallback)(async(R,S)=>{var U;if(C.current)return;C.current=!0;let k=S!=null&&S.paymentSetupConfig?{paymentSetupConfig:S.paymentSetupConfig}:(U=d.current)!=null&&U.paymentSetupConfig?{paymentSetupConfig:d.current.paymentSetupConfig}:void 0;try{let[D,b,x]=await Promise.all([e.payment.getPaymentSetup(R,k),e.payment.getExpressMethods(R,k),e.payment.getStoreConfig()]);n(D),i(b),a(x)}catch(D){C.current=!1,p(D instanceof Error?D:new Error(String(D)))}},[e]),v=(0,A.useCallback)(async R=>{var S,k,U,D;u(!0),p(null);try{let b=await e.payment.processPayment(R);if(b.status==="requires_redirect"){if(b.method==="POST"&&b.postData){let x=document.createElement("form");x.method="POST",x.action=b.redirectUrl;for(let[K,X]of Object.entries(b.postData)){let M=document.createElement("input");M.type="hidden",M.name=K,M.value=X,x.appendChild(M)}document.body.appendChild(x),x.submit()}else window.location.href=b.redirectUrl;return b}return b.status==="succeeded"?(k=(S=d.current)==null?void 0:S.onPaymentSuccess)==null||k.call(S,b):b.status==="failed"&&(p(new Error(b.error)),(D=(U=d.current)==null?void 0:U.onPaymentFailed)==null||D.call(U,b)),b}catch(b){let x=b instanceof Error?b:new Error(String(b));return p(x),{status:"failed",error:x.message}}finally{u(!1)}},[e]),O=(0,A.useCallback)(R=>async()=>{u(!0),p(null);try{return await R()}catch(S){let k=S instanceof Error?S:new Error(String(S));throw p(k),k}finally{u(!1)}},[]),g=(0,A.useCallback)(async R=>{u(!0),p(null);try{let S=await e.payment.pay(R);return l(S),S}catch(S){let k=S instanceof Error?S:new Error(String(S));throw p(k),k}finally{u(!1)}},[e]),P=(0,A.useCallback)(R=>e.payment.tokenizeCard(R),[e]),w=(0,A.useCallback)(async R=>{let k=await O(()=>e.payment.processApplePay(R))();return l(k),k},[e,O]),I=(0,A.useCallback)(async R=>{let k=await O(()=>e.payment.processGooglePay(R))();return l(k),k},[e,O]),j=(0,A.useCallback)(async R=>{let k=await O(()=>e.payment.processApm(R))();return l(k),k},[e,O]),$=(0,A.useCallback)(R=>e.payment.pollPaymentStatus(R),[e]);return{paymentSetup:t,expressMethods:r,storeConfig:o,isProcessing:c,result:m,error:f,loadPaymentSetup:h,processPayment:v,pay:g,tokenizeCard:P,processApplePay:w,processGooglePay:I,processApm:j,pollStatus:$}}var H=N("react");var kn={options:"idle",networks:[],selection:null,payment:null,paymentStatus:null,isCreating:!1,error:null},In=()=>()=>{},bt=()=>kn;function Rt({checkoutSessionId:s,enabled:e=!0,onPaid:t,pollIntervalMs:n}){let r=E(),i=(0,H.useRef)(t);(0,H.useEffect)(()=>{i.current=t},[t]);let o=(0,H.useMemo)(()=>s?r.payment.createCryptoOnchainCheckout({checkoutSessionId:s,pollIntervalMs:n,onPaid:y=>{var d;return(d=i.current)==null?void 0:d.call(i,y)}}):null,[r,s,n]),a=(0,H.useSyncExternalStore)(o?o.subscribe:In,o?o.getState:bt,o?o.getState:bt);(0,H.useEffect)(()=>{if(!(!o||!e))return o.getState().options==="idle"?o.loadOptions():o.resume(),()=>o.stop()},[o,e]);let[c,u]=(0,H.useState)(()=>Date.now()),m=o?o.getPhase(c):"waiting",l=a.payment!==null&&!ke.includes(m);(0,H.useEffect)(()=>{if(!l)return;let y=setInterval(()=>u(Date.now()),1e3);return()=>clearInterval(y)},[l]);let f=(0,H.useCallback)(y=>o==null?void 0:o.select(y),[o]),p=(0,H.useCallback)(y=>o?o.pay(y):Promise.resolve({ok:!1,code:"CHECKOUT_FAILED",message:"No checkout session"}),[o]),C=(0,H.useCallback)(()=>o?o.refreshStatus():Promise.resolve(null),[o]);return{...a,phase:m,secondsLeft:o?o.getSecondsLeft(c):0,select:f,pay:p,refreshStatus:C}}var T=N("react");function Ot(s){let e=E(),[t,n]=(0,T.useState)(null),[r,i]=(0,T.useState)(null),[o,a]=(0,T.useState)(!1),[c,u]=(0,T.useState)(null),m=(0,T.useRef)(s);m.current=s;let l=(0,T.useRef)(!1);(0,T.useEffect)(()=>{var S;if(typeof window>"u"||(S=m.current)!=null&&S.disableAutoResume||l.current)return;let w=new URLSearchParams(window.location.search),I=w.get("paymentAction"),j=w.get("paymentActionStatus"),$=w.get("paymentId");if(I!=="requireAction"||j!=="completed"||!$||(l.current=!0,!_e($)))return;a(!0),u(null),(async()=>{var k,U,D,b;try{let x=await e.payment.resumeAfterRedirect($),K=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(M=>K.delete(M));let X=K.toString()?`${window.location.pathname}?${K.toString()}`:window.location.pathname;window.history.replaceState({},document.title,X),x.status==="succeeded"?(U=(k=m.current)==null?void 0:k.onOfferAccepted)==null||U.call(k,x):x.status==="failed"&&(u(new Error(x.error)),(b=(D=m.current)==null?void 0:D.onOfferDeclined)==null||b.call(D,x))}catch(x){u(x instanceof Error?x:new Error(String(x)))}finally{a(!1)}})()},[e]);let f=(0,T.useCallback)(async w=>{a(!0),u(null);try{return await w()}catch(I){let j=I instanceof Error?I:new Error(String(I));throw u(j),j}finally{a(!1)}},[]),p=(0,T.useCallback)(w=>f(async()=>{let I=await e.offers.getOffer(w);return n(I),I}),[e,f]),C=(0,T.useCallback)(w=>e.offers.listOffers(w),[e]),y=(0,T.useCallback)(w=>f(async()=>{let I=await e.offers.previewOffer(w);return i(I),I}),[e,f]),d=(0,T.useCallback)(w=>f(()=>e.offers.payPreviewedOffer(w)),[e,f]),h=(0,T.useCallback)(async w=>{var I,j,$,R;a(!0),u(null);try{let S=await e.offers.processOfferPayment(w);if(S.status==="requires_redirect"){if(S.method==="POST"&&S.postData){let k=document.createElement("form");k.method="POST",k.action=S.redirectUrl;for(let[U,D]of Object.entries(S.postData)){let b=document.createElement("input");b.type="hidden",b.name=U,b.value=D,k.appendChild(b)}document.body.appendChild(k),k.submit()}else window.location.href=S.redirectUrl;return S}return S.status==="succeeded"?(j=(I=m.current)==null?void 0:I.onOfferAccepted)==null||j.call(I,S):S.status==="failed"&&(u(new Error(S.error)),(R=($=m.current)==null?void 0:$.onOfferDeclined)==null||R.call($,S)),S}catch(S){let k=S instanceof Error?S:new Error(String(S));return u(k),{status:"failed",error:k.message}}finally{a(!1)}},[e]),v=(0,T.useCallback)(w=>e.offers.toggleOrderBump(w),[e]),O=(0,T.useCallback)(w=>e.offers.listPostPurchaseOffers(w),[e]),g=(0,T.useCallback)(w=>f(()=>e.offers.acceptPostPurchaseOffer(w)),[e,f]),P=(0,T.useCallback)(w=>f(()=>e.offers.declinePostPurchaseOffer(w)),[e,f]);return{offer:t,preview:r,isLoading:o,error:c,getOffer:p,listOffers:C,previewOffer:y,processOfferPayment:h,payPreviewedOffer:d,toggleOrderBump:v,listPostPurchaseOffers:O,acceptPostPurchaseOffer:g,declinePostPurchaseOffer:P}}var G=N("react");function xt(s){let e=E(),[t,n]=(0,G.useState)(null),[r,i]=(0,G.useState)([]),[o,a]=(0,G.useState)([]),[c,u]=(0,G.useState)(!1),[m,l]=(0,G.useState)(null),f=(0,G.useCallback)(async d=>{u(!0),l(null);try{let h=await e.customer.getProfile(d);n(h)}catch(h){l(h instanceof Error?h:new Error(String(h)))}finally{u(!1)}},[e]),p=(0,G.useCallback)(async d=>{try{let h=await e.customer.getOrders(d);i(h.orders)}catch(h){l(h instanceof Error?h:new Error(String(h)))}},[e]),C=(0,G.useCallback)(async d=>{try{let h=await e.customer.getSubscriptions(d);a(h)}catch(h){l(h instanceof Error?h:new Error(String(h)))}},[e]),y=(0,G.useCallback)(async(d,h)=>{try{let v=await e.customer.updateProfile(d,h);n(v)}catch(v){l(v instanceof Error?v:new Error(String(v)))}},[e]);return(0,G.useEffect)(()=>{s&&f(s)},[s,f]),{customer:t,orders:r,subscriptions:o,isLoading:c,error:m,loadCustomer:f,loadOrders:p,loadSubscriptions:C,updateProfile:y}}var B=N("react");function At(s,e){let t=E(),[n,r]=(0,B.useState)(null),[i,o]=(0,B.useState)(!1),[a,c]=(0,B.useState)(null),u=(e==null?void 0:e.watchRelatedOrders)??!0,m=(e==null?void 0:e.watchTimeoutMs)??8e3,l=(e==null?void 0:e.watchIntervalMs)??2e3,f=(0,B.useRef)(0),p=(0,B.useCallback)(async()=>{if(s)try{let C=await t.customer.getOrder(s);r(C)}catch(C){c(C instanceof Error?C:new Error(String(C)))}},[t,s]);return(0,B.useEffect)(()=>{if(!s)return;let C=++f.current,y=()=>f.current===C;return o(!0),c(null),(async()=>{var d,h;try{let v=await t.customer.getOrder(s);if(!y()||(r(v),o(!1),!u||(d=v.relatedOrders)!=null&&d.length))return;let O=Date.now()+m;for(;Date.now()<O&&y();){if(await new Promise(g=>setTimeout(g,l)),!y()||(v=await t.customer.getOrder(s),!y()))return;if((h=v.relatedOrders)!=null&&h.length){r(v);return}}}catch(v){if(!y())return;c(v instanceof Error?v:new Error(String(v))),o(!1)}})(),()=>{f.current++}},[t,s,u,m,l]),{order:n,relatedOrders:(n==null?void 0:n.relatedOrders)??[],isLoading:i,error:a,refresh:p}}var W=N("react");function Tt(){let s=E(),[e,t]=(0,W.useState)([]),[n,r]=(0,W.useState)(!1),[i,o]=(0,W.useState)(null),a=(0,W.useCallback)(async u=>{r(!0),o(null);try{let m=await s.catalog.getProducts(u);return t(m),m}catch(m){let l=m instanceof Error?m:new Error(String(m));throw o(l),l}finally{r(!1)}},[s]),c=(0,W.useCallback)(async u=>{r(!0),o(null);try{return await s.catalog.getProduct(u)}catch(m){let l=m instanceof Error?m:new Error(String(m));throw o(l),l}finally{r(!1)}},[s]);return{products:e,isLoading:n,error:i,loadProducts:a,loadProduct:c}}var F=N("react");var bn=new Set(["approved","shipped","delivered","declined","cancelled","error"]);function Et(){let s=E(),[e,t]=(0,F.useState)([]),[n,r]=(0,F.useState)(null),[i,o]=(0,F.useState)(!1),[a,c]=(0,F.useState)(null),u=(0,F.useRef)(null);(0,F.useEffect)(()=>()=>{u.current&&clearInterval(u.current)},[]);let m=(0,F.useCallback)(async(y,d)=>{o(!0),c(null);try{return await s.rx.isRequiredForProduct(y,d)}catch(h){let v=h instanceof Error?h:new Error(String(h));throw c(v),v}finally{o(!1)}},[s]),l=(0,F.useCallback)(async(y,d)=>{o(!0),c(null);try{return await s.rx.getQuestionsForProduct(y,d)}catch(h){let v=h instanceof Error?h:new Error(String(h));throw c(v),v}finally{o(!1)}},[s]),f=(0,F.useCallback)(async y=>{o(!0),c(null);try{let d=await s.rx.submitCase(y);return r(d),d}catch(d){let h=d instanceof Error?d:new Error(String(d));throw c(h),h}finally{o(!1)}},[s]),p=(0,F.useCallback)(async y=>{o(!0),c(null);try{let d=await s.rx.getCasesForOrder(y);return t(d.cases),d.cases}catch(d){let h=d instanceof Error?d:new Error(String(d));throw c(h),h}finally{o(!1)}},[s]),C=(0,F.useCallback)(({orderId:y,checkoutToken:d},h)=>{u.current&&clearInterval(u.current);let v=(h==null?void 0:h.intervalMs)??5e3,O=async()=>{var g;try{let P=await s.rx.getCasesForOrder({orderId:y,checkoutToken:d});t(P.cases),(g=h==null?void 0:h.onUpdate)==null||g.call(h,P.cases),P.cases.length>0&&P.cases.every(w=>bn.has(w.status))&&(u.current&&clearInterval(u.current),u.current=null)}catch(P){let w=P instanceof Error?P:new Error(String(P));c(w)}};return O(),u.current=setInterval(O,v),()=>{u.current&&clearInterval(u.current),u.current=null}},[s]);return{cases:e,lastSubmission:n,isLoading:i,error:a,isRequiredForProduct:m,getQuestionsForProduct:l,submitCase:f,fetchCasesForOrder:p,pollOrder:C}}var _t=N("react");function Nt(s,e){let t=E(),n=e?JSON.stringify(e):"";(0,_t.useEffect)(()=>{t.track.step(s,e)},[t,s,n])}var L=N("react");var Lt=!1,Ut=!1,Ne=[];function Ve(){Ut=!0;for(let s of Ne)s();Ne.length=0}function de(s,e={}){var t,n;return Ut||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(Ve(),Promise.resolve()):Lt?new Promise(r=>Ne.push(r)):(Lt=!0,new Promise((r,i)=>{if(Ne.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let u=()=>{var m,l;(l=(m=window.google)==null?void 0:m.maps)!=null&&l.places?Ve():setTimeout(u,100)};u();return}let a=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let c=document.createElement("script");c.src=`https://maps.googleapis.com/maps/api/js?${a}`,c.async=!0,c.defer=!0,c.onload=()=>Ve(),c.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(c)}))}var V=class s{static async searchPlaces(e,t={}){var r,i;if(!((i=(r=window.google)==null?void 0:r.maps)!=null&&i.places)||!e.trim())return[];let n=new window.google.maps.places.AutocompleteService;return new Promise(o=>{n.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,c)=>{var u,m,l;o(c===((l=(m=(u=window.google)==null?void 0:u.maps)==null?void 0:m.places)==null?void 0:l.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var n,r;if(!((r=(n=window.google)==null?void 0:n.maps)!=null&&r.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var c,u,m;i(a===((m=(u=(c=window.google)==null?void 0:c.maps)==null?void 0:u.places)==null?void 0:m.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},n="",r="",i="",o="",a="",c="",u="",m="";for(let p of e.address_components??[]){let C=p.types;C.includes("subpremise")&&(t.subpremise=p.long_name),C.includes("street_number")&&(t.streetNumber=p.long_name),C.includes("premise")&&(n=p.long_name),C.includes("route")&&(t.route=p.long_name),C.includes("neighborhood")&&(r=p.long_name),C.includes("sublocality_level_5")&&(i=p.long_name),C.includes("sublocality_level_4")&&(o=p.long_name),C.includes("sublocality_level_3")&&(a=p.long_name),C.includes("sublocality_level_2")&&(c=p.long_name),C.includes("sublocality_level_1")&&(u=p.long_name),C.includes("locality")&&(t.locality=p.long_name),C.includes("postal_town")&&(m=p.long_name),C.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=p.short_name,t.administrativeAreaLevel2Long=p.long_name),C.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=p.short_name,t.administrativeAreaLevel1Long=p.long_name),C.includes("country")&&(t.country=p.short_name),C.includes("postal_code")&&(t.postalCode=p.long_name)}t.locality||(t.locality=m||c||u||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let l=t.streetNumber||n,f=t.route||i||o||a||r;if(t.subpremise&&l&&f)t.fullStreetAddress=`${t.subpremise}/${l} ${f}`;else if(l&&f)if(n&&o&&a){let p=`${a}-${o}-${n}`;c&&(p=`${p} ${c}`),t.fullStreetAddress=p}else t.fullStreetAddress=`${l} ${f}`;else f?t.fullStreetAddress=f:l&&(t.fullStreetAddress=l);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};function Dt(s){let{apiKey:e,language:t,region:n,version:r,defer:i=!1}=s,[o,a]=(0,L.useState)([]),[c,u]=(0,L.useState)(!1),[m,l]=(0,L.useState)(!1),f=(0,L.useRef)(null),p=(0,L.useRef)(null),C=(0,L.useCallback)(()=>{de(e,{language:t,region:n,version:r}).then(()=>l(!0))},[e,t,n,r]);(0,L.useEffect)(()=>{!e||i||C()},[e,i,C]),(0,L.useEffect)(()=>{if(m&&p.current){let{input:g,country:P}=p.current;p.current=null,y(g,P)}},[m]);let y=(0,L.useCallback)((g,P)=>{if(!m){i&&(p.current={input:g,country:P},C());return}if(g.length<3){a([]);return}f.current&&clearTimeout(f.current),f.current=setTimeout(async()=>{u(!0);let w=await V.searchPlaces(g,{componentRestrictions:P?{country:P.toLowerCase()}:void 0});a(w),u(!1)},300)},[m,i,C]),d=(0,L.useCallback)(g=>V.getPlaceDetails(g),[]),h=(0,L.useCallback)(g=>V.extractAddressComponents(g),[]),v=(0,L.useCallback)(g=>V.extractFormattedAddress(g),[]),O=(0,L.useCallback)(()=>a([]),[]);return{predictions:o,isLoading:c,isScriptLoaded:m,searchPlaces:y,getPlaceDetails:d,extractAddressComponents:h,extractFormattedAddress:v,clearPredictions:O}}var Q=N("react");var Mt="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",Qe=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],pe=new Map,Le=new Map,ze=new Map,Je=new Map;async function Rn(s){let e=pe.get(s);if(e)return e;let t=ze.get(s);return t||(t=(async()=>{let n=`${Mt}/${s}/countries.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return pe.set(s,i),ze.delete(s),i})(),ze.set(s,t),t)}async function On(s){let e=Le.get(s);if(e)return e;let t=Je.get(s);return t||(t=(async()=>{let n=`${Mt}/${s}/regions.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return Le.set(s,i),Je.delete(s),i})(),Je.set(s,t),t)}function xn(s){return pe.get(s)||pe.get("en")||{}}function An(s){return Le.get(s)||Le.get("en")||{}}async function me(s="en"){await Promise.all([Rn(s),On(s)])}var Ue=(s="en")=>{let e=xn(s);return Object.entries(e).map(([t,n])=>({code:t,name:n.n,iso3:n.i3,numeric:n.nu})).sort((t,n)=>t.name.localeCompare(n.name))},Ye=(s,e="en")=>{let n=An(e)[s];return n?n.map(([r,i])=>({code:r,name:i,countryCode:s})).sort((r,i)=>r.name.localeCompare(i.name)):[]};function ge(s){return pe.has(s)}var z=class s{static ensureLoaded(e="en"){return me(e)}static getCountries(e="en"){let t=Ue(e),n={};for(let r of t)n[r.code]={iso:r.code,iso3:r.iso3??"",numeric:r.numeric??0,name:r.name};return n}static getCountryOptions(e="en"){return Ue(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return Ye(e,t).map(n=>({iso:n.code,name:n.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(n=>({value:n.iso,label:n.name}))}static findRegion(e,t,n="en"){return s.getRegions(e,n).find(r=>r.iso===t)??null}static mapGoogleToISO(e,t,n,r="en"){let i=s.getRegions(n,r);if(i.length===0)return null;let o=i.find(a=>a.iso===e);return o||(o=i.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return ge(e)}static getAvailableLanguages(){return Qe}};function De(s="en"){let[e,t]=(0,Q.useState)(ge(s));return(0,Q.useEffect)(()=>{let n=!1;return me(s).then(()=>{n||t(!0)}).catch(r=>console.error("[headless-sdk] Failed to load geodata:",r)),()=>{n=!0}},[s]),(0,Q.useMemo)(()=>e?{countries:z.getCountries(s),getRegions:n=>z.getRegions(n,s),findRegion:(n,r)=>z.findRegion(n,r,s),mapGoogleToISO:(n,r,i)=>z.mapGoogleToISO(n,r,i,s),isLoaded:!0}:{countries:{},getRegions:()=>[],findRegion:()=>null,mapGoogleToISO:()=>null,isLoaded:!1},[s,e])}function Ht(s="en"){let{countries:e,isLoaded:t}=De(s);return(0,Q.useMemo)(()=>t?Object.values(e).map(n=>({value:n.iso,label:n.name})).sort((n,r)=>n.label.localeCompare(r.label)):[],[e,t])}function Ft(s,e="en"){let{getRegions:t,isLoaded:n}=De(e);return(0,Q.useMemo)(()=>!n||!s?[]:t(s).map(r=>({value:r.iso,label:r.name})).sort((r,i)=>r.label.localeCompare(i.label)),[s,t,n])}var Tn={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},En={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},_n=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),Z=class s{static getSymbol(e){return Tn[e]??e}static getName(e){return En[e]??e}static getDecimalPlaces(e){return _n.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function We(s,e="USD",t="en-US"){let n=Z.getDecimalPlaces(e),r=s/(n===0?100:Math.pow(10,n));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:n,maximumFractionDigits:n}).format(r)}catch{return`${Z.getSymbol(e)}${r.toFixed(n)}`}}return Jt(Nn);})();
6
+ "use strict";var TagadaHeadlessReactBundle=(()=>{var Bt=Object.create;var fe=Object.defineProperty;var zt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Jt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var _=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var Qt=(s,e)=>{for(var t in e)fe(s,t,{get:e[t],enumerable:!0})},Xe=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vt(e))!Yt.call(s,r)&&r!==t&&fe(s,r,{get:()=>e[r],enumerable:!(n=zt(e,r))||n.enumerable});return s};var he=(s,e,t)=>(t=s!=null?Bt(Jt(s)):{},Xe(e||!s||!s.__esModule?fe(t,"default",{value:s,enumerable:!0}):t,s)),Wt=s=>Xe(fe({},"__esModule",{value:!0}),s);var Hn={};Qt(Hn,{CRYPTO_ONCHAIN_PAYMENT_METHOD:()=>je,CurrencyUtils:()=>Z,GoogleAutocompleteCore:()=>z,ISODataCore:()=>V,TagadaHeadlessProvider:()=>It,formatCryptoOnchainCountdown:()=>pt,formatMoney:()=>Ze,isCryptoOnchainMethod:()=>dt,loadGoogleMapsScript:()=>de,parseTokensFromUrl:()=>tt,useCatalog:()=>Nt,useCheckout:()=>bt,useCountryOptions:()=>Gt,useCryptoOnchainPayment:()=>xt,useCustomer:()=>Et,useGoogleAutocomplete:()=>Ft,useHeadlessClient:()=>E,useISOData:()=>Me,useOffers:()=>Tt,useOrder:()=>_t,usePayment:()=>At,useRegionOptions:()=>jt,useRx:()=>Lt,useStep:()=>Dt});var Q=_("react");var q=class extends Error{constructor(e,t,n,r){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=r}},ye=class extends q{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},Pe=class extends q{constructor(e,t=[],n,r){super(e,"validation_error",422,{errors:t,...r}),this.name="TagadaValidationError",this.errors=t,this.appCode=n}},ee=class extends q{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},Se=class extends q{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}};var re=class extends q{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var Fe="headless",se="1.21.0";var et={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},ie=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken,this.redirect=e.redirect}static resolveBaseUrl(e,t){return t??et[e]??et.production}async request(e,t={}){var S;let{method:n="GET",body:r,headers:i={},params:o,token:a,signal:c}=t,u=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[h,k]of Object.entries(o))k!==void 0&&y.set(h,String(k));let d=y.toString();d&&(u+=`?${d}`)}let m={"Content-Type":"application/json","X-Tagada-SDK":`headless-sdk/${se}`,...i},l=a??this.apiKey??((S=this.getToken)==null?void 0:S.call(this));l&&(m["x-cms-token"]=l);let f=new AbortController,p=setTimeout(()=>f.abort(),this.timeout);try{let y=await fetch(u,{method:n,headers:m,body:r!=null?JSON.stringify(r):void 0,signal:c??f.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(p),y.ok){let d=await y.text();return d?JSON.parse(d):{}}throw await this.handleErrorResponse(y,e),new q("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(p),y instanceof q?y:y instanceof DOMException&&y.name==="AbortError"?new re(`Request to ${e} timed out after ${this.timeout}ms.`):new re(y instanceof Error?y.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let n={};try{n=await e.json()}catch{}let r=Zt(n.data),i=n.message||n.error||(typeof r.message=="string"?r.message:void 0)||(typeof n.data=="string"&&Object.keys(r).length===0?n.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof r.code=="string"?r.code:void 0;switch(e.status){case 401:case 403:throw new ye(i);case 404:throw new ee(t,"");case 422:{let a=Array.isArray(n.errors)?n.errors:[];throw new Pe(i,a,o,n)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new Se(a)}default:throw new q(i,"api_error",e.status,n)}}};function Zt(s){if(s&&typeof s=="object")return s;if(typeof s!="string")return{};try{let e=JSON.parse(s);return e&&typeof e=="object"?e:{}}catch{return{}}}var oe=class s{constructor(e,t,n,r){this.http=e;this.storeId=t;this.onTokenChange=n;this.onSession=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,n){var a,c;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.call(this,t));let r={skipAsyncWait:"false"};n!=null&&n.currency&&(r.currency=n.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:r,token:this.sessionToken}),o=this.normalizeSession(i);this._currentSession=o;try{(c=this.onSession)==null||c.call(this,o)}catch{}return o}async createSession(e){var c,u,m;let t=e.items.map(l=>({variantId:l.variantId,priceId:l.priceId,...l.sellingPlanId!==void 0?{sellingPlanId:l.sellingPlanId}:{},...l.trialDays!==void 0?{trialDays:l.trialDays}:{},...l.trialPrice!==void 0?{trialPrice:l.trialPrice}:{},quantity:l.quantity})),n={storeId:this.storeId,lineItems:t};e.returnUrl&&(n.returnUrl=e.returnUrl),e.funnelSessionId&&(n.funnelSessionId=e.funnelSessionId),(c=e.discountCodes)!=null&&c.length&&(n.discountCodes=e.discountCodes),e.metadata&&Object.keys(e.metadata).length>0&&(n.metadata=e.metadata),e.customerMetadata&&Object.keys(e.customerMetadata).length>0&&(n.customerMetadata=e.customerMetadata),(u=e.customerTags)!=null&&u.length&&(n.customerTags=e.customerTags);let r={};e.currency&&(r.currency=e.currency),e.customerEmail&&(r.email=e.customerEmail,r.firstName=e.customerFirstName,r.lastName=e.customerLastName),Object.keys(r).length>0&&(n.customer=r);let i=await this.http.post("/api/v1/checkout/session/init",n),a=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((m=this.onTokenChange)==null||m.call(this,a)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:a,customerId:i.customerId}}async createSessionUrl(e){let{checkoutPath:t="/checkout",origin:n,...r}=e,i=await this.createSession(r),o=n??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:i.checkoutToken,sessionToken:i.sessionToken}),c=`${o}${t}?${a.toString()}`;return{...i,url:c}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("checkoutToken");if(!r)return null;let i=n.searchParams.get("sessionToken")??n.searchParams.get("token")??"";return{checkoutToken:r,sessionToken:i}}parseTokensFromUrl(e){return s.parseTokensFromUrl(e)}async updateCart(e,t){let n=t.map(r=>({variantId:r.variantId,priceId:r.priceId,...r.sellingPlanId!==void 0?{sellingPlanId:r.sellingPlanId}:{},quantity:r.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:n},{token:this.sessionToken})}async updateCustomer(e,t){t.email&&(this.customerEmail=t.email),t.firstName&&(this.customerFirstName=t.firstName),t.lastName&&(this.customerLastName=t.lastName),t.phone&&(this.customerPhone=t.phone)}async updateAddress(e,t){let n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),i=n??r??{},o=r??n,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}async updateCustomerAndAddress(e,t){t.customer.email&&(this.customerEmail=t.customer.email),t.customer.firstName&&(this.customerFirstName=t.customer.firstName),t.customer.lastName&&(this.customerLastName=t.customer.lastName),t.customer.phone&&(this.customerPhone=t.customer.phone);let n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),i=n??r??{},o=r??n,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return Xt({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let n=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${n}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(n=>this.normalizeShippingRate(n))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){var m;let t=e.checkoutSession,n=t.orderSummaries??[],r=e.summary??t.summary??n[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(m=r.currency??t.selectedPresentmentCurrency)==null?void 0:m.toUpperCase(),c=i.map(l=>{let f=l.price,p=l.variant??(f==null?void 0:f.variant)??{},S=l.product??p.product??{},y=(f==null?void 0:f.currencyOptions)??{},d=(a?y[a]:void 0)??y[Object.keys(y)[0]],h=(d==null?void 0:d.amount)??0;return{id:l.id,variantId:l.variantId,priceId:l.priceId,productName:S.name??"",variantName:p.name??"",quantity:l.quantity??1,unitAmount:h,totalAmount:h*(l.quantity??1),currency:a??"USD",imageUrl:p.imageUrl??S.imageUrl??"",...f!=null&&f.recurring?{recurring:{interval:f.interval??"month",intervalCount:f.intervalCount??1}}:{}}}),u=r.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:c,totals:{subtotal:r.subtotalAmount??0,discount:r.totalPromotionAmount??0,shipping:r.shippingCost??0,tax:r.totalTaxAmount??0,total:r.totalAdjustedAmount??r.totalAmount??u.reduce((l,f)=>l+(f.amount??0),0),currency:a??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName,phone:o.phone}:void 0,shippingAddress:this.normalizeAddress(t.shippingAddress),billingAddress:this.normalizeAddress(t.billingAddress),selectedShippingRateId:t.shippingRateId??null,metadata:t.metadata,...typeof t.draft=="boolean"?{draft:t.draft}:{}}}normalizeAddress(e){if(!e||typeof e!="object")return;let t=e,n={firstName:t.firstName,lastName:t.lastName,line1:t.line1??t.address1,line2:t.line2??t.address2,city:t.city,state:t.state,postalCode:t.postalCode??t.postal,country:t.country,phone:t.phone};return Object.values(n).some(r=>r!==void 0&&r!=="")?n:void 0}},tt=oe.parseTokensFromUrl;function Xt(s){let e={};for(let[t,n]of Object.entries(s))n!=null&&n!==""&&(e[t]=n);return Object.keys(e).length>0?e:void 0}function Ce(s){var t,n;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(n=s.addressLines)==null?void 0:n[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return nt(e)?e:void 0}function we(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),n={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:s.address1,line2:[s.address2,s.address3].filter(Boolean).join(" ")||void 0,city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return nt(n)?n:void 0}function nt(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var rt="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.21.0/dist/tagada-pixels.min.js";function ct(s,e){return e()?Promise.resolve():new Promise((t,n)=>{let r=document.createElement("script");r.src=s,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error("runtime script failed to load")),document.head.appendChild(r)})}async function en(){if(typeof window>"u")return null;if(rt){let s=window;return s.TagadaPixels?s.TagadaPixels:(await ct(rt,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var st="__tgd_track",tn="__tgd_aid",nn="__tgd_sid",it=50,rn=2e3,ot=1e3,sn=64;function Ie(s){if(!(!Array.isArray(s)||s.length===0))return s.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function at(s){if(!s)return;let e={};for(let[t,n]of Object.entries(s))(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(e[t]=n);return Object.keys(e).length>0?e:void 0}var on={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function qe(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function an(s){let e={};for(let t of s){let{provider:n,id:r,idKey:i,...o}=t;(e[n]??(e[n]=[])).push({...o,enabled:!0,[i]:r,events:t.events??{}})}return e}var ke=class{constructor(e,t,n){this.baseUrl=e;this.storeId=t;this.funnelKey=n;this.records=[];this.lastStep=new Map;this.signals=[];this.currentStepId=null;this.manifestHash=null;this.loadedProviders=[];this.configPromise=null;this.corePromise=null;this.enginePromise=null;this.flushTimer=null;this.listening=!1}flag(){try{return(localStorage.getItem(st)??"").split(":")}catch{return[]}}enabled(){return this.flag()[0]===this.storeId}flagFunnelKey(){return this.flag()[1]||this.funnelKey}off(){return typeof window>"u"||!this.enabled()}arm(){try{localStorage.setItem(st,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let n=(t==null?void 0:t.path)??window.location.pathname,r=`${e}|${n}`,i=Date.now(),o=this.lastStep.get(r);o!==void 0&&i-o<ot||(this.remember(r,i),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:i,path:n}),this.pixels().then(a=>a==null?void 0:a.pageView(n,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let n=this.currentStepId;if(n===null)return;let r=on[e],i=`${r??e}_${qe()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:i,props:at(t)}),this.pixels().then(o=>r?o==null?void 0:o.track(r,t,{stepId:n,eventId:i}):o==null?void 0:o.trackCustom(e,t,{stepId:n})),this.core().then(o=>o==null?void 0:o.track(e,{...at(t)??{},step_id:n,pixel_event_id:i})).catch(()=>{})}remember(e,t){for(let[n,r]of this.lastStep)t-r>=ot&&this.lastStep.delete(n);for(;this.lastStep.size>=sn;){let n=this.lastStep.keys().next();if(n.done===!0)break;this.lastStep.delete(n.value)}this.lastStep.set(e,t)}identify(e){this.off()||(this.pixels().then(t=>t==null?void 0:t.identify({email:e.email,phone:e.phone,externalId:e.customerId})),this.core().then(t=>t==null?void 0:t.identify(e.customerId??null,{email:e.email,phone:e.phone,customerId:e.customerId})).catch(()=>{}))}consent(e){this.off()||this.pixels().then(t=>t==null?void 0:t.consent(e))}async health(){return typeof window>"u"?this.snapshot():(this.enabled()&&await this.config(),this.snapshot())}noteCheckout(e){this.notePixel("InitiateCheckout",e.checkoutSessionId,e)}notePaid(e){this.notePixel("Purchase",e.orderId,e)}notePixel(e,t,n){this.off()||this.pixels().then(r=>{var i;return r==null?void 0:r.track(e,{value:n.amount,currency:n.currency,contents:n.items,num_items:(i=n.items)==null?void 0:i.length},{eventId:`${e}_${t}`})})}noteSignal(e,t,n){this.off()||(this.signals.push({signal:e,value:t,detail:n}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:n}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:Fe,version:se},manifestHash:this.manifestHash,pixels:{loaded:this.loadedProviders.length>0,providers:[...this.loadedProviders]},signals:[...this.signals]}}config(){if(this.configPromise!==null)return this.configPromise;let e=`${this.baseUrl}/api/public/v1/sdk/config?storeId=${encodeURIComponent(this.storeId)}&funnel=${encodeURIComponent(this.flagFunnelKey())}`;return this.configPromise=(async()=>{try{let t=await fetch(e);if(!t.ok)return null;let n=await t.json();return this.manifestHash=n.manifestHash||null,n}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let n=await this.config();if(!n||!n.collect&&!n.experiments)return null;let r=this.baseUrl.replace(/\/+$/,""),i=window;return typeof((e=i.tgd)==null?void 0:e.init)!="function"&&await ct(r+"/assets/js/tgd.js",()=>{var o;return typeof((o=i.tgd)==null?void 0:o.init)=="function"}),typeof((t=i.tgd)==null?void 0:t.init)!="function"?null:(i.tgd.init({storeId:this.storeId,apiHost:n.collect?new URL(n.collect.url).origin:r,bootstrap:this.bootstrap,_source:"headless",_manualPages:!0}),i.tgd)}catch{return null}})()),this.corePromise)}noteFunnelSession(e){this.off()||this.core().then(t=>t==null?void 0:t._link(e)).catch(()=>{})}pixels(){return this.enabled()?(this.enginePromise??(this.enginePromise=this.startEngine()),this.enginePromise):Promise.resolve(null)}async startEngine(){var e;try{let t=await this.config();if(t===null)return null;let n=await en();if(n===null)return null;let r=n.createPixelEngine({pixels:an(t.pixels??[]),steps:t.steps,checkout:t.checkout,requireConsent:((e=t.consent)==null?void 0:e.required)===!0,onSignal:i=>this.onPixelSignal(i)});return await r.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(i=>i.provider))],r}catch{return null}}onPixelSignal(e){let t=e.detail??{};this.signals.push({signal:e.kind,value:e.provider,detail:t}),this.push({kind:"signal",signal:e.kind,value:e.provider,detail:t})}listen(){if(this.listening||typeof window>"u")return;this.listening=!0;let e=t=>{t.type==="visibilitychange"&&document.visibilityState!=="hidden"||this.flush()};window.addEventListener("pagehide",e),window.addEventListener("visibilitychange",e)}push(e){if(this.enabled()){if(this.records.push(e),this.records.length>=it){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),rn))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let i=qe();return n.setItem(t,i),i}catch{return qe()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,it),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:Fe,version:se},anonymousId:this.identifier("local",tn),sessionId:this.identifier("session",nn),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let n=JSON.stringify(t),r=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(r,new Blob([n],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(r,{method:"POST",body:n,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var je="crypto_onchain";var ve=["paid","underpaid","failed","expired"];function dt(s){return s?s.trim().toLowerCase().replace(/-/g,"_").split(":")[0]===je:!1}function cn(s){let e=s.filter(r=>r.assets.length>0),t=e.find(r=>!r.testnet)??e[0];if(!t)return null;let n=t.assets.find(r=>r.stable)??t.assets[0];return{chainId:t.chainId,asset:n.symbol}}function un(s,e,t){var o,a;let n=((o=s.find(c=>c.chainId===e))==null?void 0:o.assets)??[],r=n.find(c=>c.symbol===t),i=n.find(c=>c.stable)??n[0];return{chainId:e,asset:((a=r??i)==null?void 0:a.symbol)??t}}function ln(s){if(!s)return"waiting";if(s.paid)return"paid";switch(s.status){case"detected":case"overpaid":return"confirming";case"underpaid":return"underpaid";case"failed":return"failed";case"expired":return"expired";default:return s.expired?"expired":"waiting"}}function ut(s,e){if(!s)return 0;let t=Date.parse(s);return Number.isNaN(t)?0:Math.max(0,Math.floor((t-e)/1e3))}function pt(s){let e=Math.max(0,Math.floor(s)),t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=String(e%60).padStart(2,"0");return t>0?`${t}:${String(n).padStart(2,"0")}:${r}`:`${n}:${r}`}var Ge="Crypto payments are not available right now. Choose another payment method.",be=class{constructor(e,t){this.api=e;this.options=t;this.state={options:"idle",networks:[],selection:null,payment:null,paymentStatus:null,isCreating:!1,error:null};this.listeners=new Set;this.pollTimer=null;this.stopped=!1;this.paidNotified=!1;this.subscribe=this.subscribe.bind(this),this.getState=this.getState.bind(this)}getState(){return this.state}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getPhase(e=Date.now()){let{payment:t,paymentStatus:n}=this.state,r=ln(n??(t?{status:t.status,paid:!1,expired:!1}:null));return t!==null&&r==="waiting"&&ut(t.expiresAt,e)===0?"expired":r}getSecondsLeft(e=Date.now()){var t;return ut(((t=this.state.payment)==null?void 0:t.expiresAt)??null,e)}async loadOptions(){this.setState({options:"loading",error:null});try{let e=await this.api.getCryptoOnchainOptions(this.options.checkoutSessionId);if(!e.ok)return this.setState({options:"unavailable",networks:[],selection:null,error:e.message||Ge}),this.state;let t=this.state.selection??cn(e.networks);this.setState(t?{options:"ready",networks:e.networks,selection:t}:{options:"unavailable",networks:e.networks,selection:null,error:Ge})}catch(e){this.setState({options:"unavailable",error:lt(e)})}return this.state}select(e){let t=this.state.selection;if(e.chainId!==void 0&&e.chainId!==(t==null?void 0:t.chainId)){this.setState({selection:un(this.state.networks,e.chainId,e.asset??(t==null?void 0:t.asset)??"")});return}e.asset!==void 0&&t&&this.setState({selection:{...t,asset:e.asset}})}async pay(e){let t=e??this.state.selection;if(!t)return{ok:!1,code:"ASSET_NOT_AVAILABLE",message:"Choose a network and a coin"};if(this.state.isCreating)return{ok:!1,code:"CHECKOUT_FAILED",message:"A payment is already being created"};this.setState({isCreating:!0,error:null,selection:t});try{let n=await this.api.createCryptoOnchainPayment({checkoutSessionId:this.options.checkoutSessionId,chainId:t.chainId,asset:t.asset});return n.ok?(this.stopped=!1,this.setState({isCreating:!1,payment:n.payment,paymentStatus:null}),this.schedulePoll(),n):(this.setState({isCreating:!1,error:n.message}),n)}catch(n){let r=lt(n);return this.setState({isCreating:!1,error:r}),{ok:!1,code:"CHECKOUT_FAILED",message:r}}}async refreshStatus(){var t,n,r;let e=this.state.payment;if(!e)return null;try{let i=await this.api.getCryptoOnchainStatus({checkoutSessionId:this.options.checkoutSessionId,cryptoOnchainPaymentId:e.cryptoOnchainPaymentId});if(!i.ok||((t=this.state.payment)==null?void 0:t.cryptoOnchainPaymentId)!==e.cryptoOnchainPaymentId)return null;let o={status:i.status,paymentId:i.paymentId,orderId:i.orderId,confirmations:i.confirmations,requiredConfirmations:i.requiredConfirmations,txHash:i.txHash,explorerTxUrl:i.explorerTxUrl,paid:i.paid,expired:i.expired,redirectUrl:i.redirectUrl};return this.setState({paymentStatus:o}),o.paid&&!this.paidNotified&&(this.paidNotified=!0,(r=(n=this.options).onPaid)==null||r.call(n,o)),o}catch{return null}}resume(){!this.state.payment||ve.includes(this.getPhase())||(this.stopped=!1,this.schedulePoll())}stop(){this.stopped=!0,this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=null}schedulePoll(){this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.refreshStatus(),!this.stopped&&!ve.includes(this.getPhase())&&this.schedulePoll()},this.options.pollIntervalMs??5e3)}setState(e){var t,n;this.state={...this.state,...e},(n=(t=this.options).onChange)==null||n.call(t,this.state),this.listeners.forEach(r=>r(this.state))}};function lt(s){return s instanceof Error&&s.message?s.message:Ge}function $e(s){if(!s||typeof s!="object"||Array.isArray(s))return null;let{payment:e,order:t,paymentId:n,clientSecret:r,amount:i,currency:o,checkoutSessionId:a}=s;return e!==void 0||t!==void 0||typeof n!="string"||!n||typeof r!="string"||!r?null:{paymentId:n,clientSecret:r,...typeof i=="number"?{amount:i}:{},...typeof o=="string"?{currency:o}:{},...typeof a=="string"?{checkoutSessionId:a}:{}}}var mt="tgd_payments_api_return",dn=60*6e4;function gt(s){try{let e=sessionStorage.getItem(mt);if(!e)return null;let t=JSON.parse(e);return t.paymentId!==s||(sessionStorage.removeItem(mt),!t.checkoutSessionId||!t.at||Date.now()-t.at>dn)?null:{checkoutSessionId:t.checkoutSessionId}}catch{return null}}var pn="https://secure.oceanpayment.com/pages/js/oceanpayment.js",Be="oceanpayment-element";var mn={fi:"en"};function ft(s){var t;let e=(t=s==null?void 0:s.split(/[-_]/)[0])==null?void 0:t.toLowerCase();return e?mn[e]??e:"en"}var gn=3e4,ae=null;function ht(){let s=window;return s.Oceanpayment?Promise.resolve(s.Oceanpayment):ae||(ae=new Promise((e,t)=>{let n=document.createElement("script"),r=o=>{clearTimeout(i),n.remove(),ae=null,t(new Error(o))},i=setTimeout(()=>r("The Ocean Payment card form took too long to load"),gn);n.addEventListener("load",()=>{if(!s.Oceanpayment)return r("Ocean Payment script loaded without window.Oceanpayment");clearTimeout(i),e(s.Oceanpayment)}),n.addEventListener("error",()=>r("Failed to load the Ocean Payment card form")),n.src=pn,document.head.appendChild(n)}),ae)}var Ke="tgd:headless:oceanpayment:pending",fn=30*60*1e3;function yt(s){try{sessionStorage.setItem(Ke,JSON.stringify({paymentId:s,at:Date.now()}))}catch{}}function hn(){try{let s=sessionStorage.getItem(Ke);if(!s)return;sessionStorage.removeItem(Ke);let{paymentId:e,at:t}=JSON.parse(s);return!e||!t||Date.now()-t>fn?void 0:e}catch{return}}function Re(){if(typeof window>"u")return;let s=hn();if(s)try{let e=new URL(window.location.href);if(e.searchParams.get("paymentId"))return;e.searchParams.set("paymentId",s),e.searchParams.set("paymentAction","requireAction"),e.searchParams.set("paymentActionStatus","completed"),window.history.replaceState(window.history.state,"",e.toString())}catch{}}function Pn(){return Promise.reject(new Error("This store takes payments through the Payments API, which the CDN build does not support yet: install @tagadapay/headless-sdk and @tagadapay/core-js 3.7.0 or later from npm."))}var Pt=new Set(["failed","declined","rejected","error"]),te=null,Sn=()=>!!te&&(!te.attached||te.element.isConnected),St=Symbol("ocean-timed-out"),Ct=Symbol("ocean-unmounted"),Cn=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function wn(s){var o;let e=s.type==="credit-card",t=e?"card":s.type,n=s.settings??{},r=n.processors,i=n.publishableKey;return{enabled:!0,method:t,provider:e?void 0:s.type,type:e?"card":s.type,label:s.title,logoUrl:s.iconUrl,express:Cn.has(t),integrationId:e?void 0:s.id,processorId:(o=r==null?void 0:r[0])==null?void 0:o.processorId,publishableKey:typeof i=="string"?i:void 0,metadata:s.metadata??void 0}}function kn(){if(typeof window>"u")return Promise.reject(new Error("Stripe Radar needs a browser"));let s=()=>window.Stripe,e=s();return e?Promise.resolve(e):new Promise((t,n)=>{let r=document.createElement("script");r.src="https://js.stripe.com/v3/",r.async=!0,r.onload=()=>{let i=s();i?t(i):n(new Error("Stripe.js loaded without window.Stripe"))},r.onerror=()=>n(new Error("Failed to load Stripe.js")),document.head.appendChild(r)})}var Ae=class{constructor(e,t,n,r,i,o){this.http=e;this.storeId=t;this.environment=n;this.checkout=r;this.onPaid=i;this.onSignal=o;this.lastPaymentSetup=null;this.paymentsApiStarts=new Map}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return this.lastPaymentSetup=t.paymentSetupConfig,t.paymentSetupConfig;let n=this.readInjectedStepConfig();if(n)return this.lastPaymentSetup=n,n;try{let i=await this.http.get(`/api/v1/checkout-sessions/${e}/payment-setup`),o={...(i==null?void 0:i.config)??{}};return this.lastPaymentSetup=o,o}catch(i){if(!(i instanceof ee))throw i}let r=await this.getPaymentSetupFromPickerList(e);return this.lastPaymentSetup=r,r}async getPaymentSetupFromPickerList(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),n=Array.isArray(t)?t.map(wn):(t==null?void 0:t.methods)??[],r={};for(let i of n){let o=i.provider&&i.provider!==i.method?`${i.method}:${i.provider}`:i.method;r[o]=i}return r}async getExpressMethods(e,t){var i,o,a,c,u,m,l,f,p,S;let n=await this.getPaymentSetup(e,t),r={};for(let[y,d]of Object.entries(n)){if(!d.enabled)continue;if(y.startsWith("express_checkout:")&&d.methods){let A={available:!0,processorId:d.processorId,publishableKey:d.publishableKey,metadata:d.metadata};if((i=d.methods.apple_pay)!=null&&i.enabled){let g=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));r.applePay={...A,type:"apple_pay",available:!!g}}(c=d.methods.google_pay)!=null&&c.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((u=this.onSignal)==null||u.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay={...A,type:"google_pay"}),(m=d.methods.link)!=null&&m.enabled&&(r.link={...A,type:"link"}),(l=d.methods.klarna_express)!=null&&l.enabled&&(r.klarna={...A,type:"klarna_express"});continue}if(!d.express)continue;let h=d.method,k={type:h,available:!0,processorId:d.processorId,publishableKey:d.publishableKey,metadata:d.metadata};if(h==="apple_pay"||d.type==="apple_pay"){let A=typeof window<"u"&&"ApplePaySession"in window&&((p=(f=window.ApplePaySession)==null?void 0:f.canMakePayments)==null?void 0:p.call(f));r.applePay={...k,available:!!A}}else h==="google_pay"||d.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((S=this.onSignal)==null||S.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay=k):h==="paypal"?r.paypal=k:h==="klarna"||h==="klarna_express"?r.klarna=k:h==="link"&&(r.link=k)}return r}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e,t){let n=await this.getPaymentSetup(e,t);return Object.entries(n).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(r.cardholderName=e.cardholderName);let i=await n.tokenizeCardRaw(r);return{tagadaToken:t.createTagadaToken(i,n.getProvider().getProviderName()),rawToken:i}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.rememberPaymentsApiStart(await this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,returnUrl:e.returnUrl,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}),e):this.rememberPaymentsApiStart(await this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata,returnUrl:e.returnUrl}),e)}async payDirect(e){return this.rememberPaymentsApiStart(await this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId,returnUrl:e.returnUrl}),e)}async syncWalletContact(e,t){let{shippingAddress:n,billingAddress:r}=t;if(!n&&!r)return;if(!this.checkout)throw new Error("PaymentModule cannot persist the wallet contact: no CheckoutModule was provided. Build the SDK through createTagadaClient() rather than constructing PaymentModule directly.");let i={};t.email&&(i.email=t.email),t.phone&&(i.phone=t.phone),t.firstName&&(i.firstName=t.firstName),t.lastName&&(i.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:i,shippingAddress:n,billingAddress:r})}async processApplePay(e){var a,c,u,m,l,f,p,S,y;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:Ce(e.shippingContact),billingAddress:Ce(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((c=e.billingContact)==null?void 0:c.emailAddress),phone:((u=e.shippingContact)==null?void 0:u.phoneNumber)??((m=e.billingContact)==null?void 0:m.phoneNumber),firstName:((l=e.shippingContact)==null?void 0:l.givenName)??((f=e.billingContact)==null?void 0:f.givenName),lastName:((p=e.shippingContact)==null?void 0:p.familyName)??((S=e.billingContact)==null?void 0:S.familyName)});let t=e.merchantRegistrationId??((y=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:y.merchantRegistrationId),n=await this.loadCoreJs(),r=new n.Tokenizer({environment:this.environment});await r.initialize();let i=await r.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(n.createTagadaDigitalWalletToken(i,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:o,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async resolveApplePayRegistration(e){if(typeof window>"u")return null;let t=window.location.hostname.toLowerCase().split(":")[0];t.startsWith("www.")&&(t=t.slice(4));let n=i=>{var o;for(let a of Object.values(i??{})){let c=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!c||typeof c!="object")continue;let u=c[t];if(u!=null&&u.merchantRegistrationId)return{merchantRegistrationId:u.merchantRegistrationId,displayName:u.displayName}}return null},r=n(this.readInjectedStepConfig())??n(this.lastPaymentSetup);if(r)return r;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return n(await this.getPaymentSetup(e))}catch{return null}}async processGooglePay(e){var o,a,c,u;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:we(e.shippingAddress),billingAddress:we(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.emailAddress),phone:((c=e.shippingAddress)==null?void 0:c.phoneNumber)??((u=e.billingAddress)==null?void 0:u.phoneNumber)});let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r=await n.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(r,"google_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:i,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async processStripeExpress(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:!0})}async getCryptoOnchainOptions(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e)}/crypto-onchain/options`)}async createCryptoOnchainPayment(e){return this.http.post(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/session`,{chainId:e.chainId,asset:e.asset})}async getCryptoOnchainStatus(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/status`,{params:{cryptoOnchainPaymentId:e.cryptoOnchainPaymentId}})}createCryptoOnchainCheckout(e){return new be(this,e)}async getOceanPaymentConfig(e){let t=await this.http.post(`/api/v1/checkout-sessions/${e}/oceanpayment-embedded-config`,{});return{embedded:!!(t!=null&&t.embedded),sandboxed:!!(t!=null&&t.sandboxed)}}async mountOceanPayment(e){if(typeof window>"u")throw new Error("Ocean Payment needs a browser");let{checkoutSessionId:t,signal:n}=e,r=()=>Object.assign(new Error("Ocean Payment mount aborted"),{name:"AbortError"});if(n!=null&&n.aborted)throw r();let i=typeof e.container=="string"?document.querySelector(e.container):e.container;if(!i&&e.mode!=="redirect")throw new Error(`Ocean Payment container not found: ${String(e.container)}`);if(Sn()||document.getElementById(Be))throw new Error("An Ocean Payment card form is already mounted on this page");let o=window,a=document.createElement("div");a.id=Be;let c={element:a,attached:!1};te=c;let u=()=>{te===c&&(te=null)},m=!0,l=null,f=g=>{let P=l;l=null,P==null||P(g)},p=()=>{m&&(m=!1,o.oceanpaymentCallBack===f&&delete o.oceanpaymentCallBack,a.remove(),u(),f(Ct))};n==null||n.addEventListener("abort",p,{once:!0});let S,y;try{if(S=e.mode==="redirect"?{embedded:!1,sandboxed:!1}:await this.getOceanPaymentConfig(t),n!=null&&n.aborted||S.embedded&&(y=await ht(),n!=null&&n.aborted))throw r()}catch(g){throw p(),g}let d=!1;if(!y)return u(),{mode:"redirect",pay:async()=>{if(!m)return{status:"failed",error:"The Ocean Payment form was removed"};if(d)return{status:"failed",error:"Payment already in progress"};d=!0;try{let g=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-link`,{returnUrl:e.returnUrl??window.location.href});return!(g!=null&&g.url)||!g.paymentId?{status:"failed",error:"Ocean Payment is not available for this store"}:{status:"requires_redirect",redirectUrl:g.url,method:"GET",paymentId:g.paymentId}}catch(g){return{status:"failed",error:g instanceof Error?g.message:String(g)}}finally{d=!1}},unmount:p};let h=y;i.appendChild(a),c.attached=!0,o.oceanpaymentCallBack=f;let k=window.location.href;return h.init(S.sandboxed,"",ft(e.locale),{showCardName:!1}),{mode:"embedded",pay:async()=>{if(!m)return{status:"failed",error:"The Ocean Payment card form was removed"};if(d)return{status:"failed",error:"Payment already in progress"};d=!0;try{let g=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-payment`,{backUrl:k});if(!(g!=null&&g.paymentId)||!g.params)return{status:"failed",error:"Failed to start the payment"};let P=g.paymentId,w=await new Promise(j=>{let $=setTimeout(()=>{l=null,j(St)},12e4);l=R=>{clearTimeout($),j(R)},h.checkout(g.params)});if(w===St||w===Ct)return this.pollUntilDone(P);if(w&&typeof w=="object"&&"msg"in w)return{status:"failed",error:String(w.msg||"Please check your card details.")};let v=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-result`,{paymentId:P,response:String(w)});return(v==null?void 0:v.status)==="requires_action"&&v.payUrl?(yt(P),{status:"requires_redirect",redirectUrl:v.payUrl,method:"GET",paymentId:P}):(v==null?void 0:v.status)==="succeeded"||(v==null?void 0:v.status)==="pending"?this.pollUntilDone(P):{status:"failed",error:(v==null?void 0:v.message)||"Payment declined"}}catch(g){return{status:"failed",error:g instanceof Error?g.message:String(g)}}finally{d=!1}},unmount:p}}async processPayment(e){!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e);return this.finalize(t,{returnUrl:e.returnUrl})}async finalize(e,t){var i,o,a;let n=e.payment,r=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);if(!n){let c=$e(e);if(c)return this.finalizeOnPaymentsApi(c,r)}return n.status==="succeeded"?(this.emitPaid((i=e.order)==null?void 0:i.id,n),{status:"succeeded",payment:n,order:e.order}):n.status==="failed"||n.status==="declined"?{status:"failed",error:((o=n.requireActionData)==null?void 0:o.message)||((a=n.requireActionData)==null?void 0:a.errorCode)||`Payment ${n.status}`,payment:n}:n.requireAction&&n.requireAction!=="none"&&n.requireActionData?this.handlePaymentAction(n,{returnUrl:r}):this.pollUntilDone(n.id)}async resumeAfterRedirect(e){let t=gt(e);if(t){let n=typeof window<"u"?window.location.href:void 0;return this.onPaymentsApi((r,i)=>r.resumeOnPaymentsApi(i,e,t.checkoutSessionId,n))}return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;e!=null&&e.url||Re();let t=(e==null?void 0:e.url)??window.location.href,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("paymentAction"),i=n.searchParams.get("paymentActionStatus"),o=n.searchParams.get("paymentId");if(r!=="requireAction"||i!=="completed"||!o)return null;let a=await this.resumeAfterRedirect(o);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let c=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(m=>c.delete(m));let u=c.toString();try{window.history.replaceState({},document.title,window.location.pathname+(u?"?"+u:""))}catch{}}return a}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<r;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||Pt.has(o.status))return o;await new Promise(a=>setTimeout(a,n))}throw new Error(`Payment ${e} did not reach terminal status within ${r}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async markActionProcessed(e){try{await this.http.post("/api/v1/payments/require-action/processed",{paymentId:e})}catch{}}async handlePaymentAction(e,t){let n=e.requireActionData;switch(await this.markActionProcessed(e.id),n.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,n);case"redirect":return this.extractRedirect(e,n);case"stripe_radar":return this.handleStripeRadar(e);case"error":return{status:"failed",error:n.message||n.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,n)}}extractRedirect(e,t){var i,o;let n=(i=t.metadata)==null?void 0:i.redirect,r=(n==null?void 0:n.redirectUrl)||t.redirectUrl;return r?{status:"requires_redirect",redirectUrl:r,method:((o=n==null?void 0:n.method)==null?void 0:o.toUpperCase())||"GET",postData:n==null?void 0:n.data,paymentId:e.id}:{status:"failed",error:`Payment requires action (${t.type}) but no redirect URL was provided`,payment:e}}async handleThreedsAuth(e,t){var i,o;let n=(o=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:o.threedsSession;if(!(n!=null&&n.externalSessionId))return this.extractRedirect(e,e.requireActionData);let r;try{r=await import("@tagadapay/core-js")}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new r.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:n.externalSessionId,acsChallengeUrl:n.acsChallengeUrl,acsTransactionId:n.acsTransID,threeDSVersion:n.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async handleStripeRadar(e){var n,r;let t=(r=(n=e.requireActionData)==null?void 0:n.metadata)==null?void 0:r.radar;if(!(t!=null&&t.publishableKey))return{status:"failed",error:"Stripe Radar configuration missing",payment:e};try{let i=await kn(),{radarSession:o,error:a}=await i(t.publishableKey).createRadarSession();if(a||!o)throw new Error((a==null?void 0:a.message)||"No Radar session returned by Stripe");return await this.http.post("/api/v1/radar-sessions",{orderId:t.orderId,paymentId:e.id,stripeRadarSessionId:o.id,stripeRadarSessionData:o}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch(i){return{status:"failed",error:i instanceof Error?i.message:"Stripe Radar failed",payment:e}}}async pollUntilDone(e,t){var a;let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<r;){let c;try{c=await this.getPaymentStatus(e),o=0}catch{if(o++,o>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(u=>setTimeout(u,n));continue}if(c.status==="succeeded"||c.status==="pending"&&c.subStatus==="authorized")return c.status==="succeeded"&&this.emitPaid((a=c.order)==null?void 0:a.id,c),{status:"succeeded",payment:c,order:c.order};if(Pt.has(c.status))return{status:"failed",error:c.status,payment:c};if(c.requireAction&&c.requireAction!=="none"&&c.requireActionData&&!c.requireActionData.processed)return this.handlePaymentAction(c,{});await new Promise(u=>setTimeout(u,n))}return{status:"pending",paymentId:e}}rememberPaymentsApiStart(e,t){let n=e&&!e.payment?$e(e):null;return n&&this.paymentsApiStarts.set(n.paymentId,{checkoutSessionId:n.checkoutSessionId??t.checkoutSessionId,...t.paymentMethod?{paymentMethod:t.paymentMethod}:{}}),e}finalizeOnPaymentsApi(e,t){let n=this.paymentsApiStarts.get(e.paymentId);return this.paymentsApiStarts.delete(e.paymentId),this.onPaymentsApi((r,i)=>r.finalizeOnPaymentsApi(i,e,{checkoutSessionId:n==null?void 0:n.checkoutSessionId,paymentMethod:n==null?void 0:n.paymentMethod,returnUrl:t}))}async onPaymentsApi(e){let t;try{t=await Pn()}catch(n){return{status:"failed",error:n instanceof Error?n.message:String(n)}}return e(t,{http:this.http,storeId:this.storeId,checkout:this.checkout,stepConfig:this.readInjectedStepConfigRaw(),onPaid:(n,r)=>this.emitPaid(n,r)})}readInjectedStepConfig(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{let t=typeof e=="string"?JSON.parse(e):e;return(t==null?void 0:t.paymentSetupConfig)??null}catch{return null}}readInjectedStepConfigRaw(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{return typeof e=="string"?JSON.parse(e):e}catch{return null}}emitPaid(e,t){var n;if(!(!e||!this.onPaid))try{let r=(n=this.checkout)==null?void 0:n.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:Ie(r==null?void 0:r.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var J=typeof document>"u"?null:document.currentScript,In=J!=null&&J.src?new URL("tagada-headless-commerce.min.js",J.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.21.0/dist/tagada-headless-commerce.min.js",Oe;function ne(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(Oe||(Oe=new Promise((s,e)=>{let t=document.createElement("script");t.src=In,t.async=!0,J!=null&&J.nonce&&(t.nonce=J.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?s(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(s=>{throw Oe=void 0,s})),Oe)}var ce=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ne().then(e=>new e.OffersModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getOffer","listOffers","previewOffer","enterFunnelStep","payPreviewedOffer","processOfferPayment","toggleOrderBump","listPostPurchaseOffers","acceptPostPurchaseOffer","declinePostPurchaseOffer"])ce.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var ue=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ne().then(e=>new e.CustomerModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getProfile","getByEmail","updateProfile","getOrders","getOrder","getSubscriptions","getSubscription","pauseSubscription","resumeSubscription","skipSubscription","rescheduleSubscription","updateSubscriptionQuantity","changeSubscriptionFrequency","swapSubscriptionProduct","updateSubscriptionPaymentMethod","cancelSubscription"])ue.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var le=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ne().then(e=>new e.CustomerPortalModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["requestCode","verifyCode","getConfig","getMe","cancelFlow","acceptCancelOffer","switchOption","getOffer","acceptOffer","addToNextOrder","getCredits","redeemCredits","buyCreditPack","requestEmailChangeCode","updateProfile","saveAddress","removeAddress","setDefaultAddress","addCard","removeCard","setDefaultPaymentMethod","retryPayment","buyAgain","joinMembership","buyNow","sendNow","reactivateSubscription","setSubscriptionCard","setSubscriptionAddress","skipDate","unskipDate"])le.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var xe=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var r,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(r=e==null?void 0:e.productIds)!=null&&r.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var Te=class{constructor(e,t,n,r,i){this.http=e;this.storeId=t;this.checkout=n;this.accountId=r;this.onFunnelSession=i}async navigate(e){var a,c;let t=this.checkout.getCurrentSession();if(!t)throw new q("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let n=e.accountId??this.accountId;if(!n)throw new q("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let r=e.currentUrl??(typeof globalThis<"u"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,n,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:n,currentUrl:r});try{(c=this.onFunnelSession)==null||c.call(this,i)}catch{}return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:r}),funnelSessionId:i}}async ensureCmsSession(e,t,n){var o,a,c;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let r=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=r.token,this._cmsSessionId=r.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((o=n.customer)==null?void 0:o.locale)??vn(),userAgent:bn(),queryCurrency:((a=n.customer)==null?void 0:a.currency)??e.currency,queryLocale:(c=n.customer)==null?void 0:c.locale},{token:this._cmsToken});this._cmsCustomerId=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var l,f,p,S;let{funnelSessionId:t,stepId:n,session:r,input:i,currentUrl:o}=e,a=r.items.map(y=>({variantId:y.variantId,priceId:y.priceId,quantity:y.quantity})),c=i.discountCodes??(r.promotionCode?[r.promotionCode]:void 0),u={email:((l=i.customer)==null?void 0:l.email)??((f=r.customer)==null?void 0:f.email),currency:((p=i.customer)==null?void 0:p.currency)??r.currency,locale:(S=i.customer)==null?void 0:S.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:n,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:r.id,lineItems:a,customer:u,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:c,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function vn(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function bn(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var Ee=class{constructor(e,t){this.http=e;this.storeId=t}async getActivationStatus(e){let t=e??this.storeId;if(!t)throw new Error("rx.getActivationStatus: storeId is required");return this.http.get("/api/public/v1/rx/activation-status",{params:{storeId:t}})}async isRequiredForProduct(e,t){return this.http.get("/api/public/v1/rx/required-for-product",{params:{productId:e,clinicalNetworkId:t==null?void 0:t.clinicalNetworkId}})}async getCasesForOrder(e){return this.http.post("/api/public/v1/rx/cases/lookup",e)}async getIntakeContext(e){return this.http.post("/api/public/v1/rx/intake/context",e)}async submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",e)}async validateIntake(e){return this.http.post("/api/public/v1/rx/intake/validate",e)}async getQuestionsForProduct(e,t){return this.http.get("/api/public/v1/rx/questions-for-product",{params:t?{productId:e,variantId:t}:{productId:e}})}};var _e=class{constructor(e,t){this.core=e;this.bootstrap=t;this.runtime=null;this.loading=null;this.settled=!1;this.reads=new Set;this.subscribers=[]}variant(e){var t,n,r,i;return((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.arm)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.variant)??null}start(){return typeof window>"u"?Promise.resolve():(this.loading??(this.loading=(async()=>{try{this.runtime=await this.core()}catch{}this.settled=!0;let e=this.runtime;for(let t of this.reads)try{e==null||e.getVariant(t)}catch{}this.reads.clear();for(let{key:t,cb:n}of this.subscribers.splice(0))try{e?e.onVariant(t,n):n(this.variant(t))}catch{}try{await(e==null?void 0:e.ready())}catch{}})()),this.loading)}read(e){this.settled||this.reads.add(e),this.start()}getVariant(e){return this.runtime?this.runtime.getVariant(e):(this.read(e),this.variant(e))}getPayload(e){var t,n,r,i;return this.runtime?this.runtime.getPayload(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.payload)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.payload)??null)}isEnabled(e){var t,n;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:n.enabled)??!1)}onVariant(e,t){if(this.runtime){this.runtime.onVariant(e,t);return}if(this.settled){t(this.variant(e));return}this.subscribers.push({key:e,cb:t}),this.start()}ready(){return this.start()}};var ze=class{constructor(e){let t=e.environment??"production",n=ie.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new ie({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new ke(n,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new _e(()=>this.track.core(),this.config.bootstrap);let r=i=>{this._sessionToken=i};this.checkout=new oe(this.http,this.config.storeId,r,i=>this.track.noteCheckout({checkoutSessionId:i.id,amount:i.totals.total,currency:i.totals.currency,items:Ie(i.items)})),this.payment=new Ae(this.http,this.config.storeId,t,this.checkout,i=>this.track.notePaid(i),(i,o)=>this.track.noteSignal("wallet_unavailable",i,o)),this.offers=new ce(this.http,this.config.storeId,this.payment),this.customer=new ue(this.http,this.config.storeId),this.portal=new le(this.http,this.config.storeId,r),this.catalog=new xe(this.http,this.config.storeId),this.funnel=new Te(this.http,this.config.storeId,this.checkout,this.config.accountId,i=>this.track.noteFunnelSession(i)),this.rx=new Ee(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function wt(s){return new ze(s)}var vt=_("react/jsx-runtime"),kt=(0,Q.createContext)(null);function Rn(s){let e={storeId:s.storeId,environment:s.environment,apiKey:s.apiKey,baseUrl:s.baseUrl,accountId:s.accountId,funnel:s.funnel,timeout:s.timeout,bootstrap:s.bootstrap};return JSON.stringify(e)}function An(s){if(s.config)return s.config;let{storeId:e,environment:t,apiKey:n,baseUrl:r}=s;return{storeId:e,environment:t,apiKey:n,baseUrl:r}}function It(s){let e=An(s),t=Rn(e),n=(0,Q.useMemo)(()=>wt(e),[t]),r=(0,Q.useMemo)(()=>({client:n}),[n]);return(0,vt.jsx)(kt.Provider,{value:r,children:s.children})}function E(){let s=(0,Q.useContext)(kt);if(!s)throw new Error("useHeadlessClient must be used within <TagadaHeadlessProvider>");return s.client}var N=_("react");function bt(s,e){let t=E(),[n,r]=(0,N.useState)(null),[i,o]=(0,N.useState)(!1),[a,c]=(0,N.useState)(null),u=(0,N.useCallback)(async()=>{if(s){o(!0),c(null);try{let g=await t.checkout.loadSession(s,e);r(g)}catch(g){c(g instanceof Error?g:new Error(String(g)))}finally{o(!1)}}},[t,s,e]);(0,N.useEffect)(()=>{u()},[u]);let m=(0,N.useCallback)(async g=>{o(!0),c(null);try{let P=await t.checkout.createSession(g),w=new URL(window.location.href);w.searchParams.set("checkoutToken",P.checkoutToken),w.searchParams.set("token",P.sessionToken),window.history.replaceState({},"",w.toString());let v=await t.checkout.loadSession(P.checkoutToken,P.sessionToken);r(v)}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}},[t]),l=(0,N.useCallback)(async g=>{c(null);try{return await t.checkout.createSessionUrl(g)}catch(P){let w=P instanceof Error?P:new Error(String(P));throw c(w),w}},[t]),f=(0,N.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.updateCart(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),p=(0,N.useCallback)(async g=>{n&&await t.checkout.updateCustomer(n.id,g)},[t,n]),S=(0,N.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.updateAddress(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),y=(0,N.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.updateCustomerAndAddress(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),d=(0,N.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.applyPromoCode(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),h=(0,N.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.removePromoCode(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]),k=(0,N.useCallback)(async()=>n?t.checkout.getShippingRates(n.id):[],[t,n]),A=(0,N.useCallback)(async g=>{if(n){o(!0);try{await t.checkout.selectShippingRate(n.id,g),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,n,u]);return{session:n,isLoading:i,error:a,refresh:u,createSession:m,createSessionUrl:l,updateCart:f,updateCustomer:p,updateAddress:S,updateCustomerAndAddress:y,applyPromo:d,removePromo:h,getShippingRates:k,selectShippingRate:A}}var x=_("react");var Rt=new Set;function Ne(s){return Rt.has(s)?!1:(Rt.add(s),!0)}function At(s){let e=E(),[t,n]=(0,x.useState)(null),[r,i]=(0,x.useState)(null),[o,a]=(0,x.useState)(null),[c,u]=(0,x.useState)(!1),[m,l]=(0,x.useState)(null),[f,p]=(0,x.useState)(null),S=(0,x.useRef)(!1),y=(0,x.useRef)(!1),d=(0,x.useRef)(s);d.current=s,(0,x.useEffect)(()=>{if(typeof window>"u"||y.current)return;Re();let R=new URLSearchParams(window.location.search),C=R.get("paymentAction"),I=R.get("paymentActionStatus"),U=R.get("paymentId");if(C!=="requireAction"||I!=="completed"||!U||(y.current=!0,!Ne(U)))return;u(!0),p(null),(async()=>{var b,O,K,X;try{let M=await e.payment.resumeAfterRedirect(U),He=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(Kt=>He.delete(Kt));let $t=He.toString()?`${window.location.pathname}?${He.toString()}`:window.location.pathname;window.history.replaceState({},document.title,$t),M.status==="succeeded"?(O=(b=d.current)==null?void 0:b.onPaymentSuccess)==null||O.call(b,M):M.status==="failed"&&(p(new Error(M.error)),(X=(K=d.current)==null?void 0:K.onPaymentFailed)==null||X.call(K,M))}catch(M){p(M instanceof Error?M:new Error(String(M)))}finally{u(!1)}})()},[e]);let h=(0,x.useCallback)(async(R,C)=>{var U;if(S.current)return;S.current=!0;let I=C!=null&&C.paymentSetupConfig?{paymentSetupConfig:C.paymentSetupConfig}:(U=d.current)!=null&&U.paymentSetupConfig?{paymentSetupConfig:d.current.paymentSetupConfig}:void 0;try{let[D,b,O]=await Promise.all([e.payment.getPaymentSetup(R,I),e.payment.getExpressMethods(R,I),e.payment.getStoreConfig()]);n(D),i(b),a(O)}catch(D){S.current=!1,p(D instanceof Error?D:new Error(String(D)))}},[e]),k=(0,x.useCallback)(async R=>{var C,I,U,D;u(!0),p(null);try{let b=await e.payment.processPayment(R);if(b.status==="requires_redirect"){if(b.method==="POST"&&b.postData){let O=document.createElement("form");O.method="POST",O.action=b.redirectUrl;for(let[K,X]of Object.entries(b.postData)){let M=document.createElement("input");M.type="hidden",M.name=K,M.value=X,O.appendChild(M)}document.body.appendChild(O),O.submit()}else window.location.href=b.redirectUrl;return b}return b.status==="succeeded"?(I=(C=d.current)==null?void 0:C.onPaymentSuccess)==null||I.call(C,b):b.status==="failed"&&(p(new Error(b.error)),(D=(U=d.current)==null?void 0:U.onPaymentFailed)==null||D.call(U,b)),b}catch(b){let O=b instanceof Error?b:new Error(String(b));return p(O),{status:"failed",error:O.message}}finally{u(!1)}},[e]),A=(0,x.useCallback)(R=>async()=>{u(!0),p(null);try{return await R()}catch(C){let I=C instanceof Error?C:new Error(String(C));throw p(I),I}finally{u(!1)}},[]),g=(0,x.useCallback)(async R=>{u(!0),p(null);try{let C=await e.payment.pay(R);return l(C),C}catch(C){let I=C instanceof Error?C:new Error(String(C));throw p(I),I}finally{u(!1)}},[e]),P=(0,x.useCallback)(R=>e.payment.tokenizeCard(R),[e]),w=(0,x.useCallback)(async R=>{let I=await A(()=>e.payment.processApplePay(R))();return l(I),I},[e,A]),v=(0,x.useCallback)(async R=>{let I=await A(()=>e.payment.processGooglePay(R))();return l(I),I},[e,A]),j=(0,x.useCallback)(async R=>{let I=await A(()=>e.payment.processApm(R))();return l(I),I},[e,A]),$=(0,x.useCallback)(R=>e.payment.pollPaymentStatus(R),[e]);return{paymentSetup:t,expressMethods:r,storeConfig:o,isProcessing:c,result:m,error:f,loadPaymentSetup:h,processPayment:k,pay:g,tokenizeCard:P,processApplePay:w,processGooglePay:v,processApm:j,pollStatus:$}}var H=_("react");var On={options:"idle",networks:[],selection:null,payment:null,paymentStatus:null,isCreating:!1,error:null},xn=()=>()=>{},Ot=()=>On;function xt({checkoutSessionId:s,enabled:e=!0,onPaid:t,pollIntervalMs:n}){let r=E(),i=(0,H.useRef)(t);(0,H.useEffect)(()=>{i.current=t},[t]);let o=(0,H.useMemo)(()=>s?r.payment.createCryptoOnchainCheckout({checkoutSessionId:s,pollIntervalMs:n,onPaid:y=>{var d;return(d=i.current)==null?void 0:d.call(i,y)}}):null,[r,s,n]),a=(0,H.useSyncExternalStore)(o?o.subscribe:xn,o?o.getState:Ot,o?o.getState:Ot);(0,H.useEffect)(()=>{if(!(!o||!e))return o.getState().options==="idle"?o.loadOptions():o.resume(),()=>o.stop()},[o,e]);let[c,u]=(0,H.useState)(()=>Date.now()),m=o?o.getPhase(c):"waiting",l=a.payment!==null&&!ve.includes(m);(0,H.useEffect)(()=>{if(!l)return;let y=setInterval(()=>u(Date.now()),1e3);return()=>clearInterval(y)},[l]);let f=(0,H.useCallback)(y=>o==null?void 0:o.select(y),[o]),p=(0,H.useCallback)(y=>o?o.pay(y):Promise.resolve({ok:!1,code:"CHECKOUT_FAILED",message:"No checkout session"}),[o]),S=(0,H.useCallback)(()=>o?o.refreshStatus():Promise.resolve(null),[o]);return{...a,phase:m,secondsLeft:o?o.getSecondsLeft(c):0,select:f,pay:p,refreshStatus:S}}var T=_("react");function Tt(s){let e=E(),[t,n]=(0,T.useState)(null),[r,i]=(0,T.useState)(null),[o,a]=(0,T.useState)(!1),[c,u]=(0,T.useState)(null),m=(0,T.useRef)(s);m.current=s;let l=(0,T.useRef)(!1);(0,T.useEffect)(()=>{var C;if(typeof window>"u"||(C=m.current)!=null&&C.disableAutoResume||l.current)return;let w=new URLSearchParams(window.location.search),v=w.get("paymentAction"),j=w.get("paymentActionStatus"),$=w.get("paymentId");if(v!=="requireAction"||j!=="completed"||!$||(l.current=!0,!Ne($)))return;a(!0),u(null),(async()=>{var I,U,D,b;try{let O=await e.payment.resumeAfterRedirect($),K=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(M=>K.delete(M));let X=K.toString()?`${window.location.pathname}?${K.toString()}`:window.location.pathname;window.history.replaceState({},document.title,X),O.status==="succeeded"?(U=(I=m.current)==null?void 0:I.onOfferAccepted)==null||U.call(I,O):O.status==="failed"&&(u(new Error(O.error)),(b=(D=m.current)==null?void 0:D.onOfferDeclined)==null||b.call(D,O))}catch(O){u(O instanceof Error?O:new Error(String(O)))}finally{a(!1)}})()},[e]);let f=(0,T.useCallback)(async w=>{a(!0),u(null);try{return await w()}catch(v){let j=v instanceof Error?v:new Error(String(v));throw u(j),j}finally{a(!1)}},[]),p=(0,T.useCallback)(w=>f(async()=>{let v=await e.offers.getOffer(w);return n(v),v}),[e,f]),S=(0,T.useCallback)(w=>e.offers.listOffers(w),[e]),y=(0,T.useCallback)(w=>f(async()=>{let v=await e.offers.previewOffer(w);return i(v),v}),[e,f]),d=(0,T.useCallback)(w=>f(()=>e.offers.payPreviewedOffer(w)),[e,f]),h=(0,T.useCallback)(async w=>{var v,j,$,R;a(!0),u(null);try{let C=await e.offers.processOfferPayment(w);if(C.status==="requires_redirect"){if(C.method==="POST"&&C.postData){let I=document.createElement("form");I.method="POST",I.action=C.redirectUrl;for(let[U,D]of Object.entries(C.postData)){let b=document.createElement("input");b.type="hidden",b.name=U,b.value=D,I.appendChild(b)}document.body.appendChild(I),I.submit()}else window.location.href=C.redirectUrl;return C}return C.status==="succeeded"?(j=(v=m.current)==null?void 0:v.onOfferAccepted)==null||j.call(v,C):C.status==="failed"&&(u(new Error(C.error)),(R=($=m.current)==null?void 0:$.onOfferDeclined)==null||R.call($,C)),C}catch(C){let I=C instanceof Error?C:new Error(String(C));return u(I),{status:"failed",error:I.message}}finally{a(!1)}},[e]),k=(0,T.useCallback)(w=>e.offers.toggleOrderBump(w),[e]),A=(0,T.useCallback)(w=>e.offers.listPostPurchaseOffers(w),[e]),g=(0,T.useCallback)(w=>f(()=>e.offers.acceptPostPurchaseOffer(w)),[e,f]),P=(0,T.useCallback)(w=>f(()=>e.offers.declinePostPurchaseOffer(w)),[e,f]);return{offer:t,preview:r,isLoading:o,error:c,getOffer:p,listOffers:S,previewOffer:y,processOfferPayment:h,payPreviewedOffer:d,toggleOrderBump:k,listPostPurchaseOffers:A,acceptPostPurchaseOffer:g,declinePostPurchaseOffer:P}}var G=_("react");function Et(s){let e=E(),[t,n]=(0,G.useState)(null),[r,i]=(0,G.useState)([]),[o,a]=(0,G.useState)([]),[c,u]=(0,G.useState)(!1),[m,l]=(0,G.useState)(null),f=(0,G.useCallback)(async d=>{u(!0),l(null);try{let h=await e.customer.getProfile(d);n(h)}catch(h){l(h instanceof Error?h:new Error(String(h)))}finally{u(!1)}},[e]),p=(0,G.useCallback)(async d=>{try{let h=await e.customer.getOrders(d);i(h.orders)}catch(h){l(h instanceof Error?h:new Error(String(h)))}},[e]),S=(0,G.useCallback)(async d=>{try{let h=await e.customer.getSubscriptions(d);a(h)}catch(h){l(h instanceof Error?h:new Error(String(h)))}},[e]),y=(0,G.useCallback)(async(d,h)=>{try{let k=await e.customer.updateProfile(d,h);n(k)}catch(k){l(k instanceof Error?k:new Error(String(k)))}},[e]);return(0,G.useEffect)(()=>{s&&f(s)},[s,f]),{customer:t,orders:r,subscriptions:o,isLoading:c,error:m,loadCustomer:f,loadOrders:p,loadSubscriptions:S,updateProfile:y}}var B=_("react");function _t(s,e){let t=E(),[n,r]=(0,B.useState)(null),[i,o]=(0,B.useState)(!1),[a,c]=(0,B.useState)(null),u=(e==null?void 0:e.watchRelatedOrders)??!0,m=(e==null?void 0:e.watchTimeoutMs)??8e3,l=(e==null?void 0:e.watchIntervalMs)??2e3,f=(0,B.useRef)(0),p=(0,B.useCallback)(async()=>{if(s)try{let S=await t.customer.getOrder(s);r(S)}catch(S){c(S instanceof Error?S:new Error(String(S)))}},[t,s]);return(0,B.useEffect)(()=>{if(!s)return;let S=++f.current,y=()=>f.current===S;return o(!0),c(null),(async()=>{var d,h;try{let k=await t.customer.getOrder(s);if(!y()||(r(k),o(!1),!u||(d=k.relatedOrders)!=null&&d.length))return;let A=Date.now()+m;for(;Date.now()<A&&y();){if(await new Promise(g=>setTimeout(g,l)),!y()||(k=await t.customer.getOrder(s),!y()))return;if((h=k.relatedOrders)!=null&&h.length){r(k);return}}}catch(k){if(!y())return;c(k instanceof Error?k:new Error(String(k))),o(!1)}})(),()=>{f.current++}},[t,s,u,m,l]),{order:n,relatedOrders:(n==null?void 0:n.relatedOrders)??[],isLoading:i,error:a,refresh:p}}var W=_("react");function Nt(){let s=E(),[e,t]=(0,W.useState)([]),[n,r]=(0,W.useState)(!1),[i,o]=(0,W.useState)(null),a=(0,W.useCallback)(async u=>{r(!0),o(null);try{let m=await s.catalog.getProducts(u);return t(m),m}catch(m){let l=m instanceof Error?m:new Error(String(m));throw o(l),l}finally{r(!1)}},[s]),c=(0,W.useCallback)(async u=>{r(!0),o(null);try{return await s.catalog.getProduct(u)}catch(m){let l=m instanceof Error?m:new Error(String(m));throw o(l),l}finally{r(!1)}},[s]);return{products:e,isLoading:n,error:i,loadProducts:a,loadProduct:c}}var F=_("react");var Tn=new Set(["approved","shipped","delivered","declined","cancelled","error"]);function Lt(){let s=E(),[e,t]=(0,F.useState)([]),[n,r]=(0,F.useState)(null),[i,o]=(0,F.useState)(!1),[a,c]=(0,F.useState)(null),u=(0,F.useRef)(null);(0,F.useEffect)(()=>()=>{u.current&&clearInterval(u.current)},[]);let m=(0,F.useCallback)(async(y,d)=>{o(!0),c(null);try{return await s.rx.isRequiredForProduct(y,d)}catch(h){let k=h instanceof Error?h:new Error(String(h));throw c(k),k}finally{o(!1)}},[s]),l=(0,F.useCallback)(async(y,d)=>{o(!0),c(null);try{return await s.rx.getQuestionsForProduct(y,d)}catch(h){let k=h instanceof Error?h:new Error(String(h));throw c(k),k}finally{o(!1)}},[s]),f=(0,F.useCallback)(async y=>{o(!0),c(null);try{let d=await s.rx.submitCase(y);return r(d),d}catch(d){let h=d instanceof Error?d:new Error(String(d));throw c(h),h}finally{o(!1)}},[s]),p=(0,F.useCallback)(async y=>{o(!0),c(null);try{let d=await s.rx.getCasesForOrder(y);return t(d.cases),d.cases}catch(d){let h=d instanceof Error?d:new Error(String(d));throw c(h),h}finally{o(!1)}},[s]),S=(0,F.useCallback)(({orderId:y,checkoutToken:d},h)=>{u.current&&clearInterval(u.current);let k=(h==null?void 0:h.intervalMs)??5e3,A=async()=>{var g;try{let P=await s.rx.getCasesForOrder({orderId:y,checkoutToken:d});t(P.cases),(g=h==null?void 0:h.onUpdate)==null||g.call(h,P.cases),P.cases.length>0&&P.cases.every(w=>Tn.has(w.status))&&(u.current&&clearInterval(u.current),u.current=null)}catch(P){let w=P instanceof Error?P:new Error(String(P));c(w)}};return A(),u.current=setInterval(A,k),()=>{u.current&&clearInterval(u.current),u.current=null}},[s]);return{cases:e,lastSubmission:n,isLoading:i,error:a,isRequiredForProduct:m,getQuestionsForProduct:l,submitCase:f,fetchCasesForOrder:p,pollOrder:S}}var Ut=_("react");function Dt(s,e){let t=E(),n=e?JSON.stringify(e):"";(0,Ut.useEffect)(()=>{t.track.step(s,e)},[t,s,n])}var L=_("react");var Mt=!1,Ht=!1,Le=[];function Ve(){Ht=!0;for(let s of Le)s();Le.length=0}function de(s,e={}){var t,n;return Ht||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(Ve(),Promise.resolve()):Mt?new Promise(r=>Le.push(r)):(Mt=!0,new Promise((r,i)=>{if(Le.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let u=()=>{var m,l;(l=(m=window.google)==null?void 0:m.maps)!=null&&l.places?Ve():setTimeout(u,100)};u();return}let a=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let c=document.createElement("script");c.src=`https://maps.googleapis.com/maps/api/js?${a}`,c.async=!0,c.defer=!0,c.onload=()=>Ve(),c.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(c)}))}var z=class s{static async searchPlaces(e,t={}){var r,i;if(!((i=(r=window.google)==null?void 0:r.maps)!=null&&i.places)||!e.trim())return[];let n=new window.google.maps.places.AutocompleteService;return new Promise(o=>{n.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,c)=>{var u,m,l;o(c===((l=(m=(u=window.google)==null?void 0:u.maps)==null?void 0:m.places)==null?void 0:l.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var n,r;if(!((r=(n=window.google)==null?void 0:n.maps)!=null&&r.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var c,u,m;i(a===((m=(u=(c=window.google)==null?void 0:c.maps)==null?void 0:u.places)==null?void 0:m.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},n="",r="",i="",o="",a="",c="",u="",m="";for(let p of e.address_components??[]){let S=p.types;S.includes("subpremise")&&(t.subpremise=p.long_name),S.includes("street_number")&&(t.streetNumber=p.long_name),S.includes("premise")&&(n=p.long_name),S.includes("route")&&(t.route=p.long_name),S.includes("neighborhood")&&(r=p.long_name),S.includes("sublocality_level_5")&&(i=p.long_name),S.includes("sublocality_level_4")&&(o=p.long_name),S.includes("sublocality_level_3")&&(a=p.long_name),S.includes("sublocality_level_2")&&(c=p.long_name),S.includes("sublocality_level_1")&&(u=p.long_name),S.includes("locality")&&(t.locality=p.long_name),S.includes("postal_town")&&(m=p.long_name),S.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=p.short_name,t.administrativeAreaLevel2Long=p.long_name),S.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=p.short_name,t.administrativeAreaLevel1Long=p.long_name),S.includes("country")&&(t.country=p.short_name),S.includes("postal_code")&&(t.postalCode=p.long_name)}t.locality||(t.locality=m||c||u||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let l=t.streetNumber||n,f=t.route||i||o||a||r;if(t.subpremise&&l&&f)t.fullStreetAddress=`${t.subpremise}/${l} ${f}`;else if(l&&f)if(n&&o&&a){let p=`${a}-${o}-${n}`;c&&(p=`${p} ${c}`),t.fullStreetAddress=p}else t.fullStreetAddress=`${l} ${f}`;else f?t.fullStreetAddress=f:l&&(t.fullStreetAddress=l);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};function Ft(s){let{apiKey:e,language:t,region:n,version:r,defer:i=!1}=s,[o,a]=(0,L.useState)([]),[c,u]=(0,L.useState)(!1),[m,l]=(0,L.useState)(!1),f=(0,L.useRef)(null),p=(0,L.useRef)(null),S=(0,L.useCallback)(()=>{de(e,{language:t,region:n,version:r}).then(()=>l(!0))},[e,t,n,r]);(0,L.useEffect)(()=>{!e||i||S()},[e,i,S]),(0,L.useEffect)(()=>{if(m&&p.current){let{input:g,country:P}=p.current;p.current=null,y(g,P)}},[m]);let y=(0,L.useCallback)((g,P)=>{if(!m){i&&(p.current={input:g,country:P},S());return}if(g.length<3){a([]);return}f.current&&clearTimeout(f.current),f.current=setTimeout(async()=>{u(!0);let w=await z.searchPlaces(g,{componentRestrictions:P?{country:P.toLowerCase()}:void 0});a(w),u(!1)},300)},[m,i,S]),d=(0,L.useCallback)(g=>z.getPlaceDetails(g),[]),h=(0,L.useCallback)(g=>z.extractAddressComponents(g),[]),k=(0,L.useCallback)(g=>z.extractFormattedAddress(g),[]),A=(0,L.useCallback)(()=>a([]),[]);return{predictions:o,isLoading:c,isScriptLoaded:m,searchPlaces:y,getPlaceDetails:d,extractAddressComponents:h,extractFormattedAddress:k,clearPredictions:A}}var Y=_("react");var qt="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",Qe=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],pe=new Map,Ue=new Map,Je=new Map,Ye=new Map;async function En(s){let e=pe.get(s);if(e)return e;let t=Je.get(s);return t||(t=(async()=>{let n=`${qt}/${s}/countries.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return pe.set(s,i),Je.delete(s),i})(),Je.set(s,t),t)}async function _n(s){let e=Ue.get(s);if(e)return e;let t=Ye.get(s);return t||(t=(async()=>{let n=`${qt}/${s}/regions.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return Ue.set(s,i),Ye.delete(s),i})(),Ye.set(s,t),t)}function Nn(s){return pe.get(s)||pe.get("en")||{}}function Ln(s){return Ue.get(s)||Ue.get("en")||{}}async function me(s="en"){await Promise.all([En(s),_n(s)])}var De=(s="en")=>{let e=Nn(s);return Object.entries(e).map(([t,n])=>({code:t,name:n.n,iso3:n.i3,numeric:n.nu})).sort((t,n)=>t.name.localeCompare(n.name))},We=(s,e="en")=>{let n=Ln(e)[s];return n?n.map(([r,i])=>({code:r,name:i,countryCode:s})).sort((r,i)=>r.name.localeCompare(i.name)):[]};function ge(s){return pe.has(s)}var V=class s{static ensureLoaded(e="en"){return me(e)}static getCountries(e="en"){let t=De(e),n={};for(let r of t)n[r.code]={iso:r.code,iso3:r.iso3??"",numeric:r.numeric??0,name:r.name};return n}static getCountryOptions(e="en"){return De(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return We(e,t).map(n=>({iso:n.code,name:n.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(n=>({value:n.iso,label:n.name}))}static findRegion(e,t,n="en"){return s.getRegions(e,n).find(r=>r.iso===t)??null}static mapGoogleToISO(e,t,n,r="en"){let i=s.getRegions(n,r);if(i.length===0)return null;let o=i.find(a=>a.iso===e);return o||(o=i.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return ge(e)}static getAvailableLanguages(){return Qe}};function Me(s="en"){let[e,t]=(0,Y.useState)(ge(s));return(0,Y.useEffect)(()=>{let n=!1;return me(s).then(()=>{n||t(!0)}).catch(r=>console.error("[headless-sdk] Failed to load geodata:",r)),()=>{n=!0}},[s]),(0,Y.useMemo)(()=>e?{countries:V.getCountries(s),getRegions:n=>V.getRegions(n,s),findRegion:(n,r)=>V.findRegion(n,r,s),mapGoogleToISO:(n,r,i)=>V.mapGoogleToISO(n,r,i,s),isLoaded:!0}:{countries:{},getRegions:()=>[],findRegion:()=>null,mapGoogleToISO:()=>null,isLoaded:!1},[s,e])}function Gt(s="en"){let{countries:e,isLoaded:t}=Me(s);return(0,Y.useMemo)(()=>t?Object.values(e).map(n=>({value:n.iso,label:n.name})).sort((n,r)=>n.label.localeCompare(r.label)):[],[e,t])}function jt(s,e="en"){let{getRegions:t,isLoaded:n}=Me(e);return(0,Y.useMemo)(()=>!n||!s?[]:t(s).map(r=>({value:r.iso,label:r.name})).sort((r,i)=>r.label.localeCompare(i.label)),[s,t,n])}var Un={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},Dn={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},Mn=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),Z=class s{static getSymbol(e){return Un[e]??e}static getName(e){return Dn[e]??e}static getDecimalPlaces(e){return Mn.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function Ze(s,e="USD",t="en-US"){let n=Z.getDecimalPlaces(e),r=s/(n===0?100:Math.pow(10,n));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:n,maximumFractionDigits:n}).format(r)}catch{return`${Z.getSymbol(e)}${r.toFixed(n)}`}}return Wt(Hn);})();
7
7
  if(typeof window!=="undefined"&&TagadaHeadlessReactBundle){ window.TagadaHeadlessReact=TagadaHeadlessReactBundle;}
8
8
  //# sourceMappingURL=tagada-headless-react.min.js.map