@flopay/react 1.14.2 → 1.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-JCJFICSM.mjs +22 -0
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +7 -7
- package/dist/payment-method-setup-entry.cjs +3 -3
- package/dist/payment-method-setup-entry.mjs +1 -1
- package/dist/payment-method-setup-stripe-AAZGNGQO.mjs +1 -0
- package/package.json +3 -3
- package/dist/chunk-MSABDKVT.mjs +0 -22
- package/dist/payment-method-setup-stripe-ULXLO3FW.mjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Nc=Object.create;var Wa=Object.defineProperty;var Uc=Object.getOwnPropertyDescriptor;var zc=Object.getOwnPropertyNames;var qc=Object.getPrototypeOf,jc=Object.prototype.hasOwnProperty;var Vc=(e,t)=>{for(var r in t)Wa(e,r,{get:t[r],enumerable:!0})},dl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of zc(t))!jc.call(e,a)&&a!==r&&Wa(e,a,{get:()=>t[a],enumerable:!(n=Uc(t,a))||n.enumerable});return e};var Wi=(e,t,r)=>(r=e!=null?Nc(qc(e)):{},dl(t||!e||!e.__esModule?Wa(r,"default",{value:e,enumerable:!0}):r,e)),Wc=e=>dl(Wa({},"__esModule",{value:!0}),e);var vu={};Vc(vu,{DirectPayPalButton:()=>ha,FloPayAutomaticPaymentButton:()=>ac,FloPayCardSetup:()=>ic,FloPayCardSetupError:()=>xa,FloPayCheckout:()=>vi,FloPayPaymentMethodSetup:()=>hc,FloPayProvider:()=>va,SplitCardForm:()=>fi,VaultCardFields:()=>co,dropThirdPartyOnlyError:()=>vc.dropThirdPartyOnlyError,useCheckout:()=>bl,useFloPay:()=>Qn,usePayPalFloPay:()=>Ga});module.exports=Wc(vu);var vc=require("@flopay/shared");var Ci=require("@flopay/js"),mn=require("@flopay/shared"),gt=require("react");var Kt=require("react/jsx-runtime");function $c(){return(0,Kt.jsxs)(Kt.Fragment,{children:[(0,Kt.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,Kt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Kt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Kt.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,Kt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Hc(){return(0,Kt.jsx)(Kt.Fragment,{children:"Go back"})}function Kc(){return(0,Kt.jsx)(Kt.Fragment,{children:"Secure card checkout"})}function Bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Do({content:e}){return(0,Kt.jsx)(Kt.Fragment,{children:e===void 0?(0,Kt.jsx)($c,{}):e})}function Oo({content:e}){return(0,Kt.jsx)(Kt.Fragment,{children:e===void 0?(0,Kt.jsx)(Hc,{}):e})}function ua({content:e}){return(0,Kt.jsx)(Kt.Fragment,{children:e===void 0?(0,Kt.jsx)(Kc,{}):e})}var vt=require("@flopay/shared"),wn=require("@flopay/shared"),Uo=require("@flopay/shared"),vo=require("@flopay/shared"),Gc="Checkout is temporarily unavailable. Please try again later.";function $i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof vt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Yc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function ul(){return new vt.FloPayError(Gc,"api_error",{code:"CheckoutInitializationFailed"})}function pl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,vt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,vt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function yl(e,t){if(t&&(!(e instanceof vt.FloPayError)||e.type==="authentication_error"))return $i(e);if(!(e instanceof vt.FloPayError&&Yc(e))){if(!t&&!(e instanceof vt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,vt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof vt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof vt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Lo(e,t,r,n={}){let a;return(i={})=>{if(a!==void 0)return a;let l={...n,...i,email:i.email?.trim()||n.email?.trim()},u=(0,vt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,vt.isValidEmail)(l.email))return Promise.reject(new vt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[P,w]of Object.entries(l)){if(u&&P.endsWith("Name")||typeof w!="string")continue;let S=w.trim();S&&(p[P]=S)}return a=e.claimCheckoutSession(t,r,{accountData:p}),a.catch(()=>{}),a}}function ml(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Hi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function fl(e,t){let r=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],n=r.reduce((i,l)=>i+(l.overrideAmount??l.totalAmount??0),0),a=e.currency??r.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((i,l)=>({uuid:`synthetic-${i.type??"item"}-${l}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Ki(e,t){return t?{...e,...t}:e}function hr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,i=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,l=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...i?{declineCode:i}:{},...l?{sessionId:l}:{}}}function so(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Xn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Jn(e){return e?.status==="authorized"||e?.status==="complete"}function lo(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function gl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function $a(e){let t=gl(e);return new vt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ha(e){return e instanceof vt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function No(e){return gl(e)?new vt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new vt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new vt.FloPayError(vt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function pa(e,t){return e==="processing"||(0,vt.isMoneySettledOutcome)(e,t)}function hl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Pl(e,t){let r=e;if((0,vt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:i,error:l}=await r.retrieveSetupIntent(t);if(l)throw new vt.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return i??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new vt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var Xc=["apple_pay","google_pay"];function vl(e,t="automatic",r){let n=(0,vt.resolveSetupFutureUsage)(r,Xc,"wallet");return{...(0,vt.resolveWalletModeOptions)(e,t),paymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Jc=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Gi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Jc.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ya(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var ro=require("@flopay/js"),$e=require("@flopay/shared"),C=Wi(require("react"),1);var Yi=require("react"),ln=(0,Yi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),kn=(0,Yi.createContext)({session:null,loading:!1,error:null});var Za=require("@flopay/js"),et=require("@flopay/shared"),Rl=require("@paypal/paypal-js"),R=require("react");var Ka=require("@flopay/shared"),Rn=require("react"),cn=require("@flopay/shared"),Zn=require("react/jsx-runtime");function zo(){let[e,t]=(0,Rn.useState)(null),r=(0,Rn.useRef)(null),n=(0,Rn.useRef)(0),a=(0,Rn.useCallback)((l,u)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:l,identity:u}),new Promise(p=>{r.current=p})),[]),i=(0,Rn.useCallback)(l=>{let u=r.current;r.current=null,t(null),u?.(l)},[]);return(0,Rn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:i}}function qo({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[l,u]=(0,Rn.useState)(e.email?.trim()??""),p=(0,Ka.isValidEmail)(l.trim());return(0,Zn.jsxs)("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Zn.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Zn.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Zn.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:P=>u(P.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Zn.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,Zn.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Zn.jsxs)("button",{type:"button",disabled:!p||a,onClick:()=>{r((0,Ka.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var be=require("@flopay/shared");var Cl=require("@flopay/shared"),ma=require("react");function Qn(){return(0,ma.useContext)(ln).flopay}function Ga(){return(0,ma.useContext)(ln).paypalFlopay??null}function bl(){return(0,ma.useContext)(kn)}function Sl(){return(0,ma.useContext)(ln).billingApiUrl||(0,Cl.resolveBillingApiUrl)()}var Zc=require("@flopay/shared"),Ln=require("@flopay/shared"),Nn=require("@flopay/shared");var jo=require("@flopay/shared"),bo=require("react");var Ya=require("react"),Co=typeof window>"u"?Ya.useEffect:Ya.useLayoutEffect;var Xi=require("@flopay/shared");function Vo(e,t){let r=(0,bo.useRef)(e);r.current=e;let n=(0,bo.useRef)(new Set),a=(0,bo.useRef)(t),i=(0,bo.useRef)(t);return Co(()=>{i.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,bo.useCallback)(l=>{if(i.current!==t)return;let u=(0,jo.projectFloInstrument)(l);if(u){if(jo.FLO_INSTRUMENT_ONCE_NAMES.has(u.name)){if(n.current.has(u.name))return;n.current.add(u.name)}(0,jo.invokeMerchantCallback)(()=>r.current?.(u))}},[t])}var Qe=require("@flopay/shared");var wl=require("react"),fa=(0,wl.createContext)(null);function Xa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Qc=Symbol.for("@flopay/js.telemetry.bridge.v1"),ed=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function td(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function rd(e){let t=td(),r=(a,i)=>a?a.bind(e):i,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,n()-a),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function Ja(e){let t=globalThis[ed];return rd(t?.(e)??{})}function Pr(e){if(e)return e[Qc]}var pr=require("react");function ga(e,t){let r=(0,pr.useRef)(0),n=(0,pr.useRef)(null),a=(0,pr.useRef)(null),i=(0,pr.useRef)(e),l=(0,pr.useRef)(t?.onHandoffObserved),u=(0,pr.useRef)(t?.defersMissingTerminal),p=(0,pr.useRef)(t?.onMissingTerminalDeferred);(0,pr.useEffect)(()=>{i.current=e,l.current=t?.onHandoffObserved,u.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let P=(0,pr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),w=(0,pr.useCallback)(f=>{P();let v=r.current+1;return r.current=v,n.current=null,a.current={generation:v,method:f,timer:null,yieldedControl:!1},v},[P]),S=(0,pr.useCallback)(f=>{let v=a.current;return f!==void 0&&v?.generation!==f?!1:(P(v),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[P]),E=(0,pr.useCallback)(f=>{let v=a.current,ye=f??v?.generation??r.current;(f===void 0||v?.generation===f)&&(P(v),a.current=null),n.current=ye},[P]),K=(0,pr.useCallback)(f=>n.current===(f??r.current),[]),I=(0,pr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),X=(0,pr.useCallback)(()=>{let f=a.current;f&&(P(f),!f.yieldedControl&&(f.yieldedControl=!0,l.current?.(f.method)))},[P]),M=(0,pr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(P(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(u.current?.(f.method)){p.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,i.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},be.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[P]);return(0,pr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?M():X()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",X),window.addEventListener("focus",M),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",X),window.removeEventListener("focus",M),P()}},[P,X,M]),{startAttempt:w,finishAttempt:S,invalidateAttempt:E,isAttemptInvalidated:K,isAttemptCurrent:I,generationRef:r}}var dn=require("react/jsx-runtime"),Qa=45,nd=1e3,od=11e3,ad={width:"100%",minHeight:Qa,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"},id={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function sd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:id[e.kind]??null}}function kl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,be.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function ld(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function El({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:i,clientId:l,environment:u,currency:p,isSubscription:P,providerObjectType:w,approvalPresentation:S,onTokenizedBody:E,onComplete:K,onErrorChange:I,onDecline:X,onCancel:M,onTechnicalFailure:f,isProcessing:v=!1,onLoadStateChange:ye,onInitializationStateChange:b,allowAutomaticRetry:Te=!0,onButtonClick:T,runBeforeButtonClick:se,session:me,existingOrderId:pe,telemetry:Fe,telemetryContext:dt,onInstrument:He,debug:D=!1}){let St=Qn(),Ye=Vo(He,e),Oe=(0,R.useMemo)(()=>{if(St)return null;let te=Ja({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:et.SDK_VERSION,enabled:Fe!==!1});return te.setCheckoutContext(dt??{}),te.beginCheckout(dt??{}),te},[r,St,Fe,dt?.checkoutMode,dt?.layout]),ge=(0,R.useMemo)(()=>Pr(St),[St]);(0,R.useEffect)(()=>()=>{Oe&&Oe.flush().catch(()=>{}).finally(()=>Oe.destroy())},[Oe]);let Q=(0,R.useMemo)(()=>({error:te=>{ge?ge.error(te):Oe?.error(te),Ye({class:"technical_error",errorCode:te.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":te.errorCode,requestCategory:te.requestCategory,provider:te.provider})},log:te=>{ge?ge.log(te):Oe?.log(te),Ye({class:"lifecycle",name:te.name,provider:te.provider})},performance:te=>{ge?ge.performance(te):Oe?.performance(te)},terminal:te=>{ge?ge.terminal(te):Oe?.terminal(te)},startTiming:()=>ge?.now()??Oe?.now()??0,elapsed:te=>ge?.elapsed(te)??Math.max(0,(Oe?.now()??te)-te)}),[Ye,ge,Oe]),G=(0,R.useRef)(null),Be=(0,R.useRef)(0),ze=(0,R.useRef)(null),Xe=(0,R.useRef)(null),ne=(0,R.useRef)(null),ee=(0,R.useContext)(fa),le=(0,R.useRef)(null);le.current||(le.current=Xa());let V=ee??le.current,Ve=(0,R.useRef)(null),Ae=(0,R.useRef)(!1),[he,N]=(0,R.useState)(!1),[Ce,ut]=(0,R.useState)(!1),[Le,ot]=(0,R.useState)(0),Me=(0,R.useRef)(0),[tt,at]=(0,R.useState)(!1),lr=(0,R.useRef)(!1),Bt=(0,R.useRef)(!1),[wt,Se]=(0,R.useState)(!1),[x,ht]=(0,R.useState)(!1),{request:pt,collect:z,finish:we}=zo(),Dt=(0,R.useRef)({sessionId:e,required:(0,et.paypalProviderIdentityRequired)(n,me)});Dt.current.sessionId!==e&&(Dt.current={sessionId:e,required:(0,et.paypalProviderIdentityRequired)(n,me)});let Ke=Dt.current.required,kt=(0,R.useMemo)(()=>r.replace(/\/+$/,""),[r]),A=me?.gateways?.paypal?.providerObjectType??w,We=A??(P?"subscription":"order"),[ke]=(0,R.useState)(Ln.detectPayPalEnvironment),ct=me?.gateways?.paypal?.approvalPresentation??S,g=(0,Nn.resolvePayPalPresentationMode)(ke,ct==="app_switch"?"app_switch":void 0,We),J=(0,et.usesPayPalVaultedChannel)(A),q=(0,R.useMemo)(()=>JSON.stringify([kt,l,p,u??"",We,J,g,e,pe??""]),[kt,l,p,u,pe,We,J,g,e]),ue=(0,R.useRef)(q),m=ue.current!==q,Z=(0,R.useRef)(D),xe=(0,R.useRef)(null),[rt,oe]=(0,R.useState)([]),$=(0,R.useCallback)(te=>{Z.current&&oe(Ct=>[...Ct,`${new Date().toISOString().slice(11,23)} ${te}`])},[]);(0,R.useEffect)(()=>{Z.current=D,D&&$("debug:enabled"),xe.current?.setEnabled(D)},[$,D]);let Vt=(0,R.useRef)(E),Ir=(0,R.useRef)(K),br=(0,R.useRef)(I),Gt=(0,R.useRef)(X),Yt=(0,R.useRef)(M),Ur=(0,R.useRef)(f),_r=(0,R.useRef)(T),Qt=(0,R.useRef)(ye),zr=(0,R.useRef)(b),Wt=(0,R.useRef)(i),Vn=(0,R.useRef)(se),Xt=(0,R.useRef)(me),Gr=(0,R.useRef)(n),it=(0,R.useRef)(a),Mt=(0,R.useRef)(t),jt=(0,R.useRef)(null),Jt=(0,R.useRef)(new Map),Dr=(0,R.useRef)(new Map),qr=(0,R.useRef)(!1);(0,R.useEffect)(()=>(qr.current=!0,()=>{qr.current=!1}),[]),(0,R.useEffect)(()=>{Vt.current=E},[E]),(0,R.useEffect)(()=>{Wt.current=i},[i]),(0,R.useEffect)(()=>{Ir.current=K},[K]),(0,R.useEffect)(()=>{br.current=I},[I]),(0,R.useEffect)(()=>{Gt.current=X},[X]),(0,R.useEffect)(()=>{Yt.current=M},[M]),(0,R.useEffect)(()=>{Ur.current=f},[f]),(0,R.useEffect)(()=>{_r.current=T},[T]),(0,R.useEffect)(()=>{Qt.current=ye},[ye]),(0,R.useEffect)(()=>{zr.current=b},[b]),(0,R.useEffect)(()=>{Vn.current=se},[se]),(0,R.useEffect)(()=>{Xt.current=me},[me]),(0,R.useEffect)(()=>{Gr.current=n},[n]),(0,R.useEffect)(()=>{it.current=a},[a]),(0,R.useEffect)(()=>{Mt.current=t},[t]),(0,R.useEffect)(()=>{Me.current=Le},[Le]),(0,R.useEffect)(()=>{tt&&Ve.current?.focus()},[tt,Le]);let Sr=(0,R.useCallback)(()=>{window.setTimeout(()=>{Ve.current?.focus()},0)},[]),wr=(0,R.useCallback)(()=>{N(!1),ot(te=>te+1)},[]),fr=(0,R.useCallback)(()=>{at(!1),(G.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??G.current)?.focus?.()},[]);(0,R.useEffect)(()=>{!he||!Ae.current||(Ae.current=!1,fr())},[fr,he,Le]);let Tr=(0,R.useCallback)((te,Ct)=>{let _=Ct?.popupBlocked??(0,be.isPopupBlockedError)(te);_&&V.markBlocked();let xt=(0,be.buildExternalMethodRecoveryMessage)("PayPal",_,ke.inAppBrowser),At=Ur.current;if(At){let Et=_&&ke.inAppBrowser?new et.FloPayError(xt,"api_error",{code:Ct?.code??"paypal_popup_blocked"}):te;At("paypal",Et,Ct);return}br.current?.(xt)},[V,ke.inAppBrowser]),Ot=(0,R.useCallback)(te=>{let Ct=ze.current,_=Xe.current;Ct===null||!_||(Q.log({..._,popupCapability:V.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:te}),Q.performance({..._,popupCapability:V.current(),stage:"overlay_return",durationMs:Q.elapsed(Ct),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:te}),ze.current=null)},[V,Q]),Lt=(0,R.useCallback)((te,Ct,_)=>{let xt=Xe.current;Ot("overlay_timeout"),xt&&Q.error({...xt,popupCapability:V.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Tr(Ct,{..._,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:g,terminalReason:"overlay_timeout"}),at(!0),wr(),Sr()},[Ot,Sr,Tr,V,g,wr,Q]),Mr=(0,R.useCallback)(()=>{V.markAvailable();let te=Xe.current;te&&(ne.current=te.attempt,Q.log({...te,popupCapability:V.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[V,Q]),{finishAttempt:cr,generationRef:qe,invalidateAttempt:fn,isAttemptCurrent:xr,isAttemptInvalidated:Wn,startAttempt:er}=ga(Lt,{onHandoffObserved:Mr}),Ar=(0,R.useCallback)(()=>(at(!1),er("paypal")),[er]),Tn=(0,R.useCallback)(te=>{fn(te?.generation),te?.showRetry&&at(!0),te?.remount&&wr(),te?.focus!==!1&&Sr()},[Sr,fn,wr]),gn=te=>{let Ct=jt.current;return Ct&&Dr.current.set(te,Ct),te};(0,R.useEffect)(()=>{ue.current!==q&&(ue.current=q,lr.current=!1,Bt.current=!1,N(!1),ut(!1),Se(!1),zr.current?.("loading"))},[q]),(0,R.useEffect)(()=>{(0,Qe.invokeMerchantCallback)(()=>Qt.current?.(he&&!wt))},[he,wt]);let $t=(0,et.normalizeGatewayEnvironment)(u);(0,R.useEffect)(()=>{let te={attempt:qe.current+1,inAppBrowser:ke.inAppBrowser,appFamily:ke.appFamily,popupCapability:V.current(),presentationMode:g},Ct=()=>({...Xe.current??te,popupCapability:V.current()}),_={error:h=>Q.error({...h,...Ct()}),log:h=>Q.log({...h,...Ct()}),performance:h=>Q.performance({...h,...Ct()}),terminal:h=>Q.terminal({...h,...Ct()}),startTiming:Q.startTiming,elapsed:Q.elapsed},xt=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",At=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if($(`mount clientId=${xt} env=${u??"(unset)"}\u2192${$t??"live"} ccy=${p} sub=${P}`),$(`ua=${At.slice(0,80)}${At.length>80?"\u2026":""}`),!l){$("FAIL: clientId empty \u2014 gateway misconfigured"),Se(!0),_.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!G.current){$("FAIL: containerRef not attached");return}Be.current=_.startTiming(),_.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Et=!1,tr=!1,yt=()=>Et||tr,oo=J?We:void 0,Nt,Yr=!1,Mn=()=>{Nt=(0,et.generateIdempotencyKey)(),Nt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Yr=!0},nn=null,rr=!1,hn=null,$n=!1,xn=()=>{!hn||$n||($n=!0,hn.close().catch(()=>{}))},Or=!1,ao=!1,on=G.current,Hn=null,Xr=null,Pn=[],An=null,Ut=!1,Jr=!1,Zr=null,jr=h=>{if(!h||typeof h.getBoundingClientRect!="function")return"(no rect)";let y=h.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},vn=h=>{if(!h)return"(empty)";try{let y=new URL(h,typeof window>"u"?"https://localhost":window.location.href),H=y.pathname.toLowerCase();return H.includes("checkcaptcha")||H.includes("captcha")?`CAPTCHA(${y.host}${H})`:H.includes("risk")||H.includes("challenge")?`RISK(${y.host}${H})`:H.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${H}`.slice(0,100)}catch{return h.slice(0,80)}},bt=h=>{let y=h.getAttribute("src"),H=h.getAttribute("srcdoc"),Ee=h.getAttribute("name"),Je=h.getAttribute("sandbox"),mt=[];return y&&mt.push(`src=${vn(y)}`),H&&mt.push(`srcdoc[${H.length}ch]`),!y&&!H&&mt.push("src=(empty) srcdoc=(empty)"),Ee&&mt.push(`name=${Ee.slice(0,40)}`),Je!==null&&mt.push(`sandbox="${Je.slice(0,40)}"`),mt.join(" ")},kr=h=>{if(!(h instanceof HTMLIFrameElement))return"";try{let y=h.contentDocument;if(!y)return"cd=null";let H=y.body?.children.length??0,Ee=y.body?.innerHTML.length??0,Je=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${H}children,${Ee}ch] head[${Je}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},dr=[],Vr=h=>{if(yt())return;let y=h.message??String(h.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&($(`window:error ${y.slice(0,140)}`),dr.push(y))},yo=h=>{if(yt())return;let y=h.reason instanceof Error?h.reason.message:String(h.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&($(`window:rejection ${y.slice(0,140)}`),dr.push(y))},Cn={value:0},Kn=()=>{Hn?.disconnect(),Hn=null,Xr?.disconnect(),Xr=null;for(let h of Pn.splice(0))clearTimeout(h);Jr=!1,Ut&&typeof window<"u"&&(window.removeEventListener("error",Vr),window.removeEventListener("unhandledrejection",yo)),Ut=!1},Qr=()=>{if(!(Ut||yt()||Or)){if(Ut=!0,dr.length=0,Cn.value=0,typeof window<"u"&&(window.addEventListener("error",Vr),window.addEventListener("unhandledrejection",yo)),typeof PerformanceObserver<"u")try{Xr=new PerformanceObserver(h=>{if(!yt())for(let y of h.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Cn.value+=1;let H=Math.round(y.duration);$(`net ${H}ms ${y.name.slice(0,90)}`)}}),Xr.observe({type:"resource",buffered:!0})}catch{}Zr?.()}},Rr=()=>{An&&(clearTimeout(An),An=null)},Fn=()=>{Kn(),Rr()},Fr={setEnabled:h=>{h?Qr():Kn()}};xe.current=Fr,Z.current&&Qr();let L=et.isPayPalTeardownMessage,U=h=>{if(yt()||L(h))return;let y=(0,vo.applyFriendlyMessageOverride)(h)??h;(0,Qe.invokeMerchantCallback)(()=>br.current?.(y))},re=(h,y)=>{if(Et||rr)return;rr=!0,tr=!0,Fn(),xn();let H=sd({kind:h,generationActive:!0,automaticRetryAllowed:Te,automaticRetryUsed:lr.current});if(H.action==="retry"){lr.current=!0,N(!1),ht(!1),ut(!0),zr.current?.("retrying"),nn=setTimeout(()=>{Et||ot(Ee=>Ee+1)},nd);return}if(N(!1),ht(!1),ut(!1),Se(!0),H.action!=="ignore"){if(zr.current?.("exhausted"),H.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(H.report){let Ee=(0,be.classifyExternalMethodFailure)({code:kl(h,y),message:y},{inAppBrowser:ke.inAppBrowser,handoffObserved:!1});Ee.popupBlocked&&V.markBlocked(),_.error({errorCode:Ee.popupBlocked?Ee.errorCode:H.report.errorCode,stage:H.report.stage,operationOutcome:H.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Ee.terminalReason})}Bt.current||(Bt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",kl(h,y)))}};Se(!1);let Re=async(h,y=jt.current)=>{if(yt())return;let H=y?.sessionId??e;if(Vt.current){await Vt.current(h,{sessionId:H,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let Ee=_.startTiming();_.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Je=()=>{_.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),_.performance({stage:"processing",durationMs:_.elapsed(Ee),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let mt=(0,et.buildPayPalProcessPaymentRequest)({body:h,sessionId:H,nonce:y?.nonce??Mt.current,accountPatch:y?.accountPatch,session:Xt.current,email:Gr.current}),De=await new Za.PaymentAPI(kt,{telemetry:!1}).processPayment(mt.userId,mt.params);if(De.ok){if(tr||Et&&qr.current)return;Je(),_.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>Ir.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(yt())return;let st=await De.json().catch(()=>null),Rt=(0,et.describePayPalProcessFailure)(st),_t=Rt.message;Je(),De.status===400&&(typeof st?.declineCode=="string"||!Array.isArray(st?.fields))?_.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):De.status===400||De.status===422?_.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):_.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ld(De.status),failureCategory:De.status>=500?"server_error":void 0}),U(_t),(0,Qe.invokeMerchantCallback)(()=>Gt.current?.(hr("paypal",_t,{code:Rt.code,declineCode:Rt.declineCode})));return}catch(mt){if(yt())return;Je(),_.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ue=(0,et.friendlyPayPalFailureMessage)(mt instanceof Error?mt.message:void 0);U(Ue),(0,Qe.invokeMerchantCallback)(()=>Gt.current?.(hr("paypal",Ue)));return}},It=()=>new et.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),nr=h=>yt()?Promise.reject(It()):Promise.resolve(h),Ne=async h=>{if(yt())throw It();Yr||Mn();let y=jt.current,H=y?.sessionId??e,Ee=y?.nonce??Mt.current;_.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Je;try{Je=await new Za.PaymentAPI(kt,{telemetry:!1}).createSessionIntent(H,Ee??"",(0,et.buildPayPalSessionIntentRequest)(oo),{idempotencyKey:Nt})}catch(mt){throw _.error({...(0,et.classifyTelemetryFailure)(mt,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),mt}if(yt())throw It();if(Je.provider!=="paypal"||Je.providerObjectType!==We)throw new Error(h);return _.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Je.providerObjectId},ce=(h,y)=>{let H=y?.nonce??Mt.current;if(!H)return;let Ee=y?.sessionId??e,Je=(0,et.resolvePayPalDeclineReason)(h);new Za.PaymentAPI(kt,{telemetry:!1}).reportSessionIntentDecline(Ee,H,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Je}).catch(()=>{})},j=Le;$("loadScript:scheduled (deferred 1 tick)");let W=null,de=setTimeout(()=>{if(Et){$("loadScript:skipped (cancelled before defer ran)");return}$("loadScript:start");let h=$t==="live"?"production":$t,y={};We==="subscription"?y={intent:"subscription",vault:!0}:We==="order"&&(y={intent:"capture"}),W=(0,Rl.loadScript)({clientId:l,currency:p,...y,...h?{environment:h}:{},...h==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let H=!1;W.then(Ee=>{if(H=!0,$(`loadScript:resolved inactive=${yt()} ns=${!!Ee} buttons=${!!Ee?.Buttons}`),yt())return;if(!Ee?.Buttons){$("FAIL: namespace missing Buttons factory"),re("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}_.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),_.performance({stage:"provider_ready",durationMs:_.elapsed(Be.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),_.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Je=async(F,Pe)=>{if(yt()||Me.current!==j)return;let Ze=F.vaultSetupToken??F.subscriptionID??F.orderID??"",nt=Ze?Dr.current.get(Ze):Jt.current.get(j);if(!(!nt||!xr(nt.generation))&&cr(nt.generation)){Dr.current.delete(Ze),Jt.current.delete(nt.surfaceKey),Ot("approved");try{if(ht(!0),(0,Qe.invokeMerchantCallback)(()=>br.current?.(null)),!Ze)throw new et.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ae=(0,et.resolvePayPalApprovalIdentity)({accountPatch:nt.accountPatch,email:Gr.current,billingName:it.current,session:Xt.current});if((0,et.needsPayPalPayerDetails)(ae))try{ae=(0,et.mergePayPalPayerIdentity)(ae,await Pe?.order?.get?.())}catch{}if((Wt.current||Ke)&&!(0,et.isValidEmail)(ae.email)){let ve=await z("PayPal",ae);if(!ve)return;ae=ve}(0,et.isValidEmail)(ae.email)&&(nt.accountPatch=(0,cn.compactBuyerIdentity)({...nt.accountPatch,...ae}),await Wt.current?.(ae));let ur=(0,et.buildPayPalTokenizedBody)(Ze,oo);await Re(ur,nt)}catch(ae){U(ae instanceof Error?ae.message:"PayPal capture failed.")}finally{yt()||ht(!1)}}},mt=F=>{let Pe=pe?()=>nr(pe):()=>Ne(F);return async()=>gn(await Pe())},Ue=Ee.Buttons({style:{layout:"horizontal",height:Qa,tagline:!1},...g==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(F,Pe)=>{if(yt()){await Pe.reject();return}Mn();let Ze=Vn.current,nt={};if(Ze)try{let ve=await Ze("paypal");if(yt()){await Pe.reject();return}if(!ve.proceed){jt.current=null,Jt.current.delete(j),await Pe.reject();return}nt={sessionId:ve.sessionId,accountPatch:ve.accountPatch,nonce:ve.nonce}}catch(ve){$(`onClick:runBeforeButtonClick rejected msg=${(ve instanceof Error?ve.message:String(ve)).slice(0,120)}`),jt.current=null,Jt.current.delete(j),await Pe.reject();return}(0,Qe.invokeMerchantCallback)(()=>_r.current?.("paypal"));let ae=Ar(),ur={generation:ae,surfaceKey:j,...nt};jt.current=ur,Jt.current.set(j,ur),Xe.current={...te,attempt:ae},await Pe.resolve(),_.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),_.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),ze.current=_.startTiming()},createOrder:We==="order"?mt("Failed to create PayPal order."):void 0,createSubscription:We==="subscription"?mt("Failed to create PayPal subscription."):void 0,createVaultSetupToken:We==="setup_token"?async()=>gn(await Ne("Failed to create PayPal setup token.")):void 0,onApprove:Je,onCancel:()=>{if(yt())return;let F=Jt.current.get(j)??jt.current,Pe=F&&xr(F.generation)?(0,et.buildPayPalCancelEvent)(F.sessionId??e,oo):null;F&&Jt.current.delete(F.surfaceKey),jt.current=null,Ot("cancelled"),_.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ae.current=!0,Tn({generation:F?.generation,remount:!0,focus:!1}),Pe&&(0,Qe.invokeMerchantCallback)(()=>Yt.current?.(Pe))},onError:F=>{if(yt()||Me.current!==j)return;let Pe=F instanceof Error?F.message:"PayPal failed to render.";if($(`onError rendered=${Or} msg=${Pe.slice(0,120)}`),Or){let Ze=Jt.current.get(j)??jt.current;if(Ze&&!xr(Ze.generation)||!Ze&&Wn())return;if(L(Pe)){cr(Ze?.generation);return}let{errorCode:nt,popupBlocked:ae,providerDeclined:ur,terminalReason:ve}=(0,be.classifyExternalMethodFailure)(F,{inAppBrowser:ke.inAppBrowser,handoffObserved:Ze!=null&&ne.current===Ze.generation});if(ae&&V.markBlocked(),Ot(ve),ur){_.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:ve}),ce(F,Ze),(0,Qe.invokeMerchantCallback)(()=>Gt.current?.(hr("paypal",Pe))),Ze&&Jt.current.delete(Ze.surfaceKey),jt.current=null,cr(Ze?.generation);return}_.error({errorCode:nt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:ve}),Ze&&Jt.current.delete(Ze.surfaceKey),jt.current=null,Tn({generation:Ze?.generation,remount:!0,showRetry:!0,focus:!0}),Tr(F,{code:"paypal_runtime_failed",popupBlocked:ae,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:g,terminalReason:ve});return}re(L(Pe)?"teardown":"pre_ready_callback",Pe)}}),De=Ue.isEligible();if($(`isEligible=${De}`),_.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!De){N(!1),re("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ao=!0,hn=Ue,Zr=()=>{if(!Ut||Jr||yt()||Or)return;Jr=!0,$(`container:dims ${jr(on)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Hn=new MutationObserver(Pe=>{if(!yt()){for(let Ze of Pe)if(Ze.type==="childList")Ze.addedNodes.forEach(nt=>{if(!(nt instanceof Element))return;let ae=nt.tagName.toLowerCase(),ur=(nt.getAttribute("title")??"").slice(0,40),ve=ae==="iframe"?` ${bt(nt)}`:"";$(`child+ ${ae}${ur?` title="${ur}"`:""}${ve} dims=${jr(nt)}`)});else if(Ze.type==="attributes"&&Ze.target instanceof Element){let nt=Ze.target;if(nt.tagName.toLowerCase()!=="iframe")continue;let ae=Ze.attributeName;(ae==="src"||ae==="srcdoc")&&$(`attr~ iframe ${ae}=${ae==="srcdoc"?`[${(nt.getAttribute("srcdoc")??"").length}ch]`:vn(nt.getAttribute("src"))} dims=${jr(nt)}`)}}}),Hn.observe(on,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let F=Pe=>{if(yt()||Or)return;let Ze=on.querySelectorAll("iframe"),nt=typeof document<"u"&&"hasStorageAccess"in document;$(`watchdog:${Pe} container=${jr(on)} children=${on.childElementCount} iframes=${Ze.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${nt} paypalNetRequests=${Cn.value}`),Ze.forEach((ae,ur)=>{let ve=(ae.getAttribute("title")??"").slice(0,40);$(` iframe[${ur}] ${jr(ae)}${ve?` title="${ve}"`:""} ${bt(ae)}`);let Gn=kr(ae);Gn&&$(` ${Gn}`)}),dr.length===0&&$(" (no PayPal/zoid window errors captured)")};Pn.push(setTimeout(()=>F("3s"),3e3)),Pn.push(setTimeout(()=>F("8s"),8e3)),Pn.push(setTimeout(()=>F("15s"),15e3))},Zr(),$("render:start");let Rt=_.startTiming();An=setTimeout(()=>{yt()||Or||($("watchdog:11s retryable render timeout"),re("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},od);let _t=Ue.render(on);(async()=>{try{if(await _t,$(`render:resolved inactive=${yt()}`),Fn(),yt()){xn();return}Or=!0,N(!0),ut(!1),zr.current?.("ready"),_.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),_.performance({stage:"checkout_render",durationMs:_.elapsed(Rt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(F){let Pe=F instanceof Error?F.message:"PayPal failed to render.";$(`render:rejected msg=${Pe.slice(0,120)}`),Fn(),re(L(Pe)?"teardown":"render_rejected",Pe)}})()}).catch(Ee=>{let Je=Ee instanceof Error?Ee.message:"PayPal operation failed.";$(`provider:failed msg=${Je.slice(0,120)}`);let mt="script_rejected";H&&L(Je)?mt="teardown":H&&ao&&(mt="render_rejected"),re(mt,Je)})},0);return()=>{Et=!0,clearTimeout(de),nn&&clearTimeout(nn),Fn(),xe.current===Fr&&(xe.current=null),xn(),ze.current=null,Xe.current=null}},[Te,kt,l,p,u,We,g,J,e,pe,Le,Q,z,Ke,$,Ot]);let fe=D?(0,dn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:wt?"#fef2f2":"#f3f4f6",border:`1px solid ${wt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${he} failed=${wt})`,rt.length===0?`
|
|
1
|
+
"use strict";var Nc=Object.create;var Wa=Object.defineProperty;var Uc=Object.getOwnPropertyDescriptor;var zc=Object.getOwnPropertyNames;var qc=Object.getPrototypeOf,jc=Object.prototype.hasOwnProperty;var Vc=(e,t)=>{for(var r in t)Wa(e,r,{get:t[r],enumerable:!0})},dl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of zc(t))!jc.call(e,a)&&a!==r&&Wa(e,a,{get:()=>t[a],enumerable:!(n=Uc(t,a))||n.enumerable});return e};var Wi=(e,t,r)=>(r=e!=null?Nc(qc(e)):{},dl(t||!e||!e.__esModule?Wa(r,"default",{value:e,enumerable:!0}):r,e)),Wc=e=>dl(Wa({},"__esModule",{value:!0}),e);var vu={};Vc(vu,{DirectPayPalButton:()=>ha,FloPayAutomaticPaymentButton:()=>ac,FloPayCardSetup:()=>ic,FloPayCardSetupError:()=>xa,FloPayCheckout:()=>vi,FloPayPaymentMethodSetup:()=>hc,FloPayProvider:()=>va,SplitCardForm:()=>fi,VaultCardFields:()=>co,dropThirdPartyOnlyError:()=>vc.dropThirdPartyOnlyError,useCheckout:()=>bl,useFloPay:()=>Qn,usePayPalFloPay:()=>Ga});module.exports=Wc(vu);var vc=require("@flopay/shared");var Ci=require("@flopay/js"),Pn=require("@flopay/shared"),gt=require("react");var $t=require("react/jsx-runtime");function $c(){return(0,$t.jsxs)($t.Fragment,{children:[(0,$t.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,$t.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,$t.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,$t.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,$t.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Hc(){return(0,$t.jsx)($t.Fragment,{children:"Go back"})}function Kc(){return(0,$t.jsx)($t.Fragment,{children:"Secure card checkout"})}function Bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Do({content:e}){return(0,$t.jsx)($t.Fragment,{children:e===void 0?(0,$t.jsx)($c,{}):e})}function Oo({content:e}){return(0,$t.jsx)($t.Fragment,{children:e===void 0?(0,$t.jsx)(Hc,{}):e})}function ua({content:e}){return(0,$t.jsx)($t.Fragment,{children:e===void 0?(0,$t.jsx)(Kc,{}):e})}var vt=require("@flopay/shared"),Rn=require("@flopay/shared"),Uo=require("@flopay/shared"),vo=require("@flopay/shared"),Gc="Checkout is temporarily unavailable. Please try again later.";function $i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof vt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Yc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function ul(){return new vt.FloPayError(Gc,"api_error",{code:"CheckoutInitializationFailed"})}function pl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,vt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,vt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function ml(e,t){if(t&&(!(e instanceof vt.FloPayError)||e.type==="authentication_error"))return $i(e);if(!(e instanceof vt.FloPayError&&Yc(e))){if(!t&&!(e instanceof vt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,vt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof vt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof vt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Lo(e,t,r,n={}){let a;return(i={})=>{if(a!==void 0)return a;let l={...n,...i,email:i.email?.trim()||n.email?.trim()},p=(0,vt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,vt.isValidEmail)(l.email))return Promise.reject(new vt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[h,w]of Object.entries(l)){if(p&&h.endsWith("Name")||typeof w!="string")continue;let S=w.trim();S&&(m[h]=S)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function yl(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Hi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function fl(e,t){let r=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],n=r.reduce((i,l)=>i+(l.overrideAmount??l.totalAmount??0),0),a=e.currency??r.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((i,l)=>({uuid:`synthetic-${i.type??"item"}-${l}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Ki(e,t){return t?{...e,...t}:e}function wr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,i=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,l=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...i?{declineCode:i}:{},...l?{sessionId:l}:{}}}function so(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Xn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Jn(e){return e?.status==="authorized"||e?.status==="complete"}function lo(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function gl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function $a(e){let t=gl(e);return new vt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ha(e){return e instanceof vt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function No(e){return gl(e)?new vt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new vt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new vt.FloPayError(vt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function pa(e,t){return e==="processing"||(0,vt.isMoneySettledOutcome)(e,t)}function hl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Pl(e,t){let r=e;if((0,vt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:i,error:l}=await r.retrieveSetupIntent(t);if(l)throw new vt.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return i??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new vt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var Xc=["apple_pay","google_pay"];function vl(e,t="automatic",r){let n=(0,vt.resolveSetupFutureUsage)(r,Xc,"wallet");return{...(0,vt.resolveWalletModeOptions)(e,t),paymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Jc=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Gi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Jc.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ma(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var ro=require("@flopay/js"),We=require("@flopay/shared"),v=Wi(require("react"),1);var Yi=require("react"),pn=(0,Yi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),En=(0,Yi.createContext)({session:null,loading:!1,error:null});var Za=require("@flopay/js"),Qe=require("@flopay/shared"),Rl=require("@paypal/paypal-js"),k=require("react");var Ka=require("@flopay/shared"),In=require("react"),mn=require("@flopay/shared"),Zn=require("react/jsx-runtime");function zo(){let[e,t]=(0,In.useState)(null),r=(0,In.useRef)(null),n=(0,In.useRef)(0),a=(0,In.useCallback)((l,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:l,identity:p}),new Promise(m=>{r.current=m})),[]),i=(0,In.useCallback)(l=>{let p=r.current;r.current=null,t(null),p?.(l)},[]);return(0,In.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:i}}function qo({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[l,p]=(0,In.useState)(e.email?.trim()??""),m=(0,Ka.isValidEmail)(l.trim());return(0,Zn.jsxs)("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Zn.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Zn.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Zn.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:h=>p(h.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Zn.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,Zn.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Zn.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,Ka.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var ve=require("@flopay/shared");var Cl=require("@flopay/shared"),ya=require("react");function Qn(){return(0,ya.useContext)(pn).flopay}function Ga(){return(0,ya.useContext)(pn).paypalFlopay??null}function bl(){return(0,ya.useContext)(En)}function Sl(){return(0,ya.useContext)(pn).billingApiUrl||(0,Cl.resolveBillingApiUrl)()}var Zc=require("@flopay/shared"),Un=require("@flopay/shared"),zn=require("@flopay/shared");var jo=require("@flopay/shared"),bo=require("react");var Ya=require("react"),Co=typeof window>"u"?Ya.useEffect:Ya.useLayoutEffect;var Xi=require("@flopay/shared");function Vo(e,t){let r=(0,bo.useRef)(e);r.current=e;let n=(0,bo.useRef)(new Set),a=(0,bo.useRef)(t),i=(0,bo.useRef)(t);return Co(()=>{i.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,bo.useCallback)(l=>{if(i.current!==t)return;let p=(0,jo.projectFloInstrument)(l);if(p){if(jo.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,jo.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ze=require("@flopay/shared");var wl=require("react"),fa=(0,wl.createContext)(null);function Xa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Qc=Symbol.for("@flopay/js.telemetry.bridge.v1"),ed=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function td(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function rd(e){let t=td(),r=(a,i)=>a?a.bind(e):i,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,n()-a),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function Ja(e){let t=globalThis[ed];return rd(t?.(e)??{})}function kr(e){if(e)return e[Qc]}var fr=require("react");function ga(e,t){let r=(0,fr.useRef)(0),n=(0,fr.useRef)(null),a=(0,fr.useRef)(null),i=(0,fr.useRef)(e),l=(0,fr.useRef)(t?.onHandoffObserved),p=(0,fr.useRef)(t?.defersMissingTerminal),m=(0,fr.useRef)(t?.onMissingTerminalDeferred);(0,fr.useEffect)(()=>{i.current=e,l.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let h=(0,fr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),w=(0,fr.useCallback)(f=>{h();let P=r.current+1;return r.current=P,n.current=null,a.current={generation:P,method:f,timer:null,yieldedControl:!1},P},[h]),S=(0,fr.useCallback)(f=>{let P=a.current;return f!==void 0&&P?.generation!==f?!1:(h(P),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[h]),E=(0,fr.useCallback)(f=>{let P=a.current,pe=f??P?.generation??r.current;(f===void 0||P?.generation===f)&&(h(P),a.current=null),n.current=pe},[h]),Y=(0,fr.useCallback)(f=>n.current===(f??r.current),[]),I=(0,fr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),ee=(0,fr.useCallback)(()=>{let f=a.current;f&&(h(f),!f.yieldedControl&&(f.yieldedControl=!0,l.current?.(f.method)))},[h]),x=(0,fr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(h(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(p.current?.(f.method)){m.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,i.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},ve.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[h]);return(0,fr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?x():ee()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",ee),window.addEventListener("focus",x),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",ee),window.removeEventListener("focus",x),h()}},[h,ee,x]),{startAttempt:w,finishAttempt:S,invalidateAttempt:E,isAttemptInvalidated:Y,isAttemptCurrent:I,generationRef:r}}var yn=require("react/jsx-runtime"),Qa=45,nd=1e3,od=11e3,ad={width:"100%",minHeight:Qa,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"},id={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function sd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:id[e.kind]??null}}function kl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,ve.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function ld(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function El({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:i,clientId:l,environment:p,currency:m,isSubscription:h,providerObjectType:w,approvalPresentation:S,onTokenizedBody:E,onComplete:Y,onErrorChange:I,onDecline:ee,onCancel:x,onTechnicalFailure:f,isProcessing:P=!1,onLoadStateChange:pe,onInitializationStateChange:b,allowAutomaticRetry:Ie=!0,onButtonClick:_,runBeforeButtonClick:ie,session:me,existingOrderId:ue,telemetry:xe,telemetryContext:lt,onInstrument:$e,debug:B=!1}){let St=Qn(),Ge=Vo($e,e),De=(0,k.useMemo)(()=>{if(St)return null;let Z=Ja({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:Qe.SDK_VERSION,enabled:xe!==!1});return Z.setCheckoutContext(lt??{}),Z.beginCheckout(lt??{}),Z},[r,St,xe,lt?.checkoutMode,lt?.layout]),de=(0,k.useMemo)(()=>kr(St),[St]);(0,k.useEffect)(()=>()=>{De&&De.flush().catch(()=>{}).finally(()=>De.destroy())},[De]);let re=(0,k.useMemo)(()=>({error:Z=>{de?de.error(Z):De?.error(Z),Ge({class:"technical_error",errorCode:Z.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":Z.errorCode,requestCategory:Z.requestCategory,provider:Z.provider})},log:Z=>{de?de.log(Z):De?.log(Z),Ge({class:"lifecycle",name:Z.name,provider:Z.provider})},performance:Z=>{de?de.performance(Z):De?.performance(Z)},terminal:Z=>{de?de.terminal(Z):De?.terminal(Z)},startTiming:()=>de?.now()??De?.now()??0,elapsed:Z=>de?.elapsed(Z)??Math.max(0,(De?.now()??Z)-Z)}),[Ge,de,De]),X=(0,k.useRef)(null),Oe=(0,k.useRef)(0),nt=(0,k.useRef)(null),ze=(0,k.useRef)(null),te=(0,k.useRef)(null),J=(0,k.useContext)(fa),H=(0,k.useRef)(null);H.current||(H.current=Xa());let j=J??H.current,je=(0,k.useRef)(null),Te=(0,k.useRef)(!1),[fe,O]=(0,k.useState)(!1),[Pe,ut]=(0,k.useState)(!1),[Le,ot]=(0,k.useState)(0),_e=(0,k.useRef)(0),[et,at]=(0,k.useState)(!1),ar=(0,k.useRef)(!1),xt=(0,k.useRef)(!1),[Ct,Ce]=(0,k.useState)(!1),[T,ht]=(0,k.useState)(!1),{request:pt,collect:z,finish:Ae}=zo(),Dt=(0,k.useRef)({sessionId:e,required:(0,Qe.paypalProviderIdentityRequired)(n,me)});Dt.current.sessionId!==e&&(Dt.current={sessionId:e,required:(0,Qe.paypalProviderIdentityRequired)(n,me)});let be=Dt.current.required,_t=(0,k.useMemo)(()=>r.replace(/\/+$/,""),[r]),M=me?.gateways?.paypal?.providerObjectType??w,Fe=M??(h?"subscription":"order"),[Se]=(0,k.useState)(Un.detectPayPalEnvironment),ct=me?.gateways?.paypal?.approvalPresentation??S,mt=(0,zn.resolvePayPalPresentationMode)(Se,ct==="app_switch"?"app_switch":void 0,Fe),Ve=(0,Qe.usesPayPalVaultedChannel)(M),He=(0,k.useMemo)(()=>JSON.stringify([_t,l,m,p??"",Fe,Ve,mt,e,ue??""]),[_t,l,m,p,ue,Fe,Ve,mt,e]),Bt=(0,k.useRef)(He),c=Bt.current!==He,U=(0,k.useRef)(B),V=(0,k.useRef)(null),[se,R]=(0,k.useState)([]),K=(0,k.useCallback)(Z=>{U.current&&R(At=>[...At,`${new Date().toISOString().slice(11,23)} ${Z}`])},[]);(0,k.useEffect)(()=>{U.current=B,B&&K("debug:enabled"),V.current?.setEnabled(B)},[K,B]);let Ut=(0,k.useRef)(E),xr=(0,k.useRef)(Y),ir=(0,k.useRef)(I),Ht=(0,k.useRef)(ee),Tt=(0,k.useRef)(x),Lr=(0,k.useRef)(f),Ar=(0,k.useRef)(_),Zt=(0,k.useRef)(pe),$r=(0,k.useRef)(b),Mt=(0,k.useRef)(i),xn=(0,k.useRef)(ie),Kt=(0,k.useRef)(me),ln=(0,k.useRef)(n),Nr=(0,k.useRef)(a),Ur=(0,k.useRef)(t),sr=(0,k.useRef)(null),br=(0,k.useRef)(new Map),Hr=(0,k.useRef)(new Map),dt=(0,k.useRef)(!1);(0,k.useEffect)(()=>(dt.current=!0,()=>{dt.current=!1}),[]),(0,k.useEffect)(()=>{Ut.current=E},[E]),(0,k.useEffect)(()=>{Mt.current=i},[i]),(0,k.useEffect)(()=>{xr.current=Y},[Y]),(0,k.useEffect)(()=>{ir.current=I},[I]),(0,k.useEffect)(()=>{Ht.current=ee},[ee]),(0,k.useEffect)(()=>{Tt.current=x},[x]),(0,k.useEffect)(()=>{Lr.current=f},[f]),(0,k.useEffect)(()=>{Ar.current=_},[_]),(0,k.useEffect)(()=>{Zt.current=pe},[pe]),(0,k.useEffect)(()=>{$r.current=b},[b]),(0,k.useEffect)(()=>{xn.current=ie},[ie]),(0,k.useEffect)(()=>{Kt.current=me},[me]),(0,k.useEffect)(()=>{ln.current=n},[n]),(0,k.useEffect)(()=>{Nr.current=a},[a]),(0,k.useEffect)(()=>{Ur.current=t},[t]),(0,k.useEffect)(()=>{_e.current=Le},[Le]),(0,k.useEffect)(()=>{et&&je.current?.focus()},[et,Le]);let wt=(0,k.useCallback)(()=>{window.setTimeout(()=>{je.current?.focus()},0)},[]),lr=(0,k.useCallback)(()=>{O(!1),ot(Z=>Z+1)},[]),Gt=(0,k.useCallback)(()=>{at(!1),(X.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??X.current)?.focus?.()},[]);(0,k.useEffect)(()=>{!fe||!Te.current||(Te.current=!1,Gt())},[Gt,fe,Le]);let hr=(0,k.useCallback)((Z,At)=>{let Me=At?.popupBlocked??(0,ve.isPopupBlockedError)(Z);Me&&j.markBlocked();let Pr=(0,ve.buildExternalMethodRecoveryMessage)("PayPal",Me,Se.inAppBrowser),Ot=Lr.current;if(Ot){let jt=Me&&Se.inAppBrowser?new Qe.FloPayError(Pr,"api_error",{code:At?.code??"paypal_popup_blocked"}):Z;Ot("paypal",jt,At);return}ir.current?.(Pr)},[j,Se.inAppBrowser]),Yt=(0,k.useCallback)(Z=>{let At=nt.current,Me=ze.current;At===null||!Me||(re.log({...Me,popupCapability:j.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Z}),re.performance({...Me,popupCapability:j.current(),stage:"overlay_return",durationMs:re.elapsed(At),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Z}),nt.current=null)},[j,re]),cr=(0,k.useCallback)((Z,At,Me)=>{let Pr=ze.current;Yt("overlay_timeout"),Pr&&re.error({...Pr,popupCapability:j.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),hr(At,{...Me,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:mt,terminalReason:"overlay_timeout"}),at(!0),lr(),wt()},[Yt,wt,hr,j,mt,lr,re]),Ir=(0,k.useCallback)(()=>{j.markAvailable();let Z=ze.current;Z&&(te.current=Z.attempt,re.log({...Z,popupCapability:j.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[j,re]),{finishAttempt:dr,generationRef:Ye,invalidateAttempt:Fr,isAttemptCurrent:ur,isAttemptInvalidated:oo,startAttempt:zr}=ga(cr,{onHandoffObserved:Ir}),qr=(0,k.useCallback)(()=>(at(!1),zr("paypal")),[zr]),An=(0,k.useCallback)(Z=>{Fr(Z?.generation),Z?.showRetry&&at(!0),Z?.remount&&lr(),Z?.focus!==!1&&wt()},[wt,Fr,lr]),Kr=Z=>{let At=sr.current;return At&&Hr.current.set(Z,At),Z};(0,k.useEffect)(()=>{Bt.current!==He&&(Bt.current=He,ar.current=!1,xt.current=!1,O(!1),ut(!1),Ce(!1),$r.current?.("loading"))},[He]),(0,k.useEffect)(()=>{(0,Ze.invokeMerchantCallback)(()=>Zt.current?.(fe&&!Ct))},[fe,Ct]);let Xt=(0,Qe.normalizeGatewayEnvironment)(p);(0,k.useEffect)(()=>{let Z={attempt:Ye.current+1,inAppBrowser:Se.inAppBrowser,appFamily:Se.appFamily,popupCapability:j.current(),presentationMode:mt},At=()=>({...ze.current??Z,popupCapability:j.current()}),Me={error:g=>re.error({...g,...At()}),log:g=>re.log({...g,...At()}),performance:g=>re.performance({...g,...At()}),terminal:g=>re.terminal({...g,...At()}),startTiming:re.startTiming,elapsed:re.elapsed},Pr=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Ot=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(K(`mount clientId=${Pr} env=${p??"(unset)"}\u2192${Xt??"live"} ccy=${m} sub=${h}`),K(`ua=${Ot.slice(0,80)}${Ot.length>80?"\u2026":""}`),!l){K("FAIL: clientId empty \u2014 gateway misconfigured"),Ce(!0),Me.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!X.current){K("FAIL: containerRef not attached");return}Oe.current=Me.startTiming(),Me.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let jt=!1,vr=!1,$=()=>jt||vr,Vt=Ve?Fe:void 0,tt,Lt=!1,pr=()=>{tt=(0,Qe.generateIdempotencyKey)(),tt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Lt=!0},Br=null,Qt=!1,vn=null,$n=!1,Fn=()=>{!vn||$n||($n=!0,vn.close().catch(()=>{}))},jr=!1,ao=!1,cn=X.current,Hn=null,en=null,Cn=[],Bn=null,Nt=!1,tn=!1,rn=null,Gr=g=>{if(!g||typeof g.getBoundingClientRect!="function")return"(no rect)";let y=g.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},bn=g=>{if(!g)return"(empty)";try{let y=new URL(g,typeof window>"u"?"https://localhost":window.location.href),G=y.pathname.toLowerCase();return G.includes("checkcaptcha")||G.includes("captcha")?`CAPTCHA(${y.host}${G})`:G.includes("risk")||G.includes("challenge")?`RISK(${y.host}${G})`:G.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${G}`.slice(0,100)}catch{return g.slice(0,80)}},bt=g=>{let y=g.getAttribute("src"),G=g.getAttribute("srcdoc"),ke=g.getAttribute("name"),Xe=g.getAttribute("sandbox"),yt=[];return y&&yt.push(`src=${bn(y)}`),G&&yt.push(`srcdoc[${G.length}ch]`),!y&&!G&&yt.push("src=(empty) srcdoc=(empty)"),ke&&yt.push(`name=${ke.slice(0,40)}`),Xe!==null&&yt.push(`sandbox="${Xe.slice(0,40)}"`),yt.join(" ")},_r=g=>{if(!(g instanceof HTMLIFrameElement))return"";try{let y=g.contentDocument;if(!y)return"cd=null";let G=y.body?.children.length??0,ke=y.body?.innerHTML.length??0,Xe=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${G}children,${ke}ch] head[${Xe}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},mr=[],Yr=g=>{if($())return;let y=g.message??String(g.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(K(`window:error ${y.slice(0,140)}`),mr.push(y))},mo=g=>{if($())return;let y=g.reason instanceof Error?g.reason.message:String(g.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(K(`window:rejection ${y.slice(0,140)}`),mr.push(y))},Sn={value:0},Kn=()=>{Hn?.disconnect(),Hn=null,en?.disconnect(),en=null;for(let g of Cn.splice(0))clearTimeout(g);tn=!1,Nt&&typeof window<"u"&&(window.removeEventListener("error",Yr),window.removeEventListener("unhandledrejection",mo)),Nt=!1},nn=()=>{if(!(Nt||$()||jr)){if(Nt=!0,mr.length=0,Sn.value=0,typeof window<"u"&&(window.addEventListener("error",Yr),window.addEventListener("unhandledrejection",mo)),typeof PerformanceObserver<"u")try{en=new PerformanceObserver(g=>{if(!$())for(let y of g.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Sn.value+=1;let G=Math.round(y.duration);K(`net ${G}ms ${y.name.slice(0,90)}`)}}),en.observe({type:"resource",buffered:!0})}catch{}rn?.()}},Tr=()=>{Bn&&(clearTimeout(Bn),Bn=null)},Dn=()=>{Kn(),Tr()},Dr={setEnabled:g=>{g?nn():Kn()}};V.current=Dr,U.current&&nn();let L=Qe.isPayPalTeardownMessage,N=g=>{if($()||L(g))return;let y=(0,vo.applyFriendlyMessageOverride)(g)??g;(0,Ze.invokeMerchantCallback)(()=>ir.current?.(y))},ne=(g,y)=>{if(jt||Qt)return;Qt=!0,vr=!0,Dn(),Fn();let G=sd({kind:g,generationActive:!0,automaticRetryAllowed:Ie,automaticRetryUsed:ar.current});if(G.action==="retry"){ar.current=!0,O(!1),ht(!1),ut(!0),$r.current?.("retrying"),Br=setTimeout(()=>{jt||ot(ke=>ke+1)},nd);return}if(O(!1),ht(!1),ut(!1),Ce(!0),G.action!=="ignore"){if($r.current?.("exhausted"),G.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(G.report){let ke=(0,ve.classifyExternalMethodFailure)({code:kl(g,y),message:y},{inAppBrowser:Se.inAppBrowser,handoffObserved:!1});ke.popupBlocked&&j.markBlocked(),Me.error({errorCode:ke.popupBlocked?ke.errorCode:G.report.errorCode,stage:G.report.stage,operationOutcome:G.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:ke.terminalReason})}xt.current||(xt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",kl(g,y)))}};Ce(!1);let we=async(g,y=sr.current)=>{if($())return;let G=y?.sessionId??e;if(Ut.current){await Ut.current(g,{sessionId:G,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let ke=Me.startTiming();Me.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Xe=()=>{Me.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Me.performance({stage:"processing",durationMs:Me.elapsed(ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let yt=(0,Qe.buildPayPalProcessPaymentRequest)({body:g,sessionId:G,nonce:y?.nonce??Ur.current,accountPatch:y?.accountPatch,session:Kt.current,email:ln.current}),Be=await new Za.PaymentAPI(_t,{telemetry:!1}).processPayment(yt.userId,yt.params);if(Be.ok){if(vr||jt&&dt.current)return;Xe(),Me.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ze.invokeMerchantCallback)(()=>xr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if($())return;let it=await Be.json().catch(()=>null),kt=(0,Qe.describePayPalProcessFailure)(it),Et=kt.message;Xe(),Be.status===400&&(typeof it?.declineCode=="string"||!Array.isArray(it?.fields))?Me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Be.status===400||Be.status===422?Me.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):Me.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ld(Be.status),failureCategory:Be.status>=500?"server_error":void 0}),N(Et),(0,Ze.invokeMerchantCallback)(()=>Ht.current?.(wr("paypal",Et,{code:kt.code,declineCode:kt.declineCode})));return}catch(yt){if($())return;Xe(),Me.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ue=(0,Qe.friendlyPayPalFailureMessage)(yt instanceof Error?yt.message:void 0);N(Ue),(0,Ze.invokeMerchantCallback)(()=>Ht.current?.(wr("paypal",Ue)));return}},Rt=()=>new Qe.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),er=g=>$()?Promise.reject(Rt()):Promise.resolve(g),Ne=async g=>{if($())throw Rt();Lt||pr();let y=sr.current,G=y?.sessionId??e,ke=y?.nonce??Ur.current;Me.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Xe;try{Xe=await new Za.PaymentAPI(_t,{telemetry:!1}).createSessionIntent(G,ke??"",(0,Qe.buildPayPalSessionIntentRequest)(Vt),{idempotencyKey:tt})}catch(yt){throw Me.error({...(0,Qe.classifyTelemetryFailure)(yt,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),yt}if($())throw Rt();if(Xe.provider!=="paypal"||Xe.providerObjectType!==Fe)throw new Error(g);return Me.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Xe.providerObjectId},le=(g,y)=>{let G=y?.nonce??Ur.current;if(!G)return;let ke=y?.sessionId??e,Xe=(0,Qe.resolvePayPalDeclineReason)(g);new Za.PaymentAPI(_t,{telemetry:!1}).reportSessionIntentDecline(ke,G,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Xe}).catch(()=>{})},q=Le;K("loadScript:scheduled (deferred 1 tick)");let W=null,ce=setTimeout(()=>{if(jt){K("loadScript:skipped (cancelled before defer ran)");return}K("loadScript:start");let g=Xt==="live"?"production":Xt,y={};Fe==="subscription"?y={intent:"subscription",vault:!0}:Fe==="order"&&(y={intent:"capture"}),W=(0,Rl.loadScript)({clientId:l,currency:m,...y,...g?{environment:g}:{},...g==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let G=!1;W.then(ke=>{if(G=!0,K(`loadScript:resolved inactive=${$()} ns=${!!ke} buttons=${!!ke?.Buttons}`),$())return;if(!ke?.Buttons){K("FAIL: namespace missing Buttons factory"),ne("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}Me.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Me.performance({stage:"provider_ready",durationMs:Me.elapsed(Oe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Me.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Xe=async(A,ge)=>{if($()||_e.current!==q)return;let Je=A.vaultSetupToken??A.subscriptionID??A.orderID??"",rt=Je?Hr.current.get(Je):br.current.get(q);if(!(!rt||!ur(rt.generation))&&dr(rt.generation)){Hr.current.delete(Je),br.current.delete(rt.surfaceKey),Yt("approved");try{if(ht(!0),(0,Ze.invokeMerchantCallback)(()=>ir.current?.(null)),!Je)throw new Qe.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let oe=(0,Qe.resolvePayPalApprovalIdentity)({accountPatch:rt.accountPatch,email:ln.current,billingName:Nr.current,session:Kt.current});if((0,Qe.needsPayPalPayerDetails)(oe))try{oe=(0,Qe.mergePayPalPayerIdentity)(oe,await ge?.order?.get?.())}catch{}if((Mt.current||be)&&!(0,Qe.isValidEmail)(oe.email)){let he=await z("PayPal",oe);if(!he)return;oe=he}(0,Qe.isValidEmail)(oe.email)&&(rt.accountPatch=(0,mn.compactBuyerIdentity)({...rt.accountPatch,...oe}),await Mt.current?.(oe));let yr=(0,Qe.buildPayPalTokenizedBody)(Je,Vt);await we(yr,rt)}catch(oe){N(oe instanceof Error?oe.message:"PayPal capture failed.")}finally{$()||ht(!1)}}},yt=A=>{let ge=ue?()=>er(ue):()=>Ne(A);return async()=>Kr(await ge())},Ue=ke.Buttons({style:{layout:"horizontal",height:Qa,tagline:!1},...mt==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(A,ge)=>{if($()){await ge.reject();return}pr();let Je=xn.current,rt={};if(Je)try{let he=await Je("paypal");if($()){await ge.reject();return}if(!he.proceed){sr.current=null,br.current.delete(q),await ge.reject();return}rt={sessionId:he.sessionId,accountPatch:he.accountPatch,nonce:he.nonce}}catch(he){K(`onClick:runBeforeButtonClick rejected msg=${(he instanceof Error?he.message:String(he)).slice(0,120)}`),sr.current=null,br.current.delete(q),await ge.reject();return}(0,Ze.invokeMerchantCallback)(()=>Ar.current?.("paypal"));let oe=qr(),yr={generation:oe,surfaceKey:q,...rt};sr.current=yr,br.current.set(q,yr),ze.current={...Z,attempt:oe},await ge.resolve(),Me.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Me.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nt.current=Me.startTiming()},createOrder:Fe==="order"?yt("Failed to create PayPal order."):void 0,createSubscription:Fe==="subscription"?yt("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Fe==="setup_token"?async()=>Kr(await Ne("Failed to create PayPal setup token.")):void 0,onApprove:Xe,onCancel:()=>{if($())return;let A=br.current.get(q)??sr.current,ge=A&&ur(A.generation)?(0,Qe.buildPayPalCancelEvent)(A.sessionId??e,Vt):null;A&&br.current.delete(A.surfaceKey),sr.current=null,Yt("cancelled"),Me.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Te.current=!0,An({generation:A?.generation,remount:!0,focus:!1}),ge&&(0,Ze.invokeMerchantCallback)(()=>Tt.current?.(ge))},onError:A=>{if($()||_e.current!==q)return;let ge=A instanceof Error?A.message:"PayPal failed to render.";if(K(`onError rendered=${jr} msg=${ge.slice(0,120)}`),jr){let Je=br.current.get(q)??sr.current;if(Je&&!ur(Je.generation)||!Je&&oo())return;if(L(ge)){dr(Je?.generation);return}let{errorCode:rt,popupBlocked:oe,providerDeclined:yr,terminalReason:he}=(0,ve.classifyExternalMethodFailure)(A,{inAppBrowser:Se.inAppBrowser,handoffObserved:Je!=null&&te.current===Je.generation});if(oe&&j.markBlocked(),Yt(he),yr){Me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:he}),le(A,Je),(0,Ze.invokeMerchantCallback)(()=>Ht.current?.(wr("paypal",ge))),Je&&br.current.delete(Je.surfaceKey),sr.current=null,dr(Je?.generation);return}Me.error({errorCode:rt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:he}),Je&&br.current.delete(Je.surfaceKey),sr.current=null,An({generation:Je?.generation,remount:!0,showRetry:!0,focus:!0}),hr(A,{code:"paypal_runtime_failed",popupBlocked:oe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:mt,terminalReason:he});return}ne(L(ge)?"teardown":"pre_ready_callback",ge)}}),Be=Ue.isEligible();if(K(`isEligible=${Be}`),Me.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Be){O(!1),ne("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ao=!0,vn=Ue,rn=()=>{if(!Nt||tn||$()||jr)return;tn=!0,K(`container:dims ${Gr(cn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Hn=new MutationObserver(ge=>{if(!$()){for(let Je of ge)if(Je.type==="childList")Je.addedNodes.forEach(rt=>{if(!(rt instanceof Element))return;let oe=rt.tagName.toLowerCase(),yr=(rt.getAttribute("title")??"").slice(0,40),he=oe==="iframe"?` ${bt(rt)}`:"";K(`child+ ${oe}${yr?` title="${yr}"`:""}${he} dims=${Gr(rt)}`)});else if(Je.type==="attributes"&&Je.target instanceof Element){let rt=Je.target;if(rt.tagName.toLowerCase()!=="iframe")continue;let oe=Je.attributeName;(oe==="src"||oe==="srcdoc")&&K(`attr~ iframe ${oe}=${oe==="srcdoc"?`[${(rt.getAttribute("srcdoc")??"").length}ch]`:bn(rt.getAttribute("src"))} dims=${Gr(rt)}`)}}}),Hn.observe(cn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let A=ge=>{if($()||jr)return;let Je=cn.querySelectorAll("iframe"),rt=typeof document<"u"&&"hasStorageAccess"in document;K(`watchdog:${ge} container=${Gr(cn)} children=${cn.childElementCount} iframes=${Je.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${rt} paypalNetRequests=${Sn.value}`),Je.forEach((oe,yr)=>{let he=(oe.getAttribute("title")??"").slice(0,40);K(` iframe[${yr}] ${Gr(oe)}${he?` title="${he}"`:""} ${bt(oe)}`);let Gn=_r(oe);Gn&&K(` ${Gn}`)}),mr.length===0&&K(" (no PayPal/zoid window errors captured)")};Cn.push(setTimeout(()=>A("3s"),3e3)),Cn.push(setTimeout(()=>A("8s"),8e3)),Cn.push(setTimeout(()=>A("15s"),15e3))},rn(),K("render:start");let kt=Me.startTiming();Bn=setTimeout(()=>{$()||jr||(K("watchdog:11s retryable render timeout"),ne("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},od);let Et=Ue.render(cn);(async()=>{try{if(await Et,K(`render:resolved inactive=${$()}`),Dn(),$()){Fn();return}jr=!0,O(!0),ut(!1),$r.current?.("ready"),Me.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),Me.performance({stage:"checkout_render",durationMs:Me.elapsed(kt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(A){let ge=A instanceof Error?A.message:"PayPal failed to render.";K(`render:rejected msg=${ge.slice(0,120)}`),Dn(),ne(L(ge)?"teardown":"render_rejected",ge)}})()}).catch(ke=>{let Xe=ke instanceof Error?ke.message:"PayPal operation failed.";K(`provider:failed msg=${Xe.slice(0,120)}`);let yt="script_rejected";G&&L(Xe)?yt="teardown":G&&ao&&(yt="render_rejected"),ne(yt,Xe)})},0);return()=>{jt=!0,clearTimeout(ce),Br&&clearTimeout(Br),Dn(),V.current===Dr&&(V.current=null),Fn(),nt.current=null,ze.current=null}},[Ie,_t,l,m,p,Fe,mt,Ve,e,ue,Le,re,z,be,K,Yt]);let ye=B?(0,yn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ct?"#fef2f2":"#f3f4f6",border:`1px solid ${Ct?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${fe} failed=${Ct})`,se.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${se.join(`
|
|
4
|
+
`)}`]}):null;return Ct&&!c?B?(0,yn.jsx)("div",{children:ye}):null:(0,yn.jsxs)("div",{children:[ye,pt&&(0,yn.jsx)(qo,{identity:pt.identity,methodLabel:pt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ae,onCancel:()=>Ae(null)}),(0,yn.jsxs)("div",{"aria-hidden":Pe||pt?!0:void 0,style:Pe||pt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Qa},children:[!fe&&!Pe&&(0,yn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,yn.jsx)("div",{ref:X,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Qa,display:"flex",opacity:fe?1:0},"aria-busy":T||P},Le)]},Le),et&&(0,yn.jsx)("button",{ref:je,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Gt,style:ad,children:"Try PayPal again"})]})}function ha(e){return(0,yn.jsx)(El,{...e})}function Il(e){return(0,yn.jsx)(El,{...e})}var Pa=require("react/jsx-runtime");function Wo({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,Pa.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...r?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...n??{}},children:[r&&(0,Pa.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Pa.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var ft=require("@flopay/shared");var gr=require("react/jsx-runtime");var cd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Zr({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:i="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:p=cd}){let m={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,gr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,gr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...p.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,gr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,gr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,gr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,gr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,gr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,gr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,gr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,gr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,gr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,gr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,gr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,gr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,gr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:p.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&l!==null&&(0,gr.jsx)("p",{style:m,children:l}),e==="error"&&t&&(0,gr.jsx)("p",{style:m,children:t}),(0,gr.jsx)("style",{children:`
|
|
5
5
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
6
6
|
@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
|
|
7
7
|
@keyframes flopay-draw { to { stroke-dashoffset: 0; } }
|
|
8
8
|
@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
|
|
9
|
-
`})]})})}var _l=require("@flopay/shared"),Er=require("react");var Tl=require("react/jsx-runtime");function va({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[i,l]=(0,Er.useState)(e instanceof Promise?null:e),[u,p]=(0,Er.useState)(t instanceof Promise||!t?null:t),P=(0,Er.useRef)(null),w=(0,Er.useRef)(null),S=Vo(n);(0,Er.useEffect)(()=>{S({class:"lifecycle",name:"checkout.mount"})},[S]),(0,Er.useEffect)(()=>{i&&S({class:"lifecycle",name:"sdk.initialize.ready"})},[S,i]),(0,Er.useEffect)(()=>{if(i)return Pr(i)?.subscribe?.(S)},[S,i]),(0,Er.useEffect)(()=>{if(!(!u||u===i))return Pr(u)?.subscribe?.(S)},[S,i,u]),(0,Er.useEffect)(()=>{if(!i)return;let I=Pr(i);return P.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Er.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then(X=>{I||l(X)},()=>{I||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{I=!0}},[S,e]),(0,Er.useEffect)(()=>{let I=!1;if(!t){p(null);return}return t instanceof Promise?t.then(X=>{I||p(X)},()=>{I||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{I=!0}},[S,t]),(0,Er.useEffect)(()=>{if(!i||w.current===i)return;w.current=i;let I=Pr(i);I?.log({name:"checkout.rendered",stage:"checkout_render"}),S({class:"lifecycle",name:"checkout.rendered"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(P.current??0),durationMode:"machine"})},[S,i]);let E=(0,_l.resolveBillingApiUrl)(r?.billingApiUrl),K=(0,Er.useMemo)(()=>({flopay:i,paypalFlopay:u,billingApiUrl:E,emitInstrument:S}),[i,u,E,S]);return(0,Tl.jsx)(ln.Provider,{value:K,children:a})}var En=require("@flopay/shared");async function ei(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var un=require("@flopay/js"),lt=require("@flopay/shared");var ba="card";async function dd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function ud(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:u}=await e.confirmCardSetup(t,r);return{error:u,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,r);return{error:i,intent:a??null}}function $o(e){return new lt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function pd(){return new lt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Zi(e,t){return Object.assign(e,{checkoutMethod:t})}function eo(e,t){let r=e instanceof lt.FloPayError?e:new lt.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ca(e,t){try{return await e()}catch(r){throw eo(r,t)}}function xl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Al(e){return(0,un.runSavedCardChallenge)(e)}async function Ho(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,i=t.nonce??t.session.clientSecret,l=new un.PaymentAPI(r,{telemetry:!1}),u=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,p;try{p=await(0,un.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:w=>Un({type:w.declineReason??"authorization_declined",gatewayErrorCode:w.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(w){if(a.aborted||w instanceof Error&&w.name==="AbortError")throw w instanceof lt.FloPayError&&w.code==="three_ds_aborted"?w:$o(w);if(!(w instanceof lt.FloPayError)||w.code!=="three_ds_timeout"&&w.code!=="checkout_processing_timeout")throw w;try{p=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:i,statusUrl:u,timeoutMs:5e3,signal:a})}catch(E){if(a.aborted)throw $o(E);if(!(E instanceof lt.FloPayError)||E.code!=="checkout_processing_timeout")throw E}let S=p&&lo(p,t.session);if(!Jn(S)&&S?.status!=="expired"){if(t.telemetry){let E=new un.PaymentAPI(r);try{E.reportThreeDsAbandoned(n)}finally{E.destroy()}}throw pd()}}let P=p&&lo(p,t.session);if(!Jn(P))throw No(P);return{...Xn(P,n),checkoutMethod:"card"}}function Un(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=(0,vo.applyFriendlyMessageOverride)(a)??a,l=Zi(new lt.FloPayError(i,"api_error",{code:e?.code??(0,lt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,lt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(l.orderId=e.orderId),l}function Ji(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Fl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ti(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let u of i)if(typeof u=="string"&&u.length>0&&(!t?.requirePaymentIntentClientSecret||ti(u)))return u;let l=a.gateways;if(l&&typeof l=="object"){let u=l.stripe;if(u&&typeof u=="object"){let p=u,P=[p.stripeClientSecret,p.clientSecret];for(let w of P)if(typeof w=="string"&&w.length>0&&(!t?.requirePaymentIntentClientSecret||ti(w)))return w}}}}async function yd({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Fl(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let u=(await new un.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ti(u))return{type:"3ds_required",threeDSecureToken:u}}catch{}return null}async function Ko({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:i,telemetry:l}){let u=e.replace(/\/+$/,""),p=t??r.id,P=n??r.clientSecret,w=r.customer?.id??r.accountData?.userId??"",S=r.customer?.email??r.accountData?.email??"",E=r.customer?.firstName??r.accountData?.firstName??"",K=r.customer?.lastName??r.accountData?.lastName??"",I=r.customer?.country??r.accountData?.country??void 0,X=r.customer?.zip??r.accountData?.zip??void 0,f=await new un.PaymentAPI(u,l===!1?{telemetry:!1}:void 0).processPayment(w,{sessionId:p,nonce:P,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:w,email:S,firstName:E,lastName:K,country:I,zip:X},returnUrl:i??Ji(r)});if(f.ok){let b=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,lt.isAuthorizationOnlySession)(r)||b?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof b?.paymentId=="string"?b.paymentId:r.paymentId,sessionId:typeof b?.sessionId=="string"?b.sessionId:p,authorizationExpiresAt:typeof b?.authorizationExpiresAt=="string"?b.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:ya(a),checkoutMethod:Ml(a,r)}};let Te=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Te?{paymentIntentId:Te}:{},paymentMethodId:ya(a),checkoutMethod:Ml(a,r)}}}let v;try{v=await f.json()}catch(b){throw new lt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:b})}if(v?.type==="3ds_required"&&typeof v.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:v.nextActionRedirectUrl};if(v?.type==="paypal_redirect_required"||v?.type==="3ds_required"){let b=Fl(v);if(!b)throw new lt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:v.type,threeDSecureToken:b,paymentMethodId:v.paymentMethodId}}if(v?.gatewayErrorCode==="authentication_required"){let b=await yd({billingApiUrl:u,sessionId:p,nonce:P,responseJson:v});if(b)return b;throw Zi(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ye=new lt.FloPayError(v?.message??"Payment failed. Please try again.","api_error",{code:v?.code??v?.gatewayErrorCode,declineCode:v?.declineCode??v?.gatewayDeclineReason,statusCode:f.status});throw Object.assign(ye,{telemetryOutcome:(0,lt.classifyPaymentRejection)(f.status,v)})}async function ri(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:i,session:l,returnUrl:u,telemetry:p,signal:P}){let w=t?.getRawProvider();if(!w)throw eo(new lt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw Zi(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let S=(0,lt.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,K=e.paymentMethodId,I=await Ca(()=>dd(w,e.threeDSecureToken,S),"card");if(I){if(I.error)throw eo(new lt.FloPayError(I.error.message??`Failed to retrieve 3DS ${S?"setup":"payment"} status.`,"api_error",{code:I.error.code}),"card");let M=I.intent;!K&&M?.payment_method&&(typeof M.payment_method=="string"?K=M.payment_method:"id"in M.payment_method&&(K=M.payment_method.id??void 0))}let X=K?await Ca(()=>ud(w,e.threeDSecureToken,{payment_method:K,return_url:u??Ji(l)??window.location.href},S),"card"):null;if(X){if(X.error)throw eo(new lt.FloPayError(X.error.message??"3DS authentication failed.","api_error",{code:X.error.code}),"card");E=X.intent}else{let M=await Ca(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(M.error)throw eo(new lt.FloPayError(M.error.message??"3DS authentication failed.","api_error",{code:M.error.code}),"card");E=(S?M.setupIntent:M.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let M=await Ko({billingApiUrl:a,sessionId:i,session:l,telemetry:p,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:u});return M.type==="success"?{...M.result,paymentIntentId:M.result.paymentIntentId??E.id,paymentMethodId:M.result.paymentMethodId??K}:M.type==="next_action_required"?Ho(M,{billingApiUrl:a,sessionId:i??l.id,session:l,signal:P}):ri(M,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:i,session:l,returnUrl:u,telemetry:p,signal:P})}throw eo(new lt.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let S=(r??t)?.getRawProvider();if(!S)throw eo(new lt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:K}=await Ca(()=>S.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(K)throw eo(new lt.FloPayError(K.message??"PayPal authorization failed.","api_error",{code:K.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await Ca(()=>S.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:u??Ji(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw eo(new lt.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt.FloPayError("Unsupported payment redirect state.","api_error")}function Sa(e){if(e instanceof lt.FloPayError){let n=(0,vo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new lt.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,vo.applyFriendlyMessageOverride)(t)??t;return new lt.FloPayError(r,"api_error")}function Qi(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,lt.isMountableVaultBlock)(e.data.session?.vault)||(0,wn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new lt.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Ml(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,wn.canRecoverHostedCardForm)(t)?"card":void 0}async function es({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[l,u]=await Promise.all([(0,un.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),i?(0,un.loadFloPay)(i,{billingApiUrl:r,locale:n,telemetry:a}).catch(P=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",P),null)):Promise.resolve(null)]);if(!l)throw new lt.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return i?p=u:t&&(p=l),{flopay:l,paypalFlopay:p}}var _n=require("@flopay/js"),c=require("@flopay/shared"),ar=require("@stripe/react-stripe-js"),o=Wi(require("react"),1);function Go(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ni(e,t){if(e)return{error:r=>e.error(Go(t,r)),log:r=>e.log(Go(t,r)),performance:r=>e.performance(Go(t,r)),terminal:r=>e.terminal(Go(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var to=require("@flopay/shared"),Dl=require("react");var Bl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var vr=require("react/jsx-runtime"),md=`
|
|
9
|
+
`})]})})}var _l=require("@flopay/shared"),Mr=require("react");var Tl=require("react/jsx-runtime");function va({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[i,l]=(0,Mr.useState)(e instanceof Promise?null:e),[p,m]=(0,Mr.useState)(t instanceof Promise||!t?null:t),h=(0,Mr.useRef)(null),w=(0,Mr.useRef)(null),S=Vo(n);(0,Mr.useEffect)(()=>{S({class:"lifecycle",name:"checkout.mount"})},[S]),(0,Mr.useEffect)(()=>{i&&S({class:"lifecycle",name:"sdk.initialize.ready"})},[S,i]),(0,Mr.useEffect)(()=>{if(i)return kr(i)?.subscribe?.(S)},[S,i]),(0,Mr.useEffect)(()=>{if(!(!p||p===i))return kr(p)?.subscribe?.(S)},[S,i,p]),(0,Mr.useEffect)(()=>{if(!i)return;let I=kr(i);return h.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Mr.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then(ee=>{I||l(ee)},()=>{I||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{I=!0}},[S,e]),(0,Mr.useEffect)(()=>{let I=!1;if(!t){m(null);return}return t instanceof Promise?t.then(ee=>{I||m(ee)},()=>{I||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{I=!0}},[S,t]),(0,Mr.useEffect)(()=>{if(!i||w.current===i)return;w.current=i;let I=kr(i);I?.log({name:"checkout.rendered",stage:"checkout_render"}),S({class:"lifecycle",name:"checkout.rendered"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(h.current??0),durationMode:"machine"})},[S,i]);let E=(0,_l.resolveBillingApiUrl)(r?.billingApiUrl),Y=(0,Mr.useMemo)(()=>({flopay:i,paypalFlopay:p,billingApiUrl:E,emitInstrument:S}),[i,p,E,S]);return(0,Tl.jsx)(pn.Provider,{value:Y,children:a})}var _n=require("@flopay/shared");async function ei(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var fn=require("@flopay/js"),st=require("@flopay/shared");var ba="card";async function dd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function ud(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,r);return{error:i,intent:a??null}}function $o(e){return new st.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function pd(){return new st.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Zi(e,t){return Object.assign(e,{checkoutMethod:t})}function eo(e,t){let r=e instanceof st.FloPayError?e:new st.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ca(e,t){try{return await e()}catch(r){throw eo(r,t)}}function xl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Al(e){return(0,fn.runSavedCardChallenge)(e)}async function Ho(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,i=t.nonce??t.session.clientSecret,l=new fn.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,fn.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:w=>qn({type:w.declineReason??"authorization_declined",gatewayErrorCode:w.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(w){if(a.aborted||w instanceof Error&&w.name==="AbortError")throw w instanceof st.FloPayError&&w.code==="three_ds_aborted"?w:$o(w);if(!(w instanceof st.FloPayError)||w.code!=="three_ds_timeout"&&w.code!=="checkout_processing_timeout")throw w;try{m=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:i,statusUrl:p,timeoutMs:5e3,signal:a})}catch(E){if(a.aborted)throw $o(E);if(!(E instanceof st.FloPayError)||E.code!=="checkout_processing_timeout")throw E}let S=m&&lo(m,t.session);if(!Jn(S)&&S?.status!=="expired"){if(t.telemetry){let E=new fn.PaymentAPI(r);try{E.reportThreeDsAbandoned(n)}finally{E.destroy()}}throw pd()}}let h=m&&lo(m,t.session);if(!Jn(h))throw No(h);return{...Xn(h,n),checkoutMethod:"card"}}function qn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=(0,vo.applyFriendlyMessageOverride)(a)??a,l=Zi(new st.FloPayError(i,"api_error",{code:e?.code??(0,st.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,st.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(l.orderId=e.orderId),l}function Ji(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Fl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ti(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let p of i)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||ti(p)))return p;let l=a.gateways;if(l&&typeof l=="object"){let p=l.stripe;if(p&&typeof p=="object"){let m=p,h=[m.stripeClientSecret,m.clientSecret];for(let w of h)if(typeof w=="string"&&w.length>0&&(!t?.requirePaymentIntentClientSecret||ti(w)))return w}}}}async function md({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Fl(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let p=(await new fn.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ti(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function Ko({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:i,telemetry:l}){let p=e.replace(/\/+$/,""),m=t??r.id,h=n??r.clientSecret,w=r.customer?.id??r.accountData?.userId??"",S=r.customer?.email??r.accountData?.email??"",E=r.customer?.firstName??r.accountData?.firstName??"",Y=r.customer?.lastName??r.accountData?.lastName??"",I=r.customer?.country??r.accountData?.country??void 0,ee=r.customer?.zip??r.accountData?.zip??void 0,f=await new fn.PaymentAPI(p,l===!1?{telemetry:!1}:void 0).processPayment(w,{sessionId:m,nonce:h,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:w,email:S,firstName:E,lastName:Y,country:I,zip:ee},returnUrl:i??Ji(r)});if(f.ok){let b=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,st.isAuthorizationOnlySession)(r)||b?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof b?.paymentId=="string"?b.paymentId:r.paymentId,sessionId:typeof b?.sessionId=="string"?b.sessionId:m,authorizationExpiresAt:typeof b?.authorizationExpiresAt=="string"?b.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:ma(a),checkoutMethod:Ml(a,r)}};let Ie=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Ie?{paymentIntentId:Ie}:{},paymentMethodId:ma(a),checkoutMethod:Ml(a,r)}}}let P;try{P=await f.json()}catch(b){throw new st.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:b})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let b=Fl(P);if(!b)throw new st.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:P.type,threeDSecureToken:b,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let b=await md({billingApiUrl:p,sessionId:m,nonce:h,responseJson:P});if(b)return b;throw Zi(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let pe=new st.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:f.status});throw Object.assign(pe,{telemetryOutcome:(0,st.classifyPaymentRejection)(f.status,P)})}async function ri(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:i,session:l,returnUrl:p,telemetry:m,signal:h}){let w=t?.getRawProvider();if(!w)throw eo(new st.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw Zi(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let S=(0,st.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,Y=e.paymentMethodId,I=await Ca(()=>dd(w,e.threeDSecureToken,S),"card");if(I){if(I.error)throw eo(new st.FloPayError(I.error.message??`Failed to retrieve 3DS ${S?"setup":"payment"} status.`,"api_error",{code:I.error.code}),"card");let x=I.intent;!Y&&x?.payment_method&&(typeof x.payment_method=="string"?Y=x.payment_method:"id"in x.payment_method&&(Y=x.payment_method.id??void 0))}let ee=Y?await Ca(()=>ud(w,e.threeDSecureToken,{payment_method:Y,return_url:p??Ji(l)??window.location.href},S),"card"):null;if(ee){if(ee.error)throw eo(new st.FloPayError(ee.error.message??"3DS authentication failed.","api_error",{code:ee.error.code}),"card");E=ee.intent}else{let x=await Ca(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(x.error)throw eo(new st.FloPayError(x.error.message??"3DS authentication failed.","api_error",{code:x.error.code}),"card");E=(S?x.setupIntent:x.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let x=await Ko({billingApiUrl:a,sessionId:i,session:l,telemetry:m,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:p});return x.type==="success"?{...x.result,paymentIntentId:x.result.paymentIntentId??E.id,paymentMethodId:x.result.paymentMethodId??Y}:x.type==="next_action_required"?Ho(x,{billingApiUrl:a,sessionId:i??l.id,session:l,signal:h}):ri(x,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:i,session:l,returnUrl:p,telemetry:m,signal:h})}throw eo(new st.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let S=(r??t)?.getRawProvider();if(!S)throw eo(new st.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:Y}=await Ca(()=>S.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(Y)throw eo(new st.FloPayError(Y.message??"PayPal authorization failed.","api_error",{code:Y.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await Ca(()=>S.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??Ji(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw eo(new st.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new st.FloPayError("Unsupported payment redirect state.","api_error")}function Sa(e){if(e instanceof st.FloPayError){let n=(0,vo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new st.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,vo.applyFriendlyMessageOverride)(t)??t;return new st.FloPayError(r,"api_error")}function Qi(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,st.isMountableVaultBlock)(e.data.session?.vault)||(0,Rn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new st.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Ml(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Rn.canRecoverHostedCardForm)(t)?"card":void 0}async function es({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[l,p]=await Promise.all([(0,fn.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),i?(0,fn.loadFloPay)(i,{billingApiUrl:r,locale:n,telemetry:a}).catch(h=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",h),null)):Promise.resolve(null)]);if(!l)throw new st.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return i?m=p:t&&(m=l),{flopay:l,paypalFlopay:m}}var Mn=require("@flopay/js"),d=require("@flopay/shared"),rr=require("@stripe/react-stripe-js"),o=Wi(require("react"),1);function Go(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ni(e,t){if(e)return{error:r=>e.error(Go(t,r)),log:r=>e.log(Go(t,r)),performance:r=>e.performance(Go(t,r)),terminal:r=>e.terminal(Go(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var to=require("@flopay/shared"),Dl=require("react");var Bl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var Rr=require("react/jsx-runtime"),yd=`
|
|
10
10
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
11
11
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
12
12
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -27,7 +27,7 @@ ${rt.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
|
-
`,Yo=44;function Xo(){return(0,vr.jsx)("style",{children:md})}function wa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function ka({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,vr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,vr.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,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,vr.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:n})]})}function ts(e){return e!=="unavailable"&&e!=="load_error"}function oi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:l,backgroundColor:u,borderColor:p,textColor:P,borderRadius:w,fontFamily:S}){let E=(0,to.resolveStripeMethodBrandVariant)(e,t),K=Bl[e],[I,X]=(0,Dl.useState)(!1),M=!!K&&!I,f=E?.backgroundColor??u??"#ffffff",v=E?.borderColor??p??"#d1d5db",ye=E?.textColor??P??"#262833";return(0,vr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&l()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Yo,padding:"0 1rem",backgroundColor:f,color:ye,border:`1px solid ${v}`,borderRadius:w??8,fontSize:"0.95rem",fontWeight:600,fontFamily:S,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"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:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,vr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,to.getStripeMethodDisplayName)(e)}\u2026`}):(0,vr.jsxs)(vr.Fragment,{children:[(0,vr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,to.hasVendoredStripeMethodLogo)(e)?8:0},children:[M?(0,vr.jsx)("img",{src:K,alt:"","aria-hidden":"true",onError:()=>X(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!M&&E?.logoSvg?(0,vr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:E.logoSvg}}):null,(0,vr.jsx)("span",{children:(0,to.getStripeMethodDisplayName)(e)})]}),i&&(0,vr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ye,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,vr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ai(e){let t=new Set(e.map(to.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var ii={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},si={type:"accordion",defaultCollapsed:!1,radios:"never"};function li({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:i,style:l,children:u}){return(0,vr.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:i,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...l??{}},children:u})}var rn=require("react");var Ra=require("@flopay/shared"),fd=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function gd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return fd.has(t.charAt(0).toLowerCase()+t.slice(1))}function hd(e,t){return typeof t=="number"&&t!==0&&!gd(e)?`${t}px`:String(t).trim()}function Ol(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=hd(r,n)}}}var So=require("react/jsx-runtime"),rs=new WeakSet;function co({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:i,submitLabel:l,containerStyle:u,onReady:p,onError:P,onValidation:w}){let S=(0,rn.useRef)(null),E=(0,rn.useRef)(p),K=(0,rn.useRef)(P),I=(0,rn.useRef)(w);E.current=p,K.current=P,I.current=w;let X=(0,rn.useRef)(i);X.current=i;let M=(0,rn.useRef)(null),f=l??void 0,v=(0,rn.useRef)(f);v.current=f;let ye=(0,rn.useRef)(void 0);return(0,rn.useEffect)(()=>{let b=S.current;if(!b)return;let Te=!0,T=!1,se=()=>{!Te||T||(T=!0,E.current?.())},me=e.on("ready",()=>{se()}),pe=e.on("error",D=>{K.current?.(D.message??"There was a problem loading the secure card form.")}),Fe=e.on("validation",D=>{I.current?.(D.message??null)}),dt=v.current??(rs.has(e)?null:void 0),He={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...X.current?{theme:X.current}:{},...dt===void 0?{}:{submitLabel:dt}};return M.current=X.current??null,ye.current=v.current,v.current!==void 0&&rs.add(e),e.mount(b,He).then(()=>{se()}).catch(D=>{Te&&K.current?.(D instanceof Error?D.message:"Failed to load the secure card form.")}),()=>{Te=!1,me(),pe(),Fe(),e.unmount()}},[e,t,r,n,a]),Co(()=>{let b=S.current;b&&Ol(b,u)},[u]),(0,rn.useEffect)(()=>{i!==void 0&&(i===null&&M.current===null||(M.current=i,e.applyTheme?.(i)))},[e,i]),(0,rn.useEffect)(()=>{f!==ye.current&&(ye.current=f,f!==void 0&&rs.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,So.jsx)("div",{ref:S,"data-testid":"flopay-vault-card-fields"})}function ci({label:e}){return(0,So.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,So.jsx)("span",{children:e}),(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var ys=require("@flopay/shared"),d=require("react/jsx-runtime"),zn="flopay_stripe_resume",Ll="flopay_wallet_resume",Kl="fw1",Pd="fw2",Gl=300*1e3,vd=900,Cd="express_checkout_click_timeout",bd=25e3,Sd=25e3,wd=1e4,In={provider:"paypal",paymentMethodCategory:"paypal"},kd="x-flopay-process-result-source",Rd="status";async function Ed(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var di={},Ia=class{constructor(t){this.reason=t}};function Id(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function ir(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ds(e){return`${Pd}:${e}`}function ui(e){return ir(ds(e))}function pi(e,t){if(typeof window>"u")return null;let r=ds(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Gl||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ui(e),null):a}catch{return ui(e),null}}function _d(e){return ir(ds(e.sessionId),e)}function Nl(e,t,r){let n=pi(e,t);return!n||n.clientSecret!==r?!1:ui(e)}function ns(e,t,r){if(typeof window>"u")return;pi(e,t)?.clientSecret===r&&ui(e)}function Td(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function os(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":pa(e.status),a=Td(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Ul(e,t,r){let n=null;try{return await Promise.race([Pl(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},wd),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Md(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Yl(e){return e instanceof c.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function yi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new _n.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Yl(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var as=c.STRIPE_PAYPAL_RESUME_KEY,Ea=new Map,xd=250,zl="Just a moment \u2014 we are finalizing your order. Please press pay again.",Ad="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function us(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function mi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new _n.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Fd(e){return e instanceof c.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Xl({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),i=(0,Uo.splitFullName)(r),l=i.firstName?i:(0,Uo.splitFullName)(n?.name);return(0,cn.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Bd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:i}){let l=Xl({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,c.isValidEmail)(l.email)?l:i(a,l)}var _a=180,ql=`flopay-card-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,jl=`flopay-card-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Dd=`flopay-buttons-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,Od=`flopay-buttons-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Ld(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ps(e){return(0,c.derivePrimaryTileStyle)(e)}var Nd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ud(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var ss={width:"100%",minHeight:Yo,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 Vl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ls(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function zd(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function qd(e,t,r){let n=(0,c.isPostalCodeSupported)(e),a=t.trim(),i=r&&n,l=i&&!a,u=i&&!!a&&!(0,c.isValidPostalCode)(e,a);return{visible:r,supported:n,required:i,empty:l,malformed:u}}function jd(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,c.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function Vd(e){return typeof e=="number"?`${e}px`:e}function fi(e){return(0,d.jsx)(Hd,{...e})}function Wl({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:i,isProcessing:l=!1,onButtonClick:u,onDecline:p,onTechnicalFailure:P,runBeforeButtonClick:w,billingName:S,onBuyerIdentityReady:E,onLoadStateChange:K,placeholderBorderRadius:I,popupCapabilityOwner:X,externalTelemetryContext:M,presentationMode:f}){let v=Qn(),{emitInstrument:ye}=(0,o.useContext)(ln),b=(0,ar.useStripe)(),Te=(0,ar.useElements)(),T=(0,o.useMemo)(()=>ni(Pr(v),M),[M,v]),[se,me]=(0,o.useState)("loading");(0,o.useEffect)(()=>{K?.(se)},[se,K]);let[pe,Fe]=(0,o.useState)(!1),dt=(0,o.useRef)(!1),He=!(0,c.isValidEmail)(r?.trim())||!S?.trim(),{request:D,collect:St,finish:Ye}=zo(),Oe=(0,o.useRef)(!1),ge=(0,o.useRef)(null),Q=(0,o.useRef)(null),[G,Be]=(0,o.useState)(0),[ze,Xe]=(0,o.useState)(!1),ne=(0,o.useRef)(!1),ee=(0,o.useRef)(new Map),{startAttempt:le,finishAttempt:V,invalidateAttempt:Ve,isAttemptInvalidated:Ae,isAttemptCurrent:he,generationRef:N}=ga((Se,x,ht)=>{P?.(Se,x,{...ht,popupBlocked:ht?.popupBlocked??(0,be.isPopupBlockedError)(x),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),Xe(!0),Be(pt=>pt+1)},{onHandoffObserved:()=>{X.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",...In,attempt:N.current})}});(0,o.useEffect)(()=>{ze&&Q.current?.focus()},[ze,G]);let Ce=(0,o.useCallback)(()=>{Be(Se=>Se+1)},[]),ut=(0,o.useCallback)((Se,x,ht)=>{Ve(ht),P?.("paypal",Se,{code:x,popupBlocked:(0,be.isPopupBlockedError)(Se),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),Xe(!0),Ce()},[Ve,P,f,Ce]),Le=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ge.current?.querySelector("iframe")??ge.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ne.current&&(ne.current=!1,Le())},[Le,G]);let ot=(0,o.useCallback)(()=>{Xe(!1),i?.(null),Le()},[Le,i]);(0,o.useEffect)(()=>{if(!b||Oe.current)return;let[Se,x,ht]=(0,c.readStripeRedirectParams)();if(!Se||!x)return;let pt=(0,c.readMatchingStripePayPalContinuation)(x);if(!pt)return;Oe.current=!0;let z=!0,we=Ea.get(x);we||(we=ht==="failed"?Promise.resolve(null):Promise.resolve().then(()=>b.retrievePaymentIntent(x)),Ea.set(x,we));let Dt={accountPatch:pt.accountPatch,sessionId:pt.sessionId,nonce:pt.nonce},Ke=()=>{T?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...In,requestCategory:"provider_sdk"})};return T?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...In}),(async()=>{try{Fe(!0);let k=await we;if(!z)return;if(k?.error){Ea.delete(x),Ke(),i?.(k.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Ea.delete(x),ht==="failed"){let We="PayPal payment was declined. Please try again.";T?.terminal({outcome:"payment_declined",...In,terminalReason:"provider_declined"}),i?.(We),p?.(hr("paypal",We));return}let A=k?.paymentIntent;if(A&&A.id!==Se){Ke(),i?.("Failed to match the returned PayPal payment.");return}if(A&&(A.status==="requires_capture"||A.status==="succeeded")){let We=typeof A.payment_method=="string"?A.payment_method:A.payment_method?.id;a({id:We??A.id,type:"card",threeDSecureActionResultTokenId:A.id,isPaypal:!0},{...Dt,presentationMode:"redirect"})}else{let We="PayPal payment was not completed. Please try again.";T?.terminal({outcome:A?.status==="canceled"?"payment_cancelled":"payment_declined",...In,terminalReason:A?.status==="canceled"?"cancelled":"provider_declined"}),i?.(We),p?.(hr("paypal",We))}}catch(k){if(!z)return;Ea.delete(x),Ke(),i?.(k instanceof Error?k.message:"Failed to complete PayPal payment.")}finally{z&&Fe(!1)}})(),()=>{z=!1,Oe.current=!1}},[b,a,i,p,T]);let Me=(0,o.useCallback)(async(Se=!1)=>{let x=w?await w("paypal"):{proceed:!0};if(!x.proceed)return ee.current.delete(G),!1;let ht=le("paypal");return ee.current.set(G,{generation:ht,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),Xe(!1),T?.log({name:`provider.${Se?"redirect.started":"handoff.requested"}`,stage:Se?"redirect":"overlay_open",...In,attempt:ht}),u?.("paypal"),!0},[u,T,w,le,G]),tt=(0,o.useCallback)(async Se=>{if(l||pe||!await Me()){Se.reject();return}Se.resolve()},[l,Me,pe]),at=(0,o.useCallback)(async Se=>{if(!b||!Te)return;let x=ee.current.get(G);if(x&&!he(x.generation)){ee.current.delete(G);return}if(!x&&Ae()||x&&!V(x.generation))return;x||V();let ht=x??null;if(ee.current.delete(G),!ht&&w){let kt=await w("paypal");if(!kt.proceed){Se.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ht={accountPatch:kt.accountPatch,sessionId:kt.sessionId,nonce:kt.nonce}}let pt=ht?.sessionId??e,z=ht?.nonce??t,we=await Bd({event:Se,prepared:ht,email:r,billingName:S,methodLabel:"PayPal",collect:St});if(!we){Se.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Dt=we.email,Ke={...ht?.accountPatch,...(0,cn.compactBuyerIdentity)(we,!0)};try{if(Fe(!0),i?.(null),!pt||!(0,c.isValidEmail)(Dt))throw new Error("Missing sessionId or email for PayPal payment");await E?.(we);let kt=b.createPaymentMethod,{error:k,paymentMethod:A}=await kt({type:"paypal"});if(k){ut(k,"stripe_paypal_create_payment_method_failed",x?.generation),Se.paymentFailed({reason:"fail"});return}let We=await yi(n,ye,pt,z??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:A?.id??null,intentKind:"payment"});if(We.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ke=We.clientSecret,ct={return_url:(0,c.stripeRedirectReturnUrl)()};if(A?.id&&(ct.payment_method=A.id),!ir(as,{clientSecret:ke,sessionId:pt,nonce:z,accountPatch:Ke})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:J,paymentIntent:q}=await b.confirmPayment({clientSecret:ke,confirmParams:ct,redirect:"if_required"});if(J){if(ir(as),(0,be.isProviderDecline)(J)){let m=J.message??"Your payment was declined.";T?.terminal({outcome:"payment_declined",...In,terminalReason:"provider_declined"}),i?.(m),p?.(hr("paypal",m,{code:(0,be.getProviderErrorCode)(J),declineCode:(0,be.getProviderDeclineCode)(J)})),await mi({billingApiUrl:n,sessionId:pt,nonce:z,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,be.getProviderErrorCode)(J)??"provider_declined"}})}else ut(J,"stripe_paypal_confirm_failed",x?.generation);return}ir(as);let ue=typeof q?.payment_method=="string"?q.payment_method:q?.payment_method?.id;a({id:ue??q?.id,type:"card",threeDSecureActionResultTokenId:q?.id,isPaypal:!0},{accountPatch:Ke,paymentMethodCategory:"paypal",presentationMode:f,sessionId:pt,nonce:z});return}catch(kt){ut(kt,"stripe_paypal_failed",x?.generation)}finally{Fe(!1)}},[b,Te,e,t,r,S,St,E,n,ye,a,i,p,w,ut,V,he,Ae,T,f,G]),lr=(0,o.useCallback)(async()=>{if(!(dt.current||l||pe||!b||!Te)){dt.current=!0,Fe(!0);try{if(!await Me(!0))return;await at({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{dt.current=!1,Fe(!1)}}},[Te,at,l,Me,b,pe]),Bt=f==="redirect"?(0,d.jsx)("button",{type:"button",disabled:l||pe,onClick:()=>{lr()},style:{width:"100%",minHeight:Yo,border:"1px solid #d1d5db",borderRadius:I??8,background:"#ffc439",color:"#111827",cursor:l||pe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(ar.ExpressCheckoutElement,{onReady:Se=>me(wa(Se,["paypal"])),onLoadError:()=>{me("load_error"),us(T,"paypal","paypal","provider_error")},onClick:tt,onConfirm:at,onCancel:()=>{let Se=ee.current.get(G);ee.current.delete(G),T?.terminal({outcome:"payment_cancelled",...In,terminalReason:"cancelled",...Se?{attempt:Se.generation}:{}}),Ve(Se?.generation),Xe(!1),ne.current=!0,Ce()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:He,emailRequired:He,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},G),wt=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:ge,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[ze&&(0,d.jsx)("button",{ref:Q,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:ss,children:"Try PayPal again"}),D&&(0,d.jsx)(qo,{identity:D.identity,methodLabel:D.methodLabel,onComplete:Ye,onCancel:()=>Ye(null)},D.id),(0,d.jsx)("div",{style:{display:D?"none":void 0},children:Bt})]}),pe&&!D&&(0,d.jsx)(Hr,{status:"processing"})]});return f==="redirect"?wt:(0,d.jsx)(ka,{state:se,placeholderTestId:"flopay-paypal-placeholder",borderRadius:I,children:wt})}function is(e){return e==="apple_pay"||e==="google_pay"}var Wd=200;function $d({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,c.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function $l({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:i,onTokenizedBody:l,onErrorChange:u,onButtonClick:p,onDecline:P,onTechnicalFailure:w,runBeforeButtonClick:S,billingName:E,onBuyerIdentityReady:K,onLoadStateChange:I,placeholderBorderRadius:X,popupCapabilityOwner:M,externalTelemetryContext:f}){let v=Qn(),{emitInstrument:ye}=(0,o.useContext)(ln),b=(0,ar.useStripe)(),Te=(0,ar.useElements)(),T=(0,o.useMemo)(()=>ni(Pr(v),f),[f,v]),[se,me]=(0,o.useState)("loading");(0,o.useEffect)(()=>{I?.(se)},[se,I]);let[pe,Fe]=(0,o.useState)(!1);(0,o.useEffect)(()=>{Xe.current=pe},[pe]);let dt=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!E?.trim()).current,{request:He,collect:D,finish:St}=zo(),Ye=(0,o.useRef)(null),Oe=(0,o.useRef)(null),[ge,Q]=(0,o.useState)(0),[G,Be]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),ze=(0,o.useRef)(G),Xe=(0,o.useRef)(!1),[ne,ee]=(0,o.useState)(!1),[le,V]=(0,o.useState)(()=>pi(e,t)?"blocked":"idle"),[Ve,Ae]=(0,o.useState)("google_pay"),he=(0,o.useRef)(null),N=(0,o.useRef)(!0),Ce=(0,o.useRef)(!1),ut=(0,o.useRef)("google_pay"),Le=(0,o.useRef)("google_pay"),ot=(0,o.useRef)(null),Me=(0,o.useRef)(null),tt=(0,o.useRef)(new Set),at=(0,o.useRef)(null),lr=(0,o.useRef)(null);(0,o.useEffect)(()=>(N.current=!0,()=>{N.current=!1;for(let g of tt.current)window.clearTimeout(g);tt.current.clear()}),[]);let Bt=(0,o.useRef)(new Map),{startAttempt:wt,finishAttempt:Se,invalidateAttempt:x,isAttemptInvalidated:ht,isAttemptCurrent:pt,generationRef:z}=ga((g,J,q)=>{w?.(g,J,{...q,popupBlocked:q?.popupBlocked??(0,be.isPopupBlockedError)(J),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Ae(g),ee(!0),Q(ue=>ue+1)},{onHandoffObserved:g=>{lr.current=z.current,M.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:z.current,...g==="apple_pay"||g==="google_pay"?{walletType:g}:{}})},defersMissingTerminal:is,onMissingTerminalDeferred:(g,J)=>{let q=T?.now()??globalThis.performance?.now()??Date.now(),ue=at.current,m=ue?.generation===J?ue.startedAt:q;T?.performance({stage:"overlay_return",durationMs:Math.max(0,q-m),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:J,...is(g)?{walletType:g}:{}}),T?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{ne&&Oe.current?.focus()},[ne,ge]);let we=(0,o.useCallback)(()=>{Q(g=>g+1)},[]),Dt=(0,o.useCallback)((g,J,q,ue,m=!1)=>{x(ue),w?.(g,J,{code:q,popupBlocked:(0,be.isPopupBlockedError)(J),telemetryReported:m,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Ae(g),ee(!0),we()},[x,w,we]),Ke=(0,o.useCallback)(g=>{T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...is(g)?{walletType:g}:{}}),w?.(g,new Error("The wallet click was not ready within the time the wallet allows."),{code:Cd,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Ae(g),ee(!0)},[w,T]),kt=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Ye.current?.querySelector("iframe")??Ye.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Ce.current&&(Ce.current=!1,kt())},[kt,ge]);let k=(0,o.useCallback)(()=>{ee(!1),u?.(null),kt()},[kt,u]),A=(0,o.useCallback)(()=>{he.current?.()},[]);(0,o.useEffect)(()=>{let g=null,J=()=>{g=null;let ue=(0,c.shouldPreferWalletPopup)();ue!==ze.current&&(ze.current=ue,Be(ue),!Xe.current&&!pt(z.current)&&we())},q=()=>{g!==null&&window.clearTimeout(g),g=window.setTimeout(J,Wd)};return window.addEventListener("resize",q),()=>{window.removeEventListener("resize",q),g!==null&&window.clearTimeout(g)}},[z,pt,we]),(0,o.useEffect)(()=>{let g=pi(e,t);if(!g)return;let J=!1,q=!1,ue=async()=>{if(!q){q=!0,J||V("checking");try{let m=await Ul(b,g.clientSecret,tt.current);if(J)return;let Z=os(m,g.providerObjectId,(0,c.isSetupIntentClientSecret)(g.clientSecret));if(Z.kind==="confirmed"){if(!Nl(e,t,g.clientSecret))return;he.current=null,V("idle"),l({id:Z.paymentMethodId,type:"card",threeDSecureActionResultTokenId:Z.intentId},{...g.accountPatch?{accountPatch:g.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(Z.kind==="terminal"){ns(e,t,g.clientSecret),he.current=null,V("idle"),Ae(g.paymentMethodType),ee(!0),we();return}V("blocked")}catch{J||V("blocked")}finally{q=!1}}};return he.current=ue,V("blocked"),()=>{J=!0,he.current===ue&&(he.current=null)}},[t,l,we,e,b]);let We=(0,o.useCallback)(async g=>{let J=!1,q=it=>{J||(J=!0,g.paymentFailed({reason:"fail",...it?{message:it}:{}}))};if(!b||!Te){q();return}let ue=Bt.current.get(ge);if(ue&&!pt(ue.generation)){Bt.current.delete(ge),q();return}if(!ue&&ht()){q();return}if(ue&&!Se(ue.generation)){q();return}ue||Se();let m=g.expressPaymentType??ue?.method??ut.current,Z=ue??null,xe=Vl(m),rt;m==="apple_pay"?rt="apple_pay":m==="google_pay"&&(rt="google_pay");let oe=ue?.generation??z.current,$=T,Vt=$?.now()??globalThis.performance?.now()??Date.now(),Ir=new AbortController,br=!1,Gt=!1,Yt=null,Ur=e,_r="processing",Qt="other",zr="provider_runtime",Wt,Vn=new Promise((it,Mt)=>{Wt=Mt}),Xt=window.setTimeout(()=>{br=!0,Ir.abort(),Wt(di)},bd),Gr=async(it,Mt,jt)=>{_r=it,Qt=Mt,zr=Mt==="intent_create"||Mt==="session_claim"?"transport_error":"provider_runtime";let Jt=$?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([jt,Vn])}finally{let Dr=$?.now()??globalThis.performance?.now()??Date.now();$?.performance({stage:it,durationMs:Math.max(0,Dr-Jt),durationMode:"machine",requestCategory:Mt,paymentMethodCategory:"wallet",provider:"stripe",...br?{statusClass:"timeout"}:{}})}};try{if(Fe(!0),u?.(null),!Z&&S){let _=await Gr("processing","other",S(xe));if(!_.proceed){q();return}Z={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let it=Z?.sessionId??e;Ur=it;let Mt=Z?.nonce??t,jt=ot.current??Z?.accountPatch,Jt=Xl({event:g,fallbackEmail:jt?.email??r,fallbackName:[jt?.firstName,jt?.lastName].join(" ").trim()||E});if(!(0,c.isValidEmail)(Jt.email)){q("Buyer details are required."),D(ls(m),Jt).then(_=>{_&&(ot.current=_)});return}ot.current=null;let Dr={...Z?.accountPatch,...(0,cn.compactBuyerIdentity)(Jt,!0)};await Gr("processing","session_claim",Promise.resolve(K?.(Jt)));let{error:qr}=await Gr("tokenization","provider_sdk",Te.submit());if(qr){q(),Dt(m,qr,"stripe_wallet_submit_failed",ue?.generation);return}if(!it)throw new Error("Missing sessionId or email for payment.");let Sr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:m,paymentMethodId:null,intentKind:a},wr=JSON.stringify({sessionId:it,nonce:Mt??"",request:Sr}),fr=Me.current,Tr=fr?.retryIdentity===wr?fr.authorizationAttemptId:(0,c.randomUuidV4)();Me.current={authorizationAttemptId:Tr,retryIdentity:wr};let Ot=await Gr("processing","intent_create",yi(n,ye,it,Mt??"",{...Sr,authorizationAttemptId:Tr},{signal:Ir.signal}));if(Ot.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Lt=Ot.clientSecret,Mr=_d({createdAt:Date.now(),sessionId:it,...Mt?{nonce:Mt}:{},clientSecret:Lt,providerObjectId:Ot.providerObjectId,paymentMethodType:m,accountPatch:Dr});window.clearTimeout(Xt),Gt=!0,$?.performance({stage:"callback",durationMs:Math.max(0,($?.now()??globalThis.performance?.now()??Date.now())-Vt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let cr=$?.now()??globalThis.performance?.now()??Date.now(),qe={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...rt?{walletType:rt}:{},attempt:oe},fn=!1,xr=null;$?.log({name:"payment.provider_confirmation.started",...qe}),Yt=window.setTimeout(()=>{Yt!==null&&tt.current.delete(Yt),fn=!0;let _=$?.now()??globalThis.performance?.now()??Date.now();$?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...qe,operationOutcome:"watchdog_expired",durationMs:Math.max(0,_-cr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),$?.flush?.().catch(()=>{}),xr?.()},Sd),tt.current.add(Yt);let Wn=(_,xt)=>{Yt!==null&&(window.clearTimeout(Yt),tt.current.delete(Yt),Yt=null);let At=$?.now()??globalThis.performance?.now()??Date.now(),Et=Math.max(0,At-cr),tr=_;fn&&(_==="resolved"?tr="resolved_late":_==="returned_error"?tr="returned_error_late":tr="rejected_late");let yt=xt??(_==="resolved"?"approved":"provider_error");return $?.log({name:"payment.provider_confirmation.returned",...qe,operationOutcome:tr,terminalReason:yt}),$?.performance({...qe,durationMs:Et,durationMode:"buyer",operationOutcome:tr,terminalReason:yt}),{durationMs:Et,operationOutcome:tr,terminalReason:yt}},er=!1,Ar=!1,Tn=_=>{if(!_||typeof _!="object")return null;let xt=_;if(xt.error)return null;let At=xt.setupIntent??xt.paymentIntent,Et=os(At??null,void 0,!!xt.setupIntent);return Et.kind==="confirmed"?Et:null},gn=_=>{if(er||ue&&z.current!==ue.generation)return;let xt=Tn(_);if(!xt)return;if(Mr&&!Nl(it,Mt,Lt)){er=!0;return}let{intentId:At,paymentMethodId:Et}=xt;er=!0,Ar=!0,Me.current=null,he.current=null,N.current&&(V("idle"),Fe(!1));let tr=`${Kl}:${it}`;ir(tr,{createdAt:Date.now(),sessionId:it,nonce:Mt,accountPatch:Dr,paymentMethodId:Et,providerIntentId:At,paymentMethodType:m});try{l({id:Et,type:"card",threeDSecureActionResultTokenId:At},{accountPatch:Dr,paymentMethodCategory:"wallet",sessionId:it,nonce:Mt})}finally{ir(tr)}},$t=!1;xr=async()=>{if(!($t||er||Ar)){$t=!0,N.current&&V("checking");try{let _=await Ul(b,Lt,tt.current);if(er||Ar)return;let xt=(0,c.isSetupIntentClientSecret)(Lt),At=os(_,Ot.providerObjectId,xt);if(At.kind==="confirmed"){gn(xt?{setupIntent:_}:{paymentIntent:_});return}if(At.kind==="terminal"){if(Ar=!0,ns(it,Mt,Lt),Me.current=null,he.current=null,!N.current)return;V("idle"),q(),Dt(m,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",ue?.generation,!0);return}N.current&&!Ar&&(V("blocked"),Fe(!1))}catch{N.current&&!Ar&&(V("blocked"),Fe(!1))}finally{$t=!1}}},he.current=xr;let fe,te;try{let _=await((0,c.isSetupIntentClientSecret)(Lt)?b.confirmSetup({elements:Te,clientSecret:Lt,redirect:"if_required"}):b.confirmPayment({elements:Te,clientSecret:Lt,redirect:"if_required"}));if(!_||typeof _!="object")throw new Ia(Id(_));if(fe=_,!fe.error&&!Tn(fe))throw new Ia("confirmation_result_unconfirmed");te=Wn(fe.error?"returned_error":"resolved",fe.error&&(0,be.isProviderDecline)(fe.error)?"provider_declined":void 0)}catch(_){let xt=_ instanceof Ia?_.reason:void 0,At=xt!==void 0,Et=Wn(At?"returned_error":"rejected");if($?.error({...At?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:xt}:Gi(_),...qe,operationOutcome:Et.operationOutcome,durationMs:Et.durationMs,statusClass:"unknown",terminalReason:Et.terminalReason}),!N.current||er)return;await xr?.();return}let Ct=fe.error;if(Ct){if(!N.current||er)return;if((0,be.isProviderDecline)(Ct)){Ar=!0,ns(it,Mt,Lt),Me.current=null,he.current=null,V("idle");let _=Ct.message??"Your payment was declined.";q(_),u?.(_),P?.(hr(xe,_,{code:(0,be.getProviderErrorCode)(Ct),declineCode:(0,be.getProviderDeclineCode)(Ct)})),mi({billingApiUrl:n,sessionId:it,nonce:Mt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:m,providerDeclineReason:(0,be.getProviderErrorCode)(Ct)??"provider_declined",...Ot.intentKind==="payment"&&Ot.providerObjectId.startsWith("pi_")?{providerIntentId:Ot.providerObjectId}:{}}})}else $?.error({...Gi(Ct),...qe,operationOutcome:te.operationOutcome,durationMs:te.durationMs,statusClass:"unknown",terminalReason:te.terminalReason}),await xr?.();return}if(gn(fe),!er)throw new Error("Invalid provider returned for APM intent")}catch(it){if(it===di){let Mt=$?.now()??globalThis.performance?.now()??Date.now();$?.error({errorCode:Md(Qt),stage:_r,requestCategory:Qt,paymentMethodCategory:"wallet",provider:"stripe",...rt?{walletType:rt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ur,durationMs:Math.max(0,Mt-Vt),statusClass:"timeout",failureCategory:zr,attempt:oe,terminalReason:"provider_error"}),$?.flush?.().catch(()=>{})}q(),Dt(m,it,it===di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",ue?.generation,it===di)}finally{if(window.clearTimeout(Xt),Yt!==null&&(window.clearTimeout(Yt),tt.current.delete(Yt)),!Gt){let it=$?.now()??globalThis.performance?.now()??Date.now();$?.performance({stage:"callback",durationMs:Math.max(0,it-Vt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...br?{statusClass:"timeout"}:{}})}N.current&&Fe(!1)}},[b,Te,e,t,r,E,D,K,n,ye,a,l,u,P,S,Dt,Se,pt,ht,z,T,ge]),ke=(0,o.useMemo)(()=>ai(i),[i]),ct=(0,o.useMemo)(()=>i.map(c.stripeExpressMethodToOptionKey),[i]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ka,{state:se,placeholderTestId:"flopay-wallet-placeholder",borderRadius:X,children:(0,d.jsxs)("div",{ref:Ye,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ne&&(0,d.jsxs)("button",{ref:Oe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:k,style:ss,children:["Try ",ls(Ve)," again"]}),le!=="idle"&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,d.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,d.jsx)("button",{type:"button",onClick:A,disabled:le==="checking",style:ss,children:le==="checking"?"Checking payment status\u2026":"Check payment status"})]}),He&&(0,d.jsx)(qo,{identity:He.identity,methodLabel:He.methodLabel,onComplete:St,onCancel:()=>St(null)},He.id),le==="idle"&&(0,d.jsxs)("div",{style:{display:He?"none":void 0},children:[(0,d.jsx)($d,{active:G}),(0,d.jsx)(ar.ExpressCheckoutElement,{onReady:g=>{me(wa(g,ct))},onLoadError:g=>{me("load_error"),us(T,"stripe","wallet","provider_error")},onClick:async g=>{let J=T?.now()??globalThis.performance?.now()??Date.now();ut.current=g.expressPaymentType,Le.current=Vl(g.expressPaymentType);let q=!0,ue=window.setTimeout(()=>{q=!1,g.reject(),Ke(g.expressPaymentType)},vd),m=S?await S(Le.current,{abandoned:()=>!q}):{proceed:!0};if(window.clearTimeout(ue),!q)return;if(!m.proceed){Bt.current.delete(ge),g.reject();return}let Z=wt(g.expressPaymentType);at.current={generation:Z,startedAt:J},Bt.current.set(ge,{generation:Z,method:g.expressPaymentType,accountPatch:m.accountPatch,sessionId:m.sessionId,nonce:m.nonce}),ee(!1),T?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Z,...g.expressPaymentType==="apple_pay"||g.expressPaymentType==="google_pay"?{walletType:g.expressPaymentType}:{}}),p?.(Le.current),g.resolve()},onConfirm:We,onCancel:()=>{let g=Bt.current.get(ge);Bt.current.delete(ge);let J=at.current,q=T?.now()??globalThis.performance?.now()??Date.now();if(g&&J?.generation===g.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:g.method,elapsedMs:q-J.startedAt,handoffObserved:lr.current===g.generation})){T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:g.generation,walletType:"google_pay"}),Me.current=null,Dt(g.method,new Error("The browser window is too small for the Google Pay sheet."),c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,g.generation,!0);return}T?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...g?{attempt:g.generation}:{}}),x(g?.generation),Me.current=null,ee(!1),Ce.current=!0,we()},options:{...ii,paymentMethods:ke,emailRequired:dt,billingAddressRequired:dt}},ge)]})]})}),pe&&(0,d.jsx)(Hr,{status:"processing"})]})}function Jl(e,t,r){let n=(0,c.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,paymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function cs({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:u,onErrorChange:p,onDecline:P,onCancel:w,runBeforeButtonClick:S,onButtonClick:E,isProcessing:K,submitButtonColor:I,submitButtonBorderRadius:X,submitButtonStyle:M,errorText:f}){let v=Qn(),{emitInstrument:ye}=(0,o.useContext)(ln),b=(0,ar.useStripe)(),Te=(0,ar.useElements)(),[T,se]=(0,o.useState)(!1),me=(0,o.useRef)(!1),[pe,Fe]=(0,o.useState)(!1),[dt,He]=(0,o.useState)("loading"),[D,St]=(0,o.useState)(""),Ye=!(0,c.isValidEmail)(n?.trim()),Oe=!Ye||(0,c.isValidEmail)(D.trim()),ge=(0,o.useCallback)(async()=>{if(!b||!Te||K||me.current||!pe)return;me.current=!0,se(!0);let Q=S?await S("card"):{proceed:!0};if(!Q.proceed){me.current=!1,se(!1);return}E?.("card");let G=Q.sessionId??t,Be=Q.nonce??r,ze=(0,Uo.splitFullName)(a?.trim()),Xe=(0,cn.compactBuyerIdentity)({email:Q.accountPatch?.email?.trim()||n?.trim()||D.trim(),firstName:Q.accountPatch?.firstName?.trim()||ze.firstName,lastName:Q.accountPatch?.lastName?.trim()||ze.lastName}),ne=Xe.email,ee=(0,cn.compactBuyerIdentity)({...Q.accountPatch,...Xe});try{if(p?.(null),!(0,c.isValidEmail)(ne))throw new Error("A valid email address is required for payment.");await i?.(Xe);let le=await Te.submit();if(le.error){p?.(le.error.message??"Payment failed.");return}let V=[Xe.firstName,Xe.lastName].filter(Boolean).join(" "),Ve=await b.createPaymentMethod({elements:Te,params:{billing_details:{email:ne,...V?{name:V}:{}}}});if(Ve.error||!Ve.paymentMethod){p?.(Ve.error?.message??"Failed to create payment method.");return}let Ae=Ve.paymentMethod;if(!G||!ne)throw new Error("Missing sessionId or email for payment.");let he=Ae.type||e,N=await yi(l,ye,G,Be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:he,paymentMethodId:null,intentKind:"payment"});if(N.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ce=N.clientSecret;ir(zn,{clientSecret:Ce,sessionId:G,nonce:Be,accountPatch:ee,paymentMethodId:Ae.id,paymentMethodType:Ae.type??e,gateway:"stripe"});let{error:ut,paymentIntent:Le}=await b.confirmPayment({clientSecret:Ce,confirmParams:{return_url:window.location.href,payment_method:Ae.id},redirect:"if_required"});if(ut){ir(zn);let tt=ut.message??"Payment failed.";p?.(tt),P?.(hr("card",tt,{code:ut.code})),await mi({billingApiUrl:l,sessionId:G,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ut.code??"provider_declined"}});return}let ot=Le?.status;if(!pa(ot)){ir(zn);let tt=ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(tt),P?.(hr("card",tt,{code:ot??"missing_payment_intent"}));return}ir(zn);let Me=typeof Le?.payment_method=="string"?Le.payment_method:Le?.payment_method?.id;u({id:Me??Ae.id,type:"card",threeDSecureActionResultTokenId:Le?.id,gateway:"stripe",paymentMethodType:Ae.type??e},{accountPatch:ee,paymentMethodCategory:"apm",sessionId:G,nonce:Be})}catch(le){p?.(le instanceof Error?le.message:"Payment failed. Please try again.")}finally{me.current=!1,se(!1)}},[b,Te,K,pe,S,E,t,r,n,a,D,i,l,ye,e,u,p,P]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ye&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ye&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:D,onChange:Q=>St(Q.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(ar.PaymentElement,{onReady:()=>He("ready"),onLoadError:()=>{He("load_error"),us(Pr(v),"stripe","apm")},onChange:Q=>{Fe(!!Q.complete)},options:{layout:si,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,c.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,d.jsx)(li,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ge()},disabled:!pe||!Oe||T||K||dt!=="ready",color:I,borderRadius:X,style:M,children:T?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),f&&(0,d.jsx)(Wo,{margin:"0.75rem 0 0",children:f})]})}function Hl({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:l,stripeInstance:u,paymentElementBaseOptions:p,futureUseSession:P,onTokenizedBody:w,onErrorChange:S,onButtonClick:E,onDecline:K,runBeforeButtonClick:I,onLoadStateChange:X,isProcessing:M=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:v=8,submitButtonStyle:ye,buttonAppearance:b,themeId:Te,onExpandApm:T,expandedApmMethod:se}){let{emitInstrument:me}=(0,o.useContext)(ln),[pe,Fe]=(0,o.useState)(null),[dt,He]=(0,o.useState)(null),D=(0,o.useRef)(!1),{request:St,collect:Ye,finish:Oe}=zo();(0,o.useEffect)(()=>{l.length>0&&u?X?.("ready"):u||X?.("loading")},[l.length,u,X]);let ge=(0,o.useCallback)(async ne=>{if(!u||D.current||M)return;D.current=!0,He(ne);let ee=I?await I("card"):{proceed:!0};if(!ee.proceed){D.current=!1,He(null);return}E?.("card");let le=ee.sessionId??e,V=ee.nonce??t,Ve=(0,Uo.splitFullName)([ee.accountPatch?.firstName,ee.accountPatch?.lastName].filter(Boolean).join(" ")||n),Ae=(0,cn.compactBuyerIdentity)({email:ee.accountPatch?.email?.trim()||r?.trim(),firstName:ee.accountPatch?.firstName?.trim()||Ve.firstName,lastName:ee.accountPatch?.lastName?.trim()||Ve.lastName});if(!(0,c.isValidEmail)(Ae.email)){He(null);let Ce=await Ye((0,c.getStripeMethodDisplayName)(ne),Ae);if(!Ce){D.current=!1;return}Ae=Ce,He(ne)}let he=Ae.email,N=(0,cn.compactBuyerIdentity)({...ee.accountPatch,...Ae});try{if(S?.(null),!le||!(0,c.isValidEmail)(he))throw new Error("Missing sessionId or email for payment.");await a?.(Ae);let Ce=await yi(i,me,le,V??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(Ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ut=Ce.clientSecret;ir(zn,{clientSecret:ut,sessionId:le,nonce:V,accountPatch:N,paymentMethodType:ne,gateway:"stripe"});let{error:Le,paymentIntent:ot}=await u.confirmPayment({clientSecret:ut,confirmParams:{return_url:window.location.href,payment_method_data:{type:ne,billing_details:{name:[Ae.firstName,Ae.lastName].filter(Boolean).join(" "),...he?{email:he}:{}}}},redirect:"if_required"});if(Le){ir(zn);let at=Le.message??"Payment failed.";S?.(at),K?.(hr("card",at,{code:Le.code})),await mi({billingApiUrl:i,sessionId:le,nonce:V,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:Le.code??"provider_declined"}});return}let Me=ot?.status;if(!pa(Me)){ir(zn);let at=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(at),K?.(hr("card",at,{code:Me??"missing_payment_intent"}));return}ir(zn);let tt=typeof ot?.payment_method=="string"?ot.payment_method:ot?.payment_method?.id;w({id:tt??ot?.id,type:"card",threeDSecureActionResultTokenId:ot?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:N,paymentMethodCategory:"apm",sessionId:le,nonce:V})}catch(Ce){S?.(Ce instanceof Error?Ce.message:"Payment failed. Please try again.")}finally{D.current=!1,He(null)}},[u,M,I,E,e,t,r,Ye,i,me,n,a,w,S,K]),[Q,G]=(0,o.useState)(null),Be=T?se??null:Q,ze=(0,o.useCallback)(ne=>{D.current||M||Be&&Be!==ne||((0,c.needsStripeMethodExplicitConfirm)(ne)?T?T(ne):G(ne):ge(ne))},[Be,M,ge,T]),Xe=(0,o.useMemo)(()=>Q?Jl(p,Q,P):null,[Q,p,P]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:St?(0,d.jsx)(qo,{identity:St.identity,methodLabel:St.methodLabel,onComplete:Oe,onCancel:()=>Oe(null)},St.id):l.map(ne=>{let ee=se===ne,le=dt===ne,V=dt!==null&&dt!==ne||se!=null&&se!==ne;return(0,d.jsxs)(o.default.Fragment,{children:[(0,d.jsx)(oi,{method:ne,themeId:Te,submitting:le,disabled:V,highlighted:ee,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(ne),onClick:()=>ze(ne),backgroundColor:b?.backgroundColor,borderColor:b?.borderColor,textColor:b?.textColor,borderRadius:b?.borderRadius,fontFamily:b?.fontFamily}),!T&&Q===ne&&Xe&&u&&(0,d.jsx)(ar.Elements,{stripe:u,options:Xe,children:(0,d.jsx)(cs,{method:ne,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:w,onErrorChange:S,onDecline:K,onCancel:()=>G(null),runBeforeButtonClick:I,onButtonClick:E,isProcessing:M,submitButtonColor:f,submitButtonBorderRadius:v,submitButtonStyle:ye})},ne)]},ne)})})}function Hd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:i,onComplete:l,onError:u,onDecline:p,onCancel:P,onTokenizedBody:w,firstName:S,lastName:E,chv:K,className:I,submitLabel:X,isProcessing:M,error:f,onErrorChange:v,showPayPal:ye=!0,showStripe:b=!0,walletPresentation:Te="auto",enabledPaymentMethods:T,enabledPaymentMethodCountries:se,showApplePay:me=!0,showGooglePay:pe=!0,layout:Fe="default",theme:dt,buttonsTheme:He,buttonsStyles:D,appearance:St,cardButtonContent:Ye,cardBackButtonContent:Oe,cardTitleContent:ge,showSecurityFooter:Q,onButtonClick:G,onBeforeButtonClick:Be,onBuyerIdentityReady:ze,enableAVS:Xe,cardFieldOrder:ne,cardPreFormSlot:ee,avsLayout:le="row",country:V,zip:Ve,addressLine1:Ae,addressLine2:he,city:N,state:Ce,onCountryChange:ut,onZipChange:Le,avsCheck:ot,checkoutType:Me,checkoutLayout:tt,totalAmount:at=0,currency:lr="usd",initialCardOpen:Bt=!1,directPaypal:wt,isSubscription:Se=!1,session:x,dataAttachmentPending:ht=!1,dataAttachmentRequiresIdentity:pt=!1,debug:z=!1}){let we=Qn(),Dt=Ga(),Ke=(0,o.useContext)(kn),{emitInstrument:kt}=(0,o.useContext)(ln),k=(0,o.useRef)(null);k.current||(k.current=Xa());let A=k.current,[,We]=(0,o.useState)(0),ke=(0,o.useRef)(null);ke.current||(ke.current=(0,Ln.detectPayPalEnvironment)());let ct=ke.current,g=(0,o.useMemo)(()=>({browser:ct,capability:A,presentationMode:"popup"}),[ct,A]),J=x??Ke.session,q=(0,o.useMemo)(()=>({futureUse:J?.futureUse,futureUseUnsupported:J?.futureUseUnsupported}),[J?.futureUse,J?.futureUseUnsupported]),ue=J?.gateways?.paypal?.providerObjectType??wt?.providerObjectType,m=ht||Ke.claimPending===!0,Z=pt||Ke.claimRequiresIdentity===!0,xe=m&&!Z,rt=Sl(),oe=r||rt,[$,Vt]=(0,o.useState)(!1),[Ir,br]=(0,o.useState)(null),[Gt,Yt]=(0,o.useState)(V??""),[Ur,_r]=(0,o.useState)(Ve??""),[Qt,zr]=(0,o.useState)(Ae??""),[Wt,Vn]=(0,o.useState)(he??""),[Xt,Gr]=(0,o.useState)(N??""),[it,Mt]=(0,o.useState)(Ce??""),[jt,Jt]=(0,o.useState)(""),[Dr,qr]=(0,o.useState)({}),Sr=(0,o.useRef)(Ve??""),wr=(0,o.useRef)(V??""),fr=(0,o.useRef)(Ae??""),Tr=(0,o.useRef)(he??""),Ot=(0,o.useRef)(N??""),Lt=(0,o.useRef)(Ce??""),Mr=(0,o.useRef)(""),cr=(0,o.useRef)({});(0,o.useEffect)(()=>{let s=(O,ie,Ie,Y,_e)=>{if(cr.current[O])return;let zt=ie?.trim();!zt||zt===Ie.current||(Ie.current=zt,Y(zt),_e?.(zt))};s("country",V,wr,Yt,ut),s("zip",Ve,Sr,_r,Le),s("addressLine1",Ae,fr,zr),s("addressLine2",he,Tr,Vn),s("city",N,Ot,Gr),s("state",Ce,Lt,Mt)},[V,Ve,Ae,he,N,Ce,ut,Le]);let qe=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(Xe),[Xe]),fn=qe!==null,xr=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(x),[x]),Wn=(0,c.isMountableVaultBlock)(x?.vault),er=!!x?.gateways?.pcivault,Ar=(0,wn.hasServerSideCardGateway)(x),gn=!!(x?.gateways?.stripe?.enabledPaymentMethods??T)?.includes("card")||(0,wn.canRecoverHostedCardForm)(x),$t=Wn||gn||er,fe=!!(b&&$t&&e),[te,Ct]=(0,o.useState)(()=>Fe!=="buttons"||Bt?e??null:null),[_,xt]=(0,o.useState)(0),At=Fe!=="buttons"||Bt||!!e&&te===e,Et=x?.captureMethod,tr=(0,o.useRef)(we);(0,o.useEffect)(()=>{tr.current=we},[we]);let[yt,oo]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!fe||!e||!At){oo(null);return}let s=tr.current?tr.current.cardCapture({sessionId:e,captureMethod:Et}):new _n.PciVaultCardCapture({sessionId:e,captureMethod:Et,billingApiUrl:oe,telemetry:n});return oo({sessionId:e,captureMethod:Et,billingApiUrl:oe,telemetry:n,capture:s}),()=>{s.unmount()}},[fe,e,At,Et,oe,n]);let Nt=fe&&e&&At&&yt?.sessionId===e&&yt.captureMethod===Et&&yt.billingApiUrl===oe&&yt.telemetry===n?yt.capture:null,Yr=(0,o.useMemo)(()=>{let s=Gt,O=qe?(0,c.isAVSFieldVisible)(qe.postal_code,s):!1;return qd(s,Ur,O)},[qe,Gt,Ur]),{avsInvalid:Mn,invalidAvsFields:nn}=(0,o.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!fe||!qe)return{avsInvalid:!1,invalidAvsFields:s};let O=Gt,ie=(_e,zt)=>(0,c.isAVSFieldVisible)(_e,O)&&!zt.trim(),Ie={line1:ie(qe.address_line_1,Qt),city:ie(qe.city,Xt),state:ie(qe.state,it),zip:Yr.empty||Yr.malformed};return{avsInvalid:Ie.line1||Ie.city||Ie.state||Ie.zip,invalidAvsFields:Ie}},[fe,qe,Gt,Qt,Xt,it,Yr]),[rr,hn]=(0,o.useState)(!1),[$n,xn]=(0,o.useState)(!1),[Or,ao]=(0,o.useState)(!1),[on,Hn]=(0,o.useState)({line1:!1,city:!1,state:!1}),Xr=(0,o.useRef)(!1),Pn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),An=(0,o.useRef)(!1),Ut=(0,o.useCallback)(s=>{Pn.current[s]=!0,An.current=!0},[]),Jr=(0,o.useCallback)(s=>!Xr.current&&Pn.current[s],[]),Zr=(0,o.useCallback)(s=>{Jr(s)&&Hn(O=>O[s]?O:{...O,[s]:!0})},[Jr]),[jr,vn]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(x?.vault,{billingApiUrl:oe,sessionId:e,nonce:t})),[bt,kr]=(0,o.useState)(Bt&&$t?"card":"buttons"),[dr,Vr]=(0,o.useState)(null),yo=bt==="expanding"||bt==="card",Cn=x?.gateways?.stripe&&!Ar?"stripe":void 0,Kn=(0,o.useCallback)(()=>{kt?.({class:"card_surface",provider:Cn})},[Cn,kt]),Qr=(0,o.useRef)(null),Rr=(0,o.useCallback)(s=>{Qr.current&&clearTimeout(Qr.current),Qr.current=setTimeout(()=>{Qr.current=null,s()},_a)},[]);(0,o.useEffect)(()=>()=>{Qr.current&&clearTimeout(Qr.current)},[]);let Fn=(0,o.useRef)(!1),[Fr,L]=(0,o.useState)(0),U=(0,o.useRef)(null),re=(0,o.useCallback)(()=>{Kn(),Ct(e??null),Fn.current&&(Fn.current=!1,L(s=>s+1)),xt(s=>s+1),kr("expanding"),Rr(()=>kr("card"))},[Rr,Kn,e]),Re=(0,o.useCallback)(()=>{kr("collapsing"),Rr(()=>kr("buttons"))},[Rr]),It=(0,o.useCallback)(s=>{Vr(s),kr("apm-expanding"),Rr(()=>kr("apm-form"))},[Rr]),nr=(0,o.useCallback)(()=>{kr("apm-collapsing"),Rr(()=>{kr("buttons"),Vr(null)})},[Rr]);(0,o.useEffect)(()=>{Fe==="buttons"&&Bt&&$t&&(Ct(e??null),kr("card"))},[Fe,Bt,$t,e]);let[Ne,ce]=(0,o.useState)(null),j=(0,o.useRef)(!1),W=(0,o.useRef)(null),de=(0,o.useRef)("idle"),[h,y]=(0,o.useState)(!1),H=(0,o.useRef)(h);H.current=h;let[Ee,Je]=(0,o.useState)(()=>wt?.existingOrderId?{orderId:wt.existingOrderId,attempts:1}:null),mt=(0,o.useRef)(Ee);(0,o.useEffect)(()=>{mt.current=Ee},[Ee]);let Ue=(0,o.useRef)(null),De=(0,o.useMemo)(()=>{if(ze||Ke.claimBuyerIdentity||x?.buyerIdentified!==!1||!e||!t)return;let s=`${oe}|${e}|${t}`;Ue.current?.key!==s&&(Ue.current={key:s,claim:Lo(new _n.PaymentAPI(oe,{telemetry:!1}),e,t,{...i?{userId:i}:{},...S?{firstName:S}:{},...E?{lastName:E}:{}})});let O=Ue.current.claim;return async ie=>{await O(ie)}},[ze,Ke.claimBuyerIdentity,x?.buyerIdentified,e,t,oe,i,S,E]),st=ze??Ke.claimBuyerIdentity??De,Rt=f??Ir,_t=(0,o.useMemo)(()=>(0,c.resolveTheme)(dt),[dt]),F=(0,o.useMemo)(()=>{let s=_t?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(He);return D?{...s,...D,cardButton:{...s.cardButton,...D.cardButton},cardFormContainer:{...s.cardFormContainer,...D.cardFormContainer},backButton:{...s.backButton,...D.backButton},backButtonIcon:{...s.backButtonIcon,...D.backButtonIcon},submitButton:{...s.submitButton,...D.submitButton},title:{...s.title,...D.title}}:s},[_t,He,D]),Pe=St??_t?.appearance,Ze=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:Pe,buttonsStyles:F,layout:Fe}),[Pe,F,Fe]),nt=Ke.inlineSessionPatchProcessing??!1,ae=(M??$)||nt,ur=oe.replace(/\/+$/,""),ve=(0,o.useMemo)(()=>Ki({userId:i,email:a,firstName:S,lastName:E,country:V,zip:Ve},Dr),[i,a,S,E,V,Ve,Dr]),Gn=[ve.firstName,ve.lastName].filter(s=>!!s?.trim()).join(" "),ks=!(0,c.isValidEmail)(ve.email?.trim()),ki=(0,o.useRef)(null);fe&&ki.current===null&&(ki.current=ks);let io=fe&&(ki.current??ks),Ri=(0,o.useMemo)(()=>jd(jt,io),[jt,io]),ko=Ri.empty||Ri.malformed,en=(0,o.useMemo)(()=>we?we.getRawProvider():null,[we]),Rs=(0,o.useMemo)(()=>Dt?Dt.getRawProvider():null,[Dt]),Qo=at||100,Ro=lr.toLowerCase(),Ei=(0,o.useMemo)(()=>Pe?(0,_n.toStripeAppearance)(Pe):null,[Pe]),Eo=Ei,Es=(0,o.useMemo)(()=>{let s=Ei??{},O=s.rules??{};return{...s,rules:{...O,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...O[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...O[".AccordionItemContents"]??{}}}}},[Ei]),Is=(0,o.useMemo)(()=>({...vl(at,J?.captureMethod,q),currency:Ro,...Eo?{appearance:Eo}:null}),[at,Ro,J?.captureMethod,q,Eo]),Ii=(0,c.resolveSetupFutureUsage)(q,"paypal","paypal"),_s=(0,o.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,captureMethod:"manual",...Ii?{setupFutureUsage:Ii}:null,...Eo?{appearance:Eo}:null}),[Qo,Ro,Ii,Eo]),je=(0,o.useCallback)(s=>{br(s),v?.(s)},[v]),Ts=(0,o.useRef)(0);(0,o.useEffect)(()=>{Fr!==Ts.current&&(Ts.current=Fr,je(null))},[Fr,je]);let _i=(0,o.useRef)(""),[Ms,Cc]=(0,o.useState)(!1),Ti=(0,o.useCallback)(()=>{Cc(!0)},[]);(0,o.useEffect)(()=>{if(!fe||!io||!st||!Ms||ko||_i.current)return;let s=(0,cn.compactBuyerIdentity)({email:(0,c.isValidEmail)(ve.email?.trim())?ve.email?.trim():Mr.current.trim(),firstName:ve.firstName?.trim(),lastName:ve.lastName?.trim()});_i.current=JSON.stringify(s),qr(O=>({...O,...s})),Promise.resolve(st(s)).catch(O=>{_i.current="",je(O instanceof Error?O.message:"Failed to attach buyer details.")})},[fe,io,st,Ms,ko,ve.email,ve.firstName,ve.lastName,je]),(0,o.useEffect)(()=>{!fe||!Nt||Nt.setCardFieldOrder?.(ne??null,qe==null&&!io)},[fe,Nt,ne,qe,io]),(0,o.useEffect)(()=>{(bt==="expanding"||bt==="collapsing"||bt==="apm-expanding"||bt==="apm-collapsing")&&je(null)},[bt,je]);let Bn=(0,o.useCallback)((s,O,ie)=>{p?.(hr(s,O,ie))},[p]),Io=(0,o.useCallback)((s,O,ie)=>{let Ie=ie?.popupBlocked??(0,be.isPopupBlockedError)(O);Ie&&A.markBlocked()&&We(Tt=>Tt+1);let Y=ls(s),_e=ie?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(Y):(0,be.buildExternalMethodRecoveryMessage)(Y,Ie,ct.inAppBrowser),zt=(0,be.getProviderErrorCode)(O),sn=(zt?.toLowerCase()==="error"?void 0:zt)??(0,be.sanitizeExternalFailureCode)(ie?.code)??"external_payment_method_failed",Pt=new c.FloPayError(_e,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:sn,popupBlocked:Ie,inAppBrowser:ct.inAppBrowser,appFamily:ct.appFamily,popupCapability:A.current(),presentationMode:ie?.presentationMode??"popup"}});ie?.telemetryReported||Pr(we)?.error(Go({...g,presentationMode:ie?.presentationMode??"popup"},{errorCode:Ie?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:ie?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:ie?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:ie?.terminalReason??(Ie?"popup_blocked":"provider_error")})),ce(null),Fe==="buttons"&&(kr("buttons"),Vr(null)),je(_e),u?.(Pt),console.error("[FloPay] External payment method failed:",{method:s,code:sn,popupBlocked:Ie})},[ct,g,we,Fe,u,A,je]);(0,o.useEffect)(()=>{if(!fe||!e){vn(null);return}let s={billingApiUrl:ur,sessionId:e,nonce:t},O=(0,c.resolveVaultMountOptions)(x?.vault,s);if(O){vn(O);return}if(!At){vn(null);return}let ie=`${ur}\0${e}\0${t??""}`,Ie=U.current;if(Ie&&Ie.key===ie){vn(Ie.mount);return}vn(null);let Y=!0;return new _n.PaymentAPI(ur).getVaultCapture(e,t).then(_e=>{if(!Y)return;let zt=(0,c.resolveVaultMountOptions)(_e,s);zt?.verificationRequired&&!_e.html&&(U.current={key:ie,mount:zt}),zt?vn(zt):je("Failed to load the secure card form.")}).catch(_e=>{Y&&je(_e instanceof Error?_e.message:"Failed to load the secure card form.")}),()=>{Y=!1}},[fe,At,_,e,x?.vault,ur,t,je]);let bn=(0,o.useRef)({onComplete:l,onError:u,updateError:je,emitDecline:Bn,resolvedAccount:ve,avsConfig:qe,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:ur,captureMethod:x?.captureMethod,paymentId:x?.paymentId,authorizationExpiresAt:x?.authorizationExpiresAt,serverSideCardGateway:Ar});bn.current={onComplete:l,onError:u,updateError:je,emitDecline:Bn,resolvedAccount:ve,avsConfig:qe,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:ur,captureMethod:x?.captureMethod,paymentId:x?.paymentId,authorizationExpiresAt:x?.authorizationExpiresAt,serverSideCardGateway:Ar};let Mi=(0,o.useRef)(!1),xs=(0,o.useCallback)(()=>{let s=bn.current,O=s.resolvedAccount.email?.trim(),ie=(0,c.isValidEmail)(O)?O:Mr.current.trim();if(!(0,c.isValidEmail)(ie))return null;let Ie=s.resolvedAccount.firstName?.trim(),Y=s.resolvedAccount.lastName?.trim(),_e=wr.current.trim()||s.resolvedAccount.country?.trim()||"",zt=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.state,_e):!1,sn=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.address_line_1,_e):!1,Pt=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.postal_code,_e):!1,Tt=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.city,_e):!1,Ft=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.address_line_2,_e):!1,Ht=sn&&!zt&&Pt?(0,c.getStateFromPostalCode)(_e,(Sr.current??"").trim()):null,go=zt?Lt.current:Ht;return{accountData:{userId:s.resolvedAccount.userId??"",email:ie,...Ie?{firstName:Ie}:{},...Y?{lastName:Y}:{},...Pt&&Sr.current?{zip:Sr.current}:{},...Tt&&Ot.current?{city:Ot.current}:{},...go?{state:go}:{},...sn&&fr.current?{addressLine1:fr.current}:{},...Ft&&Tr.current?{addressLine2:Tr.current}:{},..._e?{country:_e}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(s.avsConfig.country,_e),postal_code:Pt,address_line_1:sn,address_line_2:Ft,city:Tt,state:zt}}:{}}},[]),As=(0,o.useRef)(m);As.current=m,(0,o.useEffect)(()=>{m||Rt!==zl||bn.current.updateError(null)},[m,Rt]),(0,o.useEffect)(()=>{!fe||!Nt||Nt.setSubmitGate?.(Mn||m||ko||h)},[fe,Nt,Mn,m,ko,h]),(0,o.useEffect)(()=>{if(!fe||!Nt)return;Mi.current=!1;let s=null,O=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,de.current="idle",ce(null)},400)},ie=Nt.on("submitting",()=>{hn(!0),W.current&&clearTimeout(W.current),de.current="validation-window",W.current=setTimeout(()=>{W.current=null,de.current==="validation-window"&&(de.current="processing")},xd),ce("processing");let Pt=bn.current;if(!Pt.sessionId||!Pt.nonce)return;let Tt=xs();if(!Tt){Pt.updateError("Enter a valid email address."),de.current="idle",ce(null);return}new _n.PaymentAPI(Pt.baseUrl).patchAccountSnapshot(Pt.sessionId,Pt.nonce,Tt,{telemetryMode:"best_effort"}).catch(Ft=>{if(!Fd(Ft))return;let Ht=Ft instanceof Error?Ft.message:"Please check your billing address and try again.";Pt.updateError(Ht),de.current="idle",ce(null),Pt.onError?.(Ft instanceof c.FloPayError?Ft:new c.FloPayError(Ht,"api_error"))})}),Ie=Nt.on("complete",Pt=>{(0,En.markSessionRecentlyCompleted)(Pt.sessionId??bn.current.sessionId),de.current="terminal",y(!1),ce("success"),setTimeout(()=>{if(Mi.current)return;Mi.current=!0;let Tt=bn.current,Ft=(0,c.isAuthorizationOnlySession)(Tt)||Pt.outcome==="authorized",Ht=Tt.serverSideCardGateway?{}:{paymentIntentId:Pt.intentId};bn.current.onComplete?.(Ft?{status:"authorized",...Ht,paymentId:Pt.paymentId??Tt.paymentId,sessionId:Pt.sessionId??Tt.sessionId,authorizationExpiresAt:Pt.authorizationExpiresAt??Tt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Ht,checkoutMethod:"card"})},600)}),Y=Nt.on("decline",Pt=>{let Tt=bn.current,Ft=Pt.message??"Your payment was declined. Please try another card or contact your bank.";de.current="terminal",y(!1),Tt.updateError(Ft),ce("error");let Ht=Pt.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(Pt.declineReason)??"authorization_declined";Tt.emitDecline("card",Ft,{code:Ht,declineCode:Ht}),O()}),_e=Nt.on("error",Pt=>{let Tt=bn.current,Ft=Pt.message??"There was a problem processing your payment. Please try again.";de.current="terminal",y(!1),Tt.updateError(Ft),ce("error"),Tt.onError?.(new c.FloPayError(Ft,"api_error",{code:Pt.failureOutcome??"capture_failed"})),O()}),zt=Nt.on("challenge_dismissed",()=>{W.current&&(clearTimeout(W.current),W.current=null),de.current="processing",y(!0),ce(null)}),sn=Nt.on("blocked",()=>{if(H.current){bn.current.updateError(Ad);return}if(!As.current){hn(!0);return}Ti(),bn.current.updateError(zl)});return()=>{s&&(clearTimeout(s),s=null),W.current&&(clearTimeout(W.current),W.current=null),de.current="idle",y(!1),ce(null),ie(),Ie(),Y(),_e(),zt(),sn()}},[fe,Nt,Ti,xs]);let Dn=!!wt?.clientId,ea=Array.isArray(T),Fa=ea&&T.length>0,Fs=ea&&T.includes("paypal"),Ba=(0,o.useRef)(null);Ba.current===null&&(Ba.current=(0,c.hasMatchingStripePayPalReturn)());let _o=Ba.current?"redirect":(0,Nn.resolveStripePayPalPresentation)(ct,Te,A.current()),{expressMethods:Da,paymentElementMethods:xi}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(T,{excludePaypal:Dn}),[T,Dn]),Bs=Dn||!!Dt||Fs&&_o==="redirect",bc=(0,o.useMemo)(()=>Bs?Da.filter(s=>s!=="paypal"):Da,[Da,Bs]),Sc=(0,o.useMemo)(()=>{let s=[];return me&&s.push("apple_pay"),pe&&s.push("google_pay"),s},[me,pe]),To=ea?bc:Sc,wc=b&&To.length>0,Ds=fn?Gt:V,Oa=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)(xi,Ds,se),[xi,Ds,se]),Ai=(0,o.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,paymentMethodCreation:"manual",appearance:Es}),[Qo,Ro,Es]),[Os,Ls]=(0,o.useState)("loading"),[Ns,Us]=(0,o.useState)("loading"),[zs,qs]=(0,o.useState)("loading"),[kc,Fi]=(0,o.useState)(!1),[js,Bi]=(0,o.useState)("loading"),[Di,Rc]=(0,o.useState)();(0,o.useEffect)(()=>{Rc((0,Ln.detectPayPalEnvironment)())},[]);let La=Di?.inAppBrowser,Na=Di?(0,Nn.resolvePayPalPresentationMode)(Di,wt?.approvalPresentation,ue??(Se?"subscription":"order")):"popup",Vs=ye&&(Dn||(ea?Fs:La===!1)),Ec=ct.inAppBrowser&&A.current()==="blocked",Ws=b&&wc&&!Ec,ta=(!xe||!!Ke.waitForDataAttachment)&&Vs&&Dn,$s=js==="retrying"||js==="exhausted",ra=null;b&&(Dt?ra=Rs:_o==="redirect"&&(ra=en));let Hs=(0,o.useMemo)(()=>({...g,presentationMode:_o}),[g,_o]),na=!xe&&Vs&&!!ra&&(!Dn||$s),Mo=!xe&&Ws&&!!en,oa=!xe&&b&&Fa&&Oa.length>0&&!!en,Ic=ta&&!$s?kc:na&&ts(Os),_c=Mo&&ts(Ns),Tc=oa&&zs!=="load_error",Ks=s=>s==="loading"||s==="ready",Gs=ta||na&&Ks(Os)||Mo&&Ks(Ns)||oa&&zs!=="load_error",Ua=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Ua.current){if(!b&&!ye){Ua.current=!0;let s=new c.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(s),je(s.message)}else if(!b&&ye&&!Dn){Ua.current=!0;let s=new c.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(s),je(s.message)}else if(La!==void 0&&!xe&&!$t&&!Gs){Ua.current=!0;let s=new c.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?.(s),je(s.message)}}},[b,ye,Dn,La,xe,$t,Gs,u,je]);let Ys=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(Ys.current||!Fa)return;let s=[];me!==!0&&s.push("showApplePay"),pe!==!0&&s.push("showGooglePay"),s.length!==0&&(Ys.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Fa,me,pe]);let Xs=(0,o.useCallback)((s,O,ie)=>Ke.applyInlineSessionPatch?Ke.applyInlineSessionPatch(s).then(Ie=>({error:null,sessionId:Ie.sessionId||e,nonce:Ie.session?.clientSecret||t})).catch(Ie=>{let Y=(0,c.normalizeBeforeButtonClickError)(O,Ie);return ie?.abandoned?.()||(je(Y.message),u?.(Y)),{error:Y,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ke.applyInlineSessionPatch,t,u,e,je]),Sn=(0,o.useCallback)(async(s,O)=>{if(s!=="card"&&xe&&await Ke.waitForDataAttachment?.(),!Be)return{proceed:!0};try{let ie=await Be({method:s,sessionId:e||void 0,createSession:Ke.inlineSessionDraft});if(ie===!1)return{proceed:!1};if(ie&&typeof ie=="object"){ie.account&&qr(Y=>({...Y??{},...ie.account}));let Ie=await Xs(ie,s,O);return Ie.error?{proceed:!1,accountPatch:ie.account}:{proceed:!0,accountPatch:ie.account,sessionId:Ie.sessionId,nonce:Ie.nonce}}return{proceed:!0}}catch(ie){if(!O?.abandoned?.()){let Ie=(0,c.normalizeBeforeButtonClickError)(s,ie);je(Ie.message),u?.(Ie)}return{proceed:!1}}},[Xs,Ke.inlineSessionDraft,Ke.waitForDataAttachment,xe,Be,u,e,je]),Js=(0,o.useCallback)(async(s,O)=>{if(j.current)return;j.current=!0,Vt(!0),ce("processing"),je(null);let ie=O?.sessionId??e,Ie=O?.nonce??t,Y=Ki(ve,O?.accountPatch),_e=O?.completionPaymentMethodId??ya(s),zt=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,sn=Ld(s),Pt=O?.presentationMode?ni(Pr(we),{...g,presentationMode:O.presentationMode}):void 0,Tt=()=>{kt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:sn}),Pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...In,requestCategory:"process_payment"})};try{let Ft=new _n.PaymentAPI(ur),Ht=await Ft.processPayment(Y.userId??"",{sessionId:ie,nonce:Ie,paymentMethodCategory:O?.paymentMethodCategory??Ud(s),tokenizedData:zt,accountData:{...O?.accountPatch,userId:Y.userId??"",email:Y.email??"",firstName:Y.firstName||void 0,lastName:Y.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:qe,country:wr.current,zip:Sr.current,city:Ot.current,state:Lt.current,addressLine1:fr.current,addressLine2:Tr.current})},...(0,c.buildCheckoutProcessMetadata)({chv:K,avsCheck:ot,checkoutType:Me,checkoutLayout:tt,avsConfig:qe,country:wr.current})}),go=async gr=>{let ho=(0,c.isAuthorizationOnlySession)(x)||gr?.status==="authorized";(0,En.markSessionRecentlyCompleted)(ie),Pt?.terminal({outcome:"payment_succeeded",...In}),ce("success"),Je(null),await new Promise(da=>setTimeout(da,600));let On;typeof gr?.paymentId=="string"?On=gr.paymentId:x?.paymentId&&(On=x.paymentId);let Po;typeof gr?.authorizationExpiresAt=="string"?Po=gr.authorizationExpiresAt:x?.authorizationExpiresAt&&(Po=x.authorizationExpiresAt),l?.(ho?{status:"authorized",...On===void 0?{}:{paymentId:On},sessionId:typeof gr?.sessionId=="string"?gr.sessionId:ie,...Po===void 0?{}:{authorizationExpiresAt:Po},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:_e,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:_e,checkoutMethod:s.isPaypal?"paypal":"card"})};if(Ht.ok){await go(Ht.status===204?null:await Ht.json().catch(()=>null));return}let tn=await Ht.json().catch(()=>null);if(tn?.type==="paypal_redirect_required"){let gr=tn.threeDSecureToken,ho=tn.paymentMethodId||s.id||"";if(!we||!gr){ce("error"),je("PayPal authorization required but no token provided.");return}try{let On=Dt?.getRawProvider();if(!On){je("PayPal is not available.");return}let Po={return_url:window.location.href};ho&&(Po.payment_method=ho);let{error:da}=await On.confirmPayment({clientSecret:gr,confirmParams:Po,redirect:"if_required"});if(da){ce("error");let cl=da.message??"PayPal payment failed.";je(cl),Bn("paypal",cl,{code:da.code})}}catch(On){ce("error"),je(On instanceof Error?On.message:"PayPal authorization failed.")}return}if(tn?.type==="paypal_direct_required"){let gr=tn.orderId;if(!gr){ce("error"),je("PayPal retry required but no order id provided.");return}let ho=mt.current?.attempts??0;if(ho>=2){ce("error"),je("PayPal payment could not be completed after multiple attempts."),Bn("paypal","paypal_direct_required retry limit exceeded");return}Fi(!1),Bi("loading"),Je({orderId:gr,attempts:ho+1}),ce(null);return}if(Ht.headers.get(kd)===Rd){let gr=await Ed(Ft,ie,Ie);if(gr!==void 0){await go(gr);return}}(0,c.classifyPaymentRejection)(Ht.status,tn)?Pt?.terminal({outcome:"payment_declined",...In,terminalReason:"provider_declined"}):Tt(),ce("error");let ll=tn?.message??"Payment failed. Please try again.";je(ll),Bn(s.isPaypal?"paypal":"card",ll,{code:tn?.code??tn?.gatewayErrorCode,declineCode:tn?.declineCode??tn?.gatewayDeclineReason}),await new Promise(gr=>setTimeout(gr,400))}catch(Ft){Yl(Ft)||Tt(),ce("error"),je(Ft instanceof Error?Ft.message:"An unexpected error occurred"),await new Promise(Ht=>setTimeout(Ht,400))}finally{Vt(!1),ce(null),j.current=!1}},[ur,e,t,ve,qe,ot,Me,tt,K,we,Dt,x,l,je,Bn,kt,g]),Wr=(0,o.useCallback)((s,O)=>{w?w(s):Js(s,O)},[w,Js]),aa=`${Kl}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(aa);if(!s)return;let O;try{O=JSON.parse(s)}catch{ir(aa);return}if(!O||typeof O.createdAt!="number"||Date.now()-O.createdAt<0||Date.now()-O.createdAt>Gl||typeof O.paymentMethodId!="string"||typeof O.providerIntentId!="string"||typeof O.paymentMethodType!="string"||O.sessionId!==e||!t||O.nonce!==t||!To.includes(O.paymentMethodType)){ir(aa);return}ir(aa),Wr({id:O.paymentMethodId,type:"card",threeDSecureActionResultTokenId:O.providerIntentId,gateway:"stripe",paymentMethodType:O.paymentMethodType},{...O.accountPatch?{accountPatch:O.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Wr,t,e,aa,To]);let Zs=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Zs.current)return;let[s,O,ie]=(0,c.readStripeRedirectParams)();if(!s||!O||Ba.current||!we)return;let Ie=we.getRawProvider();if(!Ie)return;let Y=Tt=>{let Ft=localStorage.getItem(Tt);if(!Ft)return null;try{return JSON.parse(Ft)}catch{return ir(Tt),null}},_e=Y(zn)??Y(Ll),zt;if(_e?.clientSecret){if(_e.clientSecret!==O)return;zt={..._e.accountPatch?{accountPatch:_e.accountPatch}:{},..._e.sessionId?{sessionId:_e.sessionId}:{},..._e.nonce?{nonce:_e.nonce}:{}}}else if(_e?.sessionId&&_e.sessionId!==e)return;Zs.current=!0,ir(zn),ir(Ll),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let sn=_e?.paymentMethodType??_e?.tokenType??"card",Pt="card";(async()=>{if(ie==="failed"){let Yn="Payment was declined. Please try again.";je(Yn),Bn(Pt,Yn);return}let{paymentIntent:Tt,error:Ft}=await Ie.retrievePaymentIntent(O);if(Ft){let Yn=Ft.message??"Failed to retrieve payment status.";je(Yn),Bn(Pt,Yn,{code:Ft.code});return}let Ht=Tt?.status,go=pa(Ht);if(!Tt||!go){let Yn=Ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";je(Yn),Bn(Pt,Yn,{code:Ht??"missing_payment_intent"});return}let tn=typeof Tt.payment_method=="string"?Tt.payment_method:Tt.payment_method?.id;Wr({id:tn??_e?.paymentMethodId??_e?.tokenId??Tt.id,type:"card",threeDSecureActionResultTokenId:Tt.id,gateway:_e?.gateway??"stripe",paymentMethodType:sn},zt)})()},[e,Wr,we,je,Bn]);let Oi=(0,o.useCallback)(s=>{s.preventDefault()},[]);if(!(fe||we!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ia=Fe==="buttons",$r=Pe?.variables,Mc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Li=$r?.colorBackground,xc=Li&&!Mc.has(Li)?Li:void 0,sa=F.cardInputBorder??(ia?"#e5e7eb":"#A4A4FF"),Qs=$r?.colorDanger??"#dc2626",Zt=s=>nn[s]&&(on[s]||rr),za=ko&&(Or||rr),an=s=>s?Qs:sa,qa=(Yr.malformed||Yr.empty)&&($n||rr),Ac=an(qa),Ni=F.cardFormContainer?.backgroundColor??xc??(ia?"white":"#EDEDFF"),xo=F.cardInputBackground??$r?.colorBackground??"white",Ui=Bo(Oe),el=Bo(ge),Ao=F.nameInput,tl=F.cardInputFontSize??Vd(Ao?.fontSize)??$r?.fontSizeBase??"16px",rl=typeof Ao?.fontFamily=="string"?Ao.fontFamily:$r?.fontFamily??"Poppins, sans-serif",nl=(0,c.toCssWeight)(Ao?.fontWeight)??400,Fc=F.cardInputColor??(typeof Ao?.color=="string"?Ao.color:void 0)??$r?.colorText??"#262833",Bc=F.cardInputPlaceholderColor??"#9ca3af",or=$r?.borderRadius??"8px",mo=$r?.borderRadius??F.cardButton?.borderRadius??or,fo=$r?.colorPrimary??"#4A49FF",Dc=$r?.colorPrimaryHover??(0,c.darkenHex)(fo,.12),zi=$r?.colorText??"#262833",qi={fontSize:tl,fontFamily:rl,fontWeight:nl,color:Fc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},la={marginTop:"0.375rem",...qi,fontSize:"0.75rem",lineHeight:1.4,color:Qs},Oc={"--flopay-input-placeholder-color":Bc,"--flopay-input-font-size":tl,"--flopay-input-font-family":rl,"--flopay-input-font-weight":String(nl)},ca=F.cardFormContainer??{},ji=ca.padding??(ia?"0":"1rem"),Vi=ca.borderRadius??or,Lc=Nt&&jr?(0,d.jsx)(co,{capture:Nt,html:jr.html,messageToken:jr.messageToken,expectedOrigin:jr.expectedOrigin,verificationRequired:jr.verificationRequired,theme:Ze,submitLabel:X,onReady:()=>{if(!io&&!qe||typeof document>"u")return;let s=()=>{let ie=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(ie){Xr.current=!0;try{ie.focus()}finally{Xr.current=!1}}};An.current||s()},onError:s=>{s&&jr.verificationRequired&&de.current==="idle"&&(Fn.current=!0),je(s)},onValidation:s=>{let O=de.current;(O==="idle"||O==="validation-window")&&(je(s),s&&de.current==="validation-window"&&(W.current&&(clearTimeout(W.current),W.current=null),de.current="idle",ce(null)))}},Fr):(0,d.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"}),ol=(0,d.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&Kn()},style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji,...Oc,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
|
|
30
|
+
`,Yo=44;function Xo(){return(0,Rr.jsx)("style",{children:yd})}function wa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function ka({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Rr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Rr.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,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,Rr.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:n})]})}function ts(e){return e!=="unavailable"&&e!=="load_error"}function oi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:l,backgroundColor:p,borderColor:m,textColor:h,borderRadius:w,fontFamily:S}){let E=(0,to.resolveStripeMethodBrandVariant)(e,t),Y=Bl[e],[I,ee]=(0,Dl.useState)(!1),x=!!Y&&!I,f=E?.backgroundColor??p??"#ffffff",P=E?.borderColor??m??"#d1d5db",pe=E?.textColor??h??"#262833";return(0,Rr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&l()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Yo,padding:"0 1rem",backgroundColor:f,color:pe,border:`1px solid ${P}`,borderRadius:w??8,fontSize:"0.95rem",fontWeight:600,fontFamily:S,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"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:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,Rr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,to.getStripeMethodDisplayName)(e)}\u2026`}):(0,Rr.jsxs)(Rr.Fragment,{children:[(0,Rr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,to.hasVendoredStripeMethodLogo)(e)?8:0},children:[x?(0,Rr.jsx)("img",{src:Y,alt:"","aria-hidden":"true",onError:()=>ee(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!x&&E?.logoSvg?(0,Rr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:E.logoSvg}}):null,(0,Rr.jsx)("span",{children:(0,to.getStripeMethodDisplayName)(e)})]}),i&&(0,Rr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:pe,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,Rr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ai(e){let t=new Set(e.map(to.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var ii={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},si={type:"accordion",defaultCollapsed:!1,radios:"never"};function li({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:i,style:l,children:p}){return(0,Rr.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:i,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...l??{}},children:p})}var sn=require("react");var Ra=require("@flopay/shared"),fd=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function gd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return fd.has(t.charAt(0).toLowerCase()+t.slice(1))}function hd(e,t){return typeof t=="number"&&t!==0&&!gd(e)?`${t}px`:String(t).trim()}function Ol(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=hd(r,n)}}}var So=require("react/jsx-runtime"),rs=new WeakSet;function co({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:i,submitLabel:l,containerStyle:p,onReady:m,onError:h,onValidation:w}){let S=(0,sn.useRef)(null),E=(0,sn.useRef)(m),Y=(0,sn.useRef)(h),I=(0,sn.useRef)(w);E.current=m,Y.current=h,I.current=w;let ee=(0,sn.useRef)(i);ee.current=i;let x=(0,sn.useRef)(null),f=l??void 0,P=(0,sn.useRef)(f);P.current=f;let pe=(0,sn.useRef)(void 0);return(0,sn.useEffect)(()=>{let b=S.current;if(!b)return;let Ie=!0,_=!1,ie=()=>{!Ie||_||(_=!0,E.current?.())},me=e.on("ready",()=>{ie()}),ue=e.on("error",B=>{Y.current?.(B.message??"There was a problem loading the secure card form.")}),xe=e.on("validation",B=>{I.current?.(B.message??null)}),lt=P.current??(rs.has(e)?null:void 0),$e={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...ee.current?{theme:ee.current}:{},...lt===void 0?{}:{submitLabel:lt}};return x.current=ee.current??null,pe.current=P.current,P.current!==void 0&&rs.add(e),e.mount(b,$e).then(()=>{ie()}).catch(B=>{Ie&&Y.current?.(B instanceof Error?B.message:"Failed to load the secure card form.")}),()=>{Ie=!1,me(),ue(),xe(),e.unmount()}},[e,t,r,n,a]),Co(()=>{let b=S.current;b&&Ol(b,p)},[p]),(0,sn.useEffect)(()=>{i!==void 0&&(i===null&&x.current===null||(x.current=i,e.applyTheme?.(i)))},[e,i]),(0,sn.useEffect)(()=>{f!==pe.current&&(pe.current=f,f!==void 0&&rs.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,So.jsx)("div",{ref:S,"data-testid":"flopay-vault-card-fields"})}function ci({label:e}){return(0,So.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,So.jsx)("span",{children:e}),(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var ms=require("@flopay/shared"),u=require("react/jsx-runtime"),jn="flopay_stripe_resume",Ll="flopay_wallet_resume",Kl="fw1",Pd="fw2",Gl=300*1e3,vd=900,Cd="express_checkout_click_timeout",bd=25e3,Sd=25e3,wd=1e4,Tn={provider:"paypal",paymentMethodCategory:"paypal"},kd="x-flopay-process-result-source",Rd="status";async function Ed(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var di={},Ia=class{constructor(t){this.reason=t}};function Id(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function nr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ds(e){return`${Pd}:${e}`}function ui(e){return nr(ds(e))}function pi(e,t){if(typeof window>"u")return null;let r=ds(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Gl||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ui(e),null):a}catch{return ui(e),null}}function _d(e){return nr(ds(e.sessionId),e)}function Nl(e,t,r){let n=pi(e,t);return!n||n.clientSecret!==r?!1:ui(e)}function ns(e,t,r){if(typeof window>"u")return;pi(e,t)?.clientSecret===r&&ui(e)}function Td(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function os(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":pa(e.status),a=Td(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Ul(e,t,r){let n=null;try{return await Promise.race([Pl(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},wd),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Md(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Yl(e){return e instanceof d.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function mi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Mn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Yl(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var as=d.STRIPE_PAYPAL_RESUME_KEY,Ea=new Map,xd=250,zl="Just a moment \u2014 we are finalizing your order. Please press pay again.",Ad="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function us(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function yi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Mn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Fd(e){return e instanceof d.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Xl({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),i=(0,Uo.splitFullName)(r),l=i.firstName?i:(0,Uo.splitFullName)(n?.name);return(0,mn.compactBuyerIdentity)({email:(0,d.isValidEmail)(a)?a:n?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Bd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:i}){let l=Xl({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,d.isValidEmail)(l.email)?l:i(a,l)}var _a=180,ql=`flopay-card-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,jl=`flopay-card-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Dd=`flopay-buttons-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,Od=`flopay-buttons-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Ld(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ps(e){return(0,d.derivePrimaryTileStyle)(e)}var Nd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ud(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var ss={width:"100%",minHeight:Yo,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 Vl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ls(e){return e==="paypal"?"PayPal":(0,d.getStripeMethodDisplayName)(e)}function zd(e){let t=(0,d.getPostalCodeExample)(e);return`Enter a valid ${(0,d.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function qd(e,t,r){let n=(0,d.isPostalCodeSupported)(e),a=t.trim(),i=r&&n,l=i&&!a,p=i&&!!a&&!(0,d.isValidPostalCode)(e,a);return{visible:r,supported:n,required:i,empty:l,malformed:p}}function jd(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,d.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function Vd(e){return typeof e=="number"?`${e}px`:e}function fi(e){return(0,u.jsx)(Hd,{...e})}function Wl({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:i,isProcessing:l=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:h,runBeforeButtonClick:w,billingName:S,onBuyerIdentityReady:E,onLoadStateChange:Y,placeholderBorderRadius:I,popupCapabilityOwner:ee,externalTelemetryContext:x,presentationMode:f}){let P=Qn(),{emitInstrument:pe}=(0,o.useContext)(pn),b=(0,rr.useStripe)(),Ie=(0,rr.useElements)(),_=(0,o.useMemo)(()=>ni(kr(P),x),[x,P]),[ie,me]=(0,o.useState)("loading");(0,o.useEffect)(()=>{Y?.(ie)},[ie,Y]);let[ue,xe]=(0,o.useState)(!1),lt=(0,o.useRef)(!1),$e=!(0,d.isValidEmail)(r?.trim())||!S?.trim(),{request:B,collect:St,finish:Ge}=zo(),De=(0,o.useRef)(!1),de=(0,o.useRef)(null),re=(0,o.useRef)(null),[X,Oe]=(0,o.useState)(0),[nt,ze]=(0,o.useState)(!1),te=(0,o.useRef)(!1),J=(0,o.useRef)(new Map),{startAttempt:H,finishAttempt:j,invalidateAttempt:je,isAttemptInvalidated:Te,isAttemptCurrent:fe,generationRef:O}=ga((Ce,T,ht)=>{h?.(Ce,T,{...ht,popupBlocked:ht?.popupBlocked??(0,ve.isPopupBlockedError)(T),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),ze(!0),Oe(pt=>pt+1)},{onHandoffObserved:()=>{ee.markAvailable(),_?.log({name:"provider.popup.opened",stage:"overlay_open",...Tn,attempt:O.current})}});(0,o.useEffect)(()=>{nt&&re.current?.focus()},[nt,X]);let Pe=(0,o.useCallback)(()=>{Oe(Ce=>Ce+1)},[]),ut=(0,o.useCallback)((Ce,T,ht)=>{je(ht),h?.("paypal",Ce,{code:T,popupBlocked:(0,ve.isPopupBlockedError)(Ce),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),ze(!0),Pe()},[je,h,f,Pe]),Le=(0,o.useCallback)(()=>{window.setTimeout(()=>{(de.current?.querySelector("iframe")??de.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{te.current&&(te.current=!1,Le())},[Le,X]);let ot=(0,o.useCallback)(()=>{ze(!1),i?.(null),Le()},[Le,i]);(0,o.useEffect)(()=>{if(!b||De.current)return;let[Ce,T,ht]=(0,d.readStripeRedirectParams)();if(!Ce||!T)return;let pt=(0,d.readMatchingStripePayPalContinuation)(T);if(!pt)return;De.current=!0;let z=!0,Ae=Ea.get(T);Ae||(Ae=ht==="failed"?Promise.resolve(null):Promise.resolve().then(()=>b.retrievePaymentIntent(T)),Ea.set(T,Ae));let Dt={accountPatch:pt.accountPatch,sessionId:pt.sessionId,nonce:pt.nonce},be=()=>{_?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Tn,requestCategory:"provider_sdk"})};return _?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Tn}),(async()=>{try{xe(!0);let C=await Ae;if(!z)return;if(C?.error){Ea.delete(T),be(),i?.(C.error.message??"Failed to retrieve PayPal payment status.");return}if((0,d.clearStripePayPalReturn)(),Ea.delete(T),ht==="failed"){let Fe="PayPal payment was declined. Please try again.";_?.terminal({outcome:"payment_declined",...Tn,terminalReason:"provider_declined"}),i?.(Fe),m?.(wr("paypal",Fe));return}let M=C?.paymentIntent;if(M&&M.id!==Ce){be(),i?.("Failed to match the returned PayPal payment.");return}if(M&&(M.status==="requires_capture"||M.status==="succeeded")){let Fe=typeof M.payment_method=="string"?M.payment_method:M.payment_method?.id;a({id:Fe??M.id,type:"card",threeDSecureActionResultTokenId:M.id,isPaypal:!0},{...Dt,presentationMode:"redirect"})}else{let Fe="PayPal payment was not completed. Please try again.";_?.terminal({outcome:M?.status==="canceled"?"payment_cancelled":"payment_declined",...Tn,terminalReason:M?.status==="canceled"?"cancelled":"provider_declined"}),i?.(Fe),m?.(wr("paypal",Fe))}}catch(C){if(!z)return;Ea.delete(T),be(),i?.(C instanceof Error?C.message:"Failed to complete PayPal payment.")}finally{z&&xe(!1)}})(),()=>{z=!1,De.current=!1}},[b,a,i,m,_]);let _e=(0,o.useCallback)(async(Ce=!1)=>{let T=w?await w("paypal"):{proceed:!0};if(!T.proceed)return J.current.delete(X),!1;let ht=H("paypal");return J.current.set(X,{generation:ht,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),ze(!1),_?.log({name:`provider.${Ce?"redirect.started":"handoff.requested"}`,stage:Ce?"redirect":"overlay_open",...Tn,attempt:ht}),p?.("paypal"),!0},[p,_,w,H,X]),et=(0,o.useCallback)(async Ce=>{if(l||ue||!await _e()){Ce.reject();return}Ce.resolve()},[l,_e,ue]),at=(0,o.useCallback)(async Ce=>{if(!b||!Ie)return;let T=J.current.get(X);if(T&&!fe(T.generation)){J.current.delete(X);return}if(!T&&Te()||T&&!j(T.generation))return;T||j();let ht=T??null;if(J.current.delete(X),!ht&&w){let _t=await w("paypal");if(!_t.proceed){Ce.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ht={accountPatch:_t.accountPatch,sessionId:_t.sessionId,nonce:_t.nonce}}let pt=ht?.sessionId??e,z=ht?.nonce??t,Ae=await Bd({event:Ce,prepared:ht,email:r,billingName:S,methodLabel:"PayPal",collect:St});if(!Ae){Ce.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Dt=Ae.email,be={...ht?.accountPatch,...(0,mn.compactBuyerIdentity)(Ae,!0)};try{if(xe(!0),i?.(null),!pt||!(0,d.isValidEmail)(Dt))throw new Error("Missing sessionId or email for PayPal payment");await E?.(Ae);let _t=b.createPaymentMethod,{error:C,paymentMethod:M}=await _t({type:"paypal"});if(C){ut(C,"stripe_paypal_create_payment_method_failed",T?.generation),Ce.paymentFailed({reason:"fail"});return}let Fe=await mi(n,pe,pt,z??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:M?.id??null,intentKind:"payment"});if(Fe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Se=Fe.clientSecret,ct={return_url:(0,d.stripeRedirectReturnUrl)()};if(M?.id&&(ct.payment_method=M.id),!nr(as,{clientSecret:Se,sessionId:pt,nonce:z,accountPatch:be})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Ve,paymentIntent:He}=await b.confirmPayment({clientSecret:Se,confirmParams:ct,redirect:"if_required"});if(Ve){if(nr(as),(0,ve.isProviderDecline)(Ve)){let c=Ve.message??"Your payment was declined.";_?.terminal({outcome:"payment_declined",...Tn,terminalReason:"provider_declined"}),i?.(c),m?.(wr("paypal",c,{code:(0,ve.getProviderErrorCode)(Ve),declineCode:(0,ve.getProviderDeclineCode)(Ve)})),await yi({billingApiUrl:n,sessionId:pt,nonce:z,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,ve.getProviderErrorCode)(Ve)??"provider_declined"}})}else ut(Ve,"stripe_paypal_confirm_failed",T?.generation);return}nr(as);let Bt=typeof He?.payment_method=="string"?He.payment_method:He?.payment_method?.id;a({id:Bt??He?.id,type:"card",threeDSecureActionResultTokenId:He?.id,isPaypal:!0},{accountPatch:be,paymentMethodCategory:"paypal",presentationMode:f,sessionId:pt,nonce:z});return}catch(_t){ut(_t,"stripe_paypal_failed",T?.generation)}finally{xe(!1)}},[b,Ie,e,t,r,S,St,E,n,pe,a,i,m,w,ut,j,fe,Te,_,f,X]),ar=(0,o.useCallback)(async()=>{if(!(lt.current||l||ue||!b||!Ie)){lt.current=!0,xe(!0);try{if(!await _e(!0))return;await at({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{lt.current=!1,xe(!1)}}},[Ie,at,l,_e,b,ue]),xt=f==="redirect"?(0,u.jsx)("button",{type:"button",disabled:l||ue,onClick:()=>{ar()},style:{width:"100%",minHeight:Yo,border:"1px solid #d1d5db",borderRadius:I??8,background:"#ffc439",color:"#111827",cursor:l||ue?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,u.jsx)(rr.ExpressCheckoutElement,{onReady:Ce=>me(wa(Ce,["paypal"])),onLoadError:()=>{me("load_error"),us(_,"paypal","paypal","provider_error")},onClick:et,onConfirm:at,onCancel:()=>{let Ce=J.current.get(X);J.current.delete(X),_?.terminal({outcome:"payment_cancelled",...Tn,terminalReason:"cancelled",...Ce?{attempt:Ce.generation}:{}}),je(Ce?.generation),ze(!1),te.current=!0,Pe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:$e,emailRequired:$e,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},X),Ct=(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("div",{ref:de,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[nt&&(0,u.jsx)("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:ss,children:"Try PayPal again"}),B&&(0,u.jsx)(qo,{identity:B.identity,methodLabel:B.methodLabel,onComplete:Ge,onCancel:()=>Ge(null)},B.id),(0,u.jsx)("div",{style:{display:B?"none":void 0},children:xt})]}),ue&&!B&&(0,u.jsx)(Zr,{status:"processing"})]});return f==="redirect"?Ct:(0,u.jsx)(ka,{state:ie,placeholderTestId:"flopay-paypal-placeholder",borderRadius:I,children:Ct})}function is(e){return e==="apple_pay"||e==="google_pay"}var Wd=200;function $d({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,d.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function $l({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:i,onTokenizedBody:l,onErrorChange:p,onButtonClick:m,onDecline:h,onTechnicalFailure:w,runBeforeButtonClick:S,billingName:E,onBuyerIdentityReady:Y,onLoadStateChange:I,placeholderBorderRadius:ee,popupCapabilityOwner:x,externalTelemetryContext:f}){let P=Qn(),{emitInstrument:pe}=(0,o.useContext)(pn),b=(0,rr.useStripe)(),Ie=(0,rr.useElements)(),_=(0,o.useMemo)(()=>ni(kr(P),f),[f,P]),[ie,me]=(0,o.useState)("loading");(0,o.useEffect)(()=>{I?.(ie)},[ie,I]);let[ue,xe]=(0,o.useState)(!1);(0,o.useEffect)(()=>{ze.current=ue},[ue]);let lt=(0,o.useRef)(!(0,d.isValidEmail)(r?.trim())||!E?.trim()).current,{request:$e,collect:B,finish:St}=zo(),Ge=(0,o.useRef)(null),De=(0,o.useRef)(null),[de,re]=(0,o.useState)(0),[X,Oe]=(0,o.useState)(()=>(0,d.shouldPreferWalletPopup)()),nt=(0,o.useRef)(X),ze=(0,o.useRef)(!1),[te,J]=(0,o.useState)(!1),[H,j]=(0,o.useState)(()=>pi(e,t)?"blocked":"idle"),[je,Te]=(0,o.useState)("google_pay"),fe=(0,o.useRef)(null),O=(0,o.useRef)(!0),Pe=(0,o.useRef)(!1),ut=(0,o.useRef)("google_pay"),Le=(0,o.useRef)("google_pay"),ot=(0,o.useRef)(null),_e=(0,o.useRef)(null),et=(0,o.useRef)(new Set),at=(0,o.useRef)(null),ar=(0,o.useRef)(null);(0,o.useEffect)(()=>(O.current=!0,()=>{O.current=!1;for(let c of et.current)window.clearTimeout(c);et.current.clear()}),[]);let xt=(0,o.useRef)(new Map),{startAttempt:Ct,finishAttempt:Ce,invalidateAttempt:T,isAttemptInvalidated:ht,isAttemptCurrent:pt,generationRef:z}=ga((c,U,V)=>{w?.(c,U,{...V,popupBlocked:V?.popupBlocked??(0,ve.isPopupBlockedError)(U),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Te(c),J(!0),re(se=>se+1)},{onHandoffObserved:c=>{ar.current=z.current,x.markAvailable(),_?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:z.current,...c==="apple_pay"||c==="google_pay"?{walletType:c}:{}})},defersMissingTerminal:is,onMissingTerminalDeferred:(c,U)=>{let V=_?.now()??globalThis.performance?.now()??Date.now(),se=at.current,R=se?.generation===U?se.startedAt:V;_?.performance({stage:"overlay_return",durationMs:Math.max(0,V-R),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:U,...is(c)?{walletType:c}:{}}),_?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{te&&De.current?.focus()},[te,de]);let Ae=(0,o.useRef)(0),Dt=(0,o.useRef)(!1),be=(0,o.useCallback)(()=>{if(Ae.current>0){Dt.current=!0;return}re(c=>c+1)},[]),_t=(0,o.useCallback)(()=>{Ae.current-=1,!(Ae.current>0||!Dt.current)&&(Dt.current=!1,O.current&&re(c=>c+1))},[]),C=(0,o.useCallback)((c,U,V,se,R=!1)=>{T(se),w?.(c,U,{code:V,popupBlocked:(0,ve.isPopupBlockedError)(U),telemetryReported:R,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Te(c),J(!0),be()},[T,w,be]),M=(0,o.useCallback)(c=>{_?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...is(c)?{walletType:c}:{}}),w?.(c,new Error("The wallet click was not ready within the time the wallet allows."),{code:Cd,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Te(c),J(!0)},[w,_]),Fe=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Ge.current?.querySelector("iframe")??Ge.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Pe.current&&(Pe.current=!1,Fe())},[Fe,de]);let Se=(0,o.useCallback)(()=>{J(!1),p?.(null),Fe()},[Fe,p]),ct=(0,o.useCallback)(()=>{fe.current?.()},[]);(0,o.useEffect)(()=>{let c=null,U=()=>{c=null;let se=(0,d.shouldPreferWalletPopup)();se!==nt.current&&(nt.current=se,Oe(se),!ze.current&&!pt(z.current)&&be())},V=()=>{c!==null&&window.clearTimeout(c),c=window.setTimeout(U,Wd)};return window.addEventListener("resize",V),()=>{window.removeEventListener("resize",V),c!==null&&window.clearTimeout(c)}},[z,pt,be]),(0,o.useEffect)(()=>{let c=pi(e,t);if(!c)return;let U=!1,V=!1,se=async()=>{if(!V){V=!0,U||j("checking");try{let R=await Ul(b,c.clientSecret,et.current);if(U)return;let K=os(R,c.providerObjectId,(0,d.isSetupIntentClientSecret)(c.clientSecret));if(K.kind==="confirmed"){if(!Nl(e,t,c.clientSecret))return;fe.current=null,j("idle"),l({id:K.paymentMethodId,type:"card",threeDSecureActionResultTokenId:K.intentId},{...c.accountPatch?{accountPatch:c.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(K.kind==="terminal"){ns(e,t,c.clientSecret),fe.current=null,j("idle"),Te(c.paymentMethodType),J(!0),be();return}j("blocked")}catch{U||j("blocked")}finally{V=!1}}};return fe.current=se,j("blocked"),()=>{U=!0,fe.current===se&&(fe.current=null)}},[t,l,be,e,b]);let mt=(0,o.useCallback)(async c=>{let U=!1,V=!1,se=dt=>{U||V||(U=!0,c.paymentFailed({reason:"fail",...dt?{message:dt}:{}}))};if(!b||!Ie){se();return}let R=xt.current.get(de);if(R&&!pt(R.generation)){xt.current.delete(de),se();return}if(!R&&ht()){se();return}if(R&&!Ce(R.generation)){se();return}R||(Ce(),Dt.current=!1);let K=c.expressPaymentType??R?.method??ut.current,Ut=R??null,xr=Vl(K),ir;K==="apple_pay"?ir="apple_pay":K==="google_pay"&&(ir="google_pay");let Ht=R?.generation??z.current,Tt=_,Lr=Tt?.now()??globalThis.performance?.now()??Date.now(),Ar=new AbortController,Zt=!1,$r=!1,Mt=null,xn=e,Kt="processing",ln="other",Nr="provider_runtime",Ur,sr=new Promise((dt,wt)=>{Ur=wt}),br=window.setTimeout(()=>{Zt=!0,Ar.abort(),Ur(di)},bd),Hr=async(dt,wt,lr)=>{Kt=dt,ln=wt,Nr=wt==="intent_create"||wt==="session_claim"?"transport_error":"provider_runtime";let Gt=Tt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([lr,sr])}finally{let hr=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:dt,durationMs:Math.max(0,hr-Gt),durationMode:"machine",requestCategory:wt,paymentMethodCategory:"wallet",provider:"stripe",...Zt?{statusClass:"timeout"}:{}})}};try{if(xe(!0),p?.(null),!Ut&&S){let $=await Hr("processing","other",S(xr));if(!$.proceed){se();return}Ut={accountPatch:$.accountPatch,sessionId:$.sessionId,nonce:$.nonce}}let dt=Ut?.sessionId??e;xn=dt;let wt=Ut?.nonce??t,lr=ot.current??Ut?.accountPatch,Gt=Xl({event:c,fallbackEmail:lr?.email??r,fallbackName:[lr?.firstName,lr?.lastName].join(" ").trim()||E});if(!(0,d.isValidEmail)(Gt.email)){se("Buyer details are required."),B(ls(K),Gt).then($=>{$&&(ot.current=$)});return}ot.current=null;let hr={...Ut?.accountPatch,...(0,mn.compactBuyerIdentity)(Gt,!0)};await Hr("processing","session_claim",Promise.resolve(Y?.(Gt)));let{error:Yt}=await Hr("tokenization","provider_sdk",Ie.submit());if(Yt){se(),C(K,Yt,"stripe_wallet_submit_failed",R?.generation);return}if(!dt)throw new Error("Missing sessionId or email for payment.");let cr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:K,paymentMethodId:null,intentKind:a},Ir=JSON.stringify({sessionId:dt,nonce:wt??"",request:cr}),dr=_e.current,Ye=dr?.retryIdentity===Ir?dr.authorizationAttemptId:(0,d.randomUuidV4)();_e.current={authorizationAttemptId:Ye,retryIdentity:Ir};let Fr=await Hr("processing","intent_create",mi(n,pe,dt,wt??"",{...cr,authorizationAttemptId:Ye},{signal:Ar.signal}));if(Fr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ur=Fr.clientSecret,oo=_d({createdAt:Date.now(),sessionId:dt,...wt?{nonce:wt}:{},clientSecret:ur,providerObjectId:Fr.providerObjectId,paymentMethodType:K,accountPatch:hr});window.clearTimeout(br),$r=!0,Tt?.performance({stage:"callback",durationMs:Math.max(0,(Tt?.now()??globalThis.performance?.now()??Date.now())-Lr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let zr=Tt?.now()??globalThis.performance?.now()??Date.now(),qr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...ir?{walletType:ir}:{},attempt:Ht},An=!1,Kr=null;Tt?.log({name:"payment.provider_confirmation.started",...qr}),Mt=window.setTimeout(()=>{Mt!==null&&et.current.delete(Mt),An=!0;let $=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...qr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,$-zr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{}),Kr?.()},Sd),et.current.add(Mt);let Xt=($,Vt)=>{Mt!==null&&(window.clearTimeout(Mt),et.current.delete(Mt),Mt=null);let tt=Tt?.now()??globalThis.performance?.now()??Date.now(),Lt=Math.max(0,tt-zr),pr=$;An&&($==="resolved"?pr="resolved_late":$==="returned_error"?pr="returned_error_late":pr="rejected_late");let Br=Vt??($==="resolved"?"approved":"provider_error");return Tt?.log({name:"payment.provider_confirmation.returned",...qr,operationOutcome:pr,terminalReason:Br}),Tt?.performance({...qr,durationMs:Lt,durationMode:"buyer",operationOutcome:pr,terminalReason:Br}),{durationMs:Lt,operationOutcome:pr,terminalReason:Br}},ye=!1,Z=!1,At=$=>{if(!$||typeof $!="object")return null;let Vt=$;if(Vt.error)return null;let tt=Vt.setupIntent??Vt.paymentIntent,Lt=os(tt??null,void 0,!!Vt.setupIntent);return Lt.kind==="confirmed"?Lt:null},Me=$=>{if(ye||R&&z.current!==R.generation)return;let Vt=At($);if(!Vt)return;if(oo&&!Nl(dt,wt,ur)){ye=!0;return}let{intentId:tt,paymentMethodId:Lt}=Vt;ye=!0,Z=!0,_e.current=null,fe.current=null,O.current&&(j("idle"),xe(!1));let pr=`${Kl}:${dt}`;nr(pr,{createdAt:Date.now(),sessionId:dt,nonce:wt,accountPatch:hr,paymentMethodId:Lt,providerIntentId:tt,paymentMethodType:K});try{l({id:Lt,type:"card",threeDSecureActionResultTokenId:tt},{accountPatch:hr,paymentMethodCategory:"wallet",sessionId:dt,nonce:wt})}finally{nr(pr)}},Pr=!1;Kr=async()=>{if(!(Pr||ye||Z)){Pr=!0,O.current&&j("checking");try{let $=await Ul(b,ur,et.current);if(ye||Z)return;let Vt=(0,d.isSetupIntentClientSecret)(ur),tt=os($,Fr.providerObjectId,Vt);if(tt.kind==="confirmed"){Me(Vt?{setupIntent:$}:{paymentIntent:$});return}if(tt.kind==="terminal"){if(Z=!0,ns(dt,wt,ur),_e.current=null,fe.current=null,!O.current)return;j("idle"),se(),C(K,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",R?.generation,!0);return}O.current&&!Z&&(j("blocked"),xe(!1))}catch{O.current&&!Z&&(j("blocked"),xe(!1))}finally{Pr=!1}}},fe.current=Kr;let Ot,jt;try{V=!0,Ae.current+=1;let $;try{$=await((0,d.isSetupIntentClientSecret)(ur)?b.confirmSetup({elements:Ie,clientSecret:ur,redirect:"if_required"}):b.confirmPayment({elements:Ie,clientSecret:ur,redirect:"if_required"}))}finally{_t()}if(!$||typeof $!="object")throw new Ia(Id($));if(Ot=$,!Ot.error&&!At(Ot))throw new Ia("confirmation_result_unconfirmed");jt=Xt(Ot.error?"returned_error":"resolved",Ot.error&&(0,ve.isProviderDecline)(Ot.error)?"provider_declined":void 0)}catch($){let Vt=$ instanceof Ia?$.reason:void 0,tt=Vt!==void 0,Lt=Xt(tt?"returned_error":"rejected");if(Tt?.error({...tt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Vt}:Gi($),...qr,operationOutcome:Lt.operationOutcome,durationMs:Lt.durationMs,statusClass:"unknown",terminalReason:Lt.terminalReason}),!O.current||ye)return;await Kr?.();return}let vr=Ot.error;if(vr){if(!O.current||ye)return;if((0,ve.isProviderDecline)(vr)){Z=!0,ns(dt,wt,ur),_e.current=null,fe.current=null,j("idle"),xt.current.get(de)===R&&xt.current.delete(de);let $=vr.message??"Your payment was declined.";p?.($),h?.(wr(xr,$,{code:(0,ve.getProviderErrorCode)(vr),declineCode:(0,ve.getProviderDeclineCode)(vr)})),yi({billingApiUrl:n,sessionId:dt,nonce:wt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:K,providerDeclineReason:(0,ve.getProviderErrorCode)(vr)??"provider_declined",...Fr.intentKind==="payment"&&Fr.providerObjectId.startsWith("pi_")?{providerIntentId:Fr.providerObjectId}:{}}})}else Tt?.error({...Gi(vr),...qr,operationOutcome:jt.operationOutcome,durationMs:jt.durationMs,statusClass:"unknown",terminalReason:jt.terminalReason}),await Kr?.();return}if(Me(Ot),!ye)throw new Error("Invalid provider returned for APM intent")}catch(dt){if(dt===di){let wt=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:Md(ln),stage:Kt,requestCategory:ln,paymentMethodCategory:"wallet",provider:"stripe",...ir?{walletType:ir}:{},operationOutcome:"watchdog_expired",checkoutSessionId:xn,durationMs:Math.max(0,wt-Lr),statusClass:"timeout",failureCategory:Nr,attempt:Ht,terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{})}se(),C(K,dt,dt===di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",R?.generation,dt===di)}finally{if(window.clearTimeout(br),Mt!==null&&(window.clearTimeout(Mt),et.current.delete(Mt)),!$r){let dt=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:"callback",durationMs:Math.max(0,dt-Lr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Zt?{statusClass:"timeout"}:{}})}O.current&&xe(!1)}},[b,Ie,e,t,r,E,B,Y,n,pe,a,l,p,h,S,C,_t,Ce,pt,ht,z,_,de]),Ve=(0,o.useMemo)(()=>ai(i),[i]),He=(0,o.useMemo)(()=>i.map(d.stripeExpressMethodToOptionKey),[i]),Bt=(0,o.useMemo)(()=>(0,u.jsx)(rr.ExpressCheckoutElement,{onReady:c=>{me(wa(c,He))},onLoadError:c=>{me("load_error"),us(_,"stripe","wallet","provider_error")},onClick:async c=>{let U=_?.now()??globalThis.performance?.now()??Date.now();ut.current=c.expressPaymentType,Le.current=Vl(c.expressPaymentType);let V=!0,se=window.setTimeout(()=>{V=!1,c.reject(),M(c.expressPaymentType)},vd),R=S?await S(Le.current,{abandoned:()=>!V}):{proceed:!0};if(window.clearTimeout(se),!V)return;if(!R.proceed){xt.current.delete(de),c.reject();return}let K=Ct(c.expressPaymentType);Dt.current=!1,at.current={generation:K,startedAt:U},xt.current.set(de,{generation:K,method:c.expressPaymentType,accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}),J(!1),_?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:K,...c.expressPaymentType==="apple_pay"||c.expressPaymentType==="google_pay"?{walletType:c.expressPaymentType}:{}}),m?.(Le.current),c.resolve()},onConfirm:mt,onCancel:()=>{let c=xt.current.get(de);xt.current.delete(de);let U=at.current,V=_?.now()??globalThis.performance?.now()??Date.now();if(c&&U?.generation===c.generation&&(0,d.isWalletSheetRefusedForWindowSize)({method:c.method,elapsedMs:V-U.startedAt,handoffObserved:ar.current===c.generation})){_?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:c.generation,walletType:"google_pay"}),_e.current=null,C(c.method,new Error("The browser window is too small for the Google Pay sheet."),d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,c.generation,!0);return}_?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...c?{attempt:c.generation}:{}}),T(c?.generation),_e.current=null,J(!1),Pe.current=!0,be()},options:{...ii,paymentMethods:Ve,emailRequired:lt,billingAddressRequired:lt}},de),[He,Ve,mt,T,m,lt,C,M,be,S,Ct,de,_]);return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(ka,{state:ie,placeholderTestId:"flopay-wallet-placeholder",borderRadius:ee,children:(0,u.jsxs)("div",{ref:Ge,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[te&&(0,u.jsxs)("button",{ref:De,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Se,style:ss,children:["Try ",ls(je)," again"]}),H!=="idle"&&(0,u.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,u.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,u.jsx)("button",{type:"button",onClick:ct,disabled:H==="checking",style:ss,children:H==="checking"?"Checking payment status\u2026":"Check payment status"})]}),$e&&(0,u.jsx)(qo,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:St,onCancel:()=>St(null)},$e.id),(0,u.jsxs)("div",{style:{display:$e||H!=="idle"?"none":void 0},children:[(0,u.jsx)($d,{active:X}),Bt]})]})}),ue&&(0,u.jsx)(Zr,{status:"processing"})]})}function Jl(e,t,r){let n=(0,d.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,paymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function cs({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:p,onErrorChange:m,onDecline:h,onCancel:w,runBeforeButtonClick:S,onButtonClick:E,isProcessing:Y,submitButtonColor:I,submitButtonBorderRadius:ee,submitButtonStyle:x,errorText:f}){let P=Qn(),{emitInstrument:pe}=(0,o.useContext)(pn),b=(0,rr.useStripe)(),Ie=(0,rr.useElements)(),[_,ie]=(0,o.useState)(!1),me=(0,o.useRef)(!1),[ue,xe]=(0,o.useState)(!1),[lt,$e]=(0,o.useState)("loading"),[B,St]=(0,o.useState)(""),Ge=!(0,d.isValidEmail)(n?.trim()),De=!Ge||(0,d.isValidEmail)(B.trim()),de=(0,o.useCallback)(async()=>{if(!b||!Ie||Y||me.current||!ue)return;me.current=!0,ie(!0);let re=S?await S("card"):{proceed:!0};if(!re.proceed){me.current=!1,ie(!1);return}E?.("card");let X=re.sessionId??t,Oe=re.nonce??r,nt=(0,Uo.splitFullName)(a?.trim()),ze=(0,mn.compactBuyerIdentity)({email:re.accountPatch?.email?.trim()||n?.trim()||B.trim(),firstName:re.accountPatch?.firstName?.trim()||nt.firstName,lastName:re.accountPatch?.lastName?.trim()||nt.lastName}),te=ze.email,J=(0,mn.compactBuyerIdentity)({...re.accountPatch,...ze});try{if(m?.(null),!(0,d.isValidEmail)(te))throw new Error("A valid email address is required for payment.");await i?.(ze);let H=await Ie.submit();if(H.error){m?.(H.error.message??"Payment failed.");return}let j=[ze.firstName,ze.lastName].filter(Boolean).join(" "),je=await b.createPaymentMethod({elements:Ie,params:{billing_details:{email:te,...j?{name:j}:{}}}});if(je.error||!je.paymentMethod){m?.(je.error?.message??"Failed to create payment method.");return}let Te=je.paymentMethod;if(!X||!te)throw new Error("Missing sessionId or email for payment.");let fe=Te.type||e,O=await mi(l,pe,X,Oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,paymentMethodId:null,intentKind:"payment"});if(O.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Pe=O.clientSecret;nr(jn,{clientSecret:Pe,sessionId:X,nonce:Oe,accountPatch:J,paymentMethodId:Te.id,paymentMethodType:Te.type??e,gateway:"stripe"});let{error:ut,paymentIntent:Le}=await b.confirmPayment({clientSecret:Pe,confirmParams:{return_url:window.location.href,payment_method:Te.id},redirect:"if_required"});if(ut){nr(jn);let et=ut.message??"Payment failed.";m?.(et),h?.(wr("card",et,{code:ut.code})),await yi({billingApiUrl:l,sessionId:X,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ut.code??"provider_declined"}});return}let ot=Le?.status;if(!pa(ot)){nr(jn);let et=ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(et),h?.(wr("card",et,{code:ot??"missing_payment_intent"}));return}nr(jn);let _e=typeof Le?.payment_method=="string"?Le.payment_method:Le?.payment_method?.id;p({id:_e??Te.id,type:"card",threeDSecureActionResultTokenId:Le?.id,gateway:"stripe",paymentMethodType:Te.type??e},{accountPatch:J,paymentMethodCategory:"apm",sessionId:X,nonce:Oe})}catch(H){m?.(H instanceof Error?H.message:"Payment failed. Please try again.")}finally{me.current=!1,ie(!1)}},[b,Ie,Y,ue,S,E,t,r,n,a,B,i,l,pe,e,p,m,h]);return(0,u.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ge&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ge&&(0,u.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,u.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:B,onChange:re=>St(re.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,u.jsx)(rr.PaymentElement,{onReady:()=>$e("ready"),onLoadError:()=>{$e("load_error"),us(kr(P),"stripe","apm")},onChange:re=>{xe(!!re.complete)},options:{layout:si,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,d.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,u.jsx)(li,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{de()},disabled:!ue||!De||_||Y||lt!=="ready",color:I,borderRadius:ee,style:x,children:_?"Processing\u2026":`Pay with ${(0,d.getStripeMethodDisplayName)(e)}`}),f&&(0,u.jsx)(Wo,{margin:"0.75rem 0 0",children:f})]})}function Hl({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:l,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:h,onTokenizedBody:w,onErrorChange:S,onButtonClick:E,onDecline:Y,runBeforeButtonClick:I,onLoadStateChange:ee,isProcessing:x=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:pe,buttonAppearance:b,themeId:Ie,onExpandApm:_,expandedApmMethod:ie}){let{emitInstrument:me}=(0,o.useContext)(pn),[ue,xe]=(0,o.useState)(null),[lt,$e]=(0,o.useState)(null),B=(0,o.useRef)(!1),{request:St,collect:Ge,finish:De}=zo();(0,o.useEffect)(()=>{l.length>0&&p?ee?.("ready"):p||ee?.("loading")},[l.length,p,ee]);let de=(0,o.useCallback)(async te=>{if(!p||B.current||x)return;B.current=!0,$e(te);let J=I?await I("card"):{proceed:!0};if(!J.proceed){B.current=!1,$e(null);return}E?.("card");let H=J.sessionId??e,j=J.nonce??t,je=(0,Uo.splitFullName)([J.accountPatch?.firstName,J.accountPatch?.lastName].filter(Boolean).join(" ")||n),Te=(0,mn.compactBuyerIdentity)({email:J.accountPatch?.email?.trim()||r?.trim(),firstName:J.accountPatch?.firstName?.trim()||je.firstName,lastName:J.accountPatch?.lastName?.trim()||je.lastName});if(!(0,d.isValidEmail)(Te.email)){$e(null);let Pe=await Ge((0,d.getStripeMethodDisplayName)(te),Te);if(!Pe){B.current=!1;return}Te=Pe,$e(te)}let fe=Te.email,O=(0,mn.compactBuyerIdentity)({...J.accountPatch,...Te});try{if(S?.(null),!H||!(0,d.isValidEmail)(fe))throw new Error("Missing sessionId or email for payment.");await a?.(Te);let Pe=await mi(i,me,H,j??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(Pe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ut=Pe.clientSecret;nr(jn,{clientSecret:ut,sessionId:H,nonce:j,accountPatch:O,paymentMethodType:te,gateway:"stripe"});let{error:Le,paymentIntent:ot}=await p.confirmPayment({clientSecret:ut,confirmParams:{return_url:window.location.href,payment_method_data:{type:te,billing_details:{name:[Te.firstName,Te.lastName].filter(Boolean).join(" "),...fe?{email:fe}:{}}}},redirect:"if_required"});if(Le){nr(jn);let at=Le.message??"Payment failed.";S?.(at),Y?.(wr("card",at,{code:Le.code})),await yi({billingApiUrl:i,sessionId:H,nonce:j,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:Le.code??"provider_declined"}});return}let _e=ot?.status;if(!pa(_e)){nr(jn);let at=_e==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(at),Y?.(wr("card",at,{code:_e??"missing_payment_intent"}));return}nr(jn);let et=typeof ot?.payment_method=="string"?ot.payment_method:ot?.payment_method?.id;w({id:et??ot?.id,type:"card",threeDSecureActionResultTokenId:ot?.id,gateway:"stripe",paymentMethodType:te},{accountPatch:O,paymentMethodCategory:"apm",sessionId:H,nonce:j})}catch(Pe){S?.(Pe instanceof Error?Pe.message:"Payment failed. Please try again.")}finally{B.current=!1,$e(null)}},[p,x,I,E,e,t,r,Ge,i,me,n,a,w,S,Y]),[re,X]=(0,o.useState)(null),Oe=_?ie??null:re,nt=(0,o.useCallback)(te=>{B.current||x||Oe&&Oe!==te||((0,d.needsStripeMethodExplicitConfirm)(te)?_?_(te):X(te):de(te))},[Oe,x,de,_]),ze=(0,o.useMemo)(()=>re?Jl(m,re,h):null,[re,m,h]);return(0,u.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:St?(0,u.jsx)(qo,{identity:St.identity,methodLabel:St.methodLabel,onComplete:De,onCancel:()=>De(null)},St.id):l.map(te=>{let J=ie===te,H=lt===te,j=lt!==null&<!==te||ie!=null&&ie!==te;return(0,u.jsxs)(o.default.Fragment,{children:[(0,u.jsx)(oi,{method:te,themeId:Ie,submitting:H,disabled:j,highlighted:J,hasNextStep:(0,d.needsStripeMethodExplicitConfirm)(te),onClick:()=>nt(te),backgroundColor:b?.backgroundColor,borderColor:b?.borderColor,textColor:b?.textColor,borderRadius:b?.borderRadius,fontFamily:b?.fontFamily}),!_&&re===te&&ze&&p&&(0,u.jsx)(rr.Elements,{stripe:p,options:ze,children:(0,u.jsx)(cs,{method:te,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:w,onErrorChange:S,onDecline:Y,onCancel:()=>X(null),runBeforeButtonClick:I,onButtonClick:E,isProcessing:x,submitButtonColor:f,submitButtonBorderRadius:P,submitButtonStyle:pe})},te)]},te)})})}function Hd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:i,onComplete:l,onError:p,onDecline:m,onCancel:h,onTokenizedBody:w,firstName:S,lastName:E,chv:Y,className:I,submitLabel:ee,isProcessing:x,error:f,onErrorChange:P,showPayPal:pe=!0,showStripe:b=!0,walletPresentation:Ie="auto",enabledPaymentMethods:_,enabledPaymentMethodCountries:ie,showApplePay:me=!0,showGooglePay:ue=!0,layout:xe="default",theme:lt,buttonsTheme:$e,buttonsStyles:B,appearance:St,cardButtonContent:Ge,cardBackButtonContent:De,cardTitleContent:de,showSecurityFooter:re,onButtonClick:X,onBeforeButtonClick:Oe,onBuyerIdentityReady:nt,enableAVS:ze,cardFieldOrder:te,cardPreFormSlot:J,avsLayout:H="row",country:j,zip:je,addressLine1:Te,addressLine2:fe,city:O,state:Pe,onCountryChange:ut,onZipChange:Le,avsCheck:ot,checkoutType:_e,checkoutLayout:et,totalAmount:at=0,currency:ar="usd",initialCardOpen:xt=!1,directPaypal:Ct,isSubscription:Ce=!1,session:T,dataAttachmentPending:ht=!1,dataAttachmentRequiresIdentity:pt=!1,debug:z=!1}){let Ae=Qn(),Dt=Ga(),be=(0,o.useContext)(En),{emitInstrument:_t}=(0,o.useContext)(pn),C=(0,o.useRef)(null);C.current||(C.current=Xa());let M=C.current,[,Fe]=(0,o.useState)(0),Se=(0,o.useRef)(null);Se.current||(Se.current=(0,Un.detectPayPalEnvironment)());let ct=Se.current,mt=(0,o.useMemo)(()=>({browser:ct,capability:M,presentationMode:"popup"}),[ct,M]),Ve=T??be.session,He=(0,o.useMemo)(()=>({futureUse:Ve?.futureUse,futureUseUnsupported:Ve?.futureUseUnsupported}),[Ve?.futureUse,Ve?.futureUseUnsupported]),Bt=Ve?.gateways?.paypal?.providerObjectType??Ct?.providerObjectType,c=ht||be.claimPending===!0,U=pt||be.claimRequiresIdentity===!0,V=c&&!U,se=Sl(),R=r||se,[K,Ut]=(0,o.useState)(!1),[xr,ir]=(0,o.useState)(null),[Ht,Tt]=(0,o.useState)(j??""),[Lr,Ar]=(0,o.useState)(je??""),[Zt,$r]=(0,o.useState)(Te??""),[Mt,xn]=(0,o.useState)(fe??""),[Kt,ln]=(0,o.useState)(O??""),[Nr,Ur]=(0,o.useState)(Pe??""),[sr,br]=(0,o.useState)(""),[Hr,dt]=(0,o.useState)({}),wt=(0,o.useRef)(je??""),lr=(0,o.useRef)(j??""),Gt=(0,o.useRef)(Te??""),hr=(0,o.useRef)(fe??""),Yt=(0,o.useRef)(O??""),cr=(0,o.useRef)(Pe??""),Ir=(0,o.useRef)(""),dr=(0,o.useRef)({});(0,o.useEffect)(()=>{let s=(D,ae,Re,Q,Ee)=>{if(dr.current[D])return;let zt=ae?.trim();!zt||zt===Re.current||(Re.current=zt,Q(zt),Ee?.(zt))};s("country",j,lr,Tt,ut),s("zip",je,wt,Ar,Le),s("addressLine1",Te,Gt,$r),s("addressLine2",fe,hr,xn),s("city",O,Yt,ln),s("state",Pe,cr,Ur)},[j,je,Te,fe,O,Pe,ut,Le]);let Ye=(0,o.useMemo)(()=>(0,d.resolveAVSConfig)(ze),[ze]),Fr=Ye!==null,ur=(0,o.useMemo)(()=>(0,d.isAuthorizationOnlySession)(T),[T]),oo=(0,d.isMountableVaultBlock)(T?.vault),zr=!!T?.gateways?.pcivault,qr=(0,Rn.hasServerSideCardGateway)(T),Kr=!!(T?.gateways?.stripe?.enabledPaymentMethods??_)?.includes("card")||(0,Rn.canRecoverHostedCardForm)(T),Xt=oo||Kr||zr,ye=!!(b&&Xt&&e),[Z,At]=(0,o.useState)(()=>xe!=="buttons"||xt?e??null:null),[Me,Pr]=(0,o.useState)(0),Ot=xe!=="buttons"||xt||!!e&&Z===e,jt=T?.captureMethod,vr=(0,o.useRef)(Ae);(0,o.useEffect)(()=>{vr.current=Ae},[Ae]);let[$,Vt]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!ye||!e||!Ot){Vt(null);return}let s=vr.current?vr.current.cardCapture({sessionId:e,captureMethod:jt}):new Mn.PciVaultCardCapture({sessionId:e,captureMethod:jt,billingApiUrl:R,telemetry:n});return Vt({sessionId:e,captureMethod:jt,billingApiUrl:R,telemetry:n,capture:s}),()=>{s.unmount()}},[ye,e,Ot,jt,R,n]);let tt=ye&&e&&Ot&&$?.sessionId===e&&$.captureMethod===jt&&$.billingApiUrl===R&&$.telemetry===n?$.capture:null,Lt=(0,o.useMemo)(()=>{let s=Ht,D=Ye?(0,d.isAVSFieldVisible)(Ye.postal_code,s):!1;return qd(s,Lr,D)},[Ye,Ht,Lr]),{avsInvalid:pr,invalidAvsFields:Br}=(0,o.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!ye||!Ye)return{avsInvalid:!1,invalidAvsFields:s};let D=Ht,ae=(Ee,zt)=>(0,d.isAVSFieldVisible)(Ee,D)&&!zt.trim(),Re={line1:ae(Ye.address_line_1,Zt),city:ae(Ye.city,Kt),state:ae(Ye.state,Nr),zip:Lt.empty||Lt.malformed};return{avsInvalid:Re.line1||Re.city||Re.state||Re.zip,invalidAvsFields:Re}},[ye,Ye,Ht,Zt,Kt,Nr,Lt]),[Qt,vn]=(0,o.useState)(!1),[$n,Fn]=(0,o.useState)(!1),[jr,ao]=(0,o.useState)(!1),[cn,Hn]=(0,o.useState)({line1:!1,city:!1,state:!1}),en=(0,o.useRef)(!1),Cn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Bn=(0,o.useRef)(!1),Nt=(0,o.useCallback)(s=>{Cn.current[s]=!0,Bn.current=!0},[]),tn=(0,o.useCallback)(s=>!en.current&&Cn.current[s],[]),rn=(0,o.useCallback)(s=>{tn(s)&&Hn(D=>D[s]?D:{...D,[s]:!0})},[tn]),[Gr,bn]=(0,o.useState)(()=>(0,d.resolveVaultMountOptions)(T?.vault,{billingApiUrl:R,sessionId:e,nonce:t})),[bt,_r]=(0,o.useState)(xt&&Xt?"card":"buttons"),[mr,Yr]=(0,o.useState)(null),mo=bt==="expanding"||bt==="card",Sn=T?.gateways?.stripe&&!qr?"stripe":void 0,Kn=(0,o.useCallback)(()=>{_t?.({class:"card_surface",provider:Sn})},[Sn,_t]),nn=(0,o.useRef)(null),Tr=(0,o.useCallback)(s=>{nn.current&&clearTimeout(nn.current),nn.current=setTimeout(()=>{nn.current=null,s()},_a)},[]);(0,o.useEffect)(()=>()=>{nn.current&&clearTimeout(nn.current)},[]);let Dn=(0,o.useRef)(!1),[Dr,L]=(0,o.useState)(0),N=(0,o.useRef)(null),ne=(0,o.useCallback)(()=>{Kn(),At(e??null),Dn.current&&(Dn.current=!1,L(s=>s+1)),Pr(s=>s+1),_r("expanding"),Tr(()=>_r("card"))},[Tr,Kn,e]),we=(0,o.useCallback)(()=>{_r("collapsing"),Tr(()=>_r("buttons"))},[Tr]),Rt=(0,o.useCallback)(s=>{Yr(s),_r("apm-expanding"),Tr(()=>_r("apm-form"))},[Tr]),er=(0,o.useCallback)(()=>{_r("apm-collapsing"),Tr(()=>{_r("buttons"),Yr(null)})},[Tr]);(0,o.useEffect)(()=>{xe==="buttons"&&xt&&Xt&&(At(e??null),_r("card"))},[xe,xt,Xt,e]);let[Ne,le]=(0,o.useState)(null),q=(0,o.useRef)(!1),W=(0,o.useRef)(null),ce=(0,o.useRef)("idle"),[g,y]=(0,o.useState)(!1),G=(0,o.useRef)(g);G.current=g;let[ke,Xe]=(0,o.useState)(()=>Ct?.existingOrderId?{orderId:Ct.existingOrderId,attempts:1}:null),yt=(0,o.useRef)(ke);(0,o.useEffect)(()=>{yt.current=ke},[ke]);let Ue=(0,o.useRef)(null),Be=(0,o.useMemo)(()=>{if(nt||be.claimBuyerIdentity||T?.buyerIdentified!==!1||!e||!t)return;let s=`${R}|${e}|${t}`;Ue.current?.key!==s&&(Ue.current={key:s,claim:Lo(new Mn.PaymentAPI(R,{telemetry:!1}),e,t,{...i?{userId:i}:{},...S?{firstName:S}:{},...E?{lastName:E}:{}})});let D=Ue.current.claim;return async ae=>{await D(ae)}},[nt,be.claimBuyerIdentity,T?.buyerIdentified,e,t,R,i,S,E]),it=nt??be.claimBuyerIdentity??Be,kt=f??xr,Et=(0,o.useMemo)(()=>(0,d.resolveTheme)(lt),[lt]),A=(0,o.useMemo)(()=>{let s=Et?.buttonsLayout??(0,d.resolveButtonsLayoutTheme)($e);return B?{...s,...B,cardButton:{...s.cardButton,...B.cardButton},cardFormContainer:{...s.cardFormContainer,...B.cardFormContainer},backButton:{...s.backButton,...B.backButton},backButtonIcon:{...s.backButtonIcon,...B.backButtonIcon},submitButton:{...s.submitButton,...B.submitButton},title:{...s.title,...B.title}}:s},[Et,$e,B]),ge=St??Et?.appearance,Je=(0,o.useMemo)(()=>(0,d.computeVaultCardThemeColors)({appearance:ge,buttonsStyles:A,layout:xe}),[ge,A,xe]),rt=be.inlineSessionPatchProcessing??!1,oe=(x??K)||rt,yr=R.replace(/\/+$/,""),he=(0,o.useMemo)(()=>Ki({userId:i,email:a,firstName:S,lastName:E,country:j,zip:je},Hr),[i,a,S,E,j,je,Hr]),Gn=[he.firstName,he.lastName].filter(s=>!!s?.trim()).join(" "),ks=!(0,d.isValidEmail)(he.email?.trim()),ki=(0,o.useRef)(null);ye&&ki.current===null&&(ki.current=ks);let io=ye&&(ki.current??ks),Ri=(0,o.useMemo)(()=>jd(sr,io),[sr,io]),ko=Ri.empty||Ri.malformed,on=(0,o.useMemo)(()=>Ae?Ae.getRawProvider():null,[Ae]),Rs=(0,o.useMemo)(()=>Dt?Dt.getRawProvider():null,[Dt]),Qo=at||100,Ro=ar.toLowerCase(),Ei=(0,o.useMemo)(()=>ge?(0,Mn.toStripeAppearance)(ge):null,[ge]),Eo=Ei,Es=(0,o.useMemo)(()=>{let s=Ei??{},D=s.rules??{};return{...s,rules:{...D,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...D[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...D[".AccordionItemContents"]??{}}}}},[Ei]),Is=(0,o.useMemo)(()=>({...vl(at,Ve?.captureMethod,He),currency:Ro,...Eo?{appearance:Eo}:null}),[at,Ro,Ve?.captureMethod,He,Eo]),Ii=(0,d.resolveSetupFutureUsage)(He,"paypal","paypal"),_s=(0,o.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,captureMethod:"manual",...Ii?{setupFutureUsage:Ii}:null,...Eo?{appearance:Eo}:null}),[Qo,Ro,Ii,Eo]),qe=(0,o.useCallback)(s=>{ir(s),P?.(s)},[P]),Ts=(0,o.useRef)(0);(0,o.useEffect)(()=>{Dr!==Ts.current&&(Ts.current=Dr,qe(null))},[Dr,qe]);let _i=(0,o.useRef)(""),[Ms,Cc]=(0,o.useState)(!1),Ti=(0,o.useCallback)(()=>{Cc(!0)},[]);(0,o.useEffect)(()=>{if(!ye||!io||!it||!Ms||ko||_i.current)return;let s=(0,mn.compactBuyerIdentity)({email:(0,d.isValidEmail)(he.email?.trim())?he.email?.trim():Ir.current.trim(),firstName:he.firstName?.trim(),lastName:he.lastName?.trim()});_i.current=JSON.stringify(s),dt(D=>({...D,...s})),Promise.resolve(it(s)).catch(D=>{_i.current="",qe(D instanceof Error?D.message:"Failed to attach buyer details.")})},[ye,io,it,Ms,ko,he.email,he.firstName,he.lastName,qe]),(0,o.useEffect)(()=>{!ye||!tt||tt.setCardFieldOrder?.(te??null,Ye==null&&!io)},[ye,tt,te,Ye,io]),(0,o.useEffect)(()=>{(bt==="expanding"||bt==="collapsing"||bt==="apm-expanding"||bt==="apm-collapsing")&&qe(null)},[bt,qe]);let On=(0,o.useCallback)((s,D,ae)=>{m?.(wr(s,D,ae))},[m]),Io=(0,o.useCallback)((s,D,ae)=>{let Re=ae?.popupBlocked??(0,ve.isPopupBlockedError)(D);Re&&M.markBlocked()&&Fe(It=>It+1);let Q=ls(s),Ee=ae?.code===d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,d.buildWalletSheetWindowMessage)(Q):(0,ve.buildExternalMethodRecoveryMessage)(Q,Re,ct.inAppBrowser),zt=(0,ve.getProviderErrorCode)(D),un=(zt?.toLowerCase()==="error"?void 0:zt)??(0,ve.sanitizeExternalFailureCode)(ae?.code)??"external_payment_method_failed",Pt=new d.FloPayError(Ee,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:un,popupBlocked:Re,inAppBrowser:ct.inAppBrowser,appFamily:ct.appFamily,popupCapability:M.current(),presentationMode:ae?.presentationMode??"popup"}});ae?.telemetryReported||kr(Ae)?.error(Go({...mt,presentationMode:ae?.presentationMode??"popup"},{errorCode:Re?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:ae?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:ae?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:ae?.terminalReason??(Re?"popup_blocked":"provider_error")})),le(null),xe==="buttons"&&(_r("buttons"),Yr(null)),qe(Ee),p?.(Pt),console.error("[FloPay] External payment method failed:",{method:s,code:un,popupBlocked:Re})},[ct,mt,Ae,xe,p,M,qe]);(0,o.useEffect)(()=>{if(!ye||!e){bn(null);return}let s={billingApiUrl:yr,sessionId:e,nonce:t},D=(0,d.resolveVaultMountOptions)(T?.vault,s);if(D){bn(D);return}if(!Ot){bn(null);return}let ae=`${yr}\0${e}\0${t??""}`,Re=N.current;if(Re&&Re.key===ae){bn(Re.mount);return}bn(null);let Q=!0;return new Mn.PaymentAPI(yr).getVaultCapture(e,t).then(Ee=>{if(!Q)return;let zt=(0,d.resolveVaultMountOptions)(Ee,s);zt?.verificationRequired&&!Ee.html&&(N.current={key:ae,mount:zt}),zt?bn(zt):qe("Failed to load the secure card form.")}).catch(Ee=>{Q&&qe(Ee instanceof Error?Ee.message:"Failed to load the secure card form.")}),()=>{Q=!1}},[ye,Ot,Me,e,T?.vault,yr,t,qe]);let wn=(0,o.useRef)({onComplete:l,onError:p,updateError:qe,emitDecline:On,resolvedAccount:he,avsConfig:Ye,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:yr,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt,serverSideCardGateway:qr});wn.current={onComplete:l,onError:p,updateError:qe,emitDecline:On,resolvedAccount:he,avsConfig:Ye,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:yr,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt,serverSideCardGateway:qr};let Mi=(0,o.useRef)(!1),xs=(0,o.useCallback)(()=>{let s=wn.current,D=s.resolvedAccount.email?.trim(),ae=(0,d.isValidEmail)(D)?D:Ir.current.trim();if(!(0,d.isValidEmail)(ae))return null;let Re=s.resolvedAccount.firstName?.trim(),Q=s.resolvedAccount.lastName?.trim(),Ee=lr.current.trim()||s.resolvedAccount.country?.trim()||"",zt=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.state,Ee):!1,un=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.address_line_1,Ee):!1,Pt=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.postal_code,Ee):!1,It=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.city,Ee):!1,Ft=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.address_line_2,Ee):!1,Wt=un&&!zt&&Pt?(0,d.getStateFromPostalCode)(Ee,(wt.current??"").trim()):null,go=zt?cr.current:Wt;return{accountData:{userId:s.resolvedAccount.userId??"",email:ae,...Re?{firstName:Re}:{},...Q?{lastName:Q}:{},...Pt&&wt.current?{zip:wt.current}:{},...It&&Yt.current?{city:Yt.current}:{},...go?{state:go}:{},...un&&Gt.current?{addressLine1:Gt.current}:{},...Ft&&hr.current?{addressLine2:hr.current}:{},...Ee?{country:Ee}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,d.isAVSFieldVisible)(s.avsConfig.country,Ee),postal_code:Pt,address_line_1:un,address_line_2:Ft,city:It,state:zt}}:{}}},[]),As=(0,o.useRef)(c);As.current=c,(0,o.useEffect)(()=>{c||kt!==zl||wn.current.updateError(null)},[c,kt]),(0,o.useEffect)(()=>{!ye||!tt||tt.setSubmitGate?.(pr||c||ko||g)},[ye,tt,pr,c,ko,g]),(0,o.useEffect)(()=>{if(!ye||!tt)return;Mi.current=!1;let s=null,D=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,ce.current="idle",le(null)},400)},ae=tt.on("submitting",()=>{vn(!0),W.current&&clearTimeout(W.current),ce.current="validation-window",W.current=setTimeout(()=>{W.current=null,ce.current==="validation-window"&&(ce.current="processing")},xd),le("processing");let Pt=wn.current;if(!Pt.sessionId||!Pt.nonce)return;let It=xs();if(!It){Pt.updateError("Enter a valid email address."),ce.current="idle",le(null);return}new Mn.PaymentAPI(Pt.baseUrl).patchAccountSnapshot(Pt.sessionId,Pt.nonce,It,{telemetryMode:"best_effort"}).catch(Ft=>{if(!Fd(Ft))return;let Wt=Ft instanceof Error?Ft.message:"Please check your billing address and try again.";Pt.updateError(Wt),ce.current="idle",le(null),Pt.onError?.(Ft instanceof d.FloPayError?Ft:new d.FloPayError(Wt,"api_error"))})}),Re=tt.on("complete",Pt=>{(0,_n.markSessionRecentlyCompleted)(Pt.sessionId??wn.current.sessionId),ce.current="terminal",y(!1),le("success"),setTimeout(()=>{if(Mi.current)return;Mi.current=!0;let It=wn.current,Ft=(0,d.isAuthorizationOnlySession)(It)||Pt.outcome==="authorized",Wt=It.serverSideCardGateway?{}:{paymentIntentId:Pt.intentId};wn.current.onComplete?.(Ft?{status:"authorized",...Wt,paymentId:Pt.paymentId??It.paymentId,sessionId:Pt.sessionId??It.sessionId,authorizationExpiresAt:Pt.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Wt,checkoutMethod:"card"})},600)}),Q=tt.on("decline",Pt=>{let It=wn.current,Ft=Pt.message??"Your payment was declined. Please try another card or contact your bank.";ce.current="terminal",y(!1),It.updateError(Ft),le("error");let Wt=Pt.failureOutcome??(0,d.normalizeCheckoutFailureOutcome)(Pt.declineReason)??"authorization_declined";It.emitDecline("card",Ft,{code:Wt,declineCode:Wt}),D()}),Ee=tt.on("error",Pt=>{let It=wn.current,Ft=Pt.message??"There was a problem processing your payment. Please try again.";ce.current="terminal",y(!1),It.updateError(Ft),le("error"),It.onError?.(new d.FloPayError(Ft,"api_error",{code:Pt.failureOutcome??"capture_failed"})),D()}),zt=tt.on("challenge_dismissed",()=>{W.current&&(clearTimeout(W.current),W.current=null),ce.current="processing",y(!0),le(null)}),un=tt.on("blocked",()=>{if(G.current){wn.current.updateError(Ad);return}if(!As.current){vn(!0);return}Ti(),wn.current.updateError(zl)});return()=>{s&&(clearTimeout(s),s=null),W.current&&(clearTimeout(W.current),W.current=null),ce.current="idle",y(!1),le(null),ae(),Re(),Q(),Ee(),zt(),un()}},[ye,tt,Ti,xs]);let Ln=!!Ct?.clientId,ea=Array.isArray(_),Fa=ea&&_.length>0,Fs=ea&&_.includes("paypal"),Ba=(0,o.useRef)(null);Ba.current===null&&(Ba.current=(0,d.hasMatchingStripePayPalReturn)());let _o=Ba.current?"redirect":(0,zn.resolveStripePayPalPresentation)(ct,Ie,M.current()),{expressMethods:Da,paymentElementMethods:xi}=(0,o.useMemo)(()=>(0,d.partitionStripeMethods)(_,{excludePaypal:Ln}),[_,Ln]),Bs=Ln||!!Dt||Fs&&_o==="redirect",bc=(0,o.useMemo)(()=>Bs?Da.filter(s=>s!=="paypal"):Da,[Da,Bs]),Sc=(0,o.useMemo)(()=>{let s=[];return me&&s.push("apple_pay"),ue&&s.push("google_pay"),s},[me,ue]),To=ea?bc:Sc,wc=b&&To.length>0,Ds=Fr?Ht:j,Oa=(0,o.useMemo)(()=>(0,d.filterStripeMethodsByCountryGate)(xi,Ds,ie),[xi,Ds,ie]),Ai=(0,o.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,paymentMethodCreation:"manual",appearance:Es}),[Qo,Ro,Es]),[Os,Ls]=(0,o.useState)("loading"),[Ns,Us]=(0,o.useState)("loading"),[zs,qs]=(0,o.useState)("loading"),[kc,Fi]=(0,o.useState)(!1),[js,Bi]=(0,o.useState)("loading"),[Di,Rc]=(0,o.useState)();(0,o.useEffect)(()=>{Rc((0,Un.detectPayPalEnvironment)())},[]);let La=Di?.inAppBrowser,Na=Di?(0,zn.resolvePayPalPresentationMode)(Di,Ct?.approvalPresentation,Bt??(Ce?"subscription":"order")):"popup",Vs=pe&&(Ln||(ea?Fs:La===!1)),Ec=ct.inAppBrowser&&M.current()==="blocked",Ws=b&&wc&&!Ec,ta=(!V||!!be.waitForDataAttachment)&&Vs&&Ln,$s=js==="retrying"||js==="exhausted",ra=null;b&&(Dt?ra=Rs:_o==="redirect"&&(ra=on));let Hs=(0,o.useMemo)(()=>({...mt,presentationMode:_o}),[mt,_o]),na=!V&&Vs&&!!ra&&(!Ln||$s),Mo=!V&&Ws&&!!on,oa=!V&&b&&Fa&&Oa.length>0&&!!on,Ic=ta&&!$s?kc:na&&ts(Os),_c=Mo&&ts(Ns),Tc=oa&&zs!=="load_error",Ks=s=>s==="loading"||s==="ready",Gs=ta||na&&Ks(Os)||Mo&&Ks(Ns)||oa&&zs!=="load_error",Ua=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Ua.current){if(!b&&!pe){Ua.current=!0;let s=new d.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(s),qe(s.message)}else if(!b&&pe&&!Ln){Ua.current=!0;let s=new d.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(s),qe(s.message)}else if(La!==void 0&&!V&&!Xt&&!Gs){Ua.current=!0;let s=new d.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"});p?.(s),qe(s.message)}}},[b,pe,Ln,La,V,Xt,Gs,p,qe]);let Ys=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(Ys.current||!Fa)return;let s=[];me!==!0&&s.push("showApplePay"),ue!==!0&&s.push("showGooglePay"),s.length!==0&&(Ys.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Fa,me,ue]);let Xs=(0,o.useCallback)((s,D,ae)=>be.applyInlineSessionPatch?be.applyInlineSessionPatch(s).then(Re=>({error:null,sessionId:Re.sessionId||e,nonce:Re.session?.clientSecret||t})).catch(Re=>{let Q=(0,d.normalizeBeforeButtonClickError)(D,Re);return ae?.abandoned?.()||(qe(Q.message),p?.(Q)),{error:Q,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[be.applyInlineSessionPatch,t,p,e,qe]),kn=(0,o.useCallback)(async(s,D)=>{if(s!=="card"&&V&&await be.waitForDataAttachment?.(),!Oe)return{proceed:!0};try{let ae=await Oe({method:s,sessionId:e||void 0,createSession:be.inlineSessionDraft});if(ae===!1)return{proceed:!1};if(ae&&typeof ae=="object"){ae.account&&dt(Q=>({...Q??{},...ae.account}));let Re=await Xs(ae,s,D);return Re.error?{proceed:!1,accountPatch:ae.account}:{proceed:!0,accountPatch:ae.account,sessionId:Re.sessionId,nonce:Re.nonce}}return{proceed:!0}}catch(ae){if(!D?.abandoned?.()){let Re=(0,d.normalizeBeforeButtonClickError)(s,ae);qe(Re.message),p?.(Re)}return{proceed:!1}}},[Xs,be.inlineSessionDraft,be.waitForDataAttachment,V,Oe,p,e,qe]),Js=(0,o.useCallback)(async(s,D)=>{if(q.current)return;q.current=!0,Ut(!0),le("processing"),qe(null);let ae=D?.sessionId??e,Re=D?.nonce??t,Q=Ki(he,D?.accountPatch),Ee=D?.completionPaymentMethodId??ma(s),zt=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,un=Ld(s),Pt=D?.presentationMode?ni(kr(Ae),{...mt,presentationMode:D.presentationMode}):void 0,It=()=>{_t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:un}),Pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Tn,requestCategory:"process_payment"})};try{let Ft=new Mn.PaymentAPI(yr),Wt=await Ft.processPayment(Q.userId??"",{sessionId:ae,nonce:Re,paymentMethodCategory:D?.paymentMethodCategory??Ud(s),tokenizedData:zt,accountData:{...D?.accountPatch,userId:Q.userId??"",email:Q.email??"",firstName:Q.firstName||void 0,lastName:Q.lastName||void 0,...(0,d.buildProcessPaymentAvsAccount)({avsConfig:Ye,country:lr.current,zip:wt.current,city:Yt.current,state:cr.current,addressLine1:Gt.current,addressLine2:hr.current})},...(0,d.buildCheckoutProcessMetadata)({chv:Y,avsCheck:ot,checkoutType:_e,checkoutLayout:et,avsConfig:Ye,country:lr.current})}),go=async Sr=>{let ho=(0,d.isAuthorizationOnlySession)(T)||Sr?.status==="authorized";(0,_n.markSessionRecentlyCompleted)(ae),Pt?.terminal({outcome:"payment_succeeded",...Tn}),le("success"),Xe(null),await new Promise(da=>setTimeout(da,600));let Nn;typeof Sr?.paymentId=="string"?Nn=Sr.paymentId:T?.paymentId&&(Nn=T.paymentId);let Po;typeof Sr?.authorizationExpiresAt=="string"?Po=Sr.authorizationExpiresAt:T?.authorizationExpiresAt&&(Po=T.authorizationExpiresAt),l?.(ho?{status:"authorized",...Nn===void 0?{}:{paymentId:Nn},sessionId:typeof Sr?.sessionId=="string"?Sr.sessionId:ae,...Po===void 0?{}:{authorizationExpiresAt:Po},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ee,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ee,checkoutMethod:s.isPaypal?"paypal":"card"})};if(Wt.ok){await go(Wt.status===204?null:await Wt.json().catch(()=>null));return}let an=await Wt.json().catch(()=>null);if(an?.type==="paypal_redirect_required"){let Sr=an.threeDSecureToken,ho=an.paymentMethodId||s.id||"";if(!Ae||!Sr){le("error"),qe("PayPal authorization required but no token provided.");return}try{let Nn=Dt?.getRawProvider();if(!Nn){qe("PayPal is not available.");return}let Po={return_url:window.location.href};ho&&(Po.payment_method=ho);let{error:da}=await Nn.confirmPayment({clientSecret:Sr,confirmParams:Po,redirect:"if_required"});if(da){le("error");let cl=da.message??"PayPal payment failed.";qe(cl),On("paypal",cl,{code:da.code})}}catch(Nn){le("error"),qe(Nn instanceof Error?Nn.message:"PayPal authorization failed.")}return}if(an?.type==="paypal_direct_required"){let Sr=an.orderId;if(!Sr){le("error"),qe("PayPal retry required but no order id provided.");return}let ho=yt.current?.attempts??0;if(ho>=2){le("error"),qe("PayPal payment could not be completed after multiple attempts."),On("paypal","paypal_direct_required retry limit exceeded");return}Fi(!1),Bi("loading"),Xe({orderId:Sr,attempts:ho+1}),le(null);return}if(Wt.headers.get(kd)===Rd){let Sr=await Ed(Ft,ae,Re);if(Sr!==void 0){await go(Sr);return}}(0,d.classifyPaymentRejection)(Wt.status,an)?Pt?.terminal({outcome:"payment_declined",...Tn,terminalReason:"provider_declined"}):It(),le("error");let ll=an?.message??"Payment failed. Please try again.";qe(ll),On(s.isPaypal?"paypal":"card",ll,{code:an?.code??an?.gatewayErrorCode,declineCode:an?.declineCode??an?.gatewayDeclineReason}),await new Promise(Sr=>setTimeout(Sr,400))}catch(Ft){Yl(Ft)||It(),le("error"),qe(Ft instanceof Error?Ft.message:"An unexpected error occurred"),await new Promise(Wt=>setTimeout(Wt,400))}finally{Ut(!1),le(null),q.current=!1}},[yr,e,t,he,Ye,ot,_e,et,Y,Ae,Dt,T,l,qe,On,_t,mt]),Xr=(0,o.useCallback)((s,D)=>{w?w(s):Js(s,D)},[w,Js]),aa=`${Kl}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(aa);if(!s)return;let D;try{D=JSON.parse(s)}catch{nr(aa);return}if(!D||typeof D.createdAt!="number"||Date.now()-D.createdAt<0||Date.now()-D.createdAt>Gl||typeof D.paymentMethodId!="string"||typeof D.providerIntentId!="string"||typeof D.paymentMethodType!="string"||D.sessionId!==e||!t||D.nonce!==t||!To.includes(D.paymentMethodType)){nr(aa);return}nr(aa),Xr({id:D.paymentMethodId,type:"card",threeDSecureActionResultTokenId:D.providerIntentId,gateway:"stripe",paymentMethodType:D.paymentMethodType},{...D.accountPatch?{accountPatch:D.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Xr,t,e,aa,To]);let Zs=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Zs.current)return;let[s,D,ae]=(0,d.readStripeRedirectParams)();if(!s||!D||Ba.current||!Ae)return;let Re=Ae.getRawProvider();if(!Re)return;let Q=It=>{let Ft=localStorage.getItem(It);if(!Ft)return null;try{return JSON.parse(Ft)}catch{return nr(It),null}},Ee=Q(jn)??Q(Ll),zt;if(Ee?.clientSecret){if(Ee.clientSecret!==D)return;zt={...Ee.accountPatch?{accountPatch:Ee.accountPatch}:{},...Ee.sessionId?{sessionId:Ee.sessionId}:{},...Ee.nonce?{nonce:Ee.nonce}:{}}}else if(Ee?.sessionId&&Ee.sessionId!==e)return;Zs.current=!0,nr(jn),nr(Ll),window.history.replaceState({},"",(0,d.stripeRedirectReturnUrl)());let un=Ee?.paymentMethodType??Ee?.tokenType??"card",Pt="card";(async()=>{if(ae==="failed"){let Yn="Payment was declined. Please try again.";qe(Yn),On(Pt,Yn);return}let{paymentIntent:It,error:Ft}=await Re.retrievePaymentIntent(D);if(Ft){let Yn=Ft.message??"Failed to retrieve payment status.";qe(Yn),On(Pt,Yn,{code:Ft.code});return}let Wt=It?.status,go=pa(Wt);if(!It||!go){let Yn=Wt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";qe(Yn),On(Pt,Yn,{code:Wt??"missing_payment_intent"});return}let an=typeof It.payment_method=="string"?It.payment_method:It.payment_method?.id;Xr({id:an??Ee?.paymentMethodId??Ee?.tokenId??It.id,type:"card",threeDSecureActionResultTokenId:It.id,gateway:Ee?.gateway??"stripe",paymentMethodType:un},zt)})()},[e,Xr,Ae,qe,On]);let Oi=(0,o.useCallback)(s=>{s.preventDefault()},[]);if(!(ye||Ae!==null))return(0,u.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ia=xe==="buttons",Jr=ge?.variables,Mc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Li=Jr?.colorBackground,xc=Li&&!Mc.has(Li)?Li:void 0,sa=A.cardInputBorder??(ia?"#e5e7eb":"#A4A4FF"),Qs=Jr?.colorDanger??"#dc2626",Jt=s=>Br[s]&&(cn[s]||Qt),za=ko&&(jr||Qt),dn=s=>s?Qs:sa,qa=(Lt.malformed||Lt.empty)&&($n||Qt),Ac=dn(qa),Ni=A.cardFormContainer?.backgroundColor??xc??(ia?"white":"#EDEDFF"),xo=A.cardInputBackground??Jr?.colorBackground??"white",Ui=Bo(De),el=Bo(de),Ao=A.nameInput,tl=A.cardInputFontSize??Vd(Ao?.fontSize)??Jr?.fontSizeBase??"16px",rl=typeof Ao?.fontFamily=="string"?Ao.fontFamily:Jr?.fontFamily??"Poppins, sans-serif",nl=(0,d.toCssWeight)(Ao?.fontWeight)??400,Fc=A.cardInputColor??(typeof Ao?.color=="string"?Ao.color:void 0)??Jr?.colorText??"#262833",Bc=A.cardInputPlaceholderColor??"#9ca3af",tr=Jr?.borderRadius??"8px",yo=Jr?.borderRadius??A.cardButton?.borderRadius??tr,fo=Jr?.colorPrimary??"#4A49FF",Dc=Jr?.colorPrimaryHover??(0,d.darkenHex)(fo,.12),zi=Jr?.colorText??"#262833",qi={fontSize:tl,fontFamily:rl,fontWeight:nl,color:Fc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},la={marginTop:"0.375rem",...qi,fontSize:"0.75rem",lineHeight:1.4,color:Qs},Oc={"--flopay-input-placeholder-color":Bc,"--flopay-input-font-size":tl,"--flopay-input-font-family":rl,"--flopay-input-font-weight":String(nl)},ca=A.cardFormContainer??{},ji=ca.padding??(ia?"0":"1rem"),Vi=ca.borderRadius??tr,Lc=tt&&Gr?(0,u.jsx)(co,{capture:tt,html:Gr.html,messageToken:Gr.messageToken,expectedOrigin:Gr.expectedOrigin,verificationRequired:Gr.verificationRequired,theme:Je,submitLabel:ee,onReady:()=>{if(!io&&!Ye||typeof document>"u")return;let s=()=>{let ae=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(ae){en.current=!0;try{ae.focus()}finally{en.current=!1}}};Bn.current||s()},onError:s=>{s&&Gr.verificationRequired&&ce.current==="idle"&&(Dn.current=!0),qe(s)},onValidation:s=>{let D=ce.current;(D==="idle"||D==="validation-window")&&(qe(s),s&&ce.current==="validation-window"&&(W.current&&(clearTimeout(W.current),W.current=null),ce.current="idle",le(null)))}},Dr):(0,u.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"}),ol=(0,u.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&Kn()},style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji,...Oc,display:"flex",flexDirection:"column"},children:[(0,u.jsx)("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${rt.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),ia&&yo&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:fe?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:Re,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...F.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Oo,{content:Oe})]}),el?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...F.title},children:(0,d.jsx)(ua,{content:ge})})]}),!ia&&!el&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zi,order:fe?-3:0,...F.title},children:(0,d.jsx)(ua,{content:ge})}),fe&&ee&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:ee}),fe&&io&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:xo,border:`1px solid ${an(za)}`,borderRadius:or,padding:"10px"},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:jt,onChange:s=>{Ut("email"),Mr.current=s.target.value,Jt(s.target.value)},onPointerDown:()=>Ut("email"),onKeyDown:()=>Ut("email"),onBlur:()=>{Jr("email")&&ao(!0),ko||Ti()},disabled:ae,required:!0,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...qi}})}),za&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:la,children:Ri.empty?"Email address is required":"Enter a valid email address"})]}),qe&&(0,d.jsx)("div",{style:{order:fe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Gt,O=(Y=!1)=>({backgroundColor:xo,border:`1px solid ${an(Y)}`,borderRadius:or,marginTop:"0.5rem",padding:"10px"}),ie=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...qi}),Ie=(0,c.getStateOptions)(s);return(0,d.jsxs)(d.Fragment,{children:[(0,c.isAVSFieldVisible)(qe.address_line_1,s)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:O(Zt("line1")),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Qt,onChange:Y=>{Ut("line1"),cr.current.addressLine1=!0,fr.current=Y.target.value,zr(Y.target.value)},onPointerDown:()=>Ut("line1"),onKeyDown:()=>Ut("line1"),onBlur:()=>Zr("line1"),disabled:ae,required:!0,"aria-invalid":Zt("line1")||void 0,"aria-describedby":Zt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ie()})}),Zt("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:la,children:"Street address is required"})]}),(0,c.isAVSFieldVisible)(qe.address_line_2,s)&&(0,d.jsx)("div",{style:O(),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Wt,onChange:Y=>{cr.current.addressLine2=!0,Tr.current=Y.target.value,Vn(Y.target.value)},disabled:ae,"data-testid":"flopay-address-line2",style:ie()})}),((0,c.isAVSFieldVisible)(qe.city,s)||(0,c.isAVSFieldVisible)(qe.state,s))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(qe.city,s)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${an(Zt("city"))}`,borderRight:`1px solid ${an(Zt("city"))}`,borderBottom:`1px solid ${an(Zt("city"))}`,borderLeft:`1px solid ${an(Zt("city"))}`,padding:"10px",borderTopLeftRadius:or,borderBottomLeftRadius:or,...(0,c.isAVSFieldVisible)(qe.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:or}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Xt,onChange:Y=>{Ut("city"),cr.current.city=!0,Ot.current=Y.target.value,Gr(Y.target.value)},onPointerDown:()=>Ut("city"),onKeyDown:()=>Ut("city"),onBlur:()=>Zr("city"),disabled:ae,required:!0,"aria-invalid":Zt("city")||void 0,"aria-describedby":Zt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ie()})}),(0,c.isAVSFieldVisible)(qe.state,s)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${an(Zt("state"))}`,borderRight:`1px solid ${an(Zt("state"))}`,borderBottom:`1px solid ${an(Zt("state"))}`,borderLeft:`1px solid ${an(Zt("state"))}`,padding:"10px",borderTopRightRadius:or,borderBottomRightRadius:or,...(0,c.isAVSFieldVisible)(qe.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${an(Zt("state")||Zt("city"))}`}:{borderRadius:or}},children:Ie?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:it,onChange:Y=>{Ut("state"),cr.current.state=!0,Lt.current=Y.target.value,Mt(Y.target.value)},onPointerDown:()=>Ut("state"),onKeyDown:()=>Ut("state"),onBlur:()=>Zr("state"),disabled:ae,autoComplete:"billing address-level1",required:!0,"aria-invalid":Zt("state")||void 0,"aria-describedby":Zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...ie(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,c.getStateLabel)(s)}),Ie.map(Y=>(0,d.jsx)("option",{value:Y.code,children:Y.name},Y.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,c.getStateLabel)(s),autoComplete:"billing address-level1",value:it,onChange:Y=>{Ut("state"),cr.current.state=!0,Lt.current=Y.target.value,Mt(Y.target.value)},onPointerDown:()=>Ut("state"),onKeyDown:()=>Ut("state"),onBlur:()=>Zr("state"),disabled:ae,required:!0,"aria-invalid":Zt("state")||void 0,"aria-describedby":Zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ie()})})]}),Zt("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:la,children:"City is required"}),Zt("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:la,children:[(0,c.getStateLabel)(s)," is required"]}),((0,c.isAVSFieldVisible)(qe.country,s)||(0,c.isAVSFieldVisible)(qe.postal_code,s))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:le==="column"?"column":"row",gap:le==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(qe.country,s)&&(0,d.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:xo,borderTop:`1px solid ${sa}`,borderRight:`1px solid ${sa}`,borderBottom:`1px solid ${sa}`,borderLeft:`1px solid ${sa}`,padding:"10px",...le==="row"&&(0,c.isAVSFieldVisible)(qe.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:or,borderBottomLeftRadius:or,borderRight:"none"}:{borderRadius:or}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Gt,onChange:Y=>{cr.current.country=!0,wr.current=Y.target.value,Yt(Y.target.value),ut?.(Y.target.value),Lt.current="",Mt("")},disabled:ae,autoComplete:"billing country","data-testid":"flopay-country",style:{...ie(),cursor:"pointer"},children:[Gt===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(Y=>(0,d.jsxs)("option",{value:Y.code,children:[Y.flag," ",Y.name]},Y.code))]})}),(0,c.isAVSFieldVisible)(qe.postal_code,s)&&(0,d.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:xo,border:`1px solid ${Ac}`,padding:"10px",...le==="row"&&(0,c.isAVSFieldVisible)(qe.country,s)?{borderRadius:"0",borderTopRightRadius:or,borderBottomRightRadius:or}:{borderRadius:or}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,c.getPostalCodeLabel)(Gt),autoComplete:"billing postal-code",value:Ur,onChange:Y=>{Ut("zip"),cr.current.zip=!0,Sr.current=Y.target.value,_r(Y.target.value),Le?.(Y.target.value)},onPointerDown:()=>Ut("zip"),onKeyDown:()=>Ut("zip"),onBlur:()=>{Jr("zip")&&xn(!0)},disabled:ae,required:Yr.required,"aria-invalid":qa||void 0,"aria-describedby":qa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ie()})})]}),qa&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:la,children:Yr.empty?`${(0,c.getPostalCodeLabel)(s)} is required`:zd(s)})]})})()}),fe&&Lc,Rt&&(0,d.jsx)(Wo,{margin:"0.75rem 0",styleOverride:F.errorBanner,children:Rt})]}),ja={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},al=s=>z?!ye||!Dn?(0,d.jsx)("pre",{"data-testid":s,style:ja,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":s,style:ja,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ye}`,` directPaypalConfigured=${Dn}`,` inAppBrowserDetected=${String(La)}`,` shouldRenderDirectPayPal=${ta}`,` shouldRenderStripePayPal=${na}`,` hasPaypalStripeInstance=${!!Rs}`].join(`
|
|
39
|
-
`)}):null,il=s=>z?!b||!
|
|
40
|
-
`)}):null,sl=bt==="apm-expanding"||bt==="apm-form"||bt==="apm-collapsing",Fo;bt==="apm-expanding"?Fo=ql:bt==="apm-collapsing"&&(Fo=jl);let Va=dr?Jl(Ai,dr,q):null;if(Fe==="buttons"){let s=bt==="buttons"||bt==="expanding"||bt==="apm-expanding",O=bt==="expanding"||bt==="card"||bt==="collapsing",ie=Ye===void 0?{boxSizing:"border-box",height:Yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ie;bt==="expanding"||bt==="apm-expanding"?Ie=Od:(bt==="collapsing"||bt==="apm-collapsing")&&(Ie=Dd);let Y;return bt==="expanding"?Y=ql:bt==="collapsing"&&(Y=jl),(0,d.jsxs)("form",{onSubmit:Oi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Xo,{}),Ne&&(0,d.jsx)(Hr,{status:Ne,errorMessage:Rt,authorized:xr}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Ie?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Ie?Nd:{},...Ie?{animation:Ie,pointerEvents:"none"}:{}},children:[al("flopay-direct-paypal-gate-debug"),il("flopay-stripe-gate-debug"),ta&&wt&&(0,d.jsxs)(d.Fragment,{children:[Ee&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(fa.Provider,{value:A,children:(0,d.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:oe,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,clientId:wt.clientId,environment:wt.environment,currency:lr.toUpperCase(),isSubscription:Se,providerObjectType:ue,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Wr,onComplete:l,onErrorChange:je,onDecline:p,onCancel:P,onTechnicalFailure:Io,onButtonClick:G,runBeforeButtonClick:Sn,isProcessing:ae,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:J,existingOrderId:Ee?.orderId,debug:z},Ee?.orderId??"fresh")})]}),na&&(0,d.jsx)(ar.Elements,{stripe:ra,options:_s,children:(0,d.jsx)(Wl,{sessionId:e,nonce:t,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,billingApiUrl:oe,onTokenizedBody:Wr,onErrorChange:je,isProcessing:ae,onButtonClick:G,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:Sn,onLoadStateChange:Ls,placeholderBorderRadius:mo,popupCapabilityOwner:A,externalTelemetryContext:Hs,presentationMode:_o})}),Mo?(0,d.jsx)(ar.Elements,{stripe:en,options:Is,children:(0,d.jsx)($l,{sessionId:e,nonce:t,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,billingApiUrl:oe,intentKind:at>0?"payment":"setup",expressMethods:To,onTokenizedBody:Wr,onErrorChange:je,onButtonClick:G,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:Sn,onLoadStateChange:Us,placeholderBorderRadius:mo,popupCapabilityOwner:A,externalTelemetryContext:g})}):null,!Mo&&Ws?(0,d.jsx)("div",{style:{height:Yo,borderRadius:mo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,oa&&(0,d.jsx)(Hl,{sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:st,billingApiUrl:oe,paymentElementMethods:Oa,stripeInstance:en,paymentElementBaseOptions:Ai,futureUseSession:q,onTokenizedBody:Wr,onErrorChange:je,onButtonClick:G,onDecline:p,runBeforeButtonClick:Sn,onLoadStateChange:qs,isProcessing:ae,submitButtonColor:fo,submitButtonBorderRadius:or,submitButtonStyle:F.submitButton,onExpandApm:It,expandedApmMethod:dr,themeId:dt,buttonAppearance:{backgroundColor:F.cardButton?.backgroundColor,borderColor:F.cardInputBorder,textColor:F.cardButton?.color,borderRadius:mo}}),fe&&(0,d.jsx)("button",{type:"button",onClick:async()=>{ae||!(await Sn("card")).proceed||(G?.("card"),re())},disabled:ae,style:{width:"100%",...ie,...F.cardButton,...ps({themeBundle:_t,resolvedPrimaryColor:fo,resolvedBorderRadius:or,submitButtonStyle:F.submitButton,explicitPrimaryColor:$r?.colorPrimary}),fontSize:F.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ae?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ae?.6:1},onMouseEnter:_e=>{!ae&&(_t||$r?.colorPrimary)&&(_e.currentTarget.style.backgroundColor=Dc)},onMouseLeave:_e=>{(_t||$r?.colorPrimary)&&(_e.currentTarget.style.backgroundColor=fo)},onMouseDown:_e=>{_e.currentTarget.style.transform="scale(0.985)"},onMouseUp:_e=>{_e.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Do,{content:Ye})}),Rt&&bt==="buttons"&&(0,d.jsx)(Wo,{margin:"0.25rem 0",styleOverride:F.errorBanner,children:Rt})]}),fe&&O&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...bt==="collapsing"?{pointerEvents:"none"}:{}},children:ol}),b&&sl&&dr&&Va&&en&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Fo?{animation:Fo}:{},...bt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:nr,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...F.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Oo,{content:Oe})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:zi,paddingRight:80,...F.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(dr)}`})]}),(0,d.jsx)(ar.Elements,{stripe:en,options:Va,children:(0,d.jsx)(cs,{method:dr,sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:st,billingApiUrl:oe,onTokenizedBody:Wr,onErrorChange:je,onDecline:p,onCancel:nr,runBeforeButtonClick:Sn,onButtonClick:G,isProcessing:ae,submitButtonColor:fo,submitButtonBorderRadius:or,submitButtonStyle:F.submitButton,errorText:Rt})},dr)]})})]})]})}return sl&&dr&&Va&&en&&b?(0,d.jsxs)("form",{onSubmit:Oi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Xo,{}),Ne&&(0,d.jsx)(Hr,{status:Ne,errorMessage:Rt,authorized:xr}),(0,d.jsx)("div",{style:{...Fo?{animation:Fo}:{},...bt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:nr,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...F.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Oo,{content:Oe})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:zi,paddingRight:80,...F.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(dr)}`})]}),(0,d.jsx)(ar.Elements,{stripe:en,options:Va,children:(0,d.jsx)(cs,{method:dr,sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:st,billingApiUrl:oe,onTokenizedBody:Wr,onErrorChange:je,onDecline:p,onCancel:nr,runBeforeButtonClick:Sn,onButtonClick:G,isProcessing:ae,submitButtonColor:fo,submitButtonBorderRadius:or,submitButtonStyle:F.submitButton,errorText:Rt})},dr)]})})]}):(0,d.jsxs)("form",{onSubmit:Oi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Xo,{}),Ne&&(0,d.jsx)(Hr,{status:Ne,errorMessage:Rt,authorized:xr}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[al("flopay-direct-paypal-gate-debug-default"),il("flopay-stripe-gate-debug-default"),ta&&wt&&(0,d.jsxs)(d.Fragment,{children:[Ee&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(fa.Provider,{value:A,children:(0,d.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:oe,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,clientId:wt.clientId,environment:wt.environment,currency:lr.toUpperCase(),isSubscription:Se,providerObjectType:ue,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Wr,onComplete:l,onErrorChange:je,onDecline:p,onCancel:P,onTechnicalFailure:Io,onButtonClick:G,runBeforeButtonClick:Sn,isProcessing:ae,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:J,existingOrderId:Ee?.orderId,debug:z},Ee?.orderId??"fresh")})]}),na&&(0,d.jsx)(ar.Elements,{stripe:ra,options:_s,children:(0,d.jsx)(Wl,{sessionId:e,nonce:t,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,billingApiUrl:oe,onTokenizedBody:Wr,onErrorChange:je,isProcessing:ae,onButtonClick:G,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:Sn,onLoadStateChange:Ls,placeholderBorderRadius:mo,popupCapabilityOwner:A,externalTelemetryContext:Hs,presentationMode:_o})}),Mo&&(0,d.jsx)(ar.Elements,{stripe:en,options:Is,children:(0,d.jsx)($l,{sessionId:e,nonce:t,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,billingApiUrl:oe,intentKind:at>0?"payment":"setup",expressMethods:To,onTokenizedBody:Wr,onErrorChange:je,onButtonClick:G,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:Sn,onLoadStateChange:Us,placeholderBorderRadius:mo,popupCapabilityOwner:A,externalTelemetryContext:g})}),oa&&(0,d.jsx)(Hl,{sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:oe,paymentElementMethods:Oa,stripeInstance:en,paymentElementBaseOptions:Ai,futureUseSession:q,onTokenizedBody:Wr,onErrorChange:je,onButtonClick:G,onDecline:p,runBeforeButtonClick:Sn,onLoadStateChange:qs,isProcessing:ae,submitButtonColor:fo,submitButtonBorderRadius:or,submitButtonStyle:F.submitButton,themeId:dt,onExpandApm:It,expandedApmMethod:dr,buttonAppearance:{backgroundColor:F.cardButton?.backgroundColor,borderColor:F.cardInputBorder,textColor:F.cardButton?.color,borderRadius:mo}})]}),fe&&(_c||Ic||Tc)&&(0,d.jsx)(ci,{label:"or pay with card"}),fe&&ol]})}var B=require("react/jsx-runtime"),Jo=44,vs="flopay_checkout_saved_payment_resume",Pi=new Map,gi=new Map;function Zl(e,t){t.settled&&t.consumers===0&&Pi.get(e)===t&&Pi.delete(e)}function Kd(e,t,r){let n=gi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),i={attempt:a,sdkGeneratedIdempotencyKey:t};gi.set(e,i);let l=()=>{gi.get(e)===i&&gi.delete(e)};return a.then(l,l),a}function Ta(e){return new Promise(t=>setTimeout(t,e))}function hi(e,t,r){let n=Ja({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:$e.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Ma(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ms(e,t,r,n,a,i){let l=hi(e,t,r);l.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Ma(l)}function Ql(e,t,r,n){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function ec(e,t,r,n,a){let i=(0,$e.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:i.statusClass}),t instanceof $e.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof $e.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...i,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function fs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,$e.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var Gd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Yd(e){return new ro.FloPay(Gd,{publishableKey:"provider_unavailable",...e})}async function gs(e,t){let{publishableKey:r,paypalPublishableKey:n}=Qi(e);return{...await es({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Cs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Xd(){if(!Cs())return null;try{let e=window.sessionStorage.getItem(vs);return e?JSON.parse(e):null}catch{return null}}function tc(e){if(Cs())try{window.sessionStorage.setItem(vs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function hs(){if(Cs())try{window.sessionStorage.removeItem(vs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Jd(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function rc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Ps(e,t){return(0,$e.resolveCheckoutLogLayout)(!!e,t)}function Zd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function nc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Qd(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function vi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:i,locale:l,loading:u,error:p,onComplete:P,onError:w,onInstrument:S,onDecline:E,onCancel:K,onCountryChange:I,onZipChange:X,showPayPal:M=!0,showStripe:f=!0,walletPresentation:v="auto",enabledPaymentMethods:ye,showApplePay:b=!0,showGooglePay:Te=!0,debug:T=!1,layout:se,theme:me,buttonsTheme:pe,buttonsStyles:Fe,cardButtonContent:dt,cardBackButtonContent:He,cardTitleContent:D,showSecurityFooter:St,onButtonClick:Ye,onBeforeButtonClick:Oe,enableAVS:ge,cardFieldOrder:Q,cardPreFormSlot:G,avsLayout:Be,submitLabel:ze,className:Xe,initialErrorMessage:ne=null,initialPayPalOrderId:ee,children:le,checkoutMode:V,confirmLabel:Ve,renderConfirmButton:Ae,onSessionCompleted:he}){let N=(0,$e.resolveBillingApiUrl)(n),Ce=(0,C.useMemo)(()=>(0,$e.resolveTheme)(me),[me]),ut=i??Ce?.appearance,Le=r?"embedded_checkout":"standard_checkout",ot=Ps(le,se),[Me,tt]=(0,C.useState)(null),[at,lr]=(0,C.useState)(null),Bt=(0,C.useRef)(null),wt=(0,C.useRef)(null),Se=(0,C.useRef)(0),[x,ht]=(0,C.useState)(null),pt=(0,C.useRef)(null),[z,we]=(0,C.useState)(null),Dt=(0,C.useMemo)(()=>r?(0,ft.serializeCreateParams)(r):"",[r]),Ke=r?`create:${Dt}`:`session:${e??""}`,kt=nc(z),k=(0,C.useRef)(new Set),A=(0,C.useRef)(Ke),We=(0,C.useRef)(Ke);Co(()=>{We.current=Ke,A.current!==Ke&&(A.current=Ke,k.current.clear())},[Ke]);let ke=(0,C.useCallback)(L=>{if(We.current===Ke){if(Xi.FLO_INSTRUMENT_ONCE_NAMES.has(L.name)){if(k.current.has(L.name))return;k.current.add(L.name)}(0,Qe.invokeMerchantCallback)(()=>S?.(L))}},[Ke,S]),ct=Vo(ke,Ke),g=(0,C.useRef)(!1),J=(0,C.useCallback)(L=>{if(g.current)return;let U=L.gateway||!kt?L:{...L,gateway:kt};ke(U)},[ke,kt]);(0,C.useEffect)(()=>{ct({class:"lifecycle",name:"checkout.mount"})},[ct]);let[q,ue]=(0,C.useState)(e??""),m=e??q,Z=r?"":m,[xe,rt]=(0,C.useState)(!0),[oe,$]=(0,C.useState)(null),[Vt,Ir]=(0,C.useState)(0),[br,Gt]=(0,C.useState)("full"),[Yt,Ur]=(0,C.useState)(!1),[_r,Qt]=(0,C.useState)(ne),[zr,Wt]=(0,C.useState)(null),[Vn,Xt]=(0,C.useState)(null),[Gr,it]=(0,C.useState)(!1),[Mt,jt]=(0,C.useState)(void 0),[Jt,Dr]=(0,C.useState)(""),[qr,Sr]=(0,C.useState)(!1),[wr,fr]=(0,C.useState)(!1),[Tr,Ot]=(0,C.useState)(!1),Lt=(0,C.useRef)(null),Mr=(0,C.useRef)(0),cr=(0,C.useRef)(void 0),[qe,fn]=(0,C.useState)("loading"),[xr,Wn]=(0,C.useState)(0),er=(0,C.useRef)(!1),Ar=(0,C.useRef)(!1),Tn=(0,C.useRef)(!1),gn=(0,C.useRef)(null),$t=(0,C.useRef)(null),fe=(0,C.useMemo)(()=>({checkoutMode:V??br,layout:Zd(le,se)}),[V,le,br,se]),te=(0,C.useRef)(P);te.current=P;let Ct=(0,C.useRef)(w);Ct.current=w;let _=(0,C.useRef)(E);_.current=E;let xt=(0,C.useCallback)(L=>ei(gn,async U=>{try{return await L(U)}catch(re){throw U.aborted?$o(re):re}}),[]);(0,C.useEffect)(()=>()=>{gn.current?.abort(),gn.current=null},[]);let At=(0,C.useCallback)((L,U)=>{Bt.current=L,lr(L),pt.current=U,ht(U)},[]),Et=(0,C.useCallback)(()=>{let L=wt.current;L&&(wt.current=null,L.destroy())},[]);(0,C.useEffect)(()=>{Pr(at)?.setCheckoutContext(fe),x&&x!==at&&Pr(x)?.setCheckoutContext(fe)},[at,x,fe]);let tr=(0,C.useRef)(he);tr.current=he;let yt=(0,C.useCallback)(L=>{fn(L),!(L!=="exhausted"||Tn.current)&&(Tn.current=!0,Ct.current?.(new $e.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),oo=(0,C.useCallback)(()=>{fn("retrying"),Wn(L=>L+1)},[]);(0,C.useEffect)(()=>{fn("loading"),Wn(0),Tn.current=!1},[m]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:$e.SDK_VERSION,checkout_type:Le,checkout_layout:ot,billing_api_url:N})},[ot,Le,N]);let Nt=(0,C.useMemo)(()=>r?(0,ft.serializeCreateParams)(r,!0):"",[r]),Yr=(0,C.useMemo)(()=>Jt===Nt?Mt:void 0,[Mt,Jt,Nt]),Mn=(0,C.useMemo)(()=>r?Hi(r,Yr):void 0,[r,Yr]),nn=V??Mn?.checkoutMode??"full",rr=(0,C.useMemo)(()=>Mn?{...Mn,checkoutMode:nn}:void 0,[Mn,nn]);(0,C.useEffect)(()=>{jt(void 0),Dr(Nt),cr.current=void 0,Lt.current=null,Ot(!1)},[Nt]),(0,C.useEffect)(()=>{Qt(ne)},[ne]);let hn=(0,C.useCallback)((L,U,re)=>{(0,Qe.invokeMerchantCallback)(()=>{_.current?.(hr(L,U,re))})},[]),$n=(0,C.useCallback)(async(L,U)=>{Qt(null),Xt(null),it(!1),Wt("processing");let re=U?.sessionId??L.id,Re=L.clientSecret||t,It=nc(L),nr=Bt.current??pt.current,Ne=Pr(nr),ce=nr?null:hi(N,a,fe),j={log:Ue=>{Ne?Ne.log(Ue):ce?.log(Ue)},error:Ue=>{Ne?Ne.error(Ue):ce?.error(Ue)},terminal:Ue=>{Ne?Ne.terminal(Ue):ce?.terminal(Ue)},performance:Ue=>{Ne?Ne.performance(Ue):ce?.performance(Ue)},now:()=>Ne?.now()??ce?.now()??0,elapsed:Ue=>Ne?.elapsed(Ue)??Math.max(0,(ce?.now()??Ue)-Ue)},W=j.now(),de=!!(U?.initialAutoProcessingError||U?.initialAutoProcessingPending),h=!1,y,H=()=>{h||(h=!0,de=!0,y=j.now(),j.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),j.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ee=!1,Je=()=>{Ee||(Ee=!0,j.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),j.performance({stage:"processing",durationMs:j.elapsed(W),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),y!==void 0&&j.performance({stage:"recovery",durationMs:j.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}))};j.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),g.current=!0;try{j.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{g.current=!1}ct({class:"lifecycle",name:"payment.processing.started",provider:It}),de&&H();let mt;try{let Ue=xl(U?.initialAutoProcessingError),De=U?.initialAutoProcessingError?.type==="3ds_required"&&!U.initialAutoProcessingError.threeDSecureToken&&U.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:U.initialAutoProcessingError.nextActionRedirectUrl}:null,st,Rt=_t=>(H(),xt(F=>Ho(_t,{billingApiUrl:N,sessionId:re,nonce:Re,session:L,signal:F})));if(De)st=await Rt(De);else if(Ue)H(),Ue.type==="paypal_redirect_required"&&$t.current?.publishableKey&&tc({sessionId:re,publishableKey:$t.current.publishableKey,paypalPublishableKey:$t.current.paypalPublishableKey}),st=await xt(_t=>ri(Ue,{flopay:Bt.current,paypalFlopay:pt.current,attempt3DS:U?.attempt3DS,billingApiUrl:N,sessionId:re,session:L,telemetry:!1,signal:_t})),Ue.type==="paypal_redirect_required"&&hs();else if(U?.initialAutoProcessingPending){let _t=U.initialAutoProcessingPending,F=new ro.PaymentAPI(N,{telemetry:!1}),Pe=await xt(ae=>F.waitForCheckoutSessionCompletion(_t.sessionId,{initialDelayMs:_t.retryAfterMs,nonce:Re,statusUrl:_t.statusUrl,signal:ae})),Ze=lo(Pe,L),nt=Pe.autoProcessingError?.type==="3ds_required"&&Pe.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Pe.autoProcessingError.nextActionRedirectUrl}:null;if(nt)st=await Rt(nt);else{if(!Jn(Ze))throw No(Ze);st=Xn(Ze,re)}}else{if(U?.initialAutoProcessingError)throw Un(U.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:U.initialAutoProcessingError.checkoutMethod});if(U?.fromCreateSession)return U?.fallbackToFull&&(Gt("full"),rc("full")),!1;{let _t=await Ko({billingApiUrl:N,sessionId:re,session:L,nonce:Re,telemetry:!1});_t.type==="success"?st=_t.result:_t.type==="next_action_required"?st=await Rt(_t):(H(),_t.type==="paypal_redirect_required"&&$t.current?.publishableKey&&tc({sessionId:re,publishableKey:$t.current.publishableKey,paypalPublishableKey:$t.current.paypalPublishableKey}),st=await xt(F=>ri(_t,{flopay:Bt.current,paypalFlopay:pt.current,attempt3DS:U?.attempt3DS,billingApiUrl:N,sessionId:re,session:L,telemetry:!1,signal:F})),_t.type==="paypal_redirect_required"&&hs())}}re&&(0,En.markSessionRecentlyCompleted)(re),Je(),de&&(j.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),j.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),j.terminal({outcome:st.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),it(st.status==="authorized"),Wt("success"),await Ta(600),mt=()=>te.current?.(st)}catch(Ue){let De=so(Sa(Ue),re);if(De.code==="three_ds_aborted")return!1;let st=De.checkoutMethod??ba;Qt(De.message),Xt(De.message),it(!1),U?.fallbackToFull&&(j.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Gt("full"),rc("full")),Je();let Rt=De.statusCode===void 0?void 0:(0,$e.telemetryStatusClass)(De.statusCode,"unknown"),_t=Rt==="4xx"?{requestCategory:"process_payment",statusClass:Rt}:{},F=Rt===void 0||Rt==="4xx";if(F&&(De.telemetryOutcome==="payment_declined"||!!(De.declineCode||De.code?.toLowerCase().includes("declin"))))j.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",..._t});else if(F&&(De.telemetryOutcome==="validation_rejected"||De.type==="validation_error"))j.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",..._t});else{let nt=(0,$e.classifyTelemetryFailure)(Ue,de?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ae=De.telemetryRequestCategory??"process_payment";g.current=!0;try{j.error({...nt,...De.telemetryFailureCategory?{failureCategory:De.telemetryFailureCategory}:{},stage:de?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:ae})}finally{g.current=!1}ct({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:ae,provider:It})}return(0,Qe.invokeMerchantCallback)(()=>Ct.current?.(De)),hn(st,De,{code:De.code,declineCode:De.declineCode}),Wt("error"),await Promise.allSettled([Ta(400),U?.ensureProvidersReady?U.ensureProvidersReady():Promise.resolve()]),de&&(j.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),j.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Je(),ce&&Ma(ce),Wt(null),Xt(null)}return(0,Qe.invokeMerchantCallback)(mt),!0},[hn,ct,t,N,xt,a,fe]);(0,C.useEffect)(()=>{if(typeof window>"u"||Ar.current)return;let L=new URLSearchParams(window.location.search),U=L.get("payment_intent_client_secret");if(!U)return;let re=Xd();re&&(Ar.current=!0,(async()=>{let Re,It=0;Qt(null),Xt(null),Wt("processing"),Ur(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new $e.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:nr,paypalFlopay:Ne}=await es({publishableKey:re.publishableKey,paypalPublishableKey:re.paypalPublishableKey,billingApiUrl:N,locale:l,telemetry:a});Re=Pr(Ne??nr),Re?.setCheckoutContext(fe),It=Re?.now()??0,Re?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Re?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let ce=(Ne??nr)?.getRawProvider();if(!ce)throw Object.assign(new $e.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:j,error:W}=await ce.retrievePaymentIntent(U);if(W)throw Object.assign(new $e.FloPayError(W.message??"Failed to retrieve PayPal payment status.","api_error",{code:W.code}),{checkoutMethod:"paypal"});let de=hl(j?.status);if(!j||de==="failed")throw Object.assign(new $e.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let h=typeof j.payment_method=="string"?j.payment_method:j.payment_method?.id,y=de;if(re.sessionId){let Je=(await new ro.PaymentAPI(N,{telemetry:!1}).getUnifiedCheckoutSession(re.sessionId)).data.session;if(Je&&Je.status!=="complete"){let mt=await Ko({billingApiUrl:N,sessionId:re.sessionId,session:Je,telemetry:!1,tokenizedData:{id:h??j.id,type:"card",threeDSecureActionResultTokenId:j.id,isPaypal:!0}});if(mt.type!=="success")throw Object.assign(new $e.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});y=mt.result.status}}re.sessionId&&(0,En.markSessionRecentlyCompleted)(re.sessionId),Re?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Re?.performance({stage:"redirect_resume",durationMs:Re.elapsed(It),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Re?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Wt("success"),await Ta(600),(0,Qe.invokeMerchantCallback)(()=>te.current?.({status:y,paymentIntentId:j.id,paymentMethodId:h,checkoutMethod:"paypal"}))}catch(nr){let Ne=so(Sa(nr),re.sessionId),ce=Ne.checkoutMethod??"paypal",j=!!(Ne.declineCode||Ne.code?.toLowerCase().includes("declin"));if(Re)Re.performance({stage:"redirect_resume",durationMs:Re.elapsed(It),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),j?Re.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Re.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(j){let W=hi(N,a,fe);W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ma(W)}else ms(N,a,fe,"REDIRECT_RESUME_FAILED","redirect_resume");Qt(Ne.message),Xt(Ne.message),(0,Qe.invokeMerchantCallback)(()=>Ct.current?.(Ne)),hn(ce,Ne,{code:Ne.code,declineCode:Ne.declineCode}),Wt("error"),await Ta(400)}finally{hs(),Jd(),Wt(null),Xt(null),Ur(!1)}})())},[hn,l,N,a,fe]);let xn=(0,C.useRef)(null),Or=(0,C.useMemo)(()=>rr?(0,ft.serializeCreateParams)(rr):"",[rr]),ao=(0,C.useRef)(rr);ao.current=rr,(0,C.useEffect)(()=>{ue(e??"")},[e]),(0,C.useEffect)(()=>{er.current=!1,Qt(ne),Xt(null),it(!1),Wt(null)},[Or,ne,e]);async function on(L,U,re){let Re=hi(N,a,fe),It=new ro.PaymentAPI(N,{telemetry:!1}),nr=!1;try{let Ne=L.idempotencyKey===void 0?void 0:(0,$e.resolveIdempotencyKey)(L.idempotencyKey),ce=(0,ft.readCachedInlineSession)(U,re),j=(0,ft.readCachedInlineIdempotencyKey)(U,re);ce?.canonicalIdentity===re&&j&&j.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(U,re,j.idempotencyKey),j={...j,canonicalIdentity:re});let W=Ne??(j?.canonicalIdentity===re?j.idempotencyKey:void 0),de,h=!1;Re.log({name:ce?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let y=ce?.sid??null,H=null,Ee,Je,mt=!1;if(y)try{H=await It.getUnifiedCheckoutSession(y,ce?.nonce),ce&&ce.canonicalIdentity===void 0&&((0,ft.legacyCachedSessionMatchesDraft)(H.data.session,L)?((0,ft.persistCachedInlineSession)(U,re,y,ce.nonce??H.data.session?.clientSecret),j&&j.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(U,re,j.idempotencyKey),W??(W=j.idempotencyKey))):((0,ft.clearCachedInlineCheckout)(U,re),j=null,W=Ne,y=null,H=null));let De=H?.data.session?.status,st=H?.data.session,Rt=st?.clientSecret||ce?.nonce;if(y&&st?.buyerIdentified===!1&&Rt&&(Je=Lo(It,y,Rt,L.account)),y&&H&&De==="complete"){if((0,En.wasSessionRecentlyCompleted)(y))return{sid:y,result:H};(0,ft.clearCachedInlineCheckout)(U,re),y=null,H=null,h=!0}}catch{Re.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ce?.canonicalIdentity===void 0?((0,ft.clearCachedInlineCheckout)(U,re),W=Ne):(0,ft.clearCachedInlineSession)(U,re),y=null}if(!y){!Ne&&(h||!W)&&(W=(0,$e.resolveIdempotencyKey)(),de=W),W&&(0,ft.persistCachedInlineIdempotencyKey)(U,re,W);let De=Re.now(),st=0;Re.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Rt={...L,idempotencyKey:W,avsCheck:!!ge,avsConfig:typeof ge=="object"?ge:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ps(le,se)};Object.defineProperty(Rt,ro.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Pe=>{st=Math.max(st,Pe)}}});let _t=()=>{Ql(Re,"session_create",De,st)},F=Pe=>{ec(Re,Pe,"session_create",De,st)&&ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,$e.isDetachedSessionEligible)(Rt)){let Pe=await It.createDetachedSession(Rt);Pe.claimed.catch(()=>{}),H=Pe.shell,y=Pe.sessionId,Je=Pe.claim;let Ze=Re.now();Re.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Ee=Pe.claimed.then(nt=>{let ae=nt.data.session?.id??Pe.sessionId;return ae&&(0,ft.persistCachedInlineSession)(U,re,ae,nt.data.session?.clientSecret??Pe.nonce),Ql(Re,"session_claim",Ze),_t(),nt},nt=>{throw(0,ft.clearCachedInlineSession)(U,re),ec(Re,nt,"session_claim",Ze,0)&&ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),nt}).finally(()=>Ma(Re)),Ee.catch(()=>{}),nr=!0,Re.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Re.performance({stage:"session_shell",durationMs:Re.now()-De,durationMode:"machine",requestCategory:"session_create",attempt:st,statusClass:"2xx",paymentMethodCategory:"card"})}else H=await It.createAndFetchSession(Rt),_t()}catch(Pe){throw F(Pe),Pe}y=H.data.session?.id??y??"",y&&!Ee&&(0,ft.persistCachedInlineSession)(U,re,y,H.data.session?.clientSecret)}let Ue=H?.data.session;return!Je&&y&&Ue?.buyerIdentified===!1&&Ue.clientSecret&&(Je=Lo(It,y,Ue.clientSecret,L.account)),{sid:y??"",result:H,sdkGeneratedIdempotencyKey:de,...Ee?{claimed:Ee}:{},...Je?{claim:Je}:{},...mt?{claimRequiresIdentity:!0}:{}}}finally{nr||Ma(Re)}}let Hn=(0,C.useRef)(on);Co(()=>{Hn.current=on},[on]);let Xr=(0,C.useCallback)(async(L,U)=>{let re=ao.current;if(!re)throw new $e.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Re=Hi(re,L),It=(0,ft.serializeCreateParams)(Re),nr=(0,ft.hashCreateParams)(Re),Ne=Pi.get(It);if(!Ne){let W={canonicalIdentity:It,promise:Hn.current(Re,nr,It),consumers:0,settled:!1};Ne=W,Pi.set(It,W);let de=()=>{W.settled=!0,Zl(It,W)};W.promise.then(de,de)}Ne.consumers+=1;let ce=!1,j=()=>{ce||(ce=!0,Ne.consumers-=1,Zl(It,Ne))};U?.(j);try{let W=await Ne.promise;xn.current=It,L&&(Dr(Nt),jt(Ue=>ml(Ue,L)));let{sid:de,result:h,claimed:y,claim:H,claimRequiresIdentity:Ee}=W;if(cr.current=H,Ot(Ee===!0),tt(h),h.data.session&&we(h.data.session),de&&ue(de),y){Mr.current+=1;let Ue=Mr.current;Lt.current=y,fr(!0),y.then(De=>{Mr.current===Ue&&(Lt.current===y&&(Lt.current=null),tt(De),De.data.session&&we(De.data.session),fr(!1),Ot(!1))},De=>{Mr.current===Ue&&(Lt.current===y&&(Lt.current=null),fr(!1),Ot(!1),$(De instanceof $e.FloPayError?De:new $e.FloPayError(De instanceof Error?De.message:"Failed to create session","api_error")))})}else Mr.current+=1,Lt.current=null,fr(!1),Ot(!1);let{flopay:Je,paypalFlopay:mt}=await gs(h,{billingApiUrl:N,locale:l,telemetry:a});return At(Je,mt),rt(!1),W}catch(W){throw xn.current===It&&(xn.current=null),W}finally{U||j()}},[Nt,At,l,N,a]),Pn=(0,C.useRef)($n);Pn.current=$n;let An=(0,C.useRef)(Xr);An.current=Xr;let Ut=(0,C.useCallback)(async L=>{if(!Qd(L)||qr)return{sessionId:q,session:z};Sr(!0);try{let U=await Xr(L);return{sessionId:U.sid,session:U.result.data.session??null}}finally{Sr(!1)}},[Xr,qr,q,z]),Jr=(0,C.useCallback)(async L=>{let U=cr.current;if(!U)return;let re=Mr.current,Re=await U(L);Mr.current===re&&(tt(Re),Re.data.session&&we(Re.data.session))},[]),Zr=(0,C.useCallback)(async()=>{await Lt.current},[]),jr=(0,C.useCallback)(async()=>(await Zr(),{proceed:!0}),[Zr]);(0,C.useEffect)(()=>{let L=!1,U,re=++Se.current;Et(),$(null),Ir(0);let Re=()=>{L=!0,Se.current===re&&(Se.current+=1,Et())},It=ao.current;if(Or&&It)return Gt(nn),rt(!1),xn.current===Or?Re:(we(fl(It,V)),(async()=>{let ce=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),j=nn==="auto"&&!er.current&&!ce;j&&(Qt(null),Xt(null),Wt("processing"));try{let W=await An.current(void 0,H=>{U=H}),de=W.result.data.session??null;$t.current=Qi(W.result);let h=fs(W.result),y=(0,En.wasSessionRecentlyCompleted)(W.sid||de?.id);if(!L&&j&&de&&!h&&!y){er.current=!0,await Kd(Or,W.sdkGeneratedIdempotencyKey,()=>Pn.current(de,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:W.result.autoProcessingError,initialAutoProcessingPending:W.result.autoProcessingPending,autoProcessingAttempted:W.result.autoProcessingAttempted,sessionId:W.sid||de.id}));return}!L&&j&&((h||y)&&(er.current=!0),Wt(null),Xt(null))}catch(W){if(L)return;let de=Ha(W);if(j&&de==="session_auto_completed"){er.current=!0,Wt("success"),await Ta(600),L||((0,Qe.invokeMerchantCallback)(()=>{te.current?.({status:"succeeded"})}),Wt(null),Xt(null));return}j&&(Wt(null),Xt(null));let h=W instanceof $e.FloPayError?W:new $e.FloPayError(W instanceof Error?W.message:"Failed to create session","api_error");$(h)}finally{U?.(),U=void 0}})(),()=>{Re(),U?.()});rt(!0);async function nr(){let ce=!1,j=null;try{let W=new ro.PaymentAPI(N,{telemetry:!1}),de=await W.getUnifiedCheckoutSession(m,t);if(j=de,L)return;tt(de);let h=de.data.session??null;if(we(h),!h)throw new $e.FloPayError("No session data returned","api_error");let y=h.checkoutMode;if(y==="setup")throw new $e.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(h.status==="authorized"){rt(!1),(0,Qe.invokeMerchantCallback)(()=>{te.current?.(Xn(h,m)),tr.current?.(h.successUrl??"")});return}if(h.status==="complete"){rt(!1),(0,Qe.invokeMerchantCallback)(()=>{tr.current?.(h.successUrl??"")});return}if(h.status==="expired")throw $a(h);ce=!0;let H=V??y??"full";Gt(H),Mr.current+=1;let Ee=h.clientSecret||t;cr.current=h.buyerIdentified===!1&&Ee?Lo(W,m,Ee,{...h.customer?.id?{userId:h.customer.id}:{}}):void 0,fr(!1),Ot(!1);let Je=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),mt=fs(de);if(H==="auto"&&!er.current&&!Je&&!mt){er.current=!0;let Ue=Ne(de);try{if(await Pn.current(h,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Ue,sessionId:m||h.id}),L)return;await Ue,L||rt(!1);return}catch{if(L)return;await Ue,L||rt(!1);return}}await Ne(de),L||rt(!1)}catch(W){if(L)return;let de=yl(W,ce);if(ce&&ct({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),de){let{errorCode:y,stage:H,...Ee}=de;ms(N,a,fe,y,H,Ee)}if(de?.stage==="provider_load"&&(V??j?.data.session?.checkoutMode??"full")==="full"&&pl(j,M,f)){let y=Yd({billingApiUrl:N,locale:l,telemetry:a});wt.current=y,At(y,null),Ir(1),rt(!1);return}let h=W instanceof $e.FloPayError&&de?.stage!=="provider_load"?W:ul();h!==W&&(0,Qe.invokeMerchantCallback)(()=>Ct.current?.(h)),$(h),rt(!1)}}async function Ne(ce){let{flopay:j,paypalFlopay:W,...de}=await gs(ce,{billingApiUrl:N,locale:l,telemetry:a});$t.current={publishableKey:de.publishableKey,paypalPublishableKey:de.paypalPublishableKey},At(j,W),Ir(0)}return nr(),Re},[V,Or,nn,Z,t,M,f]);let vn=(0,C.useCallback)(async()=>{if(!Me||Vt!==1)return;let L=Se.current;Ir(2);try{let{flopay:U,paypalFlopay:re}=await gs(Me,{billingApiUrl:N,locale:l,telemetry:a});if(Se.current!==L)return;Et(),At(U,re),Ir(0)}catch(U){if(Se.current!==L)return;let{errorCode:re,stage:Re,...It}=$i(U);ms(N,a,fe,re,Re,It)}},[Et,At,l,Vt,N,a,fe,Me]),bt=!!(m&&(z?.clientSecret||t)),kr=Yt||!bt,dr=(0,C.useCallback)(async()=>{if(!(Yt||!bt||!z)){Ur(!0),Qt(null);try{await $n(z,{attempt3DS:!0,fallbackToFull:!0,sessionId:m||z.id})}finally{Ur(!1)}}},[m,Yt,bt,$n,z]),Vr=(0,$e.resolveDirectPaypalConfig)(Me?.data.paypal,ee),yo=fs(Me),Cn=(0,C.useMemo)(()=>{if(!(!Me||!z||!Me.data.stripe?.publishableKey))return{billingApiUrl:N}},[Me,z,N]),Kn=!!(r&&!le&&se==="buttons"&&Oe&&nn==="full"),Qr=!!(m&&((0,$e.isMountableVaultBlock)(z?.vault)||(0,wn.canRecoverHostedCardForm)(z))),Rr=(0,C.useMemo)(()=>({session:z,loading:xe,error:oe,checkoutMode:br,inlineSessionDraft:rr,applyInlineSessionPatch:Kn?Ut:void 0,inlineSessionPatchProcessing:qr,claimPending:wr,claimRequiresIdentity:Tr,claimBuyerIdentity:Jr,waitForDataAttachment:Zr}),[z,xe,oe,br,rr,Kn,Ut,qr,wr,Tr,Jr,Zr]),Fn=!!r&&se==="buttons"&&!yo&&!Qr&&(!at||!Cn),Fr=zr?(0,B.jsx)(Hr,{status:zr,errorMessage:Vn,authorized:Gr}):null;if(xe&&!Qr){if(u)return(0,B.jsxs)(B.Fragment,{children:[u,Fr]});if(se==="buttons"){let L=Ce?.buttonsLayout?.cardButton?.borderRadius??Ce?.appearance.variables?.borderRadius??8,U=re=>(0,B.jsx)("div",{style:{height:re,borderRadius:L,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[M&&U(Jo),f&&(b||Te)&&U(Jo),f&&U(Jo),(0,B.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Fr]})}return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,B.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,B.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Fr]})}return oe?p?(0,B.jsx)(kn.Provider,{value:Rr,children:p(oe)}):(0,B.jsx)(kn.Provider,{value:Rr,children:(0,B.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:oe.message})}):Fn?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(kn.Provider,{value:Rr,children:(0,B.jsx)(tu,{onButtonClick:Ye,showPayPal:M,showStripe:f,showApplePay:b,showGooglePay:Te,theme:me,buttonsTheme:pe,buttonsStyles:Fe,cardButtonContent:dt,cardBackButtonContent:He,cardTitleContent:D})}),Fr]}):yo&&z&&Vr?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(kn.Provider,{value:Rr,children:(0,B.jsxs)("div",{className:Xe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[_r&&(0,B.jsx)(Wo,{icon:!1,children:_r}),qe==="retrying"&&(0,B.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),qe==="exhausted"&&(0,B.jsxs)("div",{role:"alert",children:[(0,B.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,B.jsx)("button",{type:"button",onClick:oo,children:"Retry PayPal"})]}),qe!=="exhausted"&&(0,B.jsx)("div",{"aria-hidden":qe==="retrying"?!0:void 0,style:qe==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,B.jsx)(Il,{sessionId:m,nonce:z.clientSecret||void 0,billingApiUrl:N,email:z.customer?.email||rr?.account?.email,billingName:[z.customer?.firstName,z.customer?.lastName].filter(Boolean).join(" ")||[rr?.account?.firstName,rr?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Jr,clientId:Vr.clientId,environment:Vr.environment,currency:(z.currency??"usd").toUpperCase(),isSubscription:z.mode==="subscription",providerObjectType:Vr.providerObjectType,approvalPresentation:Vr.approvalPresentation,existingOrderId:Vr.existingOrderId,onComplete:P,onErrorChange:Qt,onDecline:E,onCancel:K,onButtonClick:Ye,runBeforeButtonClick:jr,onInitializationStateChange:yt,allowAutomaticRetry:xr===0,session:z,telemetry:a,telemetryContext:fe,onInstrument:J,debug:T},`${Ke}:paypal-init-${xr}`)})]})}),Fr]}):br==="confirm"?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(kn.Provider,{value:Rr,children:(0,B.jsx)(va,{flopay:at,paypalFlopay:x,options:Cn??{billingApiUrl:N},onInstrument:J,children:(0,B.jsxs)("div",{className:Xe,children:[_r&&(0,B.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:_r}),Ae?Ae({onConfirm:dr,isProcessing:kr}):(0,B.jsx)("button",{type:"button",onClick:dr,disabled:kr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:kr?"not-allowed":"pointer",opacity:kr?.6:1},children:Yt?"Processing...":Ve??"Confirm Purchase"})]})},Ke)}),Fr]}):(!at||!Cn)&&!(Qr&&br==="full")?(0,B.jsx)(B.Fragment,{children:Fr}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(kn.Provider,{value:Rr,children:(0,B.jsxs)(va,{flopay:at,paypalFlopay:x,options:Cn??{billingApiUrl:N},onInstrument:J,children:[Vt===1&&(0,B.jsx)("button",{type:"button",onClick:vn,children:"Retry payment methods"}),le?(0,B.jsxs)(B.Fragment,{children:[_r&&(0,B.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:_r}),(0,B.jsx)(eu,{sessionId:m,nonce:z?.clientSecret||void 0,billingApiUrl:N,session:z,submitLabel:ze,walletPresentation:v,children:le})]}):(0,B.jsx)(fi,{sessionId:m,nonce:z?.clientSecret||void 0,telemetry:a,email:z?.customer?.email||rr?.account?.email,userId:z?.customer?.id||rr?.account?.userId,firstName:z?.customer?.firstName||rr?.account?.firstName,lastName:z?.customer?.lastName||rr?.account?.lastName,totalAmount:z?Math.round((0,$e.buildCheckoutDisplayData)(z).total*100):0,currency:z?.currency?.toLowerCase()??"usd",onComplete:P,onError:w,onDecline:E,onCancel:K,error:_r,onErrorChange:Qt,showPayPal:M,showStripe:f,walletPresentation:v,enabledPaymentMethods:Vt?[]:ye??Me?.data.stripe?.enabledPaymentMethods??z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Me?.data.stripe?.enabledPaymentMethodCountries,showApplePay:b,showGooglePay:Te,layout:se,theme:me,buttonsTheme:pe,buttonsStyles:Fe,appearance:ut,cardButtonContent:dt,cardBackButtonContent:He,cardTitleContent:D,onButtonClick:Ye,onBeforeButtonClick:Oe,onBuyerIdentityReady:Jr,enableAVS:ge,...Q?{cardFieldOrder:Q}:{},...G?{cardPreFormSlot:G}:{},avsLayout:Be,country:z?.customer?.country,city:z?.customer?.city,state:z?.customer?.state,onCountryChange:I,onZipChange:X,avsCheck:!!ge,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Ps(le,se),className:Xe,submitLabel:ze,directPaypal:Vr,isSubscription:z?.mode==="subscription",session:z,dataAttachmentPending:wr,dataAttachmentRequiresIdentity:Tr,debug:T})]},Ke)}),Fr]})}function eu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:i,children:l}){return(0,B.jsx)(B.Fragment,{children:C.default.Children.map(l,u=>{if(!C.default.isValidElement(u))return u;let p=u.props,P={};return p.sessionId||(P.sessionId=e),!p.nonce&&t&&(P.nonce=t),p.billingApiUrl||(P.billingApiUrl=r),p.submitLabel===void 0&&a!==void 0&&(P.submitLabel=a),p.walletPresentation===void 0&&(P.walletPresentation=i),n?.customer&&(p.email||(P.email=n.customer.email),p.userId||(P.userId=n.customer.id),p.firstName||(P.firstName=n.customer.firstName),p.lastName||(P.lastName=n.customer.lastName)),Object.keys(P).length===0?u:C.default.cloneElement(u,P)})})}function tu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:i,buttonsTheme:l,buttonsStyles:u,cardButtonContent:p,cardBackButtonContent:P,cardTitleContent:w}){let[S,E]=(0,C.useState)(!1),K=(0,C.useMemo)(()=>(0,$e.resolveTheme)(i),[i]),I=(0,C.useMemo)(()=>{let v=K?.buttonsLayout??(0,$e.resolveButtonsLayoutTheme)(l);return u?{...v,...u,cardButton:{...v.cardButton,...u.cardButton},cardFormContainer:{...v.cardFormContainer,...u.cardFormContainer},backButton:{...v.backButton,...u.backButton},backButtonIcon:{...v.backButtonIcon,...u.backButtonIcon},submitButton:{...v.submitButton,...u.submitButton},title:{...v.title,...u.title}}:v},[K,l,u]),X=K?.buttonsLayout?.cardButton?.borderRadius??K?.appearance.variables?.borderRadius??8,M=v=>(0,B.jsx)("div",{style:{height:v,borderRadius:X,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),f=p===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(S){let v=I.cardInputBorder??"#e5e7eb",ye=I.cardInputBackground??"white",b=Bo(P),Te=Bo(w);return(0,B.jsxs)("div",{style:{backgroundColor:I.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...I.cardFormContainer},children:[(0,B.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,B.jsxs)("button",{type:"button",onClick:()=>E(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:b?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...I.backButton},children:[(0,B.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...I.backButtonIcon},children:(0,B.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,B.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,B.jsx)(Oo,{content:P})]}),Te?(0,B.jsx)("div",{style:{flex:1}}):(0,B.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...I.title},children:(0,B.jsx)(ua,{content:w})})]}),(0,B.jsx)("div",{style:{backgroundColor:ye,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsxs)("div",{style:{display:"flex"},children:[(0,B.jsx)("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,B.jsx)("div",{style:{backgroundColor:ye,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...I.submitButton,opacity:.5}}),(0,B.jsx)("style",{children:`
|
|
38
|
+
`}),ia&&mo&&(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ye?-2:0},children:[(0,u.jsxs)("button",{type:"button",onClick:we,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:A.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...A.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...A.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Oo,{content:De})]}),el?(0,u.jsx)("div",{style:{flex:1}}):(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...A.title},children:(0,u.jsx)(ua,{content:de})})]}),!ia&&!el&&(0,u.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zi,order:ye?-3:0,...A.title},children:(0,u.jsx)(ua,{content:de})}),ye&&J&&(0,u.jsx)("div",{style:{order:-2,width:"100%"},children:J}),ye&&io&&(0,u.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,u.jsx)("div",{style:{backgroundColor:xo,border:`1px solid ${dn(za)}`,borderRadius:tr,padding:"10px"},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:sr,onChange:s=>{Nt("email"),Ir.current=s.target.value,br(s.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{tn("email")&&ao(!0),ko||Ti()},disabled:oe,required:!0,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...qi}})}),za&&(0,u.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:la,children:Ri.empty?"Email address is required":"Enter a valid email address"})]}),Ye&&(0,u.jsx)("div",{style:{order:ye?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ht,D=(Q=!1)=>({backgroundColor:xo,border:`1px solid ${dn(Q)}`,borderRadius:tr,marginTop:"0.5rem",padding:"10px"}),ae=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...qi}),Re=(0,d.getStateOptions)(s);return(0,u.jsxs)(u.Fragment,{children:[(0,d.isAVSFieldVisible)(Ye.address_line_1,s)&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)("div",{style:D(Jt("line1")),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Zt,onChange:Q=>{Nt("line1"),dr.current.addressLine1=!0,Gt.current=Q.target.value,$r(Q.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>rn("line1"),disabled:oe,required:!0,"aria-invalid":Jt("line1")||void 0,"aria-describedby":Jt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ae()})}),Jt("line1")&&(0,u.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:la,children:"Street address is required"})]}),(0,d.isAVSFieldVisible)(Ye.address_line_2,s)&&(0,u.jsx)("div",{style:D(),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Mt,onChange:Q=>{dr.current.addressLine2=!0,hr.current=Q.target.value,xn(Q.target.value)},disabled:oe,"data-testid":"flopay-address-line2",style:ae()})}),((0,d.isAVSFieldVisible)(Ye.city,s)||(0,d.isAVSFieldVisible)(Ye.state,s))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Ye.city,s)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${dn(Jt("city"))}`,borderRight:`1px solid ${dn(Jt("city"))}`,borderBottom:`1px solid ${dn(Jt("city"))}`,borderLeft:`1px solid ${dn(Jt("city"))}`,padding:"10px",borderTopLeftRadius:tr,borderBottomLeftRadius:tr,...(0,d.isAVSFieldVisible)(Ye.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:tr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Kt,onChange:Q=>{Nt("city"),dr.current.city=!0,Yt.current=Q.target.value,ln(Q.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>rn("city"),disabled:oe,required:!0,"aria-invalid":Jt("city")||void 0,"aria-describedby":Jt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ae()})}),(0,d.isAVSFieldVisible)(Ye.state,s)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${dn(Jt("state"))}`,borderRight:`1px solid ${dn(Jt("state"))}`,borderBottom:`1px solid ${dn(Jt("state"))}`,borderLeft:`1px solid ${dn(Jt("state"))}`,padding:"10px",borderTopRightRadius:tr,borderBottomRightRadius:tr,...(0,d.isAVSFieldVisible)(Ye.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${dn(Jt("state")||Jt("city"))}`}:{borderRadius:tr}},children:Re?(0,u.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Nr,onChange:Q=>{Nt("state"),dr.current.state=!0,cr.current=Q.target.value,Ur(Q.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>rn("state"),disabled:oe,autoComplete:"billing address-level1",required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...ae(),cursor:"pointer"},children:[(0,u.jsx)("option",{value:"",children:(0,d.getStateLabel)(s)}),Re.map(Q=>(0,u.jsx)("option",{value:Q.code,children:Q.name},Q.code))]}):(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,d.getStateLabel)(s),autoComplete:"billing address-level1",value:Nr,onChange:Q=>{Nt("state"),dr.current.state=!0,cr.current=Q.target.value,Ur(Q.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>rn("state"),disabled:oe,required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ae()})})]}),Jt("city")&&(0,u.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:la,children:"City is required"}),Jt("state")&&(0,u.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:la,children:[(0,d.getStateLabel)(s)," is required"]}),((0,d.isAVSFieldVisible)(Ye.country,s)||(0,d.isAVSFieldVisible)(Ye.postal_code,s))&&(0,u.jsxs)("div",{style:{display:"flex",flexDirection:H==="column"?"column":"row",gap:H==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Ye.country,s)&&(0,u.jsx)("div",{style:{flex:H==="row"?1:void 0,backgroundColor:xo,borderTop:`1px solid ${sa}`,borderRight:`1px solid ${sa}`,borderBottom:`1px solid ${sa}`,borderLeft:`1px solid ${sa}`,padding:"10px",...H==="row"&&(0,d.isAVSFieldVisible)(Ye.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:tr,borderBottomLeftRadius:tr,borderRight:"none"}:{borderRadius:tr}},children:(0,u.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Ht,onChange:Q=>{dr.current.country=!0,lr.current=Q.target.value,Tt(Q.target.value),ut?.(Q.target.value),cr.current="",Ur("")},disabled:oe,autoComplete:"billing country","data-testid":"flopay-country",style:{...ae(),cursor:"pointer"},children:[Ht===""?(0,u.jsx)("option",{value:"",children:"Select country"}):null,d.COUNTRY_OPTIONS.map(Q=>(0,u.jsxs)("option",{value:Q.code,children:[Q.flag," ",Q.name]},Q.code))]})}),(0,d.isAVSFieldVisible)(Ye.postal_code,s)&&(0,u.jsx)("div",{style:{flex:H==="row"?1:void 0,backgroundColor:xo,border:`1px solid ${Ac}`,padding:"10px",...H==="row"&&(0,d.isAVSFieldVisible)(Ye.country,s)?{borderRadius:"0",borderTopRightRadius:tr,borderBottomRightRadius:tr}:{borderRadius:tr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,d.getPostalCodeLabel)(Ht),autoComplete:"billing postal-code",value:Lr,onChange:Q=>{Nt("zip"),dr.current.zip=!0,wt.current=Q.target.value,Ar(Q.target.value),Le?.(Q.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{tn("zip")&&Fn(!0)},disabled:oe,required:Lt.required,"aria-invalid":qa||void 0,"aria-describedby":qa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ae()})})]}),qa&&(0,u.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:la,children:Lt.empty?`${(0,d.getPostalCodeLabel)(s)} is required`:zd(s)})]})})()}),ye&&Lc,kt&&(0,u.jsx)(Wo,{margin:"0.75rem 0",styleOverride:A.errorBanner,children:kt})]}),ja={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},al=s=>z?!pe||!Ln?(0,u.jsx)("pre",{"data-testid":s,style:ja,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":s,style:ja,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${pe}`,` directPaypalConfigured=${Ln}`,` inAppBrowserDetected=${String(La)}`,` shouldRenderDirectPayPal=${ta}`,` shouldRenderStripePayPal=${na}`,` hasPaypalStripeInstance=${!!Rs}`].join(`
|
|
39
|
+
`)}):null,il=s=>z?!b||!on?(0,u.jsx)("pre",{"data-testid":s,style:ja,children:"FloPay/Stripe-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":s,style:ja,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${b}`,` currency=${ar}`,` amountInCents=${Qo}`,` enabledPaymentMethods: ${JSON.stringify(_??[])}`,` enabledPaymentMethodsProvided=${ea}`,` hasEnabledMethods=${Fa}`,` expressMethods: ${JSON.stringify(Da)}`,` walletExpressMethods: ${JSON.stringify(To)}`,` paymentElementMethods: ${JSON.stringify(xi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Oa)}`,` hasStripeInstance=${!!on}`,` shouldRenderWallets=${Mo}`,` shouldRenderPaymentElement=${oa}`].join(`
|
|
40
|
+
`)}):null,sl=bt==="apm-expanding"||bt==="apm-form"||bt==="apm-collapsing",Fo;bt==="apm-expanding"?Fo=ql:bt==="apm-collapsing"&&(Fo=jl);let Va=mr?Jl(Ai,mr,He):null;if(xe==="buttons"){let s=bt==="buttons"||bt==="expanding"||bt==="apm-expanding",D=bt==="expanding"||bt==="card"||bt==="collapsing",ae=Ge===void 0?{boxSizing:"border-box",height:Yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Re;bt==="expanding"||bt==="apm-expanding"?Re=Od:(bt==="collapsing"||bt==="apm-collapsing")&&(Re=Dd);let Q;return bt==="expanding"?Q=ql:bt==="collapsing"&&(Q=jl),(0,u.jsxs)("form",{onSubmit:Oi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Xo,{}),Ne&&(0,u.jsx)(Zr,{status:Ne,errorMessage:kt,authorized:ur}),(0,u.jsxs)("div",{style:{display:"grid"},children:[(0,u.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Re?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Re?Nd:{},...Re?{animation:Re,pointerEvents:"none"}:{}},children:[al("flopay-direct-paypal-gate-debug"),il("flopay-stripe-gate-debug"),ta&&Ct&&(0,u.jsxs)(u.Fragment,{children:[ke&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(fa.Provider,{value:M,children:(0,u.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:R,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,clientId:Ct.clientId,environment:Ct.environment,currency:ar.toUpperCase(),isSubscription:Ce,providerObjectType:Bt,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Xr,onComplete:l,onErrorChange:qe,onDecline:m,onCancel:h,onTechnicalFailure:Io,onButtonClick:X,runBeforeButtonClick:kn,isProcessing:oe,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:Ve,existingOrderId:ke?.orderId,debug:z},ke?.orderId??"fresh")})]}),na&&(0,u.jsx)(rr.Elements,{stripe:ra,options:_s,children:(0,u.jsx)(Wl,{sessionId:e,nonce:t,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,billingApiUrl:R,onTokenizedBody:Xr,onErrorChange:qe,isProcessing:oe,onButtonClick:X,onDecline:m,onTechnicalFailure:Io,runBeforeButtonClick:kn,onLoadStateChange:Ls,placeholderBorderRadius:yo,popupCapabilityOwner:M,externalTelemetryContext:Hs,presentationMode:_o})}),Mo?(0,u.jsx)(rr.Elements,{stripe:on,options:Is,children:(0,u.jsx)($l,{sessionId:e,nonce:t,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,billingApiUrl:R,intentKind:at>0?"payment":"setup",expressMethods:To,onTokenizedBody:Xr,onErrorChange:qe,onButtonClick:X,onDecline:m,onTechnicalFailure:Io,runBeforeButtonClick:kn,onLoadStateChange:Us,placeholderBorderRadius:yo,popupCapabilityOwner:M,externalTelemetryContext:mt})}):null,!Mo&&Ws?(0,u.jsx)("div",{style:{height:Yo,borderRadius:yo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,oa&&(0,u.jsx)(Hl,{sessionId:e,nonce:t,email:he.email,billingName:[he.firstName,he.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:it,billingApiUrl:R,paymentElementMethods:Oa,stripeInstance:on,paymentElementBaseOptions:Ai,futureUseSession:He,onTokenizedBody:Xr,onErrorChange:qe,onButtonClick:X,onDecline:m,runBeforeButtonClick:kn,onLoadStateChange:qs,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,onExpandApm:Rt,expandedApmMethod:mr,themeId:lt,buttonAppearance:{backgroundColor:A.cardButton?.backgroundColor,borderColor:A.cardInputBorder,textColor:A.cardButton?.color,borderRadius:yo}}),ye&&(0,u.jsx)("button",{type:"button",onClick:async()=>{oe||!(await kn("card")).proceed||(X?.("card"),ne())},disabled:oe,style:{width:"100%",...ae,...A.cardButton,...ps({themeBundle:Et,resolvedPrimaryColor:fo,resolvedBorderRadius:tr,submitButtonStyle:A.submitButton,explicitPrimaryColor:Jr?.colorPrimary}),fontSize:A.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:oe?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:oe?.6:1},onMouseEnter:Ee=>{!oe&&(Et||Jr?.colorPrimary)&&(Ee.currentTarget.style.backgroundColor=Dc)},onMouseLeave:Ee=>{(Et||Jr?.colorPrimary)&&(Ee.currentTarget.style.backgroundColor=fo)},onMouseDown:Ee=>{Ee.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ee=>{Ee.currentTarget.style.transform="scale(1)"},children:(0,u.jsx)(Do,{content:Ge})}),kt&&bt==="buttons"&&(0,u.jsx)(Wo,{margin:"0.25rem 0",styleOverride:A.errorBanner,children:kt})]}),ye&&D&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...Q?{animation:Q}:{},...bt==="collapsing"?{pointerEvents:"none"}:{}},children:ol}),b&&sl&&mr&&Va&&on&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...Fo?{animation:Fo}:{},...bt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:er,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:A.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...A.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...A.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Oo,{content:De})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:zi,paddingRight:80,...A.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(mr)}`})]}),(0,u.jsx)(rr.Elements,{stripe:on,options:Va,children:(0,u.jsx)(cs,{method:mr,sessionId:e,nonce:t,email:he.email,billingName:[he.firstName,he.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:it,billingApiUrl:R,onTokenizedBody:Xr,onErrorChange:qe,onDecline:m,onCancel:er,runBeforeButtonClick:kn,onButtonClick:X,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,errorText:kt})},mr)]})})]})]})}return sl&&mr&&Va&&on&&b?(0,u.jsxs)("form",{onSubmit:Oi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Xo,{}),Ne&&(0,u.jsx)(Zr,{status:Ne,errorMessage:kt,authorized:ur}),(0,u.jsx)("div",{style:{...Fo?{animation:Fo}:{},...bt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:er,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:A.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...A.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...A.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Oo,{content:De})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:zi,paddingRight:80,...A.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(mr)}`})]}),(0,u.jsx)(rr.Elements,{stripe:on,options:Va,children:(0,u.jsx)(cs,{method:mr,sessionId:e,nonce:t,email:he.email,billingName:[he.firstName,he.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:it,billingApiUrl:R,onTokenizedBody:Xr,onErrorChange:qe,onDecline:m,onCancel:er,runBeforeButtonClick:kn,onButtonClick:X,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,errorText:kt})},mr)]})})]}):(0,u.jsxs)("form",{onSubmit:Oi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Xo,{}),Ne&&(0,u.jsx)(Zr,{status:Ne,errorMessage:kt,authorized:ur}),(0,u.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[al("flopay-direct-paypal-gate-debug-default"),il("flopay-stripe-gate-debug-default"),ta&&Ct&&(0,u.jsxs)(u.Fragment,{children:[ke&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(fa.Provider,{value:M,children:(0,u.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:R,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,clientId:Ct.clientId,environment:Ct.environment,currency:ar.toUpperCase(),isSubscription:Ce,providerObjectType:Bt,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Xr,onComplete:l,onErrorChange:qe,onDecline:m,onCancel:h,onTechnicalFailure:Io,onButtonClick:X,runBeforeButtonClick:kn,isProcessing:oe,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:Ve,existingOrderId:ke?.orderId,debug:z},ke?.orderId??"fresh")})]}),na&&(0,u.jsx)(rr.Elements,{stripe:ra,options:_s,children:(0,u.jsx)(Wl,{sessionId:e,nonce:t,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,billingApiUrl:R,onTokenizedBody:Xr,onErrorChange:qe,isProcessing:oe,onButtonClick:X,onDecline:m,onTechnicalFailure:Io,runBeforeButtonClick:kn,onLoadStateChange:Ls,placeholderBorderRadius:yo,popupCapabilityOwner:M,externalTelemetryContext:Hs,presentationMode:_o})}),Mo&&(0,u.jsx)(rr.Elements,{stripe:on,options:Is,children:(0,u.jsx)($l,{sessionId:e,nonce:t,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,billingApiUrl:R,intentKind:at>0?"payment":"setup",expressMethods:To,onTokenizedBody:Xr,onErrorChange:qe,onButtonClick:X,onDecline:m,onTechnicalFailure:Io,runBeforeButtonClick:kn,onLoadStateChange:Us,placeholderBorderRadius:yo,popupCapabilityOwner:M,externalTelemetryContext:mt})}),oa&&(0,u.jsx)(Hl,{sessionId:e,nonce:t,email:he.email,billingName:[he.firstName,he.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:R,paymentElementMethods:Oa,stripeInstance:on,paymentElementBaseOptions:Ai,futureUseSession:He,onTokenizedBody:Xr,onErrorChange:qe,onButtonClick:X,onDecline:m,runBeforeButtonClick:kn,onLoadStateChange:qs,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,themeId:lt,onExpandApm:Rt,expandedApmMethod:mr,buttonAppearance:{backgroundColor:A.cardButton?.backgroundColor,borderColor:A.cardInputBorder,textColor:A.cardButton?.color,borderRadius:yo}})]}),ye&&(_c||Ic||Tc)&&(0,u.jsx)(ci,{label:"or pay with card"}),ye&&ol]})}var F=require("react/jsx-runtime"),Jo=44,vs="flopay_checkout_saved_payment_resume",Pi=new Map,gi=new Map;function Zl(e,t){t.settled&&t.consumers===0&&Pi.get(e)===t&&Pi.delete(e)}function Kd(e,t,r){let n=gi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),i={attempt:a,sdkGeneratedIdempotencyKey:t};gi.set(e,i);let l=()=>{gi.get(e)===i&&gi.delete(e)};return a.then(l,l),a}function Ta(e){return new Promise(t=>setTimeout(t,e))}function hi(e,t,r){let n=Ja({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:We.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Ma(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ys(e,t,r,n,a,i){let l=hi(e,t,r);l.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Ma(l)}function Ql(e,t,r,n){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function ec(e,t,r,n,a){let i=(0,We.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:i.statusClass}),t instanceof We.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof We.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...i,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function fs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,We.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var Gd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Yd(e){return new ro.FloPay(Gd,{publishableKey:"provider_unavailable",...e})}async function gs(e,t){let{publishableKey:r,paypalPublishableKey:n}=Qi(e);return{...await es({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Cs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Xd(){if(!Cs())return null;try{let e=window.sessionStorage.getItem(vs);return e?JSON.parse(e):null}catch{return null}}function tc(e){if(Cs())try{window.sessionStorage.setItem(vs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function hs(){if(Cs())try{window.sessionStorage.removeItem(vs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Jd(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function rc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Ps(e,t){return(0,We.resolveCheckoutLogLayout)(!!e,t)}function Zd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function nc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Qd(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function vi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:i,locale:l,loading:p,error:m,onComplete:h,onError:w,onInstrument:S,onDecline:E,onCancel:Y,onCountryChange:I,onZipChange:ee,showPayPal:x=!0,showStripe:f=!0,walletPresentation:P="auto",enabledPaymentMethods:pe,showApplePay:b=!0,showGooglePay:Ie=!0,debug:_=!1,layout:ie,theme:me,buttonsTheme:ue,buttonsStyles:xe,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B,showSecurityFooter:St,onButtonClick:Ge,onBeforeButtonClick:De,enableAVS:de,cardFieldOrder:re,cardPreFormSlot:X,avsLayout:Oe,submitLabel:nt,className:ze,initialErrorMessage:te=null,initialPayPalOrderId:J,children:H,checkoutMode:j,confirmLabel:je,renderConfirmButton:Te,onSessionCompleted:fe}){let O=(0,We.resolveBillingApiUrl)(n),Pe=(0,v.useMemo)(()=>(0,We.resolveTheme)(me),[me]),ut=i??Pe?.appearance,Le=r?"embedded_checkout":"standard_checkout",ot=Ps(H,ie),[_e,et]=(0,v.useState)(null),[at,ar]=(0,v.useState)(null),xt=(0,v.useRef)(null),Ct=(0,v.useRef)(null),Ce=(0,v.useRef)(0),[T,ht]=(0,v.useState)(null),pt=(0,v.useRef)(null),[z,Ae]=(0,v.useState)(null),Dt=(0,v.useMemo)(()=>r?(0,ft.serializeCreateParams)(r):"",[r]),be=r?`create:${Dt}`:`session:${e??""}`,_t=nc(z),C=(0,v.useRef)(new Set),M=(0,v.useRef)(be),Fe=(0,v.useRef)(be);Co(()=>{Fe.current=be,M.current!==be&&(M.current=be,C.current.clear())},[be]);let Se=(0,v.useCallback)(L=>{if(Fe.current===be){if(Xi.FLO_INSTRUMENT_ONCE_NAMES.has(L.name)){if(C.current.has(L.name))return;C.current.add(L.name)}(0,Ze.invokeMerchantCallback)(()=>S?.(L))}},[be,S]),ct=Vo(Se,be),mt=(0,v.useRef)(!1),Ve=(0,v.useCallback)(L=>{if(mt.current)return;let N=L.gateway||!_t?L:{...L,gateway:_t};Se(N)},[Se,_t]);(0,v.useEffect)(()=>{ct({class:"lifecycle",name:"checkout.mount"})},[ct]);let[He,Bt]=(0,v.useState)(e??""),c=e??He,U=r?"":c,[V,se]=(0,v.useState)(!0),[R,K]=(0,v.useState)(null),[Ut,xr]=(0,v.useState)(0),[ir,Ht]=(0,v.useState)("full"),[Tt,Lr]=(0,v.useState)(!1),[Ar,Zt]=(0,v.useState)(te),[$r,Mt]=(0,v.useState)(null),[xn,Kt]=(0,v.useState)(null),[ln,Nr]=(0,v.useState)(!1),[Ur,sr]=(0,v.useState)(void 0),[br,Hr]=(0,v.useState)(""),[dt,wt]=(0,v.useState)(!1),[lr,Gt]=(0,v.useState)(!1),[hr,Yt]=(0,v.useState)(!1),cr=(0,v.useRef)(null),Ir=(0,v.useRef)(0),dr=(0,v.useRef)(void 0),[Ye,Fr]=(0,v.useState)("loading"),[ur,oo]=(0,v.useState)(0),zr=(0,v.useRef)(!1),qr=(0,v.useRef)(!1),An=(0,v.useRef)(!1),Kr=(0,v.useRef)(null),Xt=(0,v.useRef)(null),ye=(0,v.useMemo)(()=>({checkoutMode:j??ir,layout:Zd(H,ie)}),[j,H,ir,ie]),Z=(0,v.useRef)(h);Z.current=h;let At=(0,v.useRef)(w);At.current=w;let Me=(0,v.useRef)(E);Me.current=E;let Pr=(0,v.useCallback)(L=>ei(Kr,async N=>{try{return await L(N)}catch(ne){throw N.aborted?$o(ne):ne}}),[]);(0,v.useEffect)(()=>()=>{Kr.current?.abort(),Kr.current=null},[]);let Ot=(0,v.useCallback)((L,N)=>{xt.current=L,ar(L),pt.current=N,ht(N)},[]),jt=(0,v.useCallback)(()=>{let L=Ct.current;L&&(Ct.current=null,L.destroy())},[]);(0,v.useEffect)(()=>{kr(at)?.setCheckoutContext(ye),T&&T!==at&&kr(T)?.setCheckoutContext(ye)},[at,T,ye]);let vr=(0,v.useRef)(fe);vr.current=fe;let $=(0,v.useCallback)(L=>{Fr(L),!(L!=="exhausted"||An.current)&&(An.current=!0,At.current?.(new We.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Vt=(0,v.useCallback)(()=>{Fr("retrying"),oo(L=>L+1)},[]);(0,v.useEffect)(()=>{Fr("loading"),oo(0),An.current=!1},[c]),(0,v.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:We.SDK_VERSION,checkout_type:Le,checkout_layout:ot,billing_api_url:O})},[ot,Le,O]);let tt=(0,v.useMemo)(()=>r?(0,ft.serializeCreateParams)(r,!0):"",[r]),Lt=(0,v.useMemo)(()=>br===tt?Ur:void 0,[Ur,br,tt]),pr=(0,v.useMemo)(()=>r?Hi(r,Lt):void 0,[r,Lt]),Br=j??pr?.checkoutMode??"full",Qt=(0,v.useMemo)(()=>pr?{...pr,checkoutMode:Br}:void 0,[pr,Br]);(0,v.useEffect)(()=>{sr(void 0),Hr(tt),dr.current=void 0,cr.current=null,Yt(!1)},[tt]),(0,v.useEffect)(()=>{Zt(te)},[te]);let vn=(0,v.useCallback)((L,N,ne)=>{(0,Ze.invokeMerchantCallback)(()=>{Me.current?.(wr(L,N,ne))})},[]),$n=(0,v.useCallback)(async(L,N)=>{Zt(null),Kt(null),Nr(!1),Mt("processing");let ne=N?.sessionId??L.id,we=L.clientSecret||t,Rt=nc(L),er=xt.current??pt.current,Ne=kr(er),le=er?null:hi(O,a,ye),q={log:Ue=>{Ne?Ne.log(Ue):le?.log(Ue)},error:Ue=>{Ne?Ne.error(Ue):le?.error(Ue)},terminal:Ue=>{Ne?Ne.terminal(Ue):le?.terminal(Ue)},performance:Ue=>{Ne?Ne.performance(Ue):le?.performance(Ue)},now:()=>Ne?.now()??le?.now()??0,elapsed:Ue=>Ne?.elapsed(Ue)??Math.max(0,(le?.now()??Ue)-Ue)},W=q.now(),ce=!!(N?.initialAutoProcessingError||N?.initialAutoProcessingPending),g=!1,y,G=()=>{g||(g=!0,ce=!0,y=q.now(),q.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),q.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ke=!1,Xe=()=>{ke||(ke=!0,q.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),q.performance({stage:"processing",durationMs:q.elapsed(W),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),y!==void 0&&q.performance({stage:"recovery",durationMs:q.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}))};q.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),mt.current=!0;try{q.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{mt.current=!1}ct({class:"lifecycle",name:"payment.processing.started",provider:Rt}),ce&&G();let yt;try{let Ue=xl(N?.initialAutoProcessingError),Be=N?.initialAutoProcessingError?.type==="3ds_required"&&!N.initialAutoProcessingError.threeDSecureToken&&N.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:N.initialAutoProcessingError.nextActionRedirectUrl}:null,it,kt=Et=>(G(),Pr(A=>Ho(Et,{billingApiUrl:O,sessionId:ne,nonce:we,session:L,signal:A})));if(Be)it=await kt(Be);else if(Ue)G(),Ue.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&tc({sessionId:ne,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),it=await Pr(Et=>ri(Ue,{flopay:xt.current,paypalFlopay:pt.current,attempt3DS:N?.attempt3DS,billingApiUrl:O,sessionId:ne,session:L,telemetry:!1,signal:Et})),Ue.type==="paypal_redirect_required"&&hs();else if(N?.initialAutoProcessingPending){let Et=N.initialAutoProcessingPending,A=new ro.PaymentAPI(O,{telemetry:!1}),ge=await Pr(oe=>A.waitForCheckoutSessionCompletion(Et.sessionId,{initialDelayMs:Et.retryAfterMs,nonce:we,statusUrl:Et.statusUrl,signal:oe})),Je=lo(ge,L),rt=ge.autoProcessingError?.type==="3ds_required"&&ge.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ge.autoProcessingError.nextActionRedirectUrl}:null;if(rt)it=await kt(rt);else{if(!Jn(Je))throw No(Je);it=Xn(Je,ne)}}else{if(N?.initialAutoProcessingError)throw qn(N.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:N.initialAutoProcessingError.checkoutMethod});if(N?.fromCreateSession)return N?.fallbackToFull&&(Ht("full"),rc("full")),!1;{let Et=await Ko({billingApiUrl:O,sessionId:ne,session:L,nonce:we,telemetry:!1});Et.type==="success"?it=Et.result:Et.type==="next_action_required"?it=await kt(Et):(G(),Et.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&tc({sessionId:ne,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),it=await Pr(A=>ri(Et,{flopay:xt.current,paypalFlopay:pt.current,attempt3DS:N?.attempt3DS,billingApiUrl:O,sessionId:ne,session:L,telemetry:!1,signal:A})),Et.type==="paypal_redirect_required"&&hs())}}ne&&(0,_n.markSessionRecentlyCompleted)(ne),Xe(),ce&&(q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),q.terminal({outcome:it.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Nr(it.status==="authorized"),Mt("success"),await Ta(600),yt=()=>Z.current?.(it)}catch(Ue){let Be=so(Sa(Ue),ne);if(Be.code==="three_ds_aborted")return!1;let it=Be.checkoutMethod??ba;Zt(Be.message),Kt(Be.message),Nr(!1),N?.fallbackToFull&&(q.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ht("full"),rc("full")),Xe();let kt=Be.statusCode===void 0?void 0:(0,We.telemetryStatusClass)(Be.statusCode,"unknown"),Et=kt==="4xx"?{requestCategory:"process_payment",statusClass:kt}:{},A=kt===void 0||kt==="4xx";if(A&&(Be.telemetryOutcome==="payment_declined"||!!(Be.declineCode||Be.code?.toLowerCase().includes("declin"))))q.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Et});else if(A&&(Be.telemetryOutcome==="validation_rejected"||Be.type==="validation_error"))q.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Et});else{let rt=(0,We.classifyTelemetryFailure)(Ue,ce?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),oe=Be.telemetryRequestCategory??"process_payment";mt.current=!0;try{q.error({...rt,...Be.telemetryFailureCategory?{failureCategory:Be.telemetryFailureCategory}:{},stage:ce?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:oe})}finally{mt.current=!1}ct({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:oe,provider:Rt})}return(0,Ze.invokeMerchantCallback)(()=>At.current?.(Be)),vn(it,Be,{code:Be.code,declineCode:Be.declineCode}),Mt("error"),await Promise.allSettled([Ta(400),N?.ensureProvidersReady?N.ensureProvidersReady():Promise.resolve()]),ce&&(q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Xe(),le&&Ma(le),Mt(null),Kt(null)}return(0,Ze.invokeMerchantCallback)(yt),!0},[vn,ct,t,O,Pr,a,ye]);(0,v.useEffect)(()=>{if(typeof window>"u"||qr.current)return;let L=new URLSearchParams(window.location.search),N=L.get("payment_intent_client_secret");if(!N)return;let ne=Xd();ne&&(qr.current=!0,(async()=>{let we,Rt=0;Zt(null),Kt(null),Mt("processing"),Lr(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new We.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:er,paypalFlopay:Ne}=await es({publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey,billingApiUrl:O,locale:l,telemetry:a});we=kr(Ne??er),we?.setCheckoutContext(ye),Rt=we?.now()??0,we?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),we?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let le=(Ne??er)?.getRawProvider();if(!le)throw Object.assign(new We.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:q,error:W}=await le.retrievePaymentIntent(N);if(W)throw Object.assign(new We.FloPayError(W.message??"Failed to retrieve PayPal payment status.","api_error",{code:W.code}),{checkoutMethod:"paypal"});let ce=hl(q?.status);if(!q||ce==="failed")throw Object.assign(new We.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let g=typeof q.payment_method=="string"?q.payment_method:q.payment_method?.id,y=ce;if(ne.sessionId){let Xe=(await new ro.PaymentAPI(O,{telemetry:!1}).getUnifiedCheckoutSession(ne.sessionId)).data.session;if(Xe&&Xe.status!=="complete"){let yt=await Ko({billingApiUrl:O,sessionId:ne.sessionId,session:Xe,telemetry:!1,tokenizedData:{id:g??q.id,type:"card",threeDSecureActionResultTokenId:q.id,isPaypal:!0}});if(yt.type!=="success")throw Object.assign(new We.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});y=yt.result.status}}ne.sessionId&&(0,_n.markSessionRecentlyCompleted)(ne.sessionId),we?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),we?.performance({stage:"redirect_resume",durationMs:we.elapsed(Rt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),we?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Mt("success"),await Ta(600),(0,Ze.invokeMerchantCallback)(()=>Z.current?.({status:y,paymentIntentId:q.id,paymentMethodId:g,checkoutMethod:"paypal"}))}catch(er){let Ne=so(Sa(er),ne.sessionId),le=Ne.checkoutMethod??"paypal",q=!!(Ne.declineCode||Ne.code?.toLowerCase().includes("declin"));if(we)we.performance({stage:"redirect_resume",durationMs:we.elapsed(Rt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),q?we.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):we.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(q){let W=hi(O,a,ye);W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ma(W)}else ys(O,a,ye,"REDIRECT_RESUME_FAILED","redirect_resume");Zt(Ne.message),Kt(Ne.message),(0,Ze.invokeMerchantCallback)(()=>At.current?.(Ne)),vn(le,Ne,{code:Ne.code,declineCode:Ne.declineCode}),Mt("error"),await Ta(400)}finally{hs(),Jd(),Mt(null),Kt(null),Lr(!1)}})())},[vn,l,O,a,ye]);let Fn=(0,v.useRef)(null),jr=(0,v.useMemo)(()=>Qt?(0,ft.serializeCreateParams)(Qt):"",[Qt]),ao=(0,v.useRef)(Qt);ao.current=Qt,(0,v.useEffect)(()=>{Bt(e??"")},[e]),(0,v.useEffect)(()=>{zr.current=!1,Zt(te),Kt(null),Nr(!1),Mt(null)},[jr,te,e]);async function cn(L,N,ne){let we=hi(O,a,ye),Rt=new ro.PaymentAPI(O,{telemetry:!1}),er=!1;try{let Ne=L.idempotencyKey===void 0?void 0:(0,We.resolveIdempotencyKey)(L.idempotencyKey),le=(0,ft.readCachedInlineSession)(N,ne),q=(0,ft.readCachedInlineIdempotencyKey)(N,ne);le?.canonicalIdentity===ne&&q&&q.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(N,ne,q.idempotencyKey),q={...q,canonicalIdentity:ne});let W=Ne??(q?.canonicalIdentity===ne?q.idempotencyKey:void 0),ce,g=!1;we.log({name:le?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let y=le?.sid??null,G=null,ke,Xe,yt=!1;if(y)try{G=await Rt.getUnifiedCheckoutSession(y,le?.nonce),le&&le.canonicalIdentity===void 0&&((0,ft.legacyCachedSessionMatchesDraft)(G.data.session,L)?((0,ft.persistCachedInlineSession)(N,ne,y,le.nonce??G.data.session?.clientSecret),q&&q.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(N,ne,q.idempotencyKey),W??(W=q.idempotencyKey))):((0,ft.clearCachedInlineCheckout)(N,ne),q=null,W=Ne,y=null,G=null));let Be=G?.data.session?.status,it=G?.data.session,kt=it?.clientSecret||le?.nonce;if(y&&it?.buyerIdentified===!1&&kt&&(Xe=Lo(Rt,y,kt,L.account)),y&&G&&Be==="complete"){if((0,_n.wasSessionRecentlyCompleted)(y))return{sid:y,result:G};(0,ft.clearCachedInlineCheckout)(N,ne),y=null,G=null,g=!0}}catch{we.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),le?.canonicalIdentity===void 0?((0,ft.clearCachedInlineCheckout)(N,ne),W=Ne):(0,ft.clearCachedInlineSession)(N,ne),y=null}if(!y){!Ne&&(g||!W)&&(W=(0,We.resolveIdempotencyKey)(),ce=W),W&&(0,ft.persistCachedInlineIdempotencyKey)(N,ne,W);let Be=we.now(),it=0;we.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let kt={...L,idempotencyKey:W,avsCheck:!!de,avsConfig:typeof de=="object"?de:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ps(H,ie)};Object.defineProperty(kt,ro.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ge=>{it=Math.max(it,ge)}}});let Et=()=>{Ql(we,"session_create",Be,it)},A=ge=>{ec(we,ge,"session_create",Be,it)&&ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,We.isDetachedSessionEligible)(kt)){let ge=await Rt.createDetachedSession(kt);ge.claimed.catch(()=>{}),G=ge.shell,y=ge.sessionId,Xe=ge.claim;let Je=we.now();we.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ke=ge.claimed.then(rt=>{let oe=rt.data.session?.id??ge.sessionId;return oe&&(0,ft.persistCachedInlineSession)(N,ne,oe,rt.data.session?.clientSecret??ge.nonce),Ql(we,"session_claim",Je),Et(),rt},rt=>{throw(0,ft.clearCachedInlineSession)(N,ne),ec(we,rt,"session_claim",Je,0)&&ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),rt}).finally(()=>Ma(we)),ke.catch(()=>{}),er=!0,we.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),we.performance({stage:"session_shell",durationMs:we.now()-Be,durationMode:"machine",requestCategory:"session_create",attempt:it,statusClass:"2xx",paymentMethodCategory:"card"})}else G=await Rt.createAndFetchSession(kt),Et()}catch(ge){throw A(ge),ge}y=G.data.session?.id??y??"",y&&!ke&&(0,ft.persistCachedInlineSession)(N,ne,y,G.data.session?.clientSecret)}let Ue=G?.data.session;return!Xe&&y&&Ue?.buyerIdentified===!1&&Ue.clientSecret&&(Xe=Lo(Rt,y,Ue.clientSecret,L.account)),{sid:y??"",result:G,sdkGeneratedIdempotencyKey:ce,...ke?{claimed:ke}:{},...Xe?{claim:Xe}:{},...yt?{claimRequiresIdentity:!0}:{}}}finally{er||Ma(we)}}let Hn=(0,v.useRef)(cn);Co(()=>{Hn.current=cn},[cn]);let en=(0,v.useCallback)(async(L,N)=>{let ne=ao.current;if(!ne)throw new We.FloPayError("createSession is required to bootstrap checkout.","validation_error");let we=Hi(ne,L),Rt=(0,ft.serializeCreateParams)(we),er=(0,ft.hashCreateParams)(we),Ne=Pi.get(Rt);if(!Ne){let W={canonicalIdentity:Rt,promise:Hn.current(we,er,Rt),consumers:0,settled:!1};Ne=W,Pi.set(Rt,W);let ce=()=>{W.settled=!0,Zl(Rt,W)};W.promise.then(ce,ce)}Ne.consumers+=1;let le=!1,q=()=>{le||(le=!0,Ne.consumers-=1,Zl(Rt,Ne))};N?.(q);try{let W=await Ne.promise;Fn.current=Rt,L&&(Hr(tt),sr(Ue=>yl(Ue,L)));let{sid:ce,result:g,claimed:y,claim:G,claimRequiresIdentity:ke}=W;if(dr.current=G,Yt(ke===!0),et(g),g.data.session&&Ae(g.data.session),ce&&Bt(ce),y){Ir.current+=1;let Ue=Ir.current;cr.current=y,Gt(!0),y.then(Be=>{Ir.current===Ue&&(cr.current===y&&(cr.current=null),et(Be),Be.data.session&&Ae(Be.data.session),Gt(!1),Yt(!1))},Be=>{Ir.current===Ue&&(cr.current===y&&(cr.current=null),Gt(!1),Yt(!1),K(Be instanceof We.FloPayError?Be:new We.FloPayError(Be instanceof Error?Be.message:"Failed to create session","api_error")))})}else Ir.current+=1,cr.current=null,Gt(!1),Yt(!1);let{flopay:Xe,paypalFlopay:yt}=await gs(g,{billingApiUrl:O,locale:l,telemetry:a});return Ot(Xe,yt),se(!1),W}catch(W){throw Fn.current===Rt&&(Fn.current=null),W}finally{N||q()}},[tt,Ot,l,O,a]),Cn=(0,v.useRef)($n);Cn.current=$n;let Bn=(0,v.useRef)(en);Bn.current=en;let Nt=(0,v.useCallback)(async L=>{if(!Qd(L)||dt)return{sessionId:He,session:z};wt(!0);try{let N=await en(L);return{sessionId:N.sid,session:N.result.data.session??null}}finally{wt(!1)}},[en,dt,He,z]),tn=(0,v.useCallback)(async L=>{let N=dr.current;if(!N)return;let ne=Ir.current,we=await N(L);Ir.current===ne&&(et(we),we.data.session&&Ae(we.data.session))},[]),rn=(0,v.useCallback)(async()=>{await cr.current},[]),Gr=(0,v.useCallback)(async()=>(await rn(),{proceed:!0}),[rn]);(0,v.useEffect)(()=>{let L=!1,N,ne=++Ce.current;jt(),K(null),xr(0);let we=()=>{L=!0,Ce.current===ne&&(Ce.current+=1,jt())},Rt=ao.current;if(jr&&Rt)return Ht(Br),se(!1),Fn.current===jr?we:(Ae(fl(Rt,j)),(async()=>{let le=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),q=Br==="auto"&&!zr.current&&!le;q&&(Zt(null),Kt(null),Mt("processing"));try{let W=await Bn.current(void 0,G=>{N=G}),ce=W.result.data.session??null;Xt.current=Qi(W.result);let g=fs(W.result),y=(0,_n.wasSessionRecentlyCompleted)(W.sid||ce?.id);if(!L&&q&&ce&&!g&&!y){zr.current=!0,await Kd(jr,W.sdkGeneratedIdempotencyKey,()=>Cn.current(ce,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:W.result.autoProcessingError,initialAutoProcessingPending:W.result.autoProcessingPending,autoProcessingAttempted:W.result.autoProcessingAttempted,sessionId:W.sid||ce.id}));return}!L&&q&&((g||y)&&(zr.current=!0),Mt(null),Kt(null))}catch(W){if(L)return;let ce=Ha(W);if(q&&ce==="session_auto_completed"){zr.current=!0,Mt("success"),await Ta(600),L||((0,Ze.invokeMerchantCallback)(()=>{Z.current?.({status:"succeeded"})}),Mt(null),Kt(null));return}q&&(Mt(null),Kt(null));let g=W instanceof We.FloPayError?W:new We.FloPayError(W instanceof Error?W.message:"Failed to create session","api_error");K(g)}finally{N?.(),N=void 0}})(),()=>{we(),N?.()});se(!0);async function er(){let le=!1,q=null;try{let W=new ro.PaymentAPI(O,{telemetry:!1}),ce=await W.getUnifiedCheckoutSession(c,t);if(q=ce,L)return;et(ce);let g=ce.data.session??null;if(Ae(g),!g)throw new We.FloPayError("No session data returned","api_error");let y=g.checkoutMode;if(y==="setup")throw new We.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(g.status==="authorized"){se(!1),(0,Ze.invokeMerchantCallback)(()=>{Z.current?.(Xn(g,c)),vr.current?.(g.successUrl??"")});return}if(g.status==="complete"){se(!1),(0,Ze.invokeMerchantCallback)(()=>{vr.current?.(g.successUrl??"")});return}if(g.status==="expired")throw $a(g);le=!0;let G=j??y??"full";Ht(G),Ir.current+=1;let ke=g.clientSecret||t;dr.current=g.buyerIdentified===!1&&ke?Lo(W,c,ke,{...g.customer?.id?{userId:g.customer.id}:{}}):void 0,Gt(!1),Yt(!1);let Xe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),yt=fs(ce);if(G==="auto"&&!zr.current&&!Xe&&!yt){zr.current=!0;let Ue=Ne(ce);try{if(await Cn.current(g,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Ue,sessionId:c||g.id}),L)return;await Ue,L||se(!1);return}catch{if(L)return;await Ue,L||se(!1);return}}await Ne(ce),L||se(!1)}catch(W){if(L)return;let ce=ml(W,le);if(le&&ct({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ce){let{errorCode:y,stage:G,...ke}=ce;ys(O,a,ye,y,G,ke)}if(ce?.stage==="provider_load"&&(j??q?.data.session?.checkoutMode??"full")==="full"&&pl(q,x,f)){let y=Yd({billingApiUrl:O,locale:l,telemetry:a});Ct.current=y,Ot(y,null),xr(1),se(!1);return}let g=W instanceof We.FloPayError&&ce?.stage!=="provider_load"?W:ul();g!==W&&(0,Ze.invokeMerchantCallback)(()=>At.current?.(g)),K(g),se(!1)}}async function Ne(le){let{flopay:q,paypalFlopay:W,...ce}=await gs(le,{billingApiUrl:O,locale:l,telemetry:a});Xt.current={publishableKey:ce.publishableKey,paypalPublishableKey:ce.paypalPublishableKey},Ot(q,W),xr(0)}return er(),we},[j,jr,Br,U,t,x,f]);let bn=(0,v.useCallback)(async()=>{if(!_e||Ut!==1)return;let L=Ce.current;xr(2);try{let{flopay:N,paypalFlopay:ne}=await gs(_e,{billingApiUrl:O,locale:l,telemetry:a});if(Ce.current!==L)return;jt(),Ot(N,ne),xr(0)}catch(N){if(Ce.current!==L)return;let{errorCode:ne,stage:we,...Rt}=$i(N);ys(O,a,ye,ne,we,Rt)}},[jt,Ot,l,Ut,O,a,ye,_e]),bt=!!(c&&(z?.clientSecret||t)),_r=Tt||!bt,mr=(0,v.useCallback)(async()=>{if(!(Tt||!bt||!z)){Lr(!0),Zt(null);try{await $n(z,{attempt3DS:!0,fallbackToFull:!0,sessionId:c||z.id})}finally{Lr(!1)}}},[c,Tt,bt,$n,z]),Yr=(0,We.resolveDirectPaypalConfig)(_e?.data.paypal,J),mo=fs(_e),Sn=(0,v.useMemo)(()=>{if(!(!_e||!z||!_e.data.stripe?.publishableKey))return{billingApiUrl:O}},[_e,z,O]),Kn=!!(r&&!H&&ie==="buttons"&&De&&Br==="full"),nn=!!(c&&((0,We.isMountableVaultBlock)(z?.vault)||(0,Rn.canRecoverHostedCardForm)(z))),Tr=(0,v.useMemo)(()=>({session:z,loading:V,error:R,checkoutMode:ir,inlineSessionDraft:Qt,applyInlineSessionPatch:Kn?Nt:void 0,inlineSessionPatchProcessing:dt,claimPending:lr,claimRequiresIdentity:hr,claimBuyerIdentity:tn,waitForDataAttachment:rn}),[z,V,R,ir,Qt,Kn,Nt,dt,lr,hr,tn,rn]),Dn=!!r&&ie==="buttons"&&!mo&&!nn&&(!at||!Sn),Dr=$r?(0,F.jsx)(Zr,{status:$r,errorMessage:xn,authorized:ln}):null;if(V&&!nn){if(p)return(0,F.jsxs)(F.Fragment,{children:[p,Dr]});if(ie==="buttons"){let L=Pe?.buttonsLayout?.cardButton?.borderRadius??Pe?.appearance.variables?.borderRadius??8,N=ne=>(0,F.jsx)("div",{style:{height:ne,borderRadius:L,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[x&&N(Jo),f&&(b||Ie)&&N(Jo),f&&N(Jo),(0,F.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Dr]})}return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,F.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,F.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Dr]})}return R?m?(0,F.jsx)(En.Provider,{value:Tr,children:m(R)}):(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:R.message})}):Dn?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsx)(tu,{onButtonClick:Ge,showPayPal:x,showStripe:f,showApplePay:b,showGooglePay:Ie,theme:me,buttonsTheme:ue,buttonsStyles:xe,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B})}),Dr]}):mo&&z&&Yr?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsxs)("div",{className:ze,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ar&&(0,F.jsx)(Wo,{icon:!1,children:Ar}),Ye==="retrying"&&(0,F.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ye==="exhausted"&&(0,F.jsxs)("div",{role:"alert",children:[(0,F.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,F.jsx)("button",{type:"button",onClick:Vt,children:"Retry PayPal"})]}),Ye!=="exhausted"&&(0,F.jsx)("div",{"aria-hidden":Ye==="retrying"?!0:void 0,style:Ye==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,F.jsx)(Il,{sessionId:c,nonce:z.clientSecret||void 0,billingApiUrl:O,email:z.customer?.email||Qt?.account?.email,billingName:[z.customer?.firstName,z.customer?.lastName].filter(Boolean).join(" ")||[Qt?.account?.firstName,Qt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:tn,clientId:Yr.clientId,environment:Yr.environment,currency:(z.currency??"usd").toUpperCase(),isSubscription:z.mode==="subscription",providerObjectType:Yr.providerObjectType,approvalPresentation:Yr.approvalPresentation,existingOrderId:Yr.existingOrderId,onComplete:h,onErrorChange:Zt,onDecline:E,onCancel:Y,onButtonClick:Ge,runBeforeButtonClick:Gr,onInitializationStateChange:$,allowAutomaticRetry:ur===0,session:z,telemetry:a,telemetryContext:ye,onInstrument:Ve,debug:_},`${be}:paypal-init-${ur}`)})]})}),Dr]}):ir==="confirm"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsx)(va,{flopay:at,paypalFlopay:T,options:Sn??{billingApiUrl:O},onInstrument:Ve,children:(0,F.jsxs)("div",{className:ze,children:[Ar&&(0,F.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ar}),Te?Te({onConfirm:mr,isProcessing:_r}):(0,F.jsx)("button",{type:"button",onClick:mr,disabled:_r,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:_r?"not-allowed":"pointer",opacity:_r?.6:1},children:Tt?"Processing...":je??"Confirm Purchase"})]})},be)}),Dr]}):(!at||!Sn)&&!(nn&&ir==="full")?(0,F.jsx)(F.Fragment,{children:Dr}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsxs)(va,{flopay:at,paypalFlopay:T,options:Sn??{billingApiUrl:O},onInstrument:Ve,children:[Ut===1&&(0,F.jsx)("button",{type:"button",onClick:bn,children:"Retry payment methods"}),H?(0,F.jsxs)(F.Fragment,{children:[Ar&&(0,F.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ar}),(0,F.jsx)(eu,{sessionId:c,nonce:z?.clientSecret||void 0,billingApiUrl:O,session:z,submitLabel:nt,walletPresentation:P,children:H})]}):(0,F.jsx)(fi,{sessionId:c,nonce:z?.clientSecret||void 0,telemetry:a,email:z?.customer?.email||Qt?.account?.email,userId:z?.customer?.id||Qt?.account?.userId,firstName:z?.customer?.firstName||Qt?.account?.firstName,lastName:z?.customer?.lastName||Qt?.account?.lastName,totalAmount:z?Math.round((0,We.buildCheckoutDisplayData)(z).total*100):0,currency:z?.currency?.toLowerCase()??"usd",onComplete:h,onError:w,onDecline:E,onCancel:Y,error:Ar,onErrorChange:Zt,showPayPal:x,showStripe:f,walletPresentation:P,enabledPaymentMethods:Ut?[]:pe??_e?.data.stripe?.enabledPaymentMethods??z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:_e?.data.stripe?.enabledPaymentMethodCountries,showApplePay:b,showGooglePay:Ie,layout:ie,theme:me,buttonsTheme:ue,buttonsStyles:xe,appearance:ut,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B,onButtonClick:Ge,onBeforeButtonClick:De,onBuyerIdentityReady:tn,enableAVS:de,...re?{cardFieldOrder:re}:{},...X?{cardPreFormSlot:X}:{},avsLayout:Oe,country:z?.customer?.country,city:z?.customer?.city,state:z?.customer?.state,onCountryChange:I,onZipChange:ee,avsCheck:!!de,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Ps(H,ie),className:ze,submitLabel:nt,directPaypal:Yr,isSubscription:z?.mode==="subscription",session:z,dataAttachmentPending:lr,dataAttachmentRequiresIdentity:hr,debug:_})]},be)}),Dr]})}function eu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:i,children:l}){return(0,F.jsx)(F.Fragment,{children:v.default.Children.map(l,p=>{if(!v.default.isValidElement(p))return p;let m=p.props,h={};return m.sessionId||(h.sessionId=e),!m.nonce&&t&&(h.nonce=t),m.billingApiUrl||(h.billingApiUrl=r),m.submitLabel===void 0&&a!==void 0&&(h.submitLabel=a),m.walletPresentation===void 0&&(h.walletPresentation=i),n?.customer&&(m.email||(h.email=n.customer.email),m.userId||(h.userId=n.customer.id),m.firstName||(h.firstName=n.customer.firstName),m.lastName||(h.lastName=n.customer.lastName)),Object.keys(h).length===0?p:v.default.cloneElement(p,h)})})}function tu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:i,buttonsTheme:l,buttonsStyles:p,cardButtonContent:m,cardBackButtonContent:h,cardTitleContent:w}){let[S,E]=(0,v.useState)(!1),Y=(0,v.useMemo)(()=>(0,We.resolveTheme)(i),[i]),I=(0,v.useMemo)(()=>{let P=Y?.buttonsLayout??(0,We.resolveButtonsLayoutTheme)(l);return p?{...P,...p,cardButton:{...P.cardButton,...p.cardButton},cardFormContainer:{...P.cardFormContainer,...p.cardFormContainer},backButton:{...P.backButton,...p.backButton},backButtonIcon:{...P.backButtonIcon,...p.backButtonIcon},submitButton:{...P.submitButton,...p.submitButton},title:{...P.title,...p.title}}:P},[Y,l,p]),ee=Y?.buttonsLayout?.cardButton?.borderRadius??Y?.appearance.variables?.borderRadius??8,x=P=>(0,F.jsx)("div",{style:{height:P,borderRadius:ee,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),f=m===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(S){let P=I.cardInputBorder??"#e5e7eb",pe=I.cardInputBackground??"white",b=Bo(h),Ie=Bo(w);return(0,F.jsxs)("div",{style:{backgroundColor:I.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...I.cardFormContainer},children:[(0,F.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,F.jsxs)("button",{type:"button",onClick:()=>E(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:b?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...I.backButton},children:[(0,F.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...I.backButtonIcon},children:(0,F.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,F.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,F.jsx)(Oo,{content:h})]}),Ie?(0,F.jsx)("div",{style:{flex:1}}):(0,F.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...I.title},children:(0,F.jsx)(ua,{content:w})})]}),(0,F.jsx)("div",{style:{backgroundColor:pe,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsxs)("div",{style:{display:"flex"},children:[(0,F.jsx)("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,F.jsx)("div",{style:{backgroundColor:pe,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...I.submitButton,opacity:.5}}),(0,F.jsx)("style",{children:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}return(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&M(Jo),r&&(n||a)&&M(Jo),r&&(0,B.jsx)("button",{type:"button",onClick:()=>{e?.("card"),E(!0)},style:{width:"100%",...f,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:I.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...I.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:(0,B.jsx)(Do,{content:p})}),(0,B.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var yn=require("react/jsx-runtime"),ru=44;function oc(e){return new Promise(t=>setTimeout(t,e))}function nu(e,t){return e instanceof mn.FloPayError?e:new mn.FloPayError(e instanceof Error?e.message:t,"api_error")}function ou(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function au(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function ac({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:i,products:l,items:u,subscriptions:p,account:P,successUrl:w,cancelUrl:S,couponCodes:E,tagsData:K,utmMetadata:I,billingApiUrl:X,locale:M,theme:f,appearance:v,buttonsTheme:ye,buttonsStyles:b,onSuccess:Te,onError:T,onDecline:se,children:me,disabled:pe=!1,type:Fe="button",style:dt,...He}){let D=(0,gt.useMemo)(()=>(0,mn.resolveBillingApiUrl)(X),[X]),St=(0,gt.useMemo)(()=>au({createSession:r,clientId:i,products:l,items:u,subscriptions:p,account:P,successUrl:w,cancelUrl:S,couponCodes:E,tagsData:K,utmMetadata:I}),[P,S,i,E,r,l,u,p,w,K,I]),[Ye,Oe]=(0,gt.useState)(!1),[ge,Q]=(0,gt.useState)(null),[G,Be]=(0,gt.useState)(null),[ze,Xe]=(0,gt.useState)(!1),[ne,ee]=(0,gt.useState)(null),[le,V]=(0,gt.useState)(null),Ve=(0,gt.useRef)(!0),Ae=(0,gt.useRef)(null),he=(0,gt.useRef)(le),N=(0,gt.useRef)(Te),Ce=(0,gt.useRef)(T),ut=(0,gt.useRef)(se),Le=(0,gt.useCallback)(k=>ei(Ae,async A=>{try{return await k(A)}catch(We){throw A.aborted?$o(We):We}}),[]);(0,gt.useEffect)(()=>{he.current=le},[le]),(0,gt.useEffect)(()=>{N.current=Te},[Te]),(0,gt.useEffect)(()=>{Ce.current=T},[T]),(0,gt.useEffect)(()=>{ut.current=se},[se]),(0,gt.useEffect)(()=>(Ve.current=!0,()=>{Ve.current=!1,Ae.current?.abort()}),[]),(0,gt.useEffect)(()=>{if(typeof window>"u")return;let k=A=>{A.key==="Escape"&&V(null)};return window.addEventListener("keydown",k),()=>{window.removeEventListener("keydown",k)}},[]);let ot=(0,gt.useCallback)((k,A=ba)=>{ut.current?.(hr(A,k,{code:k.code,declineCode:k.declineCode}))},[]),Me=(0,gt.useCallback)(async k=>{Ve.current&&(Be(null),Xe(k.result.status==="authorized"),Q("success"),await oc(600),Ve.current&&(0,Qe.invokeMerchantCallback)(()=>N.current?.(k)))},[]),tt=(0,gt.useCallback)(async(k,A)=>{Ve.current&&(Ce.current?.(k),A?.emitDecline&&ot(k,A.method),Be(k.message),Xe(!1),Q("error"),await oc(400))},[ot]),at=(0,gt.useCallback)(async(k,A,We)=>{let ke=k.data.session??null;if(!ke)throw so(new mn.FloPayError("No session data returned","api_error"),A);let ct=ke.clientSecret||t;if(Jn(ke)){await Me({result:Xn(ke,A),session:ke,sessionId:ke.id||A,autoCompleted:!1});return}if(ke.status==="expired")throw so($a(ke),ke.id||A);try{if(k.autoProcessingPending){let J=k.autoProcessingPending,q=new Ci.PaymentAPI(D),ue=await Le(xe=>q.waitForCheckoutSessionCompletion(J.sessionId,{initialDelayMs:J.retryAfterMs,nonce:ct,statusUrl:J.statusUrl,signal:xe})),m=lo(ue,ke),Z=ue.autoProcessingError?.type==="3ds_required"&&ue.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ue.autoProcessingError.nextActionRedirectUrl}:null;if(Z&&A&&ct){let xe=await Le(rt=>Ho(Z,{billingApiUrl:D,sessionId:A,nonce:ct,session:ke,signal:rt,telemetry:!0}));await Me({result:xe,session:ke,sessionId:ke.id||A,autoCompleted:!1});return}if(ue.autoProcessingError)throw Un(ue.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:ue.autoProcessingError.checkoutMethod});if(!Jn(m))throw No(m);await Me({result:Xn(m,A),session:m,sessionId:m.id||A,autoCompleted:!1});return}if(k.autoProcessingError){let J=k.autoProcessingError.nextActionRedirectUrl;if(k.autoProcessingError.type==="3ds_required"&&J&&A&&ct){let q=await Le(xe=>Al({billingApiUrl:D,sessionId:A,nonce:ct,nextActionRedirectUrl:J,signal:xe}));if(q.status==="declined")throw Un({type:q.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:q.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:k.autoProcessingError.checkoutMethod});let m=await new Ci.PaymentAPI(D).waitForCheckoutSessionCompletion(A,{initialDelayMs:0,nonce:ct}),Z=lo(m,ke);if(!Jn(Z))throw Un({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:k.autoProcessingError.checkoutMethod});await Me({result:Xn(Z,A),session:Z,sessionId:Z.id||A,autoCompleted:!1});return}throw Un(k.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:k.autoProcessingError.checkoutMethod})}if(We?.fromCreateSession&&k.autoProcessingAttempted===!0)throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let g=await Ko({billingApiUrl:D,sessionId:A??ke.id,session:ke,nonce:ct});if(g.type==="next_action_required"&&ct){let J=A??ke.id,q=await Le(ue=>Ho(g,{billingApiUrl:D,sessionId:J,nonce:ct,session:ke,signal:ue,telemetry:!0}));await Me({result:q,session:ke,sessionId:ke.id||J,autoCompleted:!1});return}if(g.type!=="success")throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Me({result:g.result,session:ke,sessionId:ke.id||A,autoCompleted:!1})}catch(g){let J=ke.id||A,q=so(Sa(g),J);if(q.code==="three_ds_aborted")return;if(q.code==="checkout_processing_timeout"){if(!Ve.current)return;ee(q.message),(0,Qe.invokeMerchantCallback)(()=>Ce.current?.(q));return}await tt(q,{emitDecline:!0,method:q.checkoutMethod??ba}),ou(q,J)&&J&&Ve.current&&V({sessionId:J,errorMessage:q.message,nonce:ct||void 0,payPalOrderId:q.orderId})}},[t,D,Le,tt,Me]),lr=(0,gt.useCallback)(async k=>{if(He.onClick?.(k),!(k.defaultPrevented||pe||Ye)){if(V(null),ee(null),e&&St){let A=new mn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await tt(A),Ve.current&&(Q(null),Be(null));return}if(!e&&!St){let A=new mn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await tt(A),Ve.current&&(Q(null),Be(null));return}Oe(!0),Be(null),Xe(!1),Q("processing");try{let A=new Ci.PaymentAPI(D);if(e){let We=await A.getUnifiedCheckoutSession(e,t);await at(We,e);return}try{let We=await A.createAndFetchSession({...St});await at(We,We.data.session?.id??null,{fromCreateSession:!0})}catch(We){if(Ha(We)==="session_auto_completed"){await Me({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw We}}catch(A){await tt(so(nu(A,"Automatic payment failed. Please try again."),e))}finally{Ve.current&&(Q(null),Be(null),Oe(!1))}}},[He.onClick,St,pe,Ye,t,at,D,e,tt,Me]),Bt=(0,gt.useCallback)(k=>{let A=he.current;V(null),N.current?.({result:k,session:null,sessionId:A?.sessionId??null,autoCompleted:!1})},[]),wt=(0,gt.useCallback)(k=>{Ce.current?.(k)},[]),Se=(0,gt.useCallback)(k=>{ut.current?.(k)},[]),x=(0,gt.useMemo)(()=>(0,mn.resolveTheme)(f),[f]),ht=(0,gt.useMemo)(()=>{let k=x?.buttonsLayout??(0,mn.resolveButtonsLayoutTheme)(ye);return b?{...k,...b,cardButton:{...k.cardButton,...b.cardButton}}:k},[x,ye,b]),pt=(0,gt.useMemo)(()=>{let k=x?.appearance;return v?k?{...k,...v,variables:{...k.variables,...v.variables}}:v:k},[v,x]),z=pt?.variables,we=z?.colorPrimary??"#4A49FF",Dt=z?.colorPrimaryHover??(0,ys.darkenHex)(we,.12),Ke=z?.borderRadius??"8px";return(0,yn.jsxs)(yn.Fragment,{children:[(0,yn.jsx)("button",{...He,type:Fe,onClick:lr,disabled:pe||Ye,"aria-busy":Ye,style:{width:"100%",...me===void 0?{boxSizing:"border-box",height:ru,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ht.cardButton,...ps({themeBundle:x,resolvedPrimaryColor:we,resolvedBorderRadius:Ke,submitButtonStyle:ht.submitButton,explicitPrimaryColor:z?.colorPrimary}),fontSize:ht.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:pe||Ye?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:pe||Ye?.6:1,...dt},onMouseEnter:k=>{He.onMouseEnter?.(k),!k.defaultPrevented&&!pe&&!Ye&&(x||z?.colorPrimary)&&(k.currentTarget.style.backgroundColor=Dt)},onMouseLeave:k=>{He.onMouseLeave?.(k),!k.defaultPrevented&&(x||z?.colorPrimary)&&(k.currentTarget.style.backgroundColor=we)},onMouseDown:k=>{He.onMouseDown?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(0.985)")},onMouseUp:k=>{He.onMouseUp?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(1)")},children:(0,yn.jsx)(Do,{content:me})}),ne&&(0,yn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ne}),ge&&(0,yn.jsx)(Hr,{status:ge,errorMessage:G,authorized:ze}),le&&(0,yn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:k=>{k.target===k.currentTarget&&V(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,yn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,yn.jsx)(vi,{sessionId:le.sessionId,nonce:le.nonce,checkoutMode:"full",billingApiUrl:D,locale:M,theme:f,...pt?{appearance:pt}:{},buttonsTheme:ye,buttonsStyles:b,initialErrorMessage:le.errorMessage,initialPayPalOrderId:le.payPalOrderId,cardTitleContent:null,onComplete:Bt,onError:wt,onDecline:Se})})})]})}var Si=require("@flopay/js/card-setup"),Lr=require("@flopay/shared"),qt=require("react");var bs=require("@flopay/shared"),iu=require("@flopay/shared");function bi(e){let t=(0,bs.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var qn=require("react/jsx-runtime"),xa=class extends Lr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function no(e,t={}){let r=e instanceof Lr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new xa(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:a,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function ic({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:i,appearance:l,buttonsStyles:u,loading:p=null,onReady:P,onComplete:w,onDecline:S,onCancel:E,onValidation:K,onError:I}){let[X,M]=(0,qt.useState)(null),[f,v]=(0,qt.useState)(null),[ye,b]=(0,qt.useState)(null),[Te,T]=(0,qt.useState)(null),[se,me]=(0,qt.useState)(null),pe=(0,qt.useRef)(!1),Fe=(0,qt.useRef)(!1),{vaultTheme:dt,surface:He,overlayTheme:D}=(0,qt.useMemo)(()=>bi({theme:a,appearance:l,buttonsStyles:u}),[a,l,u]),St=(0,qt.useMemo)(()=>(0,Ra.mergeCardSetupSurface)(He,i),[He,i]),Ye=(0,qt.useRef)(P),Oe=(0,qt.useRef)(I),ge=(0,qt.useRef)(w),Q=(0,qt.useRef)(S),G=(0,qt.useRef)(E),Be=(0,qt.useRef)(K),ze=(0,qt.useRef)(!1),Xe=(0,qt.useRef)(!1),ne=(0,qt.useRef)(0);return Ye.current=P,Oe.current=I,ge.current=w,Q.current=S,G.current=E,Be.current=K,(0,qt.useEffect)(()=>{let ee=ne.current+1;return ne.current=ee,()=>{queueMicrotask(()=>{ne.current===ee&&(ze.current||Xe.current||(Xe.current=!0,(0,Qe.invokeMerchantCallback)(()=>{G.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,qt.useEffect)(()=>{let ee=!0,le=(0,Lr.resolveBillingApiUrl)(r),V=new Si.PaymentAPI(le,{telemetry:n});return M(null),v(null),b(null),ze.current=!1,Xe.current=!1,(async()=>{try{if(!e.trim())throw new Lr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Lr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ve=await V.getUnifiedCheckoutSession(e,t);if(!ee)return;let Ae=Ve.data.session;if(!Ae||!(0,Lr.isCardSetupCheckoutSession)(Ae))throw new Lr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let he=Ae.vault;(0,Lr.isMountableVaultBlock)(he)||(he=await V.getVaultCapture(e,t));let N=(0,Lr.resolveVaultMountOptions)(he,{billingApiUrl:le,sessionId:e,nonce:t});if(!N)throw new Lr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!ee)return;v(N),M(new Si.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Ve){if(!ee)return;let Ae=no(Ve);ze.current=!0,b(Ae),(0,Qe.invokeMerchantCallback)(()=>Oe.current?.(Ae))}})(),()=>{ee=!1,V.destroy()}},[r,t,e,n]),(0,qt.useEffect)(()=>{if(!X)return;let ee=!1;Fe.current=!1,pe.current=!1;let le=X.on("submitting",()=>{pe.current=!0,me(null),T("processing")}),V=X.on("complete",he=>{ze.current=!0,pe.current=!1,T("success"),(async()=>(await new Promise(N=>setTimeout(N,600)),!Fe.current&&(Fe.current=!0,(0,Qe.invokeMerchantCallback)(()=>{ge.current?.({status:"succeeded",sessionId:e,...he.paymentMethod?{paymentMethod:he.paymentMethod}:{}})}),ee||T(null))))()}),Ve=X.on("decline",he=>{ze.current=!0,pe.current=!1,me(he.message??null),T("error"),(0,Qe.invokeMerchantCallback)(()=>{Q.current?.({status:"declined",sessionId:e,...he.declineReason?{reason:he.declineReason}:{},...he.message?{message:he.message}:{}})}),(async()=>(await new Promise(N=>setTimeout(N,400)),ee||T(null)))()}),Ae=X.on("challenge_dismissed",()=>{T(null)});return()=>{ee=!0,le(),V(),Ve(),Ae()}},[X,e]),ye?(0,qn.jsx)("div",{role:"alert",children:ye.message}):!X||!f?.html?(0,qn.jsx)(qn.Fragment,{children:p}):(0,qn.jsxs)(qn.Fragment,{children:[Te&&(0,qn.jsx)(Hr,{status:Te,errorMessage:se,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...D?{theme:D}:{}}),(0,qn.jsx)(co,{capture:X,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:dt,containerStyle:St,onReady:()=>{(0,Qe.invokeMerchantCallback)(()=>Ye.current?.())},onValidation:ee=>{(0,Qe.invokeMerchantCallback)(()=>Be.current?.(ee))},onError:ee=>{if(!ee)return;pe.current&&(pe.current=!1,me(ee),T("error"),setTimeout(()=>T(null),400));let le=no(new Error(ee),{code:"card_setup_widget_failed",retryable:!0});(0,Qe.invokeMerchantCallback)(()=>Oe.current?.(le))}})]})}var sc=require("@flopay/js/card-setup"),uo=require("@flopay/shared"),lc=require("@paypal/paypal-js"),wo=require("react");var dc=require("react/jsx-runtime");function cc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:i,telemetry:l,customer:{userId:u,email:p},onSubmitting:P,onConfirmed:w,onFailed:S,onAbandoned:E}){let K=(0,wo.useRef)(null),I=(0,wo.useRef)({onSubmitting:P,onConfirmed:w,onFailed:S,onAbandoned:E});I.current={onSubmitting:P,onConfirmed:w,onFailed:S,onAbandoned:E};let[X]=(0,wo.useState)(()=>(0,Ln.detectPayPalEnvironment)().inAppBrowser);return(0,wo.useEffect)(()=>{let M=!0,f,v=new sc.PaymentAPI(i,{telemetry:l}),ye={userId:u,email:p};return(async()=>{try{let b=await(0,lc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Te=K.current;if(!M||!Te)return;if(!b?.Buttons)throw new uo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let T=b.Buttons({createVaultSetupToken:async()=>{I.current.onSubmitting();let se=await v.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(se.provider!=="paypal"||se.providerObjectType!=="setup_token")throw new uo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return se.providerObjectId},onApprove:async se=>{let me=se.vaultSetupToken;if(!me)throw new uo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let pe=await v.processPayment(ye.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:me,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:ye});if(!pe.ok)throw new uo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:pe.status});M&&I.current.onConfirmed()},onCancel:()=>{M&&I.current.onAbandoned()},onError:se=>{if(!M)return;let{popupBlocked:me}=(0,be.classifyExternalMethodFailure)(se,{inAppBrowser:X,handoffObserved:!1});I.current.onFailed(me?new Error((0,be.buildExternalMethodRecoveryMessage)("PayPal",!0,X)):se,{code:me?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>T.close(),await T.render(Te)}catch(b){if(!M)return;I.current.onFailed(b,{code:"paypal_unavailable",retryable:!0})}})(),()=>{M=!1,f?.().catch(()=>{}),v.destroy()}},[i,e,r,p,t,X,a,n,l,u]),(0,dc.jsx)("div",{ref:K,"data-flopay-paypal-setup":""})}var pc=require("@flopay/js/card-setup"),po=require("@flopay/shared"),jn=require("@stripe/react-stripe-js"),yc=require("@stripe/stripe-js"),Nr=require("react");var Br=require("react/jsx-runtime"),mc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Ss=new Map;function su(e){let t=Ss.get(e);if(t)return t;let r=(0,yc.loadStripe)(e).catch(n=>{throw Ss.delete(e),n});return Ss.set(e,r),r}function lu(e){return e?(0,po.toStripeAppearance)(e):void 0}function cu(e){return(0,be.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function uc(e){return e==="paypal"?"PayPal":(0,po.getStripeMethodDisplayName)(e)}function du(){return typeof window>"u"?"":window.location.href}var uu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function fc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:i,appearance:l}=e,[u]=(0,Nr.useState)(()=>su(t)),p=(0,Nr.useMemo)(()=>{let P=lu(l),w=(0,po.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:i},r,"setup");return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:mc[r]?.types??[r],...w?{setupFutureUsage:w}:{},...P?{appearance:P}:{}}},[l,n,a,i,r]);return(0,Br.jsx)(jn.Elements,{stripe:u,options:p,children:(0,Br.jsx)(pu,{...e})})}function pu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,appearance:l,themeId:u,buttonsLayout:p,onSubmitting:P,onConfirmed:w,onDeclined:S,onFailed:E,onValidation:K,onUnavailable:I}){let X=(0,jn.useStripe)(),M=(0,jn.useElements)(),[f,v]=(0,Nr.useState)(!1),[ye,b]=(0,Nr.useState)("loading"),[Te,T]=(0,Nr.useState)(!1),[se,me]=(0,Nr.useState)(!1),pe=(0,Nr.useRef)(!1),[Fe]=(0,Nr.useState)(()=>(0,Ln.detectPayPalEnvironment)()),[dt,He]=(0,Nr.useState)(!1),D=(0,Nr.useCallback)((G,Be)=>{if((0,be.classifyExternalMethodFailure)(G,{inAppBrowser:Fe.inAppBrowser,handoffObserved:!1}).popupBlocked){He(!0),E(new Error((0,be.buildExternalMethodRecoveryMessage)(uc(e),!0,Fe.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}E(Be.message===void 0?G:new Error(Be.message),{code:Be.code,retryable:!0})},[Fe.inAppBrowser,e,E]),St=(0,Nr.useCallback)(async()=>{if(!(!X||!M||pe.current)){pe.current=!0,v(!0);try{let G=await M.submit();if(G.error){K(G.error.message??null);return}P();let Be=await new pc.PaymentAPI(a,{telemetry:i}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(Be.provider!=="stripe"||Be.intentKind!=="setup")throw new po.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let ze=await X.confirmSetup({elements:M,clientSecret:Be.clientSecret,confirmParams:{return_url:du()},redirect:"if_required"});if(ze.error){cu(ze.error)?S({...ze.error.decline_code||ze.error.code?{reason:ze.error.decline_code??ze.error.code}:{},...ze.error.message?{message:ze.error.message}:{}}):D(ze.error,{code:"payment_method_setup_provider_failed",message:ze.error.message??"The payment method could not be saved."});return}w()}catch(G){D(G,{code:"payment_method_setup_failed"})}finally{pe.current=!1,v(!1)}}},[a,t,M,e,n,w,S,P,K,D,r,X,i]),Ye=mc[e]?.wallet,Oe=Ye==="paypal"&&(0,Nn.resolveStripePayPalPresentation)(Fe,"auto",dt?"blocked":Fe.popupCapability)==="redirect",ge=l?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&Ye&&!Oe)return(0,Br.jsxs)(Br.Fragment,{children:[(0,Br.jsx)(Xo,{}),(0,Br.jsx)(ka,{state:ye,borderRadius:ge,children:(0,Br.jsx)(jn.ExpressCheckoutElement,{options:{...ii,paymentMethods:ai([e])},onReady:G=>{let Be=wa(G,[Ye]);b(Be),Be==="unavailable"&&I()},onLoadError:()=>{b("load_error"),I()},onConfirm:()=>{St()}})})]});let Q=uc(e);return(0,Br.jsxs)(Br.Fragment,{children:[Te?(0,Br.jsx)(oi,{method:e,themeId:u,hasNextStep:!0,highlighted:se,disabled:f,onClick:()=>me(G=>!G),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:ge}):null,(0,Br.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!se,style:se?{display:"flex",flexDirection:"column"}:uu,children:[(0,Br.jsx)(jn.PaymentElement,{options:{layout:si},onReady:()=>T(!0),onLoadError:()=>I(),onChange:G=>{G.complete&&K(null)}}),(0,Br.jsx)(li,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!X||!M||f||!se,onClick:()=>{St()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:p?.submitButton,children:f?"Saving\u2026":`Save ${Q}`})]})]})}var Aa=require("@flopay/js/card-setup"),mr=require("@flopay/shared"),Ge=Wi(require("react"),1);var Zo=require("@flopay/js/card-setup"),Cr=require("@flopay/shared");var sr=require("react/jsx-runtime"),yu=15,mu=2e3;function fu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function ws(e){return new Promise(t=>setTimeout(t,e))}async function gu(e,t,r){if(!t.trim())throw new mr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new mr.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,mr.isCardSetupCheckoutSession)(a))throw new mr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let i=(0,Cr.readSetupAdvertisement)(n);if(!(0,Cr.advertisesAnyMethod)(i)){let{skippedForMissingCurrency:l}=i,u=l.length>0?`FloPay: this setup session advertises only Stripe methods (${l.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new mr.FloPayError(u,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:i}}async function hu(e,t,r,n,a){let i=t.vault??null;(0,mr.isMountableVaultBlock)(i)||(i=await e.getVaultCapture(r,n));let l=(0,mr.resolveVaultMountOptions)(i,{billingApiUrl:a,sessionId:r,nonce:n});if(!l)throw new mr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return l}var wi=class extends Ge.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function gc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,theme:l="modern-light",containerStyle:u,appearance:p,buttonsStyles:P,loading:w=null,onReady:S,onComplete:E,onDecline:K,onCancel:I,onValidation:X,onError:M}){let[f]=(0,Ge.useState)(Zo.readSetupRedirectReturn),[v,ye]=(0,Ge.useState)(null),[b,Te]=(0,Ge.useState)(!1),[T,se]=(0,Ge.useState)(null),[me,pe]=(0,Ge.useState)(null),[Fe,dt]=(0,Ge.useState)(null),[He,D]=(0,Ge.useState)(null),[St,Ye]=(0,Ge.useState)(()=>new Set),Oe=(0,Ge.useRef)(St),ge=(0,Ge.useRef)(null);ge.current=v;let Q=(0,Ge.useRef)(!1),G=(0,Ge.useRef)(!1),Be=(0,Ge.useRef)(!1),ze=(0,Ge.useRef)(!1),Xe=(0,Ge.useRef)(0),ne=(0,Ge.useRef)(0),ee=(0,Ge.useRef)(!1),{vaultTheme:le,surface:V,overlayTheme:Ve,appearance:Ae,buttonsLayout:he}=(0,Ge.useMemo)(()=>bi({theme:l,appearance:p,buttonsStyles:P}),[l,p,P]),N=(0,Ge.useMemo)(()=>(0,Ra.mergeCardSetupSurface)(V,u),[V,u]),Ce=(0,Ge.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:S,onComplete:E,onDecline:K,onCancel:I,onValidation:X,onError:M});Ce.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:S,onComplete:E,onDecline:K,onCancel:I,onValidation:X,onError:M},(0,Ge.useEffect)(()=>{ee.current=!0;let m=Xe.current+1;return Xe.current=m,()=>{ee.current=!1,ne.current+=1,queueMicrotask(()=>{Xe.current===m&&(Be.current||ze.current||(ze.current=!0,(0,Qe.invokeMerchantCallback)(()=>{Ce.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let ut=(0,Ge.useCallback)((m,Z)=>{Be.current=!0,Q.current=!1,D({status:"success",wording:m,message:null}),(async()=>(await ws(600),!G.current&&(G.current=!0,(0,Qe.invokeMerchantCallback)(()=>{Ce.current.onComplete?.({status:"succeeded",sessionId:Ce.current.sessionId,...Z?{paymentMethod:Z}:{}})}),ee.current&&D(null))))()},[]),Le=(0,Ge.useCallback)((m,Z)=>{Be.current=!0,Q.current=!1,D({status:"error",wording:m,message:Z.message??null}),(0,Qe.invokeMerchantCallback)(()=>{Ce.current.onDecline?.({status:"declined",sessionId:Ce.current.sessionId,...Z.reason?{reason:Z.reason}:{},...Z.message?{message:Z.message}:{}})}),(async()=>(await ws(400),ee.current&&D(null)))()},[]),ot=(0,Ge.useCallback)((m,Z)=>{Q.current?(Q.current=!1,D({status:"error",wording:m,message:Z.message}),setTimeout(()=>{ee.current&&D(null)},400)):D(null),(0,Qe.invokeMerchantCallback)(()=>Ce.current.onError?.(Z))},[]),Me=(0,Ge.useCallback)(async m=>{let Z=ne.current+1;ne.current=Z;let xe=()=>!ee.current||Z!==ne.current;Q.current=!0,D({status:"processing",wording:"payment_method",message:null});let rt=new Aa.PaymentAPI((0,mr.resolveBillingApiUrl)(Ce.current.billingApiUrl),{telemetry:Ce.current.telemetry});try{for(let oe=0;oe<yu;oe+=1){if((oe>0||m.waitFirst)&&await ws(mu),xe())return;let $=await rt.getUnifiedCheckoutSession(Ce.current.sessionId,Ce.current.nonce);if(xe())return;let Vt=$.data.session?.status;if(Vt==="complete"){Te(!0),ut("payment_method");return}if(Vt==="expired")throw new mr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new mr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(oe){if(xe())return;let $=oe instanceof mr.FloPayError&&oe.code==="payment_method_setup_unverified";ot("payment_method",no(oe,$?{retryable:!0}:{}))}finally{rt.destroy()}},[ot,ut]);(0,Ge.useEffect)(()=>{let m=!0,Z=(0,mr.resolveBillingApiUrl)(a),xe=new Aa.PaymentAPI(Z,{telemetry:i});ye(null),Te(!1),se(null),pe(null),dt(null);let rt=new Set;return Oe.current=rt,Ye(rt),Be.current=!1,ze.current=!1,G.current=!1,(async()=>{try{let{session:oe,advertisement:$}=await gu(xe,r,n);if(!m)return;let Vt={advertisement:$,customer:fu(oe),...oe.futureUse?{futureUse:oe.futureUse}:{},...oe.futureUseUnsupported?{futureUseUnsupported:oe.futureUseUnsupported}:{}};if(f){if((0,Zo.clearSetupRedirectParams)(),oe.status==="complete"){Te(!0),ye(Vt),ut("payment_method");return}f.failed?Le("payment_method",{reason:"redirect_failed"}):Me({waitFirst:!0})}let Ir=$.card?await hu(xe,oe,r,n,Z):null;if(!m)return;ye(Vt),Ir&&(pe(Ir),se(new Aa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:i})))}catch(oe){if(!m)return;let $=no(oe);Be.current=!0,dt($),(0,Qe.invokeMerchantCallback)(()=>Ce.current.onError?.($))}})(),()=>{m=!1,xe.destroy()}},[a,n,f,Le,ut,r,i,Me]),(0,Ge.useEffect)(()=>{if(!T)return;Q.current=!1;let m=T.on("submitting",()=>{Q.current=!0,D({status:"processing",wording:"card",message:null})}),Z=T.on("complete",oe=>{ut("card",oe.paymentMethod)}),xe=T.on("decline",oe=>{Le("card",{...oe.declineReason?{reason:oe.declineReason}:{},...oe.message?{message:oe.message}:{}})}),rt=T.on("challenge_dismissed",()=>{D(null)});return()=>{m(),Z(),xe(),rt()}},[T,Le,ut]);let tt=(0,Ge.useCallback)((m,Z,xe)=>{if(xe.retryable){ot("payment_method",no(Z,xe));return}if(Oe.current.has(m))return;let rt=new Set(Oe.current);rt.add(m),Oe.current=rt,Ye(rt);let oe=ge.current?.advertisement,$=oe?(0,Cr.advertisedMethodKeys)(oe).some(Vt=>!rt.has(Vt)):!1;ot("payment_method",no(Z,{code:xe.code,retryable:$}))},[ot]),at=(0,Ge.useMemo)(()=>({onSubmitting:()=>{Q.current=!0,D({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Me({waitFirst:!1})},onDeclined:m=>Le("payment_method",m),onValidation:m=>{(0,Qe.invokeMerchantCallback)(()=>Ce.current.onValidation?.(m))},onAbandoned:()=>{Q.current=!1,D(null)}}),[Le,Me]),lr=(0,Ge.useRef)(tt);lr.current=tt;let Bt=(0,Ge.useRef)(new Map),wt=m=>{let Z=Bt.current.get(m);if(Z)return Z;let xe=(rt,oe)=>lr.current(m,rt,oe);return Bt.current.set(m,xe),xe},Se=(0,Ge.useCallback)(m=>{if(Oe.current.has(m))return;let Z=new Set(Oe.current);Z.add(m),Oe.current=Z,Ye(Z);let xe=ge.current?.advertisement;xe&&(0,Cr.advertisedMethodKeys)(xe).some(oe=>!Z.has(oe))||ot("payment_method",no(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ot]),x=(0,Ge.useRef)(Se);x.current=Se;let ht=(0,Ge.useRef)(new Map),pt=m=>{let Z=ht.current.get(m);if(Z)return Z;let xe=()=>x.current(m);return ht.current.set(m,xe),xe},z=He?(0,sr.jsx)(Hr,{status:He.status,errorMessage:He.message,...(0,Cr.setupOverlayLabels)(He.wording),successNote:null,...Ve?{theme:Ve}:{}}):null;if(Fe)return(0,sr.jsx)("div",{role:"alert",children:Fe.message});if(!v||b)return(0,sr.jsxs)(sr.Fragment,{children:[z,v?null:w]});let{advertisement:we,customer:Dt,futureUse:Ke,futureUseUnsupported:kt}=v,k=(0,mr.resolveBillingApiUrl)(a),A=i===void 0?{}:{telemetry:i},We=we.stripe.filter(({method:m})=>!St.has(m)),ke=St.has("paypal")?null:we.paypal,ct=!!(we.card&&T&&me?.html),g=({method:m,publishableKey:Z,currency:xe})=>(0,sr.jsx)("div",{"data-flopay-payment-method":m,style:{display:"contents"},children:(0,sr.jsx)(wi,{onFailed:wt(m),children:(0,sr.jsx)(Ge.Suspense,{fallback:null,children:(0,sr.jsx)(e,{method:m,category:(0,Cr.stripeMethodCategory)(m),publishableKey:Z,currency:xe,...Ke?{futureUse:Ke}:{},...kt?{futureUseUnsupported:kt}:{},sessionId:r,nonce:n,billingApiUrl:k,...A,...Ae?{appearance:Ae}:{},...he?{buttonsLayout:he}:{},...typeof l=="string"?{themeId:l}:{},...at,onFailed:wt(m),onUnavailable:pt(m)})})})},m),J=We.filter(({method:m})=>(0,Cr.stripeMethodCategory)(m)==="wallet"),q=We.filter(({method:m})=>(0,Cr.stripeMethodCategory)(m)!=="wallet"),ue=We.length>0||ke!==null;return(0,sr.jsxs)(sr.Fragment,{children:[z,ue?(0,sr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[J.map(g),ke?(0,sr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,sr.jsx)(wi,{onFailed:wt("paypal"),children:(0,sr.jsx)(Ge.Suspense,{fallback:null,children:(0,sr.jsx)(t,{clientId:ke.clientId,...ke.environment?{environment:ke.environment}:{},...we.currency?{currency:we.currency}:{},sessionId:r,nonce:n,billingApiUrl:k,customer:Dt,...A,...at,onFailed:wt("paypal"),onUnavailable:pt("paypal")})})})}):null,q.map(g)]}):null,ct&&ue?(0,sr.jsx)(ci,{label:"or add a card"}):null,ct&&T&&me?.html?(0,sr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,sr.jsx)(co,{capture:T,html:me.html,messageToken:me.messageToken,expectedOrigin:me.expectedOrigin,verificationRequired:me.verificationRequired,theme:le,containerStyle:N,onReady:()=>{(0,Qe.invokeMerchantCallback)(()=>Ce.current.onReady?.())},onValidation:m=>{(0,Qe.invokeMerchantCallback)(()=>Ce.current.onValidation?.(m))},onError:m=>{m&&ot("card",no(new Error(m),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Pc=require("react/jsx-runtime"),Pu={StripeSetupMethod:fc,PayPalSetupMethod:cc};function hc(e){return(0,Pc.jsx)(gc,{...e,branches:Pu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&x(Jo),r&&(n||a)&&x(Jo),r&&(0,F.jsx)("button",{type:"button",onClick:()=>{e?.("card"),E(!0)},style:{width:"100%",...f,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:I.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...I.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,F.jsx)(Do,{content:m})}),(0,F.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var hn=require("react/jsx-runtime"),ru=44;function oc(e){return new Promise(t=>setTimeout(t,e))}function nu(e,t){return e instanceof Pn.FloPayError?e:new Pn.FloPayError(e instanceof Error?e.message:t,"api_error")}function ou(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function au(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function ac({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:i,products:l,items:p,subscriptions:m,account:h,successUrl:w,cancelUrl:S,couponCodes:E,tagsData:Y,utmMetadata:I,billingApiUrl:ee,locale:x,theme:f,appearance:P,buttonsTheme:pe,buttonsStyles:b,onSuccess:Ie,onError:_,onDecline:ie,children:me,disabled:ue=!1,type:xe="button",style:lt,...$e}){let B=(0,gt.useMemo)(()=>(0,Pn.resolveBillingApiUrl)(ee),[ee]),St=(0,gt.useMemo)(()=>au({createSession:r,clientId:i,products:l,items:p,subscriptions:m,account:h,successUrl:w,cancelUrl:S,couponCodes:E,tagsData:Y,utmMetadata:I}),[h,S,i,E,r,l,p,m,w,Y,I]),[Ge,De]=(0,gt.useState)(!1),[de,re]=(0,gt.useState)(null),[X,Oe]=(0,gt.useState)(null),[nt,ze]=(0,gt.useState)(!1),[te,J]=(0,gt.useState)(null),[H,j]=(0,gt.useState)(null),je=(0,gt.useRef)(!0),Te=(0,gt.useRef)(null),fe=(0,gt.useRef)(H),O=(0,gt.useRef)(Ie),Pe=(0,gt.useRef)(_),ut=(0,gt.useRef)(ie),Le=(0,gt.useCallback)(C=>ei(Te,async M=>{try{return await C(M)}catch(Fe){throw M.aborted?$o(Fe):Fe}}),[]);(0,gt.useEffect)(()=>{fe.current=H},[H]),(0,gt.useEffect)(()=>{O.current=Ie},[Ie]),(0,gt.useEffect)(()=>{Pe.current=_},[_]),(0,gt.useEffect)(()=>{ut.current=ie},[ie]),(0,gt.useEffect)(()=>(je.current=!0,()=>{je.current=!1,Te.current?.abort()}),[]),(0,gt.useEffect)(()=>{if(typeof window>"u")return;let C=M=>{M.key==="Escape"&&j(null)};return window.addEventListener("keydown",C),()=>{window.removeEventListener("keydown",C)}},[]);let ot=(0,gt.useCallback)((C,M=ba)=>{ut.current?.(wr(M,C,{code:C.code,declineCode:C.declineCode}))},[]),_e=(0,gt.useCallback)(async C=>{je.current&&(Oe(null),ze(C.result.status==="authorized"),re("success"),await oc(600),je.current&&(0,Ze.invokeMerchantCallback)(()=>O.current?.(C)))},[]),et=(0,gt.useCallback)(async(C,M)=>{je.current&&(Pe.current?.(C),M?.emitDecline&&ot(C,M.method),Oe(C.message),ze(!1),re("error"),await oc(400))},[ot]),at=(0,gt.useCallback)(async(C,M,Fe)=>{let Se=C.data.session??null;if(!Se)throw so(new Pn.FloPayError("No session data returned","api_error"),M);let ct=Se.clientSecret||t;if(Jn(Se)){await _e({result:Xn(Se,M),session:Se,sessionId:Se.id||M,autoCompleted:!1});return}if(Se.status==="expired")throw so($a(Se),Se.id||M);try{if(C.autoProcessingPending){let Ve=C.autoProcessingPending,He=new Ci.PaymentAPI(B),Bt=await Le(V=>He.waitForCheckoutSessionCompletion(Ve.sessionId,{initialDelayMs:Ve.retryAfterMs,nonce:ct,statusUrl:Ve.statusUrl,signal:V})),c=lo(Bt,Se),U=Bt.autoProcessingError?.type==="3ds_required"&&Bt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Bt.autoProcessingError.nextActionRedirectUrl}:null;if(U&&M&&ct){let V=await Le(se=>Ho(U,{billingApiUrl:B,sessionId:M,nonce:ct,session:Se,signal:se,telemetry:!0}));await _e({result:V,session:Se,sessionId:Se.id||M,autoCompleted:!1});return}if(Bt.autoProcessingError)throw qn(Bt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Bt.autoProcessingError.checkoutMethod});if(!Jn(c))throw No(c);await _e({result:Xn(c,M),session:c,sessionId:c.id||M,autoCompleted:!1});return}if(C.autoProcessingError){let Ve=C.autoProcessingError.nextActionRedirectUrl;if(C.autoProcessingError.type==="3ds_required"&&Ve&&M&&ct){let He=await Le(V=>Al({billingApiUrl:B,sessionId:M,nonce:ct,nextActionRedirectUrl:Ve,signal:V}));if(He.status==="declined")throw qn({type:He.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:He.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:C.autoProcessingError.checkoutMethod});let c=await new Ci.PaymentAPI(B).waitForCheckoutSessionCompletion(M,{initialDelayMs:0,nonce:ct}),U=lo(c,Se);if(!Jn(U))throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:C.autoProcessingError.checkoutMethod});await _e({result:Xn(U,M),session:U,sessionId:U.id||M,autoCompleted:!1});return}throw qn(C.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:C.autoProcessingError.checkoutMethod})}if(Fe?.fromCreateSession&&C.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let mt=await Ko({billingApiUrl:B,sessionId:M??Se.id,session:Se,nonce:ct});if(mt.type==="next_action_required"&&ct){let Ve=M??Se.id,He=await Le(Bt=>Ho(mt,{billingApiUrl:B,sessionId:Ve,nonce:ct,session:Se,signal:Bt,telemetry:!0}));await _e({result:He,session:Se,sessionId:Se.id||Ve,autoCompleted:!1});return}if(mt.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await _e({result:mt.result,session:Se,sessionId:Se.id||M,autoCompleted:!1})}catch(mt){let Ve=Se.id||M,He=so(Sa(mt),Ve);if(He.code==="three_ds_aborted")return;if(He.code==="checkout_processing_timeout"){if(!je.current)return;J(He.message),(0,Ze.invokeMerchantCallback)(()=>Pe.current?.(He));return}await et(He,{emitDecline:!0,method:He.checkoutMethod??ba}),ou(He,Ve)&&Ve&&je.current&&j({sessionId:Ve,errorMessage:He.message,nonce:ct||void 0,payPalOrderId:He.orderId})}},[t,B,Le,et,_e]),ar=(0,gt.useCallback)(async C=>{if($e.onClick?.(C),!(C.defaultPrevented||ue||Ge)){if(j(null),J(null),e&&St){let M=new Pn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await et(M),je.current&&(re(null),Oe(null));return}if(!e&&!St){let M=new Pn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await et(M),je.current&&(re(null),Oe(null));return}De(!0),Oe(null),ze(!1),re("processing");try{let M=new Ci.PaymentAPI(B);if(e){let Fe=await M.getUnifiedCheckoutSession(e,t);await at(Fe,e);return}try{let Fe=await M.createAndFetchSession({...St});await at(Fe,Fe.data.session?.id??null,{fromCreateSession:!0})}catch(Fe){if(Ha(Fe)==="session_auto_completed"){await _e({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Fe}}catch(M){await et(so(nu(M,"Automatic payment failed. Please try again."),e))}finally{je.current&&(re(null),Oe(null),De(!1))}}},[$e.onClick,St,ue,Ge,t,at,B,e,et,_e]),xt=(0,gt.useCallback)(C=>{let M=fe.current;j(null),O.current?.({result:C,session:null,sessionId:M?.sessionId??null,autoCompleted:!1})},[]),Ct=(0,gt.useCallback)(C=>{Pe.current?.(C)},[]),Ce=(0,gt.useCallback)(C=>{ut.current?.(C)},[]),T=(0,gt.useMemo)(()=>(0,Pn.resolveTheme)(f),[f]),ht=(0,gt.useMemo)(()=>{let C=T?.buttonsLayout??(0,Pn.resolveButtonsLayoutTheme)(pe);return b?{...C,...b,cardButton:{...C.cardButton,...b.cardButton}}:C},[T,pe,b]),pt=(0,gt.useMemo)(()=>{let C=T?.appearance;return P?C?{...C,...P,variables:{...C.variables,...P.variables}}:P:C},[P,T]),z=pt?.variables,Ae=z?.colorPrimary??"#4A49FF",Dt=z?.colorPrimaryHover??(0,ms.darkenHex)(Ae,.12),be=z?.borderRadius??"8px";return(0,hn.jsxs)(hn.Fragment,{children:[(0,hn.jsx)("button",{...$e,type:xe,onClick:ar,disabled:ue||Ge,"aria-busy":Ge,style:{width:"100%",...me===void 0?{boxSizing:"border-box",height:ru,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ht.cardButton,...ps({themeBundle:T,resolvedPrimaryColor:Ae,resolvedBorderRadius:be,submitButtonStyle:ht.submitButton,explicitPrimaryColor:z?.colorPrimary}),fontSize:ht.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ue||Ge?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ue||Ge?.6:1,...lt},onMouseEnter:C=>{$e.onMouseEnter?.(C),!C.defaultPrevented&&!ue&&!Ge&&(T||z?.colorPrimary)&&(C.currentTarget.style.backgroundColor=Dt)},onMouseLeave:C=>{$e.onMouseLeave?.(C),!C.defaultPrevented&&(T||z?.colorPrimary)&&(C.currentTarget.style.backgroundColor=Ae)},onMouseDown:C=>{$e.onMouseDown?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(0.985)")},onMouseUp:C=>{$e.onMouseUp?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(1)")},children:(0,hn.jsx)(Do,{content:me})}),te&&(0,hn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:te}),de&&(0,hn.jsx)(Zr,{status:de,errorMessage:X,authorized:nt}),H&&(0,hn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:C=>{C.target===C.currentTarget&&j(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,hn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,hn.jsx)(vi,{sessionId:H.sessionId,nonce:H.nonce,checkoutMode:"full",billingApiUrl:B,locale:x,theme:f,...pt?{appearance:pt}:{},buttonsTheme:pe,buttonsStyles:b,initialErrorMessage:H.errorMessage,initialPayPalOrderId:H.payPalOrderId,cardTitleContent:null,onComplete:xt,onError:Ct,onDecline:Ce})})})]})}var Si=require("@flopay/js/card-setup"),Vr=require("@flopay/shared"),qt=require("react");var bs=require("@flopay/shared"),iu=require("@flopay/shared");function bi(e){let t=(0,bs.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Vn=require("react/jsx-runtime"),xa=class extends Vr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function no(e,t={}){let r=e instanceof Vr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new xa(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:a,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function ic({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:i,appearance:l,buttonsStyles:p,loading:m=null,onReady:h,onComplete:w,onDecline:S,onCancel:E,onValidation:Y,onError:I}){let[ee,x]=(0,qt.useState)(null),[f,P]=(0,qt.useState)(null),[pe,b]=(0,qt.useState)(null),[Ie,_]=(0,qt.useState)(null),[ie,me]=(0,qt.useState)(null),ue=(0,qt.useRef)(!1),xe=(0,qt.useRef)(!1),{vaultTheme:lt,surface:$e,overlayTheme:B}=(0,qt.useMemo)(()=>bi({theme:a,appearance:l,buttonsStyles:p}),[a,l,p]),St=(0,qt.useMemo)(()=>(0,Ra.mergeCardSetupSurface)($e,i),[$e,i]),Ge=(0,qt.useRef)(h),De=(0,qt.useRef)(I),de=(0,qt.useRef)(w),re=(0,qt.useRef)(S),X=(0,qt.useRef)(E),Oe=(0,qt.useRef)(Y),nt=(0,qt.useRef)(!1),ze=(0,qt.useRef)(!1),te=(0,qt.useRef)(0);return Ge.current=h,De.current=I,de.current=w,re.current=S,X.current=E,Oe.current=Y,(0,qt.useEffect)(()=>{let J=te.current+1;return te.current=J,()=>{queueMicrotask(()=>{te.current===J&&(nt.current||ze.current||(ze.current=!0,(0,Ze.invokeMerchantCallback)(()=>{X.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,qt.useEffect)(()=>{let J=!0,H=(0,Vr.resolveBillingApiUrl)(r),j=new Si.PaymentAPI(H,{telemetry:n});return x(null),P(null),b(null),nt.current=!1,ze.current=!1,(async()=>{try{if(!e.trim())throw new Vr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Vr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let je=await j.getUnifiedCheckoutSession(e,t);if(!J)return;let Te=je.data.session;if(!Te||!(0,Vr.isCardSetupCheckoutSession)(Te))throw new Vr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let fe=Te.vault;(0,Vr.isMountableVaultBlock)(fe)||(fe=await j.getVaultCapture(e,t));let O=(0,Vr.resolveVaultMountOptions)(fe,{billingApiUrl:H,sessionId:e,nonce:t});if(!O)throw new Vr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!J)return;P(O),x(new Si.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(je){if(!J)return;let Te=no(je);nt.current=!0,b(Te),(0,Ze.invokeMerchantCallback)(()=>De.current?.(Te))}})(),()=>{J=!1,j.destroy()}},[r,t,e,n]),(0,qt.useEffect)(()=>{if(!ee)return;let J=!1;xe.current=!1,ue.current=!1;let H=ee.on("submitting",()=>{ue.current=!0,me(null),_("processing")}),j=ee.on("complete",fe=>{nt.current=!0,ue.current=!1,_("success"),(async()=>(await new Promise(O=>setTimeout(O,600)),!xe.current&&(xe.current=!0,(0,Ze.invokeMerchantCallback)(()=>{de.current?.({status:"succeeded",sessionId:e,...fe.paymentMethod?{paymentMethod:fe.paymentMethod}:{}})}),J||_(null))))()}),je=ee.on("decline",fe=>{nt.current=!0,ue.current=!1,me(fe.message??null),_("error"),(0,Ze.invokeMerchantCallback)(()=>{re.current?.({status:"declined",sessionId:e,...fe.declineReason?{reason:fe.declineReason}:{},...fe.message?{message:fe.message}:{}})}),(async()=>(await new Promise(O=>setTimeout(O,400)),J||_(null)))()}),Te=ee.on("challenge_dismissed",()=>{_(null)});return()=>{J=!0,H(),j(),je(),Te()}},[ee,e]),pe?(0,Vn.jsx)("div",{role:"alert",children:pe.message}):!ee||!f?.html?(0,Vn.jsx)(Vn.Fragment,{children:m}):(0,Vn.jsxs)(Vn.Fragment,{children:[Ie&&(0,Vn.jsx)(Zr,{status:Ie,errorMessage:ie,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...B?{theme:B}:{}}),(0,Vn.jsx)(co,{capture:ee,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:lt,containerStyle:St,onReady:()=>{(0,Ze.invokeMerchantCallback)(()=>Ge.current?.())},onValidation:J=>{(0,Ze.invokeMerchantCallback)(()=>Oe.current?.(J))},onError:J=>{if(!J)return;ue.current&&(ue.current=!1,me(J),_("error"),setTimeout(()=>_(null),400));let H=no(new Error(J),{code:"card_setup_widget_failed",retryable:!0});(0,Ze.invokeMerchantCallback)(()=>De.current?.(H))}})]})}var sc=require("@flopay/js/card-setup"),uo=require("@flopay/shared"),lc=require("@paypal/paypal-js"),wo=require("react");var dc=require("react/jsx-runtime");function cc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:i,telemetry:l,customer:{userId:p,email:m},onSubmitting:h,onConfirmed:w,onFailed:S,onAbandoned:E}){let Y=(0,wo.useRef)(null),I=(0,wo.useRef)({onSubmitting:h,onConfirmed:w,onFailed:S,onAbandoned:E});I.current={onSubmitting:h,onConfirmed:w,onFailed:S,onAbandoned:E};let[ee]=(0,wo.useState)(()=>(0,Un.detectPayPalEnvironment)().inAppBrowser);return(0,wo.useEffect)(()=>{let x=!0,f,P=new sc.PaymentAPI(i,{telemetry:l}),pe={userId:p,email:m};return(async()=>{try{let b=await(0,lc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Ie=Y.current;if(!x||!Ie)return;if(!b?.Buttons)throw new uo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let _=b.Buttons({createVaultSetupToken:async()=>{I.current.onSubmitting();let ie=await P.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(ie.provider!=="paypal"||ie.providerObjectType!=="setup_token")throw new uo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ie.providerObjectId},onApprove:async ie=>{let me=ie.vaultSetupToken;if(!me)throw new uo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let ue=await P.processPayment(pe.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:me,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:pe});if(!ue.ok)throw new uo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:ue.status});x&&I.current.onConfirmed()},onCancel:()=>{x&&I.current.onAbandoned()},onError:ie=>{if(!x)return;let{popupBlocked:me}=(0,ve.classifyExternalMethodFailure)(ie,{inAppBrowser:ee,handoffObserved:!1});I.current.onFailed(me?new Error((0,ve.buildExternalMethodRecoveryMessage)("PayPal",!0,ee)):ie,{code:me?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>_.close(),await _.render(Ie)}catch(b){if(!x)return;I.current.onFailed(b,{code:"paypal_unavailable",retryable:!0})}})(),()=>{x=!1,f?.().catch(()=>{}),P.destroy()}},[i,e,r,m,t,ee,a,n,l,p]),(0,dc.jsx)("div",{ref:Y,"data-flopay-paypal-setup":""})}var pc=require("@flopay/js/card-setup"),po=require("@flopay/shared"),Wn=require("@stripe/react-stripe-js"),mc=require("@stripe/stripe-js"),Wr=require("react");var Or=require("react/jsx-runtime"),yc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Ss=new Map;function su(e){let t=Ss.get(e);if(t)return t;let r=(0,mc.loadStripe)(e).catch(n=>{throw Ss.delete(e),n});return Ss.set(e,r),r}function lu(e){return e?(0,po.toStripeAppearance)(e):void 0}function cu(e){return(0,ve.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function uc(e){return e==="paypal"?"PayPal":(0,po.getStripeMethodDisplayName)(e)}function du(){return typeof window>"u"?"":window.location.href}var uu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function fc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:i,appearance:l}=e,[p]=(0,Wr.useState)(()=>su(t)),m=(0,Wr.useMemo)(()=>{let h=lu(l),w=(0,po.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:i},r,"setup");return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:yc[r]?.types??[r],...w?{setupFutureUsage:w}:{},...h?{appearance:h}:{}}},[l,n,a,i,r]);return(0,Or.jsx)(Wn.Elements,{stripe:p,options:m,children:(0,Or.jsx)(pu,{...e})})}function pu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,appearance:l,themeId:p,buttonsLayout:m,onSubmitting:h,onConfirmed:w,onDeclined:S,onFailed:E,onValidation:Y,onUnavailable:I}){let ee=(0,Wn.useStripe)(),x=(0,Wn.useElements)(),[f,P]=(0,Wr.useState)(!1),[pe,b]=(0,Wr.useState)("loading"),[Ie,_]=(0,Wr.useState)(!1),[ie,me]=(0,Wr.useState)(!1),ue=(0,Wr.useRef)(!1),[xe]=(0,Wr.useState)(()=>(0,Un.detectPayPalEnvironment)()),[lt,$e]=(0,Wr.useState)(!1),B=(0,Wr.useCallback)((X,Oe)=>{if((0,ve.classifyExternalMethodFailure)(X,{inAppBrowser:xe.inAppBrowser,handoffObserved:!1}).popupBlocked){$e(!0),E(new Error((0,ve.buildExternalMethodRecoveryMessage)(uc(e),!0,xe.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}E(Oe.message===void 0?X:new Error(Oe.message),{code:Oe.code,retryable:!0})},[xe.inAppBrowser,e,E]),St=(0,Wr.useCallback)(async X=>{let Oe=!1,nt=!1,ze=()=>{!X||Oe||nt||(nt=!0,X.paymentFailed({reason:"fail"}))};if(!ee||!x||ue.current){ze();return}ue.current=!0,P(!0);try{let te=await x.submit();if(te.error){ze(),Y(te.error.message??null);return}h();let J=await new pc.PaymentAPI(a,{telemetry:i}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(J.provider!=="stripe"||J.intentKind!=="setup")throw new po.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Oe=!0;let H=await ee.confirmSetup({elements:x,clientSecret:J.clientSecret,confirmParams:{return_url:du()},redirect:"if_required"});if(H.error){cu(H.error)?S({...H.error.decline_code||H.error.code?{reason:H.error.decline_code??H.error.code}:{},...H.error.message?{message:H.error.message}:{}}):B(H.error,{code:"payment_method_setup_provider_failed",message:H.error.message??"The payment method could not be saved."});return}w()}catch(te){ze(),B(te,{code:"payment_method_setup_failed"})}finally{ue.current=!1,P(!1)}},[a,t,x,e,n,w,S,h,Y,B,r,ee,i]),Ge=yc[e]?.wallet,De=Ge==="paypal"&&(0,zn.resolveStripePayPalPresentation)(xe,"auto",lt?"blocked":xe.popupCapability)==="redirect",de=l?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&Ge&&!De)return(0,Or.jsxs)(Or.Fragment,{children:[(0,Or.jsx)(Xo,{}),(0,Or.jsx)(ka,{state:pe,borderRadius:de,children:(0,Or.jsx)(Wn.ExpressCheckoutElement,{options:{...ii,paymentMethods:ai([e])},onReady:X=>{let Oe=wa(X,[Ge]);b(Oe),Oe==="unavailable"&&I()},onLoadError:()=>{b("load_error"),I()},onConfirm:X=>{St(X)}})})]});let re=uc(e);return(0,Or.jsxs)(Or.Fragment,{children:[Ie?(0,Or.jsx)(oi,{method:e,themeId:p,hasNextStep:!0,highlighted:ie,disabled:f,onClick:()=>me(X=>!X),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:de}):null,(0,Or.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ie,style:ie?{display:"flex",flexDirection:"column"}:uu,children:[(0,Or.jsx)(Wn.PaymentElement,{options:{layout:si},onReady:()=>_(!0),onLoadError:()=>I(),onChange:X=>{X.complete&&Y(null)}}),(0,Or.jsx)(li,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!ee||!x||f||!ie,onClick:()=>{St()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:m?.submitButton,children:f?"Saving\u2026":`Save ${re}`})]})]})}var Aa=require("@flopay/js/card-setup"),Cr=require("@flopay/shared"),Ke=Wi(require("react"),1);var Zo=require("@flopay/js/card-setup"),Er=require("@flopay/shared");var or=require("react/jsx-runtime"),mu=15,yu=2e3;function fu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function ws(e){return new Promise(t=>setTimeout(t,e))}async function gu(e,t,r){if(!t.trim())throw new Cr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Cr.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,Cr.isCardSetupCheckoutSession)(a))throw new Cr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let i=(0,Er.readSetupAdvertisement)(n);if(!(0,Er.advertisesAnyMethod)(i)){let{skippedForMissingCurrency:l}=i,p=l.length>0?`FloPay: this setup session advertises only Stripe methods (${l.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new Cr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:i}}async function hu(e,t,r,n,a){let i=t.vault??null;(0,Cr.isMountableVaultBlock)(i)||(i=await e.getVaultCapture(r,n));let l=(0,Cr.resolveVaultMountOptions)(i,{billingApiUrl:a,sessionId:r,nonce:n});if(!l)throw new Cr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return l}var wi=class extends Ke.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function gc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,theme:l="modern-light",containerStyle:p,appearance:m,buttonsStyles:h,loading:w=null,onReady:S,onComplete:E,onDecline:Y,onCancel:I,onValidation:ee,onError:x}){let[f]=(0,Ke.useState)(Zo.readSetupRedirectReturn),[P,pe]=(0,Ke.useState)(null),[b,Ie]=(0,Ke.useState)(!1),[_,ie]=(0,Ke.useState)(null),[me,ue]=(0,Ke.useState)(null),[xe,lt]=(0,Ke.useState)(null),[$e,B]=(0,Ke.useState)(null),[St,Ge]=(0,Ke.useState)(()=>new Set),De=(0,Ke.useRef)(St),de=(0,Ke.useRef)(null);de.current=P;let re=(0,Ke.useRef)(!1),X=(0,Ke.useRef)(!1),Oe=(0,Ke.useRef)(!1),nt=(0,Ke.useRef)(!1),ze=(0,Ke.useRef)(0),te=(0,Ke.useRef)(0),J=(0,Ke.useRef)(!1),{vaultTheme:H,surface:j,overlayTheme:je,appearance:Te,buttonsLayout:fe}=(0,Ke.useMemo)(()=>bi({theme:l,appearance:m,buttonsStyles:h}),[l,m,h]),O=(0,Ke.useMemo)(()=>(0,Ra.mergeCardSetupSurface)(j,p),[j,p]),Pe=(0,Ke.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:S,onComplete:E,onDecline:Y,onCancel:I,onValidation:ee,onError:x});Pe.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:S,onComplete:E,onDecline:Y,onCancel:I,onValidation:ee,onError:x},(0,Ke.useEffect)(()=>{J.current=!0;let c=ze.current+1;return ze.current=c,()=>{J.current=!1,te.current+=1,queueMicrotask(()=>{ze.current===c&&(Oe.current||nt.current||(nt.current=!0,(0,Ze.invokeMerchantCallback)(()=>{Pe.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let ut=(0,Ke.useCallback)((c,U)=>{Oe.current=!0,re.current=!1,B({status:"success",wording:c,message:null}),(async()=>(await ws(600),!X.current&&(X.current=!0,(0,Ze.invokeMerchantCallback)(()=>{Pe.current.onComplete?.({status:"succeeded",sessionId:Pe.current.sessionId,...U?{paymentMethod:U}:{}})}),J.current&&B(null))))()},[]),Le=(0,Ke.useCallback)((c,U)=>{Oe.current=!0,re.current=!1,B({status:"error",wording:c,message:U.message??null}),(0,Ze.invokeMerchantCallback)(()=>{Pe.current.onDecline?.({status:"declined",sessionId:Pe.current.sessionId,...U.reason?{reason:U.reason}:{},...U.message?{message:U.message}:{}})}),(async()=>(await ws(400),J.current&&B(null)))()},[]),ot=(0,Ke.useCallback)((c,U)=>{re.current?(re.current=!1,B({status:"error",wording:c,message:U.message}),setTimeout(()=>{J.current&&B(null)},400)):B(null),(0,Ze.invokeMerchantCallback)(()=>Pe.current.onError?.(U))},[]),_e=(0,Ke.useCallback)(async c=>{let U=te.current+1;te.current=U;let V=()=>!J.current||U!==te.current;re.current=!0,B({status:"processing",wording:"payment_method",message:null});let se=new Aa.PaymentAPI((0,Cr.resolveBillingApiUrl)(Pe.current.billingApiUrl),{telemetry:Pe.current.telemetry});try{for(let R=0;R<mu;R+=1){if((R>0||c.waitFirst)&&await ws(yu),V())return;let K=await se.getUnifiedCheckoutSession(Pe.current.sessionId,Pe.current.nonce);if(V())return;let Ut=K.data.session?.status;if(Ut==="complete"){Ie(!0),ut("payment_method");return}if(Ut==="expired")throw new Cr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Cr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(R){if(V())return;let K=R instanceof Cr.FloPayError&&R.code==="payment_method_setup_unverified";ot("payment_method",no(R,K?{retryable:!0}:{}))}finally{se.destroy()}},[ot,ut]);(0,Ke.useEffect)(()=>{let c=!0,U=(0,Cr.resolveBillingApiUrl)(a),V=new Aa.PaymentAPI(U,{telemetry:i});pe(null),Ie(!1),ie(null),ue(null),lt(null);let se=new Set;return De.current=se,Ge(se),Oe.current=!1,nt.current=!1,X.current=!1,(async()=>{try{let{session:R,advertisement:K}=await gu(V,r,n);if(!c)return;let Ut={advertisement:K,customer:fu(R),...R.futureUse?{futureUse:R.futureUse}:{},...R.futureUseUnsupported?{futureUseUnsupported:R.futureUseUnsupported}:{}};if(f){if((0,Zo.clearSetupRedirectParams)(),R.status==="complete"){Ie(!0),pe(Ut),ut("payment_method");return}f.failed?Le("payment_method",{reason:"redirect_failed"}):_e({waitFirst:!0})}let xr=K.card?await hu(V,R,r,n,U):null;if(!c)return;pe(Ut),xr&&(ue(xr),ie(new Aa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:i})))}catch(R){if(!c)return;let K=no(R);Oe.current=!0,lt(K),(0,Ze.invokeMerchantCallback)(()=>Pe.current.onError?.(K))}})(),()=>{c=!1,V.destroy()}},[a,n,f,Le,ut,r,i,_e]),(0,Ke.useEffect)(()=>{if(!_)return;re.current=!1;let c=_.on("submitting",()=>{re.current=!0,B({status:"processing",wording:"card",message:null})}),U=_.on("complete",R=>{ut("card",R.paymentMethod)}),V=_.on("decline",R=>{Le("card",{...R.declineReason?{reason:R.declineReason}:{},...R.message?{message:R.message}:{}})}),se=_.on("challenge_dismissed",()=>{B(null)});return()=>{c(),U(),V(),se()}},[_,Le,ut]);let et=(0,Ke.useCallback)((c,U,V)=>{if(V.retryable){ot("payment_method",no(U,V));return}if(De.current.has(c))return;let se=new Set(De.current);se.add(c),De.current=se,Ge(se);let R=de.current?.advertisement,K=R?(0,Er.advertisedMethodKeys)(R).some(Ut=>!se.has(Ut)):!1;ot("payment_method",no(U,{code:V.code,retryable:K}))},[ot]),at=(0,Ke.useMemo)(()=>({onSubmitting:()=>{re.current=!0,B({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{_e({waitFirst:!1})},onDeclined:c=>Le("payment_method",c),onValidation:c=>{(0,Ze.invokeMerchantCallback)(()=>Pe.current.onValidation?.(c))},onAbandoned:()=>{re.current=!1,B(null)}}),[Le,_e]),ar=(0,Ke.useRef)(et);ar.current=et;let xt=(0,Ke.useRef)(new Map),Ct=c=>{let U=xt.current.get(c);if(U)return U;let V=(se,R)=>ar.current(c,se,R);return xt.current.set(c,V),V},Ce=(0,Ke.useCallback)(c=>{if(De.current.has(c))return;let U=new Set(De.current);U.add(c),De.current=U,Ge(U);let V=de.current?.advertisement;V&&(0,Er.advertisedMethodKeys)(V).some(R=>!U.has(R))||ot("payment_method",no(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ot]),T=(0,Ke.useRef)(Ce);T.current=Ce;let ht=(0,Ke.useRef)(new Map),pt=c=>{let U=ht.current.get(c);if(U)return U;let V=()=>T.current(c);return ht.current.set(c,V),V},z=$e?(0,or.jsx)(Zr,{status:$e.status,errorMessage:$e.message,...(0,Er.setupOverlayLabels)($e.wording),successNote:null,...je?{theme:je}:{}}):null;if(xe)return(0,or.jsx)("div",{role:"alert",children:xe.message});if(!P||b)return(0,or.jsxs)(or.Fragment,{children:[z,P?null:w]});let{advertisement:Ae,customer:Dt,futureUse:be,futureUseUnsupported:_t}=P,C=(0,Cr.resolveBillingApiUrl)(a),M=i===void 0?{}:{telemetry:i},Fe=Ae.stripe.filter(({method:c})=>!St.has(c)),Se=St.has("paypal")?null:Ae.paypal,ct=!!(Ae.card&&_&&me?.html),mt=({method:c,publishableKey:U,currency:V})=>(0,or.jsx)("div",{"data-flopay-payment-method":c,style:{display:"contents"},children:(0,or.jsx)(wi,{onFailed:Ct(c),children:(0,or.jsx)(Ke.Suspense,{fallback:null,children:(0,or.jsx)(e,{method:c,category:(0,Er.stripeMethodCategory)(c),publishableKey:U,currency:V,...be?{futureUse:be}:{},..._t?{futureUseUnsupported:_t}:{},sessionId:r,nonce:n,billingApiUrl:C,...M,...Te?{appearance:Te}:{},...fe?{buttonsLayout:fe}:{},...typeof l=="string"?{themeId:l}:{},...at,onFailed:Ct(c),onUnavailable:pt(c)})})})},c),Ve=Fe.filter(({method:c})=>(0,Er.stripeMethodCategory)(c)==="wallet"),He=Fe.filter(({method:c})=>(0,Er.stripeMethodCategory)(c)!=="wallet"),Bt=Fe.length>0||Se!==null;return(0,or.jsxs)(or.Fragment,{children:[z,Bt?(0,or.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ve.map(mt),Se?(0,or.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,or.jsx)(wi,{onFailed:Ct("paypal"),children:(0,or.jsx)(Ke.Suspense,{fallback:null,children:(0,or.jsx)(t,{clientId:Se.clientId,...Se.environment?{environment:Se.environment}:{},...Ae.currency?{currency:Ae.currency}:{},sessionId:r,nonce:n,billingApiUrl:C,customer:Dt,...M,...at,onFailed:Ct("paypal"),onUnavailable:pt("paypal")})})})}):null,He.map(mt)]}):null,ct&&Bt?(0,or.jsx)(ci,{label:"or add a card"}):null,ct&&_&&me?.html?(0,or.jsx)("div",{"data-flopay-payment-method":"card",children:(0,or.jsx)(co,{capture:_,html:me.html,messageToken:me.messageToken,expectedOrigin:me.expectedOrigin,verificationRequired:me.verificationRequired,theme:H,containerStyle:O,onReady:()=>{(0,Ze.invokeMerchantCallback)(()=>Pe.current.onReady?.())},onValidation:c=>{(0,Ze.invokeMerchantCallback)(()=>Pe.current.onValidation?.(c))},onError:c=>{c&&ot("card",no(new Error(c),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Pc=require("react/jsx-runtime"),Pu={StripeSetupMethod:fc,PayPalSetupMethod:cc};function hc(e){return(0,Pc.jsx)(gc,{...e,branches:Pu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|