const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["82de4790.tszotZhd.js","630ba094.L_X-5TXi.js","6ec9a0fa.rdcQt2v8.js","f025431a.BlsbPO0-.js","4509beb0.BguNH--m.js","app.BAntcNCf.js","assets/app.CGRs8DQS.css","assets/deferred-boot.Drpcgh6C.css","6a7f8a66.BJPV7lnG.js","4618373b.CjXafxDy.js","486c3fda.B832TPZj.js","assets/a50c8864f4.DiwHZivn.css","c1e3be47.ChuSFbxF.js","assets/4eb5df94d4x8d382f2f.CRpcZnVJ.css","83f74304.Bpuuq40R.js","0d85278a.CTy9dP2P.js","assets/Tips.C-a1hvqh.css"])))=>i.map(i=>d[i]); import{Ft as e,Gt as t,It as a,Jt as s,Lt as n,Pt as r,Qt as i,Ut as o,Vt as d,Wt as l,Xt as u,Zt as c,ct as m,en as h,ft as p,gt as y,nn as v,on as f,ot as C,pt as b,qt as g,w as _,yt as P,zt as M}from"./630ba094.L_X-5TXi.js";import{l as S}from"./4509beb0.BguNH--m.js";import{f as k}from"./app.BAntcNCf.js";import{$l as A,$m as w,AO as E,Am as I,Ao as x,Au as D,Bp as L,Bs as N,Cb as T,Cm as B,Co as U,Cs as F,Df as R,Do as V,Ds as O,Du as $,Ed as q,Ef as Y,Eg as H,Es as z,Eu as j,Fh as G,Fo as K,Gg as Q,Gm as W,HD as J,Hb as X,Hd as Z,Hm as ee,Hs as te,Io as ae,Ip as se,Is as ne,JD as re,Jg as ie,Jo as oe,Jv as de,Kg as le,Ko as ue,LD as ce,Lb as me,Lh as he,Lp as pe,Ls as ye,Mm as ve,Mx as fe,Nl as Ce,No as be,Ny as ge,OO as _e,Om as Pe,Oo as Me,Op as Se,Os as ke,Ou as Ae,Oy as we,Pb as Ee,Po as Ie,Pu as xe,QA as De,Ro as Le,Rs as Ne,Ru as Te,SO as Be,Sm as Ue,So as Fe,T as Re,Tb as Ve,Tc as Oe,Tg as $e,Tm as qe,To as Ye,Ts as He,Tu as ze,Tv as je,UA as Ge,Uf as Ke,Uh as Qe,Um as We,Us as Je,Uu as Xe,Vs as Ze,Vv as et,WC as tt,Wb as at,Wd as st,Wm as nt,Xg as rt,Yf as it,Yv as ot,ZA as dt,Zd as lt,Zo as ut,_E as ct,_b as mt,_f as ht,_p as pt,_u as yt,ac as vt,bo as ft,bu as Ct,bv as bt,c_ as gt,cw as _t,cx as Pt,dD as Mt,eb as St,eu as kt,fu as At,fy as wt,gT as Et,gb as It,gu as xt,gw as Dt,hs as Lt,hu as Nt,jO as Tt,jS as Bt,ko as Ut,kp as Ft,ks as Rt,lE as Vt,lb as Ot,lk as $t,lv as qt,lx as Yt,mu as Ht,mw as zt,my as jt,of as Gt,ov as Kt,pw as Qt,rd as Wt,rf as Jt,ss as Xt,sv as Zt,sx as ea,uu as ta,uw as aa,ux as sa,uy as na,vA as ra,vT as ia,vb as oa,vu as da,wm as la,ws as ua,xO as ca,xg as ma,xm as ha,xo as pa,yg as ya,yo as va,yu as fa,zo as Ca,zs as ba}from"./6ec9a0fa.rdcQt2v8.js";import{t as ga}from"./1dbf806c.BIm0vljQ.js";import{n as _a,t as Pa}from"./4618373b.CjXafxDy.js";import{t as Ma}from"./a56386a6.BSB-hdod.js";import{m as Sa,p as ka}from"./928dbd30.BIHpBIaB.js";import{r as Aa,t as wa}from"./77d9e668.B6Nt2tia.js";import{t as Ea}from"./e1177f6f.BdwRWO6B.js";import{i as Ia,t as xa}from"./e59ed41d.DGtOZi_Z.js";import{d as Da,f as La,l as Na,u as Ta}from"./674595ba.CBCkPO6g.js";import{i as Ba}from"./16138b9e.CcOfuQrQ.js";import{t as Ua}from"./0d85278a.CTy9dP2P.js";var Fa,Ra=new Map,Va=(class e{constructor(e=[],t=[]){this.sdkQueue=e,this.initQueue=t,this.setupGeneration=0,this.currentSetupId=0,this.scriptLoaded=!1}async load(e){let t=Ra.get(e.source);t instanceof Promise||(t=ye(e,!0),Ra.set(e.source,t)),await t,this.initQueue.pop()?.(),this.initQueue=[],this.scriptLoaded=!0}async setup(t,a,s){return Oa(()=>{if(this.sdk)return;if(this.setupPromise&&this.setupForm===t)return this.setupPromise;const n=window.CardFields;if(!n)throw new Ne("Attempted to init Cardfields before it is ready");const r=++this.currentSetupId;return this.setupForm=t,s(),this.setupPromise=(async()=>{try{for(let s=0;sa.on(e,t))}off(e,t){return this.scheduleSDK(a=>a.off(e,t))}setStyles({field:e,styles:t}){return e?this.scheduleSDK(a=>a.setStyles(e,t)):this.scheduleSDK(e=>e.setStyles(t))}setFocus(e){return this.scheduleSDK(t=>t.setFocus(e))}setTranslation(e,t){return this.scheduleSDK(a=>a.setTranslation(e,t))}setPlaceholderContent(e,t){return this.scheduleSDK(a=>a.setPlaceholderContent(e,t))}setValue(e,t){return this.scheduleSDK(a=>a.setValue(e,t))}vaultCard(e){return this.scheduleSDK(t=>t.vaultCard(e))}vaultCardMultipleTimes(e,t){return this.scheduleSDK(a=>a.vaultCardMultipleTimes(e,t))}setErrors(e){return this.scheduleSDK(t=>t.setErrors(e))}clearField(e){return this.scheduleSDK(t=>t.clearField(e))}loadFonts(e){return this.scheduleSDK(t=>t.loadFonts(e))}getFieldFrame(e){return this.scheduleSDK(t=>t._getFieldFrame(e))}scheduleSDK(e){return Oa(()=>{if(!this.sdk)throw new te("The CardFields SDK has not been set up.");return e(this.sdk)},Boolean(this.sdk),this.sdkQueue)}static#e=Fa=()=>(this.MAX_SETUP_ATTEMPTS=3,this)},Fa());function Oa(e,t,a){if(t){const t=e();return t instanceof Promise?t:new Promise(e=>{e(t)})}return new Promise((t,s)=>{a.push(async()=>{try{const a=e();t(a instanceof Promise?await a:a)}catch(a){s(a)}})})}var $a=f(void 0),qa={name:!1,number:!1,expiry:!1,verification_value:!1,issue_number:!1,issue_date:!1};function Ya({children:a,value:n,sdkScriptAttributes:r,blurValidationEnabled:i=!0,blurValidationFieldDenylist:c,onError:m,onSetFieldErrors:p,onLoadSuccess:y}){const v=h(()=>new Va,[]),f=e(!0),C=e({name:null,number:null,verification_value:null,expiry:null,issue_date:null,issue_number:null,sdk:null}),b=e(void 0),g=e(void 0),_=e(void 0),M=h(()=>function(e={}){return{name:o(e.name??!1),number:o(e.number??!1),verification_value:o(e.verification_value??!1),expiry:o(e.expiry??!1),expiry_month:o(e.expiry_month??!1),expiry_year:o(e.expiry_year??!1),issue_date:o(e.issue_date??!1),issue_number:o(e.issue_number??!1)}}(),[]),S=e(""),k=e([]),A=e(qa),w=s(),E=u(e=>{d(()=>{b.value=e instanceof N?e.diagnostics:void 0,C.value={sdk:e.message},f.value=!1}),m?.(e)},[m,C,f,b]),I=u(async e=>{try{return await e()}catch(t){if(t instanceof Error){let e=null;if(t.name===Je.name)e=new Je(t.message);else if(t.name===ba.name){const a="httpStatus"in t&&"number"==typeof t.httpStatus?t.httpStatus:void 0;e=new ba(t.message,a)}else t.name===Ze.hostedFieldsName&&(e=new Ze(t.message));if(e)return E(e),"";E(t)}throw t}},[E]),x=u(async(e,t={propagateErrors:!0})=>{const{sdk:a,...s}=e;await I(()=>v.setErrors(s));const n=C.peek(),r=Object.entries(e).some(([e,t])=>n[e]!==t)?{...n,...e}:n;C.value=r,t.propagateErrors&&p?.(r)},[v,C,p,I]),D=u((e,t)=>{const a={},s=w.current;t?(e||(!M.expiry.value&&t.includes("expiry")&&(a.expiry=s?.expiry),!M.number.value&&t.includes("number")&&(a.number=s?.number_blank),!M.name.value&&t.includes("name")&&(a.name=s?.name)),!e&&!t.includes("verification_value")||M.verification_value.value||(a.verification_value=s?.verification_value)):(e||(M.expiry.value||(a.expiry=s?.expiry),M.number.value||(a.number=s?.number_blank),M.name.value||(a.name=s?.name)),M.verification_value.value||(a.verification_value=s?.verification_value));const n={...C.value,...a};return x(n),{isValid:!Object.values(n).some(Boolean)}},[C,M,x]);l(()=>{!async function(){try{if(!r)throw new Ne("Provider: hostedFieldsUrl must be provided");await v.load(r)}catch(e){e instanceof Error&&E(e)}}()},[r,v,E]);const L=u(({cardType:e,bin:t,networks:a})=>{const s=k.peek(),n=s?.length!==a?.length||(s??[]).some((e,t)=>e!==a?.[t]);d(()=>{g.value=e,S.value=t,n&&(k.value=a)})},[S,g,k]),T=u(({targetName:e})=>{_.value=e},[_]),B=u(async e=>{const{isValueValid:t,targetName:a,isValueEmpty:s}=e,n=w.current,r=A.peek()[a],o=Boolean(c?.has(a));if(i&&!o&&n&&r){const e={[a]:t?null:n[a]};"number"===a&&s&&(e[a]=n.number_blank),await x(e,{propagateErrors:!1})}_.value=void 0},[_,A,x,i,c]),U=u(async e=>{const{targetName:t,isValueEmpty:a,isTab:s}=e;s||(M[t].value=!a,A.value=function(e,t,a){return e[t]===a?e:{...e,[t]:a}}(A.peek(),t,!0),await x({[t]:null}))},[M,A,x]),F=u(e=>{M[e].value=!0},[M]),R=function(){const e=s(!0);return t(()=>()=>{e.current=!1},[]),e}(),V=u(()=>{R.current&&d(()=>{for(const e of Object.values(M))e.value=!1;k.value=[]})},[M,R,k]),O=u(()=>{I(()=>v.on("cardtype",L)),I(()=>v.on("focus",T)),I(()=>v.on("blur",B)),I(()=>v.on("keyup",U)),I(()=>v.on("change",U)),I(()=>v.on("input",U))},[I,v,L,T,B,U]),$=u(()=>{I(()=>v.off("cardtype",L)),I(()=>v.off("focus",T)),I(()=>v.off("blur",B)),I(()=>v.off("keyup",U)),I(()=>v.off("change",U)),I(()=>v.off("input",U))},[I,v,L,T,B,U]),q=u(()=>{A.value=qa},[A]),Y=h(()=>({loadFonts:e=>I(()=>v.loadFonts(e)),setErrors:e=>x(e,{propagateErrors:!1}),setStyles:(...e)=>I(()=>v.setStyles(...e)),setFocus:(...e)=>I(()=>v.setFocus(...e)),setTranslation:(...e)=>I(()=>v.setTranslation(...e)),setPlaceholderContent:(...e)=>I(()=>v.setPlaceholderContent(...e)),setValue:(e,t)=>I(()=>("string"==typeof t&&t.trim().length>0&&(M[e].value=!0),v.setValue(e,t))),setup:async(e,t,a=()=>{})=>{f.value=!0,await I(()=>v.setup(e,t,a)),y?.(),f.value=!1,w.current=t.errorMessages},teardown:()=>I(()=>v.teardown()),clearField:e=>I(()=>(M[e].value=!1,v.clearField(e))),vaultCard:(...e)=>I(()=>v.vaultCard(...e)),vaultCardMultipleTimes:(e,t)=>I(()=>v.vaultCardMultipleTimes(e,t)),getCardField:e=>v.getFieldFrame(e)}),[v,x,I,y,M,f]);l(()=>()=>{p?.({})},[p]);const H=h(()=>n??{sdk:Y,errors:C,sdkLoadDiagnostics:b,cardBrand:g,bankIdNumber:S,networks:k,focusedField:_,filled:M,loading:f,validate:D,subscribe:O,unsubscribe:$,resetTouched:q,emptyFields:V,setFilled:F,touched:A},[Y,g,S,k,C,b,M,_,f,n,D,O,$,q,V,F,A]);return P($a.Provider,{value:H,children:a})}var Ha=()=>{const e=i($a);if(null==e)throw new Ne("No cardfields found in context");return e},za=e=>e.toUpperCase(),ja=e=>e.toLowerCase();function Ga(e){return Boolean(e?.some(e=>"direct"===e.type&&e.paymentBrands.includes("BOGUS")))}function Ka({paymentMethods:e,hasBogusGateway:t=Ga(e),selectedCardRequiresProposalLineCvv:a=!1,selectedCardBrand:s,hasAmexCvvOnlyField:n=Qa({selectedCardRequiresProposalLineCvv:a,selectedCardBrand:s})}){return t?new Set(["number"]):n?new Set(["verification_value"]):new Set}function Qa({paymentLines:e,storeVaultGuestCvvVerificationEnabled:t=!1,selectedCardRequiresProposalLineCvv:a=!1,selectedCardBrand:s}){return Boolean(a&&"AMEX"===s?.toUpperCase()||t&&e?.some(({method:e})=>e.type===Dt.CreditCard&&"AMEX"===e.brand))}function Wa(e){return e.replace(/([\d.]+)rem/g,(e,t)=>10*Number(t)/14+"rem")}function Ja(){const{checkout:{negotiator:e}}=ca(),{paymentMethods:t}=e.current.fields;return r(()=>{const e=t.value?.filter(e=>e.type===Dt.CreditCard&&Boolean(e.expired));return e?e.length:0})}function Xa(){const{i18n:e}=ca();return{getAccessibilityLabel:t=>{const a="direct"===t.type?t.creditCardLastFourDigits:t.displayLastDigits;return`${I(t.brand)} ${e.translate("payment.saved_credit_card_info")} ${a}`}}}function Za(e){return e?e.map(e=>za(e)):[]}var es=mt("CreditCardNetworkContext");function ts({children:e,paymentMethod:t,publishesCardNetworkDetection:a=!1}){const{checkout:s,shop:n,source:r,observability:i,userEvents:o}=ca(),d=g(),m=t?Qt(t):d,p=s.cardNetworkSelection.forMethod(m),{bankIdNumber:y,networks:v,cardBrand:f,sdk:C,filled:b}=Ha(),_=b.number.value,M=h(()=>Za(v.value),[v.value]),S=y.value?.replace(/\s/g,"").length??0,k=S>=6&&f.value?za(f.value):void 0,A=h(()=>M.filter(e=>t?.paymentBrands.includes(e)),[M,t]),w=Boolean(t?.supportsNetworkSelection);l(()=>{a&&p.setDetectedState({networkSelectionEnabled:w,availableNetworks:A,cardBrand:k,numberFilled:_,bankIdNumberLength:S})},[a,p,w,A,k,_,S]);const E=p.selectableBrands.value;!function({displayName:e,paymentBrands:t,paymentMethodIdentifier:a,selectableBrands:s,networkSelectionSupported:n}){const r=Ha(),i=r.bankIdNumber.value,o=r.networks.value,d=r.cardBrand.value,{userEvents:u,source:{checkoutSessionIdentifier:m}}=ca(),[p,y]=c(!1),[v,f]=c(""),C=h(()=>Za(o||(d&&(i?.length??0)>=6?[d]:void 0)),[o,d,i]);l(()=>{if(!i||0===i.length||!m)return;const r={checkoutToken:m,paymentMethodIdentifier:a,displayName:e||"",supportedBrands:t.join(","),detectedBrands:C.join(","),cardIsCobadged:C.length>1,shownBrands:s.join(","),networkSelectorShown:s.length>1&&n};p||(u.monorailEvent({schemaId:"checkout_credit_card_number_interaction/1.1",payload:{...r,eventName:"first_digit_entered"}}),y(!0)),i.length>=6&&C.length>0&&r.shownBrands!==v&&(f(r.shownBrands),u.monorailEvent({schemaId:"checkout_credit_card_number_interaction/1.1",payload:{...r,eventName:"brand_shown_to_buyer"}}))},[a,e,t,C,s,i,u,m,n,v,p,y])}({displayName:t?.name,paymentBrands:t?.paymentBrands??[],paymentMethodIdentifier:t?.paymentMethodIdentifier??"",selectableBrands:E,networkSelectionSupported:t?.supportsNetworkSelection??!1});const I=u(e=>{const t=p.selectedSavedCreditCardBrand.value,a="function"==typeof e?e(t):e;p.setSelectedSavedCreditCardBrand(a)},[p]),x=u(async()=>{const e=p.selectedNetwork.value,t=e?{selected_network:ja(e)}:void 0,a=await C.vaultCard(t);return ss(o,{shopId:n.id,checkoutSessionIdentifier:r.checkoutSessionIdentifier,selectedNetwork:t?.selected_network,detectedNetworks:v.value}),a||i.log("credit_card_network_context_no_session_id_returned","No session id returned when vaulting card with selected network",{selectedNetwork:t?.selected_network}),a},[p,C,n,r,v,i,o]),D=u(async e=>{const t=p.selectedNetwork.value,a=t?{selected_network:ja(t)}:void 0,s=await C.vaultCardMultipleTimes(e,a);return ss(o,{shopId:n.id,checkoutSessionIdentifier:r.checkoutSessionIdentifier,selectedNetwork:a?.selected_network,detectedNetworks:v.value}),s},[p,C,o,n,r,v]),L=h(()=>({activePaymentBrand:p.activeBrand.value,binLength:p.bankIdNumberLength,paymentMethod:t,detectedNetworks:M,selectableBrands:E,selectedNetwork:p.selectedNetwork.value,selectedSavedCreditCardBrand:p.selectedSavedCreditCardBrand.value,setSelectedNetwork:p.setSelectedNetwork,setSelectedSavedCreditCardBrand:I,vaultCardWithSelectedNetwork:x,vaultCardMultipleTimesWithSelectedNetwork:D}),[p.activeBrand.value,p.bankIdNumberLength,p.setSelectedNetwork,p.selectedNetwork.value,p.selectedSavedCreditCardBrand.value,t,M,E,I,x,D]);return P(es.Provider,{value:L,children:e})}function as(){return oa(es)}function ss(e,{shopId:t,checkoutSessionIdentifier:a,selectedNetwork:s,detectedNetworks:n=[]}){s&&(e.monorailEvent({schemaId:"checkout_credit_card_network_selection/1.0",payload:{checkoutToken:a??"",selectedNetwork:s,supportedNetworks:n.join(",")}}),a&&e.refineryEvent(xa({eventTypeName:Ia,selectedNetwork:s,supportedNetworks:n},{shopId:t,checkoutSessionIdentifier:a,customerId:void 0})))}var ns=class extends Error{constructor(...e){super(...e),this.name="UnsupportedShopPayCustomerCardError"}};function rs({allowPreselect:e=!0,displayedPaymentMethods:t}={}){const{checkout:{identity:a,negotiator:n},observability:i,userEvents:o,shop:d}=ca(),{value:c}=o.trekkie.defaultAttributes,{hasNegotiatedAlternativePaymentCurrencySignal:m,newCardSignal:y}=n.context,v=n.current.fields.paymentMethods,f=ma(),C=n.current.fields.paymentLines,b=je(),{currencyCode:g,id:_,paymentMethodAutoSelectionDisabled:P}=d,M="shopPay"===a.current.value,S=!M,k=p(t),A=r(()=>is(k.value??f.value,"shopPay"===a.current.value)),{value:E}=n.current.fields.buyerIdentity,I=n.parts.paymentLines,{value:x}=n.current.fields.deferredTotal,{value:D}=n.current.fields.paymentFlexibilityPaymentTermsTemplate,L=Kt(),N=E?.presentmentCurrency||g,T=ya(),U=s(!1),F=s(!1),R=M?I.value.find(e=>e.method.type===Dt.CreditCard)?.method.type:void 0;l(()=>{R&&!F.current&&(F.current=!0,i.counter({name:"shop_pay_unsupported_customer_card_on_payline",value:1,attributes:{payment_method_type:R}}),i.error(new ns("Shop Pay proposed payment line contains an unsupported Customer Account saved card"),{severity:"warning",metadata:{value:{paymentMethodType:R}}}))},[i,R]);const V=r(()=>{const e=A.value.find($e);if("shopPay"!==a.current.value&&e&&w(I.value))return Qt(e);const t=I.value.filter(e=>la(e,A.value,{identity:a})||qe(e)),[s]=B(t);return void 0!==s?s:(i.leaveErrorBreadcrumb("Unexpected: Selected payment method is empty because `paymentLines` array is empty",{displayedPaymentMethods:JSON.stringify(A.value),displayedProposedPaymentLines:JSON.stringify(t)}),"")}).value,O=u((e,a,s,{rebuild:r=!1,buyerInitiated:d=!1,onlyIfChanged:l=!1})=>{const u=I.value,h=is(t??v.value??[],M),p=ds(u,h),f=u.some(e=>"direct"===e.method.type),P=a([...u,...!f&&y.value?[{method:y.value}]:[]],h,{negotiatedPaymentLines:C.value?.lines,deferredTotal:x,hasPayableDeposit:Boolean(b.value?.amount),hasFixedSellingPlan:L.value,rebuild:r,paymentTermsTemplateType:D?.type,preserveShopPayApproval:S}),k=s?function(e,t){const[a]=e;return a?e.map(e=>e.method.type===t.type&&_t(e.method,a.method)?function(e,t){return{...e,method:{...e.method,...t}}}(e,t):e):e}(P,s):P;if(l&&H(k[0],u[0])&&function(e,t){if(e.length!==t.length)return!1;const a=[...t];return e.every(e=>{const t=a.findIndex(t=>H(e,t));return-1!==t&&(a.splice(t,1),!0)})}(k,u))return;for(const t of e)ls(t,h,i);I.value=k;const A=ds(P,h),w=nt(p,A,N);w&&(m.value=!0,o.monorailEvent(function({uniqueToken:e,shopGid:t,shopCurrencyCode:a,presentmentCurrencyCode:s,checkoutSessionIdentifier:n,previousPaymentMethod:r,currentPaymentMethod:i}){return{schemaId:"multi_currency_checkout_payment_method_change/2.0",payload:{shopId:parseInt(re(t),10),userToken:e,checkoutToken:n||"",shopCurrencyCode:a,checkoutPresentmentCurrencyCode:s,priorPaymentMethodHandle:os(r),priorPaymentType:ot(r?.type||""),newPaymentMethodHandle:os(i),newPaymentType:ot(i?.type||""),isPriorPaymentMethodMc:ee(s,r),isNewPaymentMethodMc:ee(s,i)}}}({uniqueToken:c?.uniqToken||"",shopGid:_,shopCurrencyCode:g,presentmentCurrencyCode:N,previousPaymentMethod:p,currentPaymentMethod:A})));const E=d&&W(p,A);(w||E)&&n.negotiate({withResultHandling:!0})},[m,v,C.value?.lines,y,x,b.value?.amount,N,I,o,c?.uniqToken,_,g,n,D,L,t,M,S,i]),$=u((e,t,a={})=>O([e],(t,a,s)=>ha([e],t,a,s),t,a),[O]),q=u((e,t={})=>{let a=[];return O(e.map(({name:e})=>e),(t,s,n)=>{const r=Ue(e,t,s,n);return a=r.linesBySelection,r.paymentLines},void 0,t),a},[O]),Y=s(V);Y.current!==V&&(Y.current=V,T.value&&!V&&0===I.value.length&&(U.current=!1));const z=r(()=>{const[e]=A.value;return e?Qt(e):void 0}).value,j=r(()=>A.value.length).value;if(e&&!V&&!U.current&&void 0!==z&&!Ot(I.value)&&!(P&&j>1)){const e=z;i.leaveErrorBreadcrumb("rebuilding payment lines on missing selected payment line",{displayedPaymentMethods:JSON.stringify(A.value),selectedPaymentMethod:e}),$(e,void 0,{rebuild:!0}),U.current=!0}return h(()=>[V,$,q],[V,$,q])}function is(e,t){return t?e.filter(e=>e.type!==Dt.CreditCard):e}function os(e){if(void 0===e)return"";const t="name"in e&&e.name||void 0,a="paymentMethodIdentifier"in e&&e.paymentMethodIdentifier||void 0;return de(e.type,t,a)}function ds(e,t){return t.find(t=>e.find(e=>"paymentMethodIdentifier"in e.method&&"paymentMethodIdentifier"in t?e.method.paymentMethodIdentifier===t.paymentMethodIdentifier:"wallet"===e.method.type&&"wallet"===t.type?e.method.name===t.name:e.method.type===t.type))}function ls(e,t,a){if(t.some(t=>Qt(t)===e))return;const s=t.filter(t=>zt(t)&&t.name===e);0!==s.length&&a.counter({name:"payment_method_key_name_fallback",value:1,attributes:{unique:String(1===s.length)}})}function us(){const{shopPay:e,checkout:{configuration:t,negotiator:a},observability:s}=ca(),n=t.addressSettings.nonBillingAddressSettings;return{updateCheckoutAddress:u(async({shippingAddress:t,billingAddress:r,fallbackPhoneNumber:i},o=!1)=>{if(!t&&!r)return;const d=[];if(t){d.push("shippingAddress");const e=n.value.isRequired("phone",{countryCode:t.countryCode,useMerchantSettings:!0})&&!t.phone?i:t.phone;s.log("wallets_shipping_address_update","useUpdateCheckoutAddress: update with Shop Pay vaulted address",{isPostalCodePadded:Ee(t.postalCode,t.countryCode),countryCode:t.countryCode}),a.parts.shippingAddress.replace(Bt(t,{...t,phone:e,oneTimeUse:t.oneTimeUse||!1}))}if(r){d.push("billingAddress");const e=n.value.isRequired("phone",{countryCode:r.countryCode,useMerchantSettings:!0})&&!r.phone?i:r.phone;a.parts.billingAddress.replace(Bt(r,{...r,phone:e}))}const l=ne(t??a.parts.shippingAddress.value,r??a.parts.billingAddress.value);e.user.hasCreditCards.value&&(a.parts.billingAddressOption.value=l?"shipping":"custom"),o||await a.negotiate({withResultHandling:!0,silenceViolations:["non-stock",...na],fieldsToResolve:d})},[a,n,e.user,s])}}function cs(e){const{shopPay:t,checkout:a}=ca(),s=t.user.phoneNumber.value,n=t.user.addresses.value,r=a.configuration.addressSettings.nonBillingAddressSettings.value,i=n[0]?.address,o=r.defaultShippingDetails.country?.code??a.requestGeolocation.country.code;return h(()=>fe(e?e.address:{firstName:i?.firstName,lastName:i?.lastName,phone:s,countryCode:i?.countryCode||o,zoneCode:i?.zoneCode},{extendedAddressMode:a.address.extendedAddressMode}),[a.address.extendedAddressMode,e,i,o,s])}var ms=["CardFieldsFetchFailureError"];function hs({children:e,publishesCardNetworkDetection:t,directPaymentMethodConfig:a,...n}){const i=s(Rt()),{observability:o,checkout:{negotiator:d}}=ca(),l=r(()=>sa(d.current.fields.paymentMethods.value??[])),c=a??l.value,m=u(e=>{ms.includes(e.name)?o.log("default_card_fields_provider_unactionable_error","Unactionable error in card fields provider",{error:e}):o.error(e)},[o]);return P(Ya,{...n,onError:m,sdkScriptAttributes:i.current,children:P(ts,{paymentMethod:c,publishesCardNetworkDetection:t,children:e})})}function ps(){const e=ys(),{checkout:{negotiator:t}}=ca(),{value:a}=t.current.fields.paymentLines,{newCardSignal:s,hasLoadedSignal:n}=t.context,r=s.value,i=n.value,o=a?.lines?.find(e=>"direct"===e.method.type);return e.value&&!i&&o&&(n.value=!0,!r&&o.method.paymentMethodIdentifier&&(s.value=o.method)),s}function ys(){const{checkout:{configuration:e,negotiator:t}}=ca(),a=e.layout.isOnePage.value,{paymentMethods:s}=t.current.fields;return r(()=>!!a&&Boolean(Yt(s.value).length))}function vs({options:e,paymentMethodExtension:t}){const a=t[0]?.extension;if(!a)return null;const s=a.appId.split("/").pop(),n=s&&!vt.includes(s);return P(Ft,{options:e,customizations:t,transformComponents:n?fs:void 0})}var fs=He(new Set(["Image","Banner","s-image","s-banner"]));function Cs({isSelected:e,hasMsiPlan:t,isStale:a,binPrefix:s,canEditBin:n,supportedInstallmentsCount:r,isNegotiating:i}){if(!e||!t&&!a)return"hidden";if(s){if(s.length<8&&n)return"prompt"}else{if(n)return"prompt";if(0===r)return"hidden"}return i||a?"loading":"dropdown"}function bs({id:e,variant:t}){const{i18n:a}=ca(),s="prompt"===t?a.translate("msi_installments.enter_card_details_prompt"):a.translate("msi_installments.loading_installments");return l(()=>{if("loading"===t)return Ge({content:s})},[s,t]),P(pe,{id:e,name:"msiInstallments",label:a.translate("msi_installments.payment_plan_label"),value:t,disabled:"loading"===t,onChange:()=>{},children:P(se,{value:t,children:s})})}function gs({paymentMethod:e,isSelected:t,canEditBin:a=!0,isVaultedContext:s=!1,id:n="msiInstallmentsSelect"}){const{checkout:{negotiator:r}}=ca(),{bankIdNumberSignal:i,lastNegotiatedBinSignal:o}=r.context,{paymentLines:d}=r.parts,u=F(),c=a&&!s,m=e.installmentPlans?.find(e=>"MSI"===e.type),h=m?.supportedInstallments??[],p=ea(i.value),y=!s&&void 0!==p&&void 0!==o.value&&p!==o.value;l(()=>{u.value&&(t&&m&&(p||c||0!==h.length)||(d.value=ke(d.value,void 0)))},[u.value,t,m,p,c,h.length,d]);const v=Cs({isSelected:Boolean(t),hasMsiPlan:Boolean(m),isStale:y,binPrefix:p,canEditBin:c,supportedInstallmentsCount:h.length,isNegotiating:!1});return"hidden"===v?null:P(bs,"prompt"===v?{id:n,variant:"prompt"}:{id:n,variant:"loading"})}var _s=C({displayName:"MsiInstallmentsSelect",useError:et("MsiInstallmentsSelect"),load:()=>m(async()=>({default:(await k(async()=>{const{MsiInstallmentsSelect:e}=await(import("./82de4790.tszotZhd.js"));return{MsiInstallmentsSelect:e}},__vite__mapDeps([0,1,2,3,4,5,6,7]))).MsiInstallmentsSelect})),renderLoading:e=>P(gs,{...e})});function Ps({userEvents:e,shopId:t,checkoutSessionIdentifier:a,card:s}){e.monorailEvent({schemaId:"checkout_vaulted_payment_method_selected/1.0",payload:{shopId:parseInt(re(t),10),checkoutSessionIdentifier:a||"",paymentMethodId:parseInt(re(s.id),10),paymentInstrumentAccessorId:-1}})}var Ms={id:"563e8a86083a6c9ad5bd44d3a4db471e3a9919052512d2745d267074d97420fd",type:"mutation",name:"DeleteVaultedCreditCard",source:""},Ss={id:"d1f468f7d6684d3133e47cef5cf1ef67ccd2bd916b53203708d85ac3175f1bd0",type:"mutation",name:"UpdateCustomerCreditCard",source:""},ks=class extends Error{constructor(e){super("Failed to update customer credit card payment method",e),this.name="UpdateCustomerCreditCardPaymentMethodError"}},As=class extends Error{constructor(e){super("Failed to delete customer credit card payment method",e),this.name="DeleteCustomerCreditCardPaymentMethodError"}};async function ws({graphql:e,address:t,extendedAddressMode:a,defaultPaymentMethod:s,token:n,genericError:r}){if(!n)return{token:void 0};try{const{data:i,error:o}=await e.mutate(Ss,{variables:{customerCreditCardModificationInput:{token:n,defaultPaymentMethod:s,billingAddress:{streetAddress:Wt(t,{extendedAddressMode:a})}}}});if(!i?.modifyCustomerCreditCardPaymentMethod||o)throw new ks({cause:o});const{result:d,errors:l}=i.modifyCustomerCreditCardPaymentMethod;return l.length||!d?{token:void 0,error:l[0]?.localizedMessage||r}:{token:d.token}}catch{return{token:void 0,error:r}}}async function Es({graphql:e,token:t,genericError:a}){if(!t)return{token:void 0};try{const{data:s,error:n}=await e.mutate(Ms,{variables:{token:t}});if(!s?.deleteCustomerCreditCardPaymentMethod||n)throw new As({cause:n});const{result:r,errors:i}=s.deleteCustomerCreditCardPaymentMethod;return i.length||!r?{token:void 0,error:i[0]?.localizedMessage||a}:{token:r.token}}catch{return{token:void 0,error:a}}}var Is=dt("AmazonPayChangePaymentLinkButton");function xs(){const{i18n:e,observability:t}=ca(),{inMemoryAmazonPayParts:{sdkStatus:a}}=It(),s=r(()=>{const e=a.value;return e.status===ge.Available?e.sdk:void 0}),n=ga(),i=De(void 0,Is),{hasError:o}=Qe(ia),d=e.translate("vaulted.change_button");return n.value?P(b,{when:s,children:e=>P(le,{onClick:()=>{t.counter({name:"wallet_change_link_clicked",value:1,attributes:{wallet:ct.AmazonPay,link:"payment_method"}});try{const{checkout_session_id:t}=me(n.value.method.walletParams);e.Pay.changePaymentMethod({amazonCheckoutSessionId:t,isDeclined:o})}catch(a){t.error(new Ds(`Error on changing buyer payment method. Details: ${a}`,{cause:a}))}},id:i,children:d})}):null}var Ds=class extends Error{constructor(...e){super(...e),this.name="AmazonPayChangePaymentLinkError"}},Ls=new Map([["american_express","american_express"],["amex","amex"],["bogus","bogus"],["cartes_bancaires","cartes_bancaires"],["dankort","dankort"],["diners_club","diners_club"],["discover","discover"],["elo","elo"],["forbrugsforeningen","forbrugsforeningen"],["hypercard","hypercard"],["interac","interac"],["jcb","jcb"],["laser","laser"],["maestro","maestro"],["mastercard","mastercard"],["rupay","rupay"],["unionpay","unionpay"],["visa","visa"],["visaelectron","visaelectron"]]);function Ns({brand:e,descriptor:t}){const{hasError:a}=he(),s=e?.toLowerCase().replace(/\s+/g,"_")??"",n=Ls.get(s)??"generic";return P(Q,{direction:"inline",children:[a.value&&P(v,{children:[P($t,{tone:"critical",type:"alert-circle"}),P(pt,{display:"inline",inlineSize:"small-400"})]}),P(Ba,{icon:P(Ma,{type:n}),details:t})]})}var Ts=class extends S{constructor(...e){super(...e),this.name="AmazonPayMissingPaymentPreferencesError"}};function Bs(){const{checkout:{negotiator:e}}=ca(),t=e.parts.paymentLines;return r(()=>{const e=t.value,a=(()=>{const[t]=e.filter(e=>"walletsPlatformPaymentMethod"===e.method.type);if(!t)return"";const a=me(t.method.walletParams).payment_preferences?.[0];if(!a)throw new Ts("Amazon Pay wallet params missing payment preferences",{groupingHash:"AmazonPay::usePaymentDetails::AmazonPayMissingPaymentPreferencesError"});return a.paymentDescriptor.replace("****","•••• ").replace(/(\((.*?)\))/,"").trim()})();return{brand:(()=>{if(!a)return;const e=a.match(/^(.+?)\s+••••/);if(!e)return a;const t=e[1];return void 0===t?a:t.trim()})(),descriptor:a}})}var Us=Object.freeze({name:null,number:null,verification_value:null,expiry:null,issue_date:null,issue_number:null}),Fs=function(e){return e.FirstName="firstName",e.LastName="lastName",e.Number="number",e.Cvv="verificationValue",e.Month="month",e.Year="year",e.Base="base",e.DebitOnly="debitOnly",e}({}),Rs={baseMessage:null,fieldErrors:Us,blockedByDuplicateAutopayCard:!1};function Vs(){const{i18n:t,observability:a}=ca(),s=Ce(),n=e(Rs),r=u((e,t)=>{a.counter({name:e,value:1,attributes:{errorField:t.field.join("-"),errorMessage:t.message}})},[a]),i=u(e=>{if(!e||!e.length)return void(n.value={baseMessage:t.translate("credit_card_form.generic_card_error"),fieldErrors:Us,blockedByDuplicateAutopayCard:!1});const a={...Us};let i=null;e.forEach(e=>{switch(r("save_credit_card_error",e),e.field?.[1]){case"firstName":return void(a.name=t.translate("field_errors.credit_card_name_billing_invalid"));case"lastName":return void(a.name=t.translate("field_errors.credit_card_name_invalid"));case"month":case"year":return void(a.expiry=t.translate("field_errors.credit_card_expiry_invalid"));case"number":return void(a.number=t.translate("field_errors.credit_card_number_invalid"));case"verificationValue":return void(a.verification_value=t.translate("payment.card_fields.errors.invalid.verification_value"));case"debitOnly":return void(i=s.translate("payment_errors.debit_only"));case"base":if("credit_card_is_expired"===e.message)return void(a.expiry=t.translate("payment_errors.card_has_expired"));if("failed_to_verify_credit_card"===e.message)return void(i=t.translate("payment.generic_incorrect_card_info"));if("three_d_secure_authentication_failed"===e.message)return void(i=t.translate("payment_errors.three_d_secure_failed_payment_method"));if("billing_address_missing"===e.message)return void(i=t.translate("payment_errors.payment_method_billing_address"))}"too_many_credit_cards"!==e.message?(i=t.translate("credit_card_form.generic_card_error"),r("save_credit_card_error_unhandled",e)):i=t.translate("credit_card_form.max_cards_reached",{max_cards:10})}),n.value={baseMessage:i,fieldErrors:a,blockedByDuplicateAutopayCard:!1}},[n,t,s,r]),o=u(()=>{a.counter({name:"save_credit_card_blocked_by_autopay",value:1}),n.value={baseMessage:null,fieldErrors:Us,blockedByDuplicateAutopayCard:!0}},[n,a]),d=u(()=>{n.value=Rs},[n]),l=u(e=>{a.counter({name:"save_credit_card_vaulting_failure",value:1,attributes:{reason:e}}),i("missing_billing_address"===e?[{field:["creditCard","base"],message:"billing_address_missing"}]:void 0)},[a,i]);return{creditCardErrors:n.value,setCreditCardErrors:i,clearCreditCardErrors:d,failCardVaulting:l,blockDuplicateAutopayCard:o}}function Os(){const{shop:e,checkout:{wallets:t,latestReceipt:a,identity:s,proposal:n,negotiator:r},observability:i}=ca(),o=t.activeSession.value,d=a.value,{persistedPayPalSignal:u,inMemoryPayPalParts:{reportedTokenRequiringTokenization:c}}=It(),m="payPal"===s.current.value,h=d?.id,p=Jt(),y=p.value,v=void 0!==y,f=Ve(),C=u.value,b=Gt(),g=Qe(new Set(Et))?.hasError&&h!==C?.receiptIdForClearedToken,_=St("PAYPAL_EXPRESS").value?.merchantId?.trim(),P=y?.method.walletContent?.merchantId?.trim(),M=e.hasFlagEnabled("3a1b43ad")&&_&&P&&P!==_,S=C?.billingAgreementStatus&&at({checkout:{proposal:n}})&&"NOTREQUESTED"===C.billingAgreementStatus&&!y?.method.walletContent?.isVaultWithPurchaseOrder,k=!0===y?.method.walletContent?.isVaultWithPurchaseOrder&&0===f.value?.amount,A=e.hasFlagEnabled(Mt),w=Sa().value,E=ka().value,I=lt(p),x=y?.method.walletContent?.token,D="clear"===E&&!o;l(()=>{function e(){let e,t;if(g)e="SubmitForCompletion Error";else if(M)e="Gateway Mismatch";else if(k)e="Zero Payment Due";else if(w){if(c.peek()===x)return;c.value=x,e="Billing Agreement Required",t={reapprovalEnabled:A}}else e="Subscription Added";i.counter({name:"paypal_token_cleared",value:1,attributes:{clearReason:e,...t}}),i.log("paypal_token_cleared","Clearing PayPal token due to error",{clearReason:e,...t,isVenmo:I,hadPersistedBillingAgreementStatus:Boolean(u.value?.billingAgreementStatus)})}v&&(g||M||S||k||D?(e(),function(){const e={...u.value,receiptIdForClearedToken:g?h:void 0,newTokenRequiredDueToError:!0,billingAgreementStatus:void 0};u.value=e}()):w&&e(),(async()=>{(k||D||g&&!m&&!o)&&(b(),await r.negotiate({withResultHandling:!0,silenceViolations:["non-stock"]}))})())},[g,v,M,h,i,u,S,k,A,w,D,x,c,I,m,b,r,o])}function $s(e){const{checkout:{negotiator:t}}=ca(),a=t.current.fields.paymentMethods;return r(()=>{const t=e.value,s=Boolean(t?.balance?.amount),n=Boolean(a.value?.find(e=>"redeemable"===e.type&&"STORE_CREDIT"===e.redemptionSource));return Boolean(s&&n)})}function qs(){const{shop:{currencyCode:e},checkout:{negotiator:t}}=ca(),{buyerIdentity:a}=t.current.fields;return r(()=>{const t=a.value,s=t?.presentmentCurrency||e;return("CustomerProfile"===t?.customerProfile?.__typename||"BusinessCustomerProfile"===t?.customerProfile?.__typename?t.customerProfile.storeCreditAccounts:[]).find(e=>e.balance.currencyCode===s)})}function Ys(){const{checkout:{negotiator:e}}=ca(),t=e.current.fields.paymentLines;return r(()=>t.value?.lines.filter(e=>aa(e))||[])}function Hs(){const{checkout:{negotiator:e}}=ca(),t=e.current.fields.allViolations,a=r(()=>(t.value??[]).filter(e=>!!ut(e)||!!jt(e))),s=r(()=>{const[e]=a.value;return e?e.localizedMessage||e.nonLocalizedMessage:null});return P(b,{when:s,children:e=>P(Z,{tone:"critical",errorType:st.DiscountError,children:e})})}function zs({amount:e,maskedIdentifier:t,remove:a}){const{i18n:s}=ca(),n=s.formatCurrency(e.amount,{currency:e.currencyCode,form:"short"}),r=t.slice(-4).toUpperCase(),i=s.translate("payment.gift_card_wrapper.gift_card_label",{identifier:ue(r)}),o=s.translate("order_summary.gift_card_ending",{last_characters:r||""});return P(rt,{borderRadius:"base",background:"base",border:"base",padding:"small-200",children:P(Tt,{gridAutoFlow:"column",gridTemplateColumns:"minmax(0, 1fr) minmax(auto, max-content)",gridTemplateRows:"minmax(0, 1fr)",children:[P(Tt,{gridAutoFlow:"column",gridTemplateColumns:"minmax(auto, max-content) minmax(auto, max-content)",gridTemplateRows:"minmax(0, 1fr)",gap:"small-300",alignItems:"center",alignContent:"center",children:[P(Ma,{type:"gift-card"}),P(_e,{children:[P(E,{accessibilityVisibility:"hidden",children:i}),P(E,{accessibilityVisibility:"exclusive",children:o})]})]}),P(Tt,{gridAutoFlow:"column",gridTemplateColumns:"minmax(auto, max-content) minmax(auto, max-content)",gridTemplateRows:"minmax(0, 1fr)",gap:"small-100",alignItems:"center",alignContent:"center",children:[P(E,{type:"strong",children:n}),P(we,{onClick:()=>a(),accessibilityLabel:s.translate("general.remove_item",{label:o}),children:P($t,{type:"x",size:"small"})})]})]})})}var js="gift_card_option";function Gs({afterAppliedRedeemablesChange:e,autoSelect:t=!1,showHeading:a=!0}){const{i18n:s}=ca(),{paymentMethod:n,paymentLines:i,submit:o,remove:d,removeAll:m}=Le(),p=gt("Checkout::GiftCard::Render",n.value?.uiExtension?[n.value?.uiExtension]:[]),y=Ve(),v=r(()=>0===(y.value?.amount||0)),[f,C]=c([]),[b,g]=c(!1),_=v.value&&0===i.value.length,M=i.value.length;l(()=>{_?C([]):(M>0||t)&&C([js])},[t,M,_]);const S=u(async(t,a)=>{const s=await o(t,a);return s&&oe(s)&&(g(!1),e?.()),s},[e,o]),k=n.value?.paymentMethodIdentifier,A=h(()=>({paymentMethodIdentifier:k??"",submitRedeemablePaymentLine:S}),[k,S]),w=Boolean(i.value.length)||Boolean(p.length)&&Boolean(n.value);return P(ra,{id:"3p-gift-card-field",open:w,duration:"slow",children:P(Ke,{accessibilityLabel:s.translate("payment.gift_card_wrapper.heading"),children:P(Q,{gap:"base",children:[a&&P(L,{level:2,children:s.translate("payment.gift_card_wrapper.heading")}),P(_a,{name:"gift_card_option_list",values:f,multiple:!0,onChange:async t=>{if(C(t),0===t.length&&i.value.length>0){const t=await m();t&&oe(t)&&e?.()}},variant:"block",children:P(Pa,{value:js,disabled:_,selectedContent:P(Q,{gap:"base",children:[i.value.length>0?P(Q,{gap:"small-300",children:i.value.map(t=>{const{cost:a,method:s}=t;if(!a)return null;const n=s.redemptionContent?.redemptionAttributes.reduce((e,t)=>`${e},${t.key}:${t.value}`,"");return P(zs,{maskedIdentifier:s.redemptionContent?.maskedIdentifier||"",amount:{amount:a.amount,currencyCode:a.currencyCode},remove:async()=>{const t=await d(s);t&&oe(t)&&e?.()}},n)})}):null,P(Hs,{}),(()=>{if(v.value||!p.length||!n.value)return null;const e=P(vs,{paymentMethodExtension:p,options:A});return 0===i.value.length?e:P(rt,b?{children:[P(pt,{blockSize:"small-500"}),P(Q,{gap:"base",children:[P(L,{level:3,children:s.translate("payment.gift_card_wrapper.apply_another_gift_card_label")}),e]})]}:{children:[P(pt,{blockSize:"small-500"}),P(le,{textDecoration:"none",onClick:()=>g(!0),children:P(Q,{direction:"inline",alignItems:"center",gap:"small-400",children:[P($t,{type:"plus"}),P(E,{children:s.translate("payment.gift_card_wrapper.apply_another_gift_card_label")})]})})]})})()]}),children:s.translate("payment.gift_card_wrapper.apply_gift_card_label")})})]})})})}function Ks(){const{i18n:e,checkout:{negotiator:t}}=ca(),a=t.parts.purchaseOrderNumber.value;if(!a)return null;const s=`${e.translate("payment.purchase_order_number.title")} #${a}`;return P(it,{children:s})}function Qs({reason:e,vaulted:t}){const{i18n:a}=ca(),s=Ca().value.length,n=e=>{switch(e){case"giftCard":return a.translate("payment.order_covered_by_gift_cards_notice",{count:s});case"freeOrder":return a.translate("payment.free_order_notice_html");case"storeCredit":return a.translate("payment.order_covered_by_store_credit_notice");case"redeemables":return a.translate("payment.order_covered_by_redeemables_notice");case"deferred":return a.translate("payment_gateway.deferred_payment_label");default:y(e)}};return t?P(Q,{gap:"base",children:[P(ht,{children:n(e)}),P(Ks,{})]}):P(wa,{children:P(Aa,{children:P(ht,{children:n(e)})})})}var Ws=new Set(["direct","offsite","customOnsite","manualPayment","customManualPayment","paymentOnDelivery","local","wallet","walletsPlatform","deferred","bank"]);function Js(){const{router:e}=ca();return r(()=>function(e){const t=new URLSearchParams(e),a=t.get(R);var s;if(a&&(s=a,Ws.has(s)))return{paymentMethod:a,paymentMethodIdentifier:t.get("preselect_id")||void 0}}(e.currentUrl.value.search))}function Xs(e,t){return t.paymentMethodIdentifier?e.find(e=>e.type===t.paymentMethod&&"paymentMethodIdentifier"in e&&e.paymentMethodIdentifier===t.paymentMethodIdentifier):e.find(e=>e.type===t.paymentMethod)}var Zs={id:"0de248be8393ee02daaafbc0c9d726edc1213c2fc3e59ed6e33d1042b15cc783",type:"mutation",name:"CreditCardCreate",source:"mutation CreditCardCreate($billingAddress:AddressInput!,$origin:String!,$sessionId:ID!,$nickname:String,$checkoutContext:CheckoutContextInput!,$stepUpChallengeSupported:Boolean){creditCardCreate(billingAddress:$billingAddress origin:$origin sessionId:$sessionId nickname:$nickname checkoutContext:$checkoutContext stepUpChallengeSupported:$stepUpChallengeSupported){creditCard{...CreditCardFragment __typename}threeDSecureAuthenticationRequest{redirectUrl verificationId __typename}userErrors{field message __typename}__typename}}fragment CreditCardFragment on CreditCard{bank brand expired expiring expiryMonth expiryYear funding id uuid lastDigits lastUsedAt name nickname preferred supportsInstallmentsInterestLoan supportsInstallmentsSplitPayLoan installmentsInterestLoanNotSupportedReason installmentsSplitPayLoanNotSupportedReason verified billingAddressValid billingAddress{addressLineComponents{additionalInformation district streetName streetNumber subdistrict __typename}fields{key value __typename}__typename}__typename}"},en={id:"76ca67a0ff58d1f46e17614ed9f8bb5a075b761270a53c607c2dea3f863acf40",type:"mutation",name:"CreditCardCompleteVerificationAndVault",source:"mutation CreditCardCompleteVerificationAndVault($verificationId:ID!,$billingAddress:AddressInput!,$origin:String,$nickname:String){creditCardCompleteVerificationAndVault(verificationId:$verificationId billingAddress:$billingAddress origin:$origin nickname:$nickname){creditCard{...CreditCardFragment __typename}userErrors{field message __typename}__typename}}fragment CreditCardFragment on CreditCard{bank brand expired expiring expiryMonth expiryYear funding id uuid lastDigits lastUsedAt name nickname preferred supportsInstallmentsInterestLoan supportsInstallmentsSplitPayLoan installmentsInterestLoanNotSupportedReason installmentsSplitPayLoanNotSupportedReason verified billingAddressValid billingAddress{addressLineComponents{additionalInformation district streetName streetNumber subdistrict __typename}fields{key value __typename}__typename}__typename}"},tn={id:"d60ca8058fb85d0d4e3d3585e353d4317aa417ae9568973bb43da35ca94acce7",type:"mutation",name:"CreditCardDelete",source:"mutation CreditCardDelete($id:ID!,$origin:String!,$uuid:String!,$checkoutContext:CheckoutContextInput!){creditCardDelete(id:$id uuid:$uuid origin:$origin checkoutContext:$checkoutContext){userErrors{field message __typename}__typename}}"};var an={id:"ac98474896c104156273e909bd5b45075860ce9cca494dbbdab8809981f1d65d",type:"mutation",name:"CreditCardUpdate",source:"mutation CreditCardUpdate($billingAddress:AddressInput!,$id:ID!,$uuid:String!,$origin:String!,$nickname:String,$checkoutContext:CheckoutContextInput!,$stepUpChallengeSupported:Boolean){creditCardUpdate(billingAddress:$billingAddress id:$id uuid:$uuid origin:$origin nickname:$nickname checkoutContext:$checkoutContext stepUpChallengeSupported:$stepUpChallengeSupported){userErrors{field message __typename}creditCard{...CreditCardFragment __typename}__typename}}fragment CreditCardFragment on CreditCard{bank brand expired expiring expiryMonth expiryYear funding id uuid lastDigits lastUsedAt name nickname preferred supportsInstallmentsInterestLoan supportsInstallmentsSplitPayLoan installmentsInterestLoanNotSupportedReason installmentsSplitPayLoanNotSupportedReason verified billingAddressValid billingAddress{addressLineComponents{additionalInformation district streetName streetNumber subdistrict __typename}fields{key value __typename}__typename}__typename}"};function sn({isApplePayAvailable:e}){const{checkout:{identity:t,negotiator:a},shopPay:s}=ca(),n=p(e);return h(()=>V({identity:t,shopPay:s,negotiatedFields:a.current.fields},{isApplePayAvailable:n}),[t,n,a.current.fields,s])}function nn(e){return"CREDIT_CARD"===e?.paymentMethod}function rn(e){return"IDEAL"===e.paymentMethod||"CUSTOM_ONSITE"===e.paymentMethod&&!0===e.paymentBrands?.some(e=>"ideal"===e.toLowerCase())}function on(e){return"APPLE_PAY"===e.paymentMethod}function dn(e){return"CUSTOM_ONSITE"===e.paymentMethod}function ln(e){return"SHOP_PAY"===e.paymentMethod}function un(e){return"SHOP_PAY_INSTALLMENTS"===e.paymentMethod}function cn(e){return"SHOP_PAY_BALANCE"===e.paymentMethod}function mn(e){return"PAYPAL"===e.paymentMethod}function hn(e){return"BANK"===e.paymentMethod}function pn(e){return"DEFERRED"===e.paymentMethod}function yn(e){return"OFFSITE"===e.paymentMethod||"MANUAL_PAYMENT"===e.paymentMethod||"CUSTOM_MANUAL_PAYMENT"===e.paymentMethod||"PAYMENT_ON_DELIVERY"===e.paymentMethod}var vn={markBuyerHasActed:!1,updateSelectedCardBin:!1,selectedCardFirstDigits:void 0,preserveExistingBinPrefix:!1,claimMsiBin:!1,claimedMsiBin:void 0,shouldNegotiate:!1},fn=class extends S{constructor({managerName:e,methodName:t,identity:a,deployStage:s,isLocalDevelopment:n}){super(`${e}.${t} was called unexpectedly`,{groupingHash:`PaymentMethodManagerUnexpectedMethodCall::${e}::${t}`,metadata:{paymentMethodManager:{managerName:e,methodName:t,identity:a,deployStage:s,isLocalDevelopment:n}}}),this.name="UnexpectedPaymentMethodManagerMethodCallError"}};function Cn({observability:e,managerName:t,methodName:a,identity:s,deployStage:n,isLocalDevelopment:r}){if(r||"production"!==n&&"canary"!==n)return;const i=new fn({managerName:t,methodName:a,identity:s,deployStage:n,isLocalDevelopment:r});e.error(i,{severity:"warning"})}var bn={status:"failed"},gn=class{#t;#a;constructor(e){this.disabledCardMethodsForInstallments=o([]),this.isEveryCardDisabled=o(!1),this.canSetCreditCardNickname=o(!1),this.addCreditCardStrategy="direct-session-payment-line",this.deps=e,this.usesCustomerAccountSelectionRule="customerAccount"===e.identity,this.newCard=e.newCard??o(void 0);const{proposal:t}=e,{proposed:a,negotiated:s}=t,{paymentMethods:r}=s.fields,i=s.fields.paymentMethodHistory??o([]);this.availablePaymentMethods=n(()=>r.value??[]),this.promotedMethods=e.paymentMethodPromotions.promoted,this.customerCreditCards=n(()=>Pt(this.availablePaymentMethods.value)),this.selectableCustomerCreditCards=n(()=>Yt(this.availablePaymentMethods.value)),this.selectablePaypalBillingAgreements=n(()=>(e.displayablePaymentMethods?.value??this.availablePaymentMethods.value).filter(e=>e.type===Dt.PayPal)),this.selectableCustomerBanks=n(()=>this.availablePaymentMethods.value.filter(e=>"bank"===e.type&&e.availableInstruments.length>0)),this.nonCardKnownPaymentMethods=n(()=>pa({paymentMethodHistory:i.value??[],availablePaymentMethods:e.displayablePaymentMethods?.value??this.availablePaymentMethods.value})),this.guestCheckoutMethodIntentTarget=n(()=>{const t=e.guestCheckoutMethodIntent?.value;if(!t)return;const a=Xs(e.displayablePaymentMethods?.value??this.availablePaymentMethods.value,t);return a?ft(a,null):void 0}),this.availableUserStoredPaymentMethods=n(()=>{const e=[...Pn([_n({card:this.newCard.value,billingAddress:a.billingAddress.value})]),...this.selectableCustomerCreditCards.value.map(e=>U(e,{cvvVerificationEnabled:this.deps.storeVaultGuestCvvVerificationEnabled})),...this.selectablePaypalBillingAgreements.value.map(Ye)],t=An(this.selectableCustomerBanks.value.map(Fe),this.nonCardKnownPaymentMethods.value,this.promotedMethods.value),s=e.length>0||t.length>0?Pn([this.guestCheckoutMethodIntentTarget.value]):[];return[...e,...An(t,s)]}),this.autoselectTarget=n(()=>{const e=this.guestCheckoutMethodIntentTarget.value,t=e?this.availableUserStoredPaymentMethods.value.find(t=>t.paymentMethod===e.paymentMethod&&t.id===e.id):void 0;if(t)return t;const a=this.selectableCustomerCreditCards.value.find(e=>e.defaultPaymentMethod),s=a?this.availableUserStoredPaymentMethods.value.find(e=>e.id===a.token):void 0,n=this.availableUserStoredPaymentMethods.value.reduce((e,t)=>t.lastUsedAt?e?.lastUsedAt?t.lastUsedAt>e.lastUsedAt?t:e:t:e,void 0);if(this.usesCustomerAccountSelectionRule){const e=!n||nn(n);if(this.deps.storeVaultEnabled&&e&&s)return s}else if(a)return s;if(n)return n;const r=this.selectableCustomerCreditCards.value[0];if(r)return this.availableUserStoredPaymentMethods.value.find(e=>e.id===r.token);return this.availableUserStoredPaymentMethods.value.find(e=>!nn(e)&&!pn(e))||this.availableUserStoredPaymentMethods.value.find(pn)}),this.proposedSelectedPaymentMethod=n(()=>function(e,t,a,s){const n=e.some(e=>"deferred"!==e.method.type&&"giftCard"!==e.method.type&&"redeemable"!==e.method.type);for(const r of e){if("direct"===r.method.type&&s)return s;if("deferred"===r.method.type){if(n)continue;const e=t.find(pn);if(e)return e;continue}if(Mn(r)){const e=t.filter(nn).find(e=>e.id===r.method.token);if(e)return e;continue}if(Sn(r)){const e=t.find(e=>"PAYPAL"===e.paymentMethod&&"billing_agreement"===e.variant&&e.vaultedToken===r.method.token);if(e)return e;continue}const e=kn(r,t,a);if(e)return e}}(a.paymentLines.value,this.availableUserStoredPaymentMethods.value,this.availablePaymentMethods.value,_n({card:this.newCard.value,billingAddress:a.billingAddress.value}))),this.#t=n(()=>this.proposedSelectedPaymentMethod.value??this.autoselectTarget.value),this.selectedPaymentMethods=n(()=>{const e=this.#t.value;return e?[e]:[]}),this.paymentMethods=n(()=>function({cardItems:e,nonCardItems:t,autoselectTarget:a}){const s=e.find(({method:e})=>e.id===G),n=[...e.filter(({method:e})=>e.id!==G)].sort((e,t)=>Ae(e.method,t.method)),r=[...t].sort((e,t)=>Ae(e.method,t.method)),i=n.filter(wn),o=r.filter(wn),d=i.find(({method:e})=>nn(e)&&e.paymentAttributes.defaultPaymentMethod),l=[i[0],o[0]].filter(e=>void 0!==e).sort((e,t)=>Ae(e.method,t.method))[0],u=(a?[...i,...o].find(({method:e})=>e.id===a.id&&e.paymentMethod===a.paymentMethod):void 0)??d??l;return u?[...Pn([s]),u,...n.filter(e=>e!==u),...r.filter(e=>e!==u)]:[...Pn([s]),...n,...r]}({cardItems:[...Pn([_n({card:this.newCard.value,billingAddress:a.billingAddress.value})]),...this.customerCreditCards.value.map(e=>U(e,{cvvVerificationEnabled:this.deps.storeVaultGuestCvvVerificationEnabled}))].map(e=>({method:e,isValidForCheckout:!0,isExpired:e.paymentAttributes.expired,isDisabled:!1,...En({identity:this.deps.identity,storeVaultEnabled:this.deps.storeVaultEnabled,card:e})})),nonCardItems:this.availableUserStoredPaymentMethods.value.filter(e=>!nn(e)).map(e=>({method:e,isValidForCheckout:!0,isExpired:!1,isDisabled:!1,canEdit:!1,canDelete:!1,canSetDefault:!1,isDefault:!1})),autoselectTarget:this.usesCustomerAccountSelectionRule?this.autoselectTarget.value:void 0})),this.#a=n(()=>{const e=this.#t.value;if(e)return this.paymentMethods.value.find(({method:t})=>t.id===e.id&&t.paymentMethod===e.paymentMethod)}),this.selectedPaymentMethodItems=n(()=>{const e=this.#a.value;return e?[e]:[]}),this.selectedCreditCard=n(()=>{const e=this.#t.value;return nn(e)?e.paymentAttributes:void 0}),this.cardPaymentMethods=n(()=>this.paymentMethods.value.filter(e=>nn(e.method))),this.activeOrExpiredCardMethods=this.cardPaymentMethods,this.isEveryCardExpired=n(()=>{const e=this.cardPaymentMethods.value;return e.length>0&&e.every(e=>e.isExpired)});const d=n(()=>{const e=sa(this.availablePaymentMethods.value);if(!O(e))return!1;const t=this.selectedCreditCard.value;return!!t&&a.paymentLines.value.some(e=>"direct"===t.id?"direct"===e.method.type:e.method.type===Dt.CreditCard&&e.method.token===t.id)});this.msi={binResolution:"client",selectedCardBin:n(()=>{const e=this.selectedCreditCard.value;if(e)return"direct"===e.id?this.newCard.value?.creditCardFirstDigits:this.selectableCustomerCreditCards.value.find(t=>t.token===e.id)?.firstDigits}),clearInstallments:z,expandedVisible:d,collapsedVisible:d}}async promoteSelectedPaymentMethod(e){const t=ft(e,null);return t?(this.deps.paymentMethodPromotions.promote(t),this.selectPaymentMethod(t,"buyer")):{status:"handled",effects:{...vn,selectByBuyerKey:Qt(e)}}}canShowAsGuestCheckoutMethod(){return!1}async selectPaymentMethod(e,t="programmatic"){if(!e)return{status:"not-handled"};if(!nn(e)){const a=ve(e,this.availablePaymentMethods.value);if(!a)return{status:"not-handled"};const s=Qt(a);return"buyer"===t?{status:"handled",effects:{...vn,selectByBuyerKey:s}}:(this.deps.setPaymentLine(s),{status:"handled",effects:vn})}if("buyer"===t)return this.selectCreditCardByBuyer({paymentMethod:e});if("direct"===e.id)return this.deps.setPaymentLine(G),{status:"handled",effects:vn};const a=this.selectableCustomerCreditCards.value.find(t=>t.token===e.paymentAttributes.id);return a?(this.deps.setPaymentLine(Pe(a)),{status:"handled",effects:vn}):{status:"not-handled"}}async deleteCreditCard({id:e}){if("direct"===e){const{proposed:e}=this.deps.proposal;if(!this.newCard.value)return{status:"failed"};this.newCard.value=void 0,e.acceptPaymentVaulting.value=!1;const t=this.selectableCustomerCreditCards.value[0];if(t)this.deps.setPaymentLine(Pe(t));else{const t=this.autoselectTarget.value,a=t?ve(t,this.availablePaymentMethods.value):void 0;a?this.deps.setPaymentLine(Qt(a)):e.paymentLines.value=e.paymentLines.value.filter(e=>"direct"!==e.method.type)}return{status:"success",shouldResetSuggestedBillingAddress:Boolean(t),shouldResetBillingAddressToShipping:"businessCustomer"!==this.deps.identity}}const t=this.#t.value,a=nn(t)&&t.id===e,s=this.selectableCustomerCreditCards.value.find(t=>t.token!==e),n=await Es({graphql:this.deps.graphql,token:e,genericError:this.deps.i18n.translate("customer_payment_methods.delete_customer_mandate.generic_error")});return n.token?(a&&s&&this.deps.setPaymentLine(Pe(s)),{status:"success",shouldNegotiatePaymentMethods:!0}):{status:"failed",bannerError:n.error}}async updateCreditCard({id:e,billingAddress:t,defaultPaymentMethod:a=!1}){const s=await ws({graphql:this.deps.graphql,token:e,address:t,extendedAddressMode:this.deps.extendedAddressMode,defaultPaymentMethod:a,genericError:this.deps.i18n.translate("shipping.address_form.generic_error")});return s.token?{status:"success",shouldNegotiatePaymentMethods:!0}:{status:"failed",bannerError:s.error}}async addCreditCard(){return this.reportUnexpectedUse("addCreditCard"),bn}async completeCreditCardVerificationAndVault(){return this.reportUnexpectedUse("completeCreditCardVerificationAndVault"),bn}dispose(){}async selectCreditCardByBuyer({paymentMethod:e}){let t,a,s;if("direct"===e.id){const e=this.newCard.value;if(!e)return{status:"not-handled"};t=G,a=e,s=e.creditCardFirstDigits}else{const a=this.selectableCustomerCreditCards.value.find(t=>t.token===e.paymentAttributes.id);if(!a)return{status:"not-handled"};t=Pe(a),s=a.firstDigits,Ps({userEvents:this.deps.userEvents,shopId:this.deps.shopId,checkoutSessionIdentifier:this.deps.checkoutSessionIdentifier,card:a})}return this.deps.isMsiAvailable&&(this.deps.proposal.proposed.paymentLines.value=z(this.deps.proposal.proposed.paymentLines.value)),{status:"handled",effects:{...vn,selectByBuyerKey:t,...a?{selectByBuyerPaymentMethod:a}:{},updateSelectedCardBin:!0,selectedCardFirstDigits:s,preserveExistingBinPrefix:e.id===G,claimMsiBin:this.deps.isMsiAvailable,claimedMsiBin:this.deps.isMsiAvailable?s:void 0,shouldNegotiate:!0}}}reportUnexpectedUse(e){Cn({...this.deps,managerName:"CustomerPaymentMethodManager",methodName:e})}};function _n({card:e,billingAddress:t}){if(e?.brand&&e.creditCardLastFourDigits)return{id:G,paymentMethod:"CREDIT_CARD",paymentAttributes:{id:G,brand:e.brand,expired:!1,expiryMonth:0,expiryYear:0,lastDigits:e.creditCardLastFourDigits,name:e.cardholderName,billingAddress:{address:t??{}}},lastUsedAt:null}}function Pn(e){return e.filter(e=>void 0!==e)}function Mn(e){return e.method.type===Dt.CreditCard}function Sn(e){return e.method.type===Dt.PayPal}function kn(e,t,a){const s=Qt(e.method);return t.find(e=>{if(nn(e))return!1;const t=ve(e,a);return!!t&&s===Qt(t)})}function An(...e){const t=[],a=new Set;for(const s of e)for(const e of s){const s=`${e.paymentMethod}:${e.id}`;a.has(s)||(a.add(s),t.push(e))}return t}function wn(e){return e.isValidForCheckout&&!e.isExpired&&!e.isDisabled}function En({identity:e,storeVaultEnabled:t,card:a}){if("direct"===a.id)return xn;if("businessCustomer"===e)return In;const{paymentAttributes:s}=a;return t?s.expired?s.deletable?{canEdit:!1,canDelete:!0,canSetDefault:!1,isDefault:Boolean(s.defaultPaymentMethod)}:In:{canEdit:!0,canDelete:Boolean(s.deletable),canSetDefault:!0,isDefault:Boolean(s.defaultPaymentMethod)}:In}var In={canEdit:!1,canDelete:!1,canSetDefault:!1,isDefault:!1},xn={canEdit:!1,canDelete:!0,canSetDefault:!1,isDefault:!1},Dn={status:"failed"},Ln=class{constructor(e){this.availablePaymentMethods=o([]),this.availableUserStoredPaymentMethods=o([]),this.paymentMethods=o([]),this.selectedPaymentMethods=o([]),this.selectedPaymentMethodItems=o([]),this.selectedCreditCard=o(void 0),this.activeOrExpiredCardMethods=o([]),this.disabledCardMethodsForInstallments=o([]),this.isEveryCardDisabled=o(!1),this.isEveryCardExpired=o(!1),this.cardPaymentMethods=o([]),this.promotedMethods=o([]),this.msi={binResolution:"client",selectedCardBin:o(void 0),clearInstallments:e=>e,expandedVisible:o(!1),collapsedVisible:o(!1)},this.newCard=o(void 0),this.canSetCreditCardNickname=o(!1),this.addCreditCardStrategy="vault-and-select",this.unexpectedUseOptions=e}canShowAsGuestCheckoutMethod(){return!1}async selectPaymentMethod(){return this.reportUnexpectedUse("selectPaymentMethod"),{status:"not-handled"}}async promoteSelectedPaymentMethod(){return this.reportUnexpectedUse("promoteSelectedPaymentMethod"),{status:"not-handled"}}async deleteCreditCard(){return this.reportUnexpectedUse("deleteCreditCard"),Dn}async updateCreditCard(){return this.reportUnexpectedUse("updateCreditCard"),Dn}async addCreditCard(){return this.reportUnexpectedUse("addCreditCard"),Dn}async completeCreditCardVerificationAndVault(){return this.reportUnexpectedUse("completeCreditCardVerificationAndVault"),Dn}dispose(){}reportUnexpectedUse(e){Cn({...this.unexpectedUseOptions,managerName:"FallbackPaymentMethodManager",methodName:e})}};function Nn(e){return{id:e.id,bank:e.bank,brand:e.brand,defaultPaymentMethod:e.preferred,expired:e.expired,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,lastDigits:e.lastDigits,lastUsedAt:e.lastUsedAt,name:e.name,nickname:e.nickname,billingAddress:e.billingAddress,cvvVerification:e.verified?void 0:{type:"session-token"}}}function Tn(e){switch(e.paymentMethod){case"CREDIT_CARD":return{id:e.id,paymentMethod:"CREDIT_CARD",paymentAttributes:Nn(e.paymentAttributes),lastUsedAt:e.lastUsedAt};case"IDEAL":case"CUSTOM_ONSITE":case"APPLE_PAY":case"OFFSITE":case"MANUAL_PAYMENT":case"CUSTOM_MANUAL_PAYMENT":case"PAYMENT_ON_DELIVERY":case"SHOP_PAY_BALANCE":return e}}function Bn(e,t){switch(e.paymentMethod){case"CREDIT_CARD":return t.find(t=>xt(t)&&t.id===e.id);case"IDEAL":case"CUSTOM_ONSITE":case"APPLE_PAY":case"OFFSITE":case"MANUAL_PAYMENT":case"CUSTOM_MANUAL_PAYMENT":case"PAYMENT_ON_DELIVERY":case"SHOP_PAY_BALANCE":return e;case"SHOP_PAY":case"SHOP_PAY_INSTALLMENTS":case"PAYPAL":case"BANK":case"DEFERRED":return;default:y(e)}}var Un={id:"2bcff8985dbaa04eadb413f088e89a17952466f58df58d4f1fd47003417e8f71",type:"query",name:"CreditCardActiveSubscriptions",source:"query CreditCardActiveSubscriptions($id:ID!,$uuid:String!,$first:Int){creditCardActiveSubscriptions(id:$id,uuid:$uuid,first:$first){pageInfo{hasNextPage __typename}nodes __typename}}"};function Fn(e,t){let a=e.paymentMethod.toLowerCase(),s="";switch(e.paymentMethod){case"CREDIT_CARD":e.paymentAttributes?.brand&&(a=e.paymentAttributes.brand);break;case"CUSTOM_ONSITE":a=X(t,{paymentBrands:e.paymentBrands,paymentMethodIdentifier:e.paymentMethodIdentifier})?.name||"custom_onsite",s=e.paymentBrands?.slice().sort().join(",")??"";break;case"IDEAL":a="ideal";break;case"OFFSITE":a=e.name,s=e.paymentBrands?.slice().sort().join(",")??"";break;case"MANUAL_PAYMENT":case"CUSTOM_MANUAL_PAYMENT":case"PAYMENT_ON_DELIVERY":a=e.name;break;case"APPLE_PAY":a="apple_pay";break;case"SHOP_PAY":a="shop_pay";break;case"SHOP_PAY_INSTALLMENTS":a="shopify_installments";break;case"SHOP_PAY_BALANCE":a="shop_pay_balance";break;case"PAYPAL":a="paypal_express";break;case"BANK":a=e.displayName||"bank";break;case"DEFERRED":a="deferred";break;default:y(e)}return{paymentMethodName:a,paymentBrands:s}}var Rn=class extends Error{constructor(...e){super(...e),this.name="EmptySessionIdError"}},Vn=class extends Error{constructor(...e){super(...e),this.name="BuyerDetailsRefreshError"}},On=class{#t;#a;constructor(e){this.newCard=o(void 0),this.canSetCreditCardNickname=o(!0),this.addCreditCardStrategy="vault-and-select",this.deps=e;const{shopPay:t,installmentsPaymentMethodSelected:a,isApplePayAvailable:s,filteredNegotiatedPaymentMethods:r,isCreditCardDisabled:i,msiEligibilityByCardId:d,hasSellingPlan:l}=e;this.availablePaymentMethods=o(r),this.shopPayAvailableUserStoredPaymentMethods=n(()=>{const e=this.availablePaymentMethods.value;return e.length?We(t.user.paymentMethods.value,e):[]}),this.availableUserStoredPaymentMethods=n(()=>this.shopPayAvailableUserStoredPaymentMethods.value.map(Tn)),this.promotedMethods=n(()=>t.session.promotedPaymentMethods.value.map(Tn)),this.#t=n(()=>{const e=t.session.selectedPaymentMethods.value[0];return e?Tn(e):void 0}),this.selectedPaymentMethods=n(()=>{const e=this.#t.value;return e?[e]:[]}),this.selectedCreditCard=n(()=>{const e=t.session.selectedPaymentMethods.value[0];return e&&xt(e)?Nn(e.paymentAttributes):void 0}),this.listedShopPayPaymentMethods=n(()=>{const e=t.user.paymentMethods.value,n=this.shopPayAvailableUserStoredPaymentMethods.value,r=this.availablePaymentMethods.value,o=t.session.promotedPaymentMethods.value,d=t.user.paymentMethodHistory.value,l=e.filter(xt).map(e=>({method:e,isValidForCheckout:n.includes(e),isExpired:e.paymentAttributes.expired,isDisabled:i(e.paymentAttributes)})),u=a?[]:A({negotiatedPaymentMethods:r,userStoredPaymentMethods:e,paymentMethodHistory:d,isApplePayAvailable:s}),c=[...l.sort((e,t)=>Ae(e.method,t.method)),...u.sort((e,t)=>Ae(e.method,t.method))];let m=-1,h="";for(const[t,a]of c.entries()){const e=a.method.lastUsedAt??"";e>h&&(h=e,m=t)}m>0&&c.unshift(...c.splice(m,1));const p=t.session.selectedPaymentMethods.value[0],y=new Set(o.map(e=>e.id));return c.filter(({method:e})=>!!xt(e)||!(!p||xt(p)||e.id!==p.id)||!!y.has(e.id)||At(e))}),this.shopPayPaymentMethods=n(()=>{const a=this.listedShopPayPaymentMethods.value;if(!a.some(({method:e})=>"SHOP_PAY_BALANCE"===e.paymentMethod))return a;const s=e.checkout.negotiator.current.fields.paymentDue.value,n=Boolean(e.paymentExemptionReason.value),r=Nt({isShopPayExternal:"shopPayExternal"===e.source.type,hasRemoteMerchandise:Boolean(e.checkout.negotiator.current.fields.remoteMerchandiseDetails.value?.stableIdToShopId.size),hasInstallmentsPayment:Boolean(t.installments.payment.value)}),i=void 0!==s&&s.amount<=0&&!n;return a.flatMap(e=>{if("SHOP_PAY_BALANCE"!==e.method.paymentMethod)return[e];if(!r||i)return[];const t=ze(e.method.balance,s,n);return[{...e,isDisabled:!t}]})}),this.paymentMethods=n(()=>this.shopPayPaymentMethods.value.map(({method:e,...t})=>({...t,method:Tn(e),canEdit:xt(e),canDelete:xt(e),canSetDefault:!1,isDefault:!1}))),this.#a=n(()=>{const e=this.#t.value;if(e)return this.paymentMethods.value.find(({method:t})=>t.id===e.id&&t.paymentMethod===e.paymentMethod)}),this.selectedPaymentMethodItems=n(()=>{const e=this.#a.value;return e?[e]:[]}),this.cardPaymentMethods=n(()=>this.paymentMethods.value.filter(e=>nn(e.method))),this.activeOrExpiredCardMethods=n(()=>this.cardPaymentMethods.value.filter(e=>!(a&&e.isDisabled))),this.disabledCardMethodsForInstallments=n(()=>a?this.cardPaymentMethods.value.filter(e=>e.isDisabled):[]),this.isEveryCardDisabled=n(()=>{const e=this.cardPaymentMethods.value;if(0===e.length)return!1;const t=new Set(this.disabledCardMethodsForInstallments.value.map(e=>e.method.id)),a=e.filter(e=>e.isExpired&&!t.has(e.method.id)).length;return e.length===t.size+a}),this.isEveryCardExpired=n(()=>{const e=this.cardPaymentMethods.value;if(0===e.length)return!1;const t=new Set(this.disabledCardMethodsForInstallments.value.map(e=>e.method.id)),a=e.filter(e=>!t.has(e.method.id));return 0!==a.length&&a.every(e=>e.isExpired)});const u=n(()=>{const e=sa(this.availablePaymentMethods.value);if(!O(e))return!1;const t=this.selectedCreditCard.value;return Boolean(t&&d.value[t.id])});this.msi={binResolution:"server",selectedCardBin:n(()=>{}),clearInstallments:kt,expandedVisible:n(()=>!!u.value&&"SHOPIFY_INSTALLMENTS"!==t.session.paymentMethodOption.value?.name),collapsedVisible:n(()=>u.value&&!l.value)}}canShowAsGuestCheckoutMethod(e){const{shopPay:t}=this.deps;return t.visibility.showGuestCheckoutPaymentMethods&&!("wallet"===e.type&&("SHOP_PAY"===e.name||"SHOPIFY_INSTALLMENTS"===e.name))}async selectPaymentMethod(e,t="programmatic",a){const{shopPay:s,updateCheckoutAddress:n,shippingRequired:r}=this.deps;if(!e)return s.session.clearPaymentMethod(),{status:"handled",effects:vn};const i=Bn(e,s.user.paymentMethods.value);if(!i)return{status:"not-handled"};if("buyer"===t&&this.recordPaymentMethodSelected(e),nn(e)){const t=this.selectCreditCard({id:e.paymentAttributes.id});return ta(i,s.user.paymentMethods.value,ve(i,this.availablePaymentMethods.value))&&this.#s(i,a),await t,{status:"handled",effects:vn}}const o=ve(i,this.availablePaymentMethods.value);return ta(i,s.user.paymentMethods.value,o)&&this.#s(i,"buyer"===t?{...a,buyerInitiated:!0}:a),(da(i)||yt(i)||Ht(i)||fa(i))&&await n({billingAddress:s.session.selectedBillingAddress.value?.address,fallbackPhoneNumber:s.user.phoneNumber.value},r.value),{status:"handled",effects:vn}}async promoteSelectedPaymentMethod(e){const{shopPay:t}=this.deps,a=Ct(e,t.user.paymentMethods.value);return a&&(t.session.selectPaymentMethods([a]),t.session.unstable_promotePaymentMethod(a)),{status:"handled",effects:{...vn,selectByBuyerKey:Qt(e)}}}getSavedCardActiveSubscriptionsLookup(e){const t=this.deps.shopPay.user.paymentMethods.value.filter(xt).map(e=>e.paymentAttributes).find(t=>t.id===e.id);if(!t)return;const a={id:t.id,uuid:t.uuid,first:3},s=_(Un,a),{shopPayGraphql:n}=this.deps;return{key:s,read:()=>n.read(s)?.creditCardActiveSubscriptions?.nodes,async load(){const{data:e}=await n.staticQuery(Un,{variables:a});return e?.creditCardActiveSubscriptions?.nodes??[]}}}async selectCreditCard({id:e}){const{shopPay:t}=this.deps,a=t.user.paymentMethods.value.filter(xt).map(e=>e.paymentAttributes).find(t=>t.id===e);if(!a)return;const{updateCheckoutAddress:s,fallbackPhoneNumber:n}=this.deps;t.session.selectPaymentMethods([{id:a.id,lastUsedAt:a.lastUsedAt,paymentMethod:"CREDIT_CARD",paymentAttributes:a}]),this.clearShopPayPaymentLines(),await s({billingAddress:a.billingAddress.address,fallbackPhoneNumber:n})}async deleteCreditCard({id:e}){return this.deleteCreditCardById({id:e})}async updateCreditCard({id:e,billingAddress:t,nickname:a}){const{shopPay:s,updateCreditCard:n,checkoutContext:r,markShopCashStatesStale:i,observability:o}=this.deps,d=s.user.paymentMethods.value.filter(xt).map(e=>e.paymentAttributes).find(t=>t.id===e);if(!d)return{status:"failed"};const l=await n(t,e,d.uuid,r,a);if("success"===l.status&&l.creditCard){const{creditCard:t}=l;s.user.updateCreditCard(e,t),this.selectCreditCard({id:t.id}).catch(e=>{o.error(e)})}if(i(),"success"!==l.status){const e=tt();return va({addressErrors:e,shopPayErrors:l.errors,i18n:this.deps.i18n,observability:o,userEvents:this.deps.userEvents,source:this.deps.source,configuration:this.deps.checkout.configuration,shop:this.deps.shop,addressContext:"payment-method",submittedAddress:t}),{status:"failed",addressErrors:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.value]))}}return{status:"success"}}async addCreditCard({sessionId:e,billingAddress:t,nickname:a,debitOnly:s=!1,isBlocking:n=!1}){const{createCreditCard:r,checkoutContext:i,markShopCashStatesStale:o,observability:d}=this.deps;if(""===e)return d.error(new Rn("ShopPayPaymentMethodManager: addCreditCard called with empty sessionId")),{status:"failed"};const l=await r(t,e,i,a),u=await this.handleNewCardResponse(l,s,n);return o(),u}async completeCreditCardVerificationAndVault({verificationId:e,billingAddress:t,nickname:a,debitOnly:s=!1,isBlocking:n=!1}){const{completeCreditCardVerification:r,markShopCashStatesStale:i}=this.deps,o=await r(t,e,a),d=await this.handleNewCardResponse(o,s,n);return i(),d}dispose(){}async deleteCreditCardById({id:e,uuid:t}){const{shopPay:a,deleteCreditCard:s,updateCheckoutAddress:n,emptyAddress:r,fallbackPhoneNumber:i,checkoutContext:o,markShopCashStatesStale:d}=this.deps,l=t??a.user.paymentMethods.value.filter(xt).map(e=>e.paymentAttributes).find(t=>t.id===e)?.uuid;if(!l)return{status:"failed"};const u=a.session.selectedPaymentMethods.value[0],c=u&&xt(u)?u.paymentAttributes.uuid:void 0,m=await s(e,l,o);if("success"!==m.status&&!function(e){return e.errors?.some(({message:e})=>"credit_card_not_found"===e)??!1}(m))return{status:"failed"};const h=a.user.paymentMethods.value.filter(xt).map(e=>e.paymentAttributes).filter(e=>e.uuid!==l);if(a.user.removeCreditCard(e),d(),c!==l)return{status:"success"};const p=Te(h);if(p)a.session.selectPaymentMethods([{id:p.id,lastUsedAt:p.lastUsedAt,paymentMethod:"CREDIT_CARD",paymentAttributes:p}]),this.clearShopPayPaymentLines();else{const e=this.paymentMethods.value.find(({method:e,isValidForCheckout:t,isDisabled:a,isExpired:s})=>t&&!a&&!s&&function(e){return nn(e)||Boolean(e.lastUsedAt)}(e))?.method;if(e){const t=Bn(e,a.user.paymentMethods.value);t&&this.#s(t)}else a.session.clearPaymentMethod(),this.clearShopPayPaymentLines(),a.session.unstable_updateSelectedBillingAddress(a.session.selectedShippingAddress.value)}return await n({billingAddress:(p?p.billingAddress.address:a.session.selectedBillingAddress.value?.address)??r.value,fallbackPhoneNumber:i}),{status:"success"}}recordPaymentMethodSelected(e){const{client:t,observability:a,userEvents:s,source:n,checkout:r,shop:i}=this.deps,o=e.paymentMethod.toLowerCase(),{paymentMethodName:d,paymentBrands:l}=Fn(e,this.availablePaymentMethods.value);a.counter({name:"payment_method_selected",value:1,attributes:{payment_method_type:o,payment_method_name:d,payment_brands:l,location:"shop_pay_payment_selector",is_mobile:t.userAgentDetails.isMobile}}),s.monorailEvent({schemaId:"shopify_pay_payment_page_ui_interaction/1.2",payload:{...q(n,r,i),action:"payment_method_selected",paymentMethodName:d}})}async handleNewCardResponse(e,t,a){const{shopPay:s,markShopCashStatesStale:n}=this.deps;if("success"===e.status&&e.creditCard){if(t&&"debit"!==e.creditCard.funding)return await this.deleteCreditCardById({id:e.creditCard.id,uuid:e.creditCard.uuid}),{status:"failed",errors:[{field:["",Fs.DebitOnly],message:""}]};await this.refreshPaymentMethodsFromBuyerDetails()||s.user.addCreditCard(e.creditCard),a?await this.selectCreditCardAndSetPaymentLine({id:e.creditCard.id}):this.selectCreditCardAndSetPaymentLine({id:e.creditCard.id}).catch(e=>{this.deps.observability.error(e)}),n()}return e}async refreshPaymentMethodsFromBuyerDetails(){const{shopPay:e,refreshBuyerDetails:t,paymentRequiredMethod:a,observability:s}=this.deps;try{const s=await t();return"success"===s.status&&(e.updatePaymentMethodsFromBuyerDetails(s,{negotiatedPaymentMethods:this.availablePaymentMethods.value,paymentRequiredMethod:a}),!0)}catch(n){return s.error(n instanceof Error?n:new Vn("Failed to refresh Shop Pay buyer details")),!1}}async selectCreditCardAndSetPaymentLine({id:e}){const t=void 0!==ua(this.deps.proposedPaymentLines.value),a=this.selectCreditCard({id:e});if(t)return a;const{shopPay:s}=this.deps,n=s.session.selectedPaymentMethods.value[0];n&&xt(n)&&n.paymentAttributes.id===e&&ta(n,s.user.paymentMethods.value,ve(n,this.availablePaymentMethods.value))&&this.#s(n),await a}#s(e,t){const{shopPay:a,setPaymentLine:s,observability:n,proposedPaymentLines:r}=this.deps;d(()=>{if(!a.session.selectPaymentMethods([e]))return;const i=$({paymentMethod:e,negotiatedPaymentMethods:this.availablePaymentMethods.value,observability:n});if(void 0===i)return;const{partialPaymentMethod:o,rebuild:d}=j(e,r.value);o||d?s(i,o,{...t,...d&&{rebuild:d}}):t?s(i,void 0,t):s(i)})}clearShopPayPaymentLines(){const{proposedPaymentLines:e}=this.deps;e.value=e.value.filter(e=>!Vt([e],"SHOP_PAY"))}};function $n({enableAutoSelect:e=!0}={}){const{client:a,source:s,environment:n,checkout:r,shop:o,i18n:d,observability:c,userEvents:m,shopPay:p,graphql:{coreGraphql:y,shopPayGraphql:v}}=ca(),f=r.identity.current.value,C=null!=n.devMode,b=function(){const{checkout:{address:{extendedAddressMode:e}},graphql:{shopPayGraphql:t},shopPay:a,source:s}=ca(),n=K({source:s});return u(async(s,r,i,o,d=n)=>{const{data:l,error:u,stepUpDismissed:c}=await Ie(a.session,()=>t.mutate(Zs,{variables:{billingAddress:D(s,e),origin:d,sessionId:r,nickname:o,checkoutContext:i,stepUpChallengeSupported:!0}}));if(c)return{status:"failed",stepUpDismissed:c};if(u||null==l||null==l.creditCardCreate)return{status:"failed"};const{creditCardCreate:m}=l;return Xe(m.userErrors)?{status:"blocked_by_autopay"}:m.userErrors.length>0?{status:"failed",errors:m.userErrors}:m.threeDSecureAuthenticationRequest?{status:"requires_redirect",threeDSecureAuthenticationRequest:m.threeDSecureAuthenticationRequest}:{status:"success",creditCard:m.creditCard?xe(m.creditCard):void 0}},[n,e,a,t])}(),g=function(){const{checkout:{address:{extendedAddressMode:e}},graphql:{shopPayGraphql:t},source:a}=ca(),s=K({source:a});return u(async(a,n,r,i=s)=>{const{data:o,error:d}=await t.mutate(en,{variables:{verificationId:n,billingAddress:D(a,e),origin:i,nickname:r}});if(d||null==o||null==o.creditCardCompleteVerificationAndVault)return{status:"failed"};const{creditCardCompleteVerificationAndVault:l}=o;return Xe(l.userErrors)?{status:"blocked_by_autopay"}:l.userErrors.length>0?{status:"failed",errors:l.userErrors}:{status:"success",creditCard:l.creditCard?xe(l.creditCard):void 0}},[s,e,t])}(),_=function(){const{graphql:{shopPayGraphql:e},source:t}=ca(),a=K({source:t});return u(async(t,s,n,r=a)=>{const{data:i,error:o}=await e.mutate(tn,{variables:{id:t,uuid:s,origin:r,checkoutContext:n}});if(o||null==i||null==i.creditCardDelete)return{status:"failed"};const{creditCardDelete:d}=i;return d.userErrors.length>0?{status:"failed",errors:d.userErrors}:{status:"success"}},[a,e])}(),P=function(){const{graphql:{shopPayGraphql:e},source:t,shop:{myshopifyDomain:a,id:s,countryCode:n},shopPay:{config:r}}=ca(),{checkoutSessionIdentifier:i}=t,o=K({source:t}),{redirectSource:d}=r;return u(async()=>{const{data:t,error:r}=await function(e,{checkoutVersion:t,checkoutIdentifier:a,shopifyDomain:s,shopId:n,redirectSource:r,includeSpiPreselectionThreshold:i,includeSpiCheckoutBadgingVariant:o},{cache:d=!0}={}){return e.staticQuery(Me,{variables:{checkoutContextInput:{checkoutVersion:t,checkoutIdentifier:a,shopifyDomain:s,shopId:n},shopifyDomain:s,redirectSource:r??void 0,includeSpiPreselectionThreshold:i,includeSpiCheckoutBadgingVariant:o},cache:d})}(e,{checkoutVersion:o,checkoutIdentifier:i??"unknown",shopifyDomain:a,shopId:re(s),redirectSource:d,includeSpiPreselectionThreshold:!1,includeSpiCheckoutBadgingVariant:be(n)},{cache:!1});return r||!Ut(t)?{status:"failed"}:x(t)},[i,o,n,d,s,a,e])}(),M=function(){const{checkout:{address:{extendedAddressMode:e}},graphql:{shopPayGraphql:t},shopPay:a,source:s}=ca(),n=K({source:s});return u(async(s,r,i,o,d,l=n)=>{const{data:u,error:c,stepUpDismissed:m}=await Ie(a.session,()=>t.mutate(an,{variables:{id:r,uuid:i,billingAddress:D(s,e),origin:l,nickname:d,checkoutContext:o,stepUpChallengeSupported:!0}}));if(m)return{status:"failed",stepUpDismissed:m};if(c||!u?.creditCardUpdate)return{status:"failed"};const{creditCardUpdate:h}=u;return h.userErrors.length>0?{status:"failed",errors:h.userErrors}:{status:"success",creditCard:h.creditCard?xe(h.creditCard):void 0}},[n,e,a,t])}(),S=K({source:s}),k=cs(),{paymentLines:A}=r.negotiator.parts,w=ps(),{buyerHasActedSignal:E,newCardSignal:I}=r.negotiator.context,L=i(Ea),N=p.user.phoneNumber.value,T=Lt(),B=p.session.isInstallmentsSelected.value,U=sn({isApplePayAvailable:T.value}),F=ma(),{creditCardDisabled:R}=La(),V=Da(),{updateCheckoutAddress:$}=us(),[,Y]=rs({allowPreselect:!1}),H=sa(r.negotiator.current.fields.paymentMethods.value??[]),z=O(H),j=qt(),G=ae(),Q=Js(),{eligibilityByCardId:W}=Be(Ta),J=u(()=>{L&&(L.cashbackState.stale.value=!0)},[L]),X=h(()=>({checkoutIdentifier:s.checkoutSessionIdentifier??"",checkoutVersion:S,shopId:re(o.id),shopifyDomain:o.myshopifyDomain}),[s.checkoutSessionIdentifier,o.id,o.myshopifyDomain,S]),Z=h(()=>"shopPay"===f?new On({shopPay:p,negotiatedPaymentMethods:r.negotiator.current.fields.paymentMethods,installmentsPaymentMethodSelected:B,isApplePayAvailable:T.value,filteredNegotiatedPaymentMethods:U.value,isCreditCardDisabled:R,setPaymentLine:Y,updateCheckoutAddress:$,shippingRequired:r.isShippingRequired,client:a,i18n:d,observability:c,userEvents:m,source:s,checkout:r,shop:o,createCreditCard:b,deleteCreditCard:_,updateCreditCard:M,completeCreditCardVerification:g,refreshBuyerDetails:P,markShopCashStatesStale:J,shopPayGraphql:v,emptyAddress:k,proposedPaymentLines:A,checkoutContext:X,fallbackPhoneNumber:N,paymentRequiredMethod:V.value,msiEligibilityByCardId:W,hasSellingPlan:j,paymentExemptionReason:G}):"customerAccount"===f||"businessCustomer"===f?new gn({proposal:r.proposal,newCard:w,displayablePaymentMethods:F,paymentMethodPromotions:r.paymentMethodPromotions,setPaymentLine:Y,guestCheckoutMethodIntent:Q,isMsiAvailable:z,shopId:o.id,checkoutSessionIdentifier:s.checkoutSessionIdentifier,storeVaultEnabled:o.storeVaultEnabled,storeVaultGuestCvvVerificationEnabled:o.storeVaultGuestCvvVerificationEnabled,graphql:y,extendedAddressMode:r.address.extendedAddressMode,i18n:d,observability:c,userEvents:m,identity:f,deployStage:n.deployStage,isLocalDevelopment:C}):new Ln({observability:c,identity:f,deployStage:n.deployStage,isLocalDevelopment:C}),[f,n.deployStage,C,p,B,T.value,U.value,F,R,z,Y,$,r,a,c,m,s,o,d,y,v,b,_,P,M,g,J,k,A,w,X,N,V.value,W,j,G,Q]);l(()=>()=>Z.dispose(),[Z]);const ee=Z.selectedPaymentMethods.value[0],te=Z.paymentMethods.value,se=Z.availablePaymentMethods.value,ne=Z.availableUserStoredPaymentMethods.value,ie=A.value.some(e=>"direct"===e.method.type);l(()=>{if(!e)return;if("shopPay"!==f)return;if(Z.selectedPaymentMethods.peek()[0]!==ee||Z.paymentMethods.peek()!==te)return;if(ee&&function({selected:e,paymentMethods:t,availablePaymentMethods:a}){return cn(e)?t.some(({method:t})=>t.paymentMethod===e.paymentMethod):Boolean(ve(e,a)||nn(e)&&t.some(({method:t})=>t.paymentMethod===e.paymentMethod&&t.id===e.id))}({selected:ee,paymentMethods:te,availablePaymentMethods:se}))return;if(ie)return;const t=te.filter(({method:e,isValidForCheckout:t})=>t&&!cn(e)).sort((e,t)=>Ae(e.method,t.method)).map(({method:e})=>e),a=function(e){for(const t of e){if(!nn(t))return t;if(!t.paymentAttributes.expired)return t}return e[0]}(t);a&&nn(a)&&a.paymentAttributes.expired&&m.monorailEvent({schemaId:"shopify_pay_payment_page_ui_interaction/1.1",payload:{...q(s,r,o),action:"final_payment_method_expired_after_merchant_filter"}});const n=a?Bn(a,p.user.paymentMethods.value):void 0;if(n)p.session.selectPaymentMethods([n]);else{const e=p.session.clearPaymentMethod("unavailable"),a=p.user.creditCards.peek().length;e&&a>0&&(c.log("shop_pay_payment_method_auto_cleared","[usePaymentMethodManager] No listed payment method was valid for checkout, so the Shop Pay selection was cleared",{checkout_session_identifier:s.checkoutSessionIdentifier,source_type:s.type,clear_reason:"unavailable",held_card_count:a,listed_method_count:te.length,valid_for_checkout_count:t.length,negotiated_direct_present:Boolean(H)}),c.counter({name:"shop_pay_payment_method_auto_cleared",value:1,attributes:{source_type:s.type,clear_reason:"unavailable",negotiated_direct_present:Boolean(H)}}))}},[e,se,ne,r,f,H,c,m,Z,te,ee,o,p.session,p.user.creditCards,p.user.paymentMethods.value,s,ie]);const oe=E.value,de=Boolean(I.value),le=Z instanceof gn?Z.autoselectTarget.value:void 0,ue=Z instanceof gn?Z.proposedSelectedPaymentMethod.value:void 0,ce=A.value[0],me=ce?.method.type,he=Na(ce);return t(()=>{e&&("customerAccount"!==f&&"businessCustomer"!==f||oe||Z instanceof gn&&le&&(de||he||ue&&ue.paymentMethod===le.paymentMethod&&ue.id===le.id||(me&&c.log("payment_method_manager_programmatic_selection_replaced_primary_line","Programmatic payment method selection replaced the proposed primary payment line",{replacedPaymentLineMethodType:me,replacingPaymentMethodType:le.paymentMethod}),Z.selectPaymentMethod(le,"programmatic").catch(()=>{}))))},[e,f,oe,de,Z,le,ue,he,me,c]),Z}var qn="StoreCreditRedemptionCheckbox",Yn="StoreCreditSubscriptionRenewalsCheckbox",Hn=function(e){return e.Init="init",e.Loading="loading",e.Success="success",e.Error="error",e}({});function zn(e,t){return e.filter(e=>!Kn(e,t))}function jn(e,t){return e.some(e=>Kn(e,t))}function Gn({firstOrderTotal:e,storeCreditAccount:t,includeExhausted:a=!1}){if(!e||!t)return;if(e.currencyCode!==t.balance.currencyCode)return;const s=t.balance.amount-e.amount;return s<=0&&!a?void 0:{amount:Math.max(s,0),currencyCode:t.balance.currencyCode}}function Kn(e,t){return aa(e)&&e.method.redemptionContent&&"storeCreditAccountId"in e.method.redemptionContent&&e.method.redemptionContent.storeCreditAccountId===t.id}function Qn({amountDueAtCheckout:e,storeCreditAccount:t}){if(Wn({amountDueAtCheckout:e,storeCreditAccount:t})&&null!=e)return{amount:Math.min(e.amount,t.balance.amount),currencyCode:e.currencyCode}}function Wn({amountDueAtCheckout:e,storeCreditAccount:t}){return null==e||e.currencyCode===t.balance.currencyCode}function Jn({paymentLines:e,storeCreditAccount:t,cost:a}){let s=!1;const n=e.map(e=>{if(!Kn(e,t))return e;if(null==a){if(null==e.cost)return e;const{cost:t,...a}=e;return s=!0,a}return e.cost?.amount===a.amount&&e.cost.currencyCode===a.currencyCode?e:(s=!0,{...e,cost:a})});return s?n:e}function Xn(e,t,a){if("success"!==e.status&&"error"!==e.status)return!1;const s=e.negotiated?.paymentLines?.lines;return null==s?"success"===e.status:jn(s,t)===a}function Zn(e){const{checkout:{negotiator:t}}=ca();return u(async()=>new Promise(a=>{t.negotiate({withResultHandling:!0,fieldsToResolve:["paymentLines"],silenceViolations:["non-store-credit",...wt(["paymentLines"])],runListenersOnError:!0,force:!0,onComplete(t){e.value="success"===t.status?Hn.Success:Hn.Error,a(t)}})}),[t,e])}function er(e,t){const{checkout:{negotiator:a}}=ca(),s=Zn(t);return u(async()=>{const n=e.value;if(!n)return t.value=Hn.Error,!1;t.value=Hn.Loading;const r=a.parts.paymentLines.value,i=r.findIndex(e=>Kn(e,n)),o=r[i];a.parts.paymentLines.value=zn(r,n);const d=Xn(await s(),n,!1);if(o&&!d){const e=zn(a.parts.paymentLines.value,n);a.parts.paymentLines.value=[...e.slice(0,i),o,...e.slice(i)]}return d},[e,t,a.parts.paymentLines,s])}function tr(e,t){const{i18n:n,checkout:{negotiator:r}}=ca(),i=Zn(t),o=r.current.fields.paymentLines,d=Ve(),l=T(),c=qt(),m=Kt(),h=r.current.fields.paymentFlexibilityPaymentTermsTemplate,p=r.current.fields.isImmediateAmountReducedForRedeemables,y=u(()=>Oe({hasSellingPlan:c.value,hasFixedSellingPlan:m.value,paymentTermsTemplateType:h.value?.type}),[c,m,h]),v=s(!1);return a(()=>{if(!y())return;const t=d.value??l.value,a=r.parts.paymentLines.value,s=e.value;if(!s||!v.current)return;const n=o.value?.lines.find(e=>Kn(e,s))?.cost;if(p?.value){if(n){const e=Jn({paymentLines:a,storeCreditAccount:s,cost:n});e!==a&&(r.parts.paymentLines.value=e)}return}if(n&&n.amount>0)return void(v.current=!1);const i=Jn({paymentLines:a,storeCreditAccount:s,cost:Qn({amountDueAtCheckout:t,storeCreditAccount:s})});i!==a&&(r.parts.paymentLines.value=i)}),u(async()=>{const a=e.value;if(!a)return t.value=Hn.Error,!1;t.value=Hn.Loading;const s=zn(r.parts.paymentLines.value,a),o=d.value??l.value,u=y(),c=u?Qn({amountDueAtCheckout:o,storeCreditAccount:a}):void 0;if(v.current=null!=c,u&&!Wn({amountDueAtCheckout:o,storeCreditAccount:a}))return t.value=Hn.Error,Ge({content:n.translate("store_credit_errors.generic_error")}),!1;r.parts.paymentLines.value=[...s,{method:{type:"redeemable",redemptionSource:"STORE_CREDIT",redemptionContent:{storeCreditAccountId:a.id}},...c&&{cost:c}}];const m=await i();if(!Xn(m,a,!0))return v.current=!1,r.parts.paymentLines.value=zn(r.parts.paymentLines.value,a),!1;const h=u&&function(e,t){if("success"===e.status||"error"===e.status)return e.negotiated?.paymentLines?.lines.find(e=>Kn(e,t))?.cost}(m,a);return h&&h.amount>0&&(v.current=!1,r.parts.paymentLines.value=Jn({paymentLines:r.parts.paymentLines.value,storeCreditAccount:a,cost:h})),!0},[l,i,d,r.parts.paymentLines,t,y,e,n])}function ar(e){const{shop:t}=ca(),a=t.hasFlagEnabled(ce),s=T(),n=bt();return r(()=>{if(n.value)return Gn({firstOrderTotal:s.value,storeCreditAccount:e.value,includeExhausted:a})})}function sr(e){const{checkout:{negotiator:t}}=ca(),a=t.current.fields.paymentLines;return r(()=>{const t=e.value;return!(!t||!a.value?.lines)&&jn(a.value.lines,t)})}function nr({afterAppliedRedeemablesChange:s}){const{i18n:n,shop:i,webMcp:o,checkout:{negotiator:d}}=ca(),l=i.hasFlagEnabled(ce),c=Ve(),m=Zt(),h=Kt(),p=qs(),y=sr(p),v=e(Hn.Init),f=$s(p),C=ar(p),g=r(()=>l&&null!=C.value),_=r(()=>m.value||h.value),S=r(()=>m.value?n.translate("payment.store_credit.buying_gift_card"):h.value?n.translate("payment.store_credit.no_fixed_selling_plans"):void 0);a(()=>{f.value&&g.value&&!_.value||M(()=>{d.parts.useStoreCreditForSubscriptionRenewals.value&&(d.parts.useStoreCreditForSubscriptionRenewals.value=!1)})});const k=tr(p,v),A=er(p,v),w=r(()=>v.value===Hn.Loading),I=r(()=>w.value||_.value),x=r(()=>I.value||0===c.value?.amount&&!y.value),D=I,L=r(()=>{const e=[],t=g.value&&d.parts.useStoreCreditForSubscriptionRenewals.value;return(y.value||t)&&e.push(qn),t&&e.push(Yn),e}),N=u(async e=>{const t=y.value,a=e.includes(qn),n=l&&!(t&&!a)&&e.includes("StoreCreditSubscriptionRenewalsCheckbox"),r=a||n,i=d.parts.useStoreCreditForSubscriptionRenewals.peek();if(d.parts.useStoreCreditForSubscriptionRenewals.value=n,r!==t){if(!(r?await k():await A()))return void(d.parts.useStoreCreditForSubscriptionRenewals.value=!r&&i);s?.()}},[k,A,y,d.parts.useStoreCreditForSubscriptionRenewals,l,s]),T=r(()=>f.value&&Boolean(p.value)),B=r(()=>L.value.includes(qn)),U=u(e=>N(e?[...new Set([...L.value,qn])]:[]),[L,N]);t(()=>o?.unstable_provideStoreCreditController({available:T,redeeming:B,applied:y,settling:w,hasGiftCard:m,hasFixedSellingPlan:h,paymentDue:c,setRedeeming:U}),[o,T,B,y,w,m,h,c,U]);const F=r(()=>g.value?C.value:void 0),R=r(()=>{const e=F.value;return e&&e.amount>0?n.translate("payment.store_credit.remaining_for_subscription_charges_description",{amount:n.formatCurrency(e.amount,{currency:e.currencyCode})}):void 0}),V=r(()=>{const e=p.value?.balance;return e&&n.formatCurrency(e.amount,{currency:e.currencyCode})});return P(b,{when:T,children:()=>{const e=S.value;return P(Ke,{accessibilityLabel:n.translate("payment.store_credit.label"),children:P(_a,{name:"store_credit_redemption",values:L.value,multiple:!0,onChange:N,variant:"block",children:[P(Pa,{value:qn,disabled:x.value,secondaryContent:P(E,{type:"strong",children:V}),details:e&&P(E,{children:e}),children:P(Q,{direction:"inline",gap:"base",alignItems:"center",children:[P(E,{children:n.translate("payment.store_credit.apply_label")}),P(b,{when:w,children:P(ie,{})})]})}),P(b,{when:F,children:()=>P(Pa,{value:Yn,disabled:D.value,details:(R.value||e)&&P(Q,{gap:"small-500",children:[R.value&&P(E,{children:R.value}),e&&P(E,{children:e})]}),children:P(E,{children:n.translate("payment.store_credit.use_remaining_for_subscription_charges_label")})})})]})})}})}function rr({renderInSection:e}){const{i18n:t,shop:{name:a,showTipPayments:s},checkout:{negotiator:n}}=ca(),{tipLines:i}=n.current.fields,{tipLines:o}=n.parts,d=r(()=>{const e=i.value?.[0]??o.value[0];return s||Boolean(e&&e.amount.amount>0)}),l=t.translate("tips.description",{shop_name:a}),u=P(rt,{paddingBlockEnd:"base",children:[P(L,{level:2,children:t.translate("tips.title")}),P(pt,{blockSize:"base"}),P(Se,{contentDisplay:"block",inlineSize:"100%",children:l}),P(b,{when:d,children:[P(pt,{blockSize:"small-200"}),P(Se,{contentDisplay:"block",inlineSize:"100%",children:t.translate("tips.custom_label")}),P(pt,{blockSize:"small-100"}),P(Se,{contentDisplay:"block",inlineSize:"33%",children:t.translate("tips.add_tip")})]})]});return Ua(e)?P(Ke,{accessibilityLabel:t.translate("tips.title"),children:u}):u}var ir=C({displayName:"Tipping",renderLoading:e=>P(rr,{...e}),useError:function(e){const{observability:t}=ca();l(()=>{e&&t.error(e,{metadata:{tips:{component:"Tips",failure:"lazy_load"}}})},[e,t])},load:()=>k(()=>import("./6a7f8a66.BJPV7lnG.js"),__vite__mapDeps([8,1,2,3,4,5,6,7,9,10,11,12,13,14,15,16]))});function or(e){const t=Re();return P(b,{when:t,children:P(ir,{...e})})}function dr({children:e}){const t=Re();return P(b,{when:t,children:P(Xt,{sectionId:"tips",children:e})})}or.Prefetch=ir.Prefetch,or.load=ir.load;export{Ja as $,Gs as A,ws as B,un as C,Js as D,Xs as E,Vs as F,ys as G,_s as H,Bs as I,cs as J,ps as K,Ns as L,Ys as M,$s as N,Qs as O,Os as P,Xa as Q,xs as R,cn as S,sn as T,Cs as U,Ps as V,vs as W,rs as X,us as Y,as as Z,dn as _,tr as a,Ha as at,yn as b,Gn as c,$n as d,Wa as et,On as f,nn as g,hn as h,sr as i,Ga as it,qs as j,Ks as k,qn as l,on as m,or as n,Ka as nt,er as o,Fn as p,hs as q,nr as r,Qa as rt,Hn as s,dr as t,za as tt,Yn as u,pn as v,ln as w,mn as x,rn as y,Es as z};