setTimeout(y,500)),s.input.amount={amount:m.data.totalAmount.amount,currencyCode:m.data.totalAmount.currencyCode};continue}return(m.data.totalAmount.amount===l||parseFloat(m.data.totalAmount.amount)<=parseFloat(l))&&m.data.totalAmount.currencyCode===u?m:d}throw new Error("Payment update operation timed out")}async updateCartAttributes({cartId:t,attributes:n,instrumentName:r,startingCheckout:a}){const i={cartId:t,attributes:n};return await this.requestDeferredCart(mo,i,{instrumentName:r,startingCheckout:a})}async submitForCompletion(t,n,r){var a,i;const o=this.formatLanguage(this.locale),s=await this.request([Eo],{cartId:t,attemptToken:n,country:this.country,language:o,withCarrierRates:this.withCarrierRates},{instrumentName:r});return{data:(i=(a=s.data)==null?void 0:a.cartSubmitForCompletion)==null?void 0:i.result,errors:this.parseCompletionErrors(s)}}async fetchSubscriptionPolicy(){var t,n;const{data:r}=await this.request([Co],{country:this.country,language:this.formatLanguage(this.locale)},{});return(n=(t=r==null?void 0:r.shop)==null?void 0:t.subscriptionPolicy)==null?void 0:n.body}generateURLWithOperationName(t){const n=t.match(this.OPERATION_NAME_REGEX);if(n){const r=this.url.includes("?")?"&":"?",a="operation_name=".concat(n[1]);return"".concat(this.url).concat(r).concat(a)}return this.url}async request(t,n,r){return this.client.request(t.join(""),{variables:n,headers:Ir(r),url:this.generateURLWithOperationName(t[0])})}async requestStream(t,n,r){return this.client.requestStream(t.join(""),{variables:n,headers:Ir(r),url:this.generateURLWithOperationName(t[0]),signal:r.abortSignal})}async requestDeferredCart(t,n,r){var a,i,o,s,l,u,d,p,m,y;const C=this.formatLanguage(this.locale),b=await this.requestStream([t,Ee],P(_({},n),{country:this.country,language:C,withCarrierRates:this.withCarrierRates}),r);try{for(var N=V(b),U,J,Lt;U=!(J=await N.next()).done;U=!1){const kt=J.value;kt.errors&&this.onError(kt.errors);const A=(i=(a=kt.data)==null?void 0:a.result)==null?void 0:i.cart;if(A&&!kt.hasNext)return{data:await this.fetchCart({id:A.id,instrumentName:r.instrumentName,startingCheckout:!1}),errors:this.parseMutationErrors(kt,"result"),warnings:this.parseMutationWarnings((s=(o=kt.data)==null?void 0:o.result)==null?void 0:s.warnings)};if(this.lastValidCart&&(u=(l=kt.data)==null?void 0:l.result)!=null&&u.errors)return this.onResultError((p=(d=kt.data)==null?void 0:d.result)==null?void 0:p.errors),{data:this.lastValidCart,errors:this.parseMutationErrors(kt,"result"),warnings:this.parseMutationWarnings((y=(m=kt.data)==null?void 0:m.result)==null?void 0:y.warnings)}}}catch(kt){Lt=[kt]}finally{try{U&&(J=N.return)&&await J.call(N)}finally{if(Lt)throw Lt[0]}}throw new wt("Deferred cart operation returned no response")}onError(t){var n,r;if(!t)return;w.leaveBreadcrumb("GraphQL response error",t,"error");const a=(r=(n=t.graphQLErrors)==null?void 0:n.map(s=>s.message).join(", "))!=null?r:"",i="".concat(t.message).concat(a.length>0?" - ".concat(a):""),o=t!=null&&t.networkStatusCode?"with status ".concat(t.networkStatusCode," => ").concat(i):"=> ".concat(i);throw new Error("GraphQL mutation failed ".concat(o))}onResultError(t){w.leaveBreadcrumb("GraphQL result error",t,"error")}formatLanguage(t){return t.includes("-")?t.split("-")[0].toUpperCase():t.toUpperCase()}parseCartResponse(t){var n,r,a;const i=t.lines.edges.map(s=>{var l,u;const d=s.node;return{quantity:d.quantity,totalAmount:{amount:d.cost.totalAmount.amount,currencyCode:d.cost.totalAmount.currencyCode},subtotalAmount:{amount:(l=d.cost.subtotalAmount)==null?void 0:l.amount,currencyCode:(u=d.cost.subtotalAmount)==null?void 0:u.currencyCode},merchandise:{requiresShipping:d.merchandise.requiresShipping},discountAllocations:d.discountAllocations,sellingPlanAllocation:d.sellingPlanAllocation}}),o=t.deliveryGroups.edges.map(s=>s.node);return{id:t.id,totalAmount:t.cost.totalAmount,subtotalAmount:(n=t.cost.subtotalAmount)!=null?n:void 0,totalTaxAmount:(r=t.cost.totalTaxAmount)!=null?r:void 0,totalDutyAmount:(a=t.cost.totalDutyAmount)!=null?a:void 0,discountAllocations:t.discountAllocations,discountCodes:t.discountCodes,lineItems:i,deliveryGroups:o,checkoutUrl:t.checkoutUrl}}parseGraphQlErrors(t){var n,r;return(r=(n=t==null?void 0:t.graphQLErrors)==null?void 0:n.map(a=>a.message.replace(/\(Expected.*\)/,"").trim()))!=null?r:[]}parseMutationErrors(t,n){var r,a,i;const o=this.parseGraphQlErrors(t.errors),s=((i=(a=(r=t.data)==null?void 0:r[n])==null?void 0:a.errors)==null?void 0:i.map(u=>u.code===te?{code:te,message:u.message}:u.field&&u.field.length>0?"".concat(u.code,": ").concat(u.field.join(".")):u.code).filter(u=>u))||[],l=[...o,...s];return w.leaveBreadcrumb("GraphQL errors on mutation",l,"error"),l}parseMutationWarnings(t){return!t||t.length===0?[]:t.map(n=>n.code)}parseCompletionErrors(t){var n,r,a,i;const o=this.parseGraphQlErrors(t.errors);let s=[];((a=(r=(n=t.data)==null?void 0:n.cartSubmitForCompletion)==null?void 0:r.result)==null?void 0:a.__typename)==="SubmitFailed"&&(s=(i=t.data.cartSubmitForCompletion.result.errors.map(u=>u.code))!=null?i:[]);const l=[...o,...s];return w.leaveBreadcrumb("GraphQL errors on completion",l,"error"),l}}function Ir({instrumentName:e,startingCheckout:t}){const n={};return e&&(n["X-Wallet-Name"]="".concat(e)),t&&(n["X-Start-Wallet-Checkout"]="".concat(t)),n}async function Cn({cartId:e,cartClient:t,instrumentName:n,selectedDeliveryOptions:r,abortSignal:a}){try{if(!e)throw new Error("[".concat(n,"] provided no cart ID when updating shipping method"));if(!t)throw new Error("[".concat(n,"] provided invalid cart client when updating shipping method"));return await t.updateSelectedDeliveryOptions(e,r,n,a)}catch(i){throw f.updateFailed(n,"updateSelectedDeliveryOptions"),i}}async function Sn({cartId:e,token:t,cartClient:n,instrumentName:r}){try{if(!e)throw new Error("[".concat(r,"] provided no cart ID when submitting for completion"));if(!n)throw new Error("[".concat(r,"] provided invalid cart client when submitting for completion"));if(!t)throw new Error("[".concat(r,"] provided no token when submitting for completion"));return await n.submitForCompletion(e,t,r)}catch(a){throw f.updateFailed(r,"submitForCompletion"),a}}function En({selectedDeliveryOptionHandles:e,deliveryGroups:t,instrumentName:n}){return t.map(r=>{const a=r.deliveryOptions.filter(i=>e.includes(i.handle));if(!a.length)throw new Error("[".concat(n,"] could not find delivery option for group: ").concat(r.id));if(a.length>1)throw new Error("[".concat(n,"] found multiple delivery options with selectedDeliverOptionHandle in group: ").concat(r.id));return{deliveryGroupId:r.id,deliveryOptionHandle:a[0].handle}})}async function Io(e){const{cartClient:t,instrumentName:n}=e;try{if(!e.cartId)throw new Error("[".concat(n,"] provided no cart ID when updating billing address"));if(!t)throw new Error("[".concat(n,"] provided invalid cart client when updating billing address"));return await t.updateCartBillingAddress(e)}catch(r){throw f.updateFailed(n,"updateBillingAddress"),r}}class Po{constructor({accessToken:t,buyerCountry:n,buyerCurrency:r,button:a,i18n:i,merchantName:o,dataSource:s,apiClient:l,walletParams:u}){c(this,"name",g.ApplePay),c(this,"accessToken"),c(this,"button"),c(this,"buyerCountry"),c(this,"cart"),c(this,"apiClient"),c(this,"dataSource"),c(this,"i18n"),c(this,"merchantName"),c(this,"session"),c(this,"paymentSheetActionGenerator"),c(this,"cancelled"),c(this,"buyerCurrency"),c(this,"customerAccountEmail"),c(this,"abortController",null),c(this,"onvalidatemerchant",async d=>{try{const p=new URL(d.validationURL),m=this.getMerchantSession(p),{cart:y,isOutOfStock:C}=await nt({element:this.button,instrumentName:this.name,dataSource:this.dataSource});this.cart=y;const b=await m;if(w.leaveBreadcrumb("ApplePay Session completeMerchantValidation",{session:b},"log"),C){this.abortAndShowOutOfStockError();return}if(this.sessionIsCancelled())return;this.session.completeMerchantValidation(b)}catch(p){f.sheetClicked({instrument:g.ApplePay,result:"failed"}),this.terminateSession(p)}}),c(this,"onshippingcontactselected",async d=>{try{const p=Qt(d.shippingContact),m=await Et({cartId:this.cart.id,streetAddress:p,cartClient:this.apiClient,instrumentName:this.name});if(!m.data)throw new Error("Missing cart during Apple Pay Session creation");if(this.shouldDecelerate(m.data))return;await this.applyPaymentSheetActions(m,y=>this.completeShippingContactSelection(m.data,y),{shippingRequired:this.isShippingRequired})}catch(p){this.terminateSession(p)}}),c(this,"onshippingmethodselected",async d=>{var p;try{const m=d.shippingMethod.identifier.split(","),y=En({selectedDeliveryOptionHandles:m,deliveryGroups:this.cart.deliveryGroups,instrumentName:this.name}),C=await Cn({cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name,selectedDeliveryOptions:y,abortSignal:(p=this.abortController)==null?void 0:p.signal});await this.applyPaymentSheetActions(C,()=>this.completeShippingMethodSelection(C.data))}catch(m){this.terminateSession(m)}}),c(this,"onpaymentmethodselected",async d=>{try{const{billingContact:p}=d.paymentMethod;if(!this.isShippingRequired&&p){const C=Qt(p),b=await Et({cartId:this.cart.id,countryCode:C.country,cartClient:this.apiClient,instrumentName:this.name});if(!b.data)throw new Error("Missing cart during Apple Pay Session creation");if(this.shouldDecelerate(b.data))return;await this.applyPaymentSheetActions(b,()=>this.cart=b.data);const N=await Io({billingAddress:C,cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name});await this.applyPaymentSheetActions(N,()=>this.cart=N.data)}const{newTotal:m,newLineItems:y}=this.getNewTotalAndLineItems(this.cart);if(w.leaveBreadcrumb("ApplePay Session completePaymentMethodSelection",{newTotal:m,newLineItems:y},"log"),this.sessionIsCancelled())return;this.session.completePaymentMethodSelection({newTotal:m,newLineItems:y})}catch(p){this.terminateSession(p)}}),c(this,"oncancel",()=>{var d;this.cancelled=!0,f.sheetCancelled(this.name),this.button.disabled=!1,(d=this.abortController)==null||d.abort()}),c(this,"onpaymentauthorized",async d=>{f.authorizationAttempt(this.name),Yt(R.AuthorizationLatency,this.name);const p=A=>{f.authorizationComplete({instrument:this.name,measurement:tt(R.AuthorizationLatency,this.name),result:"failure"}),this.terminateSession(A)},m=async A=>{var T,M;switch((T=A.effects)==null||T.forEach(k=>k()),A.action){case"complete":{const k=ApplePaySession.STATUS_SUCCESS;try{await this.completePayment(k),yt(A.redirectUrl)}catch($){p($)}break}case"show_error":{const k=(M=A.errors)!=null?M:[];try{await this.completePayment(ApplePaySession.STATUS_FAILURE,k)}catch($){p($)}break}case"abort":{try{await this.completePayment(ApplePaySession.STATUS_FAILURE),this.button.disabled=!1}catch(k){p(k)}break}case"decelerate":{try{await this.completePayment(ApplePaySession.STATUS_FAILURE),St({checkoutUrl:A.redirectUrl,instrumentName:this.name,reason:A.reason})}catch(k){p(k)}break}default:p(new Error("[".concat(this.name,"] completion action not handled: ").concat(A.action)))}},{token:y,billingContact:C,shippingContact:b}=d.payment;let N=null,U=null;try{if(!C){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}if(N=Qt(P(_({},C),{phoneNumber:b==null?void 0:b.phoneNumber})),this.isShippingRequired){if(!b){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}U=Qt(b)}}catch(A){p(A);return}const J=async()=>{var A;try{const T=this.isShippingRequired?{validateAddress:!0,streetAddress:U}:{},M=(A=this.customerAccountEmail)!=null?A:b==null?void 0:b.emailAddress,k=await Et(_({cartId:this.cart.id,emailAddress:M,cartClient:this.apiClient,instrumentName:this.name},T)),$=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(k);await Se({paymentSheetAction:$,onProceed:async Kt=>{Kt&&Kt.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,Kt):await Lt()},terminateSession:p})}catch(T){p(T)}},Lt=async()=>{var A;try{const T=this.cart.lineItems.some($=>!!$.sellingPlanAllocation),M=await tr({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{applePayWalletContent:{billingAddress:N,data:y.paymentData.data,header:y.paymentData.header,lastDigits:y.paymentMethod.displayName.split(" ")[1],signature:y.paymentData.signature,version:y.paymentData.version}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:N,cartClient:this.apiClient,instrumentName:this.name,hasSellingPlan:T,abortSignal:(A=this.abortController)==null?void 0:A.signal}),k=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(M);await Se({paymentSheetAction:k,onProceed:async $=>{$&&$.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,$):await kt()},terminateSession:p})}catch(T){p(T)}},kt=async()=>{try{const A=await Sn({cartId:this.cart.id,token:y.transactionIdentifier,cartClient:this.apiClient,instrumentName:this.name}),T=this.paymentSheetActionGenerator.mapCompletionResultToPaymentSheetAction(A);await m(T)}catch(A){p(A)}};await J()}),c(this,"terminateSession",d=>{var p;this.button.disabled=!1,d&&w.notify(d),f.sheetFailed(this.name,d);try{w.leaveBreadcrumb("ApplePay Session abort",{},"log"),this.session.abort(),(p=this.abortController)==null||p.abort()}catch(m){console.debug("[DEBUG] InvalidAccessError occurred during Apple Pay terminateSession")}if(d){const m=this.i18n.translate("brand.apple_pay");K(m,this.i18n)}}),c(this,"abortAndShowOutOfStockError",()=>{var d;this.session.abort(),(d=this.abortController)==null||d.abort(),Q(this.i18n)}),c(this,"getMostRecentNonNullCart",(d,p)=>d?(this.cart=d,d):p),c(this,"handleNullCart",d=>{if(!d)throw new Error("[".concat(this.name,"] no cart returned on mutation, aborting"))}),c(this,"completeShippingContactSelection",(d,p)=>{try{const m=this.getMostRecentNonNullCart(d,this.cart),{newTotal:y,newLineItems:C}=this.getNewTotalAndLineItems(m),b=Gi(m.deliveryGroups,this.i18n);w.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{errors:p,newTotal:y,newLineItems:C,newShippingMethods:b},"log"),this.session.completeShippingContactSelection({errors:p!=null?p:[],newTotal:y,newLineItems:C,newShippingMethods:b})}catch(m){this.terminateSession(m)}}),c(this,"completeShippingMethodSelection",d=>{try{this.handleNullCart(d),this.cart=d;const{newTotal:p,newLineItems:m}=this.getNewTotalAndLineItems(d);w.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{newTotal:p,newLineItems:m},"log"),this.session.completeShippingMethodSelection({newTotal:p,newLineItems:m})}catch(p){this.terminateSession(p)}}),c(this,"sessionIsCancelled",()=>this.cancelled),this.accessToken=t,this.buyerCountry=n,this.button=a,this.cart=null,this.apiClient=l,this.dataSource=s,this.i18n=i,this.merchantName=o,this.cancelled=!1,this.buyerCurrency=r,this.customerAccountEmail=u.customerAccountEmail,this.session=new ApplePaySession(Gr,Vi({shippingRequired:this.isShippingRequired,walletParams:u,buyerCurrency:r})),this.session.onvalidatemerchant=this.onvalidatemerchant,this.session.onshippingcontactselected=this.onshippingcontactselected,this.session.onshippingmethodselected=this.onshippingmethodselected,this.session.onpaymentmethodselected=this.onpaymentmethodselected,this.session.oncancel=this.oncancel,this.session.onpaymentauthorized=this.onpaymentauthorized,this.paymentSheetActionGenerator=new qi(i)}begin(){w.leaveBreadcrumb("ApplePay Session begin",{},"log"),this.abortController=er(),this.session.begin()}async applyPaymentSheetActions(t,n,r){var a;const i=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(t,r);(a=i.effects)==null||a.forEach(o=>o()),!this.sessionIsCancelled()&&await Se({paymentSheetAction:i,onProceed:n,terminateSession:this.terminateSession})}async getMerchantSession(t){const n=await new fe({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,apiVersion:"unstable"}).applePaySessionCreate(t);return JSON.parse(n)}async completePayment(t,n=void 0){w.leaveBreadcrumb("ApplePay Session completePayment",{status:t,errors:n},"log"),this.session.completePayment({status:t,errors:n}),f.authorizationComplete({instrument:this.name,measurement:tt(R.AuthorizationLatency,this.name),result:t===ApplePaySession.STATUS_SUCCESS?"success":"failure"})}getNewTotalAndLineItems(t){return{newTotal:$i(this.merchantName,t.totalAmount),newLineItems:Hi({subtotal:cn(t),discountAllocations:ji(t),deliveryGroups:t.deliveryGroups,duties:t.totalDutyAmount,taxes:t.totalTaxAmount,i18n:this.i18n,formattedRecurringTotals:Wi(this.cart.lineItems,this.i18n)})}}shouldDecelerate(t){const{checkoutUrl:n,totalAmount:r}=t;return Ke({currentCartTotal:r,initialBuyerCurrency:this.buyerCurrency})?(St({checkoutUrl:n,instrumentName:this.name,reason:"currency_changed"}),this.terminateSession(),!0):!1}get isShippingRequired(){return this.button.isShippingRequired}}const Do='\n';function rr({translate:e,logoElement:t,setAriaHidden:n}){const r=document.createElement("div");return e("buy_with_button_content",{wallet:"LOGO_PLACEHOLDER"}).split(new RegExp("(LOGO_PLACEHOLDER)")).filter(Boolean).forEach(a=>{let i;a==="LOGO_PLACEHOLDER"?i=t:(i=document.createElement("span"),i.innerText=a,n&&i.setAttribute("aria-hidden","true")),r.appendChild(i)}),r}var vt;class To extends ft{constructor(){super(),c(this,"name",g.ApplePay),c(this,"button",null),c(this,"logoElement"),z(this,vt,void 0),Y(this,vt,this.attachShadow({mode:"closed"})),this.logoElement=new DOMParser().parseFromString(Do,"image/svg+xml").documentElement}static get observedAttributes(){return["disabled"]}get merchantName(){return this.walletParams.merchantName}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}attributeChangedCallback(t,n,r){super.attributeChangedCallback(t,n,r,this.button)}async handleClick(t){if(t.preventDefault(),this.disabled||!this.button||this.button.hasAttribute("aria-disabled"))return;this.disabled=!0;const[n,r,a]=await Promise.all([this.i18n,this.dataSource,this.apiClient]);let i;try{if(i=new Po({accessToken:this.accessToken,buyerCountry:this.buyerCountry,buyerCurrency:this.buyerCurrency,button:this,i18n:n,merchantName:this.merchantName,dataSource:r,apiClient:a,walletParams:this.walletParams}),!i)throw new Error("missing ApplePaySession");i.begin(),f.sheetClicked({instrument:this.name,result:"success"}),rt(this.name)}catch(o){w.notify(o),f.sheetClicked({instrument:this.name,result:"failed"}),i==null||i.terminateSession()}}async render(){var t;const{translate:n}=await this.i18n;if(!this.button){if(this.button=ue({label:n("buy_with_button_content",{wallet:n("brand.apple_pay")})}),this.button.onclick=r=>this.handleClick(r),this.button.classList.add("apple-pay-button",ta[this.buttonTheme],pt.BUTTON),this.isCTA){const r=rr({translate:n,logoElement:this.logoElement,setAriaHidden:!0});r.classList.add("apple-pay--content"),this.button.appendChild(r)}else this.button.appendChild(this.logoElement);this.initializeShadowStyles(E(this,vt),xi),E(this,vt).appendChild(this.button),(t=this.onRendered)==null||t.call(this)}this.disabled&&(this.button.setAttribute("disabled",""),this.button.setAttribute("aria-disabled","true"))}}vt=new WeakMap;function nr(e){return function(t,n,r){const a=r.value;return r.value=function(...i){const o=a.apply(this,i);return o.eligible||console.debug("[DEBUG] ".concat(e," could not be rendered. Reason: ").concat(o.reason)),o},r}}var No=Object.defineProperty,Ro=Object.getOwnPropertyDescriptor,vn=(e,t,n,r)=>{for(var a=Ro(t,n),i=e.length-1,o;i>=0;i--)(o=e[i])&&(a=o(t,n,a)||a);return a&&No(t,n,a),a};class ar extends at{constructor(t){super(t),c(this,"companyFieldRequired"),this.companyFieldRequired=!!this.walletParams.companyRequired}static walletName(){return"apple_pay"}getWebComponentName(){return"shopify-apple-pay-button"}getWebComponentClass(){return To}getInstrumentName(){return g.ApplePay}applePayInIframe(){return typeof window>"u"||window.self!==window.top}getLoadEligibility(){return this.applePayInIframe()?{eligible:!1,reason:"cannot be loaded in an iframe"}:{eligible:!0}}getPartnerSDKEligibility(){var t,n,r,a;return typeof window>"u"||window.ApplePaySession===void 0?{eligible:!1,reason:"window or ApplePaySession is undefined"}:(n=(t=window.ApplePaySession).supportsVersion)!=null&&n.call(t,Gr)?(a=(r=window.ApplePaySession).canMakePayments)!=null&&a.call(r)?{eligible:!0}:{eligible:!1,reason:"failed SDK eligibility check"}:{eligible:!1,reason:"SDK does not meet minimum version requirement"}}}vn([nr("Apple Pay")],ar.prototype,"getLoadEligibility"),vn([nr("Apple Pay")],ar.prototype,"getPartnerSDKEligibility");const Lo=".buy-with-prime-button{width:100%;height:100%;padding:12px 10px 8px;display:flex;align-items:center;justify-content:center;gap:5px;opacity:1;border-width:0px}.buy-with-prime-button:hover:enabled{background-color:#0684eb!important}.buy-with-prime-button:focus{box-shadow:0 0 0 2px #1a98ff,inset 0 0 0 2px rgb(var(--color-background))!important;outline:none!important}.buy-with-prime-button:active,.buy-with-prime-button:hover:enabled:active{background-color:#0066cd!important;box-shadow:none!important}";class re extends Error{constructor(){super(...arguments),c(this,"name","MissingAccessTokenError")}}class ir extends Error{constructor(){super(...arguments),c(this,"name","FetchingWalletsPlatformConfigError")}}class In extends Error{constructor(){super(...arguments),c(this,"name","EmptyLineItemsWalletsPlatformConfigError")}}async function Pn({configOptionsEndpoint:e,checkoutUrl:t,sourceId:n,accessToken:r,instrument:a}){try{const i=JSON.stringify({checkout_url:t,checkout_cancel_url:window.location.href,cart_id:n}),o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":r},body:i});if(o.ok)return o.json();const s=await o.json();throw s.error?new Error(s.error):new Error("Could not fetch wallets platform configs: [".concat(o.status,"] ").concat(o.statusText))}catch(i){const{message:o}=i!=null?i:{};switch(o){case"empty_line_items":throw new In("[Fetch Pay Config][".concat(a,"] No eligible line items provided in the config request."));default:throw new ir("[Fetch Pay Config][".concat(a,"] ").concat(o))}}}const ko={[S.Checkout]:"Checkout",[S.CartAjax]:"Cart",[S.CartPage]:"Cart",[S.ProductPage]:"Product",[S.Unknown]:"Product"};var Vt;const At=class Ks extends ft{constructor(){super(...arguments),c(this,"name",g.BuyWithPrime),c(this,"button",null),c(this,"apiClientId",""),z(this,Vt,this.attachShadow({mode:"closed"}))}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async createButton(){const{translate:t}=await this.i18n,n=ue({label:t("buy_with_button_content",{wallet:t("brand.buy_with_prime")})});return n.type="button",n.className="buy-with-prime-button",this.applyEnabledStyles(n),n}applyEnabledStyles(t){t.innerHTML=qt.primeLogo,t.disabled=!1,ur(t,{"background-color":"#1A98FF",color:"#FFFFFF",cursor:"pointer"})}applyDisabledStyles(t){t.innerHTML=qt.primeLogoDark,t.disabled=!0,ur(t,{"background-color":"#C0E3FF",color:"#7292AC",cursor:"not-allowed"})}async handleClick(){var t;if(!this.button)return;const[n,r]=await Promise.all([this.i18n,this.dataSource]);let a=[];try{this.applyDisabledStyles(this.button);let i=this.walletParams;if(this.apiClientId=this.apiClientId||i.appId||"",!i.createCheckoutSessionConfig){const{cart:o,isOutOfStock:s}=await nt({element:this,instrumentName:this.name,dataSource:r});if(s){Q(n);return}if(!this.accessToken)throw new re("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");i=_({},await Pn({configOptionsEndpoint:Ks.OPTIMUS_CONFIG_REST_API_URL,checkoutUrl:o.checkoutUrl,sourceId:(t=de(o))!=null?t:"",accessToken:this.accessToken,instrument:this.name}))}i.placement=this.getPlacement(),a=this.extractSKUs(i),delete i.checkoutSupportsSplitCart,delete i.appId,window.amazon.buywithprime.initCheckout({amazonPayOptions:i}),f.sheetClicked({instrument:this.name,result:"success",webPixelMetaData:this.apiClientId?{apiClientId:this.apiClientId,skus:a,pageType:this.pageType}:void 0}),rt(this.name)}catch(i){const{name:o}=i!=null?i:{};Ks.EXPECTED_ERRORS.includes(o)||w.notify(i),f.sheetClicked({instrument:this.name,result:"failed",webPixelMetaData:this.apiClientId?{apiClientId:this.apiClientId,skus:a,pageType:this.pageType}:void 0});const{title:s,content:l}=this.getErrorCopies(o,n);gt(s,l)}finally{this.applyEnabledStyles(this.button)}}getErrorCopies(t,n){const r=n.translate("brand.buy_with_prime");switch(t){case"EmptyLineItemsWalletsPlatformConfigError":return{title:n.translate("error_dialogs.wallet.buy_with_prime.empty_line_items.title"),content:n.translate("error_dialogs.wallet.buy_with_prime.empty_line_items.content")};default:return{title:n.translate("error_dialogs.wallet.title",{wallet:r}),content:n.translate("error_dialogs.wallet.generic_error",{wallet:r})}}}extractSKUs(t){var n;return(n=t.createCheckoutSessionConfig)!=null&&n.payloadJSON?JSON.parse(t.createCheckoutSessionConfig.payloadJSON).cartDetails.lineItems.map(r=>r&&r.sku).filter(r=>r):[]}getPlacement(){return this.pageType&&ko[this.pageType]||"Other"}async render(){var t;this.button||(this.button=await this.createButton(),this.button.onclick=()=>this.handleClick(),this.button.classList.add("buy-with-prime-button"),this.getPlacement().includes("Checkout")||this.button.classList.add(pt.BUTTON),await this.initializeShadowStyles(E(this,Vt),Lo),E(this,Vt).appendChild(this.button),(t=this.onRendered)==null||t.call(this))}};Vt=new WeakMap,c(At,"OPTIMUS_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/optimus")),c(At,"EXPECTED_ERRORS",[ir.name,re.name,In.name]);let Ue=At;function Dn(e,t=3,n=1e3,r=()=>!0){const a=()=>new Promise(o=>{setTimeout(o,n)}),i=async o=>{try{return await e()}catch(s){if(o>0&&r(s))return await a(),i(o-1);throw s}};return i(t-1)}async function Oo(e){return new Promise((t,n)=>{if(document.querySelector('script[src="'.concat(e,'"]'))&&window.amazon){t();return}const r=document.createElement("script");r.src=e,r.onload=()=>{window.amazon?t():n(new Error("Amazon SDK not present after loading"))},r.onerror=()=>{n(new Wt("Error loading Amazon SDK"))},document.head.append(r)})}async function Tn({sdkUrl:e=Ve,maxRetries:t=3}){return Dn(()=>Oo(e),t,200)}const j=class be extends at{static walletName(){return"buy_with_prime"}constructor(t){super(t)}getWebComponentName(){return"shopify-buy-with-prime-button"}getInstrumentName(){return g.BuyWithPrime}getWebComponentClass(){return Ue}async loadWalletSDK(){await Tn({sdkUrl:be.SDK_URL,maxRetries:be.MAX_RETRIES}),await this.loadLogos()}async loadLogos(){await Promise.all([this.loadPrimeLogo(),this.loadPrimeLogoDark()])}async loadPrimeLogo(){be.primeLogo=(await import("./prime-logo-DoVHKBSO.js")).default}async loadPrimeLogoDark(){be.primeLogoDark=(await import("./prime-logo-dark-DJIA6J0w.js")).default}};c(j,"MAX_RETRIES",3),c(j,"SDK_URL",Ve),c(j,"primeLogo"),c(j,"primeLogoDark");let qt=j;const xo="shopify-amazon-pay-button div[role=button][slot=amazon-pay-slot][data-testid=amazon-pay-button]{border-radius:0!important}",Mo=[ir.name,re.name],Pr="amazon-pay-slot";var It;const ae=class Xs extends ft{constructor(){super(),c(this,"name",g.AmazonPay),c(this,"container",null),z(this,It,void 0),Y(this,It,this.attachShadow({mode:"closed"}))}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async handleClick(t){var n;const[r,a]=await Promise.all([this.i18n,this.dataSource]);try{const{cart:i,isOutOfStock:o}=await nt({element:this,instrumentName:this.name,dataSource:a});if(o){Q(r);return}const{totalAmount:{amount:s},checkoutUrl:l}=i;let u=this.walletParams;if(!u.createCheckoutSessionConfig){if(!this.accessToken)throw new re("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");u=P(_({},await Pn({configOptionsEndpoint:Xs.CV2_CONFIG_REST_API_URL,checkoutUrl:l,sourceId:(n=de(i))!=null?n:"",accessToken:this.accessToken,instrument:this.name})),{placement:this.pageType===S.ProductPage?"Product":"Cart"})}delete u.appId,t.initCheckout(_(_({},u),Number(s)!==0&&{estimatedOrderAmount:{amount:s,currencyCode:this.buyerCurrency}})),f.sheetClicked({instrument:this.name,result:"success"}),rt(this.name)}catch(i){const{name:o}=i!=null?i:{};Mo.includes(o)||w.notify(i),f.sheetClicked({instrument:this.name,result:"failed"});const s=r.translate("brand.amazon_pay");K(s,r)}}createContainer({containerID:t,height:n}){const r=document.createElement("div");return r.id=t,r.style.display="flex",n!=null&&(r.style.height="".concat(n,"px")),r.slot=Pr,r.setAttribute("data-testid","amazon-pay-button"),r}async render(){var t;try{if(!this.container){const n=document.createElement("slot");n.name=Pr;const r=document.createElement("style");r.textContent=xo,this.appendChild(r),await this.initializeShadowStyles(E(this,It));const a=await this.containerInstanceNumber,i="AcceleratedCheckoutAmazonPayButtonContainer".concat(this.pageType).concat(a),o=document.createElement("div");o.classList.add(pt.BUTTON),o.style.overflow="hidden",o.appendChild(n),E(this,It).appendChild(o);const s=Oe(o);this.container=this.createContainer({containerID:i,height:s}),this.appendChild(this.container);const l=window.amazon.Pay.renderButton("#".concat(i),P(_({},this.walletParams),{placement:this.pageType===S.ProductPage?"Product":"Cart"}));l==null||l.onClick(()=>this.handleClick(l)),(t=this.onRendered)==null||t.call(this)}}catch(n){w.notify(n)}}};It=new WeakMap,c(ae,"CV2_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/amazon_pay"));let Be=ae;const Ct=class Js extends at{static walletName(){return"amazon_pay"}constructor(t){super(t)}getWebComponentName(){return"shopify-amazon-pay-button"}getInstrumentName(){return g.AmazonPay}getWebComponentClass(){return Be}async loadWalletSDK(){await Tn({sdkUrl:Js.SDK_URL,maxRetries:Js.MAX_RETRIES})}};c(Ct,"MAX_RETRIES",3),c(Ct,"SDK_URL",Ve);let $e=Ct;var ve={Purple:{D0:"#4524DB",D1:"#30368D",D2:"#1C234C",L0:"#6445ED",L1:"#9C83F8",L2:"#EEEAFF",L3:"#F7F5FF",Primary:"#5433EB",PrimaryLight:"#DBD1FF"},Grayscale:{Black:"#000000",D0:"#666666",D1:"#404040",D2:"#121212",D3:"#0B0B0C",D2D:"#2A2A2A",PrimaryLight:"#707070",L1:"#A8A8A7",L2:"#CBCBCA",L2L:"#E3E3E3",L3:"#F0F0F0",L4:"#F2F4F5",White:"#FFFFFF"},Green:{D1:"#008552",D2:"#004839",L1:"#BAEBCB",L2:"#D2F2DE",L3:"#E4F6EB",Primary:"#92D08D"},Poppy:{D0:"#F05D38",D1:"#D92A0F",D2:"#832711",L1:"#FFD2C2",L2:"#FFECE9",Primary:"#FF967D"},Ochre:{D0:"#F8DB67",D1:"#E3BE2B",D2:"#C29D05",D4:"#443600",L1:"#FFF4CB",L2:"#FFF9E2",Primary:"#FFEC9F"},Brand:{Aqua:"#8DC0C6",Lime:"#C7DE00",Magenta:"#D354FF",Olive:"#8B8F01",Sage:"#D8E59D",Sand:"#F4F4ED",Violet:"#A327C2"}},Fo={0:0,none:0,xxxs:2,xxs:4,xs:8,"xs-s":12,s:16,gutter:20,m:24,l:32,section:36,xl:40,xxl:48,xxxl:64,auto:"auto"},Uo=class extends HTMLElement{static get observedAttributes(){return["disabled"]}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this._updateButton()}attributeChangedCallback(){this._updateButton()}_updateButton(){var e;let t=this.shadowRoot;t&&(t.innerHTML=$o,this.hasAttribute("disabled")&&((e=this.shadowRoot.querySelector("button"))==null||e.setAttribute("disabled","")))}};function Bo(){window.customElements&&(customElements.get("gravity-button")||customElements.define("gravity-button",Uo))}var $o="\n\n\n\n');const Ho=".button-content{display:flex;align-items:center;justify-content:center;width:100%;height:100%;gap:3px;white-space:nowrap;container-type:inline-size;container-name:bc}.ShopPromise>.separator{margin:0 8px}@container bc (width <= 338px){.ShopPromise{display:none!important}}gravity-button{display:block}",Go='.accelerated-checkout-button{--gravity-button-height: clamp( 25px, var(--shopify-accelerated-checkout-button-block-size, 44px), 55px );--gravity-button-min-height: clamp( 25px, var(--shopify-accelerated-checkout-button-block-size, 44px), 55px );--gravity-button-border-radius: var( --shopify-accelerated-checkout-button-border-radius, 0px );--gravity-button-padding: 0px 10px;--gravity-button-width: 100%}:host([page-type="cart_page"]) .accelerated-checkout-button{--gravity-button-height: 100%;--gravity-button-min-height: 100%;--gravity-button-border-radius: var( --shopify-accelerated-checkout-button-border-radius, 4px );--gravity-button-width: 100%}';class Nn extends Error{constructor(){const t="DeliveryEstimatesResponseIsNullError";super("deliveryEstimates is null or undefined"),this.name=t}}class Ie extends Error{constructor(){const t="DeliveryPromiseAPIClientError";super("window.Shopify.ShopPromise.deliveryPromiseAPIClient is undefined"),this.name=t}}const zo=15,qo=200;class Vo{constructor(t){c(this,"storefrontAPIToken"),this.storefrontAPIToken=t}async fetchDeliveryPromise({variant:t,postalCode:n,defaultPostalCode:r,sellingPlanId:a}){const i=await Dn(async()=>this.fetchDeliveryOptions(t,n,r,a),zo,qo,o=>o instanceof Ie).catch(o=>{if(o instanceof Ie)throw o;return null});if(!i)throw new Nn;return i}async fetchDeliveryOptions(t,n,r,a){var i,o;const s={variantId:t,sellingPlanId:a,postalCode:n||r,isPostalCodeOverride:!!n},l=(o=(i=window==null?void 0:window.Shopify)==null?void 0:i.ShopPromise)==null?void 0:o.deliveryPromiseAPIClient;if(!l)throw new Ie;return l(s,this.storefrontAPIToken)}}function jo(e,t){switch(e){case 0:return(t==null?void 0:t.translate("shop_promise_delivery.same_day"))||null;case 1:return(t==null?void 0:t.translate("shop_promise_delivery.next_day"))||null;case 2:return(t==null?void 0:t.translate("shop_promise_delivery.two_day"))||null;default:return null}}const Wo="delivery_promise_default_address",Yo="delivery_promise_postal_code";class Ko extends pe{constructor(){super(...arguments),c(this,"lastFetchedProductVariantId"),c(this,"lastFetchSellingPlan"),c(this,"fetching",!1),c(this,"i18n",null),c(this,"daysToDelivery"),c(this,"formObserver",null)}async connectedCallback(){this.formObserver=new Xr(this,({variantId:t,sellingPlanId:n})=>{this.fetchDeliveryPromise(t,n)}),this.formObserver.setupMutationObservers()}setTranslations(t){this.i18n=t,this.render()}get postalCode(){try{return JSON.parse(Gt(Yo)||"null")||null}catch(t){return null}}get defaultDeliveryAddress(){try{return JSON.parse(Gt(Wo)||"null")}catch(t){return null}}async fetchDeliveryPromise(t,n){var r,a,i,o;if(!(!t||!this.accessToken)&&!(t===this.lastFetchedProductVariantId&&n===this.lastFetchSellingPlan))try{this.lastFetchedProductVariantId=t,this.lastFetchSellingPlan=n;const s=((r=this.defaultDeliveryAddress)==null?void 0:r.zip)||"",l=await new Vo(this.accessToken).fetchDeliveryPromise({variant:t,postalCode:this.postalCode||"",defaultPostalCode:s,sellingPlanId:n||""}),u=Ze(this),d=(i=(a=l==null?void 0:l.selectedShippingOption)==null?void 0:a.brandedPromise)==null?void 0:i.handle;if((u==null?void 0:u.sellingPlanId)!==n||(u==null?void 0:u.variantId)!==t||d!=="shop_promise")return;this.daysToDelivery=(o=l==null?void 0:l.selectedShippingOption)==null?void 0:o.maxCalendarDaysToDelivery,this.render()}catch(s){s instanceof Nn&&(this.daysToDelivery=null)}}render(){const t=jo(this.daysToDelivery,this.i18n);this.classList.add("ShopPromise"),this.innerHTML=t?'|'.concat(t,""):""}}var dt;class Qo extends ft{constructor(){super(),c(this,"name",g.ShopPay),c(this,"button",null),c(this,"shopPromiseProductPageContent",null),c(this,"shopPromiseEligible",!1),z(this,dt,void 0),Y(this,dt,this.attachShadow({mode:"closed"}))}static get observedAttributes(){return["disabled"]}connectedCallback(){this.shopPromiseEligible=Vr(),this.cleanupOnFailure(async()=>{Bo(),await this.render()},this.name)}attributeChangedCallback(t,n,r){super.attributeChangedCallback(t,n,r,this.button)}async addButtonContent(){if(!this.button)return;let t;const n=await this.i18n,r=new DOMParser().parseFromString(Ln.shopPayLogoElement,"image/svg+xml").documentElement;this.isCTA?t=rr({translate:n.translate,logoElement:r,setAriaHidden:!1}):(t=document.createElement("div"),t.appendChild(r)),t.classList.add("button-content"),this.shopPromiseEligible&&!this.shopPromiseProductPageContent&&(this.shopPromiseProductPageContent=document.createElement("shop-promise-product-page-content"),this.shopPromiseProductPageContent.setTranslations(n),this.shopPromiseProductPageContent.setAttribute("access-token",this.accessToken||""),t.appendChild(this.shopPromiseProductPageContent)),this.button.appendChild(t)}getShopPayBehavior(){return this.pageType===S.ProductPage?"force_shop_pay_product":this.pageType===S.CartPage?"force_shop_pay_cart":"force_shop_pay"}async handleClick(t){if(t.preventDefault(),this.disabled||!this.button||this.button.getAttribute("disabled"))return;this.disabled=!0;const[n,r]=await Promise.all([this.i18n,this.dataSource]);try{const{isOutOfStock:a,cart:i}=await nt({element:this,instrumentName:g.ShopPay,dataSource:r});if(f.sheetClicked({instrument:this.name,checkoutToken:de(i),result:"success"}),a){Q(n);return}rt(this.name),yt(i.checkoutUrl,this.getShopPayBehavior())}catch(a){w.notify(new Jo("An error occurred when attempting to a cart using the Shop Pay Button. Details: ".concat(a))),f.sheetClicked({instrument:this.name,result:"failed"}),gt(n.translate("error_dialogs.checkout.title"),n.translate("error_dialogs.checkout.generic_error"))}}async render(){if(E(this,dt).innerHTML)return;this.button||(this.button=document.createElement("gravity-button"));const t=document.createElement("style");t.innerHTML=[Zr,Go,Ho].join("\n"),E(this,dt).appendChild(t),await this.addButtonContent(),this.disabled&&this.button.setAttribute("disabled",""),this.button.setAttribute("aria-hidden","true"),this.button.classList.add(pt.BUTTON),this.button.onclick=n=>this.handleClick(n),E(this,dt).appendChild(this.button),this.onRendered()}}dt=new WeakMap,et("shop-promise-product-page-content",Ko);class Jo extends Error{constructor(){super(...arguments),c(this,"name","ShopPayButtonError")}}var Xo=Object.defineProperty,Zo=Object.getOwnPropertyDescriptor,ts=(e,t,n,r)=>{for(var a=Zo(t,n),i=e.length-1,o;i>=0;i--)(o=e[i])&&(a=o(t,n,a)||a);return a&&Xo(t,n,a),a},Pt;const Rn=(Pt=class extends at{static walletName(){return"shop_pay"}constructor(e){super(e)}getWebComponentName(){return"shop-pay-wallet-button"}getWebComponentClass(){return Qo}getInstrumentName(){return g.ShopPay}async loadWalletSDK(){await this.loadLogo()}getLoadEligibility(){return{eligible:!0}}async loadLogo(){Pt.shopPayLogoElement=(await import("./shop-pay-logo-CYhOC7ye.js")).default}},c(Pt,"shopPayLogoElement"),Pt);ts([nr("Shop Pay")],Rn.prototype,"getLoadEligibility");let Ln=Rn;const es=".button{display:flex;justify-content:center;align-items:center;width:100%;border:none}.button:hover:not(:disabled){filter:brightness(92%);cursor:pointer}.button:disabled{opacity:.5;cursor:not-allowed}.logo-only>svg{width:50px}.dark{background:#000;color:#fff}.dark svg{fill:#fff}.light{background:#fff;outline:1px solid #3c4043;color:#000}.light svg{fill:#0000008c}.content{display:flex;justify-content:center;align-items:center;white-space:pre}";function Pe({cart:e,i18n:t}){const n=cn(e),r={label:t.translate("order_summary.subtotal"),type:"SUBTOTAL",price:ut(n.amount)},a=on({deliveryGroups:e.deliveryGroups,i18n:t}).map(s=>rs({lineItem:s,type:"LINE_ITEM"})),i=ns(e,t),o=[r,...a,...i];if(e.totalDutyAmount){const s={label:t.translate("order_summary.duties"),type:"LINE_ITEM",price:ut(e.totalDutyAmount.amount)};o.push(s)}if(e.totalTaxAmount){const s={label:t.translate("order_summary.taxes"),type:"TAX",price:ut(e.totalTaxAmount.amount)};o.push(s)}return{totalPrice:e.totalAmount.amount,currencyCode:e.totalAmount.currencyCode,totalPriceStatus:"ESTIMATED",totalPriceLabel:t.translate("order_summary.total"),displayItems:o}}function rs({lineItem:e,type:t,status:n="FINAL"}){return{label:e.label,type:t,price:e.amount,status:n}}function ns(e,t){return[...e.lineItems.flatMap(n=>n.discountAllocations),...e.discountAllocations].flatMap(n=>{var r;const a=(r=n.title)!=null?r:n.code;return{label:a!=null?a:t.translate("order_summary.discount"),type:"LINE_ITEM",price:"-".concat(ut(Number(n.discountedAmount.amount)))}})}const kn=["PAYMENT_AUTHORIZATION"],as=kn.concat(["SHIPPING_ADDRESS","SHIPPING_OPTION"]),is=["PAN_ONLY"];function os({walletParams:e,isShippingRequired:t,hasSellingPlan:n,i18n:r,buyerCurrency:a}){const i={totalPrice:"0.01",currencyCode:a,totalPriceStatus:"ESTIMATED",totalPriceLabel:r.translate("order_summary.total"),displayItems:[{label:r.translate("order_summary.subtotal"),type:"SUBTOTAL",price:"0.01"}]},o=P(_({},e.paymentData),{shippingAddressRequired:t,shippingOptionRequired:t,transactionInfo:i});return t||delete o.shippingAddressParameters,o.callbackIntents=t?as:kn,n&&ss(o),o}function ss(e){e.allowedPaymentMethods.forEach(t=>{t.parameters.allowedAuthMethods=t.parameters.allowedAuthMethods.filter(n=>is.includes(n))})}class ls extends ln{constructor(t){super(),c(this,"brandName"),c(this,"completionResult"),this.i18n=t,this.brandName=this.i18n.translate("brand.google_pay"),this.completionResult=void 0}mapMutationResultToPaymentSheetAction(t){const n=this.mapCustomValidationFunctionErrorToAction(t.errors);if(n)return n;const r=this.getErrorActions(),a=t.errors,i=this.getUnhandledErrors(a,r);i.forEach(s=>{w.notify(new sn("[".concat(g.GooglePay,"] mutation result error not handled: ").concat(s)))});const{firstPaymentSheetAction:o}=this.getMergedPaymentSheetAction({result:t,errorActions:r});return o||(i.length>0?{action:"abort"}:{action:"update",errors:[]})}mapCompletionResultToPaymentSheetAction(t){if(!t.data)throw new Error("[".concat(g.GooglePay,"] completion returned null result"));switch(this.completionResult=t,t.data.__typename){case"SubmitSuccess":return{action:"complete",redirectUrl:t.data.redirectUrl};case"SubmitAlreadyAccepted":case"SubmitThrottled":case"SubmitFailed":{const n=this.mapCustomValidationFunctionErrorToAction(t.errors);if(n)return n;const r=this.getErrorActions(),a=t.errors;this.getUnhandledErrors(a,r).forEach(o=>{w.notify(new Error("[".concat(g.GooglePay,"] completion result error not handled: ").concat(o)))});const{prioritizedPaymentSheetAction:i}=this.getMergedPaymentSheetAction({result:t,errorActions:r});return i||(K(this.brandName,this.i18n),{action:"abort"})}default:throw new Error("[".concat(g.GooglePay,"] unknown completion result type: ").concat(t.data.__typename))}}getErrorActions(){return[{errors:[h.CaptchaCompletionRequired],generateAction:()=>{var t,n,r,a;const i=(n=(t=this.completionResult)==null?void 0:t.data)==null?void 0:n.__typename;return i==="SubmitFailed"?{action:"decelerate",redirectUrl:(a=(r=this.completionResult)==null?void 0:r.data)==null?void 0:a.checkoutUrl,reason:Yr(h.CaptchaCompletionRequired)}:{action:"abort",effects:[()=>{w.notify(new Error("[".concat(g.GooglePay,"] unexpected ").concat(h.CaptchaCompletionRequired," received in ").concat(i," response, aborting")))}]}}},{errors:[h.InvalidLanguage],generateAction:()=>({action:"abort",effects:[()=>{w.notify(new Error("[".concat(g.GooglePay,"] mutation provided invalid language, aborting")))},()=>K(this.brandName,this.i18n)]})},{errors:[h.InvalidCountry],generateAction:()=>({action:"abort",effects:[()=>{w.notify(new Error("[".concat(g.GooglePay,"] mutation provided invalid country, aborting")))},()=>K(this.brandName,this.i18n)]})},{errors:[h.MissingCartId],generateAction:()=>({action:"abort",effects:[()=>{w.notify(new Error("[".concat(g.GooglePay,"] mutation provided invalid cart ID, aborting")))},()=>K(this.brandName,this.i18n)]})},{errors:[h.UnacceptablePaymentsAmount,h.NewTaxMustBeAccepted,h.MerchandiseExpectedPriceMismatch,h.DeliveryLineChanged,h.DeliveryLocalPickupLineChanged,...jr],generateAction:()=>({action:"abort",effects:[()=>K(this.brandName,this.i18n)]})},{errors:Wr,generateAction:()=>({action:"abort",effects:[()=>Q(this.i18n)]})},{errors:[h.DeliveryNoStrategyAvailable,h.DeliveryNoLocalPickupStrategyAvailable,h.DeliveryNotAvailable],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_UNSERVICEABLE",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.shipping_address")}]})},{errors:[h.NoDeliveryGroupSelected],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_OPTION_INVALID",intent:"SHIPPING_OPTION",message:this.i18n.translate("errors.missing.shipping_option")}]})},{errors:[h.BuyerIdentityEmailDomainInvalid,h.BuyerIdentityEmailNotExpectedPattern,h.BuyerIdentityEmailInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.email")}]})},{errors:[h.BuyerIdentityEmailRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.email")}]})},{errors:[h.DeliveryAddress2Required,h.DeliveryAddress2AddressFieldRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address2")}]})},{errors:[h.DeliveryAddress2Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address2")}]})},{errors:[h.DeliveryCityAddressFieldRequired,h.DeliveryCityRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.city")}]})},{errors:[h.DeliveryCityInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.city")}]})},{errors:[h.DeliveryZoneRequiredForCountry],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.zone")}]})},{errors:[h.DeliveryZoneNotFound],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.zone")}]})},{errors:[h.DeliveryPostalCodeRequired,h.DeliveryPostalCodeAddressFieldRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.postal_code")}]})},{errors:[h.DeliveryPostalCodeInvalid,h.DeliveryInvalidPostalCodeForZone,h.DeliveryInvalidPostalCodeForCountry,h.DeliveryZipInvalidForCountry],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:[h.DeliveryPhoneNumberRequired],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.phone_number")}]})},{errors:[h.DeliveryPhoneNumberInvalid,h.BuyerIdentityInvalidPhone,h.DeliveryPhoneDoesNotMatchExpectedPattern],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.phone_number")}]})},{errors:[h.BuyerIdentityInvalidCountry,h.DeliveryCountryInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.country")}]})},{errors:[h.DeliveryFirstNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.first_name")}]})},{errors:[h.DeliveryFirstNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.first_name")}]})},{errors:[h.DeliveryLastNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.last_name")}]})},{errors:[h.DeliveryLastNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.last_name")}]})},{errors:[h.DeliveryAddress1Required],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address1")}]})},{errors:[h.DeliveryAddress1Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address1")}]})},{errors:[h.DeliveryLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.last_name")}]})},{errors:[h.DeliveryCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.city")}]})},{errors:[h.DeliveryAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address1")}]})},{errors:[h.DeliveryAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address2")}]})},{errors:[h.DeliveryPostalCodeContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.postal_code")}]})},{errors:[h.DeliveryAddress1TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address1")}]})},{errors:[h.DeliveryAddress2TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address2")}]})},{errors:[h.DeliveryFirstNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.first_name")}]})},{errors:[h.DeliveryLastNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.last_name")}]})},{errors:[h.DeliveryCityTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.city")}]})},{errors:[h.DeliveryFirstNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.first_name")}]})},{errors:[h.DeliveryLastNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.last_name")}]})},{errors:[h.DeliveryAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address1")}]})},{errors:[h.DeliveryAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address2")}]})},{errors:[h.DeliveryCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.city")}]})},{errors:[h.DeliveryFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.first_name")}]})},{errors:[h.DeliveryLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.last_name")}]})},{errors:[h.InvalidPaymentGooglePayBillingAddress],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.billing_address")}]})},{errors:[h.UnsupportedGooglePayPaymentMethod],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.payment_method")}]})}]}mapCustomValidationFunctionErrorToAction(t){const n=t.find(r=>typeof r=="object"&&(r==null?void 0:r.code)===te);return n?(w.notify(new Error("[".concat(g.GooglePay,"] custom validation function error: ").concat(t))),Ye(this.i18n.translate("error_dialogs.wallet.title",{wallet:this.brandName}),n.message),{action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"PAYMENT_AUTHORIZATION",message:this.i18n.translate("paymentSheet.errors.unknown")}]}):null}}function cs({deliveryGroups:e,i18n:t}){var n;const r=nn(an(e),t),a=r.map(o=>({id:o.handle,label:o.title||"",description:o.estimatedCost?"".concat(o.estimatedCost.amount.toString()," ").concat(o.estimatedCost.currencyCode):""})),i=(n=r.find(o=>{var s;return o.handle.includes(((s=e[0].selectedDeliveryOption)==null?void 0:s.handle)||"")}))==null?void 0:n.handle;return{shippingOptions:a,defaultSelectedOptionId:i}}function De(e){let t=e.administrativeArea,n=e.locality;e.countryCode==="AE"&&(n=e.administrativeArea,e.administrativeArea in Dr&&(t=Dr[e.administrativeArea]));let r,a;if(e.name){const[i,...o]=(e.name||"").split(" ");o.length===0?a=i:a=o.join(" "),r=i}return{firstName:r,lastName:a,address1:e.address1,address2:e.address2,city:n,province:t,country:e.countryCode,phone:e.phoneNumber,zip:e.postalCode}}const Dr={"\u0623\u0628\u0648 \u0638\u0628\u064A":"AZ","\u0625\u0645\u0627\u0631\u0629 \u0627\u0644\u0634\u0627\u0631\u0642\u0629\u0651":"SH",\u0627\u0644\u0641\u062C\u064A\u0631\u0629:"FU",\u0639\u062C\u0645\u0627\u0646:"AJ","\u0631\u0623\u0633 \u0627\u0644\u062E\u064A\u0645\u0629":"RK","\u0623\u0645 \u0627\u0644\u0642\u064A\u0648\u064A\u0646":"UQ",\u062F\u0628\u064A:"DU"},ds=27e3;class us extends Error{constructor(t){super(t),this.name="GooglePayError"}}var jt,W;class hs{constructor({walletParams:t,isShippingRequired:n,hasSellingPlan:r,dataSource:a,button:i,i18n:o,cartClient:s,buyerCurrency:l,abortController:u}){c(this,"name",g.GooglePay),c(this,"walletParams"),c(this,"cart",null),c(this,"isShippingRequired"),c(this,"hasSellingPlan"),c(this,"dataSource"),c(this,"button"),c(this,"paymentsClient"),c(this,"i18n"),c(this,"actionGenerator"),c(this,"cartClient"),c(this,"initialBuyerCurrency"),z(this,jt,void 0),z(this,W,void 0),c(this,"onPaymentDataChanged",async p=>{var m;const{callbackTrigger:y,shippingAddress:C,shippingOptionData:b}=p,{translate:N}=this.i18n;switch(y){case"INITIALIZE":{if(!this.cart)try{const{cart:U}=await nt({element:this.button,instrumentName:g.GooglePay,dataSource:this.dataSource});this.cart=U,f.sheetClicked({instrument:this.name,result:"success"})}catch(U){return f.sheetClicked({instrument:this.name,result:"failed"}),this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}return C?this.handleShippingAddressChange(this.cart.id,C):{newTransactionInfo:Pe({cart:this.cart,i18n:this.i18n})}}case"SHIPPING_ADDRESS":return this.cart?C?this.handleShippingAddressChange(this.cart.id,C):{newTransactionInfo:Pe({cart:this.cart,i18n:this.i18n})}:this.showPaymentDataRequestError({intent:y});case"SHIPPING_OPTION":{if(!this.cart)return this.showPaymentDataRequestError({intent:y});if(!b||!b.id)return{error:{reason:"SHIPPING_OPTION_INVALID",message:N("shipping_methods.choose_delivery_strategy"),intent:"SHIPPING_OPTION"}};const U=En({deliveryGroups:this.cart.deliveryGroups,instrumentName:g.GooglePay,selectedDeliveryOptionHandles:b.id.split(",")}),J=await Cn({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:g.GooglePay,selectedDeliveryOptions:U,abortSignal:(m=E(this,W))==null?void 0:m.signal});return J.data?(this.cart=J.data,this.handlePaymentDataRequestUpdate({result:J,intent:y})):this.showPaymentDataRequestError({intent:y})}default:return this.logException("Payment data changed callback returned unexpected intent: ".concat(y),{severity:"warning"}),this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}}),c(this,"onPaymentAuthorized",async p=>{var m,y,C;f.authorizationAttempt(this.name),Yt(R.AuthorizationLatency,this.name);const b=(m=p.paymentMethodData.info)==null?void 0:m.billingAddress,N=p.shippingAddress,{signature:U,signedMessage:J,protocolVersion:Lt}=JSON.parse(p.paymentMethodData.tokenizationData.token);if(!b)return this.handlePaymentAuthorizationError();if(this.isShippingRequired&&!N)return this.handlePaymentAuthorizationError();const kt=async()=>{var T,M;const k=(T=E(this,jt))!=null?T:p.email,$=this.isShippingRequired?{validateAddress:!0,streetAddress:De(N)}:{};return await Et(_({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:this.name,emailAddress:k,abortSignal:(M=E(this,W))==null?void 0:M.signal},$))},A=async()=>{var T;const M=De(b);return await tr({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{googlePayWalletContent:{billingAddress:M,signature:U,signedMessage:J,protocolVersion:Lt}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:M,cartClient:this.cartClient,instrumentName:this.name,hasSellingPlan:this.hasSellingPlan,abortSignal:(T=E(this,W))==null?void 0:T.signal})};try{const T=setTimeout(()=>{var Qs;(Qs=E(this,W))==null||Qs.abort("Google Pay Timeout")},ds),M=await kt(),k=this.handleIntermediatePaymentAuthorizationResult(M);if(k)return k;const $=await A(),Kt=this.handleIntermediatePaymentAuthorizationResult($);if(Kt)return Kt;if(clearTimeout(T),(C=(y=E(this,W))==null?void 0:y.signal)!=null&&C.aborted)return this.handlePaymentAuthorizationError();const nl=await Sn({cartId:this.cart.id,token:U,cartClient:this.cartClient,instrumentName:this.name}),rl=this.actionGenerator.mapCompletionResultToPaymentSheetAction(nl);return this.handlePaymentAuthorizationResult(rl)}catch(T){const{message:M}=T;return this.logException(M),this.handlePaymentAuthorizationError()}}),c(this,"handlePaymentAuthorizationResult",async p=>{var m,y;switch((m=p.effects)==null||m.forEach(C=>C()),p.action){case"complete":return this.emitAuthorizationCompleteMetric("success"),yt(p.redirectUrl),{transactionState:"SUCCESS"};case"show_error":return this.handlePaymentAuthorizationError({error:(y=p.errors)==null?void 0:y[0]});case"decelerate":return St({checkoutUrl:p.redirectUrl,instrumentName:this.name,reason:p.reason}),this.emitAuthorizationCompleteMetric("failure"),{transactionState:"SUCCESS"};case"abort":default:return this.emitAuthorizationCompleteMetric("failure"),{transactionState:"SUCCESS"}}}),this.walletParams=t,this.isShippingRequired=n,this.hasSellingPlan=r,this.dataSource=a,this.button=i,this.i18n=o,this.cartClient=s,this.initialBuyerCurrency=l,Y(this,jt,t.customerAccountEmail),Y(this,W,u);const d={environment:this.walletParams.environment,merchantInfo:this.walletParams.paymentData.merchantInfo,paymentDataCallbacks:{onPaymentDataChanged:this.isShippingRequired?this.onPaymentDataChanged:void 0,onPaymentAuthorized:this.onPaymentAuthorized}};this.paymentsClient=new window.google.payments.api.PaymentsClient(d),this.actionGenerator=new ls(this.i18n)}async handleClick(){if(!this.isShippingRequired)throw new Wt("Google Pay checkout started for digital cart");const t=os({walletParams:this.walletParams,isShippingRequired:this.isShippingRequired,hasSellingPlan:this.hasSellingPlan,i18n:this.i18n,buyerCurrency:this.initialBuyerCurrency});await this.paymentsClient.loadPaymentData(t)}showPaymentDataRequestError({error:t,intent:n="SHIPPING_ADDRESS"}={}){return t?{error:t}:{error:{intent:n,reason:"OTHER_ERROR",message:this.i18n.translate("error_dialogs.wallet.generic_error",{wallet:this.i18n.translate("brand.google_pay")})}}}handlePaymentAuthorizationError({error:t}={}){return this.emitAuthorizationCompleteMetric("failure"),_({transactionState:"ERROR"},this.showPaymentDataRequestError({error:t,intent:"PAYMENT_AUTHORIZATION"}))}handlePaymentDataRequestUpdate({result:t,intent:n}){var r,a;const i=this.actionGenerator.mapMutationResultToPaymentSheetAction(t);switch(i.action){case"update":{const o=i,{data:s}=t;if(!s)return this.showPaymentDataRequestError({intent:n});const{checkoutUrl:l,lineItems:u}=s;return Re(u)?(St({checkoutUrl:l,instrumentName:this.name,reason:"stock_problem"}),this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:"",intent:"OFFER"}})):this.isShippingRequired&&s.deliveryGroups.length===0?this.showPaymentDataRequestError({error:{reason:"SHIPPING_ADDRESS_INVALID",message:this.i18n.translate("errors.address_unserviceable",{shopName:this.walletParams.paymentData.merchantInfo.merchantName}),intent:"SHIPPING_ADDRESS"}}):{newTransactionInfo:Pe({cart:s,i18n:this.i18n}),newShippingOptionParameters:this.isShippingRequired?cs({deliveryGroups:s.deliveryGroups,i18n:this.i18n}):void 0,error:(r=o.errors)==null?void 0:r[0]}}case"show_error":return{error:(a=i.errors)==null?void 0:a[0]};case"abort":return this.showPaymentDataRequestError({intent:n});default:return this.logException("Payment sheet update returned unexpected action (see request tab for details)",{metadata:{request:{action:i.action,intent:n}}}),this.showPaymentDataRequestError({intent:n})}}handleIntermediatePaymentAuthorizationResult(t){var n,r,a,i;if(Re((r=(n=t.data)==null?void 0:n.lineItems)!=null?r:[]))return Q(this.i18n),{transactionState:"SUCCESS"};const o=this.actionGenerator.mapMutationResultToPaymentSheetAction(t);if(((a=t.errors)==null?void 0:a.length)>0){const s=o;if(s.action==="show_error")return this.handlePaymentAuthorizationError({error:(i=s.errors)==null?void 0:i[0]})}}handleCurrencyChange(t,n){Ke({currentCartTotal:n,initialBuyerCurrency:this.initialBuyerCurrency})&&St({checkoutUrl:t,instrumentName:this.name,reason:"currency_changed"})}async handleShippingAddressChange(t,n){var r;const a=await Et({cartClient:this.cartClient,cartId:t,streetAddress:n?De(n):{},instrumentName:g.GooglePay,abortSignal:(r=E(this,W))==null?void 0:r.signal});return a.data?(this.cart=a.data,this.handleCurrencyChange(this.cart.checkoutUrl,this.cart.totalAmount),this.handlePaymentDataRequestUpdate({result:a,intent:"SHIPPING_ADDRESS"})):this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}logException(t,{severity:n,metadata:r}={}){w.notify(new us(t),{severity:n!=null?n:"error",metadata:r})}emitAuthorizationCompleteMetric(t){f.authorizationComplete({instrument:this.name,measurement:tt(R.AuthorizationLatency,this.name),result:t})}}jt=new WeakMap,W=new WeakMap;const ps='\n',ms={LIGHT:"light",DARK:"dark"};var Dt;class ys extends ft{constructor(){super(),c(this,"name",g.GooglePay),c(this,"paymentsClient",null),c(this,"button",null),z(this,Dt,void 0),c(this,"handleClick",async()=>{if(this.disabled)return;this.disabled=!0;const t=er();try{await this.createPaymentsClient(t),await this.paymentsClient.handleClick(),rt(this.name)}catch(n){if(this.disabled=!1,n.statusCode==="CANCELED"){t==null||t.abort("Payment sheet cancelled"),f.sheetCancelled(g.GooglePay);return}t==null||t.abort("Payment sheet failure"),w.notify(n),f.sheetClicked({instrument:this.name,result:"failed"});const r=await this.i18n,a=r.translate("brand.google_pay");K(a,r)}}),Y(this,Dt,this.attachShadow({mode:"closed"}))}static get observedAttributes(){return["disabled"]}attributeChangedCallback(t,n,r){super.attributeChangedCallback(t,n,r,this.button)}async connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async createPaymentsClient(t){this.paymentsClient=new hs({walletParams:this.walletParams,isShippingRequired:this.isShippingRequired,hasSellingPlan:this.hasSellingPlan,dataSource:await this.dataSource,button:this,cartClient:await this.apiClient,i18n:await this.i18n,buyerCurrency:this.buyerCurrency,abortController:t})}async render(){if(this.button)return;await this.initializeShadowStyles(E(this,Dt),es);const{translate:t}=await this.i18n,n=ue({label:t("buy_with_button_content",{wallet:t("brand.google_pay")})});this.disabled&&n.setAttribute("disabled",""),n.classList.add("button",pt.BUTTON,ms[this.buttonTheme]),n.onclick=this.handleClick,await this.renderButtonContent(n,t),this.button=n,E(this,Dt).appendChild(n),this.onRendered()}async renderButtonContent(t,n){const r=new DOMParser().parseFromString(ps,"image/svg+xml").documentElement;if(t.style.font=window.getComputedStyle(this).font,this.isCTA){const a=rr({translate:n,logoElement:r,setAriaHidden:!0});a.classList.add("content"),t.appendChild(a)}else t.classList.add("logo-only"),t.appendChild(r)}}Dt=new WeakMap;const lt=class Ws extends at{static walletName(){return"google_pay"}constructor(t){super(t)}getWebComponentName(){return"shopify-google-pay-button"}getInstrumentName(){return g.GooglePay}getWebComponentClass(){return ys}async loadWalletSDK(){if(Ws.googlePaySDKPromise)return Ws.googlePaySDKPromise;const t=document.createElement("script");return t.setAttribute("src",this.walletParams.sdkUrl),Ws.googlePaySDKPromise=new Promise((n,r)=>{t.onload=()=>n(),t.onerror=a=>{document.body.removeChild(t),r(a)},document.body.appendChild(t)}),Ws.googlePaySDKPromise}getLoadEligibility(){const t=this.walletParams.expiresAt*1e3;return Bt()<=t?{eligible:!0}:{eligible:!1,reason:"authJwtExpired"}}getPartnerSDKEligibility(){return{eligible:!0}}};c(lt,"googlePaySDKPromise");let He=lt;const gs=[Ri,xe,ar,He,qt,$e,Ln],fs=new Map(gs.map(e=>[e.walletName(),t=>new e(t)]));function ne(e){const t=fs.get(e.name);return t?t(e):(console.debug("Can't build wallet with name ".concat(e.name)),null)}function bs(e){return e.map(t=>ne(t)).filter(t=>t!=null)}const On="*{box-sizing:border-box}.wallet-button-fade-in{animation:animation-fade-in .3s cubic-bezier(.1,.79,1,1)}@keyframes animation-fade-in{0%{opacity:0}to{opacity:1}}button[aria-disabled=true]{opacity:.5;cursor:not-allowed}";class ws{constructor(t,n,r){this.element=t,this.apiClient=n,this.instrumentName=r}async getInitialCart(t){const n=Ze(this.element);if(!n)throw new Error("[".concat(this.instrumentName,"] unable to find product form"));const r=Gt(na),{data:a,errors:i,warnings:o}=await this.apiClient.createCart(P(_({},n),{discountCodes:r?[r]:[],instrumentName:t}));return{cart:a,errors:i,warnings:o}}}function _s({instanceNumber:e,styleId:t,styles:n,cssFileName:r}){var a,i;e===1&&(i=(a=window.Shopify)==null?void 0:a.PaymentButton)!=null&&i.isStorefrontPortableWallets&&(As({styleId:t,styles:n,cssFileName:r})||Cs({styleId:t,styles:n}))}function As({styleId:e,styles:t,cssFileName:n}){return!!document.querySelector("style#".concat(e))}function Cs({styleId:e,styles:t}){const n=document.createElement("style");n.id=e,n.innerHTML=t,document.head.appendChild(n)}const G={buttonBlockSize:"--shopify-accelerated-checkout-button-block-size",buttonBorderRadius:"--shopify-accelerated-checkout-button-border-radius",buttonBoxShadow:"--shopify-accelerated-checkout-button-box-shadow",inlineAlignment:"--shopify-accelerated-checkout-inline-alignment"};function Tr(e){let t=0,n=0,r=0;const a=e.split(/\s+/);for(let i=0;i