@flopay/react 1.4.4 → 1.4.5
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/README.md +8 -3
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -487,9 +487,14 @@ best-effort **in parallel** with the widget's charge:
|
|
|
487
487
|
with the parsed `FloPayError`, and the processing overlay clears so the buyer can
|
|
488
488
|
correct and retry. The charge cannot be cancelled once submitted, so this surfaces
|
|
489
489
|
for the buyer's *next* attempt rather than stopping the in-flight one.
|
|
490
|
-
- **Transient failure (`5xx` / network)** → best-effort and silent: the
|
|
491
|
-
listener falls back to the session's baseline address while the
|
|
492
|
-
the charge.
|
|
490
|
+
- **Transient failure (`5xx` / network)** → best-effort and buyer-silent: the
|
|
491
|
+
backend listener falls back to the session's baseline address while the
|
|
492
|
+
widget completes the charge.
|
|
493
|
+
- **Internal 10-second timeout** → the same functional fallback applies, and
|
|
494
|
+
successful widget completion still reaches `onComplete`. Telemetry records
|
|
495
|
+
the privacy-safe lifecycle event `operation.fallback` with
|
|
496
|
+
`processing` / `account_snapshot` / `timeout` dimensions instead of an
|
|
497
|
+
alert-level technical error. Direct and blocking timeout paths remain errors.
|
|
493
498
|
|
|
494
499
|
### Vault PCI card form
|
|
495
500
|
|
package/dist/index.cjs
CHANGED
|
@@ -27,7 +27,7 @@ ${et.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
|
-
`,Hr=44;function So(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 Ni={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ta={width:"100%",minHeight:Hr,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 Oi(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function wa(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ba(e){return e==="paypal"?"PayPal":(0,k.getStripeMethodDisplayName)(e)}function zi(e,t){let n=`We couldn't open ${Ba(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ma(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((d=l.current)=>{let g=d;g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),s=(0,r.useCallback)((d,g)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(d),d.timer=setTimeout(()=>{d.timer=null,l.current?.generation===d.generation&&(l.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},g))},[o,e]),u=(0,r.useCallback)(d=>{d.yieldedControl&&s(d,600)},[s]),c=(0,r.useCallback)(d=>{o();let g=t.current+1;t.current=g,n.current=null;let I={generation:g,method:d,timer:null,yieldedControl:!1};return l.current=I,g},[o]),R=(0,r.useCallback)(d=>{let g=l.current;return typeof d=="number"&&g?.generation!==d?!1:(o(g),l.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),L=(0,r.useCallback)(d=>{let g=l.current,I=d??g?.generation??t.current;(!d||g?.generation===d)&&(o(g),l.current=null),n.current=I},[o]),m=(0,r.useCallback)(d=>n.current===(d??t.current),[]),_=(0,r.useCallback)(d=>l.current?.generation===d&&n.current!==d,[]),w=(0,r.useCallback)(()=>{let d=l.current;d&&u(d)},[u]),B=(0,r.useCallback)(()=>{let d=l.current;d&&(d.yieldedControl=!0,o(d))},[o]);return(0,r.useEffect)(()=>{let d=()=>{document.visibilityState==="visible"?w():B()},g=()=>{B()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",g),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",g),window.removeEventListener("focus",w),o()}},[o,B,w]),{startAttempt:c,finishAttempt:R,invalidateAttempt:L,isAttemptInvalidated:m,isAttemptCurrent:_}}function Ui(e){let t=(0,k.getPostalCodeExample)(e);return`Enter a valid ${(0,k.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function $i(e,t,n){let l=(0,k.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,u=s&&!o,c=s&&!!o&&!(0,k.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:u,malformed:c}}function ka(e,t){return t instanceof At.FloPayError?t:new At.FloPayError(t instanceof Error?t.message:`${Oi(e)} before-click hook failed.`,"validation_error")}function vo(){return(0,i.jsx)("style",{children:Li})}function qi(e){return typeof e=="number"?`${e}px`:e}function Ra(e){if(typeof e=="number"||typeof e=="string")return e}function Aa(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function Fa({state:e,placeholderTestId:t,borderRadius:n=8,children:l}){return e==="unavailable"||e==="load_error"?null:(0,i.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,i.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,i.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:l})]})}function Ia(e){return e!=="unavailable"&&e!=="load_error"}function Wr(e){return(0,i.jsx)(Vi,{...e})}function Ea({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:u=!1,onButtonClick:c,onDecline:R,onTechnicalFailure:L,runBeforeButtonClick:m,onLoadStateChange:_,placeholderBorderRadius:w}){let B=on(),d=(0,ut.useStripe)(),g=(0,ut.useElements)(),[I,A]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(I)},[I,_]);let[P,H]=(0,r.useState)(!1),Q=(0,r.useRef)(!1),me=(0,r.useRef)(null),se=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[K,ye]=(0,r.useState)(!1),W=(0,r.useRef)(!1),Y=(0,r.useRef)(new Map),{startAttempt:le,finishAttempt:Fe,invalidateAttempt:he,isAttemptInvalidated:ge,isAttemptCurrent:ne}=Ma((E,oe,de)=>{L?.(E,oe,{...de,popupBlocked:de?.popupBlocked??Dn(oe)}),ye(!0),te(Ue=>Ue+1)});(0,r.useEffect)(()=>{K&&se.current?.focus()},[K,z]);let fe=(0,r.useCallback)(()=>{te(E=>E+1)},[]),ve=(0,r.useCallback)((E,oe,de)=>{he(de),L?.("paypal",E,{code:oe,popupBlocked:Dn(E)}),ye(!0),fe()},[he,L,fe]),ce=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{W.current&&(W.current=!1,ce())},[ce,z]);let Ne=(0,r.useCallback)(()=>{ye(!1),s?.(null),ce()},[ce,s]);(0,r.useEffect)(()=>{if(!d||Q.current)return;let E=new URLSearchParams(window.location.search),oe=E.get("payment_intent"),de=E.get("payment_intent_client_secret"),Ue=E.get("redirect_status");if(!oe||!de)return;Q.current=!0;let Oe;try{let M=localStorage.getItem(br);if(M){let G=JSON.parse(M);G.clientSecret===de&&(Oe={...G.accountPatch?{accountPatch:G.accountPatch}:{},...G.sessionId?{sessionId:G.sessionId}:{},...G.nonce?{nonce:G.nonce}:{}})}}catch{}try{localStorage.removeItem(br)}catch{}let ee=new URL(window.location.href);ee.searchParams.delete("payment_intent"),ee.searchParams.delete("payment_intent_client_secret"),ee.searchParams.delete("redirect_status"),window.history.replaceState({},"",ee.toString()),(async()=>{try{if(H(!0),Ue==="failed"){let ue="PayPal payment was declined. Please try again.";s?.(ue),R?.(Tt("paypal",ue));return}let{paymentIntent:M,error:G}=await d.retrievePaymentIntent(de);if(G){s?.(G.message??"Failed to retrieve PayPal payment status.");return}if(M&&(M.status==="requires_capture"||M.status==="succeeded")){let ue=typeof M.payment_method=="string"?M.payment_method:M.payment_method?.id;o({id:ue??M.id,type:"card",threeDSecureActionResultTokenId:M.id,isPaypal:!0},Oe)}else{let ue="PayPal payment was not completed. Please try again.";s?.(ue),R?.(Tt("paypal",ue))}}catch(M){s?.(M instanceof Error?M.message:"Failed to complete PayPal payment.")}finally{H(!1)}})()},[d,o,s,R]);let Ie=(0,r.useCallback)(async E=>{if(u||P){E.reject();return}let oe=m?await m("paypal"):{proceed:!0};if(!oe.proceed){Y.current.delete(z),E.reject();return}let de=le("paypal");Y.current.set(z,{generation:de,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),ye(!1),c?.("paypal"),E.resolve()},[Y,u,c,m,le,P,z]),we=(0,r.useCallback)(async E=>{if(!d||!g)return;let oe=Y.current.get(z);if(oe&&!ne(oe.generation)){Y.current.delete(z);return}if(!oe&&ge()||oe&&!Fe(oe.generation))return;oe||Fe();let de=oe??null;if(Y.current.delete(z),!de&&m){let M=await m("paypal");if(!M.proceed){E.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}}let Ue=de?.sessionId??e,Oe=de?.nonce??t,ee=de?.accountPatch?.email??n;try{if(H(!0),s?.(null),!Ue||!ee)throw new Error("Missing sessionId or email for PayPal payment");let M=d.createPaymentMethod,{error:G,paymentMethod:ue}=await M({type:"paypal"});if(G){ve(G,"stripe_paypal_create_payment_method_failed",oe?.generation),E.paymentFailed({reason:"fail"});return}let Ee=await new Bn.PaymentAPI(l).createSessionIntent(Ue,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ue?.id??null,intentKind:"payment"});if(Ee.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let gt=Ee.clientSecret,et={return_url:window.location.href};if(ue?.id&&(et.payment_method=ue.id),typeof window<"u")try{localStorage.setItem(br,JSON.stringify({clientSecret:gt,sessionId:Ue,nonce:Oe,accountPatch:de?.accountPatch}))}catch{}let{error:Qe,paymentIntent:y}=await d.confirmPayment({clientSecret:gt,confirmParams:et,redirect:"if_required"});if(Qe){if(typeof window<"u")try{localStorage.removeItem(br)}catch{}if(hr(Qe)){let $e=Qe.message??"Your payment was declined.";s?.($e),R?.(Tt("paypal",$e,{code:xn(Qe),declineCode:er(Qe)})),await Kr({billingApiUrl:l,sessionId:Ue,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:xn(Qe)??"provider_declined"}})}else ve(Qe,"stripe_paypal_confirm_failed",oe?.generation);return}if(typeof window<"u")try{localStorage.removeItem(br)}catch{}let je=typeof y?.payment_method=="string"?y.payment_method:y?.payment_method?.id;o({id:je??y?.id,type:"card",threeDSecureActionResultTokenId:y?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:Ue,nonce:Oe});return}catch(M){ve(M,"stripe_paypal_failed",oe?.generation)}finally{H(!1)}},[d,g,e,t,n,l,o,s,R,m,ve,Fe,ne,ge,z]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Fa,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[K&&(0,i.jsx)("button",{ref:se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ne,style:Ta,children:"Try PayPal again"}),(0,i.jsx)(ut.ExpressCheckoutElement,{onReady:E=>A(Aa(E,["paypal"])),onLoadError:()=>A("load_error"),onClick:Ie,onConfirm:we,onCancel:()=>{let E=Y.current.get(z);Y.current.delete(z),Mt(B)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he(E?.generation),ye(!1),W.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},z)]})}),P&&(0,i.jsx)(bn,{status:"processing"})]})}function _a({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:u,onErrorChange:c,onButtonClick:R,onDecline:L,onTechnicalFailure:m,runBeforeButtonClick:_,onLoadStateChange:w,placeholderBorderRadius:B}){let d=on(),g=(0,ut.useStripe)(),I=(0,ut.useElements)(),[A,P]=(0,r.useState)("loading");(0,r.useEffect)(()=>{w?.(A)},[A,w]);let[H,Q]=(0,r.useState)(!1),me=(0,r.useRef)(null),se=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[K,ye]=(0,r.useState)(!1),[W,Y]=(0,r.useState)("google_pay"),le=(0,r.useRef)(!1),Fe=(0,r.useRef)("google_pay"),he=(0,r.useRef)("google_pay"),ge=(0,r.useRef)(new Map),{startAttempt:ne,finishAttempt:fe,invalidateAttempt:ve,isAttemptInvalidated:ce,isAttemptCurrent:Ne}=Ma((ee,M,G)=>{m?.(ee,M,{...G,popupBlocked:G?.popupBlocked??Dn(M)}),Y(ee),ye(!0),te(ue=>ue+1)});(0,r.useEffect)(()=>{K&&se.current?.focus()},[K,z]);let Ie=(0,r.useCallback)(()=>{te(ee=>ee+1)},[]),we=(0,r.useCallback)((ee,M,G,ue)=>{ve(ue),m?.(ee,M,{code:G,popupBlocked:Dn(M)}),Y(ee),ye(!0),Ie()},[ve,m,Ie]),E=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{le.current&&(le.current=!1,E())},[E,z]);let oe=(0,r.useCallback)(()=>{ye(!1),c?.(null),E()},[E,c]),de=(0,r.useCallback)(async ee=>{if(!g||!I)return;let M=ge.current.get(z);if(M&&!Ne(M.generation)){ge.current.delete(z);return}if(!M&&ce()||M&&!fe(M.generation))return;M||fe();let G=ee.expressPaymentType??M?.method??Fe.current,ue=M??null;ge.current.delete(z);let Ee=wa(G);if(!ue&&_){let je=await _(Ee);if(!je.proceed){ee.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ue={accountPatch:je.accountPatch,sessionId:je.sessionId,nonce:je.nonce}}let gt=Ee,et=ue?.sessionId??e,Qe=ue?.nonce??t,y=ue?.accountPatch?.email??n;try{Q(!0),c?.(null);let{error:je}=await I.submit();if(je){we(G,je,"stripe_wallet_submit_failed",M?.generation);return}let{error:$e,paymentMethod:He}=await g.createPaymentMethod({elements:I});if($e||!He){we(G,$e??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",M?.generation);return}if(!et||!y)throw new Error("Missing sessionId or email for wallet payment");let Ke=await new Bn.PaymentAPI(l).createSessionIntent(et,Qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:G??Ee,paymentMethodId:He.id,intentKind:o});if(Ke.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Wt=Ke.clientSecret,{error:bt,intentId:kt}=(0,At.isSetupIntentClientSecret)(Wt)?await g.confirmCardSetup(Wt,{payment_method:He.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await g.confirmCardPayment(Wt,{payment_method:He.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(bt){if(hr(bt)){let h=bt.message??"Your payment was declined.";c?.(h),L?.(Tt(gt,h,{code:xn(bt),declineCode:er(bt)})),await Kr({billingApiUrl:l,sessionId:et,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:G??Ee,providerDeclineReason:xn(bt)??"provider_declined"}})}else we(G,bt,"stripe_wallet_confirm_failed",M?.generation);return}u({id:He.id,type:"card",threeDSecureActionResultTokenId:kt},{accountPatch:ue?.accountPatch,sessionId:et,nonce:Qe})}catch(je){we(G,je,"stripe_wallet_failed",M?.generation)}finally{Q(!1)}},[g,I,e,t,n,l,o,u,c,L,_,we,fe,Ne,ce,z]),Ue=(0,r.useMemo)(()=>{let ee=["applePay","googlePay","paypal","link","amazonPay","klarna"],M=new Set(["applePay","googlePay"]),G=new Set(s.map(k.stripeExpressMethodToOptionKey)),ue={};for(let Ee of ee)G.has(Ee)?ue[Ee]=M.has(Ee)?"always":"auto":ue[Ee]="never";return ue},[s]),Oe=(0,r.useMemo)(()=>s.map(k.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Fa,{state:A,placeholderTestId:"flopay-wallet-placeholder",borderRadius:B,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[K&&(0,i.jsxs)("button",{ref:se,type:"button","data-testid":"flopay-wallet-retry-button",onClick:oe,style:Ta,children:["Try ",Ba(W)," again"]}),(0,i.jsx)(ut.ExpressCheckoutElement,{onReady:ee=>{P(Aa(ee,Oe))},onLoadError:ee=>{P("load_error"),Mt(d)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk"})},onClick:async ee=>{Fe.current=ee.expressPaymentType,he.current=wa(ee.expressPaymentType);let M=_?await _(he.current):{proceed:!0};if(!M.proceed){ge.current.delete(z),ee.reject();return}let G=ne(ee.expressPaymentType);ge.current.set(z,{generation:G,method:ee.expressPaymentType,accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}),ye(!1),R?.(he.current),ee.resolve()},onConfirm:de,onCancel:()=>{let ee=ge.current.get(z);ge.current.delete(z),Mt(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ve(ee?.generation),ye(!1),le.current=!0,Ie()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ue,layout:{maxColumns:1,overflow:"never"}}},z)]})}),H&&(0,i.jsx)(bn,{status:"processing"})]})}function ji({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:u,backgroundColor:c,borderColor:R,textColor:L,borderRadius:m,fontFamily:_}){let w=(0,k.resolveStripeMethodBrandVariant)(e,t),B=sa[e],d=w?.backgroundColor??c??"#ffffff",g=w?.borderColor??R??"#d1d5db",I=w?.textColor??L??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&u()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Hr,padding:"0 1rem",backgroundColor:d,color:I,border:`1px solid ${g}`,borderRadius:m??8,fontSize:"0.95rem",fontWeight:600,fontFamily:_,cursor:n||l?"not-allowed":"pointer",opacity:l&&!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,i.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,k.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,k.hasVendoredStripeMethodLogo)(e)?8:0},children:[B?(0,i.jsx)("img",{src:B,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):w?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:w.logoSvg}}):null,(0,i.jsx)("span",{children:(0,k.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:I,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,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Co({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:u,onErrorChange:c,onDecline:R,onCancel:L,runBeforeButtonClick:m,onButtonClick:_,isProcessing:w,submitButtonColor:B,submitButtonBorderRadius:d,submitButtonStyle:g,errorText:I}){let A=on(),P=(0,ut.useStripe)(),H=(0,ut.useElements)(),[Q,me]=(0,r.useState)(!1),se=(0,r.useRef)(!1),[z,te]=(0,r.useState)(!1),[K,ye]=(0,r.useState)("loading"),W=(0,r.useCallback)(async()=>{if(!P||!H||w||se.current||!z)return;se.current=!0,me(!0);let Y=m?await m("card"):{proceed:!0};if(!Y.proceed){se.current=!1,me(!1);return}_?.("card");let le=Y.sessionId??t,Fe=Y.nonce??n,he=Y.accountPatch?.email??l;try{c?.(null);let ge=await H.submit();if(ge.error){c?.(ge.error.message??"Payment failed.");return}let ne=await P.createPaymentMethod({elements:H});if(ne.error||!ne.paymentMethod){c?.(ne.error?.message??"Failed to create payment method.");return}let fe=ne.paymentMethod;if(!le||!he)throw new Error("Missing sessionId or email for payment.");let ve=fe.type||e,ce=await new Bn.PaymentAPI(s).createSessionIntent(le,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ve,paymentMethodId:null,intentKind:"payment"});if(ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ne=ce.clientSecret;if(typeof window<"u")try{localStorage.setItem(vn,JSON.stringify({clientSecret:Ne,sessionId:le,nonce:Fe,accountPatch:Y.accountPatch,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"}))}catch{}let{error:Ie,paymentIntent:we}=await P.confirmPayment({clientSecret:Ne,confirmParams:{return_url:window.location.href,payment_method:fe.id},redirect:"if_required"});if(Ie){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let de=Ie.message??"Payment failed.";c?.(de),R?.(Tt("card",de,{code:Ie.code})),await Kr({billingApiUrl:s,sessionId:le,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ie.code??"provider_declined"}});return}let E=we?.status;if(!zr(E)){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let de=E==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";c?.(de),R?.(Tt("card",de,{code:E??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let oe=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;u({id:oe??fe.id,type:"card",threeDSecureActionResultTokenId:we?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:Y.accountPatch,sessionId:le,nonce:Fe})}catch(ge){c?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{se.current=!1,me(!1)}},[P,H,w,z,m,_,t,n,l,s,e,u,c,R]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(ut.PaymentElement,{onReady:()=>ye("ready"),onLoadError:()=>{ye("load_error"),Mt(A)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"apm",requestCategory:"provider_sdk"})},onChange:Y=>{te(!!Y.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...l?{email:l}:{}}}}}),(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{W()},disabled:!z||Q||w||K!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!z||Q||w||K!=="ready"?"not-allowed":"pointer",opacity:!z||Q||w||K!=="ready"?.5:1,transition:"opacity 120ms ease-out",...g??{}},children:Q?"Processing\u2026":`Pay with ${(0,k.getStripeMethodDisplayName)(e)}`}),I&&(0,i.jsx)(Xn,{margin:"0.75rem 0 0",children:I})]})}function xa({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:u,paymentElementBaseOptions:c,onTokenizedBody:R,onErrorChange:L,onButtonClick:m,onDecline:_,runBeforeButtonClick:w,onLoadStateChange:B,isProcessing:d=!1,submitButtonColor:g="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:A,buttonAppearance:P,themeId:H,onExpandApm:Q,expandedApmMethod:me}){let[se,z]=(0,r.useState)(null),[te,K]=(0,r.useState)(null),ye=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&u?B?.("ready"):u||B?.("loading")},[s.length,u,B]);let W=(0,r.useCallback)(async ne=>{if(!u||ye.current||d)return;ye.current=!0,K(ne);let fe=w?await w("card"):{proceed:!0};if(!fe.proceed){ye.current=!1,K(null);return}m?.("card");let ve=fe.sessionId??e,ce=fe.nonce??t,Ne=fe.accountPatch?.email??n;try{if(L?.(null),!ve||!Ne)throw new Error("Missing sessionId or email for payment.");let Ie=await new Bn.PaymentAPI(o).createSessionIntent(ve,ce??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(Ie.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let we=Ie.clientSecret;if(typeof window<"u")try{localStorage.setItem(vn,JSON.stringify({clientSecret:we,sessionId:ve,nonce:ce,accountPatch:fe.accountPatch,paymentMethodType:ne,gateway:"stripe"}))}catch{}let{error:E,paymentIntent:oe}=await u.confirmPayment({clientSecret:we,confirmParams:{return_url:window.location.href,payment_method_data:{type:ne,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...Ne?{email:Ne}:{}}}},redirect:"if_required"});if(E){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Oe=E.message??"Payment failed.";L?.(Oe),_?.(Tt("card",Oe,{code:E.code})),await Kr({billingApiUrl:o,sessionId:ve,nonce:ce,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:E.code??"provider_declined"}});return}let de=oe?.status;if(!zr(de)){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Oe=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";L?.(Oe),_?.(Tt("card",Oe,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Ue=typeof oe?.payment_method=="string"?oe.payment_method:oe?.payment_method?.id;R({id:Ue??oe?.id,type:"card",threeDSecureActionResultTokenId:oe?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:fe.accountPatch,sessionId:ve,nonce:ce})}catch(Ie){L?.(Ie instanceof Error?Ie.message:"Payment failed. Please try again.")}finally{ye.current=!1,K(null)}},[u,d,w,m,e,t,n,o,l,R,L,_]),[Y,le]=(0,r.useState)(null),Fe=Q?me??null:Y,he=(0,r.useCallback)(ne=>{ye.current||d||Fe&&Fe!==ne||((0,k.needsStripeMethodExplicitConfirm)(ne)?Q?Q(ne):le(ne):W(ne))},[Fe,d,W,Q]),ge=(0,r.useMemo)(()=>Y?{...c,paymentMethodTypes:[Y]}:null,[Y,c]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ne=>{let fe=me===ne,ve=te===ne,ce=te!==null&&te!==ne||me!=null&&me!==ne;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(ji,{method:ne,themeId:H,submitting:ve,disabled:ce,highlighted:fe,hasNextStep:(0,k.needsStripeMethodExplicitConfirm)(ne),onClick:()=>he(ne),backgroundColor:P?.backgroundColor,borderColor:P?.borderColor,textColor:P?.textColor,borderRadius:P?.borderRadius,fontFamily:P?.fontFamily}),!Q&&Y===ne&&ge&&u&&(0,i.jsx)(ut.Elements,{stripe:u,options:ge,children:(0,i.jsx)(Co,{method:ne,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:R,onErrorChange:L,onDecline:_,onCancel:()=>le(null),runBeforeButtonClick:w,onButtonClick:m,isProcessing:d,submitButtonColor:g,submitButtonBorderRadius:I,submitButtonStyle:A})},ne)]},ne)})})}function Vi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:u,onDecline:c,onTokenizedBody:R,firstName:L,lastName:m,chv:_,className:w,isProcessing:B,error:d,onErrorChange:g,showPayPal:I=!0,showStripe:A=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:H,showApplePay:Q=!0,showGooglePay:me=!0,layout:se="default",theme:z,buttonsTheme:te,buttonsStyles:K,appearance:ye,cardButtonContent:W,cardBackButtonContent:Y,cardTitleContent:le,showSecurityFooter:Fe,onButtonClick:he,onBeforeButtonClick:ge,enableAVS:ne,cardFieldOrder:fe,cardPreFormSlot:ve,avsLayout:ce="row",country:Ne,zip:Ie,addressLine1:we,addressLine2:E,city:oe,state:de,onCountryChange:Ue,onZipChange:Oe,avsCheck:ee,checkoutType:M,checkoutLayout:G,totalAmount:ue=0,currency:Ee="usd",initialCardOpen:gt=!1,directPaypal:et,isSubscription:Qe=!1,session:y,debug:je=!1}){let $e=on(),He=Lr(),Ke=(0,r.useContext)(rn),Wt=Or(),[bt,kt]=(0,r.useState)(!1),[h,ke]=(0,r.useState)(null),[Ve,lt]=(0,r.useState)(Ne??"US"),[rt,ot]=(0,r.useState)(Ie??""),[Ge,Ce]=(0,r.useState)(we??""),[vt,We]=(0,r.useState)(E??""),[Dt,Rt]=(0,r.useState)(oe??""),[dn,Sn]=(0,r.useState)(de??""),[wn,Nn]=(0,r.useState)({}),ht=(0,r.useRef)(Ie??""),Lt=(0,r.useRef)(Ne??"US"),Nt=(0,r.useRef)(we??""),Yt=(0,r.useRef)(E??""),Qt=(0,r.useRef)(oe??""),un=(0,r.useRef)(de??""),J=(0,r.useMemo)(()=>(0,k.resolveAVSConfig)(ne),[ne]),Mn=J!==null,pn=!!y?.vault?.html,Ot=!!y?.gateways?.pcivault,at=pn||Ot,f=!!(A&&at&&$e&&e),xe=(0,r.useMemo)(()=>!$e||!f||!e?null:$e.cardCapture({sessionId:e}),[$e,f,e]),ct=(0,r.useMemo)(()=>{let a=Ve,C=J?(0,k.isAVSFieldVisible)(J.postal_code,a):!1;return $i(a,rt,C)},[J,Ve,rt]),{avsInvalid:kn,invalidAvsFields:Te}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!f||!J)return{avsInvalid:!1,invalidAvsFields:a};let C=Ve,V=(re,Xe)=>(0,k.isAVSFieldVisible)(re,C)&&!Xe.trim(),ie={line1:V(J.address_line_1,Ge),city:V(J.city,Dt),state:V(J.state,dn),zip:ct.empty||ct.malformed};return{avsInvalid:ie.line1||ie.city||ie.state||ie.zip,invalidAvsFields:ie}},[f,J,Ve,Ge,Dt,dn,ct]),[An,mn]=(0,r.useState)(!1),[On,yn]=(0,r.useState)(!1),[zt,Bt]=(0,r.useState)(()=>bo(y?.vault)),[Re,pt]=(0,r.useState)(gt&&at?"card":"buttons"),[it,en]=(0,r.useState)(null),Gt=Re==="expanding"||Re==="card",Pt=280,Vt=(0,r.useRef)(null),Ct=(0,r.useCallback)(a=>{Vt.current&&clearTimeout(Vt.current),Vt.current=setTimeout(()=>{Vt.current=null,a()},Pt)},[Pt]);(0,r.useEffect)(()=>()=>{Vt.current&&clearTimeout(Vt.current)},[]);let tn=(0,r.useCallback)(()=>{pt("expanding"),Ct(()=>pt("card"))},[Ct]),fn=(0,r.useCallback)(()=>{pt("collapsing"),Ct(()=>pt("buttons"))},[Ct]),Rn=(0,r.useCallback)(a=>{en(a),pt("apm-expanding"),Ct(()=>pt("apm-form"))},[Ct]),gn=(0,r.useCallback)(()=>{pt("apm-collapsing"),Ct(()=>{pt("buttons"),en(null)})},[Ct]);(0,r.useEffect)(()=>{se==="buttons"&>&&at&&pt("card")},[se,gt,at]);let[Ht,Ye]=(0,r.useState)(null),Kt=(0,r.useRef)(!1),[Ut,$t]=(0,r.useState)(null),T=(0,r.useRef)(Ut);(0,r.useEffect)(()=>{T.current=Ut},[Ut]);let U=n||Wt,q=d??h,F=(0,r.useMemo)(()=>(0,At.resolveTheme)(z),[z]),p=(0,r.useMemo)(()=>{let a=F?.buttonsLayout??(0,k.resolveButtonsLayoutTheme)(te);return K?{...a,...K,cardButton:{...a.cardButton,...K.cardButton},cardFormContainer:{...a.cardFormContainer,...K.cardFormContainer},backButton:{...a.backButton,...K.backButton},backButtonIcon:{...a.backButtonIcon,...K.backButtonIcon},submitButton:{...a.submitButton,...K.submitButton},title:{...a.title,...K.title}}:a},[F,te,K]),j=ye??F?.appearance,v=(0,r.useMemo)(()=>{let a=j?.variables,C=Xe=>typeof Xe=="string"&&Xe?Xe:void 0,V=p.submitButton,ie=C(a?.colorPrimary)??C(V?.backgroundColor)??"#4A49FF",$=se==="buttons",re=p.nameInput;return{primaryColor:ie,primaryHoverColor:C(a?.colorPrimaryHover)??Vr(ie,.12),inputBackgroundColor:C(p.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(p.cardInputColor)??C(re?.color)??C(a?.colorText)??"#262833",borderColor:C(p.cardInputBorder)??($?"#e5e7eb":"#A4A4FF"),placeholderColor:C(p.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(re?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(p.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(Ra(re?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[j,p,se]),Be=Ke.inlineSessionPatchProcessing??!1,X=(B??bt)||Be,Je=U.replace(/\/+$/,""),ae=(0,r.useMemo)(()=>ho({userId:o,email:l,firstName:L,lastName:m,country:Ne,zip:Ie},wn),[o,l,L,m,Ne,Ie,wn]),qt=[ae.firstName,ae.lastName].filter(a=>!!a?.trim()).join(" "),st=(0,r.useMemo)(()=>$e?$e.getRawProvider():null,[$e]),N=(0,r.useMemo)(()=>He?He.getRawProvider():null,[He]),b=ue||100,O=j?{appearance:j}:null,Pe=(0,r.useMemo)(()=>{let a=j??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[j]),Me=(0,r.useMemo)(()=>{let a=ya(ue);return{...a,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...O}},[ue,Ee,O]),qe=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...O}),[b,Ee,O]),Z=(0,r.useCallback)(a=>{ke(a),g?.(a)},[g]);(0,r.useEffect)(()=>{!f||!xe||xe.setCardFieldOrder?.(fe??null,J==null)},[f,xe,fe,J]),(0,r.useEffect)(()=>{(Re==="expanding"||Re==="collapsing"||Re==="apm-expanding"||Re==="apm-collapsing")&&Z(null)},[Re,Z]);let be=(0,r.useCallback)((a,C,V)=>{c?.(Tt(a,C,V))},[c]),Se=(0,r.useCallback)((a,C,V)=>{let ie=V?.popupBlocked??Dn(C),$=zi(a,ie),re=Vn(V?.code)??xn(C)??"external_payment_method_failed",Xe=new At.FloPayError($,"api_error",{code:"external_payment_method_failed",param:a});Ye(null),se==="buttons"&&(pt("buttons"),en(null)),Z($),u?.(Xe),console.error("[FloPay] External payment method failed:",{method:a,code:re,popupBlocked:ie})},[se,u,Z]);(0,r.useEffect)(()=>{if(!f||!e){Bt(null);return}let a=bo(y?.vault);if(a){Bt(a);return}Bt(null);let C=!0;return new Bn.PaymentAPI(Je).getVaultCapture(e,t).then(V=>{if(!C)return;let ie=bo(V);ie?Bt(ie):Z("Failed to load the secure card form.")}).catch(V=>{C&&Z(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{C=!1}},[f,e,y?.vault?.html,y?.vault?.messageToken,y?.vault?.expectedOrigin,Je,t,Z]);let pe=(0,r.useRef)({onComplete:s,onError:u,updateError:Z,emitDecline:be,resolvedAccount:ae,avsConfig:J,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Je});pe.current={onComplete:s,onError:u,updateError:Z,emitDecline:be,resolvedAccount:ae,avsConfig:J,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Je};let ze=(0,r.useRef)(!1),hn=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:V}=pe.current,ie=Lt.current||a.country||"US",$=C?(0,k.isAVSFieldVisible)(C.state,ie):!1,re=C?(0,k.isAVSFieldVisible)(C.address_line_1,ie):!1,Xe=C?(0,k.isAVSFieldVisible)(C.postal_code,ie):!1,St=C?(0,k.isAVSFieldVisible)(C.city,ie):!1,Et=C?(0,k.isAVSFieldVisible)(C.address_line_2,ie):!1,tt=re&&!$&&Xe?(0,k.getStateFromPostalCode)(ie,(ht.current??"").trim()):null,_t=$?un.current:tt;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Xe&&ht.current?{zip:ht.current}:{},...St&&Qt.current?{city:Qt.current}:{},..._t?{state:_t}:{},...re&&Nt.current?{addressLine1:Nt.current}:{},...Et&&Yt.current?{addressLine2:Yt.current}:{},country:ie},...V!==void 0?{avsCheck:V}:{},...C?{avsConfig:{country:(0,k.isAVSFieldVisible)(C.country,ie),postal_code:Xe,address_line_1:re,address_line_2:Et,city:St,state:$}}:{}}},[]);(0,r.useEffect)(()=>{!f||!xe||xe.setSubmitGate?.(kn)},[f,xe,kn]),(0,r.useEffect)(()=>{if(!f||!xe)return;ze.current=!1;let a=!1,C=xe.on("submitting",()=>{mn(!0),Ye("processing");let{baseUrl:re,sessionId:Xe,nonce:St,updateError:Et,onError:tt}=pe.current;!Xe||!St||new Bn.PaymentAPI(re).patchAccountSnapshot(Xe,St,hn()).catch(_t=>{if(!Di(_t))return;let De=_t instanceof Error?_t.message:"Please check your billing address and try again.";Et(De),Ye(null),tt?.(_t instanceof At.FloPayError?_t:new At.FloPayError(De,"api_error"))})}),V=xe.on("complete",async re=>{Qn(re.sessionId??pe.current.sessionId),Ye("success"),await new Promise(Xe=>setTimeout(Xe,_n)),!ze.current&&(ze.current=!0,pe.current.onComplete?.({status:"succeeded",paymentIntentId:re.intentId,checkoutMethod:"card"}))}),ie=xe.on("decline",async re=>{let{updateError:Xe,emitDecline:St}=pe.current,Et=re.message??"Your payment was declined. Please try another card or contact your bank.";Xe(Et),Ye("error"),St("card",Et,re.declineReason?{declineCode:re.declineReason}:void 0),await new Promise(tt=>setTimeout(tt,Pn)),!a&&Ye(null)}),$=xe.on("error",async re=>{let{updateError:Xe,onError:St}=pe.current,Et=re.message??"There was a problem processing your payment. Please try again.";Xe(Et),Ye("error"),St?.(new At.FloPayError(Et,"api_error")),await new Promise(tt=>setTimeout(tt,Pn)),!a&&Ye(null)});return()=>{a=!0,C(),V(),ie(),$()}},[f,xe]);let dt=!!et?.clientId,It=Array.isArray(P),wr=It&&P.length>0,Ja=It&&P.includes("paypal"),{expressMethods:kr,paymentElementMethods:ar}=(0,r.useMemo)(()=>(0,k.partitionStripeMethods)(P,{excludePaypal:dt}),[P,dt]),To=dt||!!He,Xa=(0,r.useMemo)(()=>To?kr.filter(a=>a!=="paypal"):kr,[kr,To]),Za=(0,r.useMemo)(()=>{let a=[];return Q&&a.push("apple_pay"),me&&a.push("google_pay"),a},[Q,me]),Rr=It?Xa:Za,Qa=A&&Rr.length>0,no=Mn?Ve:Ne,Ir=(0,r.useMemo)(()=>{let a=no?.trim().toUpperCase();return a?H?ar.filter(C=>{let V=H[C];return!V||V.length===0||V.includes(a)}):(0,k.filterStripeMethodsByCountry)(ar,no):ar},[ar,no,H]),ro=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",appearance:Pe}),[b,Ee,Pe]),[Bo,Mo]=(0,r.useState)("loading"),[Ao,Fo]=(0,r.useState)("loading"),[Do,Lo]=(0,r.useState)("loading"),[ei,oo]=(0,r.useState)(!1),[No,ao]=(0,r.useState)("loading"),[Er,ti]=(0,r.useState)();(0,r.useEffect)(()=>{ti(ga())},[]);let Oo=I&&(dt||(It?Ja:Er===!1)),zo=A&&Qa,ir=Oo&&dt,Uo=No==="retrying"||No==="exhausted",sr=Oo&&!!N&&(!dt||Uo),lr=zo&&!!st,cr=A&&wr&&Ir.length>0&&!!st,ni=ir&&!Uo?ei:sr&&Ia(Bo),ri=lr&&Ia(Ao),oi=cr&&Do!=="load_error",$o=a=>a==="loading"||a==="ready",qo=ir||sr&&$o(Bo)||lr&&$o(Ao)||cr&&Do!=="load_error",_r=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!_r.current){if(!A&&!I){_r.current=!0;let a=new At.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(a),Z(a.message)}else if(!A&&I&&!dt&&!N){_r.current=!0;let a=new At.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(a),Z(a.message)}else if(Er!==void 0&&!at&&!qo){_r.current=!0;let a=new At.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"});u?.(a),Z(a.message)}}},[A,I,dt,N,Er,at,qo,u,Z]);let jo=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(jo.current||!wr)return;let a=[];Q!==!0&&a.push("showApplePay"),me!==!0&&a.push("showGooglePay"),a.length!==0&&(jo.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.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.`))},[wr,Q,me]);let Vo=(0,r.useCallback)((a,C)=>Ke.applyInlineSessionPatch?Ke.applyInlineSessionPatch(a).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let ie=ka(C,V);return Z(ie.message),u?.(ie),{error:ie,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ke.applyInlineSessionPatch,t,u,e,Z]),nn=(0,r.useCallback)(async a=>{if(!ge)return{proceed:!0};try{let C=await ge({method:a,sessionId:e||void 0,createSession:Ke.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&Nn(ie=>({...ie??{},...C.account}));let V=await Vo(C,a);return V.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(C){let V=ka(a,C);return Z(V.message),u?.(V),{proceed:!1}}},[Vo,Ke.inlineSessionDraft,ge,u,e,Z]),Ho=(0,r.useCallback)(async(a,C)=>{if(Kt.current)return;Kt.current=!0,kt(!0),Ye("processing"),Z(null);let V=C?.sessionId??e,ie=C?.nonce??t,$=ho(ae,C?.accountPatch),re=C?.completionPaymentMethodId??Ur(a),Xe=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Et=await new Bn.PaymentAPI(Je).processPayment($.userId??"",{sessionId:V,nonce:ie,tokenizedData:Xe,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...J?(()=>{let De=Lt.current,Xt=(0,k.isAVSFieldVisible)(J.state,De),Zt=(0,k.isAVSFieldVisible)(J.address_line_1,De),qn=(0,k.isAVSFieldVisible)(J.postal_code,De),jn=Zt&&!Xt&&qn?(0,k.getStateFromPostalCode)(De,(ht.current??"").trim()):null,xt=Xt?un.current:jn;return{country:De,...qn&&ht.current?{zip:ht.current}:{},...(0,k.isAVSFieldVisible)(J.city,De)&&Qt.current?{city:Qt.current}:{},...xt?{state:xt}:{},...Zt&&Nt.current?{addressLine1:Nt.current}:{},...(0,k.isAVSFieldVisible)(J.address_line_2,De)&&Yt.current?{addressLine2:Yt.current}:{}}})():{}},chv:_,avsCheck:ee??!1,checkoutType:M,checkoutLayout:G,avsConfig:J?{country:(0,k.isAVSFieldVisible)(J.country,Lt.current),postal_code:(0,k.isAVSFieldVisible)(J.postal_code,Lt.current),address_line_1:(0,k.isAVSFieldVisible)(J.address_line_1,Lt.current),address_line_2:(0,k.isAVSFieldVisible)(J.address_line_2,Lt.current),city:(0,k.isAVSFieldVisible)(J.city,Lt.current),state:(0,k.isAVSFieldVisible)(J.state,Lt.current)}:void 0});if(Et.ok){Qn(V),Ye("success"),$t(null),await new Promise(De=>setTimeout(De,_n)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:re,checkoutMethod:a.isPaypal?"paypal":"card"});return}let tt=await Et.json().catch(()=>null);if(tt?.type==="paypal_redirect_required"){let De=tt.threeDSecureToken,Xt=tt.paymentMethodId||a.id||"";if(!$e||!De){Ye("error"),Z("PayPal authorization required but no token provided.");return}try{let Zt=He?.getRawProvider();if(!Zt){Z("PayPal is not available.");return}let qn={return_url:window.location.href};Xt&&(qn.payment_method=Xt);let{error:jn}=await Zt.confirmPayment({clientSecret:De,confirmParams:qn,redirect:"if_required"});if(jn){Ye("error");let xt=jn.message??"PayPal payment failed.";Z(xt),be("paypal",xt,{code:jn.code})}}catch(Zt){Ye("error"),Z(Zt instanceof Error?Zt.message:"PayPal authorization failed.")}return}if(tt?.type==="paypal_direct_required"){let De=tt.orderId;if(!De){Ye("error"),Z("PayPal retry required but no order id provided.");return}let Xt=T.current?.attempts??0;if(Xt>=2){Ye("error"),Z("PayPal payment could not be completed after multiple attempts."),be("paypal","paypal_direct_required retry limit exceeded");return}oo(!1),ao("loading"),$t({orderId:De,attempts:Xt+1}),Ye(null);return}Ye("error");let _t=tt?.message??"Payment failed. Please try again.";Z(_t),be(a.isPaypal?"paypal":"card",_t,{code:tt?.code??tt?.gatewayErrorCode,declineCode:tt?.declineCode??tt?.gatewayDeclineReason}),await new Promise(De=>setTimeout(De,Pn))}catch(St){Ye("error"),Z(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(Et=>setTimeout(Et,Pn))}finally{kt(!1),Ye(null),Kt.current=!1}},[Je,e,t,ae,qt,_,$e,He,s,u,Z,be]),Jt=(0,r.useCallback)((a,C)=>{R?R(a):Ho(a,C)},[R,Ho]),Ko=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||Ko.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),V=a.get("payment_intent_client_secret"),ie=a.get("redirect_status");if(!C||!V)return;let $=_t=>{let De=localStorage.getItem(_t);if(!De)return null;try{return JSON.parse(De)}catch{return localStorage.removeItem(_t),null}},re=$(vn)??$(Sa),Xe;if(re?.clientSecret){if(re.clientSecret!==V)return;Xe={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}}}else if(re?.sessionId&&re.sessionId!==e)return;Ko.current=!0,localStorage.removeItem(vn),localStorage.removeItem(Sa);let St=new URL(window.location.href);St.searchParams.delete("payment_intent"),St.searchParams.delete("payment_intent_client_secret"),St.searchParams.delete("redirect_status"),window.history.replaceState({},"",St.toString());let Et=re?.paymentMethodType??re?.tokenType??"card",tt="card";(async()=>{let _t=$e?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";Z(xt),be(tt,xt);return}if(ie==="failed"){let xt="Payment was declined. Please try again.";Z(xt),be(tt,xt);return}let{paymentIntent:De,error:Xt}=await _t.retrievePaymentIntent(V);if(Xt){let xt=Xt.message??"Failed to retrieve payment status.";Z(xt),be(tt,xt,{code:Xt.code});return}let Zt=De?.status,qn=zr(Zt);if(!De||!qn){let xt=Zt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Z(xt),be(tt,xt,{code:Zt??"missing_payment_intent"});return}let jn=typeof De.payment_method=="string"?De.payment_method:De.payment_method?.id;Jt({id:jn??re?.paymentMethodId??re?.tokenId??De.id,type:"card",threeDSecureActionResultTokenId:De.id,gateway:re?.gateway??"stripe",paymentMethodType:Et},Xe)})()},[e,Jt,$e,Z,be]);let io=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!($e!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let dr=se==="buttons",jt=j?.variables,ai=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),so=jt?.colorBackground,ii=so&&!ai.has(so)?so:void 0,ur=p.cardInputBorder??(dr?"#e5e7eb":"#A4A4FF"),lo=jt?.colorDanger??"#dc2626",zn=a=>An&&a?lo:ur,xr=(ct.malformed||ct.empty)&&(On||An),si=xr?lo:zn(Te.zip),co=p.cardFormContainer?.backgroundColor??ii??(dr?"white":"#EDEDFF"),pr=p.cardInputBackground??jt?.colorBackground??"white",uo=Yn(Y),Wo=Yn(le),Wn=p.nameInput,Yo=p.cardInputFontSize??qi(Wn?.fontSize)??jt?.fontSizeBase??"16px",Go=typeof Wn?.fontFamily=="string"?Wn.fontFamily:jt?.fontFamily??"Poppins, sans-serif",Jo=Ra(Wn?.fontWeight)??400,li=p.cardInputColor??(typeof Wn?.color=="string"?Wn.color:void 0)??jt?.colorText??"#262833",ci=p.cardInputPlaceholderColor??"#9ca3af",mt=jt?.borderRadius??"8px",Un=jt?.borderRadius??p.cardButton?.borderRadius??mt,$n=jt?.colorPrimary??"#4A49FF",di=jt?.colorPrimaryHover??Vr($n,.12),po=jt?.colorText??"#262833",Xo={fontSize:Yo,fontFamily:Go,fontWeight:Jo,color:li,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ui={"--flopay-input-placeholder-color":ci,"--flopay-input-font-size":Yo,"--flopay-input-font-family":Go,"--flopay-input-font-weight":String(Jo)},mr=p.cardFormContainer??{},mo=mr.padding??(dr?"0":"1rem"),yo=mr.borderRadius??mt,pi=xe&&zt?(0,i.jsx)(Dr,{capture:xe,html:zt.html,messageToken:zt.messageToken,expectedOrigin:zt.expectedOrigin,theme:v,onReady:()=>{if(!J||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let C=0,V=window.setInterval(()=>{C+=1;let ie=document.activeElement;!!ie&&ie.tagName==="IFRAME"&&ie.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(V)):C>=50&&window.clearInterval(V)},100)},onError:a=>Z(a),onValidation:a=>{Z(a),a&&Ye(null)}}):(0,i.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"}),Zo=(0,i.jsxs)("div",{style:{backgroundColor:co,borderRadius:yo,...mr,padding:mo,...ui,display:"flex",flexDirection:"column"},children:[(0,i.jsx)("style",{children:`
|
|
30
|
+
`,Hr=44;function So(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 Ni={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ta={width:"100%",minHeight:Hr,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 Oi(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function wa(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ba(e){return e==="paypal"?"PayPal":(0,k.getStripeMethodDisplayName)(e)}function zi(e,t){let n=`We couldn't open ${Ba(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ma(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((d=l.current)=>{let g=d;g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),s=(0,r.useCallback)((d,g)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(d),d.timer=setTimeout(()=>{d.timer=null,l.current?.generation===d.generation&&(l.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},g))},[o,e]),u=(0,r.useCallback)(d=>{d.yieldedControl&&s(d,600)},[s]),c=(0,r.useCallback)(d=>{o();let g=t.current+1;t.current=g,n.current=null;let I={generation:g,method:d,timer:null,yieldedControl:!1};return l.current=I,g},[o]),R=(0,r.useCallback)(d=>{let g=l.current;return typeof d=="number"&&g?.generation!==d?!1:(o(g),l.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),L=(0,r.useCallback)(d=>{let g=l.current,I=d??g?.generation??t.current;(!d||g?.generation===d)&&(o(g),l.current=null),n.current=I},[o]),m=(0,r.useCallback)(d=>n.current===(d??t.current),[]),_=(0,r.useCallback)(d=>l.current?.generation===d&&n.current!==d,[]),w=(0,r.useCallback)(()=>{let d=l.current;d&&u(d)},[u]),B=(0,r.useCallback)(()=>{let d=l.current;d&&(d.yieldedControl=!0,o(d))},[o]);return(0,r.useEffect)(()=>{let d=()=>{document.visibilityState==="visible"?w():B()},g=()=>{B()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",g),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",g),window.removeEventListener("focus",w),o()}},[o,B,w]),{startAttempt:c,finishAttempt:R,invalidateAttempt:L,isAttemptInvalidated:m,isAttemptCurrent:_}}function Ui(e){let t=(0,k.getPostalCodeExample)(e);return`Enter a valid ${(0,k.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function $i(e,t,n){let l=(0,k.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,u=s&&!o,c=s&&!!o&&!(0,k.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:u,malformed:c}}function ka(e,t){return t instanceof At.FloPayError?t:new At.FloPayError(t instanceof Error?t.message:`${Oi(e)} before-click hook failed.`,"validation_error")}function vo(){return(0,i.jsx)("style",{children:Li})}function qi(e){return typeof e=="number"?`${e}px`:e}function Ra(e){if(typeof e=="number"||typeof e=="string")return e}function Aa(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function Fa({state:e,placeholderTestId:t,borderRadius:n=8,children:l}){return e==="unavailable"||e==="load_error"?null:(0,i.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,i.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,i.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:l})]})}function Ia(e){return e!=="unavailable"&&e!=="load_error"}function Wr(e){return(0,i.jsx)(Vi,{...e})}function Ea({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:u=!1,onButtonClick:c,onDecline:R,onTechnicalFailure:L,runBeforeButtonClick:m,onLoadStateChange:_,placeholderBorderRadius:w}){let B=on(),d=(0,ut.useStripe)(),g=(0,ut.useElements)(),[I,A]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(I)},[I,_]);let[P,H]=(0,r.useState)(!1),Q=(0,r.useRef)(!1),me=(0,r.useRef)(null),se=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[K,ye]=(0,r.useState)(!1),W=(0,r.useRef)(!1),Y=(0,r.useRef)(new Map),{startAttempt:le,finishAttempt:Fe,invalidateAttempt:he,isAttemptInvalidated:ge,isAttemptCurrent:ne}=Ma((E,oe,de)=>{L?.(E,oe,{...de,popupBlocked:de?.popupBlocked??Dn(oe)}),ye(!0),te(Ue=>Ue+1)});(0,r.useEffect)(()=>{K&&se.current?.focus()},[K,z]);let fe=(0,r.useCallback)(()=>{te(E=>E+1)},[]),ve=(0,r.useCallback)((E,oe,de)=>{he(de),L?.("paypal",E,{code:oe,popupBlocked:Dn(E)}),ye(!0),fe()},[he,L,fe]),ce=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{W.current&&(W.current=!1,ce())},[ce,z]);let Ne=(0,r.useCallback)(()=>{ye(!1),s?.(null),ce()},[ce,s]);(0,r.useEffect)(()=>{if(!d||Q.current)return;let E=new URLSearchParams(window.location.search),oe=E.get("payment_intent"),de=E.get("payment_intent_client_secret"),Ue=E.get("redirect_status");if(!oe||!de)return;Q.current=!0;let Oe;try{let M=localStorage.getItem(br);if(M){let G=JSON.parse(M);G.clientSecret===de&&(Oe={...G.accountPatch?{accountPatch:G.accountPatch}:{},...G.sessionId?{sessionId:G.sessionId}:{},...G.nonce?{nonce:G.nonce}:{}})}}catch{}try{localStorage.removeItem(br)}catch{}let ee=new URL(window.location.href);ee.searchParams.delete("payment_intent"),ee.searchParams.delete("payment_intent_client_secret"),ee.searchParams.delete("redirect_status"),window.history.replaceState({},"",ee.toString()),(async()=>{try{if(H(!0),Ue==="failed"){let ue="PayPal payment was declined. Please try again.";s?.(ue),R?.(Tt("paypal",ue));return}let{paymentIntent:M,error:G}=await d.retrievePaymentIntent(de);if(G){s?.(G.message??"Failed to retrieve PayPal payment status.");return}if(M&&(M.status==="requires_capture"||M.status==="succeeded")){let ue=typeof M.payment_method=="string"?M.payment_method:M.payment_method?.id;o({id:ue??M.id,type:"card",threeDSecureActionResultTokenId:M.id,isPaypal:!0},Oe)}else{let ue="PayPal payment was not completed. Please try again.";s?.(ue),R?.(Tt("paypal",ue))}}catch(M){s?.(M instanceof Error?M.message:"Failed to complete PayPal payment.")}finally{H(!1)}})()},[d,o,s,R]);let Ie=(0,r.useCallback)(async E=>{if(u||P){E.reject();return}let oe=m?await m("paypal"):{proceed:!0};if(!oe.proceed){Y.current.delete(z),E.reject();return}let de=le("paypal");Y.current.set(z,{generation:de,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),ye(!1),c?.("paypal"),E.resolve()},[Y,u,c,m,le,P,z]),we=(0,r.useCallback)(async E=>{if(!d||!g)return;let oe=Y.current.get(z);if(oe&&!ne(oe.generation)){Y.current.delete(z);return}if(!oe&&ge()||oe&&!Fe(oe.generation))return;oe||Fe();let de=oe??null;if(Y.current.delete(z),!de&&m){let M=await m("paypal");if(!M.proceed){E.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}}let Ue=de?.sessionId??e,Oe=de?.nonce??t,ee=de?.accountPatch?.email??n;try{if(H(!0),s?.(null),!Ue||!ee)throw new Error("Missing sessionId or email for PayPal payment");let M=d.createPaymentMethod,{error:G,paymentMethod:ue}=await M({type:"paypal"});if(G){ve(G,"stripe_paypal_create_payment_method_failed",oe?.generation),E.paymentFailed({reason:"fail"});return}let Ee=await new Bn.PaymentAPI(l).createSessionIntent(Ue,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ue?.id??null,intentKind:"payment"});if(Ee.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let gt=Ee.clientSecret,et={return_url:window.location.href};if(ue?.id&&(et.payment_method=ue.id),typeof window<"u")try{localStorage.setItem(br,JSON.stringify({clientSecret:gt,sessionId:Ue,nonce:Oe,accountPatch:de?.accountPatch}))}catch{}let{error:Qe,paymentIntent:y}=await d.confirmPayment({clientSecret:gt,confirmParams:et,redirect:"if_required"});if(Qe){if(typeof window<"u")try{localStorage.removeItem(br)}catch{}if(hr(Qe)){let $e=Qe.message??"Your payment was declined.";s?.($e),R?.(Tt("paypal",$e,{code:xn(Qe),declineCode:er(Qe)})),await Kr({billingApiUrl:l,sessionId:Ue,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:xn(Qe)??"provider_declined"}})}else ve(Qe,"stripe_paypal_confirm_failed",oe?.generation);return}if(typeof window<"u")try{localStorage.removeItem(br)}catch{}let je=typeof y?.payment_method=="string"?y.payment_method:y?.payment_method?.id;o({id:je??y?.id,type:"card",threeDSecureActionResultTokenId:y?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:Ue,nonce:Oe});return}catch(M){ve(M,"stripe_paypal_failed",oe?.generation)}finally{H(!1)}},[d,g,e,t,n,l,o,s,R,m,ve,Fe,ne,ge,z]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Fa,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[K&&(0,i.jsx)("button",{ref:se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ne,style:Ta,children:"Try PayPal again"}),(0,i.jsx)(ut.ExpressCheckoutElement,{onReady:E=>A(Aa(E,["paypal"])),onLoadError:()=>A("load_error"),onClick:Ie,onConfirm:we,onCancel:()=>{let E=Y.current.get(z);Y.current.delete(z),Mt(B)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he(E?.generation),ye(!1),W.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},z)]})}),P&&(0,i.jsx)(bn,{status:"processing"})]})}function _a({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:u,onErrorChange:c,onButtonClick:R,onDecline:L,onTechnicalFailure:m,runBeforeButtonClick:_,onLoadStateChange:w,placeholderBorderRadius:B}){let d=on(),g=(0,ut.useStripe)(),I=(0,ut.useElements)(),[A,P]=(0,r.useState)("loading");(0,r.useEffect)(()=>{w?.(A)},[A,w]);let[H,Q]=(0,r.useState)(!1),me=(0,r.useRef)(null),se=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[K,ye]=(0,r.useState)(!1),[W,Y]=(0,r.useState)("google_pay"),le=(0,r.useRef)(!1),Fe=(0,r.useRef)("google_pay"),he=(0,r.useRef)("google_pay"),ge=(0,r.useRef)(new Map),{startAttempt:ne,finishAttempt:fe,invalidateAttempt:ve,isAttemptInvalidated:ce,isAttemptCurrent:Ne}=Ma((ee,M,G)=>{m?.(ee,M,{...G,popupBlocked:G?.popupBlocked??Dn(M)}),Y(ee),ye(!0),te(ue=>ue+1)});(0,r.useEffect)(()=>{K&&se.current?.focus()},[K,z]);let Ie=(0,r.useCallback)(()=>{te(ee=>ee+1)},[]),we=(0,r.useCallback)((ee,M,G,ue)=>{ve(ue),m?.(ee,M,{code:G,popupBlocked:Dn(M)}),Y(ee),ye(!0),Ie()},[ve,m,Ie]),E=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{le.current&&(le.current=!1,E())},[E,z]);let oe=(0,r.useCallback)(()=>{ye(!1),c?.(null),E()},[E,c]),de=(0,r.useCallback)(async ee=>{if(!g||!I)return;let M=ge.current.get(z);if(M&&!Ne(M.generation)){ge.current.delete(z);return}if(!M&&ce()||M&&!fe(M.generation))return;M||fe();let G=ee.expressPaymentType??M?.method??Fe.current,ue=M??null;ge.current.delete(z);let Ee=wa(G);if(!ue&&_){let je=await _(Ee);if(!je.proceed){ee.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ue={accountPatch:je.accountPatch,sessionId:je.sessionId,nonce:je.nonce}}let gt=Ee,et=ue?.sessionId??e,Qe=ue?.nonce??t,y=ue?.accountPatch?.email??n;try{Q(!0),c?.(null);let{error:je}=await I.submit();if(je){we(G,je,"stripe_wallet_submit_failed",M?.generation);return}let{error:$e,paymentMethod:He}=await g.createPaymentMethod({elements:I});if($e||!He){we(G,$e??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",M?.generation);return}if(!et||!y)throw new Error("Missing sessionId or email for wallet payment");let Ke=await new Bn.PaymentAPI(l).createSessionIntent(et,Qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:G??Ee,paymentMethodId:He.id,intentKind:o});if(Ke.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Wt=Ke.clientSecret,{error:bt,intentId:kt}=(0,At.isSetupIntentClientSecret)(Wt)?await g.confirmCardSetup(Wt,{payment_method:He.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await g.confirmCardPayment(Wt,{payment_method:He.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(bt){if(hr(bt)){let h=bt.message??"Your payment was declined.";c?.(h),L?.(Tt(gt,h,{code:xn(bt),declineCode:er(bt)})),await Kr({billingApiUrl:l,sessionId:et,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:G??Ee,providerDeclineReason:xn(bt)??"provider_declined"}})}else we(G,bt,"stripe_wallet_confirm_failed",M?.generation);return}u({id:He.id,type:"card",threeDSecureActionResultTokenId:kt},{accountPatch:ue?.accountPatch,sessionId:et,nonce:Qe})}catch(je){we(G,je,"stripe_wallet_failed",M?.generation)}finally{Q(!1)}},[g,I,e,t,n,l,o,u,c,L,_,we,fe,Ne,ce,z]),Ue=(0,r.useMemo)(()=>{let ee=["applePay","googlePay","paypal","link","amazonPay","klarna"],M=new Set(["applePay","googlePay"]),G=new Set(s.map(k.stripeExpressMethodToOptionKey)),ue={};for(let Ee of ee)G.has(Ee)?ue[Ee]=M.has(Ee)?"always":"auto":ue[Ee]="never";return ue},[s]),Oe=(0,r.useMemo)(()=>s.map(k.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Fa,{state:A,placeholderTestId:"flopay-wallet-placeholder",borderRadius:B,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[K&&(0,i.jsxs)("button",{ref:se,type:"button","data-testid":"flopay-wallet-retry-button",onClick:oe,style:Ta,children:["Try ",Ba(W)," again"]}),(0,i.jsx)(ut.ExpressCheckoutElement,{onReady:ee=>{P(Aa(ee,Oe))},onLoadError:ee=>{P("load_error"),Mt(d)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk"})},onClick:async ee=>{Fe.current=ee.expressPaymentType,he.current=wa(ee.expressPaymentType);let M=_?await _(he.current):{proceed:!0};if(!M.proceed){ge.current.delete(z),ee.reject();return}let G=ne(ee.expressPaymentType);ge.current.set(z,{generation:G,method:ee.expressPaymentType,accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}),ye(!1),R?.(he.current),ee.resolve()},onConfirm:de,onCancel:()=>{let ee=ge.current.get(z);ge.current.delete(z),Mt(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ve(ee?.generation),ye(!1),le.current=!0,Ie()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ue,layout:{maxColumns:1,overflow:"never"}}},z)]})}),H&&(0,i.jsx)(bn,{status:"processing"})]})}function ji({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:u,backgroundColor:c,borderColor:R,textColor:L,borderRadius:m,fontFamily:_}){let w=(0,k.resolveStripeMethodBrandVariant)(e,t),B=sa[e],d=w?.backgroundColor??c??"#ffffff",g=w?.borderColor??R??"#d1d5db",I=w?.textColor??L??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&u()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Hr,padding:"0 1rem",backgroundColor:d,color:I,border:`1px solid ${g}`,borderRadius:m??8,fontSize:"0.95rem",fontWeight:600,fontFamily:_,cursor:n||l?"not-allowed":"pointer",opacity:l&&!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,i.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,k.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,k.hasVendoredStripeMethodLogo)(e)?8:0},children:[B?(0,i.jsx)("img",{src:B,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):w?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:w.logoSvg}}):null,(0,i.jsx)("span",{children:(0,k.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:I,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,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Co({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:u,onErrorChange:c,onDecline:R,onCancel:L,runBeforeButtonClick:m,onButtonClick:_,isProcessing:w,submitButtonColor:B,submitButtonBorderRadius:d,submitButtonStyle:g,errorText:I}){let A=on(),P=(0,ut.useStripe)(),H=(0,ut.useElements)(),[Q,me]=(0,r.useState)(!1),se=(0,r.useRef)(!1),[z,te]=(0,r.useState)(!1),[K,ye]=(0,r.useState)("loading"),W=(0,r.useCallback)(async()=>{if(!P||!H||w||se.current||!z)return;se.current=!0,me(!0);let Y=m?await m("card"):{proceed:!0};if(!Y.proceed){se.current=!1,me(!1);return}_?.("card");let le=Y.sessionId??t,Fe=Y.nonce??n,he=Y.accountPatch?.email??l;try{c?.(null);let ge=await H.submit();if(ge.error){c?.(ge.error.message??"Payment failed.");return}let ne=await P.createPaymentMethod({elements:H});if(ne.error||!ne.paymentMethod){c?.(ne.error?.message??"Failed to create payment method.");return}let fe=ne.paymentMethod;if(!le||!he)throw new Error("Missing sessionId or email for payment.");let ve=fe.type||e,ce=await new Bn.PaymentAPI(s).createSessionIntent(le,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ve,paymentMethodId:null,intentKind:"payment"});if(ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ne=ce.clientSecret;if(typeof window<"u")try{localStorage.setItem(vn,JSON.stringify({clientSecret:Ne,sessionId:le,nonce:Fe,accountPatch:Y.accountPatch,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"}))}catch{}let{error:Ie,paymentIntent:we}=await P.confirmPayment({clientSecret:Ne,confirmParams:{return_url:window.location.href,payment_method:fe.id},redirect:"if_required"});if(Ie){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let de=Ie.message??"Payment failed.";c?.(de),R?.(Tt("card",de,{code:Ie.code})),await Kr({billingApiUrl:s,sessionId:le,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ie.code??"provider_declined"}});return}let E=we?.status;if(!zr(E)){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let de=E==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";c?.(de),R?.(Tt("card",de,{code:E??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let oe=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;u({id:oe??fe.id,type:"card",threeDSecureActionResultTokenId:we?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:Y.accountPatch,sessionId:le,nonce:Fe})}catch(ge){c?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{se.current=!1,me(!1)}},[P,H,w,z,m,_,t,n,l,s,e,u,c,R]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(ut.PaymentElement,{onReady:()=>ye("ready"),onLoadError:()=>{ye("load_error"),Mt(A)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"apm",requestCategory:"provider_sdk"})},onChange:Y=>{te(!!Y.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...l?{email:l}:{}}}}}),(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{W()},disabled:!z||Q||w||K!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!z||Q||w||K!=="ready"?"not-allowed":"pointer",opacity:!z||Q||w||K!=="ready"?.5:1,transition:"opacity 120ms ease-out",...g??{}},children:Q?"Processing\u2026":`Pay with ${(0,k.getStripeMethodDisplayName)(e)}`}),I&&(0,i.jsx)(Xn,{margin:"0.75rem 0 0",children:I})]})}function xa({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:u,paymentElementBaseOptions:c,onTokenizedBody:R,onErrorChange:L,onButtonClick:m,onDecline:_,runBeforeButtonClick:w,onLoadStateChange:B,isProcessing:d=!1,submitButtonColor:g="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:A,buttonAppearance:P,themeId:H,onExpandApm:Q,expandedApmMethod:me}){let[se,z]=(0,r.useState)(null),[te,K]=(0,r.useState)(null),ye=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&u?B?.("ready"):u||B?.("loading")},[s.length,u,B]);let W=(0,r.useCallback)(async ne=>{if(!u||ye.current||d)return;ye.current=!0,K(ne);let fe=w?await w("card"):{proceed:!0};if(!fe.proceed){ye.current=!1,K(null);return}m?.("card");let ve=fe.sessionId??e,ce=fe.nonce??t,Ne=fe.accountPatch?.email??n;try{if(L?.(null),!ve||!Ne)throw new Error("Missing sessionId or email for payment.");let Ie=await new Bn.PaymentAPI(o).createSessionIntent(ve,ce??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(Ie.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let we=Ie.clientSecret;if(typeof window<"u")try{localStorage.setItem(vn,JSON.stringify({clientSecret:we,sessionId:ve,nonce:ce,accountPatch:fe.accountPatch,paymentMethodType:ne,gateway:"stripe"}))}catch{}let{error:E,paymentIntent:oe}=await u.confirmPayment({clientSecret:we,confirmParams:{return_url:window.location.href,payment_method_data:{type:ne,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...Ne?{email:Ne}:{}}}},redirect:"if_required"});if(E){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Oe=E.message??"Payment failed.";L?.(Oe),_?.(Tt("card",Oe,{code:E.code})),await Kr({billingApiUrl:o,sessionId:ve,nonce:ce,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:E.code??"provider_declined"}});return}let de=oe?.status;if(!zr(de)){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Oe=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";L?.(Oe),_?.(Tt("card",Oe,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Ue=typeof oe?.payment_method=="string"?oe.payment_method:oe?.payment_method?.id;R({id:Ue??oe?.id,type:"card",threeDSecureActionResultTokenId:oe?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:fe.accountPatch,sessionId:ve,nonce:ce})}catch(Ie){L?.(Ie instanceof Error?Ie.message:"Payment failed. Please try again.")}finally{ye.current=!1,K(null)}},[u,d,w,m,e,t,n,o,l,R,L,_]),[Y,le]=(0,r.useState)(null),Fe=Q?me??null:Y,he=(0,r.useCallback)(ne=>{ye.current||d||Fe&&Fe!==ne||((0,k.needsStripeMethodExplicitConfirm)(ne)?Q?Q(ne):le(ne):W(ne))},[Fe,d,W,Q]),ge=(0,r.useMemo)(()=>Y?{...c,paymentMethodTypes:[Y]}:null,[Y,c]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ne=>{let fe=me===ne,ve=te===ne,ce=te!==null&&te!==ne||me!=null&&me!==ne;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(ji,{method:ne,themeId:H,submitting:ve,disabled:ce,highlighted:fe,hasNextStep:(0,k.needsStripeMethodExplicitConfirm)(ne),onClick:()=>he(ne),backgroundColor:P?.backgroundColor,borderColor:P?.borderColor,textColor:P?.textColor,borderRadius:P?.borderRadius,fontFamily:P?.fontFamily}),!Q&&Y===ne&&ge&&u&&(0,i.jsx)(ut.Elements,{stripe:u,options:ge,children:(0,i.jsx)(Co,{method:ne,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:R,onErrorChange:L,onDecline:_,onCancel:()=>le(null),runBeforeButtonClick:w,onButtonClick:m,isProcessing:d,submitButtonColor:g,submitButtonBorderRadius:I,submitButtonStyle:A})},ne)]},ne)})})}function Vi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:u,onDecline:c,onTokenizedBody:R,firstName:L,lastName:m,chv:_,className:w,isProcessing:B,error:d,onErrorChange:g,showPayPal:I=!0,showStripe:A=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:H,showApplePay:Q=!0,showGooglePay:me=!0,layout:se="default",theme:z,buttonsTheme:te,buttonsStyles:K,appearance:ye,cardButtonContent:W,cardBackButtonContent:Y,cardTitleContent:le,showSecurityFooter:Fe,onButtonClick:he,onBeforeButtonClick:ge,enableAVS:ne,cardFieldOrder:fe,cardPreFormSlot:ve,avsLayout:ce="row",country:Ne,zip:Ie,addressLine1:we,addressLine2:E,city:oe,state:de,onCountryChange:Ue,onZipChange:Oe,avsCheck:ee,checkoutType:M,checkoutLayout:G,totalAmount:ue=0,currency:Ee="usd",initialCardOpen:gt=!1,directPaypal:et,isSubscription:Qe=!1,session:y,debug:je=!1}){let $e=on(),He=Lr(),Ke=(0,r.useContext)(rn),Wt=Or(),[bt,kt]=(0,r.useState)(!1),[h,ke]=(0,r.useState)(null),[Ve,lt]=(0,r.useState)(Ne??"US"),[rt,ot]=(0,r.useState)(Ie??""),[Ge,Ce]=(0,r.useState)(we??""),[vt,We]=(0,r.useState)(E??""),[Dt,Rt]=(0,r.useState)(oe??""),[dn,Sn]=(0,r.useState)(de??""),[wn,Nn]=(0,r.useState)({}),ht=(0,r.useRef)(Ie??""),Lt=(0,r.useRef)(Ne??"US"),Nt=(0,r.useRef)(we??""),Yt=(0,r.useRef)(E??""),Qt=(0,r.useRef)(oe??""),un=(0,r.useRef)(de??""),J=(0,r.useMemo)(()=>(0,k.resolveAVSConfig)(ne),[ne]),Mn=J!==null,pn=!!y?.vault?.html,Ot=!!y?.gateways?.pcivault,at=pn||Ot,f=!!(A&&at&&$e&&e),xe=(0,r.useMemo)(()=>!$e||!f||!e?null:$e.cardCapture({sessionId:e}),[$e,f,e]),ct=(0,r.useMemo)(()=>{let a=Ve,C=J?(0,k.isAVSFieldVisible)(J.postal_code,a):!1;return $i(a,rt,C)},[J,Ve,rt]),{avsInvalid:kn,invalidAvsFields:Te}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!f||!J)return{avsInvalid:!1,invalidAvsFields:a};let C=Ve,V=(re,Xe)=>(0,k.isAVSFieldVisible)(re,C)&&!Xe.trim(),ie={line1:V(J.address_line_1,Ge),city:V(J.city,Dt),state:V(J.state,dn),zip:ct.empty||ct.malformed};return{avsInvalid:ie.line1||ie.city||ie.state||ie.zip,invalidAvsFields:ie}},[f,J,Ve,Ge,Dt,dn,ct]),[An,mn]=(0,r.useState)(!1),[On,yn]=(0,r.useState)(!1),[zt,Bt]=(0,r.useState)(()=>bo(y?.vault)),[Re,pt]=(0,r.useState)(gt&&at?"card":"buttons"),[it,en]=(0,r.useState)(null),Gt=Re==="expanding"||Re==="card",Pt=280,Vt=(0,r.useRef)(null),Ct=(0,r.useCallback)(a=>{Vt.current&&clearTimeout(Vt.current),Vt.current=setTimeout(()=>{Vt.current=null,a()},Pt)},[Pt]);(0,r.useEffect)(()=>()=>{Vt.current&&clearTimeout(Vt.current)},[]);let tn=(0,r.useCallback)(()=>{pt("expanding"),Ct(()=>pt("card"))},[Ct]),fn=(0,r.useCallback)(()=>{pt("collapsing"),Ct(()=>pt("buttons"))},[Ct]),Rn=(0,r.useCallback)(a=>{en(a),pt("apm-expanding"),Ct(()=>pt("apm-form"))},[Ct]),gn=(0,r.useCallback)(()=>{pt("apm-collapsing"),Ct(()=>{pt("buttons"),en(null)})},[Ct]);(0,r.useEffect)(()=>{se==="buttons"&>&&at&&pt("card")},[se,gt,at]);let[Ht,Ye]=(0,r.useState)(null),Kt=(0,r.useRef)(!1),[Ut,$t]=(0,r.useState)(null),T=(0,r.useRef)(Ut);(0,r.useEffect)(()=>{T.current=Ut},[Ut]);let U=n||Wt,q=d??h,F=(0,r.useMemo)(()=>(0,At.resolveTheme)(z),[z]),p=(0,r.useMemo)(()=>{let a=F?.buttonsLayout??(0,k.resolveButtonsLayoutTheme)(te);return K?{...a,...K,cardButton:{...a.cardButton,...K.cardButton},cardFormContainer:{...a.cardFormContainer,...K.cardFormContainer},backButton:{...a.backButton,...K.backButton},backButtonIcon:{...a.backButtonIcon,...K.backButtonIcon},submitButton:{...a.submitButton,...K.submitButton},title:{...a.title,...K.title}}:a},[F,te,K]),j=ye??F?.appearance,v=(0,r.useMemo)(()=>{let a=j?.variables,C=Xe=>typeof Xe=="string"&&Xe?Xe:void 0,V=p.submitButton,ie=C(a?.colorPrimary)??C(V?.backgroundColor)??"#4A49FF",$=se==="buttons",re=p.nameInput;return{primaryColor:ie,primaryHoverColor:C(a?.colorPrimaryHover)??Vr(ie,.12),inputBackgroundColor:C(p.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(p.cardInputColor)??C(re?.color)??C(a?.colorText)??"#262833",borderColor:C(p.cardInputBorder)??($?"#e5e7eb":"#A4A4FF"),placeholderColor:C(p.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(re?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(p.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(Ra(re?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[j,p,se]),Be=Ke.inlineSessionPatchProcessing??!1,X=(B??bt)||Be,Je=U.replace(/\/+$/,""),ae=(0,r.useMemo)(()=>ho({userId:o,email:l,firstName:L,lastName:m,country:Ne,zip:Ie},wn),[o,l,L,m,Ne,Ie,wn]),qt=[ae.firstName,ae.lastName].filter(a=>!!a?.trim()).join(" "),st=(0,r.useMemo)(()=>$e?$e.getRawProvider():null,[$e]),N=(0,r.useMemo)(()=>He?He.getRawProvider():null,[He]),b=ue||100,O=j?{appearance:j}:null,Pe=(0,r.useMemo)(()=>{let a=j??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[j]),Me=(0,r.useMemo)(()=>{let a=ya(ue);return{...a,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...O}},[ue,Ee,O]),qe=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...O}),[b,Ee,O]),Z=(0,r.useCallback)(a=>{ke(a),g?.(a)},[g]);(0,r.useEffect)(()=>{!f||!xe||xe.setCardFieldOrder?.(fe??null,J==null)},[f,xe,fe,J]),(0,r.useEffect)(()=>{(Re==="expanding"||Re==="collapsing"||Re==="apm-expanding"||Re==="apm-collapsing")&&Z(null)},[Re,Z]);let be=(0,r.useCallback)((a,C,V)=>{c?.(Tt(a,C,V))},[c]),Se=(0,r.useCallback)((a,C,V)=>{let ie=V?.popupBlocked??Dn(C),$=zi(a,ie),re=Vn(V?.code)??xn(C)??"external_payment_method_failed",Xe=new At.FloPayError($,"api_error",{code:"external_payment_method_failed",param:a});Ye(null),se==="buttons"&&(pt("buttons"),en(null)),Z($),u?.(Xe),console.error("[FloPay] External payment method failed:",{method:a,code:re,popupBlocked:ie})},[se,u,Z]);(0,r.useEffect)(()=>{if(!f||!e){Bt(null);return}let a=bo(y?.vault);if(a){Bt(a);return}Bt(null);let C=!0;return new Bn.PaymentAPI(Je).getVaultCapture(e,t).then(V=>{if(!C)return;let ie=bo(V);ie?Bt(ie):Z("Failed to load the secure card form.")}).catch(V=>{C&&Z(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{C=!1}},[f,e,y?.vault?.html,y?.vault?.messageToken,y?.vault?.expectedOrigin,Je,t,Z]);let pe=(0,r.useRef)({onComplete:s,onError:u,updateError:Z,emitDecline:be,resolvedAccount:ae,avsConfig:J,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Je});pe.current={onComplete:s,onError:u,updateError:Z,emitDecline:be,resolvedAccount:ae,avsConfig:J,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Je};let ze=(0,r.useRef)(!1),hn=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:V}=pe.current,ie=Lt.current||a.country||"US",$=C?(0,k.isAVSFieldVisible)(C.state,ie):!1,re=C?(0,k.isAVSFieldVisible)(C.address_line_1,ie):!1,Xe=C?(0,k.isAVSFieldVisible)(C.postal_code,ie):!1,St=C?(0,k.isAVSFieldVisible)(C.city,ie):!1,Et=C?(0,k.isAVSFieldVisible)(C.address_line_2,ie):!1,tt=re&&!$&&Xe?(0,k.getStateFromPostalCode)(ie,(ht.current??"").trim()):null,_t=$?un.current:tt;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Xe&&ht.current?{zip:ht.current}:{},...St&&Qt.current?{city:Qt.current}:{},..._t?{state:_t}:{},...re&&Nt.current?{addressLine1:Nt.current}:{},...Et&&Yt.current?{addressLine2:Yt.current}:{},country:ie},...V!==void 0?{avsCheck:V}:{},...C?{avsConfig:{country:(0,k.isAVSFieldVisible)(C.country,ie),postal_code:Xe,address_line_1:re,address_line_2:Et,city:St,state:$}}:{}}},[]);(0,r.useEffect)(()=>{!f||!xe||xe.setSubmitGate?.(kn)},[f,xe,kn]),(0,r.useEffect)(()=>{if(!f||!xe)return;ze.current=!1;let a=!1,C=xe.on("submitting",()=>{mn(!0),Ye("processing");let{baseUrl:re,sessionId:Xe,nonce:St,updateError:Et,onError:tt}=pe.current;!Xe||!St||new Bn.PaymentAPI(re).patchAccountSnapshot(Xe,St,hn(),{telemetryMode:"best_effort"}).catch(_t=>{if(!Di(_t))return;let De=_t instanceof Error?_t.message:"Please check your billing address and try again.";Et(De),Ye(null),tt?.(_t instanceof At.FloPayError?_t:new At.FloPayError(De,"api_error"))})}),V=xe.on("complete",async re=>{Qn(re.sessionId??pe.current.sessionId),Ye("success"),await new Promise(Xe=>setTimeout(Xe,_n)),!ze.current&&(ze.current=!0,pe.current.onComplete?.({status:"succeeded",paymentIntentId:re.intentId,checkoutMethod:"card"}))}),ie=xe.on("decline",async re=>{let{updateError:Xe,emitDecline:St}=pe.current,Et=re.message??"Your payment was declined. Please try another card or contact your bank.";Xe(Et),Ye("error"),St("card",Et,re.declineReason?{declineCode:re.declineReason}:void 0),await new Promise(tt=>setTimeout(tt,Pn)),!a&&Ye(null)}),$=xe.on("error",async re=>{let{updateError:Xe,onError:St}=pe.current,Et=re.message??"There was a problem processing your payment. Please try again.";Xe(Et),Ye("error"),St?.(new At.FloPayError(Et,"api_error")),await new Promise(tt=>setTimeout(tt,Pn)),!a&&Ye(null)});return()=>{a=!0,C(),V(),ie(),$()}},[f,xe]);let dt=!!et?.clientId,It=Array.isArray(P),wr=It&&P.length>0,Ja=It&&P.includes("paypal"),{expressMethods:kr,paymentElementMethods:ar}=(0,r.useMemo)(()=>(0,k.partitionStripeMethods)(P,{excludePaypal:dt}),[P,dt]),To=dt||!!He,Xa=(0,r.useMemo)(()=>To?kr.filter(a=>a!=="paypal"):kr,[kr,To]),Za=(0,r.useMemo)(()=>{let a=[];return Q&&a.push("apple_pay"),me&&a.push("google_pay"),a},[Q,me]),Rr=It?Xa:Za,Qa=A&&Rr.length>0,no=Mn?Ve:Ne,Ir=(0,r.useMemo)(()=>{let a=no?.trim().toUpperCase();return a?H?ar.filter(C=>{let V=H[C];return!V||V.length===0||V.includes(a)}):(0,k.filterStripeMethodsByCountry)(ar,no):ar},[ar,no,H]),ro=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",appearance:Pe}),[b,Ee,Pe]),[Bo,Mo]=(0,r.useState)("loading"),[Ao,Fo]=(0,r.useState)("loading"),[Do,Lo]=(0,r.useState)("loading"),[ei,oo]=(0,r.useState)(!1),[No,ao]=(0,r.useState)("loading"),[Er,ti]=(0,r.useState)();(0,r.useEffect)(()=>{ti(ga())},[]);let Oo=I&&(dt||(It?Ja:Er===!1)),zo=A&&Qa,ir=Oo&&dt,Uo=No==="retrying"||No==="exhausted",sr=Oo&&!!N&&(!dt||Uo),lr=zo&&!!st,cr=A&&wr&&Ir.length>0&&!!st,ni=ir&&!Uo?ei:sr&&Ia(Bo),ri=lr&&Ia(Ao),oi=cr&&Do!=="load_error",$o=a=>a==="loading"||a==="ready",qo=ir||sr&&$o(Bo)||lr&&$o(Ao)||cr&&Do!=="load_error",_r=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!_r.current){if(!A&&!I){_r.current=!0;let a=new At.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(a),Z(a.message)}else if(!A&&I&&!dt&&!N){_r.current=!0;let a=new At.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(a),Z(a.message)}else if(Er!==void 0&&!at&&!qo){_r.current=!0;let a=new At.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"});u?.(a),Z(a.message)}}},[A,I,dt,N,Er,at,qo,u,Z]);let jo=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(jo.current||!wr)return;let a=[];Q!==!0&&a.push("showApplePay"),me!==!0&&a.push("showGooglePay"),a.length!==0&&(jo.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.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.`))},[wr,Q,me]);let Vo=(0,r.useCallback)((a,C)=>Ke.applyInlineSessionPatch?Ke.applyInlineSessionPatch(a).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let ie=ka(C,V);return Z(ie.message),u?.(ie),{error:ie,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ke.applyInlineSessionPatch,t,u,e,Z]),nn=(0,r.useCallback)(async a=>{if(!ge)return{proceed:!0};try{let C=await ge({method:a,sessionId:e||void 0,createSession:Ke.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&Nn(ie=>({...ie??{},...C.account}));let V=await Vo(C,a);return V.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(C){let V=ka(a,C);return Z(V.message),u?.(V),{proceed:!1}}},[Vo,Ke.inlineSessionDraft,ge,u,e,Z]),Ho=(0,r.useCallback)(async(a,C)=>{if(Kt.current)return;Kt.current=!0,kt(!0),Ye("processing"),Z(null);let V=C?.sessionId??e,ie=C?.nonce??t,$=ho(ae,C?.accountPatch),re=C?.completionPaymentMethodId??Ur(a),Xe=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Et=await new Bn.PaymentAPI(Je).processPayment($.userId??"",{sessionId:V,nonce:ie,tokenizedData:Xe,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...J?(()=>{let De=Lt.current,Xt=(0,k.isAVSFieldVisible)(J.state,De),Zt=(0,k.isAVSFieldVisible)(J.address_line_1,De),qn=(0,k.isAVSFieldVisible)(J.postal_code,De),jn=Zt&&!Xt&&qn?(0,k.getStateFromPostalCode)(De,(ht.current??"").trim()):null,xt=Xt?un.current:jn;return{country:De,...qn&&ht.current?{zip:ht.current}:{},...(0,k.isAVSFieldVisible)(J.city,De)&&Qt.current?{city:Qt.current}:{},...xt?{state:xt}:{},...Zt&&Nt.current?{addressLine1:Nt.current}:{},...(0,k.isAVSFieldVisible)(J.address_line_2,De)&&Yt.current?{addressLine2:Yt.current}:{}}})():{}},chv:_,avsCheck:ee??!1,checkoutType:M,checkoutLayout:G,avsConfig:J?{country:(0,k.isAVSFieldVisible)(J.country,Lt.current),postal_code:(0,k.isAVSFieldVisible)(J.postal_code,Lt.current),address_line_1:(0,k.isAVSFieldVisible)(J.address_line_1,Lt.current),address_line_2:(0,k.isAVSFieldVisible)(J.address_line_2,Lt.current),city:(0,k.isAVSFieldVisible)(J.city,Lt.current),state:(0,k.isAVSFieldVisible)(J.state,Lt.current)}:void 0});if(Et.ok){Qn(V),Ye("success"),$t(null),await new Promise(De=>setTimeout(De,_n)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:re,checkoutMethod:a.isPaypal?"paypal":"card"});return}let tt=await Et.json().catch(()=>null);if(tt?.type==="paypal_redirect_required"){let De=tt.threeDSecureToken,Xt=tt.paymentMethodId||a.id||"";if(!$e||!De){Ye("error"),Z("PayPal authorization required but no token provided.");return}try{let Zt=He?.getRawProvider();if(!Zt){Z("PayPal is not available.");return}let qn={return_url:window.location.href};Xt&&(qn.payment_method=Xt);let{error:jn}=await Zt.confirmPayment({clientSecret:De,confirmParams:qn,redirect:"if_required"});if(jn){Ye("error");let xt=jn.message??"PayPal payment failed.";Z(xt),be("paypal",xt,{code:jn.code})}}catch(Zt){Ye("error"),Z(Zt instanceof Error?Zt.message:"PayPal authorization failed.")}return}if(tt?.type==="paypal_direct_required"){let De=tt.orderId;if(!De){Ye("error"),Z("PayPal retry required but no order id provided.");return}let Xt=T.current?.attempts??0;if(Xt>=2){Ye("error"),Z("PayPal payment could not be completed after multiple attempts."),be("paypal","paypal_direct_required retry limit exceeded");return}oo(!1),ao("loading"),$t({orderId:De,attempts:Xt+1}),Ye(null);return}Ye("error");let _t=tt?.message??"Payment failed. Please try again.";Z(_t),be(a.isPaypal?"paypal":"card",_t,{code:tt?.code??tt?.gatewayErrorCode,declineCode:tt?.declineCode??tt?.gatewayDeclineReason}),await new Promise(De=>setTimeout(De,Pn))}catch(St){Ye("error"),Z(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(Et=>setTimeout(Et,Pn))}finally{kt(!1),Ye(null),Kt.current=!1}},[Je,e,t,ae,qt,_,$e,He,s,u,Z,be]),Jt=(0,r.useCallback)((a,C)=>{R?R(a):Ho(a,C)},[R,Ho]),Ko=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||Ko.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),V=a.get("payment_intent_client_secret"),ie=a.get("redirect_status");if(!C||!V)return;let $=_t=>{let De=localStorage.getItem(_t);if(!De)return null;try{return JSON.parse(De)}catch{return localStorage.removeItem(_t),null}},re=$(vn)??$(Sa),Xe;if(re?.clientSecret){if(re.clientSecret!==V)return;Xe={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}}}else if(re?.sessionId&&re.sessionId!==e)return;Ko.current=!0,localStorage.removeItem(vn),localStorage.removeItem(Sa);let St=new URL(window.location.href);St.searchParams.delete("payment_intent"),St.searchParams.delete("payment_intent_client_secret"),St.searchParams.delete("redirect_status"),window.history.replaceState({},"",St.toString());let Et=re?.paymentMethodType??re?.tokenType??"card",tt="card";(async()=>{let _t=$e?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";Z(xt),be(tt,xt);return}if(ie==="failed"){let xt="Payment was declined. Please try again.";Z(xt),be(tt,xt);return}let{paymentIntent:De,error:Xt}=await _t.retrievePaymentIntent(V);if(Xt){let xt=Xt.message??"Failed to retrieve payment status.";Z(xt),be(tt,xt,{code:Xt.code});return}let Zt=De?.status,qn=zr(Zt);if(!De||!qn){let xt=Zt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Z(xt),be(tt,xt,{code:Zt??"missing_payment_intent"});return}let jn=typeof De.payment_method=="string"?De.payment_method:De.payment_method?.id;Jt({id:jn??re?.paymentMethodId??re?.tokenId??De.id,type:"card",threeDSecureActionResultTokenId:De.id,gateway:re?.gateway??"stripe",paymentMethodType:Et},Xe)})()},[e,Jt,$e,Z,be]);let io=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!($e!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let dr=se==="buttons",jt=j?.variables,ai=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),so=jt?.colorBackground,ii=so&&!ai.has(so)?so:void 0,ur=p.cardInputBorder??(dr?"#e5e7eb":"#A4A4FF"),lo=jt?.colorDanger??"#dc2626",zn=a=>An&&a?lo:ur,xr=(ct.malformed||ct.empty)&&(On||An),si=xr?lo:zn(Te.zip),co=p.cardFormContainer?.backgroundColor??ii??(dr?"white":"#EDEDFF"),pr=p.cardInputBackground??jt?.colorBackground??"white",uo=Yn(Y),Wo=Yn(le),Wn=p.nameInput,Yo=p.cardInputFontSize??qi(Wn?.fontSize)??jt?.fontSizeBase??"16px",Go=typeof Wn?.fontFamily=="string"?Wn.fontFamily:jt?.fontFamily??"Poppins, sans-serif",Jo=Ra(Wn?.fontWeight)??400,li=p.cardInputColor??(typeof Wn?.color=="string"?Wn.color:void 0)??jt?.colorText??"#262833",ci=p.cardInputPlaceholderColor??"#9ca3af",mt=jt?.borderRadius??"8px",Un=jt?.borderRadius??p.cardButton?.borderRadius??mt,$n=jt?.colorPrimary??"#4A49FF",di=jt?.colorPrimaryHover??Vr($n,.12),po=jt?.colorText??"#262833",Xo={fontSize:Yo,fontFamily:Go,fontWeight:Jo,color:li,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ui={"--flopay-input-placeholder-color":ci,"--flopay-input-font-size":Yo,"--flopay-input-font-family":Go,"--flopay-input-font-weight":String(Jo)},mr=p.cardFormContainer??{},mo=mr.padding??(dr?"0":"1rem"),yo=mr.borderRadius??mt,pi=xe&&zt?(0,i.jsx)(Dr,{capture:xe,html:zt.html,messageToken:zt.messageToken,expectedOrigin:zt.expectedOrigin,theme:v,onReady:()=>{if(!J||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let C=0,V=window.setInterval(()=>{C+=1;let ie=document.activeElement;!!ie&&ie.tagName==="IFRAME"&&ie.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(V)):C>=50&&window.clearInterval(V)},100)},onError:a=>Z(a),onValidation:a=>{Z(a),a&&Ye(null)}}):(0,i.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"}),Zo=(0,i.jsxs)("div",{style:{backgroundColor:co,borderRadius:yo,...mr,padding:mo,...ui,display:"flex",flexDirection:"column"},children:[(0,i.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
|
@@ -27,7 +27,7 @@ ${Ze.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
|
-
`,ro=44;function qo(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 xs={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ni={width:"100%",minHeight:ro,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 Ts(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ya(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ri(e){return e==="paypal"?"PayPal":dr(e)}function Ms(e,t){let n=`We couldn't open ${ri(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function oi(e){let t=Ne(0),n=Ne(null),i=Ne(null),r=ge((l=i.current)=>{let f=l;f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),a=ge((l,f)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(l),l.timer=setTimeout(()=>{l.timer=null,i.current?.generation===l.generation&&(i.current=null,n.current=l.generation,e(l.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},f))},[r,e]),c=ge(l=>{l.yieldedControl&&a(l,600)},[a]),s=ge(l=>{r();let f=t.current+1;t.current=f,n.current=null;let S={generation:f,method:l,timer:null,yieldedControl:!1};return i.current=S,f},[r]),w=ge(l=>{let f=i.current;return typeof l=="number"&&f?.generation!==l?!1:(r(f),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[r]),M=ge(l=>{let f=i.current,S=l??f?.generation??t.current;(!l||f?.generation===l)&&(r(f),i.current=null),n.current=S},[r]),p=ge(l=>n.current===(l??t.current),[]),R=ge(l=>i.current?.generation===l&&n.current!==l,[]),C=ge(()=>{let l=i.current;l&&c(l)},[c]),E=ge(()=>{let l=i.current;l&&(l.yieldedControl=!0,r(l))},[r]);return mt(()=>{let l=()=>{document.visibilityState==="visible"?C():E()},f=()=>{E()};return document.addEventListener("visibilitychange",l),window.addEventListener("blur",f),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("blur",f),window.removeEventListener("focus",C),r()}},[r,E,C]),{startAttempt:s,finishAttempt:w,invalidateAttempt:M,isAttemptInvalidated:p,isAttemptCurrent:R}}function Bs(e){let t=Ps(e);return`Enter a valid ${Oo(e)}${t?` (e.g. ${t})`:""}`}function As(e,t,n){let i=gs(e),r=t.trim(),a=n&&i,c=a&&!r,s=a&&!!r&&!hs(e,r);return{visible:n,supported:i,required:a,empty:c,malformed:s}}function Ga(e,t){return t instanceof Cn?t:new Cn(t instanceof Error?t.message:`${Ts(e)} before-click hook failed.`,"validation_error")}function No(){return d("style",{children:_s})}function Fs(e){return typeof e=="number"?`${e}px`:e}function Ja(e){if(typeof e=="number"||typeof e=="string")return e}function ai(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function ii({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:xe("div",{style:{position:"relative",minHeight:44},children:[d("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"}}),d("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:i})]})}function Xa(e){return e!=="unavailable"&&e!=="load_error"}function jo(e){return d(Ls,{...e})}function Za({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:w,onTechnicalFailure:M,runBeforeButtonClick:p,onLoadStateChange:R,placeholderBorderRadius:C}){let E=Pn(),l=$o(),f=Uo(),[S,x]=ve("loading");mt(()=>{R?.(S)},[S,R]);let[h,U]=ve(!1),Y=Ne(!1),ce=Ne(null),re=Ne(null),[F,J]=ve(0),[$,de]=ve(!1),q=Ne(!1),j=Ne(new Map),{startAttempt:oe,finishAttempt:Be,invalidateAttempt:me,isAttemptInvalidated:pe,isAttemptCurrent:X}=oi((k,ee,ie)=>{M?.(k,ee,{...ie,popupBlocked:ie?.popupBlocked??Ln(ee)}),de(!0),J(Oe=>Oe+1)});mt(()=>{$&&re.current?.focus()},[$,F]);let ue=ge(()=>{J(k=>k+1)},[]),he=ge((k,ee,ie)=>{me(ie),M?.("paypal",k,{code:ee,popupBlocked:Ln(k)}),de(!0),ue()},[me,M,ue]),ae=ge(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);mt(()=>{q.current&&(q.current=!1,ae())},[ae,F]);let Fe=ge(()=>{de(!1),a?.(null),ae()},[ae,a]);mt(()=>{if(!l||Y.current)return;let k=new URLSearchParams(window.location.search),ee=k.get("payment_intent"),ie=k.get("payment_intent_client_secret"),Oe=k.get("redirect_status");if(!ee||!ie)return;Y.current=!0;let De;try{let _=localStorage.getItem(Ar);if(_){let V=JSON.parse(_);V.clientSecret===ie&&(De={...V.accountPatch?{accountPatch:V.accountPatch}:{},...V.sessionId?{sessionId:V.sessionId}:{},...V.nonce?{nonce:V.nonce}:{}})}}catch{}try{localStorage.removeItem(Ar)}catch{}let G=new URL(window.location.href);G.searchParams.delete("payment_intent"),G.searchParams.delete("payment_intent_client_secret"),G.searchParams.delete("redirect_status"),window.history.replaceState({},"",G.toString()),(async()=>{try{if(U(!0),Oe==="failed"){let se="PayPal payment was declined. Please try again.";a?.(se),w?.(Bt("paypal",se));return}let{paymentIntent:_,error:V}=await l.retrievePaymentIntent(ie);if(V){a?.(V.message??"Failed to retrieve PayPal payment status.");return}if(_&&(_.status==="requires_capture"||_.status==="succeeded")){let se=typeof _.payment_method=="string"?_.payment_method:_.payment_method?.id;r({id:se??_.id,type:"card",threeDSecureActionResultTokenId:_.id,isPaypal:!0},De)}else{let se="PayPal payment was not completed. Please try again.";a?.(se),w?.(Bt("paypal",se))}}catch(_){a?.(_ instanceof Error?_.message:"Failed to complete PayPal payment.")}finally{U(!1)}})()},[l,r,a,w]);let ke=ge(async k=>{if(c||h){k.reject();return}let ee=p?await p("paypal"):{proceed:!0};if(!ee.proceed){j.current.delete(F),k.reject();return}let ie=oe("paypal");j.current.set(F,{generation:ie,accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}),de(!1),s?.("paypal"),k.resolve()},[j,c,s,p,oe,h,F]),Ce=ge(async k=>{if(!l||!f)return;let ee=j.current.get(F);if(ee&&!X(ee.generation)){j.current.delete(F);return}if(!ee&&pe()||ee&&!Be(ee.generation))return;ee||Be();let ie=ee??null;if(j.current.delete(F),!ie&&p){let _=await p("paypal");if(!_.proceed){k.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let Oe=ie?.sessionId??e,De=ie?.nonce??t,G=ie?.accountPatch?.email??n;try{if(U(!0),a?.(null),!Oe||!G)throw new Error("Missing sessionId or email for PayPal payment");let _=l.createPaymentMethod,{error:V,paymentMethod:se}=await _({type:"paypal"});if(V){he(V,"stripe_paypal_create_payment_method_failed",ee?.generation),k.paymentFailed({reason:"fail"});return}let Re=await new Nn(i).createSessionIntent(Oe,De??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:se?.id??null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ht=Re.clientSecret,Ze={return_url:window.location.href};if(se?.id&&(Ze.payment_method=se.id),typeof window<"u")try{localStorage.setItem(Ar,JSON.stringify({clientSecret:ht,sessionId:Oe,nonce:De,accountPatch:ie?.accountPatch}))}catch{}let{error:Xe,paymentIntent:m}=await l.confirmPayment({clientSecret:ht,confirmParams:Ze,redirect:"if_required"});if(Xe){if(typeof window<"u")try{localStorage.removeItem(Ar)}catch{}if(Mr(Xe)){let ze=Xe.message??"Your payment was declined.";a?.(ze),w?.(Bt("paypal",ze,{code:Mn(Xe),declineCode:sr(Xe)})),await oo({billingApiUrl:i,sessionId:Oe,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(Xe)??"provider_declined"}})}else he(Xe,"stripe_paypal_confirm_failed",ee?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ar)}catch{}let $e=typeof m?.payment_method=="string"?m.payment_method:m?.payment_method?.id;r({id:$e??m?.id,type:"card",threeDSecureActionResultTokenId:m?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:Oe,nonce:De});return}catch(_){he(_,"stripe_paypal_failed",ee?.generation)}finally{U(!1)}},[l,f,e,t,n,i,r,a,w,p,he,Be,X,pe,F]);return xe(cr,{children:[d(ii,{state:S,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[$&&d("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Fe,style:ni,children:"Try PayPal again"}),d(ti,{onReady:k=>x(ai(k,["paypal"])),onLoadError:()=>x("load_error"),onClick:ke,onConfirm:Ce,onCancel:()=>{let k=j.current.get(F);j.current.delete(F),Dt(E)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),me(k?.generation),de(!1),q.current=!0,ue()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},F)]})}),h&&d(vn,{status:"processing"})]})}function Qa({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:w,onDecline:M,onTechnicalFailure:p,runBeforeButtonClick:R,onLoadStateChange:C,placeholderBorderRadius:E}){let l=Pn(),f=$o(),S=Uo(),[x,h]=ve("loading");mt(()=>{C?.(x)},[x,C]);let[U,Y]=ve(!1),ce=Ne(null),re=Ne(null),[F,J]=ve(0),[$,de]=ve(!1),[q,j]=ve("google_pay"),oe=Ne(!1),Be=Ne("google_pay"),me=Ne("google_pay"),pe=Ne(new Map),{startAttempt:X,finishAttempt:ue,invalidateAttempt:he,isAttemptInvalidated:ae,isAttemptCurrent:Fe}=oi((G,_,V)=>{p?.(G,_,{...V,popupBlocked:V?.popupBlocked??Ln(_)}),j(G),de(!0),J(se=>se+1)});mt(()=>{$&&re.current?.focus()},[$,F]);let ke=ge(()=>{J(G=>G+1)},[]),Ce=ge((G,_,V,se)=>{he(se),p?.(G,_,{code:V,popupBlocked:Ln(_)}),j(G),de(!0),ke()},[he,p,ke]),k=ge(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);mt(()=>{oe.current&&(oe.current=!1,k())},[k,F]);let ee=ge(()=>{de(!1),s?.(null),k()},[k,s]),ie=ge(async G=>{if(!f||!S)return;let _=pe.current.get(F);if(_&&!Fe(_.generation)){pe.current.delete(F);return}if(!_&&ae()||_&&!ue(_.generation))return;_||ue();let V=G.expressPaymentType??_?.method??Be.current,se=_??null;pe.current.delete(F);let Re=Ya(V);if(!se&&R){let $e=await R(Re);if(!$e.proceed){G.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}se={accountPatch:$e.accountPatch,sessionId:$e.sessionId,nonce:$e.nonce}}let ht=Re,Ze=se?.sessionId??e,Xe=se?.nonce??t,m=se?.accountPatch?.email??n;try{Y(!0),s?.(null);let{error:$e}=await S.submit();if($e){Ce(V,$e,"stripe_wallet_submit_failed",_?.generation);return}let{error:ze,paymentMethod:je}=await f.createPaymentMethod({elements:S});if(ze||!je){Ce(V,ze??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",_?.generation);return}if(!Ze||!m)throw new Error("Missing sessionId or email for wallet payment");let Ve=await new Nn(i).createSessionIntent(Ze,Xe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V??Re,paymentMethodId:je.id,intentKind:r});if(Ve.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Yt=Ve.clientSecret,{error:vt,intentId:It}=Rs(Yt)?await f.confirmCardSetup(Yt,{payment_method:je.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await f.confirmCardPayment(Yt,{payment_method:je.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(vt){if(Mr(vt)){let g=vt.message??"Your payment was declined.";s?.(g),M?.(Bt(ht,g,{code:Mn(vt),declineCode:sr(vt)})),await oo({billingApiUrl:i,sessionId:Ze,nonce:Xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V??Re,providerDeclineReason:Mn(vt)??"provider_declined"}})}else Ce(V,vt,"stripe_wallet_confirm_failed",_?.generation);return}c({id:je.id,type:"card",threeDSecureActionResultTokenId:It},{accountPatch:se?.accountPatch,sessionId:Ze,nonce:Xe})}catch($e){Ce(V,$e,"stripe_wallet_failed",_?.generation)}finally{Y(!1)}},[f,S,e,t,n,i,r,c,s,M,R,Ce,ue,Fe,ae,F]),Oe=pt(()=>{let G=["applePay","googlePay","paypal","link","amazonPay","klarna"],_=new Set(["applePay","googlePay"]),V=new Set(a.map(Ka)),se={};for(let Re of G)V.has(Re)?se[Re]=_.has(Re)?"always":"auto":se[Re]="never";return se},[a]),De=pt(()=>a.map(Ka),[a]);return xe(cr,{children:[d(ii,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:E,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[$&&xe("button",{ref:re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ee,style:ni,children:["Try ",ri(q)," again"]}),d(ti,{onReady:G=>{h(ai(G,De))},onLoadError:G=>{h("load_error"),Dt(l)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk"})},onClick:async G=>{Be.current=G.expressPaymentType,me.current=Ya(G.expressPaymentType);let _=R?await R(me.current):{proceed:!0};if(!_.proceed){pe.current.delete(F),G.reject();return}let V=X(G.expressPaymentType);pe.current.set(F,{generation:V,method:G.expressPaymentType,accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}),de(!1),w?.(me.current),G.resolve()},onConfirm:ie,onCancel:()=>{let G=pe.current.get(F);pe.current.delete(F),Dt(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),he(G?.generation),de(!1),oe.current=!0,ke()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Oe,layout:{maxColumns:1,overflow:"never"}}},F)]})}),U&&d(vn,{status:"processing"})]})}function Ds({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:w,textColor:M,borderRadius:p,fontFamily:R}){let C=Cs(e,t),E=Ma[e],l=C?.backgroundColor??s??"#ffffff",f=C?.borderColor??w??"#d1d5db",S=C?.textColor??M??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&c()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ro,padding:"0 1rem",backgroundColor:l,color:S,border:`1px solid ${f}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||i?"not-allowed":"pointer",opacity:i&&!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:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${dr(e)}\u2026`}):xe(cr,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:vs(e)?8:0},children:[E?d("img",{src:E,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):C?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,d("span",{children:dr(e)})]}),a&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:S,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:d("path",{d:"M9 18l6-6-6-6"})})]})})}function zo({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:a,onTokenizedBody:c,onErrorChange:s,onDecline:w,onCancel:M,runBeforeButtonClick:p,onButtonClick:R,isProcessing:C,submitButtonColor:E,submitButtonBorderRadius:l,submitButtonStyle:f,errorText:S}){let x=Pn(),h=$o(),U=Uo(),[Y,ce]=ve(!1),re=Ne(!1),[F,J]=ve(!1),[$,de]=ve("loading"),q=ge(async()=>{if(!h||!U||C||re.current||!F)return;re.current=!0,ce(!0);let j=p?await p("card"):{proceed:!0};if(!j.proceed){re.current=!1,ce(!1);return}R?.("card");let oe=j.sessionId??t,Be=j.nonce??n,me=j.accountPatch?.email??i;try{s?.(null);let pe=await U.submit();if(pe.error){s?.(pe.error.message??"Payment failed.");return}let X=await h.createPaymentMethod({elements:U});if(X.error||!X.paymentMethod){s?.(X.error?.message??"Failed to create payment method.");return}let ue=X.paymentMethod;if(!oe||!me)throw new Error("Missing sessionId or email for payment.");let he=ue.type||e,ae=await new Nn(a).createSessionIntent(oe,Be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:he,paymentMethodId:null,intentKind:"payment"});if(ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Fe=ae.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Fe,sessionId:oe,nonce:Be,accountPatch:j.accountPatch,paymentMethodId:ue.id,paymentMethodType:ue.type??e,gateway:"stripe"}))}catch{}let{error:ke,paymentIntent:Ce}=await h.confirmPayment({clientSecret:Fe,confirmParams:{return_url:window.location.href,payment_method:ue.id},redirect:"if_required"});if(ke){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ie=ke.message??"Payment failed.";s?.(ie),w?.(Bt("card",ie,{code:ke.code})),await oo({billingApiUrl:a,sessionId:oe,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ke.code??"provider_declined"}});return}let k=Ce?.status;if(!Jr(k)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ie=k==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(ie),w?.(Bt("card",ie,{code:k??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ee=typeof Ce?.payment_method=="string"?Ce.payment_method:Ce?.payment_method?.id;c({id:ee??ue.id,type:"card",threeDSecureActionResultTokenId:Ce?.id,gateway:"stripe",paymentMethodType:ue.type??e},{accountPatch:j.accountPatch,sessionId:oe,nonce:Be})}catch(pe){s?.(pe instanceof Error?pe.message:"Payment failed. Please try again.")}finally{re.current=!1,ce(!1)}},[h,U,C,F,p,R,t,n,i,a,e,c,s,w]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(us,{onReady:()=>de("ready"),onLoadError:()=>{de("load_error"),Dt(x)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"apm",requestCategory:"provider_sdk"})},onChange:j=>{J(!!j.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...i?{email:i}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{q()},disabled:!F||Y||C||$!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:E,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!F||Y||C||$!=="ready"?"not-allowed":"pointer",opacity:!F||Y||C||$!=="ready"?.5:1,transition:"opacity 120ms ease-out",...f??{}},children:Y?"Processing\u2026":`Pay with ${dr(e)}`}),S&&d(or,{margin:"0.75rem 0 0",children:S})]})}function ei({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:w,onErrorChange:M,onButtonClick:p,onDecline:R,runBeforeButtonClick:C,onLoadStateChange:E,isProcessing:l=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:S=8,submitButtonStyle:x,buttonAppearance:h,themeId:U,onExpandApm:Y,expandedApmMethod:ce}){let[re,F]=ve(null),[J,$]=ve(null),de=Ne(!1);mt(()=>{a.length>0&&c?E?.("ready"):c||E?.("loading")},[a.length,c,E]);let q=ge(async X=>{if(!c||de.current||l)return;de.current=!0,$(X);let ue=C?await C("card"):{proceed:!0};if(!ue.proceed){de.current=!1,$(null);return}p?.("card");let he=ue.sessionId??e,ae=ue.nonce??t,Fe=ue.accountPatch?.email??n;try{if(M?.(null),!he||!Fe)throw new Error("Missing sessionId or email for payment.");let ke=await new Nn(r).createSessionIntent(he,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ce=ke.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ce,sessionId:he,nonce:ae,accountPatch:ue.accountPatch,paymentMethodType:X,gateway:"stripe"}))}catch{}let{error:k,paymentIntent:ee}=await c.confirmPayment({clientSecret:Ce,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...Fe?{email:Fe}:{}}}},redirect:"if_required"});if(k){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let De=k.message??"Payment failed.";M?.(De),R?.(Bt("card",De,{code:k.code})),await oo({billingApiUrl:r,sessionId:he,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:k.code??"provider_declined"}});return}let ie=ee?.status;if(!Jr(ie)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let De=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";M?.(De),R?.(Bt("card",De,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Oe=typeof ee?.payment_method=="string"?ee.payment_method:ee?.payment_method?.id;w({id:Oe??ee?.id,type:"card",threeDSecureActionResultTokenId:ee?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:ue.accountPatch,sessionId:he,nonce:ae})}catch(ke){M?.(ke instanceof Error?ke.message:"Payment failed. Please try again.")}finally{de.current=!1,$(null)}},[c,l,C,p,e,t,n,r,i,w,M,R]),[j,oe]=ve(null),Be=Y?ce??null:j,me=ge(X=>{de.current||l||Be&&Be!==X||(Ha(X)?Y?Y(X):oe(X):q(X))},[Be,l,q,Y]),pe=pt(()=>j?{...s,paymentMethodTypes:[j]}:null,[j,s]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(X=>{let ue=ce===X,he=J===X,ae=J!==null&&J!==X||ce!=null&&ce!==X;return xe(Ss.Fragment,{children:[d(Ds,{method:X,themeId:U,submitting:he,disabled:ae,highlighted:ue,hasNextStep:Ha(X),onClick:()=>me(X),backgroundColor:h?.backgroundColor,borderColor:h?.borderColor,textColor:h?.textColor,borderRadius:h?.borderRadius,fontFamily:h?.fontFamily}),!Y&&j===X&&pe&&c&&d(Jn,{stripe:c,options:pe,children:d(zo,{method:X,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:w,onErrorChange:M,onDecline:R,onCancel:()=>oe(null),runBeforeButtonClick:C,onButtonClick:p,isProcessing:l,submitButtonColor:f,submitButtonBorderRadius:S,submitButtonStyle:x})},X)]},X)})})}function Ls({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:c,onDecline:s,onTokenizedBody:w,firstName:M,lastName:p,chv:R,className:C,isProcessing:E,error:l,onErrorChange:f,showPayPal:S=!0,showStripe:x=!0,enabledPaymentMethods:h,enabledPaymentMethodCountries:U,showApplePay:Y=!0,showGooglePay:ce=!0,layout:re="default",theme:F,buttonsTheme:J,buttonsStyles:$,appearance:de,cardButtonContent:q,cardBackButtonContent:j,cardTitleContent:oe,showSecurityFooter:Be,onButtonClick:me,onBeforeButtonClick:pe,enableAVS:X,cardFieldOrder:ue,cardPreFormSlot:he,avsLayout:ae="row",country:Fe,zip:ke,addressLine1:Ce,addressLine2:k,city:ee,state:ie,onCountryChange:Oe,onZipChange:De,avsCheck:G,checkoutType:_,checkoutLayout:V,totalAmount:se=0,currency:Re="usd",initialCardOpen:ht=!1,directPaypal:Ze,isSubscription:Xe=!1,session:m,debug:$e=!1}){let ze=Pn(),je=xo(),Ve=ks(ln),Yt=Gr(),[vt,It]=ve(!1),[g,we]=ve(null),[qe,it]=ve(Fe??"US"),[et,tt]=ve(ke??""),[Ye,Pe]=ve(Ce??""),[Ct,He]=ve(k??""),[Lt,Et]=ve(ee??""),[dn,Rn]=ve(ie??""),[In,$n]=ve({}),Pt=Ne(ke??""),Nt=Ne(Fe??"US"),Ot=Ne(Ce??""),Gt=Ne(k??""),rn=Ne(ee??""),un=Ne(ie??""),H=pt(()=>fs(X),[X]),An=H!==null,pn=!!m?.vault?.html,zt=!!m?.gateways?.pcivault,nt=pn||zt,y=!!(x&&nt&&ze&&e),Ie=pt(()=>!ze||!y||!e?null:ze.cardCapture({sessionId:e}),[ze,y,e]),st=pt(()=>{let o=qe,v=H?_e(H.postal_code,o):!1;return As(o,et,v)},[H,qe,et]),{avsInvalid:En,invalidAvsFields:Ee}=pt(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!y||!H)return{avsInvalid:!1,invalidAvsFields:o};let v=qe,z=(Z,Je)=>_e(Z,v)&&!Je.trim(),ne={line1:z(H.address_line_1,Ye),city:z(H.city,Lt),state:z(H.state,dn),zip:st.empty||st.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[y,H,qe,Ye,Lt,dn,st]),[Fn,mn]=ve(!1),[qn,yn]=ve(!1),[Ut,Ft]=ve(()=>Lo(m?.vault)),[Se,yt]=ve(ht&&nt?"card":"buttons"),[rt,on]=ve(null),Jt=Se==="expanding"||Se==="card",bt=280,Ht=Ne(null),wt=ge(o=>{Ht.current&&clearTimeout(Ht.current),Ht.current=setTimeout(()=>{Ht.current=null,o()},bt)},[bt]);mt(()=>()=>{Ht.current&&clearTimeout(Ht.current)},[]);let an=ge(()=>{yt("expanding"),wt(()=>yt("card"))},[wt]),fn=ge(()=>{yt("collapsing"),wt(()=>yt("buttons"))},[wt]),_n=ge(o=>{on(o),yt("apm-expanding"),wt(()=>yt("apm-form"))},[wt]),gn=ge(()=>{yt("apm-collapsing"),wt(()=>{yt("buttons"),on(null)})},[wt]);mt(()=>{re==="buttons"&&ht&&nt&&yt("card")},[re,ht,nt]);let[Kt,Ke]=ve(null),Wt=Ne(!1),[$t,qt]=ve(null),I=Ne($t);mt(()=>{I.current=$t},[$t]);let D=n||Yt,N=l??g,T=pt(()=>Is(F),[F]),u=pt(()=>{let o=T?.buttonsLayout??ps(J);return $?{...o,...$,cardButton:{...o.cardButton,...$.cardButton},cardFormContainer:{...o.cardFormContainer,...$.cardFormContainer},backButton:{...o.backButton,...$.backButton},backButtonIcon:{...o.backButtonIcon,...$.backButtonIcon},submitButton:{...o.submitButton,...$.submitButton},title:{...o.title,...$.title}}:o},[T,J,$]),O=de??T?.appearance,b=pt(()=>{let o=O?.variables,v=Je=>typeof Je=="string"&&Je?Je:void 0,z=u.submitButton,ne=v(o?.colorPrimary)??v(z?.backgroundColor)??"#4A49FF",L=re==="buttons",Z=u.nameInput;return{primaryColor:ne,primaryHoverColor:v(o?.colorPrimaryHover)??no(ne,.12),inputBackgroundColor:v(u.cardInputBackground)??v(o?.colorBackground)??"#ffffff",textColor:v(u.cardInputColor)??v(Z?.color)??v(o?.colorText)??"#262833",borderColor:v(u.cardInputBorder)??(L?"#e5e7eb":"#A4A4FF"),placeholderColor:v(u.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(Z?.fontFamily)??v(o?.fontFamily)??"Poppins, sans-serif",fontSize:v(u.cardInputFontSize)??v(o?.fontSizeBase)??"16px",fontWeight:String(Ja(Z?.fontWeight)??400),borderRadius:v(o?.borderRadius)??"8px"}},[O,u,re]),Te=Ve.inlineSessionPatchProcessing??!1,K=(E??vt)||Te,Ge=D.replace(/\/+$/,""),te=pt(()=>Bo({userId:r,email:i,firstName:M,lastName:p,country:Fe,zip:ke},In),[r,i,M,p,Fe,ke,In]),jt=[te.firstName,te.lastName].filter(o=>!!o?.trim()).join(" "),ot=pt(()=>ze?ze.getRawProvider():null,[ze]),B=pt(()=>je?je.getRawProvider():null,[je]),P=se||100,A=O?{appearance:O}:null,ye=pt(()=>{let o=O??{},v=o.rules??{};return{...o,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[O]),Me=pt(()=>{let o=Da(se);return{...o,currency:Re.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...A}},[se,Re,A]),Ue=pt(()=>({mode:"payment",amount:P,currency:Re.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...A}),[P,Re,A]),W=ge(o=>{we(o),f?.(o)},[f]);mt(()=>{!y||!Ie||Ie.setCardFieldOrder?.(ue??null,H==null)},[y,Ie,ue,H]),mt(()=>{(Se==="expanding"||Se==="collapsing"||Se==="apm-expanding"||Se==="apm-collapsing")&&W(null)},[Se,W]);let fe=ge((o,v,z)=>{s?.(Bt(o,v,z))},[s]),be=ge((o,v,z)=>{let ne=z?.popupBlocked??Ln(v),L=Ms(o,ne),Z=Yn(z?.code)??Mn(v)??"external_payment_method_failed",Je=new Cn(L,"api_error",{code:"external_payment_method_failed",param:o});Ke(null),re==="buttons"&&(yt("buttons"),on(null)),W(L),c?.(Je),console.error("[FloPay] External payment method failed:",{method:o,code:Z,popupBlocked:ne})},[re,c,W]);mt(()=>{if(!y||!e){Ft(null);return}let o=Lo(m?.vault);if(o){Ft(o);return}Ft(null);let v=!0;return new Nn(Ge).getVaultCapture(e,t).then(z=>{if(!v)return;let ne=Lo(z);ne?Ft(ne):W("Failed to load the secure card form.")}).catch(z=>{v&&W(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{v=!1}},[y,e,m?.vault?.html,m?.vault?.messageToken,m?.vault?.expectedOrigin,Ge,t,W]);let le=Ne({onComplete:a,onError:c,updateError:W,emitDecline:fe,resolvedAccount:te,avsConfig:H,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ge});le.current={onComplete:a,onError:c,updateError:W,emitDecline:fe,resolvedAccount:te,avsConfig:H,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ge};let Le=Ne(!1),hn=ge(()=>{let{resolvedAccount:o,avsConfig:v,avsCheckProp:z}=le.current,ne=Nt.current||o.country||"US",L=v?_e(v.state,ne):!1,Z=v?_e(v.address_line_1,ne):!1,Je=v?_e(v.postal_code,ne):!1,St=v?_e(v.city,ne):!1,xt=v?_e(v.address_line_2,ne):!1,Qe=Z&&!L&&Je?Va(ne,(Pt.current??"").trim()):null,Tt=L?un.current:Qe;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Je&&Pt.current?{zip:Pt.current}:{},...St&&rn.current?{city:rn.current}:{},...Tt?{state:Tt}:{},...Z&&Ot.current?{addressLine1:Ot.current}:{},...xt&&Gt.current?{addressLine2:Gt.current}:{},country:ne},...z!==void 0?{avsCheck:z}:{},...v?{avsConfig:{country:_e(v.country,ne),postal_code:Je,address_line_1:Z,address_line_2:xt,city:St,state:L}}:{}}},[]);mt(()=>{!y||!Ie||Ie.setSubmitGate?.(En)},[y,Ie,En]),mt(()=>{if(!y||!Ie)return;Le.current=!1;let o=!1,v=Ie.on("submitting",()=>{mn(!0),Ke("processing");let{baseUrl:Z,sessionId:Je,nonce:St,updateError:xt,onError:Qe}=le.current;!Je||!St||new Nn(Z).patchAccountSnapshot(Je,St,hn()).catch(Tt=>{if(!Es(Tt))return;let Ae=Tt instanceof Error?Tt.message:"Please check your billing address and try again.";xt(Ae),Ke(null),Qe?.(Tt instanceof Cn?Tt:new Cn(Ae,"api_error"))})}),z=Ie.on("complete",async Z=>{ir(Z.sessionId??le.current.sessionId),Ke("success"),await new Promise(Je=>setTimeout(Je,Tn)),!Le.current&&(Le.current=!0,le.current.onComplete?.({status:"succeeded",paymentIntentId:Z.intentId,checkoutMethod:"card"}))}),ne=Ie.on("decline",async Z=>{let{updateError:Je,emitDecline:St}=le.current,xt=Z.message??"Your payment was declined. Please try another card or contact your bank.";Je(xt),Ke("error"),St("card",xt,Z.declineReason?{declineCode:Z.declineReason}:void 0),await new Promise(Qe=>setTimeout(Qe,bn)),!o&&Ke(null)}),L=Ie.on("error",async Z=>{let{updateError:Je,onError:St}=le.current,xt=Z.message??"There was a problem processing your payment. Please try again.";Je(xt),Ke("error"),St?.(new Cn(xt,"api_error")),await new Promise(Qe=>setTimeout(Qe,bn)),!o&&Ke(null)});return()=>{o=!0,v(),z(),ne(),L()}},[y,Ie]);let lt=!!Ze?.clientId,_t=Array.isArray(h),Nr=_t&&h.length>0,wi=_t&&h.includes("paypal"),{expressMethods:Or,paymentElementMethods:Pr}=pt(()=>ws(h,{excludePaypal:lt}),[h,lt]),ta=lt||!!je,Si=pt(()=>ta?Or.filter(o=>o!=="paypal"):Or,[Or,ta]),ki=pt(()=>{let o=[];return Y&&o.push("apple_pay"),ce&&o.push("google_pay"),o},[Y,ce]),zr=_t?Si:ki,Ri=x&&zr.length>0,yo=An?qe:Fe,Ur=pt(()=>{let o=yo?.trim().toUpperCase();return o?U?Pr.filter(v=>{let z=U[v];return!z||z.length===0||z.includes(o)}):bs(Pr,yo):Pr},[Pr,yo,U]),fo=pt(()=>({mode:"payment",amount:P,currency:Re.toLowerCase(),paymentMethodCreation:"manual",appearance:ye}),[P,Re,ye]),[na,ra]=ve("loading"),[oa,aa]=ve("loading"),[ia,sa]=ve("loading"),[Ii,go]=ve(!1),[la,ho]=ve("loading"),[$r,Ei]=ve();mt(()=>{Ei(Na())},[]);let ca=S&&(lt||(_t?wi:$r===!1)),da=x&&Ri,br=ca&<,ua=la==="retrying"||la==="exhausted",vr=ca&&!!B&&(!lt||ua),Cr=da&&!!ot,wr=x&&Nr&&Ur.length>0&&!!ot,_i=br&&!ua?Ii:vr&&Xa(na),xi=Cr&&Xa(oa),Ti=wr&&ia!=="load_error",pa=o=>o==="loading"||o==="ready",ma=br||vr&&pa(na)||Cr&&pa(oa)||wr&&ia!=="load_error",qr=Ne(!1);mt(()=>{if(!qr.current){if(!x&&!S){qr.current=!0;let o=new Cn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(o),W(o.message)}else if(!x&&S&&!lt&&!B){qr.current=!0;let o=new Cn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(o),W(o.message)}else if($r!==void 0&&!nt&&!ma){qr.current=!0;let o=new Cn("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"});c?.(o),W(o.message)}}},[x,S,lt,B,$r,nt,ma,c,W]);let ya=Ne(!1);mt(()=>{if(ya.current||!Nr)return;let o=[];Y!==!0&&o.push("showApplePay"),ce!==!0&&o.push("showGooglePay"),o.length!==0&&(ya.current=!0,console.warn(`[FloPay] ${o.join(" / ")} ${o.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.`))},[Nr,Y,ce]);let fa=ge((o,v)=>Ve.applyInlineSessionPatch?Ve.applyInlineSessionPatch(o).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let ne=Ga(v,z);return W(ne.message),c?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ve.applyInlineSessionPatch,t,c,e,W]),sn=ge(async o=>{if(!pe)return{proceed:!0};try{let v=await pe({method:o,sessionId:e||void 0,createSession:Ve.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&$n(ne=>({...ne??{},...v.account}));let z=await fa(v,o);return z.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(v){let z=Ga(o,v);return W(z.message),c?.(z),{proceed:!1}}},[fa,Ve.inlineSessionDraft,pe,c,e,W]),ga=ge(async(o,v)=>{if(Wt.current)return;Wt.current=!0,It(!0),Ke("processing"),W(null);let z=v?.sessionId??e,ne=v?.nonce??t,L=Bo(te,v?.accountPatch),Z=v?.completionPaymentMethodId??Xr(o),Je=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let xt=await new Nn(Ge).processPayment(L.userId??"",{sessionId:z,nonce:ne,tokenizedData:Je,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...H?(()=>{let Ae=Nt.current,Zt=_e(H.state,Ae),Qt=_e(H.address_line_1,Ae),Kn=_e(H.postal_code,Ae),Wn=Qt&&!Zt&&Kn?Va(Ae,(Pt.current??"").trim()):null,Mt=Zt?un.current:Wn;return{country:Ae,...Kn&&Pt.current?{zip:Pt.current}:{},..._e(H.city,Ae)&&rn.current?{city:rn.current}:{},...Mt?{state:Mt}:{},...Qt&&Ot.current?{addressLine1:Ot.current}:{},..._e(H.address_line_2,Ae)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:R,avsCheck:G??!1,checkoutType:_,checkoutLayout:V,avsConfig:H?{country:_e(H.country,Nt.current),postal_code:_e(H.postal_code,Nt.current),address_line_1:_e(H.address_line_1,Nt.current),address_line_2:_e(H.address_line_2,Nt.current),city:_e(H.city,Nt.current),state:_e(H.state,Nt.current)}:void 0});if(xt.ok){ir(z),Ke("success"),qt(null),await new Promise(Ae=>setTimeout(Ae,Tn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:Z,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Qe=await xt.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let Ae=Qe.threeDSecureToken,Zt=Qe.paymentMethodId||o.id||"";if(!ze||!Ae){Ke("error"),W("PayPal authorization required but no token provided.");return}try{let Qt=je?.getRawProvider();if(!Qt){W("PayPal is not available.");return}let Kn={return_url:window.location.href};Zt&&(Kn.payment_method=Zt);let{error:Wn}=await Qt.confirmPayment({clientSecret:Ae,confirmParams:Kn,redirect:"if_required"});if(Wn){Ke("error");let Mt=Wn.message??"PayPal payment failed.";W(Mt),fe("paypal",Mt,{code:Wn.code})}}catch(Qt){Ke("error"),W(Qt instanceof Error?Qt.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let Ae=Qe.orderId;if(!Ae){Ke("error"),W("PayPal retry required but no order id provided.");return}let Zt=I.current?.attempts??0;if(Zt>=2){Ke("error"),W("PayPal payment could not be completed after multiple attempts."),fe("paypal","paypal_direct_required retry limit exceeded");return}go(!1),ho("loading"),qt({orderId:Ae,attempts:Zt+1}),Ke(null);return}Ke("error");let Tt=Qe?.message??"Payment failed. Please try again.";W(Tt),fe(o.isPaypal?"paypal":"card",Tt,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(Ae=>setTimeout(Ae,bn))}catch(St){Ke("error"),W(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(xt=>setTimeout(xt,bn))}finally{It(!1),Ke(null),Wt.current=!1}},[Ge,e,t,te,jt,R,ze,je,a,c,W,fe]),Xt=ge((o,v)=>{w?w(o):ga(o,v)},[w,ga]),ha=Ne(!1);mt(()=>{if(typeof window>"u"||ha.current)return;let o=new URLSearchParams(window.location.search),v=o.get("payment_intent"),z=o.get("payment_intent_client_secret"),ne=o.get("redirect_status");if(!v||!z)return;let L=Tt=>{let Ae=localStorage.getItem(Tt);if(!Ae)return null;try{return JSON.parse(Ae)}catch{return localStorage.removeItem(Tt),null}},Z=L(wn)??L(Wa),Je;if(Z?.clientSecret){if(Z.clientSecret!==z)return;Je={...Z.accountPatch?{accountPatch:Z.accountPatch}:{},...Z.sessionId?{sessionId:Z.sessionId}:{},...Z.nonce?{nonce:Z.nonce}:{}}}else if(Z?.sessionId&&Z.sessionId!==e)return;ha.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Wa);let St=new URL(window.location.href);St.searchParams.delete("payment_intent"),St.searchParams.delete("payment_intent_client_secret"),St.searchParams.delete("redirect_status"),window.history.replaceState({},"",St.toString());let xt=Z?.paymentMethodType??Z?.tokenType??"card",Qe="card";(async()=>{let Tt=ze?.getRawProvider();if(!Tt){let Mt="Payment is not available \u2014 please refresh and try again.";W(Mt),fe(Qe,Mt);return}if(ne==="failed"){let Mt="Payment was declined. Please try again.";W(Mt),fe(Qe,Mt);return}let{paymentIntent:Ae,error:Zt}=await Tt.retrievePaymentIntent(z);if(Zt){let Mt=Zt.message??"Failed to retrieve payment status.";W(Mt),fe(Qe,Mt,{code:Zt.code});return}let Qt=Ae?.status,Kn=Jr(Qt);if(!Ae||!Kn){let Mt=Qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";W(Mt),fe(Qe,Mt,{code:Qt??"missing_payment_intent"});return}let Wn=typeof Ae.payment_method=="string"?Ae.payment_method:Ae.payment_method?.id;Xt({id:Wn??Z?.paymentMethodId??Z?.tokenId??Ae.id,type:"card",threeDSecureActionResultTokenId:Ae.id,gateway:Z?.gateway??"stripe",paymentMethodType:xt},Je)})()},[e,Xt,ze,W,fe]);let Po=ge(o=>{o.preventDefault()},[]);if(!(ze!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Sr=re==="buttons",Vt=O?.variables,Mi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),bo=Vt?.colorBackground,Bi=bo&&!Mi.has(bo)?bo:void 0,kr=u.cardInputBorder??(Sr?"#e5e7eb":"#A4A4FF"),vo=Vt?.colorDanger??"#dc2626",jn=o=>Fn&&o?vo:kr,jr=(st.malformed||st.empty)&&(qn||Fn),Ai=jr?vo:jn(Ee.zip),Co=u.cardFormContainer?.backgroundColor??Bi??(Sr?"white":"#EDEDFF"),Rr=u.cardInputBackground??Vt?.colorBackground??"white",wo=er(j),Pa=er(oe),Qn=u.nameInput,ba=u.cardInputFontSize??Fs(Qn?.fontSize)??Vt?.fontSizeBase??"16px",va=typeof Qn?.fontFamily=="string"?Qn.fontFamily:Vt?.fontFamily??"Poppins, sans-serif",Ca=Ja(Qn?.fontWeight)??400,Fi=u.cardInputColor??(typeof Qn?.color=="string"?Qn.color:void 0)??Vt?.colorText??"#262833",Di=u.cardInputPlaceholderColor??"#9ca3af",ft=Vt?.borderRadius??"8px",Vn=Vt?.borderRadius??u.cardButton?.borderRadius??ft,Hn=Vt?.colorPrimary??"#4A49FF",Li=Vt?.colorPrimaryHover??no(Hn,.12),So=Vt?.colorText??"#262833",wa={fontSize:ba,fontFamily:va,fontWeight:Ca,color:Fi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ni={"--flopay-input-placeholder-color":Di,"--flopay-input-font-size":ba,"--flopay-input-font-family":va,"--flopay-input-font-weight":String(Ca)},Ir=u.cardFormContainer??{},ko=Ir.padding??(Sr?"0":"1rem"),Ro=Ir.borderRadius??ft,Oi=Ie&&Ut?d(_o,{capture:Ie,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:b,onReady:()=>{if(!H||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let v=0,z=window.setInterval(()=>{v+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(z)):v>=50&&window.clearInterval(z)},100)},onError:o=>W(o),onValidation:o=>{W(o),o&&Ke(null)}}):d("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"}),Sa=xe("div",{style:{backgroundColor:Co,borderRadius:Ro,...Ir,padding:ko,...Ni,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
30
|
+
`,ro=44;function qo(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 xs={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ni={width:"100%",minHeight:ro,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 Ts(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ya(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ri(e){return e==="paypal"?"PayPal":dr(e)}function Ms(e,t){let n=`We couldn't open ${ri(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function oi(e){let t=Ne(0),n=Ne(null),i=Ne(null),r=ge((l=i.current)=>{let f=l;f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),a=ge((l,f)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(l),l.timer=setTimeout(()=>{l.timer=null,i.current?.generation===l.generation&&(i.current=null,n.current=l.generation,e(l.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},f))},[r,e]),c=ge(l=>{l.yieldedControl&&a(l,600)},[a]),s=ge(l=>{r();let f=t.current+1;t.current=f,n.current=null;let S={generation:f,method:l,timer:null,yieldedControl:!1};return i.current=S,f},[r]),w=ge(l=>{let f=i.current;return typeof l=="number"&&f?.generation!==l?!1:(r(f),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[r]),M=ge(l=>{let f=i.current,S=l??f?.generation??t.current;(!l||f?.generation===l)&&(r(f),i.current=null),n.current=S},[r]),p=ge(l=>n.current===(l??t.current),[]),R=ge(l=>i.current?.generation===l&&n.current!==l,[]),C=ge(()=>{let l=i.current;l&&c(l)},[c]),E=ge(()=>{let l=i.current;l&&(l.yieldedControl=!0,r(l))},[r]);return mt(()=>{let l=()=>{document.visibilityState==="visible"?C():E()},f=()=>{E()};return document.addEventListener("visibilitychange",l),window.addEventListener("blur",f),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("blur",f),window.removeEventListener("focus",C),r()}},[r,E,C]),{startAttempt:s,finishAttempt:w,invalidateAttempt:M,isAttemptInvalidated:p,isAttemptCurrent:R}}function Bs(e){let t=Ps(e);return`Enter a valid ${Oo(e)}${t?` (e.g. ${t})`:""}`}function As(e,t,n){let i=gs(e),r=t.trim(),a=n&&i,c=a&&!r,s=a&&!!r&&!hs(e,r);return{visible:n,supported:i,required:a,empty:c,malformed:s}}function Ga(e,t){return t instanceof Cn?t:new Cn(t instanceof Error?t.message:`${Ts(e)} before-click hook failed.`,"validation_error")}function No(){return d("style",{children:_s})}function Fs(e){return typeof e=="number"?`${e}px`:e}function Ja(e){if(typeof e=="number"||typeof e=="string")return e}function ai(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function ii({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:xe("div",{style:{position:"relative",minHeight:44},children:[d("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"}}),d("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:i})]})}function Xa(e){return e!=="unavailable"&&e!=="load_error"}function jo(e){return d(Ls,{...e})}function Za({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:w,onTechnicalFailure:M,runBeforeButtonClick:p,onLoadStateChange:R,placeholderBorderRadius:C}){let E=Pn(),l=$o(),f=Uo(),[S,x]=ve("loading");mt(()=>{R?.(S)},[S,R]);let[h,U]=ve(!1),Y=Ne(!1),ce=Ne(null),re=Ne(null),[F,J]=ve(0),[$,de]=ve(!1),q=Ne(!1),j=Ne(new Map),{startAttempt:oe,finishAttempt:Be,invalidateAttempt:me,isAttemptInvalidated:pe,isAttemptCurrent:X}=oi((k,ee,ie)=>{M?.(k,ee,{...ie,popupBlocked:ie?.popupBlocked??Ln(ee)}),de(!0),J(Oe=>Oe+1)});mt(()=>{$&&re.current?.focus()},[$,F]);let ue=ge(()=>{J(k=>k+1)},[]),he=ge((k,ee,ie)=>{me(ie),M?.("paypal",k,{code:ee,popupBlocked:Ln(k)}),de(!0),ue()},[me,M,ue]),ae=ge(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);mt(()=>{q.current&&(q.current=!1,ae())},[ae,F]);let Fe=ge(()=>{de(!1),a?.(null),ae()},[ae,a]);mt(()=>{if(!l||Y.current)return;let k=new URLSearchParams(window.location.search),ee=k.get("payment_intent"),ie=k.get("payment_intent_client_secret"),Oe=k.get("redirect_status");if(!ee||!ie)return;Y.current=!0;let De;try{let _=localStorage.getItem(Ar);if(_){let V=JSON.parse(_);V.clientSecret===ie&&(De={...V.accountPatch?{accountPatch:V.accountPatch}:{},...V.sessionId?{sessionId:V.sessionId}:{},...V.nonce?{nonce:V.nonce}:{}})}}catch{}try{localStorage.removeItem(Ar)}catch{}let G=new URL(window.location.href);G.searchParams.delete("payment_intent"),G.searchParams.delete("payment_intent_client_secret"),G.searchParams.delete("redirect_status"),window.history.replaceState({},"",G.toString()),(async()=>{try{if(U(!0),Oe==="failed"){let se="PayPal payment was declined. Please try again.";a?.(se),w?.(Bt("paypal",se));return}let{paymentIntent:_,error:V}=await l.retrievePaymentIntent(ie);if(V){a?.(V.message??"Failed to retrieve PayPal payment status.");return}if(_&&(_.status==="requires_capture"||_.status==="succeeded")){let se=typeof _.payment_method=="string"?_.payment_method:_.payment_method?.id;r({id:se??_.id,type:"card",threeDSecureActionResultTokenId:_.id,isPaypal:!0},De)}else{let se="PayPal payment was not completed. Please try again.";a?.(se),w?.(Bt("paypal",se))}}catch(_){a?.(_ instanceof Error?_.message:"Failed to complete PayPal payment.")}finally{U(!1)}})()},[l,r,a,w]);let ke=ge(async k=>{if(c||h){k.reject();return}let ee=p?await p("paypal"):{proceed:!0};if(!ee.proceed){j.current.delete(F),k.reject();return}let ie=oe("paypal");j.current.set(F,{generation:ie,accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}),de(!1),s?.("paypal"),k.resolve()},[j,c,s,p,oe,h,F]),Ce=ge(async k=>{if(!l||!f)return;let ee=j.current.get(F);if(ee&&!X(ee.generation)){j.current.delete(F);return}if(!ee&&pe()||ee&&!Be(ee.generation))return;ee||Be();let ie=ee??null;if(j.current.delete(F),!ie&&p){let _=await p("paypal");if(!_.proceed){k.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let Oe=ie?.sessionId??e,De=ie?.nonce??t,G=ie?.accountPatch?.email??n;try{if(U(!0),a?.(null),!Oe||!G)throw new Error("Missing sessionId or email for PayPal payment");let _=l.createPaymentMethod,{error:V,paymentMethod:se}=await _({type:"paypal"});if(V){he(V,"stripe_paypal_create_payment_method_failed",ee?.generation),k.paymentFailed({reason:"fail"});return}let Re=await new Nn(i).createSessionIntent(Oe,De??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:se?.id??null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ht=Re.clientSecret,Ze={return_url:window.location.href};if(se?.id&&(Ze.payment_method=se.id),typeof window<"u")try{localStorage.setItem(Ar,JSON.stringify({clientSecret:ht,sessionId:Oe,nonce:De,accountPatch:ie?.accountPatch}))}catch{}let{error:Xe,paymentIntent:m}=await l.confirmPayment({clientSecret:ht,confirmParams:Ze,redirect:"if_required"});if(Xe){if(typeof window<"u")try{localStorage.removeItem(Ar)}catch{}if(Mr(Xe)){let ze=Xe.message??"Your payment was declined.";a?.(ze),w?.(Bt("paypal",ze,{code:Mn(Xe),declineCode:sr(Xe)})),await oo({billingApiUrl:i,sessionId:Oe,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(Xe)??"provider_declined"}})}else he(Xe,"stripe_paypal_confirm_failed",ee?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ar)}catch{}let $e=typeof m?.payment_method=="string"?m.payment_method:m?.payment_method?.id;r({id:$e??m?.id,type:"card",threeDSecureActionResultTokenId:m?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:Oe,nonce:De});return}catch(_){he(_,"stripe_paypal_failed",ee?.generation)}finally{U(!1)}},[l,f,e,t,n,i,r,a,w,p,he,Be,X,pe,F]);return xe(cr,{children:[d(ii,{state:S,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[$&&d("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Fe,style:ni,children:"Try PayPal again"}),d(ti,{onReady:k=>x(ai(k,["paypal"])),onLoadError:()=>x("load_error"),onClick:ke,onConfirm:Ce,onCancel:()=>{let k=j.current.get(F);j.current.delete(F),Dt(E)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),me(k?.generation),de(!1),q.current=!0,ue()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},F)]})}),h&&d(vn,{status:"processing"})]})}function Qa({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:w,onDecline:M,onTechnicalFailure:p,runBeforeButtonClick:R,onLoadStateChange:C,placeholderBorderRadius:E}){let l=Pn(),f=$o(),S=Uo(),[x,h]=ve("loading");mt(()=>{C?.(x)},[x,C]);let[U,Y]=ve(!1),ce=Ne(null),re=Ne(null),[F,J]=ve(0),[$,de]=ve(!1),[q,j]=ve("google_pay"),oe=Ne(!1),Be=Ne("google_pay"),me=Ne("google_pay"),pe=Ne(new Map),{startAttempt:X,finishAttempt:ue,invalidateAttempt:he,isAttemptInvalidated:ae,isAttemptCurrent:Fe}=oi((G,_,V)=>{p?.(G,_,{...V,popupBlocked:V?.popupBlocked??Ln(_)}),j(G),de(!0),J(se=>se+1)});mt(()=>{$&&re.current?.focus()},[$,F]);let ke=ge(()=>{J(G=>G+1)},[]),Ce=ge((G,_,V,se)=>{he(se),p?.(G,_,{code:V,popupBlocked:Ln(_)}),j(G),de(!0),ke()},[he,p,ke]),k=ge(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);mt(()=>{oe.current&&(oe.current=!1,k())},[k,F]);let ee=ge(()=>{de(!1),s?.(null),k()},[k,s]),ie=ge(async G=>{if(!f||!S)return;let _=pe.current.get(F);if(_&&!Fe(_.generation)){pe.current.delete(F);return}if(!_&&ae()||_&&!ue(_.generation))return;_||ue();let V=G.expressPaymentType??_?.method??Be.current,se=_??null;pe.current.delete(F);let Re=Ya(V);if(!se&&R){let $e=await R(Re);if(!$e.proceed){G.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}se={accountPatch:$e.accountPatch,sessionId:$e.sessionId,nonce:$e.nonce}}let ht=Re,Ze=se?.sessionId??e,Xe=se?.nonce??t,m=se?.accountPatch?.email??n;try{Y(!0),s?.(null);let{error:$e}=await S.submit();if($e){Ce(V,$e,"stripe_wallet_submit_failed",_?.generation);return}let{error:ze,paymentMethod:je}=await f.createPaymentMethod({elements:S});if(ze||!je){Ce(V,ze??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",_?.generation);return}if(!Ze||!m)throw new Error("Missing sessionId or email for wallet payment");let Ve=await new Nn(i).createSessionIntent(Ze,Xe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V??Re,paymentMethodId:je.id,intentKind:r});if(Ve.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Yt=Ve.clientSecret,{error:vt,intentId:It}=Rs(Yt)?await f.confirmCardSetup(Yt,{payment_method:je.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await f.confirmCardPayment(Yt,{payment_method:je.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(vt){if(Mr(vt)){let g=vt.message??"Your payment was declined.";s?.(g),M?.(Bt(ht,g,{code:Mn(vt),declineCode:sr(vt)})),await oo({billingApiUrl:i,sessionId:Ze,nonce:Xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V??Re,providerDeclineReason:Mn(vt)??"provider_declined"}})}else Ce(V,vt,"stripe_wallet_confirm_failed",_?.generation);return}c({id:je.id,type:"card",threeDSecureActionResultTokenId:It},{accountPatch:se?.accountPatch,sessionId:Ze,nonce:Xe})}catch($e){Ce(V,$e,"stripe_wallet_failed",_?.generation)}finally{Y(!1)}},[f,S,e,t,n,i,r,c,s,M,R,Ce,ue,Fe,ae,F]),Oe=pt(()=>{let G=["applePay","googlePay","paypal","link","amazonPay","klarna"],_=new Set(["applePay","googlePay"]),V=new Set(a.map(Ka)),se={};for(let Re of G)V.has(Re)?se[Re]=_.has(Re)?"always":"auto":se[Re]="never";return se},[a]),De=pt(()=>a.map(Ka),[a]);return xe(cr,{children:[d(ii,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:E,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[$&&xe("button",{ref:re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ee,style:ni,children:["Try ",ri(q)," again"]}),d(ti,{onReady:G=>{h(ai(G,De))},onLoadError:G=>{h("load_error"),Dt(l)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk"})},onClick:async G=>{Be.current=G.expressPaymentType,me.current=Ya(G.expressPaymentType);let _=R?await R(me.current):{proceed:!0};if(!_.proceed){pe.current.delete(F),G.reject();return}let V=X(G.expressPaymentType);pe.current.set(F,{generation:V,method:G.expressPaymentType,accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}),de(!1),w?.(me.current),G.resolve()},onConfirm:ie,onCancel:()=>{let G=pe.current.get(F);pe.current.delete(F),Dt(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),he(G?.generation),de(!1),oe.current=!0,ke()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Oe,layout:{maxColumns:1,overflow:"never"}}},F)]})}),U&&d(vn,{status:"processing"})]})}function Ds({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:w,textColor:M,borderRadius:p,fontFamily:R}){let C=Cs(e,t),E=Ma[e],l=C?.backgroundColor??s??"#ffffff",f=C?.borderColor??w??"#d1d5db",S=C?.textColor??M??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&c()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ro,padding:"0 1rem",backgroundColor:l,color:S,border:`1px solid ${f}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||i?"not-allowed":"pointer",opacity:i&&!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:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${dr(e)}\u2026`}):xe(cr,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:vs(e)?8:0},children:[E?d("img",{src:E,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):C?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,d("span",{children:dr(e)})]}),a&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:S,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:d("path",{d:"M9 18l6-6-6-6"})})]})})}function zo({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:a,onTokenizedBody:c,onErrorChange:s,onDecline:w,onCancel:M,runBeforeButtonClick:p,onButtonClick:R,isProcessing:C,submitButtonColor:E,submitButtonBorderRadius:l,submitButtonStyle:f,errorText:S}){let x=Pn(),h=$o(),U=Uo(),[Y,ce]=ve(!1),re=Ne(!1),[F,J]=ve(!1),[$,de]=ve("loading"),q=ge(async()=>{if(!h||!U||C||re.current||!F)return;re.current=!0,ce(!0);let j=p?await p("card"):{proceed:!0};if(!j.proceed){re.current=!1,ce(!1);return}R?.("card");let oe=j.sessionId??t,Be=j.nonce??n,me=j.accountPatch?.email??i;try{s?.(null);let pe=await U.submit();if(pe.error){s?.(pe.error.message??"Payment failed.");return}let X=await h.createPaymentMethod({elements:U});if(X.error||!X.paymentMethod){s?.(X.error?.message??"Failed to create payment method.");return}let ue=X.paymentMethod;if(!oe||!me)throw new Error("Missing sessionId or email for payment.");let he=ue.type||e,ae=await new Nn(a).createSessionIntent(oe,Be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:he,paymentMethodId:null,intentKind:"payment"});if(ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Fe=ae.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Fe,sessionId:oe,nonce:Be,accountPatch:j.accountPatch,paymentMethodId:ue.id,paymentMethodType:ue.type??e,gateway:"stripe"}))}catch{}let{error:ke,paymentIntent:Ce}=await h.confirmPayment({clientSecret:Fe,confirmParams:{return_url:window.location.href,payment_method:ue.id},redirect:"if_required"});if(ke){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ie=ke.message??"Payment failed.";s?.(ie),w?.(Bt("card",ie,{code:ke.code})),await oo({billingApiUrl:a,sessionId:oe,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ke.code??"provider_declined"}});return}let k=Ce?.status;if(!Jr(k)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ie=k==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(ie),w?.(Bt("card",ie,{code:k??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ee=typeof Ce?.payment_method=="string"?Ce.payment_method:Ce?.payment_method?.id;c({id:ee??ue.id,type:"card",threeDSecureActionResultTokenId:Ce?.id,gateway:"stripe",paymentMethodType:ue.type??e},{accountPatch:j.accountPatch,sessionId:oe,nonce:Be})}catch(pe){s?.(pe instanceof Error?pe.message:"Payment failed. Please try again.")}finally{re.current=!1,ce(!1)}},[h,U,C,F,p,R,t,n,i,a,e,c,s,w]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(us,{onReady:()=>de("ready"),onLoadError:()=>{de("load_error"),Dt(x)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"apm",requestCategory:"provider_sdk"})},onChange:j=>{J(!!j.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...i?{email:i}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{q()},disabled:!F||Y||C||$!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:E,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!F||Y||C||$!=="ready"?"not-allowed":"pointer",opacity:!F||Y||C||$!=="ready"?.5:1,transition:"opacity 120ms ease-out",...f??{}},children:Y?"Processing\u2026":`Pay with ${dr(e)}`}),S&&d(or,{margin:"0.75rem 0 0",children:S})]})}function ei({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:w,onErrorChange:M,onButtonClick:p,onDecline:R,runBeforeButtonClick:C,onLoadStateChange:E,isProcessing:l=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:S=8,submitButtonStyle:x,buttonAppearance:h,themeId:U,onExpandApm:Y,expandedApmMethod:ce}){let[re,F]=ve(null),[J,$]=ve(null),de=Ne(!1);mt(()=>{a.length>0&&c?E?.("ready"):c||E?.("loading")},[a.length,c,E]);let q=ge(async X=>{if(!c||de.current||l)return;de.current=!0,$(X);let ue=C?await C("card"):{proceed:!0};if(!ue.proceed){de.current=!1,$(null);return}p?.("card");let he=ue.sessionId??e,ae=ue.nonce??t,Fe=ue.accountPatch?.email??n;try{if(M?.(null),!he||!Fe)throw new Error("Missing sessionId or email for payment.");let ke=await new Nn(r).createSessionIntent(he,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ce=ke.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ce,sessionId:he,nonce:ae,accountPatch:ue.accountPatch,paymentMethodType:X,gateway:"stripe"}))}catch{}let{error:k,paymentIntent:ee}=await c.confirmPayment({clientSecret:Ce,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...Fe?{email:Fe}:{}}}},redirect:"if_required"});if(k){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let De=k.message??"Payment failed.";M?.(De),R?.(Bt("card",De,{code:k.code})),await oo({billingApiUrl:r,sessionId:he,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:k.code??"provider_declined"}});return}let ie=ee?.status;if(!Jr(ie)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let De=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";M?.(De),R?.(Bt("card",De,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Oe=typeof ee?.payment_method=="string"?ee.payment_method:ee?.payment_method?.id;w({id:Oe??ee?.id,type:"card",threeDSecureActionResultTokenId:ee?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:ue.accountPatch,sessionId:he,nonce:ae})}catch(ke){M?.(ke instanceof Error?ke.message:"Payment failed. Please try again.")}finally{de.current=!1,$(null)}},[c,l,C,p,e,t,n,r,i,w,M,R]),[j,oe]=ve(null),Be=Y?ce??null:j,me=ge(X=>{de.current||l||Be&&Be!==X||(Ha(X)?Y?Y(X):oe(X):q(X))},[Be,l,q,Y]),pe=pt(()=>j?{...s,paymentMethodTypes:[j]}:null,[j,s]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(X=>{let ue=ce===X,he=J===X,ae=J!==null&&J!==X||ce!=null&&ce!==X;return xe(Ss.Fragment,{children:[d(Ds,{method:X,themeId:U,submitting:he,disabled:ae,highlighted:ue,hasNextStep:Ha(X),onClick:()=>me(X),backgroundColor:h?.backgroundColor,borderColor:h?.borderColor,textColor:h?.textColor,borderRadius:h?.borderRadius,fontFamily:h?.fontFamily}),!Y&&j===X&&pe&&c&&d(Jn,{stripe:c,options:pe,children:d(zo,{method:X,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:w,onErrorChange:M,onDecline:R,onCancel:()=>oe(null),runBeforeButtonClick:C,onButtonClick:p,isProcessing:l,submitButtonColor:f,submitButtonBorderRadius:S,submitButtonStyle:x})},X)]},X)})})}function Ls({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:c,onDecline:s,onTokenizedBody:w,firstName:M,lastName:p,chv:R,className:C,isProcessing:E,error:l,onErrorChange:f,showPayPal:S=!0,showStripe:x=!0,enabledPaymentMethods:h,enabledPaymentMethodCountries:U,showApplePay:Y=!0,showGooglePay:ce=!0,layout:re="default",theme:F,buttonsTheme:J,buttonsStyles:$,appearance:de,cardButtonContent:q,cardBackButtonContent:j,cardTitleContent:oe,showSecurityFooter:Be,onButtonClick:me,onBeforeButtonClick:pe,enableAVS:X,cardFieldOrder:ue,cardPreFormSlot:he,avsLayout:ae="row",country:Fe,zip:ke,addressLine1:Ce,addressLine2:k,city:ee,state:ie,onCountryChange:Oe,onZipChange:De,avsCheck:G,checkoutType:_,checkoutLayout:V,totalAmount:se=0,currency:Re="usd",initialCardOpen:ht=!1,directPaypal:Ze,isSubscription:Xe=!1,session:m,debug:$e=!1}){let ze=Pn(),je=xo(),Ve=ks(ln),Yt=Gr(),[vt,It]=ve(!1),[g,we]=ve(null),[qe,it]=ve(Fe??"US"),[et,tt]=ve(ke??""),[Ye,Pe]=ve(Ce??""),[Ct,He]=ve(k??""),[Lt,Et]=ve(ee??""),[dn,Rn]=ve(ie??""),[In,$n]=ve({}),Pt=Ne(ke??""),Nt=Ne(Fe??"US"),Ot=Ne(Ce??""),Gt=Ne(k??""),rn=Ne(ee??""),un=Ne(ie??""),H=pt(()=>fs(X),[X]),An=H!==null,pn=!!m?.vault?.html,zt=!!m?.gateways?.pcivault,nt=pn||zt,y=!!(x&&nt&&ze&&e),Ie=pt(()=>!ze||!y||!e?null:ze.cardCapture({sessionId:e}),[ze,y,e]),st=pt(()=>{let o=qe,v=H?_e(H.postal_code,o):!1;return As(o,et,v)},[H,qe,et]),{avsInvalid:En,invalidAvsFields:Ee}=pt(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!y||!H)return{avsInvalid:!1,invalidAvsFields:o};let v=qe,z=(Z,Je)=>_e(Z,v)&&!Je.trim(),ne={line1:z(H.address_line_1,Ye),city:z(H.city,Lt),state:z(H.state,dn),zip:st.empty||st.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[y,H,qe,Ye,Lt,dn,st]),[Fn,mn]=ve(!1),[qn,yn]=ve(!1),[Ut,Ft]=ve(()=>Lo(m?.vault)),[Se,yt]=ve(ht&&nt?"card":"buttons"),[rt,on]=ve(null),Jt=Se==="expanding"||Se==="card",bt=280,Ht=Ne(null),wt=ge(o=>{Ht.current&&clearTimeout(Ht.current),Ht.current=setTimeout(()=>{Ht.current=null,o()},bt)},[bt]);mt(()=>()=>{Ht.current&&clearTimeout(Ht.current)},[]);let an=ge(()=>{yt("expanding"),wt(()=>yt("card"))},[wt]),fn=ge(()=>{yt("collapsing"),wt(()=>yt("buttons"))},[wt]),_n=ge(o=>{on(o),yt("apm-expanding"),wt(()=>yt("apm-form"))},[wt]),gn=ge(()=>{yt("apm-collapsing"),wt(()=>{yt("buttons"),on(null)})},[wt]);mt(()=>{re==="buttons"&&ht&&nt&&yt("card")},[re,ht,nt]);let[Kt,Ke]=ve(null),Wt=Ne(!1),[$t,qt]=ve(null),I=Ne($t);mt(()=>{I.current=$t},[$t]);let D=n||Yt,N=l??g,T=pt(()=>Is(F),[F]),u=pt(()=>{let o=T?.buttonsLayout??ps(J);return $?{...o,...$,cardButton:{...o.cardButton,...$.cardButton},cardFormContainer:{...o.cardFormContainer,...$.cardFormContainer},backButton:{...o.backButton,...$.backButton},backButtonIcon:{...o.backButtonIcon,...$.backButtonIcon},submitButton:{...o.submitButton,...$.submitButton},title:{...o.title,...$.title}}:o},[T,J,$]),O=de??T?.appearance,b=pt(()=>{let o=O?.variables,v=Je=>typeof Je=="string"&&Je?Je:void 0,z=u.submitButton,ne=v(o?.colorPrimary)??v(z?.backgroundColor)??"#4A49FF",L=re==="buttons",Z=u.nameInput;return{primaryColor:ne,primaryHoverColor:v(o?.colorPrimaryHover)??no(ne,.12),inputBackgroundColor:v(u.cardInputBackground)??v(o?.colorBackground)??"#ffffff",textColor:v(u.cardInputColor)??v(Z?.color)??v(o?.colorText)??"#262833",borderColor:v(u.cardInputBorder)??(L?"#e5e7eb":"#A4A4FF"),placeholderColor:v(u.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(Z?.fontFamily)??v(o?.fontFamily)??"Poppins, sans-serif",fontSize:v(u.cardInputFontSize)??v(o?.fontSizeBase)??"16px",fontWeight:String(Ja(Z?.fontWeight)??400),borderRadius:v(o?.borderRadius)??"8px"}},[O,u,re]),Te=Ve.inlineSessionPatchProcessing??!1,K=(E??vt)||Te,Ge=D.replace(/\/+$/,""),te=pt(()=>Bo({userId:r,email:i,firstName:M,lastName:p,country:Fe,zip:ke},In),[r,i,M,p,Fe,ke,In]),jt=[te.firstName,te.lastName].filter(o=>!!o?.trim()).join(" "),ot=pt(()=>ze?ze.getRawProvider():null,[ze]),B=pt(()=>je?je.getRawProvider():null,[je]),P=se||100,A=O?{appearance:O}:null,ye=pt(()=>{let o=O??{},v=o.rules??{};return{...o,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[O]),Me=pt(()=>{let o=Da(se);return{...o,currency:Re.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...A}},[se,Re,A]),Ue=pt(()=>({mode:"payment",amount:P,currency:Re.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...A}),[P,Re,A]),W=ge(o=>{we(o),f?.(o)},[f]);mt(()=>{!y||!Ie||Ie.setCardFieldOrder?.(ue??null,H==null)},[y,Ie,ue,H]),mt(()=>{(Se==="expanding"||Se==="collapsing"||Se==="apm-expanding"||Se==="apm-collapsing")&&W(null)},[Se,W]);let fe=ge((o,v,z)=>{s?.(Bt(o,v,z))},[s]),be=ge((o,v,z)=>{let ne=z?.popupBlocked??Ln(v),L=Ms(o,ne),Z=Yn(z?.code)??Mn(v)??"external_payment_method_failed",Je=new Cn(L,"api_error",{code:"external_payment_method_failed",param:o});Ke(null),re==="buttons"&&(yt("buttons"),on(null)),W(L),c?.(Je),console.error("[FloPay] External payment method failed:",{method:o,code:Z,popupBlocked:ne})},[re,c,W]);mt(()=>{if(!y||!e){Ft(null);return}let o=Lo(m?.vault);if(o){Ft(o);return}Ft(null);let v=!0;return new Nn(Ge).getVaultCapture(e,t).then(z=>{if(!v)return;let ne=Lo(z);ne?Ft(ne):W("Failed to load the secure card form.")}).catch(z=>{v&&W(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{v=!1}},[y,e,m?.vault?.html,m?.vault?.messageToken,m?.vault?.expectedOrigin,Ge,t,W]);let le=Ne({onComplete:a,onError:c,updateError:W,emitDecline:fe,resolvedAccount:te,avsConfig:H,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ge});le.current={onComplete:a,onError:c,updateError:W,emitDecline:fe,resolvedAccount:te,avsConfig:H,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ge};let Le=Ne(!1),hn=ge(()=>{let{resolvedAccount:o,avsConfig:v,avsCheckProp:z}=le.current,ne=Nt.current||o.country||"US",L=v?_e(v.state,ne):!1,Z=v?_e(v.address_line_1,ne):!1,Je=v?_e(v.postal_code,ne):!1,St=v?_e(v.city,ne):!1,xt=v?_e(v.address_line_2,ne):!1,Qe=Z&&!L&&Je?Va(ne,(Pt.current??"").trim()):null,Tt=L?un.current:Qe;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Je&&Pt.current?{zip:Pt.current}:{},...St&&rn.current?{city:rn.current}:{},...Tt?{state:Tt}:{},...Z&&Ot.current?{addressLine1:Ot.current}:{},...xt&&Gt.current?{addressLine2:Gt.current}:{},country:ne},...z!==void 0?{avsCheck:z}:{},...v?{avsConfig:{country:_e(v.country,ne),postal_code:Je,address_line_1:Z,address_line_2:xt,city:St,state:L}}:{}}},[]);mt(()=>{!y||!Ie||Ie.setSubmitGate?.(En)},[y,Ie,En]),mt(()=>{if(!y||!Ie)return;Le.current=!1;let o=!1,v=Ie.on("submitting",()=>{mn(!0),Ke("processing");let{baseUrl:Z,sessionId:Je,nonce:St,updateError:xt,onError:Qe}=le.current;!Je||!St||new Nn(Z).patchAccountSnapshot(Je,St,hn(),{telemetryMode:"best_effort"}).catch(Tt=>{if(!Es(Tt))return;let Ae=Tt instanceof Error?Tt.message:"Please check your billing address and try again.";xt(Ae),Ke(null),Qe?.(Tt instanceof Cn?Tt:new Cn(Ae,"api_error"))})}),z=Ie.on("complete",async Z=>{ir(Z.sessionId??le.current.sessionId),Ke("success"),await new Promise(Je=>setTimeout(Je,Tn)),!Le.current&&(Le.current=!0,le.current.onComplete?.({status:"succeeded",paymentIntentId:Z.intentId,checkoutMethod:"card"}))}),ne=Ie.on("decline",async Z=>{let{updateError:Je,emitDecline:St}=le.current,xt=Z.message??"Your payment was declined. Please try another card or contact your bank.";Je(xt),Ke("error"),St("card",xt,Z.declineReason?{declineCode:Z.declineReason}:void 0),await new Promise(Qe=>setTimeout(Qe,bn)),!o&&Ke(null)}),L=Ie.on("error",async Z=>{let{updateError:Je,onError:St}=le.current,xt=Z.message??"There was a problem processing your payment. Please try again.";Je(xt),Ke("error"),St?.(new Cn(xt,"api_error")),await new Promise(Qe=>setTimeout(Qe,bn)),!o&&Ke(null)});return()=>{o=!0,v(),z(),ne(),L()}},[y,Ie]);let lt=!!Ze?.clientId,_t=Array.isArray(h),Nr=_t&&h.length>0,wi=_t&&h.includes("paypal"),{expressMethods:Or,paymentElementMethods:Pr}=pt(()=>ws(h,{excludePaypal:lt}),[h,lt]),ta=lt||!!je,Si=pt(()=>ta?Or.filter(o=>o!=="paypal"):Or,[Or,ta]),ki=pt(()=>{let o=[];return Y&&o.push("apple_pay"),ce&&o.push("google_pay"),o},[Y,ce]),zr=_t?Si:ki,Ri=x&&zr.length>0,yo=An?qe:Fe,Ur=pt(()=>{let o=yo?.trim().toUpperCase();return o?U?Pr.filter(v=>{let z=U[v];return!z||z.length===0||z.includes(o)}):bs(Pr,yo):Pr},[Pr,yo,U]),fo=pt(()=>({mode:"payment",amount:P,currency:Re.toLowerCase(),paymentMethodCreation:"manual",appearance:ye}),[P,Re,ye]),[na,ra]=ve("loading"),[oa,aa]=ve("loading"),[ia,sa]=ve("loading"),[Ii,go]=ve(!1),[la,ho]=ve("loading"),[$r,Ei]=ve();mt(()=>{Ei(Na())},[]);let ca=S&&(lt||(_t?wi:$r===!1)),da=x&&Ri,br=ca&<,ua=la==="retrying"||la==="exhausted",vr=ca&&!!B&&(!lt||ua),Cr=da&&!!ot,wr=x&&Nr&&Ur.length>0&&!!ot,_i=br&&!ua?Ii:vr&&Xa(na),xi=Cr&&Xa(oa),Ti=wr&&ia!=="load_error",pa=o=>o==="loading"||o==="ready",ma=br||vr&&pa(na)||Cr&&pa(oa)||wr&&ia!=="load_error",qr=Ne(!1);mt(()=>{if(!qr.current){if(!x&&!S){qr.current=!0;let o=new Cn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(o),W(o.message)}else if(!x&&S&&!lt&&!B){qr.current=!0;let o=new Cn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(o),W(o.message)}else if($r!==void 0&&!nt&&!ma){qr.current=!0;let o=new Cn("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"});c?.(o),W(o.message)}}},[x,S,lt,B,$r,nt,ma,c,W]);let ya=Ne(!1);mt(()=>{if(ya.current||!Nr)return;let o=[];Y!==!0&&o.push("showApplePay"),ce!==!0&&o.push("showGooglePay"),o.length!==0&&(ya.current=!0,console.warn(`[FloPay] ${o.join(" / ")} ${o.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.`))},[Nr,Y,ce]);let fa=ge((o,v)=>Ve.applyInlineSessionPatch?Ve.applyInlineSessionPatch(o).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let ne=Ga(v,z);return W(ne.message),c?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ve.applyInlineSessionPatch,t,c,e,W]),sn=ge(async o=>{if(!pe)return{proceed:!0};try{let v=await pe({method:o,sessionId:e||void 0,createSession:Ve.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&$n(ne=>({...ne??{},...v.account}));let z=await fa(v,o);return z.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(v){let z=Ga(o,v);return W(z.message),c?.(z),{proceed:!1}}},[fa,Ve.inlineSessionDraft,pe,c,e,W]),ga=ge(async(o,v)=>{if(Wt.current)return;Wt.current=!0,It(!0),Ke("processing"),W(null);let z=v?.sessionId??e,ne=v?.nonce??t,L=Bo(te,v?.accountPatch),Z=v?.completionPaymentMethodId??Xr(o),Je=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let xt=await new Nn(Ge).processPayment(L.userId??"",{sessionId:z,nonce:ne,tokenizedData:Je,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...H?(()=>{let Ae=Nt.current,Zt=_e(H.state,Ae),Qt=_e(H.address_line_1,Ae),Kn=_e(H.postal_code,Ae),Wn=Qt&&!Zt&&Kn?Va(Ae,(Pt.current??"").trim()):null,Mt=Zt?un.current:Wn;return{country:Ae,...Kn&&Pt.current?{zip:Pt.current}:{},..._e(H.city,Ae)&&rn.current?{city:rn.current}:{},...Mt?{state:Mt}:{},...Qt&&Ot.current?{addressLine1:Ot.current}:{},..._e(H.address_line_2,Ae)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:R,avsCheck:G??!1,checkoutType:_,checkoutLayout:V,avsConfig:H?{country:_e(H.country,Nt.current),postal_code:_e(H.postal_code,Nt.current),address_line_1:_e(H.address_line_1,Nt.current),address_line_2:_e(H.address_line_2,Nt.current),city:_e(H.city,Nt.current),state:_e(H.state,Nt.current)}:void 0});if(xt.ok){ir(z),Ke("success"),qt(null),await new Promise(Ae=>setTimeout(Ae,Tn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:Z,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Qe=await xt.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let Ae=Qe.threeDSecureToken,Zt=Qe.paymentMethodId||o.id||"";if(!ze||!Ae){Ke("error"),W("PayPal authorization required but no token provided.");return}try{let Qt=je?.getRawProvider();if(!Qt){W("PayPal is not available.");return}let Kn={return_url:window.location.href};Zt&&(Kn.payment_method=Zt);let{error:Wn}=await Qt.confirmPayment({clientSecret:Ae,confirmParams:Kn,redirect:"if_required"});if(Wn){Ke("error");let Mt=Wn.message??"PayPal payment failed.";W(Mt),fe("paypal",Mt,{code:Wn.code})}}catch(Qt){Ke("error"),W(Qt instanceof Error?Qt.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let Ae=Qe.orderId;if(!Ae){Ke("error"),W("PayPal retry required but no order id provided.");return}let Zt=I.current?.attempts??0;if(Zt>=2){Ke("error"),W("PayPal payment could not be completed after multiple attempts."),fe("paypal","paypal_direct_required retry limit exceeded");return}go(!1),ho("loading"),qt({orderId:Ae,attempts:Zt+1}),Ke(null);return}Ke("error");let Tt=Qe?.message??"Payment failed. Please try again.";W(Tt),fe(o.isPaypal?"paypal":"card",Tt,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(Ae=>setTimeout(Ae,bn))}catch(St){Ke("error"),W(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(xt=>setTimeout(xt,bn))}finally{It(!1),Ke(null),Wt.current=!1}},[Ge,e,t,te,jt,R,ze,je,a,c,W,fe]),Xt=ge((o,v)=>{w?w(o):ga(o,v)},[w,ga]),ha=Ne(!1);mt(()=>{if(typeof window>"u"||ha.current)return;let o=new URLSearchParams(window.location.search),v=o.get("payment_intent"),z=o.get("payment_intent_client_secret"),ne=o.get("redirect_status");if(!v||!z)return;let L=Tt=>{let Ae=localStorage.getItem(Tt);if(!Ae)return null;try{return JSON.parse(Ae)}catch{return localStorage.removeItem(Tt),null}},Z=L(wn)??L(Wa),Je;if(Z?.clientSecret){if(Z.clientSecret!==z)return;Je={...Z.accountPatch?{accountPatch:Z.accountPatch}:{},...Z.sessionId?{sessionId:Z.sessionId}:{},...Z.nonce?{nonce:Z.nonce}:{}}}else if(Z?.sessionId&&Z.sessionId!==e)return;ha.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Wa);let St=new URL(window.location.href);St.searchParams.delete("payment_intent"),St.searchParams.delete("payment_intent_client_secret"),St.searchParams.delete("redirect_status"),window.history.replaceState({},"",St.toString());let xt=Z?.paymentMethodType??Z?.tokenType??"card",Qe="card";(async()=>{let Tt=ze?.getRawProvider();if(!Tt){let Mt="Payment is not available \u2014 please refresh and try again.";W(Mt),fe(Qe,Mt);return}if(ne==="failed"){let Mt="Payment was declined. Please try again.";W(Mt),fe(Qe,Mt);return}let{paymentIntent:Ae,error:Zt}=await Tt.retrievePaymentIntent(z);if(Zt){let Mt=Zt.message??"Failed to retrieve payment status.";W(Mt),fe(Qe,Mt,{code:Zt.code});return}let Qt=Ae?.status,Kn=Jr(Qt);if(!Ae||!Kn){let Mt=Qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";W(Mt),fe(Qe,Mt,{code:Qt??"missing_payment_intent"});return}let Wn=typeof Ae.payment_method=="string"?Ae.payment_method:Ae.payment_method?.id;Xt({id:Wn??Z?.paymentMethodId??Z?.tokenId??Ae.id,type:"card",threeDSecureActionResultTokenId:Ae.id,gateway:Z?.gateway??"stripe",paymentMethodType:xt},Je)})()},[e,Xt,ze,W,fe]);let Po=ge(o=>{o.preventDefault()},[]);if(!(ze!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Sr=re==="buttons",Vt=O?.variables,Mi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),bo=Vt?.colorBackground,Bi=bo&&!Mi.has(bo)?bo:void 0,kr=u.cardInputBorder??(Sr?"#e5e7eb":"#A4A4FF"),vo=Vt?.colorDanger??"#dc2626",jn=o=>Fn&&o?vo:kr,jr=(st.malformed||st.empty)&&(qn||Fn),Ai=jr?vo:jn(Ee.zip),Co=u.cardFormContainer?.backgroundColor??Bi??(Sr?"white":"#EDEDFF"),Rr=u.cardInputBackground??Vt?.colorBackground??"white",wo=er(j),Pa=er(oe),Qn=u.nameInput,ba=u.cardInputFontSize??Fs(Qn?.fontSize)??Vt?.fontSizeBase??"16px",va=typeof Qn?.fontFamily=="string"?Qn.fontFamily:Vt?.fontFamily??"Poppins, sans-serif",Ca=Ja(Qn?.fontWeight)??400,Fi=u.cardInputColor??(typeof Qn?.color=="string"?Qn.color:void 0)??Vt?.colorText??"#262833",Di=u.cardInputPlaceholderColor??"#9ca3af",ft=Vt?.borderRadius??"8px",Vn=Vt?.borderRadius??u.cardButton?.borderRadius??ft,Hn=Vt?.colorPrimary??"#4A49FF",Li=Vt?.colorPrimaryHover??no(Hn,.12),So=Vt?.colorText??"#262833",wa={fontSize:ba,fontFamily:va,fontWeight:Ca,color:Fi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ni={"--flopay-input-placeholder-color":Di,"--flopay-input-font-size":ba,"--flopay-input-font-family":va,"--flopay-input-font-weight":String(Ca)},Ir=u.cardFormContainer??{},ko=Ir.padding??(Sr?"0":"1rem"),Ro=Ir.borderRadius??ft,Oi=Ie&&Ut?d(_o,{capture:Ie,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:b,onReady:()=>{if(!H||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let v=0,z=window.setInterval(()=>{v+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(z)):v>=50&&window.clearInterval(z)},100)},onError:o=>W(o),onValidation:o=>{W(o),o&&Ke(null)}}):d("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"}),Sa=xe("div",{style:{backgroundColor:Co,borderRadius:Ro,...Ir,padding:ko,...Ni,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flopay/react",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"publishConfig": {
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
"@paypal/paypal-js": "^10.0.0",
|
|
30
30
|
"@stripe/react-stripe-js": "^6.6.0",
|
|
31
31
|
"@stripe/stripe-js": "^9.8.0",
|
|
32
|
-
"@flopay/
|
|
33
|
-
"@flopay/
|
|
32
|
+
"@flopay/js": "1.4.5",
|
|
33
|
+
"@flopay/shared": "1.4.5"
|
|
34
34
|
},
|
|
35
35
|
"peerDependencies": {
|
|
36
36
|
"react": ">=18.0.0",
|