@flopay/react 1.8.12 → 1.8.14
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 +1 -1
- package/dist/index.mjs +2 -2
- package/package.json +3 -3
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,a.useRef)(!(0,u.isValidEmail)(n?.trim())||!F?.trim()).current,{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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{a as _t,b as er,c as Fa,d as So,e as Zi,f as Qi,g as Cl,h as Sl}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as kp}from"@flopay/shared";import{PaymentAPI as vi}from"@flopay/js";import{FloPayError as io,resolveBillingApiUrl as md,resolveButtonsLayoutTheme as yd,resolveTheme as fd}from"@flopay/shared";import{useCallback as Pr,useEffect as ro,useMemo as zo,useRef as oo,useState as Uo}from"react";import{Fragment as Hr,jsx as Fn,jsxs as es}from"react/jsx-runtime";function wl(){return es(Hr,{children:[es("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[Fn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Fn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Fn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:Fn("path",{d:"M9 18l6-6-6-6"})})]})}function kl(){return Fn(Hr,{children:"Go back"})}function Il(){return Fn(Hr,{children:"Secure card checkout"})}function $r(e){return e!==void 0&&(e===""||e===null||e===!1)}function jr({content:e}){return Fn(Hr,{children:e===void 0?Fn(wl,{}):e})}function Kr({content:e}){return Fn(Hr,{children:e===void 0?Fn(kl,{}):e})}function wo({content:e}){return Fn(Hr,{children:e===void 0?Fn(Il,{}):e})}import{FloPayError as Da,isMoneySettledOutcome as El,isSetupIntentClientSecret as Rd,isValidEmail as Rl}from"@flopay/shared";function Vr(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()};if(!Rl(l.email))return Promise.reject(new Da("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let s={};for(let[k,g]of Object.entries(l)){if(typeof g!="string")continue;let h=g.trim();h&&(s[k]=h)}return o=e.claimCheckoutSession(t,n,{accountData:s}),o.catch(()=>{}),o}}function ts(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:"checkoutMetadata"in e?{checkoutMetadata:e.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function La(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ns(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function Er(e){let t=e?.trim().split(/\s+/).filter(Boolean)??[];return t.length===0?{}:{firstName:t[0],lastName:t.length>1?t.slice(1).join(" "):void 0}}function Na(e,t){return t?{...e,...t}:e}function Ht(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var _l=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function yr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of _l)if(n.test(t))return r;return e}function Rr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Yr(e){return e?.status==="authorized"||e?.status==="complete"}function rs(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Qo(e){let t=rs(e);return new Da(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ea(e){let t=rs(e);return new Da(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function ko(e,t){return e==="processing"||El(e,t)}function os(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function as(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Io(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as fa,SESSION_CREATE_TELEMETRY as Gc}from"@flopay/js";import{buildCheckoutDisplayData as Jc,classifyTelemetryFailure as Ys,FloPayError as Vt,foldIntoProducts as Xc,isDetachedSessionEligible as Zc,resolveBillingApiUrl as Qc,resolveButtonsLayoutTheme as ed,resolveIdempotencyKey as Ws,resolveSessionCurrency as td,resolveTheme as Zs,SDK_VERSION as Qs,telemetryStatusClass as nd}from"@flopay/shared";import ii,{useCallback as nr,useEffect as rr,useMemo as Ln,useRef as Bt,useState as Ft}from"react";import{createContext as is}from"react";var Dn=is({flopay:null,paypalFlopay:null,billingApiUrl:""}),Vn=is({session:null,loading:!1,error:null});import{PaymentAPI as Ua}from"@flopay/js";import{classifyTelemetryFailure as Hl,FloPayError as ps,generateIdempotencyKey as Vl,isValidEmail as To,normalizeGatewayEnvironment as Yl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as qa,SDK_VERSION as Wl}from"@flopay/shared";import{loadScript as Gl}from"@paypal/paypal-js";import{useCallback as xo,useEffect as Et,useMemo as Mo,useRef as Je,useState as Tr}from"react";import{isValidEmail as Tl}from"@flopay/shared";import{useCallback as ss,useEffect as xl,useRef as ls,useState as ds}from"react";import{jsx as cs,jsxs as Eo}from"react/jsx-runtime";function Sn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),a=n?.trim();return{...r,...o?{firstName:o}:{},...a?{lastName:a}:{}}}function Wr(){let[e,t]=ds(null),n=ls(null),r=ls(0),o=ss((l,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:s}),new Promise(k=>{n.current=k})),[]),a=ss(l=>{let s=n.current;n.current=null,t(null),s?.(l)},[]);return xl(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Gr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,s]=ds(e.email?.trim()??""),k=Tl(l.trim());return Eo("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[Eo("div",{style:{fontWeight:700},children:["Continue with ",t]}),Eo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",cs("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:g=>s(g.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Eo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&cs("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Eo("button",{type:"button",disabled:!k||o,onClick:()=>{n(Sn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Ml(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function _r(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function ar(e){if(typeof e!="object"||e===null)return;let t=e;return _r(t.code)??_r(t.type)??_r(t.name)}function Jr(e){if(!(typeof e!="object"||e===null))return _r(e.decline_code)}function Ro(e){return typeof e!="object"||e===null?!1:_r(e.type)?.toLowerCase()==="card_error"||Jr(e)!==void 0}function fr(e){let t=Ml(e)?.toLowerCase()??"",r=`${ar(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Al}from"@flopay/shared";import{useContext as ta}from"react";function gr(){return ta(Dn).flopay}function Oa(){return ta(Dn).paypalFlopay??null}function Bl(){return ta(Vn)}function us(){return ta(Dn).billingApiUrl||Al()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Ll}from"@flopay/shared";import{useCallback as Nl,useRef as na}from"react";import{useEffect as Fl,useLayoutEffect as Dl}from"react";var _o=typeof window>"u"?Fl:Dl;var Ol={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function zl(e){return e==="stripe"||e==="paypal"?e:void 0}function Ul(e){let t=zl(e.provider),n={schemaVersion:Ll,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ol[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var za=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Xr(e,t){let n=na(e);n.current=e;let r=na(new Set),o=na(t),a=na(t);return _o(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Nl(l=>{if(a.current!==t)return;let s=Ul(l);if(s){if(za.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}_t(()=>n.current?.(s))}},[t])}var ql=Symbol.for("@flopay/js.telemetry.bridge.v1"),$l=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function jl(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Kl(e){let t=jl(),n=(o,a)=>o?o.bind(e):a,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function ra(e){let t=globalThis[$l];return Kl(t?.(e)??{})}function jt(e){if(e)return e[ql]}import{jsx as xr,jsxs as $a}from"react/jsx-runtime";var oa=45,Jl=1e3,Xl=11e3,Zl=["https://www.paypal.com","https://www.sandbox.paypal.com"],ms="We couldn't open PayPal. Try again or choose another payment method.",Ql={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 ys(e){return e.includes("No ack for postMessage init()")&&Zl.some(t=>e.includes(t))&&e.includes("10000ms")}function ec(e){return e?`${ms} Allow pop-ups for this site, then try again.`:ms}function tc(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function fs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:s,currency:k,isSubscription:g,providerObjectType:h,onTokenizedBody:b,onComplete:T,onErrorChange:M,onDecline:u,onTechnicalFailure:I,isProcessing:he=!1,onLoadStateChange:j,onInitializationStateChange:C,allowAutomaticRetry:pe=!0,onButtonClick:Z,runBeforeButtonClick:se,session:ae,existingOrderId:ve,telemetry:et,telemetryContext:be,onInstrument:Dt,debug:Xe=!1}){let Me=gr(),Ae=Xr(Dt,e),ee=Mo(()=>{if(Me)return null;let w=ra({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Wl,enabled:et!==!1});return w.setCheckoutContext(be??{}),w.beginCheckout(be??{}),w},[n,Me,et,be?.checkoutMode,be?.layout]),Q=Mo(()=>jt(Me),[Me]);Et(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let A=Mo(()=>({error:w=>{Q?Q.error(w):ee?.error(w),Ae({class:"technical_error",errorCode:w.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":w.errorCode,requestCategory:w.requestCategory,provider:w.provider})},log:w=>{Q?Q.log(w):ee?.log(w),Ae({class:"lifecycle",name:w.name,provider:w.provider})},performance:w=>{Q?Q.performance(w):ee?.performance(w)},terminal:w=>{Q?Q.terminal(w):ee?.terminal(w)},startTiming:()=>Q?.now()??ee?.now()??0,elapsed:w=>Q?.elapsed(w)??Math.max(0,(ee?.now()??w)-w)}),[Ae,Q,ee]),Fe=Je(null),De=Je(0),Le=Je(null),Ue=Je(!1),[ke,_]=Tr(!1),[ce,Pe]=Tr(!1),[de,K]=Tr(0),Ie=Je(0),[ot,ht]=Tr(!1),qe=Je(!1),H=Je(!1),[D,B]=Tr(!1),[Ee,Ve]=Tr(!1),{request:ie,collect:at,finish:S}=Wr(),v=Je({sessionId:e,required:!To(r?.trim()||ae?.customer?.email?.trim())});v.current.sessionId!==e&&(v.current={sessionId:e,required:!To(r?.trim()||ae?.customer?.email?.trim())});let _e=v.current.required,ne=Mo(()=>n.replace(/\/+$/,""),[n]),tt=ae?.gateways?.paypal?.providerObjectType??h,Be=tt??(g?"subscription":"order"),Ze=tt==="order"||tt==="setup_token",Mt=Mo(()=>JSON.stringify([ne,l,k,s??"",Be,Ze,e,ve??""]),[ne,l,k,s,ve,Be,Ze,e]),P=Je(Mt),U=P.current!==Mt,it=Je(Xe),Ye=Je(null),[en,Wt]=Tr([]),E=xo(w=>{it.current&&Wt(ct=>[...ct,`${new Date().toISOString().slice(11,23)} ${w}`])},[]);Et(()=>{it.current=Xe,Xe&&E("debug:enabled"),Ye.current?.setEnabled(Xe)},[E,Xe]);let mt=Je(b),Tt=Je(T),st=Je(M),Rt=Je(u),pn=Je(I),an=Je(Z),mn=Je(j),Lt=Je(C),wn=Je(a),tn=Je(se),yt=Je(ae),lt=Je(r),ft=Je(o),sn=Je(t),Qe=Je(null),Wn=Je(0),dt=Je(null),nn=Je(null),bt=Je(new Map),Gt=Je(new Map),kn=Je(!1);Et(()=>(kn.current=!0,()=>{kn.current=!1}),[]),Et(()=>{mt.current=b},[b]),Et(()=>{wn.current=a},[a]),Et(()=>{Tt.current=T},[T]),Et(()=>{st.current=M},[M]),Et(()=>{Rt.current=u},[u]),Et(()=>{pn.current=I},[I]),Et(()=>{an.current=Z},[Z]),Et(()=>{mn.current=j},[j]),Et(()=>{Lt.current=C},[C]),Et(()=>{tn.current=se},[se]),Et(()=>{yt.current=ae},[ae]),Et(()=>{lt.current=r},[r]),Et(()=>{ft.current=o},[o]),Et(()=>{sn.current=t},[t]),Et(()=>{Ie.current=de},[de]),Et(()=>{ot&&Le.current?.focus()},[ot,de]);let yn=xo(()=>{window.setTimeout(()=>{Le.current?.focus()},0)},[]),_n=xo(()=>{_(!1),K(w=>w+1)},[]),ln=xo(()=>{ht(!1),(Fe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Fe.current)?.focus?.()},[]);Et(()=>{!ke||!Ue.current||(Ue.current=!1,ln())},[ln,ke,de]);let Tn=xo((w,ct)=>{let Kt=pn.current;if(Kt){Kt("paypal",w,ct);return}st.current?.(ec(ct?.popupBlocked??fr(w)))},[]),qt=()=>{dt.current?.timer&&(clearTimeout(dt.current.timer),dt.current.timer=null)},G=()=>{qt();let w=Wn.current+1;return Wn.current=w,nn.current=null,dt.current={generation:w,timer:null,yieldedControl:!1},ht(!1),w},fn=w=>w!==void 0&&dt.current?.generation!==w?!1:(qt(),dt.current=null,nn.current=null,!0),Nn=w=>{let ct=w?.generation??dt.current?.generation??Wn.current;(!w?.generation||dt.current?.generation===ct)&&(qt(),dt.current=null),nn.current=ct,w?.showRetry&&ht(!0),w?.remount&&_n(),w?.focus!==!1&&yn()},Gn=w=>dt.current?.generation===w&&nn.current!==w,Cr=w=>{typeof document<"u"&&document.visibilityState!=="visible"||(qt(),w.timer=setTimeout(()=>{dt.current?.generation===w.generation&&(dt.current=null,nn.current=w.generation,Tn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),ht(!0),_n(),yn())},600))},Sr=()=>{let w=dt.current;w?.yieldedControl&&Cr(w)},cr=()=>{let w=dt.current;w&&(w.yieldedControl=!0,qt())},Nt=w=>{let ct=Qe.current;return ct&&Gt.current.set(w,ct),w};Et(()=>{let w=()=>{document.visibilityState==="visible"?Sr():cr()};return document.addEventListener("visibilitychange",w),window.addEventListener("focus",Sr),window.addEventListener("blur",cr),()=>{document.removeEventListener("visibilitychange",w),window.removeEventListener("focus",Sr),window.removeEventListener("blur",cr),qt()}},[]),Et(()=>{P.current!==Mt&&(P.current=Mt,qe.current=!1,H.current=!1,_(!1),Pe(!1),B(!1),Lt.current?.("loading"))},[Mt]),Et(()=>{_t(()=>mn.current?.(ke&&!D))},[ke,D]);let $e=Yl(s);Et(()=>{let w=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",ct=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(E(`mount clientId=${w} env=${s??"(unset)"}\u2192${$e??"live"} ccy=${k} sub=${g}`),E(`ua=${ct.slice(0,80)}${ct.length>80?"\u2026":""}`),!l){E("FAIL: clientId empty \u2014 gateway misconfigured"),B(!0),A.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Fe.current){E("FAIL: containerRef not attached");return}De.current=A.startTiming(),A.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Kt=!1,In=!1,me=()=>Kt||In,cn,wr=!1,Lr=()=>{cn=Vl(),cn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),wr=!0},gn=null,ur=!1,Jn=null,On=!1,Ot=()=>{!Jn||On||(On=!0,Jn.close().catch(()=>{}))},zn=null,Xn=()=>{zn!==null&&(A.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"overlay_return",durationMs:A.elapsed(zn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),zn=null)},hn=!1,rn=Fe.current,Un=null,qn=null,ut=[],bn=null,vn=!1,$n=!1,xn=null,Ce=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let d=m.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},on=m=>{if(!m)return"(empty)";try{let d=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),f=d.pathname.toLowerCase();return f.includes("checkcaptcha")||f.includes("captcha")?`CAPTCHA(${d.host}${f})`:f.includes("risk")||f.includes("challenge")?`RISK(${d.host}${f})`:f.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${f}`.slice(0,100)}catch{return m.slice(0,80)}},zt=m=>{let d=m.getAttribute("src"),f=m.getAttribute("srcdoc"),ye=m.getAttribute("name"),re=m.getAttribute("sandbox"),je=[];return d&&je.push(`src=${on(d)}`),f&&je.push(`srcdoc[${f.length}ch]`),!d&&!f&&je.push("src=(empty) srcdoc=(empty)"),ye&&je.push(`name=${ye.slice(0,40)}`),re!==null&&je.push(`sandbox="${re.slice(0,40)}"`),je.join(" ")},pr=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let d=m.contentDocument;if(!d)return"cd=null";let f=d.body?.children.length??0,ye=d.body?.innerHTML.length??0,re=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${f}children,${ye}ch] head[${re}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},jn=[],mr=m=>{if(me())return;let d=m.message??String(m.error??"(no message)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(E(`window:error ${d.slice(0,140)}`),jn.push(d))},En=m=>{if(me())return;let d=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(E(`window:rejection ${d.slice(0,140)}`),jn.push(d))},Mn={value:0},Ut=()=>{for(Un?.disconnect(),Un=null,qn?.disconnect(),qn=null;ut.length;)clearTimeout(ut.pop());$n=!1,vn&&typeof window<"u"&&(window.removeEventListener("error",mr),window.removeEventListener("unhandledrejection",En)),vn=!1},x=()=>{if(!(vn||me()||hn)){if(vn=!0,jn.length=0,Mn.value=0,typeof window<"u"&&(window.addEventListener("error",mr),window.addEventListener("unhandledrejection",En)),typeof PerformanceObserver<"u")try{qn=new PerformanceObserver(m=>{if(!me())for(let d of m.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;Mn.value+=1;let f=Math.round(d.duration);E(`net ${f}ms ${d.name.slice(0,90)}`)}}),qn.observe({type:"resource",buffered:!0})}catch{}xn?.()}},L=()=>{bn&&(clearTimeout(bn),bn=null)},V=()=>{Ut(),L()},Y={setEnabled:m=>{m?x():Ut()}};Ye.current=Y,it.current&&x();let Se=m=>{if(!m)return!1;let d=m.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},F=m=>{if(me()||Se(m))return;let d=yr(m)??m;_t(()=>st.current?.(d))},q=m=>{Kt||(B(!0),m.includes("paypal_ineligible")||A.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",m))},p=(m,d=!1)=>{if(Kt)return;let f=qe.current||!pe;if(ur)return;ur=!0,In=!0,V(),Ot();let ye=d||ys(m);if(ye&&pe&&!qe.current){qe.current=!0,_(!1),Ve(!1),Pe(!0),Lt.current?.("retrying"),gn=setTimeout(()=>{Kt||K(re=>re+1)},Jl);return}if(ye||f){if(_(!1),Ve(!1),Pe(!1),B(!0),Lt.current?.("exhausted"),!H.current){H.current=!0;let re=ys(m)?"paypal_init_timeout":d?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",re)}return}q(m)};B(!1);let O=async(m,d=Qe.current)=>{if(me())return;let f=d?.sessionId??e;if(mt.current){await mt.current(m,{sessionId:f,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let ye=A.startTiming();A.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let re=()=>{A.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"processing",durationMs:A.elapsed(ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let je=yt.current,We=d?.accountPatch?.email??lt.current,J=d?.accountPatch?.userId??je?.customer?.id??je?.accountData?.userId??"",R=d?.accountPatch?.firstName??je?.customer?.firstName??je?.accountData?.firstName,oe=d?.accountPatch?.lastName??je?.customer?.lastName??je?.accountData?.lastName,Ne=await new Ua(ne,{telemetry:!1}).processPayment(J,{sessionId:f,nonce:d?.nonce??sn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:J,email:We??je?.customer?.email??"",...R?{firstName:R}:{},...oe?{lastName:oe}:{},country:d?.accountPatch?.country??je?.customer?.country??je?.accountData?.country??void 0,zip:d?.accountPatch?.zip??je?.customer?.zip??je?.accountData?.zip??void 0}});if(Ne.ok){if(In||Kt&&kn.current)return;re(),A.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),_t(()=>Tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(me())return;let Pt=await Ne.json().catch(()=>null),Oe=Pt?.message??"PayPal payment failed.",$t=yr(Oe)??Oe;re(),Ne.status===400&&(typeof Pt?.declineCode=="string"||!Array.isArray(Pt?.fields))?A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Ne.status===400||Ne.status===422?A.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):A.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Ne.status>=500?"5xx":Ne.status>=400?"4xx":Ne.status>=300?"3xx":"unknown",failureCategory:Ne.status>=500?"server_error":void 0}),F($t),_t(()=>Rt.current?.(Ht("paypal",$t,{code:Pt?.code,declineCode:Pt?.declineCode})));return}catch(je){if(me())return;re(),A.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let We=je instanceof Error?je.message:"PayPal payment failed.",J=yr(We)??We;F(J),_t(()=>Rt.current?.(Ht("paypal",J)));return}},$=()=>new ps("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),gt=m=>me()?Promise.reject($()):Promise.resolve(m),vt=async m=>{if(me())throw $();wr||Lr();let d=Qe.current,f=d?.sessionId??e,ye=d?.nonce??sn.current;A.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let re;try{re=await new Ua(ne,{telemetry:!1}).createSessionIntent(f,ye??"",Ze?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:qa,paymentMethodId:null,intentKind:Be==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:cn})}catch(je){throw A.error({...Hl(je,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),je}if(me())throw $();if(re.provider!=="paypal"||re.providerObjectType!==Be)throw new Error(m);return A.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),re.providerObjectId},te=(m,d)=>{let f=d?.nonce??sn.current;if(!f)return;let ye=d?.sessionId??e,re=Jr(m)??ar(m)??"provider_declined";new Ua(ne,{telemetry:!1}).reportSessionIntentDecline(ye,f,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:re}).catch(()=>{})},we=de;E("loadScript:scheduled (deferred 1 tick)");let Jt=null,nt=setTimeout(()=>{if(Kt){E("loadScript:skipped (cancelled before defer ran)");return}E("loadScript:start");let m=$e==="live"?"production":$e;Jt=Gl({clientId:l,currency:k,...Be==="subscription"?{intent:"subscription",vault:!0}:Be==="order"?{intent:"capture"}:{},...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Jt.then(d=>{if(E(`loadScript:resolved inactive=${me()} ns=${!!d} buttons=${!!d?.Buttons}`),me())return;if(!d?.Buttons){E("FAIL: namespace missing Buttons factory"),p("PayPal SDK did not expose the Buttons factory.");return}A.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"provider_ready",durationMs:A.elapsed(De.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let f=async(J,R)=>{if(me()||Ie.current!==we)return;let oe=J.vaultSetupToken??J.subscriptionID??J.orderID??"",Ke=oe?Gt.current.get(oe):bt.current.get(we);if(!(!Ke||!Gn(Ke.generation))&&fn(Ke.generation)){Gt.current.delete(oe),bt.current.delete(Ke.surfaceKey),Xn();try{if(Ve(!0),_t(()=>st.current?.(null)),!oe)throw new ps("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ne=yt.current,Pt=Er(ft.current??[Ne?.customer?.firstName,Ne?.customer?.lastName].filter(Boolean).join(" ")),Oe=Sn({email:Ke.accountPatch?.email?.trim()||lt.current?.trim()||Ne?.customer?.email?.trim(),firstName:Ke.accountPatch?.firstName?.trim()||Pt.firstName,lastName:Ke.accountPatch?.lastName?.trim()||Pt.lastName});if(!To(Oe.email)||!(Oe.firstName||Oe.lastName))try{let $t=tc(await R?.order?.get?.());Oe=Sn({email:$t.email||Oe.email,firstName:$t.firstName||Oe.firstName,lastName:$t.lastName||Oe.lastName})}catch{}if((wn.current||_e)&&!To(Oe.email)){let $t=await at("PayPal",Oe);if(!$t)return;Oe=$t}To(Oe.email)&&(Ke.accountPatch=Sn({...Ke.accountPatch,...Oe}),await wn.current?.(Oe)),await O(Be==="setup_token"?{id:oe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:qa}:Ze?{id:oe,isPaypal:!0,gateway:"paypal",paymentMethodType:qa}:{id:oe,isPaypal:!0},Ke)}catch(Ne){F(Ne instanceof Error?Ne.message:"PayPal capture failed.")}finally{me()||Ve(!1)}}},ye=d.Buttons({style:{layout:"horizontal",height:oa,tagline:!1},onClick:async(J,R)=>{if(me()){await R.reject();return}Lr();let oe=tn.current,Ke={};if(oe)try{let Oe=await oe("paypal");if(me()){await R.reject();return}if(!Oe.proceed){Qe.current=null,bt.current.delete(we),await R.reject();return}Ke={sessionId:Oe.sessionId,accountPatch:Oe.accountPatch,nonce:Oe.nonce}}catch(Oe){E(`onClick:runBeforeButtonClick rejected msg=${(Oe instanceof Error?Oe.message:String(Oe)).slice(0,120)}`),Qe.current=null,bt.current.delete(we),await R.reject();return}_t(()=>an.current?.("paypal"));let Pt={generation:G(),surfaceKey:we,...Ke};Qe.current=Pt,bt.current.set(we,Pt),await R.resolve(),A.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),zn=A.startTiming()},createOrder:Be==="order"?ve?()=>gt(ve).then(Nt):()=>vt("Failed to create PayPal order.").then(Nt):void 0,createSubscription:Be==="subscription"?ve?()=>gt(ve).then(Nt):()=>vt("Failed to create PayPal subscription.").then(Nt):void 0,createVaultSetupToken:Be==="setup_token"?()=>vt("Failed to create PayPal setup token.").then(Nt):void 0,onApprove:f,onCancel:()=>{if(me())return;let J=bt.current.get(we)??Qe.current;J&&bt.current.delete(J.surfaceKey),Qe.current=null,Xn(),A.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue.current=!0,Nn({generation:J?.generation,remount:!0,focus:!1})},onError:J=>{if(me()||Ie.current!==we)return;let R=J instanceof Error?J.message:"PayPal failed to render.";if(E(`onError rendered=${hn} msg=${R.slice(0,120)}`),hn){let oe=bt.current.get(we)??Qe.current;if(oe&&!Gn(oe.generation)||!oe&&nn.current===Wn.current)return;if(Se(R)){fn(oe?.generation);return}if(Xn(),Ro(J)){A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),te(J,oe),_t(()=>Rt.current?.(Ht("paypal",R))),oe&&bt.current.delete(oe.surfaceKey),Qe.current=null,fn(oe?.generation);return}let Ke=R.toLowerCase();A.error({errorCode:Ke.includes("popup")&&Ke.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),oe&&bt.current.delete(oe.surfaceKey),Qe.current=null,Nn({generation:oe?.generation,remount:!0,showRetry:!0,focus:!0}),Tn(J,{code:"paypal_runtime_failed"});return}p(R)}}),re=ye.isEligible();if(E(`isEligible=${re}`),A.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!re){_(!1),p("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Jn=ye,xn=()=>{if(!vn||$n||me()||hn)return;$n=!0,E(`container:dims ${Ce(rn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),typeof MutationObserver<"u"&&(Un=new MutationObserver(R=>{if(!me()){for(let oe of R)if(oe.type==="childList")oe.addedNodes.forEach(Ke=>{if(!(Ke instanceof Element))return;let Ne=Ke.tagName.toLowerCase(),Pt=(Ke.getAttribute("title")??"").slice(0,40),Oe=Ne==="iframe"?` ${zt(Ke)}`:"";E(`child+ ${Ne}${Pt?` title="${Pt}"`:""}${Oe} dims=${Ce(Ke)}`)});else if(oe.type==="attributes"&&oe.target instanceof Element){let Ke=oe.target;if(Ke.tagName.toLowerCase()!=="iframe")continue;let Ne=oe.attributeName;(Ne==="src"||Ne==="srcdoc")&&E(`attr~ iframe ${Ne}=${Ne==="srcdoc"?`[${(Ke.getAttribute("srcdoc")??"").length}ch]`:on(Ke.getAttribute("src"))} dims=${Ce(Ke)}`)}}}),Un.observe(rn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let J=R=>{if(me()||hn)return;let oe=rn.querySelectorAll("iframe"),Ke=typeof document<"u"&&"hasStorageAccess"in document;E(`watchdog:${R} container=${Ce(rn)} children=${rn.childElementCount} iframes=${oe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${Ke} paypalNetRequests=${Mn.value}`),oe.forEach((Ne,Pt)=>{let Oe=(Ne.getAttribute("title")??"").slice(0,40);E(` iframe[${Pt}] ${Ce(Ne)}${Oe?` title="${Oe}"`:""} ${zt(Ne)}`);let $t=pr(Ne);$t&&E(` ${$t}`)}),jn.length===0&&E(" (no PayPal/zoid window errors captured)")};ut.push(setTimeout(()=>J("3s"),3e3)),ut.push(setTimeout(()=>J("8s"),8e3)),ut.push(setTimeout(()=>J("15s"),15e3))},xn(),E("render:start");let We=A.startTiming();bn=setTimeout(()=>{me()||hn||(E("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},Xl),ye.render(rn).then(()=>{if(E(`render:resolved inactive=${me()}`),V(),me()){Ot();return}hn=!0,_(!0),Pe(!1),Lt.current?.("ready"),A.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"checkout_render",durationMs:A.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(J=>{let R=J instanceof Error?J.message:"PayPal failed to render.";E(`render:rejected msg=${R.slice(0,120)}`),V(),p(R)})}).catch(d=>{let f=d instanceof Error?d.message:"PayPal SDK failed to load.";E(`loadScript:rejected msg=${f.slice(0,120)}`),p(f)})},0);return()=>{Kt=!0,clearTimeout(nt),gn&&clearTimeout(gn),V(),Ye.current===Y&&(Ye.current=null),Ot()}},[pe,ne,l,k,s,Be,Ze,e,ve,de,A,at,_e,E]);let dr=Xe?$a("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:D?"#fef2f2":"#f3f4f6",border:`1px solid ${D?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ke} failed=${D})`,en.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
3
|
${en.join(`
|
|
4
|
-
`)}`]}):null;return D&&!U?Xe?xr("div",{children:dr}):null:$a("div",{children:[dr,ie&&xr(Gr,{identity:ie.identity,methodLabel:ie.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:S,onCancel:()=>S(null)}),$a("div",{"aria-hidden":ce||ie?!0:void 0,style:ce||ie?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:oa},children:[!ke&&!ce&&xr("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),xr("div",{ref:Fe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:oa,display:"flex",opacity:ke?1:0},"aria-busy":Ee||he},de)]},de),ot&&xr("button",{ref:Le,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ln,style:Ql,children:"Try PayPal again"})]})}function aa(e){return xr(fs,{...e})}function gs(e){return xr(fs,{...e})}import{jsx as hs,jsxs as nc}from"react/jsx-runtime";function Zr({children:e,margin:t,icon:n=!0,styleOverride:r}){return nc("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&hs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:hs("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{resolveBillingApiUrl as rc}from"@flopay/shared";import{useEffect as hr,useMemo as oc,useRef as bs,useState as vs}from"react";import{jsx as ac}from"react/jsx-runtime";function ia({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=vs(e instanceof Promise?null:e),[s,k]=vs(t instanceof Promise||!t?null:t),g=bs(null),h=bs(null),b=Xr(r);hr(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),hr(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),hr(()=>{if(a)return jt(a)?.subscribe?.(b)},[b,a]),hr(()=>{if(!(!s||s===a))return jt(s)?.subscribe?.(b)},[b,a,s]),hr(()=>{if(!a)return;let u=jt(a);return g.current=u?.beginCheckout()??u?.now()??0,u?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{u?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),hr(()=>{let u=!1;return e instanceof Promise?e.then(I=>{u||l(I)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{u=!0}},[b,e]),hr(()=>{let u=!1;if(!t){k(null);return}return t instanceof Promise?t.then(I=>{u||k(I)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):k(t),()=>{u=!0}},[b,t]),hr(()=>{if(!a||h.current===a)return;h.current=a;let u=jt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(g.current??0),durationMode:"machine"})},[b,a]);let T=rc(n?.billingApiUrl),M=oc(()=>({flopay:a,paypalFlopay:s,billingApiUrl:T,emitInstrument:b}),[a,s,T,b]);return ac(Dn.Provider,{value:M,children:o})}var sa="flopay_recent_completion_";function Qr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(sa+e,JSON.stringify(t))}catch{}}function Ka(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(sa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(sa+e),!1):!0}catch{return!1}}import{loadFloPay as Ps,PaymentAPI as Ss}from"@flopay/js";import{classifyPaymentRejection as ic,FloPayError as Ct,isAuthorizationOnlySession as sc,isSetupIntentClientSecret as lc,normalizeCheckoutFailureOutcome as Cs}from"@flopay/shared";var Bo="card";async function cc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function dc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Va(e,t){return Object.assign(e,{checkoutMethod:t})}function ir(e,t){let n=e instanceof Ct?e:new Ct(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ao(e,t){try{return await e()}catch(n){throw ir(n,t)}}function ws(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function uc(e){return e.status==="succeeded"||e.status==="declined"}async function ks(e){if(typeof document>"u"||typeof window>"u")throw new Ct("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ct("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let h=new AbortController,b=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",b);let T=window.setTimeout(()=>h.abort(),r);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!M.ok)return{status:"unknown"};let u=await M.json().catch(()=>null);return pc(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(T),e.signal?.removeEventListener("abort",b)}},l=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let k=document.createElement("iframe");k.setAttribute("title","Card authentication"),k.setAttribute("allow","payment"),k.tabIndex=0,k.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),k.src=e.nextActionRedirectUrl,s.appendChild(k),document.body.appendChild(s),k.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let h=await new Promise((b,T)=>{let M=!1,u=0,I=0,he=0,j=!1,C=()=>{window.clearTimeout(u),window.clearInterval(I),window.clearTimeout(he),window.removeEventListener("message",ae),k.removeEventListener("load",Z),e.signal?.removeEventListener("abort",se)},pe=async()=>{if(!(M||j)){j=!0;try{let ve=await a();if(M||!uc(ve))return;M=!0,C(),b(ve)}finally{j=!1}}},Z=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{pe()},250)},se=()=>{M||(M=!0,C(),T(new Ct("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=ve=>{if(ve.source!==k.contentWindow||g&&ve.origin!==g)return;let et=ve.data;!et||typeof et!="object"||et.source!=="flopay-vault-3ds-return"||M||(M=!0,C(),b(null))};u=window.setTimeout(()=>{M||(M=!0,C(),T(new Ct("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),I=window.setInterval(()=>{pe()},n),k.addEventListener("load",Z),window.addEventListener("message",ae),e.signal?.addEventListener("abort",se),e.signal?.aborted&&se()});return h||await a()}finally{s.parentNode?.removeChild(s),l?.isConnected&&l.focus()}}function pc(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function br(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=yr(o)??o;return Va(new Ct(a,"api_error",{code:Cs(e?.outcome)??Cs(e?.type)??e?.gatewayErrorCode}),r)}function Ha(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function la(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Is(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||la(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||la(s)))return s;let l=o.gateways;if(l&&typeof l=="object"){let s=l.stripe;if(s&&typeof s=="object"){let k=s,g=[k.stripeClientSecret,k.clientSecret];for(let h of g)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||la(h)))return h}}}}async function mc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Is(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let s=(await new Ss(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(la(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function eo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let s=e.replace(/\/+$/,""),k=t??n.id,g=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,I=n.customer?.zip??n.accountData?.zip??void 0,j=await new Ss(s,l===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:k,nonce:g,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:b,firstName:T,lastName:M,country:u,zip:I},returnUrl:a??Ha(n)});if(j.ok){let Z=typeof j.json=="function"?await j.json().catch(()=>null):null;return sc(n)||Z?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Z?.paymentId=="string"?Z.paymentId:n.paymentId,sessionId:typeof Z?.sessionId=="string"?Z.sessionId:k,authorizationExpiresAt:typeof Z?.authorizationExpiresAt=="string"?Z.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Io(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Io(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let C;try{C=await j.json()}catch{throw new Ct("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status})}if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let Z=Is(C);if(!Z)throw new Ct("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status});return{type:C.type,threeDSecureToken:Z,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let Z=await mc({billingApiUrl:s,sessionId:k,nonce:g,responseJson:C});if(Z)return Z;throw Va(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let pe=new Ct(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:j.status});throw Object.assign(pe,{telemetryOutcome:ic(j.status,C)})}async function ca(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:k}){let g=t?.getRawProvider();if(!g)throw ir(new Ct("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Va(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=lc(e.threeDSecureToken),b=null,T=e.paymentMethodId,M=await Ao(()=>cc(g,e.threeDSecureToken,h),"card");if(M){if(M.error)throw ir(new Ct(M.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let I=M.intent;!T&&I?.payment_method&&(typeof I.payment_method=="string"?T=I.payment_method:"id"in I.payment_method&&(T=I.payment_method.id??void 0))}let u=T?await Ao(()=>dc(g,e.threeDSecureToken,{payment_method:T,return_url:s??Ha(l)??window.location.href},h),"card"):null;if(u){if(u.error)throw ir(new Ct(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");b=u.intent}else{let I=await Ao(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(I.error)throw ir(new Ct(I.error.message??"3DS authentication failed.","api_error",{code:I.error.code}),"card");b=(h?I.setupIntent:I.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let I=await eo({billingApiUrl:o,sessionId:a,session:l,telemetry:k,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:s});return I.type==="success"?{...I.result,paymentIntentId:I.result.paymentIntentId??b.id,paymentMethodId:I.result.paymentMethodId??T}:ca(I,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:k})}throw ir(new Ct("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw ir(new Ct("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:T}=await Ao(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(T)throw ir(new Ct(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Ao(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Ha(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw ir(new Ct(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ct("Unsupported payment redirect state.","api_error")}function Fo(e){if(e instanceof Ct){let r=yr(e.message);return r&&r!==e.message?Object.assign(new Ct(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=yr(t)??t;return new Ct(n,"api_error")}function da(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ct("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function ua({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[l,s]=await Promise.all([Ps(e,{billingApiUrl:n,locale:r,telemetry:o}),a?Ps(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(k=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",k),null)):Promise.resolve(null)]);return{flopay:l,paypalFlopay:t?a?s:l:null}}import{PaymentAPI as to,toStripeAppearance as yc}from"@flopay/js";import{COUNTRY_OPTIONS as fc,classifyPaymentRejection as gc,FloPayError as Yn,filterStripeMethodsByCountry as hc,getPostalCodeExample as bc,getPostalCodeLabel as Za,getStateFromPostalCode as _s,getStateLabel as Ya,getStateOptions as vc,getStripeMethodDisplayName as Fr,hasVendoredStripeMethodLogo as Pc,isAuthorizationOnlySession as Wa,isAVSFieldVisible as He,isPostalCodeSupported as Cc,isSetupIntentClientSecret as Sc,isValidEmail as Qt,isValidPostalCode as wc,needsStripeMethodExplicitConfirm as Ts,normalizeCheckoutFailureOutcome as kc,partitionStripeMethods as Ic,resolveAVSConfig as Ec,resolveButtonsLayoutTheme as Rc,resolveStripeMethodBrandVariant as _c,resolveTheme as Tc,stripeExpressMethodToOptionKey as xs}from"@flopay/shared";import{ExpressCheckoutElement as zs,PaymentElement as xc,Elements as Ar,useElements as ti,useStripe as ni}from"@stripe/react-stripe-js";import Mc,{useCallback as fe,useContext as no,useEffect as wt,useMemo as St,useRef as ge,useState as ue}from"react";function Es(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var Rs={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as Br,jsx as c,jsxs as xe}from"react/jsx-runtime";var tr="flopay_stripe_resume",Ms="flopay_wallet_resume",Us="fw1",Ac=300*1e3,Bc=900,Fc=25e3,Ga={};function qs(e){return e instanceof Yn&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ma(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new to(e).createSessionIntent(...n)}catch(o){throw qs(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Do="flopay_paypal_resume",Dc=250,As="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ri(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ya({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new to(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Lc(e){return e instanceof Yn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ja(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function $s({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Er(r?.name),a=Er(n);return Sn({email:(Qt(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:a.firstName??o.firstName,lastName:a.lastName??o.lastName})}async function Nc({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=$s({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return Qt(l.email)?l:a(o,l)}var Oc=`
|
|
4
|
+
`)}`]}):null;return D&&!U?Xe?xr("div",{children:dr}):null:$a("div",{children:[dr,ie&&xr(Gr,{identity:ie.identity,methodLabel:ie.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:S,onCancel:()=>S(null)}),$a("div",{"aria-hidden":ce||ie?!0:void 0,style:ce||ie?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:oa},children:[!ke&&!ce&&xr("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),xr("div",{ref:Fe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:oa,display:"flex",opacity:ke?1:0},"aria-busy":Ee||he},de)]},de),ot&&xr("button",{ref:Le,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ln,style:Ql,children:"Try PayPal again"})]})}function aa(e){return xr(fs,{...e})}function gs(e){return xr(fs,{...e})}import{jsx as hs,jsxs as nc}from"react/jsx-runtime";function Zr({children:e,margin:t,icon:n=!0,styleOverride:r}){return nc("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&hs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:hs("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{resolveBillingApiUrl as rc}from"@flopay/shared";import{useEffect as hr,useMemo as oc,useRef as bs,useState as vs}from"react";import{jsx as ac}from"react/jsx-runtime";function ia({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=vs(e instanceof Promise?null:e),[s,k]=vs(t instanceof Promise||!t?null:t),g=bs(null),h=bs(null),b=Xr(r);hr(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),hr(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),hr(()=>{if(a)return jt(a)?.subscribe?.(b)},[b,a]),hr(()=>{if(!(!s||s===a))return jt(s)?.subscribe?.(b)},[b,a,s]),hr(()=>{if(!a)return;let u=jt(a);return g.current=u?.beginCheckout()??u?.now()??0,u?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{u?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),hr(()=>{let u=!1;return e instanceof Promise?e.then(I=>{u||l(I)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{u=!0}},[b,e]),hr(()=>{let u=!1;if(!t){k(null);return}return t instanceof Promise?t.then(I=>{u||k(I)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):k(t),()=>{u=!0}},[b,t]),hr(()=>{if(!a||h.current===a)return;h.current=a;let u=jt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(g.current??0),durationMode:"machine"})},[b,a]);let T=rc(n?.billingApiUrl),M=oc(()=>({flopay:a,paypalFlopay:s,billingApiUrl:T,emitInstrument:b}),[a,s,T,b]);return ac(Dn.Provider,{value:M,children:o})}var sa="flopay_recent_completion_";function Qr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(sa+e,JSON.stringify(t))}catch{}}function Ka(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(sa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(sa+e),!1):!0}catch{return!1}}import{loadFloPay as Ps,PaymentAPI as Ss}from"@flopay/js";import{classifyPaymentRejection as ic,FloPayError as Ct,isAuthorizationOnlySession as sc,isSetupIntentClientSecret as lc,normalizeCheckoutFailureOutcome as Cs}from"@flopay/shared";var Bo="card";async function cc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function dc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Va(e,t){return Object.assign(e,{checkoutMethod:t})}function ir(e,t){let n=e instanceof Ct?e:new Ct(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ao(e,t){try{return await e()}catch(n){throw ir(n,t)}}function ws(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function uc(e){return e.status==="succeeded"||e.status==="declined"}async function ks(e){if(typeof document>"u"||typeof window>"u")throw new Ct("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ct("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let h=new AbortController,b=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",b);let T=window.setTimeout(()=>h.abort(),r);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!M.ok)return{status:"unknown"};let u=await M.json().catch(()=>null);return pc(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(T),e.signal?.removeEventListener("abort",b)}},l=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let k=document.createElement("iframe");k.setAttribute("title","Card authentication"),k.setAttribute("allow","payment"),k.tabIndex=0,k.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),k.src=e.nextActionRedirectUrl,s.appendChild(k),document.body.appendChild(s),k.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let h=await new Promise((b,T)=>{let M=!1,u=0,I=0,he=0,j=!1,C=()=>{window.clearTimeout(u),window.clearInterval(I),window.clearTimeout(he),window.removeEventListener("message",ae),k.removeEventListener("load",Z),e.signal?.removeEventListener("abort",se)},pe=async()=>{if(!(M||j)){j=!0;try{let ve=await a();if(M||!uc(ve))return;M=!0,C(),b(ve)}finally{j=!1}}},Z=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{pe()},250)},se=()=>{M||(M=!0,C(),T(new Ct("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=ve=>{if(ve.source!==k.contentWindow||g&&ve.origin!==g)return;let et=ve.data;!et||typeof et!="object"||et.source!=="flopay-vault-3ds-return"||M||(M=!0,C(),b(null))};u=window.setTimeout(()=>{M||(M=!0,C(),T(new Ct("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),I=window.setInterval(()=>{pe()},n),k.addEventListener("load",Z),window.addEventListener("message",ae),e.signal?.addEventListener("abort",se),e.signal?.aborted&&se()});return h||await a()}finally{s.parentNode?.removeChild(s),l?.isConnected&&l.focus()}}function pc(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function br(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=yr(o)??o;return Va(new Ct(a,"api_error",{code:Cs(e?.outcome)??Cs(e?.type)??e?.gatewayErrorCode}),r)}function Ha(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function la(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Is(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||la(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||la(s)))return s;let l=o.gateways;if(l&&typeof l=="object"){let s=l.stripe;if(s&&typeof s=="object"){let k=s,g=[k.stripeClientSecret,k.clientSecret];for(let h of g)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||la(h)))return h}}}}async function mc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Is(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let s=(await new Ss(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(la(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function eo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let s=e.replace(/\/+$/,""),k=t??n.id,g=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,I=n.customer?.zip??n.accountData?.zip??void 0,j=await new Ss(s,l===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:k,nonce:g,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:b,firstName:T,lastName:M,country:u,zip:I},returnUrl:a??Ha(n)});if(j.ok){let Z=typeof j.json=="function"?await j.json().catch(()=>null):null;return sc(n)||Z?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Z?.paymentId=="string"?Z.paymentId:n.paymentId,sessionId:typeof Z?.sessionId=="string"?Z.sessionId:k,authorizationExpiresAt:typeof Z?.authorizationExpiresAt=="string"?Z.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Io(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Io(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let C;try{C=await j.json()}catch{throw new Ct("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status})}if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let Z=Is(C);if(!Z)throw new Ct("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status});return{type:C.type,threeDSecureToken:Z,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let Z=await mc({billingApiUrl:s,sessionId:k,nonce:g,responseJson:C});if(Z)return Z;throw Va(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let pe=new Ct(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:j.status});throw Object.assign(pe,{telemetryOutcome:ic(j.status,C)})}async function ca(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:k}){let g=t?.getRawProvider();if(!g)throw ir(new Ct("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Va(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=lc(e.threeDSecureToken),b=null,T=e.paymentMethodId,M=await Ao(()=>cc(g,e.threeDSecureToken,h),"card");if(M){if(M.error)throw ir(new Ct(M.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let I=M.intent;!T&&I?.payment_method&&(typeof I.payment_method=="string"?T=I.payment_method:"id"in I.payment_method&&(T=I.payment_method.id??void 0))}let u=T?await Ao(()=>dc(g,e.threeDSecureToken,{payment_method:T,return_url:s??Ha(l)??window.location.href},h),"card"):null;if(u){if(u.error)throw ir(new Ct(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");b=u.intent}else{let I=await Ao(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(I.error)throw ir(new Ct(I.error.message??"3DS authentication failed.","api_error",{code:I.error.code}),"card");b=(h?I.setupIntent:I.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let I=await eo({billingApiUrl:o,sessionId:a,session:l,telemetry:k,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:s});return I.type==="success"?{...I.result,paymentIntentId:I.result.paymentIntentId??b.id,paymentMethodId:I.result.paymentMethodId??T}:ca(I,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:k})}throw ir(new Ct("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw ir(new Ct("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:T}=await Ao(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(T)throw ir(new Ct(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Ao(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Ha(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw ir(new Ct(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ct("Unsupported payment redirect state.","api_error")}function Fo(e){if(e instanceof Ct){let r=yr(e.message);return r&&r!==e.message?Object.assign(new Ct(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=yr(t)??t;return new Ct(n,"api_error")}function da(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ct("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function ua({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[l,s]=await Promise.all([Ps(e,{billingApiUrl:n,locale:r,telemetry:o}),a?Ps(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(k=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",k),null)):Promise.resolve(null)]);return{flopay:l,paypalFlopay:t?a?s:l:null}}import{PaymentAPI as to,toStripeAppearance as yc}from"@flopay/js";import{COUNTRY_OPTIONS as fc,classifyPaymentRejection as gc,FloPayError as Yn,filterStripeMethodsByCountry as hc,getPostalCodeExample as bc,getPostalCodeLabel as Za,getStateFromPostalCode as _s,getStateLabel as Ya,getStateOptions as vc,getStripeMethodDisplayName as Fr,hasVendoredStripeMethodLogo as Pc,isAuthorizationOnlySession as Wa,isAVSFieldVisible as He,isPostalCodeSupported as Cc,isSetupIntentClientSecret as Sc,isValidEmail as Qt,isValidPostalCode as wc,needsStripeMethodExplicitConfirm as Ts,normalizeCheckoutFailureOutcome as kc,partitionStripeMethods as Ic,resolveAVSConfig as Ec,resolveButtonsLayoutTheme as Rc,resolveStripeMethodBrandVariant as _c,resolveTheme as Tc,stripeExpressMethodToOptionKey as xs}from"@flopay/shared";import{ExpressCheckoutElement as zs,PaymentElement as xc,Elements as Ar,useElements as ti,useStripe as ni}from"@stripe/react-stripe-js";import Mc,{useCallback as ge,useContext as no,useEffect as wt,useMemo as St,useRef as fe,useState as ue}from"react";function Es(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var Rs={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as Br,jsx as c,jsxs as xe}from"react/jsx-runtime";var tr="flopay_stripe_resume",Ms="flopay_wallet_resume",Us="fw1",Ac=300*1e3,Bc=900,Fc=25e3,Ga={};function qs(e){return e instanceof Yn&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ma(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new to(e).createSessionIntent(...n)}catch(o){throw qs(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Do="flopay_paypal_resume",Dc=250,As="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ri(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ya({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new to(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Lc(e){return e instanceof Yn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ja(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function $s({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Er(r?.name),a=Er(n);return Sn({email:(Qt(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:a.firstName??o.firstName,lastName:a.lastName??o.lastName})}async function Nc({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=$s({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return Qt(l.email)?l:a(o,l)}var Oc=`
|
|
5
5
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
6
6
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
7
7
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -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=fe(0),n=fe(null),r=fe(null),o=ge((u=r.current)=>{let I=u;I?.timer&&(clearTimeout(I.timer),I.timer=null)},[]),a=ge((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=ge(u=>{u.yieldedControl&&a(u,600)},[a]),s=ge(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=ge(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=ge(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=ge(u=>n.current===(u??t.current),[]),b=ge(u=>r.current?.generation===u&&n.current!==u,[]),T=ge(()=>{let u=r.current;u&&l(u)},[l]),M=ge(()=>{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=fe(!1),Me=fe(null),Ae=fe(null),[ee,Q]=ue(0),[A,Fe]=ue(!1),De=fe(!1),Le=fe(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=ge(()=>{Q(H=>H+1)},[]),K=ge((H,D,B)=>{_(B),g?.("paypal",H,{code:D,popupBlocked:fr(H)}),Fe(!0),de()},[_,g,de]),Ie=ge(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);wt(()=>{De.current&&(De.current=!1,Ie())},[Ie,ee]);let ot=ge(()=>{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=ge(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=ge(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=fe(!Qt(n?.trim())||!T?.trim()).current,{request:be,collect:Dt,finish:Xe}=Wr(),Me=fe(null),Ae=fe(null),[ee,Q]=ue(0),[A,Fe]=ue(!1),[De,Le]=ue("google_pay"),Ue=fe(!1),ke=fe("google_pay"),_=fe("google_pay"),ce=fe(null),Pe=fe(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=ge(()=>{Q(S=>S+1)},[]),D=ge((S,v,_e,ne)=>{Ie(ne),h?.(S,v,{code:_e,popupBlocked:fr(v)}),Le(S),Fe(!0),H()},[Ie,h,H]),B=ge(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);wt(()=>{Ue.current&&(Ue.current=!1,B())},[B,ee]);let Ee=ge(()=>{Fe(!1),s?.(null),B()},[B,s]),Ve=ge(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=fe(!1),[be,Dt]=ue(!1),[Xe,Me]=ue("loading"),[Ae,ee]=ue(""),Q=!Qt(r?.trim()),A=!Q||Qt(Ae.trim()),Fe=ge(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=fe(!1),{request:Ae,collect:ee,finish:Q}=Wr();wt(()=>{l.length>0&&s?u?.("ready"):s||u?.("loading")},[l.length,s,u]);let A=ge(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=ge(_=>{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=fe(ce??""),Gt=fe(_??"US"),kn=fe(Pe??""),yn=fe(de??""),_n=fe(K??""),ln=fe(Ie??""),Tn=fe(""),qt=fe({});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=fe(!1),Un=fe({email:!1,line1:!1,city:!1,state:!1,zip:!1}),qn=fe(!1),ut=ge(i=>{Un.current[i]=!0,qn.current=!0},[]),bn=ge(i=>!rn.current&&Un.current[i],[]),vn=ge(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=ge(()=>{Ze?.({class:"card_surface",provider:mr})},[mr,Ze]),Mn=fe(null),Ut=ge(i=>{Mn.current&&clearTimeout(Mn.current),Mn.current=setTimeout(()=>{Mn.current=null,i()},Mr)},[]);wt(()=>()=>{Mn.current&&clearTimeout(Mn.current)},[]);let x=ge(()=>{En(),w(e??null),Kt(i=>i+1),on("expanding"),Ut(()=>on("card"))},[Ut,En,e]),L=ge(()=>{on("collapsing"),Ut(()=>on("buttons"))},[Ut]),V=ge(i=>{pr(i),on("apm-expanding"),Ut(()=>on("apm-form"))},[Ut]),Y=ge(()=>{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=fe(!1),p=fe(null),O=fe("idle"),[$,gt]=ue(null),vt=fe($);wt(()=>{vt.current=$},[$]);let te=n||en,we=fe(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=fe(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=ge(i=>{Tt(i),I?.(i)},[I]),va=fe(""),[wi,rl]=ue(!1),Pa=ge(()=>{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=ge((i,y,N)=>{s?.(Ht(i,y,N))},[s]),Or=ge((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=fe({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=fe(!1),ki=ge(()=>{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=fe(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=fe(!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=fe(!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=ge((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=ge(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=ge(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=ge((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=fe(!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=ge(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.
|
|
3
|
+
"version": "1.8.14",
|
|
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.
|
|
38
|
-
"@flopay/shared": "1.8.
|
|
37
|
+
"@flopay/js": "1.8.14",
|
|
38
|
+
"@flopay/shared": "1.8.14"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"react": ">=18.0.0",
|