@flopay/react 1.8.12 → 1.8.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -27,7 +27,7 @@ ${Zt.join(`
27
27
  0% { opacity: 1; transform: translateX(0) scale(1); }
28
28
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
29
29
  }
30
- `,oa=44,xr=280;function Va(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Ml={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Al(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var gs={width:"100%",minHeight:oa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Bl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ss(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function qa(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function Fl(e,t){let n=`We couldn't open ${qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function hs(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),r=(0,a.useRef)(null),o=(0,a.useCallback)((m=r.current)=>{let S=m;S?.timer&&(clearTimeout(S.timer),S.timer=null)},[]),i=(0,a.useCallback)((m,S)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(m),m.timer=setTimeout(()=>{m.timer=null,r.current?.generation===m.generation&&(r.current=null,n.current=m.generation,e(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},S))},[o,e]),d=(0,a.useCallback)(m=>{m.yieldedControl&&i(m,600)},[i]),c=(0,a.useCallback)(m=>{o();let S=t.current+1;t.current=S,n.current=null;let ye={generation:S,method:m,timer:null,yieldedControl:!1};return r.current=ye,S},[o]),C=(0,a.useCallback)(m=>{let S=r.current;return typeof m=="number"&&S?.generation!==m?!1:(o(S),r.current=null,(typeof m!="number"||n.current===m)&&(n.current=null),!0)},[o]),y=(0,a.useCallback)(m=>{let S=r.current,ye=m??S?.generation??t.current;(!m||S?.generation===m)&&(o(S),r.current=null),n.current=ye},[o]),b=(0,a.useCallback)(m=>n.current===(m??t.current),[]),P=(0,a.useCallback)(m=>r.current?.generation===m&&n.current!==m,[]),F=(0,a.useCallback)(()=>{let m=r.current;m&&d(m)},[d]),A=(0,a.useCallback)(()=>{let m=r.current;m&&(m.yieldedControl=!0,o(m))},[o]);return(0,a.useEffect)(()=>{let m=()=>{document.visibilityState==="visible"?F():A()},S=()=>{A()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",S),window.addEventListener("focus",F),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",S),window.removeEventListener("focus",F),o()}},[o,A,F]),{startAttempt:c,finishAttempt:C,invalidateAttempt:y,isAttemptInvalidated:b,isAttemptCurrent:P,generationRef:t}}function Dl(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ll(e,t,n){let r=(0,u.isPostalCodeSupported)(e),o=t.trim(),i=n&&r,d=i&&!o,c=i&&!!o&&!(0,u.isValidPostalCode)(e,o);return{visible:n,supported:r,required:i,empty:d,malformed:c}}function Nl(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,u.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function ls(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${Bl(e)} before-click hook failed.`,"validation_error")}function Ua(){return(0,l.jsx)("style",{children:xl})}function Ol(e){return typeof e=="number"?`${e}px`:e}function bs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function vs({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,l.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function cs(e){return e!=="unavailable"&&e!=="load_error"}function sa(e){return(0,l.jsx)(Ul,{...e})}function ds({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:C,onTechnicalFailure:y,runBeforeButtonClick:b,billingName:P,onBuyerIdentityReady:F,onLoadStateChange:A,placeholderBorderRadius:m}){let S=lr(),{emitInstrument:ye}=(0,a.useContext)(Fn),U=(0,Ft.useStripe)(),w=(0,Ft.useElements)(),[ce,q]=(0,a.useState)("loading");(0,a.useEffect)(()=>{A?.(ce)},[ce,A]);let[le,Y]=(0,a.useState)(!1),ge=!(0,u.isValidEmail)(n?.trim())||!P?.trim(),{request:$e,collect:we,finish:Et}=Vr(),ze=(0,a.useRef)(!1),Ee=(0,a.useRef)(null),Re=(0,a.useRef)(null),[oe,ee]=(0,a.useState)(0),[L,_e]=(0,a.useState)(!1),Te=(0,a.useRef)(!1),G=(0,a.useRef)(new Map),{startAttempt:Ie,finishAttempt:Pe,invalidateAttempt:M,isAttemptInvalidated:K,isAttemptCurrent:ke}=hs((te,$,O)=>{y?.(te,$,{...O,popupBlocked:O?.popupBlocked??vr($)}),_e(!0),ee(Fe=>Fe+1)});(0,a.useEffect)(()=>{L&&Re.current?.focus()},[L,oe]);let be=(0,a.useCallback)(()=>{ee(te=>te+1)},[]),Q=(0,a.useCallback)((te,$,O)=>{M(O),y?.("paypal",te,{code:$,popupBlocked:vr(te)}),_e(!0),be()},[M,y,be]),Be=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Te.current&&(Te.current=!1,Be())},[Be,oe]);let it=(0,a.useCallback)(()=>{_e(!1),i?.(null),Be()},[Be,i]);(0,a.useEffect)(()=>{if(!U||ze.current)return;let te=new URLSearchParams(window.location.search),$=te.get("payment_intent"),O=te.get("payment_intent_client_secret"),Fe=te.get("redirect_status");if(!$||!O)return;ze.current=!0;let Je;try{let st=localStorage.getItem(Ro);if(st){let _=JSON.parse(st);_.clientSecret===O&&(Je={..._.accountPatch?{accountPatch:_.accountPatch}:{},..._.sessionId?{sessionId:_.sessionId}:{},..._.nonce?{nonce:_.nonce}:{}})}}catch{}try{localStorage.removeItem(Ro)}catch{}let fe=new URL(window.location.href);fe.searchParams.delete("payment_intent"),fe.searchParams.delete("payment_intent_client_secret"),fe.searchParams.delete("redirect_status"),window.history.replaceState({},"",fe.toString()),(async()=>{try{if(Y(!0),Fe==="failed"){let E="PayPal payment was declined. Please try again.";i?.(E),C?.(Kt("paypal",E));return}let{paymentIntent:st,error:_}=await U.retrievePaymentIntent(O);if(_){i?.(_.message??"Failed to retrieve PayPal payment status.");return}if(st&&(st.status==="requires_capture"||st.status==="succeeded")){let E=typeof st.payment_method=="string"?st.payment_method:st.payment_method?.id;o({id:E??st.id,type:"card",threeDSecureActionResultTokenId:st.id,isPaypal:!0},Je)}else{let E="PayPal payment was not completed. Please try again.";i?.(E),C?.(Kt("paypal",E))}}catch(st){i?.(st instanceof Error?st.message:"Failed to complete PayPal payment.")}finally{Y(!1)}})()},[U,o,i,C]);let vt=(0,a.useCallback)(async te=>{if(d||le){te.reject();return}let $=b?await b("paypal"):{proceed:!0};if(!$.proceed){G.current.delete(oe),te.reject();return}let O=Ie("paypal");G.current.set(oe,{generation:O,accountPatch:$.accountPatch,sessionId:$.sessionId,nonce:$.nonce}),_e(!1),c?.("paypal"),te.resolve()},[d,c,b,Ie,le,oe]),He=(0,a.useCallback)(async te=>{if(!U||!w)return;let $=G.current.get(oe);if($&&!ke($.generation)){G.current.delete(oe);return}if(!$&&K()||$&&!Pe($.generation))return;$||Pe();let O=$??null;if(G.current.delete(oe),!O&&b){let E=await b("paypal");if(!E.proceed){te.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}O={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let Fe=O?.sessionId??e,Je=O?.nonce??t,fe=await Tl({event:te,prepared:O,email:n,billingName:P,methodLabel:"PayPal",collect:we});if(!fe){te.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let st=fe.email,_=Pn({...O?.accountPatch,...fe});try{if(Y(!0),i?.(null),!Fe||!(0,u.isValidEmail)(st))throw new Error("Missing sessionId or email for PayPal payment");await F?.(fe);let E=U.createPaymentMethod,{error:Le,paymentMethod:ue}=await E({type:"paypal"});if(Le){Q(Le,"stripe_paypal_create_payment_method_failed",$?.generation),te.paymentFailed({reason:"fail"});return}let ae=await aa(r,ye,Fe,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ue?.id??null,intentKind:"payment"});if(ae.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let rt=ae.clientSecret,Oe={return_url:window.location.href};if(ue?.id&&(Oe.payment_method=ue.id),typeof window<"u")try{localStorage.setItem(Ro,JSON.stringify({clientSecret:rt,sessionId:Fe,nonce:Je,accountPatch:_}))}catch{}let{error:et,paymentIntent:Mt}=await U.confirmPayment({clientSecret:rt,confirmParams:Oe,redirect:"if_required"});if(et){if(typeof window<"u")try{localStorage.removeItem(Ro)}catch{}if(bo(et)){let J=et.message??"Your payment was declined.";i?.(J),C?.(Kt("paypal",J,{code:sr(et),declineCode:Hr(et)})),await ia({billingApiUrl:r,sessionId:Fe,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:sr(et)??"provider_declined"}})}else Q(et,"stripe_paypal_confirm_failed",$?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ro)}catch{}let R=typeof Mt?.payment_method=="string"?Mt.payment_method:Mt?.payment_method?.id;o({id:R??Mt?.id,type:"card",threeDSecureActionResultTokenId:Mt?.id,isPaypal:!0},{accountPatch:_,paymentMethodCategory:"paypal",sessionId:Fe,nonce:Je});return}catch(E){Q(E,"stripe_paypal_failed",$?.generation)}finally{Y(!1)}},[U,w,e,t,n,P,we,F,r,ye,o,i,C,b,Q,Pe,ke,K,oe]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(vs,{state:ce,placeholderTestId:"flopay-paypal-placeholder",borderRadius:m,children:(0,l.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsx)("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:it,style:gs,children:"Try PayPal again"}),$e&&(0,l.jsx)(Kr,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:Et,onCancel:()=>Et(null)},$e.id),(0,l.jsx)("div",{style:{display:$e?"none":void 0},children:(0,l.jsx)(Ft.ExpressCheckoutElement,{onReady:te=>q(bs(te,["paypal"])),onLoadError:()=>{q("load_error"),ja(jt(S),"paypal","paypal")},onClick:vt,onConfirm:He,onCancel:()=>{let te=G.current.get(oe);G.current.delete(oe),jt(S)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),M(te?.generation),_e(!1),Te.current=!0,be()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ge,emailRequired:ge,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},oe)})]})}),le&&(0,l.jsx)(Ln,{status:"processing"})]})}function us({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:d,onErrorChange:c,onButtonClick:C,onDecline:y,onTechnicalFailure:b,runBeforeButtonClick:P,billingName:F,onBuyerIdentityReady:A,onLoadStateChange:m,placeholderBorderRadius:S}){let ye=lr(),{emitInstrument:U}=(0,a.useContext)(Fn),w=(0,Ft.useStripe)(),ce=(0,Ft.useElements)(),[q,le]=(0,a.useState)("loading");(0,a.useEffect)(()=>{m?.(q)},[q,m]);let[Y,ge]=(0,a.useState)(!1),$e=!(0,u.isValidEmail)(n?.trim())||!F?.trim(),{request:we,collect:Et,finish:ze}=Vr(),Ee=(0,a.useRef)(null),Re=(0,a.useRef)(null),[oe,ee]=(0,a.useState)(0),[L,_e]=(0,a.useState)(!1),[Te,G]=(0,a.useState)("google_pay"),Ie=(0,a.useRef)(!1),Pe=(0,a.useRef)("google_pay"),M=(0,a.useRef)("google_pay"),K=(0,a.useRef)(null),ke=(0,a.useRef)(new Map),{startAttempt:be,finishAttempt:Q,invalidateAttempt:Be,isAttemptInvalidated:it,isAttemptCurrent:vt,generationRef:He}=hs((_,E,Le)=>{b?.(_,E,{...Le,popupBlocked:Le?.popupBlocked??vr(E)}),G(_),_e(!0),ee(ue=>ue+1)});(0,a.useEffect)(()=>{L&&Re.current?.focus()},[L,oe]);let te=(0,a.useCallback)(()=>{ee(_=>_+1)},[]),$=(0,a.useCallback)((_,E,Le,ue)=>{Be(ue),b?.(_,E,{code:Le,popupBlocked:vr(E)}),G(_),_e(!0),te()},[Be,b,te]),O=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Ie.current&&(Ie.current=!1,O())},[O,oe]);let Fe=(0,a.useCallback)(()=>{_e(!1),c?.(null),O()},[O,c]),Je=(0,a.useCallback)(async _=>{let E=!1,Le=B=>{E||(E=!0,_.paymentFailed({reason:"fail",...B?{message:B}:{}}))};if(!w||!ce){Le();return}let ue=ke.current.get(oe);if(ue&&!vt(ue.generation)){ke.current.delete(oe),Le();return}if(!ue&&it()){Le();return}if(ue&&!Q(ue.generation)){Le();return}ue||Q();let ae=_.expressPaymentType??ue?.method??Pe.current,rt=ue??null,Oe=ss(ae),et=jt(ye),Mt=et?.now()??globalThis.performance?.now()??Date.now(),R=new AbortController,J=!1,lt,Xe=new Promise((B,ft)=>{lt=ft}),Zt=window.setTimeout(()=>{J=!0,R.abort(),lt(Oa)},El),Ht=async(B,ft,Tt)=>{let ct=et?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Tt,Xe])}finally{let Rt=et?.now()??globalThis.performance?.now()??Date.now();et?.performance({stage:B,durationMs:Math.max(0,Rt-ct),durationMode:"machine",requestCategory:ft,paymentMethodCategory:"wallet",provider:"stripe",...J?{statusClass:"timeout"}:{}})}};try{if(ge(!0),c?.(null),!rt&&P){let dt=await Ht("processing","other",P(Oe));if(!dt.proceed){Le();return}rt={accountPatch:dt.accountPatch,sessionId:dt.sessionId,nonce:dt.nonce}}let B=rt?.sessionId??e,ft=rt?.nonce??t,Tt=fs({event:_,fallbackEmail:K.current?.email??rt?.accountPatch?.email??n,fallbackName:[K.current?.firstName??rt?.accountPatch?.firstName,K.current?.lastName??rt?.accountPatch?.lastName].filter(Boolean).join(" ")||F});if(!(0,u.isValidEmail)(Tt.email)){Le("Buyer details are required."),Et(qa(ae),Tt).then(dt=>{dt&&(K.current=dt)});return}K.current=null;let ct=Pn({...rt?.accountPatch,...Tt});await Ht("processing","provider_sdk",Promise.resolve(A?.(Tt)));let{error:Rt}=await Ht("tokenization","provider_sdk",ce.submit());if(Rt){$(ae,Rt,"stripe_wallet_submit_failed",ue?.generation),Le();return}if(!B)throw new Error("Missing sessionId or email for payment.");let dn=await Ht("processing","intent_create",aa(r,U,B,ft??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ae,paymentMethodId:null,intentKind:o},{signal:R.signal}));if(dn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let rn=dn.clientSecret,un=(0,u.isSetupIntentClientSecret)(rn)?w.confirmSetup({elements:ce,clientSecret:rn,redirect:"if_required"}):w.confirmPayment({elements:ce,clientSecret:rn,redirect:"if_required"}),Dt=!1,Cn=dt=>{if(Dt||dt.error||ue&&He.current!==ue.generation)return;let ht=dt.setupIntent??dt.paymentIntent,on=ht?.id,tt=ht?.status,Jn=dt.setupIntent?tt==="succeeded":go(typeof tt=="string"?tt:void 0),pt=ht?.payment_method,en=typeof pt=="string"?pt:typeof pt?.id=="string"?pt.id:null;if(!Jn||typeof on!="string"||!en)return;Dt=!0;let Pt=`${ms}:${B}`;if(typeof window<"u")try{localStorage.setItem(Pt,JSON.stringify({createdAt:Date.now(),sessionId:B,nonce:ft,accountPatch:ct,paymentMethodId:en,providerIntentId:on,paymentMethodType:ae}))}catch{}try{d({id:en,type:"card",threeDSecureActionResultTokenId:on},{accountPatch:ct,paymentMethodCategory:"wallet",sessionId:B,nonce:ft})}finally{if(typeof window<"u")try{localStorage.removeItem(Pt)}catch{}}};un.then(dt=>{J&&Cn(dt)},()=>{});let Qt=await Ht("three_ds_handoff","provider_sdk",un),gt=Qt.error;if(gt){if(bo(gt)){let dt=gt.message??"Your payment was declined.";c?.(dt),y?.(Kt(Oe,dt,{code:sr(gt),declineCode:Hr(gt)})),Le(dt),ia({billingApiUrl:r,sessionId:B,nonce:ft,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ae,providerDeclineReason:sr(gt)??"provider_declined"}})}else $(ae,gt,"stripe_wallet_confirm_failed",ue?.generation),Le();return}if(Cn(Qt),!Dt)throw new Error("Invalid provider returned for APM intent")}catch(B){B===Oa&&et?.error({errorCode:"REQUEST_TIMEOUT",stage:"callback",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"timeout",failureCategory:"provider_runtime"}),$(ae,B,B===Oa?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",ue?.generation),Le()}finally{window.clearTimeout(Zt);let B=et?.now()??globalThis.performance?.now()??Date.now();et?.performance({stage:"callback",durationMs:Math.max(0,B-Mt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...J?{statusClass:"timeout"}:{}}),ge(!1)}},[w,ce,e,t,n,F,Et,A,r,U,o,d,c,y,P,$,Q,vt,it,He,ye,oe]),fe=(0,a.useMemo)(()=>{let _=["applePay","googlePay","paypal","link","amazonPay","klarna"],E=new Set(["applePay","googlePay"]),Le=new Set(i.map(u.stripeExpressMethodToOptionKey)),ue={};for(let ae of _)Le.has(ae)?ue[ae]=E.has(ae)?"always":"auto":ue[ae]="never";return ue},[i]),st=(0,a.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(vs,{state:q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:S,children:(0,l.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Fe,style:gs,children:["Try ",qa(Te)," again"]}),we&&(0,l.jsx)(Kr,{identity:we.identity,methodLabel:we.methodLabel,onComplete:ze,onCancel:()=>ze(null)},we.id),(0,l.jsx)("div",{style:{display:we?"none":void 0},children:(0,l.jsx)(Ft.ExpressCheckoutElement,{onReady:_=>{le(bs(_,st))},onLoadError:_=>{le("load_error"),ja(jt(ye),"stripe","wallet")},onClick:async _=>{Pe.current=_.expressPaymentType,M.current=ss(_.expressPaymentType);let E=!0,Le=window.setTimeout(()=>{E=!1,_.reject()},Il),ue=P?await P(M.current):{proceed:!0};if(window.clearTimeout(Le),!E)return;if(!ue.proceed){ke.current.delete(oe),_.reject();return}let ae=be(_.expressPaymentType);ke.current.set(oe,{generation:ae,method:_.expressPaymentType,accountPatch:ue.accountPatch,sessionId:ue.sessionId,nonce:ue.nonce}),_e(!1),C?.(M.current),_.resolve()},onConfirm:Je,onCancel:()=>{let _=ke.current.get(oe);ke.current.delete(oe),jt(ye)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Be(_?.generation),_e(!1),Ie.current=!0,te()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:fe,emailRequired:$e,billingAddressRequired:$e,layout:{maxColumns:1,overflow:"never"}}},oe)})]})}),Y&&(0,l.jsx)(Ln,{status:"processing"})]})}function zl({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:d,backgroundColor:c,borderColor:C,textColor:y,borderRadius:b,fontFamily:P}){let F=(0,u.resolveStripeMethodBrandVariant)(e,t),A=rs[e],[m,S]=(0,a.useState)(!1),ye=F?.backgroundColor??c??"#ffffff",U=F?.borderColor??C??"#d1d5db",w=F?.textColor??y??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&d()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:oa,padding:"0 1rem",backgroundColor:ye,color:w,border:`1px solid ${U}`,borderRadius:b??8,fontSize:"0.95rem",fontWeight:600,fontFamily:P,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,u.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,u.hasVendoredStripeMethodLogo)(e)?8:0},children:[A&&!m?(0,l.jsx)("img",{src:A,alt:"","aria-hidden":"true",onError:()=>S(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):F?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:F.logoSvg}}):null,(0,l.jsx)("span",{children:(0,u.getStripeMethodDisplayName)(e)})]}),i&&(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:w,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function $a({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:c,onErrorChange:C,onDecline:y,onCancel:b,runBeforeButtonClick:P,onButtonClick:F,isProcessing:A,submitButtonColor:m,submitButtonBorderRadius:S,submitButtonStyle:ye,errorText:U}){let w=lr(),{emitInstrument:ce}=(0,a.useContext)(Fn),q=(0,Ft.useStripe)(),le=(0,Ft.useElements)(),[Y,ge]=(0,a.useState)(!1),$e=(0,a.useRef)(!1),[we,Et]=(0,a.useState)(!1),[ze,Ee]=(0,a.useState)("loading"),[Re,oe]=(0,a.useState)(""),ee=!(0,u.isValidEmail)(r?.trim()),L=!ee||(0,u.isValidEmail)(Re.trim()),_e=(0,a.useCallback)(async()=>{if(!q||!le||A||$e.current||!we)return;$e.current=!0,ge(!0);let Te=P?await P("card"):{proceed:!0};if(!Te.proceed){$e.current=!1,ge(!1);return}F?.("card");let G=Te.sessionId??t,Ie=Te.nonce??n,Pe=Er(o?.trim()),M=Pn({email:Te.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:Te.accountPatch?.firstName?.trim()||Pe.firstName,lastName:Te.accountPatch?.lastName?.trim()||Pe.lastName}),K=M.email,ke=Pn({...Te.accountPatch,...M});try{if(C?.(null),!(0,u.isValidEmail)(K))throw new Error("A valid email address is required for payment.");await i?.(M);let be=await le.submit();if(be.error){C?.(be.error.message??"Payment failed.");return}let Q=[M.firstName,M.lastName].filter(Boolean).join(" "),Be=await q.createPaymentMethod({elements:le,params:{billing_details:{email:K,...Q?{name:Q}:{}}}});if(Be.error||!Be.paymentMethod){C?.(Be.error?.message??"Failed to create payment method.");return}let it=Be.paymentMethod;if(!G||!K)throw new Error("Missing sessionId or email for payment.");let vt=it.type||e,He=await aa(d,ce,G,Ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:vt,paymentMethodId:null,intentKind:"payment"});if(He.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let te=He.clientSecret;if(typeof window<"u")try{localStorage.setItem(nr,JSON.stringify({clientSecret:te,sessionId:G,nonce:Ie,accountPatch:ke,paymentMethodId:it.id,paymentMethodType:it.type??e,gateway:"stripe"}))}catch{}let{error:$,paymentIntent:O}=await q.confirmPayment({clientSecret:te,confirmParams:{return_url:window.location.href,payment_method:it.id},redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let fe=$.message??"Payment failed.";C?.(fe),y?.(Kt("card",fe,{code:$.code})),await ia({billingApiUrl:d,sessionId:G,nonce:Ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:$.code??"provider_declined"}});return}let Fe=O?.status;if(!go(Fe)){if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let fe=Fe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";C?.(fe),y?.(Kt("card",fe,{code:Fe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let Je=typeof O?.payment_method=="string"?O.payment_method:O?.payment_method?.id;c({id:Je??it.id,type:"card",threeDSecureActionResultTokenId:O?.id,gateway:"stripe",paymentMethodType:it.type??e},{accountPatch:ke,paymentMethodCategory:"apm",sessionId:G,nonce:Ie})}catch(be){C?.(be instanceof Error?be.message:"Payment failed. Please try again.")}finally{$e.current=!1,ge(!1)}},[q,le,A,we,P,F,t,n,r,o,Re,i,d,ce,e,c,C,y]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ee&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ee&&(0,l.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,l.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:Te=>oe(Te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(Ft.PaymentElement,{onReady:()=>Ee("ready"),onLoadError:()=>{Ee("load_error"),ja(jt(w),"stripe","apm")},onChange:Te=>{Et(!!Te.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,u.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{_e()},disabled:!we||!L||Y||A||ze!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:m,color:"white",border:"none",borderRadius:S,fontSize:"1rem",fontWeight:600,cursor:!we||!L||Y||A||ze!=="ready"?"not-allowed":"pointer",opacity:!we||!L||Y||A||ze!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ye??{}},children:Y?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),U&&(0,l.jsx)(Wr,{margin:"0.75rem 0 0",children:U})]})}function ps({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:d,stripeInstance:c,paymentElementBaseOptions:C,onTokenizedBody:y,onErrorChange:b,onButtonClick:P,onDecline:F,runBeforeButtonClick:A,onLoadStateChange:m,isProcessing:S=!1,submitButtonColor:ye="#4A49FF",submitButtonBorderRadius:U=8,submitButtonStyle:w,buttonAppearance:ce,themeId:q,onExpandApm:le,expandedApmMethod:Y}){let{emitInstrument:ge}=(0,a.useContext)(Fn),[$e,we]=(0,a.useState)(null),[Et,ze]=(0,a.useState)(null),Ee=(0,a.useRef)(!1),{request:Re,collect:oe,finish:ee}=Vr();(0,a.useEffect)(()=>{d.length>0&&c?m?.("ready"):c||m?.("loading")},[d.length,c,m]);let L=(0,a.useCallback)(async M=>{if(!c||Ee.current||S)return;Ee.current=!0,ze(M);let K=A?await A("card"):{proceed:!0};if(!K.proceed){Ee.current=!1,ze(null);return}P?.("card");let ke=K.sessionId??e,be=K.nonce??t,Q=Er([K.accountPatch?.firstName,K.accountPatch?.lastName].filter(Boolean).join(" ")||r),Be=Pn({email:K.accountPatch?.email?.trim()||n?.trim(),firstName:K.accountPatch?.firstName?.trim()||Q.firstName,lastName:K.accountPatch?.lastName?.trim()||Q.lastName});if(!(0,u.isValidEmail)(Be.email)){ze(null);let He=await oe((0,u.getStripeMethodDisplayName)(M),Be);if(!He){Ee.current=!1;return}Be=He,ze(M)}let it=Be.email,vt=Pn({...K.accountPatch,...Be});try{if(b?.(null),!ke||!(0,u.isValidEmail)(it))throw new Error("Missing sessionId or email for payment.");await o?.(Be);let He=await aa(i,ge,ke,be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:M,paymentMethodId:null,intentKind:"payment"});if(He.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let te=He.clientSecret;if(typeof window<"u")try{localStorage.setItem(nr,JSON.stringify({clientSecret:te,sessionId:ke,nonce:be,accountPatch:vt,paymentMethodType:M,gateway:"stripe"}))}catch{}let{error:$,paymentIntent:O}=await c.confirmPayment({clientSecret:te,confirmParams:{return_url:window.location.href,payment_method_data:{type:M,billing_details:{name:[Be.firstName,Be.lastName].filter(Boolean).join(" "),...it?{email:it}:{}}}},redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let fe=$.message??"Payment failed.";b?.(fe),F?.(Kt("card",fe,{code:$.code})),await ia({billingApiUrl:i,sessionId:ke,nonce:be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:M,providerDeclineReason:$.code??"provider_declined"}});return}let Fe=O?.status;if(!go(Fe)){if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let fe=Fe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(fe),F?.(Kt("card",fe,{code:Fe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let Je=typeof O?.payment_method=="string"?O.payment_method:O?.payment_method?.id;y({id:Je??O?.id,type:"card",threeDSecureActionResultTokenId:O?.id,gateway:"stripe",paymentMethodType:M},{accountPatch:vt,paymentMethodCategory:"apm",sessionId:ke,nonce:be})}catch(He){b?.(He instanceof Error?He.message:"Payment failed. Please try again.")}finally{Ee.current=!1,ze(null)}},[c,S,A,P,e,t,n,oe,i,ge,r,o,y,b,F]),[_e,Te]=(0,a.useState)(null),G=le?Y??null:_e,Ie=(0,a.useCallback)(M=>{Ee.current||S||G&&G!==M||((0,u.needsStripeMethodExplicitConfirm)(M)?le?le(M):Te(M):L(M))},[G,S,L,le]),Pe=(0,a.useMemo)(()=>_e?{...C,paymentMethodTypes:[_e]}:null,[_e,C]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?(0,l.jsx)(Kr,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:ee,onCancel:()=>ee(null)},Re.id):d.map(M=>{let K=Y===M,ke=Et===M,be=Et!==null&&Et!==M||Y!=null&&Y!==M;return(0,l.jsxs)(a.default.Fragment,{children:[(0,l.jsx)(zl,{method:M,themeId:q,submitting:ke,disabled:be,highlighted:K,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(M),onClick:()=>Ie(M),backgroundColor:ce?.backgroundColor,borderColor:ce?.borderColor,textColor:ce?.textColor,borderRadius:ce?.borderRadius,fontFamily:ce?.fontFamily}),!le&&_e===M&&Pe&&c&&(0,l.jsx)(Ft.Elements,{stripe:c,options:Pe,children:(0,l.jsx)($a,{method:M,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:y,onErrorChange:b,onDecline:F,onCancel:()=>Te(null),runBeforeButtonClick:A,onButtonClick:P,isProcessing:S,submitButtonColor:ye,submitButtonBorderRadius:U,submitButtonStyle:w})},M)]},M)})})}function Ul({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:d,onDecline:c,onTokenizedBody:C,firstName:y,lastName:b,chv:P,className:F,isProcessing:A,error:m,onErrorChange:S,showPayPal:ye=!0,showStripe:U=!0,enabledPaymentMethods:w,enabledPaymentMethodCountries:ce,showApplePay:q=!0,showGooglePay:le=!0,layout:Y="default",theme:ge,buttonsTheme:$e,buttonsStyles:we,appearance:Et,cardButtonContent:ze,cardBackButtonContent:Ee,cardTitleContent:Re,showSecurityFooter:oe,onButtonClick:ee,onBeforeButtonClick:L,onBuyerIdentityReady:_e,enableAVS:Te,cardFieldOrder:G,cardPreFormSlot:Ie,avsLayout:Pe="row",country:M,zip:K,addressLine1:ke,addressLine2:be,city:Q,state:Be,onCountryChange:it,onZipChange:vt,avsCheck:He,checkoutType:te,checkoutLayout:$,totalAmount:O=0,currency:Fe="usd",initialCardOpen:Je=!1,directPaypal:fe,isSubscription:st=!1,session:_,dataAttachmentPending:E=!1,dataAttachmentRequiresIdentity:Le=!1,debug:ue=!1}){let ae=lr(),rt=Yo(),Oe=(0,a.useContext)(Yn),{emitInstrument:et}=(0,a.useContext)(Fn),Mt=_??Oe.session,R=Mt?.gateways?.paypal?.providerObjectType??fe?.providerObjectType,J=E||Oe.claimPending===!0,lt=Le||Oe.claimRequiresIdentity===!0,Xe=J&&!lt,Zt=Vi(),[Ht,B]=(0,a.useState)(!1),[ft,Tt]=(0,a.useState)(null),[ct,Rt]=(0,a.useState)(M??"US"),[dn,rn]=(0,a.useState)(K??""),[un,Dt]=(0,a.useState)(ke??""),[Cn,Qt]=(0,a.useState)(be??""),[gt,dt]=(0,a.useState)(Q??""),[ht,on]=(0,a.useState)(Be??""),[tt,Jn]=(0,a.useState)(""),[pt,en]=(0,a.useState)({}),Pt=(0,a.useRef)(K??""),Yt=(0,a.useRef)(M??"US"),Sn=(0,a.useRef)(ke??""),pn=(0,a.useRef)(be??""),_n=(0,a.useRef)(Q??""),an=(0,a.useRef)(Be??""),Tn=(0,a.useRef)(""),qt=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(h,V,Ne,W,De)=>{if(qt.current[h])return;let Ke=V?.trim();!Ke||Ke===Ne.current||(Ne.current=Ke,W(Ke),De?.(Ke))};s("country",M,Yt,Rt,it),s("zip",K,Pt,rn,vt),s("addressLine1",ke,Sn,Dt),s("addressLine2",be,pn,Qt),s("city",Q,_n,dt),s("state",Be,an,on)},[M,K,ke,be,Q,Be,it,vt]);let ie=(0,a.useMemo)(()=>(0,u.resolveAVSConfig)(Te),[Te]),mn=ie!==null,On=(0,a.useMemo)(()=>(0,u.isAuthorizationOnlySession)(_),[_]),Xn=!!_?.vault?.html,Cr=!!_?.gateways?.pcivault,mr=!!(_?.gateways?.stripe?.enabledPaymentMethods??w)?.includes("card"),Lt=Xn||mr||Cr,Ye=!!(U&&Lt&&ae&&e),[yr,T]=(0,a.useState)(()=>Y!=="buttons"||Je?e??null:null),[ut,Vt]=(0,a.useState)(0),wn=Y!=="buttons"||Je||!!e&&yr===e,Ce=(0,a.useMemo)(()=>!ae||!Ye||!e||!wn?null:ae.cardCapture({sessionId:e,captureMethod:_?.captureMethod}),[ae,Ye,e,wn,_?.captureMethod]),sn=(0,a.useMemo)(()=>{let s=ct,h=ie?(0,u.isAVSFieldVisible)(ie.postal_code,s):!1;return Ll(s,dn,h)},[ie,ct,dn]),{avsInvalid:wr,invalidAvsFields:Br}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!Ye||!ie)return{avsInvalid:!1,invalidAvsFields:s};let h=ct,V=(De,Ke)=>(0,u.isAVSFieldVisible)(De,h)&&!Ke.trim(),Ne={line1:V(ie.address_line_1,un),city:V(ie.city,gt),state:V(ie.state,ht),zip:sn.empty||sn.malformed};return{avsInvalid:Ne.line1||Ne.city||Ne.state||Ne.zip,invalidAvsFields:Ne}},[Ye,ie,ct,un,gt,ht,sn]),[yn,fr]=(0,a.useState)(!1),[Zn,zn]=(0,a.useState)(!1),[Nt,Un]=(0,a.useState)(!1),[Qn,fn]=(0,a.useState)({line1:!1,city:!1,state:!1}),tn=(0,a.useRef)(!1),qn=(0,a.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),$n=(0,a.useRef)(!1),mt=(0,a.useCallback)(s=>{qn.current[s]=!0,$n.current=!0},[]),gn=(0,a.useCallback)(s=>!tn.current&&qn.current[s],[]),hn=(0,a.useCallback)(s=>{gn(s)&&fn(h=>h[s]?h:{...h,[s]:!0})},[gn]),[jn,xn]=(0,a.useState)(()=>za(_?.vault)),[xe,nn]=(0,a.useState)(Je&&Lt?"card":"buttons"),[Ot,gr]=(0,a.useState)(null),Vn=xe==="expanding"||xe==="card",hr=_?.gateways?.stripe?"stripe":void 0,kn=(0,a.useCallback)(()=>{et?.({class:"card_surface",provider:hr})},[hr,et]),Mn=(0,a.useRef)(null),zt=(0,a.useCallback)(s=>{Mn.current&&clearTimeout(Mn.current),Mn.current=setTimeout(()=>{Mn.current=null,s()},xr)},[]);(0,a.useEffect)(()=>()=>{Mn.current&&clearTimeout(Mn.current)},[]);let N=(0,a.useCallback)(()=>{kn(),T(e??null),Vt(s=>s+1),nn("expanding"),zt(()=>nn("card"))},[zt,kn,e]),j=(0,a.useCallback)(()=>{nn("collapsing"),zt(()=>nn("buttons"))},[zt]),ne=(0,a.useCallback)(s=>{gr(s),nn("apm-expanding"),zt(()=>nn("apm-form"))},[zt]),re=(0,a.useCallback)(()=>{nn("apm-collapsing"),zt(()=>{nn("buttons"),gr(null)})},[zt]);(0,a.useEffect)(()=>{Y==="buttons"&&Je&&Lt&&(T(e??null),nn("card"))},[Y,Je,Lt,e]);let[Me,z]=(0,a.useState)(null),X=(0,a.useRef)(!1),f=(0,a.useRef)(null),H=(0,a.useRef)("idle"),[Z,bt]=(0,a.useState)(null),Ct=(0,a.useRef)(Z);(0,a.useEffect)(()=>{Ct.current=Z},[Z]);let de=n||Zt,Ae=(0,a.useRef)(null),Wt=(0,a.useMemo)(()=>{if(_e||Oe.claimBuyerIdentity||_?.buyerIdentified!==!1||!e||!t)return;let s=`${de}|${e}|${t}`;Ae.current?.key!==s&&(Ae.current={key:s,claim:$r(new ur.PaymentAPI(de,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...b?{lastName:b}:{}})});let h=Ae.current.claim;return async V=>{await h(V)}},[_e,Oe.claimBuyerIdentity,_?.buyerIdentified,e,t,de,o,y,b]),ot=_e??Oe.claimBuyerIdentity??Wt,g=m??ft,p=(0,a.useMemo)(()=>(0,u.resolveTheme)(ge),[ge]),v=(0,a.useMemo)(()=>{let s=p?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)($e);return we?{...s,...we,cardButton:{...s.cardButton,...we.cardButton},cardFormContainer:{...s.cardFormContainer,...we.cardFormContainer},backButton:{...s.backButton,...we.backButton},backButtonIcon:{...s.backButtonIcon,...we.backButtonIcon},submitButton:{...s.submitButton,...we.submitButton},title:{...s.title,...we.title}}:s},[p,$e,we]),Se=Et??p?.appearance,pe=(0,a.useMemo)(()=>ra({appearance:Se,buttonsStyles:v,layout:Y}),[Se,v,Y]),We=Oe.inlineSessionPatchProcessing??!1,Ze=(A??Ht)||We,se=de.replace(/\/+$/,""),D=(0,a.useMemo)(()=>xa({userId:o,email:r,firstName:y,lastName:b,country:M,zip:K},pt),[o,r,y,b,M,K,pt]),me=[D.firstName,D.lastName].filter(s=>!!s?.trim()).join(" "),Ge=!(0,u.isValidEmail)(D.email?.trim()),je=(0,a.useRef)(null);Ye&&je.current===null&&(je.current=Ge);let St=Ye&&(je.current??Ge),Ve=(0,a.useMemo)(()=>Nl(tt,St),[tt,St]),$t=Ve.empty||Ve.malformed,In=(0,a.useMemo)(()=>ae?ae.getRawProvider():null,[ae]),Fr=(0,a.useMemo)(()=>rt?rt.getRawProvider():null,[rt]),eo=O||100,Ao=(0,a.useMemo)(()=>Se?(0,ur.toStripeAppearance)(Se):null,[Se]),Bo=Ao?{appearance:Ao}:null,ni=(0,a.useMemo)(()=>{let s=Ao??{},h=s.rules??{};return{...s,rules:{...h,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...h[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...h[".AccordionItemContents"]??{}}}}},[Ao]),ri=(0,a.useMemo)(()=>{let s=Ui(O);return{...s,currency:Fe.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...Bo}},[O,Fe,Bo]),oi=(0,a.useMemo)(()=>({mode:"payment",amount:eo,currency:Fe.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Bo}),[eo,Fe,Bo]),he=(0,a.useCallback)(s=>{Tt(s),S?.(s)},[S]),ya=(0,a.useRef)(""),[ai,xs]=(0,a.useState)(!1),fa=(0,a.useCallback)(()=>{xs(!0)},[]);(0,a.useEffect)(()=>{if(!Ye||!St||!ot||!ai||$t||ya.current)return;let s=Pn({email:(0,u.isValidEmail)(D.email?.trim())?D.email?.trim():Tn.current.trim(),firstName:D.firstName?.trim(),lastName:D.lastName?.trim()});ya.current=JSON.stringify(s),en(h=>({...h,...s})),Promise.resolve(ot(s)).catch(h=>{ya.current="",he(h instanceof Error?h.message:"Failed to attach buyer details.")})},[Ye,St,ot,ai,$t,D.email,D.firstName,D.lastName,he]),(0,a.useEffect)(()=>{!Ye||!Ce||Ce.setCardFieldOrder?.(G??null,ie==null&&!St)},[Ye,Ce,G,ie,St]),(0,a.useEffect)(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&he(null)},[xe,he]);let Kn=(0,a.useCallback)((s,h,V)=>{c?.(Kt(s,h,V))},[c]),Dr=(0,a.useCallback)((s,h,V)=>{let Ne=V?.popupBlocked??vr(h),W=Fl(s,Ne),De=_r(V?.code)??sr(h)??"external_payment_method_failed",Ke=new u.FloPayError(W,"api_error",{code:"external_payment_method_failed",param:s});z(null),Y==="buttons"&&(nn("buttons"),gr(null)),he(W),d?.(Ke),console.error("[FloPay] External payment method failed:",{method:s,code:De,popupBlocked:Ne})},[Y,d,he]);(0,a.useEffect)(()=>{if(!Ye||!e){xn(null);return}let s=za(_?.vault);if(s){xn(s);return}if(!wn){xn(null);return}xn(null);let h=!0;return new ur.PaymentAPI(se).getVaultCapture(e,t).then(V=>{if(!h)return;let Ne=za(V);Ne?xn(Ne):he("Failed to load the secure card form.")}).catch(V=>{h&&he(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{h=!1}},[Ye,wn,ut,e,_?.vault,se,t,he]);let er=(0,a.useRef)({onComplete:i,onError:d,updateError:he,emitDecline:Kn,resolvedAccount:D,avsConfig:ie,avsCheckProp:He,sessionId:e,nonce:t,baseUrl:se,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt});er.current={onComplete:i,onError:d,updateError:he,emitDecline:Kn,resolvedAccount:D,avsConfig:ie,avsCheckProp:He,sessionId:e,nonce:t,baseUrl:se,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt};let ga=(0,a.useRef)(!1),ii=(0,a.useCallback)(()=>{let{resolvedAccount:s,avsConfig:h,avsCheckProp:V}=er.current,Ne=s.email?.trim(),W=(0,u.isValidEmail)(Ne)?Ne:Tn.current.trim();if(!(0,u.isValidEmail)(W))return null;let De=s.firstName?.trim(),Ke=s.lastName?.trim(),yt=Yt.current||s.country||"US",Gt=h?(0,u.isAVSFieldVisible)(h.state,yt):!1,wt=h?(0,u.isAVSFieldVisible)(h.address_line_1,yt):!1,kt=h?(0,u.isAVSFieldVisible)(h.postal_code,yt):!1,at=h?(0,u.isAVSFieldVisible)(h.city,yt):!1,ln=h?(0,u.isAVSFieldVisible)(h.address_line_2,yt):!1,Qe=wt&&!Gt&&kt?(0,u.getStateFromPostalCode)(yt,(Pt.current??"").trim()):null,cn=Gt?an.current:Qe;return{accountData:{userId:s.userId??"",email:W,...De?{firstName:De}:{},...Ke?{lastName:Ke}:{},...kt&&Pt.current?{zip:Pt.current}:{},...at&&_n.current?{city:_n.current}:{},...cn?{state:cn}:{},...wt&&Sn.current?{addressLine1:Sn.current}:{},...ln&&pn.current?{addressLine2:pn.current}:{},country:yt},...V!==void 0?{avsCheck:V}:{},...h?{avsConfig:{country:(0,u.isAVSFieldVisible)(h.country,yt),postal_code:kt,address_line_1:wt,address_line_2:ln,city:at,state:Gt}}:{}}},[]),si=(0,a.useRef)(J);si.current=J,(0,a.useEffect)(()=>{J||g!==is||er.current.updateError(null)},[J,g]),(0,a.useEffect)(()=>{!Ye||!Ce||Ce.setSubmitGate?.(wr||J||$t)},[Ye,Ce,wr,J,$t]),(0,a.useEffect)(()=>{if(!Ye||!Ce)return;ga.current=!1;let s=!1,h=Ce.on("submitting",()=>{fr(!0),f.current&&clearTimeout(f.current),H.current="validation-window",f.current=setTimeout(()=>{f.current=null,H.current==="validation-window"&&(H.current="processing")},Rl),z("processing");let{baseUrl:Ke,sessionId:yt,nonce:Gt,updateError:wt,onError:kt}=er.current;if(!yt||!Gt)return;let at=ii();if(!at){wt("Enter a valid email address."),H.current="idle",z(null);return}new ur.PaymentAPI(Ke).patchAccountSnapshot(yt,Gt,at,{telemetryMode:"best_effort"}).catch(ln=>{if(!_l(ln))return;let Qe=ln instanceof Error?ln.message:"Please check your billing address and try again.";wt(Qe),H.current="idle",z(null),kt?.(ln instanceof u.FloPayError?ln:new u.FloPayError(Qe,"api_error"))})}),V=Ce.on("complete",async Ke=>{if(Gr(Ke.sessionId??er.current.sessionId),H.current="terminal",z("success"),await new Promise(wt=>setTimeout(wt,1200)),ga.current)return;ga.current=!0;let yt=er.current,Gt=(0,u.isAuthorizationOnlySession)(yt)||Ke.outcome==="authorized";er.current.onComplete?.(Gt?{status:"authorized",paymentIntentId:Ke.intentId,paymentId:Ke.paymentId??yt.paymentId,sessionId:Ke.sessionId??yt.sessionId,authorizationExpiresAt:Ke.authorizationExpiresAt??yt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ke.intentId,checkoutMethod:"card"})}),Ne=Ce.on("decline",async Ke=>{let{updateError:yt,emitDecline:Gt}=er.current,wt=Ke.message??"Your payment was declined. Please try another card or contact your bank.";H.current="terminal",yt(wt),z("error");let kt=Ke.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(Ke.declineReason)??"authorization_declined";Gt("card",wt,{code:kt,declineCode:kt}),await new Promise(at=>setTimeout(at,1500)),!s&&(H.current="idle",z(null))}),W=Ce.on("error",async Ke=>{let{updateError:yt,onError:Gt}=er.current,wt=Ke.message??"There was a problem processing your payment. Please try again.";H.current="terminal",yt(wt),z("error"),Gt?.(new u.FloPayError(wt,"api_error",{code:Ke.failureOutcome??"capture_failed"})),await new Promise(kt=>setTimeout(kt,1500)),!s&&(H.current="idle",z(null))}),De=Ce.on("blocked",()=>{if(!si.current){fr(!0);return}fa(),er.current.updateError(is)});return()=>{s=!0,f.current&&(clearTimeout(f.current),f.current=null),H.current="idle",h(),V(),Ne(),W(),De()}},[Ye,Ce,fa,ii]);let tr=!!fe?.clientId,to=Array.isArray(w),Fo=to&&w.length>0,Ms=to&&w.includes("paypal"),{expressMethods:Do,paymentElementMethods:no}=(0,a.useMemo)(()=>(0,u.partitionStripeMethods)(w,{excludePaypal:tr}),[w,tr]),li=tr||!!rt,As=(0,a.useMemo)(()=>li?Do.filter(s=>s!=="paypal"):Do,[Do,li]),Bs=(0,a.useMemo)(()=>{let s=[];return q&&s.push("apple_pay"),le&&s.push("google_pay"),s},[q,le]),Lr=to?As:Bs,Fs=U&&Lr.length>0,ha=mn?ct:M,Lo=(0,a.useMemo)(()=>{let s=ha?.trim().toUpperCase();return s?ce?no.filter(h=>{let V=ce[h];return!V||V.length===0||V.includes(s)}):(0,u.filterStripeMethodsByCountry)(no,ha):no},[no,ha,ce]),ba=(0,a.useMemo)(()=>({mode:"payment",amount:eo,currency:Fe.toLowerCase(),paymentMethodCreation:"manual",appearance:ni}),[eo,Fe,ni]),[ci,di]=(0,a.useState)("loading"),[ui,pi]=(0,a.useState)("loading"),[mi,yi]=(0,a.useState)("loading"),[Ds,va]=(0,a.useState)(!1),[fi,Pa]=(0,a.useState)("loading"),[No,Ls]=(0,a.useState)();(0,a.useEffect)(()=>{Ls(ns())},[]);let gi=ye&&(tr||(to?Ms:No===!1)),hi=U&&Fs,ro=!Xe&&gi&&tr,bi=fi==="retrying"||fi==="exhausted",oo=!Xe&&gi&&!!Fr&&(!tr||bi),ao=!Xe&&hi&&!!In,io=!Xe&&U&&Fo&&Lo.length>0&&!!In,Ns=ro&&!bi?Ds:oo&&cs(ci),Os=ao&&cs(ui),zs=io&&mi!=="load_error",vi=s=>s==="loading"||s==="ready",Pi=ro||oo&&vi(ci)||ao&&vi(ui)||io&&mi!=="load_error",Oo=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!Oo.current){if(!U&&!ye){Oo.current=!0;let s=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(s),he(s.message)}else if(!U&&ye&&!tr&&!Fr){Oo.current=!0;let s=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(s),he(s.message)}else if(No!==void 0&&!Xe&&!Lt&&!Pi){Oo.current=!0;let s=new u.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});d?.(s),he(s.message)}}},[U,ye,tr,Fr,No,Xe,Lt,Pi,d,he]);let Ci=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(Ci.current||!Fo)return;let s=[];q!==!0&&s.push("showApplePay"),le!==!0&&s.push("showGooglePay"),s.length!==0&&(Ci.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Fo,q,le]);let Si=(0,a.useCallback)((s,h)=>Oe.applyInlineSessionPatch?Oe.applyInlineSessionPatch(s).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let Ne=ls(h,V);return he(Ne.message),d?.(Ne),{error:Ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Oe.applyInlineSessionPatch,t,d,e,he]),Hn=(0,a.useCallback)(async s=>{if(!L)return{proceed:!0};try{let h=await L({method:s,sessionId:e||void 0,createSession:Oe.inlineSessionDraft});if(h===!1)return{proceed:!1};if(h&&typeof h=="object"){h.account&&en(Ne=>({...Ne??{},...h.account}));let V=await Si(h,s);return V.error?{proceed:!1,accountPatch:h.account}:{proceed:!0,accountPatch:h.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(h){let V=ls(s,h);return he(V.message),d?.(V),{proceed:!1}}},[Si,Oe.inlineSessionDraft,L,d,e,he]),wi=(0,a.useCallback)(async(s,h)=>{if(X.current)return;X.current=!0,B(!0),z("processing"),he(null);let V=h?.sessionId??e,Ne=h?.nonce??t,W=xa(D,h?.accountPatch),De=h?.completionPaymentMethodId??ho(s),Ke=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,yt=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,Gt=()=>{et?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:yt})};try{let kt=await new ur.PaymentAPI(se).processPayment(W.userId??"",{sessionId:V,nonce:Ne,paymentMethodCategory:h?.paymentMethodCategory??Al(s),tokenizedData:Ke,accountData:{...h?.accountPatch,userId:W.userId??"",email:W.email??"",...W.firstName?{firstName:W.firstName}:{},...W.lastName?{lastName:W.lastName}:{},...ie?(()=>{let Qe=Yt.current,cn=(0,u.isAVSFieldVisible)(ie.state,Qe),Bn=(0,u.isAVSFieldVisible)(ie.address_line_1,Qe),Jt=(0,u.isAVSFieldVisible)(ie.postal_code,Qe),mo=Bn&&!cn&&Jt?(0,u.getStateFromPostalCode)(Qe,(Pt.current??"").trim()):null,yo=cn?an.current:mo;return{country:Qe,...Jt&&Pt.current?{zip:Pt.current}:{},...(0,u.isAVSFieldVisible)(ie.city,Qe)&&_n.current?{city:_n.current}:{},...yo?{state:yo}:{},...Bn&&Sn.current?{addressLine1:Sn.current}:{},...(0,u.isAVSFieldVisible)(ie.address_line_2,Qe)&&pn.current?{addressLine2:pn.current}:{}}})():{}},chv:P,avsCheck:He??!1,checkoutType:te,checkoutLayout:$,avsConfig:ie?{country:(0,u.isAVSFieldVisible)(ie.country,Yt.current),postal_code:(0,u.isAVSFieldVisible)(ie.postal_code,Yt.current),address_line_1:(0,u.isAVSFieldVisible)(ie.address_line_1,Yt.current),address_line_2:(0,u.isAVSFieldVisible)(ie.address_line_2,Yt.current),city:(0,u.isAVSFieldVisible)(ie.city,Yt.current),state:(0,u.isAVSFieldVisible)(ie.state,Yt.current)}:void 0});if(kt.ok){let Qe=kt.status===204?null:await kt.json().catch(()=>null),cn=(0,u.isAuthorizationOnlySession)(_)||Qe?.status==="authorized";Gr(V),z("success"),bt(null),await new Promise(Bn=>setTimeout(Bn,1200)),i?.(cn?{status:"authorized",...typeof Qe?.paymentId=="string"?{paymentId:Qe.paymentId}:_?.paymentId?{paymentId:_.paymentId}:{},sessionId:typeof Qe?.sessionId=="string"?Qe.sessionId:V,...typeof Qe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Qe.authorizationExpiresAt}:_?.authorizationExpiresAt?{authorizationExpiresAt:_.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"});return}let at=await kt.json().catch(()=>null);if(at?.type==="paypal_redirect_required"){let Qe=at.threeDSecureToken,cn=at.paymentMethodId||s.id||"";if(!ae||!Qe){z("error"),he("PayPal authorization required but no token provided.");return}try{let Bn=rt?.getRawProvider();if(!Bn){he("PayPal is not available.");return}let Jt={return_url:window.location.href};cn&&(Jt.payment_method=cn);let{error:mo}=await Bn.confirmPayment({clientSecret:Qe,confirmParams:Jt,redirect:"if_required"});if(mo){z("error");let yo=mo.message??"PayPal payment failed.";he(yo),Kn("paypal",yo,{code:mo.code})}}catch(Bn){z("error"),he(Bn instanceof Error?Bn.message:"PayPal authorization failed.")}return}if(at?.type==="paypal_direct_required"){let Qe=at.orderId;if(!Qe){z("error"),he("PayPal retry required but no order id provided.");return}let cn=Ct.current?.attempts??0;if(cn>=2){z("error"),he("PayPal payment could not be completed after multiple attempts."),Kn("paypal","paypal_direct_required retry limit exceeded");return}va(!1),Pa("loading"),bt({orderId:Qe,attempts:cn+1}),z(null);return}(0,u.classifyPaymentRejection)(kt.status,at)||Gt(),z("error");let ln=at?.message??"Payment failed. Please try again.";he(ln),Kn(s.isPaypal?"paypal":"card",ln,{code:at?.code??at?.gatewayErrorCode,declineCode:at?.declineCode??at?.gatewayDeclineReason}),await new Promise(Qe=>setTimeout(Qe,1500))}catch(wt){ys(wt)||Gt(),z("error"),he(wt instanceof Error?wt.message:"An unexpected error occurred"),await new Promise(kt=>setTimeout(kt,1500))}finally{B(!1),z(null),X.current=!1}},[se,e,t,D,ie,He,te,$,P,ae,rt,_,i,he,Kn,et]),bn=(0,a.useCallback)((s,h)=>{C?C(s):wi(s,h)},[C,wi]),so=`${ms}:${e}`;(0,a.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(so);if(!s)return;let h;try{h=JSON.parse(s)}catch{localStorage.removeItem(so);return}if(!h||typeof h.createdAt!="number"||Date.now()-h.createdAt<0||Date.now()-h.createdAt>kl||typeof h.paymentMethodId!="string"||typeof h.providerIntentId!="string"||typeof h.paymentMethodType!="string"||h.sessionId!==e||!t||h.nonce!==t||!Lr.includes(h.paymentMethodType)){localStorage.removeItem(so);return}localStorage.removeItem(so),bn({id:h.paymentMethodId,type:"card",threeDSecureActionResultTokenId:h.providerIntentId,gateway:"stripe",paymentMethodType:h.paymentMethodType},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[bn,t,e,so,Lr]);let ki=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||ki.current)return;let s=new URLSearchParams(window.location.search),h=s.get("payment_intent"),V=s.get("payment_intent_client_secret"),Ne=s.get("redirect_status");if(!h||!V)return;let W=kt=>{let at=localStorage.getItem(kt);if(!at)return null;try{return JSON.parse(at)}catch{return localStorage.removeItem(kt),null}},De=W(nr)??W(as),Ke;if(De?.clientSecret){if(De.clientSecret!==V)return;Ke={...De.accountPatch?{accountPatch:De.accountPatch}:{},...De.sessionId?{sessionId:De.sessionId}:{},...De.nonce?{nonce:De.nonce}:{}}}else if(De?.sessionId&&De.sessionId!==e)return;ki.current=!0,localStorage.removeItem(nr),localStorage.removeItem(as);let yt=new URL(window.location.href);yt.searchParams.delete("payment_intent"),yt.searchParams.delete("payment_intent_client_secret"),yt.searchParams.delete("redirect_status"),window.history.replaceState({},"",yt.toString());let Gt=De?.paymentMethodType??De?.tokenType??"card",wt="card";(async()=>{let kt=ae?.getRawProvider();if(!kt){let Jt="Payment is not available \u2014 please refresh and try again.";he(Jt),Kn(wt,Jt);return}if(Ne==="failed"){let Jt="Payment was declined. Please try again.";he(Jt),Kn(wt,Jt);return}let{paymentIntent:at,error:ln}=await kt.retrievePaymentIntent(V);if(ln){let Jt=ln.message??"Failed to retrieve payment status.";he(Jt),Kn(wt,Jt,{code:ln.code});return}let Qe=at?.status,cn=go(Qe);if(!at||!cn){let Jt=Qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(Jt),Kn(wt,Jt,{code:Qe??"missing_payment_intent"});return}let Bn=typeof at.payment_method=="string"?at.payment_method:at.payment_method?.id;bn({id:Bn??De?.paymentMethodId??De?.tokenId??at.id,type:"card",threeDSecureActionResultTokenId:at.id,gateway:De?.gateway??"stripe",paymentMethodType:Gt},Ke)})()},[e,bn,ae,he,Kn]);let Ca=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(ae!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let lo=Y==="buttons",vn=Se?.variables,Us=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Sa=vn?.colorBackground,qs=Sa&&!Us.has(Sa)?Sa:void 0,co=v.cardInputBorder??(lo?"#e5e7eb":"#A4A4FF"),Ii=vn?.colorDanger??"#dc2626",xt=s=>Br[s]&&(Qn[s]||yn),zo=$t&&(Nt||yn),An=s=>s?Ii:co,Uo=(sn.malformed||sn.empty)&&(Zn||yn),$s=An(Uo),wa=v.cardFormContainer?.backgroundColor??qs??(lo?"white":"#EDEDFF"),Nr=v.cardInputBackground??vn?.colorBackground??"white",ka=zr(Ee),Ei=zr(Re),Or=v.nameInput,Ri=v.cardInputFontSize??Ol(Or?.fontSize)??vn?.fontSizeBase??"16px",_i=typeof Or?.fontFamily=="string"?Or.fontFamily:vn?.fontFamily??"Poppins, sans-serif",Ti=Na(Or?.fontWeight)??400,js=v.cardInputColor??(typeof Or?.color=="string"?Or.color:void 0)??vn?.colorText??"#262833",Vs=v.cardInputPlaceholderColor??"#9ca3af",At=vn?.borderRadius??"8px",kr=vn?.borderRadius??v.cardButton?.borderRadius??At,Ir=vn?.colorPrimary??"#4A49FF",Ks=vn?.colorPrimaryHover??Qr(Ir,.12),Ia=vn?.colorText??"#262833",Ea={fontSize:Ri,fontFamily:_i,fontWeight:Ti,color:js,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},uo={marginTop:"0.375rem",...Ea,fontSize:"0.75rem",lineHeight:1.4,color:Ii},Hs={"--flopay-input-placeholder-color":Vs,"--flopay-input-font-size":Ri,"--flopay-input-font-family":_i,"--flopay-input-font-weight":String(Ti)},po=v.cardFormContainer??{},Ra=po.padding??(lo?"0":"1rem"),_a=po.borderRadius??At,Ys=Ce&&jn?(0,l.jsx)(Zr,{capture:Ce,html:jn.html,messageToken:jn.messageToken,expectedOrigin:jn.expectedOrigin,theme:pe,onReady:()=>{if(!St&&!ie||typeof document>"u")return;let s=()=>{let V=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(V){tn.current=!0;try{V.focus()}finally{tn.current=!1}}};$n.current||s()},onError:s=>he(s),onValidation:s=>{let h=H.current;(h==="idle"||h==="validation-window")&&(he(s),s&&H.current==="validation-window"&&(f.current&&(clearTimeout(f.current),f.current=null),H.current="idle",z(null)))}}):(0,l.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),xi=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&kn()},style:{backgroundColor:wa,borderRadius:_a,...po,padding:Ra,...Hs,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
30
+ `,oa=44,xr=280;function Va(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Ml={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Al(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var gs={width:"100%",minHeight:oa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Bl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ss(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function qa(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function Fl(e,t){let n=`We couldn't open ${qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function hs(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),r=(0,a.useRef)(null),o=(0,a.useCallback)((m=r.current)=>{let S=m;S?.timer&&(clearTimeout(S.timer),S.timer=null)},[]),i=(0,a.useCallback)((m,S)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(m),m.timer=setTimeout(()=>{m.timer=null,r.current?.generation===m.generation&&(r.current=null,n.current=m.generation,e(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},S))},[o,e]),d=(0,a.useCallback)(m=>{m.yieldedControl&&i(m,600)},[i]),c=(0,a.useCallback)(m=>{o();let S=t.current+1;t.current=S,n.current=null;let ye={generation:S,method:m,timer:null,yieldedControl:!1};return r.current=ye,S},[o]),C=(0,a.useCallback)(m=>{let S=r.current;return typeof m=="number"&&S?.generation!==m?!1:(o(S),r.current=null,(typeof m!="number"||n.current===m)&&(n.current=null),!0)},[o]),y=(0,a.useCallback)(m=>{let S=r.current,ye=m??S?.generation??t.current;(!m||S?.generation===m)&&(o(S),r.current=null),n.current=ye},[o]),b=(0,a.useCallback)(m=>n.current===(m??t.current),[]),P=(0,a.useCallback)(m=>r.current?.generation===m&&n.current!==m,[]),F=(0,a.useCallback)(()=>{let m=r.current;m&&d(m)},[d]),A=(0,a.useCallback)(()=>{let m=r.current;m&&(m.yieldedControl=!0,o(m))},[o]);return(0,a.useEffect)(()=>{let m=()=>{document.visibilityState==="visible"?F():A()},S=()=>{A()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",S),window.addEventListener("focus",F),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",S),window.removeEventListener("focus",F),o()}},[o,A,F]),{startAttempt:c,finishAttempt:C,invalidateAttempt:y,isAttemptInvalidated:b,isAttemptCurrent:P,generationRef:t}}function Dl(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ll(e,t,n){let r=(0,u.isPostalCodeSupported)(e),o=t.trim(),i=n&&r,d=i&&!o,c=i&&!!o&&!(0,u.isValidPostalCode)(e,o);return{visible:n,supported:r,required:i,empty:d,malformed:c}}function Nl(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,u.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function ls(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${Bl(e)} before-click hook failed.`,"validation_error")}function Ua(){return(0,l.jsx)("style",{children:xl})}function Ol(e){return typeof e=="number"?`${e}px`:e}function bs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function vs({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,l.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function cs(e){return e!=="unavailable"&&e!=="load_error"}function sa(e){return(0,l.jsx)(Ul,{...e})}function ds({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:C,onTechnicalFailure:y,runBeforeButtonClick:b,billingName:P,onBuyerIdentityReady:F,onLoadStateChange:A,placeholderBorderRadius:m}){let S=lr(),{emitInstrument:ye}=(0,a.useContext)(Fn),U=(0,Ft.useStripe)(),w=(0,Ft.useElements)(),[ce,q]=(0,a.useState)("loading");(0,a.useEffect)(()=>{A?.(ce)},[ce,A]);let[le,Y]=(0,a.useState)(!1),ge=!(0,u.isValidEmail)(n?.trim())||!P?.trim(),{request:$e,collect:we,finish:Et}=Vr(),ze=(0,a.useRef)(!1),Ee=(0,a.useRef)(null),Re=(0,a.useRef)(null),[oe,ee]=(0,a.useState)(0),[L,_e]=(0,a.useState)(!1),Te=(0,a.useRef)(!1),G=(0,a.useRef)(new Map),{startAttempt:Ie,finishAttempt:Pe,invalidateAttempt:M,isAttemptInvalidated:K,isAttemptCurrent:ke}=hs((te,$,O)=>{y?.(te,$,{...O,popupBlocked:O?.popupBlocked??vr($)}),_e(!0),ee(Fe=>Fe+1)});(0,a.useEffect)(()=>{L&&Re.current?.focus()},[L,oe]);let be=(0,a.useCallback)(()=>{ee(te=>te+1)},[]),Q=(0,a.useCallback)((te,$,O)=>{M(O),y?.("paypal",te,{code:$,popupBlocked:vr(te)}),_e(!0),be()},[M,y,be]),Be=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Te.current&&(Te.current=!1,Be())},[Be,oe]);let it=(0,a.useCallback)(()=>{_e(!1),i?.(null),Be()},[Be,i]);(0,a.useEffect)(()=>{if(!U||ze.current)return;let te=new URLSearchParams(window.location.search),$=te.get("payment_intent"),O=te.get("payment_intent_client_secret"),Fe=te.get("redirect_status");if(!$||!O)return;ze.current=!0;let Je;try{let st=localStorage.getItem(Ro);if(st){let _=JSON.parse(st);_.clientSecret===O&&(Je={..._.accountPatch?{accountPatch:_.accountPatch}:{},..._.sessionId?{sessionId:_.sessionId}:{},..._.nonce?{nonce:_.nonce}:{}})}}catch{}try{localStorage.removeItem(Ro)}catch{}let fe=new URL(window.location.href);fe.searchParams.delete("payment_intent"),fe.searchParams.delete("payment_intent_client_secret"),fe.searchParams.delete("redirect_status"),window.history.replaceState({},"",fe.toString()),(async()=>{try{if(Y(!0),Fe==="failed"){let E="PayPal payment was declined. Please try again.";i?.(E),C?.(Kt("paypal",E));return}let{paymentIntent:st,error:_}=await U.retrievePaymentIntent(O);if(_){i?.(_.message??"Failed to retrieve PayPal payment status.");return}if(st&&(st.status==="requires_capture"||st.status==="succeeded")){let E=typeof st.payment_method=="string"?st.payment_method:st.payment_method?.id;o({id:E??st.id,type:"card",threeDSecureActionResultTokenId:st.id,isPaypal:!0},Je)}else{let E="PayPal payment was not completed. Please try again.";i?.(E),C?.(Kt("paypal",E))}}catch(st){i?.(st instanceof Error?st.message:"Failed to complete PayPal payment.")}finally{Y(!1)}})()},[U,o,i,C]);let vt=(0,a.useCallback)(async te=>{if(d||le){te.reject();return}let $=b?await b("paypal"):{proceed:!0};if(!$.proceed){G.current.delete(oe),te.reject();return}let O=Ie("paypal");G.current.set(oe,{generation:O,accountPatch:$.accountPatch,sessionId:$.sessionId,nonce:$.nonce}),_e(!1),c?.("paypal"),te.resolve()},[d,c,b,Ie,le,oe]),He=(0,a.useCallback)(async te=>{if(!U||!w)return;let $=G.current.get(oe);if($&&!ke($.generation)){G.current.delete(oe);return}if(!$&&K()||$&&!Pe($.generation))return;$||Pe();let O=$??null;if(G.current.delete(oe),!O&&b){let E=await b("paypal");if(!E.proceed){te.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}O={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let Fe=O?.sessionId??e,Je=O?.nonce??t,fe=await Tl({event:te,prepared:O,email:n,billingName:P,methodLabel:"PayPal",collect:we});if(!fe){te.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let st=fe.email,_=Pn({...O?.accountPatch,...fe});try{if(Y(!0),i?.(null),!Fe||!(0,u.isValidEmail)(st))throw new Error("Missing sessionId or email for PayPal payment");await F?.(fe);let E=U.createPaymentMethod,{error:Le,paymentMethod:ue}=await E({type:"paypal"});if(Le){Q(Le,"stripe_paypal_create_payment_method_failed",$?.generation),te.paymentFailed({reason:"fail"});return}let ae=await aa(r,ye,Fe,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ue?.id??null,intentKind:"payment"});if(ae.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let rt=ae.clientSecret,Oe={return_url:window.location.href};if(ue?.id&&(Oe.payment_method=ue.id),typeof window<"u")try{localStorage.setItem(Ro,JSON.stringify({clientSecret:rt,sessionId:Fe,nonce:Je,accountPatch:_}))}catch{}let{error:et,paymentIntent:Mt}=await U.confirmPayment({clientSecret:rt,confirmParams:Oe,redirect:"if_required"});if(et){if(typeof window<"u")try{localStorage.removeItem(Ro)}catch{}if(bo(et)){let J=et.message??"Your payment was declined.";i?.(J),C?.(Kt("paypal",J,{code:sr(et),declineCode:Hr(et)})),await ia({billingApiUrl:r,sessionId:Fe,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:sr(et)??"provider_declined"}})}else Q(et,"stripe_paypal_confirm_failed",$?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ro)}catch{}let R=typeof Mt?.payment_method=="string"?Mt.payment_method:Mt?.payment_method?.id;o({id:R??Mt?.id,type:"card",threeDSecureActionResultTokenId:Mt?.id,isPaypal:!0},{accountPatch:_,paymentMethodCategory:"paypal",sessionId:Fe,nonce:Je});return}catch(E){Q(E,"stripe_paypal_failed",$?.generation)}finally{Y(!1)}},[U,w,e,t,n,P,we,F,r,ye,o,i,C,b,Q,Pe,ke,K,oe]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(vs,{state:ce,placeholderTestId:"flopay-paypal-placeholder",borderRadius:m,children:(0,l.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsx)("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:it,style:gs,children:"Try PayPal again"}),$e&&(0,l.jsx)(Kr,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:Et,onCancel:()=>Et(null)},$e.id),(0,l.jsx)("div",{style:{display:$e?"none":void 0},children:(0,l.jsx)(Ft.ExpressCheckoutElement,{onReady:te=>q(bs(te,["paypal"])),onLoadError:()=>{q("load_error"),ja(jt(S),"paypal","paypal")},onClick:vt,onConfirm:He,onCancel:()=>{let te=G.current.get(oe);G.current.delete(oe),jt(S)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),M(te?.generation),_e(!1),Te.current=!0,be()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ge,emailRequired:ge,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},oe)})]})}),le&&(0,l.jsx)(Ln,{status:"processing"})]})}function us({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:d,onErrorChange:c,onButtonClick:C,onDecline:y,onTechnicalFailure:b,runBeforeButtonClick:P,billingName:F,onBuyerIdentityReady:A,onLoadStateChange:m,placeholderBorderRadius:S}){let ye=lr(),{emitInstrument:U}=(0,a.useContext)(Fn),w=(0,Ft.useStripe)(),ce=(0,Ft.useElements)(),[q,le]=(0,a.useState)("loading");(0,a.useEffect)(()=>{m?.(q)},[q,m]);let[Y,ge]=(0,a.useState)(!1),$e=!(0,u.isValidEmail)(n?.trim())||!F?.trim(),{request:we,collect:Et,finish:ze}=Vr(),Ee=(0,a.useRef)(null),Re=(0,a.useRef)(null),[oe,ee]=(0,a.useState)(0),[L,_e]=(0,a.useState)(!1),[Te,G]=(0,a.useState)("google_pay"),Ie=(0,a.useRef)(!1),Pe=(0,a.useRef)("google_pay"),M=(0,a.useRef)("google_pay"),K=(0,a.useRef)(null),ke=(0,a.useRef)(new Map),{startAttempt:be,finishAttempt:Q,invalidateAttempt:Be,isAttemptInvalidated:it,isAttemptCurrent:vt,generationRef:He}=hs((_,E,Le)=>{b?.(_,E,{...Le,popupBlocked:Le?.popupBlocked??vr(E)}),G(_),_e(!0),ee(ue=>ue+1)});(0,a.useEffect)(()=>{L&&Re.current?.focus()},[L,oe]);let te=(0,a.useCallback)(()=>{ee(_=>_+1)},[]),$=(0,a.useCallback)((_,E,Le,ue)=>{Be(ue),b?.(_,E,{code:Le,popupBlocked:vr(E)}),G(_),_e(!0),te()},[Be,b,te]),O=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Ie.current&&(Ie.current=!1,O())},[O,oe]);let Fe=(0,a.useCallback)(()=>{_e(!1),c?.(null),O()},[O,c]),Je=(0,a.useCallback)(async _=>{let E=!1,Le=B=>{E||(E=!0,_.paymentFailed({reason:"fail",...B?{message:B}:{}}))};if(!w||!ce){Le();return}let ue=ke.current.get(oe);if(ue&&!vt(ue.generation)){ke.current.delete(oe),Le();return}if(!ue&&it()){Le();return}if(ue&&!Q(ue.generation)){Le();return}ue||Q();let ae=_.expressPaymentType??ue?.method??Pe.current,rt=ue??null,Oe=ss(ae),et=jt(ye),Mt=et?.now()??globalThis.performance?.now()??Date.now(),R=new AbortController,J=!1,lt,Xe=new Promise((B,ft)=>{lt=ft}),Zt=window.setTimeout(()=>{J=!0,R.abort(),lt(Oa)},El),Ht=async(B,ft,Tt)=>{let ct=et?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Tt,Xe])}finally{let Rt=et?.now()??globalThis.performance?.now()??Date.now();et?.performance({stage:B,durationMs:Math.max(0,Rt-ct),durationMode:"machine",requestCategory:ft,paymentMethodCategory:"wallet",provider:"stripe",...J?{statusClass:"timeout"}:{}})}};try{if(ge(!0),c?.(null),!rt&&P){let dt=await Ht("processing","other",P(Oe));if(!dt.proceed){Le();return}rt={accountPatch:dt.accountPatch,sessionId:dt.sessionId,nonce:dt.nonce}}let B=rt?.sessionId??e,ft=rt?.nonce??t,Tt=fs({event:_,fallbackEmail:K.current?.email??rt?.accountPatch?.email??n,fallbackName:[K.current?.firstName??rt?.accountPatch?.firstName,K.current?.lastName??rt?.accountPatch?.lastName].filter(Boolean).join(" ")||F});if(!(0,u.isValidEmail)(Tt.email)){Le("Buyer details are required."),Et(qa(ae),Tt).then(dt=>{dt&&(K.current=dt)});return}K.current=null;let ct=Pn({...rt?.accountPatch,...Tt});await Ht("processing","provider_sdk",Promise.resolve(A?.(Tt)));let{error:Rt}=await Ht("tokenization","provider_sdk",ce.submit());if(Rt){Le(),$(ae,Rt,"stripe_wallet_submit_failed",ue?.generation);return}if(!B)throw new Error("Missing sessionId or email for payment.");let dn=await Ht("processing","intent_create",aa(r,U,B,ft??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ae,paymentMethodId:null,intentKind:o},{signal:R.signal}));if(dn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let rn=dn.clientSecret,un=(0,u.isSetupIntentClientSecret)(rn)?w.confirmSetup({elements:ce,clientSecret:rn,redirect:"if_required"}):w.confirmPayment({elements:ce,clientSecret:rn,redirect:"if_required"}),Dt=!1,Cn=dt=>{if(Dt||dt.error||ue&&He.current!==ue.generation)return;let ht=dt.setupIntent??dt.paymentIntent,on=ht?.id,tt=ht?.status,Jn=dt.setupIntent?tt==="succeeded":go(typeof tt=="string"?tt:void 0),pt=ht?.payment_method,en=typeof pt=="string"?pt:typeof pt?.id=="string"?pt.id:null;if(!Jn||typeof on!="string"||!en)return;Dt=!0;let Pt=`${ms}:${B}`;if(typeof window<"u")try{localStorage.setItem(Pt,JSON.stringify({createdAt:Date.now(),sessionId:B,nonce:ft,accountPatch:ct,paymentMethodId:en,providerIntentId:on,paymentMethodType:ae}))}catch{}try{d({id:en,type:"card",threeDSecureActionResultTokenId:on},{accountPatch:ct,paymentMethodCategory:"wallet",sessionId:B,nonce:ft})}finally{if(typeof window<"u")try{localStorage.removeItem(Pt)}catch{}}};un.then(dt=>{J&&Cn(dt)},()=>{});let Qt=await Ht("three_ds_handoff","provider_sdk",un),gt=Qt.error;if(gt){if(bo(gt)){let dt=gt.message??"Your payment was declined.";Le(dt),c?.(dt),y?.(Kt(Oe,dt,{code:sr(gt),declineCode:Hr(gt)})),ia({billingApiUrl:r,sessionId:B,nonce:ft,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ae,providerDeclineReason:sr(gt)??"provider_declined"}})}else Le(),$(ae,gt,"stripe_wallet_confirm_failed",ue?.generation);return}if(Cn(Qt),!Dt)throw new Error("Invalid provider returned for APM intent")}catch(B){B===Oa&&et?.error({errorCode:"REQUEST_TIMEOUT",stage:"callback",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"timeout",failureCategory:"provider_runtime"}),Le(),$(ae,B,B===Oa?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",ue?.generation)}finally{window.clearTimeout(Zt);let B=et?.now()??globalThis.performance?.now()??Date.now();et?.performance({stage:"callback",durationMs:Math.max(0,B-Mt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...J?{statusClass:"timeout"}:{}}),ge(!1)}},[w,ce,e,t,n,F,Et,A,r,U,o,d,c,y,P,$,Q,vt,it,He,ye,oe]),fe=(0,a.useMemo)(()=>{let _=["applePay","googlePay","paypal","link","amazonPay","klarna"],E=new Set(["applePay","googlePay"]),Le=new Set(i.map(u.stripeExpressMethodToOptionKey)),ue={};for(let ae of _)Le.has(ae)?ue[ae]=E.has(ae)?"always":"auto":ue[ae]="never";return ue},[i]),st=(0,a.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(vs,{state:q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:S,children:(0,l.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Fe,style:gs,children:["Try ",qa(Te)," again"]}),we&&(0,l.jsx)(Kr,{identity:we.identity,methodLabel:we.methodLabel,onComplete:ze,onCancel:()=>ze(null)},we.id),(0,l.jsx)("div",{style:{display:we?"none":void 0},children:(0,l.jsx)(Ft.ExpressCheckoutElement,{onReady:_=>{le(bs(_,st))},onLoadError:_=>{le("load_error"),ja(jt(ye),"stripe","wallet")},onClick:async _=>{Pe.current=_.expressPaymentType,M.current=ss(_.expressPaymentType);let E=!0,Le=window.setTimeout(()=>{E=!1,_.reject()},Il),ue=P?await P(M.current):{proceed:!0};if(window.clearTimeout(Le),!E)return;if(!ue.proceed){ke.current.delete(oe),_.reject();return}let ae=be(_.expressPaymentType);ke.current.set(oe,{generation:ae,method:_.expressPaymentType,accountPatch:ue.accountPatch,sessionId:ue.sessionId,nonce:ue.nonce}),_e(!1),C?.(M.current),_.resolve()},onConfirm:Je,onCancel:()=>{let _=ke.current.get(oe);ke.current.delete(oe),jt(ye)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Be(_?.generation),_e(!1),Ie.current=!0,te()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:fe,emailRequired:$e,billingAddressRequired:$e,layout:{maxColumns:1,overflow:"never"}}},oe)})]})}),Y&&(0,l.jsx)(Ln,{status:"processing"})]})}function zl({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:d,backgroundColor:c,borderColor:C,textColor:y,borderRadius:b,fontFamily:P}){let F=(0,u.resolveStripeMethodBrandVariant)(e,t),A=rs[e],[m,S]=(0,a.useState)(!1),ye=F?.backgroundColor??c??"#ffffff",U=F?.borderColor??C??"#d1d5db",w=F?.textColor??y??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&d()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:oa,padding:"0 1rem",backgroundColor:ye,color:w,border:`1px solid ${U}`,borderRadius:b??8,fontSize:"0.95rem",fontWeight:600,fontFamily:P,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,u.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,u.hasVendoredStripeMethodLogo)(e)?8:0},children:[A&&!m?(0,l.jsx)("img",{src:A,alt:"","aria-hidden":"true",onError:()=>S(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):F?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:F.logoSvg}}):null,(0,l.jsx)("span",{children:(0,u.getStripeMethodDisplayName)(e)})]}),i&&(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:w,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function $a({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:c,onErrorChange:C,onDecline:y,onCancel:b,runBeforeButtonClick:P,onButtonClick:F,isProcessing:A,submitButtonColor:m,submitButtonBorderRadius:S,submitButtonStyle:ye,errorText:U}){let w=lr(),{emitInstrument:ce}=(0,a.useContext)(Fn),q=(0,Ft.useStripe)(),le=(0,Ft.useElements)(),[Y,ge]=(0,a.useState)(!1),$e=(0,a.useRef)(!1),[we,Et]=(0,a.useState)(!1),[ze,Ee]=(0,a.useState)("loading"),[Re,oe]=(0,a.useState)(""),ee=!(0,u.isValidEmail)(r?.trim()),L=!ee||(0,u.isValidEmail)(Re.trim()),_e=(0,a.useCallback)(async()=>{if(!q||!le||A||$e.current||!we)return;$e.current=!0,ge(!0);let Te=P?await P("card"):{proceed:!0};if(!Te.proceed){$e.current=!1,ge(!1);return}F?.("card");let G=Te.sessionId??t,Ie=Te.nonce??n,Pe=Er(o?.trim()),M=Pn({email:Te.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:Te.accountPatch?.firstName?.trim()||Pe.firstName,lastName:Te.accountPatch?.lastName?.trim()||Pe.lastName}),K=M.email,ke=Pn({...Te.accountPatch,...M});try{if(C?.(null),!(0,u.isValidEmail)(K))throw new Error("A valid email address is required for payment.");await i?.(M);let be=await le.submit();if(be.error){C?.(be.error.message??"Payment failed.");return}let Q=[M.firstName,M.lastName].filter(Boolean).join(" "),Be=await q.createPaymentMethod({elements:le,params:{billing_details:{email:K,...Q?{name:Q}:{}}}});if(Be.error||!Be.paymentMethod){C?.(Be.error?.message??"Failed to create payment method.");return}let it=Be.paymentMethod;if(!G||!K)throw new Error("Missing sessionId or email for payment.");let vt=it.type||e,He=await aa(d,ce,G,Ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:vt,paymentMethodId:null,intentKind:"payment"});if(He.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let te=He.clientSecret;if(typeof window<"u")try{localStorage.setItem(nr,JSON.stringify({clientSecret:te,sessionId:G,nonce:Ie,accountPatch:ke,paymentMethodId:it.id,paymentMethodType:it.type??e,gateway:"stripe"}))}catch{}let{error:$,paymentIntent:O}=await q.confirmPayment({clientSecret:te,confirmParams:{return_url:window.location.href,payment_method:it.id},redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let fe=$.message??"Payment failed.";C?.(fe),y?.(Kt("card",fe,{code:$.code})),await ia({billingApiUrl:d,sessionId:G,nonce:Ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:$.code??"provider_declined"}});return}let Fe=O?.status;if(!go(Fe)){if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let fe=Fe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";C?.(fe),y?.(Kt("card",fe,{code:Fe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let Je=typeof O?.payment_method=="string"?O.payment_method:O?.payment_method?.id;c({id:Je??it.id,type:"card",threeDSecureActionResultTokenId:O?.id,gateway:"stripe",paymentMethodType:it.type??e},{accountPatch:ke,paymentMethodCategory:"apm",sessionId:G,nonce:Ie})}catch(be){C?.(be instanceof Error?be.message:"Payment failed. Please try again.")}finally{$e.current=!1,ge(!1)}},[q,le,A,we,P,F,t,n,r,o,Re,i,d,ce,e,c,C,y]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ee&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ee&&(0,l.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,l.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:Te=>oe(Te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(Ft.PaymentElement,{onReady:()=>Ee("ready"),onLoadError:()=>{Ee("load_error"),ja(jt(w),"stripe","apm")},onChange:Te=>{Et(!!Te.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,u.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{_e()},disabled:!we||!L||Y||A||ze!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:m,color:"white",border:"none",borderRadius:S,fontSize:"1rem",fontWeight:600,cursor:!we||!L||Y||A||ze!=="ready"?"not-allowed":"pointer",opacity:!we||!L||Y||A||ze!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ye??{}},children:Y?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),U&&(0,l.jsx)(Wr,{margin:"0.75rem 0 0",children:U})]})}function ps({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:d,stripeInstance:c,paymentElementBaseOptions:C,onTokenizedBody:y,onErrorChange:b,onButtonClick:P,onDecline:F,runBeforeButtonClick:A,onLoadStateChange:m,isProcessing:S=!1,submitButtonColor:ye="#4A49FF",submitButtonBorderRadius:U=8,submitButtonStyle:w,buttonAppearance:ce,themeId:q,onExpandApm:le,expandedApmMethod:Y}){let{emitInstrument:ge}=(0,a.useContext)(Fn),[$e,we]=(0,a.useState)(null),[Et,ze]=(0,a.useState)(null),Ee=(0,a.useRef)(!1),{request:Re,collect:oe,finish:ee}=Vr();(0,a.useEffect)(()=>{d.length>0&&c?m?.("ready"):c||m?.("loading")},[d.length,c,m]);let L=(0,a.useCallback)(async M=>{if(!c||Ee.current||S)return;Ee.current=!0,ze(M);let K=A?await A("card"):{proceed:!0};if(!K.proceed){Ee.current=!1,ze(null);return}P?.("card");let ke=K.sessionId??e,be=K.nonce??t,Q=Er([K.accountPatch?.firstName,K.accountPatch?.lastName].filter(Boolean).join(" ")||r),Be=Pn({email:K.accountPatch?.email?.trim()||n?.trim(),firstName:K.accountPatch?.firstName?.trim()||Q.firstName,lastName:K.accountPatch?.lastName?.trim()||Q.lastName});if(!(0,u.isValidEmail)(Be.email)){ze(null);let He=await oe((0,u.getStripeMethodDisplayName)(M),Be);if(!He){Ee.current=!1;return}Be=He,ze(M)}let it=Be.email,vt=Pn({...K.accountPatch,...Be});try{if(b?.(null),!ke||!(0,u.isValidEmail)(it))throw new Error("Missing sessionId or email for payment.");await o?.(Be);let He=await aa(i,ge,ke,be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:M,paymentMethodId:null,intentKind:"payment"});if(He.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let te=He.clientSecret;if(typeof window<"u")try{localStorage.setItem(nr,JSON.stringify({clientSecret:te,sessionId:ke,nonce:be,accountPatch:vt,paymentMethodType:M,gateway:"stripe"}))}catch{}let{error:$,paymentIntent:O}=await c.confirmPayment({clientSecret:te,confirmParams:{return_url:window.location.href,payment_method_data:{type:M,billing_details:{name:[Be.firstName,Be.lastName].filter(Boolean).join(" "),...it?{email:it}:{}}}},redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let fe=$.message??"Payment failed.";b?.(fe),F?.(Kt("card",fe,{code:$.code})),await ia({billingApiUrl:i,sessionId:ke,nonce:be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:M,providerDeclineReason:$.code??"provider_declined"}});return}let Fe=O?.status;if(!go(Fe)){if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let fe=Fe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(fe),F?.(Kt("card",fe,{code:Fe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(nr)}catch{}let Je=typeof O?.payment_method=="string"?O.payment_method:O?.payment_method?.id;y({id:Je??O?.id,type:"card",threeDSecureActionResultTokenId:O?.id,gateway:"stripe",paymentMethodType:M},{accountPatch:vt,paymentMethodCategory:"apm",sessionId:ke,nonce:be})}catch(He){b?.(He instanceof Error?He.message:"Payment failed. Please try again.")}finally{Ee.current=!1,ze(null)}},[c,S,A,P,e,t,n,oe,i,ge,r,o,y,b,F]),[_e,Te]=(0,a.useState)(null),G=le?Y??null:_e,Ie=(0,a.useCallback)(M=>{Ee.current||S||G&&G!==M||((0,u.needsStripeMethodExplicitConfirm)(M)?le?le(M):Te(M):L(M))},[G,S,L,le]),Pe=(0,a.useMemo)(()=>_e?{...C,paymentMethodTypes:[_e]}:null,[_e,C]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?(0,l.jsx)(Kr,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:ee,onCancel:()=>ee(null)},Re.id):d.map(M=>{let K=Y===M,ke=Et===M,be=Et!==null&&Et!==M||Y!=null&&Y!==M;return(0,l.jsxs)(a.default.Fragment,{children:[(0,l.jsx)(zl,{method:M,themeId:q,submitting:ke,disabled:be,highlighted:K,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(M),onClick:()=>Ie(M),backgroundColor:ce?.backgroundColor,borderColor:ce?.borderColor,textColor:ce?.textColor,borderRadius:ce?.borderRadius,fontFamily:ce?.fontFamily}),!le&&_e===M&&Pe&&c&&(0,l.jsx)(Ft.Elements,{stripe:c,options:Pe,children:(0,l.jsx)($a,{method:M,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:y,onErrorChange:b,onDecline:F,onCancel:()=>Te(null),runBeforeButtonClick:A,onButtonClick:P,isProcessing:S,submitButtonColor:ye,submitButtonBorderRadius:U,submitButtonStyle:w})},M)]},M)})})}function Ul({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:d,onDecline:c,onTokenizedBody:C,firstName:y,lastName:b,chv:P,className:F,isProcessing:A,error:m,onErrorChange:S,showPayPal:ye=!0,showStripe:U=!0,enabledPaymentMethods:w,enabledPaymentMethodCountries:ce,showApplePay:q=!0,showGooglePay:le=!0,layout:Y="default",theme:ge,buttonsTheme:$e,buttonsStyles:we,appearance:Et,cardButtonContent:ze,cardBackButtonContent:Ee,cardTitleContent:Re,showSecurityFooter:oe,onButtonClick:ee,onBeforeButtonClick:L,onBuyerIdentityReady:_e,enableAVS:Te,cardFieldOrder:G,cardPreFormSlot:Ie,avsLayout:Pe="row",country:M,zip:K,addressLine1:ke,addressLine2:be,city:Q,state:Be,onCountryChange:it,onZipChange:vt,avsCheck:He,checkoutType:te,checkoutLayout:$,totalAmount:O=0,currency:Fe="usd",initialCardOpen:Je=!1,directPaypal:fe,isSubscription:st=!1,session:_,dataAttachmentPending:E=!1,dataAttachmentRequiresIdentity:Le=!1,debug:ue=!1}){let ae=lr(),rt=Yo(),Oe=(0,a.useContext)(Yn),{emitInstrument:et}=(0,a.useContext)(Fn),Mt=_??Oe.session,R=Mt?.gateways?.paypal?.providerObjectType??fe?.providerObjectType,J=E||Oe.claimPending===!0,lt=Le||Oe.claimRequiresIdentity===!0,Xe=J&&!lt,Zt=Vi(),[Ht,B]=(0,a.useState)(!1),[ft,Tt]=(0,a.useState)(null),[ct,Rt]=(0,a.useState)(M??"US"),[dn,rn]=(0,a.useState)(K??""),[un,Dt]=(0,a.useState)(ke??""),[Cn,Qt]=(0,a.useState)(be??""),[gt,dt]=(0,a.useState)(Q??""),[ht,on]=(0,a.useState)(Be??""),[tt,Jn]=(0,a.useState)(""),[pt,en]=(0,a.useState)({}),Pt=(0,a.useRef)(K??""),Yt=(0,a.useRef)(M??"US"),Sn=(0,a.useRef)(ke??""),pn=(0,a.useRef)(be??""),_n=(0,a.useRef)(Q??""),an=(0,a.useRef)(Be??""),Tn=(0,a.useRef)(""),qt=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(h,V,Ne,W,De)=>{if(qt.current[h])return;let Ke=V?.trim();!Ke||Ke===Ne.current||(Ne.current=Ke,W(Ke),De?.(Ke))};s("country",M,Yt,Rt,it),s("zip",K,Pt,rn,vt),s("addressLine1",ke,Sn,Dt),s("addressLine2",be,pn,Qt),s("city",Q,_n,dt),s("state",Be,an,on)},[M,K,ke,be,Q,Be,it,vt]);let ie=(0,a.useMemo)(()=>(0,u.resolveAVSConfig)(Te),[Te]),mn=ie!==null,On=(0,a.useMemo)(()=>(0,u.isAuthorizationOnlySession)(_),[_]),Xn=!!_?.vault?.html,Cr=!!_?.gateways?.pcivault,mr=!!(_?.gateways?.stripe?.enabledPaymentMethods??w)?.includes("card"),Lt=Xn||mr||Cr,Ye=!!(U&&Lt&&ae&&e),[yr,T]=(0,a.useState)(()=>Y!=="buttons"||Je?e??null:null),[ut,Vt]=(0,a.useState)(0),wn=Y!=="buttons"||Je||!!e&&yr===e,Ce=(0,a.useMemo)(()=>!ae||!Ye||!e||!wn?null:ae.cardCapture({sessionId:e,captureMethod:_?.captureMethod}),[ae,Ye,e,wn,_?.captureMethod]),sn=(0,a.useMemo)(()=>{let s=ct,h=ie?(0,u.isAVSFieldVisible)(ie.postal_code,s):!1;return Ll(s,dn,h)},[ie,ct,dn]),{avsInvalid:wr,invalidAvsFields:Br}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!Ye||!ie)return{avsInvalid:!1,invalidAvsFields:s};let h=ct,V=(De,Ke)=>(0,u.isAVSFieldVisible)(De,h)&&!Ke.trim(),Ne={line1:V(ie.address_line_1,un),city:V(ie.city,gt),state:V(ie.state,ht),zip:sn.empty||sn.malformed};return{avsInvalid:Ne.line1||Ne.city||Ne.state||Ne.zip,invalidAvsFields:Ne}},[Ye,ie,ct,un,gt,ht,sn]),[yn,fr]=(0,a.useState)(!1),[Zn,zn]=(0,a.useState)(!1),[Nt,Un]=(0,a.useState)(!1),[Qn,fn]=(0,a.useState)({line1:!1,city:!1,state:!1}),tn=(0,a.useRef)(!1),qn=(0,a.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),$n=(0,a.useRef)(!1),mt=(0,a.useCallback)(s=>{qn.current[s]=!0,$n.current=!0},[]),gn=(0,a.useCallback)(s=>!tn.current&&qn.current[s],[]),hn=(0,a.useCallback)(s=>{gn(s)&&fn(h=>h[s]?h:{...h,[s]:!0})},[gn]),[jn,xn]=(0,a.useState)(()=>za(_?.vault)),[xe,nn]=(0,a.useState)(Je&&Lt?"card":"buttons"),[Ot,gr]=(0,a.useState)(null),Vn=xe==="expanding"||xe==="card",hr=_?.gateways?.stripe?"stripe":void 0,kn=(0,a.useCallback)(()=>{et?.({class:"card_surface",provider:hr})},[hr,et]),Mn=(0,a.useRef)(null),zt=(0,a.useCallback)(s=>{Mn.current&&clearTimeout(Mn.current),Mn.current=setTimeout(()=>{Mn.current=null,s()},xr)},[]);(0,a.useEffect)(()=>()=>{Mn.current&&clearTimeout(Mn.current)},[]);let N=(0,a.useCallback)(()=>{kn(),T(e??null),Vt(s=>s+1),nn("expanding"),zt(()=>nn("card"))},[zt,kn,e]),j=(0,a.useCallback)(()=>{nn("collapsing"),zt(()=>nn("buttons"))},[zt]),ne=(0,a.useCallback)(s=>{gr(s),nn("apm-expanding"),zt(()=>nn("apm-form"))},[zt]),re=(0,a.useCallback)(()=>{nn("apm-collapsing"),zt(()=>{nn("buttons"),gr(null)})},[zt]);(0,a.useEffect)(()=>{Y==="buttons"&&Je&&Lt&&(T(e??null),nn("card"))},[Y,Je,Lt,e]);let[Me,z]=(0,a.useState)(null),X=(0,a.useRef)(!1),f=(0,a.useRef)(null),H=(0,a.useRef)("idle"),[Z,bt]=(0,a.useState)(null),Ct=(0,a.useRef)(Z);(0,a.useEffect)(()=>{Ct.current=Z},[Z]);let de=n||Zt,Ae=(0,a.useRef)(null),Wt=(0,a.useMemo)(()=>{if(_e||Oe.claimBuyerIdentity||_?.buyerIdentified!==!1||!e||!t)return;let s=`${de}|${e}|${t}`;Ae.current?.key!==s&&(Ae.current={key:s,claim:$r(new ur.PaymentAPI(de,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...b?{lastName:b}:{}})});let h=Ae.current.claim;return async V=>{await h(V)}},[_e,Oe.claimBuyerIdentity,_?.buyerIdentified,e,t,de,o,y,b]),ot=_e??Oe.claimBuyerIdentity??Wt,g=m??ft,p=(0,a.useMemo)(()=>(0,u.resolveTheme)(ge),[ge]),v=(0,a.useMemo)(()=>{let s=p?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)($e);return we?{...s,...we,cardButton:{...s.cardButton,...we.cardButton},cardFormContainer:{...s.cardFormContainer,...we.cardFormContainer},backButton:{...s.backButton,...we.backButton},backButtonIcon:{...s.backButtonIcon,...we.backButtonIcon},submitButton:{...s.submitButton,...we.submitButton},title:{...s.title,...we.title}}:s},[p,$e,we]),Se=Et??p?.appearance,pe=(0,a.useMemo)(()=>ra({appearance:Se,buttonsStyles:v,layout:Y}),[Se,v,Y]),We=Oe.inlineSessionPatchProcessing??!1,Ze=(A??Ht)||We,se=de.replace(/\/+$/,""),D=(0,a.useMemo)(()=>xa({userId:o,email:r,firstName:y,lastName:b,country:M,zip:K},pt),[o,r,y,b,M,K,pt]),me=[D.firstName,D.lastName].filter(s=>!!s?.trim()).join(" "),Ge=!(0,u.isValidEmail)(D.email?.trim()),je=(0,a.useRef)(null);Ye&&je.current===null&&(je.current=Ge);let St=Ye&&(je.current??Ge),Ve=(0,a.useMemo)(()=>Nl(tt,St),[tt,St]),$t=Ve.empty||Ve.malformed,In=(0,a.useMemo)(()=>ae?ae.getRawProvider():null,[ae]),Fr=(0,a.useMemo)(()=>rt?rt.getRawProvider():null,[rt]),eo=O||100,Ao=(0,a.useMemo)(()=>Se?(0,ur.toStripeAppearance)(Se):null,[Se]),Bo=Ao?{appearance:Ao}:null,ni=(0,a.useMemo)(()=>{let s=Ao??{},h=s.rules??{};return{...s,rules:{...h,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...h[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...h[".AccordionItemContents"]??{}}}}},[Ao]),ri=(0,a.useMemo)(()=>{let s=Ui(O);return{...s,currency:Fe.toLowerCase(),...s.mode==="payment"?{captureMethod:"manual"}:{},...Bo}},[O,Fe,Bo]),oi=(0,a.useMemo)(()=>({mode:"payment",amount:eo,currency:Fe.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Bo}),[eo,Fe,Bo]),he=(0,a.useCallback)(s=>{Tt(s),S?.(s)},[S]),ya=(0,a.useRef)(""),[ai,xs]=(0,a.useState)(!1),fa=(0,a.useCallback)(()=>{xs(!0)},[]);(0,a.useEffect)(()=>{if(!Ye||!St||!ot||!ai||$t||ya.current)return;let s=Pn({email:(0,u.isValidEmail)(D.email?.trim())?D.email?.trim():Tn.current.trim(),firstName:D.firstName?.trim(),lastName:D.lastName?.trim()});ya.current=JSON.stringify(s),en(h=>({...h,...s})),Promise.resolve(ot(s)).catch(h=>{ya.current="",he(h instanceof Error?h.message:"Failed to attach buyer details.")})},[Ye,St,ot,ai,$t,D.email,D.firstName,D.lastName,he]),(0,a.useEffect)(()=>{!Ye||!Ce||Ce.setCardFieldOrder?.(G??null,ie==null&&!St)},[Ye,Ce,G,ie,St]),(0,a.useEffect)(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&he(null)},[xe,he]);let Kn=(0,a.useCallback)((s,h,V)=>{c?.(Kt(s,h,V))},[c]),Dr=(0,a.useCallback)((s,h,V)=>{let Ne=V?.popupBlocked??vr(h),W=Fl(s,Ne),De=_r(V?.code)??sr(h)??"external_payment_method_failed",Ke=new u.FloPayError(W,"api_error",{code:"external_payment_method_failed",param:s});z(null),Y==="buttons"&&(nn("buttons"),gr(null)),he(W),d?.(Ke),console.error("[FloPay] External payment method failed:",{method:s,code:De,popupBlocked:Ne})},[Y,d,he]);(0,a.useEffect)(()=>{if(!Ye||!e){xn(null);return}let s=za(_?.vault);if(s){xn(s);return}if(!wn){xn(null);return}xn(null);let h=!0;return new ur.PaymentAPI(se).getVaultCapture(e,t).then(V=>{if(!h)return;let Ne=za(V);Ne?xn(Ne):he("Failed to load the secure card form.")}).catch(V=>{h&&he(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{h=!1}},[Ye,wn,ut,e,_?.vault,se,t,he]);let er=(0,a.useRef)({onComplete:i,onError:d,updateError:he,emitDecline:Kn,resolvedAccount:D,avsConfig:ie,avsCheckProp:He,sessionId:e,nonce:t,baseUrl:se,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt});er.current={onComplete:i,onError:d,updateError:he,emitDecline:Kn,resolvedAccount:D,avsConfig:ie,avsCheckProp:He,sessionId:e,nonce:t,baseUrl:se,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt};let ga=(0,a.useRef)(!1),ii=(0,a.useCallback)(()=>{let{resolvedAccount:s,avsConfig:h,avsCheckProp:V}=er.current,Ne=s.email?.trim(),W=(0,u.isValidEmail)(Ne)?Ne:Tn.current.trim();if(!(0,u.isValidEmail)(W))return null;let De=s.firstName?.trim(),Ke=s.lastName?.trim(),yt=Yt.current||s.country||"US",Gt=h?(0,u.isAVSFieldVisible)(h.state,yt):!1,wt=h?(0,u.isAVSFieldVisible)(h.address_line_1,yt):!1,kt=h?(0,u.isAVSFieldVisible)(h.postal_code,yt):!1,at=h?(0,u.isAVSFieldVisible)(h.city,yt):!1,ln=h?(0,u.isAVSFieldVisible)(h.address_line_2,yt):!1,Qe=wt&&!Gt&&kt?(0,u.getStateFromPostalCode)(yt,(Pt.current??"").trim()):null,cn=Gt?an.current:Qe;return{accountData:{userId:s.userId??"",email:W,...De?{firstName:De}:{},...Ke?{lastName:Ke}:{},...kt&&Pt.current?{zip:Pt.current}:{},...at&&_n.current?{city:_n.current}:{},...cn?{state:cn}:{},...wt&&Sn.current?{addressLine1:Sn.current}:{},...ln&&pn.current?{addressLine2:pn.current}:{},country:yt},...V!==void 0?{avsCheck:V}:{},...h?{avsConfig:{country:(0,u.isAVSFieldVisible)(h.country,yt),postal_code:kt,address_line_1:wt,address_line_2:ln,city:at,state:Gt}}:{}}},[]),si=(0,a.useRef)(J);si.current=J,(0,a.useEffect)(()=>{J||g!==is||er.current.updateError(null)},[J,g]),(0,a.useEffect)(()=>{!Ye||!Ce||Ce.setSubmitGate?.(wr||J||$t)},[Ye,Ce,wr,J,$t]),(0,a.useEffect)(()=>{if(!Ye||!Ce)return;ga.current=!1;let s=!1,h=Ce.on("submitting",()=>{fr(!0),f.current&&clearTimeout(f.current),H.current="validation-window",f.current=setTimeout(()=>{f.current=null,H.current==="validation-window"&&(H.current="processing")},Rl),z("processing");let{baseUrl:Ke,sessionId:yt,nonce:Gt,updateError:wt,onError:kt}=er.current;if(!yt||!Gt)return;let at=ii();if(!at){wt("Enter a valid email address."),H.current="idle",z(null);return}new ur.PaymentAPI(Ke).patchAccountSnapshot(yt,Gt,at,{telemetryMode:"best_effort"}).catch(ln=>{if(!_l(ln))return;let Qe=ln instanceof Error?ln.message:"Please check your billing address and try again.";wt(Qe),H.current="idle",z(null),kt?.(ln instanceof u.FloPayError?ln:new u.FloPayError(Qe,"api_error"))})}),V=Ce.on("complete",async Ke=>{if(Gr(Ke.sessionId??er.current.sessionId),H.current="terminal",z("success"),await new Promise(wt=>setTimeout(wt,1200)),ga.current)return;ga.current=!0;let yt=er.current,Gt=(0,u.isAuthorizationOnlySession)(yt)||Ke.outcome==="authorized";er.current.onComplete?.(Gt?{status:"authorized",paymentIntentId:Ke.intentId,paymentId:Ke.paymentId??yt.paymentId,sessionId:Ke.sessionId??yt.sessionId,authorizationExpiresAt:Ke.authorizationExpiresAt??yt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ke.intentId,checkoutMethod:"card"})}),Ne=Ce.on("decline",async Ke=>{let{updateError:yt,emitDecline:Gt}=er.current,wt=Ke.message??"Your payment was declined. Please try another card or contact your bank.";H.current="terminal",yt(wt),z("error");let kt=Ke.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(Ke.declineReason)??"authorization_declined";Gt("card",wt,{code:kt,declineCode:kt}),await new Promise(at=>setTimeout(at,1500)),!s&&(H.current="idle",z(null))}),W=Ce.on("error",async Ke=>{let{updateError:yt,onError:Gt}=er.current,wt=Ke.message??"There was a problem processing your payment. Please try again.";H.current="terminal",yt(wt),z("error"),Gt?.(new u.FloPayError(wt,"api_error",{code:Ke.failureOutcome??"capture_failed"})),await new Promise(kt=>setTimeout(kt,1500)),!s&&(H.current="idle",z(null))}),De=Ce.on("blocked",()=>{if(!si.current){fr(!0);return}fa(),er.current.updateError(is)});return()=>{s=!0,f.current&&(clearTimeout(f.current),f.current=null),H.current="idle",h(),V(),Ne(),W(),De()}},[Ye,Ce,fa,ii]);let tr=!!fe?.clientId,to=Array.isArray(w),Fo=to&&w.length>0,Ms=to&&w.includes("paypal"),{expressMethods:Do,paymentElementMethods:no}=(0,a.useMemo)(()=>(0,u.partitionStripeMethods)(w,{excludePaypal:tr}),[w,tr]),li=tr||!!rt,As=(0,a.useMemo)(()=>li?Do.filter(s=>s!=="paypal"):Do,[Do,li]),Bs=(0,a.useMemo)(()=>{let s=[];return q&&s.push("apple_pay"),le&&s.push("google_pay"),s},[q,le]),Lr=to?As:Bs,Fs=U&&Lr.length>0,ha=mn?ct:M,Lo=(0,a.useMemo)(()=>{let s=ha?.trim().toUpperCase();return s?ce?no.filter(h=>{let V=ce[h];return!V||V.length===0||V.includes(s)}):(0,u.filterStripeMethodsByCountry)(no,ha):no},[no,ha,ce]),ba=(0,a.useMemo)(()=>({mode:"payment",amount:eo,currency:Fe.toLowerCase(),paymentMethodCreation:"manual",appearance:ni}),[eo,Fe,ni]),[ci,di]=(0,a.useState)("loading"),[ui,pi]=(0,a.useState)("loading"),[mi,yi]=(0,a.useState)("loading"),[Ds,va]=(0,a.useState)(!1),[fi,Pa]=(0,a.useState)("loading"),[No,Ls]=(0,a.useState)();(0,a.useEffect)(()=>{Ls(ns())},[]);let gi=ye&&(tr||(to?Ms:No===!1)),hi=U&&Fs,ro=!Xe&&gi&&tr,bi=fi==="retrying"||fi==="exhausted",oo=!Xe&&gi&&!!Fr&&(!tr||bi),ao=!Xe&&hi&&!!In,io=!Xe&&U&&Fo&&Lo.length>0&&!!In,Ns=ro&&!bi?Ds:oo&&cs(ci),Os=ao&&cs(ui),zs=io&&mi!=="load_error",vi=s=>s==="loading"||s==="ready",Pi=ro||oo&&vi(ci)||ao&&vi(ui)||io&&mi!=="load_error",Oo=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!Oo.current){if(!U&&!ye){Oo.current=!0;let s=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(s),he(s.message)}else if(!U&&ye&&!tr&&!Fr){Oo.current=!0;let s=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(s),he(s.message)}else if(No!==void 0&&!Xe&&!Lt&&!Pi){Oo.current=!0;let s=new u.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});d?.(s),he(s.message)}}},[U,ye,tr,Fr,No,Xe,Lt,Pi,d,he]);let Ci=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(Ci.current||!Fo)return;let s=[];q!==!0&&s.push("showApplePay"),le!==!0&&s.push("showGooglePay"),s.length!==0&&(Ci.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Fo,q,le]);let Si=(0,a.useCallback)((s,h)=>Oe.applyInlineSessionPatch?Oe.applyInlineSessionPatch(s).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let Ne=ls(h,V);return he(Ne.message),d?.(Ne),{error:Ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Oe.applyInlineSessionPatch,t,d,e,he]),Hn=(0,a.useCallback)(async s=>{if(!L)return{proceed:!0};try{let h=await L({method:s,sessionId:e||void 0,createSession:Oe.inlineSessionDraft});if(h===!1)return{proceed:!1};if(h&&typeof h=="object"){h.account&&en(Ne=>({...Ne??{},...h.account}));let V=await Si(h,s);return V.error?{proceed:!1,accountPatch:h.account}:{proceed:!0,accountPatch:h.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(h){let V=ls(s,h);return he(V.message),d?.(V),{proceed:!1}}},[Si,Oe.inlineSessionDraft,L,d,e,he]),wi=(0,a.useCallback)(async(s,h)=>{if(X.current)return;X.current=!0,B(!0),z("processing"),he(null);let V=h?.sessionId??e,Ne=h?.nonce??t,W=xa(D,h?.accountPatch),De=h?.completionPaymentMethodId??ho(s),Ke=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,yt=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,Gt=()=>{et?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:yt})};try{let kt=await new ur.PaymentAPI(se).processPayment(W.userId??"",{sessionId:V,nonce:Ne,paymentMethodCategory:h?.paymentMethodCategory??Al(s),tokenizedData:Ke,accountData:{...h?.accountPatch,userId:W.userId??"",email:W.email??"",...W.firstName?{firstName:W.firstName}:{},...W.lastName?{lastName:W.lastName}:{},...ie?(()=>{let Qe=Yt.current,cn=(0,u.isAVSFieldVisible)(ie.state,Qe),Bn=(0,u.isAVSFieldVisible)(ie.address_line_1,Qe),Jt=(0,u.isAVSFieldVisible)(ie.postal_code,Qe),mo=Bn&&!cn&&Jt?(0,u.getStateFromPostalCode)(Qe,(Pt.current??"").trim()):null,yo=cn?an.current:mo;return{country:Qe,...Jt&&Pt.current?{zip:Pt.current}:{},...(0,u.isAVSFieldVisible)(ie.city,Qe)&&_n.current?{city:_n.current}:{},...yo?{state:yo}:{},...Bn&&Sn.current?{addressLine1:Sn.current}:{},...(0,u.isAVSFieldVisible)(ie.address_line_2,Qe)&&pn.current?{addressLine2:pn.current}:{}}})():{}},chv:P,avsCheck:He??!1,checkoutType:te,checkoutLayout:$,avsConfig:ie?{country:(0,u.isAVSFieldVisible)(ie.country,Yt.current),postal_code:(0,u.isAVSFieldVisible)(ie.postal_code,Yt.current),address_line_1:(0,u.isAVSFieldVisible)(ie.address_line_1,Yt.current),address_line_2:(0,u.isAVSFieldVisible)(ie.address_line_2,Yt.current),city:(0,u.isAVSFieldVisible)(ie.city,Yt.current),state:(0,u.isAVSFieldVisible)(ie.state,Yt.current)}:void 0});if(kt.ok){let Qe=kt.status===204?null:await kt.json().catch(()=>null),cn=(0,u.isAuthorizationOnlySession)(_)||Qe?.status==="authorized";Gr(V),z("success"),bt(null),await new Promise(Bn=>setTimeout(Bn,1200)),i?.(cn?{status:"authorized",...typeof Qe?.paymentId=="string"?{paymentId:Qe.paymentId}:_?.paymentId?{paymentId:_.paymentId}:{},sessionId:typeof Qe?.sessionId=="string"?Qe.sessionId:V,...typeof Qe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Qe.authorizationExpiresAt}:_?.authorizationExpiresAt?{authorizationExpiresAt:_.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"});return}let at=await kt.json().catch(()=>null);if(at?.type==="paypal_redirect_required"){let Qe=at.threeDSecureToken,cn=at.paymentMethodId||s.id||"";if(!ae||!Qe){z("error"),he("PayPal authorization required but no token provided.");return}try{let Bn=rt?.getRawProvider();if(!Bn){he("PayPal is not available.");return}let Jt={return_url:window.location.href};cn&&(Jt.payment_method=cn);let{error:mo}=await Bn.confirmPayment({clientSecret:Qe,confirmParams:Jt,redirect:"if_required"});if(mo){z("error");let yo=mo.message??"PayPal payment failed.";he(yo),Kn("paypal",yo,{code:mo.code})}}catch(Bn){z("error"),he(Bn instanceof Error?Bn.message:"PayPal authorization failed.")}return}if(at?.type==="paypal_direct_required"){let Qe=at.orderId;if(!Qe){z("error"),he("PayPal retry required but no order id provided.");return}let cn=Ct.current?.attempts??0;if(cn>=2){z("error"),he("PayPal payment could not be completed after multiple attempts."),Kn("paypal","paypal_direct_required retry limit exceeded");return}va(!1),Pa("loading"),bt({orderId:Qe,attempts:cn+1}),z(null);return}(0,u.classifyPaymentRejection)(kt.status,at)||Gt(),z("error");let ln=at?.message??"Payment failed. Please try again.";he(ln),Kn(s.isPaypal?"paypal":"card",ln,{code:at?.code??at?.gatewayErrorCode,declineCode:at?.declineCode??at?.gatewayDeclineReason}),await new Promise(Qe=>setTimeout(Qe,1500))}catch(wt){ys(wt)||Gt(),z("error"),he(wt instanceof Error?wt.message:"An unexpected error occurred"),await new Promise(kt=>setTimeout(kt,1500))}finally{B(!1),z(null),X.current=!1}},[se,e,t,D,ie,He,te,$,P,ae,rt,_,i,he,Kn,et]),bn=(0,a.useCallback)((s,h)=>{C?C(s):wi(s,h)},[C,wi]),so=`${ms}:${e}`;(0,a.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(so);if(!s)return;let h;try{h=JSON.parse(s)}catch{localStorage.removeItem(so);return}if(!h||typeof h.createdAt!="number"||Date.now()-h.createdAt<0||Date.now()-h.createdAt>kl||typeof h.paymentMethodId!="string"||typeof h.providerIntentId!="string"||typeof h.paymentMethodType!="string"||h.sessionId!==e||!t||h.nonce!==t||!Lr.includes(h.paymentMethodType)){localStorage.removeItem(so);return}localStorage.removeItem(so),bn({id:h.paymentMethodId,type:"card",threeDSecureActionResultTokenId:h.providerIntentId,gateway:"stripe",paymentMethodType:h.paymentMethodType},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[bn,t,e,so,Lr]);let ki=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||ki.current)return;let s=new URLSearchParams(window.location.search),h=s.get("payment_intent"),V=s.get("payment_intent_client_secret"),Ne=s.get("redirect_status");if(!h||!V)return;let W=kt=>{let at=localStorage.getItem(kt);if(!at)return null;try{return JSON.parse(at)}catch{return localStorage.removeItem(kt),null}},De=W(nr)??W(as),Ke;if(De?.clientSecret){if(De.clientSecret!==V)return;Ke={...De.accountPatch?{accountPatch:De.accountPatch}:{},...De.sessionId?{sessionId:De.sessionId}:{},...De.nonce?{nonce:De.nonce}:{}}}else if(De?.sessionId&&De.sessionId!==e)return;ki.current=!0,localStorage.removeItem(nr),localStorage.removeItem(as);let yt=new URL(window.location.href);yt.searchParams.delete("payment_intent"),yt.searchParams.delete("payment_intent_client_secret"),yt.searchParams.delete("redirect_status"),window.history.replaceState({},"",yt.toString());let Gt=De?.paymentMethodType??De?.tokenType??"card",wt="card";(async()=>{let kt=ae?.getRawProvider();if(!kt){let Jt="Payment is not available \u2014 please refresh and try again.";he(Jt),Kn(wt,Jt);return}if(Ne==="failed"){let Jt="Payment was declined. Please try again.";he(Jt),Kn(wt,Jt);return}let{paymentIntent:at,error:ln}=await kt.retrievePaymentIntent(V);if(ln){let Jt=ln.message??"Failed to retrieve payment status.";he(Jt),Kn(wt,Jt,{code:ln.code});return}let Qe=at?.status,cn=go(Qe);if(!at||!cn){let Jt=Qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(Jt),Kn(wt,Jt,{code:Qe??"missing_payment_intent"});return}let Bn=typeof at.payment_method=="string"?at.payment_method:at.payment_method?.id;bn({id:Bn??De?.paymentMethodId??De?.tokenId??at.id,type:"card",threeDSecureActionResultTokenId:at.id,gateway:De?.gateway??"stripe",paymentMethodType:Gt},Ke)})()},[e,bn,ae,he,Kn]);let Ca=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(ae!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let lo=Y==="buttons",vn=Se?.variables,Us=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Sa=vn?.colorBackground,qs=Sa&&!Us.has(Sa)?Sa:void 0,co=v.cardInputBorder??(lo?"#e5e7eb":"#A4A4FF"),Ii=vn?.colorDanger??"#dc2626",xt=s=>Br[s]&&(Qn[s]||yn),zo=$t&&(Nt||yn),An=s=>s?Ii:co,Uo=(sn.malformed||sn.empty)&&(Zn||yn),$s=An(Uo),wa=v.cardFormContainer?.backgroundColor??qs??(lo?"white":"#EDEDFF"),Nr=v.cardInputBackground??vn?.colorBackground??"white",ka=zr(Ee),Ei=zr(Re),Or=v.nameInput,Ri=v.cardInputFontSize??Ol(Or?.fontSize)??vn?.fontSizeBase??"16px",_i=typeof Or?.fontFamily=="string"?Or.fontFamily:vn?.fontFamily??"Poppins, sans-serif",Ti=Na(Or?.fontWeight)??400,js=v.cardInputColor??(typeof Or?.color=="string"?Or.color:void 0)??vn?.colorText??"#262833",Vs=v.cardInputPlaceholderColor??"#9ca3af",At=vn?.borderRadius??"8px",kr=vn?.borderRadius??v.cardButton?.borderRadius??At,Ir=vn?.colorPrimary??"#4A49FF",Ks=vn?.colorPrimaryHover??Qr(Ir,.12),Ia=vn?.colorText??"#262833",Ea={fontSize:Ri,fontFamily:_i,fontWeight:Ti,color:js,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},uo={marginTop:"0.375rem",...Ea,fontSize:"0.75rem",lineHeight:1.4,color:Ii},Hs={"--flopay-input-placeholder-color":Vs,"--flopay-input-font-size":Ri,"--flopay-input-font-family":_i,"--flopay-input-font-weight":String(Ti)},po=v.cardFormContainer??{},Ra=po.padding??(lo?"0":"1rem"),_a=po.borderRadius??At,Ys=Ce&&jn?(0,l.jsx)(Zr,{capture:Ce,html:jn.html,messageToken:jn.messageToken,expectedOrigin:jn.expectedOrigin,theme:pe,onReady:()=>{if(!St&&!ie||typeof document>"u")return;let s=()=>{let V=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(V){tn.current=!0;try{V.focus()}finally{tn.current=!1}}};$n.current||s()},onError:s=>he(s),onValidation:s=>{let h=H.current;(h==="idle"||h==="validation-window")&&(he(s),s&&H.current==="validation-window"&&(f.current&&(clearTimeout(f.current),f.current=null),H.current="idle",z(null)))}}):(0,l.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),xi=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&kn()},style:{backgroundColor:wa,borderRadius:_a,...po,padding:Ra,...Hs,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
package/dist/index.mjs CHANGED
@@ -22,7 +22,7 @@ ${en.join(`
22
22
  0% { opacity: 1; transform: translateX(0) scale(1); }
23
23
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
24
24
  }
25
- `,pa=44,Mr=280;function oi(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var zc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Uc(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var js={width:"100%",minHeight:pa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function qc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Bs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Qa(e){return e==="paypal"?"PayPal":Fr(e)}function $c(e,t){let n=`We couldn't open ${Qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ks(e){let t=ge(0),n=ge(null),r=ge(null),o=fe((u=r.current)=>{let I=u;I?.timer&&(clearTimeout(I.timer),I.timer=null)},[]),a=fe((u,I)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(u),u.timer=setTimeout(()=>{u.timer=null,r.current?.generation===u.generation&&(r.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},I))},[o,e]),l=fe(u=>{u.yieldedControl&&a(u,600)},[a]),s=fe(u=>{o();let I=t.current+1;t.current=I,n.current=null;let he={generation:I,method:u,timer:null,yieldedControl:!1};return r.current=he,I},[o]),k=fe(u=>{let I=r.current;return typeof u=="number"&&I?.generation!==u?!1:(o(I),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),g=fe(u=>{let I=r.current,he=u??I?.generation??t.current;(!u||I?.generation===u)&&(o(I),r.current=null),n.current=he},[o]),h=fe(u=>n.current===(u??t.current),[]),b=fe(u=>r.current?.generation===u&&n.current!==u,[]),T=fe(()=>{let u=r.current;u&&l(u)},[l]),M=fe(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return wt(()=>{let u=()=>{document.visibilityState==="visible"?T():M()},I=()=>{M()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",I),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",I),window.removeEventListener("focus",T),o()}},[o,M,T]),{startAttempt:s,finishAttempt:k,invalidateAttempt:g,isAttemptInvalidated:h,isAttemptCurrent:b,generationRef:t}}function jc(e){let t=bc(e);return`Enter a valid ${Za(e)}${t?` (e.g. ${t})`:""}`}function Kc(e,t,n){let r=Cc(e),o=t.trim(),a=n&&r,l=a&&!o,s=a&&!!o&&!wc(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:s}}function Hc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!Qt(n);return{required:t,empty:r,malformed:o,value:n}}function Fs(e,t){return t instanceof Yn?t:new Yn(t instanceof Error?t.message:`${qc(e)} before-click hook failed.`,"validation_error")}function Xa(){return c("style",{children:Oc})}function Vc(e){return typeof e=="number"?`${e}px`:e}function Hs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Vs({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:xe("div",{style:{position:"relative",minHeight:44},children:[c("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),c("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Ds(e){return e!=="unavailable"&&e!=="load_error"}function ai(e){return c(Wc,{...e})}function Ls({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:s,onDecline:k,onTechnicalFailure:g,runBeforeButtonClick:h,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:M,placeholderBorderRadius:u}){let I=gr(),{emitInstrument:he}=no(Dn),j=ni(),C=ti(),[pe,Z]=ue("loading");wt(()=>{M?.(pe)},[pe,M]);let[se,ae]=ue(!1),ve=!Qt(n?.trim())||!b?.trim(),{request:et,collect:be,finish:Dt}=Wr(),Xe=ge(!1),Me=ge(null),Ae=ge(null),[ee,Q]=ue(0),[A,Fe]=ue(!1),De=ge(!1),Le=ge(new Map),{startAttempt:Ue,finishAttempt:ke,invalidateAttempt:_,isAttemptInvalidated:ce,isAttemptCurrent:Pe}=Ks((H,D,B)=>{g?.(H,D,{...B,popupBlocked:B?.popupBlocked??fr(D)}),Fe(!0),Q(Ee=>Ee+1)});wt(()=>{A&&Ae.current?.focus()},[A,ee]);let de=fe(()=>{Q(H=>H+1)},[]),K=fe((H,D,B)=>{_(B),g?.("paypal",H,{code:D,popupBlocked:fr(H)}),Fe(!0),de()},[_,g,de]),Ie=fe(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);wt(()=>{De.current&&(De.current=!1,Ie())},[Ie,ee]);let ot=fe(()=>{Fe(!1),a?.(null),Ie()},[Ie,a]);wt(()=>{if(!j||Xe.current)return;let H=new URLSearchParams(window.location.search),D=H.get("payment_intent"),B=H.get("payment_intent_client_secret"),Ee=H.get("redirect_status");if(!D||!B)return;Xe.current=!0;let Ve;try{let at=localStorage.getItem(Do);if(at){let S=JSON.parse(at);S.clientSecret===B&&(Ve={...S.accountPatch?{accountPatch:S.accountPatch}:{},...S.sessionId?{sessionId:S.sessionId}:{},...S.nonce?{nonce:S.nonce}:{}})}}catch{}try{localStorage.removeItem(Do)}catch{}let ie=new URL(window.location.href);ie.searchParams.delete("payment_intent"),ie.searchParams.delete("payment_intent_client_secret"),ie.searchParams.delete("redirect_status"),window.history.replaceState({},"",ie.toString()),(async()=>{try{if(ae(!0),Ee==="failed"){let v="PayPal payment was declined. Please try again.";a?.(v),k?.(Ht("paypal",v));return}let{paymentIntent:at,error:S}=await j.retrievePaymentIntent(B);if(S){a?.(S.message??"Failed to retrieve PayPal payment status.");return}if(at&&(at.status==="requires_capture"||at.status==="succeeded")){let v=typeof at.payment_method=="string"?at.payment_method:at.payment_method?.id;o({id:v??at.id,type:"card",threeDSecureActionResultTokenId:at.id,isPaypal:!0},Ve)}else{let v="PayPal payment was not completed. Please try again.";a?.(v),k?.(Ht("paypal",v))}}catch(at){a?.(at instanceof Error?at.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[j,o,a,k]);let ht=fe(async H=>{if(l||se){H.reject();return}let D=h?await h("paypal"):{proceed:!0};if(!D.proceed){Le.current.delete(ee),H.reject();return}let B=Ue("paypal");Le.current.set(ee,{generation:B,accountPatch:D.accountPatch,sessionId:D.sessionId,nonce:D.nonce}),Fe(!1),s?.("paypal"),H.resolve()},[l,s,h,Ue,se,ee]),qe=fe(async H=>{if(!j||!C)return;let D=Le.current.get(ee);if(D&&!Pe(D.generation)){Le.current.delete(ee);return}if(!D&&ce()||D&&!ke(D.generation))return;D||ke();let B=D??null;if(Le.current.delete(ee),!B&&h){let v=await h("paypal");if(!v.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}B={accountPatch:v.accountPatch,sessionId:v.sessionId,nonce:v.nonce}}let Ee=B?.sessionId??e,Ve=B?.nonce??t,ie=await Nc({event:H,prepared:B,email:n,billingName:b,methodLabel:"PayPal",collect:be});if(!ie){H.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let at=ie.email,S=Sn({...B?.accountPatch,...ie});try{if(ae(!0),a?.(null),!Ee||!Qt(at))throw new Error("Missing sessionId or email for PayPal payment");await T?.(ie);let v=j.createPaymentMethod,{error:_e,paymentMethod:ne}=await v({type:"paypal"});if(_e){K(_e,"stripe_paypal_create_payment_method_failed",D?.generation),H.paymentFailed({reason:"fail"});return}let W=await ma(r,he,Ee,Ve??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ne?.id??null,intentKind:"payment"});if(W.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let tt=W.clientSecret,Be={return_url:window.location.href};if(ne?.id&&(Be.payment_method=ne.id),typeof window<"u")try{localStorage.setItem(Do,JSON.stringify({clientSecret:tt,sessionId:Ee,nonce:Ve,accountPatch:S}))}catch{}let{error:Ze,paymentIntent:Mt}=await j.confirmPayment({clientSecret:tt,confirmParams:Be,redirect:"if_required"});if(Ze){if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}if(Ro(Ze)){let U=Ze.message??"Your payment was declined.";a?.(U),k?.(Ht("paypal",U,{code:ar(Ze),declineCode:Jr(Ze)})),await ya({billingApiUrl:r,sessionId:Ee,nonce:Ve,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ar(Ze)??"provider_declined"}})}else K(Ze,"stripe_paypal_confirm_failed",D?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}let P=typeof Mt?.payment_method=="string"?Mt.payment_method:Mt?.payment_method?.id;o({id:P??Mt?.id,type:"card",threeDSecureActionResultTokenId:Mt?.id,isPaypal:!0},{accountPatch:S,paymentMethodCategory:"paypal",sessionId:Ee,nonce:Ve});return}catch(v){K(v,"stripe_paypal_failed",D?.generation)}finally{ae(!1)}},[j,C,e,t,n,b,be,T,r,he,o,a,k,h,K,ke,Pe,ce,ee]);return xe(Br,{children:[c(Vs,{state:pe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:xe("div",{ref:Me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[A&&c("button",{ref:Ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:js,children:"Try PayPal again"}),et&&c(Gr,{identity:et.identity,methodLabel:et.methodLabel,onComplete:Dt,onCancel:()=>Dt(null)},et.id),c("div",{style:{display:et?"none":void 0},children:c(zs,{onReady:H=>Z(Hs(H,["paypal"])),onLoadError:()=>{Z("load_error"),ri(jt(I),"paypal","paypal")},onClick:ht,onConfirm:qe,onCancel:()=>{let H=Le.current.get(ee);Le.current.delete(ee),jt(I)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(H?.generation),Fe(!1),De.current=!0,de()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ve,emailRequired:ve,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),se&&c(er,{status:"processing"})]})}function Ns({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:s,onButtonClick:k,onDecline:g,onTechnicalFailure:h,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:M,onLoadStateChange:u,placeholderBorderRadius:I}){let he=gr(),{emitInstrument:j}=no(Dn),C=ni(),pe=ti(),[Z,se]=ue("loading");wt(()=>{u?.(Z)},[Z,u]);let[ae,ve]=ue(!1),et=!Qt(n?.trim())||!T?.trim(),{request:be,collect:Dt,finish:Xe}=Wr(),Me=ge(null),Ae=ge(null),[ee,Q]=ue(0),[A,Fe]=ue(!1),[De,Le]=ue("google_pay"),Ue=ge(!1),ke=ge("google_pay"),_=ge("google_pay"),ce=ge(null),Pe=ge(new Map),{startAttempt:de,finishAttempt:K,invalidateAttempt:Ie,isAttemptInvalidated:ot,isAttemptCurrent:ht,generationRef:qe}=Ks((S,v,_e)=>{h?.(S,v,{..._e,popupBlocked:_e?.popupBlocked??fr(v)}),Le(S),Fe(!0),Q(ne=>ne+1)});wt(()=>{A&&Ae.current?.focus()},[A,ee]);let H=fe(()=>{Q(S=>S+1)},[]),D=fe((S,v,_e,ne)=>{Ie(ne),h?.(S,v,{code:_e,popupBlocked:fr(v)}),Le(S),Fe(!0),H()},[Ie,h,H]),B=fe(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);wt(()=>{Ue.current&&(Ue.current=!1,B())},[B,ee]);let Ee=fe(()=>{Fe(!1),s?.(null),B()},[B,s]),Ve=fe(async S=>{let v=!1,_e=E=>{v||(v=!0,S.paymentFailed({reason:"fail",...E?{message:E}:{}}))};if(!C||!pe){_e();return}let ne=Pe.current.get(ee);if(ne&&!ht(ne.generation)){Pe.current.delete(ee),_e();return}if(!ne&&ot()){_e();return}if(ne&&!K(ne.generation)){_e();return}ne||K();let W=S.expressPaymentType??ne?.method??ke.current,tt=ne??null,Be=Bs(W),Ze=jt(he),Mt=Ze?.now()??globalThis.performance?.now()??Date.now(),P=new AbortController,U=!1,it,Ye=new Promise((E,mt)=>{it=mt}),en=window.setTimeout(()=>{U=!0,P.abort(),it(Ga)},Fc),Wt=async(E,mt,Tt)=>{let st=Ze?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Tt,Ye])}finally{let Rt=Ze?.now()??globalThis.performance?.now()??Date.now();Ze?.performance({stage:E,durationMs:Math.max(0,Rt-st),durationMode:"machine",requestCategory:mt,paymentMethodCategory:"wallet",provider:"stripe",...U?{statusClass:"timeout"}:{}})}};try{if(ve(!0),s?.(null),!tt&&b){let lt=await Wt("processing","other",b(Be));if(!lt.proceed){_e();return}tt={accountPatch:lt.accountPatch,sessionId:lt.sessionId,nonce:lt.nonce}}let E=tt?.sessionId??e,mt=tt?.nonce??t,Tt=$s({event:S,fallbackEmail:ce.current?.email??tt?.accountPatch?.email??n,fallbackName:[ce.current?.firstName??tt?.accountPatch?.firstName,ce.current?.lastName??tt?.accountPatch?.lastName].filter(Boolean).join(" ")||T});if(!Qt(Tt.email)){_e("Buyer details are required."),Dt(Qa(W),Tt).then(lt=>{lt&&(ce.current=lt)});return}ce.current=null;let st=Sn({...tt?.accountPatch,...Tt});await Wt("processing","provider_sdk",Promise.resolve(M?.(Tt)));let{error:Rt}=await Wt("tokenization","provider_sdk",pe.submit());if(Rt){D(W,Rt,"stripe_wallet_submit_failed",ne?.generation),_e();return}if(!E)throw new Error("Missing sessionId or email for payment.");let pn=await Wt("processing","intent_create",ma(r,j,E,mt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,paymentMethodId:null,intentKind:o},{signal:P.signal}));if(pn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let an=pn.clientSecret,mn=Sc(an)?C.confirmSetup({elements:pe,clientSecret:an,redirect:"if_required"}):C.confirmPayment({elements:pe,clientSecret:an,redirect:"if_required"}),Lt=!1,wn=lt=>{if(Lt||lt.error||ne&&qe.current!==ne.generation)return;let ft=lt.setupIntent??lt.paymentIntent,sn=ft?.id,Qe=ft?.status,Wn=lt.setupIntent?Qe==="succeeded":ko(typeof Qe=="string"?Qe:void 0),dt=ft?.payment_method,nn=typeof dt=="string"?dt:typeof dt?.id=="string"?dt.id:null;if(!Wn||typeof sn!="string"||!nn)return;Lt=!0;let bt=`${Us}:${E}`;if(typeof window<"u")try{localStorage.setItem(bt,JSON.stringify({createdAt:Date.now(),sessionId:E,nonce:mt,accountPatch:st,paymentMethodId:nn,providerIntentId:sn,paymentMethodType:W}))}catch{}try{l({id:nn,type:"card",threeDSecureActionResultTokenId:sn},{accountPatch:st,paymentMethodCategory:"wallet",sessionId:E,nonce:mt})}finally{if(typeof window<"u")try{localStorage.removeItem(bt)}catch{}}};mn.then(lt=>{U&&wn(lt)},()=>{});let tn=await Wt("three_ds_handoff","provider_sdk",mn),yt=tn.error;if(yt){if(Ro(yt)){let lt=yt.message??"Your payment was declined.";s?.(lt),g?.(Ht(Be,lt,{code:ar(yt),declineCode:Jr(yt)})),_e(lt),ya({billingApiUrl:r,sessionId:E,nonce:mt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,providerDeclineReason:ar(yt)??"provider_declined"}})}else D(W,yt,"stripe_wallet_confirm_failed",ne?.generation),_e();return}if(wn(tn),!Lt)throw new Error("Invalid provider returned for APM intent")}catch(E){E===Ga&&Ze?.error({errorCode:"REQUEST_TIMEOUT",stage:"callback",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"timeout",failureCategory:"provider_runtime"}),D(W,E,E===Ga?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",ne?.generation),_e()}finally{window.clearTimeout(en);let E=Ze?.now()??globalThis.performance?.now()??Date.now();Ze?.performance({stage:"callback",durationMs:Math.max(0,E-Mt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...U?{statusClass:"timeout"}:{}}),ve(!1)}},[C,pe,e,t,n,T,Dt,M,r,j,o,l,s,g,b,D,K,ht,ot,qe,he,ee]),ie=St(()=>{let S=["applePay","googlePay","paypal","link","amazonPay","klarna"],v=new Set(["applePay","googlePay"]),_e=new Set(a.map(xs)),ne={};for(let W of S)_e.has(W)?ne[W]=v.has(W)?"always":"auto":ne[W]="never";return ne},[a]),at=St(()=>a.map(xs),[a]);return xe(Br,{children:[c(Vs,{state:Z,placeholderTestId:"flopay-wallet-placeholder",borderRadius:I,children:xe("div",{ref:Me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[A&&xe("button",{ref:Ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ee,style:js,children:["Try ",Qa(De)," again"]}),be&&c(Gr,{identity:be.identity,methodLabel:be.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},be.id),c("div",{style:{display:be?"none":void 0},children:c(zs,{onReady:S=>{se(Hs(S,at))},onLoadError:S=>{se("load_error"),ri(jt(he),"stripe","wallet")},onClick:async S=>{ke.current=S.expressPaymentType,_.current=Bs(S.expressPaymentType);let v=!0,_e=window.setTimeout(()=>{v=!1,S.reject()},Bc),ne=b?await b(_.current):{proceed:!0};if(window.clearTimeout(_e),!v)return;if(!ne.proceed){Pe.current.delete(ee),S.reject();return}let W=de(S.expressPaymentType);Pe.current.set(ee,{generation:W,method:S.expressPaymentType,accountPatch:ne.accountPatch,sessionId:ne.sessionId,nonce:ne.nonce}),Fe(!1),k?.(_.current),S.resolve()},onConfirm:Ve,onCancel:()=>{let S=Pe.current.get(ee);Pe.current.delete(ee),jt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Ie(S?.generation),Fe(!1),Ue.current=!0,H()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ie,emailRequired:et,billingAddressRequired:et,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),ae&&c(er,{status:"processing"})]})}function Yc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:s,borderColor:k,textColor:g,borderRadius:h,fontFamily:b}){let T=_c(e,t),M=Rs[e],[u,I]=ue(!1),he=T?.backgroundColor??s??"#ffffff",j=T?.borderColor??k??"#d1d5db",C=T?.textColor??g??"#262833";return c("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:pa,padding:"0 1rem",backgroundColor:he,color:C,border:`1px solid ${j}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?c("span",{style:{margin:"0 auto"},children:`Connecting to ${Fr(e)}\u2026`}):xe(Br,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:Pc(e)?8:0},children:[M&&!u?c("img",{src:M,alt:"","aria-hidden":"true",onError:()=>I(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):T?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:T.logoSvg}}):null,c("span",{children:Fr(e)})]}),a&&c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:C,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:c("path",{d:"M9 18l6-6-6-6"})})]})})}function ei({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:s,onErrorChange:k,onDecline:g,onCancel:h,runBeforeButtonClick:b,onButtonClick:T,isProcessing:M,submitButtonColor:u,submitButtonBorderRadius:I,submitButtonStyle:he,errorText:j}){let C=gr(),{emitInstrument:pe}=no(Dn),Z=ni(),se=ti(),[ae,ve]=ue(!1),et=ge(!1),[be,Dt]=ue(!1),[Xe,Me]=ue("loading"),[Ae,ee]=ue(""),Q=!Qt(r?.trim()),A=!Q||Qt(Ae.trim()),Fe=fe(async()=>{if(!Z||!se||M||et.current||!be)return;et.current=!0,ve(!0);let De=b?await b("card"):{proceed:!0};if(!De.proceed){et.current=!1,ve(!1);return}T?.("card");let Le=De.sessionId??t,Ue=De.nonce??n,ke=Er(o?.trim()),_=Sn({email:De.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:De.accountPatch?.firstName?.trim()||ke.firstName,lastName:De.accountPatch?.lastName?.trim()||ke.lastName}),ce=_.email,Pe=Sn({...De.accountPatch,..._});try{if(k?.(null),!Qt(ce))throw new Error("A valid email address is required for payment.");await a?.(_);let de=await se.submit();if(de.error){k?.(de.error.message??"Payment failed.");return}let K=[_.firstName,_.lastName].filter(Boolean).join(" "),Ie=await Z.createPaymentMethod({elements:se,params:{billing_details:{email:ce,...K?{name:K}:{}}}});if(Ie.error||!Ie.paymentMethod){k?.(Ie.error?.message??"Failed to create payment method.");return}let ot=Ie.paymentMethod;if(!Le||!ce)throw new Error("Missing sessionId or email for payment.");let ht=ot.type||e,qe=await ma(l,pe,Le,Ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ht,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let H=qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(tr,JSON.stringify({clientSecret:H,sessionId:Le,nonce:Ue,accountPatch:Pe,paymentMethodId:ot.id,paymentMethodType:ot.type??e,gateway:"stripe"}))}catch{}let{error:D,paymentIntent:B}=await Z.confirmPayment({clientSecret:H,confirmParams:{return_url:window.location.href,payment_method:ot.id},redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=D.message??"Payment failed.";k?.(ie),g?.(Ht("card",ie,{code:D.code})),await ya({billingApiUrl:l,sessionId:Le,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:D.code??"provider_declined"}});return}let Ee=B?.status;if(!ko(Ee)){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=Ee==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";k?.(ie),g?.(Ht("card",ie,{code:Ee??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let Ve=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;s({id:Ve??ot.id,type:"card",threeDSecureActionResultTokenId:B?.id,gateway:"stripe",paymentMethodType:ot.type??e},{accountPatch:Pe,paymentMethodCategory:"apm",sessionId:Le,nonce:Ue})}catch(de){k?.(de instanceof Error?de.message:"Payment failed. Please try again.")}finally{et.current=!1,ve(!1)}},[Z,se,M,be,b,T,t,n,r,o,Ae,a,l,pe,e,s,k,g]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Q&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Q&&xe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:De=>ee(De.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(xc,{onReady:()=>Me("ready"),onLoadError:()=>{Me("load_error"),ri(jt(C),"stripe","apm")},onChange:De=>{Dt(!!De.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...Qt(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Fe()},disabled:!be||!A||ae||M||Xe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:I,fontSize:"1rem",fontWeight:600,cursor:!be||!A||ae||M||Xe!=="ready"?"not-allowed":"pointer",opacity:!be||!A||ae||M||Xe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:ae?"Processing\u2026":`Pay with ${Fr(e)}`}),j&&c(Zr,{margin:"0.75rem 0 0",children:j})]})}function Os({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:s,paymentElementBaseOptions:k,onTokenizedBody:g,onErrorChange:h,onButtonClick:b,onDecline:T,runBeforeButtonClick:M,onLoadStateChange:u,isProcessing:I=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:j=8,submitButtonStyle:C,buttonAppearance:pe,themeId:Z,onExpandApm:se,expandedApmMethod:ae}){let{emitInstrument:ve}=no(Dn),[et,be]=ue(null),[Dt,Xe]=ue(null),Me=ge(!1),{request:Ae,collect:ee,finish:Q}=Wr();wt(()=>{l.length>0&&s?u?.("ready"):s||u?.("loading")},[l.length,s,u]);let A=fe(async _=>{if(!s||Me.current||I)return;Me.current=!0,Xe(_);let ce=M?await M("card"):{proceed:!0};if(!ce.proceed){Me.current=!1,Xe(null);return}b?.("card");let Pe=ce.sessionId??e,de=ce.nonce??t,K=Er([ce.accountPatch?.firstName,ce.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ie=Sn({email:ce.accountPatch?.email?.trim()||n?.trim(),firstName:ce.accountPatch?.firstName?.trim()||K.firstName,lastName:ce.accountPatch?.lastName?.trim()||K.lastName});if(!Qt(Ie.email)){Xe(null);let qe=await ee(Fr(_),Ie);if(!qe){Me.current=!1;return}Ie=qe,Xe(_)}let ot=Ie.email,ht=Sn({...ce.accountPatch,...Ie});try{if(h?.(null),!Pe||!Qt(ot))throw new Error("Missing sessionId or email for payment.");await o?.(Ie);let qe=await ma(a,ve,Pe,de??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let H=qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(tr,JSON.stringify({clientSecret:H,sessionId:Pe,nonce:de,accountPatch:ht,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:D,paymentIntent:B}=await s.confirmPayment({clientSecret:H,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[Ie.firstName,Ie.lastName].filter(Boolean).join(" "),...ot?{email:ot}:{}}}},redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=D.message??"Payment failed.";h?.(ie),T?.(Ht("card",ie,{code:D.code})),await ya({billingApiUrl:a,sessionId:Pe,nonce:de,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:D.code??"provider_declined"}});return}let Ee=B?.status;if(!ko(Ee)){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=Ee==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(ie),T?.(Ht("card",ie,{code:Ee??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let Ve=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;g({id:Ve??B?.id,type:"card",threeDSecureActionResultTokenId:B?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:ht,paymentMethodCategory:"apm",sessionId:Pe,nonce:de})}catch(qe){h?.(qe instanceof Error?qe.message:"Payment failed. Please try again.")}finally{Me.current=!1,Xe(null)}},[s,I,M,b,e,t,n,ee,a,ve,r,o,g,h,T]),[Fe,De]=ue(null),Le=se?ae??null:Fe,Ue=fe(_=>{Me.current||I||Le&&Le!==_||(Ts(_)?se?se(_):De(_):A(_))},[Le,I,A,se]),ke=St(()=>Fe?{...k,paymentMethodTypes:[Fe]}:null,[Fe,k]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?c(Gr,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:Q,onCancel:()=>Q(null)},Ae.id):l.map(_=>{let ce=ae===_,Pe=Dt===_,de=Dt!==null&&Dt!==_||ae!=null&&ae!==_;return xe(Mc.Fragment,{children:[c(Yc,{method:_,themeId:Z,submitting:Pe,disabled:de,highlighted:ce,hasNextStep:Ts(_),onClick:()=>Ue(_),backgroundColor:pe?.backgroundColor,borderColor:pe?.borderColor,textColor:pe?.textColor,borderRadius:pe?.borderRadius,fontFamily:pe?.fontFamily}),!se&&Fe===_&&ke&&s&&c(Ar,{stripe:s,options:ke,children:c(ei,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:g,onErrorChange:h,onDecline:T,onCancel:()=>De(null),runBeforeButtonClick:M,onButtonClick:b,isProcessing:I,submitButtonColor:he,submitButtonBorderRadius:j,submitButtonStyle:C})},_)]},_)})})}function Wc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:s,onTokenizedBody:k,firstName:g,lastName:h,chv:b,className:T,isProcessing:M,error:u,onErrorChange:I,showPayPal:he=!0,showStripe:j=!0,enabledPaymentMethods:C,enabledPaymentMethodCountries:pe,showApplePay:Z=!0,showGooglePay:se=!0,layout:ae="default",theme:ve,buttonsTheme:et,buttonsStyles:be,appearance:Dt,cardButtonContent:Xe,cardBackButtonContent:Me,cardTitleContent:Ae,showSecurityFooter:ee,onButtonClick:Q,onBeforeButtonClick:A,onBuyerIdentityReady:Fe,enableAVS:De,cardFieldOrder:Le,cardPreFormSlot:Ue,avsLayout:ke="row",country:_,zip:ce,addressLine1:Pe,addressLine2:de,city:K,state:Ie,onCountryChange:ot,onZipChange:ht,avsCheck:qe,checkoutType:H,checkoutLayout:D,totalAmount:B=0,currency:Ee="usd",initialCardOpen:Ve=!1,directPaypal:ie,isSubscription:at=!1,session:S,dataAttachmentPending:v=!1,dataAttachmentRequiresIdentity:_e=!1,debug:ne=!1}){let W=gr(),tt=Oa(),Be=no(Vn),{emitInstrument:Ze}=no(Dn),Mt=S??Be.session,P=Mt?.gateways?.paypal?.providerObjectType??ie?.providerObjectType,U=v||Be.claimPending===!0,it=_e||Be.claimRequiresIdentity===!0,Ye=U&&!it,en=us(),[Wt,E]=ue(!1),[mt,Tt]=ue(null),[st,Rt]=ue(_??"US"),[pn,an]=ue(ce??""),[mn,Lt]=ue(Pe??""),[wn,tn]=ue(de??""),[yt,lt]=ue(K??""),[ft,sn]=ue(Ie??""),[Qe,Wn]=ue(""),[dt,nn]=ue({}),bt=ge(ce??""),Gt=ge(_??"US"),kn=ge(Pe??""),yn=ge(de??""),_n=ge(K??""),ln=ge(Ie??""),Tn=ge(""),qt=ge({});wt(()=>{let i=(y,N,Te,z,Re)=>{if(qt.current[y])return;let ze=N?.trim();!ze||ze===Te.current||(Te.current=ze,z(ze),Re?.(ze))};i("country",_,Gt,Rt,ot),i("zip",ce,bt,an,ht),i("addressLine1",Pe,kn,Lt),i("addressLine2",de,yn,tn),i("city",K,_n,lt),i("state",Ie,ln,sn)},[_,ce,Pe,de,K,Ie,ot,ht]);let G=St(()=>Ec(De),[De]),fn=G!==null,Nn=St(()=>Wa(S),[S]),Gn=!!S?.vault?.html,Cr=!!S?.gateways?.pcivault,cr=!!(S?.gateways?.stripe?.enabledPaymentMethods??C)?.includes("card"),Nt=Gn||cr||Cr,$e=!!(j&&Nt&&W&&e),[dr,w]=ue(()=>ae!=="buttons"||Ve?e??null:null),[ct,Kt]=ue(0),In=ae!=="buttons"||Ve||!!e&&dr===e,me=St(()=>!W||!$e||!e||!In?null:W.cardCapture({sessionId:e,captureMethod:S?.captureMethod}),[W,$e,e,In,S?.captureMethod]),cn=St(()=>{let i=st,y=G?He(G.postal_code,i):!1;return Kc(i,pn,y)},[G,st,pn]),{avsInvalid:wr,invalidAvsFields:Lr}=St(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!$e||!G)return{avsInvalid:!1,invalidAvsFields:i};let y=st,N=(Re,ze)=>He(Re,y)&&!ze.trim(),Te={line1:N(G.address_line_1,mn),city:N(G.city,yt),state:N(G.state,ft),zip:cn.empty||cn.malformed};return{avsInvalid:Te.line1||Te.city||Te.state||Te.zip,invalidAvsFields:Te}},[$e,G,st,mn,yt,ft,cn]),[gn,ur]=ue(!1),[Jn,On]=ue(!1),[Ot,zn]=ue(!1),[Xn,hn]=ue({line1:!1,city:!1,state:!1}),rn=ge(!1),Un=ge({email:!1,line1:!1,city:!1,state:!1,zip:!1}),qn=ge(!1),ut=fe(i=>{Un.current[i]=!0,qn.current=!0},[]),bn=fe(i=>!rn.current&&Un.current[i],[]),vn=fe(i=>{bn(i)&&hn(y=>y[i]?y:{...y,[i]:!0})},[bn]),[$n,xn]=ue(()=>Ja(S?.vault)),[Ce,on]=ue(Ve&&Nt?"card":"buttons"),[zt,pr]=ue(null),jn=Ce==="expanding"||Ce==="card",mr=S?.gateways?.stripe?"stripe":void 0,En=fe(()=>{Ze?.({class:"card_surface",provider:mr})},[mr,Ze]),Mn=ge(null),Ut=fe(i=>{Mn.current&&clearTimeout(Mn.current),Mn.current=setTimeout(()=>{Mn.current=null,i()},Mr)},[]);wt(()=>()=>{Mn.current&&clearTimeout(Mn.current)},[]);let x=fe(()=>{En(),w(e??null),Kt(i=>i+1),on("expanding"),Ut(()=>on("card"))},[Ut,En,e]),L=fe(()=>{on("collapsing"),Ut(()=>on("buttons"))},[Ut]),V=fe(i=>{pr(i),on("apm-expanding"),Ut(()=>on("apm-form"))},[Ut]),Y=fe(()=>{on("apm-collapsing"),Ut(()=>{on("buttons"),pr(null)})},[Ut]);wt(()=>{ae==="buttons"&&Ve&&Nt&&(w(e??null),on("card"))},[ae,Ve,Nt,e]);let[Se,F]=ue(null),q=ge(!1),p=ge(null),O=ge("idle"),[$,gt]=ue(null),vt=ge($);wt(()=>{vt.current=$},[$]);let te=n||en,we=ge(null),Jt=St(()=>{if(Fe||Be.claimBuyerIdentity||S?.buyerIdentified!==!1||!e||!t)return;let i=`${te}|${e}|${t}`;we.current?.key!==i&&(we.current={key:i,claim:Vr(new to(te,{telemetry:!1}),e,t,{...o?{userId:o}:{},...g?{firstName:g}:{},...h?{lastName:h}:{}})});let y=we.current.claim;return async N=>{await y(N)}},[Fe,Be.claimBuyerIdentity,S?.buyerIdentified,e,t,te,o,g,h]),nt=Fe??Be.claimBuyerIdentity??Jt,m=u??mt,d=St(()=>Tc(ve),[ve]),f=St(()=>{let i=d?.buttonsLayout??Rc(et);return be?{...i,...be,cardButton:{...i.cardButton,...be.cardButton},cardFormContainer:{...i.cardFormContainer,...be.cardFormContainer},backButton:{...i.backButton,...be.backButton},backButtonIcon:{...i.backButtonIcon,...be.backButtonIcon},submitButton:{...i.submitButton,...be.submitButton},title:{...i.title,...be.title}}:i},[d,et,be]),ye=Dt??d?.appearance,re=St(()=>Qi({appearance:ye,buttonsStyles:f,layout:ae}),[ye,f,ae]),je=Be.inlineSessionPatchProcessing??!1,We=(M??Wt)||je,J=te.replace(/\/+$/,""),R=St(()=>Na({userId:o,email:r,firstName:g,lastName:h,country:_,zip:ce},dt),[o,r,g,h,_,ce,dt]),oe=[R.firstName,R.lastName].filter(i=>!!i?.trim()).join(" "),Ke=!Qt(R.email?.trim()),Ne=ge(null);$e&&Ne.current===null&&(Ne.current=Ke);let Pt=$e&&(Ne.current??Ke),Oe=St(()=>Hc(Qe,Pt),[Qe,Pt]),$t=Oe.empty||Oe.malformed,Rn=St(()=>W?W.getRawProvider():null,[W]),Nr=St(()=>tt?tt.getRawProvider():null,[tt]),so=B||100,qo=St(()=>ye?yc(ye):null,[ye]),$o=qo?{appearance:qo}:null,Pi=St(()=>{let i=qo??{},y=i.rules??{};return{...i,rules:{...y,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...y[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...y[".AccordionItemContents"]??{}}}}},[qo]),Ci=St(()=>{let i=as(B);return{...i,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...$o}},[B,Ee,$o]),Si=St(()=>({mode:"payment",amount:so,currency:Ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...$o}),[so,Ee,$o]),le=fe(i=>{Tt(i),I?.(i)},[I]),va=ge(""),[wi,rl]=ue(!1),Pa=fe(()=>{rl(!0)},[]);wt(()=>{if(!$e||!Pt||!nt||!wi||$t||va.current)return;let i=Sn({email:Qt(R.email?.trim())?R.email?.trim():Tn.current.trim(),firstName:R.firstName?.trim(),lastName:R.lastName?.trim()});va.current=JSON.stringify(i),nn(y=>({...y,...i})),Promise.resolve(nt(i)).catch(y=>{va.current="",le(y instanceof Error?y.message:"Failed to attach buyer details.")})},[$e,Pt,nt,wi,$t,R.email,R.firstName,R.lastName,le]),wt(()=>{!$e||!me||me.setCardFieldOrder?.(Le??null,G==null&&!Pt)},[$e,me,Le,G,Pt]),wt(()=>{(Ce==="expanding"||Ce==="collapsing"||Ce==="apm-expanding"||Ce==="apm-collapsing")&&le(null)},[Ce,le]);let Kn=fe((i,y,N)=>{s?.(Ht(i,y,N))},[s]),Or=fe((i,y,N)=>{let Te=N?.popupBlocked??fr(y),z=$c(i,Te),Re=_r(N?.code)??ar(y)??"external_payment_method_failed",ze=new Yn(z,"api_error",{code:"external_payment_method_failed",param:i});F(null),ae==="buttons"&&(on("buttons"),pr(null)),le(z),l?.(ze),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:Te})},[ae,l,le]);wt(()=>{if(!$e||!e){xn(null);return}let i=Ja(S?.vault);if(i){xn(i);return}if(!In){xn(null);return}xn(null);let y=!0;return new to(J).getVaultCapture(e,t).then(N=>{if(!y)return;let Te=Ja(N);Te?xn(Te):le("Failed to load the secure card form.")}).catch(N=>{y&&le(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{y=!1}},[$e,In,ct,e,S?.vault,J,t,le]);let Zn=ge({onComplete:a,onError:l,updateError:le,emitDecline:Kn,resolvedAccount:R,avsConfig:G,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:J,captureMethod:S?.captureMethod,paymentId:S?.paymentId,authorizationExpiresAt:S?.authorizationExpiresAt});Zn.current={onComplete:a,onError:l,updateError:le,emitDecline:Kn,resolvedAccount:R,avsConfig:G,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:J,captureMethod:S?.captureMethod,paymentId:S?.paymentId,authorizationExpiresAt:S?.authorizationExpiresAt};let Ca=ge(!1),ki=fe(()=>{let{resolvedAccount:i,avsConfig:y,avsCheckProp:N}=Zn.current,Te=i.email?.trim(),z=Qt(Te)?Te:Tn.current.trim();if(!Qt(z))return null;let Re=i.firstName?.trim(),ze=i.lastName?.trim(),pt=Gt.current||i.country||"US",Xt=y?He(y.state,pt):!1,kt=y?He(y.address_line_1,pt):!1,It=y?He(y.postal_code,pt):!1,rt=y?He(y.city,pt):!1,dn=y?He(y.address_line_2,pt):!1,Ge=kt&&!Xt&&It?_s(pt,(bt.current??"").trim()):null,un=Xt?ln.current:Ge;return{accountData:{userId:i.userId??"",email:z,...Re?{firstName:Re}:{},...ze?{lastName:ze}:{},...It&&bt.current?{zip:bt.current}:{},...rt&&_n.current?{city:_n.current}:{},...un?{state:un}:{},...kt&&kn.current?{addressLine1:kn.current}:{},...dn&&yn.current?{addressLine2:yn.current}:{},country:pt},...N!==void 0?{avsCheck:N}:{},...y?{avsConfig:{country:He(y.country,pt),postal_code:It,address_line_1:kt,address_line_2:dn,city:rt,state:Xt}}:{}}},[]),Ii=ge(U);Ii.current=U,wt(()=>{U||m!==As||Zn.current.updateError(null)},[U,m]),wt(()=>{!$e||!me||me.setSubmitGate?.(wr||U||$t)},[$e,me,wr,U,$t]),wt(()=>{if(!$e||!me)return;Ca.current=!1;let i=!1,y=me.on("submitting",()=>{ur(!0),p.current&&clearTimeout(p.current),O.current="validation-window",p.current=setTimeout(()=>{p.current=null,O.current==="validation-window"&&(O.current="processing")},Dc),F("processing");let{baseUrl:ze,sessionId:pt,nonce:Xt,updateError:kt,onError:It}=Zn.current;if(!pt||!Xt)return;let rt=ki();if(!rt){kt("Enter a valid email address."),O.current="idle",F(null);return}new to(ze).patchAccountSnapshot(pt,Xt,rt,{telemetryMode:"best_effort"}).catch(dn=>{if(!Lc(dn))return;let Ge=dn instanceof Error?dn.message:"Please check your billing address and try again.";kt(Ge),O.current="idle",F(null),It?.(dn instanceof Yn?dn:new Yn(Ge,"api_error"))})}),N=me.on("complete",async ze=>{if(Qr(ze.sessionId??Zn.current.sessionId),O.current="terminal",F("success"),await new Promise(kt=>setTimeout(kt,1200)),Ca.current)return;Ca.current=!0;let pt=Zn.current,Xt=Wa(pt)||ze.outcome==="authorized";Zn.current.onComplete?.(Xt?{status:"authorized",paymentIntentId:ze.intentId,paymentId:ze.paymentId??pt.paymentId,sessionId:ze.sessionId??pt.sessionId,authorizationExpiresAt:ze.authorizationExpiresAt??pt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:ze.intentId,checkoutMethod:"card"})}),Te=me.on("decline",async ze=>{let{updateError:pt,emitDecline:Xt}=Zn.current,kt=ze.message??"Your payment was declined. Please try another card or contact your bank.";O.current="terminal",pt(kt),F("error");let It=ze.failureOutcome??kc(ze.declineReason)??"authorization_declined";Xt("card",kt,{code:It,declineCode:It}),await new Promise(rt=>setTimeout(rt,1500)),!i&&(O.current="idle",F(null))}),z=me.on("error",async ze=>{let{updateError:pt,onError:Xt}=Zn.current,kt=ze.message??"There was a problem processing your payment. Please try again.";O.current="terminal",pt(kt),F("error"),Xt?.(new Yn(kt,"api_error",{code:ze.failureOutcome??"capture_failed"})),await new Promise(It=>setTimeout(It,1500)),!i&&(O.current="idle",F(null))}),Re=me.on("blocked",()=>{if(!Ii.current){ur(!0);return}Pa(),Zn.current.updateError(As)});return()=>{i=!0,p.current&&(clearTimeout(p.current),p.current=null),O.current="idle",y(),N(),Te(),z(),Re()}},[$e,me,Pa,ki]);let Qn=!!ie?.clientId,lo=Array.isArray(C),jo=lo&&C.length>0,ol=lo&&C.includes("paypal"),{expressMethods:Ko,paymentElementMethods:co}=St(()=>Ic(C,{excludePaypal:Qn}),[C,Qn]),Ei=Qn||!!tt,al=St(()=>Ei?Ko.filter(i=>i!=="paypal"):Ko,[Ko,Ei]),il=St(()=>{let i=[];return Z&&i.push("apple_pay"),se&&i.push("google_pay"),i},[Z,se]),zr=lo?al:il,sl=j&&zr.length>0,Sa=fn?st:_,Ho=St(()=>{let i=Sa?.trim().toUpperCase();return i?pe?co.filter(y=>{let N=pe[y];return!N||N.length===0||N.includes(i)}):hc(co,Sa):co},[co,Sa,pe]),wa=St(()=>({mode:"payment",amount:so,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",appearance:Pi}),[so,Ee,Pi]),[Ri,_i]=ue("loading"),[Ti,xi]=ue("loading"),[Mi,Ai]=ue("loading"),[ll,ka]=ue(!1),[Bi,Ia]=ue("loading"),[Vo,cl]=ue();wt(()=>{cl(Es())},[]);let Fi=he&&(Qn||(lo?ol:Vo===!1)),Di=j&&sl,uo=!Ye&&Fi&&Qn,Li=Bi==="retrying"||Bi==="exhausted",po=!Ye&&Fi&&!!Nr&&(!Qn||Li),mo=!Ye&&Di&&!!Rn,yo=!Ye&&j&&jo&&Ho.length>0&&!!Rn,dl=uo&&!Li?ll:po&&Ds(Ri),ul=mo&&Ds(Ti),pl=yo&&Mi!=="load_error",Ni=i=>i==="loading"||i==="ready",Oi=uo||po&&Ni(Ri)||mo&&Ni(Ti)||yo&&Mi!=="load_error",Yo=ge(!1);wt(()=>{if(!Yo.current){if(!j&&!he){Yo.current=!0;let i=new Yn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),le(i.message)}else if(!j&&he&&!Qn&&!Nr){Yo.current=!0;let i=new Yn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(i),le(i.message)}else if(Vo!==void 0&&!Ye&&!Nt&&!Oi){Yo.current=!0;let i=new Yn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(i),le(i.message)}}},[j,he,Qn,Nr,Vo,Ye,Nt,Oi,l,le]);let zi=ge(!1);wt(()=>{if(zi.current||!jo)return;let i=[];Z!==!0&&i.push("showApplePay"),se!==!0&&i.push("showGooglePay"),i.length!==0&&(zi.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[jo,Z,se]);let Ui=fe((i,y)=>Be.applyInlineSessionPatch?Be.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let Te=Fs(y,N);return le(Te.message),l?.(Te),{error:Te,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Be.applyInlineSessionPatch,t,l,e,le]),Hn=fe(async i=>{if(!A)return{proceed:!0};try{let y=await A({method:i,sessionId:e||void 0,createSession:Be.inlineSessionDraft});if(y===!1)return{proceed:!1};if(y&&typeof y=="object"){y.account&&nn(Te=>({...Te??{},...y.account}));let N=await Ui(y,i);return N.error?{proceed:!1,accountPatch:y.account}:{proceed:!0,accountPatch:y.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(y){let N=Fs(i,y);return le(N.message),l?.(N),{proceed:!1}}},[Ui,Be.inlineSessionDraft,A,l,e,le]),qi=fe(async(i,y)=>{if(q.current)return;q.current=!0,E(!0),F("processing"),le(null);let N=y?.sessionId??e,Te=y?.nonce??t,z=Na(R,y?.accountPatch),Re=y?.completionPaymentMethodId??Io(i),ze=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,pt=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Xt=()=>{Ze?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:pt})};try{let It=await new to(J).processPayment(z.userId??"",{sessionId:N,nonce:Te,paymentMethodCategory:y?.paymentMethodCategory??Uc(i),tokenizedData:ze,accountData:{...y?.accountPatch,userId:z.userId??"",email:z.email??"",...z.firstName?{firstName:z.firstName}:{},...z.lastName?{lastName:z.lastName}:{},...G?(()=>{let Ge=Gt.current,un=He(G.state,Ge),Bn=He(G.address_line_1,Ge),Zt=He(G.postal_code,Ge),Po=Bn&&!un&&Zt?_s(Ge,(bt.current??"").trim()):null,Co=un?ln.current:Po;return{country:Ge,...Zt&&bt.current?{zip:bt.current}:{},...He(G.city,Ge)&&_n.current?{city:_n.current}:{},...Co?{state:Co}:{},...Bn&&kn.current?{addressLine1:kn.current}:{},...He(G.address_line_2,Ge)&&yn.current?{addressLine2:yn.current}:{}}})():{}},chv:b,avsCheck:qe??!1,checkoutType:H,checkoutLayout:D,avsConfig:G?{country:He(G.country,Gt.current),postal_code:He(G.postal_code,Gt.current),address_line_1:He(G.address_line_1,Gt.current),address_line_2:He(G.address_line_2,Gt.current),city:He(G.city,Gt.current),state:He(G.state,Gt.current)}:void 0});if(It.ok){let Ge=It.status===204?null:await It.json().catch(()=>null),un=Wa(S)||Ge?.status==="authorized";Qr(N),F("success"),gt(null),await new Promise(Bn=>setTimeout(Bn,1200)),a?.(un?{status:"authorized",...typeof Ge?.paymentId=="string"?{paymentId:Ge.paymentId}:S?.paymentId?{paymentId:S.paymentId}:{},sessionId:typeof Ge?.sessionId=="string"?Ge.sessionId:N,...typeof Ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Ge.authorizationExpiresAt}:S?.authorizationExpiresAt?{authorizationExpiresAt:S.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"});return}let rt=await It.json().catch(()=>null);if(rt?.type==="paypal_redirect_required"){let Ge=rt.threeDSecureToken,un=rt.paymentMethodId||i.id||"";if(!W||!Ge){F("error"),le("PayPal authorization required but no token provided.");return}try{let Bn=tt?.getRawProvider();if(!Bn){le("PayPal is not available.");return}let Zt={return_url:window.location.href};un&&(Zt.payment_method=un);let{error:Po}=await Bn.confirmPayment({clientSecret:Ge,confirmParams:Zt,redirect:"if_required"});if(Po){F("error");let Co=Po.message??"PayPal payment failed.";le(Co),Kn("paypal",Co,{code:Po.code})}}catch(Bn){F("error"),le(Bn instanceof Error?Bn.message:"PayPal authorization failed.")}return}if(rt?.type==="paypal_direct_required"){let Ge=rt.orderId;if(!Ge){F("error"),le("PayPal retry required but no order id provided.");return}let un=vt.current?.attempts??0;if(un>=2){F("error"),le("PayPal payment could not be completed after multiple attempts."),Kn("paypal","paypal_direct_required retry limit exceeded");return}ka(!1),Ia("loading"),gt({orderId:Ge,attempts:un+1}),F(null);return}gc(It.status,rt)||Xt(),F("error");let dn=rt?.message??"Payment failed. Please try again.";le(dn),Kn(i.isPaypal?"paypal":"card",dn,{code:rt?.code??rt?.gatewayErrorCode,declineCode:rt?.declineCode??rt?.gatewayDeclineReason}),await new Promise(Ge=>setTimeout(Ge,1500))}catch(kt){qs(kt)||Xt(),F("error"),le(kt instanceof Error?kt.message:"An unexpected error occurred"),await new Promise(It=>setTimeout(It,1500))}finally{E(!1),F(null),q.current=!1}},[J,e,t,R,G,qe,H,D,b,W,tt,S,a,le,Kn,Ze]),Pn=fe((i,y)=>{k?k(i):qi(i,y)},[k,qi]),fo=`${Us}:${e}`;wt(()=>{if(typeof window>"u")return;let i=localStorage.getItem(fo);if(!i)return;let y;try{y=JSON.parse(i)}catch{localStorage.removeItem(fo);return}if(!y||typeof y.createdAt!="number"||Date.now()-y.createdAt<0||Date.now()-y.createdAt>Ac||typeof y.paymentMethodId!="string"||typeof y.providerIntentId!="string"||typeof y.paymentMethodType!="string"||y.sessionId!==e||!t||y.nonce!==t||!zr.includes(y.paymentMethodType)){localStorage.removeItem(fo);return}localStorage.removeItem(fo),Pn({id:y.paymentMethodId,type:"card",threeDSecureActionResultTokenId:y.providerIntentId,gateway:"stripe",paymentMethodType:y.paymentMethodType},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Pn,t,e,fo,zr]);let $i=ge(!1);wt(()=>{if(typeof window>"u"||$i.current)return;let i=new URLSearchParams(window.location.search),y=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),Te=i.get("redirect_status");if(!y||!N)return;let z=It=>{let rt=localStorage.getItem(It);if(!rt)return null;try{return JSON.parse(rt)}catch{return localStorage.removeItem(It),null}},Re=z(tr)??z(Ms),ze;if(Re?.clientSecret){if(Re.clientSecret!==N)return;ze={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;$i.current=!0,localStorage.removeItem(tr),localStorage.removeItem(Ms);let pt=new URL(window.location.href);pt.searchParams.delete("payment_intent"),pt.searchParams.delete("payment_intent_client_secret"),pt.searchParams.delete("redirect_status"),window.history.replaceState({},"",pt.toString());let Xt=Re?.paymentMethodType??Re?.tokenType??"card",kt="card";(async()=>{let It=W?.getRawProvider();if(!It){let Zt="Payment is not available \u2014 please refresh and try again.";le(Zt),Kn(kt,Zt);return}if(Te==="failed"){let Zt="Payment was declined. Please try again.";le(Zt),Kn(kt,Zt);return}let{paymentIntent:rt,error:dn}=await It.retrievePaymentIntent(N);if(dn){let Zt=dn.message??"Failed to retrieve payment status.";le(Zt),Kn(kt,Zt,{code:dn.code});return}let Ge=rt?.status,un=ko(Ge);if(!rt||!un){let Zt=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";le(Zt),Kn(kt,Zt,{code:Ge??"missing_payment_intent"});return}let Bn=typeof rt.payment_method=="string"?rt.payment_method:rt.payment_method?.id;Pn({id:Bn??Re?.paymentMethodId??Re?.tokenId??rt.id,type:"card",threeDSecureActionResultTokenId:rt.id,gateway:Re?.gateway??"stripe",paymentMethodType:Xt},ze)})()},[e,Pn,W,le,Kn]);let Ea=fe(i=>{i.preventDefault()},[]);if(!(W!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let go=ae==="buttons",Cn=ye?.variables,ml=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ra=Cn?.colorBackground,yl=Ra&&!ml.has(Ra)?Ra:void 0,ho=f.cardInputBorder??(go?"#e5e7eb":"#A4A4FF"),ji=Cn?.colorDanger??"#dc2626",xt=i=>Lr[i]&&(Xn[i]||gn),Wo=$t&&(Ot||gn),An=i=>i?ji:ho,Go=(cn.malformed||cn.empty)&&(Jn||gn),fl=An(Go),_a=f.cardFormContainer?.backgroundColor??yl??(go?"white":"#EDEDFF"),Ur=f.cardInputBackground??Cn?.colorBackground??"white",Ta=$r(Me),Ki=$r(Ae),qr=f.nameInput,Hi=f.cardInputFontSize??Vc(qr?.fontSize)??Cn?.fontSizeBase??"16px",Vi=typeof qr?.fontFamily=="string"?qr.fontFamily:Cn?.fontFamily??"Poppins, sans-serif",Yi=Zi(qr?.fontWeight)??400,gl=f.cardInputColor??(typeof qr?.color=="string"?qr.color:void 0)??Cn?.colorText??"#262833",hl=f.cardInputPlaceholderColor??"#9ca3af",At=Cn?.borderRadius??"8px",kr=Cn?.borderRadius??f.cardButton?.borderRadius??At,Ir=Cn?.colorPrimary??"#4A49FF",bl=Cn?.colorPrimaryHover??So(Ir,.12),xa=Cn?.colorText??"#262833",Ma={fontSize:Hi,fontFamily:Vi,fontWeight:Yi,color:gl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},bo={marginTop:"0.375rem",...Ma,fontSize:"0.75rem",lineHeight:1.4,color:ji},vl={"--flopay-input-placeholder-color":hl,"--flopay-input-font-size":Hi,"--flopay-input-font-family":Vi,"--flopay-input-font-weight":String(Yi)},vo=f.cardFormContainer??{},Aa=vo.padding??(go?"0":"1rem"),Ba=vo.borderRadius??At,Pl=me&&$n?c(Fa,{capture:me,html:$n.html,messageToken:$n.messageToken,expectedOrigin:$n.expectedOrigin,theme:re,onReady:()=>{if(!Pt&&!G||typeof document>"u")return;let i=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){rn.current=!0;try{N.focus()}finally{rn.current=!1}}};qn.current||i()},onError:i=>le(i),onValidation:i=>{let y=O.current;(y==="idle"||y==="validation-window")&&(le(i),i&&O.current==="validation-window"&&(p.current&&(clearTimeout(p.current),p.current=null),O.current="idle",F(null)))}}):c("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Wi=xe("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&En()},style:{backgroundColor:_a,borderRadius:Ba,...vo,padding:Aa,...vl,display:"flex",flexDirection:"column"},children:[c("style",{children:`
25
+ `,pa=44,Mr=280;function oi(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var zc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Uc(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var js={width:"100%",minHeight:pa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function qc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Bs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Qa(e){return e==="paypal"?"PayPal":Fr(e)}function $c(e,t){let n=`We couldn't open ${Qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ks(e){let t=ge(0),n=ge(null),r=ge(null),o=fe((u=r.current)=>{let I=u;I?.timer&&(clearTimeout(I.timer),I.timer=null)},[]),a=fe((u,I)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(u),u.timer=setTimeout(()=>{u.timer=null,r.current?.generation===u.generation&&(r.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},I))},[o,e]),l=fe(u=>{u.yieldedControl&&a(u,600)},[a]),s=fe(u=>{o();let I=t.current+1;t.current=I,n.current=null;let he={generation:I,method:u,timer:null,yieldedControl:!1};return r.current=he,I},[o]),k=fe(u=>{let I=r.current;return typeof u=="number"&&I?.generation!==u?!1:(o(I),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),g=fe(u=>{let I=r.current,he=u??I?.generation??t.current;(!u||I?.generation===u)&&(o(I),r.current=null),n.current=he},[o]),h=fe(u=>n.current===(u??t.current),[]),b=fe(u=>r.current?.generation===u&&n.current!==u,[]),T=fe(()=>{let u=r.current;u&&l(u)},[l]),M=fe(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return wt(()=>{let u=()=>{document.visibilityState==="visible"?T():M()},I=()=>{M()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",I),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",I),window.removeEventListener("focus",T),o()}},[o,M,T]),{startAttempt:s,finishAttempt:k,invalidateAttempt:g,isAttemptInvalidated:h,isAttemptCurrent:b,generationRef:t}}function jc(e){let t=bc(e);return`Enter a valid ${Za(e)}${t?` (e.g. ${t})`:""}`}function Kc(e,t,n){let r=Cc(e),o=t.trim(),a=n&&r,l=a&&!o,s=a&&!!o&&!wc(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:s}}function Hc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!Qt(n);return{required:t,empty:r,malformed:o,value:n}}function Fs(e,t){return t instanceof Yn?t:new Yn(t instanceof Error?t.message:`${qc(e)} before-click hook failed.`,"validation_error")}function Xa(){return c("style",{children:Oc})}function Vc(e){return typeof e=="number"?`${e}px`:e}function Hs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Vs({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:xe("div",{style:{position:"relative",minHeight:44},children:[c("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),c("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Ds(e){return e!=="unavailable"&&e!=="load_error"}function ai(e){return c(Wc,{...e})}function Ls({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:s,onDecline:k,onTechnicalFailure:g,runBeforeButtonClick:h,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:M,placeholderBorderRadius:u}){let I=gr(),{emitInstrument:he}=no(Dn),j=ni(),C=ti(),[pe,Z]=ue("loading");wt(()=>{M?.(pe)},[pe,M]);let[se,ae]=ue(!1),ve=!Qt(n?.trim())||!b?.trim(),{request:et,collect:be,finish:Dt}=Wr(),Xe=ge(!1),Me=ge(null),Ae=ge(null),[ee,Q]=ue(0),[A,Fe]=ue(!1),De=ge(!1),Le=ge(new Map),{startAttempt:Ue,finishAttempt:ke,invalidateAttempt:_,isAttemptInvalidated:ce,isAttemptCurrent:Pe}=Ks((H,D,B)=>{g?.(H,D,{...B,popupBlocked:B?.popupBlocked??fr(D)}),Fe(!0),Q(Ee=>Ee+1)});wt(()=>{A&&Ae.current?.focus()},[A,ee]);let de=fe(()=>{Q(H=>H+1)},[]),K=fe((H,D,B)=>{_(B),g?.("paypal",H,{code:D,popupBlocked:fr(H)}),Fe(!0),de()},[_,g,de]),Ie=fe(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);wt(()=>{De.current&&(De.current=!1,Ie())},[Ie,ee]);let ot=fe(()=>{Fe(!1),a?.(null),Ie()},[Ie,a]);wt(()=>{if(!j||Xe.current)return;let H=new URLSearchParams(window.location.search),D=H.get("payment_intent"),B=H.get("payment_intent_client_secret"),Ee=H.get("redirect_status");if(!D||!B)return;Xe.current=!0;let Ve;try{let at=localStorage.getItem(Do);if(at){let S=JSON.parse(at);S.clientSecret===B&&(Ve={...S.accountPatch?{accountPatch:S.accountPatch}:{},...S.sessionId?{sessionId:S.sessionId}:{},...S.nonce?{nonce:S.nonce}:{}})}}catch{}try{localStorage.removeItem(Do)}catch{}let ie=new URL(window.location.href);ie.searchParams.delete("payment_intent"),ie.searchParams.delete("payment_intent_client_secret"),ie.searchParams.delete("redirect_status"),window.history.replaceState({},"",ie.toString()),(async()=>{try{if(ae(!0),Ee==="failed"){let v="PayPal payment was declined. Please try again.";a?.(v),k?.(Ht("paypal",v));return}let{paymentIntent:at,error:S}=await j.retrievePaymentIntent(B);if(S){a?.(S.message??"Failed to retrieve PayPal payment status.");return}if(at&&(at.status==="requires_capture"||at.status==="succeeded")){let v=typeof at.payment_method=="string"?at.payment_method:at.payment_method?.id;o({id:v??at.id,type:"card",threeDSecureActionResultTokenId:at.id,isPaypal:!0},Ve)}else{let v="PayPal payment was not completed. Please try again.";a?.(v),k?.(Ht("paypal",v))}}catch(at){a?.(at instanceof Error?at.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[j,o,a,k]);let ht=fe(async H=>{if(l||se){H.reject();return}let D=h?await h("paypal"):{proceed:!0};if(!D.proceed){Le.current.delete(ee),H.reject();return}let B=Ue("paypal");Le.current.set(ee,{generation:B,accountPatch:D.accountPatch,sessionId:D.sessionId,nonce:D.nonce}),Fe(!1),s?.("paypal"),H.resolve()},[l,s,h,Ue,se,ee]),qe=fe(async H=>{if(!j||!C)return;let D=Le.current.get(ee);if(D&&!Pe(D.generation)){Le.current.delete(ee);return}if(!D&&ce()||D&&!ke(D.generation))return;D||ke();let B=D??null;if(Le.current.delete(ee),!B&&h){let v=await h("paypal");if(!v.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}B={accountPatch:v.accountPatch,sessionId:v.sessionId,nonce:v.nonce}}let Ee=B?.sessionId??e,Ve=B?.nonce??t,ie=await Nc({event:H,prepared:B,email:n,billingName:b,methodLabel:"PayPal",collect:be});if(!ie){H.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let at=ie.email,S=Sn({...B?.accountPatch,...ie});try{if(ae(!0),a?.(null),!Ee||!Qt(at))throw new Error("Missing sessionId or email for PayPal payment");await T?.(ie);let v=j.createPaymentMethod,{error:_e,paymentMethod:ne}=await v({type:"paypal"});if(_e){K(_e,"stripe_paypal_create_payment_method_failed",D?.generation),H.paymentFailed({reason:"fail"});return}let W=await ma(r,he,Ee,Ve??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ne?.id??null,intentKind:"payment"});if(W.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let tt=W.clientSecret,Be={return_url:window.location.href};if(ne?.id&&(Be.payment_method=ne.id),typeof window<"u")try{localStorage.setItem(Do,JSON.stringify({clientSecret:tt,sessionId:Ee,nonce:Ve,accountPatch:S}))}catch{}let{error:Ze,paymentIntent:Mt}=await j.confirmPayment({clientSecret:tt,confirmParams:Be,redirect:"if_required"});if(Ze){if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}if(Ro(Ze)){let U=Ze.message??"Your payment was declined.";a?.(U),k?.(Ht("paypal",U,{code:ar(Ze),declineCode:Jr(Ze)})),await ya({billingApiUrl:r,sessionId:Ee,nonce:Ve,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ar(Ze)??"provider_declined"}})}else K(Ze,"stripe_paypal_confirm_failed",D?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}let P=typeof Mt?.payment_method=="string"?Mt.payment_method:Mt?.payment_method?.id;o({id:P??Mt?.id,type:"card",threeDSecureActionResultTokenId:Mt?.id,isPaypal:!0},{accountPatch:S,paymentMethodCategory:"paypal",sessionId:Ee,nonce:Ve});return}catch(v){K(v,"stripe_paypal_failed",D?.generation)}finally{ae(!1)}},[j,C,e,t,n,b,be,T,r,he,o,a,k,h,K,ke,Pe,ce,ee]);return xe(Br,{children:[c(Vs,{state:pe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:xe("div",{ref:Me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[A&&c("button",{ref:Ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:js,children:"Try PayPal again"}),et&&c(Gr,{identity:et.identity,methodLabel:et.methodLabel,onComplete:Dt,onCancel:()=>Dt(null)},et.id),c("div",{style:{display:et?"none":void 0},children:c(zs,{onReady:H=>Z(Hs(H,["paypal"])),onLoadError:()=>{Z("load_error"),ri(jt(I),"paypal","paypal")},onClick:ht,onConfirm:qe,onCancel:()=>{let H=Le.current.get(ee);Le.current.delete(ee),jt(I)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(H?.generation),Fe(!1),De.current=!0,de()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ve,emailRequired:ve,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),se&&c(er,{status:"processing"})]})}function Ns({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:s,onButtonClick:k,onDecline:g,onTechnicalFailure:h,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:M,onLoadStateChange:u,placeholderBorderRadius:I}){let he=gr(),{emitInstrument:j}=no(Dn),C=ni(),pe=ti(),[Z,se]=ue("loading");wt(()=>{u?.(Z)},[Z,u]);let[ae,ve]=ue(!1),et=!Qt(n?.trim())||!T?.trim(),{request:be,collect:Dt,finish:Xe}=Wr(),Me=ge(null),Ae=ge(null),[ee,Q]=ue(0),[A,Fe]=ue(!1),[De,Le]=ue("google_pay"),Ue=ge(!1),ke=ge("google_pay"),_=ge("google_pay"),ce=ge(null),Pe=ge(new Map),{startAttempt:de,finishAttempt:K,invalidateAttempt:Ie,isAttemptInvalidated:ot,isAttemptCurrent:ht,generationRef:qe}=Ks((S,v,_e)=>{h?.(S,v,{..._e,popupBlocked:_e?.popupBlocked??fr(v)}),Le(S),Fe(!0),Q(ne=>ne+1)});wt(()=>{A&&Ae.current?.focus()},[A,ee]);let H=fe(()=>{Q(S=>S+1)},[]),D=fe((S,v,_e,ne)=>{Ie(ne),h?.(S,v,{code:_e,popupBlocked:fr(v)}),Le(S),Fe(!0),H()},[Ie,h,H]),B=fe(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);wt(()=>{Ue.current&&(Ue.current=!1,B())},[B,ee]);let Ee=fe(()=>{Fe(!1),s?.(null),B()},[B,s]),Ve=fe(async S=>{let v=!1,_e=E=>{v||(v=!0,S.paymentFailed({reason:"fail",...E?{message:E}:{}}))};if(!C||!pe){_e();return}let ne=Pe.current.get(ee);if(ne&&!ht(ne.generation)){Pe.current.delete(ee),_e();return}if(!ne&&ot()){_e();return}if(ne&&!K(ne.generation)){_e();return}ne||K();let W=S.expressPaymentType??ne?.method??ke.current,tt=ne??null,Be=Bs(W),Ze=jt(he),Mt=Ze?.now()??globalThis.performance?.now()??Date.now(),P=new AbortController,U=!1,it,Ye=new Promise((E,mt)=>{it=mt}),en=window.setTimeout(()=>{U=!0,P.abort(),it(Ga)},Fc),Wt=async(E,mt,Tt)=>{let st=Ze?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Tt,Ye])}finally{let Rt=Ze?.now()??globalThis.performance?.now()??Date.now();Ze?.performance({stage:E,durationMs:Math.max(0,Rt-st),durationMode:"machine",requestCategory:mt,paymentMethodCategory:"wallet",provider:"stripe",...U?{statusClass:"timeout"}:{}})}};try{if(ve(!0),s?.(null),!tt&&b){let lt=await Wt("processing","other",b(Be));if(!lt.proceed){_e();return}tt={accountPatch:lt.accountPatch,sessionId:lt.sessionId,nonce:lt.nonce}}let E=tt?.sessionId??e,mt=tt?.nonce??t,Tt=$s({event:S,fallbackEmail:ce.current?.email??tt?.accountPatch?.email??n,fallbackName:[ce.current?.firstName??tt?.accountPatch?.firstName,ce.current?.lastName??tt?.accountPatch?.lastName].filter(Boolean).join(" ")||T});if(!Qt(Tt.email)){_e("Buyer details are required."),Dt(Qa(W),Tt).then(lt=>{lt&&(ce.current=lt)});return}ce.current=null;let st=Sn({...tt?.accountPatch,...Tt});await Wt("processing","provider_sdk",Promise.resolve(M?.(Tt)));let{error:Rt}=await Wt("tokenization","provider_sdk",pe.submit());if(Rt){_e(),D(W,Rt,"stripe_wallet_submit_failed",ne?.generation);return}if(!E)throw new Error("Missing sessionId or email for payment.");let pn=await Wt("processing","intent_create",ma(r,j,E,mt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,paymentMethodId:null,intentKind:o},{signal:P.signal}));if(pn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let an=pn.clientSecret,mn=Sc(an)?C.confirmSetup({elements:pe,clientSecret:an,redirect:"if_required"}):C.confirmPayment({elements:pe,clientSecret:an,redirect:"if_required"}),Lt=!1,wn=lt=>{if(Lt||lt.error||ne&&qe.current!==ne.generation)return;let ft=lt.setupIntent??lt.paymentIntent,sn=ft?.id,Qe=ft?.status,Wn=lt.setupIntent?Qe==="succeeded":ko(typeof Qe=="string"?Qe:void 0),dt=ft?.payment_method,nn=typeof dt=="string"?dt:typeof dt?.id=="string"?dt.id:null;if(!Wn||typeof sn!="string"||!nn)return;Lt=!0;let bt=`${Us}:${E}`;if(typeof window<"u")try{localStorage.setItem(bt,JSON.stringify({createdAt:Date.now(),sessionId:E,nonce:mt,accountPatch:st,paymentMethodId:nn,providerIntentId:sn,paymentMethodType:W}))}catch{}try{l({id:nn,type:"card",threeDSecureActionResultTokenId:sn},{accountPatch:st,paymentMethodCategory:"wallet",sessionId:E,nonce:mt})}finally{if(typeof window<"u")try{localStorage.removeItem(bt)}catch{}}};mn.then(lt=>{U&&wn(lt)},()=>{});let tn=await Wt("three_ds_handoff","provider_sdk",mn),yt=tn.error;if(yt){if(Ro(yt)){let lt=yt.message??"Your payment was declined.";_e(lt),s?.(lt),g?.(Ht(Be,lt,{code:ar(yt),declineCode:Jr(yt)})),ya({billingApiUrl:r,sessionId:E,nonce:mt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,providerDeclineReason:ar(yt)??"provider_declined"}})}else _e(),D(W,yt,"stripe_wallet_confirm_failed",ne?.generation);return}if(wn(tn),!Lt)throw new Error("Invalid provider returned for APM intent")}catch(E){E===Ga&&Ze?.error({errorCode:"REQUEST_TIMEOUT",stage:"callback",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"timeout",failureCategory:"provider_runtime"}),_e(),D(W,E,E===Ga?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",ne?.generation)}finally{window.clearTimeout(en);let E=Ze?.now()??globalThis.performance?.now()??Date.now();Ze?.performance({stage:"callback",durationMs:Math.max(0,E-Mt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...U?{statusClass:"timeout"}:{}}),ve(!1)}},[C,pe,e,t,n,T,Dt,M,r,j,o,l,s,g,b,D,K,ht,ot,qe,he,ee]),ie=St(()=>{let S=["applePay","googlePay","paypal","link","amazonPay","klarna"],v=new Set(["applePay","googlePay"]),_e=new Set(a.map(xs)),ne={};for(let W of S)_e.has(W)?ne[W]=v.has(W)?"always":"auto":ne[W]="never";return ne},[a]),at=St(()=>a.map(xs),[a]);return xe(Br,{children:[c(Vs,{state:Z,placeholderTestId:"flopay-wallet-placeholder",borderRadius:I,children:xe("div",{ref:Me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[A&&xe("button",{ref:Ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ee,style:js,children:["Try ",Qa(De)," again"]}),be&&c(Gr,{identity:be.identity,methodLabel:be.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},be.id),c("div",{style:{display:be?"none":void 0},children:c(zs,{onReady:S=>{se(Hs(S,at))},onLoadError:S=>{se("load_error"),ri(jt(he),"stripe","wallet")},onClick:async S=>{ke.current=S.expressPaymentType,_.current=Bs(S.expressPaymentType);let v=!0,_e=window.setTimeout(()=>{v=!1,S.reject()},Bc),ne=b?await b(_.current):{proceed:!0};if(window.clearTimeout(_e),!v)return;if(!ne.proceed){Pe.current.delete(ee),S.reject();return}let W=de(S.expressPaymentType);Pe.current.set(ee,{generation:W,method:S.expressPaymentType,accountPatch:ne.accountPatch,sessionId:ne.sessionId,nonce:ne.nonce}),Fe(!1),k?.(_.current),S.resolve()},onConfirm:Ve,onCancel:()=>{let S=Pe.current.get(ee);Pe.current.delete(ee),jt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Ie(S?.generation),Fe(!1),Ue.current=!0,H()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ie,emailRequired:et,billingAddressRequired:et,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),ae&&c(er,{status:"processing"})]})}function Yc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:s,borderColor:k,textColor:g,borderRadius:h,fontFamily:b}){let T=_c(e,t),M=Rs[e],[u,I]=ue(!1),he=T?.backgroundColor??s??"#ffffff",j=T?.borderColor??k??"#d1d5db",C=T?.textColor??g??"#262833";return c("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:pa,padding:"0 1rem",backgroundColor:he,color:C,border:`1px solid ${j}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?c("span",{style:{margin:"0 auto"},children:`Connecting to ${Fr(e)}\u2026`}):xe(Br,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:Pc(e)?8:0},children:[M&&!u?c("img",{src:M,alt:"","aria-hidden":"true",onError:()=>I(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):T?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:T.logoSvg}}):null,c("span",{children:Fr(e)})]}),a&&c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:C,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:c("path",{d:"M9 18l6-6-6-6"})})]})})}function ei({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:s,onErrorChange:k,onDecline:g,onCancel:h,runBeforeButtonClick:b,onButtonClick:T,isProcessing:M,submitButtonColor:u,submitButtonBorderRadius:I,submitButtonStyle:he,errorText:j}){let C=gr(),{emitInstrument:pe}=no(Dn),Z=ni(),se=ti(),[ae,ve]=ue(!1),et=ge(!1),[be,Dt]=ue(!1),[Xe,Me]=ue("loading"),[Ae,ee]=ue(""),Q=!Qt(r?.trim()),A=!Q||Qt(Ae.trim()),Fe=fe(async()=>{if(!Z||!se||M||et.current||!be)return;et.current=!0,ve(!0);let De=b?await b("card"):{proceed:!0};if(!De.proceed){et.current=!1,ve(!1);return}T?.("card");let Le=De.sessionId??t,Ue=De.nonce??n,ke=Er(o?.trim()),_=Sn({email:De.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:De.accountPatch?.firstName?.trim()||ke.firstName,lastName:De.accountPatch?.lastName?.trim()||ke.lastName}),ce=_.email,Pe=Sn({...De.accountPatch,..._});try{if(k?.(null),!Qt(ce))throw new Error("A valid email address is required for payment.");await a?.(_);let de=await se.submit();if(de.error){k?.(de.error.message??"Payment failed.");return}let K=[_.firstName,_.lastName].filter(Boolean).join(" "),Ie=await Z.createPaymentMethod({elements:se,params:{billing_details:{email:ce,...K?{name:K}:{}}}});if(Ie.error||!Ie.paymentMethod){k?.(Ie.error?.message??"Failed to create payment method.");return}let ot=Ie.paymentMethod;if(!Le||!ce)throw new Error("Missing sessionId or email for payment.");let ht=ot.type||e,qe=await ma(l,pe,Le,Ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ht,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let H=qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(tr,JSON.stringify({clientSecret:H,sessionId:Le,nonce:Ue,accountPatch:Pe,paymentMethodId:ot.id,paymentMethodType:ot.type??e,gateway:"stripe"}))}catch{}let{error:D,paymentIntent:B}=await Z.confirmPayment({clientSecret:H,confirmParams:{return_url:window.location.href,payment_method:ot.id},redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=D.message??"Payment failed.";k?.(ie),g?.(Ht("card",ie,{code:D.code})),await ya({billingApiUrl:l,sessionId:Le,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:D.code??"provider_declined"}});return}let Ee=B?.status;if(!ko(Ee)){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=Ee==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";k?.(ie),g?.(Ht("card",ie,{code:Ee??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let Ve=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;s({id:Ve??ot.id,type:"card",threeDSecureActionResultTokenId:B?.id,gateway:"stripe",paymentMethodType:ot.type??e},{accountPatch:Pe,paymentMethodCategory:"apm",sessionId:Le,nonce:Ue})}catch(de){k?.(de instanceof Error?de.message:"Payment failed. Please try again.")}finally{et.current=!1,ve(!1)}},[Z,se,M,be,b,T,t,n,r,o,Ae,a,l,pe,e,s,k,g]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Q&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Q&&xe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:De=>ee(De.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(xc,{onReady:()=>Me("ready"),onLoadError:()=>{Me("load_error"),ri(jt(C),"stripe","apm")},onChange:De=>{Dt(!!De.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...Qt(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Fe()},disabled:!be||!A||ae||M||Xe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:I,fontSize:"1rem",fontWeight:600,cursor:!be||!A||ae||M||Xe!=="ready"?"not-allowed":"pointer",opacity:!be||!A||ae||M||Xe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:ae?"Processing\u2026":`Pay with ${Fr(e)}`}),j&&c(Zr,{margin:"0.75rem 0 0",children:j})]})}function Os({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:s,paymentElementBaseOptions:k,onTokenizedBody:g,onErrorChange:h,onButtonClick:b,onDecline:T,runBeforeButtonClick:M,onLoadStateChange:u,isProcessing:I=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:j=8,submitButtonStyle:C,buttonAppearance:pe,themeId:Z,onExpandApm:se,expandedApmMethod:ae}){let{emitInstrument:ve}=no(Dn),[et,be]=ue(null),[Dt,Xe]=ue(null),Me=ge(!1),{request:Ae,collect:ee,finish:Q}=Wr();wt(()=>{l.length>0&&s?u?.("ready"):s||u?.("loading")},[l.length,s,u]);let A=fe(async _=>{if(!s||Me.current||I)return;Me.current=!0,Xe(_);let ce=M?await M("card"):{proceed:!0};if(!ce.proceed){Me.current=!1,Xe(null);return}b?.("card");let Pe=ce.sessionId??e,de=ce.nonce??t,K=Er([ce.accountPatch?.firstName,ce.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ie=Sn({email:ce.accountPatch?.email?.trim()||n?.trim(),firstName:ce.accountPatch?.firstName?.trim()||K.firstName,lastName:ce.accountPatch?.lastName?.trim()||K.lastName});if(!Qt(Ie.email)){Xe(null);let qe=await ee(Fr(_),Ie);if(!qe){Me.current=!1;return}Ie=qe,Xe(_)}let ot=Ie.email,ht=Sn({...ce.accountPatch,...Ie});try{if(h?.(null),!Pe||!Qt(ot))throw new Error("Missing sessionId or email for payment.");await o?.(Ie);let qe=await ma(a,ve,Pe,de??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let H=qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(tr,JSON.stringify({clientSecret:H,sessionId:Pe,nonce:de,accountPatch:ht,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:D,paymentIntent:B}=await s.confirmPayment({clientSecret:H,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[Ie.firstName,Ie.lastName].filter(Boolean).join(" "),...ot?{email:ot}:{}}}},redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=D.message??"Payment failed.";h?.(ie),T?.(Ht("card",ie,{code:D.code})),await ya({billingApiUrl:a,sessionId:Pe,nonce:de,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:D.code??"provider_declined"}});return}let Ee=B?.status;if(!ko(Ee)){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=Ee==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(ie),T?.(Ht("card",ie,{code:Ee??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let Ve=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;g({id:Ve??B?.id,type:"card",threeDSecureActionResultTokenId:B?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:ht,paymentMethodCategory:"apm",sessionId:Pe,nonce:de})}catch(qe){h?.(qe instanceof Error?qe.message:"Payment failed. Please try again.")}finally{Me.current=!1,Xe(null)}},[s,I,M,b,e,t,n,ee,a,ve,r,o,g,h,T]),[Fe,De]=ue(null),Le=se?ae??null:Fe,Ue=fe(_=>{Me.current||I||Le&&Le!==_||(Ts(_)?se?se(_):De(_):A(_))},[Le,I,A,se]),ke=St(()=>Fe?{...k,paymentMethodTypes:[Fe]}:null,[Fe,k]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?c(Gr,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:Q,onCancel:()=>Q(null)},Ae.id):l.map(_=>{let ce=ae===_,Pe=Dt===_,de=Dt!==null&&Dt!==_||ae!=null&&ae!==_;return xe(Mc.Fragment,{children:[c(Yc,{method:_,themeId:Z,submitting:Pe,disabled:de,highlighted:ce,hasNextStep:Ts(_),onClick:()=>Ue(_),backgroundColor:pe?.backgroundColor,borderColor:pe?.borderColor,textColor:pe?.textColor,borderRadius:pe?.borderRadius,fontFamily:pe?.fontFamily}),!se&&Fe===_&&ke&&s&&c(Ar,{stripe:s,options:ke,children:c(ei,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:g,onErrorChange:h,onDecline:T,onCancel:()=>De(null),runBeforeButtonClick:M,onButtonClick:b,isProcessing:I,submitButtonColor:he,submitButtonBorderRadius:j,submitButtonStyle:C})},_)]},_)})})}function Wc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:s,onTokenizedBody:k,firstName:g,lastName:h,chv:b,className:T,isProcessing:M,error:u,onErrorChange:I,showPayPal:he=!0,showStripe:j=!0,enabledPaymentMethods:C,enabledPaymentMethodCountries:pe,showApplePay:Z=!0,showGooglePay:se=!0,layout:ae="default",theme:ve,buttonsTheme:et,buttonsStyles:be,appearance:Dt,cardButtonContent:Xe,cardBackButtonContent:Me,cardTitleContent:Ae,showSecurityFooter:ee,onButtonClick:Q,onBeforeButtonClick:A,onBuyerIdentityReady:Fe,enableAVS:De,cardFieldOrder:Le,cardPreFormSlot:Ue,avsLayout:ke="row",country:_,zip:ce,addressLine1:Pe,addressLine2:de,city:K,state:Ie,onCountryChange:ot,onZipChange:ht,avsCheck:qe,checkoutType:H,checkoutLayout:D,totalAmount:B=0,currency:Ee="usd",initialCardOpen:Ve=!1,directPaypal:ie,isSubscription:at=!1,session:S,dataAttachmentPending:v=!1,dataAttachmentRequiresIdentity:_e=!1,debug:ne=!1}){let W=gr(),tt=Oa(),Be=no(Vn),{emitInstrument:Ze}=no(Dn),Mt=S??Be.session,P=Mt?.gateways?.paypal?.providerObjectType??ie?.providerObjectType,U=v||Be.claimPending===!0,it=_e||Be.claimRequiresIdentity===!0,Ye=U&&!it,en=us(),[Wt,E]=ue(!1),[mt,Tt]=ue(null),[st,Rt]=ue(_??"US"),[pn,an]=ue(ce??""),[mn,Lt]=ue(Pe??""),[wn,tn]=ue(de??""),[yt,lt]=ue(K??""),[ft,sn]=ue(Ie??""),[Qe,Wn]=ue(""),[dt,nn]=ue({}),bt=ge(ce??""),Gt=ge(_??"US"),kn=ge(Pe??""),yn=ge(de??""),_n=ge(K??""),ln=ge(Ie??""),Tn=ge(""),qt=ge({});wt(()=>{let i=(y,N,Te,z,Re)=>{if(qt.current[y])return;let ze=N?.trim();!ze||ze===Te.current||(Te.current=ze,z(ze),Re?.(ze))};i("country",_,Gt,Rt,ot),i("zip",ce,bt,an,ht),i("addressLine1",Pe,kn,Lt),i("addressLine2",de,yn,tn),i("city",K,_n,lt),i("state",Ie,ln,sn)},[_,ce,Pe,de,K,Ie,ot,ht]);let G=St(()=>Ec(De),[De]),fn=G!==null,Nn=St(()=>Wa(S),[S]),Gn=!!S?.vault?.html,Cr=!!S?.gateways?.pcivault,cr=!!(S?.gateways?.stripe?.enabledPaymentMethods??C)?.includes("card"),Nt=Gn||cr||Cr,$e=!!(j&&Nt&&W&&e),[dr,w]=ue(()=>ae!=="buttons"||Ve?e??null:null),[ct,Kt]=ue(0),In=ae!=="buttons"||Ve||!!e&&dr===e,me=St(()=>!W||!$e||!e||!In?null:W.cardCapture({sessionId:e,captureMethod:S?.captureMethod}),[W,$e,e,In,S?.captureMethod]),cn=St(()=>{let i=st,y=G?He(G.postal_code,i):!1;return Kc(i,pn,y)},[G,st,pn]),{avsInvalid:wr,invalidAvsFields:Lr}=St(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!$e||!G)return{avsInvalid:!1,invalidAvsFields:i};let y=st,N=(Re,ze)=>He(Re,y)&&!ze.trim(),Te={line1:N(G.address_line_1,mn),city:N(G.city,yt),state:N(G.state,ft),zip:cn.empty||cn.malformed};return{avsInvalid:Te.line1||Te.city||Te.state||Te.zip,invalidAvsFields:Te}},[$e,G,st,mn,yt,ft,cn]),[gn,ur]=ue(!1),[Jn,On]=ue(!1),[Ot,zn]=ue(!1),[Xn,hn]=ue({line1:!1,city:!1,state:!1}),rn=ge(!1),Un=ge({email:!1,line1:!1,city:!1,state:!1,zip:!1}),qn=ge(!1),ut=fe(i=>{Un.current[i]=!0,qn.current=!0},[]),bn=fe(i=>!rn.current&&Un.current[i],[]),vn=fe(i=>{bn(i)&&hn(y=>y[i]?y:{...y,[i]:!0})},[bn]),[$n,xn]=ue(()=>Ja(S?.vault)),[Ce,on]=ue(Ve&&Nt?"card":"buttons"),[zt,pr]=ue(null),jn=Ce==="expanding"||Ce==="card",mr=S?.gateways?.stripe?"stripe":void 0,En=fe(()=>{Ze?.({class:"card_surface",provider:mr})},[mr,Ze]),Mn=ge(null),Ut=fe(i=>{Mn.current&&clearTimeout(Mn.current),Mn.current=setTimeout(()=>{Mn.current=null,i()},Mr)},[]);wt(()=>()=>{Mn.current&&clearTimeout(Mn.current)},[]);let x=fe(()=>{En(),w(e??null),Kt(i=>i+1),on("expanding"),Ut(()=>on("card"))},[Ut,En,e]),L=fe(()=>{on("collapsing"),Ut(()=>on("buttons"))},[Ut]),V=fe(i=>{pr(i),on("apm-expanding"),Ut(()=>on("apm-form"))},[Ut]),Y=fe(()=>{on("apm-collapsing"),Ut(()=>{on("buttons"),pr(null)})},[Ut]);wt(()=>{ae==="buttons"&&Ve&&Nt&&(w(e??null),on("card"))},[ae,Ve,Nt,e]);let[Se,F]=ue(null),q=ge(!1),p=ge(null),O=ge("idle"),[$,gt]=ue(null),vt=ge($);wt(()=>{vt.current=$},[$]);let te=n||en,we=ge(null),Jt=St(()=>{if(Fe||Be.claimBuyerIdentity||S?.buyerIdentified!==!1||!e||!t)return;let i=`${te}|${e}|${t}`;we.current?.key!==i&&(we.current={key:i,claim:Vr(new to(te,{telemetry:!1}),e,t,{...o?{userId:o}:{},...g?{firstName:g}:{},...h?{lastName:h}:{}})});let y=we.current.claim;return async N=>{await y(N)}},[Fe,Be.claimBuyerIdentity,S?.buyerIdentified,e,t,te,o,g,h]),nt=Fe??Be.claimBuyerIdentity??Jt,m=u??mt,d=St(()=>Tc(ve),[ve]),f=St(()=>{let i=d?.buttonsLayout??Rc(et);return be?{...i,...be,cardButton:{...i.cardButton,...be.cardButton},cardFormContainer:{...i.cardFormContainer,...be.cardFormContainer},backButton:{...i.backButton,...be.backButton},backButtonIcon:{...i.backButtonIcon,...be.backButtonIcon},submitButton:{...i.submitButton,...be.submitButton},title:{...i.title,...be.title}}:i},[d,et,be]),ye=Dt??d?.appearance,re=St(()=>Qi({appearance:ye,buttonsStyles:f,layout:ae}),[ye,f,ae]),je=Be.inlineSessionPatchProcessing??!1,We=(M??Wt)||je,J=te.replace(/\/+$/,""),R=St(()=>Na({userId:o,email:r,firstName:g,lastName:h,country:_,zip:ce},dt),[o,r,g,h,_,ce,dt]),oe=[R.firstName,R.lastName].filter(i=>!!i?.trim()).join(" "),Ke=!Qt(R.email?.trim()),Ne=ge(null);$e&&Ne.current===null&&(Ne.current=Ke);let Pt=$e&&(Ne.current??Ke),Oe=St(()=>Hc(Qe,Pt),[Qe,Pt]),$t=Oe.empty||Oe.malformed,Rn=St(()=>W?W.getRawProvider():null,[W]),Nr=St(()=>tt?tt.getRawProvider():null,[tt]),so=B||100,qo=St(()=>ye?yc(ye):null,[ye]),$o=qo?{appearance:qo}:null,Pi=St(()=>{let i=qo??{},y=i.rules??{};return{...i,rules:{...y,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...y[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...y[".AccordionItemContents"]??{}}}}},[qo]),Ci=St(()=>{let i=as(B);return{...i,currency:Ee.toLowerCase(),...i.mode==="payment"?{captureMethod:"manual"}:{},...$o}},[B,Ee,$o]),Si=St(()=>({mode:"payment",amount:so,currency:Ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...$o}),[so,Ee,$o]),le=fe(i=>{Tt(i),I?.(i)},[I]),va=ge(""),[wi,rl]=ue(!1),Pa=fe(()=>{rl(!0)},[]);wt(()=>{if(!$e||!Pt||!nt||!wi||$t||va.current)return;let i=Sn({email:Qt(R.email?.trim())?R.email?.trim():Tn.current.trim(),firstName:R.firstName?.trim(),lastName:R.lastName?.trim()});va.current=JSON.stringify(i),nn(y=>({...y,...i})),Promise.resolve(nt(i)).catch(y=>{va.current="",le(y instanceof Error?y.message:"Failed to attach buyer details.")})},[$e,Pt,nt,wi,$t,R.email,R.firstName,R.lastName,le]),wt(()=>{!$e||!me||me.setCardFieldOrder?.(Le??null,G==null&&!Pt)},[$e,me,Le,G,Pt]),wt(()=>{(Ce==="expanding"||Ce==="collapsing"||Ce==="apm-expanding"||Ce==="apm-collapsing")&&le(null)},[Ce,le]);let Kn=fe((i,y,N)=>{s?.(Ht(i,y,N))},[s]),Or=fe((i,y,N)=>{let Te=N?.popupBlocked??fr(y),z=$c(i,Te),Re=_r(N?.code)??ar(y)??"external_payment_method_failed",ze=new Yn(z,"api_error",{code:"external_payment_method_failed",param:i});F(null),ae==="buttons"&&(on("buttons"),pr(null)),le(z),l?.(ze),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:Te})},[ae,l,le]);wt(()=>{if(!$e||!e){xn(null);return}let i=Ja(S?.vault);if(i){xn(i);return}if(!In){xn(null);return}xn(null);let y=!0;return new to(J).getVaultCapture(e,t).then(N=>{if(!y)return;let Te=Ja(N);Te?xn(Te):le("Failed to load the secure card form.")}).catch(N=>{y&&le(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{y=!1}},[$e,In,ct,e,S?.vault,J,t,le]);let Zn=ge({onComplete:a,onError:l,updateError:le,emitDecline:Kn,resolvedAccount:R,avsConfig:G,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:J,captureMethod:S?.captureMethod,paymentId:S?.paymentId,authorizationExpiresAt:S?.authorizationExpiresAt});Zn.current={onComplete:a,onError:l,updateError:le,emitDecline:Kn,resolvedAccount:R,avsConfig:G,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:J,captureMethod:S?.captureMethod,paymentId:S?.paymentId,authorizationExpiresAt:S?.authorizationExpiresAt};let Ca=ge(!1),ki=fe(()=>{let{resolvedAccount:i,avsConfig:y,avsCheckProp:N}=Zn.current,Te=i.email?.trim(),z=Qt(Te)?Te:Tn.current.trim();if(!Qt(z))return null;let Re=i.firstName?.trim(),ze=i.lastName?.trim(),pt=Gt.current||i.country||"US",Xt=y?He(y.state,pt):!1,kt=y?He(y.address_line_1,pt):!1,It=y?He(y.postal_code,pt):!1,rt=y?He(y.city,pt):!1,dn=y?He(y.address_line_2,pt):!1,Ge=kt&&!Xt&&It?_s(pt,(bt.current??"").trim()):null,un=Xt?ln.current:Ge;return{accountData:{userId:i.userId??"",email:z,...Re?{firstName:Re}:{},...ze?{lastName:ze}:{},...It&&bt.current?{zip:bt.current}:{},...rt&&_n.current?{city:_n.current}:{},...un?{state:un}:{},...kt&&kn.current?{addressLine1:kn.current}:{},...dn&&yn.current?{addressLine2:yn.current}:{},country:pt},...N!==void 0?{avsCheck:N}:{},...y?{avsConfig:{country:He(y.country,pt),postal_code:It,address_line_1:kt,address_line_2:dn,city:rt,state:Xt}}:{}}},[]),Ii=ge(U);Ii.current=U,wt(()=>{U||m!==As||Zn.current.updateError(null)},[U,m]),wt(()=>{!$e||!me||me.setSubmitGate?.(wr||U||$t)},[$e,me,wr,U,$t]),wt(()=>{if(!$e||!me)return;Ca.current=!1;let i=!1,y=me.on("submitting",()=>{ur(!0),p.current&&clearTimeout(p.current),O.current="validation-window",p.current=setTimeout(()=>{p.current=null,O.current==="validation-window"&&(O.current="processing")},Dc),F("processing");let{baseUrl:ze,sessionId:pt,nonce:Xt,updateError:kt,onError:It}=Zn.current;if(!pt||!Xt)return;let rt=ki();if(!rt){kt("Enter a valid email address."),O.current="idle",F(null);return}new to(ze).patchAccountSnapshot(pt,Xt,rt,{telemetryMode:"best_effort"}).catch(dn=>{if(!Lc(dn))return;let Ge=dn instanceof Error?dn.message:"Please check your billing address and try again.";kt(Ge),O.current="idle",F(null),It?.(dn instanceof Yn?dn:new Yn(Ge,"api_error"))})}),N=me.on("complete",async ze=>{if(Qr(ze.sessionId??Zn.current.sessionId),O.current="terminal",F("success"),await new Promise(kt=>setTimeout(kt,1200)),Ca.current)return;Ca.current=!0;let pt=Zn.current,Xt=Wa(pt)||ze.outcome==="authorized";Zn.current.onComplete?.(Xt?{status:"authorized",paymentIntentId:ze.intentId,paymentId:ze.paymentId??pt.paymentId,sessionId:ze.sessionId??pt.sessionId,authorizationExpiresAt:ze.authorizationExpiresAt??pt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:ze.intentId,checkoutMethod:"card"})}),Te=me.on("decline",async ze=>{let{updateError:pt,emitDecline:Xt}=Zn.current,kt=ze.message??"Your payment was declined. Please try another card or contact your bank.";O.current="terminal",pt(kt),F("error");let It=ze.failureOutcome??kc(ze.declineReason)??"authorization_declined";Xt("card",kt,{code:It,declineCode:It}),await new Promise(rt=>setTimeout(rt,1500)),!i&&(O.current="idle",F(null))}),z=me.on("error",async ze=>{let{updateError:pt,onError:Xt}=Zn.current,kt=ze.message??"There was a problem processing your payment. Please try again.";O.current="terminal",pt(kt),F("error"),Xt?.(new Yn(kt,"api_error",{code:ze.failureOutcome??"capture_failed"})),await new Promise(It=>setTimeout(It,1500)),!i&&(O.current="idle",F(null))}),Re=me.on("blocked",()=>{if(!Ii.current){ur(!0);return}Pa(),Zn.current.updateError(As)});return()=>{i=!0,p.current&&(clearTimeout(p.current),p.current=null),O.current="idle",y(),N(),Te(),z(),Re()}},[$e,me,Pa,ki]);let Qn=!!ie?.clientId,lo=Array.isArray(C),jo=lo&&C.length>0,ol=lo&&C.includes("paypal"),{expressMethods:Ko,paymentElementMethods:co}=St(()=>Ic(C,{excludePaypal:Qn}),[C,Qn]),Ei=Qn||!!tt,al=St(()=>Ei?Ko.filter(i=>i!=="paypal"):Ko,[Ko,Ei]),il=St(()=>{let i=[];return Z&&i.push("apple_pay"),se&&i.push("google_pay"),i},[Z,se]),zr=lo?al:il,sl=j&&zr.length>0,Sa=fn?st:_,Ho=St(()=>{let i=Sa?.trim().toUpperCase();return i?pe?co.filter(y=>{let N=pe[y];return!N||N.length===0||N.includes(i)}):hc(co,Sa):co},[co,Sa,pe]),wa=St(()=>({mode:"payment",amount:so,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",appearance:Pi}),[so,Ee,Pi]),[Ri,_i]=ue("loading"),[Ti,xi]=ue("loading"),[Mi,Ai]=ue("loading"),[ll,ka]=ue(!1),[Bi,Ia]=ue("loading"),[Vo,cl]=ue();wt(()=>{cl(Es())},[]);let Fi=he&&(Qn||(lo?ol:Vo===!1)),Di=j&&sl,uo=!Ye&&Fi&&Qn,Li=Bi==="retrying"||Bi==="exhausted",po=!Ye&&Fi&&!!Nr&&(!Qn||Li),mo=!Ye&&Di&&!!Rn,yo=!Ye&&j&&jo&&Ho.length>0&&!!Rn,dl=uo&&!Li?ll:po&&Ds(Ri),ul=mo&&Ds(Ti),pl=yo&&Mi!=="load_error",Ni=i=>i==="loading"||i==="ready",Oi=uo||po&&Ni(Ri)||mo&&Ni(Ti)||yo&&Mi!=="load_error",Yo=ge(!1);wt(()=>{if(!Yo.current){if(!j&&!he){Yo.current=!0;let i=new Yn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),le(i.message)}else if(!j&&he&&!Qn&&!Nr){Yo.current=!0;let i=new Yn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(i),le(i.message)}else if(Vo!==void 0&&!Ye&&!Nt&&!Oi){Yo.current=!0;let i=new Yn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(i),le(i.message)}}},[j,he,Qn,Nr,Vo,Ye,Nt,Oi,l,le]);let zi=ge(!1);wt(()=>{if(zi.current||!jo)return;let i=[];Z!==!0&&i.push("showApplePay"),se!==!0&&i.push("showGooglePay"),i.length!==0&&(zi.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[jo,Z,se]);let Ui=fe((i,y)=>Be.applyInlineSessionPatch?Be.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let Te=Fs(y,N);return le(Te.message),l?.(Te),{error:Te,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Be.applyInlineSessionPatch,t,l,e,le]),Hn=fe(async i=>{if(!A)return{proceed:!0};try{let y=await A({method:i,sessionId:e||void 0,createSession:Be.inlineSessionDraft});if(y===!1)return{proceed:!1};if(y&&typeof y=="object"){y.account&&nn(Te=>({...Te??{},...y.account}));let N=await Ui(y,i);return N.error?{proceed:!1,accountPatch:y.account}:{proceed:!0,accountPatch:y.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(y){let N=Fs(i,y);return le(N.message),l?.(N),{proceed:!1}}},[Ui,Be.inlineSessionDraft,A,l,e,le]),qi=fe(async(i,y)=>{if(q.current)return;q.current=!0,E(!0),F("processing"),le(null);let N=y?.sessionId??e,Te=y?.nonce??t,z=Na(R,y?.accountPatch),Re=y?.completionPaymentMethodId??Io(i),ze=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,pt=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Xt=()=>{Ze?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:pt})};try{let It=await new to(J).processPayment(z.userId??"",{sessionId:N,nonce:Te,paymentMethodCategory:y?.paymentMethodCategory??Uc(i),tokenizedData:ze,accountData:{...y?.accountPatch,userId:z.userId??"",email:z.email??"",...z.firstName?{firstName:z.firstName}:{},...z.lastName?{lastName:z.lastName}:{},...G?(()=>{let Ge=Gt.current,un=He(G.state,Ge),Bn=He(G.address_line_1,Ge),Zt=He(G.postal_code,Ge),Po=Bn&&!un&&Zt?_s(Ge,(bt.current??"").trim()):null,Co=un?ln.current:Po;return{country:Ge,...Zt&&bt.current?{zip:bt.current}:{},...He(G.city,Ge)&&_n.current?{city:_n.current}:{},...Co?{state:Co}:{},...Bn&&kn.current?{addressLine1:kn.current}:{},...He(G.address_line_2,Ge)&&yn.current?{addressLine2:yn.current}:{}}})():{}},chv:b,avsCheck:qe??!1,checkoutType:H,checkoutLayout:D,avsConfig:G?{country:He(G.country,Gt.current),postal_code:He(G.postal_code,Gt.current),address_line_1:He(G.address_line_1,Gt.current),address_line_2:He(G.address_line_2,Gt.current),city:He(G.city,Gt.current),state:He(G.state,Gt.current)}:void 0});if(It.ok){let Ge=It.status===204?null:await It.json().catch(()=>null),un=Wa(S)||Ge?.status==="authorized";Qr(N),F("success"),gt(null),await new Promise(Bn=>setTimeout(Bn,1200)),a?.(un?{status:"authorized",...typeof Ge?.paymentId=="string"?{paymentId:Ge.paymentId}:S?.paymentId?{paymentId:S.paymentId}:{},sessionId:typeof Ge?.sessionId=="string"?Ge.sessionId:N,...typeof Ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Ge.authorizationExpiresAt}:S?.authorizationExpiresAt?{authorizationExpiresAt:S.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"});return}let rt=await It.json().catch(()=>null);if(rt?.type==="paypal_redirect_required"){let Ge=rt.threeDSecureToken,un=rt.paymentMethodId||i.id||"";if(!W||!Ge){F("error"),le("PayPal authorization required but no token provided.");return}try{let Bn=tt?.getRawProvider();if(!Bn){le("PayPal is not available.");return}let Zt={return_url:window.location.href};un&&(Zt.payment_method=un);let{error:Po}=await Bn.confirmPayment({clientSecret:Ge,confirmParams:Zt,redirect:"if_required"});if(Po){F("error");let Co=Po.message??"PayPal payment failed.";le(Co),Kn("paypal",Co,{code:Po.code})}}catch(Bn){F("error"),le(Bn instanceof Error?Bn.message:"PayPal authorization failed.")}return}if(rt?.type==="paypal_direct_required"){let Ge=rt.orderId;if(!Ge){F("error"),le("PayPal retry required but no order id provided.");return}let un=vt.current?.attempts??0;if(un>=2){F("error"),le("PayPal payment could not be completed after multiple attempts."),Kn("paypal","paypal_direct_required retry limit exceeded");return}ka(!1),Ia("loading"),gt({orderId:Ge,attempts:un+1}),F(null);return}gc(It.status,rt)||Xt(),F("error");let dn=rt?.message??"Payment failed. Please try again.";le(dn),Kn(i.isPaypal?"paypal":"card",dn,{code:rt?.code??rt?.gatewayErrorCode,declineCode:rt?.declineCode??rt?.gatewayDeclineReason}),await new Promise(Ge=>setTimeout(Ge,1500))}catch(kt){qs(kt)||Xt(),F("error"),le(kt instanceof Error?kt.message:"An unexpected error occurred"),await new Promise(It=>setTimeout(It,1500))}finally{E(!1),F(null),q.current=!1}},[J,e,t,R,G,qe,H,D,b,W,tt,S,a,le,Kn,Ze]),Pn=fe((i,y)=>{k?k(i):qi(i,y)},[k,qi]),fo=`${Us}:${e}`;wt(()=>{if(typeof window>"u")return;let i=localStorage.getItem(fo);if(!i)return;let y;try{y=JSON.parse(i)}catch{localStorage.removeItem(fo);return}if(!y||typeof y.createdAt!="number"||Date.now()-y.createdAt<0||Date.now()-y.createdAt>Ac||typeof y.paymentMethodId!="string"||typeof y.providerIntentId!="string"||typeof y.paymentMethodType!="string"||y.sessionId!==e||!t||y.nonce!==t||!zr.includes(y.paymentMethodType)){localStorage.removeItem(fo);return}localStorage.removeItem(fo),Pn({id:y.paymentMethodId,type:"card",threeDSecureActionResultTokenId:y.providerIntentId,gateway:"stripe",paymentMethodType:y.paymentMethodType},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Pn,t,e,fo,zr]);let $i=ge(!1);wt(()=>{if(typeof window>"u"||$i.current)return;let i=new URLSearchParams(window.location.search),y=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),Te=i.get("redirect_status");if(!y||!N)return;let z=It=>{let rt=localStorage.getItem(It);if(!rt)return null;try{return JSON.parse(rt)}catch{return localStorage.removeItem(It),null}},Re=z(tr)??z(Ms),ze;if(Re?.clientSecret){if(Re.clientSecret!==N)return;ze={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;$i.current=!0,localStorage.removeItem(tr),localStorage.removeItem(Ms);let pt=new URL(window.location.href);pt.searchParams.delete("payment_intent"),pt.searchParams.delete("payment_intent_client_secret"),pt.searchParams.delete("redirect_status"),window.history.replaceState({},"",pt.toString());let Xt=Re?.paymentMethodType??Re?.tokenType??"card",kt="card";(async()=>{let It=W?.getRawProvider();if(!It){let Zt="Payment is not available \u2014 please refresh and try again.";le(Zt),Kn(kt,Zt);return}if(Te==="failed"){let Zt="Payment was declined. Please try again.";le(Zt),Kn(kt,Zt);return}let{paymentIntent:rt,error:dn}=await It.retrievePaymentIntent(N);if(dn){let Zt=dn.message??"Failed to retrieve payment status.";le(Zt),Kn(kt,Zt,{code:dn.code});return}let Ge=rt?.status,un=ko(Ge);if(!rt||!un){let Zt=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";le(Zt),Kn(kt,Zt,{code:Ge??"missing_payment_intent"});return}let Bn=typeof rt.payment_method=="string"?rt.payment_method:rt.payment_method?.id;Pn({id:Bn??Re?.paymentMethodId??Re?.tokenId??rt.id,type:"card",threeDSecureActionResultTokenId:rt.id,gateway:Re?.gateway??"stripe",paymentMethodType:Xt},ze)})()},[e,Pn,W,le,Kn]);let Ea=fe(i=>{i.preventDefault()},[]);if(!(W!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let go=ae==="buttons",Cn=ye?.variables,ml=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ra=Cn?.colorBackground,yl=Ra&&!ml.has(Ra)?Ra:void 0,ho=f.cardInputBorder??(go?"#e5e7eb":"#A4A4FF"),ji=Cn?.colorDanger??"#dc2626",xt=i=>Lr[i]&&(Xn[i]||gn),Wo=$t&&(Ot||gn),An=i=>i?ji:ho,Go=(cn.malformed||cn.empty)&&(Jn||gn),fl=An(Go),_a=f.cardFormContainer?.backgroundColor??yl??(go?"white":"#EDEDFF"),Ur=f.cardInputBackground??Cn?.colorBackground??"white",Ta=$r(Me),Ki=$r(Ae),qr=f.nameInput,Hi=f.cardInputFontSize??Vc(qr?.fontSize)??Cn?.fontSizeBase??"16px",Vi=typeof qr?.fontFamily=="string"?qr.fontFamily:Cn?.fontFamily??"Poppins, sans-serif",Yi=Zi(qr?.fontWeight)??400,gl=f.cardInputColor??(typeof qr?.color=="string"?qr.color:void 0)??Cn?.colorText??"#262833",hl=f.cardInputPlaceholderColor??"#9ca3af",At=Cn?.borderRadius??"8px",kr=Cn?.borderRadius??f.cardButton?.borderRadius??At,Ir=Cn?.colorPrimary??"#4A49FF",bl=Cn?.colorPrimaryHover??So(Ir,.12),xa=Cn?.colorText??"#262833",Ma={fontSize:Hi,fontFamily:Vi,fontWeight:Yi,color:gl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},bo={marginTop:"0.375rem",...Ma,fontSize:"0.75rem",lineHeight:1.4,color:ji},vl={"--flopay-input-placeholder-color":hl,"--flopay-input-font-size":Hi,"--flopay-input-font-family":Vi,"--flopay-input-font-weight":String(Yi)},vo=f.cardFormContainer??{},Aa=vo.padding??(go?"0":"1rem"),Ba=vo.borderRadius??At,Pl=me&&$n?c(Fa,{capture:me,html:$n.html,messageToken:$n.messageToken,expectedOrigin:$n.expectedOrigin,theme:re,onReady:()=>{if(!Pt&&!G||typeof document>"u")return;let i=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){rn.current=!0;try{N.focus()}finally{rn.current=!1}}};qn.current||i()},onError:i=>le(i),onValidation:i=>{let y=O.current;(y==="idle"||y==="validation-window")&&(le(i),i&&O.current==="validation-window"&&(p.current&&(clearTimeout(p.current),p.current=null),O.current="idle",F(null)))}}):c("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Wi=xe("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&En()},style:{backgroundColor:_a,borderRadius:Ba,...vo,padding:Aa,...vl,display:"flex",flexDirection:"column"},children:[c("style",{children:`
26
26
  .flopay-shared-input::placeholder {
27
27
  color: var(--flopay-input-placeholder-color);
28
28
  opacity: 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/react",
3
- "version": "1.8.12",
3
+ "version": "1.8.13",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -34,8 +34,8 @@
34
34
  "@paypal/paypal-js": "^10.0.0",
35
35
  "@stripe/react-stripe-js": "^6.6.0",
36
36
  "@stripe/stripe-js": "^9.8.0",
37
- "@flopay/js": "1.8.12",
38
- "@flopay/shared": "1.8.12"
37
+ "@flopay/js": "1.8.13",
38
+ "@flopay/shared": "1.8.13"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "react": ">=18.0.0",